summaryrefslogtreecommitdiff
Side-by-side diff
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--noncore/applets/autorotateapplet/autorotate.cpp10
-rw-r--r--noncore/applets/memoryapplet/swapfile.cpp21
-rw-r--r--noncore/applets/networkapplet/networkapplet.cpp16
-rw-r--r--noncore/applets/notesapplet/config.in2
-rw-r--r--noncore/applets/notesapplet/notes.cpp54
-rw-r--r--noncore/applets/notesapplet/notesapplet.pro18
-rw-r--r--noncore/applets/wirelessapplet/wireless.cpp44
-rw-r--r--noncore/applets/zkbapplet/zkbwidget.cpp2
-rw-r--r--noncore/apps/advancedfm/advancedfm.cpp44
-rw-r--r--noncore/apps/advancedfm/advancedfm.pro24
-rw-r--r--noncore/apps/advancedfm/advancedfmData.cpp12
-rw-r--r--noncore/apps/advancedfm/advancedfmMenu.cpp1681
-rw-r--r--noncore/apps/advancedfm/filePermissions.cpp2
-rw-r--r--noncore/apps/advancedfm/output.cpp23
-rw-r--r--noncore/apps/checkbook/checkbook.pro2
-rw-r--r--noncore/apps/checkbook/listedit.cpp11
-rw-r--r--noncore/apps/checkbook/tabledef.cpp6
-rw-r--r--noncore/apps/checkbook/transaction.cpp6
-rw-r--r--noncore/apps/confedit/confedit.pro24
-rw-r--r--noncore/apps/confedit/config.in2
-rw-r--r--noncore/apps/confedit/listviewconfdir.cpp12
-rw-r--r--noncore/apps/confedit/listviewitemconffile.cpp24
-rw-r--r--noncore/apps/confedit/mainwindow.cpp19
-rw-r--r--noncore/apps/keyz-cfg/cfgfile.cpp12
-rw-r--r--noncore/apps/keyz-cfg/config.in2
-rw-r--r--noncore/apps/keyz-cfg/keyz-cfg.pro16
-rw-r--r--noncore/apps/keyz-cfg/zkb.cpp4
-rw-r--r--noncore/apps/keyz-cfg/zkbcfg.cpp15
-rw-r--r--noncore/apps/opie-bartender/bartender.cpp35
-rw-r--r--noncore/apps/opie-bartender/bartender.pro7
-rw-r--r--noncore/apps/opie-bartender/config.in3
-rw-r--r--noncore/apps/opie-console/MyPty.cpp14
-rw-r--r--noncore/apps/opie-console/TEWidget.cpp6
-rw-r--r--noncore/apps/opie-console/TEmulation.cpp8
-rw-r--r--noncore/apps/opie-console/atconfigdialog.cpp13
-rw-r--r--noncore/apps/opie-console/dialer.cpp27
-rw-r--r--noncore/apps/opie-console/emulation_handler.cpp14
-rw-r--r--noncore/apps/opie-console/emulation_widget.cpp10
-rw-r--r--noncore/apps/opie-console/function_keyboard.cpp9
-rw-r--r--noncore/apps/opie-console/io_bt.cpp7
-rw-r--r--noncore/apps/opie-console/io_irda.cpp8
-rw-r--r--noncore/apps/opie-console/io_modem.cpp8
-rw-r--r--noncore/apps/opie-console/main.cpp2
-rw-r--r--noncore/apps/opie-console/mainwindow.cpp39
-rw-r--r--noncore/apps/opie-console/modemconfigwidget.cpp11
-rw-r--r--noncore/apps/opie-console/opie-console.pro4
-rw-r--r--noncore/apps/opie-console/sz_transfer.cpp6
-rw-r--r--noncore/apps/opie-console/tabwidget.cpp7
-rw-r--r--noncore/apps/opie-console/terminalwidget.cpp11
-rw-r--r--noncore/apps/opie-console/test/senderui.cpp14
-rw-r--r--noncore/apps/opie-console/widget.cpp6
-rw-r--r--noncore/apps/opie-console/widget_layer.cpp4
-rw-r--r--noncore/apps/opie-write/mainwindow.cpp12
-rw-r--r--noncore/apps/opie-write/opie-write.pro3
-rw-r--r--noncore/apps/opie-write/qcomplextext.cpp4
-rw-r--r--noncore/apps/opie-write/qrichtext.cpp28
-rw-r--r--noncore/apps/opie-write/qrichtext_p.cpp15
-rwxr-xr-xnoncore/apps/qashmoney/accountdisplay.cpp13
-rw-r--r--noncore/apps/qashmoney/config.in2
-rwxr-xr-xnoncore/apps/qashmoney/qashmoney.pro2
-rw-r--r--noncore/apps/tableviewer/db/common.cpp28
-rw-r--r--noncore/apps/tableviewer/db/datacache.cpp12
-rw-r--r--noncore/apps/tableviewer/db/xmlsource.cpp30
-rw-r--r--noncore/apps/tableviewer/tableviewer.cpp14
-rw-r--r--noncore/apps/tableviewer/tableviewer.pro8
-rw-r--r--noncore/apps/tableviewer/ui/tvlistview.cpp9
-rw-r--r--noncore/apps/tinykate/libkate/libkate.pro147
-rw-r--r--noncore/apps/tinykate/tinykate.pro26
-rw-r--r--noncore/apps/zsafe/config.in2
-rw-r--r--noncore/apps/zsafe/scqtfiledlg.cpp29
-rw-r--r--noncore/apps/zsafe/zsafe.cpp15
-rw-r--r--noncore/apps/zsafe/zsafe.pro14
-rw-r--r--noncore/comm/keypebble/config.in2
-rw-r--r--noncore/comm/keypebble/keypebble.pro9
-rw-r--r--noncore/comm/keypebble/krfbbuffer.cpp24
-rw-r--r--noncore/comm/keypebble/krfbcanvas.cpp8
-rw-r--r--noncore/comm/keypebble/krfbconnection.cpp31
-rw-r--r--noncore/comm/keypebble/krfbdecoder.cpp63
-rw-r--r--noncore/comm/keypebble/krfblogin.cpp41
-rw-r--r--noncore/comm/keypebble/kvncbookmarkdlg.cpp12
-rw-r--r--noncore/games/backgammon/backgammon.cpp16
-rw-r--r--noncore/games/backgammon/moveengine.cpp2
-rw-r--r--noncore/games/bounce/bounce.pro5
-rw-r--r--noncore/games/bounce/game.cpp15
-rw-r--r--noncore/games/go/go.pro15
-rw-r--r--noncore/games/go/gowidget.cpp9
-rw-r--r--noncore/games/kpacman/kpacman.pro4
-rw-r--r--noncore/games/kpacman/kpacmanwidget.cpp5
-rw-r--r--noncore/games/kpacman/status.cpp5
-rw-r--r--noncore/games/mindbreaker/mindbreaker.cpp2
-rw-r--r--noncore/games/oyatzee/oyatzee.cpp50
-rw-r--r--noncore/games/oyatzee/oyatzee.pro2
-rw-r--r--noncore/games/wordgame/wordgame.cpp2
-rw-r--r--noncore/graphics/opie-eye/config.in4
-rw-r--r--noncore/graphics/opie-eye/impl/dir/dir_ifaceinfo.cpp14
-rw-r--r--noncore/graphics/opie-eye/impl/dir/dir_lister.cpp8
-rw-r--r--noncore/graphics/opie-eye/lib/slavemaster.cpp12
-rw-r--r--noncore/graphics/opie-eye/phunk_view.pro2
-rw-r--r--noncore/graphics/opie-eye/slave/jpeg_slave.cpp18
-rw-r--r--noncore/graphics/opie-eye/slave/main.cpp16
-rw-r--r--noncore/graphics/opie-eye/slave/slave.pro6
-rw-r--r--noncore/graphics/opie-eye/slave/slavereciever.cpp22
-rw-r--r--noncore/graphics/opie-eye/slave/thumbnailtool.cpp11
-rw-r--r--noncore/multimedia/opieplayer2/audiowidget.cpp8
-rw-r--r--noncore/multimedia/opieplayer2/lib.cpp12
-rw-r--r--noncore/multimedia/opieplayer2/mediaplayer.cpp12
-rw-r--r--noncore/multimedia/opieplayer2/om3u.cpp14
-rw-r--r--noncore/multimedia/opieplayer2/playlistselection.cpp10
-rw-r--r--noncore/multimedia/opieplayer2/playlistwidget.cpp38
-rw-r--r--noncore/multimedia/opieplayer2/playlistwidgetgui.cpp2
-rw-r--r--noncore/multimedia/opieplayer2/skin.cpp24
-rw-r--r--noncore/multimedia/opieplayer2/threadutil.cpp6
-rw-r--r--noncore/multimedia/opieplayer2/xinecontrol.cpp8
-rw-r--r--noncore/multimedia/opierec/device.cpp46
-rw-r--r--noncore/multimedia/opierec/helpwindow.cpp11
-rw-r--r--noncore/multimedia/opierec/opierec.pro6
-rw-r--r--noncore/multimedia/opierec/qtrec.cpp129
-rw-r--r--noncore/multimedia/opierec/wavFile.cpp67
-rw-r--r--noncore/multimedia/opierec/waveform.cpp12
-rw-r--r--noncore/multimedia/powerchord/config.in6
-rw-r--r--noncore/multimedia/powerchord/powerchord.pro3
-rw-r--r--noncore/multimedia/powerchord/powerchordbase.cpp12
-rw-r--r--noncore/multimedia/showimg/ImageFileSelector.cpp20
-rw-r--r--noncore/multimedia/showimg/showimg.cpp20
-rw-r--r--noncore/multimedia/showimg/showimg.pro2
-rw-r--r--noncore/multimedia/tonleiter/config.in2
-rw-r--r--noncore/multimedia/tonleiter/editinst.cpp11
-rw-r--r--noncore/multimedia/tonleiter/fretboard.cpp13
-rw-r--r--noncore/multimedia/tonleiter/tonleiter.pro6
-rw-r--r--noncore/multimedia/tonleiter/tonleiterdata.cpp11
-rw-r--r--noncore/multimedia/tonleiter/tonleiterdatahelper.cpp6
-rw-r--r--noncore/net/mail/accountitem.cpp18
-rw-r--r--noncore/net/mail/accountview.cpp12
-rw-r--r--noncore/net/mail/composemail.cpp6
-rw-r--r--noncore/net/mail/editaccounts.cpp22
-rw-r--r--noncore/net/mail/libmailwrapper/abstractmail.cpp8
-rw-r--r--noncore/net/mail/libmailwrapper/generatemail.cpp30
-rw-r--r--noncore/net/mail/libmailwrapper/genericwrapper.cpp14
-rw-r--r--noncore/net/mail/libmailwrapper/imapwrapper.cpp66
-rw-r--r--noncore/net/mail/libmailwrapper/logindialog.cpp2
-rw-r--r--noncore/net/mail/libmailwrapper/mailtypes.cpp10
-rw-r--r--noncore/net/mail/libmailwrapper/mailwrapper.cpp2
-rw-r--r--noncore/net/mail/libmailwrapper/mboxwrapper.cpp22
-rw-r--r--noncore/net/mail/libmailwrapper/mhwrapper.cpp60
-rw-r--r--noncore/net/mail/libmailwrapper/nntpwrapper.cpp8
-rw-r--r--noncore/net/mail/libmailwrapper/pop3wrapper.cpp10
-rw-r--r--noncore/net/mail/libmailwrapper/settings.cpp18
-rw-r--r--noncore/net/mail/libmailwrapper/smtpwrapper.cpp30
-rw-r--r--noncore/net/mail/libmailwrapper/statusmail.cpp6
-rw-r--r--noncore/net/mail/libmailwrapper/storemail.cpp4
-rw-r--r--noncore/net/mail/mainwindow.cpp14
-rw-r--r--noncore/net/mail/nntpgroups.cpp2
-rw-r--r--noncore/net/mail/opiemail.cpp16
-rw-r--r--noncore/net/mail/taskbarapplet/mailapplet.cpp2
-rw-r--r--noncore/net/mail/viewmail.cpp2
-rw-r--r--noncore/net/opieftp/config.in2
-rw-r--r--noncore/net/opieftp/filePermissions.cpp2
-rw-r--r--noncore/net/opieftp/opieftp.cpp77
-rw-r--r--noncore/net/opieftp/opieftp.pro11
-rw-r--r--noncore/net/opieirc/config.in2
-rw-r--r--noncore/net/opieirc/ircmisc.cpp9
-rw-r--r--noncore/net/opieirc/opieirc.pro13
-rw-r--r--noncore/net/opietooth/applet/bluezapplet.cpp2
-rw-r--r--noncore/net/opietooth/lib/startdunconnection.cpp2
-rw-r--r--noncore/net/opietooth/lib/startpanconnection.cpp8
-rw-r--r--noncore/net/opietooth/manager/bluebase.cpp16
-rw-r--r--noncore/net/opietooth/manager/devicehandler.cpp10
-rw-r--r--noncore/net/opietooth/manager/dunpopup.cpp2
-rw-r--r--noncore/net/opietooth/manager/hciconfwrapper.cpp16
-rw-r--r--noncore/net/opietooth/manager/obexdialog.cpp2
-rw-r--r--noncore/net/opietooth/manager/obexpopup.cpp4
-rw-r--r--noncore/net/opietooth/manager/panpopup.cpp2
-rw-r--r--noncore/net/opietooth/manager/popuphelper.cpp4
-rw-r--r--noncore/net/opietooth/manager/pppdialog.cpp2
-rw-r--r--noncore/net/opietooth/manager/rfcommassigndialogimpl.cpp4
-rw-r--r--noncore/net/opietooth/manager/rfcommconfhandler.cpp10
-rw-r--r--noncore/net/opietooth/manager/rfcpopup.cpp8
-rw-r--r--noncore/net/opietooth/manager/scandialog.cpp2
-rw-r--r--noncore/net/wellenreiter/gui/configwindow.cpp30
-rw-r--r--noncore/net/wellenreiter/gui/gps.cpp12
-rw-r--r--noncore/net/wellenreiter/gui/logwindow.cpp8
-rw-r--r--noncore/net/wellenreiter/gui/main.cpp15
-rw-r--r--noncore/net/wellenreiter/gui/mainwindow.cpp57
-rw-r--r--noncore/net/wellenreiter/gui/packetview.cpp2
-rw-r--r--noncore/net/wellenreiter/gui/resource.cpp4
-rw-r--r--noncore/net/wellenreiter/gui/scanlist.cpp77
-rw-r--r--noncore/net/wellenreiter/gui/wellenreiter.cpp74
-rw-r--r--noncore/settings/backup/backuprestore.cpp28
-rw-r--r--noncore/settings/netsystemtime/settingstabwidget.cpp2
-rw-r--r--noncore/settings/networksettings/interfaces/interface.cpp20
-rw-r--r--noncore/settings/networksettings/interfaces/interfaces.cpp42
-rw-r--r--noncore/settings/networksettings/interfaces/interfacesetupimp.cpp14
-rw-r--r--noncore/settings/networksettings/mainwindowimp.cpp38
-rw-r--r--noncore/settings/networksettings/ppp/accounts.cpp2
-rw-r--r--noncore/settings/networksettings/ppp/authwidget.cpp4
-rw-r--r--noncore/settings/networksettings/ppp/connect.cpp10
-rw-r--r--noncore/settings/networksettings/ppp/devices.cpp4
-rw-r--r--noncore/settings/networksettings/ppp/general.cpp2
-rw-r--r--noncore/settings/networksettings/ppp/interfaceinformationppp.cpp2
-rw-r--r--noncore/settings/networksettings/ppp/interfaceppp.cpp14
-rw-r--r--noncore/settings/networksettings/ppp/kpppwidget.cpp20
-rw-r--r--noncore/settings/networksettings/ppp/modem.cpp48
-rw-r--r--noncore/settings/networksettings/ppp/pppconfig.cpp12
-rw-r--r--noncore/settings/networksettings/ppp/pppdata.cpp92
-rw-r--r--noncore/settings/networksettings/ppp/pppmodule.cpp20
-rw-r--r--noncore/settings/networksettings/wlan/infoimp.cpp4
-rw-r--r--noncore/settings/networksettings/wlan/wextensions.cpp12
-rw-r--r--noncore/settings/networksettings/wlan/wlanimp.cpp6
-rw-r--r--noncore/settings/networksettings/wlan/wlanimp2.cpp24
-rw-r--r--noncore/settings/networksettings/wlan/wlanmodule.cpp54
-rw-r--r--noncore/settings/sound/sound.pro11
-rw-r--r--noncore/settings/sound/soundsettings.cpp16
-rw-r--r--noncore/settings/sysinfo/benchmarkinfo.cpp10
-rw-r--r--noncore/settings/tabmanager/tabmanager.cpp20
-rw-r--r--noncore/settings/usermanager/userdialog.cpp14
-rw-r--r--noncore/settings/usermanager/usermanager.cpp11
-rw-r--r--noncore/settings/usermanager/usermanager.pro9
-rw-r--r--noncore/styles/liquid/config.in2
-rw-r--r--noncore/styles/liquid/liquid.cpp27
-rw-r--r--noncore/styles/liquid/liquid.pro6
-rw-r--r--noncore/styles/theme/othemebase.cpp27
-rw-r--r--noncore/todayplugins/fortune/fortune.pro1
-rw-r--r--noncore/todayplugins/fortune/fortunepluginwidget.cpp9
-rw-r--r--noncore/todayplugins/stockticker/stockticker/inputDialog.cpp18
-rw-r--r--noncore/todayplugins/stockticker/stocktickerlib/config.in2
-rw-r--r--noncore/todayplugins/stockticker/stocktickerlib/stocktickerlib.pro5
-rw-r--r--noncore/todayplugins/stockticker/stocktickerlib/stocktickerpluginwidget.cpp10
-rw-r--r--noncore/tools/calc2/engine.cpp10
-rw-r--r--noncore/tools/calculator/calculator.pro4
-rw-r--r--noncore/tools/calculator/calculatorimpl.cpp11
-rw-r--r--noncore/tools/formatter/formatter.cpp36
-rw-r--r--noncore/tools/formatter/formatter.pro10
232 files changed, 2793 insertions, 2569 deletions
diff --git a/noncore/applets/autorotateapplet/autorotate.cpp b/noncore/applets/autorotateapplet/autorotate.cpp
index ae7fbd0..34802fb 100644
--- a/noncore/applets/autorotateapplet/autorotate.cpp
+++ b/noncore/applets/autorotateapplet/autorotate.cpp
@@ -1,97 +1,97 @@
/*
* copyright : (c) 2003 by Greg Gilbert
* email : greg@treke.net
* based on the cardmon applet by Max Reiss
* *
* 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 "autorotate.h"
/* OPIE */
-#include <opie2/odevice.h>
+#include <opie2/odebug.h>
#include <opie2/otaskbarapplet.h>
#include <qpe/applnk.h>
#include <qpe/config.h>
#include <qpe/resource.h>
+using namespace Opie::Core;
/* QT */
#include <qpainter.h>
-using namespace Opie::Ui;
AutoRotate::AutoRotate(QWidget * parent):QWidget(parent)
{
setFixedWidth( AppLnk::smallIconSize() );
setFixedHeight( AppLnk::smallIconSize() );
enabledPm.convertFromImage( Resource::loadImage("autorotate/rotate").smoothScale( height(), width() ) );
disabledPm.convertFromImage( Resource::loadImage("autorotate/norotate").smoothScale( height(), width() ) );
repaint(true);
popupMenu = 0;
show();
}
AutoRotate::~AutoRotate()
{
if (popupMenu) {
delete popupMenu;
}
}
int AutoRotate::position()
{
return 7;
}
void AutoRotate::mousePressEvent(QMouseEvent *)
{
QPopupMenu *menu = new QPopupMenu(this);
menu->insertItem( isRotateEnabled()? "Disable Rotation" : "Enable Rotation" ,1 );
QPoint p = mapToGlobal(QPoint(0, 0));
QSize s = menu->sizeHint();
int opt = menu->exec(QPoint(p.x() + (width() / 2) - (s.width() / 2), p.y() - s.height()), 0);
if (opt==1)
{
setRotateEnabled( !isRotateEnabled() );
repaint(true);
}
delete menu;
}
void AutoRotate::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.drawPixmap( 0, 0, isRotateEnabled()? enabledPm : disabledPm );
}
void AutoRotate::setRotateEnabled(bool status)
{
Config cfg( "qpe" );
cfg.setGroup( "Appearance" );
cfg.writeEntry( "rotateEnabled", status );
}
bool AutoRotate::isRotateEnabled()
{
Config cfg( "qpe" );
cfg.setGroup( "Appearance" );
bool res = cfg.readBoolEntry( "rotateEnabled" );
if (res )
- qDebug("Enabled");
+ odebug << "Enabled" << oendl;
else
- qDebug("Disabled");
+ odebug << "Disabled" << oendl;
return res;
}
-EXPORT_OPIE_APPLET_v1( AutoRotate )
+EXPORT_OPIE_APPLET_v1( AutoRotate )
diff --git a/noncore/applets/memoryapplet/swapfile.cpp b/noncore/applets/memoryapplet/swapfile.cpp
index 9416db3..a71078f 100644
--- a/noncore/applets/memoryapplet/swapfile.cpp
+++ b/noncore/applets/memoryapplet/swapfile.cpp
@@ -1,312 +1,317 @@
/**********************************************************************
** 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 "swapfile.h"
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/resource.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qfile.h>
#include <qtextstream.h>
#include <qlabel.h>
#include <qtimer.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qhbuttongroup.h>
#include <qradiobutton.h>
#include <qlineedit.h>
#include <qprogressbar.h>
#include <qcombobox.h>
#include <qvgroupbox.h>
#include <qhbox.h>
#include <qmessagebox.h>
+#include <qcopchannel_qws.h>
+
+/* STD */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-
-#include <qcopchannel_qws.h>
-#include <qpe/resource.h>
-
#include <unistd.h>
#include <fcntl.h>
#include <sys/vfs.h>
#include <mntent.h>
#include <unistd.h>
#include <sys/types.h>
Swapfile::Swapfile( QWidget *parent, const char *name, WFlags f )
: QWidget( parent, name, f )
{
// are we running as root?
isRoot = geteuid() == 0;
- QVBoxLayout* vb = new QVBoxLayout(this, 5);
+ QVBoxLayout* vb = new QVBoxLayout(this, 5);
QHButtonGroup* cfsdRBG = new QHButtonGroup(tr("Swapfile location"), this);
cfsdRBG->setRadioButtonExclusive(true);
- vb->addWidget(cfsdRBG);
+ vb->addWidget(cfsdRBG);
ramRB = new QRadioButton(tr("RAM"), cfsdRBG);
cfRB = new QRadioButton(tr("CF Card"), cfsdRBG);
sdRB = new QRadioButton(tr("SD Card"), cfsdRBG);
QHBox *hb1 = new QHBox(this);
hb1->setSpacing(5);
swapPath1 = new QLineEdit(hb1);
swapPath1->setEnabled(false);
QPushButton* swapOn = new QPushButton(tr(" On "), hb1);
QPushButton* swapOff = new QPushButton(tr(" Off "), hb1);
vb->addWidget(hb1);
QVGroupBox* box1 = new QVGroupBox(tr("Manage Swapfile"), this);
- vb->addWidget(box1);
+ vb->addWidget(box1);
QHBox *hb2 = new QHBox(box1);
hb2->setSpacing(5);
QPushButton* mkSwap = new QPushButton(tr("Generate"), hb2);
QPushButton* rmSwap = new QPushButton(tr("Remove"), hb2);
QHBox *hb3 = new QHBox(box1);
hb3->setSpacing(5);
swapSize = new QComboBox(hb3);
swapSize->insertStringList(QStringList::split(",", tr("2 Mb,4 Mb,6 Mb,8 Mb")));
mkswapProgress = new QProgressBar(3, hb3);
mkswapProgress->setCenterIndicator(true);
QHBox *hb4 = new QHBox(this);
hb4->setSpacing(5);
swapStatusIcon = new QLabel(hb4);
swapStatus = new QLabel(tr(""), hb4);
hb4->setStretchFactor(swapStatus, 99);
vb->addWidget(hb4);
connect(swapOn, SIGNAL(clicked()), this, SLOT(swapon()));
connect(swapOff, SIGNAL(clicked()), this, SLOT(swapoff()));
connect(cfRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
connect(sdRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
connect(ramRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
connect(mkSwap, SIGNAL(clicked()), this, SLOT(makeswapfile()));
connect(rmSwap, SIGNAL(clicked()), this, SLOT(removeswapfile()));
cfRB->setEnabled(FALSE);
sdRB->setEnabled(FALSE);
QCopChannel *pcmciaChannel = new QCopChannel("QPE/Card", this);
connect(pcmciaChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(cardnotify(const QCString&,const QByteArray&)));
QCopChannel *sdChannel = new QCopChannel("QPE/Card", this);
connect(sdChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(cardnotify(const QCString&,const QByteArray&)));
cardInPcmcia0 = FALSE;
cardInPcmcia1 = FALSE;
cardInSd = FALSE;
Swapfile::status();
Swapfile::getStatusPcmcia();
Swapfile::getStatusSd();
}
int Swapfile::exec(const QString& arg)
{
return system((!isRoot ? "sudo " : "") + arg);
}
Swapfile::~Swapfile()
{
}
void Swapfile::cardnotify(const QCString & msg, const QByteArray &)
{
if (msg == "stabChanged()")
{
getStatusPcmcia();
}
else if (msg == "mtabChanged()")
{
getStatusSd();
}
}
void Swapfile::getStatusPcmcia()
{
bool cardWas0 = cardInPcmcia0; // remember last state
bool cardWas1 = cardInPcmcia1;
QString fileName;
// one of these 3 files should exist
if (QFile::exists("/var/run/stab")) {
fileName = "/var/run/stab";
} else if (QFile::exists("/var/state/pcmcia/stab")) {
fileName = "/var/state/pcmcia/stab";
} else {
fileName = "/var/lib/pcmcia/stab";
}
QFile f(fileName);
if (f.open(IO_ReadOnly)) {
QStringList list;
QTextStream stream(&f);
QString streamIn;
streamIn = stream.read();
list = QStringList::split("\n", streamIn);
for (QStringList::Iterator line = list.begin(); line != list.end();
line++) {
if ((*line).startsWith("Socket 0:")) {
if ((*line).startsWith("Socket 0: empty") && cardInPcmcia0) {
cardInPcmcia0 = FALSE;
} else if (!(*line).startsWith("Socket 0: empty")
&& !cardInPcmcia0) {
cardInPcmcia0 = TRUE;
}
} else if ((*line).startsWith("Socket 1:")) {
if ((*line).startsWith("Socket 1: empty") && cardInPcmcia1) {
cardInPcmcia1 = FALSE;
} else if (!(*line).startsWith("Socket 1: empty")
&& !cardInPcmcia1) {
cardInPcmcia1 = TRUE;
}
}
}
f.close();
if (cardWas0 != cardInPcmcia0 || cardWas1 != cardInPcmcia1) {
QString text = QString::null;
QString what = QString::null;
if (cardWas0 != cardInPcmcia0) {
if (cardInPcmcia0) {
cfRB->setEnabled(TRUE);
} else {
cfRB->setChecked(FALSE);
cfRB->setEnabled(FALSE);
}
}
if (cardWas1 != cardInPcmcia1) {
if (cardInPcmcia1) {
cfRB->setEnabled(TRUE);
} else {
cfRB->setChecked(FALSE);
cfRB->setEnabled(FALSE);
}
}
}
} else {
// no file found
- qDebug("no file found");
+ odebug << "no file found" << oendl;
cardInPcmcia0 = FALSE;
cardInPcmcia1 = FALSE;
}
Swapfile::cfsdchecked();
}
void Swapfile::getStatusSd()
{
bool cardWas = cardInSd; // remember last state
cardInSd = FALSE;
#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
struct mntent *me;
FILE *mntfp = setmntent("/etc/mtab", "r");
if (mntfp) {
while ((me = getmntent(mntfp)) != 0) {
QString fs = me->mnt_fsname;
if (fs.left(14) == "/dev/mmc/part1" || fs.left(7) == "/dev/sd"
|| fs.left(9) == "/dev/mmcd") {
cardInSd = TRUE;
show();
}
}
endmntent(mntfp);
}
if (cardWas != cardInSd) {
QString text = QString::null;
QString what = QString::null;
if (cardInSd) {
sdRB->setEnabled(TRUE);
} else {
sdRB->setChecked(FALSE);
sdRB->setEnabled(FALSE);
}
}
#else
#error "Not on Linux"
#endif
Swapfile::cfsdchecked();
}
int rc=0;
void Swapfile::swapon()
{
char swapcmd[128] ="swapon ";
Swapfile::cfsdchecked();
strcat(swapcmd,swapPath1->text());
char *runcmd = swapcmd;
rc = exec(QString("%1").arg(runcmd));
if (rc != 0) {
setStatusMessage("Failed to attach swapfile.", true);
}
else {
/* QMessageBox::information(this, "Information", "Swapfile is active!"); */
setStatusMessage("Swapfile activated.");
}
Swapfile::status();
}
void Swapfile::setStatusMessage(const QString& text, bool error /* = false */)
{
swapStatus->setText("<b>" + text + "</b>");
swapStatusIcon->setPixmap(Resource::loadPixmap(error ? "close" : "done"));
}
void Swapfile::swapoff()
{
char swapcmd[128] ="swapoff ";
if (Swapfile::cfRB->isChecked() == TRUE)
Swapfile::cfsdchecked();
strcat(swapcmd,swapPath1->text());
char *runcmd = swapcmd;
rc = exec(QString("%1").arg(runcmd));
if (rc != 0) {
setStatusMessage(tr("Failed to detach swapfile."), true);
}
else {
/* QMessageBox::information(this, "Information", "Swapfile is inactive!"); */
setStatusMessage(tr("Swapfile deactivated."));
/* Swapfile::swapPath->clear();*/
}
Swapfile::status();
}
void Swapfile::cfsdchecked()
{
/* Swapfile::swapPath->clear();*/
Swapfile::swapPath1->clear();
if (Swapfile::ramRB->isChecked() == TRUE)
diff --git a/noncore/applets/networkapplet/networkapplet.cpp b/noncore/applets/networkapplet/networkapplet.cpp
index 5eb5ad2..534a8d0 100644
--- a/noncore/applets/networkapplet/networkapplet.cpp
+++ b/noncore/applets/networkapplet/networkapplet.cpp
@@ -1,253 +1,255 @@
/*
                This file is part of the Opie Project
=. (C) 2003 Michael 'Mickey' Lauer <mickey@tm.informatik.uni-frankfurt.de>
.=l.
           .>+-=
 _;:,     .>    :=|. This program is free software; you can
.> <`_,   >  .   <= redistribute it and/or modify it under
:`=1 )Y*s>-.--   : the terms of the GNU Library General Public
.="- .-=="i,     .._ License as published by the Free Software
 - .   .-<_>     .<> Foundation; either version 2 of the License,
     ._= =}       : or (at your option) any later version.
    .%`+i>       _;_.
    .i_,=:_.      -<s. This program is distributed in the hope that
     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
    : ..    .:,     . . . without even the implied warranty of
    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
..}^=.=       =       ; Library General Public License for more
++=   -.     .`     .: details.
 :     =  ...= . :.=-
 -.   .:....=;==+<; You should have received a copy of the GNU
  -_. . .   )=.  = Library General Public License along with
    --        :-=` this library; see the file COPYING.LIB.
If not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "networkapplet.h"
/* OPIE */
#include <opie2/odebug.h>
#include <opie2/onetwork.h>
#include <opie2/otaskbarapplet.h>
#include <qpe/applnk.h>
#include <qpe/resource.h>
-#include <qpainter.h>
+using namespace Opie::Core;
+using namespace Opie::Ui;
+using namespace Opie::Net;
/* QT */
+#include <qpainter.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qobjectlist.h>
+/* STD */
#include <assert.h>
-using namespace Opie::Ui;
-using namespace Opie::Net;
IfaceUpDownButton::IfaceUpDownButton( QWidget* parent, const char* name )
:QToolButton( parent, name )
{
_iface = ONetwork::instance()->interface( name );
assert( _iface );
setToggleButton( true );
//setAutoRaise( true );
setOnIconSet( QIconSet( Resource::loadPixmap( "up" ) ) );
setOffIconSet( QIconSet( Resource::loadPixmap( "down" ) ) );
setOn( _iface->isUp() );
//setFixedWidth( 16 );
connect( this, SIGNAL( clicked() ), this, SLOT( clicked() ) );
}
IfaceUpDownButton::~IfaceUpDownButton()
{
}
void IfaceUpDownButton::clicked()
{
_iface->setUp( isOn() );
setOn( _iface->isUp() ); // it might not have worked...
repaint();
}
IfaceIPAddress::IfaceIPAddress( QWidget* parent, const char* name )
:QLineEdit( parent, name )
{
setFont( QFont( "fixed" ) );
_iface = ONetwork::instance()->interface( name );
setFixedWidth( 105 );
setText( _iface->ipV4Address() );
connect( this, SIGNAL( returnPressed() ), this, SLOT( returnPressed() ) );
}
IfaceIPAddress::~IfaceIPAddress()
{
}
void IfaceIPAddress::returnPressed()
{
QHostAddress a;
a.setAddress( text() );
QHostAddress mask;
mask.setAddress( _iface->ipV4Netmask() ); // setIPV4Address destroys the netmask...
_iface->setIPV4Address( a );
_iface->setIPV4Netmask( mask ); // recover the old netmask
setText( _iface->ipV4Address() );
repaint();
}
NetworkAppletControl::NetworkAppletControl( OTaskbarApplet* parent, const char* name )
:QFrame( parent, name, WStyle_StaysOnTop | WType_Popup ), l(0)
{
setFrameStyle( QFrame::PopupPanel | QFrame::Raised );
l = new QVBoxLayout( this, 4, 2 );
}
void NetworkAppletControl::build()
{
ONetwork::InterfaceIterator it = ONetwork::instance()->iterator();
while ( it.current() )
{
QHBoxLayout* h = new QHBoxLayout( l );
QLabel* symbol = new QLabel( this );
symbol->setPixmap( Resource::loadPixmap( guessDevice( it.current() ) ) );
h->addWidget( symbol );
symbol->show();
QLabel* name = new QLabel( it.current()->name(), this );
name->setFixedWidth( 35 );
h->addWidget( name );
name->show();
IfaceIPAddress* ip = new IfaceIPAddress( this, it.current()->name() );
h->addWidget( ip );
ip->show();
IfaceUpDownButton* tb = new IfaceUpDownButton( this, it.current()->name() );
tb->show();
h->addWidget( tb );
++it;
}
}
NetworkAppletControl::~NetworkAppletControl()
{
}
QString NetworkAppletControl::guessDevice( ONetworkInterface* iface )
{
if ( iface->isWireless() )
return "networksettings/wlan";
if ( iface->isLoopback() )
return "networksettings/lo";
if ( QString( iface->name() ).contains( "usb" ) )
return "networksettings/usb";
if ( QString( iface->name() ).contains( "ir" ) )
return "networksettings/irda";
//TODO: Insert neat symbol and check for tunnel devices
return "networksettings/lan";
}
void NetworkAppletControl::showEvent( QShowEvent* e )
{
- qDebug( "showEvent" );
+ odebug << "showEvent" << oendl;
build();
QWidget::showEvent( e );
}
void NetworkAppletControl::hideEvent( QHideEvent* e )
{
- qDebug( "hideEvent" );
+ odebug << "hideEvent" << oendl;
QWidget::hideEvent( e );
delete l;
// delete all child widgets from this frame
QObjectList* list = const_cast<QObjectList*>( children() );
QObjectListIt it(*list);
QObject* obj;
while ( (obj=it.current()) )
{
++it;
delete obj;
}
list = const_cast<QObjectList*>( children() );
if ( list )
- qWarning( "D'oh! We still have %d children...", list->count() );
+ owarn << "D'oh! We still have " << list->count() << " children..." << oendl;
// renew layout
l = new QVBoxLayout( this, 4, 2 );
resize( 0, 0 );
}
QSize NetworkAppletControl::sizeHint() const
{
ONetwork::instance()->synchronize(); // rebuild interface database
- qDebug( "sizeHint (#ifaces=%d)", ONetwork::instance()->count() );
+ odebug << "sizeHint (#ifaces=" << ONetwork::instance()->count() << ")" << oendl;
return QSize( 14+35+105+14 + 8, ONetwork::instance()->count() * 26 );
}
NetworkApplet::NetworkApplet( QWidget *parent, const char *name )
:OTaskbarApplet( parent, name )
{
setFixedHeight( AppLnk::smallIconSize() );
setFixedWidth( AppLnk::smallIconSize() );
_pixmap.convertFromImage( Resource::loadImage( "networkapplet/network" ).smoothScale( height(), width() ) );
_control = new NetworkAppletControl( this, "control" );
}
NetworkApplet::~NetworkApplet()
{
}
int NetworkApplet::position()
{
return 4;
}
void NetworkApplet::paintEvent( QPaintEvent* )
{
QPainter p(this);
p.drawPixmap(0, 2, _pixmap );
}
void NetworkApplet::mousePressEvent( QMouseEvent* )
{
if ( !_control->isVisible() )
{
popup( _control );
}
else
{
_control->hide();
}
}
EXPORT_OPIE_APPLET_v1( NetworkApplet )
diff --git a/noncore/applets/notesapplet/config.in b/noncore/applets/notesapplet/config.in
index 27a8187..c92c1d5 100644
--- a/noncore/applets/notesapplet/config.in
+++ b/noncore/applets/notesapplet/config.in
@@ -1,4 +1,4 @@
config NOTESAPPLET
boolean "opie-notesapplet (quick note taking applet)"
default "y"
- depends ( LIBQPE || LIBQPE-X11 )
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
diff --git a/noncore/applets/notesapplet/notes.cpp b/noncore/applets/notesapplet/notes.cpp
index 13f7cf3..b3e72a7 100644
--- a/noncore/applets/notesapplet/notes.cpp
+++ b/noncore/applets/notesapplet/notes.cpp
@@ -1,514 +1,516 @@
/**********************************************************************
** Copyright (C) 2002 L.J. Potter <llornkcor@handhelds.org>
** All rights reserved.
**
** 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.
**
**********************************************************************/
#include "notes.h"
-#include <qapplication.h>
-#include <stdlib.h>
-#include <qstringlist.h>
-
+/* OPIE */
+#include <opie2/odebug.h>
#include <opie2/otaskbarapplet.h>
#include <qpe/filemanager.h>
#include <qpe/qpeapplication.h>
#include <qpe/timestring.h>
#include <qpe/applnk.h>
#include <qpe/ir.h>
#include <qpe/config.h>
+using namespace Opie::Core;
+using namespace Opie::Ui;
-// #include <qsocket.h>
-// #include <qclipboard.h>
+/* QT */
#include <qmultilineedit.h>
#include <qlistbox.h>
#include <qpopupmenu.h>
#include <qmessagebox.h>
-
+#include <qapplication.h>
#include <qdir.h>
#include <qfile.h>
#include <qpoint.h>
#include <qpushbutton.h>
#include <qpainter.h>
#include <qlayout.h>
#include <qframe.h>
#include <qpixmap.h>
#include <qstring.h>
+#include <qstringlist.h>
#include <qtimer.h>
+/* STD */
+#include <stdlib.h>
+
/* XPM */
-using namespace Opie::Ui;
static char * notes_xpm[] = {
"16 16 11 1",
" c None",
". c #000000",
"+ c #7F7F7F",
"@ c #BFBFBF",
"# c #BFC1FF",
"$ c #FF0000",
"% c #FFFFFF",
"& c #00037F",
"* c #0006FF",
"= c #0005BF",
"- c #7F0000",
" .. ",
" .. ",
" ... ",
" .+ ",
" .@. ",
" . .+ ",
" ..#.@. ",
" ..###.+.. ",
" ..###$...##.. ",
"..###$$$%+$$##&.",
".*=####$-###&=&.",
".=**=###==&=&=..",
" ..=**=#&=&=.. ",
" ..=*=&=.. ",
" ..=.. ",
" . "};
NotesControl::NotesControl( QWidget *, const char * )
: QVBox( 0, "NotesControl",/* WDestructiveClose | */WStyle_StaysOnTop )
// : QFrame( parent, name, WDestructiveClose | WStyle_StaysOnTop | WType_Popup )
{
QDir d( QDir::homeDirPath()+"/notes");
if( !d.exists()) {
- qDebug("make dir");
+ odebug << "make dir" << oendl;
if(!d.mkdir( QDir::homeDirPath()+"/notes", true))
- qDebug("<<<<<<<<<<<<<<<<<<<<<<<<<<<make dir failed");
+ odebug << "<<<<<<<<<<<<<<<<<<<<<<<<<<<make dir failed" << oendl;
}
Config cfg("Notes");
cfg.setGroup("Options");
showMax = cfg.readBoolEntry("ShowMax", false);
setFrameStyle( QFrame::PopupPanel | QFrame::Raised );
loaded=false;
edited=false;
doPopulate=true;
isNew=false;
QVBox *vbox = new QVBox( this, "Vlayout" );
QHBox *hbox = new QHBox( this, "HLayout" );
view = new QMultiLineEdit(vbox, "OpieNotesView");
box = new QListBox(vbox, "OpieNotesBox");
QPEApplication::setStylusOperation( box->viewport(),QPEApplication::RightOnHold);
box->setFixedHeight(50);
vbox->setMargin( 6 );
vbox->setSpacing( 3 );
setFocusPolicy(QWidget::StrongFocus);
newButton= new QPushButton( hbox, "newButton" );
newButton->setText(tr("New"));
saveButton= new QPushButton( hbox, "saveButton" );
saveButton->setText(tr("Save"));
deleteButton= new QPushButton( hbox, "deleteButton" );
deleteButton->setText(tr("Delete"));
connect( box, SIGNAL( mouseButtonPressed(int,QListBoxItem*,const QPoint&)),
this,SLOT( boxPressed(int,QListBoxItem*,const QPoint&)) );
connect(box, SIGNAL(highlighted(const QString&)), this, SLOT(slotBoxSelected(const QString&)));
connect( &menuTimer, SIGNAL( timeout() ), SLOT( showMenu() ) );
connect(view,SIGNAL( textChanged() ), this, SLOT(slotViewEdited() ) );
connect(newButton, SIGNAL(clicked()), this, SLOT(slotNewButton()));
connect(saveButton, SIGNAL(clicked()), this, SLOT(slotSaveButton()));
connect(deleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteButtonClicked()));
populateBox();
load();
setCaption("Notes");
// parent->setFocus();
}
void NotesControl::slotSaveButton() {
slotNewButton();
populateBox();
}
void NotesControl::slotDeleteButtonClicked() {
switch ( QMessageBox::warning(this,tr("Delete?")
,tr("Do you really want to<BR><B> delete</B> this note ?")
,tr("Yes"),tr("No"),0,1,1) ) {
case 0:
slotDeleteButton();
break;
};
}
void NotesControl::slotDeleteButton() {
QString selectedText = box->currentText();
- qDebug("deleting "+selectedText);
+ odebug << "deleting "+selectedText << oendl;
if( !selectedText.isEmpty()) {
Config cfg("Notes");
cfg.setGroup("Docs");
int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
QString entryName, entryName2;;
for ( int i = 0; i < noOfFiles; i++ ) {
entryName.sprintf( "File%i", i + 1 );
if(selectedText == cfg.readEntry( entryName )) {
- qDebug("removing %s, %d", selectedText.latin1(), i);
+ odebug << "removing " << selectedText.latin1() << ", " << i << "" << oendl;
for ( int j = i; j < noOfFiles; j++ ) {
entryName.sprintf( "File%i", i + 1 );
entryName2.sprintf( "File%i", i + 2 );
QString temp = cfg.readEntry(entryName2);
- qDebug("move "+temp);
+ odebug << "move "+temp << oendl;
cfg.writeEntry(entryName, temp);
i++;
}
cfg.writeEntry("NumberOfFiles", noOfFiles-1 );
entryName.sprintf( "File%i", noOfFiles );
cfg.removeEntry(entryName);
cfg.write();
DocLnk nf(selectedText);
nf.removeFiles();
QString fi=QPEApplication::documentDir()+"/text/plain/"+selectedText+".desktop";
- qDebug(fi);
+ odebug << fi << oendl;
QFile f( fi);
- if( !f.remove()) qDebug(".desktop file not removed");
+ if( !f.remove()) odebug << ".desktop file not removed" << oendl;
}
}
view->clear();
populateBox();
}
}
void NotesControl::slotNewButton() {
if(edited) save();
view->clear();
view->setFocus();
edited=false;
isNew=false;
}
void NotesControl::slotBeamButton() {
Ir ir;
if(!ir.supported()){
} else {
this->hide();
QString selectedText = box->currentText();
if( !selectedText.isEmpty()) {
QString file = QDir::homeDirPath()+"/"+selectedText;
QFile f(file);
Ir *irFile = new Ir(this, "IR");
connect( irFile, SIGNAL(done(Ir*)), this, SLOT( slotBeamFinished(Ir*)));
irFile->send( file, "Note", "text/plain" );
}
}
}
void NotesControl::slotBeamFinished(Ir *) {
this->show();
}
void NotesControl::boxPressed(int mouse, QListBoxItem *, const QPoint&) {
switch (mouse) {
case 1:{
}
break;
case 2:
menuTimer.start( 500, TRUE );
break;
};
}
void NotesControl::slotBoxSelected(const QString &itemString) {
if(edited) {
save();
}
loaded=false;
edited=false;
load(itemString);
}
void NotesControl::showMenu() {
QPopupMenu *m = new QPopupMenu(0);
m->insertItem( tr( "Beam Out" ), this, SLOT( slotBeamButton() ));
m->insertItem( tr( "Search For..." ), this, SLOT( slotSearch() ));
m->insertItem( tr( "Toggle Maximized" ), this, SLOT( slotShowMax() ));
m->insertSeparator();
m->insertItem( tr( "Delete" ), this, SLOT( slotDeleteButton() ));
m->setFocus();
m->exec( QCursor::pos() );
if(m) delete m;
}
void NotesControl::focusOutEvent ( QFocusEvent * e) {
if( e->reason() == QFocusEvent::Popup)
save();
else {
if(!loaded) {
populateBox();
load();
}
}
QWidget::focusOutEvent(e);
}
void NotesControl::save() {
Config cfg("Notes");
cfg.setGroup("Docs");
if( edited) {
-// qDebug("is edited");
+// odebug << "is edited" << oendl;
QString rt = view->text();
if( rt.length()>1) {
QString pt = rt.simplifyWhiteSpace();
int i = pt.find( ' ', pt.find( ' ' )+2 );
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 = "Empty Text";
-// qDebug(docname);
+// odebug << docname << oendl;
if( oldDocName != docname) {
int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
QString entryName;
entryName.sprintf( "File%i", noOfFiles + 1 );
cfg.writeEntry( entryName,docname );
cfg.writeEntry("NumberOfFiles", noOfFiles+1 );
cfg.write();
}
// else
-// qDebug("oldname equals docname");
+// odebug << "oldname equals docname" << oendl;
doc = new DocLnk(docname);
if(QFile(doc->linkFile()).exists())
- qDebug("puppie");
+ odebug << "puppie" << oendl;
doc->setType("text/plain");
doc->setName(docname);
QString temp = docname.replace( QRegExp(" "), "_" );
doc->setFile( QDir::homeDirPath()+"/notes/"+temp);
FileManager fm;
if ( !fm.saveFile( *doc, rt ) ) {
}
oldDocName=docname;
edited=false;
-// qDebug("save");
+// odebug << "save" << oendl;
if (doPopulate)
populateBox();
}
cfg.writeEntry( "LastDoc",oldDocName );
cfg.write();
}
}
void NotesControl::populateBox() {
box->clear();
-// qDebug("populate");
+// odebug << "populate" << oendl;
Config cfg("Notes");
cfg.setGroup("Docs");
int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
QStringList list;
QString entryName;
for ( int i = 0; i < noOfFiles; i++ ) {
entryName.sprintf( "File%i", i + 1 );
list.append(cfg.readEntry( entryName ));
}
list.sort();
box->insertStringList(list,-1);
doPopulate=false;
update();
}
void NotesControl::load() {
if(!loaded) {
Config cfg("Notes");
cfg.setGroup("Docs");
QString lastDoc=cfg.readEntry( "LastDoc","notes");
DocLnk nf;
nf.setType("text/plain");
nf.setFile(lastDoc);
loadDoc(nf);
loaded=true;
oldDocName=lastDoc;
cfg.writeEntry( "LastDoc",oldDocName );
cfg.write();
}
}
void NotesControl::load(const QString & file) {
- qDebug("loading "+file);
+ odebug << "loading "+file << oendl;
QString name = file;
QString temp;
if( !QFile( QDir::homeDirPath()+"/"+file).exists() )
temp = QDir::homeDirPath()+"/notes/"+ name.replace( QRegExp(" "), "_" );
else
temp = name;
if(!loaded) {
DocLnk nf;
nf.setType("text/plain");
nf.setFile( temp);
if(!temp.isEmpty())
loadDoc(nf);
loaded=true;
}
// view->setFocus();
oldDocName=file;
Config cfg("Notes");
cfg.setGroup("Docs");
cfg.writeEntry( "LastDoc",oldDocName );
cfg.write();
}
void NotesControl::loadDoc( const DocLnk &f) {
FileManager fm;
QString txt;
if ( !fm.loadFile( f, txt ) ) {
- qDebug("could not load file "+f.file());
+ odebug << "could not load file "+f.file() << oendl;
return;
}
view->setText(txt);
}
void NotesControl::slotViewEdited() {
if(loaded) {
edited=true;
}
}
void NotesControl::slotShowMax() {
Config cfg("Notes");
cfg.setGroup("Options");
showMax=!showMax;
cfg.writeEntry("ShowMax", showMax);
cfg.write();
hide();
}
void NotesControl::slotSearch() {
int boxCount = box->count();
for(int i=0;i< boxCount;i++) {
}
}
// void NotesControl::keyReleaseEvent( QKeyEvent *e) {
// switch ( e->state() ) {
// case ControlButton:
// if(e->key() == Key_C) { //copy
-// qDebug("copy");
+// odebug << "copy" << oendl;
// QClipboard *cb = QApplication::clipboard();
// QString text;
// // Copy text from the clipboard (paste)
// text = cb->text();
// }
// if(e->key() == Key_X) { //cut
// }
// if(e->key() == Key_V) { //paste
// QClipboard *cb = QApplication::clipboard();
// QString text;
// //view
// cb->setText();
// }
// break;
// };
// QWidget::keyReleaseEvent(e);
// }
//===========================================================================
NotesApplet::NotesApplet( QWidget *parent, const char *name )
: QWidget( parent, name ) {
setFixedHeight( 18 );
setFixedWidth( 14 );
vc = new NotesControl;
}
NotesApplet::~NotesApplet() {
delete vc;
}
int NotesApplet::position()
{
return 6;
}
void NotesApplet::mousePressEvent( QMouseEvent *) {
if( !vc->isHidden()) {
vc->doPopulate=false;
vc->save();
vc->close();
} else {
// vc = new NotesControl;
// QPoint curPos = mapToGlobal( rect().topLeft() );
if(vc->showMax) {
- qDebug("show max");
+ odebug << "show max" << oendl;
vc->showMaximized();
} else {
- qDebug("no show max");
+ odebug << "no show max" << oendl;
QWidget *wid = QPEApplication::desktop();
QRect rect = QApplication::desktop()->geometry();
vc->setGeometry( ( wid->width() / 2) - ( vc->width() / 2 ) , 28 , wid->width() -10 , 180);
vc->move ( (rect.center()/2) - (vc->rect().center()/2));
// vc->move( (( wid->width() / 2) - ( vc->width() / 2 ))-4, 28);
}
vc->show();
vc->doPopulate=true;
vc->populateBox();
vc->doPopulate=false;
vc->loaded=false;
vc->load();
// this->setFocus();
vc->view->setFocus();
}
}
void NotesApplet::paintEvent( QPaintEvent* ) {
QPainter p(this);
p.drawPixmap( 0, 1, ( const char** ) notes_xpm );
}
EXPORT_OPIE_APPLET_v1( NotesApplet )
diff --git a/noncore/applets/notesapplet/notesapplet.pro b/noncore/applets/notesapplet/notesapplet.pro
index 44e5b34..c3f9b1c 100644
--- a/noncore/applets/notesapplet/notesapplet.pro
+++ b/noncore/applets/notesapplet/notesapplet.pro
@@ -1,12 +1,12 @@
-TEMPLATE = lib
-CONFIG += qt plugin warn_on
-HEADERS = notes.h
-SOURCES = notes.cpp
-TARGET = notesapplet
-DESTDIR = $(OPIEDIR)/plugins/applets
+TEMPLATE = lib
+CONFIG += qt plugin warn_on
+HEADERS = notes.h
+SOURCES = notes.cpp
+TARGET = notesapplet
+DESTDIR = $(OPIEDIR)/plugins/applets
INCLUDEPATH += $(OPIEDIR)/include
-DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe
-VERSION = 1.0.0
+DEPENDPATH += $(OPIEDIR)/include
+LIBS += -lqpe -lopiecore2
+VERSION = 1.0.1
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/applets/wirelessapplet/wireless.cpp b/noncore/applets/wirelessapplet/wireless.cpp
index 0491a86..364f3ad 100644
--- a/noncore/applets/wirelessapplet/wireless.cpp
+++ b/noncore/applets/wirelessapplet/wireless.cpp
@@ -1,507 +1,509 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer <mickey@vanille.de>
**
** 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.
**
**********************************************************************/
#include "wireless.h"
#include "mgraph.h"
#include "advancedconfig.h"
/* OPIE */
+#include <opie2/odebug.h>
#include <opie2/onetwork.h>
#include <opie2/otaskbarapplet.h>
#include <qpe/config.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
+using namespace Opie::Ui;
+using namespace Opie::Net;
/* QT */
#include <qradiobutton.h>
#include <qpushbutton.h>
#include <qpainter.h>
#include <qlabel.h>
#include <qslider.h>
#include <qbuttongroup.h>
#include <qlayout.h>
#include <qfile.h>
#include <qtextstream.h>
/* STD */
#include <math.h>
#include <sys/types.h>
#include <signal.h>
#if defined (__GNUC__) && (__GNUC__ < 3)
#define round qRound
#endif
//#define MDEBUG
#undef MDEBUG
-using namespace Opie::Ui;
-using namespace Opie::Net;
WirelessControl::WirelessControl( WirelessApplet *applet, QWidget *parent, const char *name )
: QFrame( parent, name, WStyle_StaysOnTop | WType_Popup ), applet( applet )
{
readConfig();
writeConfigEntry( "UpdateFrequency", updateFrequency );
setFrameStyle( QFrame::PopupPanel | QFrame::Raised );
QGridLayout *grid = new QGridLayout( this, 3, 2, 6, 2, "top layout" );
/* status label */
statusLabel = new QLabel( this, "statuslabel" );
QString text( "Wireless Status:<br>"
"*** Unknown ***<br>"
"Card not inserted ?<br>"
"Or Sharp ROM ?<br>"
"CELL: 00:00:00:00:00:00" );
/* QString text( "Station: Unknown<br>"
"ESSID: Unknown<br>"
"MODE: Unknown<br>"
"FREQ: Unknown<br>"
"CELL: AA:BB:CC:DD:EE:FF" ); */
statusLabel->setText( text );
statusLabel->setFixedSize( statusLabel->sizeHint() );
grid->addWidget( statusLabel, 0, 0 );
/* visualization group box */
/* quality graph */
mgraph = new MGraph( this );
mgraph->setFrameStyle( QFrame::Panel | QFrame::Sunken );
mgraph->setMin( 0 );
mgraph->setMax( 92 );
grid->addWidget( mgraph, 1, 0 );
mgraph->setFocusPolicy( QWidget::NoFocus );
/* advanced configuration Button */
QPushButton* advanced = new QPushButton( "Advanced...", this );
advanced->setFocusPolicy( QWidget::NoFocus );
grid->addWidget( advanced, 2, 0, Qt::AlignCenter );
connect( advanced, SIGNAL( clicked() ),
this, SLOT( advancedConfigClicked() ) );
/* update Frequency Label */
updateLabel = new QLabel( this );
text.sprintf( "Update every %d s", updateFrequency );
updateLabel->setText( text );
grid->addWidget( updateLabel, 2, 1 );
/* update Frequency Slider */
QSlider* updateSlider = new QSlider( QSlider::Horizontal, this );
updateSlider->setRange( 0, 9 );
updateSlider->setValue( updateFrequency );
updateSlider->setTickmarks( QSlider::Both );
updateSlider->setTickInterval( 1 );
updateSlider->setSteps( 1, 1 );
updateSlider->setFocusPolicy( QWidget::NoFocus );
grid->addWidget( updateSlider, 1, 1 );
connect( updateSlider, SIGNAL( valueChanged(int) ),
this, SLOT( updateDelayChange(int) ) );
setFixedSize( sizeHint() );
setFocusPolicy( QWidget::NoFocus );
applet->updateDelayChange( updateFrequency );
applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE );
}
void WirelessControl::advancedConfigClicked()
{
AdvancedConfig * a = new AdvancedConfig( this, "dialog", TRUE );
int result = a->exec();
a->hide();
delete a;
if ( result == QDialog::Accepted )
{
readConfig();
applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE );
}
}
void WirelessControl::updateDelayChange( int delay )
{
QString text;
text.sprintf( "Update every %d s", delay );
updateLabel->setText( text );
applet->updateDelayChange( delay );
writeConfigEntry( "UpdateFrequency", delay );
}
void WirelessControl::displayStyleChange( int style )
{
applet->displayStyleChange( style );
writeConfigEntry( "DisplayStyle", style );
}
void WirelessControl::show ( bool )
{
QPoint curPos = applet->mapToGlobal( QPoint ( 0, 0 ) );
int w = sizeHint().width();
int x = curPos.x() - ( w / 2 );
if ( ( x + w ) > QPEApplication::desktop() ->width() )
x = QPEApplication::desktop ( ) -> width ( ) - w;
move( x, curPos.y () - sizeHint().height () );
QFrame::show();
}
void WirelessControl::readConfig()
{
Config cfg( "qpe" );
cfg.setGroup( "Wireless" );
updateFrequency = cfg.readNumEntry( "UpdateFrequency", 2 );
rocESSID = cfg.readBoolEntry( "renew_dhcp_on_essid_change", false );
rocFREQ = cfg.readBoolEntry( "renew_dhcp_on_freq_change", false );
rocAP = cfg.readBoolEntry( "renew_dhcp_on_ap_change", false );
rocMODE = cfg.readBoolEntry( "renew_dhcp_on_mode_change", false );
}
void WirelessControl::writeConfigEntry( const char *entry, int val )
{
Config cfg( "qpe" );
cfg.setGroup( "Wireless" );
cfg.writeEntry( entry, val );
}
//===========================================================================
WirelessApplet::WirelessApplet( QWidget *parent, const char *name )
: QWidget( parent, name ),
timer( 0 ), interface( 0 ), oldiface( 0 ),
rocESSID( false ), rocFREQ( false ), rocAP( false ), rocMODE( false )
{
setFixedHeight( 18 );
setFixedWidth( 14 );
status = new WirelessControl( this, this, "wireless status" );
}
void WirelessApplet::checkInterface()
{
interface = 0L;
ONetwork* net = ONetwork::instance();
net->synchronize();
ONetwork::InterfaceIterator it = net->iterator();
while ( it.current() && !it.current()->isWireless() ) ++it;
if ( it.current() && it.current()->isWireless() )
interface = static_cast<OWirelessNetworkInterface*>( it.current() );
if ( interface )
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: using interface '%s'", ( const char* ) interface->name() );
+ odebug << "WIFIAPPLET: using interface '" << ( const char* ) interface->name() << "'" << oendl;
#endif
}
else
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: D'oh! No Wireless interface present... :(" );
+ odebug << "WIFIAPPLET: D'oh! No Wireless interface present... :(" << oendl;
#endif
hide();
}
}
void WirelessApplet::renewDHCP()
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: Going to request a DHCP configuration renew." );
+ odebug << "WIFIAPPLET: Going to request a DHCP configuration renew." << oendl;
#endif
QString pidfile;
if ( !interface )
return ;
QString ifacename( interface->name() );
// At first we are trying dhcpcd
pidfile.sprintf( "/var/run/dhcpcd-%s.pid", ( const char* ) ifacename );
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: dhcpcd pidfile is '%s'", ( const char* ) pidfile );
+ odebug << "WIFIAPPLET: dhcpcd pidfile is '" << ( const char* ) pidfile << "'" << oendl;
#endif
int pid;
QFile pfile( pidfile );
bool hasFile = pfile.open( IO_ReadOnly );
QTextStream s( &pfile );
if ( hasFile )
{
s >> pid;
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: sent SIGALARM to pid %d", pid );
+ odebug << "WIFIAPPLET: sent SIGALARM to pid " << pid << "" << oendl;
#endif
kill( pid, SIGALRM );
return ;
}
// No dhcpcd, so we are trying udhcpc
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: dhcpcd not available." );
+ odebug << "WIFIAPPLET: dhcpcd not available." << oendl;
#endif
pidfile.sprintf( "/var/run/udhcpc.%s.pid", ( const char* ) ifacename );
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: udhcpc pidfile is '%s'", ( const char* ) pidfile );
+ odebug << "WIFIAPPLET: udhcpc pidfile is '" << ( const char* ) pidfile << "'" << oendl;
#endif
QFile pfile2( pidfile );
hasFile = pfile2.open( IO_ReadOnly );
QTextStream s2( &pfile2 );
if ( hasFile )
{
s2 >> pid;
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: sent SIGUSR1 to pid %d", pid );
+ odebug << "WIFIAPPLET: sent SIGUSR1 to pid " << pid << "" << oendl;
#endif
kill( pid, SIGUSR1 );
return ;
}
}
void WirelessApplet::updateDHCPConfig( bool ESSID, bool FREQ, bool AP, bool MODE )
{
rocESSID = ESSID;
rocFREQ = FREQ;
rocAP = AP;
rocMODE = MODE;
}
void WirelessApplet::updateDelayChange( int delay )
{
if ( timer )
killTimer( timer );
delay *= 1000;
if ( delay == 0 )
delay = 50;
timer = startTimer( delay );
}
void WirelessApplet::displayStyleChange( int style )
{
visualStyle = style;
repaint();
}
WirelessApplet::~WirelessApplet()
{}
void WirelessApplet::timerEvent( QTimerEvent* )
{
#ifdef MDEBUG
- qDebug( "WirelessApplet::timerEvent" );
+ odebug << "WirelessApplet::timerEvent" << oendl;
#endif
if ( interface )
{
if ( !ONetwork::instance()->isPresent( (const char*) interface->name() ) )
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: Interface no longer present." );
+ odebug << "WIFIAPPLET: Interface no longer present." << oendl;
#endif
interface = 0L;
mustRepaint();
return;
}
if ( mustRepaint() )
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: A value has changed -> repainting." );
+ odebug << "WIFIAPPLET: A value has changed -> repainting." << oendl;
#endif
repaint();
}
if ( status->isVisible() )
{
updatePopupWindow();
}
}
else
{
checkInterface();
}
}
void WirelessApplet::mousePressEvent( QMouseEvent * )
{
if ( status->isVisible() )
status->hide();
else
status->show( true );
}
bool WirelessApplet::mustRepaint()
{
// check if there are enough changes to justify a (flickering) repaint
// has the interface changed?
if ( interface != oldiface )
{
oldiface = interface;
if ( interface )
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: We had no interface but now we have one! :-)" );
+ odebug << "WIFIAPPLET: We had no interface but now we have one! :-)" << oendl;
#endif
show();
}
else
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: We had a interface but now we don't have one! ;-(" );
+ odebug << "WIFIAPPLET: We had a interface but now we don't have one! ;-(" << oendl;
#endif
hide();
return true;
}
}
int rings = numberOfRings();
if ( rings != oldrings )
{
oldrings = rings;
return true;
}
int noiseH = 50; // iface->noisePercent() * ( height() - 3 ) / 100;
int signalH = interface->signalStrength() * ( height() - 3 ) / 100;
int qualityH = 50; // iface->qualityPercent() * ( height() - 3 ) / 100;
if ( ( noiseH != oldnoiseH )
|| ( signalH != oldsignalH )
|| ( qualityH != oldqualityH ) )
{
oldnoiseH = noiseH;
oldsignalH = signalH;
oldqualityH = qualityH;
return true;
}
if ( rocESSID && ( oldESSID != interface->SSID() ) )
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: ESSID has changed." );
+ odebug << "WIFIAPPLET: ESSID has changed." << oendl;
#endif
renewDHCP();
}
else if ( rocFREQ && ( oldFREQ != interface->frequency() ) )
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: FREQ has changed." );
+ odebug << "WIFIAPPLET: FREQ has changed." << oendl;
#endif
renewDHCP();
}
else if ( rocAP && ( oldAP != interface->associatedAP().toString() ) )
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: AP has changed." );
+ odebug << "WIFIAPPLET: AP has changed." << oendl;
#endif
renewDHCP();
}
else if ( rocMODE && ( oldMODE != interface->mode() ) )
{
#ifdef MDEBUG
- qDebug( "WIFIAPPLET: MODE has changed." );
+ odebug << "WIFIAPPLET: MODE has changed." << oendl;
#endif
renewDHCP();
}
oldESSID = interface->SSID();
oldMODE = interface->mode();
oldFREQ = interface->frequency();
oldAP = interface->associatedAP().toString();
return false;
}
void WirelessApplet::updatePopupWindow()
{
int qualityH = interface->signalStrength();
if ( status->mgraph )
status->mgraph->addValue( qualityH, false );
QString freqString;
QString cell = ( interface->mode() == "Managed" ) ? "AP: " : "Cell: ";
freqString.sprintf( "%.3f GHz", interface->frequency() );
status->statusLabel->setText( "Station: " + interface->nickName() + "<br>" +
"ESSID: " + interface->SSID() + "<br>" +
"MODE: " + interface->mode() + "<br>" +
"FREQ: " + freqString + "<br>" +
cell + " " + interface->associatedAP().toString() );
}
int WirelessApplet::numberOfRings()
{
if ( !interface ) return -1;
int qualityH = interface->signalStrength();
- qDebug( "quality = %d", qualityH );
+ odebug << "quality = " << qualityH << "" << oendl;
if ( qualityH < 1 ) return -1;
if ( qualityH < 20 ) return 0;
if ( qualityH < 40 ) return 1;
if ( qualityH < 60 ) return 2;
if ( qualityH < 65 ) return 3;
return 4;
}
void WirelessApplet::paintEvent( QPaintEvent* )
{
QPainter p( this );
int h = height();
int w = width();
int m = 2;
p.drawLine( m, h-m-1, round( w/2.0 ), round( 0+h/3.0 ) );
p.drawLine( round( w/2.0 ), round( 0+h/3.0 ), w-m, h-m-1 );
p.setPen( QColor( 150, 150, 150 ) );
p.drawLine( w-m, h-m-1, m, h-m-1 );
int rings = numberOfRings();
if ( rings == -1 )
{
p.setPen( QPen( QColor( 200, 20, 20 ), 2 ) );
p.drawLine( w/2-m-m, h/2-m-m, w/2+m+m, h/2+m+m );
p.drawLine( w/2+m+m, h/2-m-m, w/2-m-m, h/2+m+m );
return;
}
- qDebug( "WirelessApplet: painting %d rings", rings );
+ odebug << "WirelessApplet: painting " << rings << " rings" << oendl;
int radius = 2;
int rstep = 4;
int maxrings = w/rstep;
p.setPen( QColor( 200, 20, 20 ) );
for ( int i = 0; i < rings; ++i )
{
p.drawEllipse( w/2 - radius/2, h/3 - radius/2, radius, radius );
radius += rstep;
};
}
int WirelessApplet::position()
{
return 6;
}
EXPORT_OPIE_APPLET_v1( WirelessApplet )
diff --git a/noncore/applets/zkbapplet/zkbwidget.cpp b/noncore/applets/zkbapplet/zkbwidget.cpp
index 3acff1e..13d554c 100644
--- a/noncore/applets/zkbapplet/zkbwidget.cpp
+++ b/noncore/applets/zkbapplet/zkbwidget.cpp
@@ -1,161 +1,161 @@
#include <opie2/otaskbarapplet.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/applnk.h>
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
#include <stdio.h>
#include <unistd.h>
#include "zkbwidget.h"
#include "zkbcfg.h"
using namespace Opie::Ui;
ZkbWidget::ZkbWidget(QWidget* parent):QLabel(parent),keymap(0),
disabled(Resource::loadPixmap("zkb-disabled")) {
labels = new QPopupMenu();
connect(labels, SIGNAL(activated(int)), this,
SLOT(labelChanged(int)));
loadKeymap();
channel = new QCopChannel("QPE/zkb", this);
connect(channel, SIGNAL(received(const QCString&,const QByteArray&)),
this, SLOT(signalReceived(const QCString&,const QByteArray&)));
setFixedWidth ( AppLnk::smallIconSize() );
setFixedHeight ( AppLnk::smallIconSize() );
}
ZkbWidget::~ZkbWidget() {
}
int ZkbWidget::position()
{
return 8;
}
bool ZkbWidget::loadKeymap() {
ZkbConfig c(QPEApplication::qpeDir()+"/share/zkb");
QFontMetrics fm(font());
if (keymap != 0) {
delete keymap;
keymap = 0;
}
Keymap* km = new Keymap();
if (!c.load("zkb.xml", *km, "")) {
delete km;
setPixmap(disabled);
return false;
}
connect(km, SIGNAL(stateChanged(const QString&)),
this, SLOT(stateChanged(const QString&)));
qwsServer->setKeyboardFilter(km);
Keymap* oldkm = keymap;
keymap = km;
if (oldkm != 0) {
delete oldkm;
}
setText(keymap->getCurrentLabel());
labels->clear();
QStringList l = keymap->listLabels();
labels->insertItem(disabled, 0, 0);
int n = 1;
w = 0;
for(QStringList::Iterator it = l.begin(); it != l.end();
++it, n++) {
// printf("label: %s\n", (const char*) (*it).utf8());
labels->insertItem(*it, n, n);
int lw = fm.width(*it);
if (lw > w) {
w = lw;
}
}
if (w == 0) {
hide();
} else {
show();
}
return true;
}
QSize ZkbWidget::sizeHint() const {
return QSize(AppLnk::smallIconSize(),AppLnk::smallIconSize());
}
void ZkbWidget::stateChanged(const QString& s) {
-// qDebug("stateChanged: %s\n", (const char*) s.utf8());
+// odebug << "stateChanged: " << (const char*) s.utf8() << "\n" << oendl;
setText(s);
}
void ZkbWidget::labelChanged(int id) {
if (id == 0) {
keymap->disable();
setPixmap(disabled);
return;
}
keymap->enable();
QStringList l = keymap->listLabels();
QString lbl = l[id-1];
// printf("labelChanged: %s\n", (const char*) lbl.utf8());
State* state = keymap->getStateByLabel(lbl);
if (state != 0) {
keymap->setCurrentState(state);
setText(lbl);
}
}
void ZkbWidget::mouseReleaseEvent(QMouseEvent*) {
QSize sh = labels->sizeHint();
QPoint p = mapToGlobal(QPoint((width()-sh.width())/2,-sh.height()));
labels->exec(p);
}
void ZkbWidget::signalReceived(const QCString& msg, const QByteArray& data) {
QDataStream stream(data, IO_ReadOnly);
if (msg == "enable()") {
keymap->enable();
} else if (msg == "disable()") {
keymap->disable();
} else if (msg == "reload()") {
QCopEnvelope("QPE/System", "busy()");
QTimer::singleShot(0, this, SLOT(reload()));
} else if (msg == "switch(QString)") {
QString lbl;
stream >> lbl;
if (keymap != 0) {
State* state = keymap->getStateByLabel(lbl);
if (state != 0) {
keymap->setCurrentState(state);
setText(lbl);
}
}
} else if (msg == "debug(QString)") {
QString flag;
stream >> flag;
}
}
void ZkbWidget::reload() {
loadKeymap();
QCopEnvelope("QPE/System", "notBusy()");
}
EXPORT_OPIE_APPLET_v1( ZkbWidget )
diff --git a/noncore/apps/advancedfm/advancedfm.cpp b/noncore/apps/advancedfm/advancedfm.cpp
index a60d6ce..a47edd8 100644
--- a/noncore/apps/advancedfm/advancedfm.cpp
+++ b/noncore/apps/advancedfm/advancedfm.cpp
@@ -1,479 +1,479 @@
/***************************************************************************
AdvancedFm.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 "advancedfm.h"
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include <qpe/mimetype.h>
#include <qpe/applnk.h>
#include <qpe/resource.h>
#include <qpe/menubutton.h>
#include <qcombobox.h>
#include <qpopupmenu.h>
#include <qlistview.h>
#include <qmessagebox.h>
#include <qlineedit.h>
#include <sys/stat.h>
#include <time.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/vfs.h>
#include <mntent.h>
using namespace Opie::Ui;
#ifdef NOQUICKLAUNCH
AdvancedFm::AdvancedFm( )
#else
AdvancedFm::AdvancedFm(QWidget *,const char*, WFlags )
#endif
: QMainWindow( ) {
init();
renameBox = 0;
unknownXpm = Resource::loadImage( "UnknownDocument" ).smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() );
initConnections();
whichTab=1;
rePopulate();
currentPathCombo->setFocus();
channel = new QCopChannel( "QPE/Application/advancedfm", this );
connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
this, SLOT( qcopReceive(const QCString&,const QByteArray&)) );
}
AdvancedFm::~AdvancedFm() {
}
void AdvancedFm::cleanUp() {
QString sfile=QDir::homeDirPath();
if(sfile.right(1) != "/")
sfile+="/._temp";
else
sfile+="._temp";
QFile file( sfile);
if(file.exists())
file.remove();
}
void AdvancedFm::tabChanged(QWidget *) {
-// qWarning("tab changed");
+// owarn << "tab changed" << oendl;
QString path = CurrentDir()->canonicalPath();
currentPathCombo->lineEdit()->setText( path );
if(whichTab == 1) {
viewMenu->setItemChecked(viewMenu->idAt(0), true);
viewMenu->setItemChecked(viewMenu->idAt(1), false);
} else {
viewMenu->setItemChecked(viewMenu->idAt(0), false);
viewMenu->setItemChecked(viewMenu->idAt(1), true);
}
QString fs= getFileSystemType( (const QString &) path);
setCaption(tr("AdvancedFm :: ")+fs+" :: "
+checkDiskSpace( (const QString &) path )+ tr(" kB free") );
chdir( path.latin1());
}
void AdvancedFm::populateView() {
-// qWarning("PopulateView");
+// owarn << "PopulateView" << oendl;
QPixmap pm;
QListView *thisView = CurrentView();
QDir *thisDir = CurrentDir();
QString path = thisDir->canonicalPath();
-//qWarning("path is "+path);
+//owarn << "path is "+path << oendl;
thisView->clear();
thisDir->setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
thisDir->setMatchAllDirs(TRUE);
thisDir->setNameFilter(filterStr);
QString fileL, fileS, fileDate;
QString fs= getFileSystemType((const QString &) path);
setCaption(tr("AdvancedFm :: ")+fs+" :: "
+checkDiskSpace((const QString &) path)+ tr(" kB free") );
bool isDir=FALSE;
const QFileInfoList *list = thisDir->entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/);
QFileInfoListIterator it(*list);
QFileInfo *fi;
while ( (fi=it.current()) ) {
if (fi->isSymLink() ) {
QString symLink=fi->readLink();
QFileInfo sym( symLink);
fileS.sprintf( "%10i", sym.size() );
fileL = fi->fileName() +" -> " + sym.filePath().data();
fileDate = sym.lastModified().toString();
} else {
fileS.sprintf( "%10i", fi->size() );
fileL = fi->fileName();
fileDate= fi->lastModified().toString();
if( QDir(QDir::cleanDirPath( path +"/"+fileL)).exists() ) {
// if(fileL == "..")
fileL += "/";
isDir=TRUE;
}
}
QFileInfo fileInfo( path + "/" + fileL);
if(fileL !="./" && fi->exists()) {
item = new QListViewItem( thisView, fileL, fileS , fileDate);
if(isDir || fileL.find("/",0,TRUE) != -1) {
if( !QDir( fi->filePath() ).isReadable()) //is directory
pm = Resource::loadPixmap( "lockedfolder" );
else
pm= Resource::loadPixmap( "folder" );
}
else if ( fs == "vfat" && fileInfo.filePath().contains("/bin") ) {
pm = Resource::loadPixmap( "exec");
}
else if( (fileInfo.permission( QFileInfo::ExeUser)
| fileInfo.permission( QFileInfo::ExeGroup)
| fileInfo.permission( QFileInfo::ExeOther)) && fs != "vfat" ) {
pm = Resource::loadPixmap( "exec");
}
else if( !fi->isReadable() ) {
pm = Resource::loadPixmap( "locked" );
}
else { //everything else goes by mimetype
MimeType mt(fi->filePath());
pm=mt.pixmap(); //sets the correct pixmap for mimetype
if(pm.isNull()) {
pm = unknownXpm;
}
}
if( fi->isSymLink() || fileL.find("->",0,TRUE) != -1) {
- // qDebug(" overlay link image");
+ // odebug << " overlay link image" << oendl;
pm= Resource::loadPixmap( "advancedfm/symlink" );
// 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;
}
if( path.find("dev",0,TRUE) != -1) {
struct stat buf;
dev_t devT;
DIR *dir;
struct dirent *mydirent;
if((dir = opendir( path.latin1())) != NULL)
while ((mydirent = readdir(dir)) != NULL) {
lstat( mydirent->d_name, &buf);
-// qDebug(mydirent->d_name);
+// odebug << mydirent->d_name << oendl;
fileL.sprintf("%s", mydirent->d_name);
devT = buf.st_dev;
fileS.sprintf("%d, %d", (int) ( devT >>8) &0xFF, (int)devT &0xFF);
fileDate.sprintf("%s", ctime( &buf.st_mtime));
if( fileL.find(".") == -1 ) {
item= new QListViewItem( thisView, fileL, fileS, fileDate);
pm = unknownXpm;
item->setPixmap( 0,pm);
}
}
closedir(dir);
}
thisView->setSorting( 3,FALSE);
fillCombo( (const QString &) path );
}
void AdvancedFm::rePopulate() {
populateView();
setOtherTabCurrent();
populateView();
// int tmpTab = whichTab;
-// // qDebug("%d", tmpTab);
+// // odebug << "" << tmpTab << "" << oendl;
// for(int i =1; i < 3; i++) {
// TabWidget->setCurrentWidget(i - 1);
// populateView();
// }
// TabWidget->setCurrentWidget( tmpTab - 1);
}
void AdvancedFm::ListClicked(QListViewItem *selectedItem) {
-//qWarning("listclicked");
+//owarn << "listclicked" << oendl;
if(selectedItem) {
QString strItem=selectedItem->text(0);
-// qWarning(strItem);
+// owarn << strItem << oendl;
QString strSize=selectedItem->text(1);
strSize=strSize.stripWhiteSpace();
bool isDirectory = false;
QString strItem2;
if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) {//if symlink
strItem2 = dealWithSymName((const QString&)strItem);
if(QDir(strItem2).exists() )
strItem = strItem2;
}
if( strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) {
if(QDir(strItem).exists())
isDirectory = true;
}
if( isDirectory ) {
CurrentDir()->cd( strItem, TRUE);
populateView();
CurrentView()->ensureItemVisible( CurrentView()->firstChild());
}
chdir( strItem.latin1());
}
}
void AdvancedFm::ListPressed( int mouse, QListViewItem *item, const QPoint& , int ) {
dealWithSchmooSchmaa( item->listView());
switch (mouse) {
case 1:
{
if(renameBox != 0 ) {
cancelRename();
}
}
break;
case 2:
menuTimer.start( 500, TRUE );
break;
};
}
void AdvancedFm::switchToLocalTab() {
-//qWarning("switch to local view");
+//owarn << "switch to local view" << oendl;
TabWidget->setCurrentWidget(0);
Local_View->setFocus();
}
void AdvancedFm::switchToRemoteTab() {
-//qWarning("switch to local view");
+//owarn << "switch to local view" << oendl;
TabWidget->setCurrentWidget(1);
Remote_View->setFocus();
}
void AdvancedFm::readConfig() {
Config cfg("AdvancedFm");
}
void AdvancedFm::writeConfig() {
Config cfg("AdvancedFm");
}
void AdvancedFm::currentPathComboChanged() {
if(QDir( currentPathCombo->lineEdit()->text()).exists()) {
CurrentDir()->setPath( currentPathCombo->lineEdit()->text() );
populateView();
} else {
QMessageBox::message(tr("Note"),tr("That directory does not exist"));
}
}
void AdvancedFm::fillCombo(const QString &currentPath) {
if ( whichTab == 1) {
currentPathCombo->lineEdit()->setText( currentPath);
if( localDirPathStringList.grep( currentPath,TRUE).isEmpty() ) {
currentPathCombo->clear();
localDirPathStringList.prepend( currentPath );
currentPathCombo->insertStringList( localDirPathStringList,-1);
}
} else {
currentPathCombo->lineEdit()->setText( currentPath);
if( remoteDirPathStringList.grep( currentPath,TRUE).isEmpty() ) {
currentPathCombo->clear();
remoteDirPathStringList.prepend( currentPath );
currentPathCombo->insertStringList( remoteDirPathStringList,-1);
}
}
}
void AdvancedFm::currentPathComboActivated(const QString & currentPath) {
chdir( currentPath.latin1() );
CurrentDir()->cd( currentPath, TRUE);
populateView();
update();
}
QStringList AdvancedFm::getPath() {
QStringList strList;
QListView *thisView=CurrentView();
QList<QListViewItem> * getSelectedItems( QListView * thisView );
QListViewItemIterator it( thisView );
for ( ; it.current(); ++it ) {
if ( it.current()->isSelected() ) {
strList << it.current()->text(0);
-// qDebug(it.current()->text(0));
+// odebug << it.current()->text(0) << oendl;
}
}
return strList;
}
void AdvancedFm::homeButtonPushed() {
QString current = QDir::homeDirPath();
chdir( current.latin1() );
CurrentDir()->cd( current, TRUE);
populateView();
update();
}
void AdvancedFm::docButtonPushed() {
QString current = QPEApplication::documentDir();
chdir( current.latin1() );
CurrentDir()->cd( current, TRUE);
populateView();
update();
}
void AdvancedFm::SDButtonPushed() {
QString current = "/mnt/card";// this can change so fix
chdir( current.latin1() );
CurrentDir()->cd( current, TRUE);
populateView();
update();
}
void AdvancedFm::CFButtonPushed() {
QString current;
if(zaurusDevice)
current= "/mnt/cf"; //zaurus
else
current = "/mnt/hda"; //ipaq
chdir( current.latin1() );
CurrentDir()->cd( current, TRUE);
populateView();
update();
}
void AdvancedFm::doAbout() {
QMessageBox::message("AdvancedFm",tr("Advanced FileManager\n"
"is copyright 2002-2003 by\n"
"L.J.Potter<llornkcor@handhelds.org>\n"
"and is licensed by the GPL"));
}
void AdvancedFm::keyPressEvent( QKeyEvent *e) {
-// qWarning("key %d", e->key());
+// owarn << "key " << e->key() << "" << oendl;
// if( CurrentView()->hasFocus() )
{
switch ( e->key() ) {
case Key_Left:
upDir();
break;
case Key_Next:
break;
case Key_Return:
case Key_Enter:
navigateToSelected();
break;
case Key_Tab: {
setOtherTabCurrent();
}
break;
case Key_Delete:
del();
break;
case Key_A:
copyAs();
break;
case Key_C:
copy();
break;
case Key_E:
runThis();
break;
case Key_G:
{
currentPathCombo->lineEdit()->setFocus();
}
break;
case Key_H:
showHidden();
break;
case Key_I:
fileStatus();
break;
case Key_M:
move();
break;
case Key_N:
mkDir();
break;
case Key_P:
filePerms();
break;
case Key_R:
rn();
break;
case Key_U:
upDir();
break;
case Key_1:
switchToLocalTab();
break;
case Key_2:
switchToRemoteTab();
break;
case Key_3:
CFButtonPushed();
break;
case Key_4:
SDButtonPushed();
break;
case Key_5:
homeButtonPushed();
break;
case Key_6:
docButtonPushed();
break;
case Key_7:
break;
case Key_8:
break;
case Key_9:
break;
case Key_0:
break;
};
e->accept();
}
}
void AdvancedFm::keyReleaseEvent( QKeyEvent *e) {
if( CurrentView()->hasFocus() )
e->ignore();
}
void AdvancedFm::QPEButtonPushed() {
QString current = QPEApplication::qpeDir();
chdir( current.latin1() );
CurrentDir()->cd( current, TRUE);
@@ -545,341 +545,341 @@ void AdvancedFm::showFileMenu() {
MimeType mt( curApp );
const AppLnk* app = mt.application();
QFile fi(curApp);
QPopupMenu *m = new QPopupMenu(0);
QPopupMenu *n = new QPopupMenu(0);
// QPopupMenu *o = new QPopupMenu(0);
m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() ));
if ( QFileInfo(fi).isDir() ) {
m->insertSeparator();
m->insertItem( tr( "Change Directory" ), this, SLOT( doDirChange() ));
} else {
if ( app )
m->insertItem( app->pixmap(), tr( "Open in "
+ app->name() ), this, SLOT( runThis() ) );
else if( QFileInfo(fi).isExecutable() ) //damn opie doesnt like this
m->insertItem( tr( "Execute" ), this, SLOT( runThis() ) );
m->insertItem( Resource::loadPixmap( "txt" ), tr( "Open as text" ),this, SLOT( runText() ) );
}
m->insertItem(tr("Actions"),n);
n->insertItem( tr( "Make Directory" ), this, SLOT( makeDir() ));
n->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() ));
n->insertSeparator();
n->insertItem( tr( "Rename" ), this, SLOT( renameIt() ));
n->insertItem( tr( "Copy" ), this, SLOT( copy() ));
n->insertItem( tr( "Copy As" ), this, SLOT( copyAs() ));
n->insertItem( tr( "Copy Same Dir" ), this, SLOT( copySameDir() ));
n->insertItem( tr( "Move" ), this, SLOT( move() ));
n->insertSeparator();
n->insertItem( tr( "Delete" ), this, SLOT( doDelete() ));
m->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() ));
m->insertItem( tr( "Run Command" ), this, SLOT( runCommand() ));
m->insertItem( tr( "File Info" ), this, SLOT( fileStatus() ));
m->insertSeparator();
m->insertItem( tr( "Set Permissions" ), this, SLOT( filePerms() ));
#if defined(QT_QWS_OPIE)
m->insertItem( tr( "Properties" ), this, SLOT( doProperties() ));
#endif
m->setCheckable(TRUE);
if (!b)
m->setItemChecked(m->idAt(0),TRUE);
else
m->setItemChecked(m->idAt(0),FALSE);
if(Ir::supported())
m->insertItem( tr( "Beam File" ), this, SLOT( doBeam() ));
m->setFocus();
m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) );
if(m) delete m;
}
void AdvancedFm::cancelMenuTimer() {
if( menuTimer.isActive() )
menuTimer.stop();
}
QString AdvancedFm::checkDiskSpace(const QString &path) {
struct statfs fss;
if ( !statfs( path.latin1(), &fss ) ) {
int blkSize = fss.f_bsize;
// int totalBlks = fs.f_blocks;
int availBlks = fss.f_bavail;
long mult = blkSize / 1024;
long div = 1024 / blkSize;
if ( !mult ) mult = 1;
if ( !div ) div = 1;
return QString::number(availBlks * mult / div);
}
return "";
}
void AdvancedFm::addToDocs() {
QStringList strListPaths = getPath();
QDir *thisDir = CurrentDir();
if( strListPaths.count() > 0) {
QString curFile;
for ( QStringList::Iterator it = strListPaths.begin(); it != strListPaths.end(); ++it ) {
curFile = thisDir->canonicalPath()+"/"+(*it);
-// qDebug(curFile);
+// odebug << curFile << oendl;
QFileInfo fi(curFile);
DocLnk f;
// curFile.replace(QRegExp("\\..*"),"");
f.setName(fi.baseName() );
f.setFile( curFile);
f.writeLink();
}
}
}
void AdvancedFm::customDirsToMenu() {
Config cfg("AdvancedFm");
cfg.setGroup("Menu");
QStringList list = cfg.readListEntry( "CustomDir", ',');
menuButton->insertItems(list );
// for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
// {
// customDirMenu->insertItem(*it );
// }
}
void AdvancedFm::dirMenuSelected(int item) {
switch(item)
{
case -21:
case 0:
addCustomDir();
break;
case -22:
case 1:
removeCustomDir();
break;
default:
{
// gotoCustomDir( menuButton->text(item));
// gotoCustomDir( customDirMenu->text(item));
}
break;
};
}
void AdvancedFm::addCustomDir() {
Config cfg("AdvancedFm");
cfg.setGroup("Menu");
QString dir;
QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)',');
dir = CurrentDir()->canonicalPath();
bool addIt=true;
for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
if( dir == (*it)) {
addIt=false;
}
}
if(addIt) {
menuButton->insertItem(dir);
// customDirMenu->insertItem(dir);
list << dir;
}
cfg.writeEntry("CustomDir", list, ',');
cfg.write();
}
void AdvancedFm::removeCustomDir() {
-// qDebug("remove custom dir");
+// odebug << "remove custom dir" << oendl;
Config cfg("AdvancedFm");
cfg.setGroup("Menu");
QString dir;
QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)',');
QStringList list2;
dir = CurrentDir()->canonicalPath();
int ramble=2;
// int ramble=-24;
//first remove list
if(list.grep(dir,true).isEmpty()) {
QMessageBox::message(tr( "AdvancedFm" ),
tr("Cannot remove current directory\nfrom bookmarks.\nIt is not bookmarked!"));
} else {
for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
if((*it) != dir) {
//current item is not our current dir, so add it to temp list
list2 <<(*it);
} else {
// customDirMenu->removeItem( ramble);
menuButton->remove( ramble);
}
ramble++;
// ramble--;
}
cfg.writeEntry("CustomDir", list2, ',');
cfg.write();
}
// customDirsToMenu();
}
void AdvancedFm::gotoCustomDir(const QString &dir) {
-// qDebug("gotoCustomDir(const QString &dir) " +dir );
+// odebug << "gotoCustomDir(const QString &dir) " +dir << oendl;
// QString curDir = dir;
// QDir *thisDir = CurrentDir();
// if( curDir.isEmpty()) {
// }
if( dir == s_addBookmark) {
addCustomDir();
}
if( dir == s_removeBookmark) {
removeCustomDir( );
} else {
gotoDirectory( dir);
// if(QDir( curDir).exists() )
// {
// thisDir->setPath( curDir );
// chdir( curDir.latin1() );
// thisDir->cd( curDir, TRUE);
// populateView();
// }
}
}
QDir *AdvancedFm::CurrentDir() {
if ( whichTab == 1) {
return &currentDir;
} else {
return &currentRemoteDir;
}
}
QDir *AdvancedFm::OtherDir() {
if ( whichTab == 1) {
return &currentRemoteDir;
} else {
return &currentDir;
}
}
QListView * AdvancedFm::CurrentView() {
if ( whichTab == 1) {
-// qWarning("CurrentView Tab 1");
+// owarn << "CurrentView Tab 1" << oendl;
return Local_View;
} else {
-// qWarning("CurrentView Tab 2");
+// owarn << "CurrentView Tab 2" << oendl;
return Remote_View;
}
}
QListView * AdvancedFm::OtherView() {
if ( whichTab == 1)
return Remote_View;
else
return Local_View;
}
void AdvancedFm::setOtherTabCurrent() {
-// qWarning("setOtherTabCurrent() %d", whichTab);
+// owarn << "setOtherTabCurrent() " << whichTab << "" << oendl;
if ( whichTab == 1) {
TabWidget->setCurrentWidget(1);
} else {
TabWidget->setCurrentWidget(0);
}
OtherView()->setFocus();
OtherView()->setSelected( CurrentView()->firstChild(), true);
}
void AdvancedFm::qcopReceive(const QCString &msg, const QByteArray &data) {
-// qDebug("qcop message "+msg );
+// odebug << "qcop message "+msg << oendl;
QDataStream stream ( data, IO_ReadOnly );
if ( msg == "openDirectory(QString)" ) {
-// qDebug("received");
+// odebug << "received" << oendl;
QString file;
stream >> file;
gotoDirectory( (const QString &) file);
}
}
void AdvancedFm::setDocument(const QString &file) {
gotoDirectory( file);
}
void AdvancedFm::gotoDirectory(const QString &file) {
-// qWarning("goto dir "+file);
+// owarn << "goto dir "+file << oendl;
QString curDir = file;
QDir *thisDir = CurrentDir();
if(QDir( curDir).exists() ) {
thisDir->setPath( curDir );
chdir( curDir.latin1() );
thisDir->cd( curDir, TRUE);
populateView();
}
else if(QFileInfo(curDir).exists()) {
QFileInfo fileInfo(curDir);
curDir=fileInfo.dirPath();
if(QDir( curDir).exists() ) {
thisDir->setPath( curDir );
chdir( curDir.latin1() );
thisDir->cd( curDir, TRUE);
populateView();
}
findFile(file);
}
}
void AdvancedFm::findFile(const QString &fileName) {
QFileInfo fi(fileName);
QListView *thisView = CurrentView();
QListViewItemIterator it( thisView );
for ( ; it.current(); ++it ) {
if(it.current()->text(0) == fi.fileName()) {
it.current()->setSelected(true);
thisView->ensureItemVisible(it.current());
}
}
}
void AdvancedFm::slotSwitchMenu(int ) {
-// qDebug("Switch %d", item);
+// odebug << "Switch " << item << "" << oendl;
// viewMenu->setItemChecked(item, true);
}
void AdvancedFm::dealWithSchmooSchmaa(QWidget *w) {
tabChanged( w);
if( w == Local_View) {
Remote_View->clearFocus();
} else {
Local_View->clearFocus();
}
}
void AdvancedFm::navigateToSelected() {
if( !CurrentView()->currentItem()) return;
doDirChange();
}
diff --git a/noncore/apps/advancedfm/advancedfm.pro b/noncore/apps/advancedfm/advancedfm.pro
index 716343d..f1c518e 100644
--- a/noncore/apps/advancedfm/advancedfm.pro
+++ b/noncore/apps/advancedfm/advancedfm.pro
@@ -1,35 +1,15 @@
TEMPLATE = app
-CONFIG += qt warn_on quick-app
-# CONFIG += qt warn_on
+CONFIG += qt warn_on quick-app
HEADERS = advancedfm.h filePermissions.h output.h
SOURCES = advancedfm.cpp advancedfmData.cpp advancedfmMenu.cpp filePermissions.cpp output.cpp main.cpp
TARGET = advancedfm
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lopiecore2 -lopieui2
-
-TRANSLATIONS = ../../../i18n/de/advancedfm.ts \
- ../../../i18n/nl/advancedfm.ts \
- ../../../i18n/da/advancedfm.ts \
- ../../../i18n/xx/advancedfm.ts \
- ../../../i18n/en/advancedfm.ts \
- ../../../i18n/es/advancedfm.ts \
- ../../../i18n/fr/advancedfm.ts \
- ../../../i18n/hu/advancedfm.ts \
- ../../../i18n/ja/advancedfm.ts \
- ../../../i18n/ko/advancedfm.ts \
- ../../../i18n/no/advancedfm.ts \
- ../../../i18n/pl/advancedfm.ts \
- ../../../i18n/pt/advancedfm.ts \
- ../../../i18n/pt_BR/advancedfm.ts \
- ../../../i18n/sl/advancedfm.ts \
- ../../../i18n/zh_CN/advancedfm.ts \
- ../../../i18n/zh_TW/advancedfm.ts
-
+LIBS += -lqpe -lopiecore2 -lopieui2
!contains(CONFIG,quick-app) {
DESTDIR = $(OPIEDIR)/bin
DEFINES += NOQUICKLAUNCH
}
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/advancedfm/advancedfmData.cpp b/noncore/apps/advancedfm/advancedfmData.cpp
index 2997c55..29335f8 100644
--- a/noncore/apps/advancedfm/advancedfmData.cpp
+++ b/noncore/apps/advancedfm/advancedfmData.cpp
@@ -1,290 +1,294 @@
/***************************************************************************
advancedfmData.cpp
-------------------
** Created: Mon 09-23-2002 13:24:11
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 "advancedfm.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/storage.h>
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
#include <qpe/menubutton.h>
+using namespace Opie::Core;
+using namespace Opie::Ui;
+/* QT */
#include <qlayout.h>
#include <qhbox.h>
#include <qmenubar.h>
#include <qcombobox.h>
#include <qtoolbutton.h>
#include <qlineedit.h>
#include <qlistview.h>
+/* STD */
#include <sys/utsname.h>
-
-using namespace Opie::Ui;
void AdvancedFm::init() {
b = false;
setCaption( tr( "AdvancedFm" ) );
QVBoxLayout *layout = new QVBoxLayout( this );
layout->setSpacing( 2);
layout->setMargin( 0); // squeeze
QMenuBar *menuBar = new QMenuBar(this);
menuBar->setMargin( 0 ); // squeeze
fileMenu = new QPopupMenu( this );
viewMenu = new QPopupMenu( this );
// customDirMenu = new QPopupMenu( this );
layout->addWidget( menuBar );
menuBar->insertItem( tr( "File" ), fileMenu);
menuBar->insertItem( tr( "View" ), viewMenu);
cdUpButton = new QToolButton( 0,"cdUpButton");
cdUpButton->setPixmap(Resource::loadPixmap("up"));
cdUpButton->setAutoRaise( true );
menuBar->insertItem( cdUpButton );
qpeDirButton= new QToolButton( 0,"QPEButton");
qpeDirButton->setPixmap( Resource::loadPixmap("launcher/opielogo16x16"));//,"",this,"QPEButton");
qpeDirButton->setAutoRaise( true );
menuBar->insertItem( qpeDirButton );
cfButton = new QToolButton( 0, "CFButton");
cfButton->setPixmap(Resource::loadPixmap("cardmon/pcmcia"));
cfButton->setAutoRaise( true );
menuBar->insertItem( cfButton );
sdButton = new QToolButton( 0, "SDButton");
sdButton->setPixmap(Resource::loadPixmap("advancedfm/sdcard"));
sdButton->setAutoRaise( true );
menuBar->insertItem( sdButton );
docButton = new QToolButton( 0,"docsButton");
docButton->setPixmap(Resource::loadPixmap("DocsIcon"));
docButton->setAutoRaise( true );
menuBar->insertItem( docButton );
homeButton = new QToolButton( 0, "homeButton");
homeButton->setPixmap(Resource::loadPixmap("home"));
homeButton->setAutoRaise( true );
menuBar->insertItem( homeButton );
fileMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showMenuHidden() ));
fileMenu->setItemChecked( fileMenu->idAt(0),TRUE);
fileMenu->insertSeparator();
fileMenu->insertItem( tr( "File Search" ), this, SLOT( openSearch() ));
fileMenu->insertSeparator();
fileMenu->insertItem( tr( "Make Directory" ), this, SLOT( mkDir() ));
fileMenu->insertItem( tr( "Rename" ), this, SLOT( rn() ));
fileMenu->insertItem( tr( "Run Command" ), this, SLOT( runCommandStd() ));
fileMenu->insertItem( tr( "Run Command with Output" ), this, SLOT( runCommand() ));
fileMenu->insertSeparator();
fileMenu->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() ));
fileMenu->insertItem( tr( "Select All" ), this, SLOT( selectAll() ));
fileMenu->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() ));
fileMenu->insertItem( tr( "Delete" ), this, SLOT( del() ));
fileMenu->setCheckable(TRUE);
viewMenu->insertItem( tr( "Switch to View 1" ), this, SLOT( switchToLocalTab()));
viewMenu->insertItem( tr( "Switch to View 2" ), this, SLOT( switchToRemoteTab()));
// viewMenu->insertSeparator();
// viewMenu->insertItem( tr( "About" ), this, SLOT( doAbout() ));
viewMenu->setCheckable(true);
viewMenu->setItemChecked( viewMenu->idAt(0), true);
viewMenu->setItemChecked( viewMenu->idAt(1), false);
s_addBookmark = tr("Bookmark Directory");
s_removeBookmark = tr("Remove Current Directory from Bookmarks");
// menuButton->insertItem("");
// customDirMenu->insertItem(tr("Add This Directory"));
// customDirMenu->insertItem(tr("Remove This Directory"));
// customDirMenu->insertSeparator();
QHBoxLayout *CBHB = new QHBoxLayout(); // parent layout will be set later
CBHB->setMargin( 0 );
CBHB->setSpacing( 1 );
menuButton = new MenuButton( this );
menuButton->setUseLabel(false);
menuButton->setMaximumWidth( 20 );
menuButton->insertItem( s_addBookmark);
menuButton->insertItem( s_removeBookmark);
menuButton->insertSeparator();
menuButton->setFocusPolicy(NoFocus);
CBHB->addWidget( menuButton );
customDirsToMenu();
currentPathCombo = new QComboBox( FALSE, this, "currentPathCombo" );
currentPathCombo->setEditable(TRUE);
currentPathCombo->lineEdit()->setText( currentDir.canonicalPath());
currentPathCombo->setFocusPolicy(NoFocus);
CBHB->addWidget( currentPathCombo );
layout->addLayout( CBHB );
TabWidget = new OSplitter( Horizontal, this, "TabWidget" );
// TabWidget = new QTabWidget( this, "TabWidget" );
layout->addWidget( TabWidget, 4 );
tab = new QWidget( TabWidget, "tab" );
tabLayout = new QGridLayout( tab );
tabLayout->setSpacing( 2);
tabLayout->setMargin( 2);
Local_View = new QListView( tab, "Local_View" );
Local_View->addColumn( tr("File"),130);
Local_View->addColumn( tr("Size"),-1);
Local_View->setColumnAlignment(1,QListView::AlignRight);
Local_View->addColumn( tr("Date"),-1);
Local_View->setColumnAlignment(2,QListView::AlignRight);
Local_View->setAllColumnsShowFocus(TRUE);
Local_View->setMultiSelection( TRUE );
Local_View->setSelectionMode(QListView::Extended);
Local_View->setFocusPolicy(StrongFocus);
Local_View->installEventFilter( this );
QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold);
tabLayout->addWidget( Local_View, 0, 0 );
TabWidget->addWidget( tab,"advancedfm/smFileBrowser.png", tr("1"));
// TabWidget->insertTab( tab, tr("1"));
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"),130);
Remote_View->addColumn( tr("Size"),-1);
Remote_View->setColumnAlignment(1,QListView::AlignRight);
Remote_View->addColumn( tr("Date"),-1);
Remote_View->setColumnAlignment(2,QListView::AlignRight);
Remote_View->setAllColumnsShowFocus(TRUE);
Remote_View->setMultiSelection( TRUE );
Remote_View->setSelectionMode(QListView::Extended);
Remote_View->setFocusPolicy(StrongFocus);
Remote_View->installEventFilter( this );
QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold);
tabLayout_2->addWidget( Remote_View, 0, 0 );
TabWidget->addWidget( tab_2, "advancedfm/smFileBrowser.png",tr( "2"));
TabWidget->setSizeChange( 370 );
// TabWidget->insertTab( tab_2, tr( "2"));
/* tab_3 = new QWidget( TabWidget, "tab_3" );
tabLayout_3 = new QGridLayout( tab_3 );
tabLayout_3->setSpacing( 2);
tabLayout_3->setMargin( 2);
// OFileDialog fileDialog;
// fileDialog;
// fileSelector = new FileSelector( "*",tab_3, "fileselector" , FALSE, FALSE); //buggy
// fileDialog = new OFileDialog("bangalow", tab_3, 4, 2, "Bungalow");
// OFileSelector fileDialog = new OFileSelector( tab_3, 4, 2,"/");
QListView *fileTree;
fileTree = new QListView( tab_3, "tree" );
tabLayout_3->addMultiCellWidget( fileTree, 0, 0, 0, 3 );
TabWidget->insertTab( tab_3, tr( "Remote" ) );
*/
///////////////
if ( QFile::exists ( "/dev/sharp_buz" ) || QFile::exists ( "/dev/sharp_led" ))
zaurusDevice=TRUE;
else
zaurusDevice=FALSE;
if( !StorageInfo::hasSd() || !StorageInfo::hasMmc()) {
- qDebug("not have sd");
+ odebug << "not have sd" << oendl;
sdButton->hide();
}
if( !StorageInfo::hasCf() ) {
- qDebug("not have cf");
+ odebug << "not have cf" << oendl;
cfButton->hide();
}
currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
currentDir.setPath( QDir::currentDirPath());
currentRemoteDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
currentRemoteDir.setPath( QDir::currentDirPath());
// b = TRUE;
filterStr="*";
showMenuHidden();
TabWidget->setCurrentWidget(0);
}
void AdvancedFm::initConnections()
{
connect( qApp,SIGNAL( aboutToQuit()),
this, SLOT( cleanUp()) );
connect( qpeDirButton ,SIGNAL(released()),
this,SLOT( QPEButtonPushed()) );
connect( cfButton ,SIGNAL(released()),
this,SLOT( CFButtonPushed()) );
connect( sdButton ,SIGNAL(released()),
this,SLOT( SDButtonPushed()) );
connect( cdUpButton ,SIGNAL(released()),
this,SLOT( upDir()) );
connect( docButton,SIGNAL(released()),
this,SLOT( docButtonPushed()) );
connect( homeButton,SIGNAL(released()),
this,SLOT( homeButtonPushed()) );
connect( currentPathCombo, SIGNAL( activated(const QString&) ),
this, SLOT( currentPathComboActivated(const QString&) ) );
connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()),
this,SLOT(currentPathComboChanged()));
connect( Local_View, SIGNAL( clicked(QListViewItem*)),
this,SLOT( ListClicked(QListViewItem*)) );
connect( Local_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) );
connect( Local_View, SIGNAL( selectionChanged() ), SLOT( cancelMenuTimer() ) );
connect( Remote_View, SIGNAL( clicked(QListViewItem*)),
this,SLOT( ListClicked(QListViewItem*)) );
connect( Remote_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) );
connect( TabWidget,SIGNAL(currentChanged(QWidget*)),
this,SLOT(tabChanged(QWidget*)));
connect( &menuTimer, SIGNAL( timeout() ), SLOT( showFileMenu() ) );
connect( menuButton, SIGNAL( selected(const QString&)), SLOT(gotoCustomDir(const QString&)));
// connect( menuButton, SIGNAL( selected(int)), SLOT( dirMenuSelected(int)));
connect( viewMenu, SIGNAL( activated(int)), this, SLOT(slotSwitchMenu(int)));
// connect( customDirMenu, SIGNAL( activated(int)), this, SLOT( dirMenuSelected(int)));
}
diff --git a/noncore/apps/advancedfm/advancedfmMenu.cpp b/noncore/apps/advancedfm/advancedfmMenu.cpp
index 81a4318..d34f330 100644
--- a/noncore/apps/advancedfm/advancedfmMenu.cpp
+++ b/noncore/apps/advancedfm/advancedfmMenu.cpp
@@ -1,839 +1,842 @@
-/***************************************************************************
- AdvancedFm.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. *
- ***************************************************************************/
-#include "advancedfm.h"
-#include "output.h"
-#include "filePermissions.h"
-
-#include <qpe/lnkproperties.h>
-#include <qpe/qpeapplication.h>
-#include <qpe/applnk.h>
-
-#include <qmessagebox.h>
-
-
-#include <qpopupmenu.h>
-#include <qlistview.h>
-
-#include <errno.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <dirent.h>
-#include <sys/sendfile.h>
-#include <fcntl.h>
-
-
-using namespace Opie::Core;
-using namespace Opie::Core;
-void AdvancedFm::doDirChange() {
- QString pathItem = CurrentView()->currentItem()->text(0);
- if( pathItem == "../") {
- ListClicked( CurrentView()->currentItem());
- } else {
- if( pathItem.find(" -> ",0,TRUE) != -1)
- pathItem = dealWithSymName((const QString&)pathItem)+"/";
-// qWarning(pathItem);
- gotoDirectory( CurrentDir()->path()+"/"+pathItem.left( pathItem.length() - 1) );
- }
-}
-
-void AdvancedFm::showMenuHidden() {
- if (b) {
- CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
- OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
- fileMenu->setItemChecked( fileMenu->idAt(0),TRUE);
- } else {
- CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
- OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
- fileMenu->setItemChecked( fileMenu->idAt(0),FALSE);
- }
- b = !b;
- populateView();
-}
-
-void AdvancedFm::showHidden() {
- if (b) {
- CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
- OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
- } else {
- CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
- OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
- }
- populateView();
-}
-
-QString AdvancedFm::dealWithSymName(const QString &fileName) {
- QString strItem = fileName;
- return strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4);
-}
-
-void AdvancedFm::runThis() {
- if( !CurrentView()->currentItem()) return;
- QString fs;
- QDir *thisDir = CurrentDir();
-
- QString curFile = CurrentView()->currentItem()->text(0);
- QString path = thisDir->canonicalPath();
-
- if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink
-
- curFile = dealWithSymName((const QString&)curFile);
-
- if(curFile != "../") {
-
- fs = getFileSystemType((const QString &) path);
- QFileInfo fileInfo( path + "/" + curFile);
-// qDebug( fileInfo.owner());
-
- if( (fileInfo.permission( QFileInfo::ExeUser)
- | fileInfo.permission( QFileInfo::ExeGroup)
- | fileInfo.permission( QFileInfo::ExeOther)) // & fs.find("vfat",0,TRUE) == -1) {
- | fs == "vfat" && fileInfo.filePath().contains("/bin") ) {
- QCopEnvelope e("QPE/System", "execute(QString)" );
- e << curFile;
- } else {
- curFile = path + "/" + curFile;
- DocLnk nf(curFile);
- QString execStr = nf.exec();
-// qDebug( execStr);
- if( execStr.isEmpty() ) {
- } else {
- nf.execute();
- }
- }
- }
-}
-
-void AdvancedFm::runText() {
- if( !CurrentView()->currentItem()) return;
- QString curFile = CurrentView()->currentItem()->text(0);
- if(curFile != "../") {
- if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink
- curFile = dealWithSymName((const QString&)curFile);
- curFile = CurrentDir()->canonicalPath()+"/"+curFile;
- QCopEnvelope e("QPE/Application/textedit", "setDocument(QString)" );
- e << curFile;
- }
-}
-
-void AdvancedFm::makeDir() {
- InputDialog *fileDlg;
- fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0);
- fileDlg->exec();
- if( fileDlg->result() == 1 ) {
- QDir *thisDir = CurrentDir();
- QString filename = fileDlg->LineEdit1->text();
- thisDir->mkdir( thisDir->canonicalPath()+"/"+filename);
- }
- populateView();
-}
-
-void AdvancedFm::doDelete() {
- QStringList curFileList = getPath();
- bool doMsg=true;
- int count = curFileList.count();
- if( count > 0) {
- if(count > 1 ) {
- QString msg;
- msg=tr("Really delete\n%1 files?").arg(count);
- switch ( QMessageBox::warning(this,tr("Delete"),msg
- ,tr("Yes"),tr("No"),0,0,1) )
- {
- case 0:
- doMsg=false;
- break;
- case 1:
- return;
- break;
- };
- }
-
- QString myFile;
-
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
- myFile = (*it);
- if( myFile.find(" -> ",0,TRUE) != -1)
- myFile = myFile.left( myFile.find(" -> ",0,TRUE));
-
- QString f = CurrentDir()->canonicalPath();
- if(f.right(1).find("/",0,TRUE) == -1)
- f += "/";
- f += myFile;
- if(QDir(f).exists() && !QFileInfo(f).isSymLink() ) {
- //if file is a directory
-
- switch ( QMessageBox::warning( this, tr("Delete Directory?"),
- tr("Really delete %1\nand all it's contents ?" ).arg( f ) ,
- tr("Yes"), tr("No"), 0, 0, 1) ) {
- case 0:
- {
- f=f.left(f.length()-1);
- QString cmd="rm -rf "+f;
- startProcess( (const QString)cmd.latin1() );
- populateView();
- }
- break;
- case 1:
- // exit
- break;
- };
-
- } else {
- if(doMsg) {
- switch ( QMessageBox::warning(this,tr("Delete"),
- tr("Really delete\n%1?").arg( myFile ),
- tr("Yes"), tr("No"), 0, 0, 1) ) {
- case 1:
- return;
- break;
- };
- }
-
- QString cmd="rm "+f;
- QFile file(f);
- QFileInfo fi(myFile);
- if( fi.fileName().find("../",0,TRUE)==-1) {
-// qDebug("remove link files "+myFile);
-
-// DocLnk lnk(f);
- DocLnk *lnk;
- lnk = new DocLnk(f);
-// qDebug("Deleting doclnk " + lnk->linkFile());
- if(lnk->isValid())
- lnk->removeLinkFile();
- // delete lnk;
- file.remove();
- }
- }
- }
- }
- populateView();
-}
-
-void AdvancedFm::filePerms() {
- QStringList curFileList = getPath();
- QString filePath;
-
- filePath = CurrentDir()->canonicalPath()+"/";
-
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
- filePermissions *filePerm;
- filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(filePath+*it));
- QPEApplication::execDialog( filePerm );
- if( filePerm )
- delete filePerm;
- }
- populateView();
-}
-
-void AdvancedFm::doProperties() {
-#if defined(QT_QWS_OPIE)
-
- QStringList curFileList = getPath();
-
- QString filePath;
- filePath = CurrentDir()->canonicalPath()+"/";
-
-// qDebug("%d",curFileList.count());
-
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
-// qDebug((filePath+*it));
- DocLnk lnk( (filePath+*it));
- LnkProperties prop( &lnk );
- QPEApplication::execDialog( &prop );
- }
-#endif
-
-}
-
-void AdvancedFm::upDir() {
- QDir *thisDir = CurrentDir();
- QString current = thisDir->canonicalPath();
- QDir dir(current);
- dir.cdUp();
- current = dir.canonicalPath();
- chdir( current.latin1() );
- thisDir->cd( current, TRUE);
-
- populateView();
- update();
-}
-
-void AdvancedFm::copy() {
- qApp->processEvents();
- QStringList curFileList = getPath();
-
- QDir *thisDir = CurrentDir();
- QDir *thatDir = OtherDir();
-
- bool doMsg=true;
- int count=curFileList.count();
- if( count > 0) {
- if(count > 1 ){
- QString msg;
- msg=tr("Really copy\n%1 files?").arg(count);
- switch ( QMessageBox::warning(this,tr("Copy"),msg
- ,tr("Yes"),tr("No"),0,0,1) )
- {
- case 0:
- doMsg=false;
- break;
- case 1:
- return;
- break;
- };
- }
-
- QString curFile, item, destFile;
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
- item=(*it);
- if(item.find("->",0,TRUE)) //symlink
- item = item.left(item.find("->",0,TRUE));
-
- curFile = thisDir->canonicalPath()+"/"+ item;
- destFile = thatDir->canonicalPath()+"/"+ item;
-
-// qDebug("Destination file is "+destFile);
-// qDebug("CurrentFile file is " + curFile);
-
- QFile f(destFile);
- if( f.exists()) {
- if(doMsg) {
- switch ( QMessageBox::warning(this,tr("File Exists!"),
- tr("%1 exists. Ok to overwrite?").arg( item ),
- tr("Yes"),tr("No"),0,0,1) ) {
- case 1:
- return;
- break;
- };
- }
- f.remove();
- }
-
- if( !copyFile( curFile, destFile) ) {
- QMessageBox::message("AdvancedFm",
- tr( "Could not copy %1 to %2").arg( curFile ).arg( destFile ) );
- return;
- }
- }
- setOtherTabCurrent();
- rePopulate();
- }
-}
-
-void AdvancedFm::copyAs() {
- qApp->processEvents();
-
- QStringList curFileList = getPath();
- QString curFile, item;
- InputDialog *fileDlg;
-
- QDir *thisDir = CurrentDir();
- QDir *thatDir = OtherDir();
-
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
- QString destFile;
- item=(*it);
- curFile = thisDir->canonicalPath()+"/"+(*it);
- fileDlg = new InputDialog( this, tr("Copy "+curFile+" As"), TRUE, 0);
-
- fileDlg->setInputText((const QString &) destFile );
- fileDlg->exec();
-
- if( fileDlg->result() == 1 ) {
- QString filename = fileDlg->LineEdit1->text();
- destFile = thatDir->canonicalPath()+"/"+filename;
-
- QFile f( destFile);
- if( f.exists()) {
- switch (QMessageBox::warning(this,tr("File Exists!"),
- item+tr("\nexists. Ok to overwrite?"),
- tr("Yes"),tr("No"),0,0,1) ) {
- case 0:
- f.remove();
- break;
- case 1:
- return;
- break;
- };
- }
- if( !copyFile( curFile, destFile) ) {
- QMessageBox::message("AdvancedFm",tr("Could not copy\n")
- +curFile +tr("to\n")+destFile);
- return;
- }
- }
- delete fileDlg;
-
- }
- rePopulate();
- setOtherTabCurrent();
-}
-
-void AdvancedFm::copySameDir() {
- qApp->processEvents();
- QStringList curFileList = getPath();
- QString curFile, item, destFile;
- InputDialog *fileDlg;
-
- QDir *thisDir = CurrentDir();
-
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
- item=(*it);
- curFile = thisDir->canonicalPath()+"/"+ item;
-
- fileDlg = new InputDialog(this,tr("Copy ")+curFile+tr(" As"),TRUE, 0);
- fileDlg->setInputText((const QString &) destFile );
- fileDlg->exec();
-
- if( fileDlg->result() == 1 ) {
-
- QString filename = fileDlg->LineEdit1->text();
- destFile = thisDir->canonicalPath()+"/"+filename;
-
- QFile f(destFile);
- if( f.exists()) {
- switch (QMessageBox::warning(this,tr("Delete"),
- destFile+tr(" already exists.\nDo you really want to delete it?"),
- tr("Yes"),tr("No"),0,0,1) ) {
- case 0:
-
- f.remove();
- break;
- case 1:
- return;
- break;
- };
- }
- if(!copyFile( curFile,destFile) ) {
- QMessageBox::message("AdvancedFm",tr("Could not copy\n")
- +curFile +tr("to\n")+destFile);
- return;
- }
-
-// qDebug("copy "+curFile+" as "+destFile);
- }
- delete fileDlg;
- }
- rePopulate();
-}
-
-void AdvancedFm::move() {
- qApp->processEvents();
-
- QStringList curFileList = getPath();
- if( curFileList.count() > 0) {
- QString curFile, destFile, item;
-
- QDir *thisDir = CurrentDir();
- QDir *thatDir = OtherDir();
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
- item=(*it);
- QString destFile = thatDir->canonicalPath();
-
- if(destFile.right(1).find("/",0,TRUE) == -1)
- destFile+="/";
- destFile += item;
-// qDebug("Destination file is "+destFile);
-
- curFile = thisDir->canonicalPath();
- if(curFile.right(1).find("/",0,TRUE) == -1)
- curFile +="/";
- curFile+= item;
-// qDebug("CurrentFile file is " + curFile);
-
- if(QFileInfo(curFile).isDir()) {
- moveDirectory( curFile, destFile );
- rePopulate();
- return;
- }
-
- QFile f( curFile);
- if( f.exists()) {
- if( !copyFile( curFile, destFile) ) {
- QMessageBox::message(tr("Note"),tr("Could not move\n")+curFile);
- return;
- } else
- QFile::remove(curFile);
- }
- }
-
- }
- rePopulate();
- setOtherTabCurrent();
-}
-
-bool AdvancedFm::moveDirectory( const QString & src, const QString & dest ) {
- int err = 0;
- if( copyDirectory( src, dest ) ) { QString cmd = "rm -rf " + src;
- err = system((const char*)cmd);
- } else
- err = -1;
-
- if(err!=0) {
- QMessageBox::message(tr("Note"),tr("Could not move\n") + src);
- return false;
- }
- return true;
-}
-
-bool AdvancedFm::copyDirectory( const QString & src, const QString & dest ) {
-
- QString cmd = "/bin/cp -fpR " + src + " " + dest;
- qWarning(cmd);
- int err = system( (const char *) cmd );
- if ( err != 0 ) {
- QMessageBox::message("AdvancedFm",
- tr( "Could not copy \n%1 \nto \n%2").arg( src ).arg( dest ) );
- return false;
- }
-
- return true;
-}
-
-
-bool AdvancedFm::copyFile( const QString & src, const QString & dest ) {
-
-
- if(QFileInfo(src).isDir()) {
- if( copyDirectory( src, dest )) {
- setOtherTabCurrent();
- populateView();
- return true;
- }
- else
- return false;
- }
-
-
- bool success = true;
- struct stat status;
- QFile srcFile(src);
- QFile destFile(dest);
- int err=0;
- int read_fd=0;
- int write_fd=0;
- struct stat stat_buf;
- off_t offset = 0;
- if(!srcFile.open( IO_ReadOnly|IO_Raw)) {
-// qWarning("open failed");
- return success = false;
- }
- read_fd = srcFile.handle();
- if(read_fd != -1) {
- fstat (read_fd, &stat_buf);
- if( !destFile.open( IO_WriteOnly|IO_Raw ) ) {
-// qWarning("destfile open failed");
- return success = false;
- }
- write_fd = destFile.handle();
- if(write_fd != -1) {
- err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size);
- if( err == -1) {
- QString msg;
- switch(err) {
- case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. ";
- case EINVAL: msg = "Descriptor is not valid or locked. ";
- case ENOMEM: msg = "Insufficient memory to read from in_fd.";
- case EIO: msg = "Unspecified error while reading from in_fd.";
- };
- success = false;
-// qWarning(msg);
- }
- } else {
- success = false;
- }
- } else {
- success = false;
- }
- srcFile.close();
- destFile.close();
- // Set file permissions
- if( stat( (const char *) src, &status ) == 0 ) {
- chmod( (const char *) dest, status.st_mode );
- }
-
- return success;
-}
-
-void AdvancedFm::runCommand() {
- if( !CurrentView()->currentItem()) return;
- QDir *thisDir = CurrentDir();
-
- QString curFile;
- curFile = thisDir->canonicalPath() +"/"+ CurrentView()->currentItem()->text(0);
-
- InputDialog *fileDlg;
- fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0);
- fileDlg->setInputText(curFile);
- fileDlg->exec();
- //QString command;
-
- if( fileDlg->result() == 1 ) {
-// qDebug(fileDlg->LineEdit1->text());
- QStringList command;
-
- command << "/bin/sh";
- command << "-c";
- command << fileDlg->LineEdit1->text();
- Output *outDlg;
- outDlg = new Output( command, this, tr("AdvancedFm Output"), true);
- QPEApplication::execDialog( outDlg );
- qApp->processEvents();
-
- }
-}
-
-void AdvancedFm::runCommandStd() {
- if( !CurrentView()->currentItem()) return;
- QString curFile;
- QDir *thisDir = CurrentDir();
- QListView *thisView = CurrentView();
- if( thisView->currentItem())
- curFile = thisDir->canonicalPath() +"/"+ thisView->currentItem()->text(0);
-
- InputDialog *fileDlg;
- fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0);
- fileDlg->setInputText(curFile);
- fileDlg->exec();
-
- if( fileDlg->result() == 1 ) {
- qApp->processEvents();
- startProcess( (const QString)fileDlg->LineEdit1->text().latin1());
- }
-}
-
-void AdvancedFm::fileStatus() {
- if( !CurrentView()->currentItem()) return;
- QString curFile;
- curFile = CurrentView()->currentItem()->text(0);
-
- QStringList command;
- command << "/bin/sh";
- command << "-c";
- command << "stat -l "+ curFile;
-
- Output *outDlg;
- outDlg = new Output( command, this, tr("AdvancedFm Output"), true);
- QPEApplication::execDialog( outDlg );
- qApp->processEvents();
-}
-
-
-void AdvancedFm::mkDir() {
- makeDir();
-}
-
-void AdvancedFm::rn() {
- renameIt();
-}
-
-void AdvancedFm::del() {
- doDelete();
-}
-
-void AdvancedFm::mkSym() {
- QString cmd;
- QStringList curFileList = getPath();
- if( curFileList.count() > 0) {
- QDir *thisDir = CurrentDir();
- QDir * thatDir = OtherDir();
-
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
-
- QString destName = thatDir->canonicalPath()+"/"+(*it);
- if(destName.right(1) == "/") {
- destName = destName.left( destName.length() -1);
- }
-
- QString curFile = thisDir->canonicalPath()+"/"+(*it);
-
- if( curFile.right(1) == "/") {
- curFile = curFile.left( curFile.length() -1);
- }
-
- cmd = "ln -s "+curFile+" "+destName;
-// qDebug(cmd);
- startProcess( (const QString)cmd );
- }
- rePopulate();
- setOtherTabCurrent();
- }
-}
-
-void AdvancedFm::doBeam() {
- Ir ir;
- if(!ir.supported()) {
- } else {
- QStringList curFileList = getPath();
- if( curFileList.count() > 0) {
- for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
- QString curFile = (*it);
- QString curFilePath = CurrentDir()->canonicalPath()+"/"+curFile;
- if( curFilePath.right(1) == "/") {
- curFilePath = curFilePath.left( curFilePath.length() -1);
- }
- Ir *file = new Ir(this, "IR");
- connect(file, SIGNAL(done(Ir*)), this, SLOT( fileBeamFinished(Ir*)));
- file->send( curFilePath, curFile );
- }
- }
- }
-}
-
-void AdvancedFm::fileBeamFinished( Ir *) {
- QMessageBox::message( tr("Advancedfm Beam out"), tr("Ir sent.") ,tr("Ok") );
-}
-
-void AdvancedFm::selectAll() {
- QListView *thisView = CurrentView();
- thisView->selectAll(true);
- thisView->setSelected( thisView->firstChild(),false);
-}
-
-void AdvancedFm::startProcess(const QString & cmd) {
- QStringList command;
- OProcess *process;
- process = new OProcess();
- connect(process, SIGNAL(processExited(Opie::Core::OProcess*)),
- this, SLOT( processEnded(Opie::Core::OProcess*)));
-
- connect(process, SIGNAL( receivedStderr(Opie::Core::OProcess*,char*,int)),
- this, SLOT( oprocessStderr(Opie::Core::OProcess*,char*,int)));
-
- command << "/bin/sh";
- command << "-c";
- command << cmd.latin1();
- *process << command;
- if(!process->start(OProcess::NotifyOnExit, OProcess::All) )
- qDebug("could not start process");
-}
-
-void AdvancedFm::processEnded(OProcess *) {
- rePopulate();
-}
-
-void AdvancedFm::oprocessStderr(OProcess*, char *buffer, int ) {
-// qWarning("received stderrt %d bytes", buflen);
-
- QString lineStr = buffer;
- QMessageBox::warning( this, tr("Error"), lineStr ,tr("Ok") );
-}
-
-bool AdvancedFm::eventFilter( QObject * o, QEvent * e ) {
- if ( o->inherits( "QLineEdit" ) ) {
- if ( e->type() == QEvent::KeyPress ) {
- QKeyEvent *ke = (QKeyEvent*)e;
- if ( ke->key() == Key_Return ||
- ke->key() == Key_Enter ) {
- okRename();
- return true;
- }
- else if ( ke->key() == Key_Escape ) {
- cancelRename();
- return true;
- }
- }
- else if ( e->type() == QEvent::FocusOut ) {
- cancelRename();
- return true;
- }
- }
- if ( o->inherits( "QListView" ) ) {
- if ( e->type() == QEvent::FocusIn ) {
- if( o == Local_View) { //keep track of which view
- whichTab=1;
- }
- else {
- whichTab=2;
- }
- }
- OtherView()->setSelected( OtherView()->currentItem(), FALSE );//make sure there's correct selection
- }
-
- return QWidget::eventFilter( o, e );
-}
-
-
-void AdvancedFm::cancelRename() {
-// qDebug("cancel rename");
- QListView * view;
- view = CurrentView();
-
- bool resetFocus = view->viewport()->focusProxy() == renameBox;
- delete renameBox;
- renameBox = 0;
- if ( resetFocus ) {
- view->viewport()->setFocusProxy( view);
- view->setFocus();
- }
-}
-
-void AdvancedFm::doRename(QListView * view) {
- if( !CurrentView()->currentItem()) return;
-
- QRect r = view->itemRect( view->currentItem( ));
- r = QRect( view->viewportToContents( r.topLeft() ), r.size() );
- r.setX( view->contentsX() );
-
- if ( r.width() > view->visibleWidth() )
- r.setWidth( view->visibleWidth() );
-
- renameBox = new QLineEdit( view->viewport(), "qt_renamebox" );
- renameBox->setFrame(true);
-
- renameBox->setText( view->currentItem()->text(0) );
-
- renameBox->selectAll();
- renameBox->installEventFilter( this );
-
- view->addChild( renameBox, r.x(), r.y() );
-
- renameBox->resize( r.size() );
-
- view->viewport()->setFocusProxy( renameBox );
-
- renameBox->setFocus();
- renameBox->show();
-}
-
-
-void AdvancedFm::renameIt() {
- if( !CurrentView()->currentItem()) return;
-
- QListView *thisView = CurrentView();
- oldName = thisView->currentItem()->text(0);
- doRename( thisView );
-}
-
-void AdvancedFm::okRename() {
- if( !renameBox) return;
-
- QString newName = renameBox->text();
- cancelRename();
- QListView * view = CurrentView();
- QString path = CurrentDir()->canonicalPath() + "/";
- oldName = path + oldName;
- newName = path + newName;
- if( rename( oldName.latin1(), newName.latin1())== -1)
- QMessageBox::message(tr("Note"),tr("Could not rename"));
- else
- oldName = "";
- QListViewItem *item = view->currentItem();
- view->takeItem( item );
- delete item;
- rePopulate();
-}
-
-void AdvancedFm::openSearch() {
- QMessageBox::message(tr("Note"),tr("Not Yet Implemented"));
-}
+/***************************************************************************
+ AdvancedFm.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. *
+ ***************************************************************************/
+
+#include "advancedfm.h"
+#include "output.h"
+#include "filePermissions.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/lnkproperties.h>
+#include <qpe/qpeapplication.h>
+#include <qpe/applnk.h>
+using namespace Opie::Core;
+
+/* QT*/
+
+#include <qmessagebox.h>
+#include <qpopupmenu.h>
+#include <qlistview.h>
+
+/* STD */
+
+#include <errno.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <sys/sendfile.h>
+#include <fcntl.h>
+
+void AdvancedFm::doDirChange() {
+ QString pathItem = CurrentView()->currentItem()->text(0);
+ if( pathItem == "../") {
+ ListClicked( CurrentView()->currentItem());
+ } else {
+ if( pathItem.find(" -> ",0,TRUE) != -1)
+ pathItem = dealWithSymName((const QString&)pathItem)+"/";
+// owarn << pathItem << oendl;
+ gotoDirectory( CurrentDir()->path()+"/"+pathItem.left( pathItem.length() - 1) );
+ }
+}
+
+void AdvancedFm::showMenuHidden() {
+ if (b) {
+ CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
+ OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
+ fileMenu->setItemChecked( fileMenu->idAt(0),TRUE);
+ } else {
+ CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
+ OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
+ fileMenu->setItemChecked( fileMenu->idAt(0),FALSE);
+ }
+ b = !b;
+ populateView();
+}
+
+void AdvancedFm::showHidden() {
+ if (b) {
+ CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
+ OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
+ } else {
+ CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
+ OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
+ }
+ populateView();
+}
+
+QString AdvancedFm::dealWithSymName(const QString &fileName) {
+ QString strItem = fileName;
+ return strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4);
+}
+
+void AdvancedFm::runThis() {
+ if( !CurrentView()->currentItem()) return;
+ QString fs;
+ QDir *thisDir = CurrentDir();
+
+ QString curFile = CurrentView()->currentItem()->text(0);
+ QString path = thisDir->canonicalPath();
+
+ if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink
+
+ curFile = dealWithSymName((const QString&)curFile);
+
+ if(curFile != "../") {
+
+ fs = getFileSystemType((const QString &) path);
+ QFileInfo fileInfo( path + "/" + curFile);
+// odebug << fileInfo.owner() << oendl;
+
+ if( (fileInfo.permission( QFileInfo::ExeUser)
+ | fileInfo.permission( QFileInfo::ExeGroup)
+ | fileInfo.permission( QFileInfo::ExeOther)) // & fs.find("vfat",0,TRUE) == -1) {
+ | fs == "vfat" && fileInfo.filePath().contains("/bin") ) {
+ QCopEnvelope e("QPE/System", "execute(QString)" );
+ e << curFile;
+ } else {
+ curFile = path + "/" + curFile;
+ DocLnk nf(curFile);
+ QString execStr = nf.exec();
+// odebug << execStr << oendl;
+ if( execStr.isEmpty() ) {
+ } else {
+ nf.execute();
+ }
+ }
+ }
+}
+
+void AdvancedFm::runText() {
+ if( !CurrentView()->currentItem()) return;
+ QString curFile = CurrentView()->currentItem()->text(0);
+ if(curFile != "../") {
+ if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink
+ curFile = dealWithSymName((const QString&)curFile);
+ curFile = CurrentDir()->canonicalPath()+"/"+curFile;
+ QCopEnvelope e("QPE/Application/textedit", "setDocument(QString)" );
+ e << curFile;
+ }
+}
+
+void AdvancedFm::makeDir() {
+ InputDialog *fileDlg;
+ fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0);
+ fileDlg->exec();
+ if( fileDlg->result() == 1 ) {
+ QDir *thisDir = CurrentDir();
+ QString filename = fileDlg->LineEdit1->text();
+ thisDir->mkdir( thisDir->canonicalPath()+"/"+filename);
+ }
+ populateView();
+}
+
+void AdvancedFm::doDelete() {
+ QStringList curFileList = getPath();
+ bool doMsg=true;
+ int count = curFileList.count();
+ if( count > 0) {
+ if(count > 1 ) {
+ QString msg;
+ msg=tr("Really delete\n%1 files?").arg(count);
+ switch ( QMessageBox::warning(this,tr("Delete"),msg
+ ,tr("Yes"),tr("No"),0,0,1) )
+ {
+ case 0:
+ doMsg=false;
+ break;
+ case 1:
+ return;
+ break;
+ };
+ }
+
+ QString myFile;
+
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+ myFile = (*it);
+ if( myFile.find(" -> ",0,TRUE) != -1)
+ myFile = myFile.left( myFile.find(" -> ",0,TRUE));
+
+ QString f = CurrentDir()->canonicalPath();
+ if(f.right(1).find("/",0,TRUE) == -1)
+ f += "/";
+ f += myFile;
+ if(QDir(f).exists() && !QFileInfo(f).isSymLink() ) {
+ //if file is a directory
+
+ switch ( QMessageBox::warning( this, tr("Delete Directory?"),
+ tr("Really delete %1\nand all it's contents ?" ).arg( f ) ,
+ tr("Yes"), tr("No"), 0, 0, 1) ) {
+ case 0:
+ {
+ f=f.left(f.length()-1);
+ QString cmd="rm -rf "+f;
+ startProcess( (const QString)cmd.latin1() );
+ populateView();
+ }
+ break;
+ case 1:
+ // exit
+ break;
+ };
+
+ } else {
+ if(doMsg) {
+ switch ( QMessageBox::warning(this,tr("Delete"),
+ tr("Really delete\n%1?").arg( myFile ),
+ tr("Yes"), tr("No"), 0, 0, 1) ) {
+ case 1:
+ return;
+ break;
+ };
+ }
+
+ QString cmd="rm "+f;
+ QFile file(f);
+ QFileInfo fi(myFile);
+ if( fi.fileName().find("../",0,TRUE)==-1) {
+// odebug << "remove link files "+myFile << oendl;
+
+// DocLnk lnk(f);
+ DocLnk *lnk;
+ lnk = new DocLnk(f);
+// odebug << "Deleting doclnk " + lnk->linkFile() << oendl;
+ if(lnk->isValid())
+ lnk->removeLinkFile();
+ // delete lnk;
+ file.remove();
+ }
+ }
+ }
+ }
+ populateView();
+}
+
+void AdvancedFm::filePerms() {
+ QStringList curFileList = getPath();
+ QString filePath;
+
+ filePath = CurrentDir()->canonicalPath()+"/";
+
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+ filePermissions *filePerm;
+ filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(filePath+*it));
+ QPEApplication::execDialog( filePerm );
+ if( filePerm )
+ delete filePerm;
+ }
+ populateView();
+}
+
+void AdvancedFm::doProperties() {
+#if defined(QT_QWS_OPIE)
+
+ QStringList curFileList = getPath();
+
+ QString filePath;
+ filePath = CurrentDir()->canonicalPath()+"/";
+
+// odebug << "" << curFileList.count() << "" << oendl;
+
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+// odebug << (filePath+*it) << oendl;
+ DocLnk lnk( (filePath+*it));
+ LnkProperties prop( &lnk );
+ QPEApplication::execDialog( &prop );
+ }
+#endif
+
+}
+
+void AdvancedFm::upDir() {
+ QDir *thisDir = CurrentDir();
+ QString current = thisDir->canonicalPath();
+ QDir dir(current);
+ dir.cdUp();
+ current = dir.canonicalPath();
+ chdir( current.latin1() );
+ thisDir->cd( current, TRUE);
+
+ populateView();
+ update();
+}
+
+void AdvancedFm::copy() {
+ qApp->processEvents();
+ QStringList curFileList = getPath();
+
+ QDir *thisDir = CurrentDir();
+ QDir *thatDir = OtherDir();
+
+ bool doMsg=true;
+ int count=curFileList.count();
+ if( count > 0) {
+ if(count > 1 ){
+ QString msg;
+ msg=tr("Really copy\n%1 files?").arg(count);
+ switch ( QMessageBox::warning(this,tr("Copy"),msg
+ ,tr("Yes"),tr("No"),0,0,1) )
+ {
+ case 0:
+ doMsg=false;
+ break;
+ case 1:
+ return;
+ break;
+ };
+ }
+
+ QString curFile, item, destFile;
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+ item=(*it);
+ if(item.find("->",0,TRUE)) //symlink
+ item = item.left(item.find("->",0,TRUE));
+
+ curFile = thisDir->canonicalPath()+"/"+ item;
+ destFile = thatDir->canonicalPath()+"/"+ item;
+
+// odebug << "Destination file is "+destFile << oendl;
+// odebug << "CurrentFile file is " + curFile << oendl;
+
+ QFile f(destFile);
+ if( f.exists()) {
+ if(doMsg) {
+ switch ( QMessageBox::warning(this,tr("File Exists!"),
+ tr("%1 exists. Ok to overwrite?").arg( item ),
+ tr("Yes"),tr("No"),0,0,1) ) {
+ case 1:
+ return;
+ break;
+ };
+ }
+ f.remove();
+ }
+
+ if( !copyFile( curFile, destFile) ) {
+ QMessageBox::message("AdvancedFm",
+ tr( "Could not copy %1 to %2").arg( curFile ).arg( destFile ) );
+ return;
+ }
+ }
+ setOtherTabCurrent();
+ rePopulate();
+ }
+}
+
+void AdvancedFm::copyAs() {
+ qApp->processEvents();
+
+ QStringList curFileList = getPath();
+ QString curFile, item;
+ InputDialog *fileDlg;
+
+ QDir *thisDir = CurrentDir();
+ QDir *thatDir = OtherDir();
+
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+ QString destFile;
+ item=(*it);
+ curFile = thisDir->canonicalPath()+"/"+(*it);
+ fileDlg = new InputDialog( this, tr("Copy "+curFile+" As"), TRUE, 0);
+
+ fileDlg->setInputText((const QString &) destFile );
+ fileDlg->exec();
+
+ if( fileDlg->result() == 1 ) {
+ QString filename = fileDlg->LineEdit1->text();
+ destFile = thatDir->canonicalPath()+"/"+filename;
+
+ QFile f( destFile);
+ if( f.exists()) {
+ switch (QMessageBox::warning(this,tr("File Exists!"),
+ item+tr("\nexists. Ok to overwrite?"),
+ tr("Yes"),tr("No"),0,0,1) ) {
+ case 0:
+ f.remove();
+ break;
+ case 1:
+ return;
+ break;
+ };
+ }
+ if( !copyFile( curFile, destFile) ) {
+ QMessageBox::message("AdvancedFm",tr("Could not copy\n")
+ +curFile +tr("to\n")+destFile);
+ return;
+ }
+ }
+ delete fileDlg;
+
+ }
+ rePopulate();
+ setOtherTabCurrent();
+}
+
+void AdvancedFm::copySameDir() {
+ qApp->processEvents();
+ QStringList curFileList = getPath();
+ QString curFile, item, destFile;
+ InputDialog *fileDlg;
+
+ QDir *thisDir = CurrentDir();
+
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+ item=(*it);
+ curFile = thisDir->canonicalPath()+"/"+ item;
+
+ fileDlg = new InputDialog(this,tr("Copy ")+curFile+tr(" As"),TRUE, 0);
+ fileDlg->setInputText((const QString &) destFile );
+ fileDlg->exec();
+
+ if( fileDlg->result() == 1 ) {
+
+ QString filename = fileDlg->LineEdit1->text();
+ destFile = thisDir->canonicalPath()+"/"+filename;
+
+ QFile f(destFile);
+ if( f.exists()) {
+ switch (QMessageBox::warning(this,tr("Delete"),
+ destFile+tr(" already exists.\nDo you really want to delete it?"),
+ tr("Yes"),tr("No"),0,0,1) ) {
+ case 0:
+
+ f.remove();
+ break;
+ case 1:
+ return;
+ break;
+ };
+ }
+ if(!copyFile( curFile,destFile) ) {
+ QMessageBox::message("AdvancedFm",tr("Could not copy\n")
+ +curFile +tr("to\n")+destFile);
+ return;
+ }
+
+// odebug << "copy "+curFile+" as "+destFile << oendl;
+ }
+ delete fileDlg;
+ }
+ rePopulate();
+}
+
+void AdvancedFm::move() {
+ qApp->processEvents();
+
+ QStringList curFileList = getPath();
+ if( curFileList.count() > 0) {
+ QString curFile, destFile, item;
+
+ QDir *thisDir = CurrentDir();
+ QDir *thatDir = OtherDir();
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+ item=(*it);
+ QString destFile = thatDir->canonicalPath();
+
+ if(destFile.right(1).find("/",0,TRUE) == -1)
+ destFile+="/";
+ destFile += item;
+// odebug << "Destination file is "+destFile << oendl;
+
+ curFile = thisDir->canonicalPath();
+ if(curFile.right(1).find("/",0,TRUE) == -1)
+ curFile +="/";
+ curFile+= item;
+// odebug << "CurrentFile file is " + curFile << oendl;
+
+ if(QFileInfo(curFile).isDir()) {
+ moveDirectory( curFile, destFile );
+ rePopulate();
+ return;
+ }
+
+ QFile f( curFile);
+ if( f.exists()) {
+ if( !copyFile( curFile, destFile) ) {
+ QMessageBox::message(tr("Note"),tr("Could not move\n")+curFile);
+ return;
+ } else
+ QFile::remove(curFile);
+ }
+ }
+
+ }
+ rePopulate();
+ setOtherTabCurrent();
+}
+
+bool AdvancedFm::moveDirectory( const QString & src, const QString & dest ) {
+ int err = 0;
+ if( copyDirectory( src, dest ) ) { QString cmd = "rm -rf " + src;
+ err = system((const char*)cmd);
+ } else
+ err = -1;
+
+ if(err!=0) {
+ QMessageBox::message(tr("Note"),tr("Could not move\n") + src);
+ return false;
+ }
+ return true;
+}
+
+bool AdvancedFm::copyDirectory( const QString & src, const QString & dest ) {
+
+ QString cmd = "/bin/cp -fpR " + src + " " + dest;
+ owarn << cmd << oendl;
+ int err = system( (const char *) cmd );
+ if ( err != 0 ) {
+ QMessageBox::message("AdvancedFm",
+ tr( "Could not copy \n%1 \nto \n%2").arg( src ).arg( dest ) );
+ return false;
+ }
+
+ return true;
+}
+
+
+bool AdvancedFm::copyFile( const QString & src, const QString & dest ) {
+
+
+ if(QFileInfo(src).isDir()) {
+ if( copyDirectory( src, dest )) {
+ setOtherTabCurrent();
+ populateView();
+ return true;
+ }
+ else
+ return false;
+ }
+
+
+ bool success = true;
+ struct stat status;
+ QFile srcFile(src);
+ QFile destFile(dest);
+ int err=0;
+ int read_fd=0;
+ int write_fd=0;
+ struct stat stat_buf;
+ off_t offset = 0;
+ if(!srcFile.open( IO_ReadOnly|IO_Raw)) {
+// owarn << "open failed" << oendl;
+ return success = false;
+ }
+ read_fd = srcFile.handle();
+ if(read_fd != -1) {
+ fstat (read_fd, &stat_buf);
+ if( !destFile.open( IO_WriteOnly|IO_Raw ) ) {
+// owarn << "destfile open failed" << oendl;
+ return success = false;
+ }
+ write_fd = destFile.handle();
+ if(write_fd != -1) {
+ err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size);
+ if( err == -1) {
+ QString msg;
+ switch(err) {
+ case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. ";
+ case EINVAL: msg = "Descriptor is not valid or locked. ";
+ case ENOMEM: msg = "Insufficient memory to read from in_fd.";
+ case EIO: msg = "Unspecified error while reading from in_fd.";
+ };
+ success = false;
+// owarn << msg << oendl;
+ }
+ } else {
+ success = false;
+ }
+ } else {
+ success = false;
+ }
+ srcFile.close();
+ destFile.close();
+ // Set file permissions
+ if( stat( (const char *) src, &status ) == 0 ) {
+ chmod( (const char *) dest, status.st_mode );
+ }
+
+ return success;
+}
+
+void AdvancedFm::runCommand() {
+ if( !CurrentView()->currentItem()) return;
+ QDir *thisDir = CurrentDir();
+
+ QString curFile;
+ curFile = thisDir->canonicalPath() +"/"+ CurrentView()->currentItem()->text(0);
+
+ InputDialog *fileDlg;
+ fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0);
+ fileDlg->setInputText(curFile);
+ fileDlg->exec();
+ //QString command;
+
+ if( fileDlg->result() == 1 ) {
+// odebug << fileDlg->LineEdit1->text() << oendl;
+ QStringList command;
+
+ command << "/bin/sh";
+ command << "-c";
+ command << fileDlg->LineEdit1->text();
+ Output *outDlg;
+ outDlg = new Output( command, this, tr("AdvancedFm Output"), true);
+ QPEApplication::execDialog( outDlg );
+ qApp->processEvents();
+
+ }
+}
+
+void AdvancedFm::runCommandStd() {
+ if( !CurrentView()->currentItem()) return;
+ QString curFile;
+ QDir *thisDir = CurrentDir();
+ QListView *thisView = CurrentView();
+ if( thisView->currentItem())
+ curFile = thisDir->canonicalPath() +"/"+ thisView->currentItem()->text(0);
+
+ InputDialog *fileDlg;
+ fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0);
+ fileDlg->setInputText(curFile);
+ fileDlg->exec();
+
+ if( fileDlg->result() == 1 ) {
+ qApp->processEvents();
+ startProcess( (const QString)fileDlg->LineEdit1->text().latin1());
+ }
+}
+
+void AdvancedFm::fileStatus() {
+ if( !CurrentView()->currentItem()) return;
+ QString curFile;
+ curFile = CurrentView()->currentItem()->text(0);
+
+ QStringList command;
+ command << "/bin/sh";
+ command << "-c";
+ command << "stat -l "+ curFile;
+
+ Output *outDlg;
+ outDlg = new Output( command, this, tr("AdvancedFm Output"), true);
+ QPEApplication::execDialog( outDlg );
+ qApp->processEvents();
+}
+
+
+void AdvancedFm::mkDir() {
+ makeDir();
+}
+
+void AdvancedFm::rn() {
+ renameIt();
+}
+
+void AdvancedFm::del() {
+ doDelete();
+}
+
+void AdvancedFm::mkSym() {
+ QString cmd;
+ QStringList curFileList = getPath();
+ if( curFileList.count() > 0) {
+ QDir *thisDir = CurrentDir();
+ QDir * thatDir = OtherDir();
+
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+
+ QString destName = thatDir->canonicalPath()+"/"+(*it);
+ if(destName.right(1) == "/") {
+ destName = destName.left( destName.length() -1);
+ }
+
+ QString curFile = thisDir->canonicalPath()+"/"+(*it);
+
+ if( curFile.right(1) == "/") {
+ curFile = curFile.left( curFile.length() -1);
+ }
+
+ cmd = "ln -s "+curFile+" "+destName;
+// odebug << cmd << oendl;
+ startProcess( (const QString)cmd );
+ }
+ rePopulate();
+ setOtherTabCurrent();
+ }
+}
+
+void AdvancedFm::doBeam() {
+ Ir ir;
+ if(!ir.supported()) {
+ } else {
+ QStringList curFileList = getPath();
+ if( curFileList.count() > 0) {
+ for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
+ QString curFile = (*it);
+ QString curFilePath = CurrentDir()->canonicalPath()+"/"+curFile;
+ if( curFilePath.right(1) == "/") {
+ curFilePath = curFilePath.left( curFilePath.length() -1);
+ }
+ Ir *file = new Ir(this, "IR");
+ connect(file, SIGNAL(done(Ir*)), this, SLOT( fileBeamFinished(Ir*)));
+ file->send( curFilePath, curFile );
+ }
+ }
+ }
+}
+
+void AdvancedFm::fileBeamFinished( Ir *) {
+ QMessageBox::message( tr("Advancedfm Beam out"), tr("Ir sent.") ,tr("Ok") );
+}
+
+void AdvancedFm::selectAll() {
+ QListView *thisView = CurrentView();
+ thisView->selectAll(true);
+ thisView->setSelected( thisView->firstChild(),false);
+}
+
+void AdvancedFm::startProcess(const QString & cmd) {
+ QStringList command;
+ OProcess *process;
+ process = new OProcess();
+ connect(process, SIGNAL(processExited(Opie::Core::OProcess*)),
+ this, SLOT( processEnded(Opie::Core::OProcess*)));
+
+ connect(process, SIGNAL( receivedStderr(Opie::Core::OProcess*,char*,int)),
+ this, SLOT( oprocessStderr(Opie::Core::OProcess*,char*,int)));
+
+ command << "/bin/sh";
+ command << "-c";
+ command << cmd.latin1();
+ *process << command;
+ if(!process->start(OProcess::NotifyOnExit, OProcess::All) )
+ odebug << "could not start process" << oendl;
+}
+
+void AdvancedFm::processEnded(OProcess *) {
+ rePopulate();
+}
+
+void AdvancedFm::oprocessStderr(OProcess*, char *buffer, int ) {
+// owarn << "received stderrt " << buflen << " bytes" << oendl;
+
+ QString lineStr = buffer;
+ QMessageBox::warning( this, tr("Error"), lineStr ,tr("Ok") );
+}
+
+bool AdvancedFm::eventFilter( QObject * o, QEvent * e ) {
+ if ( o->inherits( "QLineEdit" ) ) {
+ if ( e->type() == QEvent::KeyPress ) {
+ QKeyEvent *ke = (QKeyEvent*)e;
+ if ( ke->key() == Key_Return ||
+ ke->key() == Key_Enter ) {
+ okRename();
+ return true;
+ }
+ else if ( ke->key() == Key_Escape ) {
+ cancelRename();
+ return true;
+ }
+ }
+ else if ( e->type() == QEvent::FocusOut ) {
+ cancelRename();
+ return true;
+ }
+ }
+ if ( o->inherits( "QListView" ) ) {
+ if ( e->type() == QEvent::FocusIn ) {
+ if( o == Local_View) { //keep track of which view
+ whichTab=1;
+ }
+ else {
+ whichTab=2;
+ }
+ }
+ OtherView()->setSelected( OtherView()->currentItem(), FALSE );//make sure there's correct selection
+ }
+
+ return QWidget::eventFilter( o, e );
+}
+
+
+void AdvancedFm::cancelRename() {
+// odebug << "cancel rename" << oendl;
+ QListView * view;
+ view = CurrentView();
+
+ bool resetFocus = view->viewport()->focusProxy() == renameBox;
+ delete renameBox;
+ renameBox = 0;
+ if ( resetFocus ) {
+ view->viewport()->setFocusProxy( view);
+ view->setFocus();
+ }
+}
+
+void AdvancedFm::doRename(QListView * view) {
+ if( !CurrentView()->currentItem()) return;
+
+ QRect r = view->itemRect( view->currentItem( ));
+ r = QRect( view->viewportToContents( r.topLeft() ), r.size() );
+ r.setX( view->contentsX() );
+
+ if ( r.width() > view->visibleWidth() )
+ r.setWidth( view->visibleWidth() );
+
+ renameBox = new QLineEdit( view->viewport(), "qt_renamebox" );
+ renameBox->setFrame(true);
+
+ renameBox->setText( view->currentItem()->text(0) );
+
+ renameBox->selectAll();
+ renameBox->installEventFilter( this );
+
+ view->addChild( renameBox, r.x(), r.y() );
+
+ renameBox->resize( r.size() );
+
+ view->viewport()->setFocusProxy( renameBox );
+
+ renameBox->setFocus();
+ renameBox->show();
+}
+
+
+void AdvancedFm::renameIt() {
+ if( !CurrentView()->currentItem()) return;
+
+ QListView *thisView = CurrentView();
+ oldName = thisView->currentItem()->text(0);
+ doRename( thisView );
+}
+
+void AdvancedFm::okRename() {
+ if( !renameBox) return;
+
+ QString newName = renameBox->text();
+ cancelRename();
+ QListView * view = CurrentView();
+ QString path = CurrentDir()->canonicalPath() + "/";
+ oldName = path + oldName;
+ newName = path + newName;
+ if( rename( oldName.latin1(), newName.latin1())== -1)
+ QMessageBox::message(tr("Note"),tr("Could not rename"));
+ else
+ oldName = "";
+ QListViewItem *item = view->currentItem();
+ view->takeItem( item );
+ delete item;
+ rePopulate();
+}
+
+void AdvancedFm::openSearch() {
+ QMessageBox::message(tr("Note"),tr("Not Yet Implemented"));
+}
diff --git a/noncore/apps/advancedfm/filePermissions.cpp b/noncore/apps/advancedfm/filePermissions.cpp
index 9698de7..b7d48e8 100644
--- a/noncore/apps/advancedfm/filePermissions.cpp
+++ b/noncore/apps/advancedfm/filePermissions.cpp
@@ -1,131 +1,131 @@
/****************************************************************************
** copyright 2002 ljp ljp@llornkcor.com
** Created: Sat Feb 23 19:44:40 2002 L.J. Potter
**
** 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.
**
****************************************************************************/
#include "filePermissions.h"
#include <qfileinfo.h>
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qmessagebox.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
filePermissions::filePermissions( QWidget* parent, const char* name, bool modal, WFlags fl, const QString &fileName )
: QDialog( parent, name, modal, fl )
{
if ( !name )
setName( tr("filePermissions") );
-// qDebug("FilePermissions "+fileName);
+// odebug << "FilePermissions "+fileName << oendl;
/* resize( 236, 210 );
setMaximumSize( QSize( 236, 210 ) );
*/ setCaption( tr( "Set File Permissions" ) );
TextLabel1 = new QLabel( this, "TextLabel1" );
TextLabel1->setGeometry( QRect( 25, 5, 175, 20 ) );
TextLabel1->setText( tr( "Set file permissions for:" ) );
LineEdit1 = new QLineEdit( this, "LineEdit1" );
LineEdit1->setGeometry( QRect( 10, 25, 218, 22 ) );
LineEdit1->setReadOnly(true);
TextLabel4 = new QLabel( this, "TextLabel4" );
TextLabel4->setGeometry( QRect( 5, 85, 50, 15 ) );
TextLabel4->setText( tr( "owner" ) );
TextLabel4_2 = new QLabel( this, "TextLabel4_2" );
TextLabel4_2->setGeometry( QRect( 5, 105, 50, 15 ) );
TextLabel4_2->setText( tr( "group" ) );
TextLabel4_3 = new QLabel( this, "TextLabel4_3" );
TextLabel4_3->setGeometry( QRect( 5, 125, 50, 15 ) );
TextLabel4_3->setText( tr( "others" ) );
CheckBox1 = new QCheckBox( this, "CheckBox1" );
CheckBox1->setGeometry( QRect( 75, 85, 20, 16 ) );
connect(CheckBox1, SIGNAL(released()),this,SLOT(ownReadCheck()));
CheckBox1_2 = new QCheckBox( this, "CheckBox1_2" );
CheckBox1_2->setGeometry( QRect( 135, 85, 20, 16 ) );
connect(CheckBox1_2, SIGNAL(released()),this,SLOT(ownWriteCheck()));
CheckBox1_3 = new QCheckBox( this, "CheckBox1_3" );
CheckBox1_3->setGeometry( QRect( 195, 85, 20, 16 ) );
connect(CheckBox1_3, SIGNAL(released()),this,SLOT(ownExeCheck()));
CheckBox1_4 = new QCheckBox( this, "CheckBox1_4" );
CheckBox1_4->setGeometry( QRect( 75, 105, 20, 16 ) );
connect(CheckBox1_4, SIGNAL(released()),this,SLOT(grpReadCheck()));
CheckBox1_5 = new QCheckBox( this, "CheckBox1_5" );
CheckBox1_5->setGeometry( QRect( 135, 105, 20, 16 ) );
connect(CheckBox1_5, SIGNAL(released()),this,SLOT(grpWriteCheck()));
CheckBox1_6 = new QCheckBox( this, "CheckBox1_6" );
CheckBox1_6->setGeometry( QRect( 195, 105, 20, 16 ) );
connect(CheckBox1_6, SIGNAL(released()),this,SLOT(grpExeCheck()));
CheckBox1_7 = new QCheckBox( this, "CheckBox1_7" );
CheckBox1_7->setGeometry( QRect( 75, 125, 16, 16 ) );
connect(CheckBox1_7, SIGNAL(released()),this,SLOT(wrldReadCheck()));
CheckBox1_8 = new QCheckBox( this, "CheckBox1_8" );
CheckBox1_8->setGeometry( QRect( 135, 125, 20, 16 ) );
connect(CheckBox1_8, SIGNAL(released()),this,SLOT(wrldWriteCheck()));
CheckBox1_8_2 = new QCheckBox( this, "CheckBox1_8_2" );
CheckBox1_8_2->setGeometry( QRect( 195, 125, 20, 16 ) );
connect(CheckBox1_8_2, SIGNAL(released()),this,SLOT(wrldExeCheck()));
GroupLineEdit = new QLineEdit( this, "GroupLineEdit" );
GroupLineEdit->setGeometry( QRect( 125, 155, 106, 22 ) );
OwnerLineEdit = new QLineEdit( this, "OwnerLineEdit" );
OwnerLineEdit->setGeometry( QRect( 10, 155, 106, 22 ) );
TextLabel5 = new QLabel( this, "TextLabel5" );
TextLabel5->setGeometry( QRect( 45, 180, 40, 16 ) );
TextLabel5->setText( tr( "Owner" ) );
TextLabel5_2 = new QLabel( this, "TextLabel5_2" );
TextLabel5_2->setGeometry( QRect( 155, 180, 40, 16 ) );
TextLabel5_2->setText( tr( "Group" ) );
ModeLine = new QLineEdit( this, "TextLabelMode" );
ModeLine->setGeometry( QRect( 10, 60, 40, 15 ) );
TextLabel3_2 = new QLabel( this, "TextLabel3_2" );
TextLabel3_2->setGeometry( QRect( 60, 55, 50, 20 ) );
TextLabel3_2->setText( tr( "read" ) );
TextLabel3_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
TextLabel3_2_2 = new QLabel( this, "TextLabel3_2_2" );
TextLabel3_2_2->setGeometry( QRect( 120, 55, 50, 20 ) );
TextLabel3_2_2->setText( tr( "write" ) );
TextLabel3_2_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
TextLabel3 = new QLabel( this, "TextLabel3" );
TextLabel3->setGeometry( QRect( 180, 55, 50, 20 ) );
TextLabel3->setText( tr( "execute" ) );
TextLabel3->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
struct stat buf;
mode_t mode;
file = fileName;
QFileInfo fi(file);
diff --git a/noncore/apps/advancedfm/output.cpp b/noncore/apps/advancedfm/output.cpp
index 6906298..8c585f4 100644
--- a/noncore/apps/advancedfm/output.cpp
+++ b/noncore/apps/advancedfm/output.cpp
@@ -1,278 +1,281 @@
/****************************************************************************
** outputEdit.cpp
**
** Copyright: Fri Apr 12 15:12:58 2002 L.J. Potter <ljp@llornkcor.com>
****************************************************************************/
#include "output.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
#include <qpe/applnk.h>
+using namespace Opie::Core;
+/* QT */
#include <qfile.h>
#include <qmultilineedit.h>
#include <qpushbutton.h>
#include <qlayout.h>
+/* STD */
#include <errno.h>
/* XPM */
-using namespace Opie::Core;
-using namespace Opie::Core;
static char * filesave_xpm[] = {
"16 16 78 1",
" c None",
". c #343434",
"+ c #A0A0A0",
"@ c #565656",
"# c #9E9E9E",
"$ c #525252",
"% c #929292",
"& c #676767",
"* c #848484",
"= c #666666",
"- c #D8D8D8",
"; c #FFFFFF",
"> c #DBDBDB",
", c #636363",
"' c #989898",
") c #2D2D2D",
"! c #909090",
"~ c #AEAEAE",
"{ c #EAEAEA",
"] c #575757",
"^ c #585858",
"/ c #8A8A8A",
"( c #828282",
"_ c #6F6F6F",
": c #C9C9C9",
"< c #050505",
"[ c #292929",
"} c #777777",
"| c #616161",
"1 c #3A3A3A",
"2 c #BEBEBE",
"3 c #2C2C2C",
"4 c #7C7C7C",
"5 c #F6F6F6",
"6 c #FCFCFC",
"7 c #6B6B6B",
"8 c #959595",
"9 c #4F4F4F",
"0 c #808080",
"a c #767676",
"b c #818181",
"c c #B8B8B8",
"d c #FBFBFB",
"e c #F9F9F9",
"f c #CCCCCC",
"g c #030303",
"h c #737373",
"i c #7A7A7A",
"j c #7E7E7E",
"k c #6A6A6A",
"l c #FAFAFA",
"m c #505050",
"n c #9D9D9D",
"o c #333333",
"p c #7B7B7B",
"q c #787878",
"r c #696969",
"s c #494949",
"t c #555555",
"u c #949494",
"v c #E6E6E6",
"w c #424242",
"x c #515151",
"y c #535353",
"z c #3E3E3E",
"A c #D4D4D4",
"B c #0C0C0C",
"C c #353535",
"D c #474747",
"E c #ECECEC",
"F c #919191",
"G c #7D7D7D",
"H c #000000",
"I c #404040",
"J c #858585",
"K c #323232",
"L c #D0D0D0",
"M c #1C1C1C",
" ...+ ",
" @#$%&..+ ",
" .*=-;;>,..+ ",
" ')!~;;;;;;{]..",
" ^/(-;;;;;;;_:<",
" [}|;;;;;;;{12$",
" #34-55;;;;678$+",
" 90ab=c;dd;e1fg ",
" [ahij((kbl0mn$ ",
" op^q^^7r&]s/$+ ",
"@btu;vbwxy]zAB ",
"CzDEvEv;;DssF$ ",
"G.H{E{E{IxsJ$+ ",
" +...vEKxzLM ",
" +...z]n$ ",
" +... "};
Output::Output( const QStringList commands, QWidget* parent, const char* name, bool modal, WFlags fl)
: QDialog( parent, name, modal, fl )
{
QStringList cmmds;
// cmmds=QStringList::split( " ", commands, false);
cmmds=commands;
-// qDebug("count %d", cmmds.count());
+// odebug << "count " << cmmds.count() << "" << oendl;
if ( !name )
setName( tr("Output"));
resize( 196, 269 );
setCaption( name );
OutputLayout = new QGridLayout( this );
OutputLayout->setSpacing( 2);
OutputLayout->setMargin( 2);
QPushButton *docButton;
docButton = new QPushButton( QPixmap(( const char** ) filesave_xpm ) ,"",this,"saveButton");
docButton->setFixedSize( QSize( 20, 20 ) );
connect( docButton,SIGNAL(released()),this,SLOT( saveOutput() ));
// docButton->setFlat(TRUE);
OutputLayout->addMultiCellWidget( docButton, 0,0,3,3 );
OutputEdit = new QMultiLineEdit( this, "OutputEdit" );
OutputLayout->addMultiCellWidget( OutputEdit, 1,1,0,3 );
proc = new OProcess();
connect(proc, SIGNAL(processExited(Opie::Core::OProcess*)),
this, SLOT( processFinished()));
connect(proc, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)),
this, SLOT(commandStdout(Opie::Core::OProcess*,char*,int)));
connect(proc, SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)),
this, SLOT(commandStderr(Opie::Core::OProcess*,char*,int)));
// connect( , SIGNAL(received(const QByteArray&)),
// this, SLOT(commandStdin(const QByteArray&)));
// * proc << commands.latin1();
for ( QStringList::Iterator it = cmmds.begin(); it != cmmds.end(); ++it ) {
- qDebug( "%s", (*it).latin1() );
+ odebug << "" << (*it).latin1() << "" << oendl;
* proc << (*it).latin1();
}
if(!proc->start(OProcess::NotifyOnExit, OProcess::All)) {
OutputEdit->append(tr("Process could not start") );
OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
perror("Error: ");
QString errorMsg=tr("Error\n")+(QString)strerror(errno);
OutputEdit->append( errorMsg);
OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
}
}
Output::~Output() {
}
void Output::saveOutput() {
InputDialog *fileDlg;
fileDlg = new InputDialog(this,tr("Save output to file (name only)"),TRUE, 0);
fileDlg->exec();
if( fileDlg->result() == 1 ) {
QString filename = QPEApplication::documentDir();
if(filename.right(1).find('/') == -1)
filename+="/";
QString name = fileDlg->LineEdit1->text();
filename+="text/plain/"+name;
- qDebug(filename);
+ odebug << filename << oendl;
QFile f(filename);
f.open( IO_WriteOnly);
if( f.writeBlock( OutputEdit->text(), qstrlen( OutputEdit->text()) ) != -1) {
DocLnk lnk;
lnk.setName(name); //sets file name
lnk.setFile(filename); //sets File property
lnk.setType("text/plain");
if(!lnk.writeLink()) {
- qDebug("Writing doclink did not work");
+ odebug << "Writing doclink did not work" << oendl;
}
} else
- qWarning("Could not write file");
+ owarn << "Could not write file" << oendl;
f.close();
}
}
void Output::commandStdout(OProcess*, char *buffer, int buflen) {
- qWarning("received stdout %d bytes", buflen);
+ owarn << "received stdout " << buflen << " bytes" << oendl;
// QByteArray data(buflen);
// data.fill(*buffer, buflen);
// for (uint i = 0; i < data.count(); i++ ) {
// printf("%c", buffer[i] );
// }
// printf("\n");
QString lineStr = buffer;
lineStr=lineStr.left(lineStr.length()-1);
OutputEdit->append(lineStr);
OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
}
void Output::commandStdin( const QByteArray &data) {
- qWarning("received stdin %d bytes", data.size());
+ owarn << "received stdin " << data.size() << " bytes" << oendl;
// recieved data from the io layer goes to sz
proc->writeStdin(data.data(), data.size());
}
void Output::commandStderr(OProcess*, char *buffer, int buflen) {
- qWarning("received stderrt %d bytes", buflen);
+ owarn << "received stderrt " << buflen << " bytes" << oendl;
QString lineStr = buffer;
// lineStr=lineStr.left(lineStr.length()-1);
OutputEdit->append(lineStr);
OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
}
void Output::processFinished() {
delete proc;
OutputEdit->append( tr("\nFinished\n") );
OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
// close();
// disconnect( layer(), SIGNAL(received(const QByteArray&)),
// this, SLOT(commandStdin(const QByteArray&)));
}
//==============================
InputDialog::InputDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
: QDialog( parent, name, modal, fl )
{
if ( !name )
setName( "InputDialog" );
resize( 234, 50 );
setMaximumSize( QSize( 240, 50 ) );
setCaption( tr(name ) );
LineEdit1 = new QLineEdit( this, "LineEdit1" );
LineEdit1->setGeometry( QRect( 10, 10, 216, 22 ) );
LineEdit1->setFocus();
LineEdit1->setFocus();
connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(returned() ));
}
InputDialog::~InputDialog() {
inputText = LineEdit1->text();
}
void InputDialog::setInputText(const QString &string) {
LineEdit1->setText( string);
}
void InputDialog::returned() {
inputText = LineEdit1->text();
this->accept();
}
diff --git a/noncore/apps/checkbook/checkbook.pro b/noncore/apps/checkbook/checkbook.pro
index 34641f4..1472df6 100644
--- a/noncore/apps/checkbook/checkbook.pro
+++ b/noncore/apps/checkbook/checkbook.pro
@@ -1,32 +1,32 @@
-CONFIG = qt warn_on quick-app
+CONFIG = qt warn_on quick-app
HEADERS = mainwindow.h \
cbinfo.h \
traninfo.h \
graphinfo.h \
configuration.h \
password.h \
checkbook.h \
transaction.h \
tabledef.h \
listedit.h \
cfg.h \
graph.h
SOURCES = main.cpp \
mainwindow.cpp \
cbinfo.cpp \
traninfo.cpp \
graphinfo.cpp \
configuration.cpp \
password.cpp \
checkbook.cpp \
transaction.cpp \
tabledef.cpp \
listedit.cpp \
cfg.cpp \
graph.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
LIBS += -lqpe -lopiecore2 -lopieui2
TARGET = checkbook
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/checkbook/listedit.cpp b/noncore/apps/checkbook/listedit.cpp
index d00e305..5026c9d 100644
--- a/noncore/apps/checkbook/listedit.cpp
+++ b/noncore/apps/checkbook/listedit.cpp
@@ -1,133 +1,138 @@
/*
                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 "listedit.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/resource.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qlayout.h>
#include <qlineedit.h>
#include <qlistview.h>
#include <qwidgetstack.h>
#include <qcombobox.h>
#include <qpushbutton.h>
-#include <qpe/resource.h>
-
// --- ListEdit ---------------------------------------------------------------
ListEdit::ListEdit( QWidget *parent, const char *sName )
: QWidget(parent, sName), TableDef(sName)
{
// get font height
int fh = fontMetrics().height();
// create layout
QGridLayout *layout=new QGridLayout(this);
layout->setSpacing( 2 );
layout->setMargin( 4 );
// type table
_typeTable = new QListView( this );
ColumnDef *def=first();
while( def ) {
_typeTable->addColumn( def->getName() );
def=next();
}
connect( _typeTable, SIGNAL( clicked(QListViewItem*,const QPoint&,int) ), this, SLOT( slotClick(QListViewItem*,const QPoint&,int) ) );
layout->addMultiCellWidget(_typeTable, 0,4,0,4);
_currentItem=NULL;
// edit field
_stack=new QWidgetStack( this );
_stack->setMaximumHeight(fh+5);
layout->addMultiCellWidget(_stack, 5,5,0,2);
_typeEdit = new QLineEdit( _stack );
_stack->raiseWidget(_typeEdit );
connect( _typeEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotEditChanged(const QString&) ) );
// combo box
_box=new QComboBox( _stack );
connect( _box, SIGNAL( activated(const QString&) ), this, SLOT( slotActivated(const QString&) ) );
// add button
QPushButton *btn = new QPushButton( Resource::loadPixmap( "checkbook/add" ), tr( "Add" ), this );
connect( btn, SIGNAL( clicked() ), this, SLOT( slotAdd() ) );
layout->addWidget( btn, 5, 3 );
// delete button
btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), this );
connect( btn, SIGNAL( clicked() ), this, SLOT( slotDel() ) );
layout->addWidget( btn, 5, 4 );
}
// --- ~ListEdit --------------------------------------------------------------
ListEdit::~ListEdit()
{
}
// --- slotEditTypeChanged ----------------------------------------------------
void ListEdit::slotEditChanged(const QString &str)
{
if( !_currentItem || _currentColumn<0 ) return;
_currentItem->setText(_currentColumn, str);
}
// --- slotAddType ------------------------------------------------------------
void ListEdit::slotAdd()
{
// construct new row
QString args[8];
ColumnDef *pCol=this->first();
int i=0;
while( pCol && i<8 ) {
args[i++]=pCol->getNewValue();
pCol=this->next();
}
_currentItem=new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7] );
// fix uniques
fixTypes();
// display col 0 of new value
QPoint pnt;
slotClick(_currentItem, pnt, 0);
_typeTable->setSelected( _currentItem, true );
// make it selected
_typeEdit->setCursorPosition(0);
_typeEdit->setSelection(0, _typeEdit->text().length() );
}
// --- slotDel -------------------------------------------------------------
void ListEdit::slotDel()
{
if( !_currentItem ) return;
delete _currentItem;
_currentItem=NULL;
_typeEdit->setText("");
_stack->raiseWidget(_typeEdit);
}
@@ -209,136 +214,136 @@ void ListEdit::fixTypes(int iColumn)
bDup=true;
break;
}
iChk++;
}
if( !bDup ) {
*lst.at(iNext)=repl;
break;
}
}
}
}
lst.sort();
// copy back clean up col map
for(int i=0; i<_typeTable->childCount(); i++) {
colMap[i]->getItem()->setText(iColumn, colMap[i]->getValue());
delete colMap[i];
}
delete colMap;
}
void ListEdit::fixTypes()
{
int i;
ColumnDef *pDef;
for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) {
if( pDef->hasFlag(ColumnDef::typeUnique) )
fixTypes(i);
}
_typeTable->sort();
}
// --- storeInList ------------------------------------------------------------
void ListEdit::storeInList(QStringList &lst)
{
// delete old content
lst.clear();
// add new one
fixTypes();
QListViewItem *itm=_typeTable->firstChild();
while( itm ) {
int i=0;
QString sAdd;
ColumnDef *pDef;
for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) {
if( i>=1 ) sAdd+=";";
sAdd += itm->text(i);
}
lst.append( sAdd );
itm=itm->nextSibling();
}
}
// --- slotClicked ------------------------------------------------------------
void ListEdit::slotClick(QListViewItem *itm, const QPoint &pnt, int col)
{
(void)pnt; // get rid of unused warning;
// save values
_currentItem=itm;
_currentColumn=col;
if( itm==NULL ) {
_typeEdit->setText("");
_stack->raiseWidget(_typeEdit);
return;
}
// display value
if( _currentColumn<0 ) _currentColumn=0;
ColumnDef *pDef=this->at(_currentColumn);
if( pDef->isType(ColumnDef::typeString) ) {
_typeEdit->setText( _currentItem->text(_currentColumn) );
_stack->raiseWidget(_typeEdit);
} else if( pDef->isType(ColumnDef::typeList) ){
_box->clear();
_box->insertStringList( pDef->getValueList() );
QStringList::Iterator itr;
int i=0;
for(itr=pDef->getValueList().begin(); itr!=pDef->getValueList().end(); itr++) {
if( (*itr)==_currentItem->text(_currentColumn) ) {
_box->setCurrentItem(i);
i=-1;
break;
}
i++;
}
if( i>=0 ) {
_box->insertItem( _currentItem->text(_currentColumn) );
_box->setCurrentItem(i);
}
_stack->raiseWidget(_box);
} else {
- qDebug( "Unsupported column type for column %s", (const char *)pDef->getName() );
+ odebug << "Unsupported column type for column " << (const char *)pDef->getName() << "" << oendl;
_typeEdit->setText("");
_stack->raiseWidget(_typeEdit);
}
}
// --- addColumnDef -----------------------------------------------------------
void ListEdit::addColumnDef(ColumnDef *pDef)
{
_typeTable->addColumn( pDef->getName() );
_vColumns.append(pDef);
}
// --- addData ----------------------------------------------------------------
void ListEdit::addData(QStringList &lst)
{
// run through list
QStringList::Iterator itr;
for(itr=lst.begin(); itr!=lst.end(); itr++) {
QStringList split=QStringList::split(";", *itr, true);
QStringList::Iterator entry;
QString args[8];
int i=0;
for(entry=split.begin(); entry!=split.end() && i<8; entry++, i++) {
args[i]= (*entry);
}
while(i<8) {
args[i++]="";
}
new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
}
}
// --- slotActivated ----------------------------------------------------------
void ListEdit::slotActivated(const QString &str)
{
if( _currentItem==NULL || _currentColumn<0 ) return;
_currentItem->setText(_currentColumn, str);
}
diff --git a/noncore/apps/checkbook/tabledef.cpp b/noncore/apps/checkbook/tabledef.cpp
index 9a42308..745cd80 100644
--- a/noncore/apps/checkbook/tabledef.cpp
+++ b/noncore/apps/checkbook/tabledef.cpp
@@ -1,74 +1,76 @@
/*
                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 "tabledef.h"
+#include <opie2/odebug.h>
+using namespace Opie::Core;
// --- ColumnDef --------------------------------------------------------------
ColumnDef::ColumnDef(const char *sName, ColumnType type, const char *sNewValue)
{
_sName=sName;
_type=type;
_sNewValue=sNewValue;
}
// --- addColumnValue ---------------------------------------------------------
void ColumnDef::addColumnValue(const QString &sValue)
{
if( (_type & 0x00ffffff) !=typeList )
- qDebug("Column %s is not a list", (const char *)_sName);
+ odebug << "Column " << (const char *)_sName << " is not a list" << oendl;
else
_valueList.append(sValue);
}
void ColumnDef::addColumnValue(const char *sValue)
{
if( (_type & 0x00ffffff)!=typeList )
- qDebug("Column %s is not a list", (const char *)_sName);
+ odebug << "Column " << (const char *)_sName << " is not a list" << oendl;
else
_valueList.append(sValue);
}
// --- TableDef ---------------------------------------------------------------
TableDef::TableDef(const char *sName)
{
_sName=sName;
_vColumns.setAutoDelete(TRUE);
}
// --- ~TableDef --------------------------------------------------------------
TableDef::~TableDef()
{
}
// --- addColumnDef -----------------------------------------------------------
void TableDef::addColumnDef(ColumnDef *pDef)
{
_vColumns.append(pDef);
}
diff --git a/noncore/apps/checkbook/transaction.cpp b/noncore/apps/checkbook/transaction.cpp
index 1b08b24..aafb588 100644
--- a/noncore/apps/checkbook/transaction.cpp
+++ b/noncore/apps/checkbook/transaction.cpp
@@ -1,131 +1,135 @@
/*
                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 "transaction.h"
#include "traninfo.h"
#include "cfg.h"
#include "checkbook.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/datebookmonth.h>
+using namespace Opie::Core;
+/* QT */
#include <qbuttongroup.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qmultilineedit.h>
#include <qradiobutton.h>
#include <qwhatsthis.h>
Transaction::Transaction( QWidget *parent, bool bNew, const QString &acctname,
TranInfo *info, Cfg *pCfg )
: QDialog( parent, 0, TRUE, WStyle_ContextHelp )
{
QString tempstr = tr( "Transaction for " );
tempstr.append( acctname );
setCaption( tempstr );
_bNew=bNew;
tran = info;
_pCfg=pCfg;
QVBoxLayout *vb = new QVBoxLayout( this );
QScrollView *sv = new QScrollView( this );
vb->addWidget( sv, 0, 0 );
sv->setResizePolicy( QScrollView::AutoOneFit );
sv->setFrameStyle( QFrame::NoFrame );
QWidget *container = new QWidget( sv->viewport() );
sv->addChild( container );
QGridLayout *layout = new QGridLayout( container );
layout->setSpacing( 2 );
layout->setMargin( 4 );
// Withdrawal/Deposit
QButtonGroup *btngrp = new QButtonGroup( container );
btngrp->setColumnLayout(0, Qt::Vertical );
btngrp->layout()->setSpacing( 0 );
btngrp->layout()->setMargin( 0 );
btngrp->setMaximumWidth( 220 );
QGridLayout *layout2 = new QGridLayout( btngrp->layout() );
layout2->setSpacing( 2 );
layout2->setMargin( 2 );
withBtn = new QRadioButton( tr( "Withdrawal" ), btngrp );
QWhatsThis::add( withBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) );
layout2->addWidget( withBtn, 0, 0 );
connect( withBtn, SIGNAL( clicked() ), this, SLOT( slotWithdrawalClicked() ) );
depBtn = new QRadioButton( tr( "Deposit" ), btngrp );
QWhatsThis::add( depBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) );
layout2->addWidget( depBtn, 0, 1 );
btngrp->setMaximumSize( 320, withBtn->height() );
connect( depBtn, SIGNAL( clicked() ), this, SLOT( slotDepositClicked() ) );
layout->addMultiCellWidget( btngrp, 0, 0, 0, 3 );
// Date
QLabel *label = new QLabel( tr( "Date:" ), container );
QWhatsThis::add( label, tr( "Select date of transaction here." ) );
layout->addWidget( label, 1, 0 );
dateBtn = new QPushButton( TimeString::shortDate( QDate::currentDate() ),
container );
QWhatsThis::add( dateBtn, tr( "Select date of transaction here." ) );
QPopupMenu *m1 = new QPopupMenu( container );
datePicker = new DateBookMonth( m1, 0, TRUE );
m1->insertItem( datePicker );
dateBtn->setPopup( m1 );
connect( datePicker, SIGNAL( dateClicked(int,int,int) ),
this, SLOT( slotDateChanged(int,int,int) ) );
layout->addWidget( dateBtn, 1, 1 );
// Check number
label = new QLabel( tr( "Number:" ), container );
QWhatsThis::add( label, tr( "Enter check number here." ) );
layout->addWidget( label, 1, 2 );
numEdit = new QLineEdit( container );
QWhatsThis::add( numEdit, tr( "Enter check number here." ) );
numEdit->setMaximumWidth( 40 );
layout->addWidget( numEdit, 1, 3 );
// Description
label = new QLabel( tr( "Description:" ), container );
QWhatsThis::add( label, tr( "Enter description of transaction here." ) );
layout->addWidget( label, 2, 0 );
_cbDesc=new QComboBox( true, container );
_cbDesc->insertStringList( _pCfg->getPayees() );
QWhatsThis::add( _cbDesc, tr( "Enter description of transaction here." ) );
layout->addMultiCellWidget( _cbDesc, 2, 2, 1, 3 );
connect( _cbDesc, SIGNAL( activated(const QString&) ), this, SLOT( slotActivated(const QString&) ) );
// Category
label = new QLabel( tr( "Category:" ), container );
QWhatsThis::add( label, tr( "Select transaction category here." ) );
layout->addWidget( label, 3, 0 );
catList = new QComboBox( container );
QWhatsThis::add( catList, tr( "Select transaction category here." ) );
@@ -239,99 +243,99 @@ void Transaction::initFromInfo(TranInfo *info, bool bPopulateOld)
noteEdit->setText( info->notes() );
}
else
{
withBtn->setChecked( TRUE );
}
}
// --- ~Transaction -----------------------------------------------------------
Transaction::~Transaction()
{
}
// --- accept -----------------------------------------------------------------
void Transaction::accept()
{
tran->setDesc( _cbDesc->currentText() );
tran->setDate( datePicker->selectedDate() );
tran->setWithdrawal( withBtn->isChecked() );
tran->setType( typeList->currentText() );
tran->setCategory( catList->currentText() );
bool ok;
tran->setAmount( amtEdit->text().toFloat( &ok ) );
tran->setFee( feeEdit->text().toFloat( &ok ) );
tran->setNumber( numEdit->text() );
tran->setNotes( noteEdit->text() );
QDialog::accept();
}
void Transaction::slotWithdrawalClicked()
{
catList->clear();
CategoryList *pCatList=_pCfg->getCategoryList();
for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) {
if( !pCat->isIncome() )
catList->insertItem( pCat->getName() );
}
catList->setCurrentItem(0);
typeList->clear();
typeList->insertItem( tr( "Debit Charge" ) );
typeList->insertItem( tr( "Written Check" ) );
typeList->insertItem( tr( "Transfer" ) );
typeList->insertItem( tr( "Credit Card" ) );
}
void Transaction::slotDepositClicked()
{
catList->clear();
CategoryList *pCatList=_pCfg->getCategoryList();
for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) {
if( pCat->isIncome() )
catList->insertItem( pCat->getName() );
}
catList->setCurrentItem( 0 );
typeList->clear();
typeList->insertItem( tr( "Written Check" ) );
typeList->insertItem( tr( "Automatic Payment" ) );
typeList->insertItem( tr( "Transfer" ) );
typeList->insertItem( tr( "Cash" ) );
}
// --- slotDateChanged --------------------------------------------------------
void Transaction::slotDateChanged( int y, int m, int d )
{
QDate date;
date.setYMD( y, m, d );
dateBtn->setText( TimeString::shortDate( date ) );
}
// --- slotActivated ----------------------------------------------------------
// Search for the most recent transaction with this description/payee and
// fill amount etc here, as long the new flag is set
void Transaction::slotActivated(const QString &arg )
{
if( !_bNew ) return;
TranInfoList *pTl=((Checkbook *)parentWidget())->getTranList();
if( pTl ) {
TranInfo *pTi=pTl->findMostRecentByDesc( arg );
if( pTi ) {
initFromInfo( pTi, true );
amtEdit->setFocus();
amtEdit->setSelection(0, amtEdit->text().length() );
amtEdit->setCursorPosition(0);
}
}
}
// slotNotNew -----------------------------------------------------------------
void Transaction::slotNotNew()
{
- qDebug("Not new");
+ odebug << "Not new" << oendl;
_bNew=false;
}
diff --git a/noncore/apps/confedit/confedit.pro b/noncore/apps/confedit/confedit.pro
index 5a71680..785c588 100644
--- a/noncore/apps/confedit/confedit.pro
+++ b/noncore/apps/confedit/confedit.pro
@@ -1,21 +1,9 @@
-CONFIG = qt warn_on quick-app
-HEADERS = mainwindow.h listviewconfdir.h listviewitemconffile.h listviewitemconfigentry.h editwidget.h listviewitemconf.h
-SOURCES = main.cpp mainwindow.cpp listviewconfdir.cpp listviewitemconffile.cpp listviewitemconfigentry.cpp editwidget.cpp listviewitemconf.cpp
-INCLUDEPATH += $(OPIEDIR)/include
+CONFIG = qt warn_on quick-app
+HEADERS = mainwindow.h listviewconfdir.h listviewitemconffile.h listviewitemconfigentry.h editwidget.h listviewitemconf.h
+SOURCES = main.cpp mainwindow.cpp listviewconfdir.cpp listviewitemconffile.cpp listviewitemconfigentry.cpp editwidget.cpp listviewitemconf.cpp
+INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-INTERFACES =
-LIBS += -lopiecore2
+LIBS += -lqpe -lopiecore2
TARGET = confedit
-!contains( platform, x11 ) {
-
- include ( $(OPIEDIR)/include.pro )
- LIBS += -lqpe
-}
-
-contains( platform, x11 ) {
- LIBS += -L$(OPIEDIR)/lib -Wl,-rpath,$(OPIEDIR)/lib
-}
-
-
-
+include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/confedit/config.in b/noncore/apps/confedit/config.in
index e377307..d7682dc 100644
--- a/noncore/apps/confedit/config.in
+++ b/noncore/apps/confedit/config.in
@@ -1,4 +1,4 @@
config CONFEDIT
- boolean "opie-confeditor (generic editor for all Opie settings)"
+ boolean "opie-confedit (generic editor for all Opie settings)"
default "y"
depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
diff --git a/noncore/apps/confedit/listviewconfdir.cpp b/noncore/apps/confedit/listviewconfdir.cpp
index 0c2feeb..33bffe1 100644
--- a/noncore/apps/confedit/listviewconfdir.cpp
+++ b/noncore/apps/confedit/listviewconfdir.cpp
@@ -1,61 +1,65 @@
/***************************************************************************
* *
* 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. Vogtp <tille@handhelds.org>
#include "listviewconfdir.h"
+#include "listviewitemconffile.h"
-#include <qmessagebox.h>
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
-#include "listviewitemconffile.h"
+/* QT */
+#include <qmessagebox.h>
ListViewConfDir::ListViewConfDir(QString settingsPath, QWidget *parent, const char *name )
: QListView(parent,name), confDir(settingsPath)
{
setRootIsDecorated( true );
addColumn(tr("Files"));
if (!confDir.isReadable())
QMessageBox::critical(this,tr("Could not open"),tr("The directory ")+settingsPath+tr(" could not be opened."),1,0);
readConfFiles();
connect( this, SIGNAL(expanded(QListViewItem*)), SLOT(expand(QListViewItem*)));
}
ListViewConfDir::~ListViewConfDir()
{
}
void ListViewConfDir::readConfFiles()
{
- confDir.setFilter( QDir::Files | QDir::NoSymLinks );
+ confDir.setFilter( QDir::Files | QDir::NoSymLinks );
confDir.setSorting( QDir::Name );
confDir.setNameFilter("*.conf");
const QFileInfoList *list = confDir.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
ListViewItemConfFile *fileEntry;
while ( (fi=it.current()) )
{
- qDebug( "opening: >%s<", fi->fileName().data() );
+ odebug << "opening: >" << fi->fileName().data() << "<" << oendl;
fileEntry = new ListViewItemConfFile( fi, this );
QListViewItem *dummy = new QListViewItem(fileEntry, "dummy");
++it;
}
}
void ListViewConfDir::expand(QListViewItem *item)
{
((ListViewItemConf*)item)->expand();
}
diff --git a/noncore/apps/confedit/listviewitemconffile.cpp b/noncore/apps/confedit/listviewitemconffile.cpp
index 1ff2c44..2958cf5 100644
--- a/noncore/apps/confedit/listviewitemconffile.cpp
+++ b/noncore/apps/confedit/listviewitemconffile.cpp
@@ -1,159 +1,165 @@
/***************************************************************************
* *
* 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 "listviewitemconffile.h"
+#include "listviewitemconfigentry.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qmessagebox.h>
#include <qtextstream.h>
-#include "listviewitemconfigentry.h"
#define tr QObject::tr
ListViewItemConfFile::ListViewItemConfFile(QFileInfo *file, QListView *parent)
: ListViewItemConf(parent), _valid(false)
{
confFileInfo = file;
-// parseFile();
+ // parseFile();
displayText();
}
ListViewItemConfFile::~ListViewItemConfFile()
{
}
void ListViewItemConfFile::displayText()
{
setText(0,(_changed?"*":"")+confFileInfo->fileName());
}
QString ListViewItemConfFile::fileName()
{
return confFileInfo->fileName();
}
void ListViewItemConfFile::parseFile()
{
- //qDebug("ListViewItemConfFile::parseFile BEGIN");
- QFile confFile(confFileInfo->absFilePath());
+ //odebug << "ListViewItemConfFile::parseFile BEGIN" << oendl;
+ QFile confFile(confFileInfo->absFilePath());
if(! confFile.open(IO_ReadOnly))
QMessageBox::critical(0,tr("Could not open"),tr("The file ")+confFileInfo->fileName()+tr(" could not be opened."),1,0);
QTextStream t( &confFile );
QString s;
QString group;
ListViewItemConfigEntry *groupItem;
ListViewItemConfigEntry *item;
while ( !t.atEnd() )
{
s = t.readLine().stripWhiteSpace();
- //qDebug( "line: >%s<\n", s.latin1() );
+ //odebug << "line: >" << s.latin1() << "<\n" << oendl;
if (s.contains("<?xml"))
{
_valid = false;
break;
}else
if ( s[0] == '[' && s[s.length()-1] == ']' )
{
- // qDebug("got group"+s);
+ // odebug << "got group"+s << oendl;
group = s.mid(1,s.length()-2);
if (!groupItem) groupItem = new ListViewItemConfigEntry(this, tr("no group") );
groupItem = new ListViewItemConfigEntry(this, group );
insertItem( groupItem );
} else
if ( int pos = s.find('=') )
{
-// qDebug("got key"+s);
- if (!groupItem) qDebug("PANIK NO GROUP! >%s<",group.latin1());
+// odebug << "got key"+s << oendl;
+ if (!groupItem) odebug << "PANIK NO GROUP! >" << group.latin1() << "<" << oendl;
item = new ListViewItemConfigEntry(this, group, s );
groupItem->insertItem( item );
}
}
confFile.close();
setExpandable( _valid );
-// qDebug("ListViewItemConfFile::parseFile END");
+// odebug << "ListViewItemConfFile::parseFile END" << oendl;
}
void ListViewItemConfFile::remove()
{
QFile::remove(confFileInfo->absFilePath());
QFile::remove(backupFileName());
delete this;
}
void ListViewItemConfFile::revert()
{
if (!_changed)
{
// read the backup file
QFile conf(confFileInfo->absFilePath());
QFile back(backupFileName());
if (!back.open(IO_ReadOnly)) return;
if (!conf.open(IO_WriteOnly)) return;
#define SIZE 124
char buf[SIZE];
while (int c = back.readBlock(buf, SIZE) ) conf.writeBlock(buf,c);
conf.close();
back.close();
}
parseFile();
expand();
}
void ListViewItemConfFile::save()
{
if (!_changed) return;
QFile conf(confFileInfo->absFilePath());
QFile back(backupFileName());
if (!conf.open(IO_ReadOnly)) return;
if (!back.open(IO_WriteOnly)) return;
char buf[SIZE];
while (int c = conf.readBlock(buf, SIZE) ) back.writeBlock(buf,c);
conf.close();
back.close();
if (!conf.open(IO_WriteOnly)) return;
QTextStream *t = new QTextStream( &conf );
for (QListViewItem *it = firstChild(); it!=0;it = it->nextSibling())
{
((ListViewItemConfigEntry*)it)->save(t);
}
conf.close();
unchanged();
}
bool ListViewItemConfFile::revertable()
{
return _changed || QFile(backupFileName()).exists();
}
QString ListViewItemConfFile::backupFileName()
{
return confFileInfo->absFilePath()+"~";
}
void ListViewItemConfFile::expand()
{
QListViewItem *subItem = firstChild();
QListViewItem *toDel;
while(subItem)
{
toDel = subItem;
subItem = subItem->nextSibling();
delete toDel;
}
parseFile();
}
diff --git a/noncore/apps/confedit/mainwindow.cpp b/noncore/apps/confedit/mainwindow.cpp
index 6ef1043..4b04c97 100644
--- a/noncore/apps/confedit/mainwindow.cpp
+++ b/noncore/apps/confedit/mainwindow.cpp
@@ -1,189 +1,192 @@
/***************************************************************************
* *
* 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 "listviewconfdir.h"
+#include "listviewitemconfigentry.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qlabel.h>
#include <qlayout.h>
#include <qlineedit.h>
-#include "listviewconfdir.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");
+ odebug << "creating settingList" << oendl;
settingList = new ListViewConfDir( QDir::homeDirPath() + "/Settings", this, "settingslist");
settingList->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) );
mainLayout->addWidget( settingList, 0);
- qDebug("creating editor");
+ odebug << "creating editor" << oendl;
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");
+// odebug << "MainWindow::setCurrent" << oendl;
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");
+odebug << "showPopup" << oendl;
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/keyz-cfg/cfgfile.cpp b/noncore/apps/keyz-cfg/cfgfile.cpp
index b0dc968..81d1ee1 100644
--- a/noncore/apps/keyz-cfg/cfgfile.cpp
+++ b/noncore/apps/keyz-cfg/cfgfile.cpp
@@ -1,205 +1,211 @@
-#include <qmessagebox.h>
#include "cfgfile.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
+#include <qmessagebox.h>
+
// CfgEntry implementation
CfgEntry::CfgEntry() {
}
CfgEntry::CfgEntry(const QString& f, const QString& l):
file(f), label(l) {
}
const QString& CfgEntry::getFile() const {
return file;
}
void CfgEntry::setFile(const QString& f) {
file = f;
}
const QString& CfgEntry::getLabel() const {
return label;
}
void CfgEntry::setLabel(const QString& f) {
label = f;
}
// CfgFile implementation
CfgFile::CfgFile():ardelay(400), arperiod(80) {
}
CfgFile::~CfgFile() {
}
QList<CfgEntry>& CfgFile::getEntries() {
return entries;
}
bool CfgFile::replaceEntry(const QString& file, const QString& label, int index) {
deleteEntry(file);
CfgEntry* entry = new CfgEntry(file, label);
if (index >= 0) {
entries.insert(index, entry);
} else {
entries.append(entry);
}
return true;
}
bool CfgFile::deleteEntry(const QString& file) {
for(int i = 0; i < (int) entries.count(); i++) {
CfgEntry* entry = entries.at(i);
if (entry->getFile() == file) {
entries.remove(i);
return true;
}
}
return false;
}
int CfgFile::getAutorepeatDelay() const {
return ardelay;
}
void CfgFile::setAutorepeatDelay(int n) {
ardelay = n;
}
int CfgFile::getAutorepeatPeriod() const {
return arperiod;
}
void CfgFile::setAutorepeatPeriod(int n) {
arperiod = n;
}
// CfgParser implementation
CfgParser::CfgParser() {
}
bool CfgParser::load(QString file, CfgFile& cfg) {
QFile f(file);
QXmlInputSource is(f);
QXmlSimpleReader reader;
CfgHandler p(*this);
reader.setErrorHandler(this);
reader.setContentHandler(&p);
err = "";
ardelay = -1;
arperiod = -1;
reader.parse(is);
if (!err.isEmpty()) {
- qDebug(err);
+ odebug << err << oendl;
return false;
}
QMap<QString, QString>::Iterator fit, lit;
for(uint i = 0; i < includeList.count(); i++) {
QString file = *includeList.at(i);
fit = includes.find(file);
QString prefix = fit.data();
QString label = "";
- qDebug("include: file=" + fit.key() + ", prefix=" + fit.data());
+ odebug << "include: file=" + fit.key() + ", prefix=" + fit.data() << oendl;
lit = labels.find(prefix+":*");
if (lit != labels.end()) {
label = lit.data();
}
cfg.replaceEntry(file, label);
}
if (ardelay != -1) {
cfg.setAutorepeatDelay(ardelay);
}
if (arperiod != -1) {
cfg.setAutorepeatPeriod(arperiod);
}
return true;
}
bool CfgParser::save(QString file, CfgFile& cfg) {
FILE* f = fopen((const char*) file.local8Bit(), "w");
fprintf(f, "<keymap autorepeat-delay=\"%d\" autorepeat-period=\"%d\" "
"author=\"keyzcfg\">\n", cfg.getAutorepeatDelay(),
cfg.getAutorepeatPeriod());
QList<CfgEntry>& entries = cfg.getEntries();
int n;
for(n=0; n < (int) entries.count(); n++) {
CfgEntry* entry = entries.at(n);
QString l = entry->getLabel();
if (!l.isEmpty()) {
fprintf(f, "\t<label name=\"%s\" state=\"km%d:*\"/>\n",
(const char*) l.utf8(), n);
}
}
for(n=0; n < (int) entries.count(); n++) {
CfgEntry* entry = entries.at(n);
fprintf(f, "\t<include file=\"%s\" prefix=\"km%d\"/>\n",
(const char*) entry->getFile().utf8(), n);
}
int k = n-1;
char* states[] = { "LShift", "LShift-Caps", "LShift-Num",
"LShift-Num-Caps", 0};
for(n=0; n < (int) entries.count(); n++) {
QString nstate = "km" + QString::number(n+1);
if (n == k) {
nstate = "km" + QString::number(0);
}
for(int i = 0; states[i] != 0; i++) {
fprintf(f, "\t<state name=\"km%d:%s\">\n",
n, states[i]);
fprintf(f, "\t\t<map keycode=\"Middle\" pressed=\"true\">\n");
fprintf(f, "\t\t\t<next-state name=\"%s:%s\"/>\n",
(const char*) nstate.utf8(), states[i]);
fprintf(f, "\t\t</map>\n\t</state>\n\n");
}
}
fprintf(f, "\t<state name=\"km0:Normal\" default=\"true\"/>\n");
fprintf(f, "</keymap>");
fclose(f);
return true;
}
CfgParser::~CfgParser() {
}
int CfgParser::getAutorepeatDelay() const {
return ardelay;
}
void CfgParser::setAutorepeatDelay(int n) {
ardelay = n;
}
int CfgParser::getAutorepeatPeriod() const {
return arperiod;
}
void CfgParser::setAutorepeatPeriod(int n) {
arperiod = n;
}
void CfgParser::addLabel(const QString& name, const QString& state) {
labels.insert(state, name);
labelList.append(&labels.find(state).data());
}
void CfgParser::addFile(const QString& file, const QString& prefix) {
diff --git a/noncore/apps/keyz-cfg/config.in b/noncore/apps/keyz-cfg/config.in
index 29a10f5..8e1be2d 100644
--- a/noncore/apps/keyz-cfg/config.in
+++ b/noncore/apps/keyz-cfg/config.in
@@ -1,4 +1,4 @@
config KEYZCFG
boolean "keyz-cfg (configuration tool for keyz applet)"
default "n"
- depends ( LIBQPE || LIBQPE-X11 )
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
diff --git a/noncore/apps/keyz-cfg/keyz-cfg.pro b/noncore/apps/keyz-cfg/keyz-cfg.pro
index 44bbb5f..7ac604b 100644
--- a/noncore/apps/keyz-cfg/keyz-cfg.pro
+++ b/noncore/apps/keyz-cfg/keyz-cfg.pro
@@ -1,24 +1,24 @@
TEMPLATE = app
DESTDIR = $(OPIEDIR)/bin
CONFIG = qt warn_on
HEADERS = zkb.h \
- zkbcfg.h \
- zkbnames.h \
- zkbxml.h \
- cfgdlg.h \
- cfgfile.h
+ zkbcfg.h \
+ zkbnames.h \
+ zkbxml.h \
+ cfgdlg.h \
+ cfgfile.h
SOURCES = main.cpp \
cfgdlg.cpp \
cfgfile.cpp \
zkb.cpp \
zkbcfg.cpp \
- zkbnames.cpp \
- zkbxml.cpp
+ zkbnames.cpp \
+ zkbxml.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe
+LIBS += -lqpe -lopiecore2
TARGET = keyz-cfg
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/keyz-cfg/zkb.cpp b/noncore/apps/keyz-cfg/zkb.cpp
index f315d4b..8382615 100644
--- a/noncore/apps/keyz-cfg/zkb.cpp
+++ b/noncore/apps/keyz-cfg/zkb.cpp
@@ -271,245 +271,245 @@ bool Keymap::filter(int unicode, int keycode, int modifiers,
Action* action = currentState->get(keycode, isPress, true);
if (action==0 || !action->isDefined()) {
return true;
}
if (action->hasEvent()) {
qDebug("filter:<<< unicode=%x, keycode=%x, modifiers=%x, "
"ispressed=%x\n", action->getUnicode(),
action->getKeycode(), action->getModifiers(),
action->isPressed());
QWSServer::sendKeyEvent(action->getUnicode(),
action->getKeycode(), action->getModifiers(),
action->isPressed(), false);
}
if (action->isAutorepeat()) {
autoRepeatAction = action;
repeater.start(repeatDelay, TRUE);
} else {
autoRepeatAction = 0;
}
State* nstate = action->getState();
if (nstate != 0) {
setCurrentState(nstate);
QString lbl = getCurrentLabel();
if (!lbl.isEmpty()) {
emit stateChanged(lbl);
}
}
return true;
}
void Keymap::enable() {
enabled = true;
}
void Keymap::disable() {
enabled = false;
}
QStringList Keymap::listStates() {
QStringList ret;
QMap<QString, State*>::Iterator it;
for(it = states.begin(); it != states.end(); ++it) {
ret.append(it.key());
}
return ret;
}
State* Keymap::getStateByName(const QString& name) {
QMap<QString, State*>::Iterator it = states.find(name);
if (it == states.end()) {
return 0;
}
return it.data();
}
QStringList Keymap::listLabels() {
QStringList ret;
for(uint i = 0; i < labelList.count(); i++) {
ret.append(*labelList.at(i));
}
return ret;
}
State* Keymap::getStateByLabel(const QString& label) {
QMap<QString, QString>::Iterator lit = labels.find(label);
State* state = 0;
if (lit == labels.end()) {
return 0;
}
QString name = lit.data();
int n = name.find(":*");
if (n>=0 && n==(int)(name.length()-2)) {
name=name.left(name.length() - 1);
n = currentStateName.findRev(":");
if (n >= 0) {
name += currentStateName.mid(n+1);
}
}
-// qDebug("look for: %s\n", (const char*) name.utf8());
+// odebug << "look for: " << (const char*) name.utf8() << "\n" << oendl;
QMap<QString, State*>::Iterator sit = states.find(name);
if (sit != states.end()) {
state = sit.data();
}
return state;
}
bool Keymap::addState(const QString& name, State* state) {
if (states.find(name) != states.end()) {
return false;
}
states.insert(name, state);
lsmapInSync = false;
if (currentState == 0) {
setCurrentState(state);
}
return true;
}
State* Keymap::getCurrentState() const {
return currentState;
}
QString Keymap::getCurrentLabel() {
return currentLabel;
}
bool Keymap::setCurrentState(State* state) {
QMap<QString, State*>::Iterator it;
for(it = states.begin(); it != states.end(); ++it) {
State* s = it.data();
if (s == state) {
currentState = s;
currentStateName = it.key();
qDebug("state changed: %s\n", (const char*)
currentStateName.utf8());
if (!lsmapInSync) {
generateLabelStateMaps();
}
QMap<State*, QString>::Iterator tit;
tit = stateLabelMap.find(state);
if (tit != stateLabelMap.end()) {
currentLabel = tit.data();
} else {
-// qDebug("no label for: " + currentStateName + "\n");
+// odebug << "no label for: " + currentStateName + "\n" << oendl;
currentLabel = "";
}
return true;
}
}
return false;
}
bool Keymap::removeState(const QString& name, bool force) {
QMap<QString, State*>::Iterator it = states.find(name);
if (it == states.end()) {
return false;
}
State* state = it.data();
QList<Action> acts = findStateUsage(state);
if (!acts.isEmpty()) {
if (!force) {
return false;
} else {
for(Action* a = acts.first(); a != 0; a = acts.next()) {
a->setState(0);
}
}
}
if (state == currentState) {
if (states.begin() != states.end()) {
setCurrentState(states.begin().data());
}
}
states.remove(it);
delete state;
lsmapInSync = false;
return true;
}
void Keymap::autoRepeat() {
if (autoRepeatAction != 0) {
qDebug("filter:<<< unicode=%x, keycode=%x, modifiers=%x, "
"ispressed=%x\n", autoRepeatAction->getUnicode(),
autoRepeatAction->getKeycode(),
autoRepeatAction->getModifiers(),
autoRepeatAction->isPressed());
QWSServer::sendKeyEvent(autoRepeatAction->getUnicode(),
autoRepeatAction->getKeycode(),
autoRepeatAction->getModifiers(),
autoRepeatAction->isPressed(), true);
}
repeater.start(repeatPeriod, TRUE);
}
bool Keymap::addLabel(const QString& label, const QString& state, int index) {
if (labels.find(label) != labels.end()) {
return false;
}
labels.insert(label, state);
const QString& l = labels.find(label).key();
if (index == -1) {
labelList.append(l);
} else {
labelList.insert(labelList.at(index), l);
}
lsmapInSync = false;
return true;
}
bool Keymap::removeLabel(const QString& label) {
if (labels.find(label) == labels.end()) {
return false;
}
labels.remove(label);
labelList.remove(label);
lsmapInSync = false;
if (label == currentLabel) {
currentLabel = "";
}
return true;
}
diff --git a/noncore/apps/keyz-cfg/zkbcfg.cpp b/noncore/apps/keyz-cfg/zkbcfg.cpp
index 0992b9a..f1d53ba 100644
--- a/noncore/apps/keyz-cfg/zkbcfg.cpp
+++ b/noncore/apps/keyz-cfg/zkbcfg.cpp
@@ -1,221 +1,224 @@
-#include <qfileinfo.h>
-
#include "zkbcfg.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
+#include <qfileinfo.h>
// Implementation of XkbConfig class
ZkbConfig::ZkbConfig(const QString& dir):path(dir) {
}
ZkbConfig::~ZkbConfig() {
}
bool ZkbConfig::load(const QString& file, Keymap& keymap, const QString& prefix) {
bool ret;
QFile f(path+"/"+file);
QFileInfo fi(f);
- qDebug("start loading file=%s\n", (const char*) file.utf8());
+ odebug << "start loading file=" << (const char*) file.utf8() << "\n" << oendl;
if (includedFiles.find(fi.absFilePath()) != includedFiles.end()) {
return false;
}
includedFiles.insert(fi.absFilePath(), 1);
QXmlInputSource is(f);
QXmlSimpleReader reader;
ZkbHandler h(*this, keymap, prefix);
reader.setContentHandler(&h);
reader.setErrorHandler(this);
ret = reader.parse(is);
includedFiles.remove(fi.absFilePath());
- qDebug("end loading file=%s : status=%s\n", (const char*) file.utf8(),
- (const char*) err.utf8());
+ odebug << "end loading file=" << file.utf8() << ": status=" << err.utf8() << oendl;
return ret;
}
bool ZkbConfig::warning(const QXmlParseException& e) {
QString tmp;
tmp.sprintf("%d: warning: %s\n", e.lineNumber(),
(const char*) e.message().utf8());
err += tmp;
return true;
}
bool ZkbConfig::error(const QXmlParseException& e) {
QString tmp;
tmp.sprintf("%d: error: %s\n", e.lineNumber(),
(const char*) e.message().utf8());
err += tmp;
return true;
}
bool ZkbConfig::fatalError(const QXmlParseException& e) {
QString tmp;
tmp.sprintf("%d: fatal error: %s\n", e.lineNumber(),
(const char*) e.message().utf8());
err += tmp;
return false;
}
QString ZkbConfig::errorString() {
return err;
}
// Implementation of ZkbHandler
ZkbHandler::ZkbHandler(ZkbConfig& z, Keymap& k, const QString& p):zkc(z), keymap(k),
prefix(p), ardelay(-1), arperiod(-1), currentState(0), currentAction(0) {
}
ZkbHandler::~ZkbHandler() {
}
bool ZkbHandler::startKeymapElement(int ard, int arp, const QString&) {
ardelay = ard;
arperiod = arp;
return true;
}
bool ZkbHandler::startIncludeElement(const QString& file,
const QString& pref) {
QString p = prefix;
if (!pref.isNull()) {
p += pref + ":";
}
bool ret = zkc.load(file, keymap, p);
if (!ret) {
setError("Error including file: " + file);
}
return ret;
}
bool ZkbHandler::startLabelElement(const QString& label,
const QString& state) {
if (!keymap.addLabel(label, prefix + state)) {
err = "label " + label + " already defined";
return false;
}
return true;
}
bool ZkbHandler::startStateElement(const QString& name,
const QString& parentName, bool dflt) {
currentStateName = prefix + name;
currentState = keymap.getStateByName(currentStateName);
-// qDebug("state name=%s\n", (const char*) currentStateName.utf8());
+// odebug << "state name=" << (const char*) currentStateName.utf8() << "\n" << oendl;
State* parent = 0;
if (!parentName.isEmpty()) {
QString pn = prefix + parentName;
parent = keymap.getStateByName(pn);
if (parent == 0) {
err = currentStateName +
": undefined parent state: " + pn;
return false;
}
}
if (currentState == 0) {
currentState = new State(parent);
keymap.addState(currentStateName, currentState);
} else {
if (parent!=0) {
currentState->setParent(parent);
}
}
if (dflt) {
keymap.setCurrentState(currentState);
}
return true;
}
bool ZkbHandler::startMapElement(int keycode, bool pressed) {
currentAction = currentState->get(keycode, pressed);
if (currentAction == 0) {
setError("keycode " + QString::number(keycode) + " not supported");
return false;
}
currentAction->setEvent(false);
currentAction->setState(0);
return true;
}
bool ZkbHandler::startEventElement(int keycode, int unicode, int modifiers,
bool pressed, bool autorepeat) {
currentAction->setEvent(true);
currentAction->setKeycode(keycode);
currentAction->setUnicode(unicode);
currentAction->setModifiers(modifiers);
currentAction->setPressed(pressed);
currentAction->setAutorepeat(autorepeat);
return true;
}
bool ZkbHandler::startNextStateElement(const QString& state) {
State* s = keymap.getStateByName(prefix + state);
if (s == 0) {
setError("undefine state: " + prefix + state);
return false;
}
currentAction->setState(s);
return true;
}
bool ZkbHandler::endKeymapElement() {
if (ardelay > 0) {
keymap.setAutorepeatDelay(ardelay);
}
if (arperiod > 0) {
keymap.setAutorepeatPeriod(arperiod);
}
return true;
}
bool ZkbHandler::endIncludeElement() {
return true;
}
bool ZkbHandler::endLabelElement() {
return true;
}
bool ZkbHandler::endStateElement() {
currentState = 0;
return true;
}
bool ZkbHandler::endMapElement() {
currentAction = 0;
return true;
}
diff --git a/noncore/apps/opie-bartender/bartender.cpp b/noncore/apps/opie-bartender/bartender.cpp
index e6cb515..59fc242 100644
--- a/noncore/apps/opie-bartender/bartender.cpp
+++ b/noncore/apps/opie-bartender/bartender.cpp
@@ -1,432 +1,435 @@
/****************************************************************************
**
** 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 "showdrinks.h"
#include "inputDialog.h"
#include "searchresults.h"
#include "bac.h"
-#include <qtoolbar.h>
-#include <qmenubar.h>
-//#include <opie2/colorpopupmenu.h>
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
+using namespace Opie::Core;
+/* QT */
#include <qlineedit.h>
#include <qdir.h>
#include <qpushbutton.h>
#include <qlistbox.h>
#include <qmultilineedit.h>
#include <qmessagebox.h>
#include <qtextstream.h>
#include <qaction.h>
#include <qheader.h>
#include <qlistview.h>
#include <qlayout.h>
+#include <qtoolbar.h>
+#include <qmenubar.h>
+/* STD */
#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 QToolBar( this, "ToolBar1" );
ToolBar1->setFixedHeight(22);
layout->addMultiCellWidget( ToolBar1, 0, 0, 0, 4 );
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));
+// odebug << s.right(s.length()-2) << oendl;
item= new QListViewItem( DrinkView, 0 );
item->setText( 0, s.right(s.length()-2));
i++;
}
}
- qDebug("there are currently %d of drinks", i);
+ odebug << "there are currently " << i << " of drinks" << oendl;
}
void Bartender::fileNew() {
New_Drink *newDrinks;
newDrinks = new New_Drink(this,"New Drink....", TRUE);
QString newName, newIng;
QPEApplication::execDialog( newDrinks );
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);
+ odebug << "writing "+newDrink << oendl;
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);
+// odebug << s2 << oendl;
showDrinks->MultiLineEdit1->append(s2);
}
if( dbFile.atEnd() ) break;
}
}
}
QPEApplication::execDialog( showDrinks );
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));
+// odebug << it.current()->text(0) << oendl;
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);
+// odebug << "last drink name "+lastDrinkName << oendl;
}
else if( s.find( searchForDrinkName ,0, FALSE) != -1 && lastDrinkName != tempName ) {
-// qDebug("appending "+lastDrinkName);
+// odebug << "appending "+lastDrinkName << oendl;
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->ListBox1->insertStringList( searchList,-1);
QPEApplication::execDialog( searchDlg );
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));
+// odebug << it2.current()->text(0) << oendl;
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;
QPEApplication::showDialog( newDrinks );
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);
+// odebug << s2 << oendl;
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);
+ odebug << "writing "+newDrink << oendl;
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);
QPEApplication::execDialog( bacDlg );
delete bacDlg;
}
void Bartender::openCurrentDrink() {
if(DrinkView->currentItem() == NULL) return;
showDrink(DrinkView->currentItem());
}
void Bartender::fileMenuActivated( int item) {
- qDebug("Item %d", item);
+ odebug << "Item " << item << "" << oendl;
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);
+ odebug << "Item " << item << "" << oendl;
/*
edit -8
*/
switch(item) {
case -8:
doEdit() ;
break;
}
}
diff --git a/noncore/apps/opie-bartender/bartender.pro b/noncore/apps/opie-bartender/bartender.pro
index 4ad3c31..41fc0e5 100644
--- a/noncore/apps/opie-bartender/bartender.pro
+++ b/noncore/apps/opie-bartender/bartender.pro
@@ -1,12 +1,11 @@
TEMPLATE = app
-#CONFIG = qt warn_on
CONFIG = qt warn_on
HEADERS = bartender.h newdrinks.h showdrinks.h inputDialog.h searchresults.h bac.h
SOURCES = main.cpp bartender.cpp newdrinks.cpp showdrinks.cpp inputDialog.cpp searchresults.cpp bac.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe
-DESTDIR = $(OPIEDIR)/bin
-TARGET = bartender
+LIBS += -lqpe -lopiecore2
+DESTDIR = $(OPIEDIR)/bin
+TARGET = bartender
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/opie-bartender/config.in b/noncore/apps/opie-bartender/config.in
index c6ca2e6..c39a7d6 100644
--- a/noncore/apps/opie-bartender/config.in
+++ b/noncore/apps/opie-bartender/config.in
@@ -1,4 +1,5 @@
config BARTENDER
boolean "bartender - bar receipe and blood alcohol estimator"
default "n"
- depends ( LIBQPE || LIBQPE-X11 )
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
+
diff --git a/noncore/apps/opie-console/MyPty.cpp b/noncore/apps/opie-console/MyPty.cpp
index a37f980..6d57703 100644
--- a/noncore/apps/opie-console/MyPty.cpp
+++ b/noncore/apps/opie-console/MyPty.cpp
@@ -1,196 +1,200 @@
/* -------------------------------------------------------------------------- */
/* */
/* [MyPty.C] Pseudo Terminal Device */
/* */
/* -------------------------------------------------------------------------- */
/* */
/* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */
/* */
/* This file is part of Konsole - an X terminal for KDE */
/* -------------------------------------------------------------------------- */
/* */
/* Ported Konsole to Qt/Embedded */
/* */
/* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */
/* */
/* -------------------------------------------------------------------------- */
/* If you're compiling konsole on non-Linux platforms and find
problems that you can track down to this file, please have
a look into ../README.ports, too.
*/
/*! \file
*/
/*! \class TEPty
\brief Ptys provide a pseudo terminal connection to a program.
Although closely related to pipes, these pseudo terminal connections have
some ability, that makes it nessesary to uses them. Most importent, they
know about changing screen sizes and UNIX job control.
Within the terminal emulation framework, this class represents the
host side of the terminal together with the connecting serial line.
One can create many instances of this class within a program.
As a side effect of using this class, a signal(2) handler is
installed on SIGCHLD.
\par FIXME
[NOTE: much of the technical stuff below will be replaced by forkpty.]
publish the SIGCHLD signal if not related to an instance.
clearify TEPty::done vs. TEPty::~TEPty semantics.
check if pty is restartable via run after done.
\par Pseudo terminals
Pseudo terminals are a unique feature of UNIX, and always come in form of
pairs of devices (/dev/ptyXX and /dev/ttyXX), which are connected to each
other by the operating system. One may think of them as two serial devices
linked by a null-modem cable. Being based on devices the number of
simultanous instances of this class is (globally) limited by the number of
those device pairs, which is 256.
Another technic are UNIX 98 PTY's. These are supported also, and prefered
over the (obsolete) predecessor.
There's a sinister ioctl(2), signal(2) and job control stuff
nessesary to make everything work as it should.
*/
+#include "procctl.h"
+#include "MyPty.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qsocketnotifier.h>
#include <qfile.h>
+/* STD */
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#ifdef HAVE_OPENPTY
#include <pty.h>
#endif
-#include "procctl.h"
-#include "MyPty.h"
-
-
#undef VERBOSE_DEBUG
/* -------------------------------------------------------------------------- */
/*!
Informs the client program about the
actual size of the window.
*/
void MyPty::setSize(int lines, int columns)
{
- qWarning("setting size");
+ owarn << "setting size" << oendl;
struct winsize wsize;
wsize.ws_row = (unsigned short)lines;
wsize.ws_col = (unsigned short)columns;
if(m_fd < 0) return;
ioctl(m_fd,TIOCSWINSZ,(char *)&wsize);
}
void MyPty::donePty()
{
// This is code from the Qt DumbTerminal example
::close(m_fd);
if (m_cpid) {
kill(m_cpid, SIGHUP);
//waitpid(m_cpid, &status, 0);
delete m_sn_e;
delete m_sn_r;
m_sn_e = 0l;
m_sn_r = 0l;
}
m_cpid = 0;
m_fd = -1;
// emit done(status);
}
const char* MyPty::deviceName()
{
return m_ttynam;
}
void MyPty::error()
{
// This is code from the Qt DumbTerminal example
donePty();
}
void MyPty::start() {
QStrList lis;
int r =run(m_cmd.latin1(), lis, 0, 0);
r = r;
}
/*!
start the client program.
*/
int MyPty::run(const char* cmd, QStrList &, const char*, int)
{
// This is code from the Qt DumbTerminal example
m_cpid = fork();
if ( !m_cpid ) {
// child - exec shell on tty
for (int sig = 1; sig < NSIG; sig++) signal(sig,SIG_DFL);
int ttyfd = ::open(m_ttynam, O_RDWR);
dup2(ttyfd, STDIN_FILENO);
dup2(ttyfd, STDOUT_FILENO);
dup2(ttyfd, STDERR_FILENO);
// should be done with tty, so close it
::close(ttyfd);
static struct termios ttmode;
if ( setsid() < 0 )
perror( "failed to set process group" );
#if defined (TIOCSCTTY)
// grabbed from APUE by Stevens
ioctl(STDIN_FILENO, TIOCSCTTY, 0);
#endif
tcgetattr( STDIN_FILENO, &ttmode );
ttmode.c_cc[VINTR] = 3;
ttmode.c_cc[VERASE] = 8;
tcsetattr( STDIN_FILENO, TCSANOW, &ttmode );
setenv("TERM",m_term,1);
setenv("COLORTERM","0",1);
EnvironmentMap::Iterator it;
for (it = m_env.begin(); it != m_env.end(); it++) {
setenv(it.key().latin1(), it.data().latin1(), 1);
}
if (getuid() == 0) {
char msg[] = "WARNING: You are running this shell as root!\n";
write(ttyfd, msg, sizeof(msg));
}
execl(cmd, cmd, 0);
donePty();
exit(-1);
}
// parent - continue as a widget
delete m_sn_r;
m_sn_r = new QSocketNotifier(m_fd,QSocketNotifier::Read,this);
delete m_sn_e;
m_sn_e = new QSocketNotifier(m_fd,QSocketNotifier::Exception,this);
connect(m_sn_r,SIGNAL(activated(int)),this,SLOT(readPty()));
diff --git a/noncore/apps/opie-console/TEWidget.cpp b/noncore/apps/opie-console/TEWidget.cpp
index e535296..d168a5e 100644
--- a/noncore/apps/opie-console/TEWidget.cpp
+++ b/noncore/apps/opie-console/TEWidget.cpp
@@ -936,236 +936,236 @@ void TEWidget::setMouseMarks(bool on)
/* ------------------------------------------------------------------------- */
/* */
/* Clipboard */
/* */
/* ------------------------------------------------------------------------- */
#undef KeyPress
void TEWidget::emitSelection()
// Paste Clipboard by simulating keypress events
{
#ifndef QT_NO_CLIPBOARD
QString text = QApplication::clipboard()->text();
if ( ! text.isNull() )
{
text.replace(QRegExp("\n"), "\r");
QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text);
emit keyPressedSignal(&e); // expose as a big fat keypress event
emit clearSelectionSignal();
}
#endif
}
void TEWidget::emitText(QString text)
{
QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text);
emit keyPressedSignal(&e); // expose as a big fat keypress event
}
void TEWidget::pasteClipboard( )
{
emitSelection();
}
void TEWidget::setSelection(const QString& t)
{
#ifndef QT_NO_CLIPBOARD
// Disconnect signal while WE set the clipboard
QObject *cb = QApplication::clipboard();
QObject::disconnect( cb, SIGNAL(dataChanged()),
this, SLOT(onClearSelection()) );
QApplication::clipboard()->setText(t);
QObject::connect( cb, SIGNAL(dataChanged()),
this, SLOT(onClearSelection()) );
#endif
}
void TEWidget::onClearSelection()
{
emit clearSelectionSignal();
}
/* ------------------------------------------------------------------------- */
/* */
/* Keyboard */
/* */
/* ------------------------------------------------------------------------- */
//FIXME: an `eventFilter' has been installed instead of a `keyPressEvent'
// due to a bug in `QT' or the ignorance of the author to prevent
// repaint events being emitted to the screen whenever one leaves
// or reenters the screen to/from another application.
//
// Troll says one needs to change focusInEvent() and focusOutEvent(),
// which would also let you have an in-focus cursor and an out-focus
// cursor like xterm does.
// for the auto-hide cursor feature, I added empty focusInEvent() and
// focusOutEvent() so that update() isn't called.
// For auto-hide, we need to get keypress-events, but we only get them when
// we have focus.
void TEWidget::doScroll(int lines)
{
scrollbar->setValue(scrollbar->value()+lines);
}
bool TEWidget::eventFilter( QObject *obj, QEvent *e )
{
if ( (e->type() == QEvent::Accel ||
e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) {
static_cast<QKeyEvent *>( e )->ignore();
return true;
}
if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ )
return FALSE; // not us
if ( e->type() == QEvent::Wheel) {
QApplication::sendEvent(scrollbar, e);
}
#ifdef FAKE_CTRL_AND_ALT
static bool control = FALSE;
static bool alt = FALSE;
-// qDebug(" Has a keyboard with no CTRL and ALT keys, but we fake it:");
+// odebug << " Has a keyboard with no CTRL and ALT keys, but we fake it:" << oendl;
bool dele=FALSE;
if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
QKeyEvent* ke = (QKeyEvent*)e;
bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat();
switch (ke->key()) {
case Key_F9: // let this be "Control"
control = keydown;
e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state());
dele=TRUE;
break;
case Key_F13: // let this be "Alt"
alt = keydown;
e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state());
dele=TRUE;
break;
default:
if ( control ) {
int a = toupper(ke->ascii())-64;
if ( a >= 0 && a < ' ' ) {
e = new QKeyEvent(e->type(), ke->key(),
a, ke->state()|ControlButton, QChar(a,0));
dele=TRUE;
}
}
if ( alt ) {
e = new QKeyEvent(e->type(), ke->key(),
ke->ascii(), ke->state()|AltButton, ke->text());
dele=TRUE;
}
}
}
#endif
if ( e->type() == QEvent::KeyPress ) {
QKeyEvent* ke = (QKeyEvent*)e;
actSel=0; // Key stroke implies a screen update, so TEWidget won't
// know where the current selection is.
-// qDebug("key pressed is 0x%x",ke->key());
+// odebug << "key pressed is 0x" << ke->key() << "" << oendl;
if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker
-// qDebug("key pressed 2 is 0x%x",ke->key());
+// odebug << "key pressed 2 is 0x" << ke->key() << "" << oendl;
emitText("\\"); // expose
} else
emit keyPressedSignal(ke); // expose
ke->accept();
#ifdef FAKE_CTRL_AND_ALT
if ( dele ) delete e;
#endif
return true; // stop the event
}
if ( e->type() == QEvent::Enter ) {
QObject::disconnect( (QObject*)cb, SIGNAL(dataChanged()),
this, SLOT(onClearSelection()) );
}
if ( e->type() == QEvent::Leave ) {
QObject::connect( (QObject*)cb, SIGNAL(dataChanged()),
this, SLOT(onClearSelection()) );
}
return QFrame::eventFilter( obj, e );
}
/* ------------------------------------------------------------------------- */
/* */
/* Frame */
/* */
/* ------------------------------------------------------------------------- */
void TEWidget::frameChanged()
{
propagateSize();
update();
}
/* ------------------------------------------------------------------------- */
/* */
/* Sound */
/* */
/* ------------------------------------------------------------------------- */
void TEWidget::Bell()
{
QApplication::beep();
}
/* ------------------------------------------------------------------------- */
/* */
/* Auxiluary */
/* */
/* ------------------------------------------------------------------------- */
void TEWidget::clearImage()
// initialize the image
// for internal use only
{
for (int y = 0; y < lines; y++)
for (int x = 0; x < columns; x++)
{
image[loc(x,y)].c = 0xff; //' ';
image[loc(x,y)].f = 0xff; //DEFAULT_FORE_COLOR;
image[loc(x,y)].b = 0xff; //DEFAULT_BACK_COLOR;
image[loc(x,y)].r = 0xff; //DEFAULT_RENDITION;
}
}
// Create Image ///////////////////////////////////////////////////////
void TEWidget::calcGeometry()
{
//FIXME: set rimX == rimY == 0 when running in full screen mode.
int showhscrollbar = 1;
int hwidth = 0;
int dcolumns;
if(vcolumns == 0) showhscrollbar = 0;
if(showhscrollbar == 1) hwidth = QApplication::style().scrollBarExtent().width();
scrollbar->resize(QApplication::style().scrollBarExtent().width(),
contentsRect().height() - hwidth);
if(!showhscrollbar) cornerButton()->move(0, 0);
else cornerButton()->move(contentsRect().width() - hwidth, contentsRect().height() - hwidth);
switch(scrollLoc)
{
case SCRNONE :
columns = ( contentsRect().width() - 2 * rimX ) / font_w;
dcolumns = columns;
if(vcolumns) columns = vcolumns;
blX = (contentsRect().width() - (columns*font_w) ) / 2;
if(showhscrollbar)
blX = -hposition * font_w;
brX = blX;
scrollbar->hide();
break;
case SCRLEFT :
diff --git a/noncore/apps/opie-console/TEmulation.cpp b/noncore/apps/opie-console/TEmulation.cpp
index d0169d7..6ff73af 100644
--- a/noncore/apps/opie-console/TEmulation.cpp
+++ b/noncore/apps/opie-console/TEmulation.cpp
@@ -1,303 +1,309 @@
/* -------------------------------------------------------------------------- */
/* */
/* [TEmulation.cpp] Terminal Emulation Decoder */
/* */
/* -------------------------------------------------------------------------- */
/* */
/* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */
/* */
/* This file is part of Konsole - an X terminal for KDE */
/* */
/* -------------------------------------------------------------------------- */
/* */
/* Ported Konsole to Qt/Embedded */
/* */
/* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */
/* */
/* -------------------------------------------------------------------------- */
/*! \class TEmulation
\brief Mediator between TEWidget and TEScreen.
This class is responsible to scan the escapes sequences of the terminal
emulation and to map it to their corresponding semantic complements.
Thus this module knows mainly about decoding escapes sequences and
is a stateless device w.r.t. the semantics.
It is also responsible to refresh the TEWidget by certain rules.
\sa TEWidget \sa TEScreen
\par A note on refreshing
Although the modifications to the current screen image could immediately
be propagated via `TEWidget' to the graphical surface, we have chosen
another way here.
The reason for doing so is twofold.
First, experiments show that directly displaying the operation results
in slowing down the overall performance of emulations. Displaying
individual characters using X11 creates a lot of overhead.
Second, by using the following refreshing method, the screen operations
can be completely separated from the displaying. This greatly simplifies
the programmer's task of coding and maintaining the screen operations,
since one need not worry about differential modifications on the
display affecting the operation of concern.
We use a refreshing algorithm here that has been adoped from rxvt/kvt.
By this, refreshing is driven by a timer, which is (re)started whenever
a new bunch of data to be interpreted by the emulation arives at `onRcvBlock'.
As soon as no more data arrive for `BULK_TIMEOUT' milliseconds, we trigger
refresh. This rule suits both bulk display operation as done by curses as
well as individual characters typed.
(BULK_TIMEOUT < 1000 / max characters received from keyboard per second).
Additionally, we trigger refreshing by newlines comming in to make visual
snapshots of lists as produced by `cat', `ls' and likely programs, thereby
producing the illusion of a permanent and immediate display operation.
As a sort of catch-all needed for cases where none of the above
conditions catch, the screen refresh is also triggered by a count
of incoming bulks (`bulk_incnt').
*/
/* FIXME
- evtl. the bulk operations could be made more transparent.
*/
#include "TEmulation.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* STD */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* ------------------------------------------------------------------------- */
/* */
/* TEmulation */
/* */
/* ------------------------------------------------------------------------- */
#define CNTL(c) ((c)-'@')
/*!
*/
TEmulation::TEmulation(TEWidget* gui)
: decoder((QTextDecoder*)NULL)
{
this->gui = gui;
screen[0] = new TEScreen(gui->Lines(),gui->Columns());
screen[1] = new TEScreen(gui->Lines(),gui->Columns());
scr = screen[0];
bulk_nlcnt = 0; // reset bulk newline counter
bulk_incnt = 0; // reset bulk counter
connected = FALSE;
QObject::connect(&bulk_timer, SIGNAL(timeout()), this, SLOT(showBulk()) );
QObject::connect(gui,SIGNAL(changedImageSizeSignal(int,int)),
this,SLOT(onImageSizeChange(int,int)));
QObject::connect(gui,SIGNAL(changedHistoryCursor(int)),
this,SLOT(onHistoryCursorChange(int)));
QObject::connect(gui,SIGNAL(keyPressedSignal(QKeyEvent*)),
this,SLOT(onKeyPress(QKeyEvent*)));
QObject::connect(gui,SIGNAL(beginSelectionSignal(const int,const int)),
this,SLOT(onSelectionBegin(const int,const int)) );
QObject::connect(gui,SIGNAL(extendSelectionSignal(const int,const int)),
this,SLOT(onSelectionExtend(const int,const int)) );
QObject::connect(gui,SIGNAL(endSelectionSignal(const BOOL)),
this,SLOT(setSelection(const BOOL)) );
QObject::connect(gui,SIGNAL(clearSelectionSignal()),
this,SLOT(clearSelection()) );
}
/*!
*/
TEmulation::~TEmulation()
{
delete screen[0];
delete screen[1];
bulk_timer.stop();
}
/*! change between primary and alternate screen
*/
void TEmulation::setScreen(int n)
{
scr = screen[n&1];
}
void TEmulation::setHistory(bool on)
{
screen[0]->setScroll(on);
if (!connected) return;
showBulk();
}
bool TEmulation::history()
{
return screen[0]->hasScroll();
}
void TEmulation::setCodec(int c)
{
//FIXME: check whether we have to free codec
codec = c ? QTextCodec::codecForName("utf8")
: QTextCodec::codecForLocale();
if (decoder) delete decoder;
decoder = codec->makeDecoder();
}
void TEmulation::setKeytrans(int no)
{
keytrans = KeyTrans::find(no);
}
void TEmulation::setKeytrans(const char * no)
{
keytrans = KeyTrans::find(no);
}
// Interpreting Codes ---------------------------------------------------------
/*
This section deals with decoding the incoming character stream.
Decoding means here, that the stream is first seperated into `tokens'
which are then mapped to a `meaning' provided as operations by the
`Screen' class.
*/
/*!
*/
void TEmulation::onRcvChar(int c)
// process application unicode input to terminal
// this is a trivial scanner
{
c &= 0xff;
switch (c)
{
case '\b' : scr->BackSpace(); break;
case '\t' : scr->Tabulate(); break;
case '\n' : scr->NewLine(); break;
case '\r' : scr->Return(); break;
case 0x07 : gui->Bell(); break;
default : scr->ShowCharacter(c); break;
};
}
/* ------------------------------------------------------------------------- */
/* */
/* Keyboard Handling */
/* */
/* ------------------------------------------------------------------------- */
/*!
*/
void TEmulation::onKeyPress( QKeyEvent* ev )
{
- qWarning("onKeyPress,....");
+ owarn << "onKeyPress,...." << oendl;
if (!connected) return; // someone else gets the keys
if (scr->getHistCursor() != scr->getHistLines());
scr->setHistCursor(scr->getHistLines());
if (!ev->text().isEmpty())
{ // A block of text
// Note that the text is proper unicode.
// We should do a conversion here, but since this
// routine will never be used, we simply emit plain ascii.
emit sndBlock(ev->text().ascii(),ev->text().length());
}
else if (ev->ascii()>0)
{ unsigned char c[1];
c[0] = ev->ascii();
emit sndBlock((char*)c,1);
}
}
// Unblocking, Byte to Unicode translation --------------------------------- --
/*
We are doing code conversion from locale to unicode first.
*/
void TEmulation::onRcvBlock(const char *s, int len)
{
bulkStart();
bulk_incnt += 1;
for (int i = 0; i < len; i++)
{
QString result = decoder->toUnicode(&s[i],1);
int reslen = result.length();
for (int j = 0; j < reslen; j++)
onRcvChar(result[j].unicode());
if (s[i] == '\n') bulkNewline();
}
bulkEnd();
}
// Selection --------------------------------------------------------------- --
void TEmulation::onSelectionBegin(const int x, const int y) {
if (!connected) return;
scr->setSelBeginXY(x,y);
showBulk();
}
void TEmulation::onSelectionExtend(const int x, const int y) {
if (!connected) return;
scr->setSelExtentXY(x,y);
showBulk();
}
void TEmulation::setSelection(const BOOL preserve_line_breaks) {
if (!connected) return;
QString t = scr->getSelText(preserve_line_breaks);
if (!t.isNull()) gui->setSelection(t);
}
void TEmulation::clearSelection() {
if (!connected) return;
scr->clearSelection();
showBulk();
}
void TEmulation::streamHistory(QTextStream* stream) {
*stream << scr->getHistory();
}
// Refreshing -------------------------------------------------------------- --
#define BULK_TIMEOUT 20
/*!
called when \n comes in. Evtl. triggers showBulk at endBulk
*/
void TEmulation::bulkNewline()
{
bulk_nlcnt += 1;
bulk_incnt = 0; // reset bulk counter since `nl' rule applies
}
/*!
*/
void TEmulation::showBulk()
{
bulk_nlcnt = 0; // reset bulk newline counter
bulk_incnt = 0; // reset bulk counter
if (connected)
{
ca* image = scr->getCookedImage(); // get the image
gui->setImage(image,
scr->getLines(),
scr->getColumns()); // actual refresh
free(image);
//FIXME: check that we do not trigger other draw event here.
gui->setScroll(scr->getHistCursor(),scr->getHistLines());
diff --git a/noncore/apps/opie-console/atconfigdialog.cpp b/noncore/apps/opie-console/atconfigdialog.cpp
index 8e91b9e..c998f96 100644
--- a/noncore/apps/opie-console/atconfigdialog.cpp
+++ b/noncore/apps/opie-console/atconfigdialog.cpp
@@ -1,215 +1,218 @@
+#include "atconfigdialog.h"
+#include "io_modem.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qlineedit.h>
#include <qspinbox.h>
#include <qlayout.h>
#include <qcombobox.h>
#include <qtabwidget.h>
#include <qlabel.h>
#include <qscrollview.h>
-#include "atconfigdialog.h"
-#include "io_modem.h"
-
-
ATConfigDialog::ATConfigDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
: QDialog( parent, name, modal, fl ) {
setCaption( tr( "Dialing parameter setup" ) );
QVBoxLayout *layout = new QVBoxLayout( this );
QTabWidget *tabWidget = new QTabWidget( this );
tabWidget->addTab( tab0( this ), tr("Settings1") );
tabWidget->addTab( tab1( this ), tr("Settings2") );
layout->addWidget( tabWidget );
}
QWidget* ATConfigDialog::tab0( QWidget* parent) {
QScrollView* sv = new QScrollView( parent );
QWidget *returnWidget = new QWidget( sv->viewport() );
sv->setResizePolicy( QScrollView::AutoOneFit );
// sv->setHScrollBarMode( QScrollView::AlwaysOff );
// sv->setFrameShape( QFrame::NoFrame );
QGridLayout *layout = new QGridLayout( returnWidget, 10, 2 );
QLabel *initStringLabel = new QLabel( tr("Init string "), returnWidget );
initStringLine = new QLineEdit( returnWidget );
layout->addWidget( initStringLabel, 0, 0 );
layout->addWidget( initStringLine, 0, 1 );
QLabel *resetStringLabel = new QLabel( tr("Reset string "), returnWidget );
resetStringLine = new QLineEdit( returnWidget );
layout->addWidget( resetStringLabel, 1, 0 );
layout->addWidget( resetStringLine, 1, 1 );
QLabel *dialPref1Label = new QLabel( tr("Dialing prefix #1 " ), returnWidget );
dialPref1Line = new QLineEdit( returnWidget );
layout->addWidget( dialPref1Label, 2, 0 );
layout->addWidget( dialPref1Line, 2, 1 );
QLabel *dialSuf1Label = new QLabel( tr("Dialing suffix #1 " ), returnWidget );
dialSuf1Line = new QLineEdit( returnWidget );
layout->addWidget( dialSuf1Label, 3, 0 );
layout->addWidget( dialSuf1Line, 3, 1 );
QLabel *dialPref2Label = new QLabel( tr("Dialing prefix #2 " ), returnWidget );
dialPref2Line = new QLineEdit( returnWidget );
layout->addWidget( dialPref2Label, 4, 0 );
layout->addWidget( dialPref2Line, 4, 1 );
QLabel *dialSuf2Label = new QLabel( tr("Dialing suffix #2 " ), returnWidget );
dialSuf2Line = new QLineEdit( returnWidget );
layout->addWidget( dialSuf2Label, 5, 0 );
layout->addWidget( dialSuf2Line, 5, 1 );
QLabel *dialPref3Label = new QLabel( tr("Dialing prefix #3 " ), returnWidget );
dialPref3Line = new QLineEdit( returnWidget );
layout->addWidget( dialPref3Label, 6, 0 );
layout->addWidget( dialPref3Line, 6, 1 );
QLabel *dialSuf3Label = new QLabel( tr("Dialing suffix #3 " ), returnWidget );
dialSuf3Line = new QLineEdit( returnWidget );
layout->addWidget( dialSuf3Label, 7, 0 );
layout->addWidget( dialSuf3Line, 7, 1 );
QLabel *connectLabel = new QLabel( tr("Connect string " ), returnWidget );
connectLine = new QLineEdit( returnWidget );
layout->addWidget( connectLabel, 8, 0 );
layout->addWidget( connectLine, 8, 1 );
QLabel *hangupLabel = new QLabel( tr("Hang-up string " ), returnWidget );
hangupLine = new QLineEdit( returnWidget );
layout->addWidget( hangupLabel, 9, 0 );
layout->addWidget( hangupLine, 9, 1 );
sv->addChild( returnWidget );
return sv;
}
QWidget* ATConfigDialog::tab1( QWidget* parent ) {
QWidget *returnWidget = new QWidget( parent );
QGridLayout *layout = new QGridLayout( returnWidget, 8, 2 );
QLabel *dialTimeLabel = new QLabel( tr("Dial time " ), returnWidget );
dialTimeSpin = new QSpinBox( returnWidget );
layout->addWidget( dialTimeLabel, 0, 0 );
layout->addWidget( dialTimeSpin, 0, 1 );
QLabel *delayRedialLabel = new QLabel( tr("Delay before redial " ), returnWidget );
delayRedialSpin = new QSpinBox( returnWidget );
layout->addWidget( delayRedialLabel, 1, 0 );
layout->addWidget( delayRedialSpin, 1, 1 );
QLabel *numberTriesLabel = new QLabel( tr("Number of tries " ), returnWidget );
numberTriesSpin = new QSpinBox( returnWidget );
layout->addWidget( numberTriesLabel, 2, 0 );
layout->addWidget( numberTriesSpin, 2, 1 );
QLabel *dtrDropTimeLabel = new QLabel( tr("DTR drop time (0=no) " ), returnWidget );
dtrDropTimeSpin = new QSpinBox( returnWidget );
layout->addWidget( dtrDropTimeLabel, 3, 0 );
layout->addWidget( dtrDropTimeSpin, 3, 1 );
QLabel *bpsDetectLabel = new QLabel( tr("Auto bps detect " ), returnWidget );
bpsDetectBox = new QComboBox( returnWidget );
layout->addWidget( bpsDetectLabel, 4, 0 );
layout->addWidget( bpsDetectBox, 4, 1 );
bpsDetectBox->insertItem( tr("No") );
bpsDetectBox->insertItem( tr("Yes") );
QLabel *dcdLinesLabel = new QLabel( tr("Modem has DCD line " ), returnWidget );
dcdLinesBox = new QComboBox( returnWidget );
layout->addWidget( dcdLinesLabel, 5, 0 );
layout->addWidget( dcdLinesBox, 5, 1 );
dcdLinesBox->insertItem( tr("No") );
dcdLinesBox->insertItem( tr("Yes") );
QLabel *multiLineUntagLabel = new QLabel( tr("Multi-line untag " ), returnWidget );
multiLineUntagBox = new QComboBox( returnWidget );
layout->addWidget( multiLineUntagLabel, 6, 0 );
layout->addWidget( multiLineUntagBox, 6, 1 );
multiLineUntagBox->insertItem( tr("No") );
multiLineUntagBox->insertItem( tr("Yes") );
return returnWidget;
}
void ATConfigDialog::readConfig( const Profile& config ) {
- qWarning("config in atconfigdialog");
+ owarn << "config in atconfigdialog" << oendl;
initStringLine->setText( config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING ) );
resetStringLine->setText( config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING ) );
dialPref1Line->setText( config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ) );
dialSuf1Line->setText( config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
dialPref2Line->setText( config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 ) );
dialSuf2Line->setText( config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
dialPref3Line->setText( config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 ) );
dialSuf3Line->setText( config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
connectLine->setText( config.readEntry("DefaultConnect", MODEM_DEFAULT_CONNECT_STRING ) );
hangupLine->setText( config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) );
dialTimeSpin->setValue( config.readNumEntry("DialTime", MODEM_DEFAULT_DIAL_TIME ) );
delayRedialSpin->setValue( config.readNumEntry("DelayRedial", MODEM_DEFAULT_DELAY_REDIAL ) );
numberTriesSpin->setValue( config.readNumEntry("NumberTries", MODEM_DEFAULT_NUMBER_TRIES ) );
dtrDropTimeSpin->setValue( config.readNumEntry("DTRDRopTime", MODEM_DEFAULT_DTR_DROP_TIME ) );
bpsDetectBox->setCurrentItem( config.readBoolEntry("BPSDetect", MODEM_DEFAULT_BPS_DETECT ) );
dcdLinesBox->setCurrentItem( config.readBoolEntry("DCDLines", MODEM_DEFAULT_DCD_LINES ) );
multiLineUntagBox->setCurrentItem( config.readBoolEntry("MultiLineUntag", MODEM_DEFAULT_MULTI_LINE_UNTAG ) );
// Not implemented yet
resetStringLine->setEnabled(false);
dialSuf1Line->setEnabled(false);
dialPref2Line->setEnabled(false);
dialSuf2Line->setEnabled(false);
dialPref3Line->setEnabled(false);
dialSuf3Line->setEnabled(false);
dialTimeSpin->setEnabled(false);
delayRedialSpin->setEnabled(false);
numberTriesSpin->setEnabled(false);
dtrDropTimeSpin->setEnabled(false);
bpsDetectBox->setEnabled(false);
dcdLinesBox->setEnabled(false);
multiLineUntagBox->setEnabled(false);
}
void ATConfigDialog::writeConfig( Profile& config ) {
config.writeEntry( "InitString", initStringLine->text() );
config.writeEntry( "ResetString", resetStringLine->text() );
config.writeEntry( "DialPrefix1", dialPref1Line->text() );
config.writeEntry( "DialSuffix1", dialSuf1Line->text() );
config.writeEntry( "DialPrefix2", dialPref2Line->text() );
config.writeEntry( "DialSuffix2", dialSuf2Line->text() );
config.writeEntry( "DialPrefix3", dialPref3Line->text() );
config.writeEntry( "DialSuffix3", dialSuf3Line->text() );
config.writeEntry( "DefaultConnect", connectLine->text() );
config.writeEntry( "HangupString", hangupLine->text() );
config.writeEntry( "DialTime", dialTimeSpin->value() );
config.writeEntry( "DelayRedial", delayRedialSpin->value() );
config.writeEntry( "NumberTries", numberTriesSpin->value() );
config.writeEntry( "DTRDRopTime", dtrDropTimeSpin->value() );
config.writeEntry( "BPSDetect", bpsDetectBox->currentItem() );
config.writeEntry( "DCDLines", dcdLinesBox->currentItem() );
config.writeEntry( "MultiLineUntag", multiLineUntagBox->currentItem() );
}
ATConfigDialog::~ATConfigDialog() {
}
diff --git a/noncore/apps/opie-console/dialer.cpp b/noncore/apps/opie-console/dialer.cpp
index 67ad10e..7010594 100644
--- a/noncore/apps/opie-console/dialer.cpp
+++ b/noncore/apps/opie-console/dialer.cpp
@@ -1,315 +1,320 @@
#include "dialer.h"
+#include "io_modem.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+/* QT */
#include <qlayout.h>
#include <qprogressbar.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qapp.h>
#include <qtimer.h>
#include <qmessagebox.h>
+/* STD */
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
-#include "io_modem.h"
-
// State machine: | When an error occurs, we don't have to
// | reset everything.
// (init) <------+ | But if the user wants to reset,
// | | | we stop dialing immediately.
// v | |
// (options) ----+ | Following the state machine is necessary
// | \ | to get determinable results.
// v ^ |
// (dial) ----+ |
// | ^ |
// v | |
// (online) --+ |
// | |
// v |
// from atconfigdialog
//initStringLine->setText( config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING ) );
//resetStringLine->setText( config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING ) );
//dialPref1Line->setText( config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ) );
//dialSuf1Line->setText( config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
//dialPref2Line->setText( config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 ) );
//dialSuf2Line->setText( config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
//dialPref3Line->setText( config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 ) );
//dialSuf3Line->setText( config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
//connectLine->setText( config.readEntry("DefaultConnect" MODEM_DEFAULT_CONNECT_STRING ) );
//hangupLine->setText( config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) );
// from modemconfigwidget
//int rad_flow = prof.readNumEntry("Flow");
//int rad_parity = prof.readNumEntry("Parity");
//int speed = prof.readNumEntry("Speed");
//QString number = prof.readEntry("Number");
Dialer::Dialer(const Profile& profile, int fd, QWidget *parent, const char *name)
: QDialog(parent, name, true), m_fd(fd), m_profile(profile)
{
QVBoxLayout *vbox;
QLabel *desc;
usercancel = 0;
cleanshutdown = 0;
desc = new QLabel(QObject::tr("Dialing number: %1").arg(m_profile.readEntry("Number")), this);
progress = new QProgressBar(this);
status = new QLabel("", this);
status->setFrameStyle(QFrame::Panel | QFrame::Sunken);
cancel = new QPushButton(QObject::tr("Cancel"), this);
vbox = new QVBoxLayout(this, 2);
vbox->add(desc);
vbox->add(progress);
vbox->add(status);
vbox->add(cancel);
connect(cancel, SIGNAL(clicked()), SLOT(slotCancel()));
show();
QTimer::singleShot(500, this, SLOT(slotAutostart()));
}
Dialer::~Dialer()
{
}
void Dialer::setHangupOnly()
{
state = state_cancel;
usercancel = 1;
send( m_profile.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING )+"\r" );
}
void Dialer::slotCancel()
{
if(state != state_online)
{
usercancel = 1;
reset();
}
else {
accept();
}
}
void Dialer::reset()
{
- qWarning("reset");
+ owarn << "reset" << oendl;
switchState(state_cancel);
}
void Dialer::slotAutostart()
{
//state = state_preinit;
dial(m_profile.readEntry("Number"));
}
void Dialer::dial(const QString& number)
{
while(state != state_online)
{
if(!usercancel)
{
state = state_preinit;
trydial(number);
}
else break;
}
if(usercancel)
{
// modem hangup
trydial(QString::null);
reject();
}
}
void Dialer::trydial(const QString& number)
{
- qWarning("TryDial:%s", number.latin1() );
+ owarn << "TryDial:" << number.latin1() << "" << oendl;
if(state != state_cancel) switchState(state_preinit);
if(cleanshutdown)
{
- qWarning("HangupString " + m_profile.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING));
+ owarn << "HangupString " << m_profile.readEntry("HangupString") << oendl;
send(m_profile.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) + "\r");
}
if(state != state_cancel)
{
switchState(state_init);
-// qWarning("Init String " + m_profile.readEntry("InitString") );
+// owarn << "Init String " + m_profile.readEntry("InitString") << oendl;
send(m_profile.readEntry("InitString",MODEM_DEFAULT_INIT_STRING ) + "\r");
QString response2 = receive();
if(!response2.contains("\nOK\r"))
reset();
}
/* if(state != state_cancel)
{
switchState(state_options);
- qWarning("ATM3l3");
+ owarn << "ATM3l3" << oendl;
send("ATM3L3\r");
QString response3 = receive();
if(!response3.contains("\nOK\r"))
reset();
}
*/
if(state != state_cancel)
{
switchState(state_dialtone);
send("ATX1\r");
QString response4 = receive();
if(!response4.contains("\nOK\r"))
reset();
}
if(state != state_cancel)
{
- qWarning("progress");
+ owarn << "progress" << oendl;
switchState(state_dialing);
// send(QString("ATDT %1\r").arg(number));
send(QString("%1 %2\r").arg(m_profile.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ))
.arg(number));
QString response5 = receive();
if(!response5.contains("CONNECT") )
{
if(response5.contains("BUSY"))
switchState(state_dialing);
else
{
QMessageBox::warning(this,
QObject::tr("Failure"),
QObject::tr("Dialing the number failed."));
slotCancel();
}
}
}
if(state != state_cancel)
{
state = state_online;
slotCancel();
}
}
void Dialer::send(const QString& msg)
{
QString m = msg;
int bytes;
QString termination;
- qWarning("Sending: %s", m.latin1());
+ owarn << "Sending: " << m.latin1() << "" << oendl;
/* termination = "\r";
//termination = m_profile.readEntry("Termination");
if(termination == "\n") m = m + "\n";
else if(termination == "\r") m = m + "\r";
else m = m + "\r\n";
*/
m = m.replace(QRegExp("\n"), "\r");
bytes = ::write(m_fd, m.local8Bit(), strlen(m.local8Bit()));
if(bytes < 0)
{
reset();
}
}
QString Dialer::receive()
{
QString buf;
char buffer[1024];
int ret;
int counter = 0;
while(1)
{
ret = ::read(m_fd, buffer, sizeof(buffer));
if(ret > 0)
{
for(int i = 0; i < ret; i++)
buffer[i] = buffer[i] & 0x7F;
buffer[ret] = 0;
- qWarning("Got: %s", buffer);
+ owarn << "Got: " << buffer << "" << oendl;
buf.append(QString(buffer));
if(buf.contains("OK") || buf.contains("ERROR") || buf.contains("CONNECT") || (buf.contains("BUSY")))
{
- //qWarning("Receiving: '%s'", buf.latin1());
+ //owarn << "Receiving: '" << buf.latin1() << "'" << oendl;
cleanshutdown = 1;
return buf;
}else if (buf.contains("NO CARRIER") || buf.contains("NO DIALTONE") ) {
cleanshutdown = 1;
return QString::null;
}
}
else if(ret < 0)
{
if(errno != EAGAIN) reset();
else if(!(counter++ % 100)) qApp->processEvents();
}
else if(!(counter++ % 100)) qApp->processEvents();
if(usercancel) return QString::null;
}
cleanshutdown = 1;
return QString::null;
}
void Dialer::switchState(int newstate)
{
int oldstate = state;
state = newstate;
switch(state)
{
case state_cancel:
status->setText(QObject::tr("Cancelling..."));
progress->setProgress(0);
break;
case state_preinit:
status->setText(QObject::tr("Searching modem"));
progress->setProgress(10);
break;
case state_init:
status->setText(QObject::tr("Initializing..."));
progress->setProgress(20);
break;
case state_options:
status->setText(QObject::tr("Reset speakers"));
progress->setProgress(30);
break;
case state_dialtone:
status->setText(QObject::tr("Turning off dialtone"));
progress->setProgress(40);
break;
case state_dialing:
if(oldstate != state_dialing) status->setText(QObject::tr("Dial number"));
else status->setText(QObject::tr("Line busy, redialing number"));
progress->setProgress(50);
break;
case state_online:
status->setText(QObject::tr("Connection established"));
progress->setProgress(100);
cancel->setText(QObject::tr("Dismiss"));
break;
}
}
diff --git a/noncore/apps/opie-console/emulation_handler.cpp b/noncore/apps/opie-console/emulation_handler.cpp
index 99d069f..89b70c6 100644
--- a/noncore/apps/opie-console/emulation_handler.cpp
+++ b/noncore/apps/opie-console/emulation_handler.cpp
@@ -1,206 +1,208 @@
-
#include "TEmuVt102.h"
-
#include "profile.h"
#include "emulation_handler.h"
#include "script.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
EmulationHandler::EmulationHandler( const Profile& prof, QWidget* parent,const char* name )
: QObject(0, name )
{
m_teWid = new TEWidget( parent, "TerminalMain");
// use setWrapAt(0) for classic behaviour (wrap at screen width, no scrollbar)
// use setWrapAt(80) for normal console with scrollbar
setWrap(prof.readNumEntry("Wrap", 0) ? 0 : 80);
m_teWid->setMinimumSize(150, 70 );
m_script = 0;
parent->resize( m_teWid->calcSize(80, 24 ) );
m_teEmu = new TEmuVt102(m_teWid );
connect(m_teEmu,SIGNAL(ImageSizeChanged(int,int) ),
this, SIGNAL(changeSize(int,int) ) );
connect(m_teEmu, SIGNAL(sndBlock(const char*,int) ),
this, SLOT(recvEmulation(const char*,int) ) );
m_teEmu->setConnect( true );
m_teEmu->setHistory( TRUE );
load( prof );
}
TEmulation* EmulationHandler::emulation() {
return m_teEmu;
}
EmulationHandler::~EmulationHandler() {
if (isRecording())
clearScript();
delete m_teEmu;
delete m_teWid;
}
void EmulationHandler::load( const Profile& prof) {
m_teWid->setVTFont( font( prof.readNumEntry("Font") ) );
int num = prof.readNumEntry("Color");
setColor( foreColor(num), backColor(num) );
m_teWid->setBackgroundColor(backColor(num) );
int term = prof.readNumEntry("Terminal", 0) ;
switch(term) {
default:
case Profile::VT102:
case Profile::VT100:
m_teEmu->setKeytrans("vt100.keytab");
break;
case Profile::Linux:
m_teEmu->setKeytrans("linux.keytab");
break;
case Profile::XTerm:
m_teEmu->setKeytrans("default.Keytab");
break;
}
}
void EmulationHandler::recv( const QByteArray& ar) {
m_teEmu->onRcvBlock(ar.data(), ar.count() );
}
void EmulationHandler::recvEmulation(const char* src, int len ) {
QByteArray ar(len);
memcpy(ar.data(), src, sizeof(char) * len );
if (isRecording())
m_script->append(ar);
emit send(ar);
}
QWidget* EmulationHandler::widget() {
return m_teWid;
}
/*
* allocate a new table of colors
*/
void EmulationHandler::setColor( const QColor& fore, const QColor& back ) {
ColorEntry table[TABLE_COLORS];
const ColorEntry *defaultCt = m_teWid->getdefaultColorTable();
for (int i = 0; i < TABLE_COLORS; i++ ) {
if ( i == 0 || i == 10 ) {
table[i].color = fore;
}else if ( i == 1 || i == 11 ) {
table[i].color = back;
table[i].transparent = 0;
}else {
table[i].color = defaultCt[i].color;
}
}
m_teWid->setColorTable(table );
m_teWid->update();
}
QFont EmulationHandler::font( int id ) {
QString name;
int size = 0;
switch(id ) {
default: // fall through
case 0:
name = QString::fromLatin1("Micro");
size = 4;
break;
case 1:
name = QString::fromLatin1("Fixed");
size = 7;
break;
case 2:
name = QString::fromLatin1("Fixed");
size = 12;
break;
}
QFont font(name, size, QFont::Normal );
font.setFixedPitch(TRUE );
return font;
}
QColor EmulationHandler::foreColor(int col) {
QColor co;
/* we need to switch it */
switch( col ) {
default:
case Profile::White:
/* color is black */
co = Qt::white;
break;
case Profile::Black:
co = Qt::black;
break;
case Profile::Green:
- qWarning("Foreground green");
+ owarn << "Foreground green" << oendl;
co = Qt::green;
break;
case Profile::Orange:
- qWarning("Foreground orange");
+ owarn << "Foreground orange" << oendl;
co.setRgb( 231, 184, 98 );
break;
}
return co;
}
QColor EmulationHandler::backColor(int col ) {
QColor co;
/* we need to switch it */
switch( col ) {
default:
case Profile::White:
/* color is white */
co = Qt::black;
break;
case Profile::Black:
co = Qt::white;
break;
case Profile::Green:
- qWarning("Background black");
+ owarn << "Background black" << oendl;
co = Qt::black;
break;
case Profile::Orange:
- qWarning("Background black");
+ owarn << "Background black" << oendl;
co = Qt::black;
break;
}
return co;
}
QPushButton* EmulationHandler::cornerButton() {
return m_teWid->cornerButton();
}
Script *EmulationHandler::script() {
return m_script;
}
bool EmulationHandler::isRecording() {
return (m_script != 0);
}
void EmulationHandler::startRecording() {
if (!isRecording())
m_script = new Script();
}
void EmulationHandler::clearScript() {
if (isRecording()) {
delete m_script;
m_script = 0;
}
}
void EmulationHandler::runScript(const Script *script) {
emit send(script->script());
}
void EmulationHandler::copy() {
m_teWid->emitSelection();
}
void EmulationHandler::paste() {
m_teWid->pasteClipboard();
}
void EmulationHandler::setWrap(int columns) {
m_teWid->setWrapAt(columns);
}
diff --git a/noncore/apps/opie-console/emulation_widget.cpp b/noncore/apps/opie-console/emulation_widget.cpp
index ad8ecba..4688551 100644
--- a/noncore/apps/opie-console/emulation_widget.cpp
+++ b/noncore/apps/opie-console/emulation_widget.cpp
@@ -131,171 +131,171 @@ void EmulationWidget::setImage( QArray<Character> const newimg, int lines, int c
for ( int y = 0; y < lins; ++y )
{ int len;
const Character* lcl = &m_image[y * m_columns];
const Character* ext = &newimg[y * m_columns];
if ( ! m_resizing )
for ( int x = 0; x < cols; ++x )
{
// disable, till widget works, WITHOUT blinking
//hasBlinker |= ( ext[x].r & RE_BLINK );
if ( ext[x] != lcl[x] )
{
cr = ext[x].r;
cb = ext[x].b;
if ( ext[x].f != cf ) cf = ext[x].f;
int lln = cols - x;
disstrU[0] = vt100extended( ext[x+0].c );
for ( len = 1; len < lln; ++len )
{
if ( ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr || ext[x+len] == lcl[x+len] )
break;
disstrU[len] = vt100extended( ext[x+len].c );
}
QString unistr( disstrU, len );
drawAttrString( unistr, paint, QRect( m_blX+tLx+f_width*x, m_bY+tLy+f_height*y, f_width*len, f_height ), ext[x], pm != NULL, true );
x += len -1;
}
}
// make image become newimg
memcpy( (void*) lcl, (const void*) ext, cols*sizeof( Character ) );
}
drawFrame( &paint );
paint.end();
setUpdatesEnabled( true );
/*if ( hasBlinker && !blinkT->isActive() )
blinkT->start(1000); //ms
if ( ! hasBlinker && blinkT->isActive() )
{
blinkT->stop();
blinking = false;
}*/
delete [] disstrU;
}
void EmulationWidget::paintEvent( QPaintEvent* pe )
{
QPainter painter;
const QPixmap* pm = backgroundPixmap();
painter.begin( this );
painter.setBackgroundMode( TransparentMode );
QRect rect = pe->rect().intersect( contentsRect() );
QPoint tL = contentsRect().topLeft();
int tLx = tL.x();
int tLy = tL.y();
int lux = QMIN(m_columns-1, QMAX(0,(rect.left() - tLx - m_blX ) / f_width));
int luy = QMIN(m_lines-1, QMAX(0,(rect.top() - tLy - m_bY ) / f_height));
int rlx = QMIN(m_columns-1, QMAX(0,(rect.right() - tLx - m_blX ) / f_width));
int rly = QMIN(m_lines-1, QMAX(0,(rect.bottom() - tLy - m_bY ) / f_height));
QChar *disstrU = new QChar[m_columns];
for (int y = luy; y <= rly; y++)
for (int x = lux; x <= rlx; x++)
{
int len = 1;
disstrU[0] = vt100extended(m_image[loc(x,y)].c);
int cf = m_image[loc(x,y)].f;
int cb = m_image[loc(x,y)].b;
int cr = m_image[loc(x,y)].r;
while (x+len <= rlx &&
m_image[loc(x+len,y)].f == cf &&
m_image[loc(x+len,y)].b == cb &&
m_image[loc(x+len,y)].r == cr )
{
disstrU[len] = vt100extended(m_image[loc(x+len,y)].c);
len += 1;
}
QString unistr(disstrU,len);
drawAttrString( unistr, painter, QRect( m_blX+tLx+f_width*x,m_bY+tLy+f_height*y,f_width*len,f_height ), m_image[loc(x ,y )], pm != 0l, false );
x +=len -1;
}
delete [] disstrU;
drawFrame( &painter );
painter.end();
}
void EmulationWidget::calcGeometry()
{
m_scrollbar->resize(QApplication::style().scrollBarExtent().width(), contentsRect().height() );
- qDebug( QString(" TEST").arg( contentsRect().width() ) );
- qDebug( QString(" TEST").arg( contentsRect().height() ) );
- qDebug("NEUER TESTT!!!!!!!!");
+ odebug << QString(" TEST").arg( contentsRect().width() ) << oendl;
+ odebug << QString(" TEST").arg( contentsRect().height() ) << oendl;
+ odebug << "NEUER TESTT!!!!!!!!" << oendl;
switch( scrollLoc )
{
case SCRNONE :
m_columns = ( contentsRect().width() -2 * rimX ) / f_width;
m_blX = ( contentsRect().width() - ( m_columns*f_width ) ) / 2;
m_brX = m_blX;
m_scrollbar->hide();
break;
case SCRLEFT :
m_columns = ( contentsRect().width() - 2 * rimX - m_scrollbar->width() ) / f_width;
m_brX = ( contentsRect().width() - ( m_columns*f_width ) - m_scrollbar->width() ) / 2;
m_blX = m_brX + m_scrollbar->width();
m_scrollbar->move( contentsRect().topLeft() );
m_scrollbar->show();
break;
case SCRIGHT:
m_columns = ( contentsRect().width() - 2 * rimX - m_scrollbar->width() ) / f_width;
m_blX = ( contentsRect().width() - ( m_columns*f_width ) - m_scrollbar->width() ) / 2;
m_brX = m_blX;
m_scrollbar->move( contentsRect().topRight() - QPoint (m_scrollbar->width()-1,0 ) );
m_scrollbar->show();
break;
}
m_lines = ( contentsRect().height() - 2 * rimY ) / f_height;
m_bY = ( contentsRect().height() - (m_lines * f_height ) ) / 2;
}
void EmulationWidget::drawAttrString( QString& string, QPainter &painter, QRect rect, Character attr, bool usePixmap, bool clear )
{
- qWarning("Color1 %s", color_table[attr.b].color.name().latin1() );
+ owarn << "Color1 " << color_table[attr.b].color.name().latin1() << "" << oendl;
if ( usePixmap && color_table[attr.b].transparent )
{
painter.setBackgroundMode( TransparentMode );
if ( clear )
erase( rect );
}
else
{
if ( blinking )
painter.fillRect( rect, color_table[attr.b].color );
else
{
painter.setBackgroundMode( OpaqueMode );
- qWarning("Color %s", color_table[attr.b].color.name().latin1() );
+ owarn << "Color " << color_table[attr.b].color.name().latin1() << "" << oendl;
painter.setBackgroundColor( color_table[attr.b].color );
}
}
if ( color_table[attr.f].bold )
painter.setPen( QColor( 0x8F, 0x00, 0x00 ) );
else
painter.setPen( color_table[attr.f].color );
painter.drawText( rect.x(), rect.y() + f_ascent, string );
}
///////////////////////
// scrollbar
// ////////////////////
void EmulationWidget::scroll( int value )
{
}
void EmulationWidget::setScroll( int cursor, int slines )
{
}
diff --git a/noncore/apps/opie-console/function_keyboard.cpp b/noncore/apps/opie-console/function_keyboard.cpp
index eb32551..6613183 100644
--- a/noncore/apps/opie-console/function_keyboard.cpp
+++ b/noncore/apps/opie-console/function_keyboard.cpp
@@ -1,136 +1,141 @@
#include "function_keyboard.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qlayout.h>
#include <qlistbox.h>
#include <qlabel.h>
#include <qdir.h>
#define DEFAULT_ROWS 2
#define DEFAULT_COLS 12
/* FunctionKeyboard {{{1 */
FunctionKeyboard::FunctionKeyboard(QWidget *parent) :
QFrame(parent), numRows(DEFAULT_ROWS), numCols(DEFAULT_COLS),
pressedRow(0), pressedCol(0) {
setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed));
/*
* all the saving/loading is now done in a profile. downside is that you cant modify
* the keyboard for all profiles, but must do it on a profile-basis
*
Config conf("opie-console-keys");
conf.setGroup("keys");
for (uint r = 0; r < numRows; r++)
for (uint c = 0; c < numCols; c++) {
QString handle = "r" + QString::number(r) + "c" + QString::number(c);
QStringList value_list = conf.readListEntry( handle, '|');
if (value_list.isEmpty()) continue;
keys.insert(
handle,
FKey (value_list[0], value_list[1], value_list[2].toUShort(), value_list[3].toUShort())
);
}
- //qWarning("loaded %d keys", keys.count());
+ //owarn << "loaded " << keys.count() << " keys" << oendl;
*/
if (keys.isEmpty()) loadDefaults();
}
FunctionKeyboard::~FunctionKeyboard() {}
void FunctionKeyboard::changeRows(int r) {
numRows = r;
// have to do this so the whole thing gets redrawn
hide(); show();
}
void FunctionKeyboard::changeCols(int c) {
numCols = c;
keyWidth = (double)width()/numCols; // have to reset this thing too
repaint(false);
}
void FunctionKeyboard::load (const Profile& prof) {
keys.clear();
numRows = prof.readNumEntry("keb_rows", 2);
numCols = prof.readNumEntry("keb_cols", 10);
keyWidth = (double)width()/numCols; // have to reset this thing too
/* load all the keys to the keyboard */
for (ushort i = 0; i <= numRows - 1; i++)
for (ushort j = 0; j <= numCols - 1; j++) {
QString h = "r" + QString::number(i) + "c" + QString::number(j);
QString values = prof.readEntry("keb_" + h);
if (!values.isEmpty()) {
QStringList l = QStringList::split(QChar('|'), values, TRUE);
keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt());
// load pixmap if used
if (!l[1].isEmpty()) {
keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) );
}
}
}
if (keys.isEmpty()) loadDefaults();
hide();
show();
}
void FunctionKeyboard::paintEvent(QPaintEvent *e) {
QPainter p(this);
p.setClipRect(e->rect());
p.fillRect(0, 0, width(), height(), QColor(255,255,255));
p.setPen(QColor(0,0,0));
/* those decimals do count! becomes short if use plain int */
for (double i = 0; i <= width(); i += keyWidth) {
p.drawLine((int)i, 0, (int)i, height());
}
// sometimes the last line doesnt get drawn
p.drawLine(width() -1, 0, width() -1, height());
for (int i = 0; i <= height(); i += keyHeight) {
p.drawLine(0, i, width(), i);
}
for (uint r = 0; r < numRows; r++) {
for (uint c = 0; c < numCols; c++) {
QString handle = "r" + QString::number(r) + "c" + QString::number(c);
if (keys.contains(handle)) {
if (keys[handle].pixFile.isEmpty())
p.drawText( c * keyWidth + 1, r * keyHeight + 1,
keyWidth, keyHeight,
Qt::AlignHCenter | Qt::AlignVCenter,
keys[handle].label
);
else {
ushort centerX = (ushort)(c *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2;
ushort centerY = r * keyHeight + (keyHeight - keys[handle].pix->height()) / 2;
p.drawPixmap(centerX, centerY, *keys[handle].pix);
@@ -163,193 +168,193 @@ void FunctionKeyboard::paintKey(uint row, uint col) {
p.drawPixmap(centerX, centerY, *keys[handle].pix);
}
if (col == numCols - 1) {
// sometimes it doesnt draw the last line
p.drawLine((col+1) * keyWidth -1, row * keyHeight,
(col+1) * keyWidth -1, (row + 1) * keyHeight
);
}
}
void FunctionKeyboard::mousePressEvent(QMouseEvent *e) {
pressedRow = e->y() / keyHeight;
pressedCol = (int) (e->x() / keyWidth);
paintKey(pressedRow, pressedCol);
// emit that sucker!
FKey k = keys["r" + QString::number(pressedRow) + "c" + QString::number(pressedCol)];
emit keyPressed(k, pressedRow, pressedCol, 1);
}
void FunctionKeyboard::mouseReleaseEvent(QMouseEvent *) {
if (pressedRow != -1 && pressedRow != -1) {
int row = pressedRow; pressedRow = -1;
int col = pressedCol; pressedCol = -1;
paintKey(row, col);
FKey k = keys["r" + QString::number(row) + "c" + QString::number(col)];
emit keyPressed(k, row, col, 0);
}
}
void FunctionKeyboard::resizeEvent(QResizeEvent*) {
/* set he default font height/width */
QFontMetrics fm=fontMetrics();
keyHeight = fm.lineSpacing() + 2;
keyWidth = (double)width()/numCols;
}
QSize FunctionKeyboard::sizeHint() const {
return QSize(width(), keyHeight * numRows + 1);
}
void FunctionKeyboard::loadDefaults() {
numRows = DEFAULT_ROWS;
numCols = DEFAULT_COLS;
keyWidth = (double)width()/numCols; // have to reset this thing too
keys.insert( "r0c0", FKey ("Enter", "enter", Qt::Key_Enter, 0));
keys.insert( "r0c1", FKey ("Space", "space", Qt::Key_Space, Qt::Key_Space));
keys.insert( "r0c2", FKey ("Tab", "tab", Qt::Key_Tab, 0));
keys.insert( "r0c3", FKey ("Up", "up", Qt::Key_Up, 0));
keys.insert( "r0c4", FKey ("Down", "down", Qt::Key_Down, 0));
keys.insert( "r0c7", FKey ("Ho", 0, 4112, 0));
keys.insert( "r0c8", FKey ("End", 0, 4113, 0));
keys.insert( "r0c9", FKey ("Pu", 0, 4118, 0));
keys.insert( "r0c10", FKey ("Pd", 0, 4119, 0));
keys.insert( "r0c11", FKey ("Esc", 0, Qt::Key_Escape, 0xfff));
keys.insert( "r1c0", FKey ("F1", 0, 4144, 0));
keys.insert( "r1c1", FKey ("F2", 0, 4145, 0));
keys.insert( "r1c2", FKey ("F3", 0, 4146, 0));
keys.insert( "r1c3", FKey ("F4", 0, 4147, 0));
keys.insert( "r1c4", FKey ("F5", 0, 4148, 0));
keys.insert( "r1c5", FKey ("F6", 0, 4149, 0));
keys.insert( "r1c6", FKey ("F7", 0, 4150, 0));
keys.insert( "r1c7", FKey ("F8", 0, 4151, 0));
keys.insert( "r1c8", FKey ("F9", 0, 4152, 0));
keys.insert( "r1c9", FKey ("F10", 0, 4153, 0));
keys.insert( "r1c10", FKey ("F11", 0, 4154, 0));
keys.insert( "r1c11", FKey ("F12", 0, 4155, 0));
}
/* FunctionKeyboardConfig {{{1 */
FunctionKeyboardConfig::FunctionKeyboardConfig(const QString& name, QWidget* parent, const char* na )
: ProfileDialogKeyWidget(name, parent, na),
selectedRow(0), selectedCol(0)
{
- qWarning("FunctionKeyboardConfig");
+ owarn << "FunctionKeyboardConfig" << oendl;
kb = new FunctionKeyboard(this);
connect (kb, SIGNAL(keyPressed(FKey,ushort,ushort,bool)),
this, SLOT(slotKeyPressed(FKey,ushort,ushort,bool)));
QGroupBox *dimentions = new QGroupBox(2, Qt::Horizontal, tr("Dimensions"), this);
QLabel *l = new QLabel("Rows", dimentions);
m_rowBox = new QSpinBox(1, 15, 1, dimentions);
connect (m_rowBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeRows(int)));
l = new QLabel("Columns", dimentions);
m_colBox = new QSpinBox(1, 15, 1, dimentions);
connect (m_colBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeCols(int)));
QGroupBox *editKey = new QGroupBox(2, Qt::Horizontal, tr("Edit Key"), this);
l = new QLabel("Label", editKey);
m_labels = new QComboBox(true, editKey);
m_labels->setInsertionPolicy(QComboBox::AtCurrent);
m_labels->insertItem("");
QStringList files = QDir( QPEApplication::qpeDir() + "pics/console/keys/", "*.png").entryList();
for (uint i = 0; i < files.count(); i++) {
m_labels->insertItem( Resource::loadPixmap("console/keys/" + files[i]), files[i]);
}
connect (m_labels, SIGNAL(activated(int)), this, SLOT(slotChangeIcon(int)));
connect (m_labels, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeLabelText(const QString&)));
l = new QLabel("Q Keycode", editKey);
m_qvalues = new QComboBox(true, editKey);
m_qvalues->setInsertionPolicy(QComboBox::AtTop);
m_qvalues->setDuplicatesEnabled(false);
m_qvalues->insertItem("");
connect (m_qvalues, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeQCode(const QString&)));
l = new QLabel("Unicode Value", editKey);
m_uniValues = new QComboBox(true, editKey);
m_uniValues->setInsertionPolicy(QComboBox::AtTop);
m_uniValues->setDuplicatesEnabled(false);
m_uniValues->insertItem("");
connect (m_uniValues, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeUnicode(const QString&)));
QVBoxLayout *root = new QVBoxLayout(this, 2);
root->addWidget(kb);
root->addWidget(dimentions);
root->addWidget(editKey);
}
FunctionKeyboardConfig::~FunctionKeyboardConfig() {
}
void FunctionKeyboardConfig::load (const Profile& prof) {
kb->keys.clear();
kb->loadDefaults();
m_rowBox->setValue(prof.readNumEntry("keb_rows", 2));
m_colBox->setValue(prof.readNumEntry("keb_cols", 10));
/* load all the keys to the keyboard */
for (int i = 0; i <= m_rowBox->value() -1; i++)
for (int j = 0; j <= m_colBox->value() -1; j++) {
QString h = "r" + QString::number(i) + "c" + QString::number(j);
QString values = prof.readEntry("keb_" + h);
if (!values.isEmpty()) {
QStringList l = QStringList::split(QChar('|'), values, TRUE);
kb->keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt());
// load pixmap if used
if (!l[1].isEmpty()) {
kb->keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) );
}
}
}
}
void FunctionKeyboardConfig::save (Profile& prof) {
prof.writeEntry("keb_rows", m_rowBox->value());
prof.writeEntry("keb_cols", m_colBox->value());
QMap<QString, FKey>::Iterator it;
for ( it = kb->keys.begin(); it != kb->keys.end(); it++) {
FKey k = it.data();
QString entry = k.label + "|"
+ k.pixFile + "|"
+ QString::number(k.qcode) + "|"
+ QString::number(k.unicode);
prof.writeEntry("keb_" + it.key(), entry);
diff --git a/noncore/apps/opie-console/io_bt.cpp b/noncore/apps/opie-console/io_bt.cpp
index a29fa8e..c102427 100644
--- a/noncore/apps/opie-console/io_bt.cpp
+++ b/noncore/apps/opie-console/io_bt.cpp
@@ -1,93 +1,96 @@
#include "io_bt.h"
+/* OPIE */
+#include <opie2/odebug.h>
using namespace Opie::Core;
+
IOBt::IOBt( const Profile &config ) : IOSerial( config ) {
m_attach = 0;
}
IOBt::~IOBt() {
if ( m_attach ) {
delete m_attach;
}
}
void IOBt::close() {
IOSerial::close();
// still need error handling
if ( m_attach ) {
delete m_attach;
m_attach = 0;
}
}
bool IOBt::open() {
bool ret = false;
// only set up bt stuff if mac address was set, otherwise use the device set
if ( !m_mac.isEmpty() ) {
// now it should also be checked, if there is a connection to the device with that mac allready
// hciattach here
m_attach = new OProcess();
*m_attach << "hciattach /dev/ttyS2 any 57600";
// then start hcid, then rcfomm handling (m_mac)
connect( m_attach, SIGNAL( processExited(Opie::Core::OProcess*) ),
this, SLOT( slotExited(Opie::Core::OProcess*) ) );
if ( m_attach->start() ) {
ret = IOSerial::open();
} else {
- qWarning("could not attach to device");
+ owarn << "could not attach to device" << oendl;
delete m_attach;
m_attach = 0;
}
} else {
// directly to the normal serial
// TODO: look first if the connection really exists. ( is set up )
ret =IOSerial::open();
}
return ret;
}
void IOBt::reload( const Profile &config ) {
m_device = config.readEntry("Device", BT_DEFAULT_DEVICE);
m_mac = config.readEntry("Mac", BT_DEFAULT_MAC);
m_baud = config.readNumEntry("Baud", BT_DEFAULT_BAUD);
m_parity = config.readNumEntry("Parity", BT_DEFAULT_PARITY);
m_dbits = config.readNumEntry("DataBits", BT_DEFAULT_DBITS);
m_sbits = config.readNumEntry("StopBits", BT_DEFAULT_SBITS);
m_flow = config.readNumEntry("Flow", BT_DEFAULT_FLOW);
}
QString IOBt::identifier() const {
return "bluetooth";
}
QString IOBt::name() const {
return "BLuetooth IO Layer";
}
void IOBt::slotExited( OProcess* proc ){
close();
delete proc;
}
QBitArray IOBt::supports() const {
return QBitArray( 3 );
}
bool IOBt::isConnected() {
return false;
}
void IOBt::send(const QByteArray &data) {
- qDebug( "Please overload me..." );
+ odebug << "Please overload me..." << oendl;
}
diff --git a/noncore/apps/opie-console/io_irda.cpp b/noncore/apps/opie-console/io_irda.cpp
index 07c2b62..38542f5 100644
--- a/noncore/apps/opie-console/io_irda.cpp
+++ b/noncore/apps/opie-console/io_irda.cpp
@@ -1,78 +1,80 @@
-
#include "io_irda.h"
+/* OPIE */
+#include <opie2/odebug.h>
using namespace Opie::Core;
+
IOIrda::IOIrda( const Profile &config ) : IOSerial( config ) {
m_attach = 0;
}
IOIrda::~IOIrda() {
if ( m_attach ) {
delete m_attach;
}
}
void IOIrda::close() {
IOSerial::close();
// still need error handling
delete m_attach;
}
bool IOIrda::open() {
bool ret;
// irdaattach here
m_attach = new OProcess();
*m_attach << "irattach /dev/ttyS2 -s";
connect( m_attach, SIGNAL( processExited(Opie::Core::OProcess*) ),
this, SLOT( slotExited(Opie::Core::OProcess*) ) );
if ( m_attach->start() ) {
ret= IOSerial::open();
} else {
// emit error!!!
- qWarning("could not attach to device");
+ owarn << "could not attach to device" << oendl;
delete m_attach;
m_attach = 0l;
}
return ret;
}
void IOIrda::reload( const Profile &config ) {
m_device = config.readEntry("Device", IRDA_DEFAULT_DEVICE);
m_baud = config.readNumEntry("Baud", IRDA_DEFAULT_BAUD);
m_parity = config.readNumEntry("Parity", IRDA_DEFAULT_PARITY);
m_dbits = config.readNumEntry("DataBits", IRDA_DEFAULT_DBITS);
m_sbits = config.readNumEntry("StopBits", IRDA_DEFAULT_SBITS);
m_flow = config.readNumEntry("Flow", IRDA_DEFAULT_FLOW);
}
QString IOIrda::identifier() const {
return "irda";
}
QString IOIrda::name() const {
return "Irda IO Layer";
}
void IOIrda::slotExited(OProcess* proc ){
close();
delete proc;
}
QBitArray IOIrda::supports()const {
return QBitArray( 3 );
}
bool IOIrda::isConnected() {
return false;
}
void IOIrda::send(const QByteArray &data) {
- qDebug( "Please overload me..." );
+ odebug << "Please overload me..." << oendl;
}
diff --git a/noncore/apps/opie-console/io_modem.cpp b/noncore/apps/opie-console/io_modem.cpp
index b74d076..c499dfe 100644
--- a/noncore/apps/opie-console/io_modem.cpp
+++ b/noncore/apps/opie-console/io_modem.cpp
@@ -1,108 +1,108 @@
#include "io_modem.h"
-
#include "dialer.h"
+/* OPIE */
+#include <opie2/odebug.h>
using namespace Opie::Core;
-using namespace Opie::Core;
+
IOModem::IOModem( const Profile &profile )
: IOSerial( profile ) {
m_profile = profile;
}
IOModem::~IOModem() {
-
}
void IOModem::close() {
// Hangup, discarding result
// int fd = rawIO();
internDetach();
Dialer d(m_profile, m_fd);
d.setHangupOnly();
//d.exec();
internAttach();
// closeRawIO(fd);
IOSerial::close();
}
bool IOModem::open() {
bool ret = IOSerial::open();
if(!ret) return false;
// int fd = rawIO();
internDetach();
Dialer d(m_profile, m_fd);
int result = d.exec();
internAttach();
// closeRawIO(fd);
if(result == QDialog::Accepted)
{
return true;
}
else
{
close();
return false;
}
}
void IOModem::reload( const Profile &config ) {
m_device = config.readEntry("Device", MODEM_DEFAULT_DEVICE);
m_baud = config.readNumEntry("Baud", MODEM_DEFAULT_BAUD);
m_parity = config.readNumEntry("Parity", MODEM_DEFAULT_PARITY);
m_dbits = config.readNumEntry("DataBits", MODEM_DEFAULT_DBITS);
m_sbits = config.readNumEntry("StopBits", MODEM_DEFAULT_SBITS);
m_flow = config.readNumEntry("Flow", MODEM_DEFAULT_FLOW);
m_initString = config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING );
m_resetString = config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING );
m_dialPref1 = config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 );
m_dialSuf1 = config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 );
m_dialPref2 = config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 );
m_dialSuf2 = config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 );
m_dialPref3 = config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 );
m_dialSuf3 = config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 );
m_connect = config.readEntry("DefaultConnect" MODEM_DEFAULT_CONNECT_STRING );
m_hangup = config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING );
m_cancel = config.readEntry("CancelString", MODEM_DEFAULT_CANCEL_STRING );
m_dialTime = config.readNumEntry("DialTime", MODEM_DEFAULT_DIAL_TIME );
m_delayRedial = config.readNumEntry("DelayRedial", MODEM_DEFAULT_DELAY_REDIAL );
m_numberTries = config.readNumEntry("NumberTries", MODEM_DEFAULT_NUMBER_TRIES );
m_dtrDropTime = config.readNumEntry("DTRDRopTime", MODEM_DEFAULT_DTR_DROP_TIME );
m_bpsDetect = config.readBoolEntry("BPSDetect", MODEM_DEFAULT_BPS_DETECT );
m_dcdLines = config.readBoolEntry("DCDLines", MODEM_DEFAULT_DCD_LINES );
m_multiLineUntag = config.readBoolEntry("MultiLineUntag", MODEM_DEFAULT_MULTI_LINE_UNTAG );
}
QString IOModem::identifier() const {
return "modem";
}
QString IOModem::name() const {
return "Modem IO Layer";
}
void IOModem::slotExited(OProcess* proc ){
close();
/* delete it afterwards */
delete proc;
}
QBitArray IOModem::supports()const {
return QBitArray( 3 );
}
bool IOModem::isConnected() {
return false;
}
void IOModem::send(const QByteArray &data) {
- qDebug( "Please overload me..." );
+ odebug << "Please overload me..." << oendl;
}
diff --git a/noncore/apps/opie-console/main.cpp b/noncore/apps/opie-console/main.cpp
index dfb2f83..1bd4338 100644
--- a/noncore/apps/opie-console/main.cpp
+++ b/noncore/apps/opie-console/main.cpp
@@ -1,110 +1,110 @@
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <qpe/qpeapplication.h>
#include "mainwindow.h"
//#define FSCKED_DISTRIBUTION 1
#ifdef FSCKED_DISTRIBUTION
/*
* The Zaurus rom
*/
class FixIt {
public:
FixIt();
~FixIt();
void fixIt();
/* no real interested in implementing it */
void breakIt() {
};
char* m_file;
};
FixIt::FixIt() {
/* the new inittab */
m_file = "#\n# /etc/inittab"
"#"
""
"# 0 - halt (Do NOT set initdefault to this)"
"# 1 - Single user mode"
"# 2 - Multiuser, without NFS (The same as 3, if you do not have networking)"
"# 3 - Full multiuser mode"
"# 4 - JavaVM(Intent) developer mode"
"# 5 - JavaVM(Intent)"
"# 6 - reboot (Do NOT set initdefault to this)"
"#"
"id:5:initdefault:"
""
"# Specify things to do when starting"
"si::sysinit:/etc/rc.d/rc.sysinit"
""
"l0:0:wait:/root/etc/rc.d/rc 0"
"l1:1:wait:/etc/rc.d/rc 1"
"l2:2:wait:/etc/rc.d/rc 2"
"l3:3:wait:/etc/rc.d/rc 3"
"l4:4:wait:/etc/rc.d/rc 4"
"l5:5:wait:/etc/rc.d/rc 5"
"l6:6:wait:/root/etc/rc.d/rc 6"
""
"# Specify things to do before rebooting"
"um::ctrlaltdel:/bin/umount -a -r > /dev/null 2>&1"
"sw::ctrlaltdel:/sbin/swapoff -a > /dev/null 2>&1"
""
"# Specify program to run on ttyS0"
"s0:24:respawn:/sbin/getty 9600 ttyS0"
"#pd:5:respawn:/etc/sync/serialctl"
""
"# Specify program to run on tty1"
"1:2:respawn:/sbin/getty 9600 tty1"
"ln:345:respawn:survive -l 6 /sbin/launch"
"#qt:5:respawn:/sbin/qt"
""
"# collie sp."
"sy::respawn:/sbin/shsync\n";
}
FixIt::~FixIt() {
}
/*
* the retail Zaurus is broken in many ways
* one is that pppd is listening on our port...
* we've to stop it from that and then do kill(SIGHUP,1);
*/
void FixIt::fixIt() {
::rename("/etc/inittab", QPEApplication::qpeDir() + "/etc/inittab" );
QFile file( "/etc/inittab" );
if ( file.open(IO_WriteOnly | IO_Raw ) ) {
file.writeBlock(m_file,strlen(m_file) );
}
file.close();
::kill( SIGHUP, 1 );
}
#endif
int main(int argc, char **argv) {
// too bad this gives us trouble the taskbar... argv[0]="embeddedkonsole";
QPEApplication app( argc, argv );
#ifdef FSCKED_DISTRIBUTION
- qWarning("fscked");
+ owarn << "fscked" << oendl;
FixIt it;
it.fixIt();
#endif
MainWindow mw;
mw.setCaption(QObject::tr("Opie Console") );
app.showMainWidget( &mw );
int ap = app.exec();
#ifdef FSCKED_DISTRIBUTION
/* should add a signal handler too */
it.breakIt();
#endif
return ap;
}
diff --git a/noncore/apps/opie-console/mainwindow.cpp b/noncore/apps/opie-console/mainwindow.cpp
index 06a8f7d..b403b4d 100644
--- a/noncore/apps/opie-console/mainwindow.cpp
+++ b/noncore/apps/opie-console/mainwindow.cpp
@@ -1,123 +1,126 @@
-#include <assert.h>
-
-#include <qaction.h>
-#include <qmenubar.h>
-#include <qtoolbar.h>
-#include <qmessagebox.h>
-#include <qwhatsthis.h>
-#include <qfileinfo.h>
-
-#include <qpe/filemanager.h>
-
-#include <opie2/ofiledialog.h>
-
#include "TEmulation.h"
#include "profileeditordialog.h"
#include "configdialog.h"
#include "default.h"
#include "profilemanager.h"
#include "mainwindow.h"
#include "tabwidget.h"
#include "transferdialog.h"
#include "function_keyboard.h"
#include "emulation_handler.h"
#include "script.h"
-
+/* OPIE */
+#include <opie2/odebug.h>
+#include <opie2/ofiledialog.h>
+#include <qpe/filemanager.h>
+using namespace Opie::Core;
using namespace Opie::Ui;
+
+/* QT */
+#include <qaction.h>
+#include <qmenubar.h>
+#include <qtoolbar.h>
+#include <qmessagebox.h>
+#include <qwhatsthis.h>
+#include <qfileinfo.h>
+
+/* STD */
+#include <assert.h>
+
MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) {
KeyTrans::loadAll();
for (int i = 0; i < KeyTrans::count(); i++ ) {
KeyTrans* s = KeyTrans::find(i );
assert( s );
}
m_factory = new MetaFactory();
Default def(m_factory);
m_sessions.setAutoDelete( TRUE );
m_curSession = 0;
m_manager = new ProfileManager( m_factory );
m_manager->load();
m_scriptsData.setAutoDelete(TRUE);
initUI();
populateProfiles();
populateScripts();
}
void MainWindow::initUI() {
setToolBarsMovable( FALSE );
/* tool bar for the menu */
m_tool = new QToolBar( this );
m_tool->setHorizontalStretchable( TRUE );
m_bar = new QMenuBar( m_tool );
m_console = new QPopupMenu( this );
m_scripts = new QPopupMenu( this );
m_sessionsPop= new QPopupMenu( this );
m_scriptsPop = new QPopupMenu( this );
/* add a toolbar for icons */
m_icons = new QToolBar(this);
/*
* the settings action
*/
m_setProfiles = new QAction(tr("Configure Profiles"),
Resource::loadPixmap( "SettingsIcon" ),
QString::null, 0, this, 0);
m_setProfiles->addTo( m_console );
connect( m_setProfiles, SIGNAL(activated() ),
this, SLOT(slotConfigure() ) );
m_console->insertSeparator();
/*
* new Action for new sessions
*/
QAction* newCon = new QAction(tr("New Profile"),
Resource::loadPixmap( "new" ),
QString::null, 0, this, 0);
newCon->addTo( m_console );
connect( newCon, SIGNAL(activated() ),
this, SLOT(slotNew() ) );
m_console->insertSeparator();
QAction *saveCon = new QAction( tr("Save Profile" ),
Resource::loadPixmap( "save" ), QString::null,
0, this, 0 );
saveCon->addTo( m_console );
connect( saveCon, SIGNAL(activated() ),
this, SLOT(slotSaveSession() ) );
m_console->insertSeparator();
/*
* connect action
*/
m_connect = new QAction( tr("Connect"), Resource::loadPixmap("console/connected"),
QString::null, 0, this, 0 );
m_connect->addTo( m_console );
connect(m_connect, SIGNAL(activated() ),
this, SLOT(slotConnect() ) );
/*
* disconnect action
*/
m_disconnect = new QAction( tr("Disconnect"), Resource::loadPixmap("console/notconnected"),
QString::null, 0, this, 0 );
m_disconnect->addTo( m_console );
connect(m_disconnect, SIGNAL(activated() ),
this, SLOT(slotDisconnect() ) );
m_console->insertSeparator();
m_quickLaunch = new QAction( tr("QuickLaunch"), Resource::loadPixmap("console/konsole_mini"), QString::null, 0, this, 0 );
m_quickLaunch->addTo( m_icons );
connect( m_quickLaunch, SIGNAL( activated() ),
this, SLOT( slotQuickLaunch() ) );
QWhatsThis::add( m_icons, tr( "The shell button launches the \"default\" profile. If there is none default values are taken" ) );
m_transfer = new QAction( tr("Transfer file..."), Resource::loadPixmap("pass") , QString::null,
@@ -353,326 +356,326 @@ void MainWindow::slotSaveScript() {
}
void MainWindow::slotRunScript(int id) {
if (currentSession()) {
int index = m_scriptsPop->indexOf(id);
DocLnk *lnk = m_scriptsData.at(index);
QString filePath = lnk->file();
Script script(filePath);
currentSession()->emulationHandler()->runScript(&script);
}
}
void MainWindow::slotConnect() {
if ( currentSession() ) {
bool ret = currentSession()->layer()->open();
if(!ret) QMessageBox::warning(currentSession()->widgetStack(),
QObject::tr("Failed"),
QObject::tr("Connecting failed for this session."));
else {
m_connect->setEnabled( false );
m_disconnect->setEnabled( true );
// if it does not support file transfer, disable the menu entry
if ( ( m_curSession->layer() )->supports()[1] == 0 ) {
m_transfer->setEnabled( false );
} else {
m_transfer->setEnabled( true );
}
m_recordScript->setEnabled( true );
m_scripts->setItemEnabled(m_runScript_id, true);
}
}
}
void MainWindow::slotDisconnect() {
if ( currentSession() ) {
currentSession()->layer()->close();
m_connect->setEnabled( true );
m_disconnect->setEnabled( false );
m_transfer->setEnabled( false );
m_recordScript->setEnabled( false);
m_saveScript->setEnabled( false );
m_scripts->setItemEnabled(m_runScript_id, false);
}
}
void MainWindow::slotTerminate() {
if ( currentSession() )
currentSession()->layer()->close();
slotClose();
/* FIXME move to the next session */
}
void MainWindow::slotQuickLaunch() {
Profile prof = manager()->profile( "default" );
if ( prof.name() == "default" ) {
create( prof );
} else {
Profile newProf = Profile( "default", "console", "default" , 0, 3, 0 );
newProf.setAutoConnect( true );
create( newProf );
slotSaveSession();
}
}
void MainWindow::slotConfigure() {
ConfigDialog conf( manager()->all(), factory() );
int ret = QPEApplication::execDialog( &conf );
if ( QDialog::Accepted == ret ) {
manager()->setProfiles( conf.list() );
manager()->save();
populateProfiles();
}
}
/*
* we will remove
* this window from the tabwidget
* remove it from the list
* delete it
* and set the currentSession()
*/
void MainWindow::slotClose() {
if (!currentSession() )
return;
Session* ses = currentSession();
- qWarning("removing! currentSession %s", currentSession()->name().latin1() );
+ owarn << "removing! currentSession " << currentSession()->name().latin1() << "" << oendl;
/* set to NULL to be safe, if its needed slotSessionChanged resets it automatically */
m_curSession = NULL;
tabWidget()->remove( /*currentSession()*/ses );
/*it's autodelete */
m_sessions.remove( ses );
- qWarning("after remove!!");
+ owarn << "after remove!!" << oendl;
if (!currentSession() ) {
m_connect->setEnabled( false );
m_disconnect->setEnabled( false );
m_terminate->setEnabled( false );
m_transfer->setEnabled( false );
m_recordScript->setEnabled( false );
m_saveScript->setEnabled( false );
m_scripts->setItemEnabled(m_runScript_id, false);
m_fullscreen->setEnabled( false );
m_wrap->setEnabled( false );
m_closewindow->setEnabled( false );
}
m_kb->loadDefaults();
}
/*
* We will get the name
* Then the profile
* and then we will make a profile
*/
void MainWindow::slotProfile( int id) {
Profile prof = manager()->profile( m_sessionsPop->text( id) );
create( prof );
}
void MainWindow::create( const Profile& prof ) {
if(m_curSession)
if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide();
Session *ses = manager()->fromProfile( prof, tabWidget() );
if((!ses) || (!ses->layer()) || (!ses->widgetStack()))
{
QMessageBox::warning(this,
QObject::tr("Session failed"),
QObject::tr("<qt>Cannot open session: Not all components were found.</qt>"));
//if(ses) delete ses;
return;
}
m_sessions.append( ses );
tabWidget()->add( ses );
tabWidget()->repaint();
m_curSession = ses;
// dicide if its a local term ( then no connction and no tranfer), maybe make a wrapper method out of it
m_connect->setEnabled( true );
m_disconnect->setEnabled( false );
m_terminate->setEnabled( true );
m_fullscreen->setEnabled( true );
m_wrap->setEnabled( true );
m_closewindow->setEnabled( true );
m_transfer->setEnabled( false );
m_recordScript->setEnabled( false );
m_saveScript->setEnabled( false );
m_scripts->setItemEnabled(m_runScript_id, false);
// is io_layer wants direct connection, then autoconnect
//if ( ( m_curSession->layer() )->supports()[0] == 1 ) {
if (prof.autoConnect()) {
slotConnect();
}
QWidget *w = currentSession()->widget();
if(w) w->setFocus();
if(currentSession()->profile().readNumEntry("Wrap", 80)){
m_isWrapped = true;
} else {
m_isWrapped = false;
}
m_kb->load(currentSession()->profile());
}
void MainWindow::slotTransfer()
{
if ( currentSession() ) {
Session *mysession = currentSession();
TransferDialog dlg(/*mysession->widgetStack()*/this, this);
mysession->setTransferDialog(&dlg);
//dlg.reparent(mysession->widgetStack(), QPoint(0, 0));
//dlg.showMaximized();
currentSession()->widgetStack()->addWidget(&dlg, -1);
dlg.show();
//dlg.exec();
while(dlg.isRunning()) qApp->processEvents();
mysession->setTransferDialog(0l);
}
}
void MainWindow::slotOpenKeb(bool state) {
if (state) m_keyBar->show();
else m_keyBar->hide();
}
void MainWindow::slotOpenButtons( bool state ) {
if ( state ) {
m_buttonBar->show();
} else {
m_buttonBar->hide();
}
}
void MainWindow::slotSessionChanged( Session* ses ) {
- qWarning("changed!");
+ owarn << "changed!" << oendl;
if(m_curSession)
if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide();
if(ses)
if(ses->transferDialog()) ses->transferDialog()->show();
if ( ses ) {
m_curSession = ses;
- qDebug(QString("is connected : %1").arg( m_curSession->layer()->isConnected() ) );
+ odebug << QString("is connected : %1").arg( m_curSession->layer()->isConnected() ) << oendl;
if ( m_curSession->layer()->isConnected() ) {
m_connect->setEnabled( false );
m_disconnect->setEnabled( true );
m_recordScript->setEnabled(!m_curSession->emulationHandler()->isRecording());
m_saveScript->setEnabled(m_curSession->emulationHandler()->isRecording());
m_scripts->setItemEnabled(m_runScript_id, true);
} else {
m_connect->setEnabled( true );
m_disconnect->setEnabled( false );
m_recordScript->setEnabled( false );
m_saveScript->setEnabled( false );
m_scripts->setItemEnabled(m_runScript_id, false);
}
if ( ( m_curSession->layer() )->supports()[1] == 0 ) {
m_transfer->setEnabled( false );
} else {
m_transfer->setEnabled( true );
}
QWidget *w = m_curSession->widget();
if(w) w->setFocus();
if(currentSession()->profile().readNumEntry("Wrap", 80)){
m_isWrapped = true;
} else {
m_isWrapped = false;
}
m_kb->load(currentSession()->profile());
}
}
void MainWindow::slotWrap()
{
if(m_curSession)
{
EmulationHandler *e = m_curSession->emulationHandler();
if(e)
{
if(m_isWrapped)
{
e->setWrap(80);
m_isWrapped = false;
}
else
{
e->setWrap(0);
m_isWrapped = true;
}
}
}
}
void MainWindow::slotFullscreen() {
if ( m_isFullscreen ) {
( m_curSession->widgetStack() )->reparent( savedParentFullscreen, 0, QPoint(0,0), true );
( m_curSession->widgetStack() )->resize( savedParentFullscreen->width(), savedParentFullscreen->height() );
( m_curSession->emulationHandler() )->cornerButton()->hide();
disconnect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) );
} else {
savedParentFullscreen = ( m_curSession->widgetStack() )->parentWidget();
( m_curSession->widgetStack() )->setFrameStyle( QFrame::NoFrame );
( m_curSession->widgetStack() )->reparent( 0, WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop
, QPoint(0,0), false );
( m_curSession->widgetStack() )->resize( qApp->desktop()->width(), qApp->desktop()->height() );
( m_curSession->widgetStack() )->setFocus();
( m_curSession->widgetStack() )->show();
( ( m_curSession->emulationHandler() )->cornerButton() )->show();
connect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) );
}
m_isFullscreen = !m_isFullscreen;
}
void MainWindow::slotKeyReceived(FKey k, ushort, ushort, bool pressed) {
if ( m_curSession ) {
QEvent::Type state;
if (pressed) state = QEvent::KeyPress;
else state = QEvent::KeyRelease;
QKeyEvent ke(state, k.qcode, k.unicode, 0, QString(QChar(k.unicode)));
// is this the best way to do this? cant figure out any other way to work
QApplication::sendEvent((QObject *)m_curSession->widget(), &ke);
ke.ignore();
diff --git a/noncore/apps/opie-console/modemconfigwidget.cpp b/noncore/apps/opie-console/modemconfigwidget.cpp
index 3466e3a..9fdaf73 100644
--- a/noncore/apps/opie-console/modemconfigwidget.cpp
+++ b/noncore/apps/opie-console/modemconfigwidget.cpp
@@ -1,234 +1,237 @@
+#include "modemconfigwidget.h"
+#include "dialdialog.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
+/* QT */
#include <qlabel.h>
#include <qlayout.h>
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qhbox.h>
-#include "modemconfigwidget.h"
-#include "dialdialog.h"
-
namespace {
void setCurrent( const QString& str, QComboBox* bo ) {
uint b = bo->count();
for (int i = 0; i < bo->count(); i++ ) {
if ( bo->text(i) == str ) {
bo->setCurrentItem( i );
return;
}
}
bo->insertItem( str );
bo->setCurrentItem( b );
}
}
ModemConfigWidget::ModemConfigWidget( const QString& name, QWidget* parent,
const char* na )
: ProfileDialogConnectionWidget( name, parent, na ) {
m_lay = new QVBoxLayout( this );
m_device = new QLabel(tr( "Modem is attached to:" ), this );
m_deviceCmb = new QComboBox(this );
m_deviceCmb->setEditable( TRUE );
QLabel* telLabel = new QLabel( this );
telLabel->setText( tr( "Enter telefon number here:" ) );
QHBox *buttonBox = new QHBox( this );
m_telNumber = new QLineEdit( buttonBox );
QPushButton *atButton = new QPushButton( buttonBox );
atButton->setText( tr( "AT commands" ) );
connect( atButton, SIGNAL( clicked() ), this, SLOT( slotAT() ) );
QPushButton *dialButton = new QPushButton( buttonBox );
dialButton->setText( tr( "Enter number" ) );
connect( dialButton, SIGNAL( clicked() ), this, SLOT( slotDial() ) );
m_base = new IOLayerBase( this, "base" );
m_lay->addWidget( m_device );
m_lay->addWidget( m_deviceCmb );
m_lay->addWidget( telLabel );
m_lay->addWidget( buttonBox );
m_lay->addWidget( m_base );
m_lay->addStretch( 0 );
m_deviceCmb->insertItem( "/dev/ttyS0" );
m_deviceCmb->insertItem( "/dev/ttyS1" );
m_deviceCmb->insertItem( "/dev/ttyS2" );
atConf = new ATConfigDialog( this, "ATConfig", true );
}
ModemConfigWidget::~ModemConfigWidget() {
}
void ModemConfigWidget::load( const Profile& prof ) {
int rad_flow = prof.readNumEntry( "Flow" );
int rad_parity = prof.readNumEntry( "Parity" );
int speed = prof.readNumEntry( "Speed" );
int dbits = prof.readNumEntry("DataBits");
int sbits = prof.readNumEntry("StopBits");
QString number = prof.readEntry( "Number" );
if ( !number.isEmpty() ) {
m_telNumber->setText( number );
}
if ( rad_flow == 1 ) {
m_base->setFlow( IOLayerBase::Hardware );
} else if (rad_flow == 2) {
m_base->setFlow( IOLayerBase::Software );
} else if (rad_flow == 0) {
m_base->setFlow( IOLayerBase::None );
}
if ( rad_parity == 1 ) {
m_base->setParity( IOLayerBase::Even );
} else if ( rad_parity == 2 ){
m_base->setParity( IOLayerBase::Odd );
} else {
m_base->setParity( IOLayerBase::NonePar );
}
switch( speed ) {
case 115200:
m_base->setSpeed( IOLayerBase::Baud_115200 );
break;
case 57600:
m_base->setSpeed( IOLayerBase::Baud_57600 );
break;
case 38400:
m_base->setSpeed( IOLayerBase::Baud_38400 );
break;
case 19200:
m_base->setSpeed( IOLayerBase::Baud_19200 );
break;
case 9600:
default:
m_base->setSpeed( IOLayerBase::Baud_9600 );
break;
}
if ( dbits == 5) {
m_base->setData( IOLayerBase::Data_Five );
} else if (rad_flow == 6) {
m_base->setData( IOLayerBase::Data_Six );
} else if (rad_flow == 7) {
m_base->setData( IOLayerBase::Data_Seven );
} else {
m_base->setData( IOLayerBase::Data_Eight );
}
if ( sbits == 2) {
m_base->setStop( IOLayerBase::Stop_Two );
} else if ( sbits == 15 ) {
m_base->setStop( IOLayerBase::Stop_OnePointFive );
} else {
m_base->setStop( IOLayerBase::Stop_One );
}
atConf->readConfig( prof );
if ( prof.readEntry( "Device" ).isEmpty() ) {
- qWarning("device empty!");
+ owarn << "device empty!" << oendl;
return;
}
setCurrent( prof.readEntry( "Device" ), m_deviceCmb );
}
/*
* save speed,
* flow,
* parity
*/
void ModemConfigWidget::save( Profile& prof ) {
int flow, parity, speed, data, stop;
flow = parity = speed = data = stop = 0;
prof.writeEntry( "Device", m_deviceCmb->currentText() );
switch( m_base->flow() ) {
case IOLayerBase::None:
flow = 0;
break;
case IOLayerBase::Software:
flow = 2;
break;
case IOLayerBase::Hardware:
flow = 1;
break;
}
switch( m_base->parity() ) {
case IOLayerBase::Odd:
parity = 2;
break;
case IOLayerBase::Even:
parity = 1;
break;
case IOLayerBase::NonePar:
parity = 0;
break;
}
switch( m_base->speed() ) {
case IOLayerBase::Baud_115200:
speed = 115200;
break;
case IOLayerBase::Baud_57600:
speed = 57600;
break;
case IOLayerBase::Baud_38400:
speed = 38400;
break;
case IOLayerBase::Baud_19200:
speed = 19200;
break;
case IOLayerBase::Baud_9600:
speed = 9600;
break;
}
switch( m_base->data() ) {
case IOLayerBase::Data_Five:
data = 5;
break;
case IOLayerBase::Data_Six:
data = 6;
break;
case IOLayerBase::Data_Seven:
data = 7;
break;
case IOLayerBase::Data_Eight:
data = 8;
break;
}
switch( m_base->stop() ) {
case IOLayerBase::Stop_One:
stop = 1;
break;
case IOLayerBase::Stop_OnePointFive:
stop = 15;
break;
case IOLayerBase::Stop_Two:
stop = 2;
break;
}
prof.writeEntry( "Flow", flow );
prof.writeEntry( "Parity", parity );
prof.writeEntry( "Speed", speed );
prof.writeEntry("DataBits", data);
prof.writeEntry("StopBits", stop);
prof.writeEntry( "Number", m_telNumber->text() );
atConf->writeConfig(prof);
diff --git a/noncore/apps/opie-console/opie-console.pro b/noncore/apps/opie-console/opie-console.pro
index 7a15828..f7e33e9 100644
--- a/noncore/apps/opie-console/opie-console.pro
+++ b/noncore/apps/opie-console/opie-console.pro
@@ -1,76 +1,74 @@
TEMPLATE = app
-TMAKE_CXXFLAGS += -DHAVE_OPENPTY
CONFIG += qt warn_on
-#CONFIG = qt
DESTDIR = $(OPIEDIR)/bin
HEADERS = io_layer.h io_serial.h io_irda.h io_bt.h io_modem.h \
file_layer.h filetransfer.h \
metafactory.h \
session.h \
mainwindow.h \
profile.h \
profileconfig.h \
profilemanager.h \
tabwidget.h \
configdialog.h \
keytrans.h \
transferdialog.h \
profiledialogwidget.h \
profileeditordialog.h \
default.h \
iolayerbase.h \
serialconfigwidget.h irdaconfigwidget.h \
btconfigwidget.h modemconfigwidget.h \
atconfigdialog.h dialdialog.h \
procctl.h \
function_keyboard.h \
receive_layer.h filereceive.h \
script.h \
dialer.h \
terminalwidget.h \
emulation_handler.h TECommon.h \
TEHistory.h TEScreen.h TEWidget.h \
TEmuVt102.h TEmulation.h MyPty.h \
consoleconfigwidget.h
SOURCES = io_layer.cpp io_serial.cpp io_irda.cpp io_bt.cpp io_modem.cpp \
file_layer.cpp filetransfer.cpp \
main.cpp \
metafactory.cpp \
session.cpp \
mainwindow.cpp \
profile.cpp \
profileconfig.cpp \
profilemanager.cpp \
tabwidget.cpp \
configdialog.cpp \
keytrans.cpp \
transferdialog.cpp \
profiledialogwidget.cpp \
profileeditordialog.cpp \
iolayerbase.cpp \
serialconfigwidget.cpp irdaconfigwidget.cpp \
btconfigwidget.cpp modemconfigwidget.cpp \
atconfigdialog.cpp dialdialog.cpp \
default.cpp procctl.cpp \
function_keyboard.cpp \
receive_layer.cpp filereceive.cpp \
script.cpp \
dialer.cpp \
terminalwidget.cpp \
emulation_handler.cpp TEHistory.cpp \
TEScreen.cpp TEWidget.cpp \
TEmuVt102.cpp TEmulation.cpp MyPty.cpp \
consoleconfigwidget.cpp
INTERFACES = configurebase.ui editbase.ui
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
LIBS += -lqpe -lopiecore2 -lopieui2 -lutil
TARGET = opie-console
-
+DEFINES += HAVE_OPENPTY
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/opie-console/sz_transfer.cpp b/noncore/apps/opie-console/sz_transfer.cpp
index fbc5306..f505998 100644
--- a/noncore/apps/opie-console/sz_transfer.cpp
+++ b/noncore/apps/opie-console/sz_transfer.cpp
@@ -1,86 +1,86 @@
#include "sz_transfer.h"
#include <qfile.h>
#include <stdio.h>
#include <sys/termios.h>
using namespace Opie::Core;
using namespace Opie::Core;
SzTransfer::SzTransfer(Type t, IOLayer *layer) : FileTransferLayer(layer), m_t(t)
{
}
SzTransfer::~SzTransfer() {
}
void SzTransfer::sendFile(const QFile& file) {
sendFile(file.name());
}
void SzTransfer::sendFile(const QString& file) {
//setcbreak(2); /* raw no echo */
proc = new OProcess;
*proc << "sz";
*proc << "-v" << "-v" << "-b" << file;
connect(proc, SIGNAL(processExited(Opie::Core::OProcess*)),
this, SLOT(sent()));
connect(proc, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)),
this, SLOT(SzReceivedStdout(Opie::Core::OProcess*,char*,int)));
connect(proc, SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)),
this, SLOT(SzReceivedStderr(Opie::Core::OProcess*,char*,int)));
connect(layer(), SIGNAL(received(const QByteArray&)),
this, SLOT(receivedStdin(const QByteArray&)));
proc->start(OProcess::NotifyOnExit, OProcess::All);
}
void SzTransfer::SzReceivedStdout(OProcess *, char *buffer, int buflen) {
- qWarning("recieved from sz on stdout %d bytes", buflen);
+ owarn << "recieved from sz on stdout " << buflen << " bytes" << oendl;
QByteArray data(buflen);
data.fill(*buffer, buflen);
for (uint i = 0; i < data.count(); i++ ) {
printf("%c", buffer[i] );
}
printf("\n");
// send out through the io layer
layer()->send(data);
}
void SzTransfer::SzReceivedStderr(OProcess *, char *buffer, int length) {
// parse and show data in a progress dialog/widget
printf("stderr:\n");
//for (int i = 0; i < length; i++)
// printf("%c", buffer[i]);
//printf("\n");
}
void SzTransfer::receivedStdin(const QByteArray &data) {
- qWarning("recieved from io_serial %d bytes", data.size());
+ owarn << "recieved from io_serial " << data.size() << " bytes" << oendl;
// recieved data from the io layer goes to sz
proc->writeStdin(data.data(), data.size());
}
void SzTransfer::sent() {
- qWarning("sent file");
+ owarn << "sent file" << oendl;
//setcbreak(0); /* default */
delete proc;
disconnect(layer(), SIGNAL(received(const QByteArray&)),
this, SLOT(receivedStdin(const QByteArray&)));
}
diff --git a/noncore/apps/opie-console/tabwidget.cpp b/noncore/apps/opie-console/tabwidget.cpp
index 6429e3c..41a91ed 100644
--- a/noncore/apps/opie-console/tabwidget.cpp
+++ b/noncore/apps/opie-console/tabwidget.cpp
@@ -1,45 +1,48 @@
-
#include "tabwidget.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
using namespace Opie::Ui;
+
TabWidget::TabWidget( QWidget* parent, const char* name )
: OTabWidget( parent, name ) {
connect(this, SIGNAL( currentChanged(QWidget*) ),
this, SLOT( slotCurChanged(QWidget*) ) );
}
TabWidget::~TabWidget() {
}
void TabWidget::add( Session* ses ) {
- qWarning("session ses " + ses->name() );
+ owarn << "session ses " + ses->name() << oendl;
if ( !ses->widgetStack() ) return;
//reparent( ses->widgetStack(), QPoint() );
addTab( ses->widgetStack(), "console/konsole", ses->name() );
//addTab( ses->widgetStack(), ses->name() );
m_map.insert( ses->widgetStack(), ses );
}
void TabWidget::remove( Session* ses ) {
m_map.remove( ses->widgetStack() );
removePage( ses->widgetStack() );
}
void TabWidget::slotCurChanged( QWidget* wid ) {
QMap<QWidget*, Session*>::Iterator it;
it = m_map.find( wid );
if ( it == m_map.end() ) {
return;
}
emit activated( it.data() );
}
void TabWidget::setCurrent( Session* ses ) {
if (!ses )
return;
//showPage( ses->widgetStack() );
setCurrentTab( ses->widgetStack() );
}
diff --git a/noncore/apps/opie-console/terminalwidget.cpp b/noncore/apps/opie-console/terminalwidget.cpp
index 6870487..087476b 100644
--- a/noncore/apps/opie-console/terminalwidget.cpp
+++ b/noncore/apps/opie-console/terminalwidget.cpp
@@ -1,168 +1,173 @@
+#include "terminalwidget.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qlabel.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qradiobutton.h>
#include <qhgroupbox.h>
#include <qhbuttongroup.h>
#include <qlayout.h>
-#include "terminalwidget.h"
-
namespace {
enum TermIds {
id_term_vt100 = 0,
id_term_vt102,
id_term_linux,
id_term_xterm
};
enum ColourIds {
id_term_black,
id_term_white,
id_term_green,
id_term_orange
};
enum FontIds {
id_size_small,
id_size_medium,
id_size_large
};
};
TerminalWidget::TerminalWidget( const QString& name, QWidget* parent,
const char* na )
: ProfileDialogTerminalWidget( name, parent, na ) {
m_terminal = new QLabel(tr("Terminal Type"), this );
m_terminalBox = new QComboBox(this);
m_colorLabel = new QLabel(tr("Color scheme"), this);
m_colorCmb = new QComboBox(this );
m_groupSize = new QHButtonGroup(tr("Font size"), this );
m_sizeSmall = new QRadioButton(tr("small"), m_groupSize );
m_sizeMedium = new QRadioButton(tr("medium"), m_groupSize );
m_sizeLarge = new QRadioButton(tr("large"), m_groupSize );
m_groupConv = new QHGroupBox( tr("Line-break conversions"), this );
m_convInbound = new QCheckBox( tr("Inbound"), m_groupConv );
m_convOutbound = new QCheckBox( tr("Outbound"), m_groupConv );
m_groupOptions = new QHGroupBox( tr("Options"), this );
m_optionEcho = new QCheckBox( tr("Local echo"), m_groupOptions );
m_optionWrap = new QCheckBox( tr("Line wrap"), m_groupOptions );
m_lroot = new QVBoxLayout( this );
m_typeBox = new QVBoxLayout( m_lroot );
m_colorBox = new QVBoxLayout( m_lroot );
// Layout
m_typeBox->add( m_terminal );
m_typeBox->add( m_terminalBox );
m_lroot->add( m_groupSize );
m_colorBox->add( m_colorLabel );
m_colorBox->add( m_colorCmb );
m_lroot->add( m_groupConv );
m_lroot->add( m_groupOptions );
m_lroot->addStretch( 0 );
// Fill in some options
- qWarning("Options for terminal box");
+ owarn << "Options for terminal box" << oendl;
m_terminalBox->insertItem( tr("VT 100"), 0 ); // /*, id_term_vt100*/ );
m_terminalBox->insertItem( tr("VT 102"), 1 ); // /* , id_term_vt102 */);
m_terminalBox->insertItem( tr("Linux Console"), 2 ); //, id_term_linux );
m_terminalBox->insertItem( tr("X-Terminal"), 3 ); //, id_term_xterm );
//m_terminalBox->insertItem( tr("ANSI"), id_term_ansi );
m_colorCmb->insertItem( tr("black on white"), id_term_black );
m_colorCmb->insertItem( tr("white on black"), id_term_white );
m_colorCmb->insertItem( tr("green on black"), id_term_green );
m_colorCmb->insertItem( tr("orange on black"), id_term_orange );
// signals + slots
/*
connect(m_terminalBox, SIGNAL(activated(int) ),
this, SLOT(slotTermTerm(int) ) );
connect(m_colorBox, SIGNAL(activated(int) ),
tis, SLOT(slotTermColor(int) ) );
connect(m_groupSize, SIGNAL(activated(int) ),
this, SLOT(slotTermFont(int) ) );
connect(m_optionEcho, SIGNAL(toggled(bool) ),
this, SLOT(slotTermEcho(bool) ) );
connect(m_optionWrap, SIGNAL(toggled(bool) ),
this, SLOT(slotTermWrap(bool) ) );
connect(m_convInbound, SIGNAL(toggled(bool) ),
this, SLOT(slotTermInbound(bool) ) );
connect(m_convOutbound, SIGNAL(toggled(bool) ),
this, SLOT(slotTermOutbound(bool) ) );
*/
}
TerminalWidget::~TerminalWidget() {
}
void TerminalWidget::load( const Profile& prof ) {
int term = prof.readNumEntry("Terminal");
int color = prof.readNumEntry("Color");
int fontsize = prof.readNumEntry("Font");
int opt_echo = prof.readNumEntry("Echo");
int opt_wrap = prof.readNumEntry("Wrap");
int opt_inbound = prof.readNumEntry("Inbound");
int opt_outbound = prof.readNumEntry("Outbound");
switch( term ) {
case Profile::VT100:
m_terminalBox->setCurrentItem(id_term_vt100 );
break;
case Profile::VT102:
m_terminalBox->setCurrentItem(id_term_vt102 );
break;
case Profile::Linux:
m_terminalBox->setCurrentItem(id_term_linux );
break;
case Profile::XTerm:
m_terminalBox->setCurrentItem(id_term_xterm );
break;
default:
m_terminalBox->setCurrentItem(id_term_vt102 );
break;
};
switch( color ) {
case Profile::Black:
m_colorCmb->setCurrentItem(id_term_black );
break;
case Profile::White:
m_colorCmb->setCurrentItem(id_term_white );
break;
case Profile::Green:
m_colorCmb->setCurrentItem(id_term_green );
break;
case Profile::Orange:
m_colorCmb->setCurrentItem(id_term_orange );
break;
default:
break;
};
switch( fontsize ) {
case Profile::Micro:
m_sizeSmall->setChecked(true );
break;
case Profile::Small:
m_sizeMedium->setChecked(true );
break;
case Profile::Medium:
m_sizeLarge->setChecked( true );
break;
default:
m_sizeMedium->setChecked(true );
break;
};
if (opt_echo) m_optionEcho->setChecked( true );
if (opt_wrap) m_optionWrap->setChecked( true );
if (opt_inbound) m_convInbound->setChecked( true );
if (opt_outbound) m_convOutbound->setChecked( true );
diff --git a/noncore/apps/opie-console/test/senderui.cpp b/noncore/apps/opie-console/test/senderui.cpp
index df27055..45fd11d 100644
--- a/noncore/apps/opie-console/test/senderui.cpp
+++ b/noncore/apps/opie-console/test/senderui.cpp
@@ -1,79 +1,79 @@
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/termios.h>
#include <qmultilineedit.h>
#include <qsocketnotifier.h>
#include "../profile.h"
#include "../io_serial.h"
#include "../filetransfer.h"
#include "../filereceive.h"
#include <opie2/oprocess.h>
#include "senderui.h"
using namespace Opie::Core;
using namespace Opie::Core;
SenderUI::SenderUI()
: Sender() {
/* we do that manually */
Profile prof;
QString str = "/dev/bty0";
prof.writeEntry("Device",str );
prof.writeEntry("Baud", 19200 );
- qWarning("prof " + prof.readEntry("Device") + " " + str);
+ owarn << "prof " + prof.readEntry("Device") + " " + str << oendl;
ser = new IOSerial(prof);
connect(ser, SIGNAL(received(const QByteArray&) ),
this, SLOT(got(const QByteArray&) ) );
if ( ser->open() )
- qWarning("opened!!!");
+ owarn << "opened!!!" << oendl;
else
- qWarning("could not open");
+ owarn << "could not open" << oendl;
}
SenderUI::~SenderUI() {
}
void SenderUI::slotSendFile() {
sz = new FileTransfer(FileTransfer::SY, ser);
sz->sendFile("/home/ich/bootopie-v06-13.jffs2");
connect (sz, SIGNAL(sent()),
this, SLOT(fileTransComplete()));
}
void SenderUI::slotSend() {
QCString str = MultiLineEdit1->text().utf8();
- qWarning("sending: %s", str.data() );
+ owarn << "sending: " << str.data() << "" << oendl;
str = str.replace( QRegExp("\n"), "\r");
ser->send( str );
}
void SenderUI::got(const QByteArray& ar) {
- qWarning("got:");
+ owarn << "got:" << oendl;
for ( uint i = 0; i < ar.count(); i++ ) {
printf("%c", ar[i] );
}
printf("\n");
}
void SenderUI::fileTransComplete() {
- qWarning("file transfer complete");
+ owarn << "file transfer complete" << oendl;
}
void SenderUI::send() {
}
void SenderUI::slotRev(){
-qWarning("Going to receive!");
+owarn << "Going to receive!" << oendl;
FileReceive *rev = new FileReceive( FileReceive::SZ, ser );
rev->receive();
}
diff --git a/noncore/apps/opie-console/widget.cpp b/noncore/apps/opie-console/widget.cpp
index e17dfd4..c51983f 100644
--- a/noncore/apps/opie-console/widget.cpp
+++ b/noncore/apps/opie-console/widget.cpp
@@ -902,236 +902,236 @@ void Widget::setMouseMarks(bool on)
/* ------------------------------------------------------------------------- */
/* */
/* Clipboard */
/* */
/* ------------------------------------------------------------------------- */
#undef KeyPress
void Widget::emitSelection()
// Paste Clipboard by simulating keypress events
{
#ifndef QT_NO_CLIPBOARD
QString text = QApplication::clipboard()->text();
if ( ! text.isNull() )
{
text.replace(QRegExp("\n"), "\r");
QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text);
emit keyPressedSignal(&e); // expose as a big fat keypress event
emit clearSelectionSignal();
}
#endif
}
void Widget::emitText(QString text)
{
QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text);
emit keyPressedSignal(&e); // expose as a big fat keypress event
}
void Widget::pasteClipboard( )
{
emitSelection();
}
void Widget::setSelection(const QString& t)
{
#ifndef QT_NO_CLIPBOARD
// Disconnect signal while WE set the clipboard
QObject *cb = QApplication::clipboard();
QObject::disconnect( cb, SIGNAL(dataChanged()),
this, SLOT(onClearSelection()) );
QApplication::clipboard()->setText(t);
QObject::connect( cb, SIGNAL(dataChanged()),
this, SLOT(onClearSelection()) );
#endif
}
void Widget::onClearSelection()
{
emit clearSelectionSignal();
}
/* ------------------------------------------------------------------------- */
/* */
/* Keyboard */
/* */
/* ------------------------------------------------------------------------- */
//FIXME: an `eventFilter' has been installed instead of a `keyPressEvent'
// due to a bug in `QT' or the ignorance of the author to prevent
// repaint events being emitted to the screen whenever one leaves
// or reenters the screen to/from another application.
//
// Troll says one needs to change focusInEvent() and focusOutEvent(),
// which would also let you have an in-focus cursor and an out-focus
// cursor like xterm does.
// for the auto-hide cursor feature, I added empty focusInEvent() and
// focusOutEvent() so that update() isn't called.
// For auto-hide, we need to get keypress-events, but we only get them when
// we have focus.
void Widget::doScroll(int lines)
{
scrollbar->setValue(scrollbar->value()+lines);
}
bool Widget::eventFilter( QObject *obj, QEvent *e )
{
if ( (e->type() == QEvent::Accel ||
e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) {
static_cast<QKeyEvent *>( e )->ignore();
return true;
}
if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ )
return FALSE; // not us
if ( e->type() == QEvent::Wheel) {
QApplication::sendEvent(scrollbar, e);
}
#ifdef FAKE_CTRL_AND_ALT
static bool control = FALSE;
static bool alt = FALSE;
-// qDebug(" Has a keyboard with no CTRL and ALT keys, but we fake it:");
+// odebug << " Has a keyboard with no CTRL and ALT keys, but we fake it:" << oendl;
bool dele=FALSE;
if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
QKeyEvent* ke = (QKeyEvent*)e;
bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat();
switch (ke->key()) {
case Key_F9: // let this be "Control"
control = keydown;
e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state());
dele=TRUE;
break;
case Key_F13: // let this be "Alt"
alt = keydown;
e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state());
dele=TRUE;
break;
default:
if ( control ) {
int a = toupper(ke->ascii())-64;
if ( a >= 0 && a < ' ' ) {
e = new QKeyEvent(e->type(), ke->key(),
a, ke->state()|ControlButton, QChar(a,0));
dele=TRUE;
}
}
if ( alt ) {
e = new QKeyEvent(e->type(), ke->key(),
ke->ascii(), ke->state()|AltButton, ke->text());
dele=TRUE;
}
}
}
#endif
if ( e->type() == QEvent::KeyPress ) {
QKeyEvent* ke = (QKeyEvent*)e;
actSel=0; // Key stroke implies a screen update, so Widget won't
// know where the current selection is.
-// qDebug("key pressed is 0x%x",ke->key());
+// odebug << "key pressed is 0x" << ke->key() << "" << oendl;
if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker
-// qDebug("key pressed 2 is 0x%x",ke->key());
+// odebug << "key pressed 2 is 0x" << ke->key() << "" << oendl;
emitText("\\"); // expose
} else
emit keyPressedSignal(ke); // expose
ke->accept();
#ifdef FAKE_CTRL_AND_ALT
if ( dele ) delete e;
#endif
return true; // stop the event
}
if ( e->type() == QEvent::Enter ) {
QObject::disconnect( (QObject*)cb, SIGNAL(dataChanged()),
this, SLOT(onClearSelection()) );
}
if ( e->type() == QEvent::Leave ) {
QObject::connect( (QObject*)cb, SIGNAL(dataChanged()),
this, SLOT(onClearSelection()) );
}
return QFrame::eventFilter( obj, e );
}
/* ------------------------------------------------------------------------- */
/* */
/* Frame */
/* */
/* ------------------------------------------------------------------------- */
void Widget::frameChanged()
{
propagateSize();
update();
}
/* ------------------------------------------------------------------------- */
/* */
/* Sound */
/* */
/* ------------------------------------------------------------------------- */
void Widget::Bell()
{
QApplication::beep();
}
/* ------------------------------------------------------------------------- */
/* */
/* Auxiluary */
/* */
/* ------------------------------------------------------------------------- */
void Widget::clearImage()
// initialize the image
// for internal use only
{
for (int y = 0; y < lines; y++)
for (int x = 0; x < columns; x++)
{
image[loc(x,y)].c = 0xff; //' ';
image[loc(x,y)].f = 0xff; //DEFAULT_FORE_COLOR;
image[loc(x,y)].b = 0xff; //DEFAULT_BACK_COLOR;
image[loc(x,y)].r = 0xff; //DEFAULT_RENDITION;
}
}
// Create Image ///////////////////////////////////////////////////////
void Widget::calcGeometry()
{
//FIXME: set rimX == rimY == 0 when running in full screen mode.
scrollbar->resize(QApplication::style().scrollBarExtent().width(),
contentsRect().height());
switch(scrollLoc)
{
case SCRNONE :
columns = ( contentsRect().width() - 2 * rimX ) / font_w;
blX = (contentsRect().width() - (columns*font_w) ) / 2;
brX = blX;
scrollbar->hide();
break;
case SCRLEFT :
columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w;
brX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2;
blX = brX + scrollbar->width();
scrollbar->move(contentsRect().topLeft());
scrollbar->show();
break;
case SCRRIGHT:
columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w;
blX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2;
brX = blX;
scrollbar->move(contentsRect().topRight() - QPoint(scrollbar->width()-1,0));
scrollbar->show();
break;
}
//FIXME: support 'rounding' styles
lines = ( contentsRect().height() - 2 * rimY ) / font_h;
diff --git a/noncore/apps/opie-console/widget_layer.cpp b/noncore/apps/opie-console/widget_layer.cpp
index 96dda1c..ab25919 100644
--- a/noncore/apps/opie-console/widget_layer.cpp
+++ b/noncore/apps/opie-console/widget_layer.cpp
@@ -1,214 +1,214 @@
/* ------------------------------------------------------------------------- */
/* */
/* widget_layer.cpp Widget Layer */
/* */
/* opie developers <opie@handhelds.org> */
/* */
/* ------------------------------------------------------------------------- */
#include "widget_layer.h"
#include <string.h>
//#include <
WidgetLayer::WidgetLayer( const Profile &config, QWidget *parent, const char *name ) : QFrame( parent, name )
{
// get the clipboard
m_clipboard = QApplication::clipboard();
// when data on clipboard changes, clear selection
QObject::connect( (QObject*) m_clipboard, SIGNAL( dataChanged() ),
(QObject*)this, SLOT( onClearSelection() ) );
// initialize vars:
m_lines = 1;
m_columns = 1;
m_resizing = false;
// just for demonstrating
//m_image = QArray<Character>( m_lines * m_columns );
m_image = QArray<Character>( 1 );
// we need to install an event filter,
// to emit keypresses.
qApp->installEventFilter( this );
}
WidgetLayer::~WidgetLayer()
{
// clean up
delete m_image;
}
QSize WidgetLayer::sizeHint()
{
return size();
}
/* --------------------------------- audio ---------------------------------- */
void WidgetLayer::bell()
{
QApplication::beep();
}
bool WidgetLayer::eventFilter( QObject *obj, QEvent *e )
{
if ( (e->type() == QEvent::Accel ||
e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) {
static_cast<QKeyEvent *>( e )->ignore();
return true;
}
if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ )
return false; // not us
#ifdef FAKE_CTRL_AND_ALT
static bool control = false;
static bool alt = false;
-// qDebug(" Has a keyboard with no CTRL and ALT keys, but we fake it:");
+// odebug << " Has a keyboard with no CTRL and ALT keys, but we fake it:" << oendl;
bool dele = false;
if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
QKeyEvent* ke = (QKeyEvent*)e;
bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat();
switch (ke->key()) {
case Key_F9: // let this be "Control"
control = keydown;
e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state());
dele=TRUE;
break;
case Key_F13: // let this be "Alt"
alt = keydown;
e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state());
dele=TRUE;
break;
default:
if ( control ) {
int a = toupper(ke->ascii())-64;
if ( a >= 0 && a < ' ' ) {
e = new QKeyEvent(e->type(), ke->key(),
a, ke->state()|ControlButton,
QChar(a,0));
dele=TRUE;
}
}
if ( alt ) {
e = new QKeyEvent(e->type(), ke->key(),
ke->ascii(), ke->state()|AltButton, ke->text());
dele=TRUE;
}
}
}
#endif
if ( e->type() == QEvent::KeyPress ) {
QKeyEvent* ke = (QKeyEvent*)e;
//actSel=0; // Key stroke implies a screen update, so Widget won't
// know where the current selection is.
-// qDebug("key pressed is 0x%x",ke->key());
+// odebug << "key pressed is 0x" << ke->key() << "" << oendl;
if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker
insertText("\\"); // expose
} else
emit keyPressed( ke ); // expose
ke->accept();
#ifdef FAKE_CTRL_AND_ALT
if ( dele ) delete e;
#endif
return true; // stop the event
}
return QFrame::eventFilter( obj, e );
}
/* --------------------------------- screen --------------------------------- */
void WidgetLayer::propagateSize()
{
QArray<Character> oldimage = m_image.copy();
int oldlines = m_lines;
int oldcolumns = m_columns;
makeImage();
// copy old image, to reduce flicker
if ( ! oldimage.isEmpty() )
{
int lins = QMIN( oldlines, m_lines );
int cols = QMIN( oldcolumns, m_columns );
for ( int lin = 0; lin < lins; ++lin )
{
memcpy( (void*) &m_image[m_columns*lin],
(void*) &oldimage[oldcolumns*lin],
cols*sizeof( Character ) );
}
}
else
clearImage();
delete oldimage;
m_resizing = true;
emit imageSizeChanged( m_lines, m_columns );
m_resizing = false;
}
void WidgetLayer::makeImage()
{
calcGeometry();
m_image = QArray<Character>( m_columns * m_lines );
clearImage();
}
void WidgetLayer::clearImage()
{
//should this belong here??
for ( int y = 0; y < m_lines; y++ )
for ( int x = 0; x < m_columns; x++ )
{
m_image[loc(x,y)].c = 0xff;
m_image[loc(x,y)].f = 0xff;
m_image[loc(x,y)].b = 0xff;
m_image[loc(x,y)].r = 0xff;
}
}
/* --------------------------------- selection ------------------------------ */
void WidgetLayer::pasteClipboard()
{
insertSelection();
}
void WidgetLayer::insertSelection()
{
QString text = QApplication::clipboard()->text();
if ( ! text.isNull() )
{
text.replace( QRegExp( "\n" ), "\r" );
insertText( text );
// selection should be unselected
emit selectionCleared();
}
}
void WidgetLayer::insertText( QString text )
{
// text is inserted as key event
QKeyEvent e( QEvent::KeyPress, 0, -1, 0, text);
emit keyPressed( &e );
}
void WidgetLayer::onClearSelection()
diff --git a/noncore/apps/opie-write/mainwindow.cpp b/noncore/apps/opie-write/mainwindow.cpp
index 90e1a70..aa03060 100644
--- a/noncore/apps/opie-write/mainwindow.cpp
+++ b/noncore/apps/opie-write/mainwindow.cpp
@@ -1,124 +1,128 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** Licensees holding valid Qtopia Developer license may use this
** file in accordance with the Qtopia Developer License Agreement
** provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
** THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
** PURPOSE.
**
** email sales@trolltech.com for information about Qtopia License
** Agreements.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "mainwindow.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/fileselector.h>
#include <qpe/applnk.h>
#include <qpe/resource.h>
#include <qpe/fontdatabase.h>
+using namespace Opie::Core;
-//#include "qspellchecker.h"
+/* QT */
#include "qtextedit.h"
#include <qaction.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qtabwidget.h>
#include <qapplication.h>
#include <qfontdatabase.h>
#include <qcombobox.h>
#include <qlineedit.h>
#include <qfileinfo.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qprinter.h>
#include <qpaintdevicemetrics.h>
#include <qmenubar.h>
#include <qpopupmenu.h>
#include <qcolordialog.h>
#include <qpainter.h>
#include <qstyle.h>
class ButtonMenu : public QToolButton
{
Q_OBJECT
public:
ButtonMenu( QWidget *parent, const char *name=0 )
: QToolButton( parent, name ), current(0)
{
setPopup( new QPopupMenu( this ) );
setPopupDelay( 1 );
connect( popup(), SIGNAL(activated(int)), this, SLOT(selected(int)) );
}
int insertItem(const QIconSet &icon, const QString &text, int id ) {
if ( !popup()->count() ) {
setIconSet( icon );
current = id;
}
return popup()->insertItem( icon, text, id );
}
void setCurrentItem( int id ) {
if ( id != current ) {
current = id;
setIconSet( *popup()->iconSet( id ) );
}
}
virtual QSize sizeHint() const {
return QToolButton::sizeHint() + QSize( 4, 0 );
}
signals:
void activated( int id );
protected slots:
void selected( int id ) {
current = id;
setIconSet( *popup()->iconSet( id ) );
emit activated( id );
}
protected:
virtual void drawButtonLabel( QPainter *p ) {
p->translate( -4, 0 );
QToolButton::drawButtonLabel( p );
p->translate( 4, 0 );
}
private:
int current;
};
//===========================================================================
MainWindow::MainWindow( QWidget *parent, const char *name, WFlags fl )
: QMainWindow( parent, name, fl ),
doc( 0 )
{
setRightJustification(TRUE);
editorStack = new QWidgetStack( this );
fileSelector = new FileSelector( "text/html",
editorStack, "fileselector" );
fileSelector->setCloseVisible( FALSE );
editorStack->addWidget( fileSelector, 0 );
editor = new Qt3::QTextEdit( editorStack );
editor->setTextFormat( Qt::RichText );
editorStack->addWidget( editor, 1 );
setupActions();
QObject::connect( fileSelector, SIGNAL(closeMe()),
@@ -351,224 +355,224 @@ void MainWindow::textFamily( const QString &f )
currentEditor()->setFamily( f );
currentEditor()->viewport()->setFocus();
}
void MainWindow::textSize( const QString &p )
{
if ( !currentEditor() )
return;
currentEditor()->setPointSize( p.toInt() );
currentEditor()->viewport()->setFocus();
}
void MainWindow::textStyle( int i )
{
if ( !currentEditor() )
return;
if ( i == 0 )
currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayBlock,
Qt3::QStyleSheetItem::ListDisc );
else if ( i == 1 )
currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
Qt3::QStyleSheetItem::ListDisc );
else if ( i == 2 )
currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
Qt3::QStyleSheetItem::ListCircle );
else if ( i == 3 )
currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
Qt3::QStyleSheetItem::ListSquare );
else if ( i == 4 )
currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
Qt3::QStyleSheetItem::ListDecimal );
else if ( i == 5 )
currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
Qt3::QStyleSheetItem::ListLowerAlpha );
else if ( i == 6 )
currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
Qt3::QStyleSheetItem::ListUpperAlpha );
currentEditor()->viewport()->setFocus();
}
void MainWindow::textAlign( int a )
{
if ( !currentEditor() )
return;
editor->setAlignment( a );
}
void MainWindow::fontChanged( const QFont &f )
{
comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( f.family() ) ) );
updateFontSizeCombo( f );
comboSize->lineEdit()->setText( QString::number( f.pointSize() ) );
actionTextBold->setOn( f.bold() );
actionTextItalic->setOn( f.italic() );
actionTextUnderline->setOn( f.underline() );
}
void MainWindow::colorChanged( const QColor & )
{
}
void MainWindow::alignmentChanged( int a )
{
if ( ( a == Qt3::AlignAuto ) || ( a & AlignLeft )) {
alignMenu->setCurrentItem(AlignLeft);
} else if ( ( a & AlignCenter ) ) {
alignMenu->setCurrentItem(AlignCenter);
} else if ( ( a & AlignRight ) ) {
alignMenu->setCurrentItem(AlignRight);
} else if ( ( a & Qt3::AlignJustify ) ) {
alignMenu->setCurrentItem(Qt3::AlignJustify);
}
}
void MainWindow::editorChanged( QWidget * )
{
if ( !currentEditor() )
return;
fontChanged( currentEditor()->font() );
colorChanged( currentEditor()->color() );
alignmentChanged( currentEditor()->alignment() );
}
void MainWindow::fileOpen()
{
save();
editorStack->raiseWidget( fileSelector );
fileSelector->reread();
hideEditTools();
fileSelector->setNewVisible( TRUE );
clear();
updateCaption();
}
void MainWindow::fileRevert()
{
- qDebug( "QMainWindow::fileRevert needs to be done" );
+ odebug << "QMainWindow::fileRevert needs to be done" << oendl;
}
void MainWindow::fileNew()
{
editor->setTextFormat( Qt::RichText );
save();
newFile(DocLnk());
}
void MainWindow::insertTable()
{
- qDebug( "MainWindow::insertTable() needs to be done" );
+ odebug << "MainWindow::insertTable() needs to be done" << oendl;
}
void MainWindow::newFile( const DocLnk &dl )
{
DocLnk nf = dl;
nf.setType( "text/html" );
clear();
editorStack->raiseWidget( editor );
editor->viewport()->setFocus();
doc = new DocLnk( nf );
updateCaption();
}
void MainWindow::openFile( const DocLnk &dl )
{
FileManager fm;
QString txt;
if ( !fm.loadFile( dl, txt ) )
- qDebug( "couldn't open file" );
+ odebug << "couldn't open file" << oendl;
clear();
editorStack->raiseWidget( editor );
editor->viewport()->setFocus();
doc = new DocLnk( dl );
editor->setText( txt );
editor->setModified( FALSE );
updateCaption();
}
void MainWindow::showEditTools( void )
{
tbMenu->show();
tbEdit->show();
tbFont->show();
tbStyle->show();
}
void MainWindow::hideEditTools( void )
{
// let's reset the buttons...
actionTextBold->setOn( FALSE );
actionTextItalic->setOn( FALSE );
actionTextUnderline->setOn( FALSE );
//comboFont->setCurrentText( QApplication::font().family() );
comboSize->lineEdit()->setText( QString::number(QApplication::font().pointSize() ) );
tbMenu->hide();
tbEdit->hide();
tbFont->hide();
tbStyle->hide();
}
void MainWindow::save()
{
if ( !doc )
return;
if ( !editor->isModified() )
return;
QString rt = editor->text();
// quick hack to get around formatting...
editor->setTextFormat( Qt::PlainText );
QString pt = editor->text();
editor->setTextFormat( Qt::RichText );
if ( doc->name().isEmpty() ) {
unsigned ispace = pt.find( ' ' );
unsigned ienter = pt.find( '\n' );
int i = (ispace < ienter) ? ispace : ienter;
QString docname;
if ( i == -1 ) {
if ( pt.isEmpty() )
docname = "Empty Text";
else
docname = pt;
} else {
docname = pt.left( i );
}
doc->setName(docname);
}
FileManager fm;
fm.saveFile( *doc, rt );
}
void MainWindow::clear()
{
delete doc;
doc = 0;
editor->clear();
}
void MainWindow::updateCaption()
{
if ( !doc )
setCaption( tr("Rich Text Editor") );
else {
QString s = doc->name();
if ( s.isEmpty() )
s = tr( "Unnamed" );
setCaption( s + " - " + tr("Rich Text Editor") );
}
}
void MainWindow::closeEvent( QCloseEvent *e )
{
if ( editorStack->visibleWidget() == editor ) {
// call fileOpen instead, don't close it
fileOpen();
e->ignore();
} else {
e->accept();
}
}
#include "mainwindow.moc"
diff --git a/noncore/apps/opie-write/opie-write.pro b/noncore/apps/opie-write/opie-write.pro
index 044ce7e..8e514d4 100644
--- a/noncore/apps/opie-write/opie-write.pro
+++ b/noncore/apps/opie-write/opie-write.pro
@@ -1,27 +1,26 @@
-CONFIG += qt warn on quick-app
-
+CONFIG += qt warn on quick-app
HEADERS = qcleanuphandler.h \
qcomplextext_p.h \
qrichtext_p.h \
qstylesheet.h \
qtextedit.h \
mainwindow.h
SOURCES = qcomplextext.cpp \
qstylesheet.cpp \
qrichtext_p.cpp \
qrichtext.cpp \
qtextedit.cpp \
main.cpp \
mainwindow.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
LIBS += -lqpe -lopiecore2
TARGET = opie-write
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/opie-write/qcomplextext.cpp b/noncore/apps/opie-write/qcomplextext.cpp
index 473f184..00a91c5 100644
--- a/noncore/apps/opie-write/qcomplextext.cpp
+++ b/noncore/apps/opie-write/qcomplextext.cpp
@@ -13,134 +13,134 @@
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "qrichtext_p.h"
#include <stdlib.h>
using namespace Qt3;
// -----------------------------------------------------
/* a small helper class used internally to resolve Bidi embedding levels.
Each line of text caches the embedding level at the start of the line for faster
relayouting
*/
QBidiContext::QBidiContext( uchar l, QChar::Direction e, QBidiContext *p, bool o )
: level(l) , override(o), dir(e)
{
if ( p )
p->ref();
parent = p;
count = 0;
}
QBidiContext::~QBidiContext()
{
if( parent && parent->deref() )
delete parent;
}
/*
Arabic shaping obeys a number of rules according to the joining classes (see Unicode book, section on
arabic).
Each unicode char has a joining class (right, dual (left&right), center (joincausing) or transparent).
transparent joining is not encoded in QChar::joining(), but applies to all combining marks and format marks.
Right join-causing: dual + center
Left join-causing: dual + right + center
Rules are as follows (for a string already in visual order, as we have it here):
R1 Transparent characters do not affect joining behaviour.
R2 A right joining character, that has a right join-causing char on the right will get form XRight
(R3 A left joining character, that has a left join-causing char on the left will get form XLeft)
Note: the above rule is meaningless, as there are no pure left joining characters defined in Unicode
R4 A dual joining character, that has a left join-causing char on the left and a right join-causing char on
the right will get form XMedial
R5 A dual joining character, that has a right join causing char on the right, and no left join causing char on the left
will get form XRight
R6 A dual joining character, that has a left join causing char on the left, and no right join causing char on the right
will get form XLeft
R7 Otherwise the character will get form XIsolated
Additionally we have to do the minimal ligature support for lam-alef ligatures:
L1 Transparent characters do not affect ligature behaviour.
L2 Any sequence of Alef(XRight) + Lam(XMedial) will form the ligature Alef.Lam(XLeft)
L3 Any sequence of Alef(XRight) + Lam(XLeft) will form the ligature Alef.Lam(XIsolated)
The two functions defined in this class do shaping in visual and logical order. For logical order just replace right with
previous and left with next in the above rules ;-)
*/
/*
Two small helper functions for arabic shaping. They get the next shape causing character on either
side of the char in question. Implements rule R1.
leftChar() returns true if the char to the left is a left join-causing char
rightChar() returns true if the char to the right is a right join-causing char
*/
static inline const QChar *prevChar( const QString &str, int pos )
{
- //qDebug("leftChar: pos=%d", pos);
+ //odebug << "leftChar: pos=" << pos << "" << oendl;
pos--;
const QChar *ch = str.unicode() + pos;
while( pos > -1 ) {
if( !ch->isMark() )
return ch;
pos--;
ch--;
}
return &QChar::replacement;
}
static inline const QChar *nextChar( const QString &str, int pos)
{
pos++;
int len = str.length();
const QChar *ch = str.unicode() + pos;
while( pos < len ) {
- //qDebug("rightChar: %d isLetter=%d, joining=%d", pos, ch.isLetter(), ch.joining());
+ //odebug << "rightChar: " << pos << " isLetter=" << ch.isLetter() << ", joining=" << ch.joining() << "" << oendl;
if( !ch->isMark() )
return ch;
// assume it's a transparent char, this might not be 100% correct
pos++;
ch++;
}
return &QChar::replacement;
}
static inline bool prevVisualCharJoins( const QString &str, int pos)
{
return ( prevChar( str, pos )->joining() != QChar::OtherJoining );
}
static inline bool nextVisualCharJoins( const QString &str, int pos)
{
QChar::Joining join = nextChar( str, pos )->joining();
return ( join == QChar::Dual || join == QChar::Center );
}
diff --git a/noncore/apps/opie-write/qrichtext.cpp b/noncore/apps/opie-write/qrichtext.cpp
index b77a0fc..c27eb1e 100644
--- a/noncore/apps/opie-write/qrichtext.cpp
+++ b/noncore/apps/opie-write/qrichtext.cpp
@@ -1,311 +1,317 @@
/****************************************************************************
** $Id$
**
** Implementation of the internal Qt classes dealing with rich text
**
** Created : 990101
**
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "qrichtext_p.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include "qdragobject.h"
#include "qpaintdevicemetrics.h"
#include "qdrawutil.h"
#include "qcleanuphandler.h"
+/* STD */
#include <stdlib.h>
using namespace Qt3;
static QTextCursor* richTextExportStart = 0;
static QTextCursor* richTextExportEnd = 0;
static QTextFormatCollection *qFormatCollection = 0;
const int border_tolerance = 2;
#ifdef Q_WS_WIN
#include "qt_windows.h"
#endif
#define QChar_linesep QChar(0x2028U)
static inline bool is_printer( QPainter *p )
{
if ( !p || !p->device() )
return FALSE;
return p->device()->devType() == QInternal::Printer;
}
static inline int scale( int value, QPainter *painter )
{
if ( is_printer( painter ) ) {
QPaintDeviceMetrics metrics( painter->device() );
#if defined(Q_WS_X11)
value = value * metrics.logicalDpiY() / QPaintDevice::x11AppDpiY();
#elif defined (Q_WS_WIN)
HDC hdc = GetDC( 0 );
int gdc = GetDeviceCaps( hdc, LOGPIXELSY );
if ( gdc )
value = value * metrics.logicalDpiY() / gdc;
ReleaseDC( 0, hdc );
#elif defined (Q_WS_MAC)
value = value * metrics.logicalDpiY() / 75; // ##### FIXME
#elif defined (Q_WS_QWS)
value = value * metrics.logicalDpiY() / 75;
#endif
}
return value;
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void QTextCommandHistory::addCommand( QTextCommand *cmd )
{
if ( current < (int)history.count() - 1 ) {
QPtrList<QTextCommand> commands;
commands.setAutoDelete( FALSE );
for( int i = 0; i <= current; ++i ) {
commands.insert( i, history.at( 0 ) );
history.take( 0 );
}
commands.append( cmd );
history.clear();
history = commands;
history.setAutoDelete( TRUE );
} else {
history.append( cmd );
}
if ( (int)history.count() > steps )
history.removeFirst();
else
++current;
}
QTextCursor *QTextCommandHistory::undo( QTextCursor *c )
{
if ( current > -1 ) {
QTextCursor *c2 = history.at( current )->unexecute( c );
--current;
return c2;
}
return 0;
}
QTextCursor *QTextCommandHistory::redo( QTextCursor *c )
{
if ( current > -1 ) {
if ( current < (int)history.count() - 1 ) {
++current;
return history.at( current )->execute( c );
}
} else {
if ( history.count() > 0 ) {
++current;
return history.at( current )->execute( c );
}
}
return 0;
}
bool QTextCommandHistory::isUndoAvailable()
{
return current > -1;
}
bool QTextCommandHistory::isRedoAvailable()
{
return current > -1 && current < (int)history.count() - 1 || current == -1 && history.count() > 0;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
QTextDeleteCommand::QTextDeleteCommand( QTextDocument *d, int i, int idx, const QMemArray<QTextStringChar> &str,
const QByteArray& oldStyleInfo )
: QTextCommand( d ), id( i ), index( idx ), parag( 0 ), text( str ), styleInformation( oldStyleInfo )
{
for ( int j = 0; j < (int)text.size(); ++j ) {
if ( text[ j ].format() )
text[ j ].format()->addRef();
}
}
QTextDeleteCommand::QTextDeleteCommand( QTextParagraph *p, int idx, const QMemArray<QTextStringChar> &str )
: QTextCommand( 0 ), id( -1 ), index( idx ), parag( p ), text( str )
{
for ( int i = 0; i < (int)text.size(); ++i ) {
if ( text[ i ].format() )
text[ i ].format()->addRef();
}
}
QTextDeleteCommand::~QTextDeleteCommand()
{
for ( int i = 0; i < (int)text.size(); ++i ) {
if ( text[ i ].format() )
text[ i ].format()->removeRef();
}
text.resize( 0 );
}
QTextCursor *QTextDeleteCommand::execute( QTextCursor *c )
{
QTextParagraph *s = doc ? doc->paragAt( id ) : parag;
if ( !s ) {
- qWarning( "can't locate parag at %d, last parag: %d", id, doc->lastParagraph()->paragId() );
+ owarn << "can't locate parag at " << id << ", last parag: " << doc->lastParagraph()->paragId() << "" << oendl;
return 0;
}
cursor.setParagraph( s );
cursor.setIndex( index );
int len = text.size();
if ( c )
*c = cursor;
if ( doc ) {
doc->setSelectionStart( QTextDocument::Temp, cursor );
for ( int i = 0; i < len; ++i )
cursor.gotoNextLetter();
doc->setSelectionEnd( QTextDocument::Temp, cursor );
doc->removeSelectedText( QTextDocument::Temp, &cursor );
if ( c )
*c = cursor;
} else {
s->remove( index, len );
}
return c;
}
QTextCursor *QTextDeleteCommand::unexecute( QTextCursor *c )
{
QTextParagraph *s = doc ? doc->paragAt( id ) : parag;
if ( !s ) {
- qWarning( "can't locate parag at %d, last parag: %d", id, doc->lastParagraph()->paragId() );
+ owarn << "can't locate parag at " << id << ", last parag: " << doc->lastParagraph()->paragId() << "" << oendl;
return 0;
}
cursor.setParagraph( s );
cursor.setIndex( index );
QString str = QTextString::toString( text );
cursor.insert( str, TRUE, &text );
cursor.setParagraph( s );
cursor.setIndex( index );
if ( c ) {
c->setParagraph( s );
c->setIndex( index );
for ( int i = 0; i < (int)text.size(); ++i )
c->gotoNextLetter();
}
if ( !styleInformation.isEmpty() ) {
QDataStream styleStream( styleInformation, IO_ReadOnly );
int num;
styleStream >> num;
QTextParagraph *p = s;
while ( num-- && p ) {
p->readStyleInformation( styleStream );
p = p->next();
}
}
s = cursor.paragraph();
while ( s ) {
s->format();
s->setChanged( TRUE );
if ( s == c->paragraph() )
break;
s = s->next();
}
return &cursor;
}
QTextFormatCommand::QTextFormatCommand( QTextDocument *d, int sid, int sidx, int eid, int eidx,
const QMemArray<QTextStringChar> &old, QTextFormat *f, int fl )
: QTextCommand( d ), startId( sid ), startIndex( sidx ), endId( eid ), endIndex( eidx ), format( f ), oldFormats( old ), flags( fl )
{
format = d->formatCollection()->format( f );
for ( int j = 0; j < (int)oldFormats.size(); ++j ) {
if ( oldFormats[ j ].format() )
oldFormats[ j ].format()->addRef();
}
}
QTextFormatCommand::~QTextFormatCommand()
{
format->removeRef();
for ( int j = 0; j < (int)oldFormats.size(); ++j ) {
if ( oldFormats[ j ].format() )
oldFormats[ j ].format()->removeRef();
}
}
QTextCursor *QTextFormatCommand::execute( QTextCursor *c )
{
QTextParagraph *sp = doc->paragAt( startId );
QTextParagraph *ep = doc->paragAt( endId );
if ( !sp || !ep )
return c;
QTextCursor start( doc );
start.setParagraph( sp );
start.setIndex( startIndex );
QTextCursor end( doc );
end.setParagraph( ep );
end.setIndex( endIndex );
doc->setSelectionStart( QTextDocument::Temp, start );
doc->setSelectionEnd( QTextDocument::Temp, end );
doc->setFormat( QTextDocument::Temp, format, flags );
doc->removeSelection( QTextDocument::Temp );
if ( endIndex == ep->length() )
end.gotoLeft();
*c = end;
return c;
}
QTextCursor *QTextFormatCommand::unexecute( QTextCursor *c )
{
QTextParagraph *sp = doc->paragAt( startId );
QTextParagraph *ep = doc->paragAt( endId );
if ( !sp || !ep )
return 0;
int idx = startIndex;
int fIndex = 0;
for ( ;; ) {
if ( oldFormats.at( fIndex ).c == '\n' ) {
if ( idx > 0 ) {
if ( idx < sp->length() && fIndex > 0 )
sp->setFormat( idx, 1, oldFormats.at( fIndex - 1 ).format() );
@@ -1451,196 +1457,196 @@ void QTextDocument::setRichTextInternal( const QString &text, QTextCursor* curso
NEWPAR;
}
// set rtext spacing to FALSE for the initial paragraph.
curpar->rtext = FALSE;
QString wellKnownTags = "br hr wsp table qt body meta title";
while ( pos < length ) {
if ( hasPrefix(doc, length, pos, '<' ) ){
if ( !hasPrefix( doc, length, pos+1, QChar('/') ) ) {
// open tag
QMap<QString, QString> attr;
bool emptyTag = FALSE;
QString tagname = parseOpenTag(doc, length, pos, attr, emptyTag);
if ( tagname.isEmpty() )
continue; // nothing we could do with this, probably parse error
const QStyleSheetItem* nstyle = sheet_->item(tagname);
if ( nstyle ) {
// we might have to close some 'forgotten' tags
while ( !nstyle->allowedInContext( curtag.style ) ) {
QString msg;
msg.sprintf( "QText Warning: Document not valid ( '%s' not allowed in '%s' #%d)",
tagname.ascii(), curtag.style->name().ascii(), pos);
sheet_->error( msg );
if ( tags.isEmpty() )
break;
curtag = tags.pop();
}
/* special handling for p and li for HTML
compatibility. We do not want to embed blocks in
p, and we do not want new blocks inside non-empty
lis. Plus we want to merge empty lis sometimes. */
if( nstyle->displayMode() == QStyleSheetItem::DisplayListItem ) {
canMergeLi = TRUE;
} else if ( nstyle->displayMode() == QStyleSheetItem::DisplayBlock ) {
while ( curtag.style->name() == "p" ) {
if ( tags.isEmpty() )
break;
curtag = tags.pop();
}
if ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ) {
// we are in a li and a new block comes along
if ( nstyle->name() == "ul" || nstyle->name() == "ol" )
hasNewPar = FALSE; // we want an empty li (like most browsers)
if ( !hasNewPar ) {
/* do not add new blocks inside
non-empty lis */
while ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ) {
if ( tags.isEmpty() )
break;
curtag = tags.pop();
}
} else if ( canMergeLi ) {
/* we have an empty li and a block
comes along, merge them */
nstyle = curtag.style;
}
canMergeLi = FALSE;
}
}
}
QTextCustomItem* custom = 0;
// some well-known tags, some have a nstyle, some not
if ( wellKnownTags.find( tagname ) != -1 ) {
if ( tagname == "br" ) {
emptyTag = space = TRUE;
int index = QMAX( curpar->length(),1) - 1;
QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor );
curpar->append( QChar_linesep );
curpar->setFormat( index, 1, &format );
} else if ( tagname == "hr" ) {
emptyTag = space = TRUE;
custom = sheet_->tag( tagname, attr, contxt, *factory_ , emptyTag, this );
NEWPAR;
} else if ( tagname == "table" ) {
emptyTag = space = TRUE;
QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor );
curpar->setAlignment( curtag.alignment );
custom = parseTable( attr, format, doc, length, pos, curpar );
} else if ( tagname == "qt" || tagname == "body" ) {
if ( attr.contains( "bgcolor" ) ) {
QBrush *b = new QBrush( QColor( attr["bgcolor"] ) );
setPaper( b );
}
if ( attr.contains( "background" ) ) {
QImage img;
QString bg = attr["background"];
const QMimeSource* m = factory_->data( bg, contxt );
if ( !m ) {
- qWarning("QRichText: no mimesource for %s", bg.latin1() );
+ owarn << "QRichText: no mimesource for " << bg.latin1() << "" << oendl;
} else {
if ( !QImageDrag::decode( m, img ) ) {
- qWarning("QTextImage: cannot decode %s", bg.latin1() );
+ owarn << "QTextImage: cannot decode " << bg.latin1() << "" << oendl;
}
}
if ( !img.isNull() ) {
QPixmap pm;
pm.convertFromImage( img );
QBrush *b = new QBrush( QColor(), pm );
setPaper( b );
}
}
if ( attr.contains( "text" ) ) {
QColor c( attr["text"] );
if ( formatCollection()->defaultFormat()->color() != c ) {
QDict<QTextFormat> formats = formatCollection()->dict();
QDictIterator<QTextFormat> it( formats );
while ( it.current() ) {
if ( it.current() == formatCollection()->defaultFormat() ) {
++it;
continue;
}
it.current()->setColor( c );
++it;
}
formatCollection()->defaultFormat()->setColor( c );
curtag.format.setColor( c );
}
}
if ( attr.contains( "link" ) )
linkColor = QColor( attr["link"] );
if ( attr.contains( "title" ) )
attribs.replace( "title", attr["title"] );
if ( textEditMode ) {
if ( attr.contains("style" ) ) {
QString a = attr["style"];
for ( int s = 0; s < a.contains(';')+1; s++ ) {
QString style = QTextDocument::section( a, ";", s, s );
if ( style.startsWith("font-size:" ) && QTextDocument::endsWith(style, "pt") ) {
scaleFontsFactor = double( formatCollection()->defaultFormat()->fn.pointSize() ) /
style.mid( 10, style.length() - 12 ).toInt();
}
}
}
nstyle = 0; // ignore body in textEditMode
}
// end qt- and body-tag handling
} else if ( tagname == "meta" ) {
if ( attr["name"] == "qrichtext" && attr["content"] == "1" )
textEditMode = TRUE;
} else if ( tagname == "title" ) {
QString title;
while ( pos < length ) {
if ( hasPrefix( doc, length, pos, QChar('<') ) && hasPrefix( doc, length, pos+1, QChar('/') ) &&
parseCloseTag( doc, length, pos ) == "title" )
break;
title += doc[ pos ];
++pos;
}
attribs.replace( "title", title );
}
} // end of well-known tag handling
if ( !custom ) // try generic custom item
custom = sheet_->tag( tagname, attr, contxt, *factory_ , emptyTag, this );
if ( !nstyle && !custom ) // we have no clue what this tag could be, ignore it
continue;
if ( custom ) {
int index = QMAX( curpar->length(),1) - 1;
QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor );
curpar->append( QChar('*') );
curpar->setFormat( index, 1, &format );
curpar->at( index )->setCustomItem( custom );
if ( !curtag.anchorHref.isEmpty() )
curpar->at(index)->setAnchor( QString::null, curtag.anchorHref );
if ( !anchorName.isEmpty() ) {
curpar->at(index)->setAnchor( anchorName, curpar->at(index)->anchorHref() );
anchorName = QString::null;
}
registerCustomItem( custom, curpar );
hasNewPar = FALSE;
} else if ( !emptyTag ) {
/* if we do nesting, push curtag on the stack,
otherwise reinint curag. */
if ( curtag.style->name() != tagname || nstyle->selfNesting() ) {
tags.push( curtag );
} else {
if ( !tags.isEmpty() )
curtag = tags.top();
else
curtag = initag;
}
curtag.name = tagname;
curtag.style = nstyle;
curtag.name = tagname;
@@ -2059,193 +2065,193 @@ QString QTextDocument::plainText() const
} else {
s += p->at( i )->c;
}
}
}
s.remove( s.length() - 1, 1 );
if ( p->next() )
s += "\n";
buffer += s;
p = p->next();
}
return buffer;
}
static QString align_to_string( int a )
{
if ( a & Qt::AlignRight )
return " align=\"right\"";
if ( a & Qt::AlignHCenter )
return " align=\"center\"";
if ( a & Qt3::AlignJustify )
return " align=\"justify\"";
return QString::null;
}
static QString direction_to_string( int d )
{
if ( d != QChar::DirON )
return ( d == QChar::DirL? " dir=\"ltr\"" : " dir=\"rtl\"" );
return QString::null;
}
static QString list_value_to_string( int v )
{
if ( v != -1 )
return " listvalue=\"" + QString::number( v ) + "\"";
return QString::null;
}
static QString list_style_to_string( int v )
{
switch( v ) {
case QStyleSheetItem::ListDecimal: return "\"1\"";
case QStyleSheetItem::ListLowerAlpha: return "\"a\"";
case QStyleSheetItem::ListUpperAlpha: return "\"A\"";
case QStyleSheetItem::ListDisc: return "\"disc\"";
case QStyleSheetItem::ListSquare: return "\"square\"";
case QStyleSheetItem::ListCircle: return "\"circle\"";
default:
return QString::null;
}
}
static inline bool list_is_ordered( int v )
{
return v == QStyleSheetItem::ListDecimal ||
v == QStyleSheetItem::ListLowerAlpha ||
v == QStyleSheetItem::ListUpperAlpha;
}
static QString margin_to_string( QStyleSheetItem* style, int t, int b, int l, int r, int fl )
{
QString s;
if ( l > 0 )
s += QString(!!s?";":"") + "margin-left:" + QString::number(l+QMAX(0,style->margin(QStyleSheetItem::MarginLeft))) + "px";
if ( r > 0 )
s += QString(!!s?";":"") + "margin-right:" + QString::number(r+QMAX(0,style->margin(QStyleSheetItem::MarginRight))) + "px";
if ( t > 0 )
s += QString(!!s?";":"") + "margin-top:" + QString::number(t+QMAX(0,style->margin(QStyleSheetItem::MarginTop))) + "px";
if ( b > 0 )
s += QString(!!s?";":"") + "margin-bottom:" + QString::number(b+QMAX(0,style->margin(QStyleSheetItem::MarginBottom))) + "px";
if ( fl > 0 )
s += QString(!!s?";":"") + "text-indent:" + QString::number(fl+QMAX(0,style->margin(QStyleSheetItem::MarginFirstLine))) + "px";
if ( !!s )
return " style=\"" + s + "\"";
return QString::null;
}
QString QTextDocument::richText() const
{
QString s = "";
if ( !par ) {
s += "<html><head><meta name=\"qrichtext\" content=\"1\" /></head><body style=\"font-size:" ;
s += QString::number( formatCollection()->defaultFormat()->font().pointSize() );
s += "pt;font-family:";
s += formatCollection()->defaultFormat()->font().family();
s +="\">";
}
QTextParagraph* p = fParag;
QStyleSheetItem* item_p = styleSheet()->item("p");
QStyleSheetItem* item_ul = styleSheet()->item("ul");
QStyleSheetItem* item_ol = styleSheet()->item("ol");
QStyleSheetItem* item_li = styleSheet()->item("li");
if ( !item_p || !item_ul || !item_ol || !item_li ) {
- qWarning( "QTextEdit: cannot export HTML due to insufficient stylesheet (lack of p, ul, ol, or li)" );
+ owarn << "QTextEdit: cannot export HTML due to insufficient stylesheet (lack of p, ul, ol, or li)" << oendl;
return QString::null;
}
int pastListDepth = 0;
int listDepth = 0;
int futureListDepth = 0;
QMemArray<int> listStyles(10);
while ( p ) {
listDepth = p->listDepth();
if ( listDepth < pastListDepth ) {
for ( int i = listDepth+1; i <= pastListDepth; i++ )
s += list_is_ordered( listStyles[i] ) ? "</ol>" : "</ul>";
s += '\n';
} else if ( listDepth > pastListDepth ) {
s += '\n';
listStyles.resize( QMAX( (int)listStyles.size(), listDepth+1 ) );
QString list_type;
listStyles[listDepth] = p->listStyle();
if ( !list_is_ordered( p->listStyle() ) || item_ol->listStyle() != p->listStyle() )
list_type = " type=" + list_style_to_string( p->listStyle() );
for ( int i = pastListDepth; i < listDepth; i++ ) {
s += list_is_ordered( p->listStyle() ) ? "<ol" : "<ul" ;
s += list_type + ">";
}
} else {
s += '\n';
}
QString ps = p->richText();
// for the bottom margin we need to know whether we are at the end of a list
futureListDepth = 0;
if ( listDepth > 0 && p->next() )
futureListDepth = p->next()->listDepth();
if ( richTextExportStart && richTextExportStart->paragraph() ==p &&
richTextExportStart->index() == 0 )
s += "<selstart/>";
if ( p->isListItem() ) {
s += "<li";
if ( p->listStyle() != listStyles[listDepth] )
s += " type=" + list_style_to_string( p->listStyle() );
s +=align_to_string( p->alignment() );
s += margin_to_string( item_li, p->utm, p->ubm, p->ulm, p->urm, p->uflm );
s += list_value_to_string( p->listValue() );
s += direction_to_string( p->direction() );
s +=">";
s += ps;
s += "</li>";
} else {
// normal paragraph item
s += "<p";
s += align_to_string( p->alignment() );
s += margin_to_string( item_p, p->utm, p->ubm, p->ulm, p->urm, p->uflm );
s +=direction_to_string( p->direction() );
s += ">";
s += ps;
s += "</p>";
}
pastListDepth = listDepth;
p = p->next();
}
while ( listDepth > 0 ) {
s += list_is_ordered( listStyles[listDepth] ) ? "</ol>" : "</ul>";
listDepth--;
}
if ( !par )
s += "\n</body></html>\n";
return s;
}
QString QTextDocument::text() const
{
if ( txtFormat == Qt::AutoText && preferRichText || txtFormat == Qt::RichText )
return richText();
return plainText();
}
QString QTextDocument::text( int parag ) const
{
QTextParagraph *p = paragAt( parag );
if ( !p )
return QString::null;
if ( txtFormat == Qt::AutoText && preferRichText || txtFormat == Qt::RichText )
return p->richText();
else
return p->string()->toString();
}
void QTextDocument::invalidate()
{
QTextParagraph *s = fParag;
@@ -4003,246 +4009,246 @@ void QTextParagraph::format( int start, bool doMove )
// with has to be the full document width on mac as the selections
// always extend completely to the right. This is a bit unefficient,
// as this results in a bigger double buffer than needed but ok for
// now.
if ( lineStarts.count() == 1 ) {
if ( !string()->isBidi() ) {
c = &str->at( str->length() - 1 );
r.setWidth( c->x + str->width( str->length() - 1 ) );
} else {
r.setWidth( lineStarts[0]->w );
}
}
if ( !hasdoc ) { // qt_format_text bounding rect handling
it = lineStarts.begin();
int usedw = 0;
for ( ; it != lineStarts.end(); ++it )
usedw = QMAX( usedw, (*it)->w );
if ( r.width() <= 0 ) {
// if the user specifies an invalid rect, this means that the
// bounding box should grow to the width that the text actually
// needs
r.setWidth( usedw );
} else {
r.setWidth( QMIN( usedw, r.width() ) );
}
}
if ( y != r.height() )
r.setHeight( y );
if ( !visible ) {
r.setHeight( 0 );
} else {
int minw = formatter()->minimumWidth();
int wused = formatter()->widthUsed();
wused = QMAX( minw, wused );
if ( hasdoc ) {
document()->setMinimumWidth( minw, wused, this );
} else {
pseudoDocument()->minw = QMAX( pseudoDocument()->minw, minw );
pseudoDocument()->wused = QMAX( pseudoDocument()->wused, wused );
}
}
// do page breaks if required
if ( hasdoc && document()->isPageBreakEnabled() ) {
int shift = document()->formatter()->formatVertically( document(), this );
if ( shift && !formattedAgain ) {
formattedAgain = TRUE;
goto formatAgain;
}
}
if ( n && doMove && n->invalid == -1 && r.y() + r.height() != n->r.y() ) {
int dy = ( r.y() + r.height() ) - n->r.y();
QTextParagraph *s = n;
bool makeInvalid = p && p->lastInFrame;
while ( s && dy ) {
if ( !s->isFullWidth() )
makeInvalid = TRUE;
if ( makeInvalid )
s->invalidate( 0 );
s->move( dy );
if ( s->lastInFrame )
makeInvalid = TRUE;
s = s->n;
}
}
firstFormat = FALSE;
changed = TRUE;
invalid = -1;
//##### string()->setTextChanged( FALSE );
}
int QTextParagraph::lineHeightOfChar( int i, int *bl, int *y ) const
{
if ( !isValid() )
( (QTextParagraph*)this )->format();
QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.end();
--it;
for ( ;; ) {
if ( i >= it.key() ) {
if ( bl )
*bl = ( *it )->baseLine;
if ( y )
*y = ( *it )->y;
return ( *it )->h;
}
if ( it == lineStarts.begin() )
break;
--it;
}
- qWarning( "QTextParagraph::lineHeightOfChar: couldn't find lh for %d", i );
+ owarn << "QTextParagraph::lineHeightOfChar: couldn't find lh for " << i << "" << oendl;
return 15;
}
QTextStringChar *QTextParagraph::lineStartOfChar( int i, int *index, int *line ) const
{
if ( !isValid() )
( (QTextParagraph*)this )->format();
int l = (int)lineStarts.count() - 1;
QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.end();
--it;
for ( ;; ) {
if ( i >= it.key() ) {
if ( index )
*index = it.key();
if ( line )
*line = l;
return &str->at( it.key() );
}
if ( it == lineStarts.begin() )
break;
--it;
--l;
}
- qWarning( "QTextParagraph::lineStartOfChar: couldn't find %d", i );
+ owarn << "QTextParagraph::lineStartOfChar: couldn't find " << i << "" << oendl;
return 0;
}
int QTextParagraph::lines() const
{
if ( !isValid() )
( (QTextParagraph*)this )->format();
return (int)lineStarts.count();
}
QTextStringChar *QTextParagraph::lineStartOfLine( int line, int *index ) const
{
if ( !isValid() )
( (QTextParagraph*)this )->format();
if ( line >= 0 && line < (int)lineStarts.count() ) {
QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
while ( line-- > 0 )
++it;
int i = it.key();
if ( index )
*index = i;
return &str->at( i );
}
- qWarning( "QTextParagraph::lineStartOfLine: couldn't find %d", line );
+ owarn << "QTextParagraph::lineStartOfLine: couldn't find " << line << "" << oendl;
return 0;
}
int QTextParagraph::leftGap() const
{
if ( !isValid() )
( (QTextParagraph*)this )->format();
int line = 0;
int x = str->at(0).x; /* set x to x of first char */
if ( str->isBidi() ) {
for ( int i = 1; i < str->length()-1; ++i )
x = QMIN(x, str->at(i).x);
return x;
}
QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
while (line < (int)lineStarts.count()) {
int i = it.key(); /* char index */
x = QMIN(x, str->at(i).x);
++it;
++line;
}
return x;
}
void QTextParagraph::setFormat( int index, int len, QTextFormat *f, bool useCollection, int flags )
{
if ( !f )
return;
if ( index < 0 )
index = 0;
if ( index > str->length() - 1 )
index = str->length() - 1;
if ( index + len >= str->length() )
len = str->length() - index;
QTextFormatCollection *fc = 0;
if ( useCollection )
fc = formatCollection();
QTextFormat *of;
for ( int i = 0; i < len; ++i ) {
of = str->at( i + index ).format();
if ( !changed && f->key() != of->key() )
changed = TRUE;
if ( invalid == -1 &&
( f->font().family() != of->font().family() ||
f->font().pointSize() != of->font().pointSize() ||
f->font().weight() != of->font().weight() ||
f->font().italic() != of->font().italic() ||
f->vAlign() != of->vAlign() ) ) {
invalidate( 0 );
}
if ( flags == -1 || flags == QTextFormat::Format || !fc ) {
if ( fc )
f = fc->format( f );
str->setFormat( i + index, f, useCollection );
} else {
QTextFormat *fm = fc->format( of, f, flags );
str->setFormat( i + index, fm, useCollection );
}
}
}
void QTextParagraph::indent( int *oldIndent, int *newIndent )
{
if ( !hasdoc || !document()->indent() || isListItem() ) {
if ( oldIndent )
*oldIndent = 0;
if ( newIndent )
*newIndent = 0;
if ( oldIndent && newIndent )
*newIndent = *oldIndent;
return;
}
document()->indent()->indent( document(), this, oldIndent, newIndent );
}
void QTextParagraph::paint( QPainter &painter, const QColorGroup &cg, QTextCursor *cursor, bool drawSelections,
int clipx, int clipy, int clipw, int cliph )
{
if ( !visible )
return;
QTextStringChar *chr = 0;
int i, y, h, baseLine, xstart, xend;
i = y =h = baseLine = 0;
QRect cursorRect;
drawSelections &= ( mSelections != 0 );
// macintosh full-width selection style
bool fullWidthStyle = FALSE;
int fullSelectionWidth = 0;
if ( drawSelections && fullWidthStyle )
fullSelectionWidth = (hasdoc ? document()->width() : r.width());
QString qstr = str->toString();
// ### workaround so that \n are not drawn, actually this should
@@ -5604,193 +5610,193 @@ QTextFormat *QTextFormatCollection::format( QTextFormat *f )
return lastFormat;
}
if ( f == lastFormat || ( lastFormat && f->key() == lastFormat->key() ) ) {
lastFormat->addRef();
return lastFormat;
}
QTextFormat *fm = cKey.find( f->key() );
if ( fm ) {
lastFormat = fm;
lastFormat->addRef();
return lastFormat;
}
if ( f->key() == defFormat->key() )
return defFormat;
lastFormat = createFormat( *f );
lastFormat->collection = this;
cKey.insert( lastFormat->key(), lastFormat );
return lastFormat;
}
QTextFormat *QTextFormatCollection::format( QTextFormat *of, QTextFormat *nf, int flags )
{
if ( cres && kof == of->key() && knf == nf->key() && cflags == flags ) {
cres->addRef();
return cres;
}
cres = createFormat( *of );
kof = of->key();
knf = nf->key();
cflags = flags;
if ( flags & QTextFormat::Bold )
cres->fn.setBold( nf->fn.bold() );
if ( flags & QTextFormat::Italic )
cres->fn.setItalic( nf->fn.italic() );
if ( flags & QTextFormat::Underline )
cres->fn.setUnderline( nf->fn.underline() );
if ( flags & QTextFormat::StrikeOut )
cres->fn.setStrikeOut( nf->fn.strikeOut() );
if ( flags & QTextFormat::Family )
cres->fn.setFamily( nf->fn.family() );
if ( flags & QTextFormat::Size ) {
if ( of->usePixelSizes )
cres->fn.setPixelSize( nf->fn.pixelSize() );
else
cres->fn.setPointSize( nf->fn.pointSize() );
}
if ( flags & QTextFormat::Color )
cres->col = nf->col;
if ( flags & QTextFormat::Misspelled )
cres->missp = nf->missp;
if ( flags & QTextFormat::VAlign )
cres->ha = nf->ha;
cres->update();
QTextFormat *fm = cKey.find( cres->key() );
if ( !fm ) {
cres->collection = this;
cKey.insert( cres->key(), cres );
} else {
delete cres;
cres = fm;
cres->addRef();
}
return cres;
}
QTextFormat *QTextFormatCollection::format( const QFont &f, const QColor &c )
{
if ( cachedFormat && cfont == f && ccol == c ) {
cachedFormat->addRef();
return cachedFormat;
}
QString key = QTextFormat::getKey( f, c, FALSE, QTextFormat::AlignNormal );
cachedFormat = cKey.find( key );
cfont = f;
ccol = c;
if ( cachedFormat ) {
cachedFormat->addRef();
return cachedFormat;
}
if ( key == defFormat->key() )
return defFormat;
cachedFormat = createFormat( f, c );
cachedFormat->collection = this;
cKey.insert( cachedFormat->key(), cachedFormat );
if ( cachedFormat->key() != key )
- qWarning("ASSERT: keys for format not identical: '%s '%s'", cachedFormat->key().latin1(), key.latin1() );
+ owarn << "ASSERT: keys for format not identical: '" << cachedFormat->key().latin1() << " '" << key.latin1() << "'" << oendl;
return cachedFormat;
}
void QTextFormatCollection::remove( QTextFormat *f )
{
if ( lastFormat == f )
lastFormat = 0;
if ( cres == f )
cres = 0;
if ( cachedFormat == f )
cachedFormat = 0;
cKey.remove( f->key() );
}
#define UPDATE( up, lo, rest ) \
if ( font.lo##rest() != defFormat->fn.lo##rest() && fm->fn.lo##rest() == defFormat->fn.lo##rest() ) \
fm->fn.set##up##rest( font.lo##rest() )
void QTextFormatCollection::updateDefaultFormat( const QFont &font, const QColor &color, QStyleSheet *sheet )
{
QDictIterator<QTextFormat> it( cKey );
QTextFormat *fm;
bool usePixels = font.pointSize() == -1;
bool changeSize = usePixels ? font.pixelSize() != defFormat->fn.pixelSize() :
font.pointSize() != defFormat->fn.pointSize();
int base = usePixels ? font.pixelSize() : font.pointSize();
while ( ( fm = it.current() ) ) {
++it;
UPDATE( F, f, amily );
UPDATE( W, w, eight );
UPDATE( B, b, old );
UPDATE( I, i, talic );
UPDATE( U, u, nderline );
if ( changeSize ) {
fm->stdSize = base;
fm->usePixelSizes = usePixels;
if ( usePixels )
fm->fn.setPixelSize( fm->stdSize );
else
fm->fn.setPointSize( fm->stdSize );
sheet->scaleFont( fm->fn, fm->logicalFontSize );
}
if ( color.isValid() && color != defFormat->col && fm->col == defFormat->col )
fm->col = color;
fm->update();
}
defFormat->fn = font;
defFormat->col = color;
defFormat->update();
defFormat->stdSize = base;
defFormat->usePixelSizes = usePixels;
updateKeys();
}
// the keys in cKey have changed, rebuild the hashtable
void QTextFormatCollection::updateKeys()
{
if ( cKey.isEmpty() )
return;
cKey.setAutoDelete( FALSE );
QTextFormat** formats = new QTextFormat*[ cKey.count() + 1 ];
QTextFormat **f = formats;
QDictIterator<QTextFormat> it( cKey );
while ( ( *f = it.current() ) ) {
++it;
++f;
}
cKey.clear();
for ( f = formats; *f; f++ )
cKey.insert( (*f)->key(), *f );
cKey.setAutoDelete( TRUE );
delete [] formats;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void QTextFormat::setBold( bool b )
{
if ( b == fn.bold() )
return;
fn.setBold( b );
update();
}
void QTextFormat::setMisspelled( bool b )
{
if ( b == (bool)missp )
return;
missp = b;
update();
}
@@ -5990,197 +5996,197 @@ QTextFormat QTextFormat::makeTextFormat( const QStyleSheetItem *style, const QMa
if ( attr.contains("size") ) {
QString a = attr["size"];
int n = a.toInt();
if ( a[0] == '+' || a[0] == '-' )
n += format.logicalFontSize;
format.logicalFontSize = n;
if ( format.usePixelSizes )
format.fn.setPixelSize( format.stdSize );
else
format.fn.setPointSize( format.stdSize );
style->styleSheet()->scaleFont( format.fn, format.logicalFontSize );
}
}
if ( attr.contains("style" ) ) {
QString a = attr["style"];
for ( int s = 0; s < a.contains(';')+1; s++ ) {
QString style = QTextDocument::section( a, ";", s, s );
if ( style.startsWith("font-size:" ) && QTextDocument::endsWith(style, "pt") ) {
format.logicalFontSize = 0;
format.setPointSize( int( scaleFontsFactor * style.mid( 10, style.length() - 12 ).toInt() ) );
} if ( style.startsWith("font-style:" ) ) {
QString s = style.mid( 11 ).stripWhiteSpace();
if ( s == "normal" )
format.fn.setItalic( FALSE );
else if ( s == "italic" || s == "oblique" )
format.fn.setItalic( TRUE );
} else if ( style.startsWith("font-weight:" ) ) {
QString s = style.mid( 12 );
bool ok = TRUE;
int n = s.toInt( &ok );
if ( ok )
format.fn.setWeight( n/8 );
} else if ( style.startsWith("font-family:" ) ) {
format.fn.setFamily( QTextDocument::section(style.mid(12),",",0,0).stripWhiteSpace() );
} else if ( style.startsWith("text-decoration:" ) ) {
QString s = style.mid( 16 ).stripWhiteSpace();
format.fn.setUnderline( s == "underline" );
} else if ( style.startsWith("vertical-align:" ) ) {
QString s = style.mid( 15 ).stripWhiteSpace();
if ( s == "sub" )
format.setVAlign( QTextFormat::AlignSubScript );
else if ( s == "super" )
format.setVAlign( QTextFormat::AlignSuperScript );
else
format.setVAlign( QTextFormat::AlignNormal );
} else if ( style.startsWith("color:" ) ) {
format.col.setNamedColor( style.mid(6) );
format.linkColor = FALSE;
}
}
}
format.update();
return format;
}
struct QPixmapInt
{
QPixmapInt() : ref( 0 ) {}
QPixmap pm;
int ref;
};
static QMap<QString, QPixmapInt> *pixmap_map = 0;
QTextImage::QTextImage( QTextDocument *p, const QMap<QString, QString> &attr, const QString& context,
QMimeSourceFactory &factory )
: QTextCustomItem( p )
{
width = height = 0;
if ( attr.contains("width") )
width = attr["width"].toInt();
if ( attr.contains("height") )
height = attr["height"].toInt();
reg = 0;
QString imageName = attr["src"];
if (!imageName)
imageName = attr["source"];
if ( !imageName.isEmpty() ) {
imgId = QString( "%1,%2,%3,%4" ).arg( imageName ).arg( width ).arg( height ).arg( (ulong)&factory );
if ( !pixmap_map )
pixmap_map = new QMap<QString, QPixmapInt>;
if ( pixmap_map->contains( imgId ) ) {
QPixmapInt& pmi = pixmap_map->operator[](imgId);
pm = pmi.pm;
pmi.ref++;
width = pm.width();
height = pm.height();
} else {
QImage img;
const QMimeSource* m =
factory.data( imageName, context );
if ( !m ) {
- qWarning("QTextImage: no mimesource for %s", imageName.latin1() );
+ owarn << "QTextImage: no mimesource for " << imageName.latin1() << "" << oendl;
}
else {
if ( !QImageDrag::decode( m, img ) ) {
- qWarning("QTextImage: cannot decode %s", imageName.latin1() );
+ owarn << "QTextImage: cannot decode " << imageName.latin1() << "" << oendl;
}
}
if ( !img.isNull() ) {
if ( width == 0 ) {
width = img.width();
if ( height != 0 ) {
width = img.width() * height / img.height();
}
}
if ( height == 0 ) {
height = img.height();
if ( width != img.width() ) {
height = img.height() * width / img.width();
}
}
if ( img.width() != width || img.height() != height ){
#ifndef QT_NO_IMAGE_SMOOTHSCALE
img = img.smoothScale(width, height);
#endif
width = img.width();
height = img.height();
}
pm.convertFromImage( img );
}
if ( !pm.isNull() ) {
QPixmapInt& pmi = pixmap_map->operator[](imgId);
pmi.pm = pm;
pmi.ref++;
}
}
if ( pm.mask() ) {
QRegion mask( *pm.mask() );
QRegion all( 0, 0, pm.width(), pm.height() );
reg = new QRegion( all.subtract( mask ) );
}
}
if ( pm.isNull() && (width*height)==0 )
width = height = 50;
place = PlaceInline;
if ( attr["align"] == "left" )
place = PlaceLeft;
else if ( attr["align"] == "right" )
place = PlaceRight;
tmpwidth = width;
tmpheight = height;
attributes = attr;
}
QTextImage::~QTextImage()
{
if ( pixmap_map && pixmap_map->contains( imgId ) ) {
QPixmapInt& pmi = pixmap_map->operator[](imgId);
pmi.ref--;
if ( !pmi.ref ) {
pixmap_map->remove( imgId );
if ( pixmap_map->isEmpty() ) {
delete pixmap_map;
pixmap_map = 0;
}
}
}
delete reg;
}
QString QTextImage::richText() const
{
QString s;
s += "<img ";
QMap<QString, QString>::ConstIterator it = attributes.begin();
for ( ; it != attributes.end(); ++it )
s += it.key() + "=" + *it + " ";
s += ">";
return s;
}
void QTextImage::adjustToPainter( QPainter* p )
{
width = scale( tmpwidth, p );
height = scale( tmpheight, p );
}
#if !defined(Q_WS_X11)
#include <qbitmap.h>
#include "qcleanuphandler.h"
static QPixmap *qrt_selection = 0;
static QSingleCleanupHandler<QPixmap> qrt_cleanup_pixmap;
static void qrt_createSelectionPixmap( const QColorGroup &cg )
{
qrt_selection = new QPixmap( 2, 2 );
qrt_cleanup_pixmap.set( &qrt_selection );
qrt_selection->fill( Qt::color0 );
diff --git a/noncore/apps/opie-write/qrichtext_p.cpp b/noncore/apps/opie-write/qrichtext_p.cpp
index 6783e0b..2e8b09c 100644
--- a/noncore/apps/opie-write/qrichtext_p.cpp
+++ b/noncore/apps/opie-write/qrichtext_p.cpp
@@ -1,236 +1,239 @@
/****************************************************************************
** $Id$
**
** Implementation of the internal Qt classes dealing with rich text
**
** Created : 990101
**
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
#include "qrichtext_p.h"
using namespace Qt3;
QTextCommand::~QTextCommand() {}
QTextCommand::Commands QTextCommand::type() const { return Invalid; }
QTextCustomItem::~QTextCustomItem() {}
void QTextCustomItem::adjustToPainter( QPainter* p){ if ( p ) width = 0; }
QTextCustomItem::Placement QTextCustomItem::placement() const { return PlaceInline; }
bool QTextCustomItem::ownLine() const { return FALSE; }
void QTextCustomItem::resize( int nwidth ){ width = nwidth; }
void QTextCustomItem::invalidate() {}
bool QTextCustomItem::isNested() const { return FALSE; }
int QTextCustomItem::minimumWidth() const { return 0; }
QString QTextCustomItem::richText() const { return QString::null; }
bool QTextCustomItem::enter( QTextCursor *, QTextDocument*&, QTextParagraph *&, int &, int &, int &, bool )
{
return TRUE;
}
bool QTextCustomItem::enterAt( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int &, const QPoint & )
{
return TRUE;
}
bool QTextCustomItem::next( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & )
{
return TRUE;
}
bool QTextCustomItem::prev( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & )
{
return TRUE;
}
bool QTextCustomItem::down( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & )
{
return TRUE;
}
bool QTextCustomItem::up( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & )
{
return TRUE;
}
void QTextFlow::setPageSize( int ps ) { pagesize = ps; }
bool QTextFlow::isEmpty() { return leftItems.isEmpty() && rightItems.isEmpty(); }
void QTextTableCell::invalidate() { cached_width = -1; cached_sizehint = -1; }
void QTextTable::invalidate() { cachewidth = -1; }
QTextParagraphData::~QTextParagraphData() {}
void QTextParagraphData::join( QTextParagraphData * ) {}
QTextFormatter::~QTextFormatter() {}
void QTextFormatter::setWrapEnabled( bool b ) { wrapEnabled = b; }
void QTextFormatter::setWrapAtColumn( int c ) { wrapColumn = c; }
int QTextCursor::x() const
{
QTextStringChar *c = para->at( idx );
int curx = c->x;
if ( !c->rightToLeft &&
c->c.isSpace() &&
idx > 0 &&
!c->lineStart &&
( para->alignment() & Qt3::AlignJustify ) == Qt3::AlignJustify )
curx = para->at( idx - 1 )->x + para->string()->width( idx - 1 );
if ( c->rightToLeft )
curx += para->string()->width( idx );
return curx;
}
int QTextCursor::y() const
{
int dummy, line;
para->lineStartOfChar( idx, &dummy, &line );
return para->lineY( line );
}
int QTextCursor::globalX() const { return totalOffsetX() + para->rect().x() + x(); }
int QTextCursor::globalY() const { return totalOffsetY() + para->rect().y() + y(); }
QTextDocument *QTextCursor::document() const
{
return para ? para->document() : 0;
}
void QTextCursor::gotoPosition( QTextParagraph* p, int index )
{
if ( para && p != para ) {
while ( para->document() != p->document() && !indices.isEmpty() )
pop();
Q_ASSERT( indices.isEmpty() || para->document() == p->document() );
}
para = p;
if ( index < 0 || index >= para->length() ) {
#if defined(QT_CHECK_RANGE)
- qWarning( "QTextCursor::gotoParagraph Index: %d out of range", index );
+ owarn << "QTextCursor::gotoParagraph Index: " << index << " out of range" << oendl;
#endif
index = index < 0 ? 0 : para->length() - 1;
}
tmpIndex = -1;
idx = index;
}
bool QTextDocument::hasSelection( int id, bool visible ) const
{
return ( selections.find( id ) != selections.end() &&
( !visible ||
( (QTextDocument*)this )->selectionStartCursor( id ) !=
( (QTextDocument*)this )->selectionEndCursor( id ) ) );
}
void QTextDocument::setSelectionStart( int id, const QTextCursor &cursor )
{
QTextDocumentSelection sel;
sel.startCursor = cursor;
sel.endCursor = cursor;
sel.swapped = FALSE;
selections[ id ] = sel;
}
QTextParagraph *QTextDocument::paragAt( int i ) const
{
QTextParagraph* p = curParag;
if ( !p || p->paragId() > i )
p = fParag;
while ( p && p->paragId() != i )
p = p->next();
((QTextDocument*)this)->curParag = p;
return p;
}
QTextFormat::~QTextFormat()
{
}
QTextFormat::QTextFormat()
: fm( QFontMetrics( fn ) ), linkColor( TRUE ), logicalFontSize( 3 ), stdSize( qApp->font().pointSize() )
{
ref = 0;
usePixelSizes = FALSE;
if ( stdSize == -1 ) {
stdSize = qApp->font().pixelSize();
usePixelSizes = TRUE;
}
missp = FALSE;
ha = AlignNormal;
collection = 0;
}
QTextFormat::QTextFormat( const QStyleSheetItem *style )
: fm( QFontMetrics( fn ) ), linkColor( TRUE ), logicalFontSize( 3 ), stdSize( qApp->font().pointSize() )
{
ref = 0;
usePixelSizes = FALSE;
if ( stdSize == -1 ) {
stdSize = qApp->font().pixelSize();
usePixelSizes = TRUE;
}
missp = FALSE;
ha = AlignNormal;
collection = 0;
fn = QFont( style->fontFamily(),
style->fontSize(),
style->fontWeight(),
style->fontItalic() );
fn.setUnderline( style->fontUnderline() );
fn.setStrikeOut( style->fontStrikeOut() );
col = style->color();
fm = QFontMetrics( fn );
leftBearing = fm.minLeftBearing();
rightBearing = fm.minRightBearing();
hei = fm.lineSpacing();
asc = fm.ascent() + (fm.leading()+1)/2;
dsc = fm.descent();
missp = FALSE;
ha = AlignNormal;
memset( widths, 0, 256 );
generateKey();
addRef();
}
QTextFormat::QTextFormat( const QFont &f, const QColor &c, QTextFormatCollection *parent )
: fn( f ), col( c ), fm( QFontMetrics( f ) ), linkColor( TRUE ),
logicalFontSize( 3 ), stdSize( f.pointSize() )
{
ref = 0;
@@ -384,220 +387,220 @@ QString QTextFormat::getKey( const QFont &fn, const QColor &col, bool misspelled
k += '/';
k += QString::number( (uint)col.rgb() );
k += '/';
k += QString::number( (int)misspelled );
k += '/';
k += QString::number( (int)a );
return k;
}
QString QTextString::toString( const QMemArray<QTextStringChar> &data )
{
QString s;
int l = data.size();
s.setUnicode( 0, l );
QTextStringChar *c = data.data();
QChar *uc = (QChar *)s.unicode();
while ( l-- ) {
*uc = c->c;
// ### workaround so that non-breaking whitespaces are drawn
// properly, actually this should be fixed in QFont somewhere
if ( *uc == (char)0xa0 )
*uc = 0x20;
uc++;
c++;
}
return s;
}
QString QTextString::toString() const
{
return toString( data );
}
void QTextParagraph::setSelection( int id, int start, int end )
{
QMap<int, QTextParagraphSelection>::ConstIterator it = selections().find( id );
if ( it != mSelections->end() ) {
if ( start == ( *it ).start && end == ( *it ).end )
return;
}
QTextParagraphSelection sel;
sel.start = start;
sel.end = end;
(*mSelections)[ id ] = sel;
setChanged( TRUE, TRUE );
}
void QTextParagraph::removeSelection( int id )
{
if ( !hasSelection( id ) )
return;
if ( mSelections )
mSelections->remove( id );
setChanged( TRUE, TRUE );
}
int QTextParagraph::selectionStart( int id ) const
{
if ( !mSelections )
return -1;
QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id );
if ( it == mSelections->end() )
return -1;
return ( *it ).start;
}
int QTextParagraph::selectionEnd( int id ) const
{
if ( !mSelections )
return -1;
QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id );
if ( it == mSelections->end() )
return -1;
return ( *it ).end;
}
bool QTextParagraph::hasSelection( int id ) const
{
return mSelections ? mSelections->contains( id ) : FALSE;
}
bool QTextParagraph::fullSelected( int id ) const
{
if ( !mSelections )
return FALSE;
QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id );
if ( it == mSelections->end() )
return FALSE;
return ( *it ).start == 0 && ( *it ).end == str->length() - 1;
}
int QTextParagraph::lineY( int l ) const
{
if ( l > (int)lineStarts.count() - 1 ) {
- qWarning( "QTextParagraph::lineY: line %d out of range!", l );
+ owarn << "QTextParagraph::lineY: line " << l << " out of range!" << oendl;
return 0;
}
if ( !isValid() )
( (QTextParagraph*)this )->format();
QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
while ( l-- > 0 )
++it;
return ( *it )->y;
}
int QTextParagraph::lineBaseLine( int l ) const
{
if ( l > (int)lineStarts.count() - 1 ) {
- qWarning( "QTextParagraph::lineBaseLine: line %d out of range!", l );
+ owarn << "QTextParagraph::lineBaseLine: line " << l << " out of range!" << oendl;
return 10;
}
if ( !isValid() )
( (QTextParagraph*)this )->format();
QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
while ( l-- > 0 )
++it;
return ( *it )->baseLine;
}
int QTextParagraph::lineHeight( int l ) const
{
if ( l > (int)lineStarts.count() - 1 ) {
- qWarning( "QTextParagraph::lineHeight: line %d out of range!", l );
+ owarn << "QTextParagraph::lineHeight: line " << l << " out of range!" << oendl;
return 15;
}
if ( !isValid() )
( (QTextParagraph*)this )->format();
QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
while ( l-- > 0 )
++it;
return ( *it )->h;
}
void QTextParagraph::lineInfo( int l, int &y, int &h, int &bl ) const
{
if ( l > (int)lineStarts.count() - 1 ) {
- qWarning( "QTextParagraph::lineInfo: line %d out of range!", l );
- qDebug( "%d %d", (int)lineStarts.count() - 1, l );
+ owarn << "QTextParagraph::lineInfo: line " << l << " out of range!" << oendl;
+ odebug << "" << (int)lineStarts.count() - 1 << " " << l << "" << oendl;
y = 0;
h = 15;
bl = 10;
return;
}
if ( !isValid() )
( (QTextParagraph*)this )->format();
QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
while ( l-- > 0 )
++it;
y = ( *it )->y;
h = ( *it )->h;
bl = ( *it )->baseLine;
}
void QTextParagraph::setAlignment( int a )
{
if ( a == (int)align )
return;
align = a;
invalidate( 0 );
}
QTextFormatter *QTextParagraph::formatter() const
{
if ( hasdoc )
return document()->formatter();
if ( pseudoDocument()->pFormatter )
return pseudoDocument()->pFormatter;
return ( ( (QTextParagraph*)this )->pseudoDocument()->pFormatter = new QTextFormatterBreakWords );
}
void QTextParagraph::setTabArray( int *a )
{
delete [] tArray;
tArray = a;
}
void QTextParagraph::setTabStops( int tw )
{
if ( hasdoc )
document()->setTabStops( tw );
else
tabStopWidth = tw;
}
QMap<int, QTextParagraphSelection> &QTextParagraph::selections() const
{
if ( !mSelections )
((QTextParagraph *)this)->mSelections = new QMap<int, QTextParagraphSelection>;
return *mSelections;
}
QPtrList<QTextCustomItem> &QTextParagraph::floatingItems() const
{
if ( !mFloatingItems )
((QTextParagraph *)this)->mFloatingItems = new QPtrList<QTextCustomItem>;
return *mFloatingItems;
}
QTextStringChar::~QTextStringChar()
{
if ( format() )
format()->removeRef();
if ( type ) // not Regular
delete d.custom;
}
QTextParagraphPseudoDocument::QTextParagraphPseudoDocument():pFormatter(0),commandHistory(0), minw(0),wused(0){}
QTextParagraphPseudoDocument::~QTextParagraphPseudoDocument(){ delete pFormatter; delete commandHistory; }
diff --git a/noncore/apps/qashmoney/accountdisplay.cpp b/noncore/apps/qashmoney/accountdisplay.cpp
index 0fe5b09..046d997 100755
--- a/noncore/apps/qashmoney/accountdisplay.cpp
+++ b/noncore/apps/qashmoney/accountdisplay.cpp
@@ -1,105 +1,110 @@
-#include <qmessagebox.h>
-#include <qheader.h>
-
#include "accountdisplay.h"
#include "newaccount.h"
#include "transaction.h"
#include "transferdialog.h"
#include "transfer.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
+#include <qmessagebox.h>
+#include <qheader.h>
+
extern Account *account;
extern Transaction *transaction;
extern Transfer *transfer;
extern Preferences *preferences;
AccountDisplay::AccountDisplay ( QWidget *parent ) : QWidget ( parent )
{
cleared = 0;
firstline = new QHBox ( this );
firstline->setSpacing ( 2 );
newaccount = new QPushButton ( firstline );
newaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/new.png") );
connect ( newaccount, SIGNAL ( released() ), this, SLOT ( addAccount() ) );
editaccount = new QPushButton ( firstline );
editaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/edit.png") );
connect ( editaccount, SIGNAL ( released() ), this, SLOT ( editAccount() ) );
deleteaccount = new QPushButton ( firstline );
deleteaccount->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/delete.png") );
connect ( deleteaccount, SIGNAL ( released() ), this, SLOT ( deleteAccount() ) );
transferbutton = new QPushButton ( firstline );
transferbutton->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/transfer.png") );
transferbutton->setToggleButton ( TRUE );
connect ( transferbutton, SIGNAL ( toggled(bool) ), this, SLOT ( accountTransfer(bool) ) );
listview = new QListView ( this );
listview->setAllColumnsShowFocus ( TRUE );
listview->setShowSortIndicator ( TRUE );
listview->setRootIsDecorated ( TRUE );
listview->setMultiSelection ( FALSE );
connect ( listview, SIGNAL ( expanded(QListViewItem*) ), this, SLOT ( setAccountExpanded(QListViewItem*) ) );
connect ( listview, SIGNAL ( collapsed(QListViewItem*) ), this, SLOT ( setAccountCollapsed(QListViewItem*) ) );
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) ) );
layout = new QVBoxLayout ( this, 2, 5 );
layout->addWidget ( firstline );
layout->addWidget ( listview );
}
void AccountDisplay::setTabs ( QWidget *newtab2, QTabWidget *newtabs )
{
tab2 = newtab2;
maintabs = newtabs;
}
void AccountDisplay::addAccount ()
{
// initialize local variables
int parentid = 0;
type = 0;
QString parentlist [ listview->childCount() + 1 ] [ 3 ] ;
// create new account window for entering data
NewAccount *newaccount = new NewAccount ( this );
int width = this->width();
newaccount->accountbox->setMaximumWidth ( ( int ) ( width * 0.5 ) );
newaccount->datebox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
newaccount->childbox->setMaximumWidth ( ( int ) ( width * 0.5 ) );
newaccount->balancebox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
newaccount->creditlimitbox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
// if there are no accounts, disable the child check box
if ( account->getNumberOfAccounts () == 0 )
newaccount->childcheckbox->setEnabled ( FALSE );
// if there are accounts, fill up the pulldown menu for
// selecting a parent account. We should only add those parents without transactions
else
{
int c = 0;
QListViewItemIterator it ( listview );
for ( ; it.current(); ++it )
{
int id = it.current()->text ( getIDColumn() ).toInt();
// iterate through accountdisplay listview and add parents with no transactions
// add this item to the list box only if it is a parent and has no transactions
if ( transfer->getNumberOfTransfers ( id ) == 0 && transaction->getNumberOfTransactions ( id ) == 0 && it.current()->parent() == 0 )
{
newaccount->childbox->insertItem ( it.current()->text ( 0 ) );
parentlist [ c ] [ 0 ] = it.current()->text ( 0 );
parentlist [ c ] [ 1 ] = it.current()->text ( getIDColumn() );
parentlist [ c ] [ 2 ] = QString::number ( c );
c++;
}
}
}
if ( preferences->getPreference ( 4 ) == 0 )
newaccount->currencybox->setEnabled ( FALSE );
@@ -174,193 +179,193 @@ void AccountDisplay::deleteAccount ()
transfer->deleteAllTransfers ( accountid );
// delete the account
account->deleteAccount ( accountid );
// update account balances
if ( parentid != -1 )
account->changeParentAccountBalance ( parentid );
//redisplay accounts
account->displayAccounts ( listview );
//remove all the columns from the accountdisplay if there are not any accounts
if ( account->getNumberOfAccounts() == 0 )
{
int columns = listview->columns();
int counter;
for ( counter = 0; counter <= columns; counter++ )
listview->removeColumn ( 0 );
}
setToggleButton();
}
}
maintabs->setTabEnabled ( tab2, FALSE );
}
void AccountDisplay::setToggleButton ()
{
// iterate through account display and determine how many "transferable" accounts we have
// if there are less than two, disable the transfer button
QListViewItemIterator it ( listview );
int counter = 0;
for ( ; it.current(); ++it )
{
// add one to counter if we find a transferable account
if ( it.current()->parent() != 0 || ( it.current()->childCount() ) == 0 )
counter++;
}
if ( counter > 1 )
transferbutton->show();
else
transferbutton->hide();
}
void AccountDisplay::accountTransfer ( bool state )
{
if ( state == TRUE )
{
firstaccountid = -1;
secondaccountid = -1;
listview->clearSelection ();
listview->setMultiSelection ( TRUE );
disableParentsWithChildren ();
connect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
}
else
{
firstaccountid = -1;
secondaccountid = -1;
listview->clearSelection ();
listview->setMultiSelection ( FALSE );
enableAccounts ();
disconnect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
}
}
void AccountDisplay::getTransferAccounts ( QListViewItem * item )
{
if ( item->parent() != 0 || item->childCount() == 0 ) // only set an account for transfer if its a child or parent with no children
{
if ( firstaccountid == -1 )
firstaccountid = item->text ( getIDColumn() ).toInt(); // set first account if we've selected a valid account
else
if ( item->text ( getIDColumn() ).toInt() != firstaccountid ) // set the second account if its not equal to the first
secondaccountid = item->text ( getIDColumn() ).toInt();
}
// open transfer window if both accounts are set
if ( firstaccountid != -1 && secondaccountid != -1 )
{
// construct the transferdialog window
TransferDialog *td = new TransferDialog ( this, firstaccountid, secondaccountid );
// enter today's date in the date box as default
QDate today = QDate::currentDate ();
int defaultday = today.day();
int defaultmonth = today.month();
int defaultyear = today.year();
td->date->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) );
if ( td->exec() == QDialog::Accepted )
{
// set the cleared integer if the checkbox is checked
if ( td->clearedcheckbox->isChecked() == TRUE )
cleared = 1;
- qDebug("Year from transferdialog = %i",td->getYear());
+ odebug << "Year from transferdialog = " << td->getYear() << "" << oendl;
// add the transfer with a new date if its been edited or use the default date
if ( td->getDateEdited () == TRUE )
transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), td->getDay(), td->getMonth(), td->getYear(), td->amount->text().toFloat(), cleared );
else
transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), defaultday, defaultmonth, defaultyear, td->amount->text().toFloat(), cleared );
// update account balances of both accounts and parents if necessary
account->updateAccountBalance ( firstaccountid );
if ( account->getParentAccountID ( firstaccountid ) != -1 )
account->changeParentAccountBalance ( account->getParentAccountID ( firstaccountid ) );
account->updateAccountBalance ( secondaccountid );
if ( account->getParentAccountID ( secondaccountid ) != -1 )
account->changeParentAccountBalance ( account->getParentAccountID ( secondaccountid ) );
// redisplay accounts
account->displayAccounts ( listview );
}
else
{
firstaccountid = -1;
secondaccountid = -1;
listview->clearSelection ();
listview->setMultiSelection ( FALSE );
disconnect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
}
// reset the accounts display window
transferbutton->toggle(); // toggling this button with clear the window as well
// reenable all the accounts so the transaction tab will be properly set
enableAccounts ();
}
}
void AccountDisplay::disableParentsWithChildren ()
{
// iterate through accountdisplay listview and disable all the parents that have children
QListViewItemIterator it ( listview );
for ( ; it.current(); ++it )
{
if ( it.current()->parent() == 0 && it.current()->childCount() != 0 )
it.current()->setSelectable ( FALSE );
}
}
void AccountDisplay::enableAccounts ()
{
// iterate through accountdisplay listview and enable all accounts
QListViewItemIterator it ( listview );
for ( ; it.current(); ++it )
it.current()->setSelectable ( TRUE );
}
void AccountDisplay::saveColumnSize ( int column, int oldsize, int newsize )
{
switch ( column )
{
case 0:
if ( listview->columns() == 3 )
preferences->changeColumnPreference ( 1, newsize );
else
preferences->changeColumnPreference ( 10, newsize );
break;
case 1:
if ( listview->columns() == 3 )
preferences->changeColumnPreference ( 2, newsize );
else
preferences->changeColumnPreference ( 11, newsize );
break;
case 2:
preferences->changeColumnPreference ( 12, newsize );
break;
}
}
void AccountDisplay::saveSortingPreference ( int column )
{
preferences->changeSortingPreference ( 1, column );
}
int AccountDisplay::getIDColumn ()
{
int counter;
int columns = listview->columns();
for ( counter = 0; counter <= columns; counter++ )
if ( listview->header()->label ( counter ).length() == 0 )
return counter;
}
void AccountDisplay::editAccount ()
{
if ( listview->selectedItem() == 0 )
QMessageBox::warning ( this, "QashMoney", "Please select an account\nto edit.");
else
{
diff --git a/noncore/apps/qashmoney/config.in b/noncore/apps/qashmoney/config.in
index 91739fe..aeed298 100644
--- a/noncore/apps/qashmoney/config.in
+++ b/noncore/apps/qashmoney/config.in
@@ -1,4 +1,4 @@
config QASHMONEY
boolean "opie-qashmoney (money manager)"
default "n"
- depends ( LIBQPE || LIBQPE-X11 )
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
diff --git a/noncore/apps/qashmoney/qashmoney.pro b/noncore/apps/qashmoney/qashmoney.pro
index 6ad3db3..8a4302f 100755
--- a/noncore/apps/qashmoney/qashmoney.pro
+++ b/noncore/apps/qashmoney/qashmoney.pro
@@ -1,49 +1,49 @@
TEMPLATE = app
CONFIG = qt warn_on
HEADERS = qashmoney.h \
accountdisplay.h \
account.h \
transaction.h \
transactiondisplay.h \
newtransaction.h \
transfer.h \
transferdialog.h \
preferences.h \
preferencedialogs.h \
memory.h \
memorydialog.h \
newaccount.h \
calculator.h \
datepicker.h \
budget.h \
budgetdisplay.h \
currency.h
SOURCES = qashmoney.cpp \
accountdisplay.cpp \
account.cpp \
transaction.cpp \
transactiondisplay.cpp \
newtransaction.cpp \
transfer.cpp \
transferdialog.cpp \
preferences.cpp \
preferencedialogs.cpp \
memory.cpp \
memorydialog.cpp \
newaccount.cpp \
calculator.cpp \
datepicker.cpp \
main.cpp \
budget.cpp \
budgetdisplay.cpp \
currency.cpp
INCLUDEPATH = $(OPIEDIR)/include
DEPENDPATH = $(OPIEDIR)/include
DESTDIR = $(OPIEDIR)/bin
unix:LIBS += -lm
-LIBS += -lqpe -lqte -lsqlite
+LIBS += -lqpe -lopiecore2 -lsqlite
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/tableviewer/db/common.cpp b/noncore/apps/tableviewer/db/common.cpp
index dbf9370..6e544ba 100644
--- a/noncore/apps/tableviewer/db/common.cpp
+++ b/noncore/apps/tableviewer/db/common.cpp
@@ -1,124 +1,132 @@
/**********************************************************************
** 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 <stdlib.h>
+#include "common.h"
+#include "datacache.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/timestring.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qstring.h>
#include <qheader.h>
#include <qvector.h>
#include <qdatetime.h>
-#include <qpe/timestring.h>
-#include "common.h"
-#include "datacache.h"
+
+/* STD */
#include <assert.h>
+#include <stdlib.h>
static const int del_flag = 0x1;
static const int new_flag = 0x2;
/* Helper function */
int parseNextNumber(QString *q) {
QChar c;
uint i;
int result = 0;
bool found_digits = FALSE;
for(i = 0; i < q->length(); i++) {
c = q->at(i);
if (c.isDigit()) {
if (found_digits)
result *= 10;
found_digits = TRUE;
result += c.digitValue();
} else {
if (found_digits)
break;
/* just skip this char */
}
}
/* now truncate q */
if (found_digits)
q->remove(0, i);
return result;
}
/*!
\class QStringVector
\brief A Vector of QStrings that can be sorted and searched
Implmented in order to allow reverse lookup on the string name
*/
/*!
This function implements the compare function in order to allow the
searching and sorting of the QStringVector to occur
\returns an int which is either
<UL>
<LI> < 0 if the first string is smaller than the second,</LI>
<LI> > 0 if the first string is bigger then the second,</LI>
<LI> == 0 if the first string is equal to the second.</LI>
</UL>
*/
int QStringVector::compareItems(Item a, Item b)
{
QString *qa = (QString *)a;
QString *qb = (QString *)b;
return QString::compare(*qa, *qb);
}
/*!
\class TVVariant
A way of abstracting void * and keeping information on
the keytypes and behaviours in one place
*/
TVVariantPrivate::TVVariantPrivate()
{
typ = TVVariant::Invalid;
}
TVVariantPrivate::TVVariantPrivate( TVVariantPrivate *d)
{
switch(d->typ)
{
case TVVariant::Invalid:
break;
case TVVariant::String:
value.ptr = new QString(*((QString *)d->value.ptr));
break;
case TVVariant::Date:
value.ptr = new QDate(*((QDate *)d->value.ptr));
break;
case TVVariant::Time:
value.ptr = new QTime(*((QTime *)d->value.ptr));
break;
case TVVariant::Int:
value.i = d->value.i;
break;
default:
ASSERT( 0 );
}
typ = d->typ;
}
TVVariantPrivate::~TVVariantPrivate()
{
@@ -219,193 +227,193 @@ void TVVariant::detach()
{
if (d->count == 1)
return;
d->deref();
d = new TVVariantPrivate(d);
}
const QString TVVariant::typeName() const
{
return typeToName(d->typ);
}
void TVVariant::clear()
{
if (d->count > 1)
{
d->deref();
d = new TVVariantPrivate;
return;
}
d->clear();
}
const QString TVVariant::typeToName(KeyType typ)
{
switch(typ) {
case String:
return QString("String");
case Date:
return QString("Date");
case Time:
return QString("Time");
case Int:
return QString("Int");
case Invalid:
default:
return QString("Invalid");
}
return QString("Invalid");
}
TVVariant::KeyType TVVariant::nameToType(const QString &name)
{
if(!qstrcmp("String", name))
return String;
if(!qstrcmp("Date", name))
return Date;
if(!qstrcmp("Time", name))
return Time;
if(!qstrcmp("Int", name))
return Int;
return Invalid;
}
void TVVariant::load(QDataStream &s )
{
KeyType t;
s >> t;
d->typ = t;
switch(t) {
case Invalid:
d->typ = t;
break;
case String:
{
QString *x = new QString;
s >> *x;
d->value.ptr = x;
}
break;
case Time:
{
QTime *x = new QTime;
s >> *x;
d->value.ptr = x;
}
break;
case Date:
{
QDate *x = new QDate;
s >> *x;
d->value.ptr = x;
}
break;
case Int:
{
int x;
s >> x;
d->value.i = x;
}
break;
default:
- qFatal("Unrecognized data type");
+ ofatal << "Unrecognized data type" << oendl;
}
}
void TVVariant::save( QDataStream &s ) const
{
s << type();
switch( d->typ ) {
case String:
s << *((QString *)d->value.ptr);
break;
case Date:
s << *((QDate *)d->value.ptr);
break;
case Time:
s << *((QTime *)d->value.ptr);
break;
case Int:
s << d->value.i;
break;
case Invalid:
break;
}
}
QDataStream& operator>>(QDataStream& s, TVVariant& p)
{
p.load( s );
return s;
}
QDataStream& operator<<(QDataStream &s, const TVVariant& p)
{
p.save( s );
return s;
}
QDataStream& operator>> (QDataStream &s, TVVariant::KeyType& p)
{
Q_UINT8 u = 0;
s >> u;
p = (TVVariant::KeyType) u;
return s;
}
QDataStream& operator<< (QDataStream& s, const TVVariant::KeyType& p)
{
s << (Q_UINT8)p;
return s;
}
const QString TVVariant::toString() const
{
switch(d->typ) {
case String:
return *((QString*)d->value.ptr);
case Date:
return ((QDate*)d->value.ptr)->toString();
case Time:
return ((QTime*)d->value.ptr)->toString();
case Int:
return QString::number(d->value.i);
case Invalid:
default:
return QString::null;
}
return QString::null;
}
// TODO DO, this properly, */
int TVVariant::toInt() const
{
if(d->typ == Int)
return d->value.i;
if(d->typ == String) {
QString tmpq(*(QString *)d->value.ptr);
return parseNextNumber(&tmpq);
}
return 0;
}
const QDate TVVariant::toDate() const
{
if(d->typ == Date)
return *((QDate *)d->value.ptr);
if(d->typ == String) {
QString q = toString();
/* date format is day mon d yyyy */
/* ignore the first three letters, read the next
three for month.. etc */
@@ -985,193 +993,193 @@ bool KeyList::validIndex(int i) const
return FALSE;
return TRUE;
}
QDataStream &operator<<( QDataStream &s, const KeyList &k)
{
s << k.getNumFields();
KeyListIterator it(k);
while(it.current()) {
s << (Q_UINT16)it.currentKey();
s << it.current()->name();
s << it.current()->example();
s << (Q_UINT16)it.current()->flags();
++it;
}
return s;
}
QDataStream &operator>>( QDataStream &s, KeyList &k)
{
int i;
int size;
int index = 0;
int flags = 0;
TVVariant type = TVVariant();
QString name;
s >> size;
for (i=0; i < size; i++) {
s >> (Q_UINT16 &)index;
s >> name;
s >> type;
s >> (Q_UINT16 &)flags;
k.replace(index, new Key(name, type, flags));
}
return s;
}
/*!
\class DataElem
\brief A class representing a single row or element of a table in a DBStore
This class holds the data of a row in a table.
*/
/*!
Constructs a DataElem. This function needs a container because the
size, types of keys and primary key are all defined by the containing
database
*/
DataElem::DataElem(DBStore *c) : values(20)
{
int size;
contained = c;
size = c->getNumFields();
values.setAutoDelete(TRUE);
}
/*!
Destroys a DataElem and frees memory used by the DataElem
*/
DataElem::~DataElem() {
}
QDataStream &operator<<( QDataStream &s, const DataElem &d)
{
int size = d.getNumFields();
s << size; /* redundent data but makes streaming easier */
KeyList k = d.getKeys();
KeyListIterator it(k);
while(it.current()) {
s << (Q_UINT16)it.currentKey();
s << d.getField(it.currentKey());
++it;
}
return s;
}
QDataStream &operator>>( QDataStream &s, DataElem &d)
{
int i;
int size;
TVVariant t;
int index = 0;
s >> size; /* redundent data but makes streaming easier */
if (size != d.getNumFields()) {
- qWarning("DataSize mis-match");
+ owarn << "DataSize mis-match" << oendl;
return s; /* sanity check failed.. don't load */
}
for(i = 0; i < size; i++) {
s >> (Q_UINT16)index;
s >> t;
d.setField(index, t);
}
return s;
}
/*! Returns the number of possible (not valid) fields in the data element */
int DataElem::getNumFields() const
{
return contained->getNumFields();
}
KeyList DataElem::getKeys() const
{
return *(contained->getKeys());
}
/*!
This function determines whether field index i of the element has been
set yet.
\return A boolean value that is TRUE if the specfied field of this
element has been set and FALSE if the field has not yet been set
*/
bool DataElem::hasValidValue(int i) const
{
if(!values.find(i))
return FALSE;
if(!contained->getKeys()->validIndex(i))
return FALSE;
return values.find(i)->isValid();
}
/*!
This function determines whether field name qs of the element has been
set yet.
\return A boolean value that is TRUE if the specfied field of this
element has been set and FALSE if the field has not yet been set
*/
bool DataElem::hasValidValue(QString qs) const
{
int i = contained->getKeyIndex(qs);
return hasValidValue(i);
}
/*! returns the type of the field specified by index i */
TVVariant::KeyType DataElem::getFieldType(int i) const
{
return contained->getKeyType(i);
}
/*! returns the type of the field specified by name qs */
TVVariant::KeyType DataElem::getFieldType(QString qs) const
{
int i = contained->getKeyIndex(qs);
return contained->getKeyType(i);
}
/*!
returns a pointer to the data stored in field index i for this
data element, (value may not be valid)
*/
TVVariant DataElem::getField(int i) const
{
if(hasValidValue(i))
return TVVariant(*values.find(i));
return TVVariant();
}
/*!
returns a pointer to the data stored in field name qs for this
data element, (value may not be valid)
*/
TVVariant DataElem::getField(QString qs) const
{
int i = contained->getKeyIndex(qs);
return getField(i);
}
/*!
Sets the value of the elements field index i to the value represented in
the QString q.
\param i index of the field to set
\param q a string that can be parsed to get the value to be set
*/
void DataElem::setField(int i, QString q)
{
/* from the type of the field, parse q and store */
TVVariant::KeyType kt = contained->getKeyType(i);
@@ -1284,187 +1292,187 @@ QString DataElem::toQString() const
/*! formats individual fields to strings so can be displayed */
QString DataElem::toQString(int i) const
{
if(hasValidValue(i)) {
return getField(i).toString();
}
return "";
}
/*! formats individual fields to strings so can be sorted by QListView */
QString DataElem::toSortableQString(int i) const
{
QString scratch = "";
if(hasValidValue(i)) {
switch (contained->getKeyType(i)) {
case TVVariant::String: {
scratch += getField(i).toString();
break;
}
case TVVariant::Int: {
scratch.sprintf("%08d", getField(i).toInt());
break;
}
case TVVariant::Date: {
static QDate epochD(1800, 1, 1);
scratch.sprintf("%08d",
epochD.daysTo(getField(i).toDate()));
break;
}
case TVVariant::Time: {
static QTime epochT(0, 0, 0);
scratch.sprintf("%08d",
epochT.msecsTo(getField(i).toTime()));
break;
}
default:
scratch += "Unknown type";
break;
}
}
return scratch;
}
/* compare functions */
bool DataElem::lessThan(int i, TVVariant v) const
{
if (!hasValidValue(i)) return FALSE;
if (getField(i).type() != v.type())
return FALSE;
return (getField(i) < v);
}
bool DataElem::moreThan(int i, TVVariant v) const
{
if (!hasValidValue(i)) return FALSE;
if (getField(i).type() != v.type())
return FALSE;
return (getField(i) > v);
}
bool DataElem::equalTo(int i, TVVariant v) const
{
if (!hasValidValue(i)) return FALSE;
if (getField(i).type() != v.type())
return FALSE;
return (getField(i) == v);
}
bool DataElem::contains(int i, TVVariant v) const
{
if (!hasValidValue(i)) return FALSE;
if (getField(i).type() != v.type())
return FALSE;
switch(getField(i).type()) {
case TVVariant::String: {
QString qs1 = getField(i).toString().lower();
QString qs2 = v.toString().lower();
if (qs1.contains(qs2) > 0) return TRUE;
break;
}
/* meaningless for ints */
/* meaningless for time */
/* meaningless for dates */
case TVVariant::Int:
case TVVariant::Time:
case TVVariant::Date:
break;
default:
- qWarning("Tried to compare unknown data type");
+ owarn << "Tried to compare unknown data type" << oendl;
}
return FALSE;
}
bool DataElem::startsWith(int i, TVVariant v) const
{
if (!hasValidValue(i)) return FALSE;
if (getField(i).type() != v.type())
return FALSE;
switch(getField(i).type()) {
case TVVariant::String: {
QString qs1 = getField(i).toString().lower();
QString qs2 = v.toString().lower();
return qs1.startsWith(qs2);
}
/* meaningless for ints */
/* meaningless for time */
/* meaningless for dates */
case TVVariant::Int:
case TVVariant::Time:
case TVVariant::Date:
return FALSE;
default:
- qWarning("Tried to compare unknown data type");
+ owarn << "Tried to compare unknown data type" << oendl;
}
return FALSE;
}
bool DataElem::endsWith(int i, TVVariant v) const
{
if (!hasValidValue(i)) return FALSE;
if (getField(i).type() != v.type())
return FALSE;
switch(getField(i).type()) {
case TVVariant::String: {
QString qs1 = getField(i).toString().lower();
QString qs2 = v.toString().lower();
return qs1.startsWith(qs2);
}
/* meaningless for ints */
/* meaningless for time */
/* meaningless for dates */
case TVVariant::Int:
case TVVariant::Time:
case TVVariant::Date:
return FALSE;
default:
- qWarning("Tried to compare unknown data type");
+ owarn << "Tried to compare unknown data type" << oendl;
}
return FALSE;
}
/*!
Determins which of the first to parameters are closer to the third, target
parameter.
\return
<UL>
<LI>TRUE if the first element is a closer match to the target than the
second element</LI>
<LI>FALSE if the first element is not a closer match to the target than
the second element</LI>
</UL>
*/
bool DataElem::closer(DataElem*d1, DataElem *d2, TVVariant target, int column)
{
int type;
if(!d1) return FALSE;
if (!d1->hasValidValue(column)) return FALSE;
if(!target.isValid()) return FALSE;
type = d1->getField(column).type();
if(d2) {
if (type != d2->getField(column).type()) {
/* can't do compare */
- qWarning("Tried to compare two incompatable types");
+ owarn << "Tried to compare two incompatable types" << oendl;
return FALSE;
}
return target.closer(d1->getField(column), d2->getField(column));
}
return target.close(d1->getField(column));
}
diff --git a/noncore/apps/tableviewer/db/datacache.cpp b/noncore/apps/tableviewer/db/datacache.cpp
index 7c14eef..6380e1b 100644
--- a/noncore/apps/tableviewer/db/datacache.cpp
+++ b/noncore/apps/tableviewer/db/datacache.cpp
@@ -1,249 +1,257 @@
/**********************************************************************
** 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.
**
**********************************************************************/
/*
* This file is used to load the xml files that represent the database.
* The main requirment for said file is each data entry must contain a key,
* otherwise any other data headings are allowed.
*/
#include "datacache.h"
#include "xmlsource.h"
#include "csvsource.h"
-#include <stdlib.h>
+
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qheader.h>
+/* STD */
+#include <stdlib.h>
+
#define INIT_TABLE_SIZE 128
/*!
\class DBStore datastore.h
\brief The DBStore class is the class responsible for storing, sorting and
searching the data loaded by the application
*/
/*!
Constructs a DBStore item
*/
DBStore::DBStore()
{
name = "";
number_elems = 0;
full = false;
kRep = new KeyList();
master_table.resize(INIT_TABLE_SIZE);
table_size = INIT_TABLE_SIZE;
current_elem = 0;
archive = 0;
}
//TODO
/*!
Reinitializes the table to empty (include a resize of the master table,
which should free some memory)
*/
void DBStore::freeTable()
{
name = "";
if(archive) {
delete archive;
archive = 0;
}
kRep->clear(); /* clear the current key list */
number_elems = 0;
table_size = INIT_TABLE_SIZE;
master_table.resize(table_size);
full = false;
current_elem = 0;
}
/*!
Removes all items from the DBStore and destroys the DBStore
*/
DBStore::~DBStore()
{
freeTable();
}
/*!
This function opens the given xml file, loads it and sets up the
appropriate data structures.
\param file_name A string representing the name of the file to be opened
\return true if successful, false otherwise.
*/
bool DBStore::openSource(QIODevice *inDev, const QString &source) {
/* first check if db is already open, if contains data.. then clear */
if(number_elems > 0) {
freeTable();
}
if (source == "text/x-xml-tableviewer") {
archive = new DBXml(this);
} else if (source == "text/csv") {
archive = new DBCsv(this);
} else
return false;
return (archive->openSource(inDev));
}
bool DBStore::saveSource(QIODevice *outDev, const QString &source)
{
/* saving a new file */
if(!archive) {
if (source == "text/x-xml-tableviewer") {
archive = new DBXml(this);
} else if (source == "text/x-xml-tableviewer") {
archive = new DBCsv(this);
} else
return false;
}
/* changing file type */
if(archive->type() != source) {
delete archive;
if (source == "text/x-xml-tableviewer") {
archive = new DBXml(this);
} else if (source == "text/x-xml-tableviewer") {
archive = new DBCsv(this);
} else
return false;
}
return (archive->saveSource(outDev));
}
/*!
This function is used to add new elements to the database. If the database
has already reached the maximum allowable size this function does not alter
the database.
\param delm An already allocated and initialized data element to be added
*/
void DBStore::addItem(DataElem *delem)
{
addItemInternal(delem);
}
void DBStore::addItemInternal(DataElem *delem)
{
/* if already full, don't over fill, do a qWarning though */
if (full) {
- qWarning("Attempted to add items to already full table");
+ owarn << "Attempted to add items to already full table" << oendl;
return;
}
master_table.insert(number_elems, delem);
current_elem = number_elems;
number_elems++;
if(number_elems >= table_size) {
/* filled current table, double if we can */
table_size = table_size << 1;
/* check that the new table size is still valid, i.e. that we didn't
just shift the 1 bit of the end of the int. */
if (!table_size) {
full = true;
/* no point in doing antying else. */
return;
}
master_table.resize(table_size);
}
}
void DBStore::removeItem(DataElem *r)
{
int position = master_table.findRef(r);
if(position != -1) {
/* there is at least one item, this is it */
/* replace this with the last element, decrease the element count */
master_table.insert(position, master_table.at(--number_elems));
master_table.remove(number_elems);
delete r;
}
}
/*!
Sets the name of the database
\param n A string representing the new name of the database.
*/
void DBStore::setName(const QString &n)
{
name = n;
}
/*!
Gets the name of the database
\return A string representing the name of the database.
*/
QString DBStore::getName()
{
return name;
}
/*!
Retrieves a pointer to the key representation of the database for
other classes to use as reference.
\return a pointer to the databases key representaion
*/
KeyList *DBStore::getKeys()
{
return kRep;
}
/*!
sets the database's key representation the passed pointer
\param a pointer to a key representaton
*/
void DBStore::setKeys(KeyList *k)
{
kRep = k;
}
/*!
Sets the current element to the first element of the database
*/
void DBStore::first()
{
current_elem = 0;
}
/*!
Sets the current element to the last element of the database
*/
void DBStore::last()
{
current_elem = number_elems - 1;
}
/*!
Sets the current element to the next element of the database if
there exists an element after the current one.
*/
bool DBStore::next()
diff --git a/noncore/apps/tableviewer/db/xmlsource.cpp b/noncore/apps/tableviewer/db/xmlsource.cpp
index 94fec36..4ca6aee 100644
--- a/noncore/apps/tableviewer/db/xmlsource.cpp
+++ b/noncore/apps/tableviewer/db/xmlsource.cpp
@@ -1,297 +1,303 @@
/**********************************************************************
** 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 "xmlsource.h"
-#include <qdict.h>
-#include <stdlib.h>
-#include <qtextstream.h>
#include "../xmlencodeattr.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+/* QT */
+#include <qdict.h>
+#include <qtextstream.h>
+
+/* STD */
+#include <stdlib.h>
DBXml::DBXml(DBStore *d)
{
dstore = d;
}
QString DBXml::type()
{
return "xml";
}
bool DBXml::openSource(QIODevice *inDev)
{
bool ok;
DBXmlHandler h(dstore);
QTextStream tsIn(inDev);
QXmlInputSource source(tsIn);
QXmlSimpleReader reader;
reader.setContentHandler(&h);
reader.setErrorHandler(&h);
ok = reader.parse(source);
return ok;
}
bool DBXml::saveSource(QIODevice *outDev)
{
int i;
DataElem *elem;
KeyList *k;
QTextStream outstream(outDev);
outstream << "<database name=\"" << dstore->getName() << "\">" << endl;
outstream << "<header>" << endl;
k = dstore->getKeys();
KeyListIterator it(*k);
while(it.current()) {
if (!it.current()->delFlag()) {
outstream << "<key name=\"KEYID" << it.currentKey() << "\" ";
outstream << "type=\""
<< TVVariant::typeToName(it.current()->type())
<< "\">";
outstream << encodeAttr(it.current()->name()) << "</key>" << endl;
}
++it;
}
outstream << "</header>" << endl;
dstore->first();
do {
elem = dstore->getCurrentData();
if (!elem)
break;
outstream << "<record>" << endl;
it.toFirst();
while (it.current()) {
i = it.currentKey();
if (elem->hasValidValue(i)) {
outstream << "<KEYID" << i << ">";
if (dstore->getKeyType(i) == TVVariant::Date) {
// dates in files are different from displayed dates
QDate date = elem->getField(i).toDate();
outstream << date.day() << "/"
<< date.month() << "/"
<< date.year();
} else {
outstream << encodeAttr(elem->toQString(i));
}
outstream << "</KEYID" << i << ">" << endl;
}
++it;
}
outstream << "</record>" << endl;
} while(dstore->next());
outstream << "</database>" << endl;
return TRUE;
}
DBXml::~DBXml() {}
/*!
\class DBXmlHandler
\brief An Xml parser for flat tables.
An xml parser for parsing the files used by the table viewer application.
The format of the xml files can be found at the front of the file
dataparser.h
*/
/*!
Constructs a new DBXmlHandler, and sets that the table should be
constructed in the DBStore pointed to by ds.
*/
DBXmlHandler::DBXmlHandler(DBStore *ds)
{
data_store = ds;
current_keyrep = 0;
}
/*!
Destroys the DBXmlHandler
*/
DBXmlHandler::~DBXmlHandler()
{
}
QString DBXmlHandler::errorProtocol()
{
- qWarning("Error reading file");
+ owarn << "Error reading file" << oendl;
return errorProt;
}
bool DBXmlHandler::startDocument()
{
errorProt = "";
state = StateInit;
return TRUE;
}
bool DBXmlHandler::startElement(const QString&, const QString&,
const QString& qName, const QXmlAttributes& atts)
{
if (state == StateInit && qName == "database") {
// First thing it expects is a <document name="..."> tag
state = StateDocument;
data_store->setName(atts.value("name"));
return TRUE;
}
if (state == StateDocument && qName == "header") {
state = StateHeader;
if (current_keyrep) delete current_keyrep;
current_keyrep = new KeyList();
return TRUE;
}
if (state == StateHeader && qName == "key") {
/* Ok, adding a new key to our KeyList TODO */
state = StateKey;
last_key_type = TVVariant::String;
key = atts.value("name");
if (key.isEmpty()) {
- qWarning("empty key name");
+ owarn << "empty key name" << oendl;
return FALSE;
}
if(!atts.value("type").isEmpty())
last_key_type = TVVariant::nameToType(atts.value("type"));
return TRUE;
}
if (state == StateDocument && qName == "record") {
state = StateRecord;
current_data = new DataElem(data_store);
// Now expecting a <record> tag
return TRUE;
}
if (state == StateRecord) {
state = StateField;
/* the qName is the name of a key */
if (!keyIndexList[qName]) {
/* invalid key, we failed */
- qWarning("Invalid key in record");
+ owarn << "Invalid key in record" << oendl;
return FALSE;
}
keyIndex = *keyIndexList[qName];
return TRUE;
}
- qWarning("Unable to determine tag type");
+ owarn << "Unable to determine tag type" << oendl;
return FALSE;
}
bool DBXmlHandler::endElement(const QString&, const QString&,
const QString& qName)
{
switch(state) {
case StateField:
// TODO checks 'could' be done of the popped value
state = StateRecord;
break;
case StateKey:
// TODO checks 'could' be done of the popped value
state = StateHeader;
break;
case StateHeader:
data_store->setKeys(current_keyrep);
state = StateDocument;
break;
case StateRecord:
data_store->addItem(current_data);
state = StateDocument;
break;
case StateDocument:
// we are done...
break;
default:
// should only get a 'endElement' from one of the above states.
- qWarning("Invalid end tag");
+ owarn << "Invalid end tag" << oendl;
return FALSE;
break;
}
return TRUE;
}
bool DBXmlHandler::characters(const QString& ch)
{
// this is where the 'between tag' stuff happens.
// e.g. the stuff between tags.
QString ch_simplified = ch.simplifyWhiteSpace();
if (ch_simplified.isEmpty())
return TRUE;
if (state == StateKey) {
int *tmp_val = new int;
/* We just grabbed the display name of a key */
*tmp_val = current_keyrep->addKey(ch_simplified, last_key_type);
keyIndexList.insert(key, tmp_val);
return TRUE;
}
if (state == StateField) {
/* Ok, need to add data here */
current_data->setField(keyIndex, ch_simplified);
return TRUE;
}
- qWarning("Junk characters found... ignored");
+ owarn << "Junk characters found... ignored" << oendl;
return TRUE;
}
QString DBXmlHandler::errorString()
{
return "the document is not in the expected file format";
}
bool DBXmlHandler::warning(const QXmlParseException& exception)
{
errorProt += QString("warning parsing error: %1 in line %2, column %3\n" )
.arg(exception.message())
.arg(exception.lineNumber())
.arg(exception.columnNumber());
- qWarning(errorProt);
+ owarn << errorProt << oendl;
return QXmlDefaultHandler::fatalError(exception);
}
bool DBXmlHandler::error(const QXmlParseException& exception)
{
errorProt += QString("error parsing error: %1 in line %2, column %3\n" )
.arg(exception.message())
.arg(exception.lineNumber())
.arg(exception.columnNumber());
- qWarning(errorProt);
+ owarn << errorProt << oendl;
return QXmlDefaultHandler::fatalError(exception);
}
bool DBXmlHandler::fatalError(const QXmlParseException& exception)
{
errorProt += QString("fatal parsing error: %1 in line %2, column %3\n" )
.arg(exception.message())
.arg(exception.lineNumber())
.arg(exception.columnNumber());
- qWarning(errorProt);
+ owarn << errorProt << oendl;
return QXmlDefaultHandler::fatalError(exception);
}
diff --git a/noncore/apps/tableviewer/tableviewer.cpp b/noncore/apps/tableviewer/tableviewer.cpp
index 102b94c..9538cb3 100644
--- a/noncore/apps/tableviewer/tableviewer.cpp
+++ b/noncore/apps/tableviewer/tableviewer.cpp
@@ -1,387 +1,389 @@
/**********************************************************************
** 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 */
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/fileselector.h>
#include <qpe/resource.h>
-#include <qtoolbar.h>
+using namespace Opie::Core;
-/* QTE includes */
+/* QT */
#include <qmenubar.h>
+#include <qtoolbar.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 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 QToolBar(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");
+ owarn << "Save unsuccessful" << oendl;
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"));
+ owarn << tr("could not load Document") << oendl;
}
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);
}
diff --git a/noncore/apps/tableviewer/tableviewer.pro b/noncore/apps/tableviewer/tableviewer.pro
index 1de23bb..564f50f 100644
--- a/noncore/apps/tableviewer/tableviewer.pro
+++ b/noncore/apps/tableviewer/tableviewer.pro
@@ -1,38 +1,38 @@
-CONFIG = qt warn_on quick-app
+CONFIG = qt warn_on quick-app
SUBDIRS = db ui
HEADERS = tableviewer.h \
xmlencodeattr.h \
ui/commonwidgets.h \
ui/tvbrowseview.h \
ui/tvlistview.h \
ui/tvfilterview.h \
ui/tveditview.h \
ui/browsekeyentry.h \
ui/filterkeyentry.h \
ui/tvkeyedit.h \
db/datacache.h \
db/common.h \
db/xmlsource.h \
db/csvsource.h
SOURCES = main.cpp \
tableviewer.cpp \
xmlencodeattr.cpp \
ui/commonwidgets.cpp \
ui/tvbrowseview.cpp \
ui/tvfilterview.cpp \
ui/browsekeyentry.cpp \
ui/filterkeyentry.cpp \
ui/tvlistview.cpp \
ui/tveditview.cpp \
ui/tvkeyedit.cpp \
db/datacache.cpp \
db/xmlsource.cpp \
db/csvsource.cpp \
db/common.cpp
INTERFACES = ui/tvkeyedit_gen.ui
TARGET = tableviewer
-INCLUDEPATH += $(OPIEDIR)/include
-DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lopiecore2
+INCLUDEPATH += $(OPIEDIR)/include
+DEPENDPATH += $(OPIEDIR)/include
+LIBS += -lqpe -lopiecore2
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/tableviewer/ui/tvlistview.cpp b/noncore/apps/tableviewer/ui/tvlistview.cpp
index b10ff1d..c3e6432 100644
--- a/noncore/apps/tableviewer/ui/tvlistview.cpp
+++ b/noncore/apps/tableviewer/ui/tvlistview.cpp
@@ -1,262 +1,269 @@
/**********************************************************************
** 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 "tvlistview.h"
#include "../db/common.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qtoolbutton.h>
#include <qlistview.h>
#include <qlayout.h>
void TVListViewPrivate::setColumnWidth(int column, int width)
{
if(width > 70) width = 70;
QListView::setColumnWidth(column, width);
}
void TVListViewPrivate::setSorting(int column, bool increasing)
{
emit sortChanged(column);
QListView::setSorting(column, increasing);
}
TVListViewPrivate::TVListViewPrivate(QWidget *parent, const char* name,
WFlags fl) : QListView(parent, name, fl) {
;
}
class TVListViewItem : public QListViewItem
{
public:
TVListViewItem(QListView *parent, DataElem *d);
~TVListViewItem();
QString text(int i) const
{
return data_reference->toQString(i);
}
/* Do nothing... all data for this item should be generated */
void setText(int i, const QString &)
{
;
}
QString key(int i, bool a) const
{
return data_reference->toSortableQString(i);
}
void setDataElem(DataElem *d)
{
data_reference = d;
}
DataElem *getDataElem() {
return data_reference;
}
private:
DataElem *data_reference;
};
TVListViewItem::TVListViewItem(QListView *parent, DataElem *d)
: QListViewItem(parent)
{
data_reference = d;
}
TVListViewItem::~TVListViewItem()
{
data_reference = 0;
}
TVListView::TVListView(TableState *t, QWidget* parent,
const char *name, WFlags fl ) : QWidget(parent, name, fl)
{
if (!name)
setName("TVListView");
// the next two lines need to be rationalized.
resize(318,457);
setSizePolicy(QSizePolicy((QSizePolicy::SizeType)7,
(QSizePolicy::SizeType)7, sizePolicy().hasHeightForWidth()));
setCaption(tr("List View"));
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setSpacing(0);
layout->setMargin(0);
listViewDisplay = new TVListViewPrivate(this, "listViewDisplay");
layout->addWidget(listViewDisplay);
connect(listViewDisplay, SIGNAL(currentChanged(QListViewItem*)), this,
SLOT(setCurrent(QListViewItem*)));
connect(listViewDisplay, SIGNAL(sortChanged(int)), this,
SLOT(setSorting(int)));
listViewDisplay->setShowSortIndicator(true);
it = new QListViewItemIterator(listViewDisplay);
ts = t;
}
TVListView::~TVListView()
{
}
void TVListView::addItem(DataElem *d)
{
TVListViewItem *i = new TVListViewItem(listViewDisplay, d);
delete it;
it = new QListViewItemIterator(i);
}
/* remove current (it) item */
void TVListView::removeItem()
{
QListViewItemIterator other(*it);
QListViewItemIterator tmp = *it;
(*it)++;
if (!it->current()) {
*it = tmp;
(*it)--;
if (!it->current()) {
delete it;
it = 0;
}
}
delete other.current();
}
void TVListView::clearItems()
{
/* This is ok since the destructor for TVListItem does not know about
the data_reference pointer.. and hence will leave it alone */
listViewDisplay->clear();
delete it;
it = new QListViewItemIterator(listViewDisplay);
}
void TVListView::first()
{
delete it;
it = new QListViewItemIterator(listViewDisplay);
}
void TVListView::last()
{
- qWarning("TVListView::last not yet implemented");
+ owarn << "TVListView::last not yet implemented" << oendl;
}
void TVListView::next()
{
QListViewItemIterator tmp = *it;
(*it)++;
if (!it->current()) {
*it = tmp;
}
}
void TVListView::previous()
{
QListViewItemIterator tmp = *it;
(*it)--;
if (!it->current()) {
*it = tmp;
}
}
DataElem *TVListView::getCurrentData() {
if (it->current()) {
return ((TVListViewItem *)it->current())->getDataElem();
}
return NULL;
}
/*! Now to implement the closest match function */
void TVListView::findItem(int keyId, TVVariant value)
{
QListViewItem *i;
TVListViewItem *best_so_far = NULL;
/* start at the beginning... go through till find the closest elem */
i = listViewDisplay->firstChild();
while (i) {
/* search stuff */
if(best_so_far) {
if (DataElem::closer(
((TVListViewItem *)i)->getDataElem(),
best_so_far->getDataElem(), value, keyId))
best_so_far = (TVListViewItem *)i;
} else {
if (DataElem::closer(
((TVListViewItem *)i)->getDataElem(),
NULL, value, keyId))
best_so_far = (TVListViewItem *)i;
}
i = i->itemBelow();
}
if (best_so_far) {
/* set best_so_far to current element */
delete it;
it = new QListViewItemIterator(best_so_far);
}
}
void TVListView::rebuildKeys()
{
int i;
if(!ts) return;
if(!ts->kRep) return;
i = listViewDisplay->columns();
while(i > 0)
listViewDisplay->removeColumn(--i);
KeyListIterator kit(*ts->kRep);
i = 0;
while(kit.current()) {
if(!kit.current()->delFlag()) {
listViewDisplay->addColumn(kit.current()->name());
keyIds.insert(i, kit.currentKey());
++i;
}
++kit;
}
}
void TVListView::setSorting(int column)
{
/* Without table state can't do anything */
if (ts == 0)
return;
if (keyIds[column] != ts->current_column) {
ts->current_column = keyIds[column];
}
}
void TVListView::rebuildData() {
int i;
QMap<int, int>::Iterator kit;
/* Need to set sort order */
if(!ts)
diff --git a/noncore/apps/tinykate/libkate/libkate.pro b/noncore/apps/tinykate/libkate/libkate.pro
index 11ee275..1552dff 100644
--- a/noncore/apps/tinykate/libkate/libkate.pro
+++ b/noncore/apps/tinykate/libkate/libkate.pro
@@ -1,90 +1,87 @@
TEMPLATE = lib
-CONFIG = qt warn_on
-HEADERS = microkde/kapplication.h \
- kateconfig.h \
- microkde/kdebug.h \
- microkde/kdialog.h \
- microkde/kdialogbase.h \
- microkde/kfiledialog.h \
- microkde/kglobal.h \
- microkde/kiconloader.h \
- microkde/klineedit.h \
- microkde/klocale.h \
- microkde/kmessagebox.h \
- microkde/kprinter.h \
- microkde/krestrictedline.h \
- microkde/kseparator.h \
- microkde/kstandarddirs.h \
- microkde/ktempfile.h \
- microkde/kunload.h \
- microkde/kurlrequester.h \
- microkde/kfontdialog.h \
- microkde/krun.h \
- microkde/knumvalidator.h \
- microkde/kstaticdeleter.h \
- microkde/klistview.h \
- microkde/kglobalsettings.h \
- microkde/kcolorbtn.h \
- \
+CONFIG = qt warn_on
+HEADERS = microkde/kapplication.h \
+ kateconfig.h \
+ microkde/kdebug.h \
+ microkde/kdialog.h \
+ microkde/kdialogbase.h \
+ microkde/kfiledialog.h \
+ microkde/kglobal.h \
+ microkde/kiconloader.h \
+ microkde/klineedit.h \
+ microkde/klocale.h \
+ microkde/kmessagebox.h \
+ microkde/kprinter.h \
+ microkde/krestrictedline.h \
+ microkde/kseparator.h \
+ microkde/kstandarddirs.h \
+ microkde/ktempfile.h \
+ microkde/kunload.h \
+ microkde/kurlrequester.h \
+ microkde/kfontdialog.h \
+ microkde/krun.h \
+ microkde/knumvalidator.h \
+ microkde/kstaticdeleter.h \
+ microkde/klistview.h \
+ microkde/kglobalsettings.h \
+ microkde/kcolorbtn.h \
\
- qt3back/qregexp3.h \
- microkde/ksharedptr.h \
- document/katebuffer.h document/katedialogs.h \
- document/katetextline.h \
- document/katecmd.h \
- document/katehighlight.h \
- document/katecmds.h document/katedocument.h \
- document/katesyntaxdocument.h \
- view/kateundohistory.h \
- view/kateview.h \
- view/kateviewdialog.h \
- interfaces/view.h \
- interfaces/document.h \
- ktexteditor/ktexteditor.h
+ qt3back/qregexp3.h \
+ microkde/ksharedptr.h \
+ document/katebuffer.h document/katedialogs.h \
+ document/katetextline.h \
+ document/katecmd.h \
+ document/katehighlight.h \
+ document/katecmds.h document/katedocument.h \
+ document/katesyntaxdocument.h \
+ view/kateundohistory.h \
+ view/kateview.h \
+ view/kateviewdialog.h \
+ interfaces/view.h \
+ interfaces/document.h \
+ ktexteditor/ktexteditor.h
-SOURCES = microkde/kapplication.cpp \
- microkde/kdialogbase.cpp \
- kateconfig.cpp \
- microkde/klocale.cpp \
- microkde/kmessagebox.cpp \
- microkde/kprocess.cpp \
- microkde/kstandarddirs.cpp \
- microkde/ktempfile.cpp \
- microkde/kurlrequester.cpp \
- microkde/kfontdialog.cpp \
- microkde/krun.cpp \
- microkde/knumvalidator.cpp \
- microkde/kglobal.cpp \
- microkde/kglobalsettings.cpp \
- microkde/kcolorbtn.cpp \
- \
- \
- qt3back/qregexp3.cpp \
- ktexteditor/ktexteditor.cpp \
- document/katebuffer.cpp document/katedialogs.cpp \
- document/katehighlight.cpp \
- document/katecmd.cpp \
- document/katesyntaxdocument.cpp document/katecmds.cpp \
- document/katedocument.cpp document/katetextline.cpp \
- view/kateundohistory.cpp \
- view/kateview.cpp \
- view/kateviewdialog.cpp \
- interfaces/interfaces.cpp
-
-INTERFACES =
-INCLUDEPATH += $(OPIEDIR)/include \
+SOURCES = microkde/kapplication.cpp \
+ microkde/kdialogbase.cpp \
+ kateconfig.cpp \
+ microkde/klocale.cpp \
+ microkde/kmessagebox.cpp \
+ microkde/kprocess.cpp \
+ microkde/kstandarddirs.cpp \
+ microkde/ktempfile.cpp \
+ microkde/kurlrequester.cpp \
+ microkde/kfontdialog.cpp \
+ microkde/krun.cpp \
+ microkde/knumvalidator.cpp \
+ microkde/kglobal.cpp \
+ microkde/kglobalsettings.cpp \
+ microkde/kcolorbtn.cpp \
+ \
+ qt3back/qregexp3.cpp \
+ ktexteditor/ktexteditor.cpp \
+ document/katebuffer.cpp document/katedialogs.cpp \
+ document/katehighlight.cpp \
+ document/katecmd.cpp \
+ document/katesyntaxdocument.cpp document/katecmds.cpp \
+ document/katedocument.cpp document/katetextline.cpp \
+ view/kateundohistory.cpp \
+ view/kateview.cpp \
+ view/kateviewdialog.cpp \
+ interfaces/interfaces.cpp
+INTERFACES =
+INCLUDEPATH += $(OPIEDIR)/include \
$(OPIEDIR)/noncore/apps/tinykate/libkate \
$(OPIEDIR)/noncore/apps/tinykate/libkate/microkde \
$(OPIEDIR)/noncore/apps/tinykate/libkate/document \
$(OPIEDIR)/noncore/apps/tinykate/libkate/view \
$(OPIEDIR)/noncore/apps/tinykate/libkate/interfaces \
$(OPIEDIR)/noncore/apps/tinykate/libkate/ktexteditor \
$(OPIEDIR)/noncore/apps/tinykate/libkate/qt3back
-DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lqtaux2 -lopiecore2 -lopieui2
-TARGET = tinykate
+DEPENDPATH += $(OPIEDIR)/include
+LIBS += -lqpe -lqtaux2 -lopiecore2 -lopieui2
+TARGET = tinykate
INCLUDEPATH += $(OPIEDIR)/include
DESTDIR = $(OPIEDIR)/lib$(PROJMAK)
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/tinykate/tinykate.pro b/noncore/apps/tinykate/tinykate.pro
index 6f4baa8..d34e519 100644
--- a/noncore/apps/tinykate/tinykate.pro
+++ b/noncore/apps/tinykate/tinykate.pro
@@ -1,22 +1,20 @@
-TEMPLATE = app
-CONFIG = qt warn_on quick-app
+TEMPLATE = app
+CONFIG = qt warn_on quick-app
DESTDIR = $(OPIEDIR)/bin
HEADERS = tinykate.h
SOURCES = tinykate.cpp main.cpp
-INTERFACES =
INCLUDEPATH += $(OPIEDIR)/include \
- $(OPIEDIR)/noncore/apps/tinykate/libkate \
- $(OPIEDIR)/noncore/apps/tinykate/libkate/microkde \
- $(OPIEDIR)/noncore/apps/tinykate/libkate/document \
- $(OPIEDIR)/noncore/apps/tinykate/libkate/view \
- $(OPIEDIR)/noncore/apps/tinykate/libkate/interfaces \
- $(OPIEDIR)/noncore/apps/tinykate/libkate/ktexteditor \
- $(OPIEDIR)/noncore/apps/tinykate/libkate/qt3back
-
-DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -ltinykate -lopiecore2 -lopieui2
-TARGET = kate
+ $(OPIEDIR)/noncore/apps/tinykate/libkate \
+ $(OPIEDIR)/noncore/apps/tinykate/libkate/microkde \
+ $(OPIEDIR)/noncore/apps/tinykate/libkate/document \
+ $(OPIEDIR)/noncore/apps/tinykate/libkate/view \
+ $(OPIEDIR)/noncore/apps/tinykate/libkate/interfaces \
+ $(OPIEDIR)/noncore/apps/tinykate/libkate/ktexteditor \
+ $(OPIEDIR)/noncore/apps/tinykate/libkate/qt3back
+DEPENDPATH += $(OPIEDIR)/include
+LIBS += -lqpe -ltinykate -lopiecore2 -lopieui2
+TARGET = kate
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/apps/zsafe/config.in b/noncore/apps/zsafe/config.in
index 6e321f3..b6d3ffe 100644
--- a/noncore/apps/zsafe/config.in
+++ b/noncore/apps/zsafe/config.in
@@ -1,5 +1,5 @@
config ZSAFE
boolean "zsafe (Zaurus Password Manager)"
default "y"
- depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && LIBOPIE2UI
diff --git a/noncore/apps/zsafe/scqtfiledlg.cpp b/noncore/apps/zsafe/scqtfiledlg.cpp
index 52b8d0d..c67bbd5 100644
--- a/noncore/apps/zsafe/scqtfiledlg.cpp
+++ b/noncore/apps/zsafe/scqtfiledlg.cpp
@@ -1,106 +1,103 @@
-/****************************************************************************
-** Form implementation generated from reading ui file 'scqtfiledlg.ui'
-**
-** Created: Sun Jun 8 15:51:12 2003
-** by: The User Interface Compiler (uic)
-**
-** WARNING! All changes made in this file will be lost!
-****************************************************************************/
#include "scqtfiledlg.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qcombobox.h>
#include <qlineedit.h>
#include <qlistview.h>
#include <qtoolbutton.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
static const char* const image0_data[] = {
"24 16 3 1",
". c None",
"# c #000040",
"a c #808080",
"........................",
"........................",
".................####...",
".................####...",
".......##........#aa#...",
"......###........#aa#...",
".....####........#aa#...",
"....##############aa#...",
"...###aaaaaaaaaaaaaa#...",
"..####aaaaaaaaaaaaaa#...",
"...###aaaaaaaaaaaaaa#...",
"....#################...",
".....####...............",
"......###...............",
".......##...............",
"........................"};
static const char* const image1_data[] = {
"24 16 4 1",
". c None",
"a c #008080",
"b c #808080",
"# c #ff0000",
"........................",
"........................",
"...####..........####...",
"...#####........#####...",
"....######.....#####a...",
".....######...#####ba...",
".....aa###########bba...",
"....aaaaa#######aabba...",
"...aaabbb######bbbbba...",
"..aaaabb########bbbba...",
"...aaa############bba...",
"....a######aaa#####aa...",
"....######.....######...",
"...#####a........####...",
"...####aa.........###...",
"........................"};
static const char* const image2_data[] = {
"17 15 4 1",
"# c #000000",
". c #dcdcdc",
"a c #ffff00",
"b c #ffffff",
".................",
"............#....",
".................",
"............#....",
".........#.....#.",
"....####..#.#.#..",
"...#abab#..#.#...",
"..##########..#.#",
"..#babababab##...",
"..#ababababa#.#..",
"..#babababab#..#.",
"..#ababababa#....",
"..#babababab#....",
"..#ababababa#....",
"..###########...."};
/*
* Constructs a ScQtFileDlg which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*
* The dialog will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal dialog.
*/
ScQtFileDlg::ScQtFileDlg( QWidget* parent, const char* name, bool modal, WFlags fl )
: QDialog( parent, name, modal, fl )
{
QPixmap image0( ( const char** ) image0_data );
QPixmap image1( ( const char** ) image1_data );
QPixmap image2( ( const char** ) image2_data );
if ( !name )
setName( "ScQtFileDlg" );
resize( 196, 279 );
if (!name)
setCaption( tr( "FileDlg" ) );
else
setCaption(name);
@@ -123,134 +120,134 @@ ScQtFileDlg::ScQtFileDlg( QWidget* parent, const char* name, bool modal, WFlags
TypeComboBox = new QComboBox( FALSE, this, "TypeComboBox" );
TypeComboBox->setEditable( TRUE );
TypeComboBox->setInsertionPolicy( QComboBox::AtBottom );
TypeComboBox->setAutoCompletion( FALSE );
TypeComboBox->setDuplicatesEnabled( FALSE );
QToolTip::add( TypeComboBox, tr( "file type filter" ) );
QWhatsThis::add( TypeComboBox, tr( "ComboBox FileTypeFilter\n"
"\n"
"edit or select the filter" ) );
Layout3->addWidget( TypeComboBox );
QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
Layout3->addItem( spacer );
OkButton = new QToolButton( this, "OkButton" );
OkButton->setText( tr( "" ) );
OkButton->setPixmap( image0 );
OkButton->setUsesBigPixmap( FALSE );
QToolTip::add( OkButton, tr( "confirms the selection and closes the form" ) );
QWhatsThis::add( OkButton, tr( "OKButton" ) );
Layout3->addWidget( OkButton );
CancelButton = new QToolButton( this, "CancelButton" );
CancelButton->setText( tr( "" ) );
CancelButton->setPixmap( image1 );
CancelButton->setUsesBigPixmap( FALSE );
QToolTip::add( CancelButton, tr( "cancels the selection and closes the form" ) );
QWhatsThis::add( CancelButton, tr( "CancelButton" ) );
Layout3->addWidget( CancelButton );
Layout4->addLayout( Layout3 );
Layout3_2 = new QHBoxLayout;
Layout3_2->setSpacing( 6 );
Layout3_2->setMargin( 0 );
FNameLineEdit = new QLineEdit( this, "FNameLineEdit" );
QToolTip::add( FNameLineEdit, tr( "shows the selected filename" ) );
QWhatsThis::add( FNameLineEdit, tr( "Filename LineEdit\n"
"\n"
"shows the selected file\n"
"and allows the direct filename\n"
"edit" ) );
Layout3_2->addWidget( FNameLineEdit );
MkDirButton = new QToolButton( this, "MkDirButton" );
MkDirButton->setText( tr( "" ) );
MkDirButton->setPixmap( image2 );
MkDirButton->setUsesBigPixmap( FALSE );
QToolTip::add( MkDirButton, tr( "confirms the selection and closes the form" ) );
QWhatsThis::add( MkDirButton, tr( "OKButton" ) );
Layout3_2->addWidget( MkDirButton );
Layout4->addLayout( Layout3_2 );
DirComboBox = new QComboBox( FALSE, this, "DirComboBox" );
DirComboBox->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)7, (QSizePolicy::SizeType)0, DirComboBox->sizePolicy().hasHeightForWidth() ) );
DirComboBox->setEditable( TRUE );
DirComboBox->setDuplicatesEnabled( FALSE );
QWhatsThis::add( DirComboBox, tr( "ComboBox Directory \n"
"edit or select the directories name" ) );
Layout4->addWidget( DirComboBox );
Layout5->addLayout( Layout4 );
ListView = new QListView( this, "ListView" );
ListView->addColumn( tr( "Name" ) );
ListView->addColumn( tr( "size" ) );
ListView->addColumn( tr( "type" ) );
ListView->setRootIsDecorated( TRUE );
QToolTip::add( ListView, tr( "directory listview" ) );
QWhatsThis::add( ListView, tr( "Directory ListView\n"
"\n"
"shows the list of dirs and files" ) );
Layout5->addWidget( ListView );
ScQtFileDlgLayout->addLayout( Layout5 );
// signals and slots connections
connect( OkButton, SIGNAL( clicked() ), this, SLOT( slotOK() ) );
connect( DirComboBox, SIGNAL( activated(int) ), this, SLOT( slotDirComboBoxChanged(int) ) );
connect( TypeComboBox, SIGNAL( activated(int) ), this, SLOT( slotTypeComboBoxChanged(int) ) );
connect( CancelButton, SIGNAL( clicked() ), this, SLOT( slotCancel() ) );
connect( ListView, SIGNAL( returnPressed(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem*) ) );
connect( ListView, SIGNAL( selectionChanged(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem*) ) );
connect( ListView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( slotDoubleClicked(QListViewItem*) ) );
connect( FNameLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotFileTextChanged(const QString&) ) );
connect( FNameLineEdit, SIGNAL( returnPressed() ), this, SLOT( slotOK() ) );
connect( MkDirButton, SIGNAL( clicked() ), this, SLOT( slotMkDir() ) );
}
/*
* Destroys the object and frees any allocated resources
*/
ScQtFileDlg::~ScQtFileDlg()
{
// no need to delete child widgets, Qt does it all for us
}
void ScQtFileDlg::slotCancel()
{
- qWarning( "ScQtFileDlg::slotCancel(): Not implemented yet!" );
+ owarn << "ScQtFileDlg::slotCancel(): Not implemented yet!" << oendl;
}
void ScQtFileDlg::slotDirComboBoxChanged( int )
{
- qWarning( "ScQtFileDlg::slotDirComboBoxChanged( int ): Not implemented yet!" );
+ owarn << "ScQtFileDlg::slotDirComboBoxChanged( int ): Not implemented yet!" << oendl;
}
void ScQtFileDlg::slotDoubleClicked(QListViewItem *)
{
- qWarning( "ScQtFileDlg::slotDoubleClicked(QListViewItem *): Not implemented yet!" );
+ owarn << "ScQtFileDlg::slotDoubleClicked(QListViewItem *): Not implemented yet!" << oendl;
}
void ScQtFileDlg::slotFileTextChanged( const QString & )
{
- qWarning( "ScQtFileDlg::slotFileTextChanged( const QString & ): Not implemented yet!" );
+ owarn << "ScQtFileDlg::slotFileTextChanged( const QString & ): Not implemented yet!" << oendl;
}
void ScQtFileDlg::slotMkDir()
{
- qWarning( "ScQtFileDlg::slotMkDir(): Not implemented yet!" );
+ owarn << "ScQtFileDlg::slotMkDir(): Not implemented yet!" << oendl;
}
void ScQtFileDlg::slotOK()
{
- qWarning( "ScQtFileDlg::slotOK(): Not implemented yet!" );
+ owarn << "ScQtFileDlg::slotOK(): Not implemented yet!" << oendl;
}
void ScQtFileDlg::slotSelectionChanged(QListViewItem *)
{
- qWarning( "ScQtFileDlg::slotSelectionChanged(QListViewItem *): Not implemented yet!" );
+ owarn << "ScQtFileDlg::slotSelectionChanged(QListViewItem *): Not implemented yet!" << oendl;
}
void ScQtFileDlg::slotTypeComboBoxChanged( int )
{
- qWarning( "ScQtFileDlg::slotTypeComboBoxChanged( int ): Not implemented yet!" );
+ owarn << "ScQtFileDlg::slotTypeComboBoxChanged( int ): Not implemented yet!" << oendl;
}
diff --git a/noncore/apps/zsafe/zsafe.cpp b/noncore/apps/zsafe/zsafe.cpp
index 3df55eb..bf8f7f4 100644
--- a/noncore/apps/zsafe/zsafe.cpp
+++ b/noncore/apps/zsafe/zsafe.cpp
@@ -1,138 +1,137 @@
/****************************************************************************
**
** Created: Sat Apr 6 17:57:45 2002
**
** Author: Carsten Schneider <CarstenSchneider@t-online.de>
**
** $Id$
**
** Homepage: http://home.t-online.de/home/CarstenSchneider/zsafe/index.html
**
** Compile Flags:
** Zaurus arm : -DNO_OPIE
** Zaurus Opie arm: none
** Linux Desktop : -DDESKTOP
** Windows Desktop: -DDESKTOP -DWIN32
**
** for japanese version additional use: -DJPATCH_HDE
**
****************************************************************************/
#include "zsafe.h"
#include "newdialog.h"
#include "searchdialog.h"
#include "categorydialog.h"
#include "passworddialog.h"
#include "infoform.h"
#include "zlistview.h"
#include "shadedlistitem.h"
#ifndef DESKTOP
#ifndef NO_OPIE
#include <opie2/ofiledialog.h>
-
+#include <opie2/odebug.h>
+using namespace Opie::Core;
using namespace Opie::Ui;
#else
#include "scqtfileedit.h"
#endif
#endif
#include <qclipboard.h>
-#include <stdio.h>
-
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#ifndef WIN32
#include <unistd.h>
#endif
#include <string.h>
#include <errno.h>
#include <qmenubar.h>
#include <qpopupmenu.h>
#ifdef DESKTOP
#include <qfiledialog.h>
#ifndef WIN32
#include <qsettings.h>
#else
#include "qsettings.h"
#endif
#include <qapplication.h>
#else
#include <qfile.h>
#include <qpe/fileselector.h>
#include <qpe/global.h>
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
#include <qpe/config.h>
#endif
#include <qtimer.h>
#include <qlayout.h>
#include <qmessagebox.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qheader.h>
#include <qlistview.h>
#include <qtoolbutton.h>
#include <qvariant.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qlineedit.h>
#include <qmultilineedit.h>
#include <qregexp.h>
#include <qdir.h>
#include <qtextbrowser.h>
#include <qlabel.h>
#include <qcombobox.h>
#include "krc2.h"
#include "wait.h"
extern int DeskW, DeskH;
#ifdef DESKTOP
extern QApplication *appl;
#else
extern QPEApplication *appl;
#endif
#ifdef JPATCH_HDE
#define tr(arg) arg
#endif
#ifdef DESKTOP
#ifndef WIN32
const QString APP_KEY="/.zsafe/";
#else
const QString APP_KEY="";
#endif
#else
const QString APP_KEY="";
#endif
// include xmp images
#include "pics/zsafe/copy.xpm"
#include "pics/zsafe/cut.xpm"
#include "pics/zsafe/edit.xpm"
#include "pics/zsafe/editdelete.xpm"
#include "pics/zsafe/find.xpm"
#include "pics/zsafe/folder_open.xpm"
#include "pics/zsafe/help_icon.xpm"
#include "pics/zsafe/new.xpm"
#include "pics/zsafe/paste.xpm"
#include "pics/zsafe/quit_icon.xpm"
#include "pics/zsafe/save.xpm"
#include "pics/zsafe/trash.xpm"
#include "pics/zsafe/expand.xpm"
#include "pics/zsafe/export.xpm"
#include "pics/zsafe/import.xpm"
#include "pics/zsafe/zsafe.xpm"
static const char* const bank_cards_data[] = {
@@ -1976,436 +1975,434 @@ bool ZSafe::openDocument(const char* _filename, const char* )
Category *c1 = new Category();
c1->setCategoryName(category);
QString icon;
QString fullIconPath;
QPixmap *pix;
// #ifndef WIN32
icon = conf->readEntry(APP_KEY+category);
// #endif
bool isIconAv = false;
if (!icon.isEmpty() && !icon.isNull())
{
// build the full path
fullIconPath = iconPath + icon;
pix = new QPixmap (fullIconPath);
if (pix)
{
QImage img = pix->convertToImage();
pix->convertFromImage(img.smoothScale(14,14));
c1->setIconName (icon);
c1->setIcon (*pix);
isIconAv = true;
}
}
if (!isIconAv)
{
c1->setIcon (*getPredefinedIcon(category));
}
c1->setListItem (catI);
c1->initListItem();
categories.insert (c1->getCategoryName(), c1);
numberOfEntries++;
}
for (int count = 0; count < FIELD_SIZE; count++) {
free(entry[count]);
}
retval = loadEntry(entry);
if (retval == 2) {
// m_parent->slotStatusHelpMsg("Last entry loaded");
}
} // end while
if (numberOfEntries == 0)
{
switch( QMessageBox::warning( this, tr("ZSafe"),
tr("Empty document or\nwrong password.\nContinue?"),
tr("&No"), tr("&Yes."),
0
) ) {
case 0: // No
retval = loadFinalize();
exitZs (1);
break;
case 1: // Yes
break;
}
}
retval = loadFinalize();
return true;
}
int ZSafe::loadInit(const char* _filename, const char *password)
{
unsigned int j = 0;
unsigned int keylength=0;
int count=0, count2=0, count3=0;
unsigned char charbuf[8];
unsigned short ciphertext[4];
char key[128];
Krc2* krc2 = new Krc2();
fd = fopen (_filename, "rb");
QFileInfo f (_filename);
load_buffer_length = f.size();
load_buffer_length = ((load_buffer_length / 1024)+1) * 1024 * 2;
if (fd == NULL)
return PWERR_OPEN;
buffer = (char *)malloc(load_buffer_length);
for (j = 0; password[j] != '\0'; j++) {
key[j] = password[j];
}
keylength = j;
krc2->rc2_expandkey (key, keylength, 128);
#ifndef WIN32
size = read(fileno (fd), (unsigned char *) (charbuf + count), 8);
#else
- printf ("LoadInit() read1");
size = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd);
#endif
if (size < 8)
return PWERR_DATA;
for (count = 0; count < 4; count++) {
count2 = count << 1;
iv[count] = charbuf[count2] << 8;
iv[count] += charbuf[count2 + 1];
}
size = 0;
bufferIndex = 0;
#ifndef WIN32
while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) {
while (count < 8) {
count2 = read (fileno (fd), (unsigned char *) (charbuf + count), 8);
#else
- printf ("LoadInit() read2");
while ((count = fread ((unsigned char *) (charbuf), sizeof(unsigned char), 8, fd)) > 0) {
while (count < 8) {
count2 = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd);
#endif
if (count2 == 0) {
return PWERR_DATA;
}
count += count2;
} /* while (count < 8) */
size += 8;
for (count2 = 0; count2 < 8; count2 += 2) {
count3 = count2 >> 1;
ciphertext[count3] = charbuf[count2] << 8;
ciphertext[count3] += charbuf[count2 + 1];
plaintext[count3] = ciphertext[count3] ^ iv[count3];
iv[count3] = plaintext[count3];
} /* for (count2) */
krc2->rc2_decrypt (plaintext);
memcpy ((unsigned char *) (buffer + bufferIndex), plaintext, 8);
bufferIndex += 8;
buffer[bufferIndex + 1] = '\0';
} /* while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) */
size -= buffer[size - 1];
lastcount = 0;
/* This will point to the starting index */
bufferIndex = 0;
return PWERR_GOOD;
}
int ZSafe::loadEntry(char *entry[FIELD_SIZE])
{
/* Strip off PKCS 5 padding
* Should check to make sure it's good here
*/
int count, count1=0;
for (count = lastcount; count < size; count++) {
if ((unsigned char) (buffer[count]) == 255) {
if (buffer[bufferIndex] == '\0') {
bufferIndex++;
}
entry[count1] = (char *) malloc (count - bufferIndex + 1);
memcpy (entry[count1], (unsigned char *) (buffer + bufferIndex), count - bufferIndex);
entry[count1][count - bufferIndex] = '\0';
count++;
bufferIndex = count;
count1++;
if (count1 == FIELD_SIZE) {
lastcount = count;
return 1;
}
} /* if ((unsigned char) (buffer[count]) == 255) */
} /* for (count = 0; count < size; count++) */
return 2;
}
int ZSafe::loadFinalize(void)
{
fclose (fd);
if (buffer) free(buffer);
return PWERR_GOOD;
}
bool ZSafe::saveDocument(const char* _filename,
bool withPwd,
const char* )
{
if (filename.isEmpty())
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("No document defined.\nYou have to create a new document"));
return false;
}
// if (m_password.isEmpty())
// withPwd = true; // the document must be saved with a valid password
if (withPwd)
{
bool pwdOk = FALSE;
while (!pwdOk)
{
getDocPassword(tr("Enter Password"));
if (m_password.isEmpty())
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("Password is empty.\nPlease enter again."));
continue;
}
QString firstPasswd = m_password;
getDocPassword(tr("Reenter Password"));
if (m_password.isEmpty())
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("Password is empty.\nPlease enter again."));
continue;
}
if (firstPasswd != m_password)
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("Passwords must be identical.\nPlease enter again."));
continue;
}
pwdOk = TRUE;
modified = false;
}
}
else if (modified)
{
QString fns(_filename);
fns = fns.right (fns.length() - fns.findRev ('/') - 1);
switch( QMessageBox::information( this, tr("ZSafe"),
tr("Do you want to save ") + fns + tr("\nbefore continuing?"),
tr("&Save"),
tr("&Don't Save"),
0 // Enter == button 0
) )
{ // Escape == button 2
case 0: // Save clicked, Alt-S or Enter pressed.
modified = false;
break;
case 1: // Don't Save clicked or Alt-D pressed
modified = false;
return true;
}
}
modified = false;
if (m_password.isEmpty())
return false;
int retval = saveInit(_filename, m_password);
// int retval = saveInit(_filename, "test");
if (retval != PWERR_GOOD) {
return false;
}
char* entry[FIELD_SIZE];
// save the validation entry
{
int i=0;
entry[i] = (char*)malloc(strlen("ZSAFECATEGORY")+1);
strcpy(entry[i++], "ZSAFECATEGORY");
entry[i] = (char*)malloc(strlen("name")+1);
strcpy(entry[i++], "name");
entry[i] = (char*)malloc(strlen("username")+1);
strcpy(entry[i++], "username");
entry[i] = (char*)malloc(strlen("password")+1);
strcpy(entry[i++], "password");
entry[i] = (char*)malloc(strlen("comment")+1);
strcpy(entry[i++], "comment");
entry[i] = (char*)malloc(strlen("field5")+1);
strcpy(entry[i++], "field5");
entry[i] = (char*)malloc(strlen("field6")+1);
strcpy(entry[i++], "field6");
retval = saveEntry(entry);
for (int z=0; z<i; z++) free(entry[z]);
if (retval == PWERR_DATA) {
- qWarning("1: Error writing file, contents not saved");
+ owarn << "1: Error writing file, contents not saved" << oendl;
saveFinalize();
return false;
}
// #ifndef WIN32
conf->writeEntry(APP_KEY+"valzsafe", 1);
// #endif
saveConf();
}
QListViewItem *i;
// step through all categories
for (i = ListView->firstChild();
i != NULL;
i = i->nextSibling())
{
// step through all subitems
QListViewItem *si;
for (si = i->firstChild();
si != NULL;
si = si->nextSibling())
{
int j=0;
entry[j] = (char*)malloc(strlen(i->text(0).utf8())+1);
strcpy(entry[j++], i->text(0).utf8());
entry[j] = (char*)malloc(strlen(si->text(0).utf8())+1);
strcpy(entry[j++], si->text(0).utf8());
entry[j] = (char*)malloc(strlen(si->text(1).utf8())+1);
strcpy(entry[j++], si->text(1).utf8());
entry[j] = (char*)malloc(strlen(si->text(2).utf8())+1);
strcpy(entry[j++], si->text(2).utf8());
entry[j] = (char*)malloc(strlen(si->text(3).utf8())+1);
strcpy(entry[j++], si->text(3).utf8());
entry[j] = (char*)malloc(strlen(si->text(4).utf8())+1);
strcpy(entry[j++], si->text(4).utf8());
entry[j] = (char*)malloc(strlen(si->text(5).utf8())+1);
strcpy(entry[j++], si->text(5).utf8());
retval = saveEntry(entry);
for (int z=0; z<j; z++)
{
free(entry[z]);
}
if (retval == PWERR_DATA) {
- qWarning("1: Error writing file, contents not saved");
+ owarn << "1: Error writing file, contents not saved" << oendl;
saveFinalize();
return false;
}
}
}
if (saveFinalize() == PWERR_DATA) {
- qWarning("2: Error writing file, contents not saved");
+ owarn << "2: Error writing file, contents not saved" << oendl;
return false;
} else {
#ifndef DESKTOP
Global::statusMessage (tr("Password file saved."));
#endif
modified = false;
return true;
}
}
PasswordForm *newPwdDialog;
bool newPwdDialogResult = false;
void ZSafe::setPasswordDialogDone()
{
newPwdDialogResult = true;
newPwdDialog->close();
}
void ZSafe::getDocPassword(QString title)
{
qWarning ("getDocPassword");
// open the 'Password' dialog
PasswordForm *dialog = new PasswordForm(this, title, TRUE);
newPwdDialog = dialog;
newPwdDialogResult = false;
connect( dialog->PasswordField, SIGNAL( returnPressed() ),
this, SLOT( setPasswordDialogDone() ) );
// CS: !!!
// int pos = filename.findRev ('/');
QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
#ifdef WIN32
dialog->setCaption("Qt " + ti);
#else
dialog->setCaption(ti);
#endif
// dialog->setCaption(title);
dialog->PasswordField->setFocus();
DialogCode result = (DialogCode) dialog->exec();
#ifdef DESKTOP
result = Accepted;
#endif
QString password;
if (result == Accepted || newPwdDialogResult)
{
m_password = dialog->PasswordField->text();
}
else
{
exitZs (1);
}
}
int ZSafe::saveInit(const char *_filename, const char *password)
{
char key[128];
unsigned int j = 0;
unsigned int keylength;
// int val;
int count2;
Krc2* krc2 = new Krc2();
/* first we should check the permissions of the filename */
/*
if (QFile::exists(_filename)) {
val = checkFile(_filename);
if (val != PWERR_GOOD)
return val;
} else
{
val = creat (_filename, (S_IRUSR | S_IWUSR));
if (val == -1)
return PWERR_OPEN;
else
close(val);
}
*/
QFileInfo f (_filename);
save_buffer_length = f.size();
save_buffer_length = ((save_buffer_length / 1024)+1) * 1024;
fd = fopen (_filename, "wb");
if (fd == NULL)
return PWERR_OPEN;
buffer = (char*)malloc(save_buffer_length);
/* make the key ready */
for (j = 0; password[j] != '\0'; j++) {
key[j] = password[j];
}
keylength = j;
krc2->rc2_expandkey (key, keylength, 128);
@@ -3097,193 +3094,193 @@ void ZSafe::editCategory()
dialog->IconField->setCurrentItem(0);
}
dialog->IconField->insertItem("predefined");
while ( (fi=it.current()) ) { // for each file...
QString fileName = fi->fileName();
if(fileName.right(4) == ".png")
{
fileName = fileName.mid(0,fileName.length()-4);
#ifdef DESKTOP
QPixmap imageOfFile;
imageOfFile.load(iconPath + fi->fileName());
#else
QPixmap imageOfFile(Resource::loadPixmap(fileName));
#endif
QImage foo = imageOfFile.convertToImage();
foo = foo.smoothScale(16,16);
imageOfFile.convertFromImage(foo);
dialog->IconField->insertItem(imageOfFile,fileName);
if(fileName+".png"==icon)
dialog->IconField->setCurrentItem(i+1);
++i;
}
++it;
}
waitDialog.hide();
}
else
{
#ifdef DESKTOP
// QDir d(QDir::homeDirPath() + "/pics/");
QDir d(iconPath);
#else
QDir d(QPEApplication::qpeDir() + "/pics/");
#endif
d.setFilter( QDir::Files);
const QFileInfoList *list = d.entryInfoList();
int i=0;
QFileInfoListIterator it( *list ); // create list iterator
QFileInfo *fi; // pointer for traversing
if (icon.isEmpty() || icon.isNull())
{
dialog->IconField->setCurrentItem(0);
}
else
{
while ( (fi=it.current()) )
{ // for each file...
QString fileName = fi->fileName();
if(fileName.right(4) == ".png")
{
fileName = fileName.mid(0,fileName.length()-4);
if(fileName+".png"==icon)
{
dialog->IconField->setCurrentItem(i+1);
break;
}
++i;
}
++it;
}
}
}
// dialog->show();
#ifndef DESKTOP
// dialog->move (20, 100);
#endif
DialogCode result = (DialogCode) dialog->exec();
#ifdef DESKTOP
result = Accepted;
#endif
QString fullIconPath;
QPixmap *pix;
if (result == Accepted)
{
modified = true;
if (category != dialog->CategoryField->currentText())
{
categories.remove (category);
// #ifndef WIN32
conf->removeEntry(category);
// #endif
saveConf();
}
category = dialog->CategoryField->currentText();
icon = dialog->IconField->currentText()+".png";
if (cat)
{
- qWarning("Category found");
+ owarn << "Category found" << oendl;
// if (!icon.isEmpty() && !icon.isNull())
if (icon != "predefined.png")
{
// build the full path
fullIconPath = iconPath + icon;
pix = new QPixmap (fullIconPath);
if (pix)
{
// save the full pixmap name into the config file
// #ifndef WIN32
conf->writeEntry(APP_KEY+category, icon);
// #endif
saveConf();
QImage img = pix->convertToImage();
pix->convertFromImage(img.smoothScale(14,14));
cat->setIconName (icon);
cat->setIcon (*pix);
}
}
else
{
// #ifndef WIN32
conf->removeEntry (category);
// #endif
saveConf();
cat->setIcon (*getPredefinedIcon(category));
}
// change the category name of the selected category
QListViewItem *catItem = cat->getListItem();
if (catItem)
{
qWarning (category);
catItem->setText( 0, tr( category ) );
cat->setCategoryName (tr(category));
cat->initListItem();
categories.insert (category, cat);
}
}
saveCategoryDialogFields(dialog);
}
else
{
// delete dialog;
dialog->hide();
return;
}
}
}
void ZSafe::cutItem()
{
if (!selectedItem)
return;
if (!isCategory(selectedItem))
{
IsCut = true;
copiedItem = selectedItem;
}
}
void ZSafe::copyItem()
{
if (!selectedItem)
return;
if (!isCategory(selectedItem))
{
IsCopy = true;
copiedItem = selectedItem;
}
}
// paste item into category
void ZSafe::pasteItem()
{
if (!selectedItem)
return;
if (isCategory(selectedItem))
{
modified = true;
if (IsCut)
{
if (copiedItem)
{
// add the new item
QListViewItem *i = new ShadedListItem (0, selectedItem);
// i->setOpen (TRUE);
i->setText (0, copiedItem->text(0));
i->setText (1, copiedItem->text(1));
i->setText (2, copiedItem->text(2));
i->setText (3, copiedItem->text(3));
i->setText (4, copiedItem->text(4));
i->setText (5, copiedItem->text(5));
diff --git a/noncore/apps/zsafe/zsafe.pro b/noncore/apps/zsafe/zsafe.pro
index 72c8fe9..3cae706 100644
--- a/noncore/apps/zsafe/zsafe.pro
+++ b/noncore/apps/zsafe/zsafe.pro
@@ -1,17 +1,17 @@
-TEMPLATE = app
-CONFIG = qt warn_on
+TEMPLATE = app
+CONFIG = qt warn_on
DESTDIR = $(OPIEDIR)/bin
HEADERS = zsafe.h krc2.h category.h categorylist.h zlistview.h \
scqtfiledlg.h
SOURCES = main.cpp zsafe.cpp krc2.cpp category.cpp \
categorylist.cpp zlistview.cpp shadedlistitem.cpp\
scqtfileedit.cpp scqtfileedit.moc.cpp \
scqtfiledlg.cpp
-INTERFACES = newdialog.ui searchdialog.ui passworddialog.ui categorydialog.ui infoform.ui wait.ui
-INCLUDEPATH += $(OPIEDIR)/include
-DEPENDPATH += $(OPIEDIR)/include
-LIBS += -Wl,-rpath,$(OPIEDIR)/lib -L$(OPIEDIR)/lib -lqpe -lopiecore2 -lopieui2
-TARGET = zsafe
+INTERFACES = newdialog.ui searchdialog.ui passworddialog.ui categorydialog.ui infoform.ui wait.ui
+INCLUDEPATH += $(OPIEDIR)/include
+DEPENDPATH += $(OPIEDIR)/include
+LIBS += -lqpe -lopiecore2 -lopieui2
+TARGET = zsafe
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/comm/keypebble/config.in b/noncore/comm/keypebble/config.in
index 20384aa..8a800b9 100644
--- a/noncore/comm/keypebble/config.in
+++ b/noncore/comm/keypebble/config.in
@@ -1,4 +1,4 @@
config KEYPEBBLE
boolean "opie-keypebble (Virtual Network Computing VNC viewer)"
default "y"
- depends ( LIBQPE || LIBQPE-X11 )
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
diff --git a/noncore/comm/keypebble/keypebble.pro b/noncore/comm/keypebble/keypebble.pro
index 3515016..7631e4e 100644
--- a/noncore/comm/keypebble/keypebble.pro
+++ b/noncore/comm/keypebble/keypebble.pro
@@ -1,35 +1,34 @@
-CONFIG += qt warn_on quick-app
+CONFIG += qt warn_on quick-app
HEADERS = d3des.h \
krfbbuffer.h \
krfbcanvas.h \
krfbconnection.h \
krfbdecoder.h \
krfblogin.h \
krfbserver.h \
krfbserverinfo.h \
kvnc.h \
kvncconndlg.h \
kvncbookmarkdlg.h \
vncauth.h
SOURCES = d3des.c \
vncauth.c \
krfbbuffer.cpp \
krfbcanvas.cpp \
krfbconnection.cpp \
krfbdecoder.cpp \
krfblogin.cpp \
krfbserver.cpp \
kvnc.cpp \
kvncconndlg.cpp \
kvncbookmarkdlg.cpp \
main.cpp
-INTERFACES = kvncconndlgbase.ui \
- kvncbookmarkdlgbase.ui
+INTERFACES = kvncconndlgbase.ui kvncbookmarkdlgbase.ui
-INCLUDEPATH += $(OPIEDIR)/include
+INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe
+LIBS += -lqpe -lopiecore2
TARGET = keypebble
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/comm/keypebble/krfbbuffer.cpp b/noncore/comm/keypebble/krfbbuffer.cpp
index 4cec0c2..4b29612 100644
--- a/noncore/comm/keypebble/krfbbuffer.cpp
+++ b/noncore/comm/keypebble/krfbbuffer.cpp
@@ -1,173 +1,181 @@
-#include <assert.h>
-#include <qimage.h>
-#include <qpainter.h>
-#include <qapplication.h>
#include "krfbdecoder.h"
#include "krfbbuffer.h"
#include "krfbconnection.h"
#include "krfbserverinfo.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
+#include <qimage.h>
+#include <qpainter.h>
+#include <qapplication.h>
+
+/* STD */
+#include <assert.h>
+
//
// Endian stuff
//
-#ifndef KDE_USE_FINAL
+#ifndef OPIE_NO_DEBUG
const int endianTest = 1;
#endif
#define Swap16IfLE(s) \
(*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s))
#define Swap32IfLE(l) \
(*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \
(((l) & 0x00ff0000) >> 8) | \
(((l) & 0x0000ff00) << 8) | \
(((l) & 0x000000ff) << 24)) : (l))
KRFBBuffer::KRFBBuffer( KRFBDecoder *decoder,
QObject *parent, const char *name )
: QObject( parent, name )
{
assert( decoder );
this->decoder = decoder;
pix = new QPixmap();
}
KRFBBuffer::~KRFBBuffer()
{
delete pix;
}
void KRFBBuffer::resize( int w, int h )
{
- qWarning( "Resizing buffer" );
+ owarn << "Resizing buffer" << oendl;
pix->resize( w, h );
QPalette pal = qApp->palette();
pix->fill( pal.active().base() );
emit sizeChanged( w, h );
}
void KRFBBuffer::soundBell()
{
emit bell();
}
void KRFBBuffer::mouseEvent( QMouseEvent *e )
{
decoder->sendMouseEvent( e );
}
void KRFBBuffer::keyPressEvent( QKeyEvent *e )
{
- qWarning( "Buffer got a key" );
+ owarn << "Buffer got a key" << oendl;
decoder->sendKeyPressEvent( e );
}
void KRFBBuffer::keyReleaseEvent( QKeyEvent *e )
{
decoder->sendKeyReleaseEvent( e );
}
void KRFBBuffer::copyRect( int srcX, int srcY,
int destX, int destY, int w, int h )
{
-// qWarning( "Got copy rect" );
+// owarn << "Got copy rect" << oendl;
bitBlt( pix, destX, destY, pix, srcX, srcY, w, h, CopyROP );
emit updated( destX, destY, w, h );
}
void KRFBBuffer::drawRawRectChunk( void *data,
int x, int y, int w, int h )
{
QImage img( w, h, 32 );
int scaleFactor=decoder->con->options()->scaleFactor;
int redMax = Swap16IfLE( decoder->format->redMax );
int greenMax = Swap16IfLE( decoder->format->greenMax );
int blueMax = Swap16IfLE( decoder->format->blueMax );
QPainter p( pix );
if ( decoder->format->bpp == 8 ) {
uchar *d = (unsigned char *) data;
uint r,g,b;
for ( int j = 0; j < h; j++) {
for ( int i = 0; i < w ; i++ ) {
r = d[ j * w + i ];
r = r >> decoder->format->redShift;
r = r & redMax;
g = d[ j * w + i ];
g = g >> decoder->format->greenShift;
g = g & greenMax;
b = d[ j * w + i ];
b = b >> decoder->format->blueShift;
b = b & blueMax;
r = ( r * 255 ) / redMax;
g = ( g * 255 ) / greenMax;
b = ( b * 255 ) / blueMax;
uint *p = ( uint * ) img.scanLine( j ) + i;
*p = qRgb( r,g,b );
}
}
}
else if ( decoder->format->bpp == 32 ) {
ulong *d = (ulong *) data;
ulong r,g,b;
for ( int j = 0; j < h; j++ ) {
for ( int i = 0; i < w ; i++ ) {
ulong pixel = d[ j * w + i ];
pixel = Swap32IfLE( pixel );
r = pixel;
r = r >> decoder->format->redShift;
r = r & redMax;
g = pixel;
g = g >> decoder->format->greenShift;
g = g & greenMax;
b = pixel;
b = b >> decoder->format->blueShift;
b = b & blueMax;
r = ( r * 255 ) / redMax;
g = ( g * 255 ) / greenMax;
b = ( b * 255 ) / blueMax;
uint *p = ( uint * ) img.scanLine( j ) + i;
*p = qRgb( r,g,b );
}
}
} else if (decoder->format->bpp == 16 ) {
CARD16 *d = (CARD16 *) data;
uint r,g,b;
for ( int j = 0; j < h; j++ ) {
for ( int i = 0; i < w ; i++ ) {
CARD16 pixel = d[ j * w + i ];
pixel = Swap16IfLE( pixel );
r = pixel;
r = r >> decoder->format->redShift;
r = r & redMax;
g = pixel;
g = g >> decoder->format->greenShift;
g = g & greenMax;
b = pixel;
diff --git a/noncore/comm/keypebble/krfbcanvas.cpp b/noncore/comm/keypebble/krfbcanvas.cpp
index cd1fda0..b3525df 100644
--- a/noncore/comm/keypebble/krfbcanvas.cpp
+++ b/noncore/comm/keypebble/krfbcanvas.cpp
@@ -1,173 +1,177 @@
#include "krfbconnection.h"
#include "krfbcanvas.h"
#include "krfbbuffer.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
+/* QT */
#include <qclipboard.h>
KRFBCanvas::KRFBCanvas( QWidget *parent, const char *name )
: QScrollView( parent, name )
{
connection_ = new KRFBConnection();
connect( connection_, SIGNAL( loggedIn() ),
this, SLOT( loggedIn() ) );
loggedIn_ = false;
//QPEApplication::setStylusOperation(viewport(), QPEApplication::RightOnHold);
viewport()->setFocusPolicy( QWidget::StrongFocus );
viewport()->setFocus();
nextRightClick=0;
nextDoubleClick=0;
}
KRFBCanvas::~KRFBCanvas()
{
}
void KRFBCanvas::openConnection(KRFBServer server)
{
QCString host = server.hostname.latin1();
password=server.password;
connection_->connectTo( server);
}
void KRFBCanvas::openURL( const QUrl &url )
{
if ( loggedIn_ ) {
- qWarning( "openURL invoked when logged in\n" );
+ owarn << "openURL invoked when logged in\n" << oendl;
return;
}
QCString host = url.host().latin1();
int display = url.port();
// connection_->connectTo( host, display );
}
void KRFBCanvas::closeConnection()
{
loggedIn_ = false;
connection_->disconnect();
viewport()->setMouseTracking( false );
viewport()->setBackgroundMode( PaletteDark );
setBackgroundMode( PaletteDark );
update();
}
void KRFBCanvas::bell()
{
if ( connection_->options()->deIconify ) {
topLevelWidget()->raise();
topLevelWidget()->show();
}
}
void KRFBCanvas::loggedIn()
{
- qWarning( "Ok, we're logged in" );
+ owarn << "Ok, we're logged in" << oendl;
//
// Get ready for action
//
loggedIn_ = true;
viewport()->setMouseTracking( true );
viewport()->setBackgroundMode( NoBackground );
setBackgroundMode( NoBackground );
// Start using the buffer
connect( connection_->buffer(), SIGNAL( sizeChanged(int,int) ),
this, SLOT( resizeContents(int,int) ) );
connect( connection_->buffer(), SIGNAL( updated(int,int,int,int) ),
this, SLOT( viewportUpdate(int,int,int,int) ) );
connect( connection_->buffer(), SIGNAL( bell() ),
this, SLOT( bell() ) );
connect( qApp->clipboard(), SIGNAL( dataChanged() ),
this, SLOT( clipboardChanged() ) );
}
void KRFBCanvas::viewportPaintEvent( QPaintEvent *e )
{
QRect r = e->rect();
if ( loggedIn_ ) {
QPixmap p;
bitBlt( viewport(), r.x(), r.y(),
connection_->buffer()->pixmap(),
r.x() + contentsX(), r.y() + contentsY(),
r.width(), r.height() );
}
else {
QScrollView::viewportPaintEvent( e );
}
}
void KRFBCanvas::viewportUpdate( int x, int y, int w, int h )
{
updateContents( x, y, w, h );
}
void KRFBCanvas::contentsMousePressEvent( QMouseEvent *e )
{
if (nextDoubleClick) {
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),LeftButton,LeftButton));
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0));
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0));
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton));
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0));
} if (nextRightClick) {
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),RightButton,RightButton));
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),RightButton,0));
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton));
connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0));
} else if ( loggedIn_ )
connection_->buffer()->mouseEvent( e );
}
void KRFBCanvas::contentsMouseReleaseEvent( QMouseEvent *e )
{
if ( loggedIn_ && !nextRightClick && !nextDoubleClick) {
connection_->buffer()->mouseEvent( e );
}
nextRightClick=0;
nextDoubleClick=0;
}
void KRFBCanvas::contentsMouseMoveEvent( QMouseEvent *e )
{
if ( loggedIn_ )
connection_->buffer()->mouseEvent( e );
}
void KRFBCanvas::keyPressEvent( QKeyEvent *e )
{
if ( loggedIn_ )
connection_->buffer()->keyPressEvent( e );
}
void KRFBCanvas::keyReleaseEvent( QKeyEvent *e )
{
if ( loggedIn_ )
connection_->buffer()->keyReleaseEvent( e );
}
void KRFBCanvas::refresh()
{
if ( loggedIn_ )
connection_->refresh();
}
void KRFBCanvas::clipboardChanged()
diff --git a/noncore/comm/keypebble/krfbconnection.cpp b/noncore/comm/keypebble/krfbconnection.cpp
index b447046..33e0563 100644
--- a/noncore/comm/keypebble/krfbconnection.cpp
+++ b/noncore/comm/keypebble/krfbconnection.cpp
@@ -1,233 +1,240 @@
-#include <assert.h>
-#include <qsocket.h>
-#include <qtimer.h>
-#include <string.h>
-
#include "krfbconnection.h"
#include "krfblogin.h"
#include "krfbdecoder.h"
#include "krfbbuffer.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
+#include <qsocket.h>
+#include <qtimer.h>
+
+/* STD */
+#include <assert.h>
+#include <string.h>
+
KRFBConnection::KRFBConnection( QObject *parent )
: QObject( parent, "KRFBConnection" )
{
portBase_ = 5900;
currentState_ = Disconnected;
sock = 0;
minData_ = 0;
options_ = new KRFBServer();
updater = 0;
decoder_ = 0;
buffer_ = 0;
}
KRFBConnection::~KRFBConnection()
{
if ( ( currentState_ != Disconnected ) && ( currentState_ != Disconnecting ) && sock ) {
disconnectDone();
}
delete options_;
}
void KRFBConnection::connectTo( KRFBServer server)
{
if ( currentState_ != Disconnected )
disconnect();
(*options_)=server;
sock = new QSocket( this, "rfbSocket" );
CHECK_PTR( sock );
// Connect to something to notice connection or error
connect( sock, SIGNAL( error(int) ), SLOT( gotSocketError(int) ) );
connect( sock, SIGNAL( connected() ), SLOT( gotSocketConnection() ) );
- qWarning( "Connecting..." );
+ owarn << "Connecting..." << oendl;
currentState_ = Connecting;
sock->connectToHost( options_->hostname.latin1(), portBase_ + options_->display );
}
void KRFBConnection::disconnect()
{
- qWarning( "Disconnecting from server" );
+ owarn << "Disconnecting from server" << oendl;
if ( ( currentState_ != Disconnected )
&& ( currentState_ != Disconnecting )
&& sock ) {
currentState_ = Disconnecting;
connect( sock, SIGNAL( delayedCloseFinished() ), SLOT( disconnectDone() ) );
sock->close();
if ( sock->state() != QSocket::Closing )
disconnectDone();
}
}
void KRFBConnection::disconnectDone()
{
currentState_ = Disconnected;
delete sock;
sock = 0;
minData_ = 0;
delete updater;
delete decoder_;
delete buffer_;
emit disconnected();
}
void KRFBConnection::gotSocketConnection()
{
currentState_ = LoggingIn;
- qWarning( "Connected, logging in..." );
+ owarn << "Connected, logging in..." << oendl;
static QString statusMsg = tr( "Connected" );
emit statusChanged( statusMsg );
// Do some login stuff
login = new KRFBLogin( this );
}
void KRFBConnection::gotRFBConnection()
{
- qWarning( "Logged into server" );
+ owarn << "Logged into server" << oendl;
currentState_ = Connected;
emit connected();
// Create the decoder and start doing stuff
decoder_ = new KRFBDecoder( this );
CHECK_PTR( decoder_ );
buffer_ = new KRFBBuffer( decoder_, this, "RFB Buffer" );
CHECK_PTR( buffer_ );
decoder_->setBuffer( buffer_ );
connect( decoder_, SIGNAL( status(const QString&) ),
this, SIGNAL( statusChanged(const QString&) ) );
emit loggedIn();
decoder_->start();
updater = new QTimer;
connect( updater, SIGNAL( timeout() ), SLOT( updateTimer() ) );
updater->start( options_->updateRate );
}
void KRFBConnection::gotSocketError( int err )
{
currentState_ = Error;
// Do some error handling stuff
- qWarning( "KRFBConnection: Socket error %d", err );
+ owarn << "KRFBConnection: Socket error " << err << "" << oendl;
static QString refused = tr( "Connection Refused" );
static QString host = tr( "Host not found" );
static QString read = tr( "Read Error: QSocket reported an error reading\n"
"data, the remote host has probably dropped the\n"
"connection." );
static QString confused = tr( "QSocket reported an invalid error code" );
QString msg;
switch ( err ) {
case QSocket::ErrConnectionRefused:
msg = refused;
break;
case QSocket::ErrHostNotFound:
msg = host;
break;
case QSocket::ErrSocketRead:
msg = read;
break;
default:
msg = confused;
};
QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) );
delete sock;
sock = 0;
currentState_ = Disconnected;
emit error( msg );
}
void KRFBConnection::gotMoreData()
{
assert( minData_ > 0 );
if ( sock->size() >= minData_ ) {
minData_ = 0;
QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) );
emit gotEnoughData();
}
}
void KRFBConnection::waitForData( unsigned int sz )
{
assert( minData_ == 0 );
assert( sz > 0 );
assert( currentState_ != Error );
if ( sock->size() >= sz ) {
- // qWarning( "No need to wait for data" );
+ // owarn << "No need to wait for data" << oendl;
emit gotEnoughData();
}
else {
- // qWarning( "Waiting for %u bytes", sz );
+ // owarn << "Waiting for " << sz << " bytes" << oendl;
minData_ = sz;
connect( sock, SIGNAL( readyRead() ), SLOT( gotMoreData() ) );
}
}
int KRFBConnection::read( void *buf, int sz )
{
return sock->readBlock( (char *) buf, sz );
}
int KRFBConnection::write( void *buf, int sz )
{
return sock->writeBlock( (const char *) buf, sz );
}
KRFBConnection::State KRFBConnection::state() const
{
return currentState_;
}
void KRFBConnection::setPortBase( int base )
{
portBase_ = base;
}
int KRFBConnection::portBase() const
{
return portBase_;
}
void KRFBConnection::updateTimer()
{
decoder_->sendUpdateRequest( true );
}
void KRFBConnection::refresh()
{
decoder_->sendUpdateRequest( false );
}
void KRFBConnection::sendCutText( const QString &text )
{
decoder_->sendCutEvent( text );
}
const QUrl &KRFBConnection::url()
{
url_.setProtocol( "vnc" );
url_.setPort( display() );
url_.setHost( host() );
url_.setPath( "/" );
return url_;
}
diff --git a/noncore/comm/keypebble/krfbdecoder.cpp b/noncore/comm/keypebble/krfbdecoder.cpp
index db95154..69457e2 100644
--- a/noncore/comm/keypebble/krfbdecoder.cpp
+++ b/noncore/comm/keypebble/krfbdecoder.cpp
@@ -1,830 +1,835 @@
#include "krfbconnection.h"
#include "krfbserverinfo.h"
#include "krfbdecoder.h"
#include "krfbbuffer.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+/* QT */
#include <qpixmap.h>
+/* STD */
#include <assert.h>
//
// Endian stuff
//
-#ifndef KDE_USE_FINAL
+#ifndef OPIE_NO_DEBUG
const int endianTest = 1;
#endif
#define Swap16IfLE(s) \
(*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s))
#define Swap32IfLE(l) \
(*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \
(((l) & 0x00ff0000) >> 8) | \
(((l) & 0x0000ff00) << 8) | \
(((l) & 0x000000ff) << 24)) : (l))
//
// The lengths of the messages we need to wait for
//
const int ServerInitLength = 24;
const int UpdateHeaderLength = 4;
const int RectHeaderLength = 12;
const int RectChunkSize = 4;
const int CopyRectPosLength = 4;
const int ServerCutLenLength = 7;
//
// Client -> Server Message Identifiers
//
static CARD8 SetPixelFormatId = 0;
//static CARD8 FixColourMapEntriesId = 1; // Not used
static CARD8 SetEncodingsId = 2;
static CARD8 UpdateRequestId = 3;
static CARD8 KeyEventId = 4;
static CARD8 PointerEventId = 5;
static CARD8 ClientCutTextId = 6;
//
// Server -> Client Message Identifiers
//
static CARD8 UpdateId = 0;
static CARD8 BellId = 2;
static CARD8 ServerCutId = 3;
//
// Encoding identifiers
//
static CARD32 RawEncoding = Swap32IfLE( 0 );
static CARD32 CopyRectEncoding = Swap32IfLE(1 );
static CARD32 RreEncoding = Swap32IfLE( 2 );
static CARD32 CorreEncoding = Swap32IfLE( 4 );
static CARD32 HexTileEncoding = Swap32IfLE( 5 );
static struct {
int keysym;
int keycode;
} keyMap[] = {
{ 0xff08, Qt::Key_Backspace },
{ 0xff09, Qt::Key_Tab },
{ 0xff0d, Qt::Key_Return },
{ 0xff1b, Qt::Key_Escape },
{ 0xff63, Qt::Key_Insert },
{ 0xffff, Qt::Key_Delete },
{ 0xff50, Qt::Key_Home },
{ 0xff57, Qt::Key_End },
{ 0xff55, Qt::Key_Prior },
{ 0xff56, Qt::Key_Next },
{ 0xff51, Qt::Key_Left },
{ 0xff52, Qt::Key_Up },
{ 0xff53, Qt::Key_Right },
{ 0xff54, Qt::Key_Down },
{ 0xffbe, Qt::Key_F1 },
{ 0xffbf, Qt::Key_F2 },
{ 0xffc0, Qt::Key_F3 },
{ 0xffc1, Qt::Key_F4 },
{ 0xffc2, Qt::Key_F5 },
{ 0xffc3, Qt::Key_F6 },
{ 0xffc4, Qt::Key_F7 },
{ 0xffc5, Qt::Key_F8 },
{ 0xffc6, Qt::Key_F9 },
{ 0xffc7, Qt::Key_F10 },
{ 0xffc8, Qt::Key_F11 },
{ 0xffc9, Qt::Key_F12 },
{ 0xffe1, Qt::Key_Shift },
{ 0xffe2, Qt::Key_Shift },
{ 0xffe3, Qt::Key_Control },
{ 0xffe4, Qt::Key_Control },
{ 0xffe7, Qt::Key_Meta },
{ 0xffe8, Qt::Key_Meta },
{ 0xffe9, Qt::Key_Alt },
{ 0xffea, Qt::Key_Alt },
{ 0, 0 }
};
KRFBDecoder::KRFBDecoder( KRFBConnection *con )
: QObject( con, "RFB Decoder" )
{
assert( con );
assert( con->state() == KRFBConnection::Connected );
this->con = con;
this->buf = 0;
this->info = 0;
this->format = 0;
this->buttonMask = 0;
currentState = Idle;
}
KRFBDecoder::~KRFBDecoder()
{
if ( info )
delete info;
if ( format )
delete format;
}
void KRFBDecoder::start()
{
sendClientInit();
}
void KRFBDecoder::sendClientInit()
{
con->write( &( con->options()->shared ), 1 );
// Wait for server init
- qWarning( "Waiting for server init" );
+ owarn << "Waiting for server init" << oendl;
static QString statusMsg = tr( "Waiting for server initialization..." );
emit status( statusMsg );
currentState = AwaitingServerInit;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerInit() ) );
con->waitForData( ServerInitLength );
}
void KRFBDecoder::gotServerInit()
{
- qWarning( "Got server init" );
+ owarn << "Got server init" << oendl;
disconnect( con, SIGNAL( gotEnoughData() ), this, SLOT( gotServerInit() ) );
if ( info )
delete info;
info = new KRFBServerInfo;
CHECK_PTR( info );
con->read( &(info->width), 2 );
info->width = Swap16IfLE( info->width );
con->read( &info->height, 2 );
info->height = Swap16IfLE( info->height );
con->read( &(info->bpp), 1 );
con->read( &(info->depth), 1 );
con->read( &(info->bigEndian), 1 );
con->read( &(info->trueColor), 1 );
con->read( &(info->redMax), 2 );
info->redMax = Swap16IfLE( info->redMax );
con->read( &(info->greenMax), 2 );
info->greenMax = Swap16IfLE( info->greenMax );
con->read( &(info->blueMax), 2 );
info->blueMax = Swap16IfLE( info->blueMax );
con->read( &(info->redShift), 1 );
con->read( &(info->greenShift), 1 );
con->read( &(info->blueShift), 1 );
con->read( info->padding, 3 );
con->read( &(info->nameLength), 4 );
info->nameLength = Swap32IfLE( info->nameLength );
- qWarning( "Width = %d, Height = %d", info->width, info->height );
+ owarn << "Width = " << info->width << ", Height = " << info->height << "" << oendl;
qWarning( "Bpp = %d, Depth = %d, Big = %d, True = %d",
info->bpp, info->depth, info->bigEndian, info->trueColor );
qWarning( "RedMax = %d, GreenMax = %d, BlueMax = %d",
info->redMax, info->greenMax, info->blueMax );
qWarning( "RedShift = %d, GreenShift = %d, BlueShift = %d",
info->redShift, info->greenShift,info-> blueShift );
buf->resize( info->width/con->options()->scaleFactor, info->height /con->options()->scaleFactor);
// Wait for desktop name
- qWarning( "Waiting for desktop name" );
+ owarn << "Waiting for desktop name" << oendl;
static QString statusMsg = tr( "Waiting for desktop name..." );
emit status( statusMsg );
currentState = AwaitingDesktopName;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotDesktopName() ) );
con->waitForData( info->nameLength );
}
void KRFBDecoder::gotDesktopName()
{
assert( info );
assert( currentState == AwaitingDesktopName );
- qWarning( "Got desktop name" );
+ owarn << "Got desktop name" << oendl;
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotDesktopName() ) );
char *buf = new char[ info->nameLength + 1 ];
CHECK_PTR( buf );
con->read( buf, info->nameLength );
buf[ info->nameLength ] = '\0';
info->name = buf;
- qWarning( "Desktop: %s", info->name.latin1() );
+ owarn << "Desktop: " << info->name.latin1() << "" << oendl;
delete buf;
// Get the format we'll really use and tell the server
decidePixelFormat();
sendPixelFormat();
sendAllowedEncodings();
currentState = Idle;
QString msg;
msg = tr( "Connected to %1" );
msg = msg.arg( info->name );
emit status( msg );
sendUpdateRequest( false );
}
void KRFBDecoder::decidePixelFormat()
{
assert( info );
if ( format )
delete format;
format = new KRFBPixelFormat;
CHECK_PTR( format );
// What depth do we want?
//
// We'll use the minimum of the remote and local depths, UNLESS an
// eight bit session has been specifically requested by the user.
int screenDepth = QPixmap::defaultDepth();
int bestDepth = ( screenDepth > info->depth ) ? info->depth : screenDepth;
int chosenDepth;
if ( con->options()->colors256 )
chosenDepth = 8;
else
chosenDepth = bestDepth;
qWarning( "Screen depth=%d, server depth=%d, best depth=%d, " \
"eight bit %d, chosenDepth=%d",
screenDepth,
info->depth,
bestDepth,
con->options()->colors256, chosenDepth );
format->depth = chosenDepth;
// If we're using the servers native depth
if ( chosenDepth == info->depth ) {
// Use the servers native format
format->bpp = info->bpp;
// format->bigEndian = info->bigEndian;
format->bigEndian = true;
format->trueColor = info->trueColor;
format->redMax = info->redMax;
format->greenMax = info->greenMax;
format->blueMax = info->blueMax;
format->redShift = info->redShift;
format->greenShift = info->greenShift;
format->blueShift = info->blueShift;
}
else {
if ( chosenDepth == 8 ) {
format->bpp = 8;
format->bigEndian = true;
format->trueColor = true;
format->redMax = 7;
format->greenMax = 7;
format->blueMax = 3;
format->redShift = 0;
format->greenShift = 3;
format->blueShift = 6;
}
}
format->redMax = Swap16IfLE( format->redMax );
format->greenMax = Swap16IfLE( format->greenMax );
format->blueMax = Swap16IfLE( format->blueMax );
}
void KRFBDecoder::sendPixelFormat()
{
static char padding[3];
con->write( &SetPixelFormatId, 1 );
con->write( padding, 3 );
con->write( &(format->bpp), 1 );
con->write( &(format->depth), 1 );
con->write( &(format->bigEndian), 1 );
con->write( &(format->trueColor), 1 );
con->write( &(format->redMax), 2 );
con->write( &(format->greenMax), 2 );
con->write( &(format->blueMax), 2 );
con->write( &(format->redShift), 1 );
con->write( &(format->greenShift), 1 );
con->write( &(format->blueShift), 1 );
con->write( format->padding, 3 ); // Padding
}
void KRFBDecoder::sendAllowedEncodings()
{
static CARD8 padding[1];
con->write( &SetEncodingsId, 1 );
con->write( padding, 1 );
CARD16 noEncodings = con->options()->encodings();
noEncodings = Swap16IfLE( noEncodings );
con->write( &noEncodings, 2 );
if ( con->options()->corre )
con->write( &CorreEncoding, 4 );
if ( con->options()->hexTile )
con->write( &HexTileEncoding, 4 );
if ( con->options()->rre )
con->write( &RreEncoding, 4 );
if ( con->options()->copyrect )
con->write( &CopyRectEncoding, 4 );
// We always support this
con->write( &RawEncoding, 4 );
}
void KRFBDecoder::sendUpdateRequest( bool incremental )
{
if ( currentState != Idle )
return;
con->write( &UpdateRequestId, 1 );
con->write( &incremental, 1 );
static CARD16 x = 0, y = 0;
static CARD16 w = Swap16IfLE( info->width );
static CARD16 h = Swap16IfLE( info->height );
con->write( &x, 2 );
con->write( &y, 2 );
con->write( &w, 2 );
con->write( &h, 2 );
// Now wait for the update
currentState = AwaitingUpdate;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) );
con->waitForData( UpdateHeaderLength );
}
void KRFBDecoder::gotUpdateHeader()
{
assert( currentState == AwaitingUpdate );
- // qWarning( "Got update header" );
+ // owarn << "Got update header" << oendl;
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotUpdateHeader() ) );
CARD8 msgType;
con->read( &msgType, 1 );
if ( msgType != UpdateId ) {
// We might have a bell or server cut
if ( msgType == ServerCutId ) {
oldState = currentState;
gotServerCut();
}
else if ( msgType == BellId ) {
oldState = currentState;
gotBell();
}
else {
int msg = msgType;
QString protocolError = tr( "Protocol Error: Message Id %1 was "
"found when expecting an update "
"message." ).arg( msg );
currentState = Error;
emit error( protocolError );
}
return;
}
CARD8 padding;
con->read( &padding, 1 );
con->read( &noRects, 2 );
noRects = Swap16IfLE( noRects );
- // qWarning( "Expecting %d rects", noRects );
+ // owarn << "Expecting " << noRects << " rects" << oendl;
// Now wait for the data
currentState = AwaitingRectHeader;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) );
con->waitForData( RectHeaderLength );
}
void KRFBDecoder::gotRectHeader()
{
assert( currentState == AwaitingRectHeader );
- // qWarning( "Got rect header" );
+ // owarn << "Got rect header" << oendl;
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotRectHeader() ) );
con->read( &x, 2 );
x = Swap16IfLE( x );
con->read( &y, 2 );
y = Swap16IfLE( y );
con->read( &w, 2 );
w = Swap16IfLE( w );
con->read( &h, 2 );
h = Swap16IfLE( h );
con->read( &encoding, 4 );
// CARD32 encodingLocal = Swap32IfLE( encoding );
// qWarning( "Rect: x=%d, y= %d, w=%d, h=%d, encoding=%ld",
// x, y, w, h, encodingLocal );
//
// Each encoding needs to be handled differently. Some require
// waiting for more data, but others like a copyrect do not.
// Our constants have already been byte swapped, so we use
// the remote value as is.
//
if ( encoding == RawEncoding ) {
- // qWarning( "Raw encoding" );
+ // owarn << "Raw encoding" << oendl;
handleRawRect();
}
else if ( encoding == CopyRectEncoding ) {
-// qWarning( "CopyRect encoding" );
+// owarn << "CopyRect encoding" << oendl;
handleCopyRect();
}
else if ( encoding == RreEncoding ) {
- qWarning( "RRE encoding" );
+ owarn << "RRE encoding" << oendl;
handleRRERect();
}
else if ( encoding == CorreEncoding ) {
- qWarning( "CoRRE encoding" );
+ owarn << "CoRRE encoding" << oendl;
handleCoRRERect();
}
else if ( encoding == HexTileEncoding ) {
- qWarning( "HexTile encoding" );
+ owarn << "HexTile encoding" << oendl;
handleHexTileRect();
}
else {
int msg = Swap32IfLE( encoding );
QString protocolError = tr( "Protocol Error: An unknown encoding was "
"used by the server %1" ).arg( msg );
currentState = Error;
- qWarning( "Unknown encoding, %d", msg );
+ owarn << "Unknown encoding, " << msg << "" << oendl;
emit error( protocolError );
return;
}
}
//
// Raw Encoding
//
void KRFBDecoder::handleRawRect()
{
// We need something a bit cleverer here to handle large
// rectanges nicely. The chunking should be based on the
// overall size (but has to be in complete lines).
- // qWarning( "Handling a raw rect chunk" );
+ // owarn << "Handling a raw rect chunk" << oendl;
// CARD32 lineCount = w * format->bpp / 8;
if ( h > RectChunkSize ) {
// if ( con->sock->size() / lineCount ) {
// getRawRectChunk( con->sock->size() / lineCount );
// }
// else {
getRawRectChunk( RectChunkSize );
// }
}
else {
getRawRectChunk( h );
}
}
void KRFBDecoder::getRawRectChunk( int lines )
{
this->lines = lines;
CARD32 count = lines * w * format->bpp / 8;
// Wait for server init
- // qWarning( "Waiting for raw rect chunk, %ld", count );
+ // owarn << "Waiting for raw rect chunk, " << count << "" << oendl;
currentState = AwaitingRawRectChunk;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRawRectChunk() ) );
con->waitForData( count );
}
void KRFBDecoder::gotRawRectChunk()
{
assert( currentState == AwaitingRawRectChunk );
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotRawRectChunk() ) );
- // qWarning( "Got raw rect chunk" );
+ // owarn << "Got raw rect chunk" << oendl;
//
// Read the rect data and copy it to the buffer.
//
// TODO: Replace this!
int count = lines * w * format->bpp / 8;
char *hack = new char[ count ];
con->read( hack, count );
buf->drawRawRectChunk( hack, x, y, w, lines );
delete hack;
// /TODO:
h = h - lines;
y = y + lines;
if ( h > 0 ) {
handleRawRect();
}
else {
noRects--;
- // qWarning( "There are %d rects left", noRects );
+ // owarn << "There are " << noRects << " rects left" << oendl;
if ( noRects ) {
currentState = AwaitingRectHeader;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) );
con->waitForData( RectHeaderLength );
}
else {
// we are now ready for the next update - no need to wait for the timer
currentState = Idle;
sendUpdateRequest (1);
}
}
}
//
// Copy Rectangle Encoding
//
void KRFBDecoder::handleCopyRect()
{
currentState = AwaitingCopyRectPos;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotCopyRectPos() ) );
con->waitForData( CopyRectPosLength );
}
void KRFBDecoder::gotCopyRectPos()
{
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotCopyRectPos() ) );
CARD16 srcX;
CARD16 srcY;
con->read( &srcX, 2 );
con->read( &srcY, 2 );
srcX = Swap16IfLE( srcX );
srcY = Swap16IfLE( srcY );
buf->copyRect( srcX, srcY, x, y, w, h );
noRects--;
- // qWarning( "There are %d rects left", noRects );
+ // owarn << "There are " << noRects << " rects left" << oendl;
if ( noRects ) {
currentState = AwaitingRectHeader;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) );
con->waitForData( RectHeaderLength );
}
else
currentState = Idle;
}
void KRFBDecoder::handleRRERect()
{
- qWarning( "RRE not implemented" );
+ owarn << "RRE not implemented" << oendl;
}
void KRFBDecoder::handleCoRRERect()
{
- qWarning( "CoRRE not implemented" );
+ owarn << "CoRRE not implemented" << oendl;
}
void KRFBDecoder::handleHexTileRect()
{
- qWarning( "HexTile not implemented" );
+ owarn << "HexTile not implemented" << oendl;
}
void KRFBDecoder::sendMouseEvent( QMouseEvent *e )
{
// Deal with the buttons
if ( e->type() != QEvent::MouseMove ) {
buttonMask = 0;
if ( e->type() == QEvent::MouseButtonPress ) {
if ( e->button() & LeftButton )
buttonMask |= 0x01;
if ( e->button() & MidButton )
buttonMask |= 0x04;
if ( e->button() & RightButton )
buttonMask |= 0x02;
}
else if ( e->type() == QEvent::MouseButtonRelease ) {
if ( e->button() & LeftButton )
buttonMask &= 0x06;
if ( e->button() & MidButton )
buttonMask |= 0x03;
if ( e->button() & RightButton )
buttonMask |= 0x05;
}
}
// HACK: Scaling
CARD16 x = Swap16IfLE( e->x() * con->options()->scaleFactor );
CARD16 y = Swap16IfLE( e->y() * con->options()->scaleFactor );
con->write( &PointerEventId, 1 );
con->write( &buttonMask, 1 );
con->write( &x, 2 );
con->write( &y, 2 );
}
void KRFBDecoder::sendCutEvent( const QString &unicode )
{
//
// Warning: There is a bug in the RFB protocol because there is no way to find
// out the codepage in use on the remote machine. This could be fixed by requiring
// the remote server to use utf8 etc. but for now we have to assume they're the
// same. I've reported this problem to the ORL guys, but they apparantly have no
// immediate plans to fix the issue. :-( (rich)
//
CARD8 padding[3];
QCString text = unicode.local8Bit();
CARD32 length = text.length();
length = Swap32IfLE( length );
con->write( &ClientCutTextId, 1 );
con->write( &padding, 3 );
con->write( &length, 4 );
con->write( text.data(), length );
}
void KRFBDecoder::gotServerCut()
{
- qWarning( "Got server cut" );
+ owarn << "Got server cut" << oendl;
currentState = AwaitingServerCutLength;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerCutLength() ) );
con->waitForData( ServerCutLenLength );
}
void KRFBDecoder::gotServerCutLength()
{
assert( currentState = AwaitingServerCutLength );
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotServerCutLength() ) );
CARD8 padding[3];
con->read( padding, 3 );
con->read( &serverCutTextLen, 4 );
serverCutTextLen = Swap32IfLE( serverCutTextLen );
currentState = AwaitingServerCutText;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerCutText() ) );
con->waitForData( serverCutTextLen );
}
void KRFBDecoder::gotServerCutText()
{
assert( currentState = AwaitingServerCutText );
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotServerCutText() ) );
//
// Warning: There is a bug in the RFB protocol because there is no way to find
// out the codepage in use on the remote machine. This could be fixed by requiring
// the remote server to use utf8 etc. but for now we have to assume they're the
// same. I've reported this problem to the ORL guys, but they apparantly have no
// immediate plans to fix the issue. :-( (rich)
//
char *cutbuf = new char[ serverCutTextLen + 1 ];
CHECK_PTR( cutbuf );
con->read( cutbuf, serverCutTextLen );
cutbuf[ serverCutTextLen ] = '\0';
/* For some reason QApplication::clipboard()->setText() segfaults when called
* from within keypebble's mass of signals and slots
- qWarning( "Server cut: %s", cutbuf );
+ owarn << "Server cut: " << cutbuf << "" << oendl;
QString cutText( cutbuf ); // DANGER!!
qApp->clipboard()->setText( cutText );
*/
delete cutbuf;
// Now wait for the update (again)
if ( oldState == AwaitingUpdate ) {
currentState = AwaitingUpdate;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) );
con->waitForData( UpdateHeaderLength );
}
else if ( oldState == Idle ) {
currentState = Idle;
}
else {
- qWarning( "Async handled in weird state" );
+ owarn << "Async handled in weird state" << oendl;
currentState = oldState;
};
}
void KRFBDecoder::gotBell()
{
- qWarning( "Got server bell" );
+ owarn << "Got server bell" << oendl;
buf->soundBell();
// Now wait for the update (again)
if ( oldState == AwaitingUpdate ) {
currentState = AwaitingUpdate;
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) );
con->waitForData( UpdateHeaderLength );
}
else if ( oldState == Idle ) {
currentState = Idle;
}
else {
- qWarning( "Async handled in weird state" );
+ owarn << "Async handled in weird state" << oendl;
currentState = oldState;
};
}
void KRFBDecoder::sendKeyPressEvent( QKeyEvent *event )
{
int key;
key = toKeySym( event );
if ( key ) {
key = Swap32IfLE( key );
CARD8 mask = true;
CARD16 padding = 0;
con->write( &KeyEventId, 1 );
con->write( &mask, 1 );
con->write( &padding, 2 );
con->write( &key, 4 );
}
}
void KRFBDecoder::sendKeyReleaseEvent( QKeyEvent *event )
{
int key;
key = toKeySym( event );
if ( key ) {
key = Swap32IfLE( key );
CARD8 mask = false;
CARD16 padding = 0;
con->write( &KeyEventId, 1 );
con->write( &mask, 1 );
con->write( &padding, 2 );
con->write( &key, 4 );
}
}
//
// The RFB protocol spec says 'For most ordinary keys, the 'keysym'
// is the same as the corresponding ASCII value.', but doesn't
// elaborate what the most ordinary keys are. The spec also lists
// a set (possibly subset, it's unspecified) of mappings for
// "other common keys" (backspace, tab, return, escape, etc).
//
int KRFBDecoder::toKeySym( QKeyEvent *k )
{
//
// Try and map these "other common keys" first.
//
if ((k->key() >= Qt::Key_Escape) && (k->key() <= Qt::Key_F12)) {
for(int i = 0; keyMap[i].keycode != 0; i++) {
if (k->key() == keyMap[i].keycode) {
return keyMap[i].keysym;
}
}
}
//
// If these keys aren't matched, return the ascii code and let the
// server figure it out. We don't return k->key(), as the data in
// key differs between input methods, and we don't want special cases.
//
return k->ascii();
}
diff --git a/noncore/comm/keypebble/krfblogin.cpp b/noncore/comm/keypebble/krfblogin.cpp
index 2bbd110..92005d2 100644
--- a/noncore/comm/keypebble/krfblogin.cpp
+++ b/noncore/comm/keypebble/krfblogin.cpp
@@ -1,253 +1,258 @@
-#include <assert.h>
+#include "krfblogin.h"
+#include "krfbconnection.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
+#include <qtimer.h>
+/* STD */
+#include <assert.h>
extern "C" {
#include "vncauth.h"
}
-#include "krfblogin.h"
-#include "krfbconnection.h"
-#include <qtimer.h>
-
// The length of the various messages (used to decide how many bytes to
// wait for).
const int ServerVersionLength = 12;
const int ClientVersionLength = 12;
const int AuthSchemeLength = 4;
const int FailureReasonSizeLength = 4;
const int ChallengeLength = 16;
const int AuthResultLength = 4;
// Authentication results
enum AuthResult {
AuthOk,
AuthFailed,
AuthTooMany
};
typedef unsigned char CARD8;
typedef unsigned short CARD16;
typedef unsigned long CARD32;
const int endianTest = 1;
// Endian stuff
#define Swap16IfLE(s) \
(*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s))
#define Swap32IfLE(l) \
(*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \
(((l) & 0x00ff0000) >> 8) | \
(((l) & 0x0000ff00) << 8) | \
(((l) & 0x000000ff) << 24)) : (l))
KRFBLogin::KRFBLogin( KRFBConnection *con )
: QObject( con, "RFB login manager" )
{
assert( con );
this->con = con;
currentState = AwaitingServerVersion;
connect( this, SIGNAL( error(const QString&) ),
con, SIGNAL( error(const QString&) ) );
- qWarning( "Waiting for server version..." );
+ owarn << "Waiting for server version..." << oendl;
static QString statusMsg = tr( "Waiting for server version..." );
emit status( statusMsg );
// Kick off the state machine
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerVersion() ) );
con->waitForData( ServerVersionLength );
}
KRFBLogin::~KRFBLogin()
{
}
KRFBLogin::State KRFBLogin::state() const
{
return currentState;
}
void KRFBLogin::gotServerVersion()
{
- qWarning( "Got server version" );
+ owarn << "Got server version" << oendl;
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotServerVersion() ) );
// Read the server's version message
char serverVersion[ ServerVersionLength + 1 ];
con->read( serverVersion, ServerVersionLength );
serverVersion[ ServerVersionLength ] = '\0';
QCString rfbString( serverVersion, ServerVersionLength + 1 );
versionString = rfbString;
QRegExp regexp( "RFB [0-9][0-9][0-9]\\.[0-9][0-9][0-9]\n" );
if ( rfbString.find( regexp ) == -1 ) {
static QString msg = tr( "Error: Invalid server version, %1" ).arg( rfbString );
- qWarning( msg );
+ owarn << msg << oendl;
emit error( msg );
currentState = Error;
return;
}
// Calculate the actual version number
serverMajor = (serverVersion[4] - '0') * 100
+ (serverVersion[5] - '0') * 10
+ (serverVersion[6] - '0');
serverMinor = (serverVersion[8] - '0') * 100
+ (serverVersion[9] - '0') * 10
+ (serverVersion[10] - '0');
- qWarning("Server Version: %03d.%03d", serverMajor, serverMinor );
+ owarn << "Server Version: " << serverMajor << "." << serverMinor << "" << oendl;
if ( serverMajor != 3 ) {
QString msg = tr( "Error: Unsupported server version, %1" )
.arg( rfbString );
- qWarning( msg );
+ owarn << msg << oendl;
emit error( msg );
currentState = Error;
return;
}
if ( serverMinor != 3 ) {
- qWarning( "Minor version mismatch: %d", serverMinor );
+ owarn << "Minor version mismatch: " << serverMinor << "" << oendl;
}
// Setup for the next state
sendClientVersion();
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthScheme() ) );
con->waitForData( AuthSchemeLength );
}
void KRFBLogin::gotAuthScheme()
{
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotAuthScheme() ) );
// Got data
CARD32 scheme;
con->read( &scheme, AuthSchemeLength );
scheme = Swap32IfLE( scheme );
static QString statusMsgOk = tr( "Logged in" );
switch ( scheme ) {
case 0:
- qWarning( "Failed" );
+ owarn << "Failed" << oendl;
// Handle failure
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotFailureReasonSize() ) );
con->waitForData( FailureReasonSizeLength );
break;
case 1:
// Handle no auth
emit status( statusMsgOk );
con->gotRFBConnection();
break;
case 2:
// Handle VNC auth
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotChallenge() ) );
con->waitForData( ChallengeLength );
break;
default:
- qWarning( "Unknown authentication scheme, 0x%08lx", scheme );
+ owarn << "Unknown authentication scheme, 0x" << scheme << "" << oendl;
currentState = Error;
break;
};
}
void KRFBLogin::gotChallenge()
{
disconnect( con, SIGNAL( gotEnoughData() ),
this, SLOT( gotChallenge() ) );
QTimer::singleShot( 0, this, SLOT(getPassword()) );
}
void KRFBLogin::getPassword()
{
// Got data
CARD8 challenge[ ChallengeLength ];
con->read( challenge, ChallengeLength );
// Last chance to enter a password
if ( con->options_->password.isNull() ) {
- qWarning( "krfblogin needs a password" );
+ owarn << "krfblogin needs a password" << oendl;
emit passwordRequired( con );
}
if ( con->options_->password.isNull() ) {
QString msg = tr( "Error: This server requires a password, but none "
"has been specified.\n" );
emit error( msg );
return;
}
vncEncryptBytes( (unsigned char *) challenge, QCString(con->options_->password.latin1()).data() );
con->write( challenge, ChallengeLength );
connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthResult() ) );
con->waitForData( AuthResultLength );
}
void KRFBLogin::gotFailureReasonSize()
{
disconnect( con, SIGNAL( gotEnoughData() ), this,
SLOT( gotFailureReasonSize() ) );
}
void KRFBLogin::gotAuthResult()
{
// Got data
disconnect( con, SIGNAL( gotEnoughData() ), this,
SLOT( gotAuthResult() ) );
long result;
con->read( &result, AuthResultLength );
result = Swap32IfLE( result );
- qWarning( "Authentication Result is 0x%08lx", result );
+ owarn << "Authentication Result is 0x" << result << "" << oendl;
static QString failed = tr( "Error: The password you specified was incorrect." );
static QString tooMany = tr( "Error: Too many invalid login attempts have been made\n"
"to this account, please try later." );
static QString statusMsgOk = tr( "Logged in" );
static QString statusMsgFailed = tr( "Login Failed" );
static QString statusMsgTooMany = tr( "Too many failures" );
switch( result ) {
case AuthOk:
emit status( statusMsgOk );
con->gotRFBConnection();
break;
case AuthFailed:
- qWarning( "Dammit" );
+ owarn << "Dammit" << oendl;
emit status( statusMsgFailed );
emit error( failed );
break;
case AuthTooMany:
emit status( statusMsgTooMany );
emit error( tooMany );
break;
default:
- qWarning( "Invalid authentication result, %lx", result );
+ owarn << "Invalid authentication result, " << result << "" << oendl;
break;
}
}
void KRFBLogin::sendClientVersion()
{
- qWarning( "Sending client version" );
+ owarn << "Sending client version" << oendl;
con->write( (void*)"RFB 003.003\n", ClientVersionLength );
}
diff --git a/noncore/comm/keypebble/kvncbookmarkdlg.cpp b/noncore/comm/keypebble/kvncbookmarkdlg.cpp
index ef2fa12..149c398 100644
--- a/noncore/comm/keypebble/kvncbookmarkdlg.cpp
+++ b/noncore/comm/keypebble/kvncbookmarkdlg.cpp
@@ -1,209 +1,215 @@
+#include "kvncbookmarkdlg.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/global.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qdir.h>
#include <qtextstream.h>
#include <qlistbox.h>
-#include <qpe/global.h>
-#include "kvncbookmarkdlg.h"
KVNCBookmarkDlg::KVNCBookmarkDlg( QWidget * parent, const char * name, WFlags f )
: KVNCBookmarkDlgBase( parent, name,f)
{
readBookmarks();
refresh();
}
KVNCBookmarkDlg::~KVNCBookmarkDlg()
{
}
void KVNCBookmarkDlg::addBookmark(KRFBServer * server)
{
if (server) {
servers.append(server);
bookmarkList->insertItem(server->name);
writeBookmarks();
refresh();
}
}
void KVNCBookmarkDlg::deleteBookmark(QString name)
{
KRFBServer * server=0;
for ( server=servers.first(); server != 0; server=servers.next() ) {
if (server->name==name) {
servers.remove(servers.at());
writeBookmarks();
refresh();
return;
}
}
}
KRFBServer *KVNCBookmarkDlg::getServer(QString name)
{
KRFBServer * server=0;
for ( server=servers.first(); server != 0; server=servers.next() ) {
if (server->name==name)
return server;
}
return 0;
}
/*
Note that the degree of protection offered by the encryption here is
only sufficient to avoid the most casual observation of the configuration
files. People with access to the files can write down the contents and
decrypt it using this source code.
Conceivably, and at some burden to the user, this encryption could
be improved.
*/
QString KVNCBookmarkDlg::encipher(const QString& plain)
{
// mainly, we make it long
QString cipher;
int mix=28730492;
for (int i=0; i<(int)plain.length(); i++) {
int u = plain[i].unicode();
int c = u ^ mix;
QString x = QString::number(c,36);
cipher.append(QChar('a'+x.length()));
cipher.append(x);
mix *= u;
}
return cipher;
}
QString KVNCBookmarkDlg::decipher(const QString& cipher)
{
QString plain;
int mix=28730492;
for (int i=0; i<(int)cipher.length();) {
int l = cipher[i].unicode()-'a';
QString x = cipher.mid(i+1,l); i+=l+1;
int u = x.toInt(0,36) ^ mix;
plain.append(QChar(u));
mix *= u;
}
return plain;
}
void KVNCBookmarkDlg::readBookmarks(void)
{
QFile f(QDir::homeDirPath() + QString("/Applications/keypebble/bookmarks"));
QStringList entry;
QString key, val;
KRFBServer * server=0;
if ( f.open(IO_ReadOnly) ) {
QTextStream t( &f );
QString s;
int n = 1;
while ( !t.eof() ) {
s = t.readLine();
entry=QStringList::split('=',s);
key=entry[0].stripWhiteSpace().lower();
val=entry[1].stripWhiteSpace();
if (key=="server") {
if (server){
servers.append(server);
server=0;
}
server = new KRFBServer();
if (!server)
return;
server->name=val;
}
else if (key=="hostname")
server->hostname=val;
else if (key=="password")
server->password=decipher(val);
else if (key=="display")
server->display=val.toInt();
else if (key=="hextile")
server->hexTile=val.toInt();
else if (key=="corre")
server->corre=val.toInt();
else if (key=="rre")
server->rre=val.toInt();
else if (key=="copyrect")
server->copyrect=val.toInt();
else if (key=="colors256")
server->colors256=val.toInt();
else if (key=="shared")
server->shared=val.toInt();
else if (key=="readonly")
server->readOnly=val.toInt();
else if (key=="deiconify")
server->deIconify=val.toInt();
else if (key=="updaterate")
server->updateRate=val.toInt();
else if (key=="scalefactor")
server->scaleFactor=val.toInt();
}
if (server){
servers.append(server);
server=0;
}
f.close();
}
}
void KVNCBookmarkDlg::writeBookmarks(void)
{
QString filename=Global::applicationFileName("keypebble","bookmarks");
QFile f(filename);
QString key, val;
KRFBServer * server=0;
if ( f.open(IO_ReadWrite) ) {
QTextStream t( &f );
QString s;
int n = 1;
KRFBServer *server;
for ( server=servers.first(); server != 0; server=servers.next() ) {
- qDebug(server->name);
+ odebug << server->name << oendl;
t << "server=" << server->name << '\n';
t << "\thostname=" << server->hostname << '\n';
t << "\tpassword=" << encipher(server->password )<< '\n';
t << "\tdisplay=" << server->display << '\n';
t << "\thextile=" << server->hexTile << '\n';
t << "\tcorre=" << server->corre << '\n';
t << "\trre=" << server->rre << '\n';
t << "\tcopyrect=" << server->copyrect << '\n';
t << "\tshared=" << server->shared << '\n';
t << "\treadonly=" << server->readOnly << '\n';
t << "\tdeiconify=" << server->deIconify << '\n';
t << "\tupdaterate=" << server->updateRate << '\n';
t << "\tscalefactor=" << server->scaleFactor << '\n';
}
f.close();
}
}
void KVNCBookmarkDlg::refresh(void)
{
bookmarkList->clear();
KRFBServer * server=0;
for ( server=servers.first(); server != 0; server=servers.next() ) {
bookmarkList->insertItem(server->name);
}
}
QString KVNCBookmarkDlg::selectedBookmark()
{
return bookmarkList->currentText();
}
diff --git a/noncore/games/backgammon/backgammon.cpp b/noncore/games/backgammon/backgammon.cpp
index 51020a0..bdb1c78 100644
--- a/noncore/games/backgammon/backgammon.cpp
+++ b/noncore/games/backgammon/backgammon.cpp
@@ -1,177 +1,181 @@
#include "backgammon.h"
-
#include "aidialog.h"
#include "filedialog.h"
#include "playerdialog.h"
#include "rulesdialog.h"
#include "themedialog.h"
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/qpeapplication.h>
+#include <qpe/config.h>
+#include <qpe/resource.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qfile.h>
#include <qlayout.h>
#include <qmessagebox.h>
#include <qtimer.h>
-#include <qpe/qpeapplication.h>
-#include <qpe/config.h>
#include <qmenubar.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");
+ odebug << "config file does not exist" << oendl;
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");
+ odebug << "theme file does not exist" << oendl;
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
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);
diff --git a/noncore/games/backgammon/moveengine.cpp b/noncore/games/backgammon/moveengine.cpp
index 7de7147..a4145cc 100644
--- a/noncore/games/backgammon/moveengine.cpp
+++ b/noncore/games/backgammon/moveengine.cpp
@@ -364,193 +364,193 @@ void MoveEngine::setRules(Rules rules)
int MoveEngine::getPossibleMoves()
{
int homezone[]={0,25,0};
int lastToHomeZone=abs(last_piece[player]-homezone[player]);
for(int field=0;field<26;field++)
{
for(int b=0;b<4;b++)
{
int dice_tmp=dice[b];
if(dice[b]!=7 && dice[b]> lastToHomeZone)
dice_tmp=lastToHomeZone;
int nextfield=(player==1) ? field+dice_tmp : field-dice_tmp;
if(nice_dice)
{
if(player==1 && nextfield>homezone[1])
nextfield=homezone[1];
else if(player==2 && nextfield<homezone[2])
nextfield=homezone[2];
}
moves[field].weight[b]=0;
moves[field].to[b]=nextfield;
int out_of_board[]={-1,0,25};
if(!move_with_pieces_out && field!=out_of_board[player] && pieces_out[player])
{
continue;
}
if(dice[b]!=7 && fieldColor(field)==player ) //player can only move his own pieces
{
if((player==1 && nextfield > homezone[1]) || (player==2 && nextfield < homezone[2]))
{
moves[field].weight[b]=0; //movement would be far out of board
}
else if(nextfield==homezone[player] && !allclear[player])
{
moves[field].weight[b]=0; //can not rescue pieces until all are in the endzone
}
else if(nextfield==homezone[player] && allclear[player])
{
moves[field].weight[b]=ai.rescue; //rescue your pieces : nuff said ;-)
}
else if(fieldColor(nextfield)==otherplayer)
{
if(abs(population[nextfield].total)>1) //can not move to this field
moves[field].weight[b]=0;
else if(abs(population[nextfield].total)==1) //eliminate opponent : very nice
moves[field].weight[b]=ai.eliminate;
}
else if(fieldColor(nextfield)==player) //nextfield already occupied by player
{
if(abs(population[field].total)==2) //expose own piece : not diserable
moves[field].weight[b]=ai.expose;
else if(abs(population[nextfield].total)>1) //own pices already there : safe
moves[field].weight[b]=ai.safe;
else if(abs(population[nextfield].total)==1) //protect own piece : most importatnt
moves[field].weight[b]=ai.protect;
}
else if(population[nextfield].total==0) //nextfield empty
{
if(abs(population[field].total)==2) //expose own piece : not diserable
moves[field].weight[b]=ai.expose;
else
moves[field].weight[b]=ai.empty;
}
else
moves[field].weight[b]=0; //default.
}
else
moves[field].weight[b]=0; //dice already used or field not used by player
}
}
int total=0;
for(int field=0;field<26;field++)
{
total+=moves[field].weight[0]+moves[field].weight[1]+moves[field].weight[2]+moves[field].weight[3];
}
return total;
}
void MoveEngine::move(const int& from, int to, const int& dice)
{
- //qDebug("%d moves from %d to %d (%d) with dice %d",player,from,to,to-from,dice);
+ //odebug << "" << player << " moves from " << from << " to " << to << " (" << to-from << ") with dice " << dice << "" << oendl;
if(player==1 && to==25)
to=26;
if(player==2 && to==0)
to=27;
//if space is occupied by enemy move pieces to startzone
if(fieldColor(to)==otherplayer)
{
population[to].total=0;
if(otherplayer==1)
population[0].total++;
else
population[25].total--;
}
if(player==1)
{
population[from].total--;
population[to].total++;
}
else //player=2
{
population[from].total++;
population[to].total--;
}
if(dice==1)
emit done_dice1();
else if(dice==2)
emit done_dice2();
else if(dice==3)
emit done_dice3();
else
emit done_dice4();
if(abs(population[26].total)==15)
emit player_finished(1);
if(abs(population[27].total)==15)
emit player_finished(2);
}
void MoveEngine::checkstate()
{
//check if pieces are out
pieces_out[1]=(population[0].total>0) ? true : false;
pieces_out[2]=(population[25].total<0) ? true : false;
//check if all pieces are in the endzones
allclear[1]=true;
allclear[2]=true;
last_piece[1]=25;
bool found_last_piece1=false;
last_piece[2]=0;
for(int a=0;a<26;a++)
{
if(a<19 && population[a].total>0)
allclear[1]=false;
if(a>6 && population[a].total<0)
allclear[2]=false;
if(population[a].total>0 && !found_last_piece1)
{
last_piece[1]=a;
found_last_piece1=true;
}
if(population[a].total<0)
last_piece[2]=a;
}
}
void MoveEngine::nomarker(Marker& marker)
{
marker.visible_current=false;
marker_current=-1;
for(int a=0;a<4;a++)
{
marker.x_next[a]=0;
marker.y_next[a]=0;
marker_next[a]=-1;
marker.visible_next[a]=false;
}
}
int MoveEngine::fieldColor(const int& index) const
{
if(population[index].total>0)
return 1;
else if(population[index].total<0)
return 2;
else
return 0;
}
diff --git a/noncore/games/bounce/bounce.pro b/noncore/games/bounce/bounce.pro
index ba745c8..56a325c 100644
--- a/noncore/games/bounce/bounce.pro
+++ b/noncore/games/bounce/bounce.pro
@@ -1,10 +1,9 @@
-#CONFIG = qt warn_on
-CONFIG = qt warn_on quick-app
+CONFIG = qt warn_on quick-app
HEADERS = game.h kbounce.h
SOURCES = game.cpp kbounce.cpp main.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lopiecore2
+LIBS += -lqpe -lopiecore2
TARGET = bounce
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/games/bounce/game.cpp b/noncore/games/bounce/game.cpp
index 1f1f8cd..bbd3d0b 100644
--- a/noncore/games/bounce/game.cpp
+++ b/noncore/games/bounce/game.cpp
@@ -1,120 +1,127 @@
/*
* Copyright (C) 2000 Stefan Schimanski <1Stein@gmx.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
-#include <stdlib.h>
-#include <qtimer.h>
+#include "game.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
-#include "game.h"
+/* QT */
+#include <qtimer.h>
+
+/* STD */
+#include <stdlib.h>
#define TILE_SIZE 9
#define TILE_FIRST ((FIELD_WIDTH-2)*(FIELD_HEIGHT-2))
#define TILE_FREE (TILE_FIRST + 0)
#define TILE_BORDER (TILE_FIRST + 1)
#define TILE_WALLEND (TILE_FIRST + 2)
#define TILE_WALLUP (TILE_FIRST + 3)
#define TILE_WALLDOWN (TILE_FIRST + 4)
#define TILE_WALLLEFT (TILE_FIRST + 5)
#define TILE_WALLRIGHT (TILE_FIRST + 6)
#define GAME_DELAY 15
#define BALL_ANIM_DELAY 60
#define WALL_DELAY 100
#define MS2TICKS( ms ) ((ms)/GAME_DELAY)
Arrow::Arrow(QCanvasPixmapArray* array, QCanvas* canvas)
: QCanvasSprite( array, canvas )
{
m_vertical = true;
move(3,3);
}
void Arrow::update()
{
if ( m_vertical )
setFrame( 0 );
else
setFrame( 1 );
}
void Arrow::changeDirection()
{
m_vertical = ! m_vertical;
update();
}
Ball::Ball(QCanvasPixmapArray* array, QCanvas* canvas)
: QCanvasSprite( array, canvas ), m_animDelay( 0 ), m_soundDelay( MS2TICKS(BALL_ANIM_DELAY)/2 )
{
}
void Ball::update()
{
m_animDelay--;
if ( m_animDelay<=0 )
{
m_animDelay = MS2TICKS(BALL_ANIM_DELAY);
int frameNum = frame();
frameNum++;
if ( frameNum>=frameCount() )
frameNum = 0;
setFrame( frameNum );
}
}
void Ball::advance(int stage)
{
bool reflectX = false;
bool reflectY = false;
// check for collisions
if ( collide(xVelocity(), 0) ) reflectX = true;
if ( collide(0, yVelocity()) ) reflectY = true;
if ( !reflectX && !reflectY && collide(xVelocity(), yVelocity()) ) reflectX = reflectY = true;
// emit collision
QRect r = boundingRect();
r.moveBy( xVelocity(), yVelocity() );
JezzField* field = (JezzField *)canvas();
int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE );
int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE );
int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE );
int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE );
if ( ul!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.top() / TILE_SIZE, ul ); else
if ( ur!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.top() / TILE_SIZE, ur ); else
if ( bl!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.bottom() / TILE_SIZE, bl ); else
if ( br!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.bottom() / TILE_SIZE, br );
// apply reflection
if ( reflectX ) setXVelocity( -xVelocity() );
if ( reflectY ) setYVelocity( -yVelocity() );
// update field
update();
QCanvasSprite::advance( stage );
}
bool Ball::collide( double dx, double dy )
{
QRect r = boundingRect();
@@ -274,193 +281,193 @@ void JezzView::viewportMouseReleaseEvent( QMouseEvent *ev )
}
void JezzView::changeCursor()
{
m_vertical = !m_vertical;
if ( m_vertical )
{
setCursor( sizeVerCursor );
}
else
{
setCursor( sizeHorCursor );
}
}
/*************************************************************************/
JezzGame::JezzGame( int ballNum, QWidget *parent, const char *name )
: QWidget( parent, name ), m_wall1( 0 ), m_wall2( 0 ),
m_text( 0 ), m_running( false ), m_percent( 0 ), m_pictured( false )
{
QString path = QPEApplication::qpeDir()+"pics/bounce/";
// load gfx
m_ballPixmaps = new QCanvasPixmapArray( path + "ball%1.png", 25 );
for ( unsigned n=0; n < m_ballPixmaps->count(); n++ )
m_ballPixmaps->image(n)->setOffset( 0, 0 );
m_arrowPixmaps = new QCanvasPixmapArray( path + "arrow%1.png", 2 );
for ( unsigned n=0; n < m_arrowPixmaps->count(); n++ )
m_arrowPixmaps->image(n)->setOffset( 0, 0 );
QPixmap tiles( path + "tiles.png" );
// create field
m_field = new JezzField( tiles, this, "m_field" );
m_field->resize( TILE_SIZE*FIELD_WIDTH, TILE_SIZE*FIELD_HEIGHT );
for ( int x=0; x<FIELD_WIDTH; x++ )
m_field->setTile( x, 0, TILE_BORDER );
for ( int y=1; y<FIELD_HEIGHT-1; y++ )
{
m_field->setTile( 0, y, TILE_BORDER );
for ( int x=1; x<FIELD_WIDTH-1; x++ )
m_field->setTile( x, y, TILE_FREE );
m_field->setTile( FIELD_WIDTH-1, y, TILE_BORDER );
}
for ( int x=0; x<FIELD_WIDTH; x++ )
m_field->setTile( x, FIELD_HEIGHT-1, TILE_BORDER );
connect( m_field, SIGNAL(ballCollision(Ball*,int,int,int)), this, SLOT(ballCollision(Ball*,int,int,int)) );
// create view
m_view = new JezzView( m_field, this, "m_view" );
m_view->move( 0, 0 );
m_view->adjustSize();
connect( m_view, SIGNAL(buildWall(int,int,bool)), this, SLOT(buildWall(int,int,bool)) );
// create balls
for ( int n=0; n<ballNum; n++ )
{
Ball *ball = new Ball( m_ballPixmaps, m_field );
m_balls.append( ball );
ball->setVelocity( ((rand() & 1)*2-1)*2, ((rand() & 1)*2-1)*2 );
ball->setFrame( rand() % 25 );
ball->move( 4*TILE_SIZE + ( rand() - 50 ) % ( (FIELD_WIDTH-8)*TILE_SIZE ),
4*TILE_SIZE + rand() % ( (FIELD_HEIGHT-8)*TILE_SIZE ) );
ball->show();
}
// create arrow
arrow = new Arrow( m_arrowPixmaps, m_field );
arrow->show();
// create text label
m_text = new QCanvasText( m_field );
// create game clock
m_clock = new QTimer( this );
connect( m_clock, SIGNAL(timeout()), this, SLOT(tick()) );
m_clock->start( GAME_DELAY );
// setup geometry
setFixedSize( m_view->size() );
}
JezzGame::~JezzGame()
{
m_balls.clear();
delete m_view;
delete m_field;
delete m_ballPixmaps;
}
void JezzGame::display( QString text, int size )
{
- qDebug("This function \"display\" shouldn't be called!!!");
+ odebug << "This function \"display\" shouldn't be called!!!" << oendl;
if ( !text.isEmpty() )
{
QFont font( "Helvetica", size, QFont::Bold );
font.setStyleHint( QFont::Helvetica );
m_text->setFont( font );
m_text->setText( text );
QRect size = m_text->boundingRect();
m_text->move( ( FIELD_WIDTH*TILE_SIZE - size.width() ) / 2,
( FIELD_HEIGHT*TILE_SIZE - size.height() ) / 2 );
m_text->show();
} else
{
m_text->hide();
}
}
void JezzGame::start()
{
m_running = true;
}
void JezzGame::stop()
{
m_running = false;
}
void JezzGame::makeBlack()
{
// copy current field into buffer
for ( int y=0; y<FIELD_HEIGHT; y++ )
for ( int x=0; x<FIELD_WIDTH; x++ )
m_buf[x][y] = m_field->tile( x, y );
// fill areas that contains a ball
for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() )
fill( ball->x()/TILE_SIZE, ball->y()/TILE_SIZE );
// areas still free can be blacked now
for ( int y=0; y<FIELD_HEIGHT; y++ )
for ( int x=0; x<FIELD_WIDTH; x++ )
{
if ( m_buf[x][y]==TILE_FREE )
m_field->setGameTile( x, y, true );
}
m_field->update();
m_view->repaint();
// count percent value of occupied area
int p = percent();
if ( p!=m_percent )
{
m_percent = p;
emit newPercent( m_percent );
}
}
int JezzGame::percent()
{
int notFree = 0;
for ( int y=1; y<FIELD_HEIGHT-1; y++ )
for ( int x=1; x<FIELD_WIDTH-1; x++ )
{
if ( m_field->tile(x,y)!=TILE_FREE )
notFree++;
}
return 100 * notFree / ( (FIELD_WIDTH-1) * (FIELD_HEIGHT-1) );
}
void JezzGame::fill( int x, int y )
{
if ( m_buf[x][y]!=TILE_FREE) return;
// go left
int _x=x;
for ( ; m_buf[_x][y]==TILE_FREE; _x-- )
m_buf[_x][y] = TILE_BORDER;
int stopx = _x;
// fill above
for ( _x=x; _x>stopx; _x-- )
if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 );
// fill below
for ( _x=x; _x>stopx; _x-- )
if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 );
// go right
for ( _x=x+1; m_buf[_x][y]==TILE_FREE; _x++ )
m_buf[_x][y] = TILE_BORDER;
stopx = _x;
diff --git a/noncore/games/go/go.pro b/noncore/games/go/go.pro
index b73bbb0..72425a5 100644
--- a/noncore/games/go/go.pro
+++ b/noncore/games/go/go.pro
@@ -1,19 +1,18 @@
-CONFIG = qt warn_on quick-app
+CONFIG = qt warn_on quick-app
HEADERS = amigo.h \
go.h \
goplayutils.h \
gowidget.h
SOURCES = amigo.c \
- goplayer.c \
- goplayutils.c \
- killable.c \
- gowidget.cpp \
- main.cpp
-INCLUDEPATH += $(OPIEDIR)/include
+ goplayer.c \
+ goplayutils.c \
+ killable.c \
+ gowidget.cpp \
+ main.cpp
+INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
LIBS += -lqpe -lopiecore2
TARGET = go
-
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/games/go/gowidget.cpp b/noncore/games/go/gowidget.cpp
index d134540..ec03c1d 100644
--- a/noncore/games/go/gowidget.cpp
+++ b/noncore/games/go/gowidget.cpp
@@ -1,131 +1,132 @@
/**********************************************************************
** 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"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/config.h>
#include <qpe/resource.h>
+using namespace Opie::Core;
+/* QT */
#include <qpainter.h>
#include <qtoolbar.h>
#include <qmenubar.h>
#include <qaction.h>
#include <qapplication.h> //processEvents()
#include <qlabel.h>
-//#include <stdio.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, WFlags fl) :
QMainWindow( parent, name, fl )
{
setToolBarsMovable( FALSE );
GoWidget *go = new GoWidget(this);
setCentralWidget(go);
toolbar = new QToolBar(this);
toolbar->setHorizontalStretchable( TRUE );
addToolBar(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");
@@ -355,106 +356,106 @@ void GoWidget::doComputerMove()
}
}
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 );
+ odebug << "intrMoveReport colour " << c << ", " << coord << " " << reason << "" << oendl;
}
void intrPrisonerReport( short blackcnt, short whitecnt )
{
GoWidget::self->reportPrisoners(blackcnt,whitecnt);
}
}
diff --git a/noncore/games/kpacman/kpacman.pro b/noncore/games/kpacman/kpacman.pro
index 8453f78..45314f9 100644
--- a/noncore/games/kpacman/kpacman.pro
+++ b/noncore/games/kpacman/kpacman.pro
@@ -1,41 +1,39 @@
TEMPLATE = app
-#CONFIG = qt warn_on
CONFIG = qt warn_on
-#TMAKE_CXXFLAGS +=
HEADERS = kpacmanwidget.h \
referee.h \
status.h \
painter.h \
score.h \
pacman.h \
monster.h \
keys.h \
fruit.h \
energizer.h \
board.h \
bitfont.h \
kpacman.h \
bitmaps.h \
colors.h \
portable.h
SOURCES = kpacmanwidget.cpp \
referee.cpp \
status.cpp \
painter.cpp \
score.cpp \
pacman.cpp \
monster.cpp \
keys.cpp \
fruit.cpp \
energizer.cpp \
board.cpp \
bitfont.cpp \
kpacman.cpp \
main.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe
+LIBS += -lqpe -lopiecore2
DESTDIR = $(OPIEDIR)/bin
TARGET = kpacman
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/games/kpacman/kpacmanwidget.cpp b/noncore/games/kpacman/kpacmanwidget.cpp
index 9631495..b59dd02 100644
--- a/noncore/games/kpacman/kpacmanwidget.cpp
+++ b/noncore/games/kpacman/kpacmanwidget.cpp
@@ -1,153 +1,154 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <kapp.h>
#include <kconfig.h>
#include <kstddirs.h>
#include <kpacmanwidget.h>
#include <kpacmanwidget.moc>
#elif defined( QPE_PORT )
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include "kpacmanwidget.h"
#endif
-
+#include <opie2/odebug.h>
+using namespace Opie::Core;
KpacmanWidget::KpacmanWidget( QWidget *parent, const char *name)
: QWidget( parent, name )
{
score = 0l;
referee = 0l;
status = 0l;
bitfont = NULL;
fontName = "";
scheme = mode = -1;
confScheme();
score = new Score(this, name, scheme, mode, bitfont);
referee = new Referee( this, name, scheme, mode, bitfont);
status = new Status(this, name, scheme, mode);
setBackgroundColor( black );
}
KpacmanWidget::~KpacmanWidget()
{
}
void KpacmanWidget::confMisc(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
//KStandardDirs *dirs = KGlobal::dirs();
QString findPath;
if (defGroup || cfg->hasKey("Font")) {
fontName = cfg->readEntry("Font");
if (fontName.left(1) != "/" && fontName.left(1) != "~")
fontName.insert(0, "fonts/");
if (fontName.right(1) == "/")
fontName.append("font.xbm");
//findPath = dirs->findResource("appdata", fontName);
findPath = FIND_APP_DATA( fontName );
if (!findPath.isEmpty())
fontName = findPath;
bitfontFirstChar = cfg->readNumEntry("FontFirstChar", 0x0e);
bitfontLastChar = cfg->readNumEntry("FontLastChar", 0x5f);
}
APP_CONFIG_END( cfg );
}
void KpacmanWidget::confScheme()
{
APP_CONFIG_BEGIN( cfg );
QString lastFontName = fontName;
SAVE_CONFIG_GROUP( cfg, oldgroup );
QString newgroup;
// if not set, read mode and scheme from the configfile
if (mode == -1 && scheme == -1) {
scheme = cfg->readNumEntry("Scheme", -1);
mode = cfg->readNumEntry("Mode", -1);
// if mode is not set in the defGroup-group, lookup the scheme group
if (scheme != -1 || mode == -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
mode = cfg->readNumEntry("Mode", -1);
RESTORE_CONFIG_GROUP( cfg, oldgroup );
}
}
confMisc();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confMisc(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confMisc(FALSE);
}
if (lastFontName != fontName) {
if (bitfont != 0)
delete bitfont;
bitfont = new Bitfont(fontName, bitfontFirstChar, bitfontLastChar);
if (bitfont->width() == 0 || bitfont->height() == 0) {
QString msg = tr("The bitfont could not be contructed.\n\n"
"The file '@FONTNAME@' does not exist,\n"
"or is of an unknown format.");
msg.replace(QRegExp("@FONTNAME@"), fontName);
// QMessageBox::critical(this, tr("Initialization Error"), msg);
printf("%s\n", msg.data());
}
}
RESTORE_CONFIG_GROUP( cfg, oldgroup );
APP_CONFIG_END( cfg );
}
void KpacmanWidget::setScheme(int Scheme, int Mode)
{
mode = Mode;
scheme = Scheme;
confScheme();
score->setScheme(Scheme, Mode, bitfont);
referee->setScheme(Scheme, Mode, bitfont);
status->setScheme(Scheme, Mode);
score->repaint(FALSE);
referee->repaint(FALSE);
status->repaint(FALSE);
}
void KpacmanWidget::resizeEvent( QResizeEvent * )
{
- qWarning("Resize");
+ owarn << "Resize" << oendl;
referee->setGeometry(0, bitfont->height()*3, referee->width(), referee->height());
referee->setBackgroundColor(BLACK);
if(!status ) return;
status->setGeometry(0, bitfont->height()*3+referee->height(), referee->width(),
status->height());
status->setBackgroundColor(BLACK);
score->setGeometry(0, 0, referee->width(), bitfont->height()*3+referee->height()+status->height());
score->setBackgroundColor(BLACK);
}
diff --git a/noncore/games/kpacman/status.cpp b/noncore/games/kpacman/status.cpp
index 02ff63d..db6938e 100644
--- a/noncore/games/kpacman/status.cpp
+++ b/noncore/games/kpacman/status.cpp
@@ -1,119 +1,122 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <kapp.h>
#include <klocale.h>
#include <kstddirs.h>
#include <status.h>
#include <status.moc>
#elif defined( QPE_PORT )
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include "status.h"
#endif
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
#include <qbitmap.h>
#include <qmsgbox.h>
#include <qfileinfo.h>
Status::Status( QWidget *parent, const char *name, int Scheme, int Mode ) :
QWidget( parent, name )
{
- qWarning("Status::Status");
+ owarn << "Status::Status" << oendl;
actualLifes = 0;
actualLevel = 0;
lifesPix = NULL;
levelPix = NULL;
scheme = Scheme;
mode = Mode;
level = 0;
confScheme();
}
QList<QPixmap> *Status::loadPixmap(QWidget *parent, QString pixmapName,
QList<QPixmap> *pixmaps)
{
if (pixmaps == NULL) {
pixmaps = new QList<QPixmap>;
pixmaps->setAutoDelete(TRUE);
}
if (!pixmaps->isEmpty())
pixmaps->clear();
QPixmap PIXMAP(pixmapName);
if (PIXMAP.isNull() || PIXMAP.mask() == NULL) {
QString msg = tr("The pixmap could not be contructed.\n\n"
"The file '@PIXMAPNAME@' does not exist,\n"
"or is of an unknown format.");
msg.replace(QRegExp("@PIXMAPNAME@"), pixmapName);
QMessageBox::information(parent, tr("Initialization Error"),
(const char *) msg);
return 0;
}
int height = PIXMAP.height();
int width = (height == 0) ? 0 : PIXMAP.width()/(PIXMAP.width()/height);
QBitmap BITMAP;
QBitmap MASK;
BITMAP = *PIXMAP.mask();
MASK.resize(width, height);
for (int x = 0; x < PIXMAP.width()/width; x++) {
QPixmap *pixmap = new QPixmap(width, height);
pixmaps->append(pixmap);
bitBlt(pixmap, 0, 0, &PIXMAP, x*width, 0, width, height, CopyROP, TRUE);
bitBlt(&MASK, 0, 0, &BITMAP, x*width, 0, width, height, CopyROP, TRUE);
pixmap->setMask(MASK);
}
return pixmaps;
}
void Status::paintEvent( QPaintEvent *)
{
for (int x = 0; x < actualLifes && !lifesPix->isEmpty(); x++)
bitBlt(this, lifesPix->at(0)->width()+(lifesPix->at(0)->width()*x),
(height()-lifesPix->at(0)->height())/2,
lifesPix->at(0), 0, 0,
lifesPix->at(0)->width(), lifesPix->at(0)->height());
for (int x = 0; x < actualLevel && !levelPix->isEmpty(); x++) {
erase((width()-levelPix->at(x)->width()*2)-(levelPix->at(x)->width()*levelPos[x]),
(height()-levelPix->at(x)->height())/2,
levelPix->at(x)->width(), levelPix->at(x)->height());
bitBlt(this, (width()-levelPix->at(x)->width()*2)-(levelPix->at(x)->width()*levelPos[x]),
(height()-levelPix->at(x)->height())/2,
levelPix->at(x), 0, 0,
levelPix->at(x)->width(), levelPix->at(x)->height());
}
}
void Status::initPixmaps()
{
if (lastLifesPixmapName != lifesPixmapName.at(level)) {
lifesPix = loadPixmap(this, lifesPixmapName.at(level), lifesPix);
lastLifesPixmapName = lifesPixmapName.at(level);
}
if (lastLevelPixmapName != levelPixmapName.at(level)) {
levelPix = loadPixmap(this, levelPixmapName.at(level), levelPix);
lastLevelPixmapName = levelPixmapName.at(level);
}
}
QString Status::decodeHexOctString(QString s)
{
QString value;
QString valids;
int pos, xpos = 0, opos = 0;
int v, len, leadin;
const char *ptr;
uchar c;
while (((xpos = s.find(QRegExp("\\\\x[0-9a-fA-F]+"), xpos)) != -1) ||
diff --git a/noncore/games/mindbreaker/mindbreaker.cpp b/noncore/games/mindbreaker/mindbreaker.cpp
index 2b924c6..1f554d2 100644
--- a/noncore/games/mindbreaker/mindbreaker.cpp
+++ b/noncore/games/mindbreaker/mindbreaker.cpp
@@ -1,189 +1,189 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "mindbreaker.h"
#include <qtopia/resource.h>
#include <qtopia/config.h>
#include <qtopia/qpeapplication.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qmessagebox.h>
#include <qlayout.h>
#include <qtimer.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
static int pegRTTI = 3393393;
static int adjusted_panel_height;
static int adjusted_panel_width;
static int adjusted_bin_margin;
static int adjusted_peg_size;
static int adjusted_answerpeg_size;
static int adjusted_title_height;
static int adjusted_title_width;
static int adjusted_first_peg_x_diff;
static int adjusted_first_peg_y_diff;
static int adjusted_peg_spacing;
static int adjusted_answerpegx;
static int adjusted_answerpegy;
static int adjusted_answerpeg_xdiff;
static int adjusted_answerpeg_ydiff;
static int adjusted_board_height;
static int adjusted_board_width;
static void setupBoardSize(int w, int h)
{
adjusted_panel_width = w * 3/4;
adjusted_title_width = w * 3/4;
adjusted_title_height = h/10;
adjusted_panel_height = (h-adjusted_title_height)/9;
adjusted_bin_margin = w * 10/240;
adjusted_peg_size = adjusted_panel_height*3/4;
adjusted_answerpeg_size = QMIN(adjusted_panel_width*15/180,adjusted_panel_height*15/25);
// looks a bit dodgy on larger sizes
if ( adjusted_peg_size > 40 )
adjusted_peg_size = 40;
adjusted_first_peg_x_diff = w * 31/240-adjusted_peg_size/2;
adjusted_first_peg_y_diff = (adjusted_panel_height - adjusted_peg_size)/2;
adjusted_peg_spacing = w * 30/240;
// looks a bit dodgy on larger sizes (still does though, but not as much...)
if ( adjusted_answerpeg_size > 22 )
adjusted_answerpeg_size = 22;
adjusted_answerpegx = adjusted_panel_width * 159/180 - adjusted_answerpeg_size/2;
adjusted_answerpegy = adjusted_panel_height/3 - adjusted_answerpeg_size/2;
adjusted_answerpeg_xdiff = adjusted_panel_width * 10/180;
adjusted_answerpeg_ydiff = adjusted_panel_height * 9/25;
adjusted_board_height = adjusted_title_height + (adjusted_panel_height * 9);
adjusted_board_width = adjusted_panel_width + (adjusted_bin_margin * 2) + adjusted_peg_size;
-// qDebug("Adjusted width %d height %d", adjusted_board_width, adjusted_board_height);
+// odebug << "Adjusted width " << adjusted_board_width << " height " << adjusted_board_height << "" << oendl;
}
/* helper class, */
class Peg : public QCanvasRectangle
{
public:
Peg(QCanvas *canvas, int type, int go = -1, int pos = -1);
int rtti() const {return pegRTTI; }
void advance(int phase);
bool hit( const QPoint &) const;
/* a placed peg is one that has been set down on the board correctly and
should not be moved, only copied */
bool placed() const;
void setPlaced(bool);
int pegGo() const;
int pegPos() const;
void setPegPos(int);
int type() const;
static void buildImages();
static QImage imageForType(int t);
static int eggLevel;
protected:
void drawShape(QPainter &);
private:
static QVector<QImage> normalPegs;
static QVector<QImage> specialPegs;
bool isplaced;
int pegtype;
int peg_go;
int peg_pos;
int aniStep;
};
int Peg::eggLevel = 0;
QVector<QImage> Peg::normalPegs;
QVector<QImage> Peg::specialPegs;
void Peg::buildImages()
{
QImage pegs = Resource::loadImage("mindbreaker/pegs");
int x = 0;
int y = 0;
int i;
eggLevel = 0;
normalPegs.resize(10);
for (i = 0; i < 6; i++) {
normalPegs.insert(i, new QImage(pegs.copy(x, y, peg_size, peg_size).
smoothScale(adjusted_peg_size, adjusted_peg_size) ));
x += peg_size;
}
specialPegs.resize(5);
for (i = 0; i < 5; i++) {
specialPegs.insert(i, new QImage(pegs.copy(x,y,peg_size, peg_size).
smoothScale(adjusted_peg_size, adjusted_peg_size) ));
x += peg_size;
}
QImage image = Resource::loadImage("mindbreaker/mindbreaker");
/* copy from master image to functional images */
x = 0;
y = panel_height;
normalPegs.insert(8,
new QImage( image.copy(x, y, panel_width, panel_height).
smoothScale( adjusted_panel_width, adjusted_panel_height)
));
y += panel_height;
y += title_height;
normalPegs.insert(9,
new QImage(image.copy(x, y, title_width, title_height).
smoothScale( adjusted_title_width, adjusted_title_height)
));
y += title_height;
x = 6 * peg_size;
normalPegs.insert(6,
new QImage(image.copy(x, y, answerpeg_size, answerpeg_size).
smoothScale( adjusted_answerpeg_size, adjusted_answerpeg_size) ));
x += answerpeg_size;
normalPegs.insert(7,
new QImage(image.copy(x, y, answerpeg_size, answerpeg_size).
smoothScale( adjusted_answerpeg_size, adjusted_answerpeg_size) ));
}
QImage Peg::imageForType(int t)
{
if (eggLevel > t ) {
if( t < 5) {
diff --git a/noncore/games/oyatzee/oyatzee.cpp b/noncore/games/oyatzee/oyatzee.cpp
index a55aa73..27c0a9f 100644
--- a/noncore/games/oyatzee/oyatzee.cpp
+++ b/noncore/games/oyatzee/oyatzee.cpp
@@ -1,490 +1,496 @@
#include "oyatzee.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qmessagebox.h>
#include <qpushbutton.h>
#include <qpainter.h>
#include <qlayout.h>
+/* STD */
#include <stdlib.h>
OYatzee::OYatzee( QWidget *parent , const char *name, WFlags fl ) : QMainWindow( parent , name , fl )
{
QWidget *thing = new QWidget( this );
setCentralWidget( thing );
setCaption( tr( "OYatzee" ) );
setPlayerNumber( 4 );
setRoundsNumber( 1 );
lastPlayerFinished = false;
currentPlayer = 1;
ps.append( new Player( "Carsten" ) );
ps.append( new Player( "Julia" ) );
ps.append( new Player( "Christine" ) );
ps.append( new Player( "Stephan" ) );
QVBoxLayout *vbox = new QVBoxLayout( thing );
sb = new Scoreboard( ps, thing , "sb" );
connect( sb->pb , SIGNAL( item(int) ), this , SLOT( slotEndRound(int) ) );
dw = new DiceWidget( thing , "dw" );
dw->setMaximumHeight( this->height()/4 );
connect( dw->rollButton, SIGNAL( clicked() ), this , SLOT( slotRollDices() ) );
vbox->addWidget( sb );
vbox->addWidget( dw );
}
void OYatzee::slotEndRound( int item )
{
- qDebug( "Der User hat Nummer %d ausgewählt" , item );
+ odebug << "Der User hat Nummer " << item << " ausgewählt" << oendl;
/*
* if the user clicked on Total, Bonus or Score and thus not on a
* selectable item return and do nothing
*/
if ( item == 7 || item == 8 || item == 16 ) return;
/*
* check if the user can really click on that item
*/
if ( posibilities.find( item ) == posibilities.end() ) return;
QValueListInt numbers;
Dice *d = dw->diceList.first();
for ( ; d != 0 ; d = dw->diceList.next() )
{
numbers.append( d->hasValue() );
}
int points = 0;
switch ( item )
{
case Ones:
points = getPoints( 1 , numbers );
break;
case Twos:
points = getPoints( 2 , numbers );
break;
case Threes:
points = getPoints( 3 , numbers );
break;
case Fours:
points = getPoints( 4 , numbers );
break;
case Fives:
points = getPoints( 5 , numbers );
break;
case Sixes:
points = getPoints( 6 , numbers );
break;
case ThreeOfAKind:
points = oakPoints;
break;
case FourOfAKind:
points = oakPoints;
break;
case FullHouse:
points = 25;
break;
case SStraight:
points = 30;
break;
case LStraight:
points = 40;
break;
case Yatzee:
points = 50;
break;
case Chance:
points = getPoints ( Chance , numbers );
}
sb->nextRB(currentPlayer-1)->updateMap( item , points );
nextPlayer();
- qDebug( "Punkte: %d" , points );
+ odebug << "Punkte: " << points << "" << oendl;
}
void OYatzee::nextPlayer()
{
currentPlayer++;
if ( currentPlayer > numOfPlayers )
{
currentPlayer = 1;
}
ps.at(currentPlayer-1)->turn = 0;
}
int OYatzee::getPoints( const int num , QValueListInt l)
{
QValueListInt::Iterator it = l.begin();
int c = 0;
if ( num != Chance )
{
for ( ; it != l.end() ; ++it )
{
if ( *it == num )
c++;
}
return c * num;
}
else
{
for ( ; it != l.end() ; ++it )
{
c += *it;
}
return c;
}
}
OYatzee::~OYatzee()
{
}
void OYatzee::detectPosibilities()
{
posibilities.clear();
- qDebug( "running detectPosibilities()" );
+ odebug << "running detectPosibilities()" << oendl;
Dice *d = dw->diceList.first();
QValueListInt numbers;
for ( ; d != 0 ; d = dw->diceList.next() )
{
numbers.append( d->hasValue() );
}
//the 6 numbers
QValueListInt::Iterator it;
for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6
{
bool cont = false;
it = numbers.begin();
for ( ; it != numbers.end() ; ++it )
{
if ( cont )
continue;
if ( numbers.find( i ) != numbers.end() )
{
posibilities.append( i );
cont = true;
}
}
}
//3er, 4er, Yatzee
it = numbers.begin();
int count;
int temp;
int countFH = 0; //for the full-house-check
for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6 at least 3 times
{
count = 0;
temp = 0;
it = numbers.begin();
for ( ; it != numbers.end() ; ++it )
{
if ( *it == i )
{
count++;
temp++;
}
if ( temp == 2 )
countFH = temp;
}
if ( count >= 3 )
{
posibilities.append( 9 );
//now we check if it is a full house
if ( count == 3 && countFH == 2 ) //aka Full House
posibilities.append( 11 );
if ( count >= 4 )
posibilities.append( 10 );
if ( count == 5 ) //Yatzee
posibilities.append( 14 );
oakPoints = count * i;
}
}
//S-Straight
if ( numbers.find( 3 ) != numbers.end() && numbers.find( 4 ) != numbers.end() )
{
bool isLong = false;
bool isShort = true;
//L-Straight
if ( numbers.find( 2 ) != numbers.end() && numbers.find( 5 ) != numbers.end() )
{
isShort = true;
//12345 or 23456
if ( numbers.find( 1 ) != numbers.end() || numbers.find( 6) != numbers.end() )
isLong = true;
}
//1234
if ( numbers.find( 1 ) != numbers.end() && numbers.find( 2 ) != numbers.end() )
isShort = true;
//3456
if ( numbers.find( 5 ) != numbers.end() && numbers.find( 6 ) != numbers.end() )
isShort = true;
if ( isShort )
posibilities.append( 12 );
if ( isLong )
posibilities.append( 13 );
}
posibilities.append( 13 ); //Chance, well, this is allways possible
displayPossibilites();
}
void OYatzee::displayPossibilites()
{
//X for ( QValueListInt::Iterator it = posibilities.begin() ; it != posibilities.end(); ++it )
//X {
-//X qDebug( QString::number( *it ) );
+//X odebug << QString::number( *it ) << oendl;
//X switch ( *it )
//X {
//X case Ones:
-//X qDebug( "1er" );
+//X odebug << "1er" << oendl;
//X break;
//X case Twos:
-//X qDebug( "2er" );
+//X odebug << "2er" << oendl;
//X break;
//X case Threes:
-//X qDebug( "3er" );
+//X odebug << "3er" << oendl;
//X break;
//X case Fours:
-//X qDebug( "4er" );
+//X odebug << "4er" << oendl;
//X break;
//X case Fives:
-//X qDebug( "5er" );
+//X odebug << "5er" << oendl;
//X break;
//X case Sixes:
-//X qDebug( "6er" );
+//X odebug << "6er" << oendl;
//X break;
//X case ThreeOfAKind:
-//X qDebug( "3oaK" );
+//X odebug << "3oaK" << oendl;
//X break;
//X case FourOfAKind:
-//X qDebug( "4oaK" );
+//X odebug << "4oaK" << oendl;
//X break;
//X case FullHouse:
-//X qDebug( "Full House" );
+//X odebug << "Full House" << oendl;
//X break;
//X case SStraight:
-//X qDebug( "Short S" );
+//X odebug << "Short S" << oendl;
//X break;
//X case LStraight:
-//X qDebug( "Long S" );
+//X odebug << "Long S" << oendl;
//X break;
//X case Yatzee:
-//X qDebug( "Yatzee!" );
+//X odebug << "Yatzee!" << oendl;
//X break;
//X case Chance:
-//X qDebug( "Chance" );
+//X odebug << "Chance" << oendl;
//X break;
//X }
//X }
sb->pb->setIntlist( posibilities );
sb->pb->update();
}
void OYatzee::startGame()
{
/*
* TODO
*/
}
void OYatzee::stopGame(){}
void OYatzee::setPlayerNumber( const int num )
{
numOfPlayers = num;
}
void OYatzee::setRoundsNumber( const int num )
{
numOfRounds = num;
}
void OYatzee::slotStartGame()
{
}
void OYatzee::slotRollDices()
{
- qDebug( "Roll nummer: %d" , ps.at( currentPlayer-1 )->turn );
+ odebug << "Roll nummer: " << ps.at( currentPlayer-1 )->turn << "" << oendl;
if ( ps.at( currentPlayer-1 )->turn == 3 )
{
QMessageBox::information( this,
"OYatzee",
tr( "Only three rolls per turn allowed." ) );
return;
}
Dice *d = dw->diceList.first();
for ( ; d != 0 ; d = dw->diceList.next() )
{
if ( !d->isSelected )
d->roll();
}
-// qDebug( "Roll nummer (vorher): %d" , ps.at( currentPlayer-1 )->turn );
+// odebug << "Roll nummer (vorher): " << ps.at( currentPlayer-1 )->turn << "" << oendl;
ps.at(currentPlayer-1)->turn++;
-// qDebug( "Roll nummer (nachher): %d" , ps.at( currentPlayer-1 )->turn );
+// odebug << "Roll nummer (nachher): " << ps.at( currentPlayer-1 )->turn << "" << oendl;
detectPosibilities();
}
/*
* Scoreboard
*/
Scoreboard::Scoreboard( playerList ps, QWidget *parent, const char *name ) : QWidget( parent , name )
{
ps_ = ps;
pb = new Possibilityboard( this , "pb" );
createResultboards( 4 );
QHBoxLayout *hbox = new QHBoxLayout( this );
hbox->addWidget( pb );
hbox->addSpacing( 25 );
Resultboard *r = rbList.first();
for ( ; r != 0 ; r = rbList.next() )
{
hbox->addWidget( r );
}
}
Resultboard* Scoreboard::nextRB( int currentPlayer )
{
Resultboard *b;
b = rbList.at( currentPlayer );
- qDebug( "Anzahl: %d" , rbList.count() );
+ odebug << "Anzahl: " << rbList.count() << "" << oendl;
return b;
}
void Scoreboard::createResultboards(const int num)
{
Player *p = ps_.first();
for ( int i = 0 ; i < num ; ++i , p = ps_.next() )
{
QString n = p->playerName;
rbList.append( new Resultboard( n , this ) );
}
}
void Scoreboard::paintEvent( QPaintEvent * )
{
//X QPainter p;
//X p.begin( this );
//X
//X p.drawRect( 0,0, this->width() , this->height() );
}
/*
* Dice
*/
Dice::Dice( QWidget *parent , const char *name ) : QFrame( parent , name )
{
QTime t = QTime::currentTime(); // set random seed
srand(t.hour()*12+t.minute()*60+t.second()*60);
connect( this , SIGNAL( selected() ), this , SLOT( slotSelected() ) );
}
void Dice::slotSelected()
{
if ( isSelected )
isSelected = false;
else isSelected = true;
update();
}
const int Dice::hasValue() const
{
return Value;
}
void Dice::roll()
{
Value = rand()%6;
Value += 1;
update();
}
void Dice::mousePressEvent( QMouseEvent* /*e*/ )
{
emit selected();
}
void Dice::paintEvent( QPaintEvent * )
{
QPainter p;
p.begin( this );
p.drawRect( 0,0, this->width() , this->height() );
if ( isSelected )
p.drawRect( 20,20, 10,10 );
paintNumber( &p );
}
void Dice::paintNumber( QPainter *p )
{
p->setBrush( Qt::black );
int w = this->width();
int h = this->height();
int r = this->width();
r /= 10;
switch ( Value )
{
case 1:
p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
break;
case 2:
p->drawEllipse( (int)( 0.3*w - r ) , (int)( 0.3*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.7*w - r ) , (int)( 0.7*h - r ) , r , r ) ;
break;
case 3:
p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
break;
@@ -515,173 +521,173 @@ void Dice::paintNumber( QPainter *p )
/*
* DiceWidget
*/
DiceWidget::DiceWidget( QWidget *parent , const char *name ) : QWidget( parent , name )
{
rollButton = new QPushButton( tr( "Roll" ) , this ) ;
for ( int i = 0 ; i < 5 ; i++ )
{
//appending the 5 dices of the game
diceList.append( new Dice( this, "wuerfel" ) );
}
QHBoxLayout *hbox = new QHBoxLayout( this );
Dice *d = diceList.first();
for ( ; d != 0 ; d = diceList.next() )
{
hbox->addWidget( d );
}
hbox->addWidget( rollButton );
}
/*
* Player
*/
Player::Player( QString name )
{
playerName = name;
setupResultList();
turn = 0;
}
void Player::setupResultList()
{
for ( int i = 1 ; i < 14 ; ++i )
{
pResults.append( 0 );
}
}
/*
* TODO: muss noch genutzt werden
*/
void Player::updateTotalPoints( pointMap m )
{
pointMap::Iterator it = m.begin();
for ( ; it != m.end() ; ++it )
{
totalPoints += it.data();
}
}
void Player::setResults( const int cat , const int points )
{
QValueListInt::Iterator it = pResults.at( cat );
*it = points;
}
/*
* Board
*/
Board::Board( QWidget *parent , const char* name ) : QWidget ( parent , name )
{
}
void Board::mousePressEvent( QMouseEvent *e )
{
emit clicked( e->pos() );
}
/*
* Resultboard
*/
Resultboard::Resultboard( QString playerName , QWidget *parent , const char* name ) : Board ( parent , name )
{
pName = playerName;
}
void Resultboard::paintEvent( QPaintEvent* )
{
QPainter p;
p.begin( this );
const int cell_width = this->width();
const int cell_height = this->height()/17;
pointMap::Iterator it = pMap.begin();
for ( ; it != pMap.end() ; ++it )
{
int i = it.key();
- qDebug( "ok: %d , %d" , i , it.data() );
+ odebug << "ok: " << i << " , " << it.data() << "" << oendl;
p.drawText( 0, i*cell_height , cell_width , cell_height , Qt::AlignCenter , QString::number( it.data() ) );
}
p.drawText( 0,0,cell_width,cell_height, Qt::AlignCenter , pName ); //Playername
}
void Resultboard::updateMap( int item , int points )
{
pMap.insert( item , points );
update();
}
/*
* Possibilityboard
*/
Possibilityboard::Possibilityboard( QWidget *parent , const char* name ) : Board ( parent , name )
{
begriffe.append( "1er" );
begriffe.append( "2er" );
begriffe.append( "3er" );
begriffe.append( "4er" );
begriffe.append( "5er" );
begriffe.append( "6er" );
begriffe.append( "Total" );
begriffe.append( "Bonus" );
begriffe.append( "3oaK" );
begriffe.append( "4oaK" );
begriffe.append( "Full House" );
begriffe.append( "Short S" );
begriffe.append( "Long S" );
begriffe.append( "Yatzee!" );
begriffe.append( "Chance" );
begriffe.append( "Score" );
connect( this , SIGNAL( clicked(QPoint) ), this , SLOT( slotClicked(QPoint) ) );
}
void Possibilityboard::slotClicked( QPoint p)
{
emit item( p.y()/(this->height()/17) );
}
void Possibilityboard::paintEvent( QPaintEvent* )
{
QPainter p;
p.begin( this );
const int cell_width = this->width();
const int cell_height = this->height()/17;
p.setBrush( Qt::blue );
QValueListInt::Iterator listIt = list.begin();
for ( ; listIt != list.end() ; ++listIt )
{
p.drawRect( 0 , (*listIt) * cell_height , cell_width , cell_height );
}
p.setBrush( Qt::black );
p.setBrush( Qt::NoBrush );
QStringList::Iterator begriffeIt = begriffe.begin();
for ( int i = 1 ; i < 18 ; ++i )
{
p.drawText( 0 , i*cell_height , cell_width , cell_height , Qt::AlignCenter , *begriffeIt );
++begriffeIt;
}
}
void Possibilityboard::setIntlist( QValueListInt &l )
{
list = l;
}
diff --git a/noncore/games/oyatzee/oyatzee.pro b/noncore/games/oyatzee/oyatzee.pro
index 754abd2..f505c66 100644
--- a/noncore/games/oyatzee/oyatzee.pro
+++ b/noncore/games/oyatzee/oyatzee.pro
@@ -1,11 +1,11 @@
TEMPLATE = app
CONFIG = qt warn_on
DESTDIR = $(OPIEDIR)/bin
HEADERS = oyatzee.h
SOURCES = main.cpp oyatzee.cpp
TARGET = oyatzee
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe
+LIBS += -lqpe -lopiecore2
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/games/wordgame/wordgame.cpp b/noncore/games/wordgame/wordgame.cpp
index a80bd35..47d6725 100644
--- a/noncore/games/wordgame/wordgame.cpp
+++ b/noncore/games/wordgame/wordgame.cpp
@@ -582,193 +582,193 @@ bool ComputerPlayer::step()
uchar nletter[4095]; // QDawg only handles 0..4095
memset(nletter,0,4096);
for (int i=0; i<rack->count(); i++) {
const Tile* r = rack->tileRef(i);
if ( r->isBlank() )
nletter[0]++;
else
nletter[r->text()[0].unicode()]++;
}
Tile blankvalues[99]; // ### max blanks
findBest(current, d, root, 0, nletter, tiles, 0, blankvalues, 0);
if ( ++current.rx() == board->xTiles() ) {
current.rx() = 0;
if ( ++current.ry() == board->yTiles() ) {
if ( across ) {
if ( dict == 1 ) {
if ( best_score >= 0 ) {
rack->arrangeTiles(best,best_n);
rack->setBlanks(best_blankvalues);
board->scoreTurn(best_start, best_n, best_dir);
board->showTurn();
}
return FALSE;
}
dict++;
across = FALSE;
current = QPoint(0,0);
} else {
across = TRUE;
current = QPoint(0,0);
}
}
}
return TRUE;
}
void ComputerPlayer::findBest(QPoint at, const QPoint& d, const QDawg::Node* node, ulong used, uchar* nletter, const Tile** tiles, int n, Tile* blankvalues, int blused)
{
if ( !node )
return;
QChar l = node->letter();
const Tile* cur = board->tile(at);
if ( cur ) {
if ( cur->text()[0] == l ) {
bool nextok = board->contains(at+d);
if ( node->isWord() && n && (!nextok || !board->tile(at+d)) )
noteChoice(tiles,n,d,blankvalues,blused);
if ( nextok )
findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused);
// #### text()[1]...
}
} else {
if ( nletter[l.unicode()] || nletter[0] ) {
int rc = rack->count();
ulong msk = 1;
for ( int x=0; x<rc; x++ ) {
if ( !(used&msk) ) {
const Tile* t = rack->tileRef(x);
if ( t->isBlank() || t->text() == l ) { // #### multi-char value()s
bool nextok = board->contains(at+d);
tiles[n++] = t;
if ( t->isBlank() )
blankvalues[blused++] = Tile(l,0);
if ( node->isWord() && (!nextok || !board->tile(at+d)) )
noteChoice(tiles,n,d,blankvalues,blused);
used |= msk; // mark
nletter[t->text()[0].unicode()]--;
if ( nextok )
findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused);
n--;
nletter[t->text()[0].unicode()]++;
if ( t->isBlank() ) {
// keep looking
blused--;
used &= ~msk; // unmark
} else {
break;
}
}
}
msk <<= 1;
}
}
// #### text()[1]...
}
findBest(at, d, node->next(), used, nletter, tiles, n, blankvalues, blused);
}
void ComputerPlayer::noteChoice(const Tile** tiles, int n, const QPoint& d, const Tile* blankvalues, int blused)
{
int s = board->score(current, tiles, n, blankvalues, d, TRUE, 0);
/*
if (s>0 || current==QPoint(5,1)){
QString st;
for ( int i=0; i<n; i++ )
st += tiles[i]->text();
-qDebug("%d,%d: %s (%d) for %d",current.x(),current.y(),st.latin1(),n,s);
+odebug << "" << current.x() << "," << current.y() << ": " << st.latin1() << " (" << n << ") for " << s << "" << oendl;
}
*/
if ( s > best_score ) {
int i;
for ( i=0; i<n; i++ )
best[i] = tiles[i];
for ( i=0; i<blused; i++ )
best_blankvalues[i] = blankvalues[i];
best_n = n;
best_blused = blused;
best_score = s;
best_dir = d;
best_start = current;
}
}
int TileItem::smallWidth()
{
return tile_smallw;
}
int TileItem::smallHeight()
{
return tile_smallh;
}
int TileItem::bigWidth()
{
return tile_bigw;
}
int TileItem::bigHeight()
{
return tile_bigh;
}
void TileItem::setState( State state )
{
hide();
s = state;
show(); // ### use update() in Qt 3.0
}
void TileItem::setTile(const Tile& tile)
{
hide();
t = tile;
show(); // ### use update() in Qt 3.0
}
void TileItem::setBig(bool b)
{
big = b;
}
void TileItem::drawShape(QPainter& p)
{
static QFont *value_font=0;
static QFont *big_font=0;
static QFont *small_font=0;
if ( !value_font ) {
value_font = new QFont("helvetica",8);
if ( TileItem::bigWidth() < 20 ) {
big_font = new QFont("helvetica",12);
small_font = new QFont("helvetica",8);
} else {
big_font = new QFont("smoothtimes",17);
small_font = new QFont("smoothtimes",10);
}
}
QRect area(x(),y(),width(),height());
p.setBrush(s == Floating ? yellow/*lightGray*/ : white);
p.drawRect(area);
if ( big ) {
p.setFont(*value_font);
QString n = QString::number(t.value());
int w = p.fontMetrics().width('1');
int h = p.fontMetrics().height();
w *= n.length();
QRect valuearea(x()+width()-w-1,y()+height()-h,w,h);
p.drawText(valuearea,AlignCenter,n);
p.setFont(*big_font);
area = QRect(x(),y()+tile_btweak,width()-4,height()-1);
} else {
p.setFont(*small_font);
area = QRect(x()+1+tile_stweak,y()+1,width(),height()-3);
}
if ( t.value() == 0 )
p.setPen(darkGray);
p.drawText(area,AlignCenter,t.text().upper());
}
Board::Board(QPixmap bgshapes, int w, int h, QWidget* parent) :
QCanvasView(new QCanvas(bgshapes,w,h, TileItem::smallWidth(), TileItem::smallHeight()),
parent)
diff --git a/noncore/graphics/opie-eye/config.in b/noncore/graphics/opie-eye/config.in
index 996dcf3..d7f9963 100644
--- a/noncore/graphics/opie-eye/config.in
+++ b/noncore/graphics/opie-eye/config.in
@@ -1,9 +1,9 @@
config OPIE_EYE
boolean "opie-eye The Image Viewer and Browser"
default "y"
- depends on ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI
+ depends on ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && LIBOPIE2UI
config OPIE_EYE_SLAVE
boolean
default "y" if OPIE_EYE
- depends on ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI
+ depends on ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && LIBOPIE2UI
diff --git a/noncore/graphics/opie-eye/impl/dir/dir_ifaceinfo.cpp b/noncore/graphics/opie-eye/impl/dir/dir_ifaceinfo.cpp
index 79f4510..5599ad1 100644
--- a/noncore/graphics/opie-eye/impl/dir/dir_ifaceinfo.cpp
+++ b/noncore/graphics/opie-eye/impl/dir/dir_ifaceinfo.cpp
@@ -1,47 +1,51 @@
/*
* GPLv2
* zecke@handhelds.org
*/
+#include "dir_ifaceinfo.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/config.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qwidget.h>
#include <qcheckbox.h>
#include <qhbox.h>
#include <qlabel.h>
-#include <qpe/config.h>
-
-#include "dir_ifaceinfo.h"
-
namespace {
class DirImageWidget : public QHBox {
public:
DirImageWidget() {
chkbox = new QCheckBox( QObject::tr("Show all files"), this );
}
~DirImageWidget() {}
QCheckBox* chkbox;
};
}
DirInterfaceInfo::DirInterfaceInfo() {
}
DirInterfaceInfo::~DirInterfaceInfo() {
}
QString DirInterfaceInfo::name()const {
return QString::fromLatin1(QObject::tr("DirView" ));
}
QWidget* DirInterfaceInfo::configWidget(const Config& cfg) {
DirImageWidget* wid = new DirImageWidget();
wid->chkbox->setChecked( cfg.readBoolEntry("Dir_Check_All_Files", true) );
return wid;
}
void DirInterfaceInfo::writeConfig( QWidget* _wid, Config& cfg) {
- qWarning( "Write Config" );
+ owarn << "Write Config" << oendl;
DirImageWidget* wid = static_cast<DirImageWidget*>(_wid);
cfg.writeEntry("Dir_Check_All_Files", wid->chkbox->isChecked() );
}
diff --git a/noncore/graphics/opie-eye/impl/dir/dir_lister.cpp b/noncore/graphics/opie-eye/impl/dir/dir_lister.cpp
index ffea29e..0a5cff4 100644
--- a/noncore/graphics/opie-eye/impl/dir/dir_lister.cpp
+++ b/noncore/graphics/opie-eye/impl/dir/dir_lister.cpp
@@ -1,94 +1,96 @@
/*
* GPLv2 zecke@handhelds.org
*/
#include "dir_lister.h"
#include <lib/slavemaster.h>
-
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/config.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
+/* QT */
#include <qdir.h>
#include <qfileinfo.h>
-
Dir_DirLister::Dir_DirLister( bool list )
: PDirLister( "dir_dir_lister" )
{
m_allFiles = list;
- qWarning("All Files %d", m_allFiles );
+ owarn << "All Files " << m_allFiles << "" << oendl;
SlaveMaster* master = SlaveMaster::self();
connect( master, SIGNAL(sig_start()), this, SIGNAL(sig_start()) );
connect( master, SIGNAL(sig_end()), this, SIGNAL(sig_end()) );
connect( master, SIGNAL(sig_thumbInfo(const QString&, const QString&)),
this, SIGNAL(sig_thumbInfo(const QString&, const QString&)) );
connect( master, SIGNAL(sig_fullInfo(const QString&, const QString&)),
this, SIGNAL(sig_fullInfo(const QString&, const QString&)) );
connect( master, SIGNAL(sig_thumbNail(const QString&, const QPixmap&)),
this, SIGNAL(sig_thumbNail(const QString&, const QPixmap&)) );
}
QString Dir_DirLister::defaultPath()const {
return QPEApplication::documentDir();
}
QString Dir_DirLister::setStartPath( const QString& path ) {
m_currentDir.cd( path );
if (!m_currentDir.exists() )
m_currentDir.cd(defaultPath());
return m_currentDir.absPath();
}
QString Dir_DirLister::currentPath()const {
return m_currentDir.absPath();
}
QStringList Dir_DirLister::folders()const {
return m_currentDir.entryList( QDir::Dirs );
}
QStringList Dir_DirLister::files()const {
if ( m_allFiles )
return m_currentDir.entryList( QDir::Files );
else {
QStringList out;
QStringList list = m_currentDir.entryList( QDir::Files | QDir::Readable );
for (QStringList::Iterator it = list.begin(); it != list.end();++it ) {
QFileInfo inf( *it );
QString ext = inf.extension(false).lower();
if( ext == QString::fromLatin1("jpg") ||
ext == QString::fromLatin1("jpeg" ) ||
ext == QString::fromLatin1("png" ) ||
ext == QString::fromLatin1("gif" ) )
out.append( *it );
}
return out;
}
}
void Dir_DirLister::deleteImage( const QString& fl) {
QFile::remove( fl );
}
void Dir_DirLister::thumbNail( const QString& str, int w, int h) {
SlaveMaster::self()->thumbNail( str, w, h );
}
QImage Dir_DirLister::image( const QString& str, Factor f, int m) {
return SlaveMaster::self()->image( str, f, m );
}
void Dir_DirLister::imageInfo( const QString& str) {
SlaveMaster::self()->thumbInfo( str );
}
void Dir_DirLister::fullImageInfo( const QString& str) {
SlaveMaster::self()->imageInfo( str );
}
diff --git a/noncore/graphics/opie-eye/lib/slavemaster.cpp b/noncore/graphics/opie-eye/lib/slavemaster.cpp
index 4e28535..5bb7ab8 100644
--- a/noncore/graphics/opie-eye/lib/slavemaster.cpp
+++ b/noncore/graphics/opie-eye/lib/slavemaster.cpp
@@ -1,150 +1,154 @@
#include "slavemaster.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
#include <qpe/qcopenvelope_qws.h>
+using namespace Opie::Core;
+/* QT */
#include <qcopchannel_qws.h>
#include <qtimer.h>
QDataStream & operator << (QDataStream & str, bool b)
{
str << Q_INT8(b);
return str;
}
QDataStream & operator >> (QDataStream & str, bool & b)
{
Q_INT8 l;
str >> l;
b = bool(l);
return str;
}
/*
* ! We don't put a Pixmap in!!!!
*/
QDataStream &operator<<( QDataStream& s, const PixmapInfo& inf) {
- qWarning( "Image request is %s %d %d", inf.file.latin1(), inf.width, inf.height );
+ owarn << "Image request is " << inf.file.latin1() << " " << inf.width << " " << inf.height << "" << oendl;
return s << inf.file << inf.width << inf.height;
}
QDataStream &operator>>( QDataStream& s, PixmapInfo& inf ) {
s >> inf.file >> inf.pixmap >> inf.width >> inf.height;
return s;
}
QDataStream &operator<<( QDataStream& s, const ImageInfo& i) {
return s << i.kind << i.file << i.info;
}
QDataStream &operator>>( QDataStream& s, ImageInfo& i ) {
s >> i.kind >> i.file >> i.info;
return s;
}
SlaveMaster* SlaveMaster::m_master = 0;
SlaveMaster::SlaveMaster()
: m_started( false )
{
QCopChannel *chan= new QCopChannel( "QPE/opie-eye",this );
connect(chan, SIGNAL(received(const QCString&,const QByteArray&)),
this, SLOT(recieve(const QCString&,const QByteArray&)) );
}
SlaveMaster::~SlaveMaster() {
}
SlaveMaster* SlaveMaster::self() {
if ( !m_master )
m_master = new SlaveMaster;
return m_master;
}
void SlaveMaster::thumbInfo( const QString& str) {
m_inThumbInfo.append( str );
if ( !m_started ) {
QTimer::singleShot( 0, this, SLOT(slotTimerStart()));
m_started = true;
}
}
void SlaveMaster::imageInfo( const QString& str ) {
m_inImageInfo.append( str );
if ( !m_started ) {
QTimer::singleShot( 0, this, SLOT(slotTimerStart()));
m_started = true;
}
}
void SlaveMaster::thumbNail( const QString& str, int w, int h ) {
if ( str.isEmpty() ) {
- qWarning( "Asking for empty nail" );
+ owarn << "Asking for empty nail" << oendl;
return;
}
- qWarning( "Asking for thumbNail in size %d %d" + str, w,h );
+ owarn << "Asking for thumbNail in size " << w << " " << h << "" + str << oendl;
PixmapInfo item;
item.file = str; item.width = w; item.height = h;
item.pixmap = QPixmap();
m_inThumbNail.append( item );
if ( !m_started ) {
QTimer::singleShot( 0, this, SLOT(slotTimerStart()));
m_started = true;
}
}
void SlaveMaster::recieve( const QCString& str, const QByteArray& at) {
ImageInfos infos;
PixmapInfos pixinfos;
QDataStream stream( at, IO_ReadOnly );
if ( str == "pixmapsHandled(PixmapList)" )
stream >> pixinfos;
else if ( str == "pixmapsHandled(StringList)" )
stream >> infos;
- qWarning( "PixInfos %d", pixinfos.count() );
+ owarn << "PixInfos " << pixinfos.count() << "" << oendl;
bool got_data = ( !infos.isEmpty() || !pixinfos.isEmpty() );
if ( got_data ) {
emit sig_start();
for ( ImageInfos::Iterator _it = infos.begin(); _it != infos.end(); ++_it ) {
if ( (*_it).kind )
emit sig_fullInfo( (*_it).file, (*_it).info );
else
emit sig_thumbInfo( (*_it).file, (*_it).info );
}
for ( PixmapInfos::Iterator it = pixinfos.begin(); it != pixinfos.end(); ++it )
emit sig_thumbNail( (*it).file, (*it).pixmap );
emit sig_end();
}
}
void SlaveMaster::slotTimerStart() {
m_started = false;
if ( !m_inThumbInfo.isEmpty() ) {
QCopEnvelope env("QPE/opie-eye_slave", "thumbInfos(QStringList)" );
env << m_inThumbInfo;
}
if ( !m_inImageInfo.isEmpty() ) {
QCopEnvelope env("QPE/opie-eye_slave", "fullInfos(QStringList)" );
env << m_inImageInfo;
}
if ( !m_inThumbNail.isEmpty() ) {
QCopEnvelope env("QPE/opie-eye_slave", "pixmapInfos(PixmapInfos)" );
env << m_inThumbNail;
}
m_inThumbInfo.clear();
m_inImageInfo.clear();
m_inThumbNail.clear();
}
QImage SlaveMaster::image( const QString& str, PDirLister::Factor, int ) {
return QImage();
}
diff --git a/noncore/graphics/opie-eye/phunk_view.pro b/noncore/graphics/opie-eye/phunk_view.pro
index 17fa22c..0e2202a 100644
--- a/noncore/graphics/opie-eye/phunk_view.pro
+++ b/noncore/graphics/opie-eye/phunk_view.pro
@@ -1,36 +1,36 @@
CONFIG += qt warn_on quick-app
DESTDIR = $(OPIEDIR)/bin
TEMPLATE = app
TARGET = opie-eye
# the name of the resulting object
HEADERS = gui/iconview.h gui/filesystem.h gui/mainwindow.h \
lib/imagecache.h impl/dir/dir_dirview.h \
iface/dirview.h iface/dirlister.h iface/ifaceinfo.h \
impl/dir/dir_lister.h impl/dir/dir_ifaceinfo.h \
lib/slavemaster.h \
iface/slaveiface.h \
gui/imageinfoui.h
# A list header files
SOURCES = gui/iconview.cpp gui/filesystem.cpp gui/mainwindow.cpp \
lib/imagecache.cpp lib/viewmap.cpp \
impl/dir/dir_dirview.cpp iface/dirlister.cpp \
iface/dirview.cpp impl/dir/dir_lister.cpp \
impl/dir/dir_ifaceinfo.cpp lib/slavemaster.cpp \
gui/imageinfoui.cpp
# A list of source files
INTERFACES =
# list of ui files
INCLUDEPATH += . $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lopieui2
+LIBS += -lqpe -lopiecore2 -lopieui2
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/graphics/opie-eye/slave/jpeg_slave.cpp b/noncore/graphics/opie-eye/slave/jpeg_slave.cpp
index 086b47f..fb7d5de 100644
--- a/noncore/graphics/opie-eye/slave/jpeg_slave.cpp
+++ b/noncore/graphics/opie-eye/slave/jpeg_slave.cpp
@@ -1,426 +1,430 @@
#include "jpeg_slave.h"
-
#include "thumbnailtool.h"
PHUNK_VIEW_INTERFACE( "JPEG", JpegSlave )
-#include <qtopia/timestring.h>
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/timestring.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qobject.h>
#include <qimage.h>
/**
exif.h
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <qstring.h>
#include <qfile.h>
#include <qimage.h>
typedef enum {
READ_EXIF = 1,
READ_IMAGE = 2,
READ_ALL = 3
}ReadMode_t;
//--------------------------------------------------------------------------
// This structure is used to store jpeg file sections in memory.
typedef struct {
uchar * Data;
int Type;
unsigned Size;
}Section_t;
typedef unsigned char uchar;
typedef struct {
unsigned short Tag;
const char*const Desc;
}TagTable_t;
#define MAX_SECTIONS 20
#define PSEUDO_IMAGE_MARKER 0x123; // Extra value.
class ExifData {
Section_t Sections[MAX_SECTIONS];
QString CameraMake;
QString CameraModel;
QString DateTime;
int Orientation;
int Height, Width;
int ExifImageLength, ExifImageWidth;
int IsColor;
int Process;
int FlashUsed;
float FocalLength;
float ExposureTime;
float ApertureFNumber;
float Distance;
int Whitebalance;
int MeteringMode;
float CCDWidth;
float ExposureBias;
int ExposureProgram;
int ISOequivalent;
int CompressionLevel;
QString UserComment;
QString Comment;
QImage Thumbnail;
int ReadJpegSections (QFile & infile, ReadMode_t ReadMode);
void DiscardData(void);
int Get16u(void * Short);
int Get32s(void * Long);
unsigned Get32u(void * Long);
double ConvertAnyFormat(void * ValuePtr, int Format);
void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength);
void process_COM (const uchar * Data, int length);
void process_SOFn (const uchar * Data, int marker);
int Get16m(const void * Short);
void process_EXIF(unsigned char * CharBuf, unsigned int length);
int Exif2tm(struct tm * timeptr, char * ExifTime);
public:
ExifData();
bool scan(const QString &);
QString getCameraMake() { return CameraMake; }
QString getCameraModel() { return CameraModel; }
QString getDateTime() { return DateTime; }
int getOrientation() { return Orientation; }
int getHeight() { return Height; }
int getWidth() { return Width; }
int getIsColor() { return IsColor; }
int getProcess() { return Process; }
int getFlashUsed() { return FlashUsed; }
float getFocalLength() { return FocalLength; }
float getExposureTime() { return ExposureTime; }
float getApertureFNumber() { return ApertureFNumber; }
float getDistance() { return Distance; }
int getWhitebalance() { return Whitebalance; }
int getMeteringMode() { return MeteringMode; }
float getCCDWidth() { return CCDWidth; }
float getExposureBias() { return ExposureBias; }
int getExposureProgram() { return ExposureProgram; }
int getISOequivalent() { return ISOequivalent; }
int getCompressionLevel() { return CompressionLevel; }
QString getUserComment() { return UserComment; }
QString getComment() { return Comment; }
QImage getThumbnail();
bool isThumbnailSane();
bool isNullThumbnail() { return !isThumbnailSane(); }
};
class FatalError {
const char* ex;
public:
FatalError(const char* s) { ex = s; }
- void debug_print() const { qWarning("exception: %s", ex ); }
+ void debug_print() const { owarn << "exception: " << ex << "" << oendl; }
};
static unsigned char * LastExifRefd;
static int ExifSettingsLength;
static double FocalplaneXRes;
static double FocalplaneUnits;
static int MotorolaOrder = 0;
static int SectionsRead;
//static int HaveAll;
//--------------------------------------------------------------------------
// Table of Jpeg encoding process names
#define M_SOF0 0xC0 // Start Of Frame N
#define M_SOF1 0xC1 // N indicates which compression process
#define M_SOF2 0xC2 // Only SOF0-SOF2 are now in common use
#define M_SOF3 0xC3
#define M_SOF5 0xC5 // NB: codes C4 and CC are NOT SOF markers
#define M_SOF6 0xC6
#define M_SOF7 0xC7
#define M_SOF9 0xC9
#define M_SOF10 0xCA
#define M_SOF11 0xCB
#define M_SOF13 0xCD
#define M_SOF14 0xCE
#define M_SOF15 0xCF
#define M_SOI 0xD8 // Start Of Image (beginning of datastream)
#define M_EOI 0xD9 // End Of Image (end of datastream)
#define M_SOS 0xDA // Start Of Scan (begins compressed data)
#define M_JFIF 0xE0 // Jfif marker
#define M_EXIF 0xE1 // Exif marker
#define M_COM 0xFE // COMment
TagTable_t ProcessTable[] = {
{ M_SOF0, "Baseline"},
{ M_SOF1, "Extended sequential"},
{ M_SOF2, "Progressive"},
{ M_SOF3, "Lossless"},
{ M_SOF5, "Differential sequential"},
{ M_SOF6, "Differential progressive"},
{ M_SOF7, "Differential lossless"},
{ M_SOF9, "Extended sequential, arithmetic coding"},
{ M_SOF10, "Progressive, arithmetic coding"},
{ M_SOF11, "Lossless, arithmetic coding"},
{ M_SOF13, "Differential sequential, arithmetic coding"},
{ M_SOF14, "Differential progressive, arithmetic coding"},
{ M_SOF15, "Differential lossless, arithmetic coding"},
{ 0, "Unknown"}
};
//--------------------------------------------------------------------------
// Describes format descriptor
static int BytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8};
#define NUM_FORMATS 12
#define FMT_BYTE 1
#define FMT_STRING 2
#define FMT_USHORT 3
#define FMT_ULONG 4
#define FMT_URATIONAL 5
#define FMT_SBYTE 6
#define FMT_UNDEFINED 7
#define FMT_SSHORT 8
#define FMT_SLONG 9
#define FMT_SRATIONAL 10
#define FMT_SINGLE 11
#define FMT_DOUBLE 12
//--------------------------------------------------------------------------
// Describes tag values
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
#define TAG_MAKE 0x010F
#define TAG_MODEL 0x0110
#define TAG_ORIENTATION 0x0112
#define TAG_EXPOSURETIME 0x829A
#define TAG_FNUMBER 0x829D
#define TAG_SHUTTERSPEED 0x9201
#define TAG_APERTURE 0x9202
#define TAG_MAXAPERTURE 0x9205
#define TAG_FOCALLENGTH 0x920A
#define TAG_DATETIME_ORIGINAL 0x9003
#define TAG_USERCOMMENT 0x9286
#define TAG_SUBJECT_DISTANCE 0x9206
#define TAG_FLASH 0x9209
#define TAG_FOCALPLANEXRES 0xa20E
#define TAG_FOCALPLANEUNITS 0xa210
#define TAG_EXIF_IMAGEWIDTH 0xA002
#define TAG_EXIF_IMAGELENGTH 0xA003
// the following is added 05-jan-2001 vcs
#define TAG_EXPOSURE_BIAS 0x9204
#define TAG_WHITEBALANCE 0x9208
#define TAG_METERING_MODE 0x9207
#define TAG_EXPOSURE_PROGRAM 0x8822
#define TAG_ISO_EQUIVALENT 0x8827
#define TAG_COMPRESSION_LEVEL 0x9102
#define TAG_THUMBNAIL_OFFSET 0x0201
#define TAG_THUMBNAIL_LENGTH 0x0202
//--------------------------------------------------------------------------
// Parse the marker stream until SOS or EOI is seen;
//--------------------------------------------------------------------------
int ExifData::ReadJpegSections (QFile & infile, ReadMode_t ReadMode)
{
int a;
a = infile.getch();
if (a != 0xff || infile.getch() != M_SOI) {
SectionsRead = 0;
return false;
}
for(SectionsRead = 0; SectionsRead < MAX_SECTIONS-1; ){
int marker = 0;
int got;
unsigned int ll,lh;
unsigned int itemlen;
uchar * Data;
for (a=0;a<7;a++){
marker = infile.getch();
if (marker != 0xff) break;
if (a >= 6){
- qWarning( "too many padding bytes" );
+ owarn << "too many padding bytes" << oendl;
return false;
}
}
if (marker == 0xff){
// 0xff is legal padding, but if we get that many, something's wrong.
return false;
}
Sections[SectionsRead].Type = marker;
// Read the length of the section.
lh = (uchar) infile.getch();
ll = (uchar) infile.getch();
itemlen = (lh << 8) | ll;
if (itemlen < 2) {
return false;;
}
Sections[SectionsRead].Size = itemlen;
Data = (uchar *)malloc(itemlen+1); // Add 1 to allow sticking a 0 at the end.
Sections[SectionsRead].Data = Data;
// Store first two pre-read bytes.
Data[0] = (uchar)lh;
Data[1] = (uchar)ll;
got = infile.readBlock((char*)Data+2, itemlen-2); // Read the whole section.
if (( unsigned ) got != itemlen-2){
return false;
}
SectionsRead++;
switch(marker){
case M_SOS: // stop before hitting compressed data
// If reading entire image is requested, read the rest of the data.
if (ReadMode & READ_IMAGE){
unsigned long size;
size = QMAX( 0ul, infile.size()-infile.at() );
Data = (uchar *)malloc(size);
if (Data == NULL){
return false;
}
got = infile.readBlock((char*)Data, size);
if (( unsigned ) got != size){
return false;
}
Sections[SectionsRead].Data = Data;
Sections[SectionsRead].Size = size;
Sections[SectionsRead].Type = PSEUDO_IMAGE_MARKER;
SectionsRead ++;
//HaveAll = 1;
}
return true;
case M_EOI: // in case it's a tables-only JPEG stream
- qWarning( "No image in jpeg!" );
+ owarn << "No image in jpeg!" << oendl;
return false;
case M_COM: // Comment section
// pieczy 2002-02-12
// now the User comment goes to UserComment
// so we can store a Comment section also in READ_EXIF mode
process_COM(Data, itemlen);
break;
case M_JFIF:
// Regular jpegs always have this tag, exif images have the exif
// marker instead, althogh ACDsee will write images with both markers.
// this program will re-create this marker on absence of exif marker.
// hence no need to keep the copy from the file.
free(Sections[--SectionsRead].Data);
break;
case M_EXIF:
// Seen files from some 'U-lead' software with Vivitar scanner
// that uses marker 31 for non exif stuff. Thus make sure
// it says 'Exif' in the section before treating it as exif.
if ((ReadMode & READ_EXIF) && memcmp(Data+2, "Exif", 4) == 0){
process_EXIF((uchar *)Data, itemlen);
}else{
// Discard this section.
free(Sections[--SectionsRead].Data);
}
break;
case M_SOF0:
case M_SOF1:
case M_SOF2:
case M_SOF3:
case M_SOF5:
case M_SOF6:
case M_SOF7:
case M_SOF9:
case M_SOF10:
case M_SOF11:
case M_SOF13:
case M_SOF14:
case M_SOF15:
process_SOFn(Data, marker);
default:
break;
break;
}
}
return true;
}
//--------------------------------------------------------------------------
// Discard read data.
//--------------------------------------------------------------------------
void ExifData::DiscardData(void)
{
for (int a=0; a < SectionsRead; a++)
free(Sections[a].Data);
SectionsRead = 0;
}
//--------------------------------------------------------------------------
// Convert a 16 bit unsigned value from file's native byte order
//--------------------------------------------------------------------------
int ExifData::Get16u(void * Short)
{
if (MotorolaOrder){
return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1];
}else{
return (((uchar *)Short)[1] << 8) | ((uchar *)Short)[0];
}
}
//--------------------------------------------------------------------------
// Convert a 32 bit signed value from file's native byte order
//--------------------------------------------------------------------------
int ExifData::Get32s(void * Long)
{
if (MotorolaOrder){
return ((( char *)Long)[0] << 24) | (((uchar *)Long)[1] << 16)
| (((uchar *)Long)[2] << 8 ) | (((uchar *)Long)[3] << 0 );
}else{
return ((( char *)Long)[3] << 24) | (((uchar *)Long)[2] << 16)
| (((uchar *)Long)[1] << 8 ) | (((uchar *)Long)[0] << 0 );
}
}
//--------------------------------------------------------------------------
// Convert a 32 bit unsigned value from file's native byte order
//--------------------------------------------------------------------------
unsigned ExifData::Get32u(void * Long)
{
return (unsigned)Get32s(Long) & 0xffffffff;
}
@@ -633,380 +637,380 @@ void ExifData::ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBa
case TAG_EXIF_IMAGELENGTH:
ExifImageLength = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_EXIF_IMAGEWIDTH:
ExifImageWidth = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_FOCALPLANEXRES:
FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_FOCALPLANEUNITS:
switch((int)ConvertAnyFormat(ValuePtr, Format)){
case 1: FocalplaneUnits = 25.4; break; // inch
case 2:
// According to the information I was using, 2 means meters.
// But looking at the Cannon powershot's files, inches is the only
// sensible value.
FocalplaneUnits = 25.4;
break;
case 3: FocalplaneUnits = 10; break; // centimeter
case 4: FocalplaneUnits = 1; break; // milimeter
case 5: FocalplaneUnits = .001; break; // micrometer
}
break;
// Remaining cases contributed by: Volker C. Schoech (schoech@gmx.de)
case TAG_EXPOSURE_BIAS:
ExifData::ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_WHITEBALANCE:
ExifData::Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_METERING_MODE:
ExifData::MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_EXPOSURE_PROGRAM:
ExifData::ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_ISO_EQUIVALENT:
ExifData::ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
if ( ExifData::ISOequivalent < 50 ) ExifData::ISOequivalent *= 200;
break;
case TAG_COMPRESSION_LEVEL:
ExifData::CompressionLevel = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_THUMBNAIL_OFFSET:
ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_THUMBNAIL_LENGTH:
ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format);
break;
}
if (Tag == TAG_EXIF_OFFSET || Tag == TAG_INTEROP_OFFSET){
unsigned char * SubdirStart;
SubdirStart = OffsetBase + Get32u(ValuePtr);
if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
return;
}
ProcessExifDir(SubdirStart, OffsetBase, ExifLength);
continue;
}
}
{
// In addition to linking to subdirectories via exif tags,
// there's also a potential link to another directory at the end of each
// directory. this has got to be the result of a comitee!
unsigned char * SubdirStart;
unsigned Offset;
if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){
Offset = Get32u(DIR_ENTRY_ADDR(DirStart, NumDirEntries));
// There is at least one jpeg from an HP camera having an Offset of almost MAXUINT.
// Adding OffsetBase to it produces an overflow, so compare with ExifLength here.
// See http://bugs.kde.org/show_bug.cgi?id=54542
if (Offset && Offset < ExifLength){
SubdirStart = OffsetBase + Offset;
if (SubdirStart > OffsetBase+ExifLength){
if (SubdirStart < OffsetBase+ExifLength+20){
// Jhead 1.3 or earlier would crop the whole directory!
// As Jhead produces this form of format incorrectness,
// I'll just let it pass silently
- qWarning( "Thumbnail removed with Jhead 1.3 or earlier" );
+ owarn << "Thumbnail removed with Jhead 1.3 or earlier" << oendl;
}else{
return;
}
}else{
if (SubdirStart <= OffsetBase+ExifLength){
ProcessExifDir(SubdirStart, OffsetBase, ExifLength);
}
}
}
}else{
// The exif header ends before the last next directory pointer.
}
}
if (ThumbnailSize && ThumbnailOffset){
if (ThumbnailSize + ThumbnailOffset <= ExifLength){
// The thumbnail pointer appears to be valid. Store it.
Thumbnail.loadFromData(OffsetBase + ThumbnailOffset, ThumbnailSize, "JPEG");
}
}
}
//--------------------------------------------------------------------------
// Process a COM marker. We want to leave the bytes unchanged. The
// progam that displays this text may decide to remove blanks, convert
// newlines, or otherwise modify the text. In particular we want to be
// safe for passing utf-8 text.
//--------------------------------------------------------------------------
void ExifData::process_COM (const uchar * Data, int length)
{
QChar ch;
int a;
for (a=2;a<length;a++){
ch = Data[a];
if (ch == '\000') continue; // Remove nulls
Comment.append(ch);
}
}
//--------------------------------------------------------------------------
// Process a SOFn marker. This is useful for the image dimensions
//--------------------------------------------------------------------------
void ExifData::process_SOFn (const uchar * Data, int marker)
{
int data_precision, num_components;
data_precision = Data[2];
ExifData::Height = Get16m(Data+3);
ExifData::Width = Get16m(Data+5);
num_components = Data[7];
if (num_components == 3){
ExifData::IsColor = 1;
}else{
ExifData::IsColor = 0;
}
ExifData::Process = marker;
}
//--------------------------------------------------------------------------
// Get 16 bits motorola order (always) for jpeg header stuff.
//--------------------------------------------------------------------------
int ExifData::Get16m(const void * Short)
{
return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1];
}
//--------------------------------------------------------------------------
// Process a EXIF marker
// Describes all the drivel that most digital cameras include...
//--------------------------------------------------------------------------
void ExifData::process_EXIF(unsigned char * CharBuf, unsigned int length)
{
ExifData::FlashUsed = 0; // If it s from a digicam, and it used flash, it says so.
FocalplaneXRes = 0;
FocalplaneUnits = 0;
ExifImageWidth = 0;
ExifImageLength = 0;
{ // Check the EXIF header component
static const uchar ExifHeader[] = "Exif\0\0";
if (memcmp(CharBuf+2, ExifHeader,6)){
return;
}
}
if (memcmp(CharBuf+8,"II",2) == 0){
// printf("Exif section in Intel order\n");
MotorolaOrder = 0;
}else{
if (memcmp(CharBuf+8,"MM",2) == 0){
// printf("Exif section in Motorola order\n");
MotorolaOrder = 1;
}else{
return;
}
}
// Check the next two values for correctness.
if (Get16u(CharBuf+10) != 0x2a
|| Get32u(CharBuf+12) != 0x08){
return;
}
LastExifRefd = CharBuf;
// First directory starts 16 bytes in. Offsets start at 8 bytes in.
ProcessExifDir(CharBuf+16, CharBuf+8, length-6);
// This is how far the interesting (non thumbnail) part of the exif went.
ExifSettingsLength = LastExifRefd - CharBuf;
// Compute the CCD width, in milimeters.
if (FocalplaneXRes != 0){
ExifData::CCDWidth = (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes);
}
}
//--------------------------------------------------------------------------
// Convert exif time to Unix time structure
//--------------------------------------------------------------------------
int ExifData::Exif2tm(struct tm * timeptr, char * ExifTime)
{
int a;
timeptr->tm_wday = -1;
// Check for format: YYYY:MM:DD HH:MM:SS format.
a = sscanf(ExifTime, "%d:%d:%d %d:%d:%d",
&timeptr->tm_year, &timeptr->tm_mon, &timeptr->tm_mday,
&timeptr->tm_hour, &timeptr->tm_min, &timeptr->tm_sec);
if (a == 6){
timeptr->tm_isdst = -1;
timeptr->tm_mon -= 1; // Adjust for unix zero-based months
timeptr->tm_year -= 1900; // Adjust for year starting at 1900
return true; // worked.
}
return false; // Wasn't in Exif date format.
}
//--------------------------------------------------------------------------
// Contructor for initialising
//--------------------------------------------------------------------------
ExifData::ExifData()
{
ExifData::Whitebalance = -1;
ExifData::MeteringMode = -1;
ExifData::FlashUsed = -1;
Orientation = 0;
Height = 0;
Width = 0;
IsColor = 0;
Process = 0;
FocalLength = 0;
ExposureTime = 0;
ApertureFNumber = 0;
Distance = 0;
CCDWidth = 0;
ExposureBias = 0;
ExposureProgram = 0;
ISOequivalent = 0;
CompressionLevel = 0;
}
//--------------------------------------------------------------------------
// process a EXIF jpeg file
//--------------------------------------------------------------------------
bool ExifData::scan(const QString & path)
{
int ret;
QFile f(path);
f.open(IO_ReadOnly);
// Scan the JPEG headers.
ret = ReadJpegSections(f, READ_EXIF);
if (ret == false){
- qWarning( "Not JPEG file!" );
+ owarn << "Not JPEG file!" << oendl;
DiscardData();
f.close();
return false;
}
f.close();
DiscardData();
//now make the strings clean,
// for exmaple my Casio is a "QV-4000 "
CameraMake = CameraMake.stripWhiteSpace();
CameraModel = CameraModel.stripWhiteSpace();
UserComment = UserComment.stripWhiteSpace();
Comment = Comment.stripWhiteSpace();
return true;
}
//--------------------------------------------------------------------------
// Does the embedded thumbnail match the jpeg image?
//--------------------------------------------------------------------------
#ifndef JPEG_TOL
#define JPEG_TOL 0.02
#endif
bool ExifData::isThumbnailSane() {
if (Thumbnail.isNull()) return false;
// check whether thumbnail dimensions match the image
// not foolproof, but catches some altered images (jpegtran -rotate)
if (ExifImageLength != 0 && ExifImageLength != Height) return false;
if (ExifImageWidth != 0 && ExifImageWidth != Width) return false;
if (Thumbnail.width() == 0 || Thumbnail.height() == 0) return false;
if (Height == 0 || Width == 0) return false;
double d = (double)Height/Width*Thumbnail.width()/Thumbnail.height();
return (1-JPEG_TOL < d) && (d < 1+JPEG_TOL);
}
static QImage flip_image( const QImage& img );
static QImage rotate_90( const QImage& img );
static QImage rotate_180( const QImage& );
static QImage rotate_270( const QImage& );
//--------------------------------------------------------------------------
// return a thumbnail that respects the orientation flag
// only if it seems sane
//--------------------------------------------------------------------------
QImage ExifData::getThumbnail() {
if (!isThumbnailSane()) return NULL;
if (!Orientation || Orientation == 1) return Thumbnail;
// now fix orientation
QImage dest = Thumbnail;
switch (Orientation) { // notice intentional fallthroughs
case 2: dest = flip_image( dest ); break;
case 4: dest = flip_image( dest );
case 3: dest =rotate_180( dest ); break;
case 5: dest = flip_image( dest );
case 6: dest = rotate_90( dest ); break;
case 7: dest = flip_image( dest );
case 8: dest = rotate_270( dest ); break;
default: break; // should never happen
}
return dest;
}
/*
*
*/
static QImage flip_image( const QImage& img ) {
return img.mirror( TRUE, FALSE );
}
static QImage dest;
static int x, y;
static unsigned int *srcData, *destData; // we're not threaded anyway
static unsigned char *srcData8, *destData8; // 8 bit is char
static unsigned int *srcTable, *destTable; // destination table
static QImage rotate_90_8( const QImage &img ) {
dest.create(img.height(), img.width(), img.depth());
dest.setNumColors(img.numColors());
srcTable = (unsigned int *)img.colorTable();
destTable = (unsigned int *)dest.colorTable();
for ( x=0; x < img.numColors(); ++x )
destTable[x] = srcTable[x];
for ( y=0; y < img.height(); ++y ){
srcData8 = (unsigned char *)img.scanLine(y);
for ( x=0; x < img.width(); ++x ){
destData8 = (unsigned char *)dest.scanLine(x);
destData8[img.height()-y-1] = srcData8[x];
}
}
diff --git a/noncore/graphics/opie-eye/slave/main.cpp b/noncore/graphics/opie-eye/slave/main.cpp
index 37020e6..5b90483 100644
--- a/noncore/graphics/opie-eye/slave/main.cpp
+++ b/noncore/graphics/opie-eye/slave/main.cpp
@@ -1,59 +1,59 @@
/*
* GPLv2 Slave Main
*/
#include "gif_slave.h"
#include "png_slave.h"
#include "jpeg_slave.h"
#include "thumbnailtool.h"
#include "slavereciever.h"
#include <qpixmap.h>
#include <qcopchannel_qws.h>
#include <qtopia/qpeapplication.h>
int main( int argc, char* argv[] ) {
QPEApplication app( argc, argv );
SlaveReciever rec( 0 );
QCopChannel chan( "QPE/opie-eye_slave" );
QObject::connect(&chan,SIGNAL(received(const QCString&, const QByteArray&)),
&rec, SLOT(recieveAnswer(const QCString&,const QByteArray&)));
QObject::connect(qApp,SIGNAL(appMessage(const QCString&, const QByteArray&)),
&rec, SLOT(recieveAnswer(const QCString&,const QByteArray&)));
return app.exec();
}
#ifdef DEBUG_IT
int main( int argc, char* argv[] ) {
QString str = QString::fromLatin1(argv[2] );
QApplication app( argc, argv );
GifSlave slave;
- qWarning( str +" "+slave.iconViewName(str ) );
- qWarning( str+" "+slave.fullImageInfo( str ) );
+ owarn << str +" "+slave.iconViewName(str ) << oendl;
+ owarn << str+" "+slave.fullImageInfo( str ) << oendl;
PNGSlave pngslave;
- qWarning( str + " " + pngslave.iconViewName(str) );
- qWarning( str + " " + pngslave.fullImageInfo(str));
+ owarn << str + " " + pngslave.iconViewName(str) << oendl;
+ owarn << str + " " + pngslave.fullImageInfo(str) << oendl;
JpegSlave jpgslave;
- qWarning( str + " " + jpgslave.iconViewName(str ) );
- qWarning( str + " " + jpgslave.fullImageInfo( str ) );
+ owarn << str + " " + jpgslave.iconViewName(str ) << oendl;
+ owarn << str + " " + jpgslave.fullImageInfo( str ) << oendl;
//return app.exec();
QPixmap pix = ThumbNailTool::getThumb( str, 24, 24 );
if ( pix.isNull() ) {
- qWarning( "No Thumbnail" );
+ owarn << "No Thumbnail" << oendl;
pix = slave.pixmap(str, 24, 24);
}
if (!pix.isNull() ) {
- qWarning( "Saving Thumbnail" );
+ owarn << "Saving Thumbnail" << oendl;
ThumbNailTool::putThumb( str, pix, 24, 24 );
}
}
#endif
diff --git a/noncore/graphics/opie-eye/slave/slave.pro b/noncore/graphics/opie-eye/slave/slave.pro
index 3f42495..903d667 100644
--- a/noncore/graphics/opie-eye/slave/slave.pro
+++ b/noncore/graphics/opie-eye/slave/slave.pro
@@ -1,18 +1,18 @@
-CONFIG += qte
+CONFIG = qt
TEMPLATE = app
TARGET = opie-eye_slave
DESTDIR = $(OPIEDIR)/bin
HEADERS = gif_slave.h slaveiface.h slavereciever.h \
thumbnailtool.h png_slave.h jpeg_slave.h \
../iface/slaveiface.h
SOURCES = main.cpp gif_slave.cpp slavereciever.cpp \
slaveiface.cpp thumbnailtool.cpp png_slave.cpp \
jpeg_slave.cpp
INCLUDEPATH += $(OPIEDIR)/include ../
DEPENDSPATH += $(OPIEDIR)/include
-LIBS += -lqpe
+LIBS += -lqpe -lopiecore2
-include ( $(OPIEDIR)/include.pro ) \ No newline at end of file
+include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/graphics/opie-eye/slave/slavereciever.cpp b/noncore/graphics/opie-eye/slave/slavereciever.cpp
index bbbbb30..82b3d23 100644
--- a/noncore/graphics/opie-eye/slave/slavereciever.cpp
+++ b/noncore/graphics/opie-eye/slave/slavereciever.cpp
@@ -1,226 +1,230 @@
/*
* GPLv2 zecke@handhelds.org
*/
#include "slavereciever.h"
#include "slaveiface.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
+/* QT */
#include <qtimer.h>
static SlaveObjects* _slaveObj = 0;
QDataStream & operator << (QDataStream & str, bool b)
{
str << Q_INT8(b);
return str;
}
QDataStream & operator >> (QDataStream & str, bool & b)
{
Q_INT8 l;
str >> l;
b = bool(l);
return str;
}
QDataStream &operator<<( QDataStream& s, const PixmapInfo& inf) {
return s << inf.file << inf.pixmap << inf.width << inf.height;
}
/*
* GUI sends no QPIxmap!!!
*/
QDataStream &operator>>( QDataStream& s, PixmapInfo& inf ) {
s >> inf.file >> inf.width >> inf.height;
- qWarning( "Recieved %s %d %d", inf.file.latin1(), inf.width, inf.height );
+ owarn << "Recieved " << inf.file.latin1() << " " << inf.width << " " << inf.height << "" << oendl;
return s;
}
QDataStream &operator<<( QDataStream& s, const ImageInfo& i) {
return s << i.kind << i.file << i.info;
}
QDataStream &operator>>( QDataStream& s, ImageInfo& i ) {
s >> i.kind >> i.file >> i.info;
return s;
}
SlaveObjects* slaveObjects() {
if ( !_slaveObj )
_slaveObj = new SlaveObjects;
return _slaveObj;
}
SlaveReciever::SlaveReciever( QObject* par)
: QObject( par ), m_refs( 0 )
{
m_inf = new QTimer(this);
connect(m_inf,SIGNAL(timeout()),
this, SLOT(slotImageInfo()));
m_pix = new QTimer(this);
connect(m_pix,SIGNAL(timeout()),
this, SLOT(slotThumbNail()));
m_out = new QTimer(this);
connect(m_out,SIGNAL(timeout()),
this, SLOT(slotSend()));
SlaveObjects *obj = slaveObjects(); // won't be changed
SlaveMap::Iterator it;
SlaveMap* map = slaveMap(); // SlaveMap won't be changed during execution!!!
for(it = map->begin(); it != map->end(); ++it ) {
obj->insert( it.key(), (*it.data())() );
}
}
SlaveReciever::~SlaveReciever() {
}
void SlaveReciever::recieveAnswer( const QCString& string, const QByteArray& ar) {
- qWarning( "String is %s", string.data() );
+ owarn << "String is " << string.data() << "" << oendl;
QDataStream stream(ar, IO_ReadOnly );
QStringList lst;
static ImageInfo inf;
static PixmapInfo pix;
if ( string == "thumbInfo(QString)" ) {
stream >> inf.file;
m_inList.append(inf);
}else if ( string == "thumbInfos(QStringList)" ) {
stream >> lst;
for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) {
- qWarning( "Adding thumbinfo for file "+ *it );
+ owarn << "Adding thumbinfo for file "+ *it << oendl;
inf.file = (*it);
m_inList.append(inf);
}
}else if ( string == "fullInfo(QString)" ) {
inf.kind = true;
stream >> inf.file;
m_inList.append(inf);
}else if ( string == "fullInfos(QStringList)" ) {
stream >> lst;
for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) {
- qWarning( "Adding fullInfo for"+ *it );
+ owarn << "Adding fullInfo for"+ *it << oendl;
inf.file = (*it);
inf.kind = true;
m_inList.append(inf);
}
}else if ( string == "pixmapInfo(QString,int,int)" ) {
stream >> pix.file >> pix.width >> pix.height;
m_inPix.append(pix);
}else if ( string == "pixmapInfos(PixmapInfos)" ) {
PixmapList list;
stream >> list;
for(PixmapList::Iterator it = list.begin(); it != list.end(); ++it ) {
- qWarning( "Got %d %d " + (*it).file, (*it).width , (*it).height );
+ owarn << "Got " << (*it).width << " " << (*it).height << " " + (*it).file << oendl;
m_inPix.append(*it);
}
}else if ( string == "refUp()" ) {
m_refs++;
}else if ( string == "refDown()" ) {
m_refs--;
}
if (!m_inf->isActive() && !m_inList.isEmpty() )
m_inf->start(5);
if (!m_pix->isActive() && !m_inPix.isEmpty() )
m_pix->start(5);
if ( m_refs )
QPEApplication::setKeepRunning();
else
qApp->quit();
}
PixmapList SlaveReciever::outPix()const {
return m_outPix;
}
StringList SlaveReciever::outInf()const{
return m_outList;
}
void SlaveReciever::slotImageInfo() {
ImageInfo inf = m_inList.first();
m_inList.remove( inf );
static SlaveObjects::Iterator it;
static SlaveObjects* map = slaveObjects(); // SlaveMap won't be changed during execution!!!
for(it = map->begin(); it != map->end(); ++it ) {
if( (*it)->supports(inf.file ) ) {
/* full image info */
if (inf.kind )
inf.info = (*it)->fullImageInfo( inf.file );
else
inf.info = (*it)->iconViewName( inf.file );
m_outList.append( inf );
break;
}
}
if (m_inList.isEmpty() )
m_inf->stop();
if (!m_out->isActive() && !m_outList.isEmpty() )
m_out->start( 100 );
}
void SlaveReciever::slotThumbNail() {
PixmapInfo inf = m_inPix.first();
m_inPix.remove( inf );
static SlaveObjects::Iterator it;
static SlaveObjects* map = slaveObjects(); // SlaveMap won't be changed during execution!!!
for(it = map->begin(); it != map->end(); ++it ) {
SlaveInterface* iface = it.data();
if( iface->supports(inf.file ) ) {
/* pixmap */
- qWarning( "Asking for thumbNail in size %d %d for "+inf.file, inf.width, inf.height );
+ owarn << "Asking for thumbNail in size " << inf.width << " " << inf.height << " for "+inf.file << oendl;
inf.pixmap = iface->pixmap(inf.file, 64, 64);
m_outPix.append( inf );
break;
}
}
if(m_inPix.isEmpty() )
m_pix->stop();
if(!m_out->isActive() && !m_outPix.isEmpty() )
m_out->start(100);
}
void SlaveReciever::slotSend() {
m_out->stop();
- qWarning( "Sending %d %d", outPix().count(), outInf().count() );
+ owarn << "Sending " << outPix().count() << " " << outInf().count() << "" << oendl;
/* queue it and send */
/* if this ever gets a service introduce request queues
* so we can differinatate between different clients
*/
if (! m_outPix.isEmpty() ) {
QCopEnvelope answer("QPE/opie-eye", "pixmapsHandled(PixmapList)" );
answer << outPix();
for ( PixmapList::Iterator it = m_outPix.begin();it!=m_outPix.end();++it ) {
- qWarning( "Sending out %s %d %d", (*it).file.latin1(), (*it).width, (*it).height );
+ owarn << "Sending out " << (*it).file.latin1() << " " << (*it).width << " " << (*it).height << "" << oendl;
}
}
if ( !m_outList.isEmpty() ) {
QCopEnvelope answer("QPE/opie-eye", "pixmapsHandled(StringList)" );
answer << outInf();
for ( StringList::Iterator it = m_outList.begin();it!=m_outList.end();++it ) {
- qWarning( "Sending out2 " + (*it).file );
+ owarn << "Sending out2 " + (*it).file << oendl;
}
}
m_outList.clear();
m_outPix.clear();
}
diff --git a/noncore/graphics/opie-eye/slave/thumbnailtool.cpp b/noncore/graphics/opie-eye/slave/thumbnailtool.cpp
index a202457..d2e169c 100644
--- a/noncore/graphics/opie-eye/slave/thumbnailtool.cpp
+++ b/noncore/graphics/opie-eye/slave/thumbnailtool.cpp
@@ -1,61 +1,66 @@
#include "thumbnailtool.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qfileinfo.h>
#include <qdir.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qstring.h>
static bool makeThumbDir( const QFileInfo& inf, bool make = false) {
QDir dir( inf.dirPath()+ "/.opie-eye" );
if ( !dir.exists() )
if ( make )
return dir.mkdir(QString::null);
else
return false;
return true;
}
/*
* check if the Opie opie-eye dir exists
* check if a thumbnail exists
* load the thumbnail
* /foo/bar/imagefoo.gif
* check for a png in /foo/bar/.opie-eye/%dx%d-imagefoo.gif
*/
QPixmap ThumbNailTool::getThumb( const QString& path, int width, int height ) {
QFileInfo inf( path );
- qWarning( "Get Thumb" );
+ owarn << "Get Thumb" << oendl;
if ( !makeThumbDir( inf ) ) {
QPixmap pix;
return pix;
}
QString str = QString( "/.opie-eye/%1x%2-%3" ).arg( width ).arg( height ).arg( inf.fileName() );
- qWarning( inf.dirPath()+str );
+ owarn << inf.dirPath()+str << oendl;
return QPixmap( inf.dirPath()+str,"PNG" );
}
void ThumbNailTool::putThumb( const QString& path, const QPixmap& pix, int width, int height ) {
QFileInfo inf( path );
makeThumbDir( inf, true );
QString str = QString( "/.opie-eye/%1x%2-%3" ).arg( width ).arg( height ).arg( inf.fileName() );
- qWarning( inf.dirPath()+str );
+ owarn << inf.dirPath()+str << oendl;
pix.save( inf.dirPath()+str, "PNG" );
}
QPixmap ThumbNailTool::scaleImage( QImage& img, int w, int h ) {
double hs = (double)h / (double)img.height() ;
double ws = (double)w / (double)img.width() ;
double scaleFactor = (hs > ws) ? ws : hs;
int smoothW = (int)(scaleFactor * img.width());
int smoothH = (int)(scaleFactor * img.height());
QPixmap pixmap;
if ( img.width() <= w && img.height() <= h )
pixmap.convertFromImage( img );
else
pixmap.convertFromImage( img.smoothScale( smoothW, smoothH) );
return pixmap;
}
diff --git a/noncore/multimedia/opieplayer2/audiowidget.cpp b/noncore/multimedia/opieplayer2/audiowidget.cpp
index 28a42eb..36def67 100644
--- a/noncore/multimedia/opieplayer2/audiowidget.cpp
+++ b/noncore/multimedia/opieplayer2/audiowidget.cpp
@@ -40,286 +40,286 @@ using namespace Opie::Ui;
namespace
{
const int xo = -2; // movable x offset
const int yo = 22; // movable y offset
const MediaWidget::SkinButtonInfo skinInfo[] =
{
{ MediaWidget::Play, "play", MediaWidget::ToggleButton },
{ MediaWidget::Stop, "stop", MediaWidget::NormalButton },
{ MediaWidget::Next, "next", MediaWidget::NormalButton },
{ MediaWidget::Previous, "prev", MediaWidget::NormalButton },
{ MediaWidget::VolumeUp, "up", MediaWidget::NormalButton },
{ MediaWidget::VolumeDown, "down", MediaWidget::NormalButton },
{ MediaWidget::Loop, "loop", MediaWidget::ToggleButton },
{ MediaWidget::PlayList, "playlist", MediaWidget::NormalButton },
{ MediaWidget::Forward, "forward", MediaWidget::NormalButton },
{ MediaWidget::Back, "back", MediaWidget::NormalButton }
};
const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] );
void changeTextColor( QWidget * w) {
QPalette p = w->palette();
p.setBrush( QColorGroup::Background, QColor( 167, 212, 167 ) );
p.setBrush( QColorGroup::Base, QColor( 167, 212, 167 ) );
w->setPalette( p );
}
}
AudioWidget::AudioWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name) :
MediaWidget( playList, mediaPlayerState, parent, name ), songInfo( this ), slider( Qt::Horizontal, this ), time( this ),
audioSliderBeingMoved( false )
{
setCaption( tr("OpiePlayer") );
loadSkin();
connect( &mediaPlayerState, SIGNAL( loopingToggled(bool) ), this, SLOT( setLooping(bool) ) );
connect( &mediaPlayerState, SIGNAL( isSeekableToggled(bool) ), this, SLOT( setSeekable(bool) ) );
connect( this, SIGNAL( forwardClicked() ), this, SLOT( skipFor() ) );
connect( this, SIGNAL( backClicked() ), this, SLOT( skipBack() ) );
connect( this, SIGNAL( forwardReleased() ), this, SLOT( stopSkip() ) );
connect( this, SIGNAL( backReleased() ), this, SLOT( stopSkip() ) );
// Intialise state
setLength( mediaPlayerState.length() );
setPosition( mediaPlayerState.position() );
setLooping( mediaPlayerState.isFullscreen() );
// setPaused( mediaPlayerState->paused() );
setPlaying( mediaPlayerState.isPlaying() );
}
AudioWidget::~AudioWidget() {
// mediaPlayerState->setPlaying(false);
}
MediaWidget::GUIInfo AudioWidget::guiInfo()
{
return GUIInfo( QString::null /* infix */, ::skinInfo, ::buttonCount );
}
void AudioWidget::resizeEvent( QResizeEvent *e ) {
int h = height();
int w = width();
songInfo.setGeometry( QRect( 2, 2, w - 4, 20 ) );
slider.setFixedWidth( w - 110 );
slider.setGeometry( QRect( 15, h - 22, w - 90, 20 ) );
slider.setBackgroundOrigin( QWidget::ParentOrigin );
time.setGeometry( QRect( w - 85, h - 30, 70, 20 ) );
upperLeftOfButtonMask.rx() = ( w - buttonUpImage.width() ) / 2;
upperLeftOfButtonMask.ry() = (( h - buttonUpImage.height() ) / 2) - 10;
MediaWidget::resizeEvent( e );
}
void AudioWidget::sliderPressed() {
audioSliderBeingMoved = TRUE;
}
void AudioWidget::sliderReleased() {
audioSliderBeingMoved = FALSE;
if ( slider.width() == 0 )
return;
long val = long((double)slider.value() * mediaPlayerState.length() / slider.width());
mediaPlayerState.setPosition( val );
}
void AudioWidget::setPosition( long i ) {
- // qDebug("<<<<<<<<<<<<<<<<<<<<<<<<set position %d",i);
+ // odebug << "<<<<<<<<<<<<<<<<<<<<<<<<set position " << i << "" << oendl;
updateSlider( i, mediaPlayerState.length() );
}
void AudioWidget::setLength( long max ) {
updateSlider( mediaPlayerState.position(), max );
}
void AudioWidget::setDisplayType( MediaPlayerState::DisplayType mediaType ) {
if ( mediaType == MediaPlayerState::Audio ) {
// startTimer( 150 );
QPEApplication::showWidget( this );
return;
}
killTimers();
hide();
}
void AudioWidget::loadSkin()
{
loadDefaultSkin( guiInfo() );
songInfo.setFocusPolicy( QWidget::NoFocus );
// changeTextColor( &songInfo );
// songInfo.setBackgroundColor( QColor( 167, 212, 167 ));
// songInfo.setFrameStyle( QFrame::NoFrame);
songInfo.setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
// songInfo.setForegroundColor(Qt::white);
slider.setFixedHeight( 20 );
slider.setMinValue( 0 );
slider.setMaxValue( 1 );
slider.setFocusPolicy( QWidget::NoFocus );
slider.setBackgroundPixmap( backgroundPixmap );
// Config cofg("qpe");
// cofg.setGroup("Appearance");
// QColor backgroundcolor = QColor( cofg.readEntry( "Background", "#E5E1D5" ) );
time.setFocusPolicy( QWidget::NoFocus );
time.setAlignment( Qt::AlignCenter );
// time.setFrame(FALSE);
// changeTextColor( &time );
resizeEvent( 0 );
}
void AudioWidget::setSeekable( bool isSeekable ) {
if ( !isSeekable ) {
- qDebug("<<<<<<<<<<<<<<file is STREAMING>>>>>>>>>>>>>>>>>>>");
+ odebug << "<<<<<<<<<<<<<<file is STREAMING>>>>>>>>>>>>>>>>>>>" << oendl;
if( !slider.isHidden()) {
slider.hide();
}
disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
disconnect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
disconnect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
} else {
// this stops the slider from being moved, thus
// does not stop stream when it reaches the end
slider.show();
- qDebug( " CONNECT SET POSTION " );
+ odebug << " CONNECT SET POSTION " << oendl;
connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
connect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
connect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
}
}
static QString timeAsString( long length ) {
int minutes = length / 60;
int seconds = length % 60;
return QString("%1:%2%3").arg( minutes ).arg( seconds / 10 ).arg( seconds % 10 );
}
void AudioWidget::updateSlider( long i, long max ) {
time.setText( timeAsString( i ) + " / " + timeAsString( max ) );
// qDebug( timeAsString( i ) + " / " + timeAsString( max ) ) ;
if ( max == 0 ) {
return;
}
// Will flicker too much if we don't do this
// Scale to something reasonable
int width = slider.width();
int val = int((double)i * width / max);
if ( !audioSliderBeingMoved ) {
if ( slider.value() != val ) {
slider.setValue( val );
}
if ( slider.maxValue() != width ) {
slider.setMaxValue( width );
}
}
}
void AudioWidget::skipFor() {
skipDirection = +1;
startTimer( 50 );
mediaPlayerState.setPosition( mediaPlayerState.position() + 2 );
}
void AudioWidget::skipBack() {
skipDirection = -1;
startTimer( 50 );
mediaPlayerState.setPosition( mediaPlayerState.position() - 2 );
}
void AudioWidget::stopSkip() {
killTimers();
}
void AudioWidget::timerEvent( QTimerEvent * ) {
if ( skipDirection == +1 ) {
mediaPlayerState.setPosition( mediaPlayerState.position() + 2 );
} else if ( skipDirection == -1 ) {
mediaPlayerState.setPosition( mediaPlayerState.position() - 2 );
}
}
void AudioWidget::keyReleaseEvent( QKeyEvent *e) {
switch ( e->key() ) {
////////////////////////////// Zaurus keys
case Key_Home:
break;
case Key_F9: //activity
hide();
- // qDebug("Audio F9");
+ // odebug << "Audio F9" << oendl;
e->accept();
break;
case Key_F10: //contacts
break;
case Key_F11: //menu
mediaPlayerState.toggleBlank();
e->accept();
break;
case Key_F12: //home
break;
case Key_F13: //mail
mediaPlayerState.toggleBlank();
e->accept();
break;
case Key_Space: {
e->accept();
mediaPlayerState.togglePaused();
}
break;
case Key_Down:
// toggleButton(6);
emit lessClicked();
emit lessReleased();
// toggleButton(6);
e->accept();
break;
case Key_Up:
// toggleButton(5);
emit moreClicked();
emit moreReleased();
// toggleButton(5);
e->accept();
break;
case Key_Right:
// toggleButton(3);
mediaPlayerState.setNext();
// toggleButton(3);
e->accept();
break;
case Key_Left:
// toggleButton(4);
mediaPlayerState.setPrev();
// toggleButton(4);
e->accept();
break;
case Key_Escape: {
}
break;
};
}
diff --git a/noncore/multimedia/opieplayer2/lib.cpp b/noncore/multimedia/opieplayer2/lib.cpp
index a42b8e5..5c24dbe 100644
--- a/noncore/multimedia/opieplayer2/lib.cpp
+++ b/noncore/multimedia/opieplayer2/lib.cpp
@@ -13,420 +13,420 @@
.="- .-=="i,     .._ License as published by the Free Software
 - .   .-<_>     .<> Foundation; either version 2 of the License,
     ._= =}       : or (at your option) any later version.
    .%`+i>       _;_.
    .i_,=:_.      -<s. This program is distributed in the hope that
     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
    : ..    .:,     . . . without even the implied warranty of
    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
..}^=.=       =       ; Library General Public License for more
++=   -.     .`     .: details.
 :     =  ...= . :.=-
 -.   .:....=;==+<; You should have received a copy of the GNU
  -_. . .   )=.  = Library General Public License along with
    --        :-=` this library; see the file COPYING.LIB.
If not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qtextstream.h>
#include <qdir.h>
#include <qgfx_qws.h>
#include <assert.h>
#include "xinevideowidget.h"
#include "frame.h"
#include "lib.h"
typedef void (*display_xine_frame_t) (void *user_data, uint8_t* frame,
int width, int height,int bytes );
extern "C" {
xine_vo_driver_t* init_video_out_plugin( xine_t *xine, void* video, display_xine_frame_t, void * );
int null_is_showing_video( const xine_vo_driver_t* self );
void null_set_show_video( const xine_vo_driver_t* self, int show );
int null_is_fullscreen( const xine_vo_driver_t* self );
void null_set_fullscreen( const xine_vo_driver_t* self, int screen );
int null_is_scaling( const xine_vo_driver_t* self );
void null_set_scaling( const xine_vo_driver_t* self, int scale );
void null_set_gui_width( const xine_vo_driver_t* self, int width );
void null_set_gui_height( const xine_vo_driver_t* self, int height );
void null_set_mode( const xine_vo_driver_t* self, int depth, int rgb );
void null_set_videoGamma( const xine_vo_driver_t* self , int value );
void null_display_handler( const xine_vo_driver_t* self, display_xine_frame_t t, void* user_data );
void null_preload_decoders( xine_stream_t *stream );
}
using namespace XINE;
Lib::Lib( InitializationMode initMode, XineVideoWidget* widget )
{
m_initialized = false;
m_duringInitialization = false;
m_video = false;
m_wid = widget;
printf("Lib");
QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf";
// get the configuration
// not really OO, should be an extra class, later
if ( !QFile::exists(configPath) ) {
QFile f(configPath);
f.open(IO_WriteOnly);
QTextStream ts( &f );
ts << "misc.memcpy_method:glibc\n";
ts << "# uncomment if you experience double speed audio \n #audio.oss_sync_method:softsync\n";
ts << "codec.ffmpeg_pp_quality:3\n";
ts << "audio.num_buffers:50\n";
ts << "audio.size_buffers:4096\n";
ts << "video.num_buffers:20\n";
ts << "video.size_buffers:4096\n";
ts << "audio.out_num_audio_buf:16\n";
ts << "audio.out_size_audio_buf:8096\n";
ts << "audio.out_size_zero_buf:1024\n";
ts << "audio.passthrough_offset:0\n";
f.close();
}
if ( initMode == InitializeImmediately ) {
initialize();
m_initialized = true;
}
else
start();
}
void Lib::run()
{
- qDebug( "Lib::run() started" );
+ odebug << "Lib::run() started" << oendl;
initialize();
m_initialized = true;
- qDebug( "Lib::run() finished" );
+ odebug << "Lib::run() finished" << oendl;
}
void Lib::initialize()
{
m_duringInitialization = true;
m_xine = xine_new( );
QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf";
xine_config_load( m_xine, QFile::encodeName( configPath ) );
xine_init( m_xine );
// allocate oss for sound
// and fb for framebuffer
m_audioOutput = xine_open_audio_driver( m_xine, "oss", NULL );
m_videoOutput = ::init_video_out_plugin( m_xine, NULL, xine_display_frame, this );
//xine_open_video_driver( m_xine, NULL, XINE_VISUAL_TYPE_FB, NULL);
// null_display_handler( m_videoOutput, xine_display_frame, this );
m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput );
if (m_wid != 0 ) {
printf( "!0\n" );
setWidget( m_wid );
}
m_queue = xine_event_new_queue (m_stream);
xine_event_create_listener_thread (m_queue, xine_event_handler, this);
::null_preload_decoders( m_stream );
m_duringInitialization = false;
}
Lib::~Lib() {
assert( isRunning() == false );
assert( m_initialized );
// free( m_config );
xine_close( m_stream );
xine_event_dispose_queue( m_queue );
xine_dispose( m_stream );
xine_exit( m_xine );
/* FIXME either free or delete but valgrind bitches against both */
//free( m_videoOutput );
//delete m_audioOutput;
}
void Lib::resize ( const QSize &s ) {
assert( m_initialized || m_duringInitialization );
if ( s. width ( ) && s. height ( ) ) {
::null_set_gui_width( m_videoOutput, s. width() );
::null_set_gui_height( m_videoOutput, s. height() );
}
}
int Lib::majorVersion() {
int major, minor, sub;
xine_get_version ( &major, &minor, &sub );
return major;
}
int Lib::minorVersion() {
int major, minor, sub;
xine_get_version ( &major, &minor, &sub );
return minor;
}
int Lib::subVersion() {
int major, minor, sub;
xine_get_version ( &major, &minor, &sub );
return sub;
}
int Lib::play( const QString& fileName, int startPos, int start_time ) {
assert( m_initialized );
// FIXME actually a hack imho. Should not be needed to dispose the whole stream
// but without we get wrong media length reads from libxine for the second media
//xine_dispose ( m_stream );
QString str = fileName.stripWhiteSpace();
//m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput );
//m_queue = xine_event_new_queue (m_stream);
//xine_event_create_listener_thread (m_queue, xine_event_handler, this);
if ( !xine_open( m_stream, str.utf8().data() ) ) {
return 0;
}
return xine_play( m_stream, startPos, start_time);
}
void Lib::stop() {
assert( m_initialized );
- qDebug("<<<<<<<< STOP IN LIB TRIGGERED >>>>>>>");
+ odebug << "<<<<<<<< STOP IN LIB TRIGGERED >>>>>>>" << oendl;
xine_stop( m_stream );
}
void Lib::pause( bool toggle ) {
assert( m_initialized );
xine_set_param( m_stream, XINE_PARAM_SPEED, toggle ? XINE_SPEED_PAUSE : XINE_SPEED_NORMAL );
}
int Lib::speed() const {
assert( m_initialized );
return xine_get_param ( m_stream, XINE_PARAM_SPEED );
}
void Lib::setSpeed( int speed ) {
assert( m_initialized );
xine_set_param ( m_stream, XINE_PARAM_SPEED, speed );
}
int Lib::status() const {
assert( m_initialized );
return xine_get_status( m_stream );
}
int Lib::currentPosition() const {
assert( m_initialized );
int pos, time, length;
xine_get_pos_length( m_stream, &pos, &time, &length );
return pos;
}
int Lib::currentTime() const {
assert( m_initialized );
int pos, time, length;
xine_get_pos_length( m_stream, &pos, &time, &length );
if ( time > 0 ) {
return time/1000;
} else {
return 0;
}
}
int Lib::length() const {
assert( m_initialized );
int pos, time, length;
/* dilb: patch to solve the wrong stream length reported to the GUI*/
int iRetVal=0, iTestLoop=0;
do
{
iRetVal = xine_get_pos_length( m_stream, &pos, &time, &length );
if (iRetVal)
{/* if the function didn't return 0, then pos, time and length are valid.*/
return length/1000;
}
/*don't poll too much*/
usleep(100000);
iTestLoop++;
}
while ( iTestLoop < 10 ); /* if after 1s, we still don't have any
valid stream, then return -1 (this value could be used to make the stream
unseekable, but it should never occur!! Mr. Murphy ? :) ) */
return -1;
}
bool Lib::isSeekable() const {
assert( m_initialized );
return xine_get_stream_info( m_stream, XINE_STREAM_INFO_SEEKABLE );
}
void Lib::seekTo( int time ) {
assert( m_initialized );
//xine_trick_mode ( m_stream, XINE_TRICK_MODE_SEEK_TO_TIME, time ); NOT IMPLEMENTED YET IN XINE :_(
// since its now milliseconds we need *1000
xine_play( m_stream, 0, time*1000 );
}
Frame Lib::currentFrame() const {
assert( m_initialized );
Frame frame;
return frame;
};
QString Lib::metaInfo( int number) const {
assert( m_initialized );
return xine_get_meta_info( m_stream, number );
}
int Lib::error() const {
assert( m_initialized );
return xine_get_error( m_stream );
};
void Lib::ensureInitialized()
{
if ( m_initialized )
return;
- qDebug( "waiting for initialization thread to finish" );
+ odebug << "waiting for initialization thread to finish" << oendl;
wait();
- qDebug( "initialization thread finished!" );
+ odebug << "initialization thread finished!" << oendl;
}
void Lib::setWidget( XineVideoWidget *widget )
{
m_wid = widget;
resize ( m_wid-> size ( ) );
::null_set_mode( m_videoOutput, qt_screen->depth(), qt_screen->pixelType() );
m_wid->repaint();
}
void Lib::receiveMessage( ThreadUtil::ChannelMessage *msg, SendType sendType )
{
assert( sendType == ThreadUtil::Channel::OneWay );
handleXineEvent( msg->type() );
delete msg;
}
void Lib::handleXineEvent( const xine_event_t* t ) {
send( new ThreadUtil::ChannelMessage( t->type ), OneWay );
}
void Lib::handleXineEvent( int type ) {
assert( m_initialized );
if ( type == XINE_EVENT_UI_PLAYBACK_FINISHED ) {
emit stopped();
}
}
void Lib::setShowVideo( bool video ) {
assert( m_initialized );
m_video = video;
::null_set_show_video( m_videoOutput, video );
}
bool Lib::isShowingVideo() const {
assert( m_initialized );
return ::null_is_showing_video( m_videoOutput );
}
bool Lib::hasVideo() const {
assert( m_initialized );
return xine_get_stream_info( m_stream, 18 );
}
void Lib::showVideoFullScreen( bool fullScreen ) {
assert( m_initialized );
::null_set_fullscreen( m_videoOutput, fullScreen );
}
bool Lib::isVideoFullScreen() const {
assert( m_initialized );
return ::null_is_fullscreen( m_videoOutput );
}
void Lib::setScaling( bool scale ) {
assert( m_initialized );
::null_set_scaling( m_videoOutput, scale );
}
void Lib::setGamma( int value ) {
assert( m_initialized );
::null_set_videoGamma( m_videoOutput, value );
}
bool Lib::isScaling() const {
assert( m_initialized );
return ::null_is_scaling( m_videoOutput );
}
void Lib::xine_event_handler( void* user_data, const xine_event_t* t ) {
( (Lib*)user_data)->handleXineEvent( t );
}
void Lib::xine_display_frame( void* user_data, uint8_t *frame,
int width, int height, int bytes ) {
( (Lib*)user_data)->drawFrame( frame, width, height, bytes );
}
void Lib::drawFrame( uint8_t* frame, int width, int height, int bytes ) {
assert( m_initialized );
if ( !m_video ) {
- qWarning("not showing video now");
+ owarn << "not showing video now" << oendl;
return;
}
assert( m_wid );
m_wid-> setVideoFrame ( frame, width, height, bytes );
}
diff --git a/noncore/multimedia/opieplayer2/mediaplayer.cpp b/noncore/multimedia/opieplayer2/mediaplayer.cpp
index a236775..7e38fc7 100644
--- a/noncore/multimedia/opieplayer2/mediaplayer.cpp
+++ b/noncore/multimedia/opieplayer2/mediaplayer.cpp
@@ -59,343 +59,343 @@ MediaPlayer::~MediaPlayer() {
delete xine;
}
delete m_xineControl;
delete m_audioUI;
delete m_videoUI;
delete volControl;
}
void MediaPlayer::pauseCheck( bool b ) {
if ( b && !mediaPlayerState.isPlaying() ) {
mediaPlayerState.setPaused( FALSE );
}
}
void MediaPlayer::play() {
mediaPlayerState.setPlaying( FALSE );
mediaPlayerState.setPlaying( TRUE );
}
void MediaPlayer::setPlaying( bool play ) {
if ( !play ) {
return;
}
if ( mediaPlayerState.isPaused() ) {
mediaPlayerState.setPaused( FALSE );
return;
}
QString tickerText, time, fileName;
if ( playList.currentTab() != PlayListWidget::CurrentPlayList ) {
//if playing in file list.. play in a different way
// random and looping settings enabled causes problems here,
// since there is no selected file in the playlist, but a selected file in the file list,
// so we remember and shutoff
l = mediaPlayerState.isLooping();
if(l) {
mediaPlayerState.setLooping( false );
}
r = mediaPlayerState.isShuffled();
mediaPlayerState.setShuffled( false );
}
PlayListWidget::Entry playListEntry = playList.currentEntry();
fileName = playListEntry.name;
xineControl()->play( playListEntry.file );
long seconds = mediaPlayerState.length();
time.sprintf("%li:%02i", seconds/60, (int)seconds%60 );
if( fileName.left(4) == "http" ) {
fileName = QFileInfo( fileName ).baseName();
if ( xineControl()->getMetaInfo().isEmpty() ) {
tickerText = tr( " File: " ) + fileName;
} else {
tickerText = xineControl()->getMetaInfo();
}
} else {
if ( xineControl()->getMetaInfo().isEmpty() ) {
tickerText = tr( " File: " ) + fileName + tr( ", Length: " ) + time + " ";
} else {
tickerText = xineControl()->getMetaInfo() + " Length: " + time + " ";
}
}
audioUI()->setTickerText( tickerText );
}
void MediaPlayer::prev() {
if( playList.currentTab() == PlayListWidget::CurrentPlayList ) { //if using the playlist
if ( playList.prev() ) {
play();
} else if ( mediaPlayerState.isLooping() ) {
if ( playList.last() ) {
play();
}
} else {
mediaPlayerState.setList();
}
}
}
void MediaPlayer::next() {
if(playList.currentTab() == PlayListWidget::CurrentPlayList) { //if using the playlist
if ( playList.next() ) {
play();
} else if ( mediaPlayerState.isLooping() ) {
if ( playList.first() ) {
play();
}
} else {
mediaPlayerState.setList();
}
} else { //if playing from file list, let's just stop
- qDebug("<<<<<<<<<<<<<<<<<stop for filelists");
+ odebug << "<<<<<<<<<<<<<<<<<stop for filelists" << oendl;
mediaPlayerState.setPlaying(false);
mediaPlayerState.setDisplayType( MediaPlayerState::MediaSelection );
if(l) mediaPlayerState.setLooping(l);
if(r) mediaPlayerState.setShuffled(r);
}
qApp->processEvents();
}
void MediaPlayer::startDecreasingVolume() {
volumeDirection = -1;
startTimer( 100 );
volControl->decVol(2);
}
void MediaPlayer::startIncreasingVolume() {
volumeDirection = +1;
startTimer( 100 );
volControl->incVol(2);
}
bool drawnOnScreenDisplay = FALSE;
unsigned int onScreenDisplayVolume = 0;
const int yoff = 110;
void MediaPlayer::stopChangingVolume() {
killTimers();
// Get rid of the on-screen display stuff
drawnOnScreenDisplay = FALSE;
onScreenDisplayVolume = 0;
int w=0;
int h=0;
if( !xineControl()->hasVideo() ) {
w = audioUI()->width();
h = audioUI()->height();
audioUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE );
} else {
w = videoUI()->width();
h = videoUI()->height();
videoUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE );
}
}
void MediaPlayer::timerEvent( QTimerEvent * ) {
if ( volumeDirection == +1 ) {
volControl->incVol( 2 );
} else if ( volumeDirection == -1 ) {
volControl->decVol( 2 );
}
// TODO FIXME
// huh??
unsigned int v= 0;
v = volControl->volume();
v = v / 10;
if ( drawnOnScreenDisplay && onScreenDisplayVolume == v ) {
return;
}
int w=0; int h=0;
if( !xineControl()->hasVideo() ) {
w = audioUI()->width();
h = audioUI()->height();
if ( drawnOnScreenDisplay ) {
if ( onScreenDisplayVolume > v ) {
audioUI()->repaint( ( w - 200 ) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE );
}
}
drawnOnScreenDisplay = TRUE;
onScreenDisplayVolume = v;
QPainter p( audioUI() );
p.setPen( QColor( 0x10, 0xD0, 0x10 ) );
p.setBrush( QColor( 0x10, 0xD0, 0x10 ) );
QFont f;
f.setPixelSize( 20 );
f.setBold( TRUE );
p.setFont( f );
p.drawText( (w - 200) / 2, h - yoff + 20, tr("Volume") );
for ( unsigned int i = 0; i < 10; i++ ) {
if ( v > i ) {
p.drawRect( ( w - 200 ) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 );
} else {
p.drawRect( ( w - 200 ) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 );
}
}
} else {
w = videoUI()->width();
h = videoUI()->height();
if ( drawnOnScreenDisplay ) {
if ( onScreenDisplayVolume > v ) {
videoUI()->repaint( (w - 200) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE );
}
}
drawnOnScreenDisplay = TRUE;
onScreenDisplayVolume = v;
QPainter p( videoUI() );
p.setPen( QColor( 0x10, 0xD0, 0x10 ) );
p.setBrush( QColor( 0x10, 0xD0, 0x10 ) );
QFont f;
f.setPixelSize( 20 );
f.setBold( TRUE );
p.setFont( f );
p.drawText( (w - 200) / 2, h - yoff + 20, tr( "Volume" ) );
for ( unsigned int i = 0; i < 10; i++ ) {
if ( v > i ) {
p.drawRect( (w - 200) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 );
} else {
p.drawRect( (w - 200) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 );
}
}
}
}
void MediaPlayer::blank( bool b ) {
fd=open("/dev/fb0",O_RDWR);
#ifdef QT_QWS_SL5XXX
fl= open( "/dev/fl", O_RDWR );
#endif
if (fd != -1) {
if ( b ) {
- qDebug("do blanking");
+ odebug << "do blanking" << oendl;
#ifdef QT_QWS_SL5XXX
ioctl( fd, FBIOBLANK, 1 );
if(fl !=-1) {
ioctl( fl, 2 );
::close(fl);
}
#else
ioctl( fd, FBIOBLANK, 3 );
#endif
isBlanked = TRUE;
} else {
- qDebug("do unblanking");
+ odebug << "do unblanking" << oendl;
ioctl( fd, FBIOBLANK, 0);
#ifdef QT_QWS_SL5XXX
if(fl != -1) {
ioctl( fl, 1);
::close(fl);
}
#endif
isBlanked = FALSE;
}
close( fd );
} else {
- qDebug("<< /dev/fb0 could not be opened >>");
+ odebug << "<< /dev/fb0 could not be opened >>" << oendl;
}
}
void MediaPlayer::keyReleaseEvent( QKeyEvent *e) {
switch ( e->key() ) {
////////////////////////////// Zaurus keys
case Key_Home:
break;
case Key_F9: //activity
break;
case Key_F10: //contacts
break;
case Key_F11: //menu
break;
case Key_F12: //home
- qDebug("Blank here");
+ odebug << "Blank here" << oendl;
// mediaPlayerState->toggleBlank();
break;
case Key_F13: //mail
- qDebug("Blank here");
+ odebug << "Blank here" << oendl;
// mediaPlayerState->toggleBlank();
break;
}
}
void MediaPlayer::cleanUp() {// this happens on closing
Config cfg( "OpiePlayer" );
mediaPlayerState.writeConfig( cfg );
playList.writeDefaultPlaylist( );
// QPEApplication::grabKeyboard();
// QPEApplication::ungrabKeyboard();
}
void MediaPlayer::recreateAudioAndVideoWidgets() const
{
delete m_skinLoader;
delete m_xineControl;
delete m_audioUI;
delete m_videoUI;
m_audioUI = new AudioWidget( playList, mediaPlayerState, 0, "audioUI" );
m_videoUI = new VideoWidget( playList, mediaPlayerState, 0, "videoUI" );
connect( m_audioUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) );
connect( m_audioUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) );
connect( m_audioUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) );
connect( m_audioUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) );
connect( m_videoUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) );
connect( m_videoUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) );
connect( m_videoUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) );
connect( m_videoUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) );
if ( !xine )
xine = new XINE::Lib( XINE::Lib::InitializeImmediately );
m_xineControl = new XineControl( xine, m_videoUI->vidWidget(), mediaPlayerState );
xine = 0;
}
AudioWidget *MediaPlayer::audioUI() const
{
if ( !m_audioUI )
recreateAudioAndVideoWidgets();
return m_audioUI;
}
VideoWidget *MediaPlayer::videoUI() const
{
if ( !m_videoUI )
recreateAudioAndVideoWidgets();
return m_videoUI;
}
XineControl *MediaPlayer::xineControl() const
{
if ( !m_xineControl )
recreateAudioAndVideoWidgets();
return m_xineControl;
}
void MediaPlayer::reloadSkins()
{
audioUI()->loadSkin();
videoUI()->loadSkin();
}
diff --git a/noncore/multimedia/opieplayer2/om3u.cpp b/noncore/multimedia/opieplayer2/om3u.cpp
index 26d5e15..95dbab5 100644
--- a/noncore/multimedia/opieplayer2/om3u.cpp
+++ b/noncore/multimedia/opieplayer2/om3u.cpp
@@ -1,150 +1,150 @@
/*
                This file is part of the Opie Project
Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
=.
.=l.
           .>+-=
 _;:,     .>    :=|. This program is free software; you can
.> <`_,   >  .   <= redistribute it and/or modify it under
:`=1 )Y*s>-.--   : the terms of the GNU General Public
.="- .-=="i,     .._ License as published by the Free Software
 - .   .-<_>     .<> Foundation; either version 2 of the License,
     ._= =}       : or (at your option) any later version.
    .%`+i>       _;_.
    .i_,=:_.      -<s. This program is distributed in the hope that
     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
    : ..    .:,     . . . without even the implied warranty of
    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
..}^=.=       =       ; General Public License for more
++=   -.     .`     .: details.
 :     =  ...= . :.=-
 -.   .:....=;==+<; You should have received a copy of the GNU
  -_. . .   )=.  = General Public License along with
    --        :-=` this library; see the file COPYING.LIB.
If not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "om3u.h"
//extern PlayListWidget *playList;
Om3u::Om3u( const QString &filePath, int mode)
: QStringList (){
-qDebug("<<<<<<<new m3u "+filePath);
+odebug << "<<<<<<<new m3u "+filePath << oendl;
f.setName(filePath);
f.open(mode);
}
Om3u::~Om3u(){}
void Om3u::readM3u() {
-// qDebug("<<<<<<reading m3u "+f.name());
+// odebug << "<<<<<<reading m3u "+f.name() << oendl;
QTextStream t(&f);
t.setEncoding(QTextStream::UnicodeUTF8);
QString s;
while ( !t.atEnd() ) {
s=t.readLine();
-// qDebug(s);
+// odebug << s << oendl;
if( s.find( "#", 0, TRUE) == -1 ) {
if( s.left(2) == "E:" || s.left(2) == "P:" ) {
s = s.right( s.length() -2 );
QFileInfo f( s );
QString name = f.baseName();
name = name.right( name.length() - name.findRev( "\\", -1, TRUE ) -1 );
s=s.replace( QRegExp( "\\" ), "/" );
append(s);
-// qDebug(s);
+// odebug << s << oendl;
} else { // is url
QString name;
name = s;
append(name);
}
}
}
}
void Om3u::readPls() { //it's a pls file
QTextStream t( &f );
t.setEncoding(QTextStream::UnicodeUTF8);
QString s;
while ( !t.atEnd() ) {
s = t.readLine();
if( s.left(4) == "File" ) {
s = s.right( s.length() - s.find("=",0,true)-1 );
s = s.stripWhiteSpace();
s.replace( QRegExp( "%20" )," ");
-// qDebug( "adding " + s + " to playlist" );
+// odebug << "adding " + s + " to playlist" << oendl;
// numberofentries=2
// File1=http
// Title
// Length
// Version
// File2=http
s = s.replace( QRegExp( "\\" ), "/" );
QFileInfo f( s );
QString name = f.baseName();
if( name.left( 4 ) == "http" ) {
name = s.right( s.length() - 7);
} else {
name = s;
}
name = name.right( name.length() - name.findRev( "\\", -1, TRUE) - 1 );
if( s.at( s.length() - 4) == '.') // if this is probably a file
append(s);
else { //if its a url
// if( name.right( 1 ).find( '/' ) == -1) {
// s += "/";
// }
append(s);
}
}
}
}
void Om3u::write() { //writes list to m3u file
QString list;
QTextStream t(&f);
t.setEncoding(QTextStream::UnicodeUTF8);
if(count()>0) {
for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) {
-// qDebug(*it);
+// odebug << *it << oendl;
t << *it << "\n";
}
}
// f.close();
}
void Om3u::add(const QString &filePath) { //adds to m3u file
append(filePath);
}
void Om3u::remove(const QString &filePath) { //removes from m3u list
QString list, currentFile;
if(count()>0) {
for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) {
currentFile=*it;
- // qDebug(*it);
+ // odebug << *it << oendl;
if( filePath != currentFile)
list += currentFile+"\n";
}
f.writeBlock( list, list.length() );
}
}
void Om3u::deleteFile(const QString &/*filePath*/) {//deletes m3u file
f.close();
f.remove();
}
void Om3u::close() { //closes m3u file
f.close();
}
diff --git a/noncore/multimedia/opieplayer2/playlistselection.cpp b/noncore/multimedia/opieplayer2/playlistselection.cpp
index 015896f..3499837 100644
--- a/noncore/multimedia/opieplayer2/playlistselection.cpp
+++ b/noncore/multimedia/opieplayer2/playlistselection.cpp
@@ -1,206 +1,206 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include <qheader.h>
#include "playlistselection.h"
#include <stdlib.h>
class PlayListSelectionItem : public QListViewItem {
public:
PlayListSelectionItem( QListView *parent, const DocLnk *f ) : QListViewItem( parent ), fl( f ) {
setText( 0, f->name() );
setPixmap( 0, f->pixmap() );
}
~PlayListSelectionItem() {
};
const DocLnk *file() const { return fl; }
private:
const DocLnk *fl;
};
PlayListSelection::PlayListSelection( QWidget *parent, const char *name )
: QListView( parent, name )
{
-// qDebug("starting playlistselector");
+// odebug << "starting playlistselector" << oendl;
// #ifdef USE_PLAYLIST_BACKGROUND
// setStaticBackground( TRUE );
// setBackgroundPixmap( Resource::loadPixmap( "opieplayer/background" ) );
// setBackgroundPixmap( Resource::loadPixmap( "launcher/opielogo" ) );
// #endif
// addColumn("Title",236);
// setAllColumnsShowFocus( TRUE );
addColumn( tr( "Playlist Selection" ) );
header()->hide();
setSorting( -1, FALSE );
}
PlayListSelection::~PlayListSelection() {
}
// #ifdef USE_PLAYLIST_BACKGROUND
void PlayListSelection::drawBackground( QPainter *p, const QRect &r ) {
-// qDebug("drawBackground");
+// odebug << "drawBackground" << oendl;
p->fillRect( r, QBrush( white ) );
// QImage logo = Resource::loadImage( "launcher/opielogo" );
// if ( !logo.isNull() )
// p->drawImage( (width() - logo.width()) / 2, (height() - logo.height()) / 2, logo );
}
// #endif
void PlayListSelection::contentsMouseMoveEvent( QMouseEvent *event ) {
if ( event->state() == QMouseEvent::LeftButton ) {
QListViewItem *currentItem = selectedItem();
QListViewItem *itemUnder = itemAt( QPoint( event->pos().x(), event->pos().y() - contentsY() ) );
if ( currentItem && currentItem->itemAbove() == itemUnder )
moveSelectedUp();
else if ( currentItem && currentItem->itemBelow() == itemUnder )
moveSelectedDown();
}
}
const DocLnk *PlayListSelection::current() {
PlayListSelectionItem *item = (PlayListSelectionItem *)selectedItem();
if ( item )
return item->file();
return NULL;
}
void PlayListSelection::addToSelection( const DocLnk &lnk ) {
PlayListSelectionItem *item = new PlayListSelectionItem( this, new DocLnk( lnk ) );
QListViewItem *current = selectedItem();
if ( current )
item->moveItem( current );
setSelected( item, TRUE );
ensureItemVisible( selectedItem() );
}
void PlayListSelection::removeSelected() {
QListViewItem *item = selectedItem();
delete item;
setSelected( currentItem(), TRUE );
ensureItemVisible( selectedItem() );
}
void PlayListSelection::moveSelectedUp() {
QListViewItem *item = selectedItem();
if ( item && item->itemAbove() )
item->itemAbove()->moveItem( item );
ensureItemVisible( selectedItem() );
}
void PlayListSelection::moveSelectedDown() {
QListViewItem *item = selectedItem();
if ( item && item->itemBelow() )
item->moveItem( item->itemBelow() );
ensureItemVisible( selectedItem() );
}
bool PlayListSelection::prev() {
QListViewItem *item = selectedItem();
if ( item && item->itemAbove() )
setSelected( item->itemAbove(), TRUE );
else
return FALSE;
ensureItemVisible( selectedItem() );
return TRUE;
}
bool PlayListSelection::next() {
QListViewItem *item = selectedItem();
if ( item && item->itemBelow() )
setSelected( item->itemBelow(), TRUE );
else
return FALSE;
ensureItemVisible( selectedItem() );
return TRUE;
}
bool PlayListSelection::first() {
QListViewItem *item = firstChild();
if ( item )
setSelected( item, TRUE );
else
return FALSE;
ensureItemVisible( selectedItem() );
return TRUE;
}
bool PlayListSelection::last() {
QListViewItem *prevItem = NULL;
QListViewItem *item = firstChild();
while ( ( item = item->nextSibling() ) )
prevItem = item;
if ( prevItem )
setSelected( prevItem, TRUE );
else
return FALSE;
ensureItemVisible( selectedItem() );
return TRUE;
}
void PlayListSelection::unSelect()
{
//QListViewItem *item = selectedItem();
setSelected( currentItem(), FALSE);
}
void PlayListSelection::writeCurrent( Config& cfg ) {
cfg.setGroup("PlayList");
QListViewItem *item = selectedItem();
if ( item )
cfg.writeEntry("current", item->text(0) );
- qDebug(item->text(0));
+ odebug << item->text(0) << oendl;
}
void PlayListSelection::setSelectedItem(const QString &strk ) {
unSelect();
QListViewItemIterator it( this );
for ( ; it.current(); ++it ) {
-// qDebug( it.current()->text(0));
+// odebug << it.current()->text(0) << oendl;
if( strk == it.current()->text(0)) {
-// qDebug( "We have a match "+strk);
+// odebug << "We have a match "+strk << oendl;
setSelected( it.current(), TRUE);
ensureItemVisible( it.current() );
return;
}
}
// setSelected( item, TRUE );
// ensureItemVisible( selectedItem() );
}
diff --git a/noncore/multimedia/opieplayer2/playlistwidget.cpp b/noncore/multimedia/opieplayer2/playlistwidget.cpp
index 4460833..956d206 100644
--- a/noncore/multimedia/opieplayer2/playlistwidget.cpp
+++ b/noncore/multimedia/opieplayer2/playlistwidget.cpp
@@ -89,412 +89,412 @@ PlayListWidget::PlayListWidget(QWidget* parent, const char* name, WFlags fl )
audioView, SLOT( scanFiles() ) );
(void)new MenuItem( pmPlayList, tr( "Rescan for Video Files" ),
videoView, SLOT( scanFiles() ) );
pmView->insertItem( Resource::loadPixmap("fullscreen") , tr( "Full Screen"),
mediaPlayerState, SLOT( toggleFullscreen() ) );
Config cfg( "OpiePlayer" );
bool b= cfg.readBoolEntry("FullScreen", 0);
mediaPlayerState->setFullscreen( b );
pmView->setItemChecked( -16, b );
(void)new ToolButton( vbox1, tr( "Move Up" ), "opieplayer2/up",
d->selectedFiles, SLOT(moveSelectedUp() ) );
(void)new ToolButton( vbox1, tr( "Remove" ), "opieplayer2/cut",
d->selectedFiles, SLOT(removeSelected() ) );
(void)new ToolButton( vbox1, tr( "Move Down" ), "opieplayer2/down",
d->selectedFiles, SLOT(moveSelectedDown() ) );
QVBox *stretch2 = new QVBox( vbox1 );
connect( tbDeletePlaylist, ( SIGNAL( released() ) ),
SLOT( deletePlaylist() ) );
connect( pmView, SIGNAL( activated(int) ),
this, SLOT( pmViewActivated(int) ) );
connect( skinsMenu, SIGNAL( activated(int) ) ,
this, SLOT( skinsMenuActivated(int) ) );
connect( d->selectedFiles, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
this,SLOT( playlistViewPressed(int,QListViewItem*,const QPoint&,int) ) );
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*) ) );
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*) ) );
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( d->selectedFiles, SIGNAL( doubleClicked(QListViewItem*) ),
this, SLOT( playIt(QListViewItem*) ) );
connect ( gammaSlider, SIGNAL( valueChanged(int) ),
mediaPlayerState, SLOT( setVideoGamma(int) ) );
connect( this, SIGNAL(skinSelected() ),
m_mp, SLOT( reloadSkins() ) );
// see which skins are installed
populateSkinsMenu();
initializeStates();
channel = new QCopChannel( "QPE/Application/opieplayer2", this );
connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
this, SLOT( qcopReceive(const QCString&,const QByteArray&)) );
cfg.setGroup("PlayList");
QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default");
loadList(DocLnk( currentPlaylist ) );
tabWidget->showPage( playListTab );
}
PlayListWidget::~PlayListWidget() {
delete d;
delete m_mp;
}
void PlayListWidget::initializeStates() {
d->tbPlay->setOn( mediaPlayerState->isPlaying() );
d->tbLoop->setOn( mediaPlayerState->isLooping() );
d->tbShuffle->setOn( mediaPlayerState->isShuffled() );
d->playListFrame->show();
}
void PlayListWidget::writeDefaultPlaylist() {
Config config( "OpiePlayer" );
config.setGroup( "PlayList" );
QString filename=QPEApplication::documentDir() + "/default.m3u";
QString currentString = config.readEntry( "CurrentPlaylist", filename);
if( currentString == filename) {
Om3u *m3uList;
- // qDebug("<<<<<<<<<<<<<default>>>>>>>>>>>>>>>>>>>");
+ // odebug << "<<<<<<<<<<<<<default>>>>>>>>>>>>>>>>>>>" << oendl;
if( d->selectedFiles->first() ) {
m3uList = new Om3u(filename, IO_ReadWrite | IO_Truncate);
do {
- // qDebug(d->selectedFiles->current()->file());
+ // odebug << d->selectedFiles->current()->file() << oendl;
m3uList->add( d->selectedFiles->current()->file() );
}
while ( d->selectedFiles->next() );
m3uList->write();
m3uList->close();
delete m3uList;
}
}
}
void PlayListWidget::addToSelection( const DocLnk& lnk ) {
d->setDocumentUsed = FALSE;
if( QFileInfo( lnk.file() ).exists() ||
lnk.file().left(4) == "http" ) {
d->selectedFiles->addToSelection( lnk );
}
// writeCurrentM3u();
}
void PlayListWidget::clearList() {
while ( first() ) {
d->selectedFiles->removeSelected();
}
Config cfg( "OpiePlayer" );
cfg.setGroup("PlayList");
cfg.writeEntry("CurrentPlaylist","default");
setCaption("OpiePlayer");
}
void PlayListWidget::viewPressed( int mouse, QListViewItem *, const QPoint& , int) {
switch (mouse) {
case LeftButton:
break;
case RightButton:
{
QPopupMenu m;
m.insertItem( tr( "Play Selected" ), this, SLOT( playSelected() ));
m.insertItem( tr( "Add to Playlist" ), this, SLOT( addSelected() ));
m.exec( QCursor::pos() );
}
break;
}
}
void PlayListWidget::playlistViewPressed( int mouse, QListViewItem *, const QPoint& , int ) {
switch (mouse) {
case LeftButton:
break;
case RightButton:
{
QPopupMenu m;
m.insertItem( tr( "Play" ), this, SLOT( playSelected() ));
m.insertItem( tr( "Remove" ), this, SLOT( removeSelected() ));
m.exec( QCursor::pos() );
}
break;
}
}
void PlayListWidget::addAllToList() {
audioView->populateView();
QListViewItemIterator audioIt( audioView );
DocLnk lnk;
QString filename;
// iterate through all items of the listview
for ( ; audioIt.current(); ++audioIt ) {
filename = audioIt.current()->text(3);
lnk.setName( QFileInfo(filename).baseName() ); //sets name
lnk.setFile( filename ); //sets file name
d->selectedFiles->addToSelection( lnk);
}
videoView->populateView();
QListViewItemIterator videoIt( videoView );
for ( ; videoIt.current(); ++videoIt ) {
filename = videoIt.current()->text(3);
lnk.setName( QFileInfo(filename).baseName() ); //sets name
lnk.setFile( filename ); //sets file name
d->selectedFiles->addToSelection( lnk);
}
tabWidget->setCurrentPage(0);
writeCurrentM3u();
d->selectedFiles->first();
}
void PlayListWidget::addAllMusicToList() {
audioView->populateView();
QListViewItemIterator audioIt( audioView );
DocLnk lnk;
QString filename;
// iterate through all items of the listview
for ( ; audioIt.current(); ++audioIt ) {
filename = audioIt.current()->text(3);
lnk.setName( QFileInfo(filename).baseName() ); //sets name
lnk.setFile( filename ); //sets file name
d->selectedFiles->addToSelection( lnk);
}
tabWidget->setCurrentPage(0);
writeCurrentM3u();
d->selectedFiles->first();
}
void PlayListWidget::addAllVideoToList() {
videoView->populateView();
QListViewItemIterator videoIt( videoView );
DocLnk lnk;
QString filename;
for ( ; videoIt.current(); ++videoIt ) {
filename = videoIt.current()->text(3);
lnk.setName( QFileInfo(filename).baseName() ); //sets name
lnk.setFile( filename ); //sets file name
d->selectedFiles->addToSelection( lnk);
}
tabWidget->setCurrentPage(0);
writeCurrentM3u();
d->selectedFiles->first();
}
void PlayListWidget::setDocument( const QString& fileref ) {
- // qDebug( "<<<<<<<<set document>>>>>>>>>> "+fileref );
+ // odebug << "<<<<<<<<set document>>>>>>>>>> "+fileref << oendl;
fromSetDocument = TRUE;
QFileInfo fileInfo(fileref);
if ( !fileInfo.exists() ) {
QMessageBox::warning( this, tr( "Invalid File" ),
tr( "There was a problem in getting the file." ) );
return;
}
clearList();
QString extension = fileInfo.extension(false);
if( extension.find( "m3u", 0, false) != -1
|| extension.find( "pls", 0, false) != -1 ) {
readListFromFile( fileref );
} else {
clearList();
DocLnk lnk;
lnk.setName( fileInfo.baseName() ); //sets name
lnk.setFile( fileref ); //sets file name
addToSelection( lnk );
writeCurrentM3u();
d->setDocumentUsed = TRUE;
mediaPlayerState->setPlaying( FALSE );
mediaPlayerState->setPlaying( TRUE );
}
}
void PlayListWidget::useSelectedDocument() {
d->setDocumentUsed = FALSE;
}
const DocLnk *PlayListWidget::current() const { // this is fugly
assert( currentTab() == CurrentPlayList );
const DocLnk *lnk = d->selectedFiles->current();
if ( !lnk ) {
d->selectedFiles->first();
lnk = d->selectedFiles->current();
}
assert( lnk );
return lnk;
}
bool PlayListWidget::prev() {
if ( mediaPlayerState->isShuffled() ) {
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->isLooping() ) {
return d->selectedFiles->last();
} else {
return FALSE;
}
}
return TRUE;
}
}
bool PlayListWidget::next() {
-//qDebug("<<<<<<<<<<<<next()");
+//odebug << "<<<<<<<<<<<<next()" << oendl;
if ( mediaPlayerState->isShuffled() ) {
return prev();
} else {
if ( !d->selectedFiles->next() ) {
if ( mediaPlayerState->isLooping() ) {
return d->selectedFiles->first();
} else {
return FALSE;
}
}
return TRUE;
}
}
bool PlayListWidget::first() {
return d->selectedFiles->first();
}
bool PlayListWidget::last() {
return d->selectedFiles->last();
}
void PlayListWidget::saveList() {
writem3u();
}
void PlayListWidget::loadList( const DocLnk & lnk) {
QString name = lnk.name();
if( name.length()>0) {
setCaption("OpiePlayer: "+name);
clearList();
readListFromFile(lnk.file());
tabWidget->setCurrentPage(0);
}
}
void PlayListWidget::addSelected() {
assert( inFileListMode() );
QListViewItemIterator it( currentFileListView );
for ( ; it.current(); ++it )
if ( it.current()->isSelected() ) {
QString filename = it.current()->text(3);
DocLnk lnk;
lnk.setName( QFileInfo( filename ).baseName() ); //sets name
lnk.setFile( filename ); //sets file name
d->selectedFiles->addToSelection( lnk );
}
currentFileListView->clearSelection();
writeCurrentM3u();
}
void PlayListWidget::removeSelected() {
d->selectedFiles->removeSelected( );
writeCurrentM3u();
}
void PlayListWidget::playIt( QListViewItem *it) {
if(!it) return;
mediaPlayerState->setPlaying(FALSE);
mediaPlayerState->setPlaying(TRUE);
d->selectedFiles->unSelect();
}
void PlayListWidget::addToSelection( QListViewItem *it) {
d->setDocumentUsed = FALSE;
if(it) {
if ( currentTab() == CurrentPlayList )
return;
DocLnk lnk;
QString filename;
filename=it->text(3);
lnk.setName( QFileInfo(filename).baseName() ); //sets name
lnk.setFile( filename ); //sets file name
d->selectedFiles->addToSelection( lnk);
writeCurrentM3u();
// tabWidget->setCurrentPage(0);
}
}
@@ -519,525 +519,525 @@ void PlayListWidget::tabChanged(QWidget *) {
d->tbRemoveFromList->setEnabled(TRUE);
d->tbAddToList->setEnabled(FALSE);
d->tbPlay->setEnabled( !d->selectedFiles->isEmpty() );
}
break;
case AudioFiles:
{
audioView->populateView();
if( !tbDeletePlaylist->isHidden() ) {
tbDeletePlaylist->hide();
}
d->tbRemoveFromList->setEnabled(FALSE);
d->tbAddToList->setEnabled(TRUE);
connect( audioView, SIGNAL( itemsSelected(bool) ),
d->tbPlay, SLOT( setEnabled(bool) ) );
d->tbPlay->setEnabled( audioView->hasSelection() );
currentFileListView = audioView;
}
break;
case VideoFiles:
{
videoView->populateView();
if( !tbDeletePlaylist->isHidden() ) {
tbDeletePlaylist->hide();
}
d->tbRemoveFromList->setEnabled(FALSE);
d->tbAddToList->setEnabled(TRUE);
connect( videoView, SIGNAL( itemsSelected(bool) ),
d->tbPlay, SLOT( setEnabled(bool) ) );
d->tbPlay->setEnabled( videoView->hasSelection() );
currentFileListView = videoView;
}
break;
case PlayLists:
{
if( tbDeletePlaylist->isHidden() ) {
tbDeletePlaylist->show();
}
playLists->reread();
d->tbAddToList->setEnabled(FALSE);
d->tbPlay->setEnabled( false );
}
break;
};
}
void PlayListWidget::btnPlay(bool b) {
// mediaPlayerState->setPlaying(false);
mediaPlayerState->setPlaying(b);
insanityBool=FALSE;
}
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::playSelected() {
btnPlay( TRUE);
}
bool PlayListWidget::inFileListMode() const
{
TabType tab = currentTab();
return tab == AudioFiles || tab == VideoFiles;
}
void PlayListWidget::openURL() {
// http://66.28.164.33:2080
// http://somafm.com/star0242.m3u
QString filename, name;
InputDialog *fileDlg;
fileDlg = new InputDialog(this,tr("Add URL"),TRUE, 0);
fileDlg->exec();
if( fileDlg->result() == 1 ) {
filename = fileDlg->text();
- qDebug( "Selected filename is " + filename );
+ odebug << "Selected filename is " + filename << oendl;
// Om3u *m3uList;
DocLnk lnk;
Config cfg( "OpiePlayer" );
cfg.setGroup("PlayList");
if(filename.left(4) == "http") {
QString m3uFile, m3uFilePath;
if(filename.find(":",8,TRUE) != -1) { //found a port
m3uFile = filename.left( filename.find( ":",8,TRUE));
m3uFile = m3uFile.right( 7);
} else if(filename.left(4) == "http"){
m3uFile=filename;
m3uFile = m3uFile.right( m3uFile.length() - 7);
} else{
m3uFile=filename;
}
lnk.setName( filename ); //sets name
lnk.setFile( filename ); //sets file name
// lnk.setIcon("opieplayer2/musicfile");
d->selectedFiles->addToSelection( lnk );
writeCurrentM3u();
d->selectedFiles->setSelectedItem( lnk.name());
}
else if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) {
readListFromFile( filename );
} else {
lnk.setName( QFileInfo(filename).baseName() ); //sets name
lnk.setFile( filename ); //sets file name
d->selectedFiles->addToSelection( lnk);
writeCurrentM3u();
d->selectedFiles->setSelectedItem( lnk.name());
}
}
delete fileDlg;
}
void PlayListWidget::openFile() {
QString filename, name;
Config cfg( "OpiePlayer" );
cfg.setGroup("Dialog");
MimeTypes types;
QStringList audio, video, all;
audio << "audio/*";
audio << "playlist/plain";
audio << "audio/x-ogg";
audio << "audio/x-mpegurl";
video << "video/*";
video << "playlist/plain";
all += audio;
all += video;
types.insert("All Media Files", all );
types.insert("Audio", audio );
types.insert("Video", video );
QString str = OFileDialog::getOpenFileName( 1,
cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"",
types, 0 );
if(str.left(2) == "//") {
str=str.right(str.length()-1);
}
cfg.writeEntry( "LastDirectory" ,QFileInfo( str ).dirPath() );
if( !str.isEmpty() ) {
- qDebug( "Selected filename is " + str );
+ odebug << "Selected filename is " + str << oendl;
filename = str;
DocLnk lnk;
if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) {
readListFromFile( filename );
} else {
lnk.setName( QFileInfo(filename).baseName() ); //sets name
lnk.setFile( filename ); //sets file name
d->selectedFiles->addToSelection( lnk );
writeCurrentM3u();
d->selectedFiles->setSelectedItem( lnk.name() );
}
}
}
void PlayListWidget::readListFromFile( const QString &filename ) {
- qDebug( "read list filename " + filename );
+ odebug << "read list filename " + filename << oendl;
QFileInfo fi(filename);
Om3u *m3uList;
QString s, name;
m3uList = new Om3u( filename, IO_ReadOnly );
if(fi.extension(false).find("m3u",0,false) != -1 )
m3uList->readM3u();
else if(fi.extension(false).find("pls",0,false) != -1 )
m3uList->readPls();
DocLnk lnk;
for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) {
s = *it;
- // qDebug(s);
+ // odebug << s << oendl;
if(s.left(4)=="http") {
lnk.setName( s ); //sets file name
lnk.setIcon("opieplayer2/musicfile");
lnk.setFile( s ); //sets file name
} else { //is file
lnk.setName( QFileInfo(s).baseName());
if(s.left(1) != "/") {
lnk.setFile( QFileInfo(filename).dirPath()+"/"+s);
} else {
lnk.setFile( s);
}
}
d->selectedFiles->addToSelection( lnk );
}
Config config( "OpiePlayer" );
config.setGroup( "PlayList" );
config.writeEntry("CurrentPlaylist",filename);
config.write();
currentPlayList=filename;
m3uList->close();
delete m3uList;
d->selectedFiles->setSelectedItem( s);
setCaption(tr("OpiePlayer: ")+ QFileInfo(filename).baseName());
}
// writes current playlist to current m3u file */
void PlayListWidget::writeCurrentM3u() {
- qDebug("writing to current m3u");
+ odebug << "writing to current m3u" << oendl;
Config cfg( "OpiePlayer" );
cfg.setGroup("PlayList");
QString currentPlaylist = cfg.readEntry("CurrentPlaylist","default");
Om3u *m3uList;
m3uList = new Om3u( currentPlaylist, IO_ReadWrite | IO_Truncate );
if( d->selectedFiles->first()) {
do {
- // qDebug( "add writeCurrentM3u " +d->selectedFiles->current()->file());
+ // odebug << "add writeCurrentM3u " +d->selectedFiles->current()->file() << oendl;
m3uList->add( d->selectedFiles->current()->file() );
}
while ( d->selectedFiles->next() );
- // qDebug( "<<<<<<<<<<<<>>>>>>>>>>>>>>>>>" );
+ // odebug << "<<<<<<<<<<<<>>>>>>>>>>>>>>>>>" << oendl;
m3uList->write();
m3uList->close();
}
delete m3uList;
}
/*
writes current playlist to m3u file */
void PlayListWidget::writem3u() {
//InputDilog *fileDlg;
//fileDlg = new InputDialog( this, tr( "Save m3u Playlist " ), TRUE, 0);
//fileDlg->exec();
Config cfg( "OpiePlayer" );
cfg.setGroup("Dialog");
MimeTypes types;
QStringList audio, video, all;
audio << "audio/*";
audio << "playlist/plain";
audio << "audio/x-mpegurl";
video << "video/*";
video << "playlist/plain";
all += audio;
all += video;
types.insert("All Media Files", all );
types.insert("Audio", audio );
types.insert("Video", video );
QString str = OFileDialog::getOpenFileName( 1,
cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"",
types, 0 );
if(str.left(2) == "//") str=str.right(str.length()-1);
cfg.writeEntry("LastDirectory" ,QFileInfo(str).dirPath());
QString name, filename, list;
Om3u *m3uList;
if( !str.isEmpty() ) {
name = str;
// name = fileDlg->text();
-// qDebug( filename );
+// odebug << filename << oendl;
if( name.find("/",0,true) != -1) {// assume they specify a file path
filename = name;
name = name.right(name.length()- name.findRev("/",-1,true) - 1 );
}
else //otherwise dump it somewhere noticable
filename = QPEApplication::documentDir() + "/" + name;
if( filename.right( 3 ) != "m3u" ) //needs filename extension
filename += ".m3u";
if( d->selectedFiles->first()) { //ramble through playlist view
m3uList = new Om3u( filename, IO_ReadWrite | IO_Truncate);
do {
m3uList->add( d->selectedFiles->current()->file());
}
while ( d->selectedFiles->next() );
- // qDebug( list );
+ // odebug << list << oendl;
m3uList->write();
m3uList->close();
delete m3uList;
//delete fileDlg;
DocLnk lnk;
lnk.setFile( filename);
lnk.setIcon("opieplayer2/playlist2");
lnk.setName( name); //sets file name
- // qDebug(filename);
+ // odebug << filename << oendl;
Config config( "OpiePlayer" );
config.setGroup( "PlayList" );
config.writeEntry("CurrentPlaylist",filename);
currentPlayList=filename;
if(!lnk.writeLink()) {
- qDebug("Writing doclink did not work");
+ odebug << "Writing doclink did not work" << oendl;
}
setCaption(tr("OpiePlayer: ") + name);
}
}
}
void PlayListWidget::keyReleaseEvent( QKeyEvent *e ) {
switch ( e->key() ) {
////////////////////////////// Zaurus keys
case Key_F9: //activity
// if(audioUI->isHidden())
// audioUI->showMaximized();
break;
case Key_F10: //contacts
// if( videoUI->isHidden())
// videoUI->showMaximized();
break;
case Key_F11: //menu
break;
case Key_F12: //home
// doBlank();
break;
case Key_F13: //mail
// doUnblank();
break;
case Key_Q: //add to playlist
addSelected();
break;
case Key_R: //remove from playlist
removeSelected();
break;
// case Key_P: //play
- // qDebug("Play");
+ // odebug << "Play" << oendl;
// playSelected();
// break;
case Key_Space:
// playSelected(); puh
break;
case Key_1:
tabWidget->setCurrentPage( 0 );
break;
case Key_2:
tabWidget->setCurrentPage( 1 );
break;
case Key_3:
tabWidget->setCurrentPage( 2 );
break;
case Key_4:
tabWidget->setCurrentPage( 3 );
break;
case Key_Down:
if ( !d->selectedFiles->next() )
d->selectedFiles->first();
break;
case Key_Up:
if ( !d->selectedFiles->prev() )
// d->selectedFiles->last();
break;
}
}
void PlayListWidget::pmViewActivated(int index) {
-// qDebug("%d", index);
+// odebug << "" << index << "" << oendl;
switch(index) {
case -16:
{
mediaPlayerState->toggleFullscreen();
bool b=mediaPlayerState->isFullscreen();
pmView->setItemChecked( index, b);
Config cfg( "OpiePlayer" );
cfg.writeEntry( "FullScreen", b );
}
break;
};
}
void PlayListWidget::populateSkinsMenu() {
int item = 0;
defaultSkinIndex = 0;
QString skinName;
Config cfg( "OpiePlayer" );
cfg.setGroup("Options" );
QString skin = cfg.readEntry( "Skin", "default" );
QDir skinsDir( QPEApplication::qpeDir() + "/pics/opieplayer2/skins" );
skinsDir.setFilter( QDir::Dirs );
skinsDir.setSorting(QDir::Name );
const QFileInfoList *skinslist = skinsDir.entryInfoList();
QFileInfoListIterator it( *skinslist );
QFileInfo *fi;
while ( ( fi = it.current() ) ) {
skinName = fi->fileName();
-// qDebug( fi->fileName() );
+// odebug << fi->fileName() << oendl;
if( skinName != "." && skinName != ".." && skinName !="CVS" ) {
item = skinsMenu->insertItem( fi->fileName() ) ;
}
if( skinName == "default" ) {
defaultSkinIndex = item;
}
if( skinName == skin ) {
skinsMenu->setItemChecked( item, TRUE );
}
++it;
}
}
void PlayListWidget::skinsMenuActivated( int item ) {
for(unsigned int i = defaultSkinIndex; i > defaultSkinIndex - skinsMenu->count(); i-- ) {
skinsMenu->setItemChecked( i, FALSE );
}
skinsMenu->setItemChecked( item, TRUE );
{
Config cfg( "OpiePlayer" );
cfg.setGroup("Options");
cfg.writeEntry("Skin", skinsMenu->text( item ) );
}
emit skinSelected();
}
PlayListWidget::TabType PlayListWidget::currentTab() const
{
static const TabType indexToTabType[ TabTypeCount ] =
{ CurrentPlayList, AudioFiles, VideoFiles, PlayLists };
int index = tabWidget->currentPageIndex();
assert( index < TabTypeCount && index >= 0 );
return indexToTabType[ index ];
}
PlayListWidget::Entry PlayListWidget::currentEntry() const
{
if ( currentTab() == CurrentPlayList ) {
const DocLnk *lnk = current();
return Entry( lnk->name(), lnk->file() );
}
return Entry( currentFileListPathName() );
}
QString PlayListWidget::currentFileListPathName() const {
return currentFileListView->currentItem()->text( 3 );
}
void PlayListWidget::qcopReceive(const QCString &msg, const QByteArray &data) {
- qDebug("qcop message "+msg );
+ odebug << "qcop message "+msg << oendl;
QDataStream stream ( data, IO_ReadOnly );
if ( msg == "play()" ) { //plays current selection
btnPlay( true);
} else if ( msg == "stop()" ) {
mediaPlayerState->setPlaying( false);
} else if ( msg == "togglePause()" ) {
mediaPlayerState->togglePaused();
} else if ( msg == "next()" ) { //select next in list
mediaPlayerState->setNext();
} else if ( msg == "prev()" ) { //select previous in list
mediaPlayerState->setPrev();
} else if ( msg == "toggleLooping()" ) { //loop or not loop
mediaPlayerState->toggleLooping();
} else if ( msg == "toggleShuffled()" ) { //shuffled or not shuffled
mediaPlayerState->toggleShuffled();
} else if ( msg == "volUp()" ) { //volume more
// emit moreClicked();
// emit moreReleased();
} else if ( msg == "volDown()" ) { //volume less
// emit lessClicked();
// emit lessReleased();
} else if ( msg == "play(QString)" ) { //play this now
QString file;
stream >> file;
setDocument( (const QString &) file);
} else if ( msg == "add(QString)" ) { //add to playlist
QString file;
stream >> file;
QFileInfo fileInfo(file);
DocLnk lnk;
lnk.setName( fileInfo.baseName() ); //sets name
lnk.setFile( file ); //sets file name
addToSelection( lnk );
} else if ( msg == "rem(QString)" ) { //remove from playlist
QString file;
stream >> file;
}
}
diff --git a/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp b/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp
index 2ff190d..922f9d7 100644
--- a/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp
+++ b/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp
@@ -90,104 +90,104 @@ PlayListWidgetGui::PlayListWidgetGui(QWidget* parent, const char* name )
gammaSlider->setTickmarks( QSlider::Left );
gammaSlider->setTickInterval( 20 );
gammaSlider->setFocusPolicy( QWidget::StrongFocus );
gammaSlider->setValue( 0 );
gammaSlider->setMinimumHeight( 50 );
gammaLCD = new QLCDNumber( 3, gammaMenu );
gammaLCD-> setFrameShape ( QFrame::NoFrame );
gammaLCD-> setSegmentStyle ( QLCDNumber::Flat );
gammaMenu->insertItem( gammaSlider );
gammaMenu->insertItem( gammaLCD );
connect( gammaSlider, SIGNAL( valueChanged(int) ), gammaLCD, SLOT( display(int) ) );
vbox5 = new QVBox( this );
QVBox *vbox4 = new QVBox( vbox5 );
QHBox *hbox6 = new QHBox( vbox4 );
tabWidget = new QTabWidget( hbox6, "tabWidget" );
playListTab = new QWidget( tabWidget, "PlayListTab" );
tabWidget->insertTab( playListTab, "Playlist");
QGridLayout *Playout = new QGridLayout( playListTab );
Playout->setSpacing( 2);
Playout->setMargin( 2);
// Add the playlist area
QVBox *vbox3 = new QVBox( playListTab );
d->playListFrame = vbox3;
QHBox *hbox2 = new QHBox( vbox3 );
d->selectedFiles = new PlayListSelection( hbox2 );
vbox1 = new QVBox( hbox2 );
QPEApplication::setStylusOperation( d->selectedFiles->viewport(), QPEApplication::RightOnHold );
QVBox *stretch1 = new QVBox( vbox1 ); // add stretch
Playout->addMultiCellWidget( vbox3, 0, 0, 0, 1 );
QWidget *aTab;
aTab = new QWidget( tabWidget, "aTab" );
QGridLayout *Alayout = new QGridLayout( aTab );
Alayout->setSpacing( 2 );
Alayout->setMargin( 2 );
// no m3u's here please
audioView = new PlayListFileView( "audio/mpeg;audio/x-wav;application/ogg", "opieplayer2/musicfile", aTab, "Audioview" );
Alayout->addMultiCellWidget( audioView, 0, 0, 0, 1 );
tabWidget->insertTab( aTab, tr( "Audio" ) );
QPEApplication::setStylusOperation( audioView->viewport(), QPEApplication::RightOnHold );
QWidget *vTab;
vTab = new QWidget( tabWidget, "vTab" );
QGridLayout *Vlayout = new QGridLayout( vTab );
Vlayout->setSpacing( 2 );
Vlayout->setMargin( 2 );
videoView = new PlayListFileView( "video/*", "opieplayer2/videofile", vTab, "Videoview" );
Vlayout->addMultiCellWidget( videoView, 0, 0, 0, 1 );
QPEApplication::setStylusOperation( videoView->viewport(), QPEApplication::RightOnHold );
tabWidget->insertTab( vTab, tr( "Video" ) );
//playlists list
QWidget *LTab;
LTab = new QWidget( tabWidget, "LTab" );
QGridLayout *Llayout = new QGridLayout( LTab );
Llayout->setSpacing( 2 );
Llayout->setMargin( 2 );
playLists = new FileSelector( "playlist/plain;audio/x-mpegurl", LTab, "fileselector" , FALSE, FALSE );
Llayout->addMultiCellWidget( playLists, 0, 0, 0, 1 );
tabWidget->insertTab( LTab, tr( "Lists" ) );
setCentralWidget( vbox5 );
}
PlayListWidgetGui::~PlayListWidgetGui() {
}
void PlayListWidgetGui::setView( char view ) {
if ( view == 'l' )
showMaximized();
else
hide();
}
void PlayListWidgetGui::setActiveWindow() {
- // qDebug("SETTING active window");
+ // odebug << "SETTING active window" << oendl;
// When we get raised we need to ensure that it switches views
MediaPlayerState::DisplayType origDisplayType = mediaPlayerState->displayType();
mediaPlayerState->setDisplayType( MediaPlayerState::MediaSelection ); // invalidate
mediaPlayerState->setDisplayType( origDisplayType ); // now switch back
}
diff --git a/noncore/multimedia/opieplayer2/skin.cpp b/noncore/multimedia/opieplayer2/skin.cpp
index 7c38983..84f5f87 100644
--- a/noncore/multimedia/opieplayer2/skin.cpp
+++ b/noncore/multimedia/opieplayer2/skin.cpp
@@ -85,238 +85,238 @@ void Skin::init( const QString &name )
{
m_isCachable = true;
m_skinPath = "opieplayer2/skins/" + name;
d = SkinCache::self().lookupAndTake( m_skinPath, m_fileNameInfix );
}
QPixmap Skin::backgroundPixmap() const
{
if ( d->backgroundPixmap.isNull() )
d->backgroundPixmap = loadImage( QString( "%1/background" ).arg( m_skinPath ) );
return d->backgroundPixmap;
}
QImage Skin::buttonUpImage() const
{
if ( d->buttonUpImage.isNull() )
d->buttonUpImage = loadImage( QString( "%1/skin%2_up" ).arg( m_skinPath ).arg( m_fileNameInfix ) );
return d->buttonUpImage;
}
QImage Skin::buttonDownImage() const
{
if ( d->buttonDownImage.isNull() )
d->buttonDownImage = loadImage( QString( "%1/skin%2_down" ).arg( m_skinPath ).arg( m_fileNameInfix ) );
return d->buttonDownImage;
}
QImage Skin::buttonMask( const MediaWidget::SkinButtonInfo *skinButtonInfo, uint buttonCount ) const
{
if ( !d->buttonMask.isNull() )
return d->buttonMask;
QSize buttonAreaSize = buttonUpImage().size();
d->buttonMask = QImage( buttonAreaSize, 8, 255 );
d->buttonMask.fill( 0 );
for ( uint i = 0; i < buttonCount; ++i )
addButtonToMask( skinButtonInfo[ i ].command + 1, buttonMaskImage( skinButtonInfo[ i ].fileName ) );
return d->buttonMask;
}
void Skin::addButtonToMask( int tag, const QImage &maskImage ) const
{
if ( maskImage.isNull() )
return;
uchar **dest = d->buttonMask.jumpTable();
for ( int y = 0; y < d->buttonMask.height(); y++ ) {
uchar *line = dest[y];
for ( int x = 0; x < d->buttonMask.width(); x++ )
if ( !qRed( maskImage.pixel( x, y ) ) )
line[x] = tag;
}
}
QImage Skin::buttonMaskImage( const QString &fileName ) const
{
SkinData::ButtonMaskImageMap::Iterator it = d->buttonMasks.find( fileName );
if ( it == d->buttonMasks.end() ) {
QString prefix = m_skinPath + QString::fromLatin1( "/skin%1_mask_" ).arg( m_fileNameInfix );
QString path = prefix + fileName;
it = d->buttonMasks.insert( fileName, loadImage( path ) );
}
return *it;
}
QString Skin::defaultSkinName()
{
Config cfg( "OpiePlayer" );
cfg.setGroup( "Options" );
return cfg.readEntry( "Skin", "default" );
}
QImage Skin::loadImage( const QString &fileName )
{
return QImage( Resource::findPixmap( fileName ) );
}
SkinCache::SkinCache()
{
// let's say we cache two skins (audio+video) at maximum
m_cache.setMaxCost( 2 );
// ... and one background pixmap
m_backgroundPixmapCache.setMaxCost( 1 );
}
SkinData *SkinCache::lookupAndTake( const QString &skinPath, const QString &fileNameInfix )
{
QString key = skinPath + fileNameInfix;
SkinData *data = m_cache.take( key );
if ( !data )
data = new SkinData;
else
- qDebug( "SkinCache: hit" );
+ odebug << "SkinCache: hit" << oendl;
QPixmap *bgPixmap = m_backgroundPixmapCache.find( skinPath );
if ( bgPixmap ) {
- qDebug( "SkinCache: hit on bgpixmap" );
+ odebug << "SkinCache: hit on bgpixmap" << oendl;
data->backgroundPixmap = *bgPixmap;
}
else
data->backgroundPixmap = QPixmap();
return data;
}
void SkinCache::store( const QString &skinPath, const QString &fileNameInfix, SkinData *data )
{
QPixmap *backgroundPixmap = new QPixmap( data->backgroundPixmap );
data->backgroundPixmap = QPixmap();
QString key = skinPath + fileNameInfix;
if ( m_cache.find( key, false /*ref*/ ) != 0 ||
!m_cache.insert( key, data ) )
delete data;
if ( m_backgroundPixmapCache.find( skinPath, false /*ref*/ ) != 0 ||
!m_backgroundPixmapCache.insert( skinPath, backgroundPixmap ) )
delete backgroundPixmap;
}
SkinLoader::IncrementalLoader::IncrementalLoader( const Info &info )
: m_skin( info.skinName, info.fileNameInfix ), m_info( info )
{
m_currentState = LoadBackgroundPixmap;
}
SkinLoader::IncrementalLoader::LoaderResult SkinLoader::IncrementalLoader::loadStep()
{
switch ( m_currentState ) {
case LoadBackgroundPixmap:
- qDebug( "load bgpixmap" );
+ odebug << "load bgpixmap" << oendl;
m_skin.backgroundPixmap();
m_currentState = LoadButtonUpImage;
break;
case LoadButtonUpImage:
- qDebug( "load upimage" );
+ odebug << "load upimage" << oendl;
m_skin.buttonUpImage();
m_currentState = LoadButtonDownImage;
break;
case LoadButtonDownImage:
- qDebug( "load downimage" );
+ odebug << "load downimage" << oendl;
m_skin.buttonDownImage();
m_currentState = LoadButtonMasks;
m_currentButton = 0;
break;
case LoadButtonMasks:
- qDebug( "load button masks %i", m_currentButton );
+ odebug << "load button masks " << m_currentButton << "" << oendl;
m_skin.buttonMaskImage( m_info.buttonInfo[ m_currentButton ].fileName );
m_currentButton++;
if ( m_currentButton >= m_info.buttonCount )
m_currentState = LoadButtonMask;
break;
case LoadButtonMask:
- qDebug( "load whole mask" );
+ odebug << "load whole mask" << oendl;
m_skin.buttonMask( m_info.buttonInfo, m_info.buttonCount );
return LoadingCompleted;
}
return MoreToCome;
}
SkinLoader::SkinLoader()
: m_currentLoader( 0 ), m_timerId( -1 )
{
}
SkinLoader::~SkinLoader()
{
- qDebug( "SkinLoader::~SkinLoader()" );
+ odebug << "SkinLoader::~SkinLoader()" << oendl;
killTimers();
delete m_currentLoader;
}
void SkinLoader::schedule( const MediaWidget::GUIInfo &guiInfo )
{
schedule( Skin::defaultSkinName(), guiInfo );
}
void SkinLoader::schedule( const QString &skinName, const MediaWidget::GUIInfo &guiInfo )
{
pendingSkins << Info( skinName, guiInfo );
}
void SkinLoader::start()
{
assert( m_timerId == -1 );
m_timerId = startTimer( 100 /* ms */ );
- qDebug( "SkinLoader::start() %d jobs", pendingSkins.count() );
+ odebug << "SkinLoader::start() " << pendingSkins.count() << " jobs" << oendl;
}
void SkinLoader::timerEvent( QTimerEvent *ev )
{
if ( ev->timerId() != m_timerId ) {
QObject::timerEvent( ev );
return;
}
if ( !m_currentLoader ) {
if ( pendingSkins.isEmpty() ) {
- qDebug( "all jobs done" );
+ odebug << "all jobs done" << oendl;
killTimer( m_timerId );
m_timerId = -1;
// ### qt3: use deleteLater();
QTimer::singleShot( 0, this, SLOT( deleteMe() ) );
return;
}
Info nfo = *pendingSkins.begin();
pendingSkins.remove( pendingSkins.begin() );
m_currentLoader = new IncrementalLoader( nfo );
- qDebug( "new loader %i jobs left", pendingSkins.count() );
+ odebug << "new loader " << pendingSkins.count() << " jobs left" << oendl;
}
if ( m_currentLoader->loadStep() == IncrementalLoader::LoadingCompleted ) {
delete m_currentLoader;
m_currentLoader = 0;
}
- qDebug( "finished step" );
+ odebug << "finished step" << oendl;
}
void SkinLoader::deleteMe()
{
delete this;
}
/* vim: et sw=4 ts=4
*/
diff --git a/noncore/multimedia/opieplayer2/threadutil.cpp b/noncore/multimedia/opieplayer2/threadutil.cpp
index fb951b4..d8b8abe 100644
--- a/noncore/multimedia/opieplayer2/threadutil.cpp
+++ b/noncore/multimedia/opieplayer2/threadutil.cpp
@@ -94,290 +94,290 @@ struct WaitCondition::Data
WaitCondition::WaitCondition()
: d( new Data )
{
}
WaitCondition::~WaitCondition()
{
delete d;
}
bool WaitCondition::wait()
{
Mutex m;
m.lock();
return wait( m );
}
bool WaitCondition::wait( Mutex &mutex )
{
return pthread_cond_wait( &d->waitCondition, &mutex.d->mutex );
}
void WaitCondition::wakeOne()
{
pthread_cond_signal( &d->waitCondition );
}
void WaitCondition::wakeAll()
{
pthread_cond_broadcast( &d->waitCondition );
}
struct Thread::Data
{
Data() : isRunning( false )
{}
pthread_t self;
Mutex guard;
bool isRunning;
WaitCondition finishCondition;
Thread *thr;
void run() { thr->run(); }
};
extern "C"
{
static void terminate_thread( void *arg )
{
Thread::Data *data = ( Thread::Data* )arg;
assert( data );
AutoLock locker( data->guard );
data->isRunning = false;
data->finishCondition.wakeAll();
}
static void *start_thread( void *arg )
{
Thread::Data *data = ( Thread::Data* )arg;
pthread_cleanup_push( terminate_thread, data );
data->isRunning = true;
data->run();
pthread_cleanup_pop( true );
Thread::exit();
return 0; // never reached
}
}
Thread::Thread()
: d( new Data )
{
d->thr = this;
}
Thread::~Thread()
{
assert( d->isRunning == false );
delete d;
}
void Thread::start()
{
AutoLock lock( d->guard );
if ( d->isRunning ) {
- qDebug( "ThreadUtil::Thread::start() called for running thread." );
+ odebug << "ThreadUtil::Thread::start() called for running thread." << oendl;
return;
}
pthread_attr_t attributes;
pthread_attr_init( &attributes );
pthread_attr_setscope( &attributes, PTHREAD_SCOPE_SYSTEM );
int err = pthread_create( &d->self, &attributes, start_thread, ( void* )d );
if ( err != 0 ) {
- qDebug( "ThreadUtil::Thread::start() : can't create thread: %s", strerror( err ) );
+ odebug << "ThreadUtil::Thread::start() : can't create thread: " << strerror( err ) << "" << oendl;
pthread_attr_destroy( &attributes );
return;
}
pthread_attr_destroy( &attributes );
}
void Thread::terminate()
{
AutoLock lock( d->guard );
if ( !d->isRunning )
return;
pthread_cancel( d->self );
}
bool Thread::wait()
{
AutoLock lock( d->guard );
if ( !d->isRunning )
return true;
return d->finishCondition.wait( d->guard );
}
bool Thread::isRunning() const
{
AutoLock lock( d->guard );
return d->isRunning;
}
void Thread::exit()
{
pthread_exit( 0 );
}
OnewayNotifier::OnewayNotifier()
{
int fds[ 2 ];
pipe( fds );
m_readFd = fds[ 0 ];
m_writeFd = fds[ 1 ];
m_notifier = new QSocketNotifier( m_readFd, QSocketNotifier::Read );
connect( m_notifier, SIGNAL( activated(int) ),
this, SLOT( wakeUp() ) );
}
OnewayNotifier::~OnewayNotifier()
{
delete m_notifier;
::close( m_readFd );
::close( m_writeFd );
}
void OnewayNotifier::notify()
{
const char c = 42;
::write( m_writeFd, &c, 1 );
}
void OnewayNotifier::wakeUp()
{
char c = 0;
if ( ::read( m_readFd, &c, 1 ) != 1 )
return;
emit awake();
}
ChannelMessage::ChannelMessage( int type )
: m_type( type ), m_isCall( false ), m_replied( false ),
m_inEventHandler( false )
{
}
ChannelMessage::~ChannelMessage()
{
if ( m_guard.isLocked() )
m_guard.unlock();
}
void ChannelMessage::reply()
{
if ( !m_isCall )
{
- qDebug( "ChannelMessage::reply() - can't reply oneway message!" );
+ odebug << "ChannelMessage::reply() - can't reply oneway message!" << oendl;
return;
}
if ( m_inEventHandler )
{
m_replied = true;
return;
}
m_condition.wakeOne();
m_guard.unlock();
}
struct Channel::Private
{
Private()
{
ownerThread = pthread_self();
}
pthread_t ownerThread;
};
Channel::Channel( QObject *parent, const char *name )
: QObject( parent, name ), d( new Private )
{
connect( &m_notifier, SIGNAL( awake() ),
this, SLOT( deliver() ) );
}
Channel::~Channel()
{
delete d;
}
void Channel::send( ChannelMessage *message, SendType type )
{
if ( type == WaitForReply )
{
message->m_guard.lock();
message->m_isCall = true;
}
m_pendingMessagesGuard.lock();
m_pendingMessages << MsgEnvelope( type, message );
m_pendingMessagesGuard.unlock();
if ( d->ownerThread == pthread_self() ) {
assert( type != WaitForReply );
deliver();
}
else
m_notifier.notify();
//QThread::postEvent( this, new QCustomEvent( QEvent::User, envelope ) );
if ( type == WaitForReply )
{
message->m_condition.wait( message->m_guard );
message->m_guard.unlock();
}
}
void Channel::deliver()
{
AutoLock lock( m_pendingMessagesGuard );
while ( !m_pendingMessages.isEmpty() ) {
MsgEnvelope envelope = m_pendingMessages.first();
m_pendingMessages.remove( m_pendingMessages.begin() );
m_pendingMessagesGuard.unlock();
deliverOne( envelope );
m_pendingMessagesGuard.lock();
}
}
void Channel::deliverOne( const MsgEnvelope &envelope )
{
ChannelMessage *msg = envelope.msg;
assert( msg );
if ( envelope.type == WaitForReply )
{
msg->m_guard.lock();
msg->m_inEventHandler = true;
}
receiveMessage( msg, envelope.type );
if ( envelope.type == WaitForReply )
{
msg->m_inEventHandler = false;
if ( msg->m_replied )
diff --git a/noncore/multimedia/opieplayer2/xinecontrol.cpp b/noncore/multimedia/opieplayer2/xinecontrol.cpp
index 8f11b2e..94f99f8 100644
--- a/noncore/multimedia/opieplayer2/xinecontrol.cpp
+++ b/noncore/multimedia/opieplayer2/xinecontrol.cpp
@@ -1,271 +1,271 @@
/*
                This file is part of the Opie Project
              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org>
Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
Copyright (c) 2002 Holger Freyther <zecke@handhelds.org>
=.
.=l.
           .>+-=
 _;:,     .>    :=|. This program is free software; you can
.> <`_,   >  .   <= redistribute it and/or modify it under
:`=1 )Y*s>-.--   : the terms of the GNU General Public
.="- .-=="i,     .._ License as published by the Free Software
 - .   .-<_>     .<> Foundation; either version 2 of the License,
     ._= =}       : or (at your option) any later version.
    .%`+i>       _;_.
    .i_,=:_.      -<s. This program is distributed in the hope that
     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
    : ..    .:,     . . . without even the implied warranty of
    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
..}^=.=       =       ; General Public License for more
++=   -.     .`     .: details.
 :     =  ...= . :.=-
 -.   .:....=;==+<; You should have received a copy of the GNU
  -_. . .   )=.  = General Public License along with
    --        :-=` this library; see the file COPYING.LIB.
If not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qtimer.h>
#include <qmessagebox.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/qpeapplication.h>
#include "xinecontrol.h"
#include "xinevideowidget.h"
XineControl::XineControl( XineVideoWidget *xineWidget,
MediaPlayerState &_mediaPlayerState,
QObject *parent, const char *name )
: QObject( parent, name ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget )
{
libXine = new XINE::Lib( XINE::Lib::InitializeImmediately, xineWidget );
init();
}
XineControl::XineControl( XINE::Lib *xine, XineVideoWidget *xineWidget,
MediaPlayerState &_mediaPlayerState,
QObject *parent, const char *name )
: QObject( parent, name ), libXine( xine ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget )
{
xine->ensureInitialized();
xine->setWidget( xineWidget );
init();
}
void XineControl::init()
{
connect( &mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( pause(bool) ) );
connect( this, SIGNAL( positionChanged(long) ), &mediaPlayerState, SLOT( updatePosition(long) ) );
connect( &mediaPlayerState, SIGNAL( playingToggled(bool) ), this, SLOT( stop(bool) ) );
connect( &mediaPlayerState, SIGNAL( fullscreenToggled(bool) ), this, SLOT( setFullscreen(bool) ) );
connect( &mediaPlayerState, SIGNAL( positionChanged(long) ), this, SLOT( seekTo(long) ) );
connect( &mediaPlayerState, SIGNAL( videoGammaChanged(int) ), this, SLOT( setGamma(int) ) );
connect( libXine, SIGNAL( stopped() ), this, SLOT( nextMedia() ) );
connect( xineVideoWidget, SIGNAL( videoResized(const QSize&) ), this, SLOT( videoResized(const QSize&) ) );
disabledSuspendScreenSaver = FALSE;
}
XineControl::~XineControl() {
#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
if ( disabledSuspendScreenSaver ) {
disabledSuspendScreenSaver = FALSE;
// Re-enable the suspend mode
QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
}
#endif
delete libXine;
}
void XineControl::play( const QString& fileName ) {
hasVideoChannel = FALSE;
hasAudioChannel = FALSE;
m_fileName = fileName;
- qDebug("<<FILENAME: " + fileName + ">>>>");
+ odebug << "<<FILENAME: " + fileName + ">>>>" << oendl;
if ( !libXine->play( fileName, 0, 0 ) ) {
QMessageBox::warning( 0l , tr( "Failure" ), getErrorCode() );
// toggle stop so the the play button is reset
mediaPlayerState.setPlaying( false );
return;
}
mediaPlayerState.setPlaying( true );
MediaPlayerState::DisplayType displayType;
if ( !libXine->hasVideo() ) {
displayType = MediaPlayerState::Audio;
- qDebug("HAS AUDIO");
+ odebug << "HAS AUDIO" << oendl;
libXine->setShowVideo( false );
hasAudioChannel = TRUE;
} else {
displayType = MediaPlayerState::Video;
- qDebug("HAS VIDEO");
+ odebug << "HAS VIDEO" << oendl;
libXine->setShowVideo( true );
hasVideoChannel = TRUE;
}
// determine if slider is shown
mediaPlayerState.setIsSeekable( libXine->isSeekable() );
// which gui (video / audio)
mediaPlayerState.setDisplayType( displayType );
#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
if ( !disabledSuspendScreenSaver ) {
disabledSuspendScreenSaver = TRUE;
// Stop the screen from blanking and power saving state
QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" )
<< ( displayType == MediaPlayerState::Video ? QPEApplication::Disable : QPEApplication::DisableSuspend );
}
#endif
length();
position();
}
void XineControl::nextMedia() {
mediaPlayerState.setNext();
}
void XineControl::setGamma( int value ) {
libXine->setGamma( value );
}
void XineControl::stop( bool isSet ) {
if ( !isSet ) {
libXine->stop();
#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
if ( disabledSuspendScreenSaver ) {
disabledSuspendScreenSaver = FALSE;
// Re-enable the suspend mode
QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
}
#endif
}
}
/**
* Pause playback
* @isSet
*/
void XineControl::pause( bool isSet) {
libXine->pause( isSet );
}
/**
* get current time in playback
*/
long XineControl::currentTime() {
// todo: jede sekunde überprüfen
m_currentTime = libXine->currentTime();
return m_currentTime;
QTimer::singleShot( 1000, this, SLOT( currentTime() ) );
}
/**
* Set the length of the media file
*/
void XineControl::length() {
m_length = libXine->length();
mediaPlayerState.setLength( m_length );
}
/**
* Reports the position the xine backend is at right now
* @return long the postion in seconds
*/
long XineControl::position() {
m_position = ( currentTime() );
mediaPlayerState.updatePosition( m_position );
long emitPos = (long)m_position;
emit positionChanged( emitPos );
if( mediaPlayerState.isPlaying() ) {
// needs to be stopped the media is stopped
QTimer::singleShot( 1000, this, SLOT( position() ) );
}
return m_position;
}
/**
* Set videoplayback to fullscreen
* @param isSet
*/
void XineControl::setFullscreen( bool isSet ) {
libXine->showVideoFullScreen( isSet );
}
QString XineControl::getMetaInfo() {
QString returnString;
if ( !libXine->metaInfo( 0 ).isEmpty() ) {
returnString += tr( " Title: " + libXine->metaInfo( 0 ) );
}
if ( !libXine->metaInfo( 1 ).isEmpty() ) {
returnString += tr( " Comment: " + libXine->metaInfo( 1 ) );
}
if ( !libXine->metaInfo( 2 ).isEmpty() ) {
returnString += tr( " Artist: " + libXine->metaInfo( 2 ) );
}
if ( !libXine->metaInfo( 3 ).isEmpty() ) {
returnString += tr( " Genre: " + libXine->metaInfo( 3 ) );
}
if ( !libXine->metaInfo( 4 ).isEmpty() ) {
returnString += tr( " Album: " + libXine->metaInfo( 4 ) );
}
if ( !libXine->metaInfo( 5 ).isEmpty() ) {
returnString += tr( " Year: " + libXine->metaInfo( 5 ) );
}
return returnString;
}
QString XineControl::getErrorCode() {
int errorCode = libXine->error();
- qDebug( QString("ERRORCODE: %1 ").arg(errorCode) );
+ odebug << QString("ERRORCODE: %1 ").arg(errorCode) << oendl;
if ( errorCode == 1 ) {
return tr( "No input plugin found for this media type" );
} else if ( errorCode == 2 ) {
return tr( "No demux plugin found for this media type" );
} else if ( errorCode == 3 ) {
return tr( "Demuxing failed for this media type" );
} else if ( errorCode == 4 ) {
return tr( "Malformed MRL" );
} else {
return tr( "Some other error" );
}
}
/**
* Seek to a position in the track
* @param second the second to jump to
*/
void XineControl::seekTo( long second ) {
libXine->seekTo( (int)second );
}
void XineControl::videoResized ( const QSize &s ) {
libXine->resize( s );
}
diff --git a/noncore/multimedia/opierec/device.cpp b/noncore/multimedia/opierec/device.cpp
index ce49e96..5319d97 100644
--- a/noncore/multimedia/opierec/device.cpp
+++ b/noncore/multimedia/opierec/device.cpp
@@ -1,358 +1,358 @@
// device.cpp
#include "device.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/config.h>
#include <qpe/qcopenvelope_qws.h>
+using namespace Opie::Core;
-
+/* STD */
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
#include <unistd.h>
-#include<sys/wait.h>
-// #include <sys/stat.h>
-// #include <sys/time.h>
-// #include <sys/types.h>
+#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
//extern QtRec *qperec;
Device::Device( QObject * parent, const char * dsp, const char * mixr, bool record )
: QObject( parent)
{
dspstr = (char *)dsp;
mixstr = (char *)mixr;
devForm=-1;
devCh=-1;
devRate=-1;
if( !record){ //playing
- qDebug("setting up DSP for playing");
+ odebug << "setting up DSP for playing" << oendl;
flags = O_WRONLY;
} else { //recording
- qDebug("setting up DSP for recording");
+ odebug << "setting up DSP for recording" << oendl;
flags = O_RDWR;
// flags = O_RDONLY;
// selectMicInput();
}
}
bool Device::openDsp() {
if( openDevice( flags) == -1) {
perror("<<<<<<<<<<<<<<ioctl(\"Open device\")");
return false;
}
return true;
}
int Device::getOutVolume( ) {
unsigned int volume;
int mixerHandle = open( mixstr, O_RDWR );
if ( mixerHandle >= 0 ) {
if(ioctl( mixerHandle, MIXER_READ(SOUND_MIXER_VOLUME), &volume )==-1)
perror("<<<<<<<<<<<<<<ioctl(\"MIXER_READ\")");
::close( mixerHandle );
} else
perror("open(\"/dev/mixer\")");
printf("<<<<<<<<<<<<<<<<<<<<output volume %d\n",volume);
Config cfg("qpe");
cfg.setGroup("Volume");
return cfg.readNumEntry("VolumePercent");
}
int Device::getInVolume() {
unsigned int volume=0;
int mixerHandle = ::open( mixstr, O_RDWR );
if ( mixerHandle >= 0 ) {
if(ioctl( mixerHandle, MIXER_READ(SOUND_MIXER_MIC), &volume )==-1)
perror("<<<<<<<<<<<<<<<ioctl(\"MIXER_READ\")");
::close( mixerHandle );
} else
perror("open(\"/dev/mixer\")");
printf("<<<<<<<<<<<<<<input volume %d\n", volume );
Config cfg("qpe");
cfg.setGroup("Volume");
return cfg.readNumEntry("Mic");
}
void Device::changedOutVolume(int vol) {
int level = (vol << 8) + vol;
int fd = 0;
if ((fd = open("/dev/mixer", O_RDWR))>=0) {
if(ioctl(fd, MIXER_WRITE(SOUND_MIXER_VOLUME), &level) == -1)
perror("ioctl(\"MIXER_IN_WRITE\")");
Config cfg("qpe");
cfg.setGroup("Volume");
cfg.writeEntry("VolumePercent", QString::number( vol ));
QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << false;
- qWarning("changing output vol %d", vol);
+ owarn << "changing output vol " << vol << "" << oendl;
}
::close(fd);
}
void Device::changedInVolume(int vol ) {
int level = (vol << 8) + vol;
int fd = 0;
if ((fd = open("/dev/mixer", O_RDWR))>=0) {
if(ioctl(fd, MIXER_WRITE(SOUND_MIXER_MIC), &level) == -1)
perror("ioctl(\"MIXER_IN_WRITE\")");
Config cfg("qpe");
cfg.setGroup("Volume");
cfg.writeEntry("Mic", QString::number(vol ));
QCopEnvelope( "QPE/System", "micChange(bool)" ) << false;
- qWarning("changing input volume %d", vol);
+ owarn << "changing input volume " << vol << "" << oendl;
}
::close(fd);
}
bool Device::selectMicInput() {
int md=0;
int info=MIXER_WRITE(SOUND_MIXER_MIC);
md = ::open( "/dev/mixer", O_RDWR );
if ( md == -1)
perror("open(\"/dev/mixer\")");
else {
if( ioctl( md, SOUND_MIXER_WRITE_RECSRC, &info) == -1)
perror("ioctl(\"SOUND_MIXER_WRITE_RECSRC\")");
::close(md);
return false;
}
::close(md);
return true;
}
int Device::openDevice( int flags) {
/* pid_t pid;
int status;
int pipefd[2];
char message[20];
if (pipe(pipefd) == -1){
perror ("Error creating pipe");
exit(1);
}
switch (pid = fork()) {
case -1:
perror("The fork failed!");
break;
case 0: {
*/
-qDebug("Opening %s",dspstr);
+odebug << "Opening " << dspstr << "" << oendl;
if (( sd = ::open( dspstr, flags)) == -1) {
perror("open(\"/dev/dsp\")");
QString errorMsg="Could not open audio device\n /dev/dsp\n"
+(QString)strerror(errno);
- qDebug("XXXXXXXXXXXXXXXXXXXXXXX "+errorMsg);
+ odebug << "XXXXXXXXXXXXXXXXXXXXXXX "+errorMsg << oendl;
return -1;
}
-qDebug("Opening mixer");
+odebug << "Opening mixer" << oendl;
int mixerHandle=0;
if (( mixerHandle = open("/dev/mixer",O_RDWR))<0) {
perror("open(\"/dev/mixer\")");
QString errorMsg="Could not open audio device\n /dev/dsp\n"
+(QString)strerror(errno);
- qDebug("XXXXXXXXXXXXXXXXXXXXXX "+errorMsg);
+ odebug << "XXXXXXXXXXXXXXXXXXXXXX "+errorMsg << oendl;
}
if(ioctl(sd,SNDCTL_DSP_RESET,0)<0){
perror("ioctl RESET");
}
// sprintf(message, "%d", sd);
/* QFile f1("/pid");
f1.open(IO_WriteOnly );
f1.writeBlock(message, strlen(message));
f1.close();
*/
/* close(pipefd[0]);
write(pipefd[1], message, sizeof(message));
close(pipefd[1]);
- // qDebug("%d",soundDevice->sd );
+ // odebug << "" << soundDevice->sd << "" << oendl;
_exit(0);
}
default:
// pid greater than zero is parent getting the child's pid
printf("Child's pid is %d\n",pid);
QString s;
close(pipefd[1]);
read(pipefd[0], message, sizeof(message));
s = message;
close(pipefd[0]);
// while(wait(NULL)!=pid)
// ;
printf("child %ld terminated normally, return status is zero\n", (long) pid);
*/
// filePara.sd=(long) pid;
/* QFile f2("/pid");
f2.open(IO_ReadOnly);
QTextStream t(&f2);
// for(int f=0; f < t.atEnd() ;f++) {
s = t.readLine();
// }
*/
// bool ok;
// sd = s.toInt(&ok, 10);
-// qDebug("<<<<<<<<<<<<<>>>>>>>>>>>>"+s);
+// odebug << "<<<<<<<<<<<<<>>>>>>>>>>>>"+s << oendl;
// f2.close();
// }
::close(mixerHandle );
-// qDebug("open device %s", dspstr);
-// qDebug("success! %d",sd);
+// odebug << "open device " << dspstr << "" << oendl;
+// odebug << "success! " << sd << "" << oendl;
return sd;
}
bool Device::closeDevice( bool) {
// if(b) {//close now
// if (ioctl( sd, SNDCTL_DSP_RESET, 0) == -1) {
// perror("ioctl(\"SNDCTL_DSP_RESET\")");
// }
// } else { //let play
// if (ioctl( sd, SNDCTL_DSP_SYNC, 0) == -1) {
// perror("ioctl(\"SNDCTL_DSP_SYNC\")");
// }
// }
::close( sd); //close sound device
// sdfd=0;
// sd=0;
-// qDebug("closed dsp");
+// odebug << "closed dsp" << oendl;
return true;
}
bool Device::setDeviceFormat( int form) {
- qDebug("set device res %d %d", form, sd);
+ odebug << "set device res " << form << " " << sd << "" << oendl;
if (ioctl( sd, SNDCTL_DSP_SETFMT, &form)==-1) { //set format
perror("ioctl(\"SNDCTL_DSP_SETFMT\")");
return false;
}
devRes=form;
return true;
}
bool Device::setDeviceChannels( int ch) {
- qDebug("set channels %d %d", ch, sd);
+ odebug << "set channels " << ch << " " << sd << "" << oendl;
if (ioctl( sd, SNDCTL_DSP_CHANNELS, &ch)==-1) {
perror("ioctl(\"SNDCTL_DSP_CHANNELS\")");
return false;
}
devCh=ch;
return true;
}
bool Device::setDeviceRate( int rate) {
- qDebug("set rate %d %d", rate, sd);
+ odebug << "set rate " << rate << " " << sd << "" << oendl;
if (ioctl( sd, SNDCTL_DSP_SPEED, &rate) == -1) {
perror("ioctl(\"SNDCTL_DSP_SPEED\")");
return false;
}
devRate=rate;
return true;
}
int Device::getRes() {
return devRes;
}
int Device::getFormat() {
return devForm;
}
int Device::getRate() {
return devRate;
}
int Device::getChannels() {
return devCh;
}
int Device::getDeviceFormat() {
return 0;
}
int Device::getDeviceRate() {
int dRate=0;
if (ioctl( sd, SOUND_PCM_READ_RATE, &dRate) == -1) {
perror("ioctl(\"SNDCTL_PCM_READ_RATE\")");
}
return dRate;
}
int Device::getDeviceBits() {
int dBits=0;
#ifndef QT_QWS_EBX // zaurus doesnt have this
if (ioctl( sd, SOUND_PCM_READ_BITS, &dBits) == -1) {
perror("ioctl(\"SNDCTL_PCM_READ_BITS\")");
}
#endif
return dBits;
}
int Device::getDeviceChannels() {
int dCh=0;
if (ioctl( sd, SOUND_PCM_READ_CHANNELS, &dCh) == -1) {
perror("ioctl(\"SNDCTL_PCM_READ_CHANNELS\")");
}
return dCh;
}
int Device::getDeviceFragSize() {
int frag_size;
if (ioctl( sd, SNDCTL_DSP_GETBLKSIZE, &frag_size) == -1) {
- qDebug("no fragsize");
+ odebug << "no fragsize" << oendl;
} else {
- qDebug("driver says frag size is %d", frag_size);
+ odebug << "driver says frag size is " << frag_size << "" << oendl;
}
return frag_size;
}
bool Device::setFragSize(int frag) {
if (ioctl(sd, SNDCTL_DSP_SETFRAGMENT, &frag)) {
perror("ioctl(\"SNDCTL_DSP_SETFRAGMENT\")");
return false;
}
return true;
}
bool Device::reset() {
closeDevice(true);
openDsp();
if (ioctl( sd, SNDCTL_DSP_RESET, 0) == -1) {
perror("ioctl(\"SNDCTL_DSP_RESET\")");
return false;
}
return true;
}
int Device::devRead(int soundDescriptor, short *buf, int size) {
int number = 0;
number = ::read( soundDescriptor, (char *)buf, size);
return number;
}
int Device::devWrite(int soundDescriptor, short * buf, int size) {
int bytesWritten = 0;
bytesWritten = ::write( soundDescriptor, buf, size);
return bytesWritten;
}
diff --git a/noncore/multimedia/opierec/helpwindow.cpp b/noncore/multimedia/opierec/helpwindow.cpp
index 6aebaa1..7f984c3 100644
--- a/noncore/multimedia/opierec/helpwindow.cpp
+++ b/noncore/multimedia/opierec/helpwindow.cpp
@@ -1,124 +1,129 @@
/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include "helpwindow.h"
-#include <qlayout.h>
-#include <qtoolbar.h>
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/resource.h>
+using namespace Opie::Core;
+/* QT */
+#include <qlayout.h>
+#include <qtoolbar.h>
#include <qaction.h>
#include <qmenubar.h>
+/* STD */
#include <ctype.h>
HelpWindow::HelpWindow( const QString& home_, const QString& _path, QWidget* parent, const char *name )
: QMainWindow( parent, name, WDestructiveClose ), pathCombo( 0 ), selectedURL()
{
QGridLayout *layout = new QGridLayout( this );
layout->setSpacing( 2);
layout->setMargin( 2);
- qDebug(_path);
+ odebug << _path << oendl;
browser = new QTextBrowser( this );
QStringList Strlist;
Strlist.append( home_);
browser->mimeSourceFactory()->setFilePath( Strlist );
browser->setFrameStyle( QFrame::Panel | QFrame::Sunken );
connect( browser, SIGNAL( textChanged() ), this, SLOT( textChanged() ) );
if ( !home_.isEmpty() )
browser->setSource( home_ );
QToolBar *toolbar = new QToolBar( this );
QAction *a = new QAction( tr( "Backward" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 );
connect( a, SIGNAL( activated() ), browser, SLOT( backward() ) );
a->addTo( toolbar );
a = new QAction( tr( "Forward" ), Resource::loadPixmap( "forward" ), QString::null, 0, this, 0 );
connect( a, SIGNAL( activated() ), browser, SLOT( forward() ) );
a->addTo( toolbar );
layout->addMultiCellWidget( toolbar, 0, 0, 0, 0);
layout->addMultiCellWidget( browser, 1, 2, 0, 2);
browser->setFocus();
}
void HelpWindow::setBackwardAvailable( bool b)
{
menuBar()->setItemEnabled( backwardId, b);
}
void HelpWindow::setForwardAvailable( bool b)
{
menuBar()->setItemEnabled( forwardId, b);
}
void HelpWindow::textChanged()
{
if ( browser->documentTitle().isNull() ) {
setCaption( "QpeRec - Helpviewer - " + browser->context() );
selectedURL = browser->context();
}
else {
setCaption( "QpeRec - Helpviewer - " + browser->documentTitle() ) ;
selectedURL = browser->documentTitle();
}
// if ( !selectedURL.isEmpty() && pathCombo ) {
// bool exists = FALSE;
// int i;
// for ( i = 0; i < pathCombo->count(); ++i ) {
// if ( pathCombo->text( i ) == selectedURL ) {
// exists = TRUE;
// break;
// }
// }
// if ( !exists ) {
// pathCombo->insertItem( selectedURL, 0 );
// pathCombo->setCurrentItem( 0 );
// mHistory[ hist->insertItem( selectedURL ) ] = selectedURL;
// } else
// pathCombo->setCurrentItem( i );
// selectedURL = QString::null;
// }
}
HelpWindow::~HelpWindow()
{
history.clear();
QMap<int, QString>::Iterator it = mHistory.begin();
for ( ; it != mHistory.end(); ++it )
history.append( *it );
QFile f( QDir::currentDirPath() + "/.history" );
f.open( IO_WriteOnly );
QDataStream s( &f );
s << history;
f.close();
bookmarks.clear();
QMap<int, QString>::Iterator it2 = mBookmarks.begin();
for ( ; it2 != mBookmarks.end(); ++it2 )
bookmarks.append( *it2 );
QFile f2( QDir::currentDirPath() + "/.bookmarks" );
f2.open( IO_WriteOnly );
QDataStream s2( &f2 );
s2 << bookmarks;
f2.close();
}
void HelpWindow::openFile()
diff --git a/noncore/multimedia/opierec/opierec.pro b/noncore/multimedia/opierec/opierec.pro
index 7b08f0e..ea1bae3 100644
--- a/noncore/multimedia/opierec/opierec.pro
+++ b/noncore/multimedia/opierec/opierec.pro
@@ -1,41 +1,39 @@
-#CONFIG = qt warn_on pdaudio
-CONFIG = qt warn_on opie
-#CONFIG = qt warn_on quick-app
+CONFIG = qt warn_on
HEADERS = adpcm.h \
pixmaps.h \
helpwindow.h \
qtrec.h \
device.h \
wavFile.h \
waveform.h
SOURCES = adpcm.c \
helpwindow.cpp \
main.cpp \
qtrec.cpp \
device.cpp \
wavFile.cpp \
waveform.cpp
INTERFACES =
contains(CONFIG, pdaudio) {
# LIBS += -L/opt/buildroot-opie/output/staging/target/lib -lqpe -lpthread -ljpeg -lpng -lz
LIBS += -L$(QPEDIR)/lib -lqpe -lpthread -ljpeg -lpng -lz -lopiecore2
INCLUDEPATH += $(QPEDIR)/include
DEPENDPATH += $(QPEDIR)/include
DEFINES += PDAUDIO
DEFINES += THREADED
TARGET = qperec
# DESTDIR=$(QPEDIR)/bin
}
-contains(CONFIG, opie) {
+!contains(CONFIG, pdaudio) {
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
DESTDIR=$(OPIEDIR)/bin
LIBS += -lqpe -lopiecore2 -lpthread
TARGET = opierec
include ( $(OPIEDIR)/include.pro )
}
diff --git a/noncore/multimedia/opierec/qtrec.cpp b/noncore/multimedia/opierec/qtrec.cpp
index 1c64ab1..2187d5a 100644
--- a/noncore/multimedia/opierec/qtrec.cpp
+++ b/noncore/multimedia/opierec/qtrec.cpp
@@ -1,472 +1,471 @@
/****************************************************************************
// qtrec.cpp
Created: Thu Jan 17 11:19:58 2002
copyright 2002 by L.J. Potter <ljp@llornkcor.com>
****************************************************************************/
#define DEV_VERSION
#include "pixmaps.h"
#include "qtrec.h"
#include "waveform.h"
-
-#include <pthread.h>
-
extern "C" {
#include "adpcm.h"
}
-#include <sys/soundcard.h>
-
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/config.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
#include <qpe/storage.h>
+using namespace Opie::Core;
+/* QT */
#include <qcheckbox.h>
#include <qcombobox.h>
-//#include <qdatetime.h>
#include <qdir.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlistview.h>
#include <qmessagebox.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qslider.h>
#include <qtabwidget.h>
#include <qtimer.h>
+/* STD */
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <mntent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/vfs.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/signal.h>
-
+#include <pthread.h>
#ifdef PDAUDIO //ALSA
#include <alsa/asoundlib.h>
static int deviceSampleRates[8] = { 32000, 44100, 48000, 88200, 96000, 176400, 192000, -1 };
static int deviceBitRates[] = { 8, 16, 24, 32, -1 };
#else //OSS
static int deviceSampleRates[6] = { 11025, 16000, 22050, 32000, 44100, -1 };
static int deviceBitRates[] = { 8, 16, -1 };
#endif
#if defined(QT_QWS_SL5XXX)
///#if defined(QT_QWS_EBX)
#define DSPSTROUT "/dev/dsp"
#define DSPSTRIN "/dev/dsp1"
#define DSPSTRMIXEROUT "/dev/mixer"
#define DSPSTRMIXERIN "/dev/mixer1"
#else
#define DSPSTROUT "/dev/dsp"
#define DSPSTRIN "/dev/dsp"
#define DSPSTRMIXERIN "/dev/mixer"
#define DSPSTRMIXEROUT "/dev/mixer"
#endif
//#define ZAURUS 0
struct adpcm_state encoder_state;
struct adpcm_state decoder_state;
typedef struct {
int sampleRate;
/* int fragSize; */
/* int blockSize; */
int resolution; //bitrate
int channels; //number of channels
int fd; //file descriptor
int sd; //sound device descriptor
int numberSamples; //total number of samples
int SecondsToRecord; // number of seconds that should be recorded
float numberOfRecordedSeconds; //total number of samples recorded
int samplesToRecord; //number of samples to be recorded
int inVol; //input volume
int outVol; //output volume
int format; //wavfile format PCM.. ADPCM
const char *fileName; //name of fiel to be played/recorded
} fileParameters;
fileParameters filePara;
bool monitoring, recording, playing;
bool stopped;
QLabel *timeLabel;
QSlider *timeSlider;
int sd;
Waveform* waveform;
Device *soundDevice;
#ifdef THREADED
void quickRec()
#else
void QtRec::quickRec()
#endif
{
qDebug("%d",
filePara.numberSamples/filePara.sampleRate * filePara.channels);
qDebug("samples %d, rate %d, channels %d",
filePara.numberSamples, filePara.sampleRate, filePara.channels);
int total = 0; // Total number of bytes read in so far.
int bytesWritten, number;
bytesWritten = 0;
number = 0;
QString num;
int level = 0;
int threshold = 0;
// int bits = filePara.resolution;
-// qDebug("bits %d", bits);
+// odebug << "bits " << bits << "" << oendl;
if( filePara.resolution == 16 ) { //AFMT_S16_LE)
-// qDebug("AFMT_S16_LE size %d", filePara.SecondsToRecord);
-// qDebug("samples to record %d", filePara.samplesToRecord);
-// qDebug("%d", filePara.sd);
+// odebug << "AFMT_S16_LE size " << filePara.SecondsToRecord << "" << oendl;
+// odebug << "samples to record " << filePara.samplesToRecord << "" << oendl;
+// odebug << "" << filePara.sd << "" << oendl;
level = 7;
threshold = 0;
if( filePara.format == WAVE_FORMAT_DVI_ADPCM) {
-// qDebug("start recording WAVE_FORMAT_DVI_ADPCM");
+// odebug << "start recording WAVE_FORMAT_DVI_ADPCM" << oendl;
// <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>>
char abuf[ BUFSIZE/2 ];
short sbuf[ BUFSIZE ];
short sbuf2[ BUFSIZE ];
memset( abuf, 0, BUFSIZE/2);
memset( sbuf, 0, BUFSIZE);
memset( sbuf2, 0, BUFSIZE);
for(;;) {
if ( stopped) {
-// qDebug("quickRec:: stopped");
+// odebug << "quickRec:: stopped" << oendl;
break;
}
// number=::read( filePara.sd, sbuf, BUFSIZE);
number = soundDevice ->devRead( filePara.sd, sbuf, BUFSIZE);
if(number <= 0) {
perror("recording error ");
- qDebug( "%s %d", filePara.fileName, number);
+ odebug << "" << filePara.fileName << " " << number << "" << oendl;
stopped = true;
return;
}
//if(stereo == 2) {
// adpcm_coder( sbuf2, abuf, number/2, &encoder_state);
adpcm_coder( sbuf, abuf, number/2, &encoder_state);
bytesWritten = ::write( filePara.fd , (short *)abuf, number/4);
waveform->newSamples( (const short *)abuf, bytesWritten );
total += bytesWritten;
filePara.numberSamples = total;
timeSlider->setValue( total);
filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate * (float)2 / filePara.channels;
qApp->processEvents();
if( total >= filePara.samplesToRecord) {
stopped = true;
break;
}
}
} else {
// <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>>
- qDebug("start recording WAVE_FORMAT_PCM");
+ odebug << "start recording WAVE_FORMAT_PCM" << oendl;
short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ];
memset( inbuffer, 0, BUFSIZE);
memset( outbuffer, 0, BUFSIZE);
for(;;) {
if ( stopped) {
- qDebug("quickRec:: stopped");
+ odebug << "quickRec:: stopped" << oendl;
stopped = true;
break; // stop if playing was set to false
return;
}
number = soundDevice->devRead( filePara.sd, (short *)inbuffer, BUFSIZE);
waveform->newSamples( inbuffer, number );
if( number <= 0) {
perror( "recording error ");
- qDebug( filePara.fileName);
+ odebug << filePara.fileName << oendl;
stopped = true;
return;
}
bytesWritten = ::write( filePara.fd , inbuffer, number);
if( bytesWritten < 0) {
perror("File writing error ");
stopped = true;
return;
}
total += bytesWritten;
filePara.numberSamples = total;
if( filePara.SecondsToRecord != 0)
timeSlider->setValue( total);
// printf("Writing number %d, bytes %d,total %d\r",number, bytesWritten , total);
// fflush(stdout);
filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2/filePara.channels;
qApp->processEvents();
if( total >= filePara.samplesToRecord) {
stopped = true;
break;
}
}
} //end main loop
} else {
// <<<<<<<<<<<<<<<<<<<<<<< format = AFMT_U8;
unsigned char unsigned_inbuffer[ BUFSIZE ], unsigned_outbuffer[ BUFSIZE ];
memset( unsigned_inbuffer, 0, BUFSIZE);
memset( unsigned_outbuffer, 0, BUFSIZE);
for(;;) {
if ( stopped) {
- qDebug("quickRec:: stopped");
+ odebug << "quickRec:: stopped" << oendl;
break; // stop if playing was set to false
}
number = ::read( filePara.sd, unsigned_inbuffer, BUFSIZE);
bytesWritten = ::write( filePara.fd , unsigned_inbuffer, number);
if(bytesWritten < 0) {
stopped = true;
QMessageBox::message("Note","There was a problem\nwriting to the file");
perror("File writing error ");
return;
}
total += bytesWritten;
filePara.numberSamples = total;
// printf("\nWriting number %d, bytes %d,total %d \r",number, bytesWritten , total);
// fflush(stdout);
if( filePara.SecondsToRecord !=0)
timeSlider->setValue( total);
filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate;
qApp->processEvents();
if( total >= filePara.samplesToRecord) {
stopped = true;
break;
}
} //end main loop
}
} /// END quickRec()
#ifdef THREADED
void playIt()
#else
void QtRec::playIt()
#endif
{
int bytesWritten = 0;
int number = 0;
int total = 0; // Total number of bytes read in so far.
if( filePara.resolution == 16 ) { //AFMT_S16_LE) {
if( filePara.format == WAVE_FORMAT_DVI_ADPCM) {
char abuf[ BUFSIZE / 2 ];
short sbuf[ BUFSIZE ];
short sbuf2[ BUFSIZE * 2 ];
memset( abuf, 0, BUFSIZE / 2);
memset( sbuf, 0, BUFSIZE);
memset( sbuf2, 0, BUFSIZE * 2);
// <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>>
for(;;) { // play loop
if ( stopped) {
break;
return;
}// stop if playing was set to false
number = ::read( filePara.fd, abuf, BUFSIZE / 2);
adpcm_decoder( abuf, sbuf, number * 2, &decoder_state);
// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel
// sbuf2[i+1]=sbuf2[i]=sbuf[i];
// }
bytesWritten = write ( filePara.sd, sbuf, number * 4);
waveform->newSamples( (const short *)sbuf, number );
// if(filePara.channels==1)
// total += bytesWritten/2; //mono
// else
total += bytesWritten;
filePara.numberSamples = total/4;
filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / 2;
timeSlider->setValue( total/4);
// timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds);
// if(filePara.numberOfRecordedSeconds>1)
// timeLabel->setText( timeString+ tr(" seconds"));
// printf("playing number %d, bytes %d, total %d\n",number, bytesWritten, total/4);
// fflush(stdout);
qApp->processEvents();
if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
// if( total >= filePara.numberSamples ){//|| secCount > filePara.numberOfRecordedSeconds ) {
stopped = true;
break;
}
}
} else {
// <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>>
short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ];
memset( inbuffer, 0, BUFSIZE);
memset( outbuffer, 0, BUFSIZE);
for(;;) { // play loop
if ( stopped) {
break;
return;
}
// stop if playing was set to false
number = ::read( filePara.fd, inbuffer, BUFSIZE);
// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel
// // for (int i=0;i< number ; i++) { //2*i is left channel
// outbuffer[i+1]= outbuffer[i]=inbuffer[i];
// }
bytesWritten = ::write( filePara.sd, inbuffer, number);
waveform->newSamples( inbuffer, bytesWritten );
//-------------->>>> out to device
// total+=bytesWritten;
// if(filePara.channels==1)
// total += bytesWritten/2; //mono
// else
total += bytesWritten;
timeSlider->setValue( total);
filePara.numberSamples = total;
filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2;
// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds);
// timeLabel->setText( timeString + tr(" seconds"));
qApp->processEvents();
if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
- qWarning("Jane! Stop this crazy thing!");
+ owarn << "Jane! Stop this crazy thing!" << oendl;
stopped = true;
// playing = false;
break;
}
}
printf("\nplaying number %d, bytes %d, total %d\r",number, bytesWritten, total);
fflush(stdout);
} //end loop
} else {
/////////////////////////////// format = AFMT_U8;
unsigned char unsigned_inbuffer[ BUFSIZE ]; //, unsigned_outbuffer[BUFSIZE];
memset( unsigned_inbuffer, 0, BUFSIZE);
for(;;) {
// main loop
if (stopped) {
break; // stop if playing was set to false
return;
}
number = ::read( filePara.fd, unsigned_inbuffer, BUFSIZE);
//data = (val >> 8) ^ 0x80;
// unsigned_outbuffer = (unsigned_inbuffer >> 8) ^ 0x80;
bytesWritten = write ( filePara.sd, unsigned_inbuffer, number);
waveform->newSamples( (const short *)unsigned_inbuffer, bytesWritten );
total += bytesWritten;
timeSlider->setValue( total);
filePara.numberSamples = total;
filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate;
// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds);
// timeLabel->setText( timeString + tr(" seconds"));
qApp->processEvents();
if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
// if( total >= filePara.numberSamples ) {
stopped = true;
break;
}
// printf("Writing number %d, bytes %d, total %d, numberSamples %d\r",number, bytesWritten , total, filePara.numberSamples);
// fflush(stdout);
}
}
}
QtRec::QtRec( QWidget* parent, const char* name, WFlags fl )
: QWidget( parent, name, fl )
{
if ( !name )
setName( "OpieRec" );
init();
initConfig();
initConnections();
renameBox = 0;
// open sound device to get volumes
Config hwcfg("OpieRec");
hwcfg.setGroup("Hardware");
soundDevice = new Device( this,
hwcfg.readEntry( "Audio",DSPSTROUT),
hwcfg.readEntry( "Mixer",DSPSTRMIXEROUT), false);
// soundDevice = new Device( this, hwcfg.readEntry( "Audio","hw:0"), hwcfg.readEntry( "Mixer","hw:0"), false);
// soundDevice->setDeviceFormat(AFMT_S16_LE);
// soundDevice->setDeviceChannels(1);
// soundDevice->setDeviceRate( 22050);
getInVol();
getOutVol();
soundDevice->closeDevice( true);
soundDevice->sd = -1;
soundDevice = 0;
wavFile = 0;
if( soundDevice) delete soundDevice;
initIconView();
if( autoMute)
doMute( true);
ListView1->setFocus();
playing = false;
}
QtRec::~QtRec() {
}
void QtRec::cleanUp() {
if( !stopped) {
stopped = true;
endRecording();
@@ -625,1477 +624,1477 @@ void QtRec::init() {
glayout3->addMultiCellWidget( dirGroup, 1, 1, 0, 0);
bitGroup = new QGroupBox( tab_3, "bitGroup" );
bitGroup->setTitle( tr( "Bit Depth" ) );
bitGroup->setFixedSize( 65, 50);
bitRateComboBox = new QComboBox( false, bitGroup, "BitRateComboBox" );
z = 0;
while( deviceBitRates[z] != -1) {
bitRateComboBox->insertItem( s.setNum( deviceBitRates[z], 10) );
z++;
}
bitRateComboBox->setGeometry( QRect( 5, 20, 50, 25 ) );
glayout3->addMultiCellWidget( bitGroup, 1, 1, 1, 1);
compressionCheckBox = new QCheckBox ( tr("Wave Compression (smaller files)"), tab_3 );
autoMuteCheckBox = new QCheckBox ( tr("Auto Mute"), tab_3 );
stereoCheckBox = new QCheckBox ( tr("Stereo Channels"), tab_3 );
glayout3->addMultiCellWidget( compressionCheckBox, 2, 2, 0, 3);
glayout3->addMultiCellWidget( autoMuteCheckBox, 3, 3, 0, 0);
glayout3->addMultiCellWidget( stereoCheckBox, 3, 3, 1, 1);
tab_5 = new QWidget( TabWidget, "tab_5" );
QHBoxLayout *Layout19a;
Layout19a = new QHBoxLayout( tab_5);
Layout19a->setSpacing( 2 );
Layout19a->setMargin( 0 );
Layout15 = new QVBoxLayout( this);
Layout15->setSpacing( 2 );
Layout15->setMargin( 0 );
Layout15b = new QVBoxLayout( this);
Layout15b->setSpacing( 2 );
Layout15b->setMargin( 0 );
TextLabel2 = new QLabel( tab_5, "InputLabel" );
TextLabel2->setText( tr( "In"));
TextLabel2->setFixedWidth( 35);
Layout15->addWidget( TextLabel2 );
TextLabel3 = new QLabel( tab_5, "OutputLabel" );
TextLabel3->setText( tr( "Out" ) );
Layout15b->addWidget( TextLabel3 );
InputSlider = new QSlider( -100, 0, 10, 0, QSlider::Vertical, tab_5, (const char *) "InputSlider" );
InputSlider->setTickmarks( QSlider::Both);
Layout15->addWidget( InputSlider);
OutputSlider = new QSlider( -100,0,10,0, QSlider::Vertical,tab_5,(const char *) "OutputSlider" );
OutputSlider->setTickmarks( QSlider::Both);
Layout15b->addWidget( OutputSlider );
outMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 );
Layout15->addWidget( outMuteCheckBox );
inMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 );
inMuteCheckBox-> setFocusPolicy ( QWidget::NoFocus );
Layout15b->addWidget( inMuteCheckBox );
Layout19a->addLayout( Layout15 );
Layout19a->addLayout( Layout15b );
fillDirectoryCombo();
TabWidget->insertTab( tab_3, tr( "Options" ) );
TabWidget->insertTab( tab_5, tr( "Volume" ) );
waveform = new Waveform( this, "waveform" );
// waveform->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)3, waveform->sizePolicy().hasHeightForWidth() ) );
waveform->setMinimumSize( QSize( 0, 50 ) );
layout->addMultiCellWidget( waveform, 8, 8, 0, 7 );
waveform->setBackgroundColor ( black );
}
void QtRec::initIconView() {
ListView1->clear();
Config cfg("OpieRec");
cfg.setGroup("Sounds");
QString temp;
QPixmap image0( ( const char** ) image0_data );
int nFiles = cfg.readNumEntry("NumberofFiles",0);
-// qDebug("init number of files %d", nFiles);
+// odebug << "init number of files " << nFiles << "" << oendl;
for(int i=1;i<= nFiles;i++) {
QListViewItem * item;
QString fileS, mediaLocation, fileDate, filePath;
temp.sprintf( "%d",i);
temp = cfg.readEntry( temp,""); //reads currentFile
filePath = cfg.readEntry( temp,""); //currentFileName
QFileInfo info(filePath);
fileDate = info.lastModified().toString();
fileS = cfg.readEntry( filePath, "0" );// file length in seconds
mediaLocation = getStorage( filePath);
if( info.exists()) {
item = new QListViewItem( ListView1, temp, fileS, mediaLocation, fileDate);
item->setPixmap( 0, image0);
if( currentFileName == filePath)
ListView1->setSelected( item, true);
}
}
}
void QtRec::initConnections() {
connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
connect( toBeginningButton, SIGNAL( pressed()),
this, SLOT( rewindPressed() ));
connect( toBeginningButton, SIGNAL( released()),
this, SLOT( rewindReleased() ));
connect( toEndButton, SIGNAL( pressed()),
this, SLOT( FastforwardPressed() ));
connect( toEndButton, SIGNAL( released()),
this, SLOT( FastforwardReleased() ));
connect( deleteSoundButton, SIGNAL(released()),
this, SLOT( deleteSound() ));
connect( Stop_PushButton, SIGNAL(released()),
this, SLOT( doPlayBtn() ));
connect( Rec_PushButton, SIGNAL(released()),
this, SLOT( newSound() ) );
connect( TabWidget, SIGNAL( currentChanged(QWidget*)),
this, SLOT(thisTab(QWidget*) ));
connect( OutputSlider, SIGNAL(sliderReleased()),
this, SLOT( changedOutVolume()) );
connect( InputSlider, SIGNAL(sliderReleased()),
this, SLOT( changedInVolume()) );
connect( sampleRateComboBox, SIGNAL(activated(int)),
this, SLOT( changesamplerateCombo(int)) );
connect( bitRateComboBox, SIGNAL(activated(int)),
this, SLOT( changebitrateCombo(int)) );
connect( directoryComboBox, SIGNAL(activated(int)),
this, SLOT( changeDirCombo(int)) );
connect( sizeLimitCombo, SIGNAL(activated(int)),
this, SLOT( changeSizeLimitCombo(int)) );
connect( stereoCheckBox, SIGNAL(toggled(bool)),
this, SLOT( changeStereoCheck(bool)) );
connect( outMuteCheckBox, SIGNAL(toggled(bool)),
this, SLOT( doVolMuting(bool)) );
connect( inMuteCheckBox , SIGNAL(toggled(bool)),
this, SLOT( doMicMuting(bool)) );
connect( ListView1,SIGNAL(doubleClicked(QListViewItem*)),
this,SLOT( itClick(QListViewItem*)));
connect( ListView1, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
this,SLOT( listPressed(int,QListViewItem*,const QPoint&,int)) );
connect( timeSlider, SIGNAL( sliderMoved(int)),
this, SLOT( changeTimeSlider(int) ));
connect( timeSlider, SIGNAL( sliderPressed()),
this, SLOT( timeSliderPressed() ));
connect( timeSlider, SIGNAL( sliderReleased()),
this, SLOT( timeSliderReleased() ));
connect( compressionCheckBox, SIGNAL( toggled(bool)),
this, SLOT( compressionSelected(bool)));
connect( autoMuteCheckBox, SIGNAL( toggled(bool)),
this, SLOT( slotAutoMute(bool)));
}
void QtRec::initConfig() {
int index, fred, i;
Config cfg("OpieRec");
cfg.setGroup("Settings");
index = cfg.readNumEntry("samplerate",22050);
bool ok;
for(int ws=0;ws<sampleRateComboBox->count();ws++) {
fred = sampleRateComboBox->text(ws).toInt(&ok, 10);
if( index == fred) {
filePara.sampleRate = fred;
sampleRateComboBox->setCurrentItem(ws);
}
}
i = cfg.readNumEntry("bitrate",16);
if(i == 16)
bitRateComboBox->setCurrentItem( 1);
else if(i == 24)
bitRateComboBox->setCurrentItem( 2);
else if(i == 32)
bitRateComboBox->setCurrentItem( 3);
else
bitRateComboBox->setCurrentItem( 0);
filePara.resolution = i;
i = cfg.readNumEntry("sizeLimit", 5 );
QString temp;
sizeLimitCombo->setCurrentItem((i/5));
stereoCheckBox->setChecked( cfg.readBoolEntry("stereo", 1));
if( stereoCheckBox->isChecked()) {
filePara.channels = 2;
} else {
filePara.channels = 1;
}
compressionCheckBox->setChecked( cfg.readBoolEntry("wavCompression",1));
if( compressionCheckBox->isChecked()) {
bitRateComboBox->setEnabled(false);
bitRateComboBox->setCurrentItem(0);
filePara.resolution=16;
}
autoMuteCheckBox->setChecked( cfg.readBoolEntry("useAutoMute",0));
if( autoMuteCheckBox->isChecked())
slotAutoMute(true);
else
slotAutoMute(false);
Config cofg( "qpe");
cofg.setGroup( "Volume");
outMuteCheckBox->setChecked( cofg.readBoolEntry( "Mute",0));
inMuteCheckBox->setChecked( cofg.readBoolEntry( "MicMute",0));
}
void QtRec::stop() {
- qWarning("STOP");
+ owarn << "STOP" << oendl;
setRecordButton(false);
if( !recording)
endPlaying();
else
endRecording();
timeSlider->setValue(0);
}
void QtRec::doPlayBtn() {
if(!stopped) {
playLabel2->setText(tr("Play"));
stop();
} else {
if(ListView1->currentItem() == 0) return;
playLabel2->setText(tr("Stop"));
currentFile = ListView1->currentItem()->text(0);
start();
}
}
void QtRec::start() { //play
if( stopped) {
QPixmap image3( ( const char** ) image3_data );
Stop_PushButton->setPixmap( image3 );
Stop_PushButton->setDown( true);
stopped = false;
paused = false;
secCount = 1;
if( openPlayFile())
if( setupAudio( false)) //recording is false
doPlay();
}
}
bool QtRec::rec() { //record
QString timeString;
timeString.sprintf("%.0f", 0.0);
timeLabel->setText( timeString+ " seconds");
if(!stopped) {
monitoring = true;
return false;
} else {
secCount = 1;
playLabel2->setText(tr("Stop"));
monitoring = false;
setRecordButton( true);
if( setupAudio( true))
if(setUpFile()) {
int fileSize = 0;
Config cfg("OpieRec");
cfg.setGroup("Settings");
// qDebug( "<<<<<<<Device bits %d, device rate %d, device channels %d",
// soundDevice->getDeviceBits(),
// soundDevice->getDeviceRate(),
// soundDevice->getDeviceChannels());
//filePara.sampleRate = cfg.readNumEntry("samplerate", 22050);
-// qDebug("sample rate is %d", filePara.sampleRate);
+// odebug << "sample rate is " << filePara.sampleRate << "" << oendl;
filePara.SecondsToRecord = getCurrentSizeLimit();
-// qDebug("size limit %d sec", filePara.SecondsToRecord);
+// odebug << "size limit " << filePara.SecondsToRecord << " sec" << oendl;
int diskSize = checkDiskSpace( (const QString &) wavFile->trackName());
if( filePara.SecondsToRecord == 0) {
fileSize = diskSize;
} else if( filePara.format == WAVE_FORMAT_PCM) {
-// qDebug("WAVE_FORMAT_PCM");
+// odebug << "WAVE_FORMAT_PCM" << oendl;
fileSize = (filePara.SecondsToRecord ) * filePara.channels
* filePara.sampleRate * ( filePara.resolution / 8) + 1000;
} else {
-// qDebug("WAVE_FORMAT_DVI_ADPCM");
+// odebug << "WAVE_FORMAT_DVI_ADPCM" << oendl;
fileSize = ((filePara.SecondsToRecord) * filePara.channels
* filePara.sampleRate * ( filePara.resolution / 8) ) / 4 + 250;
}
filePara.samplesToRecord = fileSize;
qDebug("filesize should be %d, bits %d, rate %d",
filePara.samplesToRecord, filePara.resolution, filePara.sampleRate);
if( paused) {
paused = false;
}
// else {
- qDebug("Setting timeslider %d", filePara.samplesToRecord);
+ odebug << "Setting timeslider " << filePara.samplesToRecord << "" << oendl;
// if(fileSize != 0)
timeSlider->setRange(0, filePara.samplesToRecord);
// }
if( diskSize < fileSize/1024) {
QMessageBox::warning(this,
tr("Low Disk Space"),
tr("You are running low of\nrecording space\n"
"or a card isn't being recognized"));
stopped = true; //we need to be stopped
stop();
} else {
QString msg;
msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution);
#ifdef DEV_VERSION
setCaption( msg);
#endif
filePara.fileName=currentFile.latin1();
- qDebug("Start recording thread");
+ odebug << "Start recording thread" << oendl;
stopped = false;
#ifdef THREADED
pthread_t thread1;
pthread_create( &thread1, NULL, (void * (*)(void *))quickRec, NULL/* &*/);
#endif
toBeginningButton->setEnabled( false);
toEndButton->setEnabled( false);
startTimer(1000);
#ifndef THREADED
quickRec();
#endif
}
} //end setUpFile
} //end setupAudio
return true;
}
/*
This happens when a tab is selected*/
void QtRec::thisTab(QWidget* widg) {
if(widg != NULL) {
int index = TabWidget->currentPageIndex();
if(index == 0) { //file page
}
if(index == 1) { //control page
fillDirectoryCombo();
// soundDevice->getOutVol();
// soundDevice->getInVol();
}
if( index==2) { //help page
}
qApp->processEvents();
update();
}
}
void QtRec::getOutVol( ) {
filePara.outVol = soundDevice->getOutVolume();
-// qDebug("out vol %d", filePara.outVol);
+// odebug << "out vol " << filePara.outVol << "" << oendl;
OutputSlider->setValue( -filePara.outVol);
}
void QtRec::getInVol() {
filePara.inVol = soundDevice->getInVolume();
-// qDebug("in vol %d", filePara.inVol);
+// odebug << "in vol " << filePara.inVol << "" << oendl;
InputSlider->setValue( -filePara.inVol);
}
void QtRec::changedOutVolume() {
soundDevice->changedOutVolume( -OutputSlider->value());
}
void QtRec::changedInVolume( ) {
soundDevice->changedInVolume( -InputSlider->value());
}
bool QtRec::setupAudio( bool b) {
bool ok;
int sampleformat, stereo, flags;
QString dspString, mixerString;
filePara.resolution = bitRateComboBox->currentText().toInt( &ok,10); //16
if( !b) {
// we want to play
#ifdef PDAUDIO //ALSA
if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) {
sampleformat = SND_PCM_FORMAT_S16;
filePara.resolution = 16;
} else if( filePara.resolution == 24 || compressionCheckBox->isChecked() ) {
sampleformat = SND_PCM_FORMAT_S24;
filePara.resolution = 24;
} else if( filePara.resolution == 32 || compressionCheckBox->isChecked() ) {
sampleformat = SND_PCM_FORMAT_S32;
filePara.resolution = 32;
} else {
sampleformat = SND_PCM_FORMAT_U8;
filePara.resolution = 8;
}
#else
// we want to play
if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) {
sampleformat = AFMT_S16_LE;
filePara.resolution = 16;
} else {
sampleformat = AFMT_U8;
filePara.resolution = 8;
}
#endif
stereo = filePara.channels;
flags = O_WRONLY;
Config hwcfg("OpieRec");
hwcfg.setGroup("Hardware");
dspString = hwcfg.readEntry( "Audio", DSPSTROUT);
mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXEROUT);
recording = false;
} else { // we want to record
#ifdef PDAUDIO //ALSA
if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16")
sampleformat = SND_PCM_FORMAT_S16;
else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "24")
sampleformat = SND_PCM_FORMAT_S24;
else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "32")
sampleformat = SND_PCM_FORMAT_S32;
else
sampleformat = SND_PCM_FORMAT_U8;
#else
if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16")
sampleformat = AFMT_S16_LE;
else
sampleformat = AFMT_U8;
if( !compressionCheckBox->isChecked()) {
filePara.format = WAVE_FORMAT_PCM;
-// qDebug("WAVE_FORMAT_PCM");
+// odebug << "WAVE_FORMAT_PCM" << oendl;
} else {
filePara.format = WAVE_FORMAT_DVI_ADPCM;
sampleformat = AFMT_S16_LE;
-// qDebug("WAVE_FORMAT_DVI_ADPCM");
+// odebug << "WAVE_FORMAT_DVI_ADPCM" << oendl;
}
#endif
stereo = filePara.channels;
// filePara.sampleRate = sampleRateComboBox->currentText().toInt( &ok,10);//44100;
flags= O_RDWR;
// flags= O_RDONLY;
Config hwcfg("OpieRec");
hwcfg.setGroup("Hardware");
dspString = hwcfg.readEntry( "Audio", DSPSTRIN);
mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXERIN);
recording = true;
}
// if(soundDevice) delete soundDevice;
- qDebug("<<<<<<<<<<<<<<<<<<<open dsp %d %d %d", filePara.sampleRate, filePara.channels, sampleformat);
- qWarning("change waveform settings");
+ odebug << "<<<<<<<<<<<<<<<<<<<open dsp " << filePara.sampleRate << " " << filePara.channels << " " << sampleformat << "" << oendl;
+ owarn << "change waveform settings" << oendl;
waveform->changeSettings( filePara.sampleRate, filePara.channels );
soundDevice = new Device( this, dspString, mixerString, b);
// soundDevice->openDsp();
soundDevice->reset();
- qDebug("device has been made %d", soundDevice->sd);
+ odebug << "device has been made " << soundDevice->sd << "" << oendl;
////////////////// <<<<<<<<<<<<>>>>>>>>>>>>
soundDevice->setDeviceFormat( sampleformat);
soundDevice->setDeviceChannels( filePara.channels);
soundDevice->setDeviceRate( filePara.sampleRate);
soundDevice->getDeviceFragSize();
#ifdef QT_QWS_EBX
int frag = FRAGSIZE;
soundDevice->setFragSize( frag);
soundDevice->getDeviceFragSize();
#endif
/////////////////
filePara.sd = soundDevice->sd;
if ( filePara.sd == -1) {
monitoring = false;
stopped = true;
update();
setCaption( tr( "OpieRecord " )+ QString::number(VERSION) );
return false;
}
if(autoMute)
doMute(false);
return true;
}
bool QtRec::setUpFile() { //setup file for recording
-// qDebug("Setting up wavfile");
+// odebug << "Setting up wavfile" << oendl;
// if(wavFile) delete wavFile;
wavFile = new WavFile( this, (const QString &)"",
true,
filePara.sampleRate,
filePara.channels,
filePara.resolution,
filePara.format);
filePara.fd = wavFile->wavHandle();
if(filePara.fd == -1) {
return false;
} else {
// filePara.channels=1;
}
return true;
}
/// <<<<<<<<<<<<<<<< PLAY >>>>>>>>>>>>>>>>>>>
bool QtRec::doPlay() {
if( !paused) {
total = 0;
filePara.numberOfRecordedSeconds = 0;
} else {
paused = false;
secCount = (int)filePara.numberOfRecordedSeconds;
}
playing = true;
stopped = false;
recording = false;
QString num;
- qDebug( "Play number of samples %d", filePara.numberSamples);
+ odebug << "Play number of samples " << filePara.numberSamples << "" << oendl;
// timeSlider->setRange( 0, filePara.numberSamples);
timeString.sprintf("%f", filePara.numberOfRecordedSeconds);
timeLabel->setText( timeString+ tr(" seconds"));
QString msg;
msg.sprintf("%d, %d, %d",
filePara.sampleRate,
filePara.channels,
filePara.resolution);
#ifdef DEV_VERSION
setCaption( msg);
#endif
startTimer( 1000);
#ifdef THREADED
pthread_t thread2;
pthread_create( &thread2, NULL, (void * (*)(void *))playIt, NULL/* &*/);
#endif
toBeginningButton->setEnabled( false);
toEndButton->setEnabled( false);
#ifndef THREADED
playIt();
#endif
return true;
}
void QtRec::changebitrateCombo(int i) {
Config cfg("OpieRec");
cfg.setGroup("Settings");
int bits = 0;
if( i == 1) { bits = 16; }
else if( i == 2) { bits = 24; }
else if( i == 3) { bits = 32; }
else { bits=8; }
cfg.writeEntry("bitrate", bits);
filePara.resolution = bits;
cfg.write();
}
void QtRec::changesamplerateCombo(int i) {
Config cfg("OpieRec");
cfg.setGroup("Settings");
int rate=0;
bool ok;
rate = sampleRateComboBox->text(i).toInt(&ok, 10);
cfg.writeEntry( "samplerate",rate);
filePara.sampleRate=rate;
- qDebug( "Change sample rate %d", rate);
+ odebug << "Change sample rate " << rate << "" << oendl;
cfg.write();
}
void QtRec::changeDirCombo(int index) {
Config cfg("OpieRec");
cfg.setGroup("Settings");
QString sName = directoryComboBox->text(index);
StorageInfo storageInfo;
const QList<FileSystem> &fs = storageInfo.fileSystems();
QListIterator<FileSystem> it ( fs );
QString storage;
for( ; it.current(); ++it ){
if( sName == (*it)->name()+" "+ (*it)->path() ||
(*it)->name() == sName ) {
const QString path = (*it)->path();
recDir = path;
cfg.writeEntry("directory", recDir);
- qDebug("new rec dir "+recDir);
+ odebug << "new rec dir "+recDir << oendl;
}
}
cfg.write();
}
void QtRec::changeSizeLimitCombo(int) {
Config cfg("OpieRec");
cfg.setGroup("Settings");
cfg.writeEntry("sizeLimit", getCurrentSizeLimit() );
cfg.write();
}
void QtRec::newSound() {
if( !rec()) {
endRecording();
deleteSound();
}
}
void QtRec::itClick(QListViewItem *item) {
currentFile = item->text(0);
setCaption("OpieRecord "+currentFile);
}
void QtRec::deleteSound() {
Config cfg("OpieRec");
cfg.setGroup("Sounds");
if( ListView1->currentItem() == NULL)
return;
#ifndef DEV_VERSION
switch ( QMessageBox::warning(this,tr("Delete"),
tr("Do you really want to <font size=+2><B>DELETE</B></font>\nthe selected file?"),
tr("Yes"),tr("No"),0,1,1) ) {
case 0:
#endif
{
QString file = ListView1->currentItem()->text(0);
QString fileName;
fileName = cfg.readEntry( file, "");
QFile f( fileName);
if( f.exists())
if( !f.remove())
QMessageBox::message( tr("Error"), tr("Could not remove file."));
int nFiles = cfg.readNumEntry( "NumberofFiles",0);
bool found = false;
for(int i=0;i<nFiles+1;i++) {
if( cfg.readEntry( QString::number(i),"").find( file,0,true) != -1) {
found = true;
cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),""));
}
if(found)
cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),""));
}
cfg.removeEntry( cfg.readEntry( file));
cfg.removeEntry( file);
cfg.writeEntry( "NumberofFiles", nFiles-1);
cfg.write();
ListView1->takeItem( ListView1->currentItem() );
delete ListView1->currentItem();
ListView1->clear();
ListView1->setSelected( ListView1->firstChild(), true);
initIconView();
update();
}
#ifndef DEV_VERSION
};
#endif
setCaption( tr( "OpieRecord " ) + QString::number(VERSION) );
}
void QtRec::keyPressEvent( QKeyEvent *e) {
switch ( e->key() ) {
// case Key_F1:
// if(stopped && !recording)
// newSound();
// else
// stop();
// break;
// case Key_F2: {
// if( !e->isAutoRepeat())
// rewindPressed();
// }
// break;
// case Key_F3: {
// if( !e->isAutoRepeat())
// FastforwardPressed();
// }
// break;
////////////////////////////// Zaurus keys
case Key_F9: //activity
break;
case Key_F10: //contacts
break;
case Key_F11: //menu
break;
case Key_F12: //home
break;
case Key_F13: //mail
break;
case Key_Space:
break;
case Key_Delete:
break;
case Key_Up:
// stop();
break;
case Key_Down:
// newSound();
break;
case Key_Left: {
- qDebug("rewinding");
+ odebug << "rewinding" << oendl;
if( !e->isAutoRepeat())
rewindPressed();
}
break;
case Key_Right: {
if( !e->isAutoRepeat())
FastforwardPressed();
}
break;
}
}
void QtRec::keyReleaseEvent( QKeyEvent *e) {
switch ( e->key() ) {
// case Key_F1:
// if(stopped && !recording)
// newSound();
// else
// stop();
// break;
// case Key_F2:
// rewindReleased();
// break;
// case Key_F3:
// FastforwardReleased();
// break;
////////////////////////////// Zaurus keys
case Key_F9: //activity
break;
case Key_F10: //contacts
break;
case Key_F11: //menu
break;
case Key_F12: //home
if(stopped)
doPlayBtn();
else
stop();
break;
case Key_F13: //mail
break;
case Key_Space:
if(stopped && !recording)
newSound();
else
stop();
break;
case Key_Delete:
deleteSound();
break;
case Key_Up:
// stop();
- qDebug("Up");
+ odebug << "Up" << oendl;
break;
case Key_Down:
// start();
- // qDebug("Down");
+ // odebug << "Down" << oendl;
// newSound();
break;
case Key_Left:
- qDebug("Left");
+ odebug << "Left" << oendl;
rewindReleased();
break;
case Key_Right:
- qDebug("Right");
+ odebug << "Right" << oendl;
FastforwardReleased();
break;
}
}
void QtRec::endRecording() {
monitoring = false;
recording = false;
stopped = true;
waveform->reset();
setRecordButton( false);
toBeginningButton->setEnabled( true);
toEndButton->setEnabled( true);
killTimers();
if(autoMute)
doMute( true);
soundDevice->closeDevice( true);
if( wavFile->track.isOpen()) {
wavFile->adjustHeaders( filePara.fd, filePara.numberSamples);
// soundDevice->sd=-1;
filePara.numberSamples = 0;
// filePara.sd=-1;
wavFile->closeFile();
filePara.fd=0;
if( wavFile->isTempFile()) {
// move tmp file to regular file
QString cmd;
cmd.sprintf("mv "+ wavFile->trackName() + " " + wavFile->currentFileName);
-// qDebug("moving tmp file to "+currentFileName);
+// odebug << "moving tmp file to "+currentFileName << oendl;
system( cmd.latin1());
}
- qDebug("Just moved " + wavFile->currentFileName);
+ odebug << "Just moved " + wavFile->currentFileName << oendl;
Config cfg("OpieRec");
cfg.setGroup("Sounds");
int nFiles = cfg.readNumEntry( "NumberofFiles",0);
currentFile = QFileInfo( wavFile->currentFileName).fileName();
currentFile = currentFile.left( currentFile.length() - 4);
cfg.writeEntry( "NumberofFiles", nFiles + 1);
cfg.writeEntry( QString::number( nFiles + 1), currentFile);
cfg.writeEntry( currentFile, wavFile->currentFileName);
QString time;
time.sprintf("%.2f", filePara.numberOfRecordedSeconds);
cfg.writeEntry( wavFile->currentFileName, time );
-// qDebug("writing config numberOfRecordedSeconds "+time);
+// odebug << "writing config numberOfRecordedSeconds "+time << oendl;
cfg.write();
- qDebug("finished recording");
+ odebug << "finished recording" << oendl;
timeLabel->setText("");
}
if(soundDevice) delete soundDevice;
timeSlider->setValue(0);
initIconView();
selectItemByName( currentFile);
}
void QtRec::endPlaying() {
monitoring = false;
recording = false;
playing = false;
stopped = true;
waveform->reset();
// errorStop();
-// qDebug("end playing");
+// odebug << "end playing" << oendl;
setRecordButton( false);
toBeginningButton->setEnabled( true);
toEndButton->setEnabled( true);
if(autoMute)
doMute( true);
soundDevice->closeDevice( false);
soundDevice->sd = -1;
// if(soundDevice) delete soundDevice;
-// qDebug("file and sound device closed");
+// odebug << "file and sound device closed" << oendl;
timeLabel->setText("");
total = 0;
filePara.numberSamples = 0;
filePara.sd = -1;
// wavFile->closeFile();
filePara.fd = 0;
// if(wavFile) delete wavFile; //this crashes
-// qDebug("track closed");
+// odebug << "track closed" << oendl;
killTimers();
- qWarning("reset slider");
+ owarn << "reset slider" << oendl;
timeSlider->setValue(0);
if(soundDevice) delete soundDevice;
}
bool QtRec::openPlayFile() {
qApp->processEvents();
if( currentFile.isEmpty()) {
QMessageBox::message(tr("Opierec"),tr("Please select file to play"));
endPlaying();
return false;
}
QString currentFileName;
Config cfg("OpieRec");
cfg.setGroup("Sounds");
int nFiles = cfg.readNumEntry( "NumberofFiles", 0);
for(int i=0;i<nFiles+1;i++) { //look for file
if( cfg.readEntry( QString::number(i),"").find( currentFile,0,true) != -1) {
currentFileName = cfg.readEntry( currentFile, "" );
- qDebug("opening for play: " + currentFileName);
+ odebug << "opening for play: " + currentFileName << oendl;
}
}
wavFile = new WavFile(this,
currentFileName,
false);
filePara.fd = wavFile->wavHandle();
if(filePara.fd == -1) {
// if(!track.open(IO_ReadOnly)) {
QString errorMsg = (QString)strerror(errno);
monitoring = false;
setCaption( tr( "OpieRecord " ) + QString::number(VERSION) );
QMessageBox::message(tr("Note"), tr("Could not open audio file.\n")
+ errorMsg + "\n" + currentFile);
return false;
} else {
filePara.numberSamples = wavFile->getNumberSamples();
filePara.format = wavFile->getFormat();
filePara.sampleRate = wavFile->getSampleRate();
filePara.resolution = wavFile->getResolution();
filePara.channels = wavFile->getChannels();
timeSlider->setPageStep(1);
monitoring = true;
- qDebug("file %d, samples %d %d", filePara.fd, filePara.numberSamples, filePara.sampleRate);
+ odebug << "file " << filePara.fd << ", samples " << filePara.numberSamples << " " << filePara.sampleRate << "" << oendl;
int sec = (int) (( filePara.numberSamples / filePara.sampleRate) / filePara.channels) / ( filePara.channels*( filePara.resolution/8));
- qWarning("seconds %d", sec);
+ owarn << "seconds " << sec << "" << oendl;
timeSlider->setRange(0, filePara.numberSamples );
}
return true;
}
void QtRec::listPressed( int mouse, QListViewItem *item, const QPoint &, int ) {
if(item == NULL )
return;
switch (mouse) {
case 1: {
if( renameBox != 0 ) //tricky
cancelRename();
currentFile = item->text(0);
setCaption( "OpieRecord " + currentFile);
}
break;
case 2:
showListMenu(item);
ListView1->clearSelection();
break;
};
}
void QtRec::showListMenu(QListViewItem * item) {
if(item == NULL)
return;
QPopupMenu *m = new QPopupMenu(this);
m->insertItem( tr("Play"), this, SLOT( doMenuPlay() ));
if(Ir::supported()) m->insertItem( tr( "Send with Ir" ), this, SLOT( doBeam() ));
m->insertItem( tr( "Rename" ), this, SLOT( doRename() ));
// #if defined (QTOPIA_INTERNAL_FSLP)
// m->insertItem( tr( "Properties" ), this, SLOT( doProperties() ));
// #endif
m->insertSeparator();
m->insertItem( tr("Delete"), this, SLOT( deleteSound() ) );
m->exec( QCursor::pos() );
qApp->processEvents();
}
void QtRec::fileBeamFinished( Ir *ir) {
if(ir)
QMessageBox::message( tr("Ir Beam out"), tr("Ir sent.") ,tr("Ok") );
}
void QtRec::doBeam() {
qApp->processEvents();
if( ListView1->currentItem() == NULL)
return;
Ir ir;
if( ir.supported()) {
QString file = ListView1->currentItem()->text(0);
Config cfg("OpieRec");
cfg.setGroup("Sounds");
int nFiles = cfg.readNumEntry("NumberofFiles",0);
for(int i=0;i<nFiles+1;i++) {
if( cfg.readEntry( QString::number( i),"").find( file, 0, true) != -1) {
QString filePath = cfg.readEntry(file,"");
Ir *file = new Ir(this, "IR");
connect( file, SIGNAL( done(Ir*)),
this, SLOT( fileBeamFinished(Ir*)));
file->send( filePath, "OPieRec audio file\n" + filePath );
}
}
}
}
void QtRec::doMenuPlay() {
qApp->processEvents();
currentFile = ListView1->currentItem()->text(0);
}
void QtRec::doRename() {
QRect r = ListView1->itemRect( ListView1->currentItem( ));
r = QRect( ListView1->viewportToContents( r.topLeft() ), r.size() );
r.setX( ListView1->contentsX() );
if ( r.width() > ListView1->visibleWidth() )
r.setWidth( ListView1->visibleWidth() );
renameBox = new QLineEdit( ListView1->viewport(), "qt_renamebox" );
renameBox->setFrame(true);
renameBox->setText( ListView1->currentItem()->text(0) );
renameBox->selectAll();
renameBox->installEventFilter( this );
ListView1->addChild( renameBox, r.x(), r.y() );
renameBox->resize( r.size() );
ListView1->viewport()->setFocusProxy( renameBox );
renameBox->setFocus();
renameBox->show();
}
void QtRec::okRename() {
- qDebug(renameBox->text());
+ odebug << renameBox->text() << oendl;
QString filename = renameBox->text();
cancelRename();
if( ListView1->currentItem() == NULL)
return;
Config cfg("OpieRec");
cfg.setGroup("Sounds");
QString file = ListView1->currentItem()->text(0);
- qDebug("filename is " + filename);
+ odebug << "filename is " + filename << oendl;
int nFiles = cfg.readNumEntry("NumberofFiles",0);
for(int i=0;i<nFiles+1;i++) { //look for file
if( cfg.readEntry( QString::number(i),"").find(file,0,true) != -1) {
QString filePath = cfg.readEntry(file,"");
cfg.writeEntry( QString::number(i), filename );
cfg.writeEntry( filename, filePath );
cfg.removeEntry( file);
cfg.write();
}
}
ListView1->takeItem( ListView1->currentItem() );
delete ListView1->currentItem();
ListView1->clear();
initIconView();
update();
}
void QtRec::cancelRename() {
bool resetFocus = ListView1->viewport()->focusProxy() == renameBox;
delete renameBox;
renameBox = 0;
if ( resetFocus ) {
ListView1->viewport()->setFocusProxy( ListView1 );
ListView1->setFocus();
}
}
bool QtRec::eventFilter( QObject * o, QEvent * e ) {
if ( o->inherits( "QLineEdit" ) ) {
if ( e->type() == QEvent::KeyPress ) {
QKeyEvent *ke = (QKeyEvent*)e;
if ( ke->key() == Key_Return ||
ke->key() == Key_Enter ) {
okRename();
return true;
} else if ( ke->key() == Key_Escape ) {
cancelRename();
return true;
}
} else if ( e->type() == QEvent::FocusOut ) {
cancelRename();
return true;
}
}
return QWidget::eventFilter( o, e );
}
int QtRec::getCurrentSizeLimit() {
return sizeLimitCombo->currentItem() * 5;
}
void QtRec::timerBreak() {
endPlaying();
}
void QtRec::doVolMuting(bool b) {
Config cfg( "qpe" );
cfg. setGroup( "Volume" );
cfg.writeEntry( "Mute",b);
cfg.write();
QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << b;
}
void QtRec::doMicMuting(bool b) {
- // qDebug("mic mute");
+ // odebug << "mic mute" << oendl;
Config cfg( "qpe" );
cfg. setGroup( "Volume" );
cfg.writeEntry( "MicMute",b);
cfg.write();
QCopEnvelope( "QPE/System", "micChange(bool)" ) << b;
}
void QtRec::compressionSelected(bool b) {
Config cfg("OpieRec");
cfg.setGroup("Settings");
cfg.writeEntry("wavCompression", b);
cfg.writeEntry("bitrate", 16);
filePara.resolution = 16;
cfg.write();
if(b) {
bitRateComboBox->setEnabled( false);
bitRateComboBox->setCurrentItem( 0);
filePara.resolution = 16;
} else{
bitRateComboBox->setEnabled( true);
}
}
long QtRec::checkDiskSpace(const QString &path) {
struct statfs fs;
if ( !statfs( path.latin1(), &fs ) ) {
int blkSize = fs.f_bsize;
int availBlks = fs.f_bavail;
long mult = blkSize / 1024;
long div = 1024 / blkSize;
if ( !mult ) mult = 1;
if ( !div ) div = 1;
return availBlks * mult / div;
}
return -1;
}
// short f_fstyp; /* File system type */
// long f_bsize; /* Block size */
// long f_frsize; /* Fragment size */
// long f_blocks; /* Total number of blocks*/
// long f_bfree; /* Count of free blocks */
// long f_files; /* Total number of file nodes */
// long f_ffree; /* Count of free file nodes */
// char f_fname[6]; /* Volumename */
// char f_fpack[6]; /* Pack name */
void QtRec::receive( const QCString &msg, const QByteArray & ) {
- qDebug("Voicerecord received message "+msg);
+ odebug << "Voicerecord received message "+msg << oendl;
}
///////////////////////////// timerEvent
void QtRec::timerEvent( QTimerEvent * ) {
// if(!recording)
// timeSlider->setValue( secCount);
// else
// timeSlider->setValue( filePara.numberOfRecordedSeconds);
if( stopped && playing) {
stop();
}
if( stopped && recording ){
stop();
}
if( recording && filePara.SecondsToRecord < secCount && filePara.SecondsToRecord != 0) {
stop();
}
- qDebug( "%d", secCount );
+ odebug << "" << secCount << "" << oendl;
QString timeString;
#ifdef DEV_VERSION
QString msg;
msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution);
setCaption( msg +" :: "+QString::number(secCount));
#endif
timeString.sprintf("%d", secCount);
timeLabel->setText( timeString + " seconds");
secCount++;
}
void QtRec::changeTimeSlider(int index) {
if( ListView1->currentItem() == 0 || !wavFile->track.isOpen()) return;
- // qDebug("Slider moved to %d",index);
+ // odebug << "Slider moved to " << index << "" << oendl;
paused = true;
stopped = true;
sliderPos=index;
QString timeString;
filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
secCount = (int)filePara.numberOfRecordedSeconds;
timeLabel->setText( timeString + tr(" seconds"));
}
void QtRec::timeSliderPressed() {
if( ListView1->currentItem() == 0) return;
- // qDebug("slider pressed");
+ // odebug << "slider pressed" << oendl;
paused = true;
stopped = true;
}
void QtRec::timeSliderReleased() {
if( ListView1->currentItem() == 0) return;
sliderPos = timeSlider->value();
- // qDebug("slider released %d", sliderPos);
+ // odebug << "slider released " << sliderPos << "" << oendl;
stopped = false;
int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
total = newPos*4;
filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
doPlay();
}
void QtRec::rewindPressed() {
if( ListView1->currentItem() == 0) return;
if( !wavFile->track.isOpen()) {
if( !openPlayFile() )
return;
else
if( !setupAudio( false))
return;
} else {
killTimers();
paused = true;
stopped = true;
rewindTimer->start( 50, false);
}
}
void QtRec::rewindTimerTimeout() {
int sliderValue = timeSlider->value();
sliderValue = sliderValue - ( filePara.numberSamples / 100);
// if(toBeginningButton->isDown())
timeSlider->setValue( sliderValue ) ;
- // qDebug("%d", sliderValue);
+ // odebug << "" << sliderValue << "" << oendl;
QString timeString;
filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2;
timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
timeLabel->setText( timeString+ tr(" seconds"));
}
void QtRec::rewindReleased() {
rewindTimer->stop();
if( wavFile->track.isOpen()) {
sliderPos=timeSlider->value();
stopped = false;
int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
total = newPos * 4;
- // qDebug("rewind released %d", total);
+ // odebug << "rewind released " << total << "" << oendl;
startTimer( 1000);
doPlay();
}
}
void QtRec::FastforwardPressed() {
if( ListView1->currentItem() == 0) return;
if( !wavFile->track.isOpen())
if( !openPlayFile() )
return;
else
if( !setupAudio( false))
return;
killTimers();
paused = true;
stopped = true;
forwardTimer->start(50, false);
}
void QtRec::forwardTimerTimeout() {
int sliderValue = timeSlider->value();
sliderValue = sliderValue + ( filePara.numberSamples / 100);
// if(toEndButton->isDown())
timeSlider->setValue( sliderValue);
QString timeString;
filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2;
timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
timeLabel->setText( timeString+ tr(" seconds"));
}
void QtRec::FastforwardReleased() {
forwardTimer->stop();
if( wavFile->track.isOpen()) {
sliderPos=timeSlider->value();
stopped = false;
int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
total = newPos * 4;
filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
startTimer( 1000);
doPlay();
}
}
QString QtRec::getStorage(const QString &fileName) {
StorageInfo storageInfo;
const QList<FileSystem> &fs = storageInfo.fileSystems();
QListIterator<FileSystem> it ( fs );
QString storage;
for( ; it.current(); ++it ){
const QString name = ( *it)->name();
const QString path = ( *it)->path();
const QString disk = ( *it)->disk();
if( fileName.find( path,0,true) != -1)
storage = name;
// const QString options = (*it)->options();
// if( name.find( tr("Internal"),0,true) == -1) {
// storageComboBox->insertItem( name +" -> "+disk);
- // qDebug(name);
+ // odebug << name << oendl;
}
return storage;
// struct mntent *me;
// // if(fileName == "/etc/mtab") {
// FILE *mntfp = setmntent( fileName.latin1(), "r" );
// if ( mntfp ) {
// while ( (me = getmntent( mntfp )) != 0 ) {
// QString filesystemType = me->mnt_type;
// }
// }
// endmntent( mntfp );
}
void QtRec::setRecordButton(bool b) {
if(b) { //about to record or play
Rec_PushButton->setDown( true);
QPixmap image3( ( const char** ) image3_data );
Stop_PushButton->setPixmap( image3 );
if(Stop_PushButton->isDown())
Stop_PushButton->setDown( true);
playLabel2->setText( tr("Stop") );
} else { //about to stop
QPixmap image4( ( const char** ) image4_data );
Stop_PushButton->setPixmap( image4);
if(Stop_PushButton->isDown())
Stop_PushButton->setDown( false);
playLabel2->setText( tr("Play") );
if(Rec_PushButton->isDown())
Rec_PushButton->setDown( false);
}
}
void QtRec::fillDirectoryCombo() {
if( directoryComboBox->count() > 0)
directoryComboBox->clear();
int index = 0;
Config cfg("OpieRec");
cfg.setGroup("Settings");
QString dir = cfg.readEntry("directory", "/");
StorageInfo storageInfo;
const QList<FileSystem> &fs = storageInfo.fileSystems();
QListIterator<FileSystem> it ( fs );
QString storage;
for( ; it.current(); ++it ){
const QString name = ( *it)->name();
const QString path = ( *it)->path();
// directoryComboBox->insertItem(name+" "+path);
directoryComboBox->insertItem(name);
if( path == dir)
directoryComboBox->setCurrentItem( index);
index++;
}
}
void QtRec::errorStop() {
stopped = true;
wavFile->closeFile();
killTimers();
}
void QtRec::doMute(bool b) {
doVolMuting( b);
doMicMuting( b);
}
void QtRec::slotAutoMute(bool b) {
autoMute = b;
Config cfg("OpieRec");
cfg.setGroup("Settings");
cfg.writeEntry("useAutoMute",b);
doMute( b);
outMuteCheckBox->setChecked( b);
inMuteCheckBox->setChecked( b);
}
void QtRec::selectItemByName(const QString & name) {
QListViewItemIterator it( ListView1 );
for ( ; it.current(); ++it )
if( name == it.current()->text(0))
ListView1->setCurrentItem(it.current());
}
// long findPeak(long input ) {
// // halfLife = time in seconds for output to decay to half value after an impulse
// static float output = 0.0;
// float halfLife = .0025;
// float vsf = .0025;
// float scalar = pow( 0.5, 1.0/(halfLife * filePara.sampleRate ));
// if( input < 0.0 )
diff --git a/noncore/multimedia/opierec/wavFile.cpp b/noncore/multimedia/opierec/wavFile.cpp
index 35bc14d..7e9b50f 100644
--- a/noncore/multimedia/opierec/wavFile.cpp
+++ b/noncore/multimedia/opierec/wavFile.cpp
@@ -1,311 +1,314 @@
//wavFile.cpp
#include "wavFile.h"
#include "qtrec.h"
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/config.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qmessagebox.h>
#include <qdir.h>
-#include <qpe/config.h>
-
+/* STD */
#include <errno.h>
-
#include <sys/time.h>
#include <sys/types.h>
#include <sys/vfs.h>
-
#include <fcntl.h>
#include <math.h>
#include <mntent.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
WavFile::WavFile( QObject * parent,const QString &fileName, bool makeNwFile, int sampleRate,
int channels, int resolution, int format )
: QObject( parent)
{
-//qDebug("new wave file");
+//odebug << "new wave file" << oendl;
bool b = makeNwFile;
wavSampleRate=sampleRate;
wavFormat=format;
wavChannels=channels;
wavResolution=resolution;
useTmpFile=false;
if( b) {
newFile();
} else {
openFile(fileName);
}
}
bool WavFile::newFile() {
-// qDebug("Set up new file");
+// odebug << "Set up new file" << oendl;
Config cfg("OpieRec");
cfg.setGroup("Settings");
currentFileName=cfg.readEntry("directory",QDir::homeDirPath());
QString date;
QDateTime dt = QDateTime::currentDateTime();
date = dt.toString();//TimeString::dateString( QDateTime::currentDateTime(),false,true);
date.replace(QRegExp("'"),"");
date.replace(QRegExp(" "),"_");
date.replace(QRegExp(":"),".");
date.replace(QRegExp(","),"");
QString currentFile=date;
if(currentFileName.right(1).find("/",0,true) == -1)
currentFileName += "/" + date;
else
currentFileName += date;
currentFileName+=".wav";
-// qDebug("set up file for recording: "+currentFileName);
+// odebug << "set up file for recording: "+currentFileName << oendl;
char pointer[] = "/tmp/opierec-XXXXXX";
int fd = 0;
if( currentFileName.find("/mnt",0,true) == -1
&& currentFileName.find("/tmp",0,true) == -1 ) {
// if destination file is most likely in flash (assuming jffs2)
// we have to write to a different filesystem first
useTmpFile = true;
if(( fd = mkstemp( pointer)) < 0 ) {
perror("mkstemp failed");
return false;
}
-// qDebug("Opening tmp file %s",pointer);
+// odebug << "Opening tmp file " << pointer << "" << oendl;
track.setName( pointer);
} else { //just use regular file.. no moving
useTmpFile = false;
track.setName( currentFileName);
}
if(!track.open( IO_ReadWrite | IO_Truncate)) {
QString errorMsg=(QString)strerror(errno);
- qDebug(errorMsg);
+ odebug << errorMsg << oendl;
QMessageBox::message("Note", "Error opening file.\n" +errorMsg);
return false;
} else {
setWavHeader( track.handle() , &hdr);
}
return true;
}
WavFile::~WavFile() {
closeFile();
}
void WavFile::closeFile() {
if(track.isOpen())
track.close();
}
int WavFile::openFile(const QString &currentFileName) {
-// qDebug("open play file "+currentFileName);
+// odebug << "open play file "+currentFileName << oendl;
closeFile();
track.setName(currentFileName);
if(!track.open(IO_ReadOnly)) {
QString errorMsg=(QString)strerror(errno);
- qDebug("<<<<<<<<<<< "+errorMsg+currentFileName);
+ odebug << "<<<<<<<<<<< "+errorMsg+currentFileName << oendl;
QMessageBox::message("Note", "Error opening file.\n" +errorMsg);
return -1;
} else {
parseWavHeader( track.handle());
}
return track.handle();
}
bool WavFile::setWavHeader(int fd, wavhdr *hdr) {
strncpy((*hdr).riffID, "RIFF", 4); // RIFF
strncpy((*hdr).wavID, "WAVE", 4); //WAVE
strncpy((*hdr).fmtID, "fmt ", 4); // fmt
(*hdr).fmtLen = 16; // format length = 16
if( wavFormat == WAVE_FORMAT_PCM) {
(*hdr).fmtTag = 1; // PCM
-// qDebug("set header WAVE_FORMAT_PCM");
+// odebug << "set header WAVE_FORMAT_PCM" << oendl;
}
else {
(*hdr).fmtTag = WAVE_FORMAT_DVI_ADPCM; //intel ADPCM
- // qDebug("set header WAVE_FORMAT_DVI_ADPCM");
+ // odebug << "set header WAVE_FORMAT_DVI_ADPCM" << oendl;
}
// (*hdr).nChannels = 1;//filePara.channels;// ? 2 : 1*/; // channels
(*hdr).nChannels = wavChannels;// ? 2 : 1*/; // channels
(*hdr).sampleRate = wavSampleRate; //samples per second
(*hdr).avgBytesPerSec = (wavSampleRate)*( wavChannels*(wavResolution/8)); // bytes per second
(*hdr).nBlockAlign = wavChannels*( wavResolution/8); //block align
(*hdr).bitsPerSample = wavResolution; //bits per sample 8, or 16
strncpy((*hdr).dataID, "data", 4);
write( fd,hdr, sizeof(*hdr));
qDebug("writing header: bitrate%d, samplerate %d, channels %d",
wavResolution, wavSampleRate, wavChannels);
return true;
}
bool WavFile::adjustHeaders(int fd, int total) {
lseek(fd, 4, SEEK_SET);
int i = total + 36;
write( fd, &i, sizeof(i));
lseek( fd, 40, SEEK_SET);
write( fd, &total, sizeof(total));
- qDebug("adjusting header %d", total);
+ odebug << "adjusting header " << total << "" << oendl;
return true;
}
int WavFile::parseWavHeader(int fd) {
- qDebug("Parsing wav header");
+ odebug << "Parsing wav header" << oendl;
char string[4];
int found;
short fmt;
unsigned short ch, bitrate;
unsigned long samplerrate, longdata;
if (read(fd, string, 4) < 4) {
- qDebug(" Could not read from sound file.\n");
+ odebug << " Could not read from sound file.\n" << oendl;
return -1;
}
if (strncmp(string, "RIFF", 4)) {
- qDebug(" not a valid WAV file.\n");
+ odebug << " not a valid WAV file.\n" << oendl;
return -1;
}
lseek(fd, 4, SEEK_CUR);
if (read(fd, string, 4) < 4) {
- qDebug("Could not read from sound file.\n");
+ odebug << "Could not read from sound file.\n" << oendl;
return -1;
}
if (strncmp(string, "WAVE", 4)) {
- qDebug("not a valid WAV file.\n");
+ odebug << "not a valid WAV file.\n" << oendl;
return -1;
}
found = 0;
while (!found) {
if (read(fd, string, 4) < 4) {
- qDebug("Could not read from sound file.\n");
+ odebug << "Could not read from sound file.\n" << oendl;
return -1;
}
if (strncmp(string, "fmt ", 4)) {
if (read(fd, &longdata, 4) < 4) {
- qDebug("Could not read from sound file.\n");
+ odebug << "Could not read from sound file.\n" << oendl;
return -1;
}
lseek(fd, longdata, SEEK_CUR);
} else {
lseek(fd, 4, SEEK_CUR);
if (read(fd, &fmt, 2) < 2) {
- qDebug("Could not read format chunk.\n");
+ odebug << "Could not read format chunk.\n" << oendl;
return -1;
}
if (fmt != WAVE_FORMAT_PCM && fmt != WAVE_FORMAT_DVI_ADPCM) {
qDebug("Wave file contains unknown format."
" Unable to continue.\n");
return -1;
}
wavFormat = fmt;
// compressionFormat=fmt;
- qDebug("compressionFormat is %d", fmt);
+ odebug << "compressionFormat is " << fmt << "" << oendl;
if (read(fd, &ch, 2) < 2) {
- qDebug("Could not read format chunk.\n");
+ odebug << "Could not read format chunk.\n" << oendl;
return -1;
} else {
wavChannels = ch;
- qDebug("File has %d channels", ch);
+ odebug << "File has " << ch << " channels" << oendl;
}
if (read(fd, &samplerrate, 4) < 4) {
- qDebug("Could not read from format chunk.\n");
+ odebug << "Could not read from format chunk.\n" << oendl;
return -1;
} else {
wavSampleRate = samplerrate;
// sampleRate = samplerrate;
- qDebug("File has samplerate of %d",(int) samplerrate);
+ odebug << "File has samplerate of " << (int) samplerrate << "" << oendl;
}
lseek(fd, 6, SEEK_CUR);
if (read(fd, &bitrate, 2) < 2) {
- qDebug("Could not read format chunk.\n");
+ odebug << "Could not read format chunk.\n" << oendl;
return -1;
} else {
wavResolution=bitrate;
// resolution = bitrate;
- qDebug("File has bitrate of %d", bitrate);
+ odebug << "File has bitrate of " << bitrate << "" << oendl;
}
found++;
}
}
found = 0;
while (!found) {
if (read(fd, string, 4) < 4) {
- qDebug("Could not read from sound file.\n");
+ odebug << "Could not read from sound file.\n" << oendl;
return -1;
}
if (strncmp(string, "data", 4)) {
if (read(fd, &longdata, 4)<4) {
- qDebug("Could not read from sound file.\n");
+ odebug << "Could not read from sound file.\n" << oendl;
return -1;
}
lseek(fd, longdata, SEEK_CUR);
} else {
if (read(fd, &longdata, 4) < 4) {
- qDebug("Could not read from sound file.\n");
+ odebug << "Could not read from sound file.\n" << oendl;
return -1;
} else {
wavNumberSamples = longdata;
qDebug("file has length of %d \nlasting %d seconds", (int)longdata,
(int)(( longdata / wavSampleRate) / wavChannels) / ( wavChannels*( wavResolution/8)) );
// wavSeconds = (( longdata / wavSampleRate) / wavChannels) / ( wavChannels*( wavResolution/8));
return longdata;
}
}
}
lseek(fd, 0, SEEK_SET);
return 0;
}
QString WavFile::trackName() {
return track.name();
}
int WavFile::wavHandle(){
return track.handle();
}
int WavFile::getFormat() {
return wavFormat;
}
int WavFile::getResolution() {
return wavResolution;
}
int WavFile::getSampleRate() {
return wavSampleRate;
}
int WavFile::getNumberSamples() {
return wavNumberSamples;
}
bool WavFile::isTempFile() {
return useTmpFile;
}
int WavFile::getChannels() {
return wavChannels;
}
diff --git a/noncore/multimedia/opierec/waveform.cpp b/noncore/multimedia/opierec/waveform.cpp
index 9cc40b4..7c9a25f 100644
--- a/noncore/multimedia/opierec/waveform.cpp
+++ b/noncore/multimedia/opierec/waveform.cpp
@@ -1,159 +1,163 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "waveform.h"
-#include <qpainter.h>
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+/* QT */
+#include <qpainter.h>
Waveform::Waveform( QWidget *parent, const char *name, WFlags fl )
: QWidget( parent, name, fl )
{
pixmap = 0;
windowSize = 100;
samplesPerPixel = 8000 / (5 * windowSize);
currentValue = 0;
numSamples = 0;
windowPosn = 0;
window = 0;
}
void Waveform::changeSettings( int frequency, int channels )
{
makePixmap();
-// qWarning("change waveform %d, %d", frequency, channels);
+// owarn << "change waveform " << frequency << ", " << channels << "" << oendl;
samplesPerPixel = frequency * channels / (5 * windowSize);
- qWarning("Waveform::changeSettings %d", samplesPerPixel);
+ owarn << "Waveform::changeSettings " << samplesPerPixel << "" << oendl;
if ( !samplesPerPixel )
samplesPerPixel = 1;
currentValue = 0;
numSamples = 0;
windowPosn = 0;
draw();
}
Waveform::~Waveform()
{
if ( window )
delete[] window;
if ( pixmap )
delete pixmap;
}
void Waveform::reset()
{
makePixmap();
currentValue = 0;
numSamples = 0;
windowPosn = 0;
draw();
}
void Waveform::newSamples( const short *buf, int len )
{
// Cache the object values in local variables.
int samplesPerPixel = this->samplesPerPixel;
int currentValue = this->currentValue;
int numSamples = this->numSamples;
short *window = this->window;
int windowPosn = this->windowPosn;
int windowSize = this->windowSize;
// Average the incoming samples to scale them to the window.
while ( len > 0 ) {
currentValue += *buf++;
--len;
if ( ++numSamples >= samplesPerPixel ) {
window[windowPosn++] = (short)(currentValue / numSamples);
if ( windowPosn >= windowSize ) {
this->windowPosn = windowPosn;
draw();
windowPosn = 0;
}
numSamples = 0;
currentValue = 0;
}
}
// Copy the final state back to the object.
-//qWarning("%d, %d, %d", currentValue, numSamples, windowPosn);
+//owarn << "" << currentValue << ", " << numSamples << ", " << windowPosn << "" << oendl;
this->currentValue = currentValue;
this->numSamples = numSamples;
this->windowPosn = windowPosn;
}
void Waveform::makePixmap()
{
if ( !pixmap ) {
pixmap = new QPixmap( size() );
windowSize = pixmap->width();
window = new short [windowSize];
}
}
void Waveform::draw()
{
pixmap->fill( Qt::black );
QPainter painter;
painter.begin( pixmap );
painter.setPen( Qt::green );
int middle = pixmap->height() / 2;
int mag;
short *window = this->window;
int posn;
int size = windowPosn;
for( posn = 0; posn < size; ++posn )
{
mag = (window[posn] * middle / 32768);
painter.drawLine(posn, middle - mag, posn, middle + mag);
}
if ( windowPosn < windowSize )
{
painter.drawLine(windowPosn, middle, windowSize, middle);
}
painter.end();
paintEvent( 0 );
}
void Waveform::paintEvent( QPaintEvent * )
{
QPainter painter;
painter.begin( this );
if ( pixmap ) {
painter.drawPixmap( 0, 0, *pixmap );
} else {
painter.setPen( Qt::green );
QSize sz = size();
painter.drawLine(0, sz.height() / 2, sz.width(), sz.height() / 2);
}
painter.end();
}
diff --git a/noncore/multimedia/powerchord/config.in b/noncore/multimedia/powerchord/config.in
index ab1512b..5db784a 100644
--- a/noncore/multimedia/powerchord/config.in
+++ b/noncore/multimedia/powerchord/config.in
@@ -1,7 +1,7 @@
config POWERCHORD
boolean "opie-powerchord (guitar chord generator and tuning)"
default "n"
- depends ( LIBQPE || LIBQPE-X11 )
- comment "opie-powerchord needs a libqpe"
- depends !(( LIBQPE || LIBQPE-X11 ) )
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
+ comment "opie-powerchord needs a libqpe and libopiecore2"
+ depends !(( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE )
diff --git a/noncore/multimedia/powerchord/powerchord.pro b/noncore/multimedia/powerchord/powerchord.pro
index 917c88f..f7af6d6 100644
--- a/noncore/multimedia/powerchord/powerchord.pro
+++ b/noncore/multimedia/powerchord/powerchord.pro
@@ -1,27 +1,26 @@
TEMPLATE = app
CONFIG = qt warn_on
HEADERS = powerchord.h \
fretboard.h \
chordengine.h \
vumeter.h \
gs.h gt.h \
powerchordbase.h
SOURCES = main.cpp \
powerchord.cpp \
fretboard.cpp \
chordengine.cpp \
vumeter.cpp \
gs.cpp gt.cpp \
powerchordbase.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe
-#INTERFACES = powerchordbase.ui
+LIBS += -lqpe -lopiecore2
DESTDIR = $(OPIEDIR)/bin
TARGET = powerchord
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/multimedia/powerchord/powerchordbase.cpp b/noncore/multimedia/powerchord/powerchordbase.cpp
index 4fb5dda..0694ba3 100644
--- a/noncore/multimedia/powerchord/powerchordbase.cpp
+++ b/noncore/multimedia/powerchord/powerchordbase.cpp
@@ -1,118 +1,122 @@
/****************************************************************************
** Form implementation generated from reading ui file 'powerchordbase.ui'
**
** Created: Sun Jan 13 23:05:11 2002
** by: The User Interface Compiler (uic)
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/
#include "powerchordbase.h"
-
#include "fretboard.h"
#include "vumeter.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/resource.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qcombobox.h>
#include <qlabel.h>
#include <qlistbox.h>
#include <qpushbutton.h>
#include <qspinbox.h>
#include <qtabwidget.h>
#include <qlayout.h>
#include <qtooltip.h>
-#include <qpe/resource.h>
-
/*
* Constructs a PowerchordBase which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*/
PowerchordBase::PowerchordBase( QWidget* parent, const char* name, WFlags fl )
: QWidget( parent, name, fl )
{
simulation_timer = 0;
audio_timer = 0;
// setPalette( QPalette( QColor( 232, 227, 215) ) );
// QPixmap image0(QString("/opt/Qtopia/pics/powerchord/image0"));
QPixmap image1 = Resource::loadPixmap( "powerchord/image1");
QPixmap image2 = Resource::loadPixmap( "powerchord/image2");
QPixmap image3 = Resource::loadPixmap( "powerchord/image3");
QPixmap image4 = Resource::loadPixmap( "powerchord/image4");
QPixmap image5 = Resource::loadPixmap( "powerchord/image5");
image6 = Resource::loadPixmap( "powerchord/image6");
image_open = Resource::loadPixmap( "powerchord/image_open");
// image0.setMask(image0.createHeuristicMask());
image1.setMask(image1.createHeuristicMask());
// image2.setMask(image2.createHeuristicMask());
// image3.setMask(image3.createHeuristicMask());
// image4.setMask(image4.createHeuristicMask());
// image5.setMask(image5.createHeuristicMask());
// image6->setMask(image6->createHeuristicMask());
// image_open->setMask(image_open->createHeuristicMask());
if ( !name )
setName( "PowerchordBase" );
resize( 240, 284 );
setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)5, sizePolicy().hasHeightForWidth() ) );
setMinimumSize( QSize( 240, 284 ) );
setMaximumSize( QSize( 240, 284 ) );
setCaption( tr( "Powerchord" ) );
tabs = new QTabWidget( this, "tabs" );
tabs->setEnabled( TRUE );
tabs->setGeometry( QRect( 0, 0, 240, 286 ) );
tabs->setTabPosition( QTabWidget::Bottom );
tab = new QWidget( tabs, "tab" );
chordkey = new QComboBox( FALSE, tab, "chordkey" );
chordkey->insertItem( tr( "maj" ) );
chordkey->insertItem( tr( "min" ) );
chordkey->insertItem( tr( "7th" ) );
chordkey->insertItem( tr( "m7" ) );
chordkey->insertItem( tr( "maj7" ) );
chordkey->insertItem( tr( "6th" ) );
chordkey->insertItem( tr( "m6th" ) );
chordkey->insertItem( tr( "aug" ) );
chordkey->insertItem( tr( "dim" ) );
chordkey->insertItem( tr( "sus4" ) );
chordkey->insertItem( tr( "7sus4" ) );
chordkey->insertItem( tr( "9th" ) );
chordkey->insertItem( tr( "add9" ) );
chordkey->insertItem( tr( "m9th" ) );
chordkey->insertItem( tr( "maj9" ) );
chordkey->insertItem( tr( "sus2" ) );
chordkey->insertItem( tr( "7sus2" ) );
chordkey->insertItem( tr( "11th" ) );
chordkey->insertItem( tr( "m11th" ) );
chordkey->insertItem( tr( "13th" ) );
chordkey->insertItem( tr( "m13th" ) );
chordkey->insertItem( tr( "maj13" ) );
chordkey->insertItem( tr( "6/9" ) );
chordkey->insertItem( tr( "flat5" ) );
chordkey->insertItem( tr( "7#9" ) );
chordkey->insertItem( tr( QString::fromUtf8( "ø7" ) ) );
chordkey->insertItem( tr( "5" ) );
chordkey->setGeometry( QRect( 40, 0, 51, 21 ) );
chordfret = new QComboBox( FALSE, tab, "chordfret" );
chordfret->insertItem( tr( "open" ) );
chordfret->insertItem( tr( "1st" ) );
chordfret->insertItem( tr( "2nd" ) );
chordfret->insertItem( tr( "3rd" ) );
chordfret->insertItem( tr( "4th" ) );
chordfret->insertItem( tr( "5th" ) );
chordfret->insertItem( tr( "6th" ) );
chordfret->insertItem( tr( "7th" ) );
chordfret->insertItem( tr( "8th" ) );
chordfret->insertItem( tr( "9th" ) );
chordfret->insertItem( tr( "10th" ) );
chordfret->insertItem( tr( "11th" ) );
chordfret->insertItem( tr( "12th" ) );
chordfret->insertItem( tr( "13th" ) );
chordfret->insertItem( tr( "14th" ) );
chordfret->insertItem( tr( "15th" ) );
chordfret->insertItem( tr( "16th" ) );
chordfret->setGeometry( QRect( 90, 0, 55, 21 ) ); //cxm less 5 width
@@ -487,99 +491,99 @@ void PowerchordBase::audio_cb(){
// the real tuner
// void PowerchordBase::tuner_start_cb(){
// if (tuner->Listening()){
// simulation_timer->stop();
// tuner->Stop();
// tuner_pic1->setPixmap( *image6 );
// }else{
// tuner_pic1->setPixmap( *image_open );
// if (!simulation_timer){
// simulation_timer = new QTimer();
// connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_cb() ));
// }
// simulation_timer->start(50);
// tuner->Listen();
// }
// }
void PowerchordBase::tuner_cb(){
if (tuner->Listening()){
tuner->read_buffer();
tuner->process_buffer();
// update gui
// do something with the note: tuner->Note()
emit frequency_change(tuner->Tuning());
}else{
simulation_timer->stop();
tuner->Stop();
tuner_pic1->setPixmap( image6 );
}
}
void PowerchordBase::tuner_start_cb(){
if (0 == QMessageBox::information(this, "Powerchord", "Using the microphone,\nthe note's frequency\nis analysed. This\nis a simulation.", "OK", "Cancel", 0, 1)){
if (simulation_timer){
simulation_timer->stop();
}else{
simulation_timer = new QTimer();
connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_simulation_cb() ));
}
simulation_x = -45;
simulation_v = 0;
simulation_iter = 0;
tuner_pic1->setPixmap( image_open );
simulation_timer->start(100);
}
}
#include <stdio.h>
void PowerchordBase::tuner_simulation_cb(){
if (simulation_x < -10 || simulation_x > 10){
simulation_v = (simulation_v/2)-(simulation_x/5);
}
simulation_x += simulation_v;
simulation_iter++;
if (simulation_x > 50){
simulation_x = 50;
}
if (simulation_x < -50){
simulation_x = -50;
}
if (simulation_iter > 50){
simulation_timer->stop();
emit frequency_change(0);
tuner_pic1->setPixmap( image6 );
}else{
emit frequency_change(simulation_x);
}
}
/*
* Destroys the object and frees any allocated resources
*/
PowerchordBase::~PowerchordBase()
{
// no need to delete child widgets, Qt does it all for us
}
void PowerchordBase::change_handler()
{
- qWarning( "PowerchordBase::change_handler(): Not implemented yet!" );
+ owarn << "PowerchordBase::change_handler(): Not implemented yet!" << oendl;
}
diff --git a/noncore/multimedia/showimg/ImageFileSelector.cpp b/noncore/multimedia/showimg/ImageFileSelector.cpp
index 79ee925..53cc883 100644
--- a/noncore/multimedia/showimg/ImageFileSelector.cpp
+++ b/noncore/multimedia/showimg/ImageFileSelector.cpp
@@ -1,260 +1,262 @@
+#include "ImageFileSelector.h"
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
-#include "qpe/qpeapplication.h"
-
-#include <stdlib.h>
-
-#include <qlabel.h>
+/* QT */
+#include <qlabel.h>
#include <qfileinfo.h>
-#include "ImageFileSelector.h"
-
+/* STD */
+#include <stdlib.h>
ThumbWidget::ThumbWidget(QPixmap p,QString text,const DocLnk& f,QWidget *parent,int w)
: QWidget( parent ),fl(f)
{
setBackgroundMode(NoBackground);
if ( w!=-1 )
setMinimumSize(w,p.height()+24);
else
setMinimumSize(p.width(),p.height()+24);
description=new QLabel(text,this);
description->setBackgroundColor(colorGroup().base());
description->setAlignment(AlignCenter);
description->setGeometry(0,height()-24,width(),24);
pixmap=p;
}
void ThumbWidget::resizeEvent(QResizeEvent *)
{
description->setGeometry(0,height()-24,width(),24);
}
void ThumbWidget::paintEvent( QPaintEvent *e )
{
QPainter painter(this);
painter.setClipRect(e->rect());
painter.fillRect(0,0,width(),height(),QColor(255,255,255));
painter.drawPixmap((width() - pixmap.width()) / 2,0, pixmap);
}
void ThumbWidget::mouseReleaseEvent(QMouseEvent* )
{
emit clicked(fl);
}
ImageFileSelectorItem::ImageFileSelectorItem( QListView *parent, const DocLnk &f)
: QListViewItem( parent ), fl( f )
{
setText( 0, f.name() );
QFileInfo fi(f.file());
setText( 1, (fi.extension()).upper() );
setPixmap( 0, f.pixmap() );
}
ImageFileSelectorItem::~ImageFileSelectorItem()
{
}
ImageFileSelector::ImageFileSelector( CURRENT_VIEW scv,QWidget *parent,const char * )
: QWidgetStack(parent)
{
detailed=new QListView(this);
detailed->addColumn (tr("Title"));
detailed->addColumn (tr("Type"));
detailed->setAllColumnsShowFocus( true );
tList.setAutoDelete(true);
thumb =new QScrollView(this);
thumb->setVScrollBarMode (QScrollView::Auto );
thumb->viewport()->setBackgroundColor(colorGroup().base());
background=new QWidget(0);
background->setBackgroundColor(colorGroup().base());
thumb->addChild(background);
gl = new QGridLayout(background,1,2,4,4);
connect( detailed, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),
this, SLOT( fileClicked(int,QListViewItem*,const QPoint&,int) ) );
connect( detailed, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
this, SLOT( filePressed(int,QListViewItem*,const QPoint&,int) ) );
connect( detailed, SIGNAL( returnPressed(QListViewItem*) ),
this, SLOT( fileClicked(QListViewItem*) ) );
cView=UNKNOWN;
setView(scv);
reread();
}
ImageFileSelector::~ImageFileSelector()
{
}
void ImageFileSelector::switchView()
{
CURRENT_VIEW v=cView;
if ( v==DETAILED )
v=THUMBNAIL;
else
v=DETAILED;
setView(v);
}
void ImageFileSelector::setView(CURRENT_VIEW v)
{
if ( v==cView )
return;
cView=v;
if ( cView!=DETAILED )
{
raiseWidget(thumb);
updateSizes();
}
else
{
raiseWidget(detailed);
updateSizes();
}
}
void ImageFileSelector::resizeEvent(QResizeEvent *)
{
updateSizes();
}
void ImageFileSelector::updateSizes()
{
int ww=(detailed->width()-detailed->frameWidth()*2);
double w=(double)ww*0.70;
detailed->setColumnWidth(0,(int)w);
detailed->setColumnWidth(1,ww-(int)w);
background->setMinimumWidth(thumb->visibleWidth());
thumb->updateScrollBars();
}
void ImageFileSelector::reread(bool)
{
-// qDebug("reread");
+// odebug << "reread" << oendl;
ImageFileSelectorItem *item = (ImageFileSelectorItem *)detailed->selectedItem();
QString oldFile;
if ( item )
oldFile = item->file().file();
detailed->clear();
tList.clear();
DocLnkSet files;
Global::findDocuments(&files, "image/*");
count = files.children().count();
QListIterator<DocLnk> dit( files.children() );
// int y=0;
// int x=4;
// int totalHeight=4;
ThumbWidget *l=0;
int width=80;
gl->expand(dit.count()/2,2);
int i,j;
i=j=0;
detailed->setUpdatesEnabled(false);
thumb->setUpdatesEnabled(false);
for ( ; dit.current(); ++dit ) {
item = new ImageFileSelectorItem( detailed, **dit );
if ( item->file().file() == oldFile )
detailed->setCurrentItem( item );
}
QListViewItemIterator it( detailed );
ImageFileSelectorItem *ii;
// iterate through all items of the listview
for ( ; it.current(); ++it ) {
ii=(ImageFileSelectorItem *)it.current();
QImage img( ii->file().file() );
if( !img.isNull()) {
img=img.smoothScale(64,64);
QPixmap pix;
pix.convertFromImage(img);
l=new ThumbWidget(pix,ii->file().name(),ii->file(),background,width);
l->setBackgroundColor(colorGroup().base());
gl->addWidget(l,j,i);
i++;
if ( i==2 ) {
i=0;
j++;
}
tList.append(l);
connect(l,SIGNAL(clicked(const DocLnk&)),this,SLOT(thumbClicked(const DocLnk&)));
}
}
if ( !detailed->selectedItem() )
detailed->setCurrentItem( detailed->firstChild() );
detailed->setUpdatesEnabled(true);
thumb->setUpdatesEnabled(true);
detailed->update();
thumb->update();
}
int ImageFileSelector::fileCount()
{
return count;
}
const DocLnk * ImageFileSelector::selected()
{
- qDebug("image selected");
+ odebug << "image selected" << oendl;
ImageFileSelectorItem *item = (ImageFileSelectorItem *) detailed->selectedItem();
if ( item )
return new DocLnk( item->file() );
return 0;
}
void ImageFileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int )
{
if ( !i )
return;
if ( button == Qt::LeftButton )
{
fileClicked( i );
}
}
// pressed to get 'right down'
void ImageFileSelector::filePressed( int, QListViewItem *, const QPoint &, int )
{
}
void ImageFileSelector::fileClicked( QListViewItem *i)
{
if ( !i )
return;
emit fileSelected( ( (ImageFileSelectorItem*)i )->file() );
emit closeMe();
}
void ImageFileSelector::thumbClicked(const DocLnk &f)
{
emit fileSelected( f );
emit closeMe();
}
diff --git a/noncore/multimedia/showimg/showimg.cpp b/noncore/multimedia/showimg/showimg.cpp
index 696a57b..24377ed 100644
--- a/noncore/multimedia/showimg/showimg.cpp
+++ b/noncore/multimedia/showimg/showimg.cpp
@@ -1,141 +1,143 @@
/**********************************************************************
** 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"
-
+/* OPIE */
+#include <opie2/odebug.h>
#include <opie2/ofiledialog.h>
-
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include <qpe/resource.h>
-#include <qtoolbar.h>
+using namespace Opie::Core;
+using namespace Opie::Ui;
+/* QT */
+#include <qtoolbar.h>
#include <qaction.h>
#include <qfiledialog.h>
#include <qmenubar.h>
#include <qspinbox.h>
+/* STD */
#include <math.h>
-
-using namespace Opie::Ui;
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++;
}
}
}
@@ -193,442 +195,442 @@ void ImageWidget::paintEvent( QPaintEvent *e )
}
}
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 QToolBar( this );
toolBar->setHorizontalStretchable( TRUE );
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);
+ odebug << "cv = " << cv << "" << oendl;
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 QToolBar(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("<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>");
+ odebug << "<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>" << oendl;
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);
+// odebug << "Show "+fileref << oendl;
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());
+ odebug << "open "+link.name() << oendl;
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();
}
diff --git a/noncore/multimedia/showimg/showimg.pro b/noncore/multimedia/showimg/showimg.pro
index 6fd019e..c905da8 100644
--- a/noncore/multimedia/showimg/showimg.pro
+++ b/noncore/multimedia/showimg/showimg.pro
@@ -1,9 +1,9 @@
-CONFIG += qt warn_on quick-app
+CONFIG += qt warn_on quick-app
HEADERS = showimg.h ImageFileSelector.h settingsdialog.h settingsdialogbase.h
SOURCES = main.cpp showimg.cpp ImageFileSelector.cpp settingsdialog.cpp settingsdialogbase.cpp
TARGET = showimg
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
LIBS += -lqpe -lopiecore2 -lopieui2
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/multimedia/tonleiter/config.in b/noncore/multimedia/tonleiter/config.in
index d580ad7..9bd167e 100644
--- a/noncore/multimedia/tonleiter/config.in
+++ b/noncore/multimedia/tonleiter/config.in
@@ -1,4 +1,4 @@
config TONLEITER
boolean "tonleiter (shows scales on sting instruments)"
default "n"
- depends ( LIBQPE || LIBQPE-X11 )
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
diff --git a/noncore/multimedia/tonleiter/editinst.cpp b/noncore/multimedia/tonleiter/editinst.cpp
index ccb4560..a8c20c8 100644
--- a/noncore/multimedia/tonleiter/editinst.cpp
+++ b/noncore/multimedia/tonleiter/editinst.cpp
@@ -1,110 +1,115 @@
#include "editinst.h"
-#include <qpushbutton.h>
-
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/config.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
+
+/* QT */
+#include <qpushbutton.h>
Menu::InstEditDialog::InstEditDialog(TonleiterData* data,QWidget* parent,const char* name)
:QDialog(parent,name,true,0),data(data)
{
setCaption("Tonleiter::"+tr("Instrument"));
QBoxLayout* masterlayout=new QBoxLayout(this,QBoxLayout::TopToBottom);
instid=data->getCurrentInstrumentID();
stringlist.setAutoDelete(true);
QBoxLayout* toplayout=new QBoxLayout(masterlayout,QBoxLayout::LeftToRight);
//Name combo + Add + Delete
boxInst=new QComboBox(this,"boxInst");
boxInst->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Maximum));
connect(boxInst,SIGNAL(activated(int)),this,SLOT(setCurrentInstrumetID(int)));
for(int i=0;i<data->noOfInstruments();i++)
{
Instrument inst=data->getInstrument(i);
QString name=inst.instName();
if(name.isNull()) continue;
boxInst->insertItem(name,i);
}
boxInst->setCurrentItem(instid);
toplayout->addWidget(boxInst);
QPushButton* addButton=new QPushButton(tr("Add"),this,"addButton");
connect(addButton,SIGNAL(pressed()),this,SLOT(addInstrument()));
toplayout->addWidget(addButton);
QPushButton* delButton=new QPushButton(tr("Delete"),this,"delButton");
connect(delButton,SIGNAL(pressed()),this,SLOT(deleteInstrument()));
toplayout->addWidget(delButton);
QPushButton* addhighButton=new QPushButton(tr("Add High String"),this,"addhighButton");
masterlayout->addWidget(addhighButton);
scrollview=new QScrollView(this);
scrollview->setVScrollBarMode(QScrollView::AlwaysOn);
scrollview->setHScrollBarMode(QScrollView::AlwaysOff);
stringwidget=new QVBox(scrollview->viewport());
stringwidget->setSizePolicy(QSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum));
stringwidget->setSpacing(10);
scrollview->addChild(stringwidget);
scrollview->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Maximum));
masterlayout->addWidget(scrollview);
loadInstrument();
QPushButton* addlowButton=new QPushButton(tr("Add Low String"),this,"addlowButton");
masterlayout->addWidget(addlowButton);
//make dialog fit the screen
QPEApplication::showDialog( this );
}
//****************************************************************************
Menu::InstEditDialog::~InstEditDialog()
{
}
//****************************************************************************
void Menu::InstEditDialog::setCurrentInstrumetID(int id)
{
saveInstrument();
instid=id;
data->setCurrentInstrumetID(id);
loadInstrument();
}
//****************************************************************************
void Menu::InstEditDialog::addInstrument()
{
}
//****************************************************************************
void Menu::InstEditDialog::deleteInstrument()
{
}
//****************************************************************************
void Menu::InstEditDialog::addLowString()
{
}
//****************************************************************************
void Menu::InstEditDialog::addHighString()
{
}
//****************************************************************************
void Menu::InstEditDialog::deleteString(int id)
{
}
//****************************************************************************
void Menu::InstEditDialog::saveInstrument()
{
//auto delete is set to true so widgets _should_ be deleted
stringlist.clear();
}
//****************************************************************************
void Menu::InstEditDialog::loadInstrument()
{
stringlist.clear();
Instrument inst=data->getInstrument(instid);
- qDebug("load Instrument : %d strings",inst.noOfStrings());
+ odebug << "load Instrument : " << inst.noOfStrings() << " strings" << oendl;
for(uint s=0;s<inst.noOfStrings();s++)
{
stringlist.append(new EditStringWidget(inst.string(s),stringwidget));
}
}
//****************************************************************************
//****************************************************************************
diff --git a/noncore/multimedia/tonleiter/fretboard.cpp b/noncore/multimedia/tonleiter/fretboard.cpp
index 7e63e01..58bdb86 100644
--- a/noncore/multimedia/tonleiter/fretboard.cpp
+++ b/noncore/multimedia/tonleiter/fretboard.cpp
@@ -1,186 +1,191 @@
#include "fretboard.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qpainter.h>
Graph::FretBoard::FretBoard(TonleiterData* data,QWidget* parent,const char* name,WFlags f)
:QWidget(parent,name,f),data(data)
{
setBackgroundColor(QColor(0,0,0));
fretpen=QPen(QColor(155,155,155),0);
markerbrush=QBrush(QColor(155,155,155));
stringpen=QPen(QColor(255,255,255),3);
connect(data,SIGNAL(dataChange()),this,SLOT(dataChange()));
}
//****************************************************************************
Graph::FretBoard::~FretBoard()
{
}
//****************************************************************************
void Graph::FretBoard::dataChange()
{
repaint(true);
}
//****************************************************************************
void Graph::FretBoard::paintEvent(QPaintEvent* pe)
{
Q_UNUSED(pe);
int instid=data->getCurrentInstrumentID();
inst=data->getInstrument(instid);
- //qDebug("inst %d is %s",instid,inst.instName().data());
+ //odebug << "inst " << instid << " is " << inst.instName().data() << "" << oendl;
QRect mysize=rect();
xmargin=(int)(mysize.width()*0.05);
xmin=2*xmargin;
xmax=mysize.width()-xmargin;
xwidth=xmax-xmin;
ymargin=(int)(mysize.height()*0.1);
ymin=ymargin;
ymax=mysize.height()-2*ymargin;
yheight=ymax-ymin;
QPainter p(this);
paintBoard(&p);
paintFrets(&p);
paintStrings(&p);
paintScale(&p);
}
//****************************************************************************
void Graph::FretBoard::resizeEvent(QResizeEvent* re)
{
Q_UNUSED(re);
}
//****************************************************************************
void Graph::FretBoard::mouseReleaseEvent(QMouseEvent* me)
{
Q_UNUSED(me);
emit pressed();
}
//****************************************************************************
void Graph::FretBoard::paintBoard(QPainter* p)
{
//debug
QColor bgc=QColor(142,138,120);
p->setPen(QPen(bgc,5));
p->setBrush(QBrush(bgc));
p->drawRect(xmin,ymin,xwidth,yheight);
}
//****************************************************************************
void Graph::FretBoard::paintFrets(QPainter* p)
{
//draw frets
p->setPen(fretpen);
p->setBrush(markerbrush);
fretdist=(double)(xwidth)/(double)(inst.noOfFrets());
int markerwidth = (int)(fretdist/4.0);
if(markerwidth>5)
markerwidth=5;
else if(markerwidth<2)
markerwidth=2;
for(int f=0;f<=inst.noOfFrets();f++)
{
int fretpos=(int)(fretdist*f);
p->drawLine(fretpos+xmin,ymin,fretpos+xmin,ymax);
int above_octave=f%12;
int octave=(f-above_octave)/12;
int marker=f-12*octave;
if(marker==5 || marker==7 || marker==9)
{
p->drawEllipse(fretpos+xmin,ymax+ymargin,markerwidth,markerwidth);
}
else if(marker==0 && f!=0)
{
p->drawEllipse(fretpos+xmin,ymax+ymargin+2*markerwidth,markerwidth,markerwidth);
p->drawEllipse(fretpos+xmin,ymax+ymargin-2*markerwidth,markerwidth,markerwidth);
}
}
}
//****************************************************************************
void Graph::FretBoard::paintStrings(QPainter* p)
{
//draw strings
p->setPen(stringpen);
stringdist=(double)(yheight)/(double)(inst.noOfStrings()-1);
for(int s=0;s<inst.noOfStrings();s++)
{
int stringpos=(int)(stringdist*s);
p->drawLine(xmin,stringpos+ymin,xmax,stringpos+ymin);
int stinglabelid=inst.noOfStrings()-(s+1);
QString label=Note::getNameOfNote(inst.string(stinglabelid));
p->drawText(xmargin/2,stringpos+ymin,label);
}
}
//****************************************************************************
void Graph::FretBoard::paintScale(QPainter* p)
{
int dotsize=10;
int scaleid=data->getCurrentScaleID();
Scale scale=data->getScale(scaleid);
int baseoctave=Note::octaveOfBaseNote(data->getCurrentBaseNote(),inst.lowestNote());
for(int s=0;s<inst.noOfStrings();s++)
{
int y=(int)(stringdist*s)+ymin;
int stingid=inst.noOfStrings()-(s+1);
for(int f=0;f<=inst.noOfFrets();f++)
{
int note=inst.string(stingid)+f;
if(scale.noteInScale(data->getCurrentBaseNote(),note))
{
int x=(int)(fretdist*f)+xmin;
//no more than six octaves can be visualised (there is a zero octave)
int octave=Note::octaveOfBaseNote(data->getCurrentBaseNote(),note)-baseoctave;
if(octave<0)
- qDebug("%d,%d",octave,baseoctave);
+ odebug << "" << octave << "," << baseoctave << "" << oendl;
if(octave>5)
{
- qDebug("octave out of range");
+ odebug << "octave out of range" << oendl;
octave=5;
}
p->setPen(QColor(255,0,0));
int c= ( (note-12*baseoctave) - (12*octave+data->getCurrentBaseNote()) )*15;
if(c<0 || c>255)
- qDebug("%d = %d - ( %d + %d)",c,note,12*octave,data->getCurrentBaseNote());
+ odebug << "" << c << " = " << note << " - ( " << 12*octave << " + " << data->getCurrentBaseNote() << ")" << oendl;
QColor dotcolor(255,255,255);
if(octave==0)
dotcolor=QColor(c,c,255);
else if(octave==1)
dotcolor=QColor(c,255,c);
else if(octave==2)
dotcolor=QColor(255,c,c);
else if(octave==3)
dotcolor=QColor(255,255,c);
else if(octave==4)
dotcolor=QColor(255,c,255);
else
dotcolor=QColor(c,255,255);
p->setBrush(dotcolor);
p->drawEllipse(x-dotsize/2,y-dotsize/2,dotsize,dotsize);
if(data->isDrawNames())
{
p->setPen(QColor(255,155,0));
p->drawText(x-dotsize/2,y-dotsize/2,Note::getNameOfNote(note));
}
}
}
}
}
//****************************************************************************
//****************************************************************************
diff --git a/noncore/multimedia/tonleiter/tonleiter.pro b/noncore/multimedia/tonleiter/tonleiter.pro
index 4bd1bc2..4be3bef 100644
--- a/noncore/multimedia/tonleiter/tonleiter.pro
+++ b/noncore/multimedia/tonleiter/tonleiter.pro
@@ -1,13 +1,11 @@
TEMPLATE = app
-#CONFIG = qt warn_on
CONFIG = qt warn_on
HEADERS = mainwidget.h tonleiterdata.h tonleiterdatahelper.h fretboard.h menuwidget.h editinst.h editstringwidget.h editscale.h pianoscale.h
SOURCES = mainwidget.cpp tonleiterdata.cpp tonleiterdatahelper.cpp fretboard.cpp menuwidget.cpp main.cpp editinst.cpp editstringwidget.cpp editscale.cpp pianoscale.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe
-INTERFACES =
+LIBS += -lqpe -lopiecore2
TARGET = tonleiter
DESTDIR = $(OPIEDIR)/bin
-#TMAKE_CXXFLAGS += -DQT_QWS_VERCEL_IDR -DQWS -fno-exceptions -fno-rtti
+
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/multimedia/tonleiter/tonleiterdata.cpp b/noncore/multimedia/tonleiter/tonleiterdata.cpp
index 33b3c49..564b7f0 100644
--- a/noncore/multimedia/tonleiter/tonleiterdata.cpp
+++ b/noncore/multimedia/tonleiter/tonleiterdata.cpp
@@ -1,198 +1,199 @@
#include "tonleiterdata.h"
-
-#include <qpe/config.h>
-
using namespace Data;
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/config.h>
+using namespace Opie::Core;
TonleiterData::TonleiterData(QObject* parent)
:QObject(parent)
{
drawnames=true;
loadData();
}
//****************************************************************************
TonleiterData::~TonleiterData()
{
saveData();
}
//****************************************************************************
void TonleiterData::setCurrentInstrumetID(int id)
{
if(id>=0 && id<noOfInstruments())
{
currentInstrumentID=id;
emit dataChange();
}
}
//****************************************************************************
void TonleiterData::setCurrentScaleID(int id)
{
if(id>=0 && id<noOfScales())
{
currentScaleID=id;
emit dataChange();
}
}
//****************************************************************************
void TonleiterData::setCurrentNote(int id)
{
if(id>=0 && id<12)
{
currentNote=id;
emit dataChange();
}
}
//****************************************************************************
void TonleiterData::setDrawNames(bool dn)
{
drawnames=dn;
emit dataChange();
}
//****************************************************************************
void TonleiterData::loadData()
{
Config load("Tonleiter");
if(!load.isValid())
{
//write some default values
load.setGroup("General");
load.writeEntry("currentInstrumentID",1);
load.writeEntry("currentNote",3);
load.writeEntry("currentScaleID",0);
load.writeEntry("drawnames",1);
load.setGroup("Instrument");
load.writeEntry("Inst0","Thumb6;26;14;19;24;29;34;39;");
load.writeEntry("Inst1","Bass 4;12;19;24;29;34;");
load.writeEntry("noOfInstruments",2);
load.setGroup("Scale");
load.writeEntry("Scale0","ionian;0;2;4;5;7;9;11;");
load.writeEntry("Scale1","aeolian;0;2;3;5;7;8;10;");
load.writeEntry("Scale2","dorian;0;2;3;5;7;9;10;");
load.writeEntry("Scale3","phrygian;0;1;3;5;7;8;10;");
load.writeEntry("Scale4","lydian;0;2;4;6;7;9;11;");
load.writeEntry("Scale5","mixolydian;0;2;4;5;7;9;10;");
load.writeEntry("noOfScales",6);
}
load.setGroup("General");
currentNote=load.readNumEntry("currentNote");
drawnames=load.readBoolEntry("drawnames");
currentInstrumentID=load.readNumEntry("currentInstrumentID");
currentScaleID=load.readNumEntry("currentScaleID");
load.setGroup("Instrument");
int noOfInstr=load.readNumEntry("noOfInstruments",0);
for(int i=0;i<noOfInstr;i++)
{
QStringList instlist=load.readListEntry("Inst"+QString::number(i),';');
QValueList<int> strings;
for(int st=2;st<(int)instlist.count();st++)
strings.append(instlist[st].toInt());
instruments.append(Instrument(instlist[0],instlist[1].toInt(),strings));
}
load.setGroup("Scale");
int scaleno=load.readNumEntry("noOfScales",0);
for(int s=0;s<scaleno;s++)
{
QStringList scalelist=load.readListEntry("Scale"+QString::number(s),';');
QValueList<int> halftones;
for(int ht=1;ht<(int)scalelist.count();ht++)
halftones.append(scalelist[ht].toInt());
scales.append(Scale(scalelist[0],halftones));
}
}
//****************************************************************************
void TonleiterData::saveData()
{
Config save("Tonleiter");
save.setGroup("General");
save.writeEntry("currentNote",currentNote);
save.writeEntry("drawnames",drawnames);
save.writeEntry("currentInstrumentID",currentInstrumentID);
save.writeEntry("currentScaleID",currentScaleID);
save.setGroup("Instrument");
save.writeEntry("noOfInstruments",noOfInstruments());
for(int i=0;i<noOfInstruments();i++)
{
QStringList instlist;
Instrument inst=getInstrument(i);
instlist.append(inst.instName());
instlist.append(QString::number(inst.noOfFrets()));
for(int st=0;st<inst.noOfStrings();st++)
instlist.append(QString::number(inst.string(st)));
save.writeEntry("Inst"+QString::number(i),instlist,';');
}
save.setGroup("Scale");
save.writeEntry("noOfScales",noOfScales());
for(int s=0;s<noOfScales();s++)
{
QStringList scalelist;
Scale scale=getScale(s);
scalelist.append(scale.scaleName());
for(int ht=0;ht<scale.noOfHaltones();ht++)
scalelist.append(QString::number(scale.getHalfTone(ht)));
save.writeEntry("Scale"+QString::number(s),scalelist,';');
}
}
//****************************************************************************
int TonleiterData::noOfInstruments()
{
return (int)instruments.count();
}
//****************************************************************************
Instrument TonleiterData::getInstrument(int id)
{
if(id>=0 && id<noOfInstruments())
return instruments[id];
else
{
- qDebug("undefined insrtument %d of %d",id,instruments.count());
+ odebug << "undefined insrtument " << id << " of " << instruments.count() << "" << oendl;
return Instrument();
}
}
//****************************************************************************
int TonleiterData::getCurrentInstrumentID()
{
return currentInstrumentID;
}
//****************************************************************************
int TonleiterData::noOfScales()
{
return (int)scales.count();
}
//****************************************************************************
Scale TonleiterData::getScale(int id)
{
if(id>=0 && id<noOfScales())
return scales[id];
else
{
- qDebug("Undefined scale");
+ odebug << "Undefined scale" << oendl;
return Scale();
}
}
//****************************************************************************
int TonleiterData::getCurrentScaleID()
{
return currentScaleID;
}
//****************************************************************************
int TonleiterData::getCurrentBaseNote()
{
return currentNote;
}
//****************************************************************************
bool TonleiterData::isDrawNames()
{
return drawnames;
}
//****************************************************************************
//****************************************************************************
diff --git a/noncore/multimedia/tonleiter/tonleiterdatahelper.cpp b/noncore/multimedia/tonleiter/tonleiterdatahelper.cpp
index d904a71..285d2c1 100644
--- a/noncore/multimedia/tonleiter/tonleiterdatahelper.cpp
+++ b/noncore/multimedia/tonleiter/tonleiterdatahelper.cpp
@@ -1,144 +1,144 @@
#include "tonleiterdatahelper.h"
#include <math.h>
using namespace Data;
int Note::getOctaveOfNote(int note)
{
int remain=note%12;
return (note-remain)/12;
}
//****************************************************************************
QString Note::getNameOfNote(int note)
{
int octave=getOctaveOfNote(note);
return notenames[note-12*octave];
}
//****************************************************************************
int Note::getNoteFromName(QString name,int octave)
{
int notevalue=0;
for(int a=0;a<12;a++)
{
if(name==notenames[a])
{
notevalue=a;
break;
}
}
return notevalue+12*octave;
}
//****************************************************************************
int Note::octaveOfBaseNote(int base,int note)
{
int normnote = (note>=base) ? note-base : (12-base)+note;
int octave=getOctaveOfNote(normnote);
- //qDebug("note %d of %d base is norm %d -> ocatve %d",note,base,normnote,octave);
+ //odebug << "note " << note << " of " << base << " base is norm " << normnote << " -> ocatve " << octave << "" << oendl;
return octave;
}
//****************************************************************************
//****************************************************************************
Instrument::Instrument()
{
name="UNDEFINED";
frets=0;
}
//****************************************************************************
Instrument::Instrument(QString name,int frets,QValueList<int> strings)
:name(name),frets(frets),strings(strings)
{
}
//****************************************************************************
Instrument::~Instrument()
{
}
//****************************************************************************
int Instrument::noOfStrings()
{
return (int)strings.count();
}
//****************************************************************************
int Instrument::noOfFrets()
{
return frets;
}
//****************************************************************************
QString Instrument::instName()
{
return name;
}
//****************************************************************************
int Instrument::string(int id)
{
return strings[id];
}
//****************************************************************************
int Instrument::noOfOctaves()
{
return (int) ceil((highestNote()-lowestNote())/12.0);
}
//****************************************************************************
int Instrument::lowestNote()
{
return strings[0];
}
//****************************************************************************
int Instrument::highestNote()
{
return strings[strings.count()-1]+frets;
}
//****************************************************************************
//****************************************************************************
Scale::Scale()
{
name="UNDEFINED";
}
//****************************************************************************
Scale::Scale(QString name,QValueList<int> halftones)
:name(name),halftones(halftones)
{
}
//****************************************************************************
Scale::~Scale()
{
}
//****************************************************************************
int Scale::noOfHaltones()
{
return (int)halftones.count();
}
//****************************************************************************
int Scale::getHalfTone(int id)
{
if(id>=0 && id<noOfHaltones())
return halftones[id];
else
return 0;
}
//****************************************************************************
QString Scale::scaleName()
{
return name;
}
//****************************************************************************
bool Scale::noteInScale(int base,int note)
{
int octave=Note::getOctaveOfNote(note);
note-=12*octave;
int normnote = (note>=base) ? note-base : (12-base)+note;
if(halftones.contains(normnote)>0)
{
- //qDebug("OK : base : %d, note %d -> norm %d",base,note,normnote);
+ //odebug << "OK : base : " << base << ", note " << note << " -> norm " << normnote << "" << oendl;
return true;
}
else
{
- //qDebug("BAD : base : %d, note %d -> norm %d",base,note,normnote);
+ //odebug << "BAD : base : " << base << ", note " << note << " -> norm " << normnote << "" << oendl;
return false;
}
}
//****************************************************************************
//****************************************************************************
diff --git a/noncore/net/mail/accountitem.cpp b/noncore/net/mail/accountitem.cpp
index 54d2da2..ae28313 100644
--- a/noncore/net/mail/accountitem.cpp
+++ b/noncore/net/mail/accountitem.cpp
@@ -1,1134 +1,1134 @@
#include "accountitem.h"
#include "accountview.h"
#include "newmaildir.h"
#include "nntpgroupsdlg.h"
#include "defines.h"
/* OPIE */
#include <libmailwrapper/mailtypes.h>
#include <libmailwrapper/abstractmail.h>
#include <libmailwrapper/mailwrapper.h>
#include <qpe/qpeapplication.h>
/* QT */
#include <qpopupmenu.h>
#include <qmessagebox.h>
using namespace Opie::Core;
#define SETPIX(x) if (!account->getOffline()) {setPixmap( 0,x);} else {setPixmap( 0, PIXMAP_OFFLINE );}
/**
* POP3 Account stuff
*/
POP3viewItem::POP3viewItem( POP3account *a, AccountView *parent )
: AccountViewItem( parent )
{
account = a;
wrapper = AbstractMail::getWrapper( account );
SETPIX(PIXMAP_POP3FOLDER);
#if 0
if (!account->getOffline())
{
setPixmap( 0, );
}
else
{
setPixmap( 0, PIXMAP_OFFLINE );
}
#endif
setText( 0, account->getAccountName() );
setOpen( true );
}
POP3viewItem::~POP3viewItem()
{
delete wrapper;
}
AbstractMail *POP3viewItem::getWrapper()
{
return wrapper;
}
void POP3viewItem::refresh(QValueList<Opie::Core::OSmartPointer<RecMail> > & )
{
refresh();
}
void POP3viewItem::refresh()
{
if (account->getOffline()) return;
QValueList<FolderP> *folders = wrapper->listFolders();
QListViewItem *child = firstChild();
while ( child )
{
QListViewItem *tmp = child;
child = child->nextSibling();
delete tmp;
}
QValueList<FolderP>::ConstIterator it;
QListViewItem*item = 0;
for ( it = folders->begin(); it!=folders->end(); ++it)
{
item = new POP3folderItem( (*it), this , item );
item->setSelectable( (*it)->may_select());
}
delete folders;
}
RECBODYP POP3viewItem::fetchBody( const RecMailP &mail )
{
- qDebug( "POP3 fetchBody" );
+ odebug << "POP3 fetchBody" << oendl;
return wrapper->fetchBody( mail );
}
QPopupMenu * POP3viewItem::getContextMenu()
{
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
if (!account->getOffline())
{
m->insertItem(QObject::tr("Disconnect",contextName),0);
m->insertItem(QObject::tr("Set offline",contextName),1);
}
else
{
m->insertItem(QObject::tr("Set online",contextName),1);
}
}
return m;
}
void POP3viewItem::disconnect()
{
QListViewItem *child = firstChild();
while ( child )
{
QListViewItem *tmp = child;
child = child->nextSibling();
delete tmp;
}
wrapper->logout();
}
void POP3viewItem::setOnOffline()
{
if (!account->getOffline())
{
disconnect();
}
account->setOffline(!account->getOffline());
account->save();
SETPIX(PIXMAP_POP3FOLDER);
refresh();
}
void POP3viewItem::contextMenuSelected(int which)
{
switch (which)
{
case 0:
disconnect();
break;
case 1:
setOnOffline();
break;
}
}
POP3folderItem::~POP3folderItem()
{}
POP3folderItem::POP3folderItem( const FolderP&folderInit, POP3viewItem *parent , QListViewItem*after )
: AccountViewItem(folderInit,parent,after )
{
pop3 = parent;
if (folder->getDisplayName().lower()!="inbox")
{
setPixmap( 0, PIXMAP_POP3FOLDER );
}
else
{
setPixmap( 0, PIXMAP_INBOXFOLDER);
}
setText( 0, folder->getDisplayName() );
}
void POP3folderItem::refresh(QValueList<RecMailP>&target)
{
if (folder->may_select())
pop3->getWrapper()->listMessages( folder->getName(),target );
}
RECBODYP POP3folderItem::fetchBody(const RecMailP&aMail)
{
return pop3->getWrapper()->fetchBody(aMail);
}
QPopupMenu * POP3folderItem::getContextMenu()
{
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
m->insertItem(QObject::tr("Refresh header list",contextName),0);
m->insertItem(QObject::tr("Delete all mails",contextName),1);
m->insertItem(QObject::tr("Move/Copie all mails",contextName),2);
}
return m;
}
void POP3folderItem::downloadMails()
{
AccountView*bl = pop3->accountView();
if (!bl) return;
bl->downloadMails(folder,pop3->getWrapper());
}
void POP3folderItem::contextMenuSelected(int which)
{
AccountView * view = (AccountView*)listView();
switch (which)
{
case 0:
/* must be 'cause pop3 lists are cached */
pop3->getWrapper()->logout();
view->refreshCurrent();
break;
case 1:
deleteAllMail(pop3->getWrapper(),folder);
break;
case 2:
downloadMails();
break;
default:
break;
}
}
/**
* NNTP Account stuff
*/
NNTPviewItem::NNTPviewItem( NNTPaccount *a, AccountView *parent )
: AccountViewItem( parent )
{
account = a;
wrapper = AbstractMail::getWrapper( account );
//FIXME
SETPIX(PIXMAP_POP3FOLDER);
#if 0
if (!account->getOffline())
{
setPixmap( 0, );
}
else
{
setPixmap( 0, PIXMAP_OFFLINE );
}
#endif
setText( 0, account->getAccountName() );
setOpen( true );
}
NNTPviewItem::~NNTPviewItem()
{
delete wrapper;
}
AbstractMail *NNTPviewItem::getWrapper()
{
return wrapper;
}
void NNTPviewItem::refresh( QValueList<RecMailP> & )
{
refresh();
}
void NNTPviewItem::refresh()
{
if (account->getOffline()) return;
QValueList<FolderP> *folders = wrapper->listFolders();
QListViewItem *child = firstChild();
while ( child )
{
QListViewItem *tmp = child;
child = child->nextSibling();
delete tmp;
}
QValueList<FolderP>::ConstIterator it;
QListViewItem*item = 0;
for ( it = folders->begin(); it!=folders->end(); ++it)
{
item = new NNTPfolderItem( (*it), this , item );
item->setSelectable( (*it)->may_select());
}
delete folders;
}
RECBODYP NNTPviewItem::fetchBody( const RecMailP &mail )
{
- qDebug( "NNTP fetchBody" );
+ odebug << "NNTP fetchBody" << oendl;
return wrapper->fetchBody( mail );
}
QPopupMenu * NNTPviewItem::getContextMenu()
{
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
if (!account->getOffline())
{
m->insertItem(QObject::tr("Disconnect",contextName),0);
m->insertItem(QObject::tr("Set offline",contextName),1);
m->insertItem(QObject::tr("(Un-)Subscribe groups",contextName),2);
}
else
{
m->insertItem(QObject::tr("Set online",contextName),1);
}
}
return m;
}
void NNTPviewItem::subscribeGroups()
{
NNTPGroupsDlg dlg(account);
if (QPEApplication::execDialog(&dlg)== QDialog::Accepted ){
refresh();
}
}
void NNTPviewItem::disconnect()
{
QListViewItem *child = firstChild();
while ( child )
{
QListViewItem *tmp = child;
child = child->nextSibling();
delete tmp;
}
wrapper->logout();
}
void NNTPviewItem::setOnOffline()
{
if (!account->getOffline())
{
disconnect();
}
account->setOffline(!account->getOffline());
account->save();
//FIXME
SETPIX(PIXMAP_POP3FOLDER);
refresh();
}
void NNTPviewItem::contextMenuSelected(int which)
{
switch (which)
{
case 0:
disconnect();
break;
case 1:
setOnOffline();
break;
case 2:
subscribeGroups();
break;
}
}
NNTPfolderItem::~NNTPfolderItem()
{}
NNTPfolderItem::NNTPfolderItem( const FolderP &folderInit, NNTPviewItem *parent , QListViewItem*after )
: AccountViewItem( folderInit, parent,after )
{
nntp = parent;
if (folder->getDisplayName().lower()!="inbox")
{
setPixmap( 0, PIXMAP_POP3FOLDER );
}
else
{
setPixmap( 0, PIXMAP_INBOXFOLDER);
}
setText( 0, folder->getDisplayName() );
}
void NNTPfolderItem::refresh(QValueList<RecMailP>&target)
{
if (folder->may_select())
nntp->getWrapper()->listMessages( folder->getName(),target );
}
RECBODYP NNTPfolderItem::fetchBody(const RecMailP&aMail)
{
return nntp->getWrapper()->fetchBody(aMail);
}
QPopupMenu * NNTPfolderItem::getContextMenu()
{
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
m->insertItem(QObject::tr("Refresh header list",contextName),0);
m->insertItem(QObject::tr("Copy all postings",contextName),1);
}
return m;
}
void NNTPfolderItem::downloadMails()
{
AccountView*bl = nntp->accountView();
if (!bl) return;
bl->downloadMails(folder,nntp->getWrapper());
}
void NNTPfolderItem::contextMenuSelected(int which)
{
AccountView * view = (AccountView*)listView();
switch (which)
{
case 0:
/* must be 'cause pop3 lists are cached */
nntp->getWrapper()->logout();
view->refreshCurrent();
break;
case 1:
downloadMails();
break;
default:
break;
}
}
/**
* IMAP Account stuff
*/
IMAPviewItem::IMAPviewItem( IMAPaccount *a, AccountView *parent )
: AccountViewItem( parent )
{
account = a;
wrapper = AbstractMail::getWrapper( account );
SETPIX(PIXMAP_IMAPFOLDER);
setText( 0, account->getAccountName() );
setOpen( true );
}
IMAPviewItem::~IMAPviewItem()
{
delete wrapper;
}
AbstractMail *IMAPviewItem::getWrapper()
{
return wrapper;
}
void IMAPviewItem::refresh(QValueList<RecMailP>&)
{
refreshFolders(false);
}
const QStringList&IMAPviewItem::subFolders()
{
return currentFolders;
}
void IMAPviewItem::refreshFolders(bool force)
{
if (childCount()>0 && force==false) return;
if (account->getOffline()) return;
removeChilds();
currentFolders.clear();
QValueList<FolderP> * folders = wrapper->listFolders();
QValueList<FolderP>::Iterator it;
QListViewItem*item = 0;
QListViewItem*titem = 0;
QString fname,del,search;
int pos;
for ( it = folders->begin(); it!=folders->end(); ++it)
{
if ((*it)->getDisplayName().lower()=="inbox")
{
item = new IMAPfolderItem( (*it), this , item );
folders->remove(it);
- qDebug("inbox found");
+ odebug << "inbox found" << oendl;
break;
}
}
for ( it = folders->begin(); it!=folders->end(); ++it)
{
fname = (*it)->getDisplayName();
currentFolders.append((*it)->getName());
pos = fname.findRev((*it)->Separator());
if (pos != -1)
{
fname = fname.left(pos);
}
IMAPfolderItem*pitem = (IMAPfolderItem*)findSubItem(fname);
if (pitem)
{
titem = item;
item = new IMAPfolderItem( (*it),pitem,pitem->firstChild(),this);
/* setup the short name */
item->setText(0,(*it)->getDisplayName().right((*it)->getDisplayName().length()-pos-1));
item = titem;
}
else
{
item = new IMAPfolderItem( (*it), this , item );
}
}
delete folders;
}
QPopupMenu * IMAPviewItem::getContextMenu()
{
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
if (!account->getOffline())
{
m->insertItem(QObject::tr("Refresh folder list",contextName),0);
m->insertItem(QObject::tr("Create new folder",contextName),1);
m->insertSeparator();
m->insertItem(QObject::tr("Disconnect",contextName),2);
m->insertItem(QObject::tr("Set offline",contextName),3);
}
else
{
m->insertItem(QObject::tr("Set online",contextName),3);
}
}
return m;
}
void IMAPviewItem::createNewFolder()
{
Newmdirdlg ndirdlg;
if ( QPEApplication::execDialog( &ndirdlg ))
{
QString ndir = ndirdlg.Newdir();
bool makesubs = ndirdlg.subpossible();
QString delemiter = "/";
IMAPfolderItem*item = (IMAPfolderItem*)firstChild();
if (item)
{
delemiter = item->Delemiter();
}
if (wrapper->createMbox(ndir,0,delemiter,makesubs))
{
refreshFolders(true);
}
}
}
void IMAPviewItem::contextMenuSelected(int id)
{
- qDebug("Id selected: %i",id);
+ odebug << "Id selected: " << id << "" << oendl;
switch (id)
{
case 0:
refreshFolders(true);
break;
case 1:
createNewFolder();
break;
case 2:
removeChilds();
wrapper->logout();
break;
case 3:
if (account->getOffline()==false)
{
removeChilds();
wrapper->logout();
}
account->setOffline(!account->getOffline());
account->save();
SETPIX(PIXMAP_IMAPFOLDER);
refreshFolders(false);
break;
default:
break;
}
}
RECBODYP IMAPviewItem::fetchBody(const RecMailP&)
{
return new RecBody();
}
bool IMAPviewItem::offline()
{
return account->getOffline();
}
IMAPfolderItem::IMAPfolderItem( const FolderP& folderInit, IMAPviewItem *parent , QListViewItem*after )
: AccountViewItem( folderInit, parent , after )
{
imap = parent;
if (folder->getDisplayName().lower()!="inbox")
{
setPixmap( 0, PIXMAP_IMAPFOLDER );
}
else
{
setPixmap( 0, PIXMAP_INBOXFOLDER);
}
setText( 0, folder->getDisplayName() );
}
IMAPfolderItem::IMAPfolderItem(const FolderP &folderInit, IMAPfolderItem *parent , QListViewItem*after, IMAPviewItem *master )
: AccountViewItem(folderInit, parent,after )
{
imap = master;
if (folder->getDisplayName().lower()!="inbox")
{
setPixmap( 0, PIXMAP_IMAPFOLDER );
}
else
{
setPixmap( 0, PIXMAP_INBOXFOLDER);
}
setText( 0, folder->getDisplayName() );
}
IMAPfolderItem::~IMAPfolderItem()
{}
const QString& IMAPfolderItem::Delemiter()const
{
return folder->Separator();
}
void IMAPfolderItem::refresh(QValueList<RecMailP>&target)
{
if (folder->may_select())
{
imap->getWrapper()->listMessages( folder->getName(),target );
}
else
{
target.clear();
}
}
RECBODYP IMAPfolderItem::fetchBody(const RecMailP&aMail)
{
return imap->getWrapper()->fetchBody(aMail);
}
QPopupMenu * IMAPfolderItem::getContextMenu()
{
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
if (folder->may_select())
{
m->insertItem(QObject::tr("Refresh header list",contextName),0);
m->insertItem(QObject::tr("Move/Copie all mails",contextName),4);
m->insertItem(QObject::tr("Delete all mails",contextName),1);
}
if (folder->no_inferior()==false)
{
m->insertItem(QObject::tr("Create new subfolder",contextName),2);
}
if (folder->getDisplayName().lower()!="inbox")
{
m->insertItem(QObject::tr("Delete folder",contextName),3);
}
}
return m;
}
void IMAPfolderItem::createNewFolder()
{
Newmdirdlg ndirdlg;
if ( QPEApplication::execDialog( &ndirdlg ) )
{
QString ndir = ndirdlg.Newdir();
bool makesubs = ndirdlg.subpossible();
QString delemiter = Delemiter();
if (imap->wrapper->createMbox(ndir,folder,delemiter,makesubs))
{
imap->refreshFolders(true);
}
}
}
void IMAPfolderItem::deleteFolder()
{
int yesno = QMessageBox::warning(0,QObject::tr("Delete folder",contextName),
QObject::tr("<center>Realy delete folder <br><b>%1</b><br>and all if it content?</center>",contextName).arg(folder->getDisplayName()),
QObject::tr("Yes",contextName),
QObject::tr("No",contextName),QString::null,1,1);
- qDebug("Auswahl: %i",yesno);
+ odebug << "Auswahl: " << yesno << "" << oendl;
if (yesno == 0)
{
if (imap->getWrapper()->deleteMbox(folder))
{
QListView*v=listView();
IMAPviewItem * box = imap;
/* be carefull - after that this object is destroyd so don't use
* any member of it after that call!!*/
imap->refreshFolders(true);
if (v)
{
v->setSelected(box,true);
}
}
}
}
void IMAPfolderItem::downloadMails()
{
AccountView*bl = imap->accountView();
if (!bl) return;
bl->downloadMails(folder,imap->getWrapper());
}
void IMAPfolderItem::contextMenuSelected(int id)
{
- qDebug("Selected id: %i",id);
+ odebug << "Selected id: " << id << "" << oendl;
AccountView * view = (AccountView*)listView();
switch(id)
{
case 0:
view->refreshCurrent();
break;
case 1:
deleteAllMail(imap->getWrapper(),folder);
break;
case 2:
createNewFolder();
break;
case 3:
deleteFolder();
break;
case 4:
downloadMails();
break;
default:
break;
}
}
/**
* MH Account stuff
*/
/* MH is a little bit different - the top folder can contains messages other than in IMAP and
POP3 and MBOX */
MHviewItem::MHviewItem( const QString&aPath, AccountView *parent )
: AccountViewItem( parent )
{
m_Path = aPath;
/* be carefull - the space within settext is wanted - thats why the string twice */
wrapper = AbstractMail::getWrapper( m_Path,"Local Folders");
setPixmap( 0, PIXMAP_LOCALFOLDER );
setText( 0, " Local Folders" );
setOpen( true );
folder = 0;
}
MHviewItem::~MHviewItem()
{
delete wrapper;
}
AbstractMail *MHviewItem::getWrapper()
{
return wrapper;
}
void MHviewItem::refresh( QValueList<RecMailP> & target)
{
refresh(false);
getWrapper()->listMessages( "",target );
}
void MHviewItem::refresh(bool force)
{
if (childCount()>0 && force==false) return;
removeChilds();
currentFolders.clear();
QValueList<FolderP> *folders = wrapper->listFolders();
QValueList<FolderP>::ConstIterator it;
MHfolderItem*item = 0;
MHfolderItem*pmaster = 0;
QString fname = "";
int pos;
for ( it = folders->begin(); it!=folders->end(); ++it)
{
fname = (*it)->getDisplayName();
/* this folder itself */
if (fname=="/")
{
currentFolders.append(fname);
folder = (*it);
continue;
}
currentFolders.append(fname);
pos = fname.findRev("/");
if (pos > 0)
{
fname = fname.left(pos);
pmaster = (MHfolderItem*)findSubItem(fname);
}
else
{
pmaster = 0;
}
if (pmaster)
{
item = new MHfolderItem( (*it), pmaster, item, this );
}
else
{
item = new MHfolderItem( (*it), this , item );
}
item->setSelectable((*it)->may_select());
}
delete folders;
}
RECBODYP MHviewItem::fetchBody( const RecMailP &mail )
{
- qDebug( "MH fetchBody" );
+ odebug << "MH fetchBody" << oendl;
return wrapper->fetchBody( mail );
}
QPopupMenu * MHviewItem::getContextMenu()
{
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
m->insertItem(QObject::tr("Refresh folder list",contextName),0);
m->insertItem(QObject::tr("Create new folder",contextName),1);
m->insertItem(QObject::tr("Delete all mails",contextName),2);
m->insertItem(QObject::tr("Move/Copie all mails",contextName),3);
}
return m;
}
void MHviewItem::createFolder()
{
Newmdirdlg ndirdlg(0,0,true);
if ( QPEApplication::execDialog( &ndirdlg ) )
{
QString ndir = ndirdlg.Newdir();
if (wrapper->createMbox(ndir))
{
refresh(true);
}
}
}
void MHviewItem::downloadMails()
{
AccountView*bl = accountView();
if (!bl) return;
bl->downloadMails(folder,getWrapper());
}
QStringList MHviewItem::subFolders()
{
return currentFolders;
}
void MHviewItem::contextMenuSelected(int which)
{
switch (which)
{
case 0:
refresh(true);
break;
case 1:
createFolder();
break;
case 2:
deleteAllMail(getWrapper(),folder);
break;
case 3:
downloadMails();
break;
default:
break;
}
}
MHfolderItem::~MHfolderItem()
{}
MHfolderItem::MHfolderItem( const FolderP &folderInit, MHviewItem *parent , QListViewItem*after )
: AccountViewItem(folderInit, parent,after )
{
mbox = parent;
initName();
}
MHfolderItem::MHfolderItem(const FolderP& folderInit, MHfolderItem *parent, QListViewItem*after, MHviewItem*master)
: AccountViewItem(folderInit, parent,after )
{
folder = folderInit;
mbox = master;
initName();
}
void MHfolderItem::initName()
{
QString bName = folder->getDisplayName();
if (bName.startsWith("/")&&bName.length()>1)
{
bName.replace(0,1,"");
}
int pos = bName.findRev("/");
if (pos > 0)
{
bName.replace(0,pos+1,"");
}
if (bName.lower() == "outgoing")
{
setPixmap( 0, PIXMAP_OUTBOXFOLDER );
}
else if (bName.lower() == "inbox")
{
setPixmap( 0, PIXMAP_INBOXFOLDER);
} else if (bName.lower() == "drafts") {
setPixmap(0, Resource::loadPixmap("inline/edit"));
} else {
setPixmap( 0, PIXMAP_MBOXFOLDER );
}
setText( 0, bName );
}
const FolderP&MHfolderItem::getFolder()const
{
return folder;
}
void MHfolderItem::refresh(QValueList<RecMailP>&target)
{
if (folder->may_select())
mbox->getWrapper()->listMessages( folder->getName(),target );
}
RECBODYP MHfolderItem::fetchBody(const RecMailP&aMail)
{
return mbox->getWrapper()->fetchBody(aMail);
}
void MHfolderItem::deleteFolder()
{
int yesno = QMessageBox::warning(0,QObject::tr("Delete folder",contextName),
QObject::tr("<center>Realy delete folder <br><b>%1</b><br>and all if it content?</center>",contextName).arg(folder->getDisplayName()),
QObject::tr("Yes",contextName),
QObject::tr("No",contextName),QString::null,1,1);
- qDebug("Auswahl: %i",yesno);
+ odebug << "Auswahl: " << yesno << "" << oendl;
if (yesno == 0)
{
if (mbox->getWrapper()->deleteMbox(folder))
{
QListView*v=listView();
MHviewItem * box = mbox;
/* be carefull - after that this object is destroyd so don't use
* any member of it after that call!!*/
mbox->refresh(true);
if (v)
{
v->setSelected(box,true);
}
}
}
}
QPopupMenu * MHfolderItem::getContextMenu()
{
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
m->insertItem(QObject::tr("Move/Copie all mails",contextName),2);
m->insertItem(QObject::tr("Delete all mails",contextName),0);
m->insertItem(QObject::tr("Create new subfolder",contextName),3);
m->insertItem(QObject::tr("Delete folder",contextName),1);
}
return m;
}
void MHfolderItem::downloadMails()
{
AccountView*bl = mbox->accountView();
if (!bl) return;
bl->downloadMails(folder,mbox->getWrapper());
}
void MHfolderItem::createFolder()
{
Newmdirdlg ndirdlg(0,0,true);
if ( QPEApplication::execDialog( &ndirdlg ) )
{
QString ndir = ndirdlg.Newdir();
if (mbox->getWrapper()->createMbox(ndir,folder))
{
QListView*v=listView();
MHviewItem * box = mbox;
/* be carefull - after that this object is destroyd so don't use
* any member of it after that call!!*/
mbox->refresh(true);
if (v)
{
v->setSelected(box,true);
}
}
}
}
void MHfolderItem::contextMenuSelected(int which)
{
switch(which)
{
case 0:
deleteAllMail(mbox->getWrapper(),folder);
break;
case 1:
deleteFolder();
break;
case 2:
downloadMails();
break;
case 3:
createFolder();
break;
default:
break;
}
}
bool MHfolderItem::isDraftfolder()
{
if (folder && folder->getName()==AbstractMail::defaultLocalfolder()+"/"+AbstractMail::draftFolder()) return true;
return false;
}
/**
* Generic stuff
*/
const QString AccountViewItem::contextName="AccountViewItem";
AccountViewItem::AccountViewItem( AccountView *parent )
: QListViewItem( parent )
{
init();
m_Backlink = parent;
}
AccountViewItem::AccountViewItem( QListViewItem *parent)
: QListViewItem( parent),folder(0)
{
init();
}
AccountViewItem::AccountViewItem( QListViewItem *parent , QListViewItem*after )
:QListViewItem( parent,after ),folder(0)
{
init();
}
AccountViewItem::AccountViewItem( const Opie::Core::OSmartPointer<Folder>&folderInit,QListViewItem *parent , QListViewItem*after )
:QListViewItem( parent,after ),folder(folderInit)
{
init();
}
void AccountViewItem::init()
{
m_Backlink = 0;
}
AccountViewItem::~AccountViewItem()
{
folder = 0;
}
AccountView*AccountViewItem::accountView()
{
return m_Backlink;
}
void AccountViewItem::deleteAllMail(AbstractMail*wrapper,const FolderP&folder)
{
if (!wrapper) return;
QString fname="";
if (folder) fname = folder->getDisplayName();
int yesno = QMessageBox::warning(0,QObject::tr("Delete all mails",contextName),
QObject::tr("<center>Realy delete all mails in box <br>%1</center>",contextName).
arg(fname),
QObject::tr("Yes",contextName),
QObject::tr("No",contextName),QString::null,1,1);
- qDebug("Auswahl: %i",yesno);
+ odebug << "Auswahl: " << yesno << "" << oendl;
if (yesno == 0)
{
if (wrapper->deleteAllMail(folder))
{
AccountView * view = (AccountView*)listView();
if (view) view->refreshCurrent();
}
}
}
void AccountViewItem::removeChilds()
{
QListViewItem *child = firstChild();
while ( child )
{
QListViewItem *tmp = child;
child = child->nextSibling();
delete tmp;
}
}
bool AccountViewItem::matchName(const QString&name)const
{
if (!folder) return false;
return folder->getDisplayName()==name;
}
AccountViewItem*AccountViewItem::findSubItem(const QString&path,AccountViewItem*start)
{
AccountViewItem*pitem,*sitem;
if (!start) pitem = (AccountViewItem*)firstChild();
else pitem = (AccountViewItem*)start->firstChild();
while (pitem)
{
if (pitem->matchName(path))
{
break;
}
if (pitem->childCount()>0)
{
sitem = findSubItem(path,pitem);
if (sitem)
{
pitem = sitem;
break;
}
}
pitem=(AccountViewItem*)pitem->nextSibling();
}
return pitem;
}
bool AccountViewItem::isDraftfolder()
{
return false;
}
diff --git a/noncore/net/mail/accountview.cpp b/noncore/net/mail/accountview.cpp
index f0a163e..0052061 100644
--- a/noncore/net/mail/accountview.cpp
+++ b/noncore/net/mail/accountview.cpp
@@ -1,176 +1,176 @@
#include "accountview.h"
#include "accountitem.h"
#include "selectstore.h"
/* OPIE */
#include <libmailwrapper/settings.h>
#include <libmailwrapper/mailwrapper.h>
#include <libmailwrapper/mailtypes.h>
#include <libmailwrapper/abstractmail.h>
#include <qpe/qpeapplication.h>
/* QT */
#include <qmessagebox.h>
#include <qpopupmenu.h>
using namespace Opie::Core;
AccountView::AccountView( QWidget *parent, const char *name, WFlags flags )
: QListView( parent, name, flags )
{
connect( this, SIGNAL( selectionChanged(QListViewItem*) ),
SLOT( refresh(QListViewItem*) ) );
connect( this, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),this,
SLOT( slotHold(int,QListViewItem*,const QPoint&,int) ) );
setSorting(0);
}
AccountView::~AccountView()
{
imapAccounts.clear();
mhAccounts.clear();
}
void AccountView::slotContextMenu(int id)
{
AccountViewItem *view = static_cast<AccountViewItem *>(currentItem());
if (!view) return;
view->contextMenuSelected(id);
}
void AccountView::slotHold(int button, QListViewItem * item,const QPoint&,int)
{
if (button==1) {return;}
if (!item) return;
AccountViewItem *view = static_cast<AccountViewItem *>(item);
QPopupMenu*m = view->getContextMenu();
if (!m) return;
connect(m,SIGNAL(activated(int)),this,SLOT(slotContextMenu(int)));
m->setFocus();
m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) );
delete m;
}
void AccountView::populate( QList<Account> list )
{
clear();
imapAccounts.clear();
mhAccounts.clear();
mhAccounts.append(new MHviewItem(AbstractMail::defaultLocalfolder(),this));
Account *it;
for ( it = list.first(); it; it = list.next() )
{
if ( it->getType() == MAILLIB::A_IMAP )
{
IMAPaccount *imap = static_cast<IMAPaccount *>(it);
- qDebug( "added IMAP " + imap->getAccountName() );
+ odebug << "added IMAP " + imap->getAccountName() << oendl;
imapAccounts.append(new IMAPviewItem( imap, this ));
}
else if ( it->getType() == MAILLIB::A_POP3 )
{
POP3account *pop3 = static_cast<POP3account *>(it);
- qDebug( "added POP3 " + pop3->getAccountName() );
+ odebug << "added POP3 " + pop3->getAccountName() << oendl;
/* must not be hold 'cause it isn't required */
(void) new POP3viewItem( pop3, this );
}
else if ( it->getType() == MAILLIB::A_NNTP )
{
NNTPaccount *nntp = static_cast<NNTPaccount *>(it);
- qDebug( "added NNTP " + nntp->getAccountName() );
+ odebug << "added NNTP " + nntp->getAccountName() << oendl;
/* must not be hold 'cause it isn't required */
(void) new NNTPviewItem( nntp, this );
}
}
}
void AccountView::refresh(QListViewItem *item)
{
- qDebug("AccountView refresh...");
+ odebug << "AccountView refresh..." << oendl;
if ( item )
{
m_currentItem = item;
QValueList<RecMailP> headerlist;
AccountViewItem *view = static_cast<AccountViewItem *>(item);
view->refresh(headerlist);
emit refreshMailview(headerlist);
}
}
void AccountView::refreshCurrent()
{
m_currentItem = currentItem();
if ( !m_currentItem ) return;
QValueList<RecMailP> headerlist;
AccountViewItem *view = static_cast<AccountViewItem *>(m_currentItem);
view->refresh(headerlist);
emit refreshMailview(headerlist);
}
void AccountView::refreshAll()
{
}
RecBodyP AccountView::fetchBody(const RecMailP&aMail)
{
QListViewItem*item = selectedItem ();
if (!item) return new RecBody();
AccountViewItem *view = static_cast<AccountViewItem *>(item);
return view->fetchBody(aMail);
}
void AccountView::setupFolderselect(Selectstore*sels)
{
QPEApplication::showDialog( sels );
QStringList sFolders;
unsigned int i = 0;
for (i=0; i < mhAccounts.count();++i)
{
mhAccounts[i]->refresh(false);
sFolders = mhAccounts[i]->subFolders();
sels->addAccounts(mhAccounts[i]->getWrapper(),sFolders);
}
for (i=0; i < imapAccounts.count();++i)
{
if (imapAccounts[i]->offline())
continue;
imapAccounts[i]->refreshFolders(false);
sels->addAccounts(imapAccounts[i]->getWrapper(),imapAccounts[i]->subFolders());
}
}
void AccountView::downloadMails(const FolderP&fromFolder,AbstractMail*fromWrapper)
{
AbstractMail*targetMail = 0;
QString targetFolder = "";
Selectstore sels;
setupFolderselect(&sels);
if (!sels.exec()) return;
targetMail = sels.currentMail();
targetFolder = sels.currentFolder();
if ( (fromWrapper==targetMail && fromFolder->getName()==targetFolder) ||
targetFolder.isEmpty())
{
return;
}
if (sels.newFolder() && !targetMail->createMbox(targetFolder))
{
QMessageBox::critical(0,tr("Error creating new Folder"),
tr("<center>Error while creating<br>new folder - breaking.</center>"));
return;
}
- qDebug("Targetfolder: %s",targetFolder.latin1());
- qDebug("Fromfolder: %s",fromFolder->getName().latin1());
+ odebug << "Targetfolder: " << targetFolder.latin1() << "" << oendl;
+ odebug << "Fromfolder: " << fromFolder->getName().latin1() << "" << oendl;
fromWrapper->mvcpAllMails(fromFolder,targetFolder,targetMail,sels.moveMails());
refreshCurrent();
}
bool AccountView::currentisDraft()
{
AccountViewItem *view = static_cast<AccountViewItem *>(currentItem());
if (!view) return false;
return view->isDraftfolder();
}
diff --git a/noncore/net/mail/composemail.cpp b/noncore/net/mail/composemail.cpp
index 988a1d9..fa703c4 100644
--- a/noncore/net/mail/composemail.cpp
+++ b/noncore/net/mail/composemail.cpp
@@ -90,213 +90,213 @@ void ComposeMail::pickAddress( QLineEdit *line )
void ComposeMail::setTo( const QString & to )
{
toLine->setText( to );
}
void ComposeMail::setSubject( const QString & subject )
{
subjectLine->setText( subject );
}
void ComposeMail::setInReplyTo( const QString & messageId )
{
m_replyid = messageId;
}
void ComposeMail::setMessage( const QString & text )
{
message->setText( text );
}
void ComposeMail::pickAddressTo()
{
pickAddress( toLine );
}
void ComposeMail::pickAddressCC()
{
pickAddress( ccLine );
}
void ComposeMail::pickAddressBCC()
{
pickAddress( bccLine );
}
void ComposeMail::pickAddressReply()
{
pickAddress( replyLine );
}
void ComposeMail::fillValues( int )
{
#if 0
SMTPaccount *smtp = smtpAccounts.at( current );
ccLine->clear();
if ( smtp->getUseCC() ) {
ccLine->setText( smtp->getCC() );
}
bccLine->clear();
if ( smtp->getUseBCC() ) {
bccLine->setText( smtp->getBCC() );
}
replyLine->clear();
if ( smtp->getUseReply() ) {
replyLine->setText( smtp->getReply() );
}
sigMultiLine->setText( smtp->getSignature() );
#endif
}
void ComposeMail::slotAdjustColumns()
{
int currPage = tabWidget->currentPageIndex();
tabWidget->showPage( attachTab );
attList->setColumnWidth( 0, attList->visibleWidth() - 80 );
attList->setColumnWidth( 1, 80 );
tabWidget->setCurrentPage( currPage );
}
void ComposeMail::addAttachment()
{
DocLnk lnk = OFileDialog::getOpenFileName( 1, "/" );
if ( !lnk.name().isEmpty() ) {
Attachment *att = new Attachment( lnk );
(void) new AttachViewItem( attList, att );
}
}
void ComposeMail::removeAttachment()
{
if ( !attList->currentItem() ) {
QMessageBox::information( this, tr( "Error" ),
tr( "<p>Please select a File.</p>" ),
tr( "Ok" ) );
} else {
attList->takeItem( attList->currentItem() );
}
}
void ComposeMail::accept()
{
if ( checkBoxLater->isChecked() ) {
- qDebug( "Send later" );
+ odebug << "Send later" << oendl;
}
#if 0
qDebug( "Sending Mail with " +
smtpAccounts.at( smtpAccountBox->currentItem() )->getAccountName() );
#endif
Opie::Core::OSmartPointer<Mail> mail=new Mail;
SMTPaccount *smtp = smtpAccounts.at( smtpAccountBox->currentItem() );
mail->setMail(fromBox->currentText());
if ( !toLine->text().isEmpty() ) {
mail->setTo( toLine->text() );
} else {
QMessageBox::warning(0,tr("Sending mail"),
tr("No Receiver spezified" ) );
return;
}
mail->setName(senderNameEdit->text());
mail->setCC( ccLine->text() );
mail->setBCC( bccLine->text() );
mail->setReply( replyLine->text() );
mail->setSubject( subjectLine->text() );
if (!m_replyid.isEmpty()) {
QStringList ids;
ids.append(m_replyid);
mail->setInreply(ids);
}
QString txt = message->text();
if ( !sigMultiLine->text().isEmpty() ) {
txt.append( "\n--\n" );
txt.append( sigMultiLine->text() );
}
mail->setMessage( txt );
AttachViewItem *it = (AttachViewItem *) attList->firstChild();
while ( it != NULL ) {
mail->addAttachment( it->getAttachment() );
it = (AttachViewItem *) it->nextSibling();
}
SMTPwrapper wrapper( smtp );
wrapper.sendMail( mail,checkBoxLater->isChecked() );
QDialog::accept();
}
void ComposeMail::reject()
{
int yesno = QMessageBox::warning(0,tr("Store message"),
tr("Store message into drafts?"),
tr("Yes"),
tr("No"),QString::null,0,1);
if (yesno == 0) {
Opie::Core::OSmartPointer<Mail> mail=new Mail();
mail->setMail(fromBox->currentText());
mail->setTo( toLine->text() );
mail->setName(senderNameEdit->text());
mail->setCC( ccLine->text() );
mail->setBCC( bccLine->text() );
mail->setReply( replyLine->text() );
mail->setSubject( subjectLine->text() );
if (!m_replyid.isEmpty()) {
QStringList ids;
ids.append(m_replyid);
mail->setInreply(ids);
}
QString txt = message->text();
if ( !sigMultiLine->text().isEmpty() ) {
txt.append( "\n--\n" );
txt.append( sigMultiLine->text() );
}
- qDebug(txt);
+ odebug << txt << oendl;
mail->setMessage( txt );
/* only use the default drafts folder name! */
Storemail wrapper(AbstractMail::draftFolder());
wrapper.storeMail(mail);
AttachViewItem *it = (AttachViewItem *) attList->firstChild();
/* attachments we will ignore! */
if ( it != NULL ) {
QMessageBox::warning(0,tr("Store message"),
tr("<center>Attachments will not be stored in \"Draft\" folder</center>"));
}
}
QDialog::reject();
}
ComposeMail::~ComposeMail()
{
}
void ComposeMail::reEditMail(const RecMailP&current)
{
RecMailP data = current;
message->setText(data->Wrapper()->fetchBody(current)->Bodytext());
subjectLine->setText( data->getSubject());
toLine->setText(data->To().join(","));
ccLine->setText(data->CC().join(","));
bccLine->setText(data->Bcc().join(","));
replyLine->setText(data->Replyto());
}
AttachViewItem::AttachViewItem( QListView *parent, Attachment *att )
: QListViewItem( parent )
{
attachment = att;
- qDebug( att->getMimeType() );
+ odebug << att->getMimeType() << oendl;
setPixmap( 0, attachment->getDocLnk().pixmap().isNull() ?
Resource::loadPixmap( "UnknownDocument-14" ) :
attachment->getDocLnk().pixmap() );
setText( 0, att->getName().isEmpty() ? att->getFileName() : att->getName() );
setText( 1, QString::number( att->getSize() ) );
}
diff --git a/noncore/net/mail/editaccounts.cpp b/noncore/net/mail/editaccounts.cpp
index 5c4bdf7..de064ca 100644
--- a/noncore/net/mail/editaccounts.cpp
+++ b/noncore/net/mail/editaccounts.cpp
@@ -1,361 +1,361 @@
#include "defines.h"
#include "editaccounts.h"
/* OPIE */
#include <qpe/qpeapplication.h>
/* QT */
#include <qt.h>
#include <qstringlist.h>
#include <libmailwrapper/nntpwrapper.h>
AccountListItem::AccountListItem( QListView *parent, Account *a)
: QListViewItem( parent )
{
account = a;
setText( 0, account->getAccountName() );
QString ttext = "";
switch (account->getType()) {
case MAILLIB::A_NNTP:
ttext="NNTP";
break;
case MAILLIB::A_POP3:
ttext = "POP3";
break;
case MAILLIB::A_IMAP:
ttext = "IMAP";
break;
case MAILLIB::A_SMTP:
ttext = "SMTP";
break;
default:
ttext = "UNKNOWN";
break;
}
setText( 1, ttext);
}
EditAccounts::EditAccounts( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags )
: EditAccountsUI( parent, name, modal, flags )
{
- qDebug( "New Account Configuration Widget" );
+ odebug << "New Account Configuration Widget" << oendl;
settings = s;
mailList->addColumn( tr( "Account" ) );
mailList->addColumn( tr( "Type" ) );
newsList->addColumn( tr( "Account" ) );
connect( newMail, SIGNAL( clicked() ), SLOT( slotNewMail() ) );
connect( editMail, SIGNAL( clicked() ), SLOT( slotEditMail() ) );
connect( deleteMail, SIGNAL( clicked() ), SLOT( slotDeleteMail() ) );
connect( newNews, SIGNAL( clicked() ), SLOT( slotNewNews() ) );
connect( editNews, SIGNAL( clicked() ), SLOT( slotEditNews() ) );
connect( deleteNews, SIGNAL( clicked() ), SLOT( slotDeleteNews() ) );
slotFillLists();
}
void EditAccounts::slotFillLists()
{
mailList->clear();
newsList->clear();
QList<Account> accounts = settings->getAccounts();
Account *it;
for ( it = accounts.first(); it; it = accounts.next() )
{
if ( it->getType()==MAILLIB::A_NNTP )
{
(void) new AccountListItem( newsList, it );
}
else
{
(void) new AccountListItem( mailList, it );
}
}
}
void EditAccounts::slotNewMail()
{
- qDebug( "New Mail Account" );
+ odebug << "New Mail Account" << oendl;
QString *selection = new QString();
SelectMailType selType( selection, this, 0, true );
selType.show();
if ( QDialog::Accepted == selType.exec() )
{
slotNewAccount( *selection );
}
}
void EditAccounts::slotNewAccount( const QString &type )
{
if ( type.compare( "IMAP" ) == 0 )
{
- qDebug( "-> config IMAP" );
+ odebug << "-> config IMAP" << oendl;
IMAPaccount *account = new IMAPaccount();
IMAPconfig imap( account, this, 0, true );
if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) )
{
settings->addAccount( account );
account->save();
slotFillLists();
}
else
{
account->remove();
}
}
else if ( type.compare( "POP3" ) == 0 )
{
- qDebug( "-> config POP3" );
+ odebug << "-> config POP3" << oendl;
POP3account *account = new POP3account();
POP3config pop3( account, this, 0, true, WStyle_ContextHelp );
if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) )
{
settings->addAccount( account );
account->save();
slotFillLists();
}
else
{
account->remove();
}
}
else if ( type.compare( "SMTP" ) == 0 )
{
- qDebug( "-> config SMTP" );
+ odebug << "-> config SMTP" << oendl;
SMTPaccount *account = new SMTPaccount();
SMTPconfig smtp( account, this, 0, true, WStyle_ContextHelp );
if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) )
{
settings->addAccount( account );
account->save();
slotFillLists();
}
else
{
account->remove();
}
}
else if ( type.compare( "NNTP" ) == 0 )
{
- qDebug( "-> config NNTP" );
+ odebug << "-> config NNTP" << oendl;
NNTPaccount *account = new NNTPaccount();
NNTPconfig nntp( account, this, 0, true, WStyle_ContextHelp );
if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) )
{
settings->addAccount( account );
account->save();
slotFillLists();
}
else
{
account->remove();
}
}
}
void EditAccounts::slotEditAccount( Account *account )
{
if ( account->getType() == MAILLIB::A_IMAP )
{
IMAPaccount *imapAcc = static_cast<IMAPaccount *>(account);
IMAPconfig imap( imapAcc, this, 0, true, WStyle_ContextHelp );
if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) )
{
slotFillLists();
}
}
else if ( account->getType()==MAILLIB::A_POP3 )
{
POP3account *pop3Acc = static_cast<POP3account *>(account);
POP3config pop3( pop3Acc, this, 0, true, WStyle_ContextHelp );
if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) )
{
slotFillLists();
}
}
else if ( account->getType()==MAILLIB::A_SMTP )
{
SMTPaccount *smtpAcc = static_cast<SMTPaccount *>(account);
SMTPconfig smtp( smtpAcc, this, 0, true, WStyle_ContextHelp );
if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) )
{
slotFillLists();
}
}
else if ( account->getType()==MAILLIB::A_NNTP)
{
NNTPaccount *nntpAcc = static_cast<NNTPaccount *>(account);
NNTPconfig nntp( nntpAcc, this, 0, true, WStyle_ContextHelp );
if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) )
{
slotFillLists();
}
}
}
void EditAccounts::slotDeleteAccount( Account *account )
{
if ( QMessageBox::information( this, tr( "Question" ),
tr( "<p>Do you really want to delete the selected Account?</p>" ),
tr( "Yes" ), tr( "No" ) ) == 0 )
{
settings->delAccount( account );
slotFillLists();
}
}
void EditAccounts::slotEditMail()
{
- qDebug( "Edit Mail Account" );
+ odebug << "Edit Mail Account" << oendl;
if ( !mailList->currentItem() )
{
QMessageBox::information( this, tr( "Error" ),
tr( "<p>Please select an account.</p>" ),
tr( "Ok" ) );
return;
}
Account *a = ((AccountListItem *) mailList->currentItem())->getAccount();
slotEditAccount( a );
}
void EditAccounts::slotDeleteMail()
{
if ( !mailList->currentItem() )
{
QMessageBox::information( this, tr( "Error" ),
tr( "<p>Please select an account.</p>" ),
tr( "Ok" ) );
return;
}
Account *a = ((AccountListItem *) mailList->currentItem())->getAccount();
slotDeleteAccount( a );
}
void EditAccounts::slotNewNews()
{
- qDebug( "New News Account" );
+ odebug << "New News Account" << oendl;
slotNewAccount( "NNTP" );
}
void EditAccounts::slotEditNews()
{
- qDebug( "Edit News Account" );
+ odebug << "Edit News Account" << oendl;
if ( !newsList->currentItem() )
{
QMessageBox::information( this, tr( "Error" ),
tr( "<p>Please select an account.</p>" ),
tr( "Ok" ) );
return;
}
Account *a = ((AccountListItem *) newsList->currentItem())->getAccount();
slotEditAccount( a );
}
void EditAccounts::slotDeleteNews()
{
- qDebug( "Delete News Account" );
+ odebug << "Delete News Account" << oendl;
if ( !newsList->currentItem() )
{
QMessageBox::information( this, tr( "Error" ),
tr( "<p>Please select an account.</p>" ),
tr( "Ok" ) );
return;
}
Account *a = ((AccountListItem *) newsList->currentItem())->getAccount();
slotDeleteAccount( a );
}
void EditAccounts::slotAdjustColumns()
{
int currPage = configTab->currentPageIndex();
configTab->showPage( mailTab );
mailList->setColumnWidth( 0, mailList->visibleWidth() - 50 );
mailList->setColumnWidth( 1, 50 );
configTab->showPage( newsTab );
newsList->setColumnWidth( 0, newsList->visibleWidth() );
configTab->setCurrentPage( currPage );
}
void EditAccounts::accept()
{
settings->saveAccounts();
QDialog::accept();
}
/**
* SelectMailType
*/
SelectMailType::SelectMailType( QString *selection, QWidget *parent, const char *name, bool modal, WFlags flags )
: SelectMailTypeUI( parent, name, modal, flags )
{
selected = selection;
selected->replace( 0, selected->length(), typeBox->currentText() );
connect( typeBox, SIGNAL( activated(const QString&) ), SLOT( slotSelection(const QString&) ) );
}
void SelectMailType::slotSelection( const QString &sel )
{
selected->replace( 0, selected->length(), sel );
}
/**
* IMAPconfig
*/
IMAPconfig::IMAPconfig( IMAPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags )
: IMAPconfigUI( parent, name, modal, flags )
{
data = account;
fillValues();
connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) );
ComboBox1->insertItem( "Only if available", 0 );
ComboBox1->insertItem( "Always, Negotiated", 1 );
ComboBox1->insertItem( "Connect on secure port", 2 );
ComboBox1->insertItem( "Run command instead", 3 );
CommandEdit->hide();
ComboBox1->setCurrentItem( data->ConnectionType() );
}
void IMAPconfig::slotConnectionToggle( int index )
{
if ( index == 2 )
{
portLine->setText( IMAP_SSL_PORT );
}
else if ( index == 3 )
{
portLine->setText( IMAP_PORT );
CommandEdit->show();
}
else
{
portLine->setText( IMAP_PORT );
}
}
void IMAPconfig::fillValues()
{
accountLine->setText( data->getAccountName() );
serverLine->setText( data->getServer() );
portLine->setText( data->getPort() );
ComboBox1->setCurrentItem( data->ConnectionType() );
userLine->setText( data->getUser() );
passLine->setText( data->getPassword() );
prefixLine->setText(data->getPrefix());
@@ -485,110 +485,110 @@ void SMTPconfig::fillValues()
passLine->setText( data->getPassword() );
}
void SMTPconfig::accept()
{
data->setAccountName( accountLine->text() );
data->setServer( serverLine->text() );
data->setPort( portLine->text() );
data->setConnectionType( ComboBox1->currentItem() );
data->setLogin( loginBox->isChecked() );
data->setUser( userLine->text() );
data->setPassword( passLine->text() );
QDialog::accept();
}
/**
* NNTPconfig
*/
NNTPconfig::NNTPconfig( NNTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags )
: NNTPconfigUI( parent, name, modal, flags )
{
data = account;
connect( loginBox, SIGNAL( toggled(bool) ), userLine, SLOT( setEnabled(bool) ) );
connect( loginBox, SIGNAL( toggled(bool) ), passLine, SLOT( setEnabled(bool) ) );
connect( GetNGButton, SIGNAL( clicked() ), this, SLOT( slotGetNG() ) );
fillValues();
connect( sslBox, SIGNAL( toggled(bool) ), SLOT( slotSSL(bool) ) );
}
void NNTPconfig::slotGetNG() {
save();
data->save();
NNTPwrapper* tmp = new NNTPwrapper( data );
QStringList list = tmp->listAllNewsgroups();
ListViewGroups->clear();
for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
QCheckListItem *item;
item = new QCheckListItem( ListViewGroups, (*it), QCheckListItem::CheckBox );
if ( subscribedGroups.contains( (*it) ) >= 1 ) {
item->setOn( true );
}
}
}
void NNTPconfig::slotSSL( bool enabled )
{
if ( enabled )
{
portLine->setText( NNTP_SSL_PORT );
}
else
{
portLine->setText( NNTP_PORT );
}
}
void NNTPconfig::fillValues()
{
accountLine->setText( data->getAccountName() );
serverLine->setText( data->getServer() );
portLine->setText( data->getPort() );
sslBox->setChecked( data->getSSL() );
loginBox->setChecked( data->getLogin() );
userLine->setText( data->getUser() );
passLine->setText( data->getPassword() );
subscribedGroups = data->getGroups();
/* don't forget that - you will overwrite values if user clicks cancel! */
for ( QStringList::Iterator it = subscribedGroups.begin(); it != subscribedGroups.end(); ++it ) {
QCheckListItem *item;
item = new QCheckListItem( ListViewGroups, (*it), QCheckListItem::CheckBox );
item->setOn( true );
}
}
void NNTPconfig::save()
{
data->setAccountName( accountLine->text() );
data->setServer( serverLine->text() );
data->setPort( portLine->text() );
data->setSSL( sslBox->isChecked() );
data->setLogin( loginBox->isChecked() );
data->setUser( userLine->text() );
data->setPassword( passLine->text() );
QListViewItemIterator list_it( ListViewGroups );
QStringList groupList;
for ( ; list_it.current(); ++list_it ) {
if ( ( (QCheckListItem*)list_it.current() )->isOn() ) {
- qDebug(list_it.current()->text(0) );
+ odebug << list_it.current()->text(0) << oendl;
groupList.append( list_it.current()->text(0) );
}
}
data->setGroups( groupList );
}
void NNTPconfig::accept()
{
save();
QDialog::accept();
}
diff --git a/noncore/net/mail/libmailwrapper/abstractmail.cpp b/noncore/net/mail/libmailwrapper/abstractmail.cpp
index 6bebb7b..1a26351 100644
--- a/noncore/net/mail/libmailwrapper/abstractmail.cpp
+++ b/noncore/net/mail/libmailwrapper/abstractmail.cpp
@@ -1,168 +1,168 @@
#include "abstractmail.h"
#include "imapwrapper.h"
#include "pop3wrapper.h"
#include "nntpwrapper.h"
#include "mhwrapper.h"
#include "mailtypes.h"
#include <qfile.h>
#include <qtextstream.h>
#include <stdlib.h>
#include <libetpan/mailmime_content.h>
#include <libetpan/mailmime.h>
using namespace Opie::Core;
AbstractMail* AbstractMail::getWrapper(IMAPaccount *a)
{
return new IMAPwrapper(a);
}
AbstractMail* AbstractMail::getWrapper(POP3account *a)
{
return new POP3wrapper(a);
}
AbstractMail* AbstractMail::getWrapper(NNTPaccount *a)
{
return new NNTPwrapper(a);
}
AbstractMail* AbstractMail::getWrapper(const QString&a,const QString&name)
{
return new MHwrapper(a,name);
}
AbstractMail* AbstractMail::getWrapper(Account*a)
{
if (!a) return 0;
switch (a->getType()) {
case MAILLIB::A_IMAP:
return new IMAPwrapper((IMAPaccount*)a);
break;
case MAILLIB::A_POP3:
return new POP3wrapper((POP3account*)a);
break;
case MAILLIB::A_NNTP:
return new NNTPwrapper((NNTPaccount*)a);
break;
default:
return 0;
}
}
encodedString* AbstractMail::decode_String(const encodedString*text,const QString&enc)
{
- qDebug("Decode string start");
+ odebug << "Decode string start" << oendl;
char*result_text;
size_t index = 0;
/* reset for recursive use! */
size_t target_length = 0;
result_text = 0;
int mimetype = MAILMIME_MECHANISM_7BIT;
if (enc.lower()=="quoted-printable") {
mimetype = MAILMIME_MECHANISM_QUOTED_PRINTABLE;
} else if (enc.lower()=="base64") {
mimetype = MAILMIME_MECHANISM_BASE64;
} else if (enc.lower()=="8bit") {
mimetype = MAILMIME_MECHANISM_8BIT;
} else if (enc.lower()=="binary") {
mimetype = MAILMIME_MECHANISM_BINARY;
}
int err = mailmime_part_parse(text->Content(),text->Length(),&index,mimetype,
&result_text,&target_length);
encodedString* result = new encodedString();
if (err == MAILIMF_NO_ERROR) {
result->setContent(result_text,target_length);
}
- qDebug("Decode string finished");
+ odebug << "Decode string finished" << oendl;
return result;
}
QString AbstractMail::convert_String(const char*text)
{
//size_t index = 0;
char*res = 0;
int err = MAILIMF_NO_ERROR;
QString result(text);
/* due a bug in libetpan it isn't usable this moment */
/* int err = mailmime_encoded_phrase_parse("iso-8859-1",
text, strlen(text),&index, "iso-8859-1",&res);*/
- //qDebug("Input: %s",text);
+ //odebug << "Input: " << text << "" << oendl;
if (err == MAILIMF_NO_ERROR && res && strlen(res)) {
// result = QString(res);
-// qDebug("Res: %s, length: %i",res,strlen(res));
+// odebug << "Res: " << res << ", length: " << strlen(res) << "" << oendl;
}
if (res) free(res);
return result;
}
/* cp & paste from launcher */
QString AbstractMail::gen_attachment_id()
{
QFile file( "/proc/sys/kernel/random/uuid" );
if (!file.open(IO_ReadOnly ) )
return QString::null;
QTextStream stream(&file);
return "{" + stream.read().stripWhiteSpace() + "}";
}
int AbstractMail::createMbox(const QString&,const FolderP&,const QString& ,bool)
{
return 0;
}
QString AbstractMail::defaultLocalfolder()
{
QString f = getenv( "HOME" );
f += "/Applications/opiemail/localmail";
return f;
}
QString AbstractMail::draftFolder()
{
return QString("Drafts");
}
/* temporary - will be removed when implemented in all classes */
void AbstractMail::deleteMails(const QString &,const QValueList<Opie::Core::OSmartPointer<RecMail> > &)
{
}
void AbstractMail::mvcpAllMails(const FolderP&fromFolder,
const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
{
QValueList<RecMailP> t;
listMessages(fromFolder->getName(),t);
encodedString*st = 0;
while (t.count()>0) {
RecMailP r = (*t.begin());
st = fetchRawBody(r);
if (st) {
targetWrapper->storeMessage(st->Content(),st->Length(),targetFolder);
delete st;
}
t.remove(t.begin());
}
if (moveit) {
deleteAllMail(fromFolder);
}
}
void AbstractMail::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
{
encodedString*st = 0;
st = fetchRawBody(mail);
if (st) {
targetWrapper->storeMessage(st->Content(),st->Length(),targetFolder);
delete st;
}
if (moveit) {
deleteMail(mail);
}
}
diff --git a/noncore/net/mail/libmailwrapper/generatemail.cpp b/noncore/net/mail/libmailwrapper/generatemail.cpp
index cb58d82..36ec232 100644
--- a/noncore/net/mail/libmailwrapper/generatemail.cpp
+++ b/noncore/net/mail/libmailwrapper/generatemail.cpp
@@ -4,465 +4,465 @@
#include <libetpan/libetpan.h>
#include <qt.h>
using namespace Opie::Core;
const char* Generatemail::USER_AGENT="OpieMail v0.6";
Generatemail::Generatemail()
{
}
Generatemail::~Generatemail()
{
}
void Generatemail::addRcpts( clist *list, mailimf_address_list *addr_list ) {
clistiter *it, *it2;
for ( it = clist_begin( addr_list->ad_list ); it; it = it->next ) {
mailimf_address *addr;
addr = (mailimf_address *) it->data;
if ( addr->ad_type == MAILIMF_ADDRESS_MAILBOX ) {
esmtp_address_list_add( list, addr->ad_data.ad_mailbox->mb_addr_spec, 0, NULL );
} else if ( addr->ad_type == MAILIMF_ADDRESS_GROUP ) {
clist *l = addr->ad_data.ad_group->grp_mb_list->mb_list;
for ( it2 = clist_begin( l ); it2; it2 = it2->next ) {
mailimf_mailbox *mbox;
mbox = (mailimf_mailbox *) it2->data;
esmtp_address_list_add( list, mbox->mb_addr_spec, 0, NULL );
}
}
}
}
char *Generatemail::getFrom( mailimf_field *ffrom) {
char *from = NULL;
if ( ffrom && (ffrom->fld_type == MAILIMF_FIELD_FROM)
&& ffrom->fld_data.fld_from->frm_mb_list && ffrom->fld_data.fld_from->frm_mb_list->mb_list ) {
clist *cl = ffrom->fld_data.fld_from->frm_mb_list->mb_list;
clistiter *it;
for ( it = clist_begin( cl ); it; it = it->next ) {
mailimf_mailbox *mb = (mailimf_mailbox *) it->data;
from = strdup( mb->mb_addr_spec );
}
}
return from;
}
char *Generatemail::getFrom( mailmime *mail ) {
/* no need to delete - its just a pointer to structure content */
mailimf_field *ffrom = 0;
ffrom = getField( mail->mm_data.mm_message.mm_fields, MAILIMF_FIELD_FROM );
return getFrom(ffrom);
}
mailimf_field *Generatemail::getField( mailimf_fields *fields, int type ) {
mailimf_field *field;
clistiter *it;
it = clist_begin( fields->fld_list );
while ( it ) {
field = (mailimf_field *) it->data;
if ( field->fld_type == type ) {
return field;
}
it = it->next;
}
return NULL;
}
mailimf_address_list *Generatemail::parseAddresses(const QString&addr ) {
mailimf_address_list *addresses;
if ( addr.isEmpty() )
return NULL;
addresses = mailimf_address_list_new_empty();
bool literal_open = false;
unsigned int startpos = 0;
QStringList list;
QString s;
unsigned int i = 0;
for (; i < addr.length();++i) {
switch (addr[i]) {
case '\"':
literal_open = !literal_open;
break;
case ',':
if (!literal_open) {
s = addr.mid(startpos,i-startpos);
if (!s.isEmpty()) {
list.append(s);
- qDebug("Appended %s",s.latin1());
+ odebug << "Appended " << s.latin1() << "" << oendl;
}
// !!!! this is a MUST BE!
startpos = ++i;
}
break;
default:
break;
}
}
s = addr.mid(startpos,i-startpos);
if (!s.isEmpty()) {
list.append(s);
- qDebug("Appended %s",s.latin1());
+ odebug << "Appended " << s.latin1() << "" << oendl;
}
QStringList::Iterator it;
for ( it = list.begin(); it != list.end(); it++ ) {
int err = mailimf_address_list_add_parse( addresses, (char*)(*it).latin1() );
if ( err != MAILIMF_NO_ERROR ) {
- qDebug( "Error parsing" );
- qDebug( *it );
+ odebug << "Error parsing" << oendl;
+ odebug << *it << oendl;
} else {
- qDebug( "Parse success! %s",(*it).latin1());
+ odebug << "Parse success! " << (*it).latin1() << "" << oendl;
}
}
return addresses;
}
mailmime *Generatemail::buildFilePart(const QString&filename,const QString&mimetype,const QString&TextContent ) {
mailmime * filePart = 0;
mailmime_fields * fields = 0;
mailmime_content * content = 0;
mailmime_parameter * param = 0;
char*name = 0;
char*file = 0;
int err;
int pos = filename.findRev( '/' );
if (filename.length()>0) {
QString tmp = filename.right( filename.length() - ( pos + 1 ) );
name = strdup( tmp.latin1() ); // just filename
file = strdup( filename.latin1() ); // full name with path
}
int disptype = MAILMIME_DISPOSITION_TYPE_ATTACHMENT;
int mechanism = MAILMIME_MECHANISM_BASE64;
if ( mimetype.startsWith( "text/" ) ) {
param = mailmime_parameter_new( strdup( "charset" ),
strdup( "iso-8859-1" ) );
mechanism = MAILMIME_MECHANISM_QUOTED_PRINTABLE;
}
fields = mailmime_fields_new_filename(
disptype, name,
mechanism );
content = mailmime_content_new_with_str( (char*)mimetype.latin1() );
if (content!=0 && fields != 0) {
if (param) {
clist_append(content->ct_parameters,param);
param = 0;
}
if (filename.length()>0) {
QFileInfo f(filename);
param = mailmime_parameter_new(strdup("name"),strdup(f.fileName().latin1()));
clist_append(content->ct_parameters,param);
param = 0;
}
filePart = mailmime_new_empty( content, fields );
}
if (filePart) {
if (filename.length()>0) {
err = mailmime_set_body_file( filePart, file );
} else {
err = mailmime_set_body_text(filePart,strdup(TextContent.data()),TextContent.length());
}
if (err != MAILIMF_NO_ERROR) {
- qDebug("Error setting body with file %s",file);
+ odebug << "Error setting body with file " << file << "" << oendl;
mailmime_free( filePart );
filePart = 0;
}
}
if (!filePart) {
if ( param != NULL ) {
mailmime_parameter_free( param );
}
if (content) {
mailmime_content_free( content );
}
if (fields) {
mailmime_fields_free( fields );
} else {
if (name) {
free( name );
}
if (file) {
free( file );
}
}
}
return filePart; // Success :)
}
void Generatemail::addFileParts( mailmime *message,const QList<Attachment>&files ) {
const Attachment *it;
unsigned int count = files.count();
- qDebug("List contains %i values",count);
+ odebug << "List contains " << count << " values" << oendl;
for ( unsigned int i = 0; i < count; ++i ) {
- qDebug( "Adding file" );
+ odebug << "Adding file" << oendl;
mailmime *filePart;
int err;
it = ((QList<Attachment>)files).at(i);
filePart = buildFilePart( it->getFileName(), it->getMimeType(),"" );
if ( filePart == NULL ) {
- qDebug( "addFileParts: error adding file:" );
- qDebug( it->getFileName() );
+ odebug << "addFileParts: error adding file:" << oendl;
+ odebug << it->getFileName() << oendl;
continue;
}
err = mailmime_smart_add_part( message, filePart );
if ( err != MAILIMF_NO_ERROR ) {
mailmime_free( filePart );
- qDebug("error smart add");
+ odebug << "error smart add" << oendl;
}
}
}
mailmime *Generatemail::buildTxtPart(const QString&str ) {
mailmime *txtPart;
mailmime_fields *fields;
mailmime_content *content;
mailmime_parameter *param;
int err;
param = mailmime_parameter_new( strdup( "charset" ),
strdup( "iso-8859-1" ) );
if ( param == NULL )
goto err_free;
content = mailmime_content_new_with_str( "text/plain" );
if ( content == NULL )
goto err_free_param;
err = clist_append( content->ct_parameters, param );
if ( err != MAILIMF_NO_ERROR )
goto err_free_content;
fields = mailmime_fields_new_encoding(MAILMIME_MECHANISM_8BIT);
if ( fields == NULL )
goto err_free_content;
txtPart = mailmime_new_empty( content, fields );
if ( txtPart == NULL )
goto err_free_fields;
err = mailmime_set_body_text( txtPart, (char*)str.data(), str.length() );
if ( err != MAILIMF_NO_ERROR )
goto err_free_txtPart;
return txtPart; // Success :)
err_free_txtPart:
mailmime_free( txtPart );
err_free_fields:
mailmime_fields_free( fields );
err_free_content:
mailmime_content_free( content );
err_free_param:
mailmime_parameter_free( param );
err_free:
- qDebug( "buildTxtPart - error" );
+ odebug << "buildTxtPart - error" << oendl;
return NULL; // Error :(
}
mailimf_mailbox *Generatemail::newMailbox(const QString&name, const QString&mail ) {
return mailimf_mailbox_new( strdup( name.latin1() ),
strdup( mail.latin1() ) );
}
mailimf_fields *Generatemail::createImfFields(const Opie::Core::OSmartPointer<Mail>&mail )
{
mailimf_fields *fields = NULL;
mailimf_field *xmailer = NULL;
mailimf_mailbox *sender=0,*fromBox=0;
mailimf_mailbox_list *from=0;
mailimf_address_list *to=0, *cc=0, *bcc=0, *reply=0;
clist*in_reply_to = 0;
char *subject = strdup( mail->getSubject().latin1() );
int err;
int res = 1;
sender = newMailbox( mail->getName(), mail->getMail() );
if ( sender == NULL ) {
res = 0;
}
if (res) {
fromBox = newMailbox( mail->getName(), mail->getMail() );
}
if ( fromBox == NULL ) {
res = 0;
}
if (res) {
from = mailimf_mailbox_list_new_empty();
}
if ( from == NULL ) {
res = 0;
}
if (res && from) {
err = mailimf_mailbox_list_add( from, fromBox );
if ( err != MAILIMF_NO_ERROR ) {
res = 0;
}
}
if (res) to = parseAddresses( mail->getTo() );
if (res) cc = parseAddresses( mail->getCC() );
if (res) bcc = parseAddresses( mail->getBCC() );
if (res) reply = parseAddresses( mail->getReply() );
if (res && mail->Inreply().count()>0) {
in_reply_to = clist_new();
char*c_reply;
unsigned int nsize = 0;
for (QStringList::ConstIterator it=mail->Inreply().begin();
it != mail->Inreply().end();++it) {
if ((*it).isEmpty())
continue;
QString h((*it));
while (h.length()>0 && h[0]=='<') {
h.remove(0,1);
}
while (h.length()>0 && h[h.length()-1]=='>') {
h.remove(h.length()-1,1);
}
if (h.isEmpty()) continue;
nsize = strlen(h.latin1());
/* yes! must be malloc! */
c_reply = (char*)malloc( (nsize+1)*sizeof(char));
memset(c_reply,0,nsize+1);
memcpy(c_reply,h.latin1(),nsize);
clist_append(in_reply_to,c_reply);
- qDebug("In reply to: %s",c_reply);
+ odebug << "In reply to: " << c_reply << "" << oendl;
}
}
if (res) {
fields = mailimf_fields_new_with_data( from, sender, reply, to, cc, bcc,
in_reply_to, NULL, subject );
if ( fields == NULL ) {
- qDebug("Error creating mailimf fields");
+ odebug << "Error creating mailimf fields" << oendl;
res = 0;
}
}
if (res) xmailer = mailimf_field_new_custom( strdup( "User-Agent" ),
strdup( USER_AGENT ) );
if ( xmailer == NULL ) {
res = 0;
} else {
err = mailimf_fields_add( fields, xmailer );
if ( err != MAILIMF_NO_ERROR ) {
res = 0;
}
}
if (!res ) {
if (xmailer) {
mailimf_field_free( xmailer );
xmailer = NULL;
}
if (fields) {
mailimf_fields_free( fields );
fields = NULL;
} else {
if (reply)
mailimf_address_list_free( reply );
if (bcc)
mailimf_address_list_free( bcc );
if (cc)
mailimf_address_list_free( cc );
if (to)
mailimf_address_list_free( to );
if (fromBox) {
mailimf_mailbox_free( fromBox );
} else if (from) {
mailimf_mailbox_list_free( from );
}
if (sender) {
mailimf_mailbox_free( sender );
}
if (subject) {
free( subject );
}
}
}
return fields;
}
mailmime *Generatemail::createMimeMail(const Opie::Core::OSmartPointer<Mail> &mail ) {
mailmime *message, *txtPart;
mailimf_fields *fields;
int err;
fields = createImfFields( mail );
if ( fields == NULL )
goto err_free;
message = mailmime_new_message_data( NULL );
if ( message == NULL )
goto err_free_fields;
mailmime_set_imf_fields( message, fields );
txtPart = buildTxtPart( mail->getMessage() );
if ( txtPart == NULL )
goto err_free_message;
err = mailmime_smart_add_part( message, txtPart );
if ( err != MAILIMF_NO_ERROR )
goto err_free_txtPart;
addFileParts( message, mail->getAttachments() );
return message; // Success :)
err_free_txtPart:
mailmime_free( txtPart );
err_free_message:
mailmime_free( message );
err_free_fields:
mailimf_fields_free( fields );
err_free:
- qDebug( "createMimeMail: error" );
+ odebug << "createMimeMail: error" << oendl;
return NULL; // Error :(
}
clist *Generatemail::createRcptList( mailimf_fields *fields ) {
clist *rcptList;
mailimf_field *field;
rcptList = esmtp_address_list_new();
field = getField( fields, MAILIMF_FIELD_TO );
if ( field && (field->fld_type == MAILIMF_FIELD_TO)
&& field->fld_data.fld_to->to_addr_list ) {
addRcpts( rcptList, field->fld_data.fld_to->to_addr_list );
}
field = getField( fields, MAILIMF_FIELD_CC );
if ( field && (field->fld_type == MAILIMF_FIELD_CC)
&& field->fld_data.fld_cc->cc_addr_list ) {
addRcpts( rcptList, field->fld_data.fld_cc->cc_addr_list );
}
field = getField( fields, MAILIMF_FIELD_BCC );
if ( field && (field->fld_type == MAILIMF_FIELD_BCC)
&& field->fld_data.fld_bcc->bcc_addr_list ) {
addRcpts( rcptList, field->fld_data.fld_bcc->bcc_addr_list );
}
return rcptList;
}
diff --git a/noncore/net/mail/libmailwrapper/genericwrapper.cpp b/noncore/net/mail/libmailwrapper/genericwrapper.cpp
index 0c68280..fae4c99 100644
--- a/noncore/net/mail/libmailwrapper/genericwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/genericwrapper.cpp
@@ -42,435 +42,435 @@ void Genericwrapper::fillSingleBody(RecPartP&target,mailmessage*,mailmime*mime)
target->setSubtype("plain");
} else {
target->setSubtype(type->ct_subtype);
switch(type->ct_type->tp_data.tp_discrete_type->dt_type) {
case MAILMIME_DISCRETE_TYPE_TEXT:
target->setType("text");
break;
case MAILMIME_DISCRETE_TYPE_IMAGE:
target->setType("image");
break;
case MAILMIME_DISCRETE_TYPE_AUDIO:
target->setType("audio");
break;
case MAILMIME_DISCRETE_TYPE_VIDEO:
target->setType("video");
break;
case MAILMIME_DISCRETE_TYPE_APPLICATION:
target->setType("application");
break;
case MAILMIME_DISCRETE_TYPE_EXTENSION:
default:
if (type->ct_type->tp_data.tp_discrete_type->dt_extension) {
target->setType(type->ct_type->tp_data.tp_discrete_type->dt_extension);
}
break;
}
if (type->ct_parameters) {
fillParameters(target,type->ct_parameters);
}
}
if (mime->mm_mime_fields && mime->mm_mime_fields->fld_list) {
for (current=clist_begin(mime->mm_mime_fields->fld_list);current!=0;current=clist_next(current)) {
field = (mailmime_field*)current->data;
switch(field->fld_type) {
case MAILMIME_FIELD_TRANSFER_ENCODING:
target->setEncoding(getencoding(field->fld_data.fld_encoding));
break;
case MAILMIME_FIELD_ID:
target->setIdentifier(field->fld_data.fld_id);
break;
case MAILMIME_FIELD_DESCRIPTION:
target->setDescription(field->fld_data.fld_description);
break;
default:
break;
}
}
}
}
void Genericwrapper::fillParameters(RecPartP&target,clist*parameters)
{
if (!parameters) {return;}
clistcell*current=0;
mailmime_parameter*param;
for (current=clist_begin(parameters);current!=0;current=clist_next(current)) {
param = (mailmime_parameter*)current->data;
if (param) {
target->addParameter(QString(param->pa_name).lower(),QString(param->pa_value));
}
}
}
QString Genericwrapper::getencoding(mailmime_mechanism*aEnc)
{
QString enc="7bit";
if (!aEnc) return enc;
switch(aEnc->enc_type) {
case MAILMIME_MECHANISM_7BIT:
enc = "7bit";
break;
case MAILMIME_MECHANISM_8BIT:
enc = "8bit";
break;
case MAILMIME_MECHANISM_BINARY:
enc = "binary";
break;
case MAILMIME_MECHANISM_QUOTED_PRINTABLE:
enc = "quoted-printable";
break;
case MAILMIME_MECHANISM_BASE64:
enc = "base64";
break;
case MAILMIME_MECHANISM_TOKEN:
default:
if (aEnc->enc_token) {
enc = QString(aEnc->enc_token);
}
break;
}
return enc;
}
void Genericwrapper::traverseBody(RecBodyP&target,mailmessage*message,mailmime*mime,QValueList<int>recList,unsigned int current_rec,int current_count)
{
if (current_rec >= 10) {
- qDebug("too deep recursion!");
+ odebug << "too deep recursion!" << oendl;
}
if (!message || !mime) {
return;
}
int r;
char*data = 0;
size_t len;
clistiter * cur = 0;
QString b;
RecPartP part = new RecPart();
switch (mime->mm_type) {
case MAILMIME_SINGLE:
{
QValueList<int>countlist = recList;
countlist.append(current_count);
r = mailmessage_fetch_section(message,mime,&data,&len);
part->setSize(len);
part->setPositionlist(countlist);
b = gen_attachment_id();
part->setIdentifier(b);
fillSingleBody(part,message,mime);
if (part->Type()=="text" && target->Bodytext().isNull()) {
encodedString*rs = new encodedString();
rs->setContent(data,len);
encodedString*res = decode_String(rs,part->Encoding());
if (countlist.count()>2) {
bodyCache[b]=rs;
target->addPart(part);
} else {
delete rs;
}
b = QString(res->Content());
delete res;
target->setBodytext(b);
target->setDescription(part);
} else {
bodyCache[b]=new encodedString(data,len);
target->addPart(part);
}
}
break;
case MAILMIME_MULTIPLE:
{
unsigned int ccount = 1;
mailmime*cbody=0;
QValueList<int>countlist = recList;
for (cur = clist_begin(mime->mm_data.mm_multipart.mm_mp_list) ; cur != NULL ; cur = clist_next(cur)) {
cbody = (mailmime*)clist_content(cur);
if (cbody->mm_type==MAILMIME_MULTIPLE) {
RecPartP targetPart = new RecPart();
targetPart->setType("multipart");
countlist.append(current_count);
targetPart->setPositionlist(countlist);
target->addPart(targetPart);
}
traverseBody(target,message, cbody,countlist,current_rec+1,ccount);
if (cbody->mm_type==MAILMIME_MULTIPLE) {
countlist = recList;
}
++ccount;
}
}
break;
case MAILMIME_MESSAGE:
{
QValueList<int>countlist = recList;
countlist.append(current_count);
/* the own header is always at recursion 0 - we don't need that */
if (current_rec > 0) {
part->setPositionlist(countlist);
r = mailmessage_fetch_section(message,mime,&data,&len);
part->setSize(len);
part->setPositionlist(countlist);
b = gen_attachment_id();
part->setIdentifier(b);
part->setType("message");
part->setSubtype("rfc822");
bodyCache[b]=new encodedString(data,len);
target->addPart(part);
}
if (mime->mm_data.mm_message.mm_msg_mime != NULL) {
traverseBody(target,message,mime->mm_data.mm_message.mm_msg_mime,countlist,current_rec+1);
}
}
break;
}
}
RecBodyP Genericwrapper::parseMail( mailmessage * msg )
{
int err = MAILIMF_NO_ERROR;
mailmime_single_fields fields;
/* is bound to msg and will be freed there */
mailmime * mime=0;
RecBodyP body = new RecBody();
memset(&fields, 0, sizeof(struct mailmime_single_fields));
err = mailmessage_get_bodystructure(msg,&mime);
QValueList<int>recList;
traverseBody(body,msg,mime,recList);
return body;
}
QString Genericwrapper::parseDateTime( mailimf_date_time *date )
{
char tmp[23];
snprintf( tmp, 23, "%02i.%02i.%04i %02i:%02i:%02i %+05i",
date->dt_day, date->dt_month, date->dt_year, date->dt_hour, date->dt_min, date->dt_sec, date->dt_zone );
return QString( tmp );
}
QString Genericwrapper::parseAddressList( mailimf_address_list *list )
{
QString result( "" );
bool first = true;
if (list == 0) return result;
for ( clistiter *current = clist_begin( list->ad_list ); current != NULL; current = current->next ) {
mailimf_address *addr = (mailimf_address *) current->data;
if ( !first ) {
result.append( "," );
} else {
first = false;
}
switch ( addr->ad_type ) {
case MAILIMF_ADDRESS_MAILBOX:
result.append( parseMailbox( addr->ad_data.ad_mailbox ) );
break;
case MAILIMF_ADDRESS_GROUP:
result.append( parseGroup( addr->ad_data.ad_group ) );
break;
default:
- qDebug( "Generic: unkown mailimf address type" );
+ odebug << "Generic: unkown mailimf address type" << oendl;
break;
}
}
return result;
}
QString Genericwrapper::parseGroup( mailimf_group *group )
{
QString result( "" );
result.append( group->grp_display_name );
result.append( ": " );
if ( group->grp_mb_list != NULL ) {
result.append( parseMailboxList( group->grp_mb_list ) );
}
result.append( ";" );
return result;
}
QString Genericwrapper::parseMailbox( mailimf_mailbox *box )
{
QString result( "" );
if ( box->mb_display_name == NULL ) {
result.append( box->mb_addr_spec );
} else {
result.append( convert_String(box->mb_display_name).latin1() );
result.append( " <" );
result.append( box->mb_addr_spec );
result.append( ">" );
}
return result;
}
QString Genericwrapper::parseMailboxList( mailimf_mailbox_list *list )
{
QString result( "" );
bool first = true;
for ( clistiter *current = clist_begin( list->mb_list ); current != NULL; current = current->next ) {
mailimf_mailbox *box = (mailimf_mailbox *) current->data;
if ( !first ) {
result.append( "," );
} else {
first = false;
}
result.append( parseMailbox( box ) );
}
return result;
}
encodedString* Genericwrapper::fetchDecodedPart(const RecMailP&,const RecPartP&part)
{
QMap<QString,encodedString*>::ConstIterator it = bodyCache.find(part->Identifier());
if (it==bodyCache.end()) return new encodedString();
encodedString*t = decode_String(it.data(),part->Encoding());
return t;
}
encodedString* Genericwrapper::fetchRawPart(const RecMailP&,const RecPartP&part)
{
QMap<QString,encodedString*>::ConstIterator it = bodyCache.find(part->Identifier());
if (it==bodyCache.end()) return new encodedString();
encodedString*t = it.data();
return t;
}
QString Genericwrapper::fetchTextPart(const RecMailP&mail,const RecPartP&part)
{
encodedString*t = fetchDecodedPart(mail,part);
QString text=t->Content();
delete t;
return text;
}
void Genericwrapper::cleanMimeCache()
{
QMap<QString,encodedString*>::Iterator it = bodyCache.begin();
for (;it!=bodyCache.end();++it) {
encodedString*t = it.data();
//it.setValue(0);
if (t) delete t;
}
bodyCache.clear();
- qDebug("Genericwrapper: cache cleaned");
+ odebug << "Genericwrapper: cache cleaned" << oendl;
}
QStringList Genericwrapper::parseInreplies(mailimf_in_reply_to * in_replies)
{
QStringList res;
if (!in_replies || !in_replies->mid_list) return res;
clistiter * current = 0;
for ( current = clist_begin( in_replies->mid_list ); current != NULL; current = current->next ) {
QString h((char*)current->data);
while (h.length()>0 && h[0]=='<') {
h.remove(0,1);
}
while (h.length()>0 && h[h.length()-1]=='>') {
h.remove(h.length()-1,1);
}
if (h.length()>0) {
res.append(h);
}
}
return res;
}
void Genericwrapper::parseList(QValueList<Opie::Core::OSmartPointer<RecMail> > &target,mailsession*session,const QString&mailbox,bool mbox_as_to)
{
int r;
mailmessage_list * env_list = 0;
r = mailsession_get_messages_list(session,&env_list);
if (r != MAIL_NO_ERROR) {
- qDebug("Error message list");
+ odebug << "Error message list" << oendl;
return;
}
r = mailsession_get_envelopes_list(session, env_list);
if (r != MAIL_NO_ERROR) {
- qDebug("Error filling message list");
+ odebug << "Error filling message list" << oendl;
if (env_list) {
mailmessage_list_free(env_list);
}
return;
}
mailimf_references * refs = 0;
mailimf_in_reply_to * in_replies = 0;
uint32_t i = 0;
for(; i < carray_count(env_list->msg_tab) ; ++i) {
mailmessage * msg;
QBitArray mFlags(7);
msg = (mailmessage*)carray_get(env_list->msg_tab, i);
if (msg->msg_fields == NULL) {
- //qDebug("could not fetch envelope of message %i", i);
+ //odebug << "could not fetch envelope of message " << i << "" << oendl;
continue;
}
RecMailP mail = new RecMail();
mail->setWrapper(this);
mail_flags * flag_result = 0;
r = mailmessage_get_flags(msg,&flag_result);
if (r == MAIL_ERROR_NOT_IMPLEMENTED) {
mFlags.setBit(FLAG_SEEN);
}
mailimf_single_fields single_fields;
mailimf_single_fields_init(&single_fields, msg->msg_fields);
mail->setMsgsize(msg->msg_size);
mail->setFlags(mFlags);
mail->setMbox(mailbox);
mail->setNumber(msg->msg_index);
if (single_fields.fld_subject)
mail->setSubject( convert_String(single_fields.fld_subject->sbj_value));
if (single_fields.fld_from)
mail->setFrom(parseMailboxList(single_fields.fld_from->frm_mb_list));
if (!mbox_as_to) {
if (single_fields.fld_to)
mail->setTo( parseAddressList( single_fields.fld_to->to_addr_list ) );
} else {
mail->setTo(mailbox);
}
if (single_fields.fld_cc)
mail->setCC( parseAddressList( single_fields.fld_cc->cc_addr_list ) );
if (single_fields.fld_bcc)
mail->setBcc( parseAddressList( single_fields.fld_bcc->bcc_addr_list ) );
if (single_fields.fld_orig_date)
mail->setDate( parseDateTime( single_fields.fld_orig_date->dt_date_time ) );
// crashes when accessing pop3 account?
if (single_fields.fld_message_id->mid_value) {
mail->setMsgid(QString(single_fields.fld_message_id->mid_value));
- qDebug("Msgid == %s",mail->Msgid().latin1());
+ odebug << "Msgid == " << mail->Msgid().latin1() << "" << oendl;
}
if (single_fields.fld_reply_to) {
QStringList t = parseAddressList(single_fields.fld_reply_to->rt_addr_list);
if (t.count()>0) {
mail->setReplyto(t[0]);
}
}
#if 0
refs = single_fields.fld_references;
if (refs && refs->mid_list && clist_count(refs->mid_list)) {
char * text = (char*)refs->mid_list->first->data;
mail->setReplyto(QString(text));
}
#endif
if (single_fields.fld_in_reply_to && single_fields.fld_in_reply_to->mid_list &&
clist_count(single_fields.fld_in_reply_to->mid_list)) {
mail->setInreply(parseInreplies(single_fields.fld_in_reply_to));
}
target.append(mail);
}
if (env_list) {
mailmessage_list_free(env_list);
}
}
diff --git a/noncore/net/mail/libmailwrapper/imapwrapper.cpp b/noncore/net/mail/libmailwrapper/imapwrapper.cpp
index 657c2ba..35468fe 100644
--- a/noncore/net/mail/libmailwrapper/imapwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/imapwrapper.cpp
@@ -1,1187 +1,1187 @@
#include <stdlib.h>
#include <libetpan/libetpan.h>
#include <qpe/global.h>
#include <opie2/oapplication.h>
#include "imapwrapper.h"
#include "mailtypes.h"
#include "logindialog.h"
using namespace Opie::Core;
IMAPwrapper::IMAPwrapper( IMAPaccount *a )
: AbstractMail()
{
account = a;
m_imap = 0;
m_Lastmbox = "";
}
IMAPwrapper::~IMAPwrapper()
{
logout();
}
/* to avoid to often select statements in loops etc.
we trust that we are logged in and connection is established!*/
int IMAPwrapper::selectMbox(const QString&mbox)
{
if (mbox == m_Lastmbox) {
return MAILIMAP_NO_ERROR;
}
int err = mailimap_select( m_imap, (char*)mbox.latin1());
if ( err != MAILIMAP_NO_ERROR ) {
- qDebug("error selecting mailbox: %s",m_imap->imap_response);
+ odebug << "error selecting mailbox: " << m_imap->imap_response << "" << oendl;
m_Lastmbox = "";
return err;
}
m_Lastmbox = mbox;
return err;
}
void IMAPwrapper::imap_progress( size_t current, size_t maximum )
{
qApp->processEvents();
- qDebug( "IMAP: %i of %i", current, maximum );
+ odebug << "IMAP: " << current << " of " << maximum << "" << oendl;
}
bool IMAPwrapper::start_tls(bool force_tls)
{
int err;
bool try_tls;
mailimap_capability_data * cap_data = 0;
err = mailimap_capability(m_imap,&cap_data);
if (err != MAILIMAP_NO_ERROR) {
Global::statusMessage("error getting capabilities!");
- qDebug("error getting capabilities!");
+ odebug << "error getting capabilities!" << oendl;
return false;
}
clistiter * cur;
for(cur = clist_begin(cap_data->cap_list) ; cur != NULL;cur = clist_next(cur)) {
struct mailimap_capability * cap;
cap = (struct mailimap_capability *)clist_content(cur);
if (cap->cap_type == MAILIMAP_CAPABILITY_NAME) {
if (strcasecmp(cap->cap_data.cap_name, "STARTTLS") == 0) {
try_tls = true;
break;
}
}
}
if (cap_data) {
mailimap_capability_data_free(cap_data);
}
if (try_tls) {
err = mailimap_starttls(m_imap);
if (err != MAILIMAP_NO_ERROR && force_tls) {
Global::statusMessage(tr("Server has no TLS support!"));
- qDebug("Server has no TLS support!");
+ odebug << "Server has no TLS support!" << oendl;
try_tls = false;
} else {
mailstream_low * low;
mailstream_low * new_low;
low = mailstream_get_low(m_imap->imap_stream);
if (!low) {
try_tls = false;
} else {
int fd = mailstream_low_get_fd(low);
if (fd > -1 && (new_low = mailstream_low_ssl_open(fd))!=0) {
mailstream_low_free(low);
mailstream_set_low(m_imap->imap_stream, new_low);
} else {
try_tls = false;
}
}
}
}
return try_tls;
}
void IMAPwrapper::login()
{
const char *server, *user, *pass;
uint16_t port;
int err = MAILIMAP_NO_ERROR;
if (account->getOffline()) return;
/* we are connected this moment */
/* TODO: setup a timer holding the line or if connection closed - delete the value */
if (m_imap) {
err = mailimap_noop(m_imap);
if (err!=MAILIMAP_NO_ERROR) {
logout();
} else {
mailstream_flush(m_imap->imap_stream);
return;
}
}
server = account->getServer().latin1();
port = account->getPort().toUInt();
if ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) {
LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true );
login.show();
if ( QDialog::Accepted == login.exec() ) {
// ok
user = login.getUser().latin1();
pass = login.getPassword().latin1();
} else {
// cancel
- qDebug( "IMAP: Login canceled" );
+ odebug << "IMAP: Login canceled" << oendl;
return;
}
} else {
user = account->getUser().latin1();
pass = account->getPassword().latin1();
}
m_imap = mailimap_new( 20, &imap_progress );
/* connect */
bool ssl = false;
bool try_tls = false;
bool force_tls = false;
if ( account->ConnectionType() == 2 ) {
ssl = true;
}
if (account->ConnectionType()==1) {
force_tls = true;
}
if ( ssl ) {
- qDebug( "using ssl" );
+ odebug << "using ssl" << oendl;
err = mailimap_ssl_connect( m_imap, (char*)server, port );
} else {
err = mailimap_socket_connect( m_imap, (char*)server, port );
}
if ( err != MAILIMAP_NO_ERROR &&
err != MAILIMAP_NO_ERROR_AUTHENTICATED &&
err != MAILIMAP_NO_ERROR_NON_AUTHENTICATED ) {
QString failure = "";
if (err == MAILIMAP_ERROR_CONNECTION_REFUSED) {
failure="Connection refused";
} else {
failure="Unknown failure";
}
Global::statusMessage(tr("error connecting imap server: %1").arg(failure));
mailimap_free( m_imap );
m_imap = 0;
return;
}
if (!ssl) {
try_tls = start_tls(force_tls);
}
bool ok = true;
if (force_tls && !try_tls) {
Global::statusMessage(tr("Server has no TLS support!"));
- qDebug("Server has no TLS support!");
+ odebug << "Server has no TLS support!" << oendl;
ok = false;
}
/* login */
if (ok) {
err = mailimap_login_simple( m_imap, (char*)user, (char*)pass );
if ( err != MAILIMAP_NO_ERROR ) {
Global::statusMessage(tr("error logging in imap server: %1").arg(m_imap->imap_response));
ok = false;
}
}
if (!ok) {
err = mailimap_close( m_imap );
mailimap_free( m_imap );
m_imap = 0;
}
}
void IMAPwrapper::logout()
{
int err = MAILIMAP_NO_ERROR;
if (!m_imap) return;
err = mailimap_logout( m_imap );
err = mailimap_close( m_imap );
mailimap_free( m_imap );
m_imap = 0;
m_Lastmbox = "";
}
void IMAPwrapper::listMessages(const QString&mailbox,QValueList<Opie::Core::OSmartPointer<RecMail> > &target )
{
int err = MAILIMAP_NO_ERROR;
clist *result = 0;
clistcell *current;
mailimap_fetch_type *fetchType = 0;
mailimap_set *set = 0;
login();
if (!m_imap) {
return;
}
/* select mailbox READONLY for operations */
err = selectMbox(mailbox);
if ( err != MAILIMAP_NO_ERROR ) {
return;
}
int last = m_imap->imap_selection_info->sel_exists;
if (last == 0) {
Global::statusMessage(tr("Mailbox has no mails"));
return;
} else {
}
/* the range has to start at 1!!! not with 0!!!! */
set = mailimap_set_new_interval( 1, last );
fetchType = mailimap_fetch_type_new_fetch_att_list_empty();
mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_envelope());
mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_flags());
mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_internaldate());
mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_rfc822_size());
err = mailimap_fetch( m_imap, set, fetchType, &result );
mailimap_set_free( set );
mailimap_fetch_type_free( fetchType );
QString date,subject,from;
if ( err == MAILIMAP_NO_ERROR ) {
mailimap_msg_att * msg_att;
int i = 0;
for (current = clist_begin(result); current != 0; current=clist_next(current)) {
++i;
msg_att = (mailimap_msg_att*)current->data;
RecMail*m = parse_list_result(msg_att);
if (m) {
m->setNumber(i);
m->setMbox(mailbox);
m->setWrapper(this);
target.append(m);
}
}
Global::statusMessage(tr("Mailbox has %1 mails").arg(target.count()));
} else {
Global::statusMessage(tr("Error fetching headers: %1").arg(m_imap->imap_response));
}
if (result) mailimap_fetch_list_free(result);
}
QValueList<Opie::Core::OSmartPointer<Folder> >* IMAPwrapper::listFolders()
{
const char *path, *mask;
int err = MAILIMAP_NO_ERROR;
clist *result = 0;
clistcell *current = 0;
clistcell*cur_flag = 0;
mailimap_mbx_list_flags*bflags = 0;
QValueList<FolderP>* folders = new QValueList<FolderP>();
login();
if (!m_imap) {
return folders;
}
/*
* First we have to check for INBOX 'cause it sometimes it's not inside the path.
* We must not forget to filter them out in next loop!
* it seems like ugly code. and yes - it is ugly code. but the best way.
*/
QString temp;
mask = "INBOX" ;
mailimap_mailbox_list *list;
err = mailimap_list( m_imap, (char*)"", (char*)mask, &result );
QString del;
bool selectable = true;
bool no_inferiors = false;
if ( err == MAILIMAP_NO_ERROR ) {
current = result->first;
for ( int i = result->count; i > 0; i-- ) {
list = (mailimap_mailbox_list *) current->data;
// it is better use the deep copy mechanism of qt itself
// instead of using strdup!
temp = list->mb_name;
del = list->mb_delimiter;
current = current->next;
if ( (bflags = list->mb_flag) ) {
selectable = !(bflags->mbf_type==MAILIMAP_MBX_LIST_FLAGS_SFLAG&&
bflags->mbf_sflag==MAILIMAP_MBX_LIST_SFLAG_NOSELECT);
for(cur_flag=clist_begin(bflags->mbf_oflags);cur_flag;cur_flag=clist_next(cur_flag)) {
if ( ((mailimap_mbx_list_oflag*)cur_flag->data)->of_type==MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS) {
no_inferiors = true;
}
}
}
folders->append( new IMAPFolder(temp,del,selectable,no_inferiors,account->getPrefix()));
}
} else {
- qDebug("error fetching folders: %s",m_imap->imap_response);
+ odebug << "error fetching folders: " << m_imap->imap_response << "" << oendl;
}
mailimap_list_result_free( result );
/*
* second stage - get the other then inbox folders
*/
mask = "*" ;
path = account->getPrefix().latin1();
if (!path) path = "";
- qDebug(path);
+ odebug << path << oendl;
err = mailimap_list( m_imap, (char*)path, (char*)mask, &result );
if ( err == MAILIMAP_NO_ERROR ) {
current = result->first;
for ( current=clist_begin(result);current!=NULL;current=clist_next(current)) {
no_inferiors = false;
list = (mailimap_mailbox_list *) current->data;
// it is better use the deep copy mechanism of qt itself
// instead of using strdup!
temp = list->mb_name;
if (temp.lower()=="inbox")
continue;
if (temp.lower()==account->getPrefix().lower())
continue;
if ( (bflags = list->mb_flag) ) {
selectable = !(bflags->mbf_type==MAILIMAP_MBX_LIST_FLAGS_SFLAG&&
bflags->mbf_sflag==MAILIMAP_MBX_LIST_SFLAG_NOSELECT);
for(cur_flag=clist_begin(bflags->mbf_oflags);cur_flag;cur_flag=clist_next(cur_flag)) {
if ( ((mailimap_mbx_list_oflag*)cur_flag->data)->of_type==MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS) {
no_inferiors = true;
}
}
}
del = list->mb_delimiter;
folders->append(new IMAPFolder(temp,del,selectable,no_inferiors,account->getPrefix()));
}
} else {
- qDebug("error fetching folders %s",m_imap->imap_response);
+ odebug << "error fetching folders " << m_imap->imap_response << "" << oendl;
}
if (result) mailimap_list_result_free( result );
return folders;
}
RecMail*IMAPwrapper::parse_list_result(mailimap_msg_att* m_att)
{
RecMail * m = 0;
mailimap_msg_att_item *item=0;
clistcell *current,*c,*cf;
mailimap_msg_att_dynamic*flist;
mailimap_flag_fetch*cflag;
int size;
QBitArray mFlags(7);
QStringList addresslist;
if (!m_att) {
return m;
}
m = new RecMail();
for (c = clist_begin(m_att->att_list); c!=NULL;c=clist_next(c) ) {
current = c;
size = 0;
item = (mailimap_msg_att_item*)current->data;
if (item->att_type!=MAILIMAP_MSG_ATT_ITEM_STATIC) {
flist = (mailimap_msg_att_dynamic*)item->att_data.att_dyn;
if (!flist->att_list) {
continue;
}
cf = flist->att_list->first;
for (cf = clist_begin(flist->att_list); cf!=NULL; cf = clist_next(cf)) {
cflag = (mailimap_flag_fetch*)cf->data;
if (cflag->fl_type==MAILIMAP_FLAG_FETCH_OTHER && cflag->fl_flag!=0) {
switch (cflag->fl_flag->fl_type) {
case MAILIMAP_FLAG_ANSWERED: /* \Answered flag */
mFlags.setBit(FLAG_ANSWERED);
break;
case MAILIMAP_FLAG_FLAGGED: /* \Flagged flag */
mFlags.setBit(FLAG_FLAGGED);
break;
case MAILIMAP_FLAG_DELETED: /* \Deleted flag */
mFlags.setBit(FLAG_DELETED);
break;
case MAILIMAP_FLAG_SEEN: /* \Seen flag */
mFlags.setBit(FLAG_SEEN);
break;
case MAILIMAP_FLAG_DRAFT: /* \Draft flag */
mFlags.setBit(FLAG_DRAFT);
break;
case MAILIMAP_FLAG_KEYWORD: /* keyword flag */
break;
case MAILIMAP_FLAG_EXTENSION: /* \extension flag */
break;
default:
break;
}
} else if (cflag->fl_type==MAILIMAP_FLAG_FETCH_RECENT) {
mFlags.setBit(FLAG_RECENT);
}
}
continue;
}
if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_ENVELOPE) {
mailimap_envelope * head = item->att_data.att_static->att_data.att_env;
m->setDate(head->env_date);
m->setSubject(convert_String((const char*)head->env_subject));
//m->setSubject(head->env_subject);
if (head->env_from!=NULL) {
addresslist = address_list_to_stringlist(head->env_from->frm_list);
if (addresslist.count()) {
m->setFrom(addresslist.first());
}
}
if (head->env_to!=NULL) {
addresslist = address_list_to_stringlist(head->env_to->to_list);
m->setTo(addresslist);
}
if (head->env_cc!=NULL) {
addresslist = address_list_to_stringlist(head->env_cc->cc_list);
m->setCC(addresslist);
}
if (head->env_bcc!=NULL) {
addresslist = address_list_to_stringlist(head->env_bcc->bcc_list);
m->setBcc(addresslist);
}
/* reply to address, eg. email. */
if (head->env_reply_to!=NULL) {
addresslist = address_list_to_stringlist(head->env_reply_to->rt_list);
if (addresslist.count()) {
m->setReplyto(addresslist.first());
}
}
if (head->env_in_reply_to!=NULL) {
QString h(head->env_in_reply_to);
while (h.length()>0 && h[0]=='<') {
h.remove(0,1);
}
while (h.length()>0 && h[h.length()-1]=='>') {
h.remove(h.length()-1,1);
}
if (h.length()>0) {
m->setInreply(QStringList(h));
}
}
if (head->env_message_id) {
m->setMsgid(QString(head->env_message_id));
}
} else if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_INTERNALDATE) {
#if 0
mailimap_date_time*d = item->att_data.att_static->att_data.att_internal_date;
QDateTime da(QDate(d->dt_year,d->dt_month,d->dt_day),QTime(d->dt_hour,d->dt_min,d->dt_sec));
- qDebug("%i %i %i - %i %i %i",d->dt_year,d->dt_month,d->dt_day,d->dt_hour,d->dt_min,d->dt_sec);
- qDebug(da.toString());
+ odebug << "" << d->dt_year << " " << d->dt_month << " " << d->dt_day << " - " << d->dt_hour << " " << d->dt_min << " " << d->dt_sec << "" << oendl;
+ odebug << da.toString() << oendl;
#endif
} else if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_RFC822_SIZE) {
size = item->att_data.att_static->att_data.att_rfc822_size;
}
}
/* msg is already deleted */
if (mFlags.testBit(FLAG_DELETED) && m) {
delete m;
m = 0;
}
if (m) {
m->setFlags(mFlags);
m->setMsgsize(size);
}
return m;
}
RecBodyP IMAPwrapper::fetchBody(const RecMailP&mail)
{
RecBodyP body = new RecBody();
const char *mb;
int err = MAILIMAP_NO_ERROR;
clist *result = 0;
clistcell *current;
mailimap_fetch_att *fetchAtt = 0;
mailimap_fetch_type *fetchType = 0;
mailimap_set *set = 0;
mailimap_body*body_desc = 0;
mb = mail->getMbox().latin1();
login();
if (!m_imap) {
return body;
}
err = selectMbox(mail->getMbox());
if ( err != MAILIMAP_NO_ERROR ) {
return body;
}
/* the range has to start at 1!!! not with 0!!!! */
set = mailimap_set_new_interval( mail->getNumber(),mail->getNumber() );
fetchAtt = mailimap_fetch_att_new_bodystructure();
fetchType = mailimap_fetch_type_new_fetch_att(fetchAtt);
err = mailimap_fetch( m_imap, set, fetchType, &result );
mailimap_set_free( set );
mailimap_fetch_type_free( fetchType );
if (err == MAILIMAP_NO_ERROR && (current=clist_begin(result)) ) {
mailimap_msg_att * msg_att;
msg_att = (mailimap_msg_att*)current->data;
mailimap_msg_att_item*item = (mailimap_msg_att_item*)msg_att->att_list->first->data;
QValueList<int> path;
body_desc = item->att_data.att_static->att_data.att_body;
traverseBody(mail,body_desc,body,0,path);
} else {
- qDebug("error fetching body: %s",m_imap->imap_response);
+ odebug << "error fetching body: " << m_imap->imap_response << "" << oendl;
}
if (result) mailimap_fetch_list_free(result);
return body;
}
QStringList IMAPwrapper::address_list_to_stringlist(clist*list)
{
QStringList l;
QString from;
bool named_from;
clistcell *current = NULL;
mailimap_address * current_address=NULL;
if (!list) {
return l;
}
unsigned int count = 0;
for (current=clist_begin(list);current!= NULL;current=clist_next(current)) {
from = "";
named_from = false;
current_address=(mailimap_address*)current->data;
if (current_address->ad_personal_name){
from+=convert_String((const char*)current_address->ad_personal_name);
from+=" ";
named_from = true;
}
if (named_from && (current_address->ad_mailbox_name || current_address->ad_host_name)) {
from+="<";
}
if (current_address->ad_mailbox_name) {
from+=QString(current_address->ad_mailbox_name);
from+="@";
}
if (current_address->ad_host_name) {
from+=QString(current_address->ad_host_name);
}
if (named_from && (current_address->ad_mailbox_name || current_address->ad_host_name)) {
from+=">";
}
l.append(QString(from));
if (++count > 99) {
break;
}
}
return l;
}
encodedString*IMAPwrapper::fetchRawPart(const RecMailP&mail,const QValueList<int>&path,bool internal_call)
{
encodedString*res=new encodedString;
int err;
mailimap_fetch_type *fetchType;
mailimap_set *set;
clistcell*current,*cur;
mailimap_section_part * section_part = 0;
mailimap_section_spec * section_spec = 0;
mailimap_section * section = 0;
mailimap_fetch_att * fetch_att = 0;
login();
if (!m_imap) {
return res;
}
if (!internal_call) {
err = selectMbox(mail->getMbox());
if ( err != MAILIMAP_NO_ERROR ) {
return res;
}
}
set = mailimap_set_new_single(mail->getNumber());
clist*id_list = 0;
/* if path == empty then its a request for the whole rfc822 mail and generates
a "fetch <id> (body[])" statement on imap server */
if (path.count()>0 ) {
id_list = clist_new();
for (unsigned j=0; j < path.count();++j) {
uint32_t * p_id = (uint32_t *)malloc(sizeof(*p_id));
*p_id = path[j];
clist_append(id_list,p_id);
}
section_part = mailimap_section_part_new(id_list);
section_spec = mailimap_section_spec_new(MAILIMAP_SECTION_SPEC_SECTION_PART, NULL, section_part, NULL);
}
section = mailimap_section_new(section_spec);
fetch_att = mailimap_fetch_att_new_body_section(section);
fetchType = mailimap_fetch_type_new_fetch_att(fetch_att);
clist*result = 0;
err = mailimap_fetch( m_imap, set, fetchType, &result );
mailimap_set_free( set );
mailimap_fetch_type_free( fetchType );
if (err == MAILIMAP_NO_ERROR && (current=clist_begin(result)) ) {
mailimap_msg_att * msg_att;
msg_att = (mailimap_msg_att*)current->data;
mailimap_msg_att_item*msg_att_item;
for(cur = clist_begin(msg_att->att_list) ; cur != NULL ; cur = clist_next(cur)) {
msg_att_item = (mailimap_msg_att_item*)clist_content(cur);
if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
if (msg_att_item->att_data.att_static->att_type == MAILIMAP_MSG_ATT_BODY_SECTION) {
char*text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
/* detach - we take over the content */
msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = 0L;
res->setContent(text,msg_att_item->att_data.att_static->att_data.att_body_section->sec_length);
}
}
}
} else {
- qDebug("error fetching text: %s",m_imap->imap_response);
+ odebug << "error fetching text: " << m_imap->imap_response << "" << oendl;
}
if (result) mailimap_fetch_list_free(result);
return res;
}
/* current_recursion is for recursive calls.
current_count means the position inside the internal loop! */
void IMAPwrapper::traverseBody(const RecMailP&mail,mailimap_body*body,RecBodyP&target_body,
int current_recursion,QValueList<int>recList,int current_count)
{
if (!body || current_recursion>=10) {
return;
}
switch (body->bd_type) {
case MAILIMAP_BODY_1PART:
{
QValueList<int>countlist = recList;
countlist.append(current_count);
RecPartP currentPart = new RecPart();
mailimap_body_type_1part*part1 = body->bd_data.bd_body_1part;
QString id("");
currentPart->setPositionlist(countlist);
for (unsigned int j = 0; j < countlist.count();++j) {
id+=(j>0?" ":"");
id+=QString("%1").arg(countlist[j]);
}
- qDebug("ID = %s",id.latin1());
+ odebug << "ID = " << id.latin1() << "" << oendl;
currentPart->setIdentifier(id);
fillSinglePart(currentPart,part1);
/* important: Check for is NULL 'cause a body can be empty!
And we put it only into the mail if it is the FIRST part */
if (part1->bd_type==MAILIMAP_BODY_TYPE_1PART_TEXT && target_body->Bodytext().isNull() && countlist[0]==1) {
QString body_text = fetchTextPart(mail,countlist,true,currentPart->Encoding());
target_body->setDescription(currentPart);
target_body->setBodytext(body_text);
if (countlist.count()>1) {
target_body->addPart(currentPart);
}
} else {
target_body->addPart(currentPart);
}
if (part1->bd_type==MAILIMAP_BODY_TYPE_1PART_MSG) {
traverseBody(mail,part1->bd_data.bd_type_msg->bd_body,target_body,current_recursion+1,countlist);
}
}
break;
case MAILIMAP_BODY_MPART:
{
QValueList<int>countlist = recList;
clistcell*current=0;
mailimap_body*current_body=0;
unsigned int ccount = 1;
mailimap_body_type_mpart*mailDescription = body->bd_data.bd_body_mpart;
for (current=clist_begin(mailDescription->bd_list);current!=0;current=clist_next(current)) {
current_body = (mailimap_body*)current->data;
if (current_body->bd_type==MAILIMAP_BODY_MPART) {
RecPartP targetPart = new RecPart();
targetPart->setType("multipart");
fillMultiPart(targetPart,mailDescription);
countlist.append(current_count);
targetPart->setPositionlist(countlist);
target_body->addPart(targetPart);
QString id("");
for (unsigned int j = 0; j < countlist.count();++j) {
id+=(j>0?" ":"");
id+=QString("%1").arg(countlist[j]);
}
- qDebug("ID(mpart) = %s",id.latin1());
+ odebug << "ID(mpart) = " << id.latin1() << "" << oendl;
}
traverseBody(mail,current_body,target_body,current_recursion+1,countlist,ccount);
if (current_body->bd_type==MAILIMAP_BODY_MPART) {
countlist = recList;
}
++ccount;
}
}
break;
default:
break;
}
}
void IMAPwrapper::fillSinglePart(RecPartP&target_part,mailimap_body_type_1part*Description)
{
if (!Description) {
return;
}
switch (Description->bd_type) {
case MAILIMAP_BODY_TYPE_1PART_TEXT:
target_part->setType("text");
fillSingleTextPart(target_part,Description->bd_data.bd_type_text);
break;
case MAILIMAP_BODY_TYPE_1PART_BASIC:
fillSingleBasicPart(target_part,Description->bd_data.bd_type_basic);
break;
case MAILIMAP_BODY_TYPE_1PART_MSG:
target_part->setType("message");
fillSingleMsgPart(target_part,Description->bd_data.bd_type_msg);
break;
default:
break;
}
}
void IMAPwrapper::fillSingleTextPart(RecPartP&target_part,mailimap_body_type_text*which)
{
if (!which) {
return;
}
QString sub;
sub = which->bd_media_text;
- qDebug("Type= text/%s",which->bd_media_text);
+ odebug << "Type= text/" << which->bd_media_text << "" << oendl;
target_part->setSubtype(sub.lower());
target_part->setLines(which->bd_lines);
fillBodyFields(target_part,which->bd_fields);
}
void IMAPwrapper::fillSingleMsgPart(RecPartP&target_part,mailimap_body_type_msg*which)
{
if (!which) {
return;
}
target_part->setSubtype("rfc822");
- qDebug("Message part");
+ odebug << "Message part" << oendl;
/* we set this type to text/plain */
target_part->setLines(which->bd_lines);
fillBodyFields(target_part,which->bd_fields);
}
void IMAPwrapper::fillMultiPart(RecPartP&target_part,mailimap_body_type_mpart*which)
{
if (!which) return;
QString sub = which->bd_media_subtype;
target_part->setSubtype(sub.lower());
if (which->bd_ext_mpart && which->bd_ext_mpart->bd_parameter && which->bd_ext_mpart->bd_parameter->pa_list) {
clistcell*cur = 0;
mailimap_single_body_fld_param*param=0;
for (cur = clist_begin(which->bd_ext_mpart->bd_parameter->pa_list);cur!=NULL;cur=clist_next(cur)) {
param = (mailimap_single_body_fld_param*)cur->data;
if (param) {
target_part->addParameter(QString(param->pa_name).lower(),QString(param->pa_value));
}
}
}
}
void IMAPwrapper::fillSingleBasicPart(RecPartP&target_part,mailimap_body_type_basic*which)
{
if (!which) {
return;
}
QString type,sub;
switch (which->bd_media_basic->med_type) {
case MAILIMAP_MEDIA_BASIC_APPLICATION:
type = "application";
break;
case MAILIMAP_MEDIA_BASIC_AUDIO:
type = "audio";
break;
case MAILIMAP_MEDIA_BASIC_IMAGE:
type = "image";
break;
case MAILIMAP_MEDIA_BASIC_MESSAGE:
type = "message";
break;
case MAILIMAP_MEDIA_BASIC_VIDEO:
type = "video";
break;
case MAILIMAP_MEDIA_BASIC_OTHER:
default:
if (which->bd_media_basic->med_basic_type) {
type = which->bd_media_basic->med_basic_type;
} else {
type = "";
}
break;
}
if (which->bd_media_basic->med_subtype) {
sub = which->bd_media_basic->med_subtype;
} else {
sub = "";
}
- qDebug("Type = %s/%s",type.latin1(),sub.latin1());
+ odebug << "Type = " << type.latin1() << "/" << sub.latin1() << "" << oendl;
target_part->setType(type.lower());
target_part->setSubtype(sub.lower());
fillBodyFields(target_part,which->bd_fields);
}
void IMAPwrapper::fillBodyFields(RecPartP&target_part,mailimap_body_fields*which)
{
if (!which) return;
if (which->bd_parameter && which->bd_parameter->pa_list && which->bd_parameter->pa_list->count>0) {
clistcell*cur;
mailimap_single_body_fld_param*param=0;
for (cur = clist_begin(which->bd_parameter->pa_list);cur!=NULL;cur=clist_next(cur)) {
param = (mailimap_single_body_fld_param*)cur->data;
if (param) {
target_part->addParameter(QString(param->pa_name).lower(),QString(param->pa_value));
}
}
}
mailimap_body_fld_enc*enc = which->bd_encoding;
QString encoding("");
switch (enc->enc_type) {
case MAILIMAP_BODY_FLD_ENC_7BIT:
encoding = "7bit";
break;
case MAILIMAP_BODY_FLD_ENC_8BIT:
encoding = "8bit";
break;
case MAILIMAP_BODY_FLD_ENC_BINARY:
encoding="binary";
break;
case MAILIMAP_BODY_FLD_ENC_BASE64:
encoding="base64";
break;
case MAILIMAP_BODY_FLD_ENC_QUOTED_PRINTABLE:
encoding="quoted-printable";
break;
case MAILIMAP_BODY_FLD_ENC_OTHER:
default:
if (enc->enc_value) {
char*t=enc->enc_value;
encoding=QString(enc->enc_value);
enc->enc_value=0L;
free(t);
}
}
if (which->bd_description) {
target_part->setDescription(QString(which->bd_description));
}
target_part->setEncoding(encoding);
target_part->setSize(which->bd_size);
}
void IMAPwrapper::deleteMail(const RecMailP&mail)
{
mailimap_flag_list*flist;
mailimap_set *set;
mailimap_store_att_flags * store_flags;
int err;
login();
if (!m_imap) {
return;
}
err = selectMbox(mail->getMbox());
if ( err != MAILIMAP_NO_ERROR ) {
return;
}
flist = mailimap_flag_list_new_empty();
mailimap_flag_list_add(flist,mailimap_flag_new_deleted());
store_flags = mailimap_store_att_flags_new_set_flags(flist);
set = mailimap_set_new_single(mail->getNumber());
err = mailimap_store(m_imap,set,store_flags);
mailimap_set_free( set );
mailimap_store_att_flags_free(store_flags);
if (err != MAILIMAP_NO_ERROR) {
- qDebug("error deleting mail: %s",m_imap->imap_response);
+ odebug << "error deleting mail: " << m_imap->imap_response << "" << oendl;
return;
}
- qDebug("deleting mail: %s",m_imap->imap_response);
+ odebug << "deleting mail: " << m_imap->imap_response << "" << oendl;
/* should we realy do that at this moment? */
err = mailimap_expunge(m_imap);
if (err != MAILIMAP_NO_ERROR) {
- qDebug("error deleting mail: %s",m_imap->imap_response);
+ odebug << "error deleting mail: " << m_imap->imap_response << "" << oendl;
}
- qDebug("Delete successfull %s",m_imap->imap_response);
+ odebug << "Delete successfull " << m_imap->imap_response << "" << oendl;
}
void IMAPwrapper::answeredMail(const RecMailP&mail)
{
mailimap_flag_list*flist;
mailimap_set *set;
mailimap_store_att_flags * store_flags;
int err;
login();
if (!m_imap) {
return;
}
err = selectMbox(mail->getMbox());
if ( err != MAILIMAP_NO_ERROR ) {
return;
}
flist = mailimap_flag_list_new_empty();
mailimap_flag_list_add(flist,mailimap_flag_new_answered());
store_flags = mailimap_store_att_flags_new_add_flags(flist);
set = mailimap_set_new_single(mail->getNumber());
err = mailimap_store(m_imap,set,store_flags);
mailimap_set_free( set );
mailimap_store_att_flags_free(store_flags);
if (err != MAILIMAP_NO_ERROR) {
- qDebug("error marking mail: %s",m_imap->imap_response);
+ odebug << "error marking mail: " << m_imap->imap_response << "" << oendl;
return;
}
}
QString IMAPwrapper::fetchTextPart(const RecMailP&mail,const QValueList<int>&path,bool internal_call,const QString&enc)
{
QString body("");
encodedString*res = fetchRawPart(mail,path,internal_call);
encodedString*r = decode_String(res,enc);
delete res;
if (r) {
if (r->Length()>0) {
body = r->Content();
}
delete r;
}
return body;
}
QString IMAPwrapper::fetchTextPart(const RecMailP&mail,const RecPartP&part)
{
return fetchTextPart(mail,part->Positionlist(),false,part->Encoding());
}
encodedString* IMAPwrapper::fetchDecodedPart(const RecMailP&mail,const RecPartP&part)
{
encodedString*res = fetchRawPart(mail,part->Positionlist(),false);
encodedString*r = decode_String(res,part->Encoding());
delete res;
return r;
}
encodedString* IMAPwrapper::fetchRawPart(const RecMailP&mail,const RecPartP&part)
{
return fetchRawPart(mail,part->Positionlist(),false);
}
int IMAPwrapper::deleteAllMail(const FolderP&folder)
{
login();
if (!m_imap) {
return 0;
}
mailimap_flag_list*flist;
mailimap_set *set;
mailimap_store_att_flags * store_flags;
int err = selectMbox(folder->getName());
if ( err != MAILIMAP_NO_ERROR ) {
return 0;
}
int last = m_imap->imap_selection_info->sel_exists;
if (last == 0) {
Global::statusMessage(tr("Mailbox has no mails!"));
return 0;
}
flist = mailimap_flag_list_new_empty();
mailimap_flag_list_add(flist,mailimap_flag_new_deleted());
store_flags = mailimap_store_att_flags_new_set_flags(flist);
set = mailimap_set_new_interval( 1, last );
err = mailimap_store(m_imap,set,store_flags);
mailimap_set_free( set );
mailimap_store_att_flags_free(store_flags);
if (err != MAILIMAP_NO_ERROR) {
Global::statusMessage(tr("error deleting mail: %s").arg(m_imap->imap_response));
return 0;
}
- qDebug("deleting mail: %s",m_imap->imap_response);
+ odebug << "deleting mail: " << m_imap->imap_response << "" << oendl;
/* should we realy do that at this moment? */
err = mailimap_expunge(m_imap);
if (err != MAILIMAP_NO_ERROR) {
Global::statusMessage(tr("error deleting mail: %s").arg(m_imap->imap_response));
return 0;
}
- qDebug("Delete successfull %s",m_imap->imap_response);
+ odebug << "Delete successfull " << m_imap->imap_response << "" << oendl;
return 1;
}
int IMAPwrapper::createMbox(const QString&folder,const FolderP&parentfolder,const QString& delemiter,bool getsubfolder)
{
if (folder.length()==0) return 0;
login();
if (!m_imap) {return 0;}
QString pre = account->getPrefix();
if (delemiter.length()>0 && pre.findRev(delemiter)!=pre.length()-1) {
pre+=delemiter;
}
if (parentfolder) {
pre += parentfolder->getDisplayName()+delemiter;
}
pre+=folder;
if (getsubfolder) {
if (delemiter.length()>0) {
pre+=delemiter;
} else {
Global::statusMessage(tr("Cannot create folder %1 for holding subfolders").arg(pre));
return 0;
}
}
- qDebug("Creating %s",pre.latin1());
+ odebug << "Creating " << pre.latin1() << "" << oendl;
int res = mailimap_create(m_imap,pre.latin1());
if (res != MAILIMAP_NO_ERROR) {
Global::statusMessage(tr("%1").arg(m_imap->imap_response));
return 0;
}
return 1;
}
int IMAPwrapper::deleteMbox(const FolderP&folder)
{
if (!folder) return 0;
login();
if (!m_imap) {return 0;}
int res = mailimap_delete(m_imap,folder->getName());
if (res != MAILIMAP_NO_ERROR) {
Global::statusMessage(tr("%1").arg(m_imap->imap_response));
return 0;
}
return 1;
}
void IMAPwrapper::statusFolder(folderStat&target_stat,const QString & mailbox)
{
mailimap_status_att_list * att_list =0;
mailimap_mailbox_data_status * status=0;
clistiter * cur = 0;
int r = 0;
target_stat.message_count = 0;
target_stat.message_unseen = 0;
target_stat.message_recent = 0;
login();
if (!m_imap) {
return;
}
att_list = mailimap_status_att_list_new_empty();
if (!att_list) return;
r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_MESSAGES);
r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_RECENT);
r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_UNSEEN);
r = mailimap_status(m_imap, mailbox.latin1(), att_list, &status);
if (r==MAILIMAP_NO_ERROR&&status->st_info_list!=0) {
for (cur = clist_begin(status->st_info_list);
cur != NULL ; cur = clist_next(cur)) {
mailimap_status_info * status_info;
status_info = (mailimap_status_info *)clist_content(cur);
switch (status_info->st_att) {
case MAILIMAP_STATUS_ATT_MESSAGES:
target_stat.message_count = status_info->st_value;
break;
case MAILIMAP_STATUS_ATT_RECENT:
target_stat.message_recent = status_info->st_value;
break;
case MAILIMAP_STATUS_ATT_UNSEEN:
target_stat.message_unseen = status_info->st_value;
break;
}
}
} else {
- qDebug("Error retrieving status");
+ odebug << "Error retrieving status" << oendl;
}
if (status) mailimap_mailbox_data_status_free(status);
if (att_list) mailimap_status_att_list_free(att_list);
}
void IMAPwrapper::storeMessage(const char*msg,size_t length, const QString&folder)
{
login();
if (!m_imap) return;
if (!msg) return;
int r = mailimap_append(m_imap,(char*)folder.latin1(),0,0,msg,length);
if (r != MAILIMAP_NO_ERROR) {
Global::statusMessage("Error storing mail!");
}
}
MAILLIB::ATYPE IMAPwrapper::getType()const
{
return account->getType();
}
const QString&IMAPwrapper::getName()const
{
- qDebug("Get name: %s",account->getAccountName().latin1());
+ odebug << "Get name: " << account->getAccountName().latin1() << "" << oendl;
return account->getAccountName();
}
encodedString* IMAPwrapper::fetchRawBody(const RecMailP&mail)
{
// dummy
QValueList<int> path;
return fetchRawPart(mail,path,false);
}
void IMAPwrapper::mvcpAllMails(const FolderP&fromFolder,
const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
{
if (targetWrapper != this) {
AbstractMail::mvcpAllMails(fromFolder,targetFolder,targetWrapper,moveit);
- qDebug("Using generic");
+ odebug << "Using generic" << oendl;
return;
}
mailimap_set *set = 0;
login();
if (!m_imap) {
return;
}
int err = selectMbox(fromFolder->getName());
if ( err != MAILIMAP_NO_ERROR ) {
return;
}
int last = m_imap->imap_selection_info->sel_exists;
set = mailimap_set_new_interval( 1, last );
err = mailimap_copy(m_imap,set,targetFolder.latin1());
mailimap_set_free( set );
if ( err != MAILIMAP_NO_ERROR ) {
QString error_msg = tr("error copy mails: %1").arg(m_imap->imap_response);
Global::statusMessage(error_msg);
- qDebug(error_msg);
+ odebug << error_msg << oendl;
return;
}
if (moveit) {
deleteAllMail(fromFolder);
}
}
void IMAPwrapper::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
{
if (targetWrapper != this) {
- qDebug("Using generic");
+ odebug << "Using generic" << oendl;
AbstractMail::mvcpMail(mail,targetFolder,targetWrapper,moveit);
return;
}
mailimap_set *set = 0;
login();
if (!m_imap) {
return;
}
int err = selectMbox(mail->getMbox());
if ( err != MAILIMAP_NO_ERROR ) {
return;
}
set = mailimap_set_new_single(mail->getNumber());
err = mailimap_copy(m_imap,set,targetFolder.latin1());
mailimap_set_free( set );
if ( err != MAILIMAP_NO_ERROR ) {
QString error_msg = tr("error copy mail: %1").arg(m_imap->imap_response);
Global::statusMessage(error_msg);
- qDebug(error_msg);
+ odebug << error_msg << oendl;
return;
}
if (moveit) {
deleteMail(mail);
}
}
diff --git a/noncore/net/mail/libmailwrapper/logindialog.cpp b/noncore/net/mail/libmailwrapper/logindialog.cpp
index 01d177e..c9ae190 100644
--- a/noncore/net/mail/libmailwrapper/logindialog.cpp
+++ b/noncore/net/mail/libmailwrapper/logindialog.cpp
@@ -1,29 +1,29 @@
#include <qlineedit.h>
#include "logindialog.h"
LoginDialog::LoginDialog(const QString&user,const QString&pass, QWidget *parent, const char *name, bool modal, WFlags flags )
: LoginDialogUI( parent, name, modal, flags )
{
userLine->setText( (user.isEmpty()?QString(""):user) );
passLine->setText( (pass.isEmpty()?QString(""):pass) );
_user = user;
_pass = pass;
if ( user.isEmpty() ) {
userLine->setFocus();
} else {
passLine->setFocus();
}
}
void LoginDialog::accept()
{
//_user.replace( 0, _user.length(), userLine->text() );
//_pass.replace( 0, _pass.length(), passLine->text() );
_user = userLine->text();
_pass = passLine->text();
- qDebug("User im accept: |%s|",_user.latin1());
+ odebug << "User im accept: |" << _user.latin1() << "|" << oendl;
QDialog::accept();
}
diff --git a/noncore/net/mail/libmailwrapper/mailtypes.cpp b/noncore/net/mail/libmailwrapper/mailtypes.cpp
index 90b8865..6d44db4 100644
--- a/noncore/net/mail/libmailwrapper/mailtypes.cpp
+++ b/noncore/net/mail/libmailwrapper/mailtypes.cpp
@@ -1,396 +1,396 @@
#include "mailtypes.h"
#include <stdlib.h>
using namespace Opie::Core;
RecMail::RecMail()
:Opie::Core::ORefCount(),subject(""),date(""),from(""),mbox(""),msg_id(""),msg_number(0),msg_size(0),msg_flags(7)
{
init();
}
RecMail::RecMail(const RecMail&old)
:Opie::Core::ORefCount(),subject(""),date(""),from(""),mbox(""),msg_id(""),msg_number(0),msg_flags(7)
{
init();
copy_old(old);
- qDebug("Copy constructor RecMail");
+ odebug << "Copy constructor RecMail" << oendl;
}
RecMail::~RecMail()
{
wrapper = 0;
}
void RecMail::copy_old(const RecMail&old)
{
subject = old.subject;
date = old.date;
mbox = old.mbox;
msg_id = old.msg_id;
msg_size = old.msg_size;
msg_number = old.msg_number;
from = old.from;
msg_flags = old.msg_flags;
to = old.to;
cc = old.cc;
bcc = old.bcc;
wrapper = old.wrapper;
in_reply_to = old.in_reply_to;
references = old.references;
replyto = old.replyto;
}
void RecMail::init()
{
to.clear();
cc.clear();
bcc.clear();
in_reply_to.clear();
references.clear();
wrapper = 0;
}
void RecMail::setWrapper(AbstractMail*awrapper)
{
wrapper = awrapper;
}
AbstractMail* RecMail::Wrapper()
{
return wrapper;
}
void RecMail::setTo(const QStringList&list)
{
to = list;
}
const QStringList&RecMail::To()const
{
return to;
}
void RecMail::setCC(const QStringList&list)
{
cc = list;
}
const QStringList&RecMail::CC()const
{
return cc;
}
void RecMail::setBcc(const QStringList&list)
{
bcc = list;
}
const QStringList& RecMail::Bcc()const
{
return bcc;
}
void RecMail::setInreply(const QStringList&list)
{
in_reply_to = list;
}
const QStringList& RecMail::Inreply()const
{
return in_reply_to;
}
void RecMail::setReferences(const QStringList&list)
{
references = list;
}
const QStringList& RecMail::References()const
{
return references;
}
RecPart::RecPart()
: Opie::Core::ORefCount(),
m_type(""),m_subtype(""),m_identifier(""),m_encoding(""),m_description(""),m_lines(0),m_size(0)
{
m_Parameters.clear();
m_poslist.clear();
}
RecPart::RecPart(const RecPart&old)
: Opie::Core::ORefCount(),
m_type(""),m_subtype(""),m_identifier(""),m_encoding(""),m_description(""),m_lines(0),m_size(0)
{
m_type = old.m_type;
m_subtype = old.m_subtype;
m_identifier = old.m_identifier;
m_encoding = old.m_encoding;
m_description = old.m_description;
m_lines = old.m_lines;
m_size = old.m_size;
m_Parameters = old.m_Parameters;
m_poslist = old.m_poslist;
- qDebug("RecPart copy constructor");
+ odebug << "RecPart copy constructor" << oendl;
}
RecPart::~RecPart()
{
}
void RecPart::setSize(unsigned int size)
{
m_size = size;
}
const unsigned int RecPart::Size()const
{
return m_size;
}
void RecPart::setLines(unsigned int lines)
{
m_lines = lines;
}
const unsigned int RecPart::Lines()const
{
return m_lines;
}
const QString& RecPart::Type()const
{
return m_type;
}
void RecPart::setType(const QString&type)
{
m_type = type;
}
const QString& RecPart::Subtype()const
{
return m_subtype;
}
void RecPart::setSubtype(const QString&subtype)
{
m_subtype = subtype;
}
const QString& RecPart::Identifier()const
{
return m_identifier;
}
void RecPart::setIdentifier(const QString&identifier)
{
m_identifier = identifier;
}
const QString& RecPart::Encoding()const
{
return m_encoding;
}
void RecPart::setEncoding(const QString&encoding)
{
m_encoding = encoding;
}
const QString& RecPart::Description()const
{
return m_description;
}
void RecPart::setDescription(const QString&desc)
{
m_description = desc;
}
void RecPart::setParameters(const part_plist_t&list)
{
m_Parameters = list;
}
const part_plist_t& RecPart::Parameters()const
{
return m_Parameters;
}
void RecPart::addParameter(const QString&key,const QString&value)
{
m_Parameters[key]=value;
}
const QString RecPart::searchParamter(const QString&key)const
{
QString value("");
part_plist_t::ConstIterator it = m_Parameters.find(key);
if (it != m_Parameters.end()) {
value = it.data();
}
return value;
}
void RecPart::setPositionlist(const QValueList<int>&poslist)
{
m_poslist = poslist;
}
const QValueList<int>& RecPart::Positionlist()const
{
return m_poslist;
}
RecBody::RecBody()
: Opie::Core::ORefCount(),m_BodyText(),m_description(new RecPart())
{
m_PartsList.clear();
}
RecBody::RecBody(const RecBody&old)
:Opie::Core::ORefCount(),m_BodyText(),m_PartsList(),m_description(new RecPart())
{
m_BodyText = old.m_BodyText;
m_PartsList = old.m_PartsList;
m_description = old.m_description;
- qDebug("Recbody copy constructor");
+ odebug << "Recbody copy constructor" << oendl;
}
RecBody::~RecBody()
{
}
void RecBody::setBodytext(const QString&bodyText)
{
m_BodyText = bodyText;
}
const QString& RecBody::Bodytext()const
{
return m_BodyText;
}
void RecBody::setParts(const QValueList<RecPartP>&parts)
{
m_PartsList.clear();
m_PartsList = parts;
}
const QValueList<RecPartP>& RecBody::Parts()const
{
return m_PartsList;
}
void RecBody::addPart(const RecPartP& part)
{
m_PartsList.append(part);
}
void RecBody::setDescription(const RecPartP&des)
{
m_description = des;
}
const RecPartP& RecBody::Description()const
{
return m_description;
}
/* handling encoded content */
encodedString::encodedString()
{
init();
}
encodedString::encodedString(const char*nContent,unsigned int nSize)
{
init();
setContent(nContent,nSize);
}
encodedString::encodedString(char*nContent,unsigned int nSize)
{
init();
setContent(nContent,nSize);
}
encodedString::encodedString(const encodedString&old)
{
init();
copy_old(old);
- qDebug("encodedeString: copy constructor!");
+ odebug << "encodedeString: copy constructor!" << oendl;
}
encodedString& encodedString::operator=(const encodedString&old)
{
init();
copy_old(old);
- qDebug("encodedString: assign operator!");
+ odebug << "encodedString: assign operator!" << oendl;
return *this;
}
encodedString::~encodedString()
{
clean();
}
void encodedString::init()
{
content = 0;
size = 0;
}
void encodedString::clean()
{
if (content) {
free(content);
}
content = 0;
size = 0;
}
void encodedString::copy_old(const encodedString&old)
{
clean();
if (old.size>0 && old.content) {
content = (char*)malloc(old.size*sizeof(char));
memcpy(content,old.content,size);
size = old.size;
}
}
const char*encodedString::Content()const
{
return content;
}
const int encodedString::Length()const
{
return size;
}
void encodedString::setContent(const char*nContent,int nSize)
{
if (nSize>0 && nContent) {
content = (char*)malloc(nSize*sizeof(char));
memcpy(content,nContent,nSize);
size = nSize;
}
}
void encodedString::setContent(char*nContent,int nSize)
{
content = nContent;
size = nSize;
}
folderStat&folderStat::operator=(const folderStat&old)
{
message_count = old.message_count;
message_unseen = old.message_unseen;
message_recent = old.message_recent;
return *this;
}
diff --git a/noncore/net/mail/libmailwrapper/mailwrapper.cpp b/noncore/net/mail/libmailwrapper/mailwrapper.cpp
index eddc0b9..2b0d112 100644
--- a/noncore/net/mail/libmailwrapper/mailwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/mailwrapper.cpp
@@ -1,150 +1,150 @@
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <qdir.h>
#include "mailwrapper.h"
//#include "logindialog.h"
//#include "defines.h"
#define UNDEFINED 64
#define MAXLINE 76
#define UTF16MASK 0x03FFUL
#define UTF16SHIFT 10
#define UTF16BASE 0x10000UL
#define UTF16HIGHSTART 0xD800UL
#define UTF16HIGHEND 0xDBFFUL
#define UTF16LOSTART 0xDC00UL
#define UTF16LOEND 0xDFFFUL
using namespace Opie::Core;
Attachment::Attachment( DocLnk lnk )
{
doc = lnk;
size = QFileInfo( doc.file() ).size();
}
Folder::Folder(const QString&tmp_name, const QString&sep )
{
name = tmp_name;
nameDisplay = name;
separator = sep;
prefix = "";
}
Folder::~Folder()
{
}
const QString& Folder::Separator()const
{
return separator;
}
IMAPFolder::IMAPFolder(const QString&name,const QString&sep, bool select,bool no_inf, const QString&aprefix )
: Folder( name,sep ),m_MaySelect(select),m_NoInferior(no_inf)
{
// Decode IMAP foldername
nameDisplay = IMAPFolder::decodeFolderName( name );
/*
- qDebug( "folder " + name + " - displayed as " + nameDisplay );
+ odebug << "folder " + name + " - displayed as " + nameDisplay << oendl;
*/
prefix = aprefix;
if (prefix.length()>0) {
if (nameDisplay.startsWith(prefix) && nameDisplay.length()>prefix.length()) {
nameDisplay=nameDisplay.right(nameDisplay.length()-prefix.length());
}
}
}
IMAPFolder::~IMAPFolder()
{
}
static unsigned char base64chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
/**
* Decodes base64 encoded parts of the imapfolder name
* Code taken from kde cvs: kdebase/kioslave/imap4/rfcdecoder.cc
*/
QString IMAPFolder::decodeFolderName( const QString &name )
{
unsigned char c, i, bitcount;
unsigned long ucs4, utf16, bitbuf;
unsigned char base64[256], utf8[6];
unsigned long srcPtr = 0;
QCString dst = "";
QCString src = name.ascii();
/* initialize modified base64 decoding table */
memset(base64, UNDEFINED, sizeof(base64));
for (i = 0; i < sizeof(base64chars); ++i) {
base64[(int)base64chars[i]] = i;
}
/* loop until end of string */
while (srcPtr < src.length ()) {
c = src[srcPtr++];
/* deal with literal characters and &- */
if (c != '&' || src[srcPtr] == '-') {
/* encode literally */
dst += c;
/* skip over the '-' if this is an &- sequence */
if (c == '&')
srcPtr++;
} else {
/* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
bitbuf = 0;
bitcount = 0;
ucs4 = 0;
while ((c = base64[(unsigned char) src[srcPtr]]) != UNDEFINED) {
++srcPtr;
bitbuf = (bitbuf << 6) | c;
bitcount += 6;
/* enough bits for a UTF-16 character? */
if (bitcount >= 16) {
bitcount -= 16;
utf16 = (bitcount ? bitbuf >> bitcount : bitbuf) & 0xffff;
/* convert UTF16 to UCS4 */
if (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
continue;
} else if (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
} else {
ucs4 = utf16;
}
/* convert UTF-16 range of UCS4 to UTF-8 */
if (ucs4 <= 0x7fUL) {
utf8[0] = ucs4;
i = 1;
} else if (ucs4 <= 0x7ffUL) {
utf8[0] = 0xc0 | (ucs4 >> 6);
utf8[1] = 0x80 | (ucs4 & 0x3f);
i = 2;
} else if (ucs4 <= 0xffffUL) {
utf8[0] = 0xe0 | (ucs4 >> 12);
utf8[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
utf8[2] = 0x80 | (ucs4 & 0x3f);
i = 3;
} else {
utf8[0] = 0xf0 | (ucs4 >> 18);
utf8[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
utf8[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
utf8[3] = 0x80 | (ucs4 & 0x3f);
i = 4;
}
/* copy it */
for (c = 0; c < i; ++c) {
dst += utf8[c];
}
}
}
/* skip over trailing '-' in modified UTF-7 encoding */
if (src[srcPtr] == '-')
diff --git a/noncore/net/mail/libmailwrapper/mboxwrapper.cpp b/noncore/net/mail/libmailwrapper/mboxwrapper.cpp
index e3c75f3..df2112f 100644
--- a/noncore/net/mail/libmailwrapper/mboxwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/mboxwrapper.cpp
@@ -1,336 +1,336 @@
#include "mboxwrapper.h"
#include "mailtypes.h"
#include "mailwrapper.h"
#include <libetpan/libetpan.h>
#include <qdir.h>
#include <stdlib.h>
#include <qpe/global.h>
using namespace Opie::Core;
MBOXwrapper::MBOXwrapper(const QString & mbox_dir,const QString&mbox_name)
: Genericwrapper(),MBOXPath(mbox_dir),MBOXName(mbox_name)
{
QDir dir(MBOXPath);
if (!dir.exists()) {
dir.mkdir(MBOXPath);
}
}
MBOXwrapper::~MBOXwrapper()
{
}
void MBOXwrapper::listMessages(const QString & mailbox, QValueList<RecMailP> &target )
{
mailstorage*storage = mailstorage_new(NULL);
QString p = MBOXPath+"/";
p+=mailbox;
int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
mailfolder*folder;
folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
r = mailfolder_connect(folder);
if (r != MAIL_NO_ERROR) {
- qDebug("Error initializing mbox");
+ odebug << "Error initializing mbox" << oendl;
mailfolder_free(folder);
mailstorage_free(storage);
return;
}
parseList(target,folder->fld_session,mailbox);
mailfolder_disconnect(folder);
mailfolder_free(folder);
mailstorage_free(storage);
Global::statusMessage(tr("Mailbox has %1 mail(s)").arg(target.count()));
}
QValueList<Opie::Core::OSmartPointer<Folder> >* MBOXwrapper::listFolders()
{
QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >();
QDir dir(MBOXPath);
if (!dir.exists()) return folders;
dir.setFilter(QDir::Files|QDir::Writable|QDir::Readable);
QStringList entries = dir.entryList();
QStringList::ConstIterator it = entries.begin();
for (;it!=entries.end();++it) {
FolderP inb=new Folder(*it,"/");
folders->append(inb);
}
return folders;
}
void MBOXwrapper::deleteMail(const RecMailP & mail)
{
mailstorage*storage = mailstorage_new(NULL);
QString p = MBOXPath+"/";
p+=mail->getMbox();
int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
mailfolder*folder;
folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
r = mailfolder_connect(folder);
if (r != MAIL_NO_ERROR) {
- qDebug("Error initializing mbox");
+ odebug << "Error initializing mbox" << oendl;
mailfolder_free(folder);
mailstorage_free(storage);
return;
}
r = mailsession_remove_message(folder->fld_session,mail->getNumber());
if (r != MAIL_NO_ERROR) {
- qDebug("error deleting mail");
+ odebug << "error deleting mail" << oendl;
}
mailfolder_free(folder);
mailstorage_free(storage);
}
void MBOXwrapper::answeredMail(const RecMailP&)
{
}
RecBodyP MBOXwrapper::fetchBody( const RecMailP &mail )
{
RecBodyP body = new RecBody();
mailstorage*storage = mailstorage_new(NULL);
QString p = MBOXPath+"/";
p+=mail->getMbox();
mailmessage * msg;
char*data=0;
size_t size;
int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
mailfolder*folder;
folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
r = mailfolder_connect(folder);
if (r != MAIL_NO_ERROR) {
- qDebug("Error initializing mbox");
+ odebug << "Error initializing mbox" << oendl;
mailfolder_free(folder);
mailstorage_free(storage);
return body;
}
r = mailsession_get_message(folder->fld_session, mail->getNumber(), &msg);
if (r != MAIL_NO_ERROR) {
- qDebug("Error fetching mail %i",mail->getNumber());
+ odebug << "Error fetching mail " << mail->getNumber() << "" << oendl;
mailfolder_free(folder);
mailstorage_free(storage);
return body;
}
r = mailmessage_fetch(msg,&data,&size);
if (r != MAIL_NO_ERROR) {
- qDebug("Error fetching mail %i",mail->getNumber());
+ odebug << "Error fetching mail " << mail->getNumber() << "" << oendl;
mailfolder_free(folder);
mailstorage_free(storage);
mailmessage_free(msg);
return body;
}
body = parseMail(msg);
mailmessage_fetch_result_free(msg,data);
mailfolder_free(folder);
mailstorage_free(storage);
return body;
}
void MBOXwrapper::mbox_progress( size_t current, size_t maximum )
{
- qDebug("MBOX %i von %i",current,maximum);
+ odebug << "MBOX " << current << " von " << maximum << "" << oendl;
}
int MBOXwrapper::createMbox(const QString&folder,const FolderP&,const QString&,bool )
{
QString p = MBOXPath+"/";
p+=folder;
QFileInfo fi(p);
if (fi.exists()) {
Global::statusMessage(tr("Mailbox exists."));
return 0;
}
mailmbox_folder*f = 0;
if (mailmbox_init(p.latin1(),0,1,0,&f) != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error init folder"));
return 0;
}
if (f) mailmbox_done(f);
return 1;
}
void MBOXwrapper::storeMessage(const char*msg,size_t length, const QString&folder)
{
QString p = MBOXPath+"/";
p+=folder;
mailmbox_folder*f = 0;
int r = mailmbox_init(p.latin1(),0,1,0,&f);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error init folder"));
return;
}
r = mailmbox_append_message(f,msg,length);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error writing to message folder"));
}
mailmbox_done(f);
}
encodedString* MBOXwrapper::fetchRawBody(const RecMailP&mail)
{
RecBody body;
mailstorage*storage = mailstorage_new(NULL);
QString p = MBOXPath+"/";
p+=mail->getMbox();
mailmessage * msg;
char*data=0;
size_t size;
int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
mailfolder*folder;
folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
r = mailfolder_connect(folder);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error initializing mbox"));
mailfolder_free(folder);
mailstorage_free(storage);
return 0;
}
r = mailsession_get_message(folder->fld_session, mail->getNumber(), &msg);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber()));
mailfolder_free(folder);
mailstorage_free(storage);
return 0;
}
r = mailmessage_fetch(msg,&data,&size);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber()));
mailfolder_free(folder);
mailstorage_free(storage);
mailmessage_free(msg);
return 0;
}
encodedString*result = new encodedString(data,size);
mailfolder_free(folder);
mailstorage_free(storage);
mailmessage_free(msg);
return result;
}
void MBOXwrapper::deleteMails(const QString & mailbox,const QValueList<RecMailP> &target)
{
QString p = MBOXPath+"/";
p+=mailbox;
mailmbox_folder*f = 0;
int r = mailmbox_init(p.latin1(),0,1,0,&f);
if (r != MAIL_NO_ERROR) {
- qDebug("Error init folder");
+ odebug << "Error init folder" << oendl;
return;
}
deleteMails(f,target);
mailmbox_done(f);
}
void MBOXwrapper::deleteMails(mailmbox_folder*f,const QValueList<RecMailP> &target)
{
if (!f) return;
int r;
QValueList<RecMailP>::ConstIterator it;
for (it=target.begin(); it != target.end();++it) {
r = mailmbox_delete_msg(f,(*it)->getNumber());
if (r!=MAILMBOX_NO_ERROR) {
- qDebug("error delete mail");
+ odebug << "error delete mail" << oendl;
}
}
r = mailmbox_expunge(f);
if (r != MAILMBOX_NO_ERROR) {
- qDebug("error expunge mailbox");
+ odebug << "error expunge mailbox" << oendl;
}
}
int MBOXwrapper::deleteAllMail(const FolderP&tfolder)
{
if (!tfolder) return 0;
QString p = MBOXPath+"/"+tfolder->getDisplayName();
int res = 1;
mailfolder*folder = 0;
mailmessage_list*l=0;
mailstorage*storage = mailstorage_new(NULL);
int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error initializing mbox"));
res = 0;
}
if (res) {
folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
r = mailfolder_connect(folder);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error initializing mbox"));
res = 0;
}
}
if (res) {
r = mailsession_get_messages_list(folder->fld_session,&l);
if (r != MAIL_NO_ERROR) {
- qDebug("Error message list");
+ odebug << "Error message list" << oendl;
res=0;
}
}
for(unsigned int i = 0 ; l!= 0 && res==1 && i < carray_count(l->msg_tab) ; ++i) {
r = mailsession_remove_message(folder->fld_session,i+1);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error deleting mail %1").arg(i+1));
res = 0;
break;
}
}
if (l) mailmessage_list_free(l);
if (folder) mailfolder_free(folder);
if (storage) mailstorage_free(storage);
return res;
}
int MBOXwrapper::deleteMbox(const FolderP&tfolder)
{
if (!tfolder) return 0;
QString p = MBOXPath+"/"+tfolder->getDisplayName();
QFile fi(p);
if (!fi.exists()) {
Global::statusMessage(tr("Mailbox doesn't exist."));
return 0;
}
if (!fi.remove()) {
Global::statusMessage(tr("Error deleting Mailbox."));
return 0;
}
return 1;
}
void MBOXwrapper::statusFolder(folderStat&target_stat,const QString & mailbox)
{
mailfolder*folder = 0;
mailstorage*storage = mailstorage_new(NULL);
target_stat.message_count = 0;
target_stat.message_unseen = 0;
target_stat.message_recent = 0;
QString p = MBOXPath+"/"+mailbox;
QFile fi(p);
if (!fi.exists()) {
Global::statusMessage(tr("Mailbox doesn't exist."));
return;
}
int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
r = mailfolder_connect(folder);
r = mailsession_status_folder(folder->fld_session,(char*)mailbox.latin1(),&target_stat.message_count,
&target_stat.message_recent,&target_stat.message_unseen);
if (folder) mailfolder_free(folder);
if (storage) mailstorage_free(storage);
}
MAILLIB::ATYPE MBOXwrapper::getType()const
{
return MAILLIB::A_MBOX;
}
const QString&MBOXwrapper::getName()const
{
return MBOXName;
}
diff --git a/noncore/net/mail/libmailwrapper/mhwrapper.cpp b/noncore/net/mail/libmailwrapper/mhwrapper.cpp
index 12472e9..cd7cecb 100644
--- a/noncore/net/mail/libmailwrapper/mhwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/mhwrapper.cpp
@@ -1,442 +1,442 @@
#include "mhwrapper.h"
#include "mailtypes.h"
#include "mailwrapper.h"
#include <libetpan/libetpan.h>
#include <qdir.h>
#include <qmessagebox.h>
#include <stdlib.h>
#include <qpe/global.h>
#include <opie2/oprocess.h>
using namespace Opie::Core;
MHwrapper::MHwrapper(const QString & mbox_dir,const QString&mbox_name)
: Genericwrapper(),MHPath(mbox_dir),MHName(mbox_name)
{
if (MHPath.length()>0) {
if (MHPath[MHPath.length()-1]=='/') {
MHPath=MHPath.left(MHPath.length()-1);
}
- qDebug(MHPath);
+ odebug << MHPath << oendl;
QDir dir(MHPath);
if (!dir.exists()) {
dir.mkdir(MHPath);
}
init_storage();
}
}
void MHwrapper::init_storage()
{
int r;
QString pre = MHPath;
if (!m_storage) {
m_storage = mailstorage_new(NULL);
r = mh_mailstorage_init(m_storage,(char*)pre.latin1(),0,0,0);
if (r != MAIL_NO_ERROR) {
- qDebug("error initializing storage");
+ odebug << "error initializing storage" << oendl;
mailstorage_free(m_storage);
m_storage = 0;
return;
}
}
r = mailstorage_connect(m_storage);
if (r!=MAIL_NO_ERROR) {
- qDebug("error connecting storage");
+ odebug << "error connecting storage" << oendl;
mailstorage_free(m_storage);
m_storage = 0;
}
}
void MHwrapper::clean_storage()
{
if (m_storage) {
mailstorage_disconnect(m_storage);
mailstorage_free(m_storage);
m_storage = 0;
}
}
MHwrapper::~MHwrapper()
{
clean_storage();
}
void MHwrapper::listMessages(const QString & mailbox, QValueList<Opie::Core::OSmartPointer<RecMail> > &target )
{
init_storage();
if (!m_storage) {
return;
}
QString f = buildPath(mailbox);
int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
if (r!=MAIL_NO_ERROR) {
- qDebug("listMessages: error selecting folder!");
+ odebug << "listMessages: error selecting folder!" << oendl;
return;
}
parseList(target,m_storage->sto_session,f);
Global::statusMessage(tr("Mailbox has %1 mail(s)").arg(target.count()));
}
QValueList<Opie::Core::OSmartPointer<Folder> >* MHwrapper::listFolders()
{
QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >();
/* this is needed! */
if (m_storage) mailstorage_disconnect(m_storage);
init_storage();
if (!m_storage) {
return folders;
}
mail_list*flist = 0;
clistcell*current=0;
int r = mailsession_list_folders(m_storage->sto_session,NULL,&flist);
if (r != MAIL_NO_ERROR || !flist) {
- qDebug("error getting folder list");
+ odebug << "error getting folder list" << oendl;
return folders;
}
for (current=clist_begin(flist->mb_list);current!=0;current=clist_next(current)) {
QString t = (char*)current->data;
t.replace(0,MHPath.length(),"");
folders->append(new MHFolder(t,MHPath));
}
mail_list_free(flist);
return folders;
}
void MHwrapper::deleteMail(const RecMailP&mail)
{
init_storage();
if (!m_storage) {
return;
}
int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1());
if (r!=MAIL_NO_ERROR) {
- qDebug("error selecting folder!");
+ odebug << "error selecting folder!" << oendl;
return;
}
r = mailsession_remove_message(m_storage->sto_session,mail->getNumber());
if (r != MAIL_NO_ERROR) {
- qDebug("error deleting mail");
+ odebug << "error deleting mail" << oendl;
}
}
void MHwrapper::answeredMail(const RecMailP&)
{
}
RecBodyP MHwrapper::fetchBody( const RecMailP &mail )
{
RecBodyP body = new RecBody();
init_storage();
if (!m_storage) {
return body;
}
mailmessage * msg;
char*data=0;
/* mail should hold the complete path! */
int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1());
if (r != MAIL_NO_ERROR) {
return body;
}
r = mailsession_get_message(m_storage->sto_session, mail->getNumber(), &msg);
if (r != MAIL_NO_ERROR) {
- qDebug("Error fetching mail %i",mail->getNumber());
+ odebug << "Error fetching mail " << mail->getNumber() << "" << oendl;
return body;
}
body = parseMail(msg);
mailmessage_fetch_result_free(msg,data);
return body;
}
void MHwrapper::mbox_progress( size_t current, size_t maximum )
{
- qDebug("MH %i von %i",current,maximum);
+ odebug << "MH " << current << " von " << maximum << "" << oendl;
}
QString MHwrapper::buildPath(const QString&p)
{
QString f="";
if (p.length()==0||p=="/")
return MHPath;
if (!p.startsWith(MHPath)) {
f+=MHPath;
}
if (!p.startsWith("/")) {
f+="/";
}
f+=p;
return f;
}
int MHwrapper::createMbox(const QString&folder,const FolderP&pfolder,const QString&,bool )
{
init_storage();
if (!m_storage) {
return 0;
}
QString f;
if (!pfolder) {
// toplevel folder
f = buildPath(folder);
} else {
f = pfolder->getName();
f+="/";
f+=folder;
}
- qDebug(f);
+ odebug << f << oendl;
int r = mailsession_create_folder(m_storage->sto_session,(char*)f.latin1());
if (r != MAIL_NO_ERROR) {
- qDebug("error creating folder %i",r);
+ odebug << "error creating folder " << r << "" << oendl;
return 0;
}
- qDebug("Folder created");
+ odebug << "Folder created" << oendl;
return 1;
}
void MHwrapper::storeMessage(const char*msg,size_t length, const QString&Folder)
{
init_storage();
if (!m_storage) {
return;
}
QString f = buildPath(Folder);
int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
if (r!=MAIL_NO_ERROR) {
- qDebug("error selecting folder!");
+ odebug << "error selecting folder!" << oendl;
return;
}
r = mailsession_append_message(m_storage->sto_session,(char*)msg,length);
if (r!=MAIL_NO_ERROR) {
- qDebug("error storing mail");
+ odebug << "error storing mail" << oendl;
}
return;
}
encodedString* MHwrapper::fetchRawBody(const RecMailP&mail)
{
encodedString*result = 0;
init_storage();
if (!m_storage) {
return result;
}
mailmessage * msg = 0;
char*data=0;
size_t size;
int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1());
if (r!=MAIL_NO_ERROR) {
- qDebug("error selecting folder!");
+ odebug << "error selecting folder!" << oendl;
return result;
}
r = mailsession_get_message(m_storage->sto_session, mail->getNumber(), &msg);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber()));
return 0;
}
r = mailmessage_fetch(msg,&data,&size);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber()));
if (msg) mailmessage_free(msg);
return 0;
}
result = new encodedString(data,size);
if (msg) mailmessage_free(msg);
return result;
}
void MHwrapper::deleteMails(const QString & mailbox,const QValueList<RecMailP> &target)
{
QString f = buildPath(mailbox);
int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
if (r!=MAIL_NO_ERROR) {
- qDebug("deleteMails: error selecting folder!");
+ odebug << "deleteMails: error selecting folder!" << oendl;
return;
}
QValueList<RecMailP>::ConstIterator it;
for (it=target.begin(); it!=target.end();++it) {
r = mailsession_remove_message(m_storage->sto_session,(*it)->getNumber());
if (r != MAIL_NO_ERROR) {
- qDebug("error deleting mail");
+ odebug << "error deleting mail" << oendl;
break;
}
}
}
int MHwrapper::deleteAllMail(const FolderP&tfolder)
{
init_storage();
if (!m_storage) {
return 0;
}
int res = 1;
if (!tfolder) return 0;
int r = mailsession_select_folder(m_storage->sto_session,(char*)tfolder->getName().latin1());
if (r!=MAIL_NO_ERROR) {
- qDebug("error selecting folder!");
+ odebug << "error selecting folder!" << oendl;
return 0;
}
mailmessage_list*l=0;
r = mailsession_get_messages_list(m_storage->sto_session,&l);
if (r != MAIL_NO_ERROR) {
- qDebug("Error message list");
+ odebug << "Error message list" << oendl;
res = 0;
}
unsigned j = 0;
for(unsigned int i = 0 ; l!= 0 && res==1 && i < carray_count(l->msg_tab) ; ++i) {
mailmessage * msg;
msg = (mailmessage*)carray_get(l->msg_tab, i);
j = msg->msg_index;
r = mailsession_remove_message(m_storage->sto_session,j);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error deleting mail %1").arg(i+1));
res = 0;
break;
}
}
if (l) mailmessage_list_free(l);
return res;
}
int MHwrapper::deleteMbox(const FolderP&tfolder)
{
init_storage();
if (!m_storage) {
return 0;
}
if (!tfolder) return 0;
if (tfolder->getName()=="/" || tfolder->getName().isEmpty()) return 0;
int r = mailsession_delete_folder(m_storage->sto_session,(char*)tfolder->getName().latin1());
if (r != MAIL_NO_ERROR) {
- qDebug("error deleting mail box");
+ odebug << "error deleting mail box" << oendl;
return 0;
}
QString cmd = "rm -rf "+tfolder->getName();
QStringList command;
command << "/bin/sh";
command << "-c";
command << cmd.latin1();
OProcess *process = new OProcess();
connect(process, SIGNAL(processExited(Opie::Core::OProcess*)),
this, SLOT( processEnded(Opie::Core::OProcess*)));
connect(process, SIGNAL( receivedStderr(Opie::Core::OProcess*,char*,int)),
this, SLOT( oprocessStderr(Opie::Core::OProcess*,char*,int)));
*process << command;
removeMboxfailed = false;
if(!process->start(OProcess::Block, OProcess::All) ) {
- qDebug("could not start process");
+ odebug << "could not start process" << oendl;
return 0;
}
- qDebug("mail box deleted");
+ odebug << "mail box deleted" << oendl;
return 1;
}
void MHwrapper::processEnded(OProcess *p)
{
if (p) delete p;
}
void MHwrapper::oprocessStderr(OProcess*, char *buffer, int )
{
QString lineStr = buffer;
QMessageBox::warning( 0, tr("Error"), lineStr ,tr("Ok") );
removeMboxfailed = true;
}
void MHwrapper::statusFolder(folderStat&target_stat,const QString & mailbox)
{
init_storage();
if (!m_storage) {
return;
}
target_stat.message_count = 0;
target_stat.message_unseen = 0;
target_stat.message_recent = 0;
QString f = buildPath(mailbox);
int r = mailsession_status_folder(m_storage->sto_session,(char*)f.latin1(),&target_stat.message_count,
&target_stat.message_recent,&target_stat.message_unseen);
if (r != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error retrieving status"));
}
}
MAILLIB::ATYPE MHwrapper::getType()const
{
return MAILLIB::A_MH;
}
const QString&MHwrapper::getName()const
{
return MHName;
}
void MHwrapper::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
{
init_storage();
if (!m_storage) {
return;
}
if (targetWrapper != this) {
- qDebug("Using generic");
+ odebug << "Using generic" << oendl;
Genericwrapper::mvcpMail(mail,targetFolder,targetWrapper,moveit);
return;
}
- qDebug("Using internal routines for move/copy");
+ odebug << "Using internal routines for move/copy" << oendl;
QString tf = buildPath(targetFolder);
int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1());
if (r != MAIL_NO_ERROR) {
- qDebug("Error selecting source mailbox");
+ odebug << "Error selecting source mailbox" << oendl;
return;
}
if (moveit) {
r = mailsession_move_message(m_storage->sto_session,mail->getNumber(),(char*)tf.latin1());
} else {
r = mailsession_copy_message(m_storage->sto_session,mail->getNumber(),(char*)tf.latin1());
}
if (r != MAIL_NO_ERROR) {
- qDebug("Error copy/moving mail internal (%i)",r);
+ odebug << "Error copy/moving mail internal (" << r << ")" << oendl;
}
}
void MHwrapper::mvcpAllMails(const FolderP&fromFolder,
const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
{
init_storage();
if (!m_storage) {
return;
}
if (targetWrapper != this) {
- qDebug("Using generic");
+ odebug << "Using generic" << oendl;
Genericwrapper::mvcpAllMails(fromFolder,targetFolder,targetWrapper,moveit);
return;
}
if (!fromFolder) return;
int r = mailsession_select_folder(m_storage->sto_session,(char*)fromFolder->getName().latin1());
if (r!=MAIL_NO_ERROR) {
- qDebug("error selecting source folder!");
+ odebug << "error selecting source folder!" << oendl;
return;
}
QString tf = buildPath(targetFolder);
mailmessage_list*l=0;
r = mailsession_get_messages_list(m_storage->sto_session,&l);
if (r != MAIL_NO_ERROR) {
- qDebug("Error message list");
+ odebug << "Error message list" << oendl;
}
unsigned j = 0;
for(unsigned int i = 0 ; l!= 0 && i < carray_count(l->msg_tab) ; ++i) {
mailmessage * msg;
msg = (mailmessage*)carray_get(l->msg_tab, i);
j = msg->msg_index;
if (moveit) {
r = mailsession_move_message(m_storage->sto_session,j,(char*)tf.latin1());
} else {
r = mailsession_copy_message(m_storage->sto_session,j,(char*)tf.latin1());
}
if (r != MAIL_NO_ERROR) {
- qDebug("Error copy/moving mail internal (%i)",r);
+ odebug << "Error copy/moving mail internal (" << r << ")" << oendl;
break;
}
}
if (l) mailmessage_list_free(l);
}
diff --git a/noncore/net/mail/libmailwrapper/nntpwrapper.cpp b/noncore/net/mail/libmailwrapper/nntpwrapper.cpp
index cfded43..5d5011a 100644
--- a/noncore/net/mail/libmailwrapper/nntpwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/nntpwrapper.cpp
@@ -1,270 +1,270 @@
#include "nntpwrapper.h"
#include "logindialog.h"
#include "mailtypes.h"
#include <qfile.h>
#include <stdlib.h>
#include <libetpan/libetpan.h>
#define HARD_MSG_SIZE_LIMIT 5242880
using namespace Opie::Core;
NNTPwrapper::NNTPwrapper( NNTPaccount *a )
: Genericwrapper() {
account = a;
m_nntp = NULL;
msgTempName = a->getFileName()+"_msg_cache";
last_msg_id = 0;
}
NNTPwrapper::~NNTPwrapper() {
logout();
QFile msg_cache(msgTempName);
if (msg_cache.exists()) {
msg_cache.remove();
}
}
void NNTPwrapper::nntp_progress( size_t current, size_t maximum ) {
- qDebug( "NNTP: %i of %i", current, maximum );
+ odebug << "NNTP: " << current << " of " << maximum << "" << oendl;
}
RecBodyP NNTPwrapper::fetchBody( const RecMailP &mail ) {
int err = NEWSNNTP_NO_ERROR;
char *message = 0;
size_t length = 0;
RecBodyP body = new RecBody();
login();
if ( !m_nntp ) {
return body;
}
mailmessage * mailmsg;
if (mail->Msgsize()>HARD_MSG_SIZE_LIMIT) {
- qDebug("Message to large: %i",mail->Msgsize());
+ odebug << "Message to large: " << mail->Msgsize() << "" << oendl;
return body;
}
QFile msg_cache(msgTempName);
cleanMimeCache();
if (mail->getNumber()!=last_msg_id) {
if (msg_cache.exists()) {
msg_cache.remove();
}
msg_cache.open(IO_ReadWrite|IO_Truncate);
last_msg_id = mail->getNumber();
err = mailsession_get_message(m_nntp->sto_session, mail->getNumber(), &mailmsg);
err = mailmessage_fetch(mailmsg,&message,&length);
msg_cache.writeBlock(message,length);
} else {
QString msg="";
msg_cache.open(IO_ReadOnly);
message = new char[4096];
memset(message,0,4096);
while (msg_cache.readBlock(message,4095)>0) {
msg+=message;
memset(message,0,4096);
}
delete message;
message = (char*)malloc(msg.length()+1*sizeof(char));
memset(message,0,msg.length()+1);
memcpy(message,msg.latin1(),msg.length());
/* transform to libetpan stuff */
mailmsg = mailmessage_new();
mailmessage_init(mailmsg, NULL, data_message_driver, 0, strlen(message));
generic_message_t * msg_data;
msg_data = (generic_message_t *)mailmsg->msg_data;
msg_data->msg_fetched = 1;
msg_data->msg_message = message;
msg_data->msg_length = strlen(message);
}
body = parseMail(mailmsg);
/* clean up */
if (mailmsg)
mailmessage_free(mailmsg);
if (message)
free(message);
return body;
}
void NNTPwrapper::listMessages(const QString & which, QValueList<Opie::Core::OSmartPointer<RecMail> > &target )
{
login();
if (!m_nntp)
return;
uint32_t res_messages,res_recent,res_unseen;
mailsession_status_folder(m_nntp->sto_session,(char*)which.latin1(),&res_messages,&res_recent,&res_unseen);
parseList(target,m_nntp->sto_session,which,true);
}
void NNTPwrapper::login()
{
if (account->getOffline())
return;
/* we'll hold the line */
if ( m_nntp != NULL )
return;
const char *server, *user, *pass;
QString User,Pass;
uint16_t port;
int err = NEWSNNTP_NO_ERROR;
server = account->getServer().latin1();
port = account->getPort().toUInt();
user = pass = 0;
if ( ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) && account->getLogin() ) {
LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true );
login.show();
if ( QDialog::Accepted == login.exec() ) {
// ok
User = login.getUser().latin1();
Pass = login.getPassword().latin1();
} else {
// cancel
- qDebug( "NNTP: Login canceled" );
+ odebug << "NNTP: Login canceled" << oendl;
return;
}
} else {
User = account->getUser().latin1();
Pass = account->getPassword().latin1();
}
if (User.isEmpty()) {
user=0;
pass = 0;
} else {
user=User.latin1();
pass=Pass.latin1();
}
// bool ssl = account->getSSL();
m_nntp=mailstorage_new(NULL);
int conntypeset = account->ConnectionType();
int conntype = 0;
if ( conntypeset == 3 ) {
conntype = CONNECTION_TYPE_COMMAND;
} else if ( conntypeset == 2 ) {
conntype = CONNECTION_TYPE_TLS;
} else if ( conntypeset == 1 ) {
conntype = CONNECTION_TYPE_STARTTLS;
} else if ( conntypeset == 0 ) {
conntype = CONNECTION_TYPE_TRY_STARTTLS;
}
nntp_mailstorage_init(m_nntp,(char*)server, port, NULL, CONNECTION_TYPE_PLAIN, NNTP_AUTH_TYPE_PLAIN,
(char*)user,(char*)pass,0,0,0);
err = mailstorage_connect( m_nntp );
if (err != NEWSNNTP_NO_ERROR) {
- qDebug( QString( "FEHLERNUMMER %1" ).arg( err ) );
+ odebug << QString( "FEHLERNUMMER %1" ).arg( err ) << oendl;
// Global::statusMessage(tr("Error initializing folder"));
mailstorage_free(m_nntp);
m_nntp = 0;
} else {
mailsession * session = m_nntp->sto_session;
newsnntp * news = ( ( nntp_session_state_data * )session->sess_data )->nntp_session;
news->nntp_progr_fun = &nntp_progress;
}
}
void NNTPwrapper::logout()
{
int err = NEWSNNTP_NO_ERROR;
if ( m_nntp == NULL )
return;
mailstorage_free(m_nntp);
m_nntp = 0;
}
QValueList<Opie::Core::OSmartPointer<Folder> >* NNTPwrapper::listFolders() {
QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >();
QStringList groups;
if (account) {
groups = account->getGroups();
}
for ( QStringList::Iterator it = groups.begin(); it != groups.end(); ++it ) {
folders->append(new Folder((*it),"."));
}
return folders;
}
/* we made this method in raw nntp access of etpan and not via generic interface
* 'cause in that case there will be doubled copy operations. eg. the etpan would
* copy that stuff into its own structures and we must copy it into useable c++
* structures for our frontend. this would not make sense, so it is better to reimplement
* the stuff from generic interface of etpan but copy it direct to qt classes.
*/
QStringList NNTPwrapper::listAllNewsgroups(const QString&mask) {
login();
QStringList res;
clist *result = 0;
clistcell *current = 0;
newsnntp_group_description *group;
if ( m_nntp ) {
mailsession * session = m_nntp->sto_session;
newsnntp * news = ( ( nntp_session_state_data * )session->sess_data )->nntp_session;
int err = NEWSNNTP_NO_ERROR;
if (mask.isEmpty()) {
err = newsnntp_list(news, &result);
} else {
/* taken from generic wrapper of etpan */
QString nmask = mask+".*";
err = newsnntp_list_active(news, nmask.latin1(), &result);
}
if ( err == NEWSNNTP_NO_ERROR && result) {
for ( current=clist_begin(result);current!=NULL;current=clist_next(current) ) {
group = ( newsnntp_group_description* ) current->data;
if (!group||!group->grp_name||strlen(group->grp_name)==0) continue;
res.append(group->grp_name);
}
}
}
if (result) {
newsnntp_list_free(result);
}
return res;
}
void NNTPwrapper::answeredMail(const RecMailP&) {}
void NNTPwrapper::statusFolder(folderStat&target_stat,const QString&) {
login();
target_stat.message_count = 0;
target_stat.message_unseen = 0;
target_stat.message_recent = 0;
if (!m_nntp)
return;
int r = mailsession_status_folder(m_nntp->sto_session,0,&target_stat.message_count,
&target_stat.message_recent,&target_stat.message_unseen);
}
encodedString* NNTPwrapper::fetchRawBody(const RecMailP&mail) {
char*target=0;
size_t length=0;
encodedString*res = 0;
mailmessage * mailmsg = 0;
int err = mailsession_get_message(m_nntp->sto_session, mail->getNumber(), &mailmsg);
err = mailmessage_fetch(mailmsg,&target,&length);
if (mailmsg)
mailmessage_free(mailmsg);
if (target) {
diff --git a/noncore/net/mail/libmailwrapper/pop3wrapper.cpp b/noncore/net/mail/libmailwrapper/pop3wrapper.cpp
index 5467547..c586c29 100644
--- a/noncore/net/mail/libmailwrapper/pop3wrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/pop3wrapper.cpp
@@ -1,264 +1,264 @@
#include <stdlib.h>
#include "pop3wrapper.h"
#include "mailtypes.h"
#include "logindialog.h"
#include <libetpan/libetpan.h>
#include <qpe/global.h>
#include <qfile.h>
//#include <qstring.h>
/* we don't fetch messages larger than 5 MB */
#define HARD_MSG_SIZE_LIMIT 5242880
using namespace Opie::Core;
POP3wrapper::POP3wrapper( POP3account *a )
: Genericwrapper() {
account = a;
m_pop3 = NULL;
msgTempName = a->getFileName()+"_msg_cache";
last_msg_id = 0;
}
POP3wrapper::~POP3wrapper() {
logout();
QFile msg_cache(msgTempName);
if (msg_cache.exists()) {
msg_cache.remove();
}
}
void POP3wrapper::pop3_progress( size_t current, size_t maximum ) {
- qDebug( "POP3: %i of %i", current, maximum );
+ odebug << "POP3: " << current << " of " << maximum << "" << oendl;
}
RecBodyP POP3wrapper::fetchBody( const RecMailP &mail ) {
int err = MAILPOP3_NO_ERROR;
char *message = 0;
size_t length = 0;
RecBodyP body = new RecBody();
login();
if ( !m_pop3 ) {
return body;
}
mailmessage * mailmsg;
if (mail->Msgsize()>HARD_MSG_SIZE_LIMIT) {
- qDebug("Message to large: %i",mail->Msgsize());
+ odebug << "Message to large: " << mail->Msgsize() << "" << oendl;
return body;
}
QFile msg_cache(msgTempName);
cleanMimeCache();
if (mail->getNumber()!=last_msg_id) {
if (msg_cache.exists()) {
msg_cache.remove();
}
msg_cache.open(IO_ReadWrite|IO_Truncate);
last_msg_id = mail->getNumber();
err = mailsession_get_message(m_pop3->sto_session, mail->getNumber(), &mailmsg);
err = mailmessage_fetch(mailmsg,&message,&length);
msg_cache.writeBlock(message,length);
} else {
QString msg="";
msg_cache.open(IO_ReadOnly);
message = new char[4096];
memset(message,0,4096);
while (msg_cache.readBlock(message,4095)>0) {
msg+=message;
memset(message,0,4096);
}
delete message;
message = (char*)malloc(msg.length()+1*sizeof(char));
memset(message,0,msg.length()+1);
memcpy(message,msg.latin1(),msg.length());
/* transform to libetpan stuff */
mailmsg = mailmessage_new();
mailmessage_init(mailmsg, NULL, data_message_driver, 0, strlen(message));
generic_message_t * msg_data;
msg_data = (generic_message_t *)mailmsg->msg_data;
msg_data->msg_fetched = 1;
msg_data->msg_message = message;
msg_data->msg_length = strlen(message);
}
body = parseMail(mailmsg);
/* clean up */
if (mailmsg)
mailmessage_free(mailmsg);
if (message)
free(message);
return body;
}
void POP3wrapper::listMessages(const QString &, QValueList<Opie::Core::OSmartPointer<RecMail> > &target )
{
login();
if (!m_pop3)
return;
uint32_t res_messages,res_recent,res_unseen;
mailsession_status_folder(m_pop3->sto_session,"INBOX",&res_messages,&res_recent,&res_unseen);
parseList(target,m_pop3->sto_session,"INBOX");
Global::statusMessage( tr("Mailbox contains %1 mail(s)").arg(res_messages));
}
void POP3wrapper::login()
{
if (account->getOffline())
return;
/* we'll hold the line */
if ( m_pop3 != NULL )
return;
const char *server, *user, *pass;
uint16_t port;
int err = MAILPOP3_NO_ERROR;
server = account->getServer().latin1();
port = account->getPort().toUInt();
if ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) {
LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true );
login.show();
if ( QDialog::Accepted == login.exec() ) {
// ok
user = login.getUser().latin1();
pass = login.getPassword().latin1();
} else {
// cancel
- qDebug( "POP3: Login canceled" );
+ odebug << "POP3: Login canceled" << oendl;
return;
}
} else {
user = account->getUser().latin1();
pass = account->getPassword().latin1();
}
// bool ssl = account->getSSL();
m_pop3=mailstorage_new(NULL);
int conntypeset = account->ConnectionType();
int conntype = 0;
if ( conntypeset == 3 ) {
conntype = CONNECTION_TYPE_COMMAND;
} else if ( conntypeset == 2 ) {
conntype = CONNECTION_TYPE_TLS;
} else if ( conntypeset == 1 ) {
conntype = CONNECTION_TYPE_STARTTLS;
} else if ( conntypeset == 0 ) {
conntype = CONNECTION_TYPE_TRY_STARTTLS;
}
//(ssl?CONNECTION_TYPE_TLS:CONNECTION_TYPE_PLAIN);
pop3_mailstorage_init(m_pop3,(char*)server, port, NULL, conntype, POP3_AUTH_TYPE_PLAIN,
(char*)user,(char*)pass,0,0,0);
err = mailstorage_connect(m_pop3);
if (err != MAIL_NO_ERROR) {
- qDebug( QString( "FEHLERNUMMER %1" ).arg( err ) );
+ odebug << QString( "FEHLERNUMMER %1" ).arg( err ) << oendl;
Global::statusMessage(tr("Error initializing folder"));
mailstorage_free(m_pop3);
m_pop3 = 0;
} else {
mailsession * session = m_pop3->sto_session;
mailpop3 * mail = ( ( pop3_session_state_data * )session->sess_data )->pop3_session;
if (mail) {
mail->pop3_progr_fun = &pop3_progress;
}
}
}
void POP3wrapper::logout()
{
if ( m_pop3 == NULL )
return;
mailstorage_free(m_pop3);
m_pop3 = 0;
}
QValueList<Opie::Core::OSmartPointer<Folder> >* POP3wrapper::listFolders() {
QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<FolderP>();
FolderP inb=new Folder("INBOX","/");
folders->append(inb);
return folders;
}
void POP3wrapper::deleteMail(const RecMailP&mail) {
login();
if (!m_pop3)
return;
int err = mailsession_remove_message(m_pop3->sto_session,mail->getNumber());
if (err != MAIL_NO_ERROR) {
Global::statusMessage(tr("error deleting mail"));
}
}
void POP3wrapper::answeredMail(const RecMailP&) {}
int POP3wrapper::deleteAllMail(const FolderP&) {
login();
if (!m_pop3)
return 0;
int res = 1;
uint32_t result = 0;
int err = mailsession_messages_number(m_pop3->sto_session,NULL,&result);
if (err != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error getting folder info"));
return 0;
}
for (unsigned int i = 0; i < result; ++i) {
err = mailsession_remove_message(m_pop3->sto_session,i+1);
if (err != MAIL_NO_ERROR) {
Global::statusMessage(tr("Error deleting mail %1").arg(i+1));
res=0;
}
break;
}
return res;
}
void POP3wrapper::statusFolder(folderStat&target_stat,const QString&) {
login();
target_stat.message_count = 0;
target_stat.message_unseen = 0;
target_stat.message_recent = 0;
if (!m_pop3)
return;
int r = mailsession_status_folder(m_pop3->sto_session,0,&target_stat.message_count,
&target_stat.message_recent,&target_stat.message_unseen);
if (r != MAIL_NO_ERROR) {
- qDebug("error getting folter status.");
+ odebug << "error getting folter status." << oendl;
}
}
encodedString* POP3wrapper::fetchRawBody(const RecMailP&mail) {
char*target=0;
size_t length=0;
encodedString*res = 0;
mailmessage * mailmsg = 0;
int err = mailsession_get_message(m_pop3->sto_session, mail->getNumber(), &mailmsg);
err = mailmessage_fetch(mailmsg,&target,&length);
if (mailmsg)
mailmessage_free(mailmsg);
if (target) {
res = new encodedString(target,length);
}
return res;
}
MAILLIB::ATYPE POP3wrapper::getType()const {
return account->getType();
}
const QString&POP3wrapper::getName()const{
return account->getAccountName();
}
diff --git a/noncore/net/mail/libmailwrapper/settings.cpp b/noncore/net/mail/libmailwrapper/settings.cpp
index 2c81963..de36eeb 100644
--- a/noncore/net/mail/libmailwrapper/settings.cpp
+++ b/noncore/net/mail/libmailwrapper/settings.cpp
@@ -1,440 +1,440 @@
#include <stdlib.h>
#include <qdir.h>
#include <qpe/config.h>
#include "settings.h"
//#include "defines.h"
#define IMAP_PORT "143"
#define IMAP_SSL_PORT "993"
#define SMTP_PORT "25"
#define SMTP_SSL_PORT "465"
#define POP3_PORT "110"
#define POP3_SSL_PORT "995"
#define NNTP_PORT "119"
#define NNTP_SSL_PORT "563"
Settings::Settings()
: QObject()
{
updateAccounts();
}
void Settings::checkDirectory()
{
if ( !QDir( (QString) getenv( "HOME" ) + "/Applications/opiemail/" ).exists() ) {
system( "mkdir -p $HOME/Applications/opiemail" );
- qDebug( "$HOME/Applications/opiemail created" );
+ odebug << "$HOME/Applications/opiemail created" << oendl;
}
}
QList<Account> Settings::getAccounts()
{
return accounts;
}
void Settings::addAccount( Account *account )
{
accounts.append( account );
}
void Settings::delAccount( Account *account )
{
accounts.remove( account );
account->remove();
}
void Settings::updateAccounts()
{
accounts.clear();
QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
QStringList::Iterator it;
QStringList imap = dir.entryList( "imap-*" );
for ( it = imap.begin(); it != imap.end(); it++ ) {
- qDebug( "Added IMAP account" );
+ odebug << "Added IMAP account" << oendl;
IMAPaccount *account = new IMAPaccount( (*it).replace(0, 5, "") );
accounts.append( account );
}
QStringList pop3 = dir.entryList( "pop3-*" );
for ( it = pop3.begin(); it != pop3.end(); it++ ) {
- qDebug( "Added POP account" );
+ odebug << "Added POP account" << oendl;
POP3account *account = new POP3account( (*it).replace(0, 5, "") );
accounts.append( account );
}
QStringList smtp = dir.entryList( "smtp-*" );
for ( it = smtp.begin(); it != smtp.end(); it++ ) {
- qDebug( "Added SMTP account" );
+ odebug << "Added SMTP account" << oendl;
SMTPaccount *account = new SMTPaccount( (*it).replace(0, 5, "") );
accounts.append( account );
}
QStringList nntp = dir.entryList( "nntp-*" );
for ( it = nntp.begin(); it != nntp.end(); it++ ) {
- qDebug( "Added NNTP account" );
+ odebug << "Added NNTP account" << oendl;
NNTPaccount *account = new NNTPaccount( (*it).replace(0, 5, "") );
accounts.append( account );
}
readAccounts();
}
void Settings::saveAccounts()
{
checkDirectory();
Account *it;
for ( it = accounts.first(); it; it = accounts.next() ) {
it->save();
}
}
void Settings::readAccounts()
{
checkDirectory();
Account *it;
for ( it = accounts.first(); it; it = accounts.next() ) {
it->read();
}
}
Account::Account()
{
accountName = "changeMe";
type = MAILLIB::A_UNDEFINED;
ssl = false;
connectionType = 1;
offline = false;
}
void Account::remove()
{
QFile file( getFileName() );
file.remove();
}
IMAPaccount::IMAPaccount()
: Account()
{
file = IMAPaccount::getUniqueFileName();
accountName = "New IMAP Account";
ssl = false;
connectionType = 1;
type = MAILLIB::A_IMAP;
port = IMAP_PORT;
}
IMAPaccount::IMAPaccount( QString filename )
: Account()
{
file = filename;
accountName = "New IMAP Account";
ssl = false;
connectionType = 1;
type = MAILLIB::A_IMAP;
port = IMAP_PORT;
}
QString IMAPaccount::getUniqueFileName()
{
int num = 0;
QString unique;
QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
QStringList imap = dir.entryList( "imap-*" );
do {
unique.setNum( num++ );
} while ( imap.contains( "imap-" + unique ) > 0 );
return unique;
}
void IMAPaccount::read()
{
Config *conf = new Config( getFileName(), Config::File );
conf->setGroup( "IMAP Account" );
accountName = conf->readEntry( "Account","" );
if (accountName.isNull()) accountName = "";
server = conf->readEntry( "Server","" );
if (server.isNull()) server="";
port = conf->readEntry( "Port","" );
if (port.isNull()) port="143";
connectionType = conf->readNumEntry( "ConnectionType" );
ssl = conf->readBoolEntry( "SSL",false );
user = conf->readEntry( "User","" );
if (user.isNull()) user = "";
password = conf->readEntryCrypt( "Password","" );
if (password.isNull()) password = "";
prefix = conf->readEntry("MailPrefix","");
if (prefix.isNull()) prefix = "";
offline = conf->readBoolEntry("Offline",false);
delete conf;
}
void IMAPaccount::save()
{
- qDebug( "saving " + getFileName() );
+ odebug << "saving " + getFileName() << oendl;
Settings::checkDirectory();
Config *conf = new Config( getFileName(), Config::File );
conf->setGroup( "IMAP Account" );
conf->writeEntry( "Account", accountName );
conf->writeEntry( "Server", server );
conf->writeEntry( "Port", port );
conf->writeEntry( "SSL", ssl );
conf->writeEntry( "ConnectionType", connectionType );
conf->writeEntry( "User", user );
conf->writeEntryCrypt( "Password", password );
conf->writeEntry( "MailPrefix",prefix);
conf->writeEntry( "Offline",offline);
conf->write();
delete conf;
}
QString IMAPaccount::getFileName()
{
return (QString) getenv( "HOME" ) + "/Applications/opiemail/imap-" + file;
}
POP3account::POP3account()
: Account()
{
file = POP3account::getUniqueFileName();
accountName = "New POP3 Account";
ssl = false;
connectionType = 1;
type = MAILLIB::A_POP3;
port = POP3_PORT;
}
POP3account::POP3account( QString filename )
: Account()
{
file = filename;
accountName = "New POP3 Account";
ssl = false;
connectionType = 1;
type = MAILLIB::A_POP3;
port = POP3_PORT;
}
QString POP3account::getUniqueFileName()
{
int num = 0;
QString unique;
QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
QStringList imap = dir.entryList( "pop3-*" );
do {
unique.setNum( num++ );
} while ( imap.contains( "pop3-" + unique ) > 0 );
return unique;
}
void POP3account::read()
{
Config *conf = new Config( getFileName(), Config::File );
conf->setGroup( "POP3 Account" );
accountName = conf->readEntry( "Account" );
server = conf->readEntry( "Server" );
port = conf->readEntry( "Port" );
ssl = conf->readBoolEntry( "SSL" );
connectionType = conf->readNumEntry( "ConnectionType" );
user = conf->readEntry( "User" );
password = conf->readEntryCrypt( "Password" );
offline = conf->readBoolEntry("Offline",false);
delete conf;
}
void POP3account::save()
{
- qDebug( "saving " + getFileName() );
+ odebug << "saving " + getFileName() << oendl;
Settings::checkDirectory();
Config *conf = new Config( getFileName(), Config::File );
conf->setGroup( "POP3 Account" );
conf->writeEntry( "Account", accountName );
conf->writeEntry( "Server", server );
conf->writeEntry( "Port", port );
conf->writeEntry( "SSL", ssl );
conf->writeEntry( "ConnectionType", connectionType );
conf->writeEntry( "User", user );
conf->writeEntryCrypt( "Password", password );
conf->writeEntry( "Offline",offline);
conf->write();
delete conf;
}
QString POP3account::getFileName()
{
return (QString) getenv( "HOME" ) + "/Applications/opiemail/pop3-" + file;
}
SMTPaccount::SMTPaccount()
: Account()
{
file = SMTPaccount::getUniqueFileName();
accountName = "New SMTP Account";
ssl = false;
connectionType = 1;
login = false;
useCC = false;
useBCC = false;
useReply = false;
type = MAILLIB::A_SMTP;
port = SMTP_PORT;
}
SMTPaccount::SMTPaccount( QString filename )
: Account()
{
file = filename;
accountName = "New SMTP Account";
ssl = false;
connectionType = 1;
login = false;
type = MAILLIB::A_SMTP;
port = SMTP_PORT;
}
QString SMTPaccount::getUniqueFileName()
{
int num = 0;
QString unique;
QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
QStringList imap = dir.entryList( "smtp-*" );
do {
unique.setNum( num++ );
} while ( imap.contains( "smtp-" + unique ) > 0 );
return unique;
}
void SMTPaccount::read()
{
Config *conf = new Config( getFileName(), Config::File );
conf->setGroup( "SMTP Account" );
accountName = conf->readEntry( "Account" );
server = conf->readEntry( "Server" );
port = conf->readEntry( "Port" );
ssl = conf->readBoolEntry( "SSL" );
connectionType = conf->readNumEntry( "ConnectionType" );
login = conf->readBoolEntry( "Login" );
user = conf->readEntry( "User" );
password = conf->readEntryCrypt( "Password" );
delete conf;
}
void SMTPaccount::save()
{
- qDebug( "saving " + getFileName() );
+ odebug << "saving " + getFileName() << oendl;
Settings::checkDirectory();
Config *conf = new Config( getFileName(), Config::File );
conf->setGroup( "SMTP Account" );
conf->writeEntry( "Account", accountName );
conf->writeEntry( "Server", server );
conf->writeEntry( "Port", port );
conf->writeEntry( "SSL", ssl );
conf->writeEntry( "ConnectionType", connectionType );
conf->writeEntry( "Login", login );
conf->writeEntry( "User", user );
conf->writeEntryCrypt( "Password", password );
conf->write();
delete conf;
}
QString SMTPaccount::getFileName()
{
return (QString) getenv( "HOME" ) + "/Applications/opiemail/smtp-" + file;
}
NNTPaccount::NNTPaccount()
: Account()
{
file = NNTPaccount::getUniqueFileName();
accountName = "New NNTP Account";
ssl = false;
login = false;
type = MAILLIB::A_NNTP;
port = NNTP_PORT;
}
NNTPaccount::NNTPaccount( QString filename )
: Account()
{
file = filename;
accountName = "New NNTP Account";
ssl = false;
login = false;
type = MAILLIB::A_NNTP;
port = NNTP_PORT;
}
QString NNTPaccount::getUniqueFileName()
{
int num = 0;
QString unique;
QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
QStringList imap = dir.entryList( "nntp-*" );
do {
unique.setNum( num++ );
} while ( imap.contains( "nntp-" + unique ) > 0 );
return unique;
}
void NNTPaccount::read()
{
Config *conf = new Config( getFileName(), Config::File );
conf->setGroup( "NNTP Account" );
accountName = conf->readEntry( "Account" );
server = conf->readEntry( "Server" );
port = conf->readEntry( "Port" );
ssl = conf->readBoolEntry( "SSL" );
login = conf->readBoolEntry( "Login" );
user = conf->readEntry( "User" );
password = conf->readEntryCrypt( "Password" );
subscribedGroups = conf->readListEntry( "Subscribed", ',' );
delete conf;
}
void NNTPaccount::save()
{
- qDebug( "saving " + getFileName() );
+ odebug << "saving " + getFileName() << oendl;
Settings::checkDirectory();
Config *conf = new Config( getFileName(), Config::File );
conf->setGroup( "NNTP Account" );
conf->writeEntry( "Account", accountName );
conf->writeEntry( "Server", server );
conf->writeEntry( "Port", port );
conf->writeEntry( "SSL", ssl );
conf->writeEntry( "Login", login );
conf->writeEntry( "User", user );
conf->writeEntryCrypt( "Password", password );
conf->writeEntry( "Subscribed" , subscribedGroups, ',' );
conf->write();
delete conf;
}
QString NNTPaccount::getFileName()
{
return (QString) getenv( "HOME" ) + "/Applications/opiemail/nntp-" + file;
}
diff --git a/noncore/net/mail/libmailwrapper/smtpwrapper.cpp b/noncore/net/mail/libmailwrapper/smtpwrapper.cpp
index e2cea7a..ba78c3b 100644
--- a/noncore/net/mail/libmailwrapper/smtpwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/smtpwrapper.cpp
@@ -22,434 +22,434 @@ SMTPwrapper::SMTPwrapper(SMTPaccount * aSmtp )
m_SmtpAccount = aSmtp;
Config cfg( "mail" );
cfg.setGroup( "Status" );
m_queuedMail = cfg.readNumEntry( "outgoing", 0 );
emit queuedMails( m_queuedMail );
connect( this, SIGNAL( queuedMails(int) ), this, SLOT( emitQCop(int) ) );
m_smtp = 0;
}
SMTPwrapper::~SMTPwrapper()
{
disc_server();
}
void SMTPwrapper::emitQCop( int queued ) {
QCopEnvelope env( "QPE/Pim", "outgoingMails(int)" );
env << queued;
}
QString SMTPwrapper::mailsmtpError( int errnum ) {
switch ( errnum ) {
case MAILSMTP_NO_ERROR:
return tr( "No error" );
case MAILSMTP_ERROR_UNEXPECTED_CODE:
return tr( "Unexpected error code" );
case MAILSMTP_ERROR_SERVICE_NOT_AVAILABLE:
return tr( "Service not available" );
case MAILSMTP_ERROR_STREAM:
return tr( "Stream error" );
case MAILSMTP_ERROR_HOSTNAME:
return tr( "gethostname() failed" );
case MAILSMTP_ERROR_NOT_IMPLEMENTED:
return tr( "Not implemented" );
case MAILSMTP_ERROR_ACTION_NOT_TAKEN:
return tr( "Error, action not taken" );
case MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION:
return tr( "Data exceeds storage allocation" );
case MAILSMTP_ERROR_IN_PROCESSING:
return tr( "Error in processing" );
case MAILSMTP_ERROR_STARTTLS_NOT_SUPPORTED:
return tr( "Starttls not supported" );
// case MAILSMTP_ERROR_INSUFFISANT_SYSTEM_STORAGE:
// return tr( "Insufficient system storage" );
case MAILSMTP_ERROR_MAILBOX_UNAVAILABLE:
return tr( "Mailbox unavailable" );
case MAILSMTP_ERROR_MAILBOX_NAME_NOT_ALLOWED:
return tr( "Mailbox name not allowed" );
case MAILSMTP_ERROR_BAD_SEQUENCE_OF_COMMAND:
return tr( "Bad command sequence" );
case MAILSMTP_ERROR_USER_NOT_LOCAL:
return tr( "User not local" );
case MAILSMTP_ERROR_TRANSACTION_FAILED:
return tr( "Transaction failed" );
case MAILSMTP_ERROR_MEMORY:
return tr( "Memory error" );
case MAILSMTP_ERROR_CONNECTION_REFUSED:
return tr( "Connection refused" );
default:
return tr( "Unknown error code" );
}
}
void SMTPwrapper::progress( size_t current, size_t maximum ) {
if (SMTPwrapper::sendProgress) {
SMTPwrapper::sendProgress->setSingleMail(current, maximum );
qApp->processEvents();
}
}
void SMTPwrapper::storeMail(const char*mail, size_t length, const QString&box) {
if (!mail)
return;
QString localfolders = AbstractMail::defaultLocalfolder();
AbstractMail*wrap = AbstractMail::getWrapper(localfolders);
wrap->createMbox(box);
wrap->storeMessage(mail,length,box);
delete wrap;
}
void SMTPwrapper::smtpSend( mailmime *mail,bool later) {
clist *rcpts = 0;
char *from, *data;
size_t size;
from = data = 0;
mailmessage * msg = 0;
msg = mime_message_init(mail);
mime_message_set_tmpdir(msg,getenv( "HOME" ));
int r = mailmessage_fetch(msg,&data,&size);
mime_message_detach_mime(msg);
mailmessage_free(msg);
if (r != MAIL_NO_ERROR || !data) {
if (data)
free(data);
- qDebug("Error fetching mime...");
+ odebug << "Error fetching mime..." << oendl;
return;
}
msg = 0;
if (later) {
storeMail(data,size,"Outgoing");
if (data)
free( data );
Config cfg( "mail" );
cfg.setGroup( "Status" );
cfg.writeEntry( "outgoing", ++m_queuedMail );
emit queuedMails( m_queuedMail );
return;
}
from = getFrom( mail );
rcpts = createRcptList( mail->mm_data.mm_message.mm_fields );
smtpSend(from,rcpts,data,size);
if (data) {
free(data);
}
if (from) {
free(from);
}
if (rcpts)
smtp_address_list_free( rcpts );
}
void SMTPwrapper::storeFailedMail(const char*data,unsigned int size, const char*failuremessage)
{
if (data) {
storeMail(data,size,"Sendfailed");
}
if (failuremessage) {
QMessageBox::critical(0,tr("Error sending mail"),
tr("<center>%1</center>").arg(failuremessage));
}
}
int SMTPwrapper::start_smtp_tls()
{
if (!m_smtp) {
return MAILSMTP_ERROR_IN_PROCESSING;
}
int err = mailesmtp_starttls(m_smtp);
if (err != MAILSMTP_NO_ERROR) return err;
mailstream_low * low;
mailstream_low * new_low;
low = mailstream_get_low(m_smtp->stream);
if (!low) {
return MAILSMTP_ERROR_IN_PROCESSING;
}
int fd = mailstream_low_get_fd(low);
if (fd > -1 && (new_low = mailstream_low_ssl_open(fd))!=0) {
mailstream_low_free(low);
mailstream_set_low(m_smtp->stream, new_low);
} else {
return MAILSMTP_ERROR_IN_PROCESSING;
}
return err;
}
void SMTPwrapper::connect_server()
{
const char *server, *user, *pass;
bool ssl;
uint16_t port;
ssl = false;
bool try_tls = true;
bool force_tls=false;
server = user = pass = 0;
QString failuretext = "";
if (m_smtp || !m_SmtpAccount) {
return;
}
server = m_SmtpAccount->getServer().latin1();
if ( m_SmtpAccount->ConnectionType() == 2 ) {
ssl = true;
try_tls = false;
} else if (m_SmtpAccount->ConnectionType() == 1) {
force_tls = true;
}
int result = 1;
port = m_SmtpAccount->getPort().toUInt();
m_smtp = mailsmtp_new( 20, &progress );
if ( m_smtp == NULL ) {
/* no failure message cause this happens when problems with memory - than we
we can not display any messagebox */
return;
}
int err = MAILSMTP_NO_ERROR;
- qDebug( "Servername %s at port %i", server, port );
+ odebug << "Servername " << server << " at port " << port << "" << oendl;
if ( ssl ) {
- qDebug( "SSL session" );
+ odebug << "SSL session" << oendl;
err = mailsmtp_ssl_connect( m_smtp, server, port );
} else {
- qDebug( "No SSL session" );
+ odebug << "No SSL session" << oendl;
err = mailsmtp_socket_connect( m_smtp, server, port );
}
if ( err != MAILSMTP_NO_ERROR ) {
- qDebug("Error init connection");
+ odebug << "Error init connection" << oendl;
failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err));
result = 0;
}
/* switch to tls after init 'cause there it will send the ehlo */
if (result) {
err = mailsmtp_init( m_smtp );
if (err != MAILSMTP_NO_ERROR) {
result = 0;
failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err));
}
}
if (try_tls) {
err = start_smtp_tls();
if (err != MAILSMTP_NO_ERROR) {
try_tls = false;
} else {
err = mailesmtp_ehlo(m_smtp);
}
}
if (!try_tls && force_tls) {
result = 0;
failuretext = tr("Error init SMTP tls: %1").arg(mailsmtpError(err));
}
if (result==1 && m_SmtpAccount->getLogin() ) {
- qDebug("smtp with auth");
+ odebug << "smtp with auth" << oendl;
if ( m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty() ) {
// get'em
LoginDialog login( m_SmtpAccount->getUser(),
m_SmtpAccount->getPassword(), NULL, 0, true );
login.show();
if ( QDialog::Accepted == login.exec() ) {
// ok
user = login.getUser().latin1();
pass = login.getPassword().latin1();
} else {
result = 0;
failuretext=tr("Login aborted - storing mail to localfolder");
}
} else {
user = m_SmtpAccount->getUser().latin1();
pass = m_SmtpAccount->getPassword().latin1();
}
- qDebug( "session->auth: %i", m_smtp->auth);
+ odebug << "session->auth: " << m_smtp->auth << "" << oendl;
if (result) {
err = mailsmtp_auth( m_smtp, (char*)user, (char*)pass );
if ( err == MAILSMTP_NO_ERROR ) {
- qDebug("auth ok");
+ odebug << "auth ok" << oendl;
} else {
failuretext = tr("Authentification failed");
result = 0;
}
}
}
}
void SMTPwrapper::disc_server()
{
if (m_smtp) {
mailsmtp_quit( m_smtp );
mailsmtp_free( m_smtp );
m_smtp = 0;
}
}
int SMTPwrapper::smtpSend(char*from,clist*rcpts,const char*data,size_t size )
{
int err,result;
QString failuretext = "";
connect_server();
result = 1;
if (m_smtp) {
err = mailsmtp_send( m_smtp, from, rcpts, data, size );
if ( err != MAILSMTP_NO_ERROR ) {
failuretext=tr("Error sending mail: %1").arg(mailsmtpError(err));
result = 0;
}
} else {
result = 0;
}
if (!result) {
storeFailedMail(data,size,failuretext);
} else {
- qDebug( "Mail sent." );
+ odebug << "Mail sent." << oendl;
storeMail(data,size,"Sent");
}
return result;
}
void SMTPwrapper::sendMail(const Opie::Core::OSmartPointer<Mail>&mail,bool later )
{
mailmime * mimeMail;
mimeMail = createMimeMail(mail );
if ( mimeMail == NULL ) {
- qDebug( "sendMail: error creating mime mail" );
+ odebug << "sendMail: error creating mime mail" << oendl;
} else {
sendProgress = new progressMailSend();
sendProgress->show();
sendProgress->setMaxMails(1);
smtpSend( mimeMail,later);
- qDebug("Clean up done");
+ odebug << "Clean up done" << oendl;
sendProgress->hide();
delete sendProgress;
sendProgress = 0;
mailmime_free( mimeMail );
}
}
int SMTPwrapper::sendQueuedMail(AbstractMail*wrap,const RecMailP&which) {
size_t curTok = 0;
mailimf_fields *fields = 0;
mailimf_field*ffrom = 0;
clist *rcpts = 0;
char*from = 0;
int res = 0;
encodedString * data = wrap->fetchRawBody(which);
if (!data)
return 0;
int err = mailimf_fields_parse( data->Content(), data->Length(), &curTok, &fields );
if (err != MAILIMF_NO_ERROR) {
delete data;
delete wrap;
return 0;
}
rcpts = createRcptList( fields );
ffrom = getField(fields, MAILIMF_FIELD_FROM );
from = getFrom(ffrom);
if (rcpts && from) {
res = smtpSend(from,rcpts,data->Content(),data->Length());
}
if (fields) {
mailimf_fields_free(fields);
fields = 0;
}
if (data) {
delete data;
}
if (from) {
free(from);
}
if (rcpts) {
smtp_address_list_free( rcpts );
}
return res;
}
/* this is a special fun */
bool SMTPwrapper::flushOutbox() {
bool returnValue = true;
- qDebug("Sending the queue");
+ odebug << "Sending the queue" << oendl;
if (!m_SmtpAccount) {
- qDebug("No smtp account given");
+ odebug << "No smtp account given" << oendl;
return false;
}
bool reset_user_value = false;
QString localfolders = AbstractMail::defaultLocalfolder();
AbstractMail*wrap = AbstractMail::getWrapper(localfolders);
if (!wrap) {
- qDebug("memory error");
+ odebug << "memory error" << oendl;
return false;
}
QString oldPw, oldUser;
QValueList<RecMailP> mailsToSend;
QValueList<RecMailP> mailsToRemove;
QString mbox("Outgoing");
wrap->listMessages(mbox,mailsToSend);
if (mailsToSend.count()==0) {
delete wrap;
- qDebug("No mails to send");
+ odebug << "No mails to send" << oendl;
return false;
}
oldPw = m_SmtpAccount->getPassword();
oldUser = m_SmtpAccount->getUser();
if (m_SmtpAccount->getLogin() && (m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty()) ) {
// get'em
QString user,pass;
LoginDialog login( m_SmtpAccount->getUser(), m_SmtpAccount->getPassword(), NULL, 0, true );
login.show();
if ( QDialog::Accepted == login.exec() ) {
// ok
user = login.getUser().latin1();
pass = login.getPassword().latin1();
reset_user_value = true;
m_SmtpAccount->setUser(user);
m_SmtpAccount->setPassword(pass);
} else {
return true;
}
}
sendProgress = new progressMailSend();
sendProgress->show();
sendProgress->setMaxMails(mailsToSend.count());
while (mailsToSend.count()>0) {
if (sendQueuedMail(wrap, (*mailsToSend.begin()))==0) {
QMessageBox::critical(0,tr("Error sending mail"),
tr("Error sending queued mail - breaking"));
returnValue = false;
break;
}
mailsToRemove.append((*mailsToSend.begin()));
mailsToSend.remove(mailsToSend.begin());
sendProgress->setCurrentMails(mailsToRemove.count());
}
if (reset_user_value) {
m_SmtpAccount->setUser(oldUser);
m_SmtpAccount->setPassword(oldPw);
}
Config cfg( "mail" );
cfg.setGroup( "Status" );
m_queuedMail = 0;
cfg.writeEntry( "outgoing", m_queuedMail );
emit queuedMails( m_queuedMail );
sendProgress->hide();
delete sendProgress;
sendProgress = 0;
wrap->deleteMails(mbox,mailsToRemove);
delete wrap;
return returnValue;
}
diff --git a/noncore/net/mail/libmailwrapper/statusmail.cpp b/noncore/net/mail/libmailwrapper/statusmail.cpp
index b78244d..51383f6 100644
--- a/noncore/net/mail/libmailwrapper/statusmail.cpp
+++ b/noncore/net/mail/libmailwrapper/statusmail.cpp
@@ -1,90 +1,90 @@
#include "statusmail.h"
StatusMail::StatusMail(QList<Account>&list)
{
currentImapStat.message_count=0;
currentImapStat.message_unseen=0;
currentImapStat.message_recent=0;
lastPop3Stat = currentImapStat;
currentPop3Stat = currentImapStat;
connectionList.setAutoDelete(true);
connectionList.clear();
initAccounts(list);
}
StatusMail::~StatusMail()
{
}
void StatusMail::initAccounts(QList<Account>&accounts)
{
Account *it;
folderStat currentStat;
AbstractMail * current = 0;
currentPop3Stat.message_count=0;
currentPop3Stat.message_recent=0;
currentPop3Stat.message_unseen=0;
for ( it = accounts.first(); it; it = accounts.next() ) {
if ( it->getType()==MAILLIB::A_IMAP && !it->getOffline() ) {
IMAPaccount*ima = static_cast<IMAPaccount *>(it);
current = AbstractMail::getWrapper(ima);
connectionList.append(current);
current->statusFolder(currentStat);
currentImapStat.message_count+=currentStat.message_unseen;
currentImapStat.message_count+=currentStat.message_recent;
currentImapStat.message_count+=currentStat.message_count;
} else if ( it->getType() == MAILLIB::A_POP3 && !it->getOffline() ) {
POP3account *pop3 = static_cast<POP3account *>(it);
current = AbstractMail::getWrapper(pop3);
connectionList.append(current);
current->statusFolder(currentStat);
currentPop3Stat.message_count+=currentStat.message_count;
}
current->logout();
}
- qDebug("Pop3 init count: %i",currentPop3Stat.message_count);
+ odebug << "Pop3 init count: " << currentPop3Stat.message_count << "" << oendl;
currentPop3Stat.message_recent = currentPop3Stat.message_unseen = 0;
lastPop3Stat.message_unseen = currentPop3Stat.message_unseen;
lastPop3Stat.message_recent = currentPop3Stat.message_recent;
lastPop3Stat.message_count = currentPop3Stat.message_count;
}
void StatusMail::reset_status()
{
lastPop3Stat = currentPop3Stat;
}
void StatusMail::check_current_stat(folderStat&targetStat)
{
AbstractMail*it = 0;
folderStat currentStat;
currentPop3Stat.message_recent = 0;
currentPop3Stat.message_count = 0;
currentPop3Stat.message_unseen = 0;
currentImapStat = currentPop3Stat;
for ( it = connectionList.first(); it; it = connectionList.next() ) {
it->statusFolder(currentStat);
it->logout();
if (it->getType() == MAILLIB::A_IMAP) {
currentImapStat.message_unseen+=currentStat.message_unseen;
currentImapStat.message_recent+=currentStat.message_recent;
currentImapStat.message_count+=currentStat.message_count;
} else if (it->getType() == MAILLIB::A_POP3) {
currentPop3Stat.message_count+=currentStat.message_count;
- qDebug("Pop3 count: %i",currentPop3Stat.message_count);
+ odebug << "Pop3 count: " << currentPop3Stat.message_count << "" << oendl;
}
}
- qDebug("Pop3 last: %i",lastPop3Stat.message_count);
+ odebug << "Pop3 last: " << lastPop3Stat.message_count << "" << oendl;
if (currentPop3Stat.message_count > lastPop3Stat.message_count) {
currentPop3Stat.message_recent = currentPop3Stat.message_count - lastPop3Stat.message_count;
currentPop3Stat.message_unseen = currentPop3Stat.message_recent;
} else {
lastPop3Stat.message_count = currentPop3Stat.message_count;
currentPop3Stat.message_recent = currentPop3Stat.message_unseen = 0;
}
targetStat = currentImapStat;
targetStat.message_unseen+=currentPop3Stat.message_unseen;
targetStat.message_recent+=currentPop3Stat.message_recent;
targetStat.message_count+=currentPop3Stat.message_count;
}
diff --git a/noncore/net/mail/libmailwrapper/storemail.cpp b/noncore/net/mail/libmailwrapper/storemail.cpp
index 914a11d..546d756 100644
--- a/noncore/net/mail/libmailwrapper/storemail.cpp
+++ b/noncore/net/mail/libmailwrapper/storemail.cpp
@@ -1,91 +1,91 @@
#include "storemail.h"
#include "mailwrapper.h"
#include "settings.h"
#include "abstractmail.h"
#include <libetpan/libetpan.h>
#include <qstring.h>
#include <stdlib.h>
using namespace Opie::Core;
Storemail::Storemail(Account*aAccount,const QString&aFolder)
: Generatemail()
{
wrapper = 0;
m_Account = aAccount;
m_tfolder = aFolder;
wrapper = AbstractMail::getWrapper(m_Account);
if (wrapper) {
wrapper->createMbox(m_tfolder);
}
}
Storemail::Storemail(const QString&dir,const QString&aFolder)
: Generatemail()
{
wrapper = 0;
m_Account = 0;
m_tfolder = aFolder;
wrapper = AbstractMail::getWrapper(dir);
if (wrapper) {
wrapper->createMbox(m_tfolder);
}
}
Storemail::Storemail(const QString&aFolder)
: Generatemail()
{
wrapper = 0;
m_Account = 0;
m_tfolder = aFolder;
wrapper = AbstractMail::getWrapper(AbstractMail::defaultLocalfolder());
if (wrapper) {
wrapper->createMbox(m_tfolder);
}
}
Storemail::~Storemail()
{
}
int Storemail::storeMail(const Opie::Core::OSmartPointer<Mail>&mail)
{
if (!wrapper) return 0;
int ret = 1;
mailmime * mimeMail = 0;
mimeMail = createMimeMail(mail );
if ( mimeMail == NULL ) {
- qDebug( "storeMail: error creating mime mail" );
+ odebug << "storeMail: error creating mime mail" << oendl;
return 0;
}
char *data;
size_t size;
data = 0;
mailmessage * msg = 0;
msg = mime_message_init(mimeMail);
mime_message_set_tmpdir(msg,getenv( "HOME" ));
int r = mailmessage_fetch(msg,&data,&size);
mime_message_detach_mime(msg);
mailmessage_free(msg);
msg = 0;
if (r != MAIL_NO_ERROR || !data) {
- qDebug("Error fetching mime...");
+ odebug << "Error fetching mime..." << oendl;
ret = 0;
}
if (ret) {
wrapper->storeMessage(data,size,m_tfolder);
}
if (data) {
free(data);
}
if (mimeMail) {
mailmime_free( mimeMail );
}
return ret;
}
diff --git a/noncore/net/mail/mainwindow.cpp b/noncore/net/mail/mainwindow.cpp
index c23ad3f..4c87d64 100644
--- a/noncore/net/mail/mainwindow.cpp
+++ b/noncore/net/mail/mainwindow.cpp
@@ -48,169 +48,169 @@ MainWindow::MainWindow( QWidget *parent, const char *name, WFlags flags )
syncFolders->addTo( mailMenu );
*/
showFolders = new QAction( tr( "Show/Hide folders" ), ICON_SHOWFOLDERS,
0, 0, this, 0, true );
showFolders->addTo( toolBar );
showFolders->addTo( mailMenu );
showFolders->setOn( true );
connect(showFolders, SIGNAL( toggled(bool) ),
SLOT( slotShowFolders(bool) ) );
/*
searchMails = new QAction( tr( "Search mails" ), QIconSet( Resource::loadPixmap("find") ),
0, 0, this );
searchMails->addTo( toolBar );
searchMails->addTo( mailMenu );
*/
deleteMails = new QAction(tr("Delete Mail"), QIconSet( Resource::loadPixmap("trash")), 0, 0, this);
deleteMails->addTo( toolBar );
deleteMails->addTo( mailMenu );
connect( deleteMails, SIGNAL( activated() ),
SLOT( slotDeleteMail() ) );
editSettings = new QAction( tr( "Edit settings" ), QIconSet( Resource::loadPixmap("SettingsIcon") ) ,
0, 0, this );
editSettings->addTo( settingsMenu );
connect( editSettings, SIGNAL( activated() ),
SLOT( slotEditSettings() ) );
editAccounts = new QAction( tr( "Configure accounts" ), QIconSet( Resource::loadPixmap("mail/editaccounts") ) ,
0, 0, this );
editAccounts->addTo( settingsMenu );
//setCentralWidget( view );
QVBox* wrapperBox = new QVBox( this );
setCentralWidget( wrapperBox );
QWidget *view = new QWidget( wrapperBox );
layout = new QBoxLayout ( view, QBoxLayout::LeftToRight );
folderView = new AccountView( view );
folderView->header()->hide();
folderView->setRootIsDecorated( true );
folderView->addColumn( tr( "Mailbox" ) );
layout->addWidget( folderView );
mailView = new QListView( view );
mailView->addColumn( tr( "" ) );
mailView->addColumn( tr( "Subject" ),QListView::Manual );
mailView->addColumn( tr( "Sender" ),QListView::Manual );
mailView->addColumn( tr( "Size" ),QListView::Manual);
mailView->addColumn( tr( "Date" ));
mailView->setAllColumnsShowFocus(true);
mailView->setSorting(-1);
statusWidget = new StatusWidget( wrapperBox );
statusWidget->hide();
layout->addWidget( mailView );
layout->setStretchFactor( folderView, 1 );
layout->setStretchFactor( mailView, 2 );
slotAdjustLayout();
QPEApplication::setStylusOperation( mailView->viewport(),QPEApplication::RightOnHold);
QPEApplication::setStylusOperation( folderView->viewport(),QPEApplication::RightOnHold);
connect( mailView, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),this,
SLOT( mailLeftClicked(int,QListViewItem*,const QPoint&,int) ) );
connect( mailView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),this,
SLOT( mailHold(int,QListViewItem*,const QPoint&,int) ) );
connect(folderView, SIGNAL(refreshMailview(const QValueList<RecMailP>&)),
this,SLOT(refreshMailView(const QValueList<RecMailP>&)));
connect( composeMail, SIGNAL( activated() ), SLOT( slotComposeMail() ) );
connect( sendQueued, SIGNAL( activated() ), SLOT( slotSendQueued() ) );
// connect( searchMails, SIGNAL( activated() ), SLOT( slotSearchMails() ) );
connect( editAccounts, SIGNAL( activated() ), SLOT( slotEditAccounts() ) );
// Added by Stefan Eilers to allow starting by addressbook..
// copied from old mail2
#if !defined(QT_NO_COP)
connect( qApp, SIGNAL( appMessage(const QCString&,const QByteArray&) ),
this, SLOT( appMessage(const QCString&,const QByteArray&) ) );
#endif
QTimer::singleShot( 1000, this, SLOT( slotAdjustColumns() ) );
}
MainWindow::~MainWindow()
{
}
void MainWindow::appMessage(const QCString &, const QByteArray &)
{
- qDebug("appMessage not reached");
+ odebug << "appMessage not reached" << oendl;
}
void MainWindow::slotAdjustLayout() {
QWidget *d = QApplication::desktop();
if ( d->width() < d->height() ) {
layout->setDirection( QBoxLayout::TopToBottom );
} else {
layout->setDirection( QBoxLayout::LeftToRight );
}
}
void MainWindow::slotAdjustColumns()
{
bool hidden = folderView->isHidden();
if ( hidden ) folderView->show();
folderView->setColumnWidth( 0, folderView->visibleWidth() );
if ( hidden ) folderView->hide();
mailView->setColumnWidth( 0, 10 );
mailView->setColumnWidth( 1, mailView->visibleWidth() - 130 );
mailView->setColumnWidth( 2, 80 );
mailView->setColumnWidth( 3, 50 );
mailView->setColumnWidth( 4, 50 );
}
void MainWindow::slotEditSettings()
{
}
void MainWindow::slotShowFolders( bool )
{
- qDebug( "slotShowFolders not reached" );
+ odebug << "slotShowFolders not reached" << oendl;
}
void MainWindow::refreshMailView(const QValueList<RecMailP>&)
{
- qDebug( "refreshMailView not reached" );
+ odebug << "refreshMailView not reached" << oendl;
}
void MainWindow::mailLeftClicked(int, QListViewItem *,const QPoint&,int )
{
- qDebug( "mailLeftClicked not reached" );
+ odebug << "mailLeftClicked not reached" << oendl;
}
void MainWindow::displayMail()
{
- qDebug("displayMail not reached");
+ odebug << "displayMail not reached" << oendl;
}
void MainWindow::slotDeleteMail()
{
- qDebug("deleteMail not reached");
+ odebug << "deleteMail not reached" << oendl;
}
void MainWindow::mailHold(int, QListViewItem *,const QPoint&,int )
{
- qDebug("mailHold not reached");
+ odebug << "mailHold not reached" << oendl;
}
void MainWindow::slotSendQueued()
{
}
void MainWindow::slotEditAccounts()
{
}
void MainWindow::slotComposeMail()
{
}
diff --git a/noncore/net/mail/nntpgroups.cpp b/noncore/net/mail/nntpgroups.cpp
index 8741c4b..3243ee3 100644
--- a/noncore/net/mail/nntpgroups.cpp
+++ b/noncore/net/mail/nntpgroups.cpp
@@ -1,62 +1,62 @@
#include "nntpgroups.h"
#include <libmailwrapper/settings.h>
#include <qlistview.h>
#include <qlineedit.h>
NNTPGroups::NNTPGroups(NNTPaccount *account, QWidget* parent, const char* name, WFlags fl)
: NNTPGroupsUI(parent,name,fl),subscribedGroups()
{
m_Account = account;
fillGroups();
}
NNTPGroups::~NNTPGroups()
{
}
void NNTPGroups::slotGetNG()
{
if (!m_Account) return;
GroupListView->clear();
NNTPwrapper tmp( m_Account );
QString filter = Groupfilteredit->text();
QStringList list = tmp.listAllNewsgroups(filter);
subscribedGroupsNotListed = subscribedGroups;
for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
QCheckListItem *item;
item = new QCheckListItem( GroupListView, (*it), QCheckListItem::CheckBox );
if ( subscribedGroups.contains( (*it) ) >= 1 ) {
item->setOn( true );
subscribedGroupsNotListed.remove((*it));
}
}
}
void NNTPGroups::fillGroups()
{
if (!m_Account) return;
subscribedGroups = m_Account->getGroups();
for ( QStringList::Iterator it = subscribedGroups.begin(); it != subscribedGroups.end(); ++it ) {
QCheckListItem *item;
item = new QCheckListItem( GroupListView, (*it), QCheckListItem::CheckBox );
item->setOn( true );
}
}
void NNTPGroups::storeValues()
{
if (!m_Account) return;
QListViewItemIterator list_it( GroupListView );
subscribedGroups.clear();
for ( ; list_it.current(); ++list_it ) {
if ( ( (QCheckListItem*)list_it.current() )->isOn() ) {
- qDebug(list_it.current()->text(0) );
+ odebug << list_it.current()->text(0) << oendl;
subscribedGroups.append( list_it.current()->text(0) );
}
}
subscribedGroups+=subscribedGroupsNotListed;
m_Account->setGroups( subscribedGroups );
}
diff --git a/noncore/net/mail/opiemail.cpp b/noncore/net/mail/opiemail.cpp
index 5da2161..0669b5a 100644
--- a/noncore/net/mail/opiemail.cpp
+++ b/noncore/net/mail/opiemail.cpp
@@ -1,280 +1,280 @@
#include "settingsdialog.h"
#include "opiemail.h"
#include "editaccounts.h"
#include "composemail.h"
#include "mailistviewitem.h"
#include "viewmail.h"
#include "selectstore.h"
#include "selectsmtp.h"
/* OPIE */
#include <libmailwrapper/smtpwrapper.h>
#include <libmailwrapper/mailtypes.h>
#include <libmailwrapper/abstractmail.h>
#include <qpe/resource.h>
#include <qpe/qpeapplication.h>
/* QT */
OpieMail::OpieMail( QWidget *parent, const char *name, WFlags flags )
: MainWindow( parent, name, WStyle_ContextHelp )
{
settings = new Settings();
folderView->populate( settings->getAccounts() );
}
OpieMail::~OpieMail()
{
if (settings) delete settings;
}
void OpieMail::appMessage(const QCString &msg, const QByteArray &data)
{
// copied from old mail2
if (msg == "writeMail(QString,QString)")
{
QDataStream stream(data,IO_ReadOnly);
QString name, email;
stream >> name >> email;
// removing the whitespaces at beginning and end is needed!
slotwriteMail(name.stripWhiteSpace(),email.stripWhiteSpace());
}
else if (msg == "newMail()")
{
slotComposeMail();
}
}
void OpieMail::slotwriteMail(const QString&name,const QString&email)
{
ComposeMail compose( settings, this, 0, true , WStyle_ContextHelp );
if (!email.isEmpty())
{
if (!name.isEmpty())
{
compose.setTo("\"" + name + "\"" + " " + "<"+ email + ">");
}
else
{
compose.setTo(email);
}
}
compose.slotAdjustColumns();
QPEApplication::execDialog( &compose );
}
void OpieMail::slotComposeMail()
{
- qDebug( "Compose Mail" );
+ odebug << "Compose Mail" << oendl;
slotwriteMail(0l,0l);
}
void OpieMail::slotSendQueued()
{
- qDebug( "Send Queued" );
+ odebug << "Send Queued" << oendl;
SMTPaccount *smtp = 0;
QList<Account> list = settings->getAccounts();
QList<SMTPaccount> smtpList;
smtpList.setAutoDelete(false);
Account *it;
for ( it = list.first(); it; it = list.next() )
{
if ( it->getType() == MAILLIB::A_SMTP )
{
smtp = static_cast<SMTPaccount *>(it);
smtpList.append(smtp);
}
}
if (smtpList.count()==0)
{
QMessageBox::information(0,tr("Info"),tr("Define a smtp account first"));
return;
}
if (smtpList.count()==1)
{
smtp = smtpList.at(0);
}
else
{
smtp = 0;
selectsmtp selsmtp;
selsmtp.setSelectionlist(&smtpList);
if ( QPEApplication::execDialog( &selsmtp ) == QDialog::Accepted )
{
smtp = selsmtp.selected_smtp();
}
}
if (smtp)
{
SMTPwrapper * wrap = new SMTPwrapper(smtp);
if ( wrap->flushOutbox() )
{
QMessageBox::information(0,tr("Info"),tr("Mail queue flushed"));
}
delete wrap;
}
}
void OpieMail::slotSearchMails()
{
- qDebug( "Search Mails" );
+ odebug << "Search Mails" << oendl;
}
void OpieMail::slotEditSettings()
{
SettingsDialog settingsDialog( this, 0, true, WStyle_ContextHelp );
QPEApplication::execDialog( &settingsDialog );
}
void OpieMail::slotEditAccounts()
{
- qDebug( "Edit Accounts" );
+ odebug << "Edit Accounts" << oendl;
EditAccounts eaDialog( settings, this, 0, true, WStyle_ContextHelp );
eaDialog.slotAdjustColumns();
QPEApplication::execDialog( &eaDialog );
if ( settings ) delete settings;
settings = new Settings();
folderView->populate( settings->getAccounts() );
}
void OpieMail::displayMail()
{
QListViewItem*item = mailView->currentItem();
if (!item) return;
RecMailP mail = ((MailListViewItem*)item)->data();
RecBodyP body = folderView->fetchBody(mail);
ViewMail readMail( this,"", Qt::WType_Modal | WStyle_ContextHelp );
readMail.setBody( body );
readMail.setMail( mail );
readMail.showMaximized();
readMail.exec();
if ( readMail.deleted )
{
folderView->refreshCurrent();
}
else
{
( (MailListViewItem*)item )->setPixmap( 0, Resource::loadPixmap( "" ) );
}
}
void OpieMail::slotDeleteMail()
{
if (!mailView->currentItem()) return;
RecMailP mail = ((MailListViewItem*)mailView->currentItem() )->data();
if ( QMessageBox::warning(this, tr("Delete Mail"), QString( tr("<p>Do you really want to delete this mail? <br><br>" ) + mail->getFrom() + " - " + mail->getSubject() ) , QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes )
{
mail->Wrapper()->deleteMail( mail );
folderView->refreshCurrent();
}
}
void OpieMail::mailHold(int button, QListViewItem *item,const QPoint&,int )
{
if (!mailView->currentItem()) return;
MAILLIB::ATYPE mailtype = ((MailListViewItem*)mailView->currentItem() )->wrapperType();
/* just the RIGHT button - or hold on pda */
if (button!=2) {return;}
- qDebug("Event right/hold");
+ odebug << "Event right/hold" << oendl;
if (!item) return;
QPopupMenu *m = new QPopupMenu(0);
if (m)
{
if (mailtype==MAILLIB::A_NNTP) {
m->insertItem(tr("Read this posting"),this,SLOT(displayMail()));
// m->insertItem(tr("Copy this posting"),this,SLOT(slotMoveCopyMail()));
} else {
if (folderView->currentisDraft()) {
m->insertItem(tr("Edit this mail"),this,SLOT(reEditMail()));
}
m->insertItem(tr("Read this mail"),this,SLOT(displayMail()));
m->insertItem(tr("Delete this mail"),this,SLOT(slotDeleteMail()));
m->insertItem(tr("Copy/Move this mail"),this,SLOT(slotMoveCopyMail()));
}
m->setFocus();
m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) );
delete m;
}
}
void OpieMail::slotShowFolders( bool show )
{
- qDebug( "Show Folders" );
+ odebug << "Show Folders" << oendl;
if ( show && folderView->isHidden() )
{
- qDebug( "-> showing" );
+ odebug << "-> showing" << oendl;
folderView->show();
}
else if ( !show && !folderView->isHidden() )
{
- qDebug( "-> hiding" );
+ odebug << "-> hiding" << oendl;
folderView->hide();
}
}
void OpieMail::refreshMailView(const QValueList<RecMailP>&list)
{
MailListViewItem*item = 0;
mailView->clear();
QValueList<RecMailP>::ConstIterator it;
for (it = list.begin(); it != list.end();++it)
{
item = new MailListViewItem(mailView,item);
item->storeData((*it));
item->showEntry();
}
}
void OpieMail::mailLeftClicked(int button, QListViewItem *item,const QPoint&,int )
{
/* just LEFT button - or tap with stylus on pda */
if (button!=1) return;
if (!item) return;
if (folderView->currentisDraft()) {
reEditMail();
} else {
displayMail();
}
}
void OpieMail::slotMoveCopyMail()
{
if (!mailView->currentItem()) return;
RecMailP mail = ((MailListViewItem*)mailView->currentItem() )->data();
AbstractMail*targetMail = 0;
QString targetFolder = "";
Selectstore sels;
folderView->setupFolderselect(&sels);
if (!sels.exec()) return;
targetMail = sels.currentMail();
targetFolder = sels.currentFolder();
if ( (mail->Wrapper()==targetMail && mail->getMbox()==targetFolder) ||
targetFolder.isEmpty())
{
return;
}
if (sels.newFolder() && !targetMail->createMbox(targetFolder))
{
QMessageBox::critical(0,tr("Error creating new Folder"),
tr("<center>Error while creating<br>new folder - breaking.</center>"));
return;
}
mail->Wrapper()->mvcpMail(mail,targetFolder,targetMail,sels.moveMails());
folderView->refreshCurrent();
}
void OpieMail::reEditMail()
{
if (!mailView->currentItem()) return;
ComposeMail compose( settings, this, 0, true , WStyle_ContextHelp );
compose.reEditMail(((MailListViewItem*)mailView->currentItem() )->data());
compose.slotAdjustColumns();
QPEApplication::execDialog( &compose );
}
diff --git a/noncore/net/mail/taskbarapplet/mailapplet.cpp b/noncore/net/mail/taskbarapplet/mailapplet.cpp
index f672a36..cac9048 100644
--- a/noncore/net/mail/taskbarapplet/mailapplet.cpp
+++ b/noncore/net/mail/taskbarapplet/mailapplet.cpp
@@ -11,135 +11,135 @@
#include <libmailwrapper/settings.h>
#include "mailapplet.h"
using namespace Opie::Core;
MailApplet::MailApplet( QWidget *parent )
: QWidget( parent ) {
m_config = new Config( "mail" );
m_config->setGroup( "Applet" );
setFixedWidth( AppLnk::smallIconSize() );
setFixedHeight( AppLnk::smallIconSize() );
hide();
m_newMails = 0;
m_statusMail = 0l;
if ( !m_config->readBoolEntry( "Disabled", false ) ) {
// delay 5 sec until the whole mail backend gets started .-)
QTimer::singleShot( 5000, this, SLOT( startup() ) );
}
repaint( true );
}
MailApplet::~MailApplet() {
if ( m_statusMail )
delete m_statusMail;
if ( m_config )
delete m_config;
}
void MailApplet::paintEvent( QPaintEvent* ) {
QPainter p( this );
p.drawPixmap( 0, 0, Resource::loadPixmap( "mail/inbox" ) );
QFont f( "vera", AppLnk::smallIconSize() );
QFontMetrics fm( f );
p.setFont( f );
p.setPen( Qt::blue );
p.drawText( AppLnk::smallIconSize()/3, AppLnk::smallIconSize() - 2, QString::number( m_newMails ) );
return;
}
void MailApplet::mouseReleaseEvent( QMouseEvent* e ) {
slotClicked();
}
void MailApplet::slotClicked() {
QCopEnvelope e( "QPE/System", "execute(QString)" );
e << QString( "opiemail" );
ODevice *device = ODevice::inst();
if ( !device-> ledList().isEmpty() ) {
OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0];
device->setLedState( led, Led_Off );
}
if (m_statusMail)
m_statusMail->reset_status();
hide();
}
void MailApplet::startup() {
Settings *settings = new Settings();
QList<Account> ma = settings->getAccounts();
m_statusMail = new StatusMail( ma );
delete settings;
m_intervalMs = m_config->readNumEntry( "CheckEvery", 5 ) * 60000;
m_intervalTimer = new QTimer();
m_intervalTimer->start( m_intervalMs );
connect( m_intervalTimer, SIGNAL( timeout() ), this, SLOT( slotCheck() ) );
}
void MailApplet::slotCheck() {
// Check wether the check interval has been changed.
int newIntervalMs = m_config->readNumEntry( "CheckEvery", 5 ) * 60000;
if ( newIntervalMs != m_intervalMs ) {
m_intervalTimer->changeInterval( newIntervalMs );
m_intervalMs = newIntervalMs;
}
if (m_statusMail == 0) {
return;
}
folderStat stat;
m_statusMail->check_current_stat( stat );
int newMailsOld = m_newMails;
m_newMails = stat.message_unseen;
- qDebug( QString( "test %1" ).arg( m_newMails ) );
+ odebug << QString( "test %1" ).arg( m_newMails ) << oendl;
if ( m_newMails > 0 && newMailsOld != m_newMails ) {
ODevice *device = ODevice::inst();
if ( isHidden() )
show();
if ( m_config->readBoolEntry( "BlinkLed", true ) ) {
if ( !device->ledList().isEmpty() ) {
OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0];
device->setLedState( led, device->ledStateList( led ).contains( Led_BlinkSlow ) ? Led_BlinkSlow : Led_On );
}
}
if ( m_config->readBoolEntry( "PlaySound", false ) )
device->playAlarmSound();
Config cfg( "mail" );
cfg.setGroup( "Status" );
cfg.writeEntry( "newMails", m_newMails );
QCopEnvelope env( "QPE/Pim", "newMails(int)" );
env << m_newMails;
repaint( true );
} else {
ODevice *device = ODevice::inst();
if ( !isHidden() )
hide();
if ( !device->ledList().isEmpty() ) {
OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0];
device->setLedState( led, Led_Off );
}
if ( newMailsOld != m_newMails ) {
Config cfg( "mail" );
cfg.setGroup( "Status" );
cfg.writeEntry( "newMails", m_newMails );
QCopEnvelope env( "QPE/Pim", "newMails(int)" );
env << m_newMails;
}
}
}
diff --git a/noncore/net/mail/viewmail.cpp b/noncore/net/mail/viewmail.cpp
index 156e11d..a574ea1 100644
--- a/noncore/net/mail/viewmail.cpp
+++ b/noncore/net/mail/viewmail.cpp
@@ -46,193 +46,193 @@ bool AttachItem::isParentof(const QValueList<int>&path)
/* if not set, then no parent */
if (path.count()==0||_path.count()==0) return false;
/* the parent must have one digit less then a child */
if (path.count()!=_path.count()+1) return false;
for (unsigned int i=0; i < _path.count();++i)
{
if (_path[i]!=path[i]) return false;
}
return true;
}
AttachItem* ViewMail::searchParent(const QValueList<int>&path)
{
QListViewItemIterator it( attachments );
for ( ; it.current(); ++it )
{
AttachItem*ati = (AttachItem*)it.current();
if (ati->isParentof(path)) return ati;
}
return 0;
}
AttachItem* ViewMail::lastChild(AttachItem*parent)
{
if (!parent) return 0;
AttachItem* item = (AttachItem*)parent->firstChild();
if (!item) return item;
AttachItem*temp=0;
while( (temp=(AttachItem*)item->nextSibling()))
{
item = temp;
}
return item;
}
void ViewMail::setBody(const RecBodyP&body )
{
m_body = body;
m_mail[2] = body->Bodytext();
attachbutton->setEnabled(body->Parts().count()>0);
attachments->setEnabled(body->Parts().count()>0);
if (body->Parts().count()==0)
{
return;
}
AttachItem * curItem=0;
AttachItem * parentItem = 0;
QString type=body->Description()->Type()+"/"+body->Description()->Subtype();
QString desc,fsize;
double s = body->Description()->Size();
int w;
w=0;
while (s>1024)
{
s/=1024;
++w;
if (w>=2) break;
}
QString q="";
switch(w)
{
case 1:
q="k";
break;
case 2:
q="M";
break;
default:
break;
}
{
/* I did not found a method to make a CONTENT reset on a QTextStream
so I use this construct that the stream will re-constructed in each
loop. To let it work, the textstream is packed into a own area of
code is it will be destructed after finishing its small job.
*/
QTextOStream o(&fsize);
if (w>0) o.precision(2); else o.precision(0);
o.setf(QTextStream::fixed);
o << s << " " << q << "Byte";
}
curItem=new AttachItem(attachments,curItem,type,"Mailbody","",fsize,-1,body->Description()->Positionlist());
QString filename = "";
for (unsigned int i = 0; i < body->Parts().count();++i)
{
filename = "";
type = body->Parts()[i]->Type()+"/"+body->Parts()[i]->Subtype();
part_plist_t::ConstIterator it = body->Parts()[i]->Parameters().begin();
for (;it!=body->Parts()[i]->Parameters().end();++it)
{
- qDebug(it.key());
+ odebug << it.key() << oendl;
if (it.key().lower()=="name")
{
filename=it.data();
}
}
s = body->Parts()[i]->Size();
w = 0;
while (s>1024)
{
s/=1024;
++w;
if (w>=2) break;
}
switch(w)
{
case 1:
q="k";
break;
case 2:
q="M";
break;
default:
q="";
break;
}
QTextOStream o(&fsize);
if (w>0) o.precision(2); else o.precision(0);
o.setf(QTextStream::fixed);
o << s << " " << q << "Byte";
desc = body->Parts()[i]->Description();
parentItem = searchParent(body->Parts()[i]->Positionlist());
if (parentItem)
{
AttachItem*temp = lastChild(parentItem);
if (temp) curItem = temp;
curItem=new AttachItem(parentItem,curItem,type,desc,filename,fsize,i,body->Parts()[i]->Positionlist());
attachments->setRootIsDecorated(true);
curItem = parentItem;
}
else
{
curItem=new AttachItem(attachments,curItem,type,desc,filename,fsize,i,body->Parts()[i]->Positionlist());
}
}
}
void ViewMail::slotShowHtml( bool state )
{
m_showHtml = state;
setText();
}
void ViewMail::slotItemClicked( QListViewItem * item , const QPoint & point, int )
{
if (!item )
return;
if ( ( ( AttachItem* )item )->Partnumber() == -1 )
{
setText();
return;
}
QPopupMenu *menu = new QPopupMenu();
int ret=0;
if ( item->text( 0 ).left( 5 ) == "text/" || item->text(0)=="message/rfc822" )
{
menu->insertItem( tr( "Show Text" ), 1 );
}
menu->insertItem( tr( "Save Attachment" ), 0 );
menu->insertSeparator(1);
ret = menu->exec( point, 0 );
switch(ret)
{
case 0:
{
MimeTypes types;
types.insert( "all", "*" );
QString str = OFileDialog::getSaveFileName( 1,
"/", item->text( 2 ) , types, 0 );
if( !str.isEmpty() )
{
encodedString*content = m_recMail->Wrapper()->fetchDecodedPart( m_recMail, m_body->Parts()[ ( ( AttachItem* )item )->Partnumber() ] );
if (content)
{
QFile output(str);
output.open(IO_WriteOnly);
output.writeBlock(content->Content(),content->Length());
output.close();
delete content;
}
}
diff --git a/noncore/net/opieftp/config.in b/noncore/net/opieftp/config.in
index 96e8b27..95cf73c 100644
--- a/noncore/net/opieftp/config.in
+++ b/noncore/net/opieftp/config.in
@@ -1,4 +1,4 @@
config OPIEFTP
boolean "opie-ftp (ftp client for Opie)"
default "y"
- depends ( LIBQPE || LIBQPE-X11 ) && FTPLIB
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && FTPLIB
diff --git a/noncore/net/opieftp/filePermissions.cpp b/noncore/net/opieftp/filePermissions.cpp
index f545c1f..991fcd5 100644
--- a/noncore/net/opieftp/filePermissions.cpp
+++ b/noncore/net/opieftp/filePermissions.cpp
@@ -1,131 +1,131 @@
/****************************************************************************
** copyright 2002 ljp ljp@llornkcor.com
** Created: Sat Feb 23 19:44:40 2002 L.J. Potter
**
** 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.
**
****************************************************************************/
#include "filePermissions.h"
#include <qfileinfo.h>
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qmessagebox.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
filePermissions::filePermissions( QWidget* parent, const char* name, bool modal, WFlags fl, const QString &fileName, bool useRemote )
: QDialog( parent, name, modal, fl )
{
if ( !name )
setName( tr("filePermissions") );
-// qDebug("FilePermissions "+fileName);
+// odebug << "FilePermissions "+fileName << oendl;
resize( 236, 210 );
isRemote=useRemote;
setMaximumSize( QSize( 236, 210 ) );
setCaption( tr( "Set File Permissions" ) );
TextLabel1 = new QLabel( this, "TextLabel1" );
TextLabel1->setGeometry( QRect( 25, 5, 175, 20 ) );
TextLabel1->setText( tr( "Set file permissions for:" ) );
LineEdit1 = new QLineEdit( this, "LineEdit1" );
LineEdit1->setGeometry( QRect( 10, 25, 218, 22 ) );
LineEdit1->setReadOnly(true);
TextLabel4 = new QLabel( this, "TextLabel4" );
TextLabel4->setGeometry( QRect( 5, 85, 50, 15 ) );
TextLabel4->setText( tr( "owner" ) );
TextLabel4_2 = new QLabel( this, "TextLabel4_2" );
TextLabel4_2->setGeometry( QRect( 5, 105, 50, 15 ) );
TextLabel4_2->setText( tr( "group" ) );
TextLabel4_3 = new QLabel( this, "TextLabel4_3" );
TextLabel4_3->setGeometry( QRect( 5, 125, 50, 15 ) );
TextLabel4_3->setText( tr( "others" ) );
CheckBox1 = new QCheckBox( this, "CheckBox1" );
CheckBox1->setGeometry( QRect( 75, 85, 20, 16 ) );
connect(CheckBox1, SIGNAL(released()),this,SLOT(ownReadCheck()));
CheckBox1_2 = new QCheckBox( this, "CheckBox1_2" );
CheckBox1_2->setGeometry( QRect( 135, 85, 20, 16 ) );
connect(CheckBox1_2, SIGNAL(released()),this,SLOT(ownWriteCheck()));
CheckBox1_3 = new QCheckBox( this, "CheckBox1_3" );
CheckBox1_3->setGeometry( QRect( 195, 85, 20, 16 ) );
connect(CheckBox1_3, SIGNAL(released()),this,SLOT(ownExeCheck()));
CheckBox1_4 = new QCheckBox( this, "CheckBox1_4" );
CheckBox1_4->setGeometry( QRect( 75, 105, 20, 16 ) );
connect(CheckBox1_4, SIGNAL(released()),this,SLOT(grpReadCheck()));
CheckBox1_5 = new QCheckBox( this, "CheckBox1_5" );
CheckBox1_5->setGeometry( QRect( 135, 105, 20, 16 ) );
connect(CheckBox1_5, SIGNAL(released()),this,SLOT(grpWriteCheck()));
CheckBox1_6 = new QCheckBox( this, "CheckBox1_6" );
CheckBox1_6->setGeometry( QRect( 195, 105, 20, 16 ) );
connect(CheckBox1_6, SIGNAL(released()),this,SLOT(grpExeCheck()));
CheckBox1_7 = new QCheckBox( this, "CheckBox1_7" );
CheckBox1_7->setGeometry( QRect( 75, 125, 16, 16 ) );
connect(CheckBox1_7, SIGNAL(released()),this,SLOT(wrldReadCheck()));
CheckBox1_8 = new QCheckBox( this, "CheckBox1_8" );
CheckBox1_8->setGeometry( QRect( 135, 125, 20, 16 ) );
connect(CheckBox1_8, SIGNAL(released()),this,SLOT(wrldWriteCheck()));
CheckBox1_8_2 = new QCheckBox( this, "CheckBox1_8_2" );
CheckBox1_8_2->setGeometry( QRect( 195, 125, 20, 16 ) );
connect(CheckBox1_8_2, SIGNAL(released()),this,SLOT(wrldExeCheck()));
GroupLineEdit = new QLineEdit( this, "GroupLineEdit" );
GroupLineEdit->setGeometry( QRect( 125, 155, 106, 22 ) );
OwnerLineEdit = new QLineEdit( this, "OwnerLineEdit" );
OwnerLineEdit->setGeometry( QRect( 10, 155, 106, 22 ) );
TextLabel5 = new QLabel( this, "TextLabel5" );
TextLabel5->setGeometry( QRect( 45, 180, 40, 16 ) );
TextLabel5->setText( tr( "Owner" ) );
TextLabel5_2 = new QLabel( this, "TextLabel5_2" );
TextLabel5_2->setGeometry( QRect( 155, 180, 40, 16 ) );
TextLabel5_2->setText( tr( "Group" ) );
ModeLine = new QLineEdit( this, "TextLabelMode" );
ModeLine->setGeometry( QRect( 10, 60, 40, 15 ) );
TextLabel3_2 = new QLabel( this, "TextLabel3_2" );
TextLabel3_2->setGeometry( QRect( 60, 55, 50, 20 ) );
TextLabel3_2->setText( tr( "read" ) );
TextLabel3_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
TextLabel3_2_2 = new QLabel( this, "TextLabel3_2_2" );
TextLabel3_2_2->setGeometry( QRect( 120, 55, 50, 20 ) );
TextLabel3_2_2->setText( tr( "write" ) );
TextLabel3_2_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
TextLabel3 = new QLabel( this, "TextLabel3" );
TextLabel3->setGeometry( QRect( 180, 55, 50, 20 ) );
TextLabel3->setText( tr( "execute" ) );
TextLabel3->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
struct stat buf;
mode_t mode;
file = fileName;
diff --git a/noncore/net/opieftp/opieftp.cpp b/noncore/net/opieftp/opieftp.cpp
index 4c39569..fe96103 100644
--- a/noncore/net/opieftp/opieftp.cpp
+++ b/noncore/net/opieftp/opieftp.cpp
@@ -1,160 +1,163 @@
/***************************************************************************
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 <qmenubar.h>
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
#include <qpe/config.h>
#include <qpe/mimetype.h>
+using namespace Opie::Core;
#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 <qmenubar.h>
#include <qlineedit.h>
#include <qlistbox.h>
#include <qvbox.h>
+/* STD */
#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 )
{
- qDebug("OpieFtp constructor");
+ odebug << "OpieFtp constructor" << oendl;
setCaption( tr( "OpieFtp" ) );
fuckeduphack=FALSE;
QVBox* wrapperBox = new QVBox( this );
setCentralWidget( wrapperBox );
QWidget *view = new QWidget( wrapperBox );
QGridLayout *layout = new QGridLayout( view );
layout->setSpacing( 2);
layout->setMargin( 2);
connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
QMenuBar *menuBar = new QMenuBar(this);
// QToolBar *menuBar = new QToolBar(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 );
//#if 0
layout->addMultiCellWidget( menuBar, 0, 0, 0, 2 );
//#endif
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( view,"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"),"",view,"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(view,"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( view, "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);
@@ -241,725 +244,725 @@ OpieFtp::OpieFtp( QWidget* parent, const char* name, WFlags fl)
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" ) );
#if 0
connect(TabWidget,SIGNAL(currentChanged(QWidget*)),
this,SLOT(tabChanged(QWidget*)));
#endif
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, view, "currentPathCombo" );
layout->addMultiCellWidget( currentPathCombo, 3, 3, 0, 4);
currentPathCombo ->setFixedWidth(220);
currentPathCombo->setEditable(TRUE);
currentPathCombo->lineEdit()->setText( currentDir.canonicalPath());
#if 0
connect( currentPathCombo, SIGNAL( activated(const QString&) ),
this, SLOT( currentPathComboActivated(const QString&) ) );
connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()),
this,SLOT(currentPathComboChanged()));
#endif
ProgressBar = new QProgressBar( view, "ProgressBar" );
layout->addMultiCellWidget( ProgressBar, 4, 4, 0, 4);
ProgressBar->setMaximumHeight(10);
filterStr="*";
b=FALSE;
#if 0
populateLocalView();
#endif
readConfig();
// ServerComboBox->setCurrentItem(currentServerConfig);
TabWidget->setCurrentPage(2);
- qDebug("Constructor done");
+ odebug << "Constructor done" << oendl;
}
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");
+// odebug << "ServerComboEdited" << oendl;
// // 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());
+ odebug << "Put: " << localFile.latin1() << ", " << remoteFile.latin1() << "" << oendl;
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());
+ odebug << "Get: " << localFile.latin1() << ", " << remoteFile.latin1() << "" << oendl;
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);
+// odebug << "Listing remote dir "+tmp << oendl;
// 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);
+// odebug << msg << oendl;
// 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);
+ odebug << "Symlink detected "+symLink << oendl;
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);
+ odebug << "Not a dir: "+currentDir.canonicalPath()+fileL << oendl;
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);
+ odebug << fileL << oendl;
}
}
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");
+// odebug << "populate remoteview" << oendl;
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 successfully "+sfile);
+ odebug << "temp file not opened successfully "+sfile << oendl;
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);
+// odebug << msg << oendl;
}
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);
+// odebug << msg << oendl;
}
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);
+// odebug << "RemoteCurrentDir1 "+oldRemoteCurrentDir << oendl;
}
} else if(strItem.find("/",0,TRUE) != -1) { // this is a directory
if( !remoteChDir( (const QString &)currentRemoteDir + strItem)) {
currentRemoteDir = oldRemoteCurrentDir;
strItem="";
-// qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir);
+// odebug << "RemoteCurrentDir1 "+oldRemoteCurrentDir << oendl;
} 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);
+ // odebug << "upload "+strItem << oendl;
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() );
@@ -1077,453 +1080,453 @@ void OpieFtp::remoteDelete()
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
}
}
void OpieFtp::localRename()
{
QString curFile = Local_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 = currentDir.canonicalPath() + "/" + curFile;
QString newName = currentDir.canonicalPath() + "/" + fileDlg->LineEdit1->text();//+".playlist";
if( rename(oldname.latin1(), newName.latin1())== -1)
QMessageBox::message(tr("Note"),tr("Could not rename"));
}
populateLocalView();
}
void OpieFtp::currentPathComboActivated(const QString & currentPath) {
if (TabWidget->currentPageIndex() == 0) {
chdir( currentPath.latin1() );
currentDir.cd( currentPath, TRUE);
populateLocalView();
update();
} else {
// chdir( currentPath.latin1() );
// currentDir.cd( currentPath, TRUE);
// populateList();
// update();
}
}
void OpieFtp::fillCombo(const QString &currentPath) {
currentPathCombo->lineEdit()->setText(currentPath);
if( localDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
currentPathCombo->clear();
localDirPathStringList.prepend(currentPath );
currentPathCombo->insertStringList( localDirPathStringList,-1);
}
currentPathCombo->lineEdit()->setText(currentPath);
if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
currentPathCombo->clear();
remoteDirPathStringList.prepend(currentPath );
currentPathCombo->insertStringList( remoteDirPathStringList,-1);
}
}
void OpieFtp::fillRemoteCombo(const QString &currentPath) {
currentPathCombo->lineEdit()->setText(currentPath);
if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
currentPathCombo->clear();
remoteDirPathStringList.prepend(currentPath );
currentPathCombo->insertStringList( remoteDirPathStringList,-1);
}
}
void OpieFtp::currentPathComboChanged()
{
QString oldRemoteCurrentDir = currentRemoteDir;
-// qDebug("oldRemoteCurrentDir "+oldRemoteCurrentDir);
+// odebug << "oldRemoteCurrentDir "+oldRemoteCurrentDir << oendl;
if (TabWidget->currentPageIndex() == 0) {
if(QDir( currentPathCombo->lineEdit()->text()).exists()) {
currentDir.setPath( currentPathCombo->lineEdit()->text() );
populateLocalView();
} else {
QMessageBox::message(tr("Note"),tr("That directory does not exist"));
}
}
if (TabWidget->currentPageIndex() == 1) {
currentRemoteDir = currentPathCombo->lineEdit()->text();
if(currentRemoteDir.right(1) !="/") {
currentRemoteDir = currentRemoteDir +"/";
currentPathCombo->lineEdit()->setText( currentRemoteDir );
}
if( !remoteChDir( (const QString &)currentRemoteDir) ) {
currentRemoteDir = oldRemoteCurrentDir;
currentPathCombo->lineEdit()->setText( currentRemoteDir );
}
remoteDirList( (const QString &)currentRemoteDir);
}
}
void OpieFtp::switchToLocalTab()
{
TabWidget->setCurrentPage(0);
}
void OpieFtp::switchToRemoteTab()
{
TabWidget->setCurrentPage(1);
}
void OpieFtp::switchToConfigTab()
{
TabWidget->setCurrentPage(2);
}
void OpieFtp::readConfig()
{
fillCombos();
Config cfg("opieftp");
cfg.setGroup("Server");
currentServerConfig = cfg.readNumEntry("currentServer", -1);
-// qDebug("Reading %d", currentServerConfig);
+// odebug << "Reading " << currentServerConfig << "" << oendl;
serverComboSelected( currentServerConfig-1);
}
void OpieFtp::writeConfig()
{
- qDebug("write config");
+ odebug << "write config" << oendl;
Config cfg("opieftp");
cfg.setGroup("Server");
QString username, remoteServerStr, remotePathStr, password, port, temp;
int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
if( currentServerConfig == -1) {
for (int i = 1; i <= numberOfEntries; i++) {
temp.setNum(i);
cfg.setGroup("Server");
QString tempStr = cfg.readEntry( temp,"");
}
temp.setNum( numberOfEntries + 1);
cfg.setGroup("Server");
remoteServerStr = cfg.readEntry( temp,"");
int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider);
temp.setNum(numberOfEntries+1);
cfg.setGroup("Server");
cfg.writeEntry( temp, ServerComboBox->currentText() +":"+PortSpinBox->cleanText() );
cfg.writeEntry("currentServer", numberOfEntries+1);
currentServerConfig = numberOfEntries+1;
- qDebug("setting currentserverconfig to %d", currentServerConfig);
+ odebug << "setting currentserverconfig to " << currentServerConfig << "" << oendl;
cfg.setGroup(temp);
if(!newServerName.isEmpty())
cfg.writeEntry("ServerName", newServerName);
cfg.writeEntry("RemotePath", remotePath->text());
cfg.writeEntry("Username", UsernameComboBox->currentText());
cfg.writeEntryCrypt( UsernameComboBox->currentText(), PasswordEdit->text());
cfg.setGroup("Server");
cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries + 1 ));
}
}
void OpieFtp::clearCombos() {
- qDebug("clearing");
+ odebug << "clearing" << oendl;
ServerComboBox->clear();
UsernameComboBox->clear();
PasswordEdit->clear();
serverListView->clear();
}
void OpieFtp::fillCombos()
{
clearCombos();
Config cfg("opieftp");
cfg.setGroup("Server");
QString username, remoteServerStr, remotePathStr, password, port, temp;
int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
for (int i = 1; i <= numberOfEntries; i++) {
temp.setNum(i);
- qDebug(temp);
+ odebug << temp << oendl;
cfg.setGroup("Server");
remoteServerStr = cfg.readEntry( temp,"");
- qDebug( remoteServerStr);
+ odebug << remoteServerStr << oendl;
int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
port = remoteServerStr.right( divider - 1);
bool ok;
PortSpinBox->setValue( port.toInt(&ok,10));
remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider);
- qDebug( "remote server string "+remoteServerStr);
+ odebug << "remote server string "+remoteServerStr << oendl;
ServerComboBox->insertItem( remoteServerStr );
cfg.setGroup(temp);
username = cfg.readEntry(temp);
UsernameComboBox->insertItem(username);
password = cfg.readEntryCrypt(username,"");
PasswordEdit->setText(password);
serverListView->insertItem( cfg.readEntry("ServerName"));
}
}
void OpieFtp::serverComboSelected(int index)
{
currentServerConfig = index+1;
- qDebug("server combo selected %d", index+1);
+ odebug << "server combo selected " << index+1 << "" << oendl;
QString username, remoteServerStr, remotePathStr, password, port, temp;
// remoteServerStr = ServerComboBox->text(index);
Config cfg("opieftp");
cfg.setGroup("Server");
// int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
temp.setNum(index+1);
remoteServerStr = cfg.readEntry( temp,"");
- qDebug("Group" +temp);
+ odebug << "Group" +temp << oendl;
cfg.setGroup(temp);
-// qDebug(temp);
+// odebug << temp << oendl;
int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
port = remoteServerStr.right( divider - 1);
bool ok;
int portInt = port.toInt(&ok,10);
if( portInt == 0) portInt = 21;
ServerComboBox->lineEdit()->setText(remoteServerStr.left( remoteServerStr.find(":",0,TRUE)));
PortSpinBox->setValue( portInt);
remotePath->setText(cfg.readEntry("RemotePath", "/"));
username = cfg.readEntry("Username", "anonymous");
UsernameComboBox->lineEdit()->setText(username);
- qDebug(username);
-// qDebug("Password is "+cfg.readEntryCrypt(username, "me@opieftp.org"));
+ odebug << username << oendl;
+// odebug << "Password is "+cfg.readEntryCrypt(username << oendl;
PasswordEdit->setText(cfg.readEntryCrypt(username, "me@opieftp.org"));
// UsernameComboBox
// PasswordEdit
cfg.setGroup("Server");
temp.sprintf("%d",currentServerConfig);
cfg.writeEntry("currentServer", temp);
fuckeduphack = TRUE;
serverListView->setCurrentItem( index);
fuckeduphack=FALSE;
- qDebug("server list set selected %d",index);
+ odebug << "server list set selected " << index << "" << oendl;
update();
}
void OpieFtp::deleteServer()
{
QString username, remoteServerStr, remotePathStr, password, port, temp, servername;
remoteServerStr = ServerComboBox->currentText( );
username = UsernameComboBox->currentText();
servername=serverListView->currentText();
Config cfg("opieftp");
cfg.setGroup("Server");
QString tempname;
int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
for (int i = 1; i <= numberOfEntries; i++) {
temp.setNum(i);
// cfg.setGroup("Server");
cfg.setGroup(QString::number(i));
tempname=cfg.readEntry( "ServerName","");
if( tempname.find( servername,0,TRUE) != -1 ) {
// servername.find( cfg.readEntry("ServerName")) != -1 &&
// remoteServerStr.find( cfg.readEntry("RemotePath")) != -1 &&
// username.find( cfg.readEntry("Username")) != -1) {
serverListView->removeItem(i);
- qDebug("OK DELETE "+tempname);
+ odebug << "OK DELETE "+tempname << oendl;
cfg.removeEntry(QString::number(i));
for ( ; i <= numberOfEntries; i++) {
cfg.setGroup("Server");
cfg.writeEntry("Server", QString::number(numberOfEntries + 1 ));
cfg.setGroup(QString::number(i+1)); //get next server config
servername=cfg.readEntry("ServerName");
remoteServerStr=cfg.readEntry("RemotePath");
username=cfg.readEntry("Username");
password=cfg.readEntryCrypt( username);
cfg.setGroup(QString::number(i));
cfg.writeEntry("RemotePath", remoteServerStr);
cfg.writeEntry("ServerName", servername);
cfg.writeEntry("Username", username);
cfg.writeEntryCrypt( username, password);
}
cfg.setGroup("Server");
cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries - 1 ));
}
}
cfg.setGroup(QString::number(numberOfEntries));
cfg.removeEntry("Server");
cfg.removeEntry("RemotePath");
cfg.removeEntry("ServerName");
username=cfg.readEntry("Username");
cfg.removeEntry("Username");
cfg.removeEntry(username);
currentServerConfig=currentServerConfig-1;
fillCombos();
update();
}
void OpieFtp::upDir()
{
if (TabWidget->currentPageIndex() == 0) {
QString current = currentDir.canonicalPath();
QDir dir(current);
dir.cdUp();
current = dir.canonicalPath();
chdir( current.latin1() );
currentDir.cd( current, TRUE);
populateLocalView();
update();
} else {
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);
+// odebug << msg << oendl;
}
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);
+// odebug << msg << oendl;
}
currentRemoteDir=path;
remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
if(currentRemoteDir.right(1) !="/")
currentRemoteDir +="/";
currentPathCombo->lineEdit()->setText( currentRemoteDir);
fillRemoteCombo( (const QString &)currentRemoteDir);
}
}
void OpieFtp::docButtonPushed() {
QString current = QPEApplication::documentDir();
chdir( current.latin1() );
currentDir.cd( current, TRUE);
populateLocalView();
update();
}
void OpieFtp::homeButtonPushed() {
QString current = QDir::homeDirPath();
chdir( current.latin1() );
currentDir.cd( current, TRUE);
populateLocalView();
update();
}
void OpieFtp::doAbout() {
QMessageBox::message("OpieFtp","Opie ftp client is copyright 2002 by\n"
"L.J.Potter<llornkcor@handhelds.org>\n"
"and uses ftplib copyright 1996-2000\n"
"by Thomas Pfau, pfau@cnj.digex.net\n\n"
"and is licensed by the GPL");
}
void OpieFtp::NewServer() {
InputDialog *fileDlg;
fileDlg = new InputDialog(this,tr("New Server name"),TRUE, 0);
fileDlg->exec();
Config cfg("opieftp");
if( fileDlg->result() == 1 ) {
newServerName = fileDlg->LineEdit1->text();
for(int i=1;i<serverListView->count();i++) {
cfg.setGroup( QString::number(i));
if(cfg.readEntry("ServerName").find(newServerName,0,TRUE) != -1) {
QMessageBox::message(tr("OpieFtp"),tr("Sorry name already taken"));
return;
}
}
currentServerConfig =-1;
writeConfig();
serverListView->insertItem( newServerName );
serverListView->setCurrentItem( serverListView->count());
}
}
void OpieFtp::serverListClicked( const QString &item) {
if(item.isEmpty()) return;
Config cfg("opieftp");
- qDebug("highltined "+item);
+ odebug << "highltined "+item << oendl;
int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
for (int i = 1; i <= numberOfEntries; i++) {
cfg.setGroup(QString::number(i));
if(cfg.readEntry( "ServerName").find(item) != -1 && !fuckeduphack)
serverComboSelected(i-1);
}
}
void OpieFtp::timerOut() {
}
diff --git a/noncore/net/opieftp/opieftp.pro b/noncore/net/opieftp/opieftp.pro
index 2f97dc2..003b166 100644
--- a/noncore/net/opieftp/opieftp.pro
+++ b/noncore/net/opieftp/opieftp.pro
@@ -1,11 +1,10 @@
-#CONFIG += qt warn_on quick-app
-CONFIG += qt warn_on
-HEADERS = opieftp.h inputDialog.h
-SOURCES = opieftp.cpp inputDialog.cpp main.cpp
-TARGET = opieftp
+CONFIG += qt warn_on
+HEADERS = opieftp.h inputDialog.h
+SOURCES = opieftp.cpp inputDialog.cpp main.cpp
+TARGET = opieftp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lftplib
+LIBS += -lqpe -lopiecore2 -lftplib
DESTDIR = $(OPIEDIR)/bin
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/net/opieirc/config.in b/noncore/net/opieirc/config.in
index a61cf70..2c56523 100644
--- a/noncore/net/opieirc/config.in
+++ b/noncore/net/opieirc/config.in
@@ -1,4 +1,4 @@
config OPIEIRC
boolean "opie-irc (chat via your favorite IRC server)"
default "y"
- depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI && LIBQTAUX
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && LIBOPIE2UI && LIBQTAUX
diff --git a/noncore/net/opieirc/ircmisc.cpp b/noncore/net/opieirc/ircmisc.cpp
index 22387b3..6d93a34 100644
--- a/noncore/net/opieirc/ircmisc.cpp
+++ b/noncore/net/opieirc/ircmisc.cpp
@@ -1,83 +1,86 @@
-#include <stdio.h>
#include "ircmisc.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
IRCTabBar::IRCTabBar(QWidget *parent, const char *name) : QTabBar(parent, name) {
}
int IRCTabBar::insertTab(QTab *tab, int index) {
/* FIXME: find some nicer way to do this */
QExtTab *ext = new QExtTab();
ext->color = black;
ext->label = tab->text();
ext->r = tab->rect();
ext->enabled = tab->isEnabled();
ext->iconset = tab->iconSet();
delete tab;
return QTabBar::insertTab(ext, index);
}
void IRCTabBar::setTabColor(int index, QColor color) {
((QExtTab *)tab(index))->color = color;
update();
}
void IRCTabBar::paintLabel(QPainter* p, const QRect& br, QTab* t, bool focus) const {
QRect r = br;
QTabBar::paintLabel(p, br, t, focus);
if (t->id == currentTab())
r.setBottom(r.bottom() - style().defaultFrameWidth());
p->setPen(((QExtTab *)t)->color);
p->drawText(r, AlignCenter | ShowPrefix, t->label);
}
IRCTabWidget::IRCTabWidget(QWidget *parent, const char *name) : QTabWidget(parent, name) {
setTabBar(new IRCTabBar(this, "tab control"));
}
void IRCTabWidget::setTabColor(int index, QColor color) {
((IRCTabBar *)tabBar())->setTabColor(index, color);
}
IRCHistoryLineEdit::IRCHistoryLineEdit(QWidget *parent, const char *name) : QLineEdit(parent, name) {
m_index = -1;
installEventFilter(this);
}
void IRCHistoryLineEdit::keyPressEvent(QKeyEvent *event) {
int key = event->key();
if (key == Key_Up) {
if (m_history.count() > 0 && m_index < (signed int)m_history.count()-1) {
m_index++;
setText(m_history[m_index]);
}
} else if (key == Key_Down) {
if (m_history.count() > 0 && m_index > 0) {
m_index--;
setText(m_history[m_index]);
}
if (m_index == 0) {
m_index = -1;
setText("");
}
} else if (key == Key_Return) {
m_history.prepend(text());
m_index = -1;
} else if (key == Key_Tab) {
- printf("got tab\n");
+ odebug << "got tab" << oendl;
return;
}
QLineEdit::keyPressEvent(event);
}
bool IRCHistoryLineEdit::eventFilter(QObject *object, QEvent *event) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *k = (QKeyEvent *) event;
/* Catch tab characters */
if (k->key() == Key_Tab) {
- qDebug("tab!");
+ odebug << "tab!" << oendl;
return TRUE;
}
}
return QLineEdit::eventFilter(object, event);
}
diff --git a/noncore/net/opieirc/opieirc.pro b/noncore/net/opieirc/opieirc.pro
index 4f9092f..2455ec4 100644
--- a/noncore/net/opieirc/opieirc.pro
+++ b/noncore/net/opieirc/opieirc.pro
@@ -1,25 +1,24 @@
-CONFIG = qt warn_on quick-app
-HEADERS = ircchannel.h ircconnection.h \
+CONFIG = qt warn_on quick-app
+HEADERS = ircchannel.h ircconnection.h \
ircmessage.h \
ircmessageparser.h ircoutput.h \
ircperson.h ircserver.h ircsession.h \
mainwindow.h irctab.h ircservertab.h \
ircchanneltab.h ircchannellist.h \
ircserverlist.h ircservereditor.h \
ircquerytab.h ircsettings.h ircmisc.h
-SOURCES = ircchannel.cpp ircconnection.cpp \
+SOURCES = ircchannel.cpp ircconnection.cpp \
ircmessage.cpp \
ircmessageparser.cpp ircoutput.cpp \
ircperson.cpp ircserver.cpp \
ircsession.cpp main.cpp mainwindow.cpp \
irctab.cpp ircservertab.cpp \
ircchanneltab.cpp ircchannellist.cpp \
ircserverlist.cpp ircservereditor.cpp \
ircquerytab.cpp ircsettings.cpp ircmisc.cpp
INCLUDEPATH += $(OPIEDIR)/include
-DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lopieui2 -lqtaux2
-
-TARGET = opieirc
+DEPENDPATH += $(OPIEDIR)/include
+LIBS += -lqpe -lopiecore2 -lopieui2 -lqtaux2
+TARGET = opieirc
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/net/opietooth/applet/bluezapplet.cpp b/noncore/net/opietooth/applet/bluezapplet.cpp
index 8a7f0bc..1d93f5c 100644
--- a/noncore/net/opietooth/applet/bluezapplet.cpp
+++ b/noncore/net/opietooth/applet/bluezapplet.cpp
@@ -113,109 +113,109 @@ namespace OpieTooth {
int BluezApplet::setBluezDiscoveryStatus(int d) {
}
void BluezApplet::mousePressEvent( QMouseEvent *) {
QPopupMenu *menu = new QPopupMenu();
QPopupMenu *signal = new QPopupMenu();
int ret=0;
/* Refresh active state */
timerEvent( 0 );
if (bluezactive) {
menu->insertItem( tr("Disable Bluetooth"), 0 );
} else {
menu->insertItem( tr("Enable Bluetooth"), 1 );
}
menu->insertItem( tr("Launch manager"), 2 );
menu->insertSeparator(6);
//menu->insertItem( tr("Signal strength"), signal, 5);
//menu->insertSeparator(8);
if (bluezDiscoveryActive) {
menu->insertItem( tr("Disable discovery"), 3 );
} else {
menu->insertItem( tr("Enable discovery"), 4 );
}
QPoint p = mapToGlobal( QPoint(1, -menu->sizeHint().height()-1) );
ret = menu->exec(p, 0);
switch(ret) {
case 0:
setBluezStatus(0);
timerEvent( 0 );
break;
case 1:
setBluezStatus(1);
timerEvent( 0 );
break;
case 2:
// start bluetoothmanager
launchManager();
timerEvent( 0 );
break;
case 3:
setBluezDiscoveryStatus(0);
timerEvent( 0 );
break;
case 4:
setBluezDiscoveryStatus(1);
timerEvent(0 );
break;
//case 7:
// With table of currently-detected devices.
}
delete signal;
delete menu;
}
/**
* Launches the bluetooth manager
*/
void BluezApplet::launchManager() {
QCopEnvelope e("QPE/System", "execute(QString)");
e << QString("bluetooth-manager");
}
/**
* Refresh timer
* @param the timer event
*/
void BluezApplet::timerEvent( QTimerEvent * ) {
bool oldactive = bluezactive;
int olddiscovery = bluezDiscoveryActive;
bluezactive = checkBluezStatus();
bluezDiscoveryActive = checkBluezDiscoveryStatus();
if ((bluezactive != oldactive) || (bluezDiscoveryActive != olddiscovery)) {
update();
}
}
/**
* Implementation of the paint event
* @param the QPaintEvent
*/
void BluezApplet::paintEvent( QPaintEvent* ) {
QPainter p(this);
- qDebug("paint bluetooth pixmap");
+ odebug << "paint bluetooth pixmap" << oendl;
if (bluezactive > 0) {
p.drawPixmap( 0, 1, bluezOnPixmap );
} else {
p.drawPixmap( 0, 1, bluezOffPixmap );
}
if (bluezDiscoveryActive > 0) {
p.drawPixmap( 0, 1, bluezDiscoveryOnPixmap );
}
}
};
diff --git a/noncore/net/opietooth/lib/startdunconnection.cpp b/noncore/net/opietooth/lib/startdunconnection.cpp
index 09b19d2..37f2ae7 100644
--- a/noncore/net/opietooth/lib/startdunconnection.cpp
+++ b/noncore/net/opietooth/lib/startdunconnection.cpp
@@ -1,68 +1,68 @@
#include "startdunconnection.h"
using namespace OpieTooth;
using namespace Opie::Core;
StartDunConnection::StartDunConnection() {
m_dunConnect = 0l;
setConnectionType();
}
StartDunConnection::~StartDunConnection() {
delete m_dunConnect;
}
StartDunConnection::StartDunConnection( QString mac ) {
m_dunConnect = 0l;
m_mac = mac;
setConnectionType();
}
void StartDunConnection::setName( QString name ) {
m_name = name;
}
QString StartDunConnection::name() {
return m_name;
}
void StartDunConnection::setConnectionType() {
m_connectionType = Pan;
}
StartConnection::ConnectionType StartDunConnection::type() {
return m_connectionType;
}
void StartDunConnection::start() {
m_dunConnect = new OProcess();
*m_dunConnect << "dund" << "--listen" << "--connect" << m_mac;
connect( m_dunConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) ,
this, SLOT( slotExited(Opie::Core::OProcess*) ) );
connect( m_dunConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ),
this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) );
if (!m_dunConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
- qWarning( "could not start" );
+ owarn << "could not start" << oendl;
delete m_dunConnect;
}
}
void StartDunConnection::slotExited( OProcess* proc ) {
delete m_dunConnect;
}
void StartDunConnection::slotStdOut(OProcess* proc, char* chars, int len)
{}
void StartDunConnection::stop() {
if ( m_dunConnect ) {
delete m_dunConnect;
m_dunConnect = 0l;
}
}
diff --git a/noncore/net/opietooth/lib/startpanconnection.cpp b/noncore/net/opietooth/lib/startpanconnection.cpp
index 24ac530..50afc9f 100644
--- a/noncore/net/opietooth/lib/startpanconnection.cpp
+++ b/noncore/net/opietooth/lib/startpanconnection.cpp
@@ -1,84 +1,84 @@
#include "startpanconnection.h"
using namespace OpieTooth;
using namespace Opie::Core;
using namespace Opie::Core;
StartPanConnection::StartPanConnection() {
m_panConnect = 0l;
setConnectionType();
}
StartPanConnection::~StartPanConnection() {
delete m_panConnect;
}
StartPanConnection::StartPanConnection( QString mac ) {
m_panConnect = 0l;
m_mac = mac;
setConnectionType();
}
void StartPanConnection::setName( QString name ) {
m_name = name;
}
QString StartPanConnection::name() {
return m_name;
}
void StartPanConnection::setConnectionType() {
m_connectionType = Pan;
}
StartConnection::ConnectionType StartPanConnection::type() {
return m_connectionType;
}
void StartPanConnection::start() {
m_panConnect = new OProcess();
- qDebug( "IM START " + m_mac );
+ odebug << "IM START " + m_mac << oendl;
*m_panConnect << "pand" << "--connect" << m_mac;
connect( m_panConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) ,
this, SLOT( slotExited(Opie::Core::OProcess*) ) );
connect( m_panConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ),
this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) );
if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
- qWarning( "could not start" );
+ owarn << "could not start" << oendl;
delete m_panConnect;
}
}
void StartPanConnection::slotExited( OProcess* proc ) {
delete m_panConnect;
m_panConnect = 0l;
}
void StartPanConnection::slotStdOut(OProcess* proc, char* chars, int len)
{}
void StartPanConnection::stop() {
if ( m_panConnect ) {
delete m_panConnect;
m_panConnect = 0l;
}
m_panConnect = new OProcess();
- qDebug("IM STOP " + m_mac);
+ odebug << "IM STOP " + m_mac << oendl;
*m_panConnect << "pand" << "--kill" << m_mac;
connect( m_panConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) ,
this, SLOT( slotExited(Opie::Core::OProcess*) ) );
connect( m_panConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ),
this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) );
if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
- qWarning( "could not stop" );
+ owarn << "could not stop" << oendl;
delete m_panConnect;
}
}
diff --git a/noncore/net/opietooth/manager/bluebase.cpp b/noncore/net/opietooth/manager/bluebase.cpp
index 29030ab..b1cddd2 100644
--- a/noncore/net/opietooth/manager/bluebase.cpp
+++ b/noncore/net/opietooth/manager/bluebase.cpp
@@ -62,193 +62,193 @@ BlueBase::BlueBase( QWidget* parent, const char* name, WFlags fl )
connect( PushButton2, SIGNAL( clicked() ), this, SLOT(startScan() ) );
connect( configApplyButton, SIGNAL(clicked() ), this, SLOT(applyConfigChanges() ) );
connect( rfcommBindButton, SIGNAL( clicked() ), this, SLOT( rfcommDialog() ) );
// not good since lib is async
// connect( ListView2, SIGNAL( expanded(QListViewItem*) ),
// this, SLOT( addServicesToDevice(QListViewItem*) ) );
connect( ListView2, SIGNAL( clicked(QListViewItem*)),
this, SLOT( startServiceActionClicked(QListViewItem*) ) );
connect( ListView2, SIGNAL( rightButtonClicked(QListViewItem*,const QPoint&,int) ),
this, SLOT(startServiceActionHold(QListViewItem*,const QPoint&,int) ) );
connect( m_localDevice , SIGNAL( foundServices(const QString&,Services::ValueList) ),
this, SLOT( addServicesToDevice(const QString&,Services::ValueList) ) );
connect( m_localDevice, SIGNAL( available(const QString&,bool) ),
this, SLOT( deviceActive(const QString&,bool) ) );
connect( m_localDevice, SIGNAL( connections(ConnectionState::ValueList) ),
this, SLOT( addConnectedDevices(ConnectionState::ValueList) ) );
connect( m_localDevice, SIGNAL( signalStrength(const QString&,const QString&) ),
this, SLOT( addSignalStrength(const QString&,const QString&) ) );
// let hold be rightButtonClicked()
QPEApplication::setStylusOperation( ListView2->viewport(), QPEApplication::RightOnHold);
QPEApplication::setStylusOperation( ListView4->viewport(), QPEApplication::RightOnHold);
//Load all icons needed
m_offPix = Resource::loadPixmap( "opietooth/notconnected" );
m_onPix = Resource::loadPixmap( "opietooth/connected" );
m_findPix = Resource::loadPixmap( "opietooth/find" );
QPalette pal = this->palette();
QColor col = pal.color( QPalette::Active, QColorGroup::Background );
pal.setColor( QPalette::Active, QColorGroup::Button, col );
pal.setColor( QPalette::Inactive, QColorGroup::Button, col );
pal.setColor( QPalette::Normal, QColorGroup::Button, col );
pal.setColor( QPalette::Disabled, QColorGroup::Button, col );
this->setPalette( pal );
setCaption( tr( "Bluetooth Manager" ) );
readConfig();
initGui();
ListView2->setRootIsDecorated(true);
writeToHciConfig();
// search conncetions
addConnectedDevices();
addSignalStrength();
m_iconLoader = new BTIconLoader();
readSavedDevices();
}
/**
* Reads all options from the config file
*/
void BlueBase::readConfig()
{
Config cfg( "bluetoothmanager" );
cfg.setGroup( "bluezsettings" );
m_deviceName = cfg.readEntry( "name" , "No name" ); // name the device should identify with
m_defaultPasskey = cfg.readEntryCrypt( "passkey" , "" ); // <- hmm, look up how good the trolls did that, maybe too weak
m_useEncryption = cfg.readBoolEntry( "useEncryption" , TRUE );
m_enableAuthentification = cfg.readBoolEntry( "enableAuthentification" , TRUE );
m_enablePagescan = cfg.readBoolEntry( "enablePagescan" , TRUE );
m_enableInquiryscan = cfg.readBoolEntry( "enableInquiryscan" , TRUE );
}
/**
* Writes all options to the config file
*/
void BlueBase::writeConfig()
{
Config cfg( "bluetoothmanager" );
cfg.setGroup( "bluezsettings" );
cfg.writeEntry( "name" , m_deviceName );
cfg.writeEntryCrypt( "passkey" , m_defaultPasskey );
cfg.writeEntry( "useEncryption" , m_useEncryption );
cfg.writeEntry( "enableAuthentification" , m_enableAuthentification );
cfg.writeEntry( "enablePagescan" , m_enablePagescan );
cfg.writeEntry( "enableInquiryscan" , m_enableInquiryscan );
writeToHciConfig();
}
/**
* Modify the hcid.conf file to our needs
*/
void BlueBase::writeToHciConfig()
{
- qWarning("writeToHciConfig");
+ owarn << "writeToHciConfig" << oendl;
HciConfWrapper hciconf ( "/etc/bluetooth/hcid.conf" );
hciconf.load();
hciconf.setPinHelper( "/opt/QtPalmtop/bin/bluepin" );
hciconf.setName( m_deviceName );
hciconf.setEncrypt( m_useEncryption );
hciconf.setAuth( m_enableAuthentification );
hciconf.setPscan( m_enablePagescan );
hciconf.setIscan( m_enableInquiryscan );
hciconf.save();
}
/**
* Read the list of allready known devices
*/
void BlueBase::readSavedDevices()
{
QValueList<RemoteDevice> loadedDevices;
DeviceHandler handler;
loadedDevices = handler.load();
addSearchedDevices( loadedDevices );
}
/**
* Write the list of allready known devices
*/
void BlueBase::writeSavedDevices()
{
QListViewItemIterator it( ListView2 );
BTListItem* item;
BTDeviceItem* device;
RemoteDevice::ValueList list;
for ( ; it.current(); ++it )
{
item = (BTListItem*)it.current();
if(item->typeId() != BTListItem::Device )
continue;
device = (BTDeviceItem*)item;
list.append( device->remoteDevice() );
}
/*
* if not empty save the List through DeviceHandler
*/
if ( list.isEmpty() )
return;
DeviceHandler handler;
handler.save( list );
}
/**
* Set up the gui
*/
void BlueBase::initGui()
{
StatusLabel->setText( status() ); // maybe move it to getStatus()
cryptCheckBox->setChecked( m_useEncryption );
authCheckBox->setChecked( m_enableAuthentification );
pagescanCheckBox->setChecked( m_enablePagescan );
inquiryscanCheckBox->setChecked( m_enableInquiryscan );
deviceNameLine->setText( m_deviceName );
passkeyLine->setText( m_defaultPasskey );
// set info tab
setInfo();
}
/**
* Get the status informations and returns it
* @return QString the status informations gathered
*/
QString BlueBase::status()const
{
QString infoString = tr( "<b>Device name : </b> Ipaq" );
infoString += QString( "<br><b>" + tr( "MAC adress: " ) +"</b> No idea" );
infoString += QString( "<br><b>" + tr( "Class" ) + "</b> PDA" );
return (infoString);
}
/**
* Read the current values from the gui and invoke writeConfig()
*/
void BlueBase::applyConfigChanges()
{
m_deviceName = deviceNameLine->text();
m_defaultPasskey = passkeyLine->text();
m_useEncryption = cryptCheckBox->isChecked();
m_enableAuthentification = authCheckBox->isChecked();
m_enablePagescan = pagescanCheckBox->isChecked();
m_enableInquiryscan = inquiryscanCheckBox->isChecked();
@@ -274,415 +274,415 @@ void BlueBase::rfcommDialog()
/**
* Add fresh found devices from scan dialog to the listing
*
*/
void BlueBase::addSearchedDevices( const QValueList<RemoteDevice> &newDevices )
{
BTDeviceItem * deviceItem;
QValueList<RemoteDevice>::ConstIterator it;
for( it = newDevices.begin(); it != newDevices.end() ; ++it )
{
if (find( (*it) )) // is already inserted
continue;
deviceItem = new BTDeviceItem( ListView2 , (*it) );
deviceItem->setPixmap( 1, m_findPix );
deviceItem->setExpandable ( true );
// look if device is avail. atm, async
deviceActive( (*it) );
// ggf auch hier?
addServicesToDevice( deviceItem );
}
}
/**
* Action that is toggled on entrys on click
*/
void BlueBase::startServiceActionClicked( QListViewItem */*item*/ )
{}
/**
* Action that are toggled on hold (mostly QPopups i guess)
*/
void BlueBase::startServiceActionHold( QListViewItem * item, const QPoint & point, int /*column*/ )
{
if (!item )
return;
QPopupMenu *menu = new QPopupMenu();
int ret=0;
if ( ((BTListItem*)item)->type() == "device")
{
QPopupMenu *groups = new QPopupMenu();
menu->insertItem( ((BTDeviceItem*)item)->name(),0 );
menu->insertSeparator(1);
menu->insertItem( tr("rescan sevices"), 2);
menu->insertItem( tr("to group"), groups , 3);
menu->insertItem( tr("delete"), 4);
ret = menu->exec( point , 0);
switch(ret)
{
case -1:
break;
case 2:
addServicesToDevice( (BTDeviceItem*)item );
break;
case 4:
// deletes childs too
delete item;
break;
}
delete groups;
}
/*
* We got service sensitive PopupMenus in our factory
* We will create one through the factory and will insert
* our Separator + ShowInfo into the menu or create a new
* one if the factory returns 0
* PopupMenu deletion is kind of weird.
* If escaped( -1 ) or any of our items were chosen we'll
* delete the PopupMenu otherwise it's the responsibility of
* the PopupMenu to delete itself
*
*/
else if ( ((BTListItem*)item)->type() == "service")
{
BTServiceItem* service = (BTServiceItem*)item;
QMap<int, QString> list = service->services().classIdList();
QMap<int, QString>::Iterator it = list.begin();
QPopupMenu *popup =0l;
if ( it != list.end() )
{
- qWarning("Searching id %d %s", it.key(), it.data().latin1() );
+ owarn << "Searching id " << it.key() << " " << it.data().latin1() << "" << oendl;
popup = m_popHelper.find( it.key(),
service->services(),
(BTDeviceItem*)service->parent() );
}
else
{
- qWarning("Empty");
+ owarn << "Empty" << oendl;
}
if ( popup == 0l )
{
- qWarning("factory returned 0l");
+ owarn << "factory returned 0l" << oendl;
popup = new QPopupMenu();
}
int test1 = popup->insertItem( tr("Test1:"), 2);
ret = popup->exec( point );
- qWarning("returned from exec() ");
+ owarn << "returned from exec() " << oendl;
if ( ret == -1 )
{
;
}
else if ( ret == test1 )
{
;
}
delete popup;
}
delete menu;
}
/**
* Search and display avail. services for a device (on expand from device listing)
* @param item the service item returned
*/
void BlueBase::addServicesToDevice( BTDeviceItem * item )
{
- qDebug("addServicesToDevice");
+ odebug << "addServicesToDevice" << oendl;
// row of mac adress text(3)
RemoteDevice device = item->remoteDevice();
m_deviceList.insert( item->mac() , item );
// and some time later I get a signal foundServices( const QString& device, Services::ValueList ); back
m_localDevice->searchServices( device );
}
/**
* Overloaded. This one it the one that is
ted to the foundServices signal
* @param device the mac address of the remote device
* @param servicesList the list with the service the device has.
*/
void BlueBase::addServicesToDevice( const QString& device, Services::ValueList servicesList )
{
- qDebug("fill services list");
+ odebug << "fill services list" << oendl;
QMap<QString,BTDeviceItem*>::Iterator it;
BTDeviceItem* deviceItem = 0;
// get the right devices which requested the search
it = m_deviceList.find( device );
if( it == m_deviceList.end() )
return;
deviceItem = it.data();
// remove previous entries
QList<QListViewItem> tempList;
tempList.setAutoDelete( true );
QListViewItem * child = deviceItem->firstChild();
while( child )
{
tempList.append( child );
child = child->nextSibling();
}
tempList.clear();
QValueList<OpieTooth::Services>::Iterator it2;
BTServiceItem* serviceItem;
if (!servicesList.isEmpty() )
{
// add services
QMap<int, QString> list;
QMap<int, QString>::Iterator classIt;
for( it2 = servicesList.begin(); it2 != servicesList.end(); ++it2 )
{
serviceItem = new BTServiceItem( deviceItem, (*it2) );
list = (*it2).classIdList();
classIt = list.begin();
int classId=0;
if ( classIt != list.end() )
{
classId = classIt.key();
}
serviceItem->setPixmap( 0, m_iconLoader->serviceIcon( classId ) );
}
}
else
{
Services s1;
s1.setServiceName( tr("no services found") );
serviceItem = new BTServiceItem( deviceItem, s1 );
}
// now remove them from the list
m_deviceList.remove( it );
}
void BlueBase::addSignalStrength()
{
QListViewItemIterator it( ListView4 );
for ( ; it.current(); ++it )
{
m_localDevice->signalStrength( ((BTConnectionItem*)it.current() )->connection().mac() );
}
QTimer::singleShot( 5000, this, SLOT( addSignalStrength() ) );
}
void BlueBase::addSignalStrength( const QString& mac, const QString& strength )
{
QListViewItemIterator it( ListView4 );
for ( ; it.current(); ++it )
{
if( ((BTConnectionItem*)it.current())->connection().mac() == mac )
{
((BTConnectionItem*)it.current() )->setSignalStrength( strength );
}
}
}
/**
* Add the existing connections (pairs) to the connections tab.
* This one triggers the search
*/
void BlueBase::addConnectedDevices()
{
m_localDevice->searchConnections();
}
/**
* This adds the found connections to the connection tab.
* @param connectionList the ValueList with all current connections
*/
void BlueBase::addConnectedDevices( ConnectionState::ValueList connectionList )
{
QValueList<OpieTooth::ConnectionState>::Iterator it;
BTConnectionItem * connectionItem;
if ( !connectionList.isEmpty() )
{
for (it = connectionList.begin(); it != connectionList.end(); ++it)
{
QListViewItemIterator it2( ListView4 );
bool found = false;
for ( ; it2.current(); ++it2 )
{
if( ( (BTConnectionItem*)it2.current())->connection().mac() == (*it).mac() )
{
found = true;
}
}
if ( found == false )
{
connectionItem = new BTConnectionItem( ListView4, (*it) );
if( m_deviceList.find((*it).mac()).data() )
{
connectionItem->setName( m_deviceList.find( (*it).mac()).data()->name() );
}
}
}
QListViewItemIterator it2( ListView4 );
for ( ; it2.current(); ++it2 )
{
bool found = false;
for (it = connectionList.begin(); it != connectionList.end(); ++it)
{
if( ( ((BTConnectionItem*)it2.current())->connection().mac() ) == (*it).mac() )
{
found = true;
}
}
if ( !found )
{
delete it2.current();
}
}
}
else
{
ListView4->clear();
ConnectionState con;
con.setMac( tr("No connections found") );
connectionItem = new BTConnectionItem( ListView4 , con );
}
// recall connection search after some time
QTimer::singleShot( 15000, this, SLOT( addConnectedDevices() ) );
}
/**
* Find out if a device can currently be reached
* @param device
*/
void BlueBase::deviceActive( const RemoteDevice &device )
{
// search by mac, async, gets a signal back
// We should have a BTDeviceItem there or where does it get added to the map -zecke
m_localDevice->isAvailable( device.mac() );
}
/**
* The signal catcher. Set the avail. status on device.
* @param device - the mac address
* @param connected - if it is avail. or not
*/
void BlueBase::deviceActive( const QString& device, bool connected )
{
- qDebug("deviceActive slot");
+ odebug << "deviceActive slot" << oendl;
QMap<QString,BTDeviceItem*>::Iterator it;
it = m_deviceList.find( device );
if( it == m_deviceList.end() )
return;
BTDeviceItem* deviceItem = it.data();
if ( connected )
{
deviceItem->setPixmap( 1, m_onPix );
}
else
{
deviceItem->setPixmap( 1, m_offPix );
}
m_deviceList.remove( it );
}
/**
* Open the "scan for devices" dialog
*/
void BlueBase::startScan()
{
ScanDialog *scan = new ScanDialog( this, "ScanDialog",
true, WDestructiveClose );
QObject::connect( scan, SIGNAL( selectedDevices(const QValueList<RemoteDevice>&) ),
this, SLOT( addSearchedDevices(const QValueList<RemoteDevice>&) ) );
QPEApplication::showDialog( scan );
}
/**
* Set the informations about the local device in information Tab
*/
void BlueBase::setInfo()
{
StatusLabel->setText( status() );
}
/**
* Decontructor
*/
BlueBase::~BlueBase()
{
writeSavedDevices();
delete m_iconLoader;
}
/**
* find searches the ListView for a BTDeviceItem containig
* the same Device if found return true else false
* @param dev RemoteDevice to find
* @return returns true if found
*/
bool BlueBase::find( const RemoteDevice& rem )
{
QListViewItemIterator it( ListView2 );
BTListItem* item;
BTDeviceItem* device;
for (; it.current(); ++it )
{
item = (BTListItem*) it.current();
if ( item->typeId() != BTListItem::Device )
continue;
device = (BTDeviceItem*)item;
if ( rem.equals( device->remoteDevice() ) )
return true;
}
return false; // not found
}
diff --git a/noncore/net/opietooth/manager/devicehandler.cpp b/noncore/net/opietooth/manager/devicehandler.cpp
index 9c5b817..bd34351 100644
--- a/noncore/net/opietooth/manager/devicehandler.cpp
+++ b/noncore/net/opietooth/manager/devicehandler.cpp
@@ -1,87 +1,87 @@
#include <stdlib.h>
#include <qdir.h>
#include <qpe/config.h>
#include "devicehandler.h"
using namespace OpieTooth;
DeviceHandler::DeviceHandler() {
};
DeviceHandler::~DeviceHandler() {
}
RemoteDevice::ValueList DeviceHandler::load() {
RemoteDevice::ValueList list;
QString path = QDir::homeDirPath() + "/Settings/bluetooth";
QDir deviceListSave( path);
// list of .conf files
QStringList devicesFileList = deviceListSave.entryList();
// cut .conf of to get the mac and also read the name entry in it.
if (!devicesFileList.isEmpty() ) {
QString name;
QString mac;
QStringList::Iterator it;
for (it = devicesFileList.begin(); it != devicesFileList.end(); ++it ) {
if ( (*it) == "." || (*it) == ".." )
continue;
- qDebug((*it).latin1() );
+ odebug << (*it).latin1() << oendl;
Config conf(path + "/"+(*it), Config::File);
conf.setGroup("Info");
name = conf.readEntry("name", "Error");
mac = conf.readEntry("mac", QString::null);
- qDebug("MAC: " + mac);
- qDebug("NAME: " + name);
+ odebug << "MAC: " + mac << oendl;
+ odebug << "NAME: " + name << oendl;
if (mac.isEmpty() )
continue;
RemoteDevice currentDevice( mac , name );
list.append( currentDevice );
}
}
return list;
};
/*
* This is some how rude but make sure all old devices
* are getting deleted
*/
void DeviceHandler::save( const RemoteDevice::ValueList& list) {
QCString rm;
rm += "rm -rf ";
rm += QDir::homeDirPath() + "/Settings/bluetooth";
system ( rm.data() );
if (list.isEmpty() ) // no need to create the dir
return;
/**
* Create a new dir
*/
rm = "mkdir ";
rm += QDir::homeDirPath() + "/Settings/bluetooth";
- qWarning("out %s", rm.data() );
+ owarn << "out " << rm.data() << "" << oendl;
system( rm.data() );
RemoteDevice::ValueList::ConstIterator it;
// write the config
for ( it = list.begin(); it != list.end(); ++it ) {
- qDebug( "/Settings/bluetooth/" + (*it).mac() + ".conf");
+ odebug << "/Settings/bluetooth/" + (*it).mac() + ".conf" << oendl;
Config conf( QDir::homeDirPath() +
"/Settings/bluetooth/" +
(*it).mac() + ".conf", Config::File );
conf.setGroup( "Info" );
conf.writeEntry( "name", (*it).name() );
conf.writeEntry( "mac", (*it).mac() );
}
}
diff --git a/noncore/net/opietooth/manager/dunpopup.cpp b/noncore/net/opietooth/manager/dunpopup.cpp
index 3043f71..5b01d2f 100644
--- a/noncore/net/opietooth/manager/dunpopup.cpp
+++ b/noncore/net/opietooth/manager/dunpopup.cpp
@@ -1,63 +1,63 @@
#include <qpe/qcopenvelope_qws.h>
#include <qtimer.h>
#include "dunpopup.h"
using namespace OpieTooth;
/*
* c'tor init the QAction
*/
DunPopup::DunPopup( OpieTooth::BTDeviceItem* item ) : QPopupMenu() {
- qWarning("DunPopup c'tor");
+ owarn << "DunPopup c'tor" << oendl;
m_item = item;
QAction *a, *b, *c;
m_dunconnection = 0l;
/* connect action */
a = new QAction(); // so it's get deleted
a->setText( tr("connect") );
a->addTo( this );
connect( a, SIGNAL( activated() ), this, SLOT( slotConnect() ) );
b = new QAction();
b->setText( tr( "connect+conf" ) );
b->addTo( this );
connect( b, SIGNAL( activated() ), this, SLOT( slotConnectAndConfig() ) );
c = new QAction();
c->setText( tr( "disconnect" ) );
c->addTo( this );
connect( c, SIGNAL( activated() ), this, SLOT( slotDisconnect() ) );
};
DunPopup::~DunPopup() {
}
void DunPopup::slotConnect() {
m_dunconnection = new StartDunConnection( m_item->mac() );
m_dunconnection->start();
}
void DunPopup::slotDisconnect() {
m_dunconnection->stop();
}
void DunPopup::slotConnectAndConfig() {
slotConnect();
// more intelligence here later like passing the device ( bnepX )
QCopEnvelope e( "QPE/System", "execute(QString)" );
e << QString( "networksettings" );
}
diff --git a/noncore/net/opietooth/manager/hciconfwrapper.cpp b/noncore/net/opietooth/manager/hciconfwrapper.cpp
index 35e9cd9..71c935c 100644
--- a/noncore/net/opietooth/manager/hciconfwrapper.cpp
+++ b/noncore/net/opietooth/manager/hciconfwrapper.cpp
@@ -1,139 +1,139 @@
#include "hciconfwrapper.h"
#include <qfile.h>
#include <qtextstream.h>
#include <qregexp.h>
namespace OpieTooth {
HciConfWrapper::HciConfWrapper( const QString &fileName) {
m_fileName = fileName;
}
HciConfWrapper::~HciConfWrapper() {
}
void HciConfWrapper::setPinHelper( const QString& app ) {
setValue( "pin_helper" , app );
}
void HciConfWrapper::setName( const QString &name ) {
qDebug ("NAME : " + name);
setValue( "name" , "\"" + name + "\"" );
}
void HciConfWrapper::setIscan( bool enable) {
if ( enable ) {
setValue( "iscan" , "enable" );
} else {
setValue( "iscan" , "disable" );
}
}
void HciConfWrapper::setPscan( bool enable) {
if ( enable ) {
setValue( "pscan" , "enable" );
} else {
setValue( "pscan" , "disable" );
}
}
void HciConfWrapper::setAuth( bool enable) {
if ( enable ) {
setValue( "auth" , "enable" );
} else {
setValue( "auth" , "disable" );
}
}
void HciConfWrapper::setEncrypt( bool enable) {
if ( enable ) {
setValue( "encrypt" , "enable" );
} else {
setValue( "encrypt" , "disable" );
}
}
void HciConfWrapper::setValue(const QString &key, const QString &value ) {
if (m_file.isEmpty() ) // load first
return;
QStringList::Iterator it;
QString str;
for (it = m_file.begin(); it != m_file.end(); ++it ) {
str = (*it);
if( (str.contains(key)) > 0 ) {
- qDebug("Found");
+ odebug << "Found" << oendl;
// still need to look if its commented out!!!
str.simplifyWhiteSpace();
- qDebug( key );
+ odebug << key << oendl;
if (str.startsWith("#")) {
str = (key + " " + value + ";");
} else {
str = str.replace( QRegExp( "\\s*"+key+"\\s+[^\\s][^;]*;" ), key + " " + value + ";");
}
- qDebug( str );
+ odebug << str << oendl;
it = m_file.remove( it );
it = m_file.insert( it, str );
//return; the regexp is too wide -zecke // all set
}
}
}
/**
* This loads the config file and stores it inside
* the m_file
*/
void HciConfWrapper::load() {
- qWarning("loaded");
+ owarn << "loaded" << oendl;
m_file.clear();
QFile file( m_fileName );
if (!file.open( IO_ReadOnly ) ) {
- qDebug("Could not open");
+ odebug << "Could not open" << oendl;
return;
}
/**
* readAll() into a QByteArray
* QStringList::split('\n', array )
* would this be faster? -zecke
*/
QTextStream stream(&file );
QString tmp;
while ( !stream.atEnd() ) {
tmp = stream.readLine();
m_file.append( tmp );
}
}
void HciConfWrapper::save() {
- qWarning("save");
+ owarn << "save" << oendl;
if (m_file.isEmpty() ) // load first
return;
QFile file( m_fileName );
if ( !file.open(IO_WriteOnly ) ) {
- qWarning("could not open %s", m_fileName.latin1() );
+ owarn << "could not open " << m_fileName.latin1() << "" << oendl;
return;
}
QTextStream stream(&file );
QStringList::Iterator it;
for ( it = m_file.begin(); it != m_file.end(); ++it ) {
stream << (*it) << endl;
}
- qWarning("saved");
+ owarn << "saved" << oendl;
};
}
diff --git a/noncore/net/opietooth/manager/obexdialog.cpp b/noncore/net/opietooth/manager/obexdialog.cpp
index 1ef862a..3a3dbb0 100644
--- a/noncore/net/opietooth/manager/obexdialog.cpp
+++ b/noncore/net/opietooth/manager/obexdialog.cpp
@@ -1,89 +1,89 @@
#include "obexdialog.h"
#include <qpushbutton.h>
#include <qmultilineedit.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qfileinfo.h>
#include <qpe/resource.h>
#include <opie2/oprocess.h>
#include <opie2/ofiledialog.h>
using namespace OpieTooth;
using namespace Opie::Core;
using namespace Opie::Ui;
using namespace Opie::Core;
ObexDialog::ObexDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device )
: QDialog( parent, name, modal, fl ) {
if ( !name )
setName( "ObexDialog" );
setCaption( tr( "beam files " ) ) ;
m_device = device;
layout = new QVBoxLayout( this );
QLabel* info = new QLabel( this );
info->setText( tr("Which file should be beamed?") );
cmdLine = new QLineEdit( this );
QPushButton *browserButton;
browserButton = new QPushButton( Resource::loadIconSet("fileopen"),"",this,"BrowseButton");
connect( browserButton, SIGNAL(released() ), this , SLOT(browse() ) );
chNameLine = new QLineEdit( this );
sendButton = new QPushButton( this );
sendButton->setText( tr( "Send" ) );
layout->addWidget(info);
layout->addWidget(cmdLine);
layout->addWidget(browserButton);
layout->addWidget(chNameLine);
layout->addWidget(sendButton);
connect( sendButton, SIGNAL( clicked() ), this, SLOT( sendData() ) );
}
ObexDialog::~ObexDialog() {
}
void ObexDialog::browse() {
MimeTypes types;
QStringList all;
all << "*/*";
types.insert("All Files", all );
QString str = OFileDialog::getOpenFileName( 1,"/","", types, 0 );
cmdLine->setText( str );
}
void ObexDialog::sendData() {
QString fileURL = cmdLine->text();
QString file = QFileInfo( fileURL ).fileName();
QString modifiedName = chNameLine->text();
// vom popupmenu beziehen
OProcess* obexSend = new OProcess();
if ( !modifiedName.isEmpty() ) {
*obexSend << "ussp-push" << m_device << fileURL << modifiedName;
} else {
*obexSend << "ussp-push" << m_device << fileURL << file;
}
if (!obexSend->start(OProcess::DontCare, OProcess::AllOutput) ) {
- qWarning("could not start");
+ owarn << "could not start" << oendl;
delete obexSend;
}
}
diff --git a/noncore/net/opietooth/manager/obexpopup.cpp b/noncore/net/opietooth/manager/obexpopup.cpp
index d147d52..9a50199 100644
--- a/noncore/net/opietooth/manager/obexpopup.cpp
+++ b/noncore/net/opietooth/manager/obexpopup.cpp
@@ -1,45 +1,45 @@
#include "obexdialog.h"
#include "obexpopup.h"
/* OPIE */
#include <qpe/qpeapplication.h>
/* QT */
#include <qtimer.h>
using namespace OpieTooth;
/*
* c'tor init the QAction
*/
ObexPopup::ObexPopup()
: QPopupMenu()
{
- qWarning("RfcCommPopup c'tor");
+ owarn << "RfcCommPopup c'tor" << oendl;
QAction* a;
/* connect action */
a = new QAction( ); // so it's get deleted
a->setText("Push file");
a->addTo( this );
connect( a, SIGNAL( activated() ),
this, SLOT( slotPush() ) );
};
ObexPopup::~ObexPopup()
{}
void ObexPopup::slotPush()
{
- qWarning("push something");
+ owarn << "push something" << oendl;
ObexDialog obexDialog;
QPEApplication::execDialog( &obexDialog );
}
diff --git a/noncore/net/opietooth/manager/panpopup.cpp b/noncore/net/opietooth/manager/panpopup.cpp
index 8b05964..43c2777 100644
--- a/noncore/net/opietooth/manager/panpopup.cpp
+++ b/noncore/net/opietooth/manager/panpopup.cpp
@@ -1,64 +1,64 @@
#include <qpe/qcopenvelope_qws.h>
#include <qtimer.h>
#include "panpopup.h"
using namespace OpieTooth;
/*
* c'tor init the QAction
*/
PanPopup::PanPopup( OpieTooth::BTDeviceItem* item ) : QPopupMenu() {
- qWarning("PanPopup c'tor");
+ owarn << "PanPopup c'tor" << oendl;
m_item = item;
QAction *a, *b, *c;
m_panconnection = 0l;
/* connect action */
a = new QAction(); // so it's get deleted
a->setText( tr("connect") );
a->addTo( this );
connect( a, SIGNAL( activated() ), this, SLOT( slotConnect() ) );
b = new QAction();
b->setText( tr( "connect+conf" ) );
b->addTo( this );
connect( b, SIGNAL( activated() ), this, SLOT( slotConnectAndConfig() ) );
c = new QAction();
c->setText( tr( "disconnect" ) );
c->addTo( this );
connect( c, SIGNAL( activated() ), this, SLOT( slotDisconnect() ) );
};
PanPopup::~PanPopup() {
}
void PanPopup::slotConnect() {
m_panconnection = new StartPanConnection( m_item->mac() );
m_panconnection->start();
}
void PanPopup::slotDisconnect() {
if (!m_panconnection) m_panconnection = new StartPanConnection( m_item->mac() );
m_panconnection->stop();
}
void PanPopup::slotConnectAndConfig() {
slotConnect();
// more intelligence here later like passing the device ( bnepX )
QCopEnvelope e( "QPE/System", "execute(QString)" );
e << QString( "networksettings" );
}
diff --git a/noncore/net/opietooth/manager/popuphelper.cpp b/noncore/net/opietooth/manager/popuphelper.cpp
index ab22fea..19deb19 100644
--- a/noncore/net/opietooth/manager/popuphelper.cpp
+++ b/noncore/net/opietooth/manager/popuphelper.cpp
@@ -1,36 +1,36 @@
#include "stdpopups.h"
#include "popuphelper.h"
using namespace OpieTooth;
PopupHelper::PopupHelper() {
init();
}
PopupHelper::~PopupHelper() {
}
void PopupHelper::insert( int id, popupFactory fact ) {
m_map.insert(id, fact );
}
QPopupMenu* PopupHelper::find( int id, const Services& ser, BTDeviceItem* item ) {
- //qWarning("find");
+ //owarn << "find" << oendl;
FactoryMap::Iterator it = m_map.find(id );
if ( it != m_map.end() ) {
- //qWarning("found");
+ //owarn << "found" << oendl;
popupFactory fact = it.data();
return (*fact)(ser, item);
}
return 0l;
}
void PopupHelper::init() {
insert( 4355, newRfcComPopup );
insert( 4354, newDunPopup );
insert( 4353, newRfcComPopup );
insert( 4357, newObexPushPopup );
insert( 4358, newObexPushPopup );
insert( 4374, newPanPopup );
}
diff --git a/noncore/net/opietooth/manager/pppdialog.cpp b/noncore/net/opietooth/manager/pppdialog.cpp
index 78c1501..989bf45 100644
--- a/noncore/net/opietooth/manager/pppdialog.cpp
+++ b/noncore/net/opietooth/manager/pppdialog.cpp
@@ -1,69 +1,69 @@
#include "pppdialog.h"
#include <qpushbutton.h>
#include <qmultilineedit.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <qlabel.h>
#include <opie2/oprocess.h>
using namespace OpieTooth;
using namespace Opie::Core;
PPPDialog::PPPDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device )
: QDialog( parent, name, modal, fl ) {
if ( !name )
setName( "PPPDialog" );
setCaption( tr( "ppp connection " ) ) ;
m_device = device;
layout = new QVBoxLayout( this );
QLabel* info = new QLabel( this );
info->setText( tr("Enter an ppp script name:") );
cmdLine = new QLineEdit( this );
outPut = new QMultiLineEdit( this );
QFont outPut_font( outPut->font() );
outPut_font.setPointSize( 8 );
outPut->setFont( outPut_font );
outPut->setWordWrap( QMultiLineEdit::WidgetWidth );
connectButton = new QPushButton( this );
connectButton->setText( tr( "Connect" ) );
layout->addWidget(info);
layout->addWidget(cmdLine);
layout->addWidget(outPut);
layout->addWidget(connectButton);
connect( connectButton, SIGNAL( clicked() ), this, SLOT( connectToDevice() ) );
}
PPPDialog::~PPPDialog() {
}
void PPPDialog::connectToDevice() {
outPut->clear();
// vom popupmenu beziehen
QString connectScript = "/etc/ppp/peers/" + cmdLine->text();
OProcess* pppDial = new OProcess();
*pppDial << "pppd" << m_device << "call" << connectScript;
connect( pppDial, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int) ),
this, SLOT(fillOutPut(Opie::Core::OProcess*,char*,int) ) );
if (!pppDial->start(OProcess::DontCare, OProcess::AllOutput) ) {
- qWarning("could not start");
+ owarn << "could not start" << oendl;
delete pppDial;
}
}
void PPPDialog::fillOutPut( OProcess* pppDial, char* cha, int len ) {
QCString str(cha, len );
outPut->insertLine( str );
delete pppDial;
}
diff --git a/noncore/net/opietooth/manager/rfcommassigndialogimpl.cpp b/noncore/net/opietooth/manager/rfcommassigndialogimpl.cpp
index fc76301..4469129 100644
--- a/noncore/net/opietooth/manager/rfcommassigndialogimpl.cpp
+++ b/noncore/net/opietooth/manager/rfcommassigndialogimpl.cpp
@@ -1,135 +1,135 @@
#include "rfcommassigndialogimpl.h"
#include "rfcommassigndialogitem.h"
#include "rfcommconfhandler.h"
/* OPIE */
#include <qpe/config.h>
#include <qpe/qpeapplication.h>
/* QT */
#include <qlayout.h>
using namespace OpieTooth;
// TODO: write only the file in bluebase?
// muss rfcommd dann neu gestartet werden
// sollte rfcomm bind all nicht eh default config sein ( polled das? - d.h. sobald nen gerät in der nähe ist bindet es?
RfcommAssignDialog::RfcommAssignDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
: RfcommAssignDialogBase( parent, name, modal, fl )
{
m_range = 5;
m_scrollView = new QScrollView( this );
m_scrollView->setResizePolicy( QScrollView::AutoOneFit );
m_scrollView->setHScrollBarMode( QScrollView::AlwaysOff );
RfcommAssignDialogBaseLayout->addWidget( m_scrollView );
m_box = new QVBox( m_scrollView->viewport() );
m_scrollView->addChild( m_box );
confHandler = new RfCommConfHandler( "/etc/bluetooth/rfcomm.conf" );
loadConfig();
}
RfcommAssignDialog::~RfcommAssignDialog()
{
if ( confHandler )
{
delete confHandler;
}
}
void RfcommAssignDialog::newDevice( const QString & mac )
{
for ( int i = 0 ; i < m_range; i++ )
{
QMap<QString, RfCommConfObject*>::Iterator it;
it = confHandler->foundEntries().find( QString("%1").arg( i ) );
// make sure that rfcommX is not assigned yet
if ( it == confHandler->foundEntries().end() )
{
QDialog dialog( this, "newdevice", true, WStyle_ContextHelp );
RfcommDialogItem *newDev = new RfcommDialogItem( &dialog );
newDev->setIdent( i );
newDev->setMac( mac );
if ( QPEApplication::execDialog( &dialog ) == QDialog::Accepted )
{
RfcommDialogItem *rfcomm = new RfcommDialogItem( m_box );
m_itemList.insert( i , rfcomm );
rfcomm->setIdent( i );
rfcomm->setMac( mac );
rfcomm->setChannel( newDev->channel() );
rfcomm->setComment( newDev->comment() );
- qDebug( "New device set up" );
+ odebug << "New device set up" << oendl;
}
}
}
}
void RfcommAssignDialog::loadConfig()
{
//Config cfg( "bluetoothmanager-rfcommbind" );
for ( int i = 0 ; i < m_range; i++ )
{
// cfg.setGroup( QString("%1").arg( i ) );
RfcommDialogItem *rfcomm = new RfcommDialogItem( m_box );
m_itemList.insert( i , rfcomm );
rfcomm->setIdent( i );
QMap<QString, RfCommConfObject*>::Iterator it;
it = confHandler->foundEntries().find( QString("%1").arg( i ) );
if ( it != confHandler->foundEntries().end() )
{
- qDebug( "Found key in foundEntries() " );
+ odebug << "Found key in foundEntries() " << oendl;
rfcomm->setMac( it.data()->mac() );
rfcomm->setChannel( it.data()->channel() );
rfcomm->setComment( it.data()->comment() );
}
/* Use rfcomm.conf directly for now
* rfcomm->setMac( cfg.readEntry( "mac", "" ) );
* rfcomm->setChannel( cfg.readNumEntry( "channel", 1 ) );
* rfcomm->setComment( cfg.readEntry( "comment", "" ) );
*/
}
}
void RfcommAssignDialog::saveConfig()
{
//Config cfg( "bluetoothmanager-rfcommbind" );
QMap< int, RfcommDialogItem*>::Iterator it;
QMap< QString, RfCommConfObject*> outMap;
for( it = m_itemList.begin(); it != m_itemList.end(); ++it )
{
//cfg.setGroup( QString("%1").arg( it.key() ) );
RfcommDialogItem *rfcomm = it.data();
outMap.insert( QString( "%1").arg( it.key() ), new RfCommConfObject( it.key(), rfcomm->mac(), rfcomm->channel(), rfcomm->comment() ) );
//cfg.writeEntry( "mac", rfcomm->mac() );
//cfg.writeEntry( "channel", rfcomm->channel() );
//cfg.writeEntry( "comment", rfcomm->comment() );
}
confHandler->save( outMap );
}
diff --git a/noncore/net/opietooth/manager/rfcommconfhandler.cpp b/noncore/net/opietooth/manager/rfcommconfhandler.cpp
index 20453e8..2ef95ff 100644
--- a/noncore/net/opietooth/manager/rfcommconfhandler.cpp
+++ b/noncore/net/opietooth/manager/rfcommconfhandler.cpp
@@ -1,114 +1,114 @@
#include <qtextstream.h>
#include "rfcommconfhandler.h"
using namespace OpieTooth;
// move to lib
RfCommConfObject::RfCommConfObject( int number, QString mac, int channel, QString comment ) {
m_number = number;
m_mac = mac;
m_channel = channel;
m_comment = comment;
// m_foundEntries = 0;
}
void RfCommConfObject::setNumber( int number ) {
m_number = number;
}
void RfCommConfObject::setMac( QString mac ) {
m_mac = mac;
}
void RfCommConfObject::setChannel( int channel ) {
m_channel = channel;
}
void RfCommConfObject::setComment( QString comment ) {
m_comment = comment;
}
RfCommConfObject::~RfCommConfObject() {
}
RfCommConfHandler::RfCommConfHandler( const QString & filename ) {
m_filename = filename;
load();
}
RfCommConfHandler::~RfCommConfHandler() {
}
void RfCommConfHandler::save( QMap<QString, RfCommConfObject*> devices ) {
QFile rfCommConf( "/tmp/test" );
QTextStream outStream( &rfCommConf );
if ( rfCommConf.open( IO_WriteOnly ) ) {
QMap<QString, RfCommConfObject*>::Iterator it;
for( it = devices.begin(); it != devices.end(); ++it ) {
outStream << "rfcomm" + QString("%1").arg( it.data()->number() ) + " {\n";
outStream << " device " + it.data()->mac() + ";\n";
outStream << " channel " + QString( "%1" ).arg( it.data()->channel() ) + ";\n";
outStream << " comment \"" + it.data()->comment() + "\";\n";
outStream << "}\n\n";
}
rfCommConf.close();
}
}
QMap<QString, RfCommConfObject*> RfCommConfHandler::foundEntries() {
return m_foundEntries;
}
void RfCommConfHandler::load() {
QFile rfCommConf( m_filename );
if ( rfCommConf.open( IO_ReadOnly ) ) {
QStringList list;
QTextStream inStream( &rfCommConf );
list = QStringList::split( "\n", inStream.read() );
QString number;
QString mac;
QString channel;
QString comment;
for ( QStringList::Iterator line=list.begin(); line != list.end(); line++ ) {
QString tmpLine = ( *line ).stripWhiteSpace();
if ( tmpLine.startsWith("rfcomm") ) {
QString number = tmpLine.mid( 6,1 );
- qDebug( tmpLine );
- qDebug( "TEST " + number );
+ odebug << tmpLine << oendl;
+ odebug << "TEST " + number << oendl;
} else if ( tmpLine.startsWith( "}" ) ) {
m_foundEntries.insert( number, new RfCommConfObject( number.toInt(), mac, channel.toInt(), comment ) );
} else if ( tmpLine.startsWith( "device" ) ) {
mac = tmpLine.mid( 7, 17 );
- qDebug( "mac" + mac );
+ odebug << "mac" + mac << oendl;
} else if ( tmpLine.startsWith( "channel" ) ) {
channel = tmpLine.mid( 8, 1 );
qDebug ( "Channel :" + channel );
} else if ( tmpLine.startsWith( "comment" ) ) {
comment = tmpLine.mid( 9, tmpLine.find( ';' ) - 9 - 1 );
- qDebug( "Comment: " + comment );
+ odebug << "Comment: " + comment << oendl;
}
}
rfCommConf.close();
}
save( m_foundEntries );
- qDebug( QString( "ENTries: %1").arg( m_foundEntries.count() ) );
+ odebug << QString( "ENTries: %1").arg( m_foundEntries.count() ) << oendl;
}
diff --git a/noncore/net/opietooth/manager/rfcpopup.cpp b/noncore/net/opietooth/manager/rfcpopup.cpp
index 04bfe48..01ad616 100644
--- a/noncore/net/opietooth/manager/rfcpopup.cpp
+++ b/noncore/net/opietooth/manager/rfcpopup.cpp
@@ -1,103 +1,103 @@
#include "pppdialog.h"
#include "rfcpopup.h"
#include "rfcommassigndialogimpl.h"
/* OPIE */
#include <qpe/qpeapplication.h>
/* QT */
#include <qtimer.h>
using namespace OpieTooth;
/*
* c'tor init the QAction
*/
RfcCommPopup::RfcCommPopup( OpieTooth::BTDeviceItem* item )
: QPopupMenu()
{
- qWarning("RfcCommPopup c'tor");
+ owarn << "RfcCommPopup c'tor" << oendl;
QAction* a;
m_item = item;
/* connect action */
a = new QAction( ); // so it's get deleted
a->setText("Connect");
a->addTo( this );
connect( a, SIGNAL( activated() ),
this, SLOT( slotConnect() ) );
/* disconnect action */
a = new QAction( );
a->setText("Disconnect");
a->addTo( this );
connect( a, SIGNAL( activated() ) ,
this, SLOT( slotDisconnect() ) );
/* foo action */
a = new QAction( );
a->setText("Bind table");
a->addTo( this );
connect( a, SIGNAL( activated() ),
this, SLOT( slotBind() ) );
/* bar action */
a = new QAction( );
a->setText( "Bar" );
a->addTo( this );
connect( a, SIGNAL( activated() ),
this, SLOT( slotBar() ) );
};
RfcCommPopup::~RfcCommPopup()
{
/* delete m_con;
delete m_dis;
delete m_foo;
delete m_bar; */
}
void RfcCommPopup::slotConnect()
{
- qWarning("connect");
+ owarn << "connect" << oendl;
PPPDialog pppDialog;
QPEApplication::execDialog( &pppDialog );
}
void RfcCommPopup::slotDisconnect()
{
- qWarning("slot disconnected");
+ owarn << "slot disconnected" << oendl;
}
void RfcCommPopup::slotBind()
{
RfcommAssignDialog rfcommAssign ( this, "RfcommAssignDialog", true, WStyle_ContextHelp );
rfcommAssign.newDevice( m_item->mac() );
if ( QPEApplication::execDialog( &rfcommAssign ) == QDialog::Accepted )
{
rfcommAssign.saveConfig();
}
}
void RfcCommPopup::slotBar()
{
- qWarning("slotBar");
+ owarn << "slotBar" << oendl;
};
diff --git a/noncore/net/opietooth/manager/scandialog.cpp b/noncore/net/opietooth/manager/scandialog.cpp
index c8ea3e3..3b005c4 100644
--- a/noncore/net/opietooth/manager/scandialog.cpp
+++ b/noncore/net/opietooth/manager/scandialog.cpp
@@ -62,100 +62,100 @@ namespace OpieTooth {
Layout11->addWidget( ListView1 );
Layout11->addWidget( progress );
Layout11->addWidget( StartStopButton );
localDevice = new Manager( "hci0" );
connect( StartStopButton, SIGNAL( clicked() ), this, SLOT( startSearch() ) );
connect( localDevice, SIGNAL( foundDevices(const QString&,RemoteDevice::ValueList) ),
this, SLOT( fillList(const QString&,RemoteDevice::ValueList) ) ) ;
progressStat = 0;
m_search = false;
}
// hack, make cleaner later
void ScanDialog::progressTimer() {
progressStat++;
if ( progressStat++ < 20 && m_search ) {
QTimer::singleShot( 2000, this, SLOT( progressTimer() ) );
progress->setProgress( progressStat++ );
}
}
void ScanDialog::accept() {
emitToManager();
QDialog::accept();
}
void ScanDialog::startSearch() {
if ( m_search ) {
stopSearch();
return;
}
m_search = true;
progress->setProgress(0);
progressStat = 0;
// empty list before a new scan
ListView1->clear();
progressTimer();
// when finished, it emmite foundDevices()
// checken ob initialisiert , qcop ans applet.
StartStopButton->setText( tr( "Stop scan" ) );
localDevice->searchDevices();
}
void ScanDialog::stopSearch() {
m_search = true;
}
void ScanDialog::fillList(const QString&, RemoteDevice::ValueList deviceList) {
progress->setProgress(0);
progressStat = 0;
QCheckListItem * deviceItem;
RemoteDevice::ValueList::Iterator it;
for( it = deviceList.begin(); it != deviceList.end(); ++it ) {
deviceItem = new QCheckListItem( ListView1, (*it).name(), QCheckListItem::CheckBox );
deviceItem->setText( 1, (*it).mac() );
}
m_search = false;
StartStopButton->setText( tr( "Start scan" ) );
}
/**
* Iterates trough the items, and collects the checked items.
* Then it emits it, so the manager can connect to the signal to fill the listing.
*/
void ScanDialog::emitToManager() {
if (!ListView1) {
return;
}
QValueList<RemoteDevice> deviceList;
QListViewItemIterator it( ListView1 );
for ( ; it.current(); ++it ) {
if ( ( (QCheckListItem*)it.current() )->isOn() ) {
RemoteDevice device( it.current()->text(1), it.current()->text(0) );
deviceList.append( device );
}
}
emit selectedDevices( deviceList );
}
/**
* Cleanup
*/
ScanDialog::~ScanDialog() {
- qWarning("delete scan dialog");
+ owarn << "delete scan dialog" << oendl;
delete localDevice;
}
}
diff --git a/noncore/net/wellenreiter/gui/configwindow.cpp b/noncore/net/wellenreiter/gui/configwindow.cpp
index da39113..bfdb20a 100644
--- a/noncore/net/wellenreiter/gui/configwindow.cpp
+++ b/noncore/net/wellenreiter/gui/configwindow.cpp
@@ -1,480 +1,476 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
**
** This file is part of Wellenreiter II.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
/* LOCAL */
#include "configwindow.h"
#include "mainwindow.h"
/* OPIE */
#include <opie2/onetwork.h>
#ifdef QWS
#include <opie2/oapplication.h>
#include <opie2/oconfig.h>
#include <opie2/odevice.h>
-using namespace Opie;
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+using namespace Opie::Net;
#endif
/* QT */
#include <qapplication.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qfile.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <qmap.h>
#include <qpushbutton.h>
#include <qtabwidget.h>
#include <qtoolbutton.h>
#include <qspinbox.h>
#include <qtextstream.h>
-/* POSIX */
+/* STD */
#include <assert.h>
-using namespace Opie::Core;
-using namespace Opie::Net;
-using namespace Opie::Core;
-using namespace Opie::Net;
-using namespace Opie::Core;
-using namespace Opie::Net;
WellenreiterConfigWindow* WellenreiterConfigWindow::_instance = 0;
WellenreiterConfigWindow::WellenreiterConfigWindow( QWidget * parent, const char * name, WFlags f )
:WellenreiterConfigBase( parent, name, true, f )
{
_devicetype[ "cisco" ] = DEVTYPE_CISCO;
_devicetype[ "wlan-ng" ] = DEVTYPE_WLAN_NG;
_devicetype[ "hostap" ] = DEVTYPE_HOSTAP;
_devicetype[ "orinoco" ] = DEVTYPE_ORINOCO;
_devicetype[ "<manual>" ] = DEVTYPE_MANUAL;
_devicetype[ "<file>" ] = DEVTYPE_FILE;
// gather possible interface names from ONetwork
ONetwork* net = ONetwork::instance();
ONetwork::InterfaceIterator it = net->iterator();
while ( it.current() )
{
if ( it.current()->isWireless() )
interfaceName->insertItem( it.current()->name() );
++it;
}
load();
#ifdef Q_WS_X11 // We're on X11: adding an Ok-Button for the Dialog here
QPushButton* okButton = new QPushButton( "ok", this );
okButton->show();
WellenreiterConfigBaseLayout->addWidget( okButton, 0, 3 ); //FIXME: rename this in configbase.ui
connect( okButton, SIGNAL( clicked() ), this, SLOT( accept() ) );
#endif
WellenreiterConfigWindow::_instance = this;
connect( deviceType, SIGNAL( activated(int) ), this, SLOT( changedDeviceType(int) ) );
connect( newNetworkAction, SIGNAL( activated(int) ), this, SLOT( changedNetworkAction(int) ) );
connect( newClientAction, SIGNAL( activated(int) ), this, SLOT( changedClientAction(int) ) );
connect( newStationAction, SIGNAL( activated(int) ), this, SLOT( changedStationAction(int) ) );
connect( getCaptureFileName, SIGNAL( clicked() ), this, SLOT( getCaptureFileNameClicked() ) );
// make the checkbox 'channelAll' control all other channels
connect( channelAll, SIGNAL( stateChanged(int) ), this, SLOT( channelAllClicked(int) ) );
connect( autodetect, SIGNAL( clicked() ), this, SLOT( performAutodetection() ) );
// hide tab4 (parse) until Wellenreiter 1.2
tab->removePage( tab_4 );
};
void WellenreiterConfigWindow::accept()
{
save();
QDialog::accept();
}
WellenreiterConfigWindow::~WellenreiterConfigWindow()
{
}
void WellenreiterConfigWindow::performAutodetection()
{
//TODO: insert modal splash screen here
// and sleep a second, so that it looks
// like we're actually doing something fancy... ;-)
- qDebug( "WellenreiterConfigWindow::performAutodetection()" );
+ odebug << "WellenreiterConfigWindow::performAutodetection()" << oendl;
// try to guess device type
QFile m( "/proc/modules" );
if ( m.open( IO_ReadOnly ) )
{
int devicetype(0);
QString line;
QTextStream modules( &m );
while( !modules.atEnd() && !devicetype )
{
modules >> line;
if ( line.contains( "cisco" ) ) devicetype = DEVTYPE_CISCO;
else if ( line.contains( "hostap" ) ) devicetype = DEVTYPE_HOSTAP;
else if ( line.contains( "prism" ) ) devicetype = DEVTYPE_WLAN_NG;
else if ( line.contains( "orinoco" ) ) devicetype = DEVTYPE_ORINOCO;
}
if ( devicetype )
{
deviceType->setCurrentItem( devicetype );
_guess = devicetype;
- qDebug( "Wellenreiter: guessed device type to be #%d", devicetype );
+ odebug << "Wellenreiter: guessed device type to be #" << devicetype << "" << oendl;
}
}
}
int WellenreiterConfigWindow::driverType() const
{
QString name = deviceType->currentText();
if ( _devicetype.contains( name ) )
{
return _devicetype[name];
}
else
{
return 0;
}
};
int WellenreiterConfigWindow::hoppingInterval() const
{
return hopInterval->cleanText().toInt();
}
bool WellenreiterConfigWindow::usePrismHeader() const
{
return prismHeader->isChecked();
}
bool WellenreiterConfigWindow::isChannelChecked( int channel ) const
{
switch ( channel )
{
case 1: return channel1->isOn();
case 2: return channel2->isOn();
case 3: return channel3->isOn();
case 4: return channel4->isOn();
case 5: return channel5->isOn();
case 6: return channel6->isOn();
case 7: return channel7->isOn();
case 8: return channel8->isOn();
case 9: return channel9->isOn();
case 10: return channel10->isOn();
case 11: return channel11->isOn();
case 12: return channel12->isOn();
case 13: return channel13->isOn();
case 14: return channel14->isOn();
}
}
void WellenreiterConfigWindow::changedDeviceType(int t)
{
if ( t != DEVTYPE_FILE ) return;
QString name = ( (WellenreiterMainWindow*) qApp->mainWidget() )->getFileName(false);
if ( !name.isEmpty() && QFile::exists( name ) )
{
interfaceName->insertItem( name );
interfaceName->setCurrentItem( interfaceName->count()-1 );
}
else
{
deviceType->setCurrentItem( _guess );
}
}
void WellenreiterConfigWindow::synchronizeActionsAndScripts()
{
if ( newNetworkAction->currentItem() == 4 ) newNetworkScript->show(); else newNetworkScript->hide();
if ( newClientAction->currentItem() == 4 ) newClientScript->show(); else newClientScript->hide();
if ( newStationAction->currentItem() == 4 ) newStationScript->show(); else newStationScript->hide();
//newNetworkScript->setEnabled( newNetworkAction->currentItem() == 4 );
//newClientScript->setEnabled( newClientAction->currentItem() == 4 );
//newStationScript->setEnabled( newStationAction->currentItem() == 4 );
}
void WellenreiterConfigWindow::changedNetworkAction(int t)
{
synchronizeActionsAndScripts();
}
void WellenreiterConfigWindow::changedClientAction(int t)
{
synchronizeActionsAndScripts();
}
void WellenreiterConfigWindow::changedStationAction(int t)
{
synchronizeActionsAndScripts();
}
void WellenreiterConfigWindow::getCaptureFileNameClicked()
{
QString name = ( (WellenreiterMainWindow*) qApp->mainWidget() )->getFileName(true);
- qDebug( "name = %s", (const char*) name );
+ odebug << "name = " << (const char*) name << "" << oendl;
if ( !name.isEmpty() )
{
captureFileName->setText( name );
}
}
void WellenreiterConfigWindow::channelAllClicked(int state)
{
bool b = state;
channel1->setChecked( b );
channel2->setChecked( b );
channel3->setChecked( b );
channel4->setChecked( b );
channel5->setChecked( b );
channel6->setChecked( b );
channel7->setChecked( b );
channel8->setChecked( b );
channel9->setChecked( b );
channel10->setChecked( b );
channel11->setChecked( b );
channel12->setChecked( b );
channel13->setChecked( b );
channel14->setChecked( b );
}
bool WellenreiterConfigWindow::useGPS() const
{
return enableGPS->isChecked();
}
const QString WellenreiterConfigWindow::gpsHost() const
{
return useGPS() ? gpsdHost->currentText() : QString::null;
}
int WellenreiterConfigWindow::gpsPort() const
{
bool ok;
return useGPS() ? gpsdPort->value() : -1;
}
void WellenreiterConfigWindow::performAction( const QString& type,
const QString& essid,
const QString& mac,
bool wep,
int channel,
int signal
/* , const GpsLocation& loc */ )
{
int action;
QString script;
if ( type == "network" )
{
action = newNetworkAction->currentItem();
script = newNetworkScript->text();
}
else if ( type == "managed" || type == "adhoc" )
{
action = newClientAction->currentItem();
script = newClientScript->text();
}
else if ( type == "station" )
{
action = newStationAction->currentItem();
script = newStationScript->text();
}
else
{
- qWarning( "WellenreiterConfigWindow::performAction(): unknown type '%s'", (const char*) type );
+ owarn << "WellenreiterConfigWindow::performAction(): unknown type '" << (const char*) type << "'" << oendl;
return;
}
- qDebug( "for event '%s' I'm going to perform action %d (script='%s')", (const char*) type, action, (const char*) script );
+ odebug << "for event '" << (const char*) type << "' I'm going to perform action " << action << " (script='" << (const char*) script << "')" << oendl;
switch( action )
{
case 0: /* Ignore */ return;
case 1: /* Play Alarm */ ODevice::inst()->playAlarmSound(); return;
case 2: /* Play Click */ ODevice::inst()->playTouchSound(); return;
case 3: /* Blink LED */ break; //FIXME: Implement this
case 4: /* Run Script */
{
/**
*
* Script Substitution Information:
*
* $SSID = SSID
* $MAC = MAC
* $WEP = Wep
* $CHAN = Channel
*
**/
script = script.replace( QRegExp( "$SSID" ), essid );
script = script.replace( QRegExp( "$MAC" ), mac );
script = script.replace( QRegExp( "$WEP" ), wep ? QString( "true" ) : QString( "false" ) );
script = script.replace( QRegExp( "$CHAN" ), QString::number( channel ) );
- qDebug( "going to call script '%s'", (const char*) script );
+ odebug << "going to call script '" << (const char*) script << "'" << oendl;
::system( script );
- qDebug( "script returned." );
+ odebug << "script returned." << oendl;
return;
}
default: assert( false );
}
}
void WellenreiterConfigWindow::load()
{
#ifdef Q_WS_X11
#warning Persistent Configuration not yet implemented for standalone X11 build
performAutodetection();
#else
- qDebug( "loading configuration settings..." );
+ odebug << "loading configuration settings..." << oendl;
/* This is dumb monkey typing stuff... We _need_ to do this automatically! */
OConfig* c = oApp->config();
c->setGroup( "Interface" );
QString interface = c->readEntry( "name", "<none>" );
if ( interface != "<none>" )
{
#if QT_VERSION < 300
interfaceName->insertItem( interface, 0 );
interfaceName->setCurrentItem( 0 );
#else
interfaceName->setCurrentText( interface );
#endif
QString device = c->readEntry( "type", "<select>" );
#if QT_VERSION < 300
for ( int i = 0; i < deviceType->count(); ++i )
{
if ( deviceType->text( i ) == device )
{
deviceType->setCurrentItem( i );
break;
}
}
#else
deviceType->setCurrentText( device );
#endif
}
else
{
performAutodetection();
}
prismHeader->setChecked( c->readBoolEntry( "prism", false ) );
hopChannels->setChecked( c->readBoolEntry( "hop", true ) );
hopInterval->setValue( c->readNumEntry( "interval", 250 ) );
adaptiveHopping->setChecked( c->readBoolEntry( "adaptive", true ) );
c->setGroup( "Capture" );
captureFileName->setText( c->readEntry( "filename", "/tmp/capture" ) );
c->setGroup( "UI" );
lookupVendor->setChecked( c->readBoolEntry( "lookupVendor", true ) );
openTree->setChecked( c->readBoolEntry( "openTree", true ) );
disablePM->setChecked( c->readBoolEntry( "disablePM", true ) );
newNetworkAction->setCurrentItem( c->readNumEntry( "newNetworkAction", 1 ) ); // Default: Play Alarm
newNetworkScript->setText( c->readEntry( "newNetworkScript", "" ) );
newClientAction->setCurrentItem( c->readNumEntry( "newClientAction", 2 ) ); // Default: Play Click
newClientScript->setText( c->readEntry( "newClientScript", "" ) );
newStationAction->setCurrentItem( c->readNumEntry( "newStationAction", 2 ) ); // Default: Play Click
newStationScript->setText( c->readEntry( "newStationScript", "" ) );
synchronizeActionsAndScripts(); // needed for showing/hiding the script QLineEdit on demand
c->setGroup( "GPS" );
enableGPS->setChecked( c->readBoolEntry( "use", false ) );
#if QT_VERSION < 300
gpsdHost->insertItem( c->readEntry( "host", "localhost" ), 0 );
gpsdHost->setCurrentItem( 0 );
#else
gpsdHost->setCurrentText( c->readEntry( "host", "localhost" ) );
#endif
gpsdPort->setValue( c->readNumEntry( "port", 2947 ) );
startGPS->setChecked( c->readBoolEntry( "start", false ) );
commandGPS->setText( c->readEntry( "command", "gpsd -p /dev/ttyS3 -s 57600" ) );
#endif
}
void WellenreiterConfigWindow::save()
{
#ifdef Q_WS_X11
#warning Persistent Configuration not yet implemented for standalone X11 build
#else
- qDebug( "saving configuration settings..." );
+ odebug << "saving configuration settings..." << oendl;
/* This is dumb monkey typing stuff... We _need_ to do this automatically! */
OConfig* c = oApp->config();
c->setGroup( "Interface" );
c->writeEntry( "name", interfaceName->currentText() );
c->writeEntry( "type", deviceType->currentText() );
c->writeEntry( "prism", prismHeader->isChecked() );
c->writeEntry( "hop", hopChannels->isChecked() );
c->writeEntry( "interval", hopInterval->value() );
c->writeEntry( "adaptive", adaptiveHopping->isChecked() );
c->setGroup( "Capture" );
c->writeEntry( "filename", captureFileName->text() );
c->setGroup( "UI" );
c->writeEntry( "lookupVendor", lookupVendor->isChecked() );
c->writeEntry( "openTree", openTree->isChecked() );
c->writeEntry( "disablePM", disablePM->isChecked() );
c->writeEntry( "newNetworkAction", newNetworkAction->currentItem() );
c->writeEntry( "newNetworkScript", newNetworkScript->text() );
c->writeEntry( "newClientAction", newClientAction->currentItem() );
c->writeEntry( "newClientScript", newClientScript->text() );
c->writeEntry( "newStationAction", newStationAction->currentItem() );
c->writeEntry( "newStationScript", newStationScript->text() );
c->setGroup( "GPS" );
c->writeEntry( "use", enableGPS->isChecked() );
c->writeEntry( "host", gpsdHost->currentText() );
c->writeEntry( "port", gpsdPort->value() );
c->writeEntry( "start", startGPS->isChecked() );
c->writeEntry( "command", commandGPS->text() );
c->write();
#endif
}
diff --git a/noncore/net/wellenreiter/gui/gps.cpp b/noncore/net/wellenreiter/gui/gps.cpp
index a47b4ec..bd91e35 100644
--- a/noncore/net/wellenreiter/gui/gps.cpp
+++ b/noncore/net/wellenreiter/gui/gps.cpp
@@ -1,127 +1,131 @@
/**********************************************************************
** Copyright (C) 2003 Michael 'Mickey' Lauer. All rights reserved.
**
** This file is part of Wellenreiter II.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "gps.h"
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
/* QT */
#include <qtextstream.h>
/* STD */
#include <stdlib.h>
#include <unistd.h>
GPS::GPS( QObject* parent, const char * name )
:QObject( parent, name )
{
- qDebug( "GPS::GPS()" );
+ odebug << "GPS::GPS()" << oendl;
_socket = new QSocket( this, "gpsd commsock" );
}
GPS::~GPS()
{
- qDebug( "GPS::~GPS()" );
+ odebug << "GPS::~GPS()" << oendl;
}
bool GPS::open( const QString& host, int port )
{
_socket->connectToHost( host, port );
}
GpsLocation GPS::position() const
{
char buf[256];
double lat = -111.0;
double lon = -111.0;
int result = _socket->writeBlock( "p\r\n", 3 );
_socket->flush();
if ( result )
{
int numAvail = _socket->bytesAvailable();
- qDebug( "GPS write succeeded, %d bytes available for reading...", numAvail );
+ odebug << "GPS write succeeded, " << numAvail << " bytes available for reading..." << oendl;
if ( numAvail )
{
int numRead = _socket->readBlock( &buf[0], sizeof buf );
int numScan = ::sscanf( &buf[0], "GPSD,P=%lg %lg", &lat, &lon);
if ( numRead < 7 || numScan != 2 )
{
- qDebug( "GPS read %d bytes succeeded, invalid response: '%s'", numRead, &buf[0] );
+ odebug << "GPS read " << numRead << " bytes succeeded, invalid response: '" << &buf[0] << "'" << oendl;
return GpsLocation( -111, -111 );
}
else
{
return GpsLocation( lat, lon );
}
}
}
return GpsLocation( -111, -111 );
}
QString GpsLocation::dmsPosition() const
{
if ( _latitude == -111 || _longitude == -111 )
return "N/A";
if ( _latitude == 0.0 && _longitude == 0.0 )
return "NULL";
/* compute latitude */
QString dms = "N";
if ( _latitude >= 0 ) dms.append( "+" );
int trunc = int( _latitude );
float rest = _latitude - trunc;
float minf = rest * 60;
int minutes = int( minf );
rest = minf - minutes;
int seconds = int( rest * 60 );
dms.append( QString::number( trunc ) );
dms.append( "° " );
dms.append( QString::number( ::abs( minutes ) ) );
dms.append( "' " );
dms.append( QString::number( ::abs( seconds ) ) );
dms.append( "'' " );
/* compute longitude */
dms.append( " | W" );
if ( _longitude > 0 ) dms.append( "+" );
trunc = int( _longitude );
rest = _longitude - trunc;
minf = rest * 60;
minutes = int( minf );
rest = minf - minutes;
seconds = int( rest * 60 );
dms.append( QString::number( trunc ) );
dms.append( "° " );
dms.append( QString::number( ::abs( minutes ) ) );
dms.append( "' " );
dms.append( QString::number( ::abs( seconds ) ) );
dms.append( "'' " );
return dms;
}
diff --git a/noncore/net/wellenreiter/gui/logwindow.cpp b/noncore/net/wellenreiter/gui/logwindow.cpp
index 1c72cf4..714a9a9 100644
--- a/noncore/net/wellenreiter/gui/logwindow.cpp
+++ b/noncore/net/wellenreiter/gui/logwindow.cpp
@@ -1,54 +1,60 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
**
** This file is part of Wellenreiter II.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "logwindow.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qmultilineedit.h>
#include <qdatetime.h>
MLogWindow* MLogWindow::_instance;
MLogWindow::MLogWindow( QWidget * parent, const char * name, WFlags f )
:QVBox( parent, name, f )
{
ledit = new QMultiLineEdit( this );
ledit->setReadOnly( true );
MLogWindow::_instance = this;
}
void MLogWindow::log( QString text )
{
QTime time = QTime::currentTime();
QString line;
line.sprintf( "[%s] %s\n", (const char*) time.toString(), (const char*) text );
int col;
int row;
ledit->getCursorPosition( &col, &row );
ledit->insertAt( line, col, row );
- qDebug( line );
+ odebug << line << oendl;
}
void MLogWindow::clear()
{
ledit->clear();
}
const QString MLogWindow::getLog() const
{
return ledit->text();
}
diff --git a/noncore/net/wellenreiter/gui/main.cpp b/noncore/net/wellenreiter/gui/main.cpp
index 6bbc39b..62db967 100644
--- a/noncore/net/wellenreiter/gui/main.cpp
+++ b/noncore/net/wellenreiter/gui/main.cpp
@@ -1,113 +1,116 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
**
** This file is part of Wellenreiter II.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "mainwindow.h"
+
#ifdef QWS
+#include <opie2/odebug.h>
#include <opie2/oapplication.h>
#include <opie2/oprocess.h>
#else
#include <qapplication.h>
#endif
+/* QT */
#include <qmessagebox.h>
#include <qstringlist.h>
+/* STD */
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
using namespace Opie::Core;
-using namespace Opie::Core;
-using namespace Opie::Core;
+
int main( int argc, char **argv )
{
#ifdef QWS
OApplication a( argc, argv, "Wellenreiter II" );
#else
QApplication a( argc, argv );
#endif
WellenreiterMainWindow* w = new WellenreiterMainWindow();
#ifdef QWS
a.showMainWidget( w );
#else
a.setMainWidget( w );
w->setCaption( "Wellenreiter II" );
w->show();
#endif
a.processEvents(); // show the window before doing the safety checks
int result = -1;
static int killed = false;
bool check = true;
for ( int i = 1; i < argc; ++i )
{
- qDebug( "Wellenreiter::main() parsing argument %d = '%s'", i, argv[i] );
+ odebug << "Wellenreiter::main() parsing argument " << i << " = '" << argv[i] << "'" << oendl;
if ( !strcmp( "-nocheck", argv[i] ) )
{
- qDebug( "-nocheck found" );
+ odebug << "-nocheck found" << oendl;
check = false;
break;
}
}
if ( check )
{
// root check
if ( getuid() )
{
- qWarning( QObject::tr( "Wellenreiter: trying to run as non-root!" ) );
+ owarn << QObject::tr( "Wellenreiter: trying to run as non-root!" ) << oendl;
result = QMessageBox::warning( w, " - Wellenreiter II - (non-root)", QObject::tr( "You have started Wellenreiter II\n"
"as non-root. You will have\nonly limited functionality.\nProceed anyway?" ),
QMessageBox::Yes, QMessageBox::No );
if ( result == QMessageBox::No ) return -1;
}
int dhcpid = OProcess::processPID( "dhcpc" );
if ( dhcpid )
{
result = QMessageBox::warning( w, " - Wellenreiter II - (dhcp)", QObject::tr( "You have a dhcp client running.\n"
"(PID = %1)\nThis can severly limit scanning!\nShould I kill it for you?" ).arg( dhcpid ),
QMessageBox::Yes, QMessageBox::No );
if ( result == QMessageBox::Yes )
{
if ( -1 == ::kill( dhcpid, SIGTERM ) )
- qWarning( "Wellenreiter: can't kill process #%d (%s)", result, strerror( errno ) );
+ owarn << "Wellenreiter: can't kill process #" << result << " (" << strerror( errno ) << ")" << oendl;
else
killed = true;
}
}
}
a.exec();
if ( check )
{
if ( killed )
{
result = QMessageBox::warning( w, " - Wellenreiter II - (dhcp)", QObject::tr( "Restart your dhcp client?" ), QMessageBox::Yes, QMessageBox::No );
if ( result == QMessageBox::Yes )
{
::system( QString().sprintf( "dhclient &; udhcpcd &; dhcpcd &" ) );
}
}
delete w;
}
return 0;
}
diff --git a/noncore/net/wellenreiter/gui/mainwindow.cpp b/noncore/net/wellenreiter/gui/mainwindow.cpp
index 7add6cd..a4b8839 100644
--- a/noncore/net/wellenreiter/gui/mainwindow.cpp
+++ b/noncore/net/wellenreiter/gui/mainwindow.cpp
@@ -1,541 +1,542 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
**
** This file is part of Wellenreiter II.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "configwindow.h"
#include "gps.h"
#include "logwindow.h"
#include "packetview.h"
#include "mainwindow.h"
#include "wellenreiter.h"
#include "scanlist.h"
+/* OPIE */
+#ifdef QWS
+#include <qpe/resource.h>
+#include <opie2/odebug.h>
+#include <opie2/ofiledialog.h>
+#else
+#include "resource.h"
+#include <qapplication.h>
+#include <qfiledialog.h>
+#endif
+using namespace Opie::Core;
+using namespace Opie::Net;
+using namespace Opie::Ui;
+
+/* QT */
#include <qcombobox.h>
#include <qdatastream.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qiconset.h>
#include <qmenubar.h>
#include <qmessagebox.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qstatusbar.h>
#include <qspinbox.h>
#include <qtextstream.h>
#include <qtoolbutton.h>
#include <qwhatsthis.h>
-#ifdef QWS
-#include <qpe/resource.h>
-#include <opie2/ofiledialog.h>
-using namespace Opie;
-#else
-#include "resource.h"
-#include <qapplication.h>
-#include <qfiledialog.h>
-#endif
-
+/* STD */
#include <unistd.h>
-using namespace Opie::Ui;
-using namespace Opie::Net;
-using namespace Opie::Ui;
-using namespace Opie::Net;
-using namespace Opie::Net;
WellenreiterMainWindow::WellenreiterMainWindow( QWidget * parent, const char * name, WFlags f )
:QMainWindow( parent, name, f )
{
cw = new WellenreiterConfigWindow( this );
mw = new Wellenreiter( this );
mw->setConfigWindow( cw );
setCentralWidget( mw );
// setup application icon
setIcon( Resource::loadPixmap( "wellenreiter/appicon-trans" ) );
#ifndef QWS
setIconText( "Wellenreiter/X11" );
#endif
// setup tool buttons
startButton = new QToolButton( 0 );
QWhatsThis::add( startButton, tr( "Click here to start scanning." ) );
#ifdef QWS
startButton->setAutoRaise( true );
#endif
startButton->setIconSet( Resource::loadIconSet( "wellenreiter/SearchIcon" ) );
startButton->setEnabled( false );
connect( startButton, SIGNAL( clicked() ), mw, SLOT( startClicked() ) );
stopButton = new QToolButton( 0 );
QWhatsThis::add( stopButton, tr( "Click here to stop scanning." ) );
#ifdef QWS
stopButton->setAutoRaise( true );
#endif
stopButton->setIconSet( Resource::loadIconSet( "wellenreiter/CancelIcon" ) );
stopButton->setEnabled( false );
connect( stopButton, SIGNAL( clicked() ), mw, SLOT( stopClicked() ) );
QToolButton* d = new QToolButton( 0 );
QWhatsThis::add( d, tr( "Click here to open the configure dialog." ) ),
#ifdef QWS
d->setAutoRaise( true );
#endif
d->setIconSet( Resource::loadIconSet( "wellenreiter/SettingsIcon" ) );
connect( d, SIGNAL( clicked() ), this, SLOT( showConfigure() ) );
uploadButton = new QToolButton( 0 );
QWhatsThis::add( uploadButton, tr( "Click here to upload a capture session." ) );
#ifdef QWS
uploadButton->setAutoRaise( true );
#endif
uploadButton->setIconSet( Resource::loadIconSet( "up" ) );
uploadButton->setEnabled( false );
//uploadButton->setEnabled( true ); // DEBUGGING
connect( uploadButton, SIGNAL( clicked() ), this, SLOT( uploadSession() ) );
// setup menu bar
int id;
QMenuBar* mb = menuBar();
QPopupMenu* fileSave = new QPopupMenu( mb );
fileSave->insertItem( tr( "&Session..." ), this, SLOT( fileSaveSession() ) );
fileSave->insertItem( tr( "&Text Log..." ), this, SLOT( fileSaveLog() ) );
fileSave->insertItem( tr( "&Hex Log..." ), this, SLOT( fileSaveHex() ) );
QPopupMenu* fileLoad = new QPopupMenu( mb );
fileLoad->insertItem( tr( "&Session..." ), this, SLOT( fileLoadSession() ) );
//fileLoad->insertItem( "&Log", this, SLOT( fileLoadLog() ) );
QPopupMenu* file = new QPopupMenu( mb );
file->insertItem( tr( "&New" ), this, SLOT( fileNew() ) );
id = file->insertItem( tr( "&Load" ), fileLoad );
file->insertItem( tr( "&Save" ), fileSave );
file->insertSeparator();
uploadID = file->insertItem( tr( "&Upload Session" ), this, SLOT( uploadSession() ) );
file->insertSeparator();
file->insertItem( tr( "&Exit" ), qApp, SLOT( quit() ) );
QPopupMenu* sniffer = new QPopupMenu( mb );
sniffer->insertItem( tr( "&Configure..." ), this, SLOT( showConfigure() ) );
sniffer->insertSeparator();
startID = sniffer->insertItem( tr( "&Start" ), mw, SLOT( startClicked() ) );
sniffer->setItemEnabled( startID, false );
stopID = sniffer->insertItem( tr( "Sto&p" ), mw, SLOT( stopClicked() ) );
sniffer->setItemEnabled( stopID, false );
QPopupMenu* view = new QPopupMenu( mb );
view->insertItem( tr( "&Expand All" ), this, SLOT( viewExpandAll() ) );
view->insertItem( tr( "&Collapse All" ), this, SLOT( viewCollapseAll() ) );
QPopupMenu* demo = new QPopupMenu( mb );
demo->insertItem( tr( "&Add something" ), this, SLOT( demoAddStations() ) );
//demo->insertItem( tr( "&Read from GPSd" ), this, SLOT( demoReadFromGps() ) );
id = mb->insertItem( tr( "&File" ), file );
id = mb->insertItem( tr( "&View" ), view );
//mb->setItemEnabled( id, false );
id = mb->insertItem( tr( "&Sniffer" ), sniffer );
id = mb->insertItem( tr( "&Demo" ), demo );
mb->setItemEnabled( id, true );
mb->setItemEnabled( uploadID, false );
#ifdef QWS
mb->insertItem( startButton );
mb->insertItem( stopButton );
mb->insertItem( uploadButton );
mb->insertItem( d );
#else // Qt3 changed the insertion order. It's now totally random :(
mb->insertItem( d );
mb->insertItem( uploadButton );
mb->insertItem( stopButton );
mb->insertItem( startButton );
#endif
updateToolButtonState();
// setup status bar (for now only on X11)
#ifndef QWS
statusBar()->message( tr( "Ready." ) );
#endif
connect( mw, SIGNAL( startedSniffing() ), this, SLOT( changedSniffingState() ) );
connect( mw, SIGNAL( stoppedSniffing() ), this, SLOT( changedSniffingState() ) );
};
void WellenreiterMainWindow::showConfigure()
{
- qDebug( "show configure..." );
+ odebug << "show configure..." << oendl;
cw->setCaption( tr( "Configure" ) );
int result = QPEApplication::execDialog( cw );
if ( result ) updateToolButtonState();
}
void WellenreiterMainWindow::updateToolButtonState()
{
const QString& interface = cw->interfaceName->currentText();
const int cardtype = cw->driverType();
if ( ( interface != "<select>" ) && ( cardtype != 0 ) )
{
startButton->setEnabled( true );
menuBar()->setItemEnabled( startID, true );
}
else
{
startButton->setEnabled( false );
menuBar()->setItemEnabled( startID, false );
}
}
void WellenreiterMainWindow::changedSniffingState()
{
startButton->setEnabled( !mw->sniffing );
menuBar()->setItemEnabled( startID, !mw->sniffing );
stopButton->setEnabled( mw->sniffing );
menuBar()->setItemEnabled( stopID, mw->sniffing );
if ( !mw->sniffing )
{
menuBar()->setItemEnabled( uploadID, true );
uploadButton->setEnabled( true );
}
}
WellenreiterMainWindow::~WellenreiterMainWindow()
{
- qDebug( "Wellenreiter: bye." );
+ odebug << "Wellenreiter: bye." << oendl;
};
void WellenreiterMainWindow::demoAddStations()
{
//mw = 0; // test SIGSEGV handling
mw->netView()->addNewItem( "managed", "Vanille", OMacAddress::fromString("00:00:20:EF:A6:43"), true, 6, 80, GpsLocation( 39.8794, -94.0936) );
mw->netView()->addNewItem( "managed", "Vanille", OMacAddress::fromString("00:30:6D:EF:A6:23"), true, 11, 10, GpsLocation( 0.0, 0.0 ) );
mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:03:F8:E7:16:22"), false, 3, 10, GpsLocation( 5.5, 2.3 ) );
mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:04:01:E7:56:62"), false, 3, 15, GpsLocation( 2.3, 5.5 ) );
mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:05:8E:E7:56:E2"), false, 3, 20, GpsLocation( -10.0, -20.5 ) );
}
void WellenreiterMainWindow::demoReadFromGps()
{
WellenreiterConfigWindow* configwindow = WellenreiterConfigWindow::instance();
GPS* gps = new GPS( this );
- qDebug( "Wellenreiter::demoReadFromGps(): url=gps://%s:%d/", (const char*) configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() );
+ odebug << "Wellenreiter::demoReadFromGps(): url=gps://" << (const char*) configwindow->gpsdHost->currentText() << ":" << configwindow->gpsdPort->value() << "/" << oendl;
gps->open( configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() );
GpsLocation loc = gps->position();
QMessageBox::information( this, "Wellenreiter/Opie", tr( "GPS said:\n%1" ).arg( loc.dmsPosition() ) );
delete gps;
}
QString WellenreiterMainWindow::getFileName( bool save )
{
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;
if ( save )
{
#ifdef QWS
str = OFileDialog::getSaveFileName( 2, "/", QString::null, map );
#else
str = QFileDialog::getSaveFileName();
#endif
if ( str.isEmpty() /*|| QFileInfo(str).isDir()*/ )
return "";
}
else
{
#ifdef QWS
str = OFileDialog::getOpenFileName( 2, "/", QString::null, map );
#else
str = QFileDialog::getOpenFileName();
#endif
if ( str.isEmpty() || !QFile(str).exists() || QFileInfo(str).isDir() )
return "";
}
return str;
}
void WellenreiterMainWindow::fileSaveLog()
{
QString fname = getFileName( true );
if ( !fname.isEmpty() )
{
QFile f( fname );
if ( f.open(IO_WriteOnly) )
{
QTextStream t( &f );
t << mw->logWindow()->getLog();
f.close();
- qDebug( "Saved log to file '%s'", (const char*) fname );
+ odebug << "Saved log to file '" << (const char*) fname << "'" << oendl;
}
else
{
- qDebug( "Problem saving log to file '%s'", (const char*) fname );
+ odebug << "Problem saving log to file '" << (const char*) fname << "'" << oendl;
}
}
}
void WellenreiterMainWindow::fileSaveSession()
{
QString fname = getFileName( true );
if ( !fname.isEmpty() )
{
QFile f( fname );
if ( f.open(IO_WriteOnly) )
{
QDataStream t( &f );
t << *mw->netView();
f.close();
- qDebug( "Saved session to file '%s'", (const char*) fname );
+ odebug << "Saved session to file '" << (const char*) fname << "'" << oendl;
}
else
{
- qDebug( "Problem saving session to file '%s'", (const char*) fname );
+ odebug << "Problem saving session to file '" << (const char*) fname << "'" << oendl;
}
}
}
void WellenreiterMainWindow::fileSaveHex()
{
#warning DOES NOT WORK AT THE MOMENT
/*
QString fname = getFileName( true );
if ( !fname.isEmpty() )
{
QFile f( fname );
if ( f.open(IO_WriteOnly) )
{
QTextStream t( &f );
t << mw->hexWindow()->getLog();
f.close();
- qDebug( "Saved hex log to file '%s'", (const char*) fname );
+ odebug << "Saved hex log to file '" << (const char*) fname << "'" << oendl;
}
else
{
- qDebug( "Problem saving hex log to file '%s'", (const char*) fname );
+ odebug << "Problem saving hex log to file '" << (const char*) fname << "'" << oendl;
}
}
*/
}
void WellenreiterMainWindow::fileLoadSession()
{
QString fname = getFileName( false );
if ( !fname.isEmpty() )
{
QFile f( fname );
if ( f.open(IO_ReadOnly) )
{
QDataStream t( &f );
t >> *mw->netView();
f.close();
- qDebug( "Loaded session from file '%s'", (const char*) fname );
+ odebug << "Loaded session from file '" << (const char*) fname << "'" << oendl;
}
else
{
- qDebug( "Problem loading session from file '%s'", (const char*) fname );
+ odebug << "Problem loading session from file '" << (const char*) fname << "'" << oendl;
}
}
}
void WellenreiterMainWindow::fileNew()
{
mw->netView()->clear();
mw->logWindow()->clear();
mw->hexWindow()->clear();
}
void WellenreiterMainWindow::closeEvent( QCloseEvent* e )
{
if ( mw->isDaemonRunning() )
{
QMessageBox::warning( this, "Wellenreiter/Opie",
tr( "Sniffing in progress!\nPlease stop sniffing before closing." ) );
e->ignore();
}
else
{
QMainWindow::closeEvent( e );
}
}
static const char* CAP_hostname = "www.vanille.de";
#include <netdb.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
void WellenreiterMainWindow::uploadSession()
{
QLineEdit* from;
QLineEdit* location;
QLineEdit* comments;
QPushButton* accept;
QPushButton* reject;
QDialog* d = new QDialog( 0, "session upload", true );
d->setCaption( tr( "Upload Session" ) );
QGridLayout* g = new QGridLayout( d, 4, 2, 3 );
g->addWidget( new QLabel( tr( "From: " ), d ), 0, 0 );
g->addWidget( from = new QLineEdit( d ), 0, 1 );
g->addWidget( new QLabel( tr( "Location: " ), d ), 1, 0 );
g->addWidget( location = new QLineEdit( d ), 1, 1 );
g->addWidget( new QLabel( tr( "Comments: " ), d ), 2, 0 );
g->addWidget( comments = new QLineEdit( d ), 2, 1 );
g->addWidget( accept = new QPushButton( tr( "&Ok" ), d ), 3, 0 );
g->addWidget( reject = new QPushButton( tr( "&Cancel" ), d ), 3, 1 );
accept->setDefault( true );
accept->setAutoDefault( true );
from->setText( "WL II User" );
location->setText( "WL II Location" );
comments->setText( "No Comments." );
connect( accept, SIGNAL( clicked() ), d, SLOT( accept() ) );
connect( reject, SIGNAL( clicked() ), d, SLOT( reject() ) );
int result = d->exec();
if ( !result )
{
- qDebug( "Session upload cancelled :(" );
+ odebug << "Session upload cancelled :(" << oendl;
return;
}
- qDebug( "Starting upload..." );
+ odebug << "Starting upload..." << oendl;
struct sockaddr_in raddr;
struct hostent *rhost_info;
int sock = -1;
bool ok = false;
rhost_info = (struct hostent *) ::gethostbyname( CAP_hostname );
if ( rhost_info )
{
if ( !QFile::exists( mw->captureFileName() ) )
{
QMessageBox::warning( 0, tr( "Error" ), tr( "<p>Logfile '%1' doesn't exist</p>").arg( mw->captureFileName() ) );
return;
}
QFile f( mw->captureFileName() );
if ( !f.open( IO_ReadOnly ) )
{
QMessageBox::warning( 0, tr( "Error" ), tr( "<p>Can't open Logfile '%1'</p>").arg( mw->captureFileName() ) );
return;
}
int content_length = f.size();
::memset( &raddr, 0, sizeof (struct sockaddr_in) );
::memcpy( &raddr. sin_addr, rhost_info-> h_addr, rhost_info-> h_length );
raddr.sin_family = rhost_info-> h_addrtype;
raddr.sin_port = htons ( 80 );
sock = ::socket( AF_INET, SOCK_STREAM, 0 );
if ( sock >= 0 )
{
if ( ::connect ( sock, (struct sockaddr *) & raddr, sizeof (struct sockaddr)) >= 0 )
{
QString header;
QString content;
QString preambel;
header = ""
"POST /projects/capturedump.spy HTTP/1.1\r\n"
"Host: www.vanille.de\r\n"
"User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.5) Gecko/20031010 Galeon/1.3.10\r\n"
"Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1\r\n"
"Accept-Language: en\r\n"
"Accept-Encoding: gzip, deflate, compress;q=0.9\r\n"
"Accept-Charset: us-ascii,utf-8;q=0.7,*;q=0.7\r\n"
"Keep-Alive: 300\r\n"
"Connection: keep-alive\r\n"
"Referer: http://www.vanille.de/projects/capturedump.spy\r\n"
"Content-Type: multipart/form-data; boundary=---------------------------97267758015830030481215568065\r\n"
"Content-Length: %1\r\n"
"\r\n";
content = ""
"-----------------------------97267758015830030481215568065\r\n"
"Content-Disposition: form-data; name=\"Name\"\r\n"
"\r\n"
"%1\r\n"
"-----------------------------97267758015830030481215568065\r\n"
"Content-Disposition: form-data; name=\"Location\"\r\n"
"\r\n"
"%2\r\n"
"-----------------------------97267758015830030481215568065\r\n"
"Content-Disposition: form-data; name=\"Comments\"\r\n"
"\r\n"
"%3\r\n"
"-----------------------------97267758015830030481215568065\r\n"
"Content-Disposition: form-data; name=\"upfile\"; filename=\"%4\"\r\n"
"Content-Type: application/octet-stream\r\n"
"\r\n";
preambel = ""
"\r\n-----------------------------97267758015830030481215568065--\r\n";
content = content.arg( from->text().isEmpty() ? QString( "Anonymous Wellenreiter II User" ) : from->text() );
content = content.arg( location->text().isEmpty() ? QString( "Anonymous Wellenreiter II Location" ) : location->text() );
content = content.arg( comments->text().isEmpty() ? QString( "Anonymous Wellenreiter II Comments" ) : comments->text() );
content = content.arg( mw->captureFileName() );
header = header.arg( QString::number( content.length() + f.size() + preambel.length() ) );
// write header
const char* ascii = header.latin1();
uint ascii_len = ::strlen( ascii );
::write ( sock, ascii, ascii_len );
// write fixed content
ascii = content.latin1();
ascii_len = ::strlen( ascii );
::write ( sock, ascii, ascii_len );
diff --git a/noncore/net/wellenreiter/gui/packetview.cpp b/noncore/net/wellenreiter/gui/packetview.cpp
index 3d3aa18..4df01da 100644
--- a/noncore/net/wellenreiter/gui/packetview.cpp
+++ b/noncore/net/wellenreiter/gui/packetview.cpp
@@ -1,121 +1,121 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
**
** This file is part of Wellenreiter II.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "packetview.h"
/* OPIE */
#include <opie2/opcap.h>
#include <opie2/odebug.h>
#include <opie2/olistview.h>
/* QT */
#include <qfont.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlist.h>
#include <qlistview.h>
#include <qobjectlist.h>
#include <qspinbox.h>
#include <qtextview.h>
using namespace Opie::Net;
using namespace Opie::Core;
using namespace Opie::Ui;
PacketView::PacketView( QWidget * parent, const char * name, WFlags f )
:QFrame( parent, name, f )
{
_number = new QSpinBox( this );
_number->setPrefix( "Packet # " );
_label = new QLabel( this );
_label->setText( "eth0 2004/03/08 - 00:00:21" );
_list = new OListView( this );
_list->addColumn( "#" );
_list->addColumn( "Packet Type" );
_list->setColumnAlignment( 0, Qt::AlignCenter );
_list->setColumnAlignment( 1, Qt::AlignLeft );
_list->setAllColumnsShowFocus( true );
_list->setFont( QFont( "Fixed", 8 ) );
_hex = new QTextView( this );
_hex->setFont( QFont( "Fixed", 8 ) );
QVBoxLayout* vb = new QVBoxLayout( this, 2, 2 );
QHBoxLayout* hb = new QHBoxLayout( vb, 2 );
hb->addWidget( _label );
hb->addWidget( _number );
vb->addWidget( _list );
vb->addWidget( _hex );
_packets.setAutoDelete( true );
connect( _number, SIGNAL( valueChanged( int ) ), this, SLOT( showPacket( int ) ) );
}
void PacketView::add( const OPacket* p )
{
_packets.append( p );
// Add Circular Buffer and check for number of elements here
}
void PacketView::showPacket( int number )
{
_list->clear();
_hex->setText("");
const OPacket* p = _packets.at( number );
if ( p )
{
_doSubPackets( const_cast<QObjectList*>( p->children() ), 0 );
_doHexPacket( p );
}
else
{
- qDebug( "D'oh! No packet!" );
+ odebug << "D'oh! No packet!" << oendl;
}
}
void PacketView::_doSubPackets( QObjectList* l, int counter )
{
if (!l) return;
QObject* o = l->first();
while ( o )
{
new OListViewItem( _list, QString::number( counter++ ), o->name() );
_doSubPackets( const_cast<QObjectList*>( o->children() ), counter );
o = l->next();
}
}
void PacketView::_doHexPacket( const OPacket* p )
{
_hex->setText( p->dump( 16 ) );
}
const QString PacketView::getLog() const
{
}
void PacketView::clear()
{
_packets.clear();
_number->setMinValue( 0 );
_number->setMaxValue( 0 );
_label->setText( "---" );
_list->clear();
_hex->setText( " <i>-- no Packet available --</i> " );
}
diff --git a/noncore/net/wellenreiter/gui/resource.cpp b/noncore/net/wellenreiter/gui/resource.cpp
index d98ef0b..cb17f51 100644
--- a/noncore/net/wellenreiter/gui/resource.cpp
+++ b/noncore/net/wellenreiter/gui/resource.cpp
@@ -1,49 +1,49 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
**
** This file is part of Wellenreiter II.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "resource.h"
#define PIXMAPPATH "/usr/local/share"
#include <qiconset.h>
namespace Resource
{
QPixmap loadPixmap( const QString& pix )
{
QString filename;
filename.sprintf( "%s/%s.png", (const char*) PIXMAPPATH, (const char*) pix );
QPixmap pixmap( filename );
if ( pixmap.isNull() )
{
- qDebug( "Wellenreiter::Resource: can't find pixmap " + filename );
+ odebug << "Wellenreiter::Resource: can't find pixmap " + filename << oendl;
}
return pixmap;
};
QIconSet loadIconSet( const QString& pix )
{
QString filename;
filename.sprintf( "%s/%s.png", (const char*) PIXMAPPATH, (const char*) pix );
QPixmap pixmap( filename );
if ( pixmap.isNull() )
{
- qDebug( "Wellenreiter::Resource: can't find pixmap " + filename );
+ odebug << "Wellenreiter::Resource: can't find pixmap " + filename << oendl;
}
return QIconSet( pixmap );
};
};
diff --git a/noncore/net/wellenreiter/gui/scanlist.cpp b/noncore/net/wellenreiter/gui/scanlist.cpp
index 3b7120a..a2be782 100644
--- a/noncore/net/wellenreiter/gui/scanlist.cpp
+++ b/noncore/net/wellenreiter/gui/scanlist.cpp
@@ -1,568 +1,567 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
**
** This file is part of Wellenreiter II.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "scanlist.h"
#include "configwindow.h"
#include "logwindow.h"
-#include <assert.h>
-#include <qcursor.h>
-#include <qdatetime.h>
-#include <qpopupmenu.h>
-#include <qcheckbox.h>
-
+/* OPIE */
#ifdef QWS
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
-#endif
-
-#ifdef QWS
#include <qpe/resource.h>
#else
#include "resource.h"
#endif
+using namespace Opie::Core;
+using namespace Opie::Ui;
+using namespace Opie::Net;
+
+/* QT */
+#include <qcursor.h>
+#include <qdatetime.h>
+#include <qpopupmenu.h>
+#include <qcheckbox.h>
+
+/* STD */
+#include <assert.h>
const int col_type = 0;
const int col_essid = 0;
const int col_sig = 1;
const int col_ap = 2;
const int col_channel = 3;
const int col_wep = 4;
const int col_traffic = 5;
const int col_ip = 6;
const int col_manuf = 7;
const int col_firstseen = 8;
const int col_lastseen = 9;
const int col_location = 10;
-using namespace Opie::Net;
-using namespace Opie::Ui;
-using namespace Opie::Net;
-using namespace Opie::Ui;
-using namespace Opie::Ui;
-using namespace Opie::Net;
MScanListView::MScanListView( QWidget* parent, const char* name )
:OListView( parent, name )
{
setFrameShape( QListView::StyledPanel );
setFrameShadow( QListView::Sunken );
addColumn( tr( "Net/Station" ) );
setColumnAlignment( col_essid, AlignLeft || AlignVCenter );
addColumn( tr( "#" ) );
setColumnAlignment( col_sig, AlignCenter );
addColumn( tr( "MAC" ) );
setColumnAlignment( col_ap, AlignCenter );
addColumn( tr( "Chn" ) );
setColumnAlignment( col_channel, AlignCenter );
addColumn( tr( "W" ) );
setColumnAlignment( col_wep, AlignCenter );
addColumn( tr( "T" ) );
setColumnAlignment( col_traffic, AlignCenter );
addColumn( tr( "IP" ) );
setColumnAlignment( col_ip, AlignCenter );
addColumn( tr( "Manufacturer" ) );
setColumnAlignment( col_manuf, AlignCenter );
addColumn( tr( "First Seen" ) );
setColumnAlignment( col_firstseen, AlignCenter );
addColumn( tr( "Last Seen" ) );
setColumnAlignment( col_lastseen, AlignCenter );
addColumn( tr( "Location" ) );
setColumnAlignment( col_location, AlignCenter );
setRootIsDecorated( true );
setAllColumnsShowFocus( true );
connect( this, SIGNAL( rightButtonClicked(QListViewItem*,const QPoint&,int) ),
this, SLOT( contextMenuRequested(QListViewItem*,const QPoint&,int) ) );
#ifdef QWS
QPEApplication::setStylusOperation( viewport(), QPEApplication::RightOnHold );
#endif
};
MScanListView::~MScanListView()
{
};
OListViewItem* MScanListView::childFactory()
{
return new MScanListItem( this );
}
void MScanListView::serializeTo( QDataStream& s) const
{
- qDebug( "serializing MScanListView" );
+ odebug << "serializing MScanListView" << oendl;
OListView::serializeTo( s );
}
void MScanListView::serializeFrom( QDataStream& s)
{
- qDebug( "serializing MScanListView" );
+ odebug << "serializing MScanListView" << oendl;
OListView::serializeFrom( s );
}
void MScanListView::addNewItem( const QString& type,
const QString& essid,
const OMacAddress& mac,
bool wep,
int channel,
int signal,
const GpsLocation& loc,
bool probe )
{
QString macaddr = mac.toString(true);
#ifdef DEBUG
qDebug( "MScanList::addNewItem( %s / %s / %s [%d]", (const char*) type,
(const char*) essid, (const char*) macaddr, channel );
#endif
// search, if we already have seen this net
QString s;
MScanListItem* network;
MScanListItem* item = static_cast<MScanListItem*> ( firstChild() );
while ( item && ( item->text( col_essid ) != essid ) )
{
#ifdef DEBUG
- qDebug( "itemtext: %s", (const char*) item->text( col_essid ) );
+ odebug << "itemtext: " << (const char*) item->text( col_essid ) << "" << oendl;
#endif
item = static_cast<MScanListItem*> ( item->nextSibling() );
}
if ( item )
{
// we have already seen this net, check all childs if MAC exists
network = item;
item = static_cast<MScanListItem*> ( item->firstChild() );
assert( item ); // this shouldn't fail
while ( item && ( item->text( col_ap ) != macaddr ) )
{
#ifdef DEBUG
- qDebug( "subitemtext: %s", (const char*) item->text( col_ap ) );
+ odebug << "subitemtext: " << (const char*) item->text( col_ap ) << "" << oendl;
#endif
item = static_cast<MScanListItem*> ( item->nextSibling() );
}
if ( item )
{
// we have already seen this item, it's a dupe
#ifdef DEBUG
- qDebug( "%s is a dupe - ignoring...", (const char*) macaddr );
+ odebug << "" << (const char*) macaddr << " is a dupe - ignoring..." << oendl;
#endif
item->receivedBeacon();
return;
}
}
else
{
s.sprintf( "(i) New network: ESSID '%s'", (const char*) essid );
MLogWindow::logwindow()->log( s );
network = new MScanListItem( this, "network", essid, QString::null, 0, 0, 0, probe );
}
// insert new station as child from network
// no essid to reduce clutter, maybe later we have a nick or stationname to display!?
#ifdef DEBUG
- qDebug( "inserting new station %s", (const char*) macaddr );
+ odebug << "inserting new station " << (const char*) macaddr << "" << oendl;
#endif
MScanListItem* station = new MScanListItem( network, type, "", macaddr, wep, channel, signal );
station->setManufacturer( mac.manufacturer() );
station->setLocation( loc.dmsPosition() );
if ( type == "managed" )
{
s.sprintf( "(i) New Access Point in '%s' [%d]", (const char*) essid, channel );
}
else
{
s.sprintf( "(i) New AdHoc station in '%s' [%d]", (const char*) essid, channel );
}
MLogWindow::logwindow()->log( s );
}
void MScanListView::addIfNotExisting( MScanListItem* network, const OMacAddress& addr, const QString& type )
{
MScanListItem* subitem = static_cast<MScanListItem*>( network->firstChild() );
while ( subitem && ( subitem->text( col_ap ) != addr.toString(true) ) )
{
#ifdef DEBUG
- qDebug( "subitemtext: %s", (const char*) subitem->text( col_ap ) );
+ odebug << "subitemtext: " << (const char*) subitem->text( col_ap ) << "" << oendl;
#endif
subitem = static_cast<MScanListItem*> ( subitem->nextSibling() );
}
if ( subitem )
{
// we have already seen this item, it's a dupe
#ifdef DEBUG
- qDebug( "%s is a dupe - ignoring...", (const char*) addr.toString(true) );
+ odebug << "" << (const char*) addr.toString(true) << " is a dupe - ignoring..." << oendl;
#endif
subitem->receivedBeacon(); //FIXME: sent data bit
return;
}
// Hey, it seems to be a new item :-D
MScanListItem* station = new MScanListItem( network, type, /* network->text( col_essid ) */ "", addr.toString(true), false, -1, -1 );
station->setManufacturer( addr.manufacturer() );
QString s;
if ( type == "station" )
{
s.sprintf( "(i) New Station in '%s' [xx]", (const char*) network->text( col_essid ) );
}
else
{
s.sprintf( "(i) New Wireless Station in '%s' [xx]", (const char*) network->text( col_essid ) );
}
MLogWindow::logwindow()->log( s );
}
void MScanListView::WDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& viaFrom, const OMacAddress& viaTo )
{
- qDebug( "WDSTraffic: %s and %s seem to form a WDS", (const char*) viaFrom.toString(), (const char*) viaTo.toString() );
+ odebug << "WDSTraffic: " << (const char*) viaFrom.toString() << " and " << (const char*) viaTo.toString() << " seem to form a WDS" << oendl;
QString s;
MScanListItem* network;
QListViewItemIterator it( this );
while ( it.current() &&
it.current()->text( col_ap ) != viaFrom.toString(true) &&
it.current()->text( col_ap ) != viaTo.toString(true) ) ++it;
MScanListItem* item = static_cast<MScanListItem*>( it.current() );
if ( item ) // Either viaFrom or viaTo AP has shown up yet, so just add our two new stations
{
addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from );
addIfNotExisting( static_cast<MScanListItem*>(item->parent()), to );
}
else
{
- qDebug( "D'Oh! Stations without AP... ignoring for now... will handle this in 1.1 version :-D" );
+ odebug << "D'Oh! Stations without AP... ignoring for now... will handle this in 1.1 version :-D" << oendl;
MLogWindow::logwindow()->log( "WARNING: Unhandled WSD traffic!" );
}
}
void MScanListView::toDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via )
{
QString s;
MScanListItem* network;
QListViewItemIterator it( this );
while ( it.current() && it.current()->text( col_ap ) != via.toString(true) ) ++it;
MScanListItem* item = static_cast<MScanListItem*>( it.current() );
if ( item ) // AP has shown up yet, so just add our new "from" - station
{
addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from, "adhoc" );
}
else
{
- qDebug( "D'Oh! Station without AP... ignoring for now... will handle this in 1.1 :-D" );
+ odebug << "D'Oh! Station without AP... ignoring for now... will handle this in 1.1 :-D" << oendl;
MLogWindow::logwindow()->log( "WARNING: Unhandled toDS traffic!" );
}
}
void MScanListView::fromDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via )
{
QString s;
MScanListItem* network;
QListViewItemIterator it( this );
while ( it.current() && it.current()->text( col_ap ) != via.toString(true) ) ++it;
MScanListItem* item = static_cast<MScanListItem*>( it.current() );
if ( item ) // AP has shown up yet, so just add our new "from" - station
{
addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from, "station" );
}
else
{
- qDebug( "D'Oh! Station without AP... ignoring for now... will handle this in 1.1 :-D" );
+ odebug << "D'Oh! Station without AP... ignoring for now... will handle this in 1.1 :-D" << oendl;
MLogWindow::logwindow()->log( "WARNING: Unhandled fromDS traffic!" );
}
}
void MScanListView::IBSStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via )
{
- qWarning( "D'oh! Not yet implemented..." );
+ owarn << "D'oh! Not yet implemented..." << oendl;
MLogWindow::logwindow()->log( "WARNING: Unhandled IBSS traffic!" );
}
void MScanListView::identify( const OMacAddress& macaddr, const QString& ip )
{
- qDebug( "identify %s = %s", (const char*) macaddr.toString(), (const char*) ip );
+ odebug << "identify " << (const char*) macaddr.toString() << " = " << (const char*) ip << "" << oendl;
QListViewItemIterator it( this );
for ( ; it.current(); ++it )
{
if ( it.current()->text( col_ap ) == macaddr.toString(true) )
{
it.current()->setText( col_ip, ip );
return;
}
}
- qDebug( "D'oh! Received identification, but item not yet in list... ==> Handle this!" );
+ odebug << "D'oh! Received identification, but item not yet in list... ==> Handle this!" << oendl;
MLogWindow::logwindow()->log( QString().sprintf( "WARNING: Unhandled identification %s = %s!",
(const char*) macaddr.toString(), (const char*) ip ) );
}
void MScanListView::addService( const QString& name, const OMacAddress& macaddr, const QString& ip )
{
- qDebug( "addService '%s', Server = %s = %s", (const char*) name, (const char*) macaddr.toString(), (const char*) ip );
+ odebug << "addService '" << (const char*) name << "', Server = " << (const char*) macaddr.toString() << " = " << (const char*) ip << "" << oendl;
//TODO: Refactor that out, we need it all over the place.
// Best to do it in a more comfortable abstraction in OListView
// (Hmm, didn't I already start something in this direction?)
QListViewItemIterator it( this );
for ( ; it.current(); ++it )
{
if ( it.current()->text( col_ap ) == macaddr.toString(true) )
{
MScanListItem* subitem = static_cast<MScanListItem*>( it.current()->firstChild() );
while ( subitem && ( subitem->text( col_essid ) != name ) )
{
#ifdef DEBUG
- qDebug( "subitemtext: %s", (const char*) subitem->text( col_essid ) );
+ odebug << "subitemtext: " << (const char*) subitem->text( col_essid ) << "" << oendl;
#endif
subitem = static_cast<MScanListItem*> ( subitem->nextSibling() );
}
if ( subitem )
{
// we have already seen this item, it's a dupe
#ifdef DEBUG
- qDebug( "%s is a dupe - ignoring...", (const char*) name );
+ odebug << "" << (const char*) name << " is a dupe - ignoring..." << oendl;
#endif
subitem->receivedBeacon(); //FIXME: sent data bit
return;
}
// never seen that - add new item
MScanListItem* item = new MScanListItem( it.current(), "service", "N/A", " ", false, -1, -1 );
item->setText( col_essid, name );
return;
}
}
- qDebug( "D'oh! Received identification, but item not yet in list... ==> Handle this!" );
+ odebug << "D'oh! Received identification, but item not yet in list... ==> Handle this!" << oendl;
MLogWindow::logwindow()->log( QString().sprintf( "WARNING: Unhandled service addition %s = %s!",
(const char*) macaddr.toString(), (const char*) ip ) );
}
void MScanListView::contextMenuRequested( QListViewItem* item, const QPoint&, int col )
{
if ( !item ) return;
MScanListItem* itm = static_cast<MScanListItem*>( item );
qDebug( "contextMenuRequested on item '%s' (%s) in column: '%d'",
(const char*) itm->text(0), (const char*) itm->type, col );
if ( itm->type == "adhoc" || itm->type == "managed" )
{
QString entry = QString().sprintf( "&Join %s Net '%s'...", (const char*) itm->type, (const char*) itm->essid() );
QPopupMenu m( this );
m.insertItem( entry, 37773, 0 );
int result = m.exec( QCursor::pos() );
if ( result == 37773 )
emit joinNetwork( itm->type, itm->essid(), itm->channel(), itm->macaddr() );
}
}
//============================================================
// MScanListItem
//============================================================
MScanListItem::MScanListItem( QListView* parent, const QString& type, const QString& essid, const QString& macaddr,
bool wep, int channel, int signal, bool probed )
:OListViewItem( parent, essid, QString::null, macaddr, QString::null, QString::null ),
_type( type ), _essid( essid ), _macaddr( macaddr ), _wep( wep ),
_channel( channel ), _signal( signal ), _beacons( 1 )
{
#ifdef DEBUG
- qDebug( "creating scanlist item" );
+ odebug << "creating scanlist item" << oendl;
#endif
if ( WellenreiterConfigWindow::instance() )
WellenreiterConfigWindow::instance()->performAction( type, essid, macaddr, wep, channel, signal ); // better use signal/slot combination here
decorateItem( type, essid, macaddr, wep, channel, signal, probed );
}
MScanListItem::MScanListItem( QListViewItem* parent, const QString& type, const QString& essid, const QString& macaddr,
bool wep, int channel, int signal )
:OListViewItem( parent, essid, QString::null, macaddr, QString::null, QString::null )
{
#ifdef DEBUG
- qDebug( "creating scanlist item" );
+ odebug << "creating scanlist item" << oendl;
#endif
if ( WellenreiterConfigWindow::instance() )
WellenreiterConfigWindow::instance()->performAction( type, essid, macaddr, wep, channel, signal ); // better use signal/slot combination here
decorateItem( type, essid, macaddr, wep, channel, signal, false );
}
const QString& MScanListItem::essid() const
{
if ( type == "network" )
return _essid;
else
return ( (MScanListItem*) parent() )->essid();
}
OListViewItem* MScanListItem::childFactory()
{
return new MScanListItem( this );
}
void MScanListItem::serializeTo( QDataStream& s ) const
{
#ifdef DEBUG
- qDebug( "serializing MScanListItem" );
+ odebug << "serializing MScanListItem" << oendl;
#endif
OListViewItem::serializeTo( s );
s << _type;
s << (Q_UINT8) ( _wep ? 'y' : 'n' );
}
void MScanListItem::serializeFrom( QDataStream& s )
{
#ifdef DEBUG
- qDebug( "serializing MScanListItem" );
+ odebug << "serializing MScanListItem" << oendl;
#endif
OListViewItem::serializeFrom( s );
char wep;
s >> _type;
s >> (Q_UINT8) wep;
_wep = (wep == 'y');
QString name;
name.sprintf( "wellenreiter/%s", (const char*) _type );
setPixmap( col_type, Resource::loadPixmap( name ) );
if ( _wep )
setPixmap( col_wep, Resource::loadPixmap( "wellenreiter/cracked" ) ); //FIXME: rename the pixmap!
listView()->triggerUpdate();
}
void MScanListItem::decorateItem( QString type, QString essid, QString macaddr, bool wep, int channel, int signal, bool probed )
{
#ifdef DEBUG
qDebug( "decorating scanlist item %s / %s / %s [%d]",
(const char*) type,
(const char*) essid,
(const char*) macaddr,
channel );
#endif
// set icon for managed or adhoc mode
QString name;
name.sprintf( "wellenreiter/%s", (const char*) type );
setPixmap( col_type, Resource::loadPixmap( name ) );
// special case for probed networks FIXME: This is ugly at present
if ( type == "network" && probed )
{
setPixmap( col_type, Resource::loadPixmap( "wellenreiter/network-probed.png" ) );
}
// set icon for wep (wireless encryption protocol)
if ( wep )
setPixmap( col_wep, Resource::loadPixmap( "wellenreiter/cracked" ) ); //FIXME: rename the pixmap!
// set channel and signal text
if ( signal != -1 )
setText( col_sig, QString::number( signal ) );
if ( channel != -1 )
setText( col_channel, QString::number( channel ) );
setText( col_firstseen, QTime::currentTime().toString() );
//setText( col_lastseen, QTime::currentTime().toString() );
listView()->triggerUpdate();
this->type = type;
_type = type;
_essid = essid;
_macaddr = macaddr;
_channel = channel;
_beacons = 1;
_signal = 0;
if ( WellenreiterConfigWindow::instance()->openTree->isChecked() )
{
listView()->ensureItemVisible( this );
}
}
void MScanListItem::setManufacturer( const QString& manufacturer )
{
setText( col_manuf, manufacturer );
}
void MScanListItem::setLocation( const QString& location )
{
setText( col_location, location );
}
void MScanListItem::receivedBeacon()
{
_beacons++;
#ifdef DEBUG
- qDebug( "MScanListItem %s: received beacon #%d", (const char*) _macaddr, _beacons );
+ odebug << "MScanListItem " << (const char*) _macaddr << ": received beacon #" << _beacons << "" << oendl;
#endif
setText( col_sig, QString::number( _beacons ) );
setText( col_lastseen, QTime::currentTime().toString() );
MScanListItem* p = (MScanListItem*) parent();
if ( p ) p->receivedBeacon();
}
diff --git a/noncore/net/wellenreiter/gui/wellenreiter.cpp b/noncore/net/wellenreiter/gui/wellenreiter.cpp
index fff7c35..fad6efd 100644
--- a/noncore/net/wellenreiter/gui/wellenreiter.cpp
+++ b/noncore/net/wellenreiter/gui/wellenreiter.cpp
@@ -1,733 +1,725 @@
/**********************************************************************
** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
***********************************************************************/
-// Local
-
#include "gps.h"
#include "wellenreiter.h"
#include "scanlist.h"
#include "logwindow.h"
#include "packetview.h"
#include "configwindow.h"
#include "statwindow.h"
#include "graphwindow.h"
#include "protolistview.h"
-// Opie
-
+/* OPIE */
#ifdef QWS
#include <opie2/oapplication.h>
+#include <opie2/odebug.h>
#include <opie2/odevice.h>
#else
#include <qapplication.h>
#endif
#include <opie2/omanufacturerdb.h>
#include <opie2/onetwork.h>
#include <opie2/opcap.h>
#include <qpe/qcopenvelope_qws.h>
-using namespace Opie;
-
-// Qt
+using namespace Opie::Core;
+using namespace Opie::Net;
+using namespace Opie::Ui;
+/* QT */
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qdatetime.h>
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qmessagebox.h>
#include <qobjectlist.h>
#include <qregexp.h>
#include <qspinbox.h>
#include <qtimer.h>
#include <qtoolbutton.h>
#include <qmainwindow.h>
-// Standard
-
+/* STD */
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
-using namespace Opie::Core;
-using namespace Opie::Net;
-using namespace Opie::Net;
-using namespace Opie::Core;
-using namespace Opie::Net;
-using namespace Opie::Core;
Wellenreiter::Wellenreiter( QWidget* parent )
: WellenreiterBase( parent, 0, 0 ),
sniffing( false ), iface( 0 ), configwindow( 0 )
{
logwindow->log( "(i) Wellenreiter has been started." );
//
// detect operating system
//
#ifdef QWS
QString sys;
sys.sprintf( "(i) Running on '%s'.", (const char*) ODevice::inst()->systemString() );
_system = ODevice::inst()->system();
logwindow->log( sys );
#endif
netview->setColumnWidthMode( 1, QListView::Manual );
connect( netview, SIGNAL( joinNetwork(const QString&,const QString&,int,const QString&) ),
this, SLOT( joinNetwork(const QString&,const QString&,int,const QString&) ) );
pcap = new OPacketCapturer();
pcap->setAutoDelete( false );
gps = new GPS( this );
QTimer::singleShot( 1000, this, SLOT( initialTimer() ) );
}
Wellenreiter::~Wellenreiter()
{
delete pcap;
}
void Wellenreiter::initialTimer()
{
- qDebug( "Wellenreiter::preloading manufacturer database..." );
+ odebug << "Wellenreiter::preloading manufacturer database..." << oendl;
OManufacturerDB::instance();
}
void Wellenreiter::setConfigWindow( WellenreiterConfigWindow* cw )
{
configwindow = cw;
}
void Wellenreiter::channelHopped(int c)
{
QString title = "Wellenreiter II -scan- [";
QString left;
if ( c > 1 ) left.fill( '.', c-1 );
title.append( left );
title.append( '|' );
if ( c < iface->channels() )
{
QString right;
right.fill( '.', iface->channels()-c );
title.append( right );
}
title.append( "]" );
//title.append( QString().sprintf( " %02d", c ) );
assert( parent() );
( (QMainWindow*) parent() )->setCaption( title );
}
void Wellenreiter::handleNotification( OPacket* p )
{
QObjectList* l = p->queryList();
QObjectListIt it( *l );
QObject* o;
while ( (o = it.current()) != 0 )
{
QString name = it.current()->name();
if ( configwindow->parsePackets->isProtocolChecked( name ) )
{
QString action = configwindow->parsePackets->protocolAction( name );
- qDebug( "parsePacket-action for '%s' seems to be '%s'", (const char*) name, (const char*) action );
+ odebug << "parsePacket-action for '" << (const char*) name << "' seems to be '" << (const char*) action << "'" << oendl;
doAction( action, name, p );
}
else
{
- qDebug( "protocol '%s' not checked in parsePackets.", (const char*) name );
+ odebug << "protocol '" << (const char*) name << "' not checked in parsePackets." << oendl;
}
++it;
}
}
void Wellenreiter::handleManagementFrame( OPacket* p, OWaveLanManagementPacket* manage )
{
if ( manage->managementType() == "Beacon" ) handleManagementFrameBeacon( p, manage );
else if ( manage->managementType() == "ProbeRequest" ) handleManagementFrameProbeRequest( p, manage );
else if ( manage->managementType() == "ProbeResponse" ) handleManagementFrameProbeResponse( p, manage );
- else qWarning( "Wellenreiter::handleManagementFrame(): '%s' - please handle me!", (const char*) manage->managementType() );
+ else owarn << "Wellenreiter::handleManagementFrame(): '" << (const char*) manage->managementType() << "' - please handle me!" << oendl;
}
void Wellenreiter::handleManagementFrameProbeRequest( OPacket* p, OWaveLanManagementPacket* request )
{
OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) );
QString essid = ssid ? ssid->ID( true /* decloak */ ) : QString("<unknown>");
OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) );
int channel = ds ? ds->channel() : -1;
OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
GpsLocation loc( -111, -111 );
if ( configwindow->enableGPS->isChecked() )
{
// TODO: add check if GPS is working!?
- qDebug( "Wellenreiter::gathering GPS data..." );
+ odebug << "Wellenreiter::gathering GPS data..." << oendl;
loc = gps->position();
- qDebug( "Wellenreiter::GPS data received is ( %f , %f ) - dms string = '%s'", loc.latitude(), loc.longitude(), loc.dmsPosition().latin1() );
+ odebug << "Wellenreiter::GPS data received is ( " << loc.latitude() << " , " << loc.longitude() << " ) - dms string = '" << loc.dmsPosition().latin1() << "'" << oendl;
}
if ( essid.length() )
netView()->addNewItem( "adhoc", essid, header->macAddress2(), false /* should check FrameControl field */, -1, 0, loc, true /* only probed */ );
- qDebug( "Wellenreiter::invalid frame [possibly noise] detected!" );
+ odebug << "Wellenreiter::invalid frame [possibly noise] detected!" << oendl;
}
void Wellenreiter::handleManagementFrameProbeResponse( OPacket* p, OWaveLanManagementPacket* response )
{
}
void Wellenreiter::handleManagementFrameBeacon( OPacket* p, OWaveLanManagementPacket* beacon )
{
QString type;
if ( beacon->canIBSS() )
{
type = "adhoc";
}
else if ( beacon->canESS() )
{
type = "managed";
}
else
{
- qWarning( "Wellenreiter::invalid frame [possibly noise] detected!" );
+ owarn << "Wellenreiter::invalid frame [possibly noise] detected!" << oendl;
return;
}
OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) );
QString essid = ssid ? ssid->ID( true /* decloak */ ) : QString("<unknown>");
OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) );
int channel = ds ? ds->channel() : -1;
OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
GpsLocation loc( -111, -111 );
if ( configwindow->enableGPS->isChecked() )
{
// TODO: add check if GPS is working!?
- qDebug( "Wellenreiter::gathering GPS data..." );
+ odebug << "Wellenreiter::gathering GPS data..." << oendl;
loc = gps->position();
- qDebug( "Wellenreiter::GPS data received is ( %f , %f ) - dms string = '%s'", loc.latitude(), loc.longitude(), loc.dmsPosition().latin1() );
+ odebug << "Wellenreiter::GPS data received is ( " << loc.latitude() << " , " << loc.longitude() << " ) - dms string = '" << loc.dmsPosition().latin1() << "'" << oendl;
}
netView()->addNewItem( type, essid, header->macAddress2(), beacon->canPrivacy(), channel, 0, loc );
// update graph window
if ( ds )
{
OPrismHeaderPacket* prism = static_cast<OPrismHeaderPacket*>( p->child( "Prism" ) );
if ( prism )
graphwindow->traffic( ds->channel(), prism->signalStrength() );
else
graphwindow->traffic( ds->channel(), 95 );
}
}
void Wellenreiter::handleControlFrame( OPacket* p, OWaveLanControlPacket* control )
{
OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
if ( control->controlType() == "Acknowledge" )
{
netView()->addNewItem( "adhoc", "<unknown>", header->macAddress1(), false, -1, 0, GpsLocation( -111, -111 ) );
}
else
{
- qDebug( "Wellenreiter::handleControlFrame - please handle %s in a future version! :D", (const char*) control->controlType() );
+ odebug << "Wellenreiter::handleControlFrame - please handle " << (const char*) control->controlType() << " in a future version! :D" << oendl;
}
}
void Wellenreiter::handleWlanData( OPacket* p, OWaveLanDataPacket* data, OMacAddress& from, OMacAddress& to )
{
OWaveLanPacket* wlan = (OWaveLanPacket*) p->child( "802.11" );
if ( wlan->fromDS() && !wlan->toDS() )
{
netView()->fromDStraffic( wlan->macAddress3(), wlan->macAddress1(), wlan->macAddress2() );
from = wlan->macAddress3();
to = wlan->macAddress2();
}
else if ( !wlan->fromDS() && wlan->toDS() )
{
netView()->toDStraffic( wlan->macAddress2(), wlan->macAddress3(), wlan->macAddress1() );
from = wlan->macAddress2();
to = wlan->macAddress3();
}
else if ( wlan->fromDS() && wlan->toDS() )
{
netView()->WDStraffic( wlan->macAddress4(), wlan->macAddress3(), wlan->macAddress1(), wlan->macAddress2() );
from = wlan->macAddress4();
to = wlan->macAddress3();
}
else
{
netView()->IBSStraffic( wlan->macAddress2(), wlan->macAddress1(), wlan->macAddress3() );
from = wlan->macAddress2();
to = wlan->macAddress1();
}
}
void Wellenreiter::handleEthernetData( OPacket* p, OEthernetPacket* data, OMacAddress& from, OMacAddress& to )
{
from = data->sourceAddress();
to = data->destinationAddress();
netView()->addNewItem( "station", "<wired>", from, false, -1, 0, GpsLocation( -111, -111 ) );
}
void Wellenreiter::handleARPData( OPacket* p, OARPPacket*, OMacAddress& source, OMacAddress& dest )
{
OARPPacket* arp = (OARPPacket*) p->child( "ARP" );
if ( arp )
{
- qDebug( "Received ARP traffic (type '%s'): ", (const char*) arp->type() );
+ odebug << "Received ARP traffic (type '" << (const char*) arp->type() << "'): " << oendl;
if ( arp->type() == "REQUEST" )
{
netView()->identify( arp->senderMacAddress(), arp->senderIPV4Address().toString() );
}
else if ( arp->type() == "REPLY" )
{
netView()->identify( arp->senderMacAddress(), arp->senderIPV4Address().toString() );
netView()->identify( arp->targetMacAddress(), arp->targetIPV4Address().toString() );
}
}
}
void Wellenreiter::handleIPData( OPacket* p, OIPPacket* ip, OMacAddress& source, OMacAddress& dest )
{
//TODO: Implement more IP based protocols
ODHCPPacket* dhcp = (ODHCPPacket*) p->child( "DHCP" );
if ( dhcp )
{
- qDebug( "Received DHCP '%s' packet", (const char*) dhcp->type() );
+ odebug << "Received DHCP '" << (const char*) dhcp->type() << "' packet" << oendl;
if ( dhcp->type() == "OFFER" )
{
- qDebug( "DHCP: '%s' ('%s') seems to be a DHCP server.", (const char*) source.toString(), (const char*) dhcp->serverAddress().toString() );
+ odebug << "DHCP: '" << (const char*) source.toString() << "' ('" << (const char*) dhcp->serverAddress().toString() << "') seems to be a DHCP server." << oendl;
netView()->identify( source, dhcp->serverAddress().toString() );
netView()->addService( "DHCP", source, dhcp->serverAddress().toString() );
}
else if ( dhcp->type() == "ACK" )
{
- qDebug( "DHCP: '%s' ('%s') accepted the offered DHCP address.", (const char*) dhcp->clientMacAddress().toString(), (const char*) dhcp->yourAddress().toString() );
+ odebug << "DHCP: '" << (const char*) dhcp->clientMacAddress().toString() << "' ('" << (const char*) dhcp->yourAddress().toString() << "') accepted the offered DHCP address." << oendl;
netView()->identify( dhcp->clientMacAddress(), dhcp->yourAddress().toString() );
}
}
}
QObject* Wellenreiter::childIfToParse( OPacket* p, const QString& protocol )
{
if ( configwindow->parsePackets->isProtocolChecked( protocol ) )
if ( configwindow->parsePackets->protocolAction( protocol ) == "Discard!" )
return 0;
return p->child( protocol );
}
bool Wellenreiter::checkDumpPacket( OPacket* p )
{
// go through all child packets and see if one is inside the child hierarchy for p
// if so, do what the user requested (protocolAction), e.g. pass or discard
if ( !configwindow->writeCaptureFile->isChecked() )
return true; // semantic change - we're logging anyway now to /tmp/wellenreiter
QObjectList* l = p->queryList();
QObjectListIt it( *l );
QObject* o;
while ( (o = it.current()) != 0 )
{
QString name = it.current()->name();
if ( configwindow->capturePackets->isProtocolChecked( name ) )
{
QString action = configwindow->capturePackets->protocolAction( name );
- qDebug( "capturePackets-action for '%s' seems to be '%s'", (const char*) name, (const char*) action );
+ odebug << "capturePackets-action for '" << (const char*) name << "' seems to be '" << (const char*) action << "'" << oendl;
if ( action == "Discard" )
{
logwindow->log( QString().sprintf( "(i) dump-discarding of '%s' packet requested.", (const char*) name ) );
return false;
}
}
else
{
- qDebug( "protocol '%s' not checked in capturePackets.", (const char*) name );
+ odebug << "protocol '" << (const char*) name << "' not checked in capturePackets." << oendl;
}
++it;
}
return true;
}
void Wellenreiter::receivePacket( OPacket* p )
{
hexWindow()->add( p );
if ( checkDumpPacket( p ) )
{
pcap->dump( p );
}
// check for a management frame
OWaveLanManagementPacket* manage = static_cast<OWaveLanManagementPacket*>( childIfToParse( p, "802.11 Management" ) );
if ( manage )
{
handleManagementFrame( p, manage );
return;
}
// check for a control frame
OWaveLanControlPacket* control = static_cast<OWaveLanControlPacket*>( childIfToParse( p, "802.11 Control" ) );
if ( control )
{
handleControlFrame( p, control );
return;
}
OMacAddress source;
OMacAddress dest;
//TODO: WEP check here
// check for a wireless data frame
OWaveLanDataPacket* wlan = static_cast<OWaveLanDataPacket*>( childIfToParse( p, "802.11 Data" ) );
if ( wlan )
{
handleWlanData( p, wlan, source, dest );
}
// check for a wired data frame
OEthernetPacket* eth = static_cast<OEthernetPacket*>( childIfToParse( p, "Ethernet" ) );
if ( eth )
{
handleEthernetData( p, eth, source, dest );
}
// check for an arp frame since arp frames come in two flavours:
// 802.11 encapsulates ARP data within IP packets while wired ethernet doesn't.
OARPPacket* arp = static_cast<OARPPacket*>( childIfToParse( p, "ARP" ) );
if ( arp )
{
handleARPData( p, arp, source, dest );
}
// check for a ip frame
OIPPacket* ip = static_cast<OIPPacket*>( childIfToParse( p, "IP" ) );
if ( ip )
{
handleIPData( p, ip, source, dest );
}
//handleNotification( p );
}
void Wellenreiter::stopClicked()
{
if ( iface )
{
disconnect( SIGNAL( receivedPacket(Opie::Net::OPacket*) ), this, SLOT( receivePacket(Opie::Net::OPacket*) ) );
disconnect( SIGNAL( hopped(int) ), this, SLOT( channelHopped(int) ) );
iface->setChannelHopping(); // stop hopping channels
}
else
killTimers();
pcap->close();
sniffing = false;
if ( iface )
{
// switch off monitor mode
iface->setMode( "managed" );
// switch off promisc flag
iface->setPromiscuousMode( false );
system( "cardctl reset; sleep 1" ); //FIXME: Use OProcess
}
logwindow->log( "(i) Stopped Scanning." );
assert( parent() );
( (QMainWindow*) parent() )->setCaption( "Wellenreiter II" );
// message the user
QMessageBox::information( this, "Wellenreiter II",
tr( "Your wireless card\nshould now be usable again." ) );
sniffing = false;
emit( stoppedSniffing() );
#ifdef QWS
if ( WellenreiterConfigWindow::instance()->disablePM->isChecked() )
{
QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
}
#else
#warning FIXME: setScreenSaverMode is not operational on the X11 build
#endif
// print out statistics
for( QMap<QString,int>::ConstIterator it = pcap->statistics().begin(); it != pcap->statistics().end(); ++it )
statwindow->updateCounter( it.key(), it.data() );
}
void Wellenreiter::startClicked()
{
// get configuration from config window
const QString& interface = configwindow->interfaceName->currentText();
const int cardtype = configwindow->driverType();
const int interval = configwindow->hoppingInterval();
if ( ( interface == "" ) || ( cardtype == 0 ) )
{
QMessageBox::information( this, "Wellenreiter II",
tr( "Your device is not\nproperly configured. Please reconfigure!" ) );
return;
}
// configure device
ONetwork* net = ONetwork::instance();
// TODO: check if interface is wireless and support sniffing for non-wireless interfaces
if ( cardtype != DEVTYPE_FILE )
{
if ( !net->isPresent( interface ) )
{
QMessageBox::information( this, "Wellenreiter II",
tr( "The configured device (%1)\nis not available on this system\n. Please reconfigure!" ).arg( interface ) );
return;
}
iface = static_cast<OWirelessNetworkInterface*>(net->interface( interface )); // fails if network is not wireless!
assert( iface );
// bring device UP
iface->setUp( true );
if ( !iface->isUp() )
{
QMessageBox::warning( this, "Wellenreiter II",
tr( "Can't bring interface '%1' up:\n" ).arg( iface->name() ) + strerror( errno ) );
return;
}
}
// set monitor mode
bool usePrism = configwindow->usePrismHeader();
switch ( cardtype )
{
case DEVTYPE_CISCO: iface->setMonitoring( new OCiscoMonitoringInterface( iface, usePrism ) ); break;
case DEVTYPE_WLAN_NG: iface->setMonitoring( new OWlanNGMonitoringInterface( iface, usePrism ) ); break;
case DEVTYPE_HOSTAP: iface->setMonitoring( new OHostAPMonitoringInterface( iface, usePrism ) ); break;
case DEVTYPE_ORINOCO: iface->setMonitoring( new OOrinocoMonitoringInterface( iface, usePrism ) ); break;
case DEVTYPE_MANUAL: QMessageBox::information( this, "Wellenreiter II", tr( "Bring your device into\nmonitor mode now." ) ); break;
- case DEVTYPE_FILE: qDebug( "Wellenreiter: Capturing from file '%s'", (const char*) interface ); break;
+ case DEVTYPE_FILE: odebug << "Wellenreiter: Capturing from file '" << (const char*) interface << "'" << oendl; break;
default: assert( 0 ); // shouldn't reach this
}
// switch device into monitor mode
if ( cardtype < DEVTYPE_FILE )
{
if ( cardtype != DEVTYPE_MANUAL )
iface->setMode( "monitor" );
if ( iface->mode() != "monitor" )
{
if ( QMessageBox::warning( this, "Wellenreiter II",
tr( "Can't set interface '%1'\ninto monitor mode:\n" ).arg( iface->name() ) + strerror( errno ) +
tr( "\nContinue with limited functionality?" ), QMessageBox::Yes, QMessageBox::No ) == QMessageBox::No )
return;
}
}
// open GPS device
if ( configwindow->enableGPS->isChecked() )
{
- qDebug( "Wellenreiter:GPS enabled @ %s:%d", (const char*) configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() );
+ odebug << "Wellenreiter:GPS enabled @ " << (const char*) configwindow->gpsdHost->currentText() << ":" << configwindow->gpsdPort->value() << "" << oendl;
gps->open( configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() );
}
// open pcap and start sniffing
if ( configwindow->writeCaptureFile->isChecked() ) // write to a user specified capture file?
{
dumpname = configwindow->captureFileName->text();
if ( dumpname.isEmpty() ) dumpname = "captureFile";
dumpname.append( '-' );
dumpname.append( QTime::currentTime().toString().replace( QRegExp( ":" ), "-" ) );
dumpname.append( ".wellenreiter" );
}
else // write it anyway ;)
{
dumpname = "/var/log/dump.wellenreiter";
}
if ( cardtype != DEVTYPE_FILE )
pcap->open( interface );
else
pcap->open( QFile( interface ) );
- qDebug( "Wellenreiter:: dumping to %s", (const char*) dumpname );
+ odebug << "Wellenreiter:: dumping to " << (const char*) dumpname << "" << oendl;
pcap->openDumpFile( dumpname );
if ( !pcap->isOpen() )
{
QMessageBox::warning( this, "Wellenreiter II", tr( "Can't open packet capturer for\n'%1':\n" ).arg(
cardtype == DEVTYPE_FILE ? (const char*) interface : iface->name() ) + QString(strerror( errno ) ));
return;
}
// set capturer to non-blocking mode
pcap->setBlocking( false );
// start channel hopper
if ( cardtype != DEVTYPE_FILE )
{
logwindow->log( QString().sprintf( "(i) Starting channel hopper (d=%d ms)", configwindow->hopInterval->value() ) );
iface->setChannelHopping( configwindow->hopInterval->value() ); //use interval from config window
}
if ( cardtype != DEVTYPE_FILE )
{
// connect socket notifier and start channel hopper
connect( pcap, SIGNAL( receivedPacket(Opie::Net::OPacket*) ), this, SLOT( receivePacket(Opie::Net::OPacket*) ) );
connect( iface->channelHopper(), SIGNAL( hopped(int) ), this, SLOT( channelHopped(int) ) );
}
else
{
// start timer for reading packets
startTimer( 100 );
}
logwindow->log( "(i) Started Scanning." );
sniffing = true;
#ifdef QWS
if ( WellenreiterConfigWindow::instance()->disablePM->isChecked() )
{
QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Disable;
}
#else
#warning FIXME: setScreenSaverMode is not operational on the X11 build
#endif
emit( startedSniffing() );
if ( cardtype != DEVTYPE_FILE ) channelHopped( 6 ); // set title
else
{
assert( parent() );
( (QMainWindow*) parent() )->setCaption( tr( "Wellenreiter II - replaying capture file..." ) );
}
}
void Wellenreiter::timerEvent( QTimerEvent* )
{
- qDebug( "Wellenreiter::timerEvent()" );
+ odebug << "Wellenreiter::timerEvent()" << oendl;
OPacket* p = pcap->next();
if ( !p ) // no more packets available
{
stopClicked();
}
else
{
receivePacket( p );
// We no longer delete packets here. Ownership of the packets is
// transferred to the PacketView.
//delete p;
}
}
void Wellenreiter::doAction( const QString& action, const QString& protocol, OPacket* p )
{
#ifdef QWS
if ( action == "TouchSound" )
ODevice::inst()->playTouchSound();
else if ( action == "AlarmSound" )
ODevice::inst()->playAlarmSound();
else if ( action == "KeySound" )
ODevice::inst()->playKeySound();
else if ( action == "LedOn" )
ODevice::inst()->setLedState( Led_Mail, Led_On );
else if ( action == "LedOff" )
ODevice::inst()->setLedState( Led_Mail, Led_Off );
else if ( action == "LogMessage" )
logwindow->log( QString().sprintf( "Got packet with protocol '%s'", (const char*) protocol ) );
else if ( action == "MessageBox" )
QMessageBox::information( this, "Notification!",
QString().sprintf( "Got packet with protocol '%s'", (const char*) protocol ) );
#else
#warning Actions do not work with Qt/X11 yet
#endif
}
void Wellenreiter::joinNetwork(const QString& type, const QString& essid, int channel, const QString& macaddr)
{
#ifdef QWS
if ( !iface )
{
QMessageBox::warning( this, tr( "Can't do that!" ), tr( "No wireless\ninterface available." ) );
return;
}
if ( sniffing )
{
QMessageBox::warning( this, tr( "Can't do that!" ), tr( "Stop sniffing before\njoining a net." ) );
return;
}
qDebug( "joinNetwork() with Interface %s: %s, %s, %d, %s",
(const char*) iface->name(),
(const char*) type,
(const char*) essid,
channel,
(const char*) macaddr );
QCopEnvelope msg( "QPE/Application/networksettings", "wlan(QString,QString,QString)" );
int count = 3;
- qDebug("sending %d messages",count);
+ odebug << "sending " << count << " messages" << oendl;
msg << QString("count") << QString::number(count);
- qDebug("msg >%s< Mode >%s<", iface->name(),type.latin1() );
+ odebug << "msg >" << iface->name() << "< Mode >" << type.latin1() << "<" << oendl;
msg << QString(iface->name()) << QString("Mode") << type;
- qDebug("msg >%s< essid >%s<", iface->name(),essid.latin1());
+ odebug << "msg >" << iface->name() << "< essid >" << essid.latin1() << "<" << oendl;
msg << QString(iface->name()) << QString("ESSID") << essid;
- qDebug("msg >%s< channel >%d<", iface->name(),channel);
+ odebug << "msg >" << iface->name() << "< channel >" << channel << "<" << oendl;
msg << QString(iface->name()) << QString("Channel") << channel;
-// qDebug("msg >%s< mac >%s<", iface->name(),macaddr);
+// odebug << "msg >" << iface->name() << "< mac >" << macaddr << "<" << oendl;
// msg << QString(iface->name()) << QString("MacAddr") << macaddr;
#else
QMessageBox::warning( this, tr( "Can't do that!" ), tr( "Function only available on Embedded build" ) );
#endif
}
diff --git a/noncore/settings/backup/backuprestore.cpp b/noncore/settings/backup/backuprestore.cpp
index 58e5c71..2eccdfe 100644
--- a/noncore/settings/backup/backuprestore.cpp
+++ b/noncore/settings/backup/backuprestore.cpp
@@ -1,528 +1,528 @@
-
#include "backuprestore.h"
#include "errordialog.h"
/* OPIE */
+#include <opie2/odebug.h>
#include <opie2/ostorageinfo.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
/* QT */
#include <qapplication.h>
#include <qmultilineedit.h>
#include <qdir.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qlistview.h>
#include <qpushbutton.h>
#include <qheader.h>
#include <qpe/resource.h>
#include <qpe/config.h>
#include <qmessagebox.h>
#include <qcombobox.h>
#include <qlist.h>
#include <stdlib.h>
#include <qregexp.h>
#include <qtextstream.h>
#include <qtextview.h>
/* STD */
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#define HEADER_NAME 0
#define HEADER_BACKUP 1
#define BACKUP_LOCATION 2
#define EXTENSION ".bck"
const QString tempFileName = "/tmp/backup.err";
-
BackupAndRestore::BackupAndRestore( QWidget* parent, const char* name, WFlags fl)
: BackupAndRestoreBase(parent, name, fl)
{
backupList->header()->hide();
restoreList->header()->hide();
connect(backupButton, SIGNAL(clicked()),
this, SLOT(backup()));
connect(restoreButton, SIGNAL(clicked()),
this, SLOT(restore()));
connect(backupList, SIGNAL(clicked(QListViewItem*)),
this, SLOT(selectItem(QListViewItem*)));
connect(restoreSource, SIGNAL(activated(int)),
this, SLOT(sourceDirChanged(int)));
connect(updateList, SIGNAL(clicked()),
this, SLOT( fileListUpdate()));
//add directorys for backing up
applicationSettings = new QListViewItem(backupList, "Application Settings", "", "Settings/");
selectItem(applicationSettings);
applicationSettings = new QListViewItem(backupList, "Application Data", "", "Applications/");
selectItem(applicationSettings);
documents= new QListViewItem(backupList, "Documents", "", "Documents/");
selectItem(documents);
scanForApplicationSettings();
Opie::Core::OStorageInfo storage;
backupLocations.insert( "Documents", QDir::homeDirPath() + "/Documents" );
if ( storage.hasCf() )
{
backupLocations.insert( "CF", storage.cfPath() );
- qDebug( "Cf Path: " + storage.cfPath() );
+ odebug << "Cf Path: " + storage.cfPath() << oendl;
}
if ( storage.hasSd() )
{
backupLocations.insert( "SD", storage.sdPath() );
- qDebug( " Sd Path: " + storage.sdPath() );
+ odebug << " Sd Path: " + storage.sdPath() << oendl;
}
if ( storage.hasMmc() )
{
backupLocations.insert( "MMC", storage.mmcPath() );
- qDebug( "Mmc Path: " + storage.mmcPath() );
+ odebug << "Mmc Path: " + storage.mmcPath() << oendl;
}
Config config("BackupAndRestore");
//read last locations
config.setGroup("LastLocation");
QString lastStoreLocation = config.readEntry( "LastStoreLocation", "" );
QString lastRestoreLocation = config.readEntry( "LastRestoreLocation", "" );
int locationIndex = 0;
QMap<QString, QString>::Iterator it;
for( it = backupLocations.begin(); it != backupLocations.end(); ++it )
{
storeToLocation->insertItem(it.key());
restoreSource->insertItem(it.key());
//check for last locations
if ( it.key() == lastStoreLocation )
storeToLocation->setCurrentItem( locationIndex );
if ( it.key() == lastRestoreLocation )
restoreSource->setCurrentItem( locationIndex );
locationIndex++;
}
// Read the list of items to ignore.
QList<QString> dontBackupList;
dontBackupList.setAutoDelete(true);
config.setGroup("DontBackup");
int total = config.readNumEntry("Total", 0);
for(int i = 0; i < total; i++)
{
dontBackupList.append(new QString(config.readEntry(QString("%1").arg(i), "")));
}
QList<QListViewItem> list;
getAllItems(backupList->firstChild(), list);
for(uint i = 0; i < list.count(); i++)
{
QString text = list.at(i)->text(HEADER_NAME);
for(uint i2 = 0; i2 < dontBackupList.count(); i2++)
{
if(*dontBackupList.at(i2) == text)
{
selectItem(list.at(i));
break;
}
}
}
QPEApplication::showWidget( this );
}
BackupAndRestore::~BackupAndRestore()
{
QList<QListViewItem> list;
getAllItems(backupList->firstChild(), list);
Config config("BackupAndRestore");
config.setGroup("DontBackup");
config.clearGroup();
int count = 0;
for(uint i = 0; i < list.count(); i++)
{
if(list.at(i)->text(HEADER_BACKUP) == "")
{
config.writeEntry(QString("%1").arg(count), list.at(i)->text(HEADER_NAME));
count++;
}
}
config.writeEntry("Total", count);
// Remove Temp File
if ( QFile::exists( tempFileName ) )
QFile::remove( tempFileName );
}
QList<QListViewItem> BackupAndRestore::getAllItems(QListViewItem *item, QList<QListViewItem> &list)
{
while(item)
{
if(item->childCount() > 0)
getAllItems(item->firstChild(), list);
list.append(item);
item = item->nextSibling();
}
return list;
}
/**
* Selects and unselects the item by setting the HEADER_BACKUP to B or !.
* and changing the icon to match
* @param currentItem the item to swich the selection choice.
*/
void BackupAndRestore::selectItem(QListViewItem *currentItem)
{
if(!currentItem)
return;
if(currentItem->text(HEADER_BACKUP) == "B")
{
currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/null"));
currentItem->setText(HEADER_BACKUP, "");
}
else
{
currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/check"));
currentItem->setText(HEADER_BACKUP, "B");
}
}
void BackupAndRestore::scanForApplicationSettings()
{
QDir d( QDir::homeDirPath() + "/" + QString( applicationSettings->text(BACKUP_LOCATION) ) );
d.setFilter( QDir::Dirs | QDir::Files | QDir::NoSymLinks );
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
while ( (fi=it.current()) )
{
- //qDebug((d.path()+"/"+fi->fileName()).latin1());
+ //odebug << (d.path()+"/"+fi->fileName()).latin1() << oendl;
if ( ( fi->fileName() != "." ) && ( fi->fileName() != ".." ) )
{
QListViewItem *newItem = new QListViewItem(applicationSettings, fi->fileName());
selectItem(newItem);
}
++it;
}
}
/**
* The "Backup" button has been pressed. Get a list of all of the files that
* should be backed up. If there are no files, emit and error and exit.
* Determine the file name to store the backup in. Backup the file(s) using
* tar and gzip --best. Report failure or success
*/
void BackupAndRestore::backup()
{
QString backupFiles;
if(getBackupFiles(backupFiles, NULL) == 0)
{
QMessageBox::critical(this, "Message",
"No items selected.",QString("Ok") );
return;
}
setCaption(tr("Backup and Restore... working..."));
QString outputFile = backupLocations[storeToLocation->currentText()];
QDateTime datetime = QDateTime::currentDateTime();
QString dateString = QString::number( datetime.date().year() ) + QString::number( datetime.date().month() ).rightJustify(2, '0') +
QString::number( datetime.date().day() ).rightJustify(2, '0');
outputFile += "/" + dateString;
QString t = outputFile;
int c = 1;
while(QFile::exists(outputFile + EXTENSION))
{
outputFile = t + QString("%1").arg(c);
c++;
}
// We execute tar and compressing its output with gzip..
// The error output will be written into a temp-file which could be provided
// for debugging..
- qDebug( "Storing file: %s", outputFile.latin1() );
+ odebug << "Storing file: " << outputFile.latin1() << "" << oendl;
outputFile += EXTENSION;
QString commandLine = QString( "cd %1 && (tar -X %1 -cz %2 Applications/backup/exclude -f %3 ) 2> %4" ).arg( QDir::homeDirPath() )
.arg( getExcludeFile() )
.arg( backupFiles )
.arg( outputFile.latin1() )
.arg( tempFileName.latin1() );
- qDebug( commandLine );
+ odebug << commandLine << oendl;
int r = system( commandLine );
if(r != 0)
{
perror("Error: ");
QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno );
switch( QMessageBox::critical(this, tr( "Message" ), tr( "Backup Failed!" ) + "\n"
+ errorMsg, QString( tr( "Ok" ) ), QString( tr( "Details" ) ) ) )
{
case 1:
- qWarning("Details pressed !");
+ owarn << "Details pressed !" << oendl;
ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true );
QFile errorFile( tempFileName );
if ( errorFile.open(IO_ReadOnly) )
{
QTextStream t( &errorFile );
QString s;
while ( !t.eof() )
{ // until end of file...
s += t.readLine(); // line of text excluding '\n'
}
errorFile.close();
pErrDialog->m_textarea->setText( s );
}
else
{
pErrDialog->m_textarea->setText( "Unable to open File: /tmp/backup.er" );
}
QPEApplication::execDialog( pErrDialog );
delete pErrDialog;
break;
}
setCaption(tr("Backup and Restore.. Failed !!"));
return;
}
else
{
QMessageBox::information(this, tr( "Message" ), tr( "Backup Successful." ), QString(tr( "Ok" ) ) );
}
//write store-location
Config config( "BackupAndRestore" );
config.setGroup( "LastLocation" );
config.writeEntry( "LastStoreLocation", storeToLocation->currentText() );
setCaption(tr("Backup and Restore"));
}
/***
* Get a list of all of the files to backup.
*/
int BackupAndRestore::getBackupFiles(QString &backupFiles, QListViewItem *parent)
{
QListViewItem * currentItem;
QString currentHome;
if(!parent)
currentItem = backupList->firstChild();
else
{
currentItem = parent->firstChild();
currentHome = parent->text(BACKUP_LOCATION);
}
uint count = 0;
while( currentItem != 0 )
{
if(currentItem->text(HEADER_BACKUP) == "B" )
{
if(currentItem->childCount() == 0 )
{
if(parent == NULL)
backupFiles += currentItem->text(BACKUP_LOCATION);
else
backupFiles += currentHome + currentItem->text(HEADER_NAME);
backupFiles += " ";
count++;
}
else
{
count += getBackupFiles(backupFiles, currentItem);
}
}
currentItem = currentItem->nextSibling();
}
return count;
}
void BackupAndRestore::sourceDirChanged(int selection)
{
restoreList->clear();
rescanFolder(backupLocations[restoreSource->text(selection)]);
}
void BackupAndRestore::fileListUpdate()
{
- qWarning("void BackupAndRestore::fileListUpdate()");
+ owarn << "void BackupAndRestore::fileListUpdate()" << oendl;
restoreList->clear();
rescanFolder( backupLocations[restoreSource->currentText()] );
}
/**
* Scans directory for any backup files. Will recursivly go down,
* but will not follow symlinks.
* @param directory - the directory to look in.
*/
void BackupAndRestore::rescanFolder(QString directory)
{
- //qDebug(QString("rescanFolder: ") + directory.latin1());
+ //odebug << QString("rescanFolder: ") + directory.latin1() << oendl;
QDir d(directory);
if(!d.exists())
return;
d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs);
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *file;
while ( (file=it.current()) )
{ // for each file...
// If it is a dir and not .. or . then add it as a tab and go down.
if(file->isDir())
{
if(file->fileName() != ".." && file->fileName() != ".")
{
rescanFolder(directory + "/" + file->fileName());
}
}
else
{
// If it is a backup file add to list.
if(file->fileName().contains(EXTENSION))
(void)new QListViewItem(restoreList, file->fileName());
}
++it;
}
}
/**
* Restore a backup file.
* Report errors or success
*/
void BackupAndRestore::restore()
{
QListViewItem *restoreItem = restoreList->currentItem();
if(!restoreItem)
{
QMessageBox::critical(this, tr( "Message" ),
tr( "Please select something to restore." ),QString( tr( "Ok") ) );
return;
}
setCaption(tr("Backup and Restore... working..."));
QString restoreFile = backupLocations[restoreSource->currentText()];
restoreFile += "/" + restoreItem->text(0);
- qDebug( restoreFile );
+ odebug << restoreFile << oendl;
//check if backup file come from opie 1.0.x
QString commandLine = QString( "tar -tzf %1 | grep Applications/backup/exclude" ).arg( restoreFile.latin1() );
int r = system( commandLine );
QString startDir;
if( r != 0 ) //Applications/backup/exclude not found - old backup file
{
startDir = QString( "/" );
} else
{
startDir = QDir::homeDirPath();
}
//unpack backup file
commandLine = QString( "cd %1 && tar -zxf %2 2> %3" ).arg( startDir )
.arg( restoreFile.latin1() )
.arg( tempFileName.latin1() );
- qDebug( commandLine );
+ odebug << commandLine << oendl;
r = system( commandLine );
//error handling
if(r != 0)
{
QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno );
switch( QMessageBox::critical(this, tr( "Message" ), tr( "Restore Failed." ) + "\n"
+ errorMsg, QString( tr( "Ok") ), QString( tr( "Details" ) ) ) )
{
case 1:
- qWarning("Details pressed !");
+ owarn << "Details pressed !" << oendl;
ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true );
QFile errorFile( tempFileName );
if ( errorFile.open(IO_ReadOnly) )
{
QTextStream t( &errorFile );
QString s;
while ( !t.eof() )
{ // until end of file...
s += t.readLine(); // line of text excluding '\n'
}
errorFile.close();
pErrDialog->m_textarea->setText( s );
}
else
{
pErrDialog->m_textarea->setText( tr( "Unable to open File: %1" ).arg( "/tmp/backup.er" ) );
}
QPEApplication::execDialog( pErrDialog );
delete pErrDialog;
setCaption(tr("Backup and Restore.. Failed !!"));
return;
break;
}
}
else
{
QMessageBox::information(this, tr( "Message" ), tr( "Restore Successful." ), QString( tr( "Ok") ) );
}
//write restore-location
Config config( "BackupAndRestore" );
config.setGroup( "LastLocation" );
config.writeEntry( "LastRestoreLocation", restoreSource->currentText() );
setCaption(tr("Backup and Restore"));
}
/**
* Check for exclude in Applications/backup
* If it does not exist, the function will create the file with *.bck as content
* The exclude_files is read by tar and will provide to exclude special files out from backup.
* e.g. alle *.bck files (backup-files) will not be backed up by default
*/
QString BackupAndRestore::getExcludeFile()
{
QString excludeFileName = Global::applicationFileName( "backup", "exclude" );
if ( !QFile::exists( excludeFileName ) )
{
QFile excludeFile( excludeFileName);
if ( excludeFile.open( IO_WriteOnly ) == true )
{
QTextStream writeStream( &excludeFile );
writeStream << "*.bck" << "\n";
excludeFile.close();
}
else
{
return QString::null;
}
}
return excludeFileName;
}
// backuprestore.cpp
diff --git a/noncore/settings/netsystemtime/settingstabwidget.cpp b/noncore/settings/netsystemtime/settingstabwidget.cpp
index ad80e05..1307082 100644
--- a/noncore/settings/netsystemtime/settingstabwidget.cpp
+++ b/noncore/settings/netsystemtime/settingstabwidget.cpp
@@ -46,114 +46,114 @@ SettingsTabWidget::SettingsTabWidget( QWidget *parent )
tmpvb->addWidget( sv, 0, 0 );
sv->setResizePolicy( QScrollView::AutoOneFit );
sv->setFrameStyle( QFrame::NoFrame );
QWidget *container = new QWidget( sv->viewport() );
sv->addChild( container );
QGridLayout *layout = new QGridLayout( container );
layout->setMargin( 2 );
layout->setSpacing( 4 );
// Time server selector
layout->addWidget( new QLabel( tr( "Time server" ), container ), 0, 0 );
cbTimeServer = new QComboBox( TRUE, container );
layout->addMultiCellWidget( cbTimeServer, 1, 1, 0, 1 );
// Lookup delay selector
layout->addWidget( new QLabel( tr( "minutes between time updates" ), container ), 2, 1 );
sbNtpDelay = new QSpinBox( 1, 9999999, 1, container );
sbNtpDelay->setWrapping( TRUE );
sbNtpDelay->setMaximumWidth( 50 );
connect( sbNtpDelay, SIGNAL(valueChanged(int)), this, SIGNAL(ntpDelayChanged(int)) );
layout->addWidget( sbNtpDelay, 2, 0 );
// Prediction delay selector
layout->addWidget( new QLabel( tr( "minutes between prediction updates" ), container ), 3, 1 );
sbPredictDelay = new QSpinBox( 42, 9999999, 1, container );
sbPredictDelay->setWrapping( TRUE );
sbPredictDelay->setMaximumWidth( 50 );
layout->addWidget( sbPredictDelay, 3, 0 );
// Space filler
layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 4, 0 );
// Display time server information selector
chNtpTab = new QCheckBox( tr( "Display time server information" ), container );
connect( chNtpTab, SIGNAL( toggled(bool) ), this, SIGNAL( displayNTPTab(bool) ) );
layout->addMultiCellWidget( chNtpTab, 5, 5, 0, 1 );
// Display time prediction information selector
chPredictTab = new QCheckBox( tr( "Display time prediction information" ), container );
connect( chPredictTab, SIGNAL( toggled(bool) ), this, SIGNAL( displayPredictTab(bool) ) );
layout->addMultiCellWidget( chPredictTab, 6, 6, 0, 1 );
// Space filler
layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 7, 0 );
// Initialize values
QString ntpSrvsFile = QPEApplication::qpeDir();
ntpSrvsFile.append( "etc/ntpservers" );
Config ntpSrvs( ntpSrvsFile, Config::File );
ntpSrvs.setGroup( "servers" );
int srvCount = ntpSrvs.readNumEntry( "count", 0 );
for ( int i = 0; i < srvCount; i++ )
{
ntpSrvs.setGroup( QString::number( i ) );
cbTimeServer->insertItem( ntpSrvs.readEntry( "name" ) );
}
if ( srvCount==0 )
cbTimeServer->insertItem( "time.fu-berlin.de" );
Config config( "ntp" );
config.setGroup( "settings" );
sbPredictDelay->setValue( config.readNumEntry( "minLookupDiff", 720 ) );
sbNtpDelay->setValue( config.readNumEntry( "ntpRefreshFreq", 1440 ) );
cbTimeServer->setCurrentItem( config.readNumEntry( "ntpServer", 0 ) );
chNtpTab->setChecked( config.readBoolEntry( "displayNtpTab", FALSE ) );
chPredictTab->setChecked( config.readBoolEntry( "displayPredictTab", FALSE ) );
}
SettingsTabWidget::~SettingsTabWidget()
{
}
void SettingsTabWidget::saveSettings()
{
int srvCount = cbTimeServer->count();
bool serversChanged = TRUE;
int curSrv = cbTimeServer->currentItem();
QString edit = cbTimeServer->currentText();
for ( int i = 0; i < srvCount; i++ )
{
if ( edit == cbTimeServer->text( i ) )
serversChanged = FALSE;
}
if ( serversChanged )
{
QString ntpSrvsFile = QPEApplication::qpeDir();
ntpSrvsFile.append( "etc/ntpservers" );
Config ntpSrvs( ntpSrvsFile, Config::File );
ntpSrvs.setGroup( "servers" );
ntpSrvs.writeEntry( "count", ++srvCount );
ntpSrvs.setGroup( "0" );
ntpSrvs.writeEntry( "name", edit );
curSrv = 0;
for ( int i = 1; i < srvCount; i++ )
{
-// qDebug( "ntpSrvs[%i/%i]=%s", i, srvCount, cbTimeServer->text( i ).latin1() );
+// odebug << "ntpSrvs[" << i << "/" << srvCount << "]=" << cbTimeServer->text( i ).latin1() << "" << oendl;
ntpSrvs.setGroup( QString::number( i ) );
ntpSrvs.writeEntry( "name", cbTimeServer->text( i-1 ) );
}
}
Config config( "ntp", Config::User );
config.setGroup( "settings" );
config.writeEntry( "ntpServer", curSrv );
config.writeEntry( "minLookupDiff", sbPredictDelay->value() );
config.writeEntry( "ntpRefreshFreq", sbNtpDelay->value() );
config.writeEntry( "displayNtpTab", chNtpTab->isChecked() );
config.writeEntry( "displayPredictTab", chPredictTab->isChecked() );
}
QString SettingsTabWidget::ntpServer()
{
return cbTimeServer->currentText();
}
diff --git a/noncore/settings/networksettings/interfaces/interface.cpp b/noncore/settings/networksettings/interfaces/interface.cpp
index b00b899..d2b106a 100644
--- a/noncore/settings/networksettings/interfaces/interface.cpp
+++ b/noncore/settings/networksettings/interfaces/interface.cpp
@@ -44,259 +44,259 @@ void Interface::setAttached(bool isAttached){
/**
* Set Hardware name
* @param name - the new name
* emit updateInterface
*/
void Interface::setHardwareName(const QString &name){
hardwareName = name;
emit(updateInterface(this));
};
/**
* Set Module owner
* @param owner - the new owner
* emit updateInterface
*/
void Interface::setModuleOwner(Module *owner){
moduleOwner = owner;
emit(updateInterface(this));
};
/**
* Try to start the interface.
*/
void Interface::start(){
// check to see if we are already running.
if(true == status){
emit (updateMessage("Unable to start interface,\n already started"));
return;
}
int ret = system(QString("%1 %2 up").arg(IFCONFIG).arg(this->name()).latin1());
// See if it was successful...
if(ret != 0){
emit (updateMessage("Starting interface failed"));
return;
}
status = true;
refresh();
emit (updateMessage("Start successful"));
}
/**
* Try to stop the interface.
*/
void Interface::stop(){
// check to see if we are already stopped.
if(false == status){
emit (updateMessage("Unable to stop interface,\n already stopped"));
return;
}
int ret = system(QString("%1 %2 down").arg(IFCONFIG).arg(this->name()).latin1());
if(ret != 0){
emit (updateMessage("Stopping interface failed"));
return;
}
status = false;
refresh();
emit (updateMessage("Stop successful"));
}
/**
* Try to restart the interface.
*/
void Interface::restart(){
stop();
start();
}
/**
* Try to refresh the information about the interface.
* First call ifconfig, then check the dhcp-info file
* @return bool true if successful.
*/
bool Interface::refresh(){
// See if we are up.
if(status == false){
macAddress = "";
ip = "0.0.0.0";
subnetMask = "0.0.0.0";
broadcast = "";
dhcp = false;
dhcpServerIp = "";
leaseObtained = "";
leaseExpires = "";
emit(updateInterface(this));
return true;
}
QString fileName = QString("/tmp/%1_ifconfig_info").arg(this->name());
int ret = system(QString("LANG=C %1 %2 > %3").arg(IFCONFIG).arg(this->name()).arg(fileName).latin1());
if(ret != 0){
- qDebug(QString("Interface: Ifconfig return value: %1, is not 0").arg(ret).latin1());
+ odebug << QString("Interface: Ifconfig return value: %1, is not 0").arg(ret).latin1() << oendl;
return false;
}
QFile file(fileName);
if (!file.open(IO_ReadOnly)){
- qDebug(QString("Interface: Can't open file: %1").arg(fileName).latin1());
+ odebug << QString("Interface: Can't open file: %1").arg(fileName).latin1() << oendl;
return false;
}
// Set to the defaults
macAddress = "";
ip = "0.0.0.0";
subnetMask = "0.0.0.0";
broadcast = "";
QTextStream stream( &file );
QString line;
while ( !stream.eof() ) {
line = stream.readLine();
if(line.contains("HWaddr")){
int mac = line.find("HWaddr");
macAddress = line.mid(mac+7, line.length());
}
if(line.contains("inet addr")){
int ipl = line.find("inet addr");
int space = line.find(" ", ipl+10);
ip = line.mid(ipl+10, space-ipl-10);
}
if(line.contains("Mask")){
int mask = line.find("Mask");
subnetMask = line.mid(mask+5, line.length());
}
if(line.contains("Bcast")){
int mask = line.find("Bcast");
int space = line.find(" ", mask+6);
broadcast = line.mid(mask+6, space-mask-6);
}
}
file.close();
QFile::remove(fileName);
// DHCP TESTING
// reset DHCP info
dhcpServerIp = "";
leaseObtained = "";
leaseExpires = "";
dhcp = false;
QString dhcpDirectory(DHCP_INFO_DIR);
QDir d(dhcpDirectory);
if(!d.exists(dhcpDirectory))
dhcpDirectory = "/var/run";
// See if we have
QString dhcpFile(QString(dhcpDirectory+"/dhcpcd-%1.info").arg(this->name()));
// If there is no DHCP information then exit now with no errors.
if(!QFile::exists(dhcpFile)){
emit(updateInterface(this));
return true;
}
file.setName(dhcpFile);
if (!file.open(IO_ReadOnly)){
- qDebug(QString("Interface: Can't open file: %1").arg(dhcpFile).latin1());
+ odebug << QString("Interface: Can't open file: %1").arg(dhcpFile).latin1() << oendl;
return false;
}
// leaseTime and renewalTime and used if pid and deamon exe can be accessed.
int leaseTime = 0;
int renewalTime = 0;
stream.setDevice( &file );
while ( !stream.eof() ) {
line = stream.readLine();
if(line.contains("DHCPSIADDR="))
dhcpServerIp = line.mid(11, line.length());
if(line.contains("LEASETIME="))
leaseTime = line.mid(10, line.length()).toInt();
if(line.contains("RENEWALTIME="))
renewalTime = line.mid(12, line.length()).toInt();
}
file.close();
- //qDebug(QString("Interface: leaseTime: %1").arg(leaseTime).latin1());
- //qDebug(QString("Interface: renewalTime: %1").arg(renewalTime).latin1());
+ //odebug << QString("Interface: leaseTime: %1").arg(leaseTime).latin1() << oendl;
+ //odebug << QString("Interface: renewalTime: %1").arg(renewalTime).latin1() << oendl;
// Get the pid of the deamond
dhcpFile = (QString(dhcpDirectory+"/dhcpcd-%1.pid").arg(this->name()));
file.setName(dhcpFile);
if (!file.open(IO_ReadOnly)){
- qDebug(QString("Interface: Can't open file: %1").arg(dhcpFile).latin1());
+ odebug << QString("Interface: Can't open file: %1").arg(dhcpFile).latin1() << oendl;
return false;
}
int pid = -1;
stream.setDevice( &file );
while ( !stream.eof() ) {
line = stream.readLine();
pid = line.toInt();
}
file.close();
if( pid == -1){
- qDebug("Interface: Could not get pid of dhcpc deamon.");
+ odebug << "Interface: Could not get pid of dhcpc deamon." << oendl;
return false;
}
// Get the start running time of the deamon
fileName = (QString("/proc/%1/stat").arg(pid));
file.setName(fileName);
stream.setDevice( &file );
if (!file.open(IO_ReadOnly)){
- qDebug(QString("Interface: Can't open file: %1").arg(fileName).latin1());
+ odebug << QString("Interface: Can't open file: %1").arg(fileName).latin1() << oendl;
return false;
}
while ( !stream.eof() ) {
line = stream.readLine();
}
file.close();
long time = 0;
// Grab the start time
// pid com state ppid pgrp session tty_nr tpgid flags
sscanf(line.latin1(), "%*d %*s %*c %*d %*d %*d %*d %*d %*u "
// minflt cminflt majflt cmajflt utime stime cutime cstime priority
"%*u %*u %*u %*u %*u %*u %*d %*d %*d "
// nice 0 itrealvalue starttime
"%*d %*d %*d %lu", (long*) &time);
time = time/100;
QDateTime datetime(QDateTime::currentDateTime());
// Get the uptime of the computer.
QFile f("/proc/uptime");
if ( f.open(IO_ReadOnly) ) { // file opened successfully
QTextStream t( &f ); // use a text stream
int sec = 0;
t >> sec;
datetime = datetime.addSecs((-1*sec));
f.close();
}
else{
- qDebug("Interface: Can't open /proc/uptime to retrive uptime.");
+ odebug << "Interface: Can't open /proc/uptime to retrive uptime." << oendl;
return false;
}
datetime = datetime.addSecs(time);
- //qDebug(QString("Interface: %1 %2").arg(datetime.toString()).arg(pid).latin1());
+ //odebug << QString("Interface: %1 %2").arg(datetime.toString()).arg(pid).latin1() << oendl;
// Calculate the start and renew times
leaseObtained = datetime.toString();
// Calculate the start and renew times
datetime = datetime.addSecs(leaseTime);
leaseExpires = datetime.toString();
dhcp = true;
emit(updateInterface(this));
return true;
}
// interface.cpp
diff --git a/noncore/settings/networksettings/interfaces/interfaces.cpp b/noncore/settings/networksettings/interfaces/interfaces.cpp
index 6b161ae..e283926 100644
--- a/noncore/settings/networksettings/interfaces/interfaces.cpp
+++ b/noncore/settings/networksettings/interfaces/interfaces.cpp
@@ -1,712 +1,712 @@
#include "interfaces.h"
#include <qcheckbox.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qregexp.h>
// The three stanza's
#define AUTO "auto"
#define IFACE "iface"
#define MAPPING "mapping"
/**
* Constructor. Reads in the interfaces file and then split the file up by
* the \n for interfaces variable.
* @param useInterfacesFile if an interface file other then the default is
* desired to be used it should be passed in.
*/
Interfaces::Interfaces(QString useInterfacesFile){
acceptedFamily.append(INTERFACES_FAMILY_INET);
acceptedFamily.append(INTERFACES_FAMILY_IPX);
acceptedFamily.append(INTERFACES_FAMILY_INET6);
interfacesFile = useInterfacesFile;
QFile file(interfacesFile);
if (!file.open(IO_ReadOnly)){
- qDebug("Interfaces: Can't open file: %s for reading.", interfacesFile.latin1() );
+ odebug << "Interfaces: Can't open file: " << interfacesFile.latin1() << " for reading." << oendl;
currentIface = interfaces.end();
currentMapping = interfaces.end();
return;
}
QTextStream stream( &file );
QString line;
while ( !stream.eof() ) {
line += stream.readLine();
line += "\n";
}
file.close();
interfaces = QStringList::split("\n", line, true);
currentIface = interfaces.end();
currentMapping = interfaces.end();
}
/**
* Get a list of all interfaces in the interface file. Useful for
* hardware that is not currently connected such as an 802.11b card
* not plugged in, but configured for when it is plugged in.
* @return Return string list of interfaces.
**/
QStringList Interfaces::getInterfaceList(){
QStringList list;
for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) {
QString line = (*it).simplifyWhiteSpace();
if(line.contains(IFACE) && line.at(0) != '#'){
line = line.mid(QString(IFACE).length() +1, line.length());
line = line.simplifyWhiteSpace();
int findSpace = line.find(" ");
if( findSpace >= 0){
line = line.mid(0, findSpace);
list.append(line);
}
}
}
return list;
}
/**
* Find out if interface is in an "auto" group or not.
* Report any duplicates such as eth0 being in two differnt auto's
* @param interface interface to check to see if it is on or not.
* @return true is interface is in auto
*/
bool Interfaces::isAuto(const QString &interface) const {
QStringList autoLines = interfaces.grep(QRegExp(AUTO));
QStringList awi = autoLines.grep(QRegExp(interface));
if(awi.count() > 1)
- qDebug(QString("Interfaces: Found more then auto group with interface: %1.").arg(interface).latin1());
+ odebug << QString("Interfaces: Found more then auto group with interface: %1.").arg(interface).latin1() << oendl;
return awi.count() > 0;
}
/**
* Attempt to set the auto option for interface to setAuto.
* @param interface the interface to set
* @param setAuto the value to set interface to.
* @return false if already set to setAuto.
* */
bool Interfaces::setAuto(const QString &interface, bool setAuto){
// Don't need to set it if it is already set.
if(isAuto(interface) == setAuto)
return false;
bool changed = false;
for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) {
if((*it).contains(AUTO)){
//We know that they are not in any group so let add to this auto.
if(setAuto){
(*it) = (*it) += " " + interface;
// Don't care to have such thins as: auto eth0 lo usb0
(*it) = (*it).simplifyWhiteSpace();
changed = true;
break;
}
// else see if we need to remove from this one
else{
if((*it).contains(interface)){
(*it) = (*it).replace(QRegExp(interface), "");
// if AUTO is the only thing left clear the line
if(((*it).simplifyWhiteSpace()).replace(QRegExp(" "),"") == AUTO)
(*it) = "";
changed = true;
// Don't break because we want to make sure we remove all cases.
}
}
}
}
// In the case where there is no AUTO field add one.
if(!changed && setAuto)
interfaces.append(QString(AUTO" %1").arg(interface));
return true;
}
/**
* Set the current interface to interface. This needs to be done before you
* can call getFamily(), getMethod, and get/setOption().
* @param interface the name of the interface to set. All whitespace is
* removed from the interface name.
* @return bool true if it is successful.
*/
bool Interfaces::setInterface(QString interface){
interface = interface.simplifyWhiteSpace();
interface = interface.replace(QRegExp(" "), "");
return setStanza(IFACE, interface, currentIface);
}
/**
* A quick helper funtion to see if the current interface is set.
* @return bool true if set, false otherwise.
*/
bool Interfaces::isInterfaceSet() const {
return (interfaces.end() != currentIface);
}
/**
* Add a new interface of with the settings - family and method
* @param interface the name of the interface to set. All whitespace is
* removed from the interface name.
* @param family the family of this interface inet or inet, ipx or inet6
* Must of one of the families defined in interfaces.h
* @param method for the family. see interfaces man page for family methods.
* @return true if successful.
*/
bool Interfaces::addInterface(const QString &interface, const QString &family, const QString &method){
- qDebug("Interfaces::addInterface(%s)",interface.latin1());
+ odebug << "Interfaces::addInterface(" << interface.latin1() << ")" << oendl;
if(0 == acceptedFamily.contains(family))
return false;
QString newInterface = interface.simplifyWhiteSpace();
newInterface = newInterface.replace(QRegExp(" "), "");
interfaces.append("");
interfaces.append(QString(IFACE " %1 %2 %3").arg(newInterface).arg(family).arg(method));
return true;
}
/**
* Copies interface with name interface to name newInterface
* @param newInterface name of the new interface.
* @return bool true if successful
*/
bool Interfaces::copyInterface(const QString &interface, const QString &newInterface){
- qDebug("copy interface %s to %s", interface.latin1(), newInterface.latin1());
+ odebug << "copy interface " << interface.latin1() << " to " << newInterface.latin1() << "" << oendl;
if(!setInterface(interface))
return false;
// Store the old interface and bump past the stanza line.
QStringList::Iterator it = currentIface;
it++;
// Add the new interface
bool error;
addInterface(newInterface, getInterfaceFamily(error), getInterfaceMethod(error));
if(!setInterface(newInterface))
return false;
QStringList::Iterator newIface = currentIface;
newIface++;
// Copy all of the lines
for ( ; it != interfaces.end(); ++it ){
if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)))
break;
newIface = interfaces.insert(newIface, *it);
}
return true;
}
/**
* Remove the currently selected interface and all of its options.
* @return bool if successful or not.
*/
bool Interfaces::removeInterface(){
return removeStanza(currentIface);
}
/**
* Gets the hardware name of the interface that is currently selected.
* @return QString name of the hardware interface (eth0, usb2, wlan1...).
* @param error set to true if any error occurs, false otherwise.
*/
QString Interfaces::getInterfaceName(bool &error){
if(currentIface == interfaces.end()){
error = true;
return QString();
}
QString line = (*currentIface);
line = line.mid(QString(IFACE).length() +1, line.length());
line = line.simplifyWhiteSpace();
int findSpace = line.find(" ");
if( findSpace < 0){
error = true;
return QString();
}
error = false;
return line.mid(0, findSpace);
}
/**
* Gets the family name of the interface that is currently selected.
* @return QString name of the family (inet, inet6, ipx).
* @param error set to true if any error occurs, false otherwise.
*/
QString Interfaces::getInterfaceFamily(bool &error){
QString name = getInterfaceName(error);
if(error)
return QString();
QString line = (*currentIface);
line = line.mid(QString(IFACE).length() +1, line.length());
line = line.mid(name.length()+1, line.length());
line = line.simplifyWhiteSpace();
int findSpace = line.find(" ");
if( findSpace < 0){
error = true;
return QString();
}
error = false;
return line.mid(0, findSpace);
}
/**
* Gets the method of the interface that is currently selected.
* @return QString name of the method such as staic or dhcp.
* See the man page of interfaces for possible methods depending on the family.
* @param error set to true if any error occurs, false otherwise.
*/
QString Interfaces::getInterfaceMethod(bool &error){
QString name = getInterfaceName(error);
if(error)
return QString();
QString family = getInterfaceFamily(error);
if(error)
return QString();
QString line = (*currentIface);
line = line.mid(QString(IFACE).length()+1, line.length());
line = line.mid(name.length()+1, line.length());
line = line.mid(family.length()+1, line.length());
line = line.simplifyWhiteSpace();
error = false;
return line;
}
/**
* Sets the interface name to newName.
* @param newName the new name of the interface. All whitespace is removed.
* @return bool true if successful.
*/
bool Interfaces::setInterfaceName(const QString &newName){
- qDebug("setInterfaceName %s", newName.latin1());
+ odebug << "setInterfaceName " << newName.latin1() << "" << oendl;
if(currentIface == interfaces.end())
return false;
QString name = newName.simplifyWhiteSpace();
name = name.replace(QRegExp(" "), "");
bool returnValue = false;
QString tmp = QString("iface %1 %2 %3").arg(name).arg(getInterfaceFamily(returnValue)).arg(getInterfaceMethod(returnValue));
- qDebug("setting %s",tmp.latin1());
+ odebug << "setting " << tmp.latin1() << "" << oendl;
(*currentIface) = tmp;
return !returnValue;
}
/**
* Sets the interface family to newName.
* @param newName the new name of the interface. Must be one of the families
* defined in the interfaces.h file.
* @return bool true if successful.
*/
bool Interfaces::setInterfaceFamily(const QString &newName){
if(currentIface == interfaces.end())
return false;
if(acceptedFamily.contains(newName)==0)
return false;
bool returnValue = false;
(*currentIface) = QString("iface %1 %2 %3").arg(getInterfaceName(returnValue)).arg(newName).arg(getInterfaceMethod(returnValue));
return !returnValue;
}
/**
* Sets the interface method to newName
* @param newName the new name of the interface
* @return bool true if successful.
*/
bool Interfaces::setInterfaceMethod(const QString &newName){
if(currentIface == interfaces.end())
return false;
bool returnValue = false;
(*currentIface) = QString("iface %1 %2 %3").arg(getInterfaceName(returnValue)).arg(getInterfaceFamily(returnValue)).arg(newName);
return !returnValue;
}
/**
* Get a value for an option in the currently selected interface. For example
* calling getInterfaceOption("address") on the following stanza would
* return 192.168.1.1.
* iface eth0 static
* address 192.168.1.1
* @param option the options to get the value.
* @param error set to true if any error occurs, false otherwise.
* @return QString the options value. QString::null if error == true
*/
QString Interfaces::getInterfaceOption(const QString &option, bool &error){
return getOption(currentIface, option, error);
}
/**
* Set a value for an option in the currently selected interface. If option
* doesn't exist then it is added along with the value.
* If value isEmpty() then we will remove the option
*
* @param option the options to set the value.
* @param value the value that option should be set to.
* @param error set to true if any error occurs, false otherwise.
* @return QString the options value. QString::null if error == true
*/
bool Interfaces::setInterfaceOption(const QString &option, const QString &value){
if( value.stripWhiteSpace().isEmpty() )
return removeInterfaceOption( option );
- qDebug("iface >%s< option >%s< value >%s<", (*currentIface).latin1(), option.latin1(),value.latin1());
+ odebug << "iface >" << (*currentIface).latin1() << "< option >" << option.latin1() << "< value >" << value.latin1() << "<" << oendl;
return setOption(currentIface, option, value);
}
/**
* Removes a value for an option in the currently selected interface.
* @param option the options to set the value.
* @param error set to true if any error occurs, false otherwise.
* @return QString the options value. QString::null if error == true
*/
bool Interfaces::removeInterfaceOption(const QString &option){
return removeOption(currentIface, option);
}
/**
* Removes a value for an option in the currently selected interface.
* @param option the options to set the value.
* @param value the value that option should be set to.
* @param error set to true if any error occurs, false otherwise.
* @return QString the options value. QString::null if error == true
*/
bool Interfaces::removeInterfaceOption(const QString &option, const QString &value){
return removeOption(currentIface, option, value);
}
/**
* Removes all of the options from the currently selected interface.
* @return bool error if if successful
*/
bool Interfaces::removeAllInterfaceOptions(){
return removeAllOptions(currentIface);
}
/**
* Set the current map to interface's map. This needs to be done before you
* can call addMapping(), set/getMap(), and get/setScript().
* @param interface the name of the interface to set. All whitespace is
* removed from the interface name.
* @return bool true if it is successful.
*/
bool Interfaces::setMapping(const QString &interface){
QString interfaceName = interface.simplifyWhiteSpace();
interfaceName = interfaceName.replace(QRegExp(" "), "");
return setStanza(MAPPING, interfaceName, currentMapping);
}
/**
* Adds a new Mapping to the interfaces file with interfaces.
* @param interface the name(s) of the interfaces to set to this mapping
*/
void Interfaces::addMapping(const QString &option){
interfaces.append("");
interfaces.append(QString(MAPPING " %1").arg(option));
}
/**
* Remove the currently selected map and all of its options.
* @return bool if successful or not.
*/
bool Interfaces::removeMapping(){
return removeStanza(currentMapping);
}
/**
* Set a map option within a mapping.
* @param map map to use
* @param value value to go with map
* @return bool true if it is successful.
*/
bool Interfaces::setMap(const QString &map, const QString &value){
return setOption(currentMapping, map, value);
}
/**
* Removes a map option within a mapping.
* @param map map to use
* @param value value to go with map
* @return bool true if it is successful.
*/
bool Interfaces::removeMap(const QString &map, const QString &value){
return removeOption(currentMapping, map, value);
}
/**
* Get a map value within a mapping.
* @param map map to get value of
* @param bool true if it is successful.
* @return value that goes to the map
*/
QString Interfaces::getMap(const QString &map, bool &error){
return getOption(currentMapping, map, error);
}
/**
* Sets a script value of the current mapping to argument.
* @param argument the script name.
* @return true if successful.
*/
bool Interfaces::setScript(const QString &argument){
return setOption(currentMapping, "script", argument);
}
/**
* @param error true if could not retrieve the current script argument.
* @return QString the argument of the script for the current mapping.
*/
QString Interfaces::getScript(bool &error){
return getOption(currentMapping, "script", error);
}
/**
* Helper function used to parse through the QStringList and put pointers in
* the correct place.
* @param stanza The stanza (auto, iface, mapping) to look for.
* @param option string that must be in the stanza's main line.
* @param interator interator to place at location of stanza if successful.
* @return bool true if the stanza is found.
*/
bool Interfaces::setStanza(const QString &stanza, const QString &option, QStringList::Iterator &iterator){
bool found = false;
iterator = interfaces.end();
for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) {
QString line = (*it).simplifyWhiteSpace();
if(line.contains(stanza) && line.contains(option) && line.at(0) != '#'){
uint point = line.find(option);
bool valid = true;
if(point > 0){
// There are more chars in the line. check +1
if(line.at(point-1) != ' ')
valid = false;
}
point += option.length();
if(point < line.length()-1){
// There are more chars in the line. check -1
if(line.at(point) != ' ')
valid = false;
}
if(valid){
if(found == true){
- qDebug(QString("Interfaces: Found multiple stanza's for search: %1 %2").arg(stanza).arg(option).latin1());
+ odebug << QString("Interfaces: Found multiple stanza's for search: %1 %2").arg(stanza).arg(option).latin1() << oendl;
}
found = true;
iterator = it;
}
}
}
return found;
}
/**
* Sets a value of an option in a stanza
* @param start the start of the stanza
* @param option the option to use when setting value.
* @return bool true if successful, false otherwise.
*/
bool Interfaces::setOption(const QStringList::Iterator &start, const QString &option, const QString &value){
if(start == interfaces.end())
return false;
- qDebug("setting option");
+ odebug << "setting option" << oendl;
bool found = false;
bool replaced = false;
QStringList::Iterator insertAt = NULL;
for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) {
- qDebug(" Interfaces::setOption got line >%s<",(*it).latin1());
+ odebug << " Interfaces::setOption got line >" << (*it).latin1() << "<" << oendl;
// FIXME: was not completly stupid just wrong sice all options got inserted bevore the iface line
// but since it works with an empty interfaces file I (tille) will not do anything more
if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) ){
if (found) break;
// && it != start){
// if(!found && value != ""){
// // Got to the end of the stanza without finding it, so append it.
-// qDebug(" Got to the end of the stanza without finding it, so append it.");
+// odebug << " Got to the end of the stanza without finding it, so append it." << oendl;
// interfaces.insert(--it, QString("\t%1 %2").arg(option).arg(value));
// }
- qDebug("found 1");
+ odebug << "found 1" << oendl;
// interfaces.insert(++it, QString("\t%1 %2").arg(option).arg(value));
found = true;
insertAt = it;
}
if((*it).contains(option) && it != start && (*it).at(0) != '#'){
// Found it in stanza so replace it.
- qDebug("found 2");
+ odebug << "found 2" << oendl;
if(found)
- qDebug(QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1());
+ odebug << QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1() << oendl;
found = true;
replaced = true;
(*it) = QString("\t%1 %2").arg(option).arg(value);
}
}
if(!found){
- qDebug("! found insert anyway");
+ odebug << "! found insert anyway" << oendl;
QStringList::Iterator p = start;
interfaces.insert(++p, QString("\t%1 %2").arg(option).arg(value));
found = true;
}
if(found && !replaced){
- qDebug("found iface but not the option so insert it here...");
+ odebug << "found iface but not the option so insert it here..." << oendl;
interfaces.insert(++insertAt, QString("\t%1 %2").arg(option).arg(value));
}
return found;
}
/**
* Removes a stanza and all of its options
* @param stanza the stanza to remove
* @return bool true if successful.
*/
bool Interfaces::removeStanza(QStringList::Iterator &stanza){
if(stanza == interfaces.end())
return false;
(*stanza) = "";
return removeAllOptions(stanza);
}
/**
* Removes a option in a stanza
* @param start the start of the stanza
* @param option the option to remove
* @return bool true if successful, false otherwise.
*/
bool Interfaces::removeOption(const QStringList::Iterator &start, const QString &option){
if(start == interfaces.end())
return false;
bool found = false;
for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) {
if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){
// got to the end without finding it
break;
}
if((*it).contains(option) && it != start && (*it).at(0) != '#'){
// Found it in stanza so replace it.
if(found)
- qDebug(QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1());
+ odebug << QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1() << oendl;
found = true;
it = interfaces.remove( it ); // we really want to remove the line
--it; // we do ++it later in the head of the for loop
}
}
return found;
}
/**
* Removes a option in a stanza
* @param start the start of the stanza
* @param option the option to use when setting value.
* @return bool true if successful, false otherwise.
*/
bool Interfaces::removeOption(const QStringList::Iterator &start, const QString &option, const QString &value){
if(start == interfaces.end())
return false;
bool found = false;
for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) {
if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){
// got to the end without finding it
break;
}
if((*it).contains(option) && (*it).contains(value) && it != start && (*it).at(0) != '#'){
// Found it in stanza so replace it.
if(found)
- qDebug(QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1());
+ odebug << QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1() << oendl;
found = true;
it = interfaces.remove( it ); // we really want to remove the line
--it; // we do ++it later in the head of the for loop
}
}
return found;
}
/**
* Removes all options in a stanza
* @param start the start of the stanza
* @return bool true if successful, false otherwise.
*/
bool Interfaces::removeAllOptions(const QStringList::Iterator &start){
if(start == interfaces.end())
return false;
QStringList::Iterator it = start;
it = ++it;
for (; it != interfaces.end(); ++it ) {
if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){
break;
}
it = interfaces.remove(it);
it = --it;
}
// Leave a space between this interface and the next.
interfaces.insert(it, QString(""));
return true;
}
/**
* Gets a value of an option in a stanza
* @param start the start of the stanza
* @param option the option to use when getting the value.
* @param bool true if errors false otherwise.
* @return QString the value of option QString::null() if error == true.
*/
QString Interfaces::getOption(const QStringList::Iterator &start, const QString &option, bool &error){
if(start == interfaces.end()){
error = false;
return QString();
}
QString value;
bool found = false;
for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) {
if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){
break;
}
if((*it).contains(option) && (*it).at(0) != '#'){
if(found)
- qDebug(QString("Interfaces: getOption found more then one value: %1 for option: %2 in stanza %3").arg((*it)).arg(option).arg((*start)).latin1());
+ odebug << QString("Interfaces: getOption found more then one value: %1 for option: %2 in stanza %3").arg((*it)).arg(option).arg((*start)).latin1() << oendl;
found = true;
QString line = (*it).simplifyWhiteSpace();
int space = line.find(" ", option.length());
if(space != -1){
value = line.mid(space+1, line.length());
break;
}
}
}
error = !found;
return value;
}
/**
* Write out the interfaces file to the file passed into the constructor.
* Removes any excess blank lines over 1 line long.
* @return bool true if successful, false if not.
*/
bool Interfaces::write(){
QFile::remove(interfacesFile);
QFile file(interfacesFile);
if (!file.open(IO_ReadWrite)){
- qDebug(QString("Interfaces: Can't open file: %1 for writing.").arg(interfacesFile).latin1());
+ odebug << QString("Interfaces: Can't open file: %1 for writing.").arg(interfacesFile).latin1() << oendl;
return false;
}
QTextStream stream( &file );
int whiteSpaceCount = 0;
for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) {
QString line = (*it).simplifyWhiteSpace();
line = line.replace(QRegExp(" "),"");
if(line.length() == 0)
whiteSpaceCount++;
else
whiteSpaceCount = 0;
if(whiteSpaceCount < 2){
- qDebug((*it).latin1());
+ odebug << (*it).latin1() << oendl;
stream << (*it) << '\n';
}
}
file.close();
return true;
}
// interfaces.cpp
diff --git a/noncore/settings/networksettings/interfaces/interfacesetupimp.cpp b/noncore/settings/networksettings/interfaces/interfacesetupimp.cpp
index 7c2f85c..ec3bad3 100644
--- a/noncore/settings/networksettings/interfaces/interfacesetupimp.cpp
+++ b/noncore/settings/networksettings/interfaces/interfacesetupimp.cpp
@@ -1,208 +1,208 @@
#include "interfacesetupimp.h"
#include "interface.h"
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <opie2/oprocess.h>
#ifdef QWS
#include <opie2/owait.h>
#include <qpe/global.h>
#include <qapplication.h>
#endif
#define DNSSCRIPT "changedns"
/**
* Constuctor. Set up the connection. A profile must be set.
*/
using namespace Opie::Ui;
using namespace Opie::Core;
InterfaceSetupImp::InterfaceSetupImp(QWidget* parent, const char* name, Interface *i, Interfaces *j, WFlags fl) : InterfaceSetup(parent, name, fl), interface(i), interfaces(j), delInterfaces(false){
if (j == 0) {
delInterfaces = true;
interfaces = new Interfaces;
}
}
/**
* Destructor
*/
InterfaceSetupImp::~InterfaceSetupImp(){
if(delInterfaces) {
delete interfaces;
}
}
/**
* Save the current settings, then write out the interfaces file and close.
*/
bool InterfaceSetupImp::saveChanges(){
bool error;
QString iface = interfaces->getInterfaceName(error);
- qDebug("InterfaceSetupImp::saveChanges saves interface %s", iface.latin1() );
+ odebug << "InterfaceSetupImp::saveChanges saves interface " << iface.latin1() << "" << oendl;
if(!saveSettings())
return false;
interfaces->write();
if (interface->getStatus()) {
QString ifup;
ifup += "ifdown ";
ifup += iface;
ifup += "; ifup ";
ifup += iface;
ifup += ";";
OProcess restart;
restart << "sh";
restart << "-c";
restart << ifup;
OWait *owait = new OWait();
Global::statusMessage( tr( "Restarting interface" ) );
owait->show();
qApp->processEvents();
if (!restart.start(OProcess::Block, OProcess::NoCommunication) ) {
- qWarning("unstable to spawn ifdown/ifup");
+ owarn << "unstable to spawn ifdown/ifup" << oendl;
}
owait->hide();
delete owait;
interface->refresh();
}
return true;
}
/**
* Save the settings for the current Interface.
* @return bool true if successful, false otherwise
*/
bool InterfaceSetupImp::saveSettings(){
// eh can't really do anything about it other then return. :-D
if(!interfaces->isInterfaceSet())
return true;
bool error = false;
// Loopback case
if(interfaces->getInterfaceMethod(error) == INTERFACES_LOOPBACK){
interfaces->setAuto(interface->getInterfaceName(), autoStart->isChecked());
return true;
}
if(!dhcpCheckBox->isChecked() && (ipAddressEdit->text().isEmpty() || subnetMaskEdit->text().isEmpty())){
QMessageBox::information(this, "Not Saved.", "Please fill in the IP address and\n subnet entries.", QMessageBox::Ok);
return false;
}
// DHCP
if(dhcpCheckBox->isChecked()) {
interfaces->setInterfaceMethod(INTERFACES_METHOD_DHCP);
interfaces->removeInterfaceOption("address");
interfaces->removeInterfaceOption("netmask");
interfaces->removeInterfaceOption("gateway");
interfaces->removeInterfaceOption("up "DNSSCRIPT" -a ");
interfaces->removeInterfaceOption("down "DNSSCRIPT" -r ");
} else{
interfaces->setInterfaceMethod("static");
interfaces->setInterfaceOption("address", ipAddressEdit->text());
interfaces->setInterfaceOption("netmask", subnetMaskEdit->text());
interfaces->setInterfaceOption("gateway", gatewayEdit->text());
if(!firstDNSLineEdit->text().isEmpty() || !secondDNSLineEdit->text().isEmpty()){
QString dns = firstDNSLineEdit->text() + " " + secondDNSLineEdit->text();
interfaces->setInterfaceOption("up "DNSSCRIPT" -a ", dns);
interfaces->setInterfaceOption("down "DNSSCRIPT" -r ", dns);
}else{
interfaces->removeInterfaceOption("up "DNSSCRIPT" -a ");
interfaces->removeInterfaceOption("down "DNSSCRIPT" -r");
}
}
// IP Information
interfaces->setAuto(interface->getInterfaceName(), autoStart->isChecked());
return true;
}
/**
* The Profile has changed.
* @param QString profile the new profile.
*/
void InterfaceSetupImp::setProfile(const QString &profile){
/*
bool error = false;
if(interfaces->getInterfaceMethod(error) == INTERFACES_LOOPBACK){
staticGroupBox->hide();
dhcpCheckBox->hide();
leaseTime->hide();
leaseHoursLabel->hide();
}
*/
QString newInterfaceName = interface->getInterfaceName();
if(profile.length() > 0)
newInterfaceName += "_" + profile;
// See if we have to make a interface.
if(!interfaces->setInterface(newInterfaceName)){
// Add making for this new interface if need too
if(profile != ""){
interfaces->copyInterface(interface->getInterfaceName(), newInterfaceName);
if(!interfaces->setMapping(interface->getInterfaceName())){
interfaces->addMapping(interface->getInterfaceName());
if(!interfaces->setMapping(interface->getInterfaceName())){
- qDebug("InterfaceSetupImp: Added Mapping, but still can't setInterface.");
+ odebug << "InterfaceSetupImp: Added Mapping, but still can't setInterface." << oendl;
return;
}
}
interfaces->setMap("map", newInterfaceName);
interfaces->setScript("getprofile.sh");
}
else{
interfaces->addInterface(newInterfaceName, INTERFACES_FAMILY_INET, INTERFACES_METHOD_DHCP);
if(!interfaces->setInterface(newInterfaceName)){
- qDebug("InterfaceSetupImp: Added interface, but still can't setInterface.");
+ odebug << "InterfaceSetupImp: Added interface, but still can't setInterface." << oendl;
return;
}
}
}
// We must have a valid interface to get this far so read some settings.
// DHCP
bool error = false;
if(interfaces->getInterfaceMethod(error) == INTERFACES_METHOD_DHCP)
dhcpCheckBox->setChecked(true);
else
dhcpCheckBox->setChecked(false);
// IP Information
autoStart->setChecked(interfaces->isAuto(interface->getInterfaceName()));
QString dns = interfaces->getInterfaceOption("up "DNSSCRIPT" -a", error);
- qDebug("dns >%s<",dns.latin1());
+ odebug << "dns >" << dns.latin1() << "<" << oendl;
if(dns.contains(" ")){
firstDNSLineEdit->setText(dns.mid(0, dns.find(" ")));
secondDNSLineEdit->setText(dns.mid(dns.find(" ")+1, dns.length()));
}else firstDNSLineEdit->setText(dns);
ipAddressEdit->setText(interfaces->getInterfaceOption("address", error));
subnetMaskEdit->setText(interfaces->getInterfaceOption("netmask", error));
if (subnetMaskEdit->text().isEmpty())
subnetMaskEdit->setText( "255.255.255.0" );
gatewayEdit->setText(interfaces->getInterfaceOption("gateway", error));
- qWarning("InterfaceSetupImp::setProfile(%s)\n", profile.latin1());
- qWarning("InterfaceSetupImp::setProfile: iface is %s\n", interfaces->getInterfaceName(error).latin1());
+ owarn << "InterfaceSetupImp::setProfile(" << profile.latin1() << ")\n" << oendl;
+ owarn << "InterfaceSetupImp::setProfile: iface is " << interfaces->getInterfaceName(error).latin1() << "\n" << oendl;
}
// interfacesetup.cpp
diff --git a/noncore/settings/networksettings/mainwindowimp.cpp b/noncore/settings/networksettings/mainwindowimp.cpp
index 1e16b97..3e1a650 100644
--- a/noncore/settings/networksettings/mainwindowimp.cpp
+++ b/noncore/settings/networksettings/mainwindowimp.cpp
@@ -1,748 +1,748 @@
#include "mainwindowimp.h"
#include "addconnectionimp.h"
#include "interfaceinformationimp.h"
#include "interfacesetupimp.h"
#include "interfaces.h"
#include "module.h"
/* OPIE */
#include <qpe/qcopenvelope_qws.h>
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include <qpe/qlibrary.h>
#include <qpe/resource.h>
/* QT */
#include <qpushbutton.h>
#include <qlistbox.h>
#include <qlineedit.h>
#include <qlistview.h>
#include <qheader.h>
#include <qlabel.h>
#include <qtabwidget.h> // in order to disable the profiles tab
#include <qmessagebox.h>
#if QT_VERSION < 300
#include <qlist.h>
#else
#include <qptrlist.h>
#endif
#include <qdir.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qregexp.h>
/* STD */
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#define DEFAULT_SCHEME "/var/lib/pcmcia/scheme"
#define _PROCNETDEV "/proc/net/dev"
MainWindowImp::MainWindowImp(QWidget *parent, const char *name, WFlags) : MainWindow(parent, name, Qt::WStyle_ContextHelp), advancedUserMode(true), scheme(DEFAULT_SCHEME)
{
connect(addConnectionButton, SIGNAL(clicked()), this, SLOT(addClicked()));
connect(removeConnectionButton, SIGNAL(clicked()), this, SLOT(removeClicked()));
connect(informationConnectionButton, SIGNAL(clicked()), this, SLOT(informationClicked()));
connect(configureConnectionButton, SIGNAL(clicked()), this, SLOT(configureClicked()));
connect(newProfileButton, SIGNAL(clicked()), this, SLOT(addProfile()));
connect(removeProfileButton, SIGNAL(clicked()), this, SLOT(removeProfile()));
connect(setCurrentProfileButton, SIGNAL(clicked()), this, SLOT(changeProfile()));
connect(newProfile, SIGNAL(textChanged(const QString&)), this, SLOT(newProfileChanged(const QString&)));
//FIXME: disable profiles for the moment:
tabWidget->setTabEnabled( tab, false );
// Load connections.
// /usr/local/kde/lib/libinterfaces.la
#ifdef QWS
loadModules(QPEApplication::qpeDir() + "plugins/networksettings");
#else
loader = KLibLoader::self();
loadModules(QString("/usr/")+KStandardDirs::kde_default("lib"));
#endif
getAllInterfaces();
Interfaces i;
QStringList list = i.getInterfaceList();
QMap<QString, Interface*>::Iterator it;
for ( QStringList::Iterator ni = list.begin(); ni != list.end(); ++ni )
{
/*
* we skipped it in getAllInterfaces now
* we need to ignore it as well
*/
if (m_handledIfaces.contains( *ni) )
{
- qDebug("Not up iface handled by module");
+ odebug << "Not up iface handled by module" << oendl;
continue;
}
bool found = false;
for( it = interfaceNames.begin(); it != interfaceNames.end(); ++it )
{
if(it.key() == (*ni))
found = true;
}
if(!found)
{
if(!(*ni).contains("_"))
{
Interface *i = new Interface(this, *ni, false);
i->setAttached(false);
i->setHardwareName(tr("Disconnected"));
interfaceNames.insert(i->getInterfaceName(), i);
updateInterface(i);
connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*)));
}
}
}
//getInterfaceList();
connectionList->header()->hide();
Config cfg("NetworkSetup");
profiles = QStringList::split(" ", cfg.readEntry("Profiles", "All"));
for ( QStringList::Iterator it = profiles.begin();
it != profiles.end(); ++it)
profilesList->insertItem((*it));
currentProfileLabel->setText(cfg.readEntry("CurrentProfile", "All"));
advancedUserMode = cfg.readBoolEntry("AdvancedUserMode", false);
scheme = cfg.readEntry("SchemeFile", DEFAULT_SCHEME);
QFile file(scheme);
if ( file.open(IO_ReadOnly) )
{ // file opened successfully
QTextStream stream( &file ); // use a text stream
while ( !stream.eof() )
{ // until end of file...
QString line = stream.readLine(); // line of text excluding '\n'
if(line.contains("SCHEME"))
{
line = line.mid(7, line.length());
currentProfileLabel->setText(line);
break;
}
}
file.close();
}
makeChannel();
}
/**
* Deconstructor. Save profiles. Delete loaded libraries.
*/
MainWindowImp::~MainWindowImp()
{
// Save profiles.
Config cfg("NetworkSetup");
cfg.setGroup("General");
cfg.writeEntry("Profiles", profiles.join(" "));
// Delete all interfaces that don't have owners.
QMap<Interface*, QListViewItem*>::Iterator iIt;
for( iIt = items.begin(); iIt != items.end(); ++iIt )
{
if(iIt.key()->getModuleOwner() == NULL)
delete iIt.key();
}
#ifdef QWS
// Delete Modules and Libraries
QMap<Module*, QLibrary*>::Iterator it;
for( it = libraries.begin(); it != libraries.end(); ++it )
{
delete it.key();
// I wonder why I can't delete the libraries
// What fucking shit this is.
//delete it.data();
}
#else
// klibloader automaticly deletes the libraries for us...
#endif
}
/**
* Query the kernel for all of the interfaces.
*/
void MainWindowImp::getAllInterfaces()
{
int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
if(sockfd == -1)
return;
struct ifreq ifr;
QStringList ifaces;
QFile procFile(QString(_PROCNETDEV));
int result;
Interface *i;
if (! procFile.exists())
{
struct ifreq ifrs[100];
struct ifconf ifc;
ifc.ifc_len = sizeof(ifrs);
ifc.ifc_req = ifrs;
result = ioctl(sockfd, SIOCGIFCONF, &ifc);
for (unsigned int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++)
{
struct ifreq *pifr = &ifrs[i];
ifaces += pifr->ifr_name;
}
}
else
{
procFile.open(IO_ReadOnly);
QString line;
QTextStream procTs(&procFile);
int loc = -1;
procTs.readLine(); // eat a line
procTs.readLine(); // eat a line
while((line = procTs.readLine().simplifyWhiteSpace()) != QString::null)
{
if((loc = line.find(":")) != -1)
{
ifaces += line.left(loc);
}
}
}
for (QStringList::Iterator it = ifaces.begin(); it != ifaces.end(); ++it)
{
int flags = 0;
if ( m_handledIfaces.contains( (*it) ) )
{
- qDebug(" %s is handled by a module", (*it).latin1() );
+ odebug << " " << (*it).latin1() << " is handled by a module" << oendl;
continue;
}
// int family;
i = NULL;
strcpy(ifr.ifr_name, (*it).latin1());
struct ifreq ifcopy;
ifcopy = ifr;
result = ioctl(sockfd, SIOCGIFFLAGS, &ifcopy);
flags = ifcopy.ifr_flags;
i = new Interface(this, ifr.ifr_name, false);
i->setAttached(true);
if ((flags & IFF_UP) == IFF_UP)
i->setStatus(true);
else
i->setStatus(false);
if ((flags & IFF_BROADCAST) == IFF_BROADCAST)
i->setHardwareName("Ethernet");
else if ((flags & IFF_POINTOPOINT) == IFF_POINTOPOINT)
i->setHardwareName("Point to Point");
else if ((flags & IFF_MULTICAST) == IFF_MULTICAST)
i->setHardwareName("Multicast");
else if ((flags & IFF_LOOPBACK) == IFF_LOOPBACK)
i->setHardwareName("Loopback");
else
i->setHardwareName("Unknown");
- qWarning("Adding interface %s to interfaceNames\n", ifr.ifr_name);
+ owarn << "Adding interface " << ifr.ifr_name << " to interfaceNames\n" << oendl;
interfaceNames.insert(i->getInterfaceName(), i);
updateInterface(i);
connect(i, SIGNAL(updateInterface(Interface*)),
this, SLOT(updateInterface(Interface*)));
}
// now lets ask the plugins too ;)
QMap<Module*, QLibrary*>::Iterator it;
QList<Interface> ilist;
for( it = libraries.begin(); it != libraries.end(); ++it )
{
if(it.key())
{
ilist = it.key()->getInterfaces();
for( i = ilist.first(); i != 0; i = ilist.next() )
{
- qWarning("Adding interface %s to interfaceNames\n", i->getInterfaceName().latin1() );
+ owarn << "Adding interface " << i->getInterfaceName().latin1() << " to interfaceNames\n" << oendl;
interfaceNames.insert(i->getInterfaceName(), i);
updateInterface(i);
connect(i, SIGNAL(updateInterface(Interface*)),
this, SLOT(updateInterface(Interface*)));
}
}
}
}
/**
* Load all modules that are found in the path
* @param path a directory that is scaned for any plugins that can be loaded
* and attempts to load them
*/
void MainWindowImp::loadModules(const QString &path)
{
#ifdef DEBUG
- qDebug("MainWindowImp::loadModules: %s", path.latin1());
+ odebug << "MainWindowImp::loadModules: " << path.latin1() << "" << oendl;
#endif
QDir d(path);
if(!d.exists())
return;
// Don't want sym links
d.setFilter( QDir::Files | QDir::NoSymLinks );
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
while ( (fi=it.current()) )
{
#ifdef QWS
if(fi->fileName().contains(".so"))
{
#else
if(fi->fileName().contains(".so") && fi->fileName().contains("networksettings_"))
{
#endif
loadPlugin(path + "/" + fi->fileName());
- qDebug("loaded plugin: >%s< ",QString(path + "/" + fi->fileName()).latin1());
+ odebug << "loaded plugin: >" << QString(path + "/" + fi->fileName()).latin1() << "< " << oendl;
}
++it;
}
}
/**
* Attempt to load a function and resolve a function.
* @param pluginFileName - the name of the file in which to attempt to load
* @param resolveString - function pointer to resolve
* @return pointer to the function with name resolveString or NULL
*/
Module* MainWindowImp::loadPlugin(const QString &pluginFileName, const QString &resolveString)
{
#ifdef DEBUG
- qDebug("MainWindowImp::loadPlugin: %s: resolving %s", pluginFileName.latin1(), resolveString.latin1());
+ odebug << "MainWindowImp::loadPlugin: " << pluginFileName.latin1() << ": resolving " << resolveString.latin1() << "" << oendl;
#endif
#ifdef QWS
QLibrary *lib = new QLibrary(pluginFileName);
void *functionPointer = lib->resolve(resolveString);
if( !functionPointer )
{
#ifdef DEBUG
- qDebug("MainWindowImp::loadPlugin: Warning: %s is not a plugin", pluginFileName.latin1());
+ odebug << "MainWindowImp::loadPlugin: Warning: " << pluginFileName.latin1() << " is not a plugin" << oendl;
#endif
delete lib;
return NULL;
}
// Try to get an object.
Module *object = ((Module* (*)()) functionPointer)();
if(object == NULL)
{
#ifdef DEBUG
- qDebug("MainWindowImp: Couldn't create object, but did load library!");
+ odebug << "MainWindowImp: Couldn't create object, but did load library!" << oendl;
#endif
delete lib;
return NULL;
}
m_handledIfaces += object->handledInterfaceNames();
// Store for deletion later
libraries.insert(object, lib);
return object;
#else
QLibrary *lib = loader->library(pluginFileName);
if( !lib || !lib->hasSymbol(resolveString) )
{
- qDebug(QString("MainWindowImp::loadPlugin: File: %1 is not a plugin, but though was.").arg(pluginFileName).latin1());
+ odebug << QString("MainWindowImp::loadPlugin: File: %1 is not a plugin, but though was.").arg(pluginFileName).latin1() << oendl;
return NULL;
}
// Try to get an object.
Module *object = ((Module* (*)()) lib->symbol(resolveString))();
if(object == NULL)
{
#ifdef DEBUG
- qDebug("MainWindowImp: Couldn't create object, but did load library!");
+ odebug << "MainWindowImp: Couldn't create object, but did load library!" << oendl;
#endif
return NULL;
}
#ifdef DEBUG
- qDebug("MainWindowImp::loadPlugin:: Found object, storing.");
+ odebug << "MainWindowImp::loadPlugin:: Found object, storing." << oendl;
#endif
// Store for deletion later
libraries.insert(object, lib);
return object;
#endif
}
/**
* The Add button was clicked. Bring up the add dialog and if OK is hit
* load the plugin and append it to the list
*/
void MainWindowImp::addClicked()
{
QMap<Module*, QLibrary*>::Iterator it;
QMap<QString, QString> list;
QMap<QString, Module*> newInterfaceOwners;
for( it = libraries.begin(); it != libraries.end(); ++it )
{
if(it.key())
{
(it.key())->possibleNewInterfaces(list);
}
}
// See if the list has anything that we can add.
if(list.count() == 0)
{
QMessageBox::information(this, "Sorry", "Nothing to add.", QMessageBox::Ok);
return;
}
AddConnectionImp addNewConnection(this, "AddConnectionImp", true);
addNewConnection.addConnections(list);
if( QDialog::Accepted == QPEApplication::execDialog( &addNewConnection ) )
{
QListViewItem *item = addNewConnection.registeredServicesList->currentItem();
if(!item)
return;
for( it = libraries.begin(); it != libraries.end(); ++it )
{
if(it.key())
{
Interface *i = (it.key())->addNewInterface(item->text(0));
if(i)
{
- qDebug("iface name %s",i->getInterfaceName().latin1());
+ odebug << "iface name " << i->getInterfaceName().latin1() << "" << oendl;
interfaceNames.insert(i->getInterfaceName(), i);
updateInterface(i);
}
}
}
}
}
/**
* Prompt the user to see if they really want to do this.
* If they do then remove from the list and unload.
*/
void MainWindowImp::removeClicked()
{
QListViewItem *item = connectionList->currentItem();
if(!item)
{
QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok);
return;
}
Interface *i = interfaceItems[item];
if(i->getModuleOwner() == NULL)
{
QMessageBox::information(this, "Can't remove interface.", "Interface is built in.", QMessageBox::Ok);
}
else
{
if(!i->getModuleOwner()->remove(i))
QMessageBox::information(this, tr("Error"), tr("Unable to remove."), QMessageBox::Ok);
else
{
delete item;
// QMessageBox::information(this, "Success", "Interface was removed.", QMessageBox::Ok);
}
}
}
/**
* Pull up the configure about the currently selected interface.
* Report an error if no interface is selected.
* If the interface has a module owner then request its configure.
*/
void MainWindowImp::configureClicked()
{
QListViewItem *item = connectionList->currentItem();
if(!item)
{
QMessageBox::information(this, tr("Sorry"),tr("Please select an interface first."), QMessageBox::Ok);
return;
}
QString currentProfileText = currentProfileLabel->text();
if(currentProfileText.upper() == "ALL");
currentProfileText = "";
Interface *i = interfaceItems[item];
if(i->getModuleOwner())
{
QWidget *moduleConfigure = i->getModuleOwner()->configure(i);
if(moduleConfigure != NULL)
{
i->getModuleOwner()->setProfile(currentProfileText);
QPEApplication::showWidget( moduleConfigure );
return;
}
}
InterfaceSetupImpDialog *configure = new InterfaceSetupImpDialog(this, "InterfaceSetupImp", i, true, Qt::WDestructiveClose | Qt::WStyle_ContextHelp );
configure->setProfile(currentProfileText);
QPEApplication::showDialog( configure );
}
/**
* Pull up the information about the currently selected interface.
* Report an error if no interface is selected.
* If the interface has a module owner then request its configure.
*/
void MainWindowImp::informationClicked()
{
QListViewItem *item = connectionList->currentItem();
if(!item)
{
QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok);
return;
}
Interface *i = interfaceItems[item];
// if(!i->isAttached()){
// QMessageBox::information(this, "Sorry","No information about\na disconnected interface.", QMessageBox::Ok);
// return;
// }
if(i->getModuleOwner())
{
QWidget *moduleInformation = i->getModuleOwner()->information(i);
if(moduleInformation != NULL)
{
QPEApplication::showWidget( moduleInformation );
#ifdef DEBUG
- qDebug("MainWindowImp::informationClicked:: Module owner has created, we showed.");
+ odebug << "MainWindowImp::informationClicked:: Module owner has created, we showed." << oendl;
#endif
return;
}
}
InterfaceInformationImp *information = new InterfaceInformationImp(this, "InterfaceSetupImp", i, Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog | Qt::WStyle_ContextHelp);
QPEApplication::showWidget( information );
}
/**
* Update this interface. If no QListViewItem exists create one.
* @param Interface* pointer to the interface that needs to be updated.
*/
void MainWindowImp::updateInterface(Interface *i)
{
if(!advancedUserMode)
{
if(i->getInterfaceName() == "lo")
return;
}
QListViewItem *item = NULL;
// Find the interface, making it if needed.
if(items.find(i) == items.end())
{
item = new QListViewItem(connectionList, "", "", "");
// See if you can't find a module owner for this interface
QMap<Module*, QLibrary*>::Iterator it;
for( it = libraries.begin(); it != libraries.end(); ++it )
{
if(it.key()->isOwner(i))
i->setModuleOwner(it.key());
}
items.insert(i, item);
interfaceItems.insert(item, i);
}
else
item = items[i];
// Update the icons and information
#ifdef QWS
item->setPixmap(0, (Resource::loadPixmap(i->getStatus() ? "up": "down")));
#else
item->setPixmap(0, (SmallIcon(i->getStatus() ? "up": "down")));
#endif
QString typeName = "lan";
if(i->getInterfaceName() == "lo")
typeName = "lo";
if(i->getInterfaceName().contains("irda"))
typeName = "irda";
if(i->getInterfaceName().contains("wlan"))
typeName = "wlan";
if(i->getInterfaceName().contains("usb"))
typeName = "usb";
if(!i->isAttached())
typeName = "connect_no";
// Actually try to use the Module
if(i->getModuleOwner() != NULL)
typeName = i->getModuleOwner()->getPixmapName(i);
#ifdef QWS
item->setPixmap(1, (Resource::loadPixmap(QString("networksettings/") + typeName)));
#else
item->setPixmap(1, (SmallIcon(typeName)));
#endif
item->setText(2, i->getHardwareName());
item->setText(3, QString("(%1)").arg(i->getInterfaceName()));
item->setText(4, (i->getStatus()) ? i->getIp() : QString(""));
}
void MainWindowImp::newProfileChanged(const QString& newText)
{
if(newText.length() > 0)
newProfileButton->setEnabled(true);
else
newProfileButton->setEnabled(false);
}
/**
* Adds a new profile to the list of profiles.
* Don't add profiles that already exists.
* Appends to the list and QStringList
*/
void MainWindowImp::addProfile()
{
QString newProfileName = newProfile->text();
if(profiles.grep(newProfileName).count() > 0)
{
QMessageBox::information(this, "Can't Add","Profile already exists.", QMessageBox::Ok);
return;
}
profiles.append(newProfileName);
profilesList->insertItem(newProfileName);
}
/**
* Removes the currently selected profile in the combo.
* Doesn't delete if there are less then 2 profiles.
*/
void MainWindowImp::removeProfile()
{
if(profilesList->count() <= 1)
{
QMessageBox::information(this, "Can't remove.","At least one profile\nis needed.", QMessageBox::Ok);
return;
}
QString profileToRemove = profilesList->currentText();
if(profileToRemove == "All")
{
QMessageBox::information(this, "Can't remove.","Can't remove default.", QMessageBox::Ok);
return;
}
// Can't remove the curent profile
if(profileToRemove == currentProfileLabel->text())
{
QMessageBox::information(this, "Can't remove.",QString("%1 is the current profile.").arg(profileToRemove), QMessageBox::Ok);
return;
}
if(QMessageBox::information(this, "Question",QString("Remove profile: %1").arg(profileToRemove), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
{
profiles = QStringList::split(" ", profiles.join(" ").replace(QRegExp(profileToRemove), ""));
profilesList->clear();
for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it)
profilesList->insertItem((*it));
// Remove any interface settings and mappings.
Interfaces interfaces;
// Go through them one by one
QMap<Interface*, QListViewItem*>::Iterator it;
for( it = items.begin(); it != items.end(); ++it )
{
QString interfaceName = it.key()->getInterfaceName();
- qDebug(interfaceName.latin1());
+ odebug << interfaceName.latin1() << oendl;
if(interfaces.setInterface(interfaceName + "_" + profileToRemove))
{
interfaces.removeInterface();
if(interfaces.setMapping(interfaceName))
{
if(profilesList->count() == 1)
interfaces.removeMapping();
else
{
interfaces.removeMap("map", interfaceName + "_" + profileToRemove);
}
}
interfaces.write();
break;
}
}
}
}
/**
* A new profile has been selected, change.
* @param newProfile the new profile.
*/
void MainWindowImp::changeProfile()
{
if(profilesList->currentItem() == -1)
{
QMessageBox::information(this, "Can't Change.","Please select a profile.", QMessageBox::Ok);
return;
}
QString newProfile = profilesList->text(profilesList->currentItem());
if(newProfile != currentProfileLabel->text())
{
currentProfileLabel->setText(newProfile);
QFile::remove(scheme);
QFile file(scheme);
if ( file.open(IO_ReadWrite) )
{
QTextStream stream( &file );
stream << QString("SCHEME=%1").arg(newProfile);
file.close();
}
// restart all up devices?
if(QMessageBox::information(this, "Question","Restart all running interfaces?", QMessageBox::Ok, QMessageBox::No) == QMessageBox::Ok)
{
// Go through them one by one
QMap<Interface*, QListViewItem*>::Iterator it;
for( it = items.begin(); it != items.end(); ++it )
{
if(it.key()->getStatus() == true)
it.key()->restart();
}
}
}
// TODO change the profile in the modules
}
void MainWindowImp::makeChannel()
{
channel = new QCopChannel( "QPE/Application/networksettings", this );
connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
this, SLOT(receive(const QCString&,const QByteArray&)) );
}
void MainWindowImp::receive(const QCString &msg, const QByteArray &arg)
{
bool found = false;
- qDebug("MainWindowImp::receive QCop msg >"+msg+"<");
+ odebug << "MainWindowImp::receive QCop msg >"+msg+"<" << oendl;
if (msg == "raise")
{
raise();
return;
}
QString dest = msg.left(msg.find("("));
QCString param = msg.right(msg.length() - msg.find("(") - 1);
param = param.left( param.length() - 1 );
- qDebug("dest >%s< param >"+param+"<",dest.latin1());
+ odebug << "dest >" << dest.latin1() << "< param >"+param+"<" << oendl;
QMap<Module*, QLibrary*>::Iterator it;
for( it = libraries.begin(); it != libraries.end(); ++it )
{
- qDebug("plugin >%s<", it.key()->type().latin1() );
+ odebug << "plugin >" << it.key()->type().latin1() << "<" << oendl;
if(it.key()->type() == dest)
{
it.key()->receive( param, arg );
found = true;
}
}
if (found) QPEApplication::setKeepRunning();
- else qDebug("Huh what do ya want");
+ else odebug << "Huh what do ya want" << oendl;
}
diff --git a/noncore/settings/networksettings/ppp/accounts.cpp b/noncore/settings/networksettings/ppp/accounts.cpp
index b8a1925a..aedc0b9 100644
--- a/noncore/settings/networksettings/ppp/accounts.cpp
+++ b/noncore/settings/networksettings/ppp/accounts.cpp
@@ -25,193 +25,193 @@
*/
#include "accounts.h"
#include "authwidget.h"
#include "pppdata.h"
#include "edit.h"
/* OPIE */
#include <qpe/qpeapplication.h>
/* QT */
#include <qdir.h>
#include <qlayout.h>
#include <qtabwidget.h>
#include <qtabdialog.h>
#include <qwhatsthis.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include <qbuttongroup.h>
#include <qmessagebox.h>
#include <qvgroupbox.h>
/* STD */
#include <stdlib.h>
void parseargs(char* buf, char** args);
AccountWidget::AccountWidget( PPPData *pd, QWidget *parent, const char *name, WFlags f )
: ChooserWidget( pd, parent, name, f )
{
QWhatsThis::add(edit_b, tr("Allows you to modify the selected account"));
QWhatsThis::add(new_b, tr("Create a new dialup connection\n"
"to the Internet"));
QWhatsThis::add(copy_b,
tr("Makes a copy of the selected account. All\n"
"settings of the selected account are copied\n"
"to a new account, that you can modify to fit your\n"
"needs"));
QWhatsThis::add(delete_b,
tr("<p>Deletes the selected account\n\n"
"<font color=\"red\"><b>Use with care!</b></font>"));
copy_b->setEnabled( false ); //FIXME
// delete_b->setEnabled( false ); //FIXME
listListbox->insertStringList(_pppdata->getAccountList());
for (uint i = 0; i < listListbox->count(); i++)
{
if ( listListbox->text(i) == _pppdata->accname() )
listListbox->setCurrentItem( i );
}
}
void AccountWidget::slotListBoxSelect(int idx)
{
bool ok = _pppdata->setAccount( listListbox->text(idx) );
ok = (bool)(idx != -1);
delete_b->setEnabled(ok);
edit_b->setEnabled(ok);
//FIXME copy_b->setEnabled(ok);
}
void AccountWidget::edit()
{
_pppdata->setAccount(listListbox->text(listListbox->currentItem()));
int result = doTab();
if(result == QDialog::Accepted)
{
listListbox->changeItem(_pppdata->accname(),listListbox->currentItem());
// emit resetaccounts();
_pppdata->save();
}
}
void AccountWidget::create()
{
// if(listListbox->count() == MAX_ACCOUNTS) {
// QMessageBox::information(this, "sorry",
// tr("Maximum number of accounts reached."));
// return;
// }
int result;
if (_pppdata->newaccount() == -1)
{
- qDebug("_pppdata->newaccount() == -1");
+ odebug << "_pppdata->newaccount() == -1" << oendl;
return;
}
result = doTab();
if(result == QDialog::Accepted)
{
listListbox->insertItem(_pppdata->accname());
listListbox->setSelected(listListbox->findItem(_pppdata->accname()),true);
_pppdata->save();
}
else
_pppdata->deleteAccount();
}
void AccountWidget::copy()
{
// if(listListbox->count() == MAX_ACCOUNTS) {
// QMessageBox::information(this, "sorry", tr("Maximum number of accounts reached."));
// return;
// }
if(listListbox->currentItem()<0)
{
QMessageBox::information(this, "sorry", tr("No account selected."));
return;
}
_pppdata->copyaccount(listListbox->currentText());
listListbox->insertItem(_pppdata->accname());
// emit resetaccounts();
_pppdata->save();
}
void AccountWidget::remove()
{
QString s = tr("Are you sure you want to delete\nthe account \"%1\"?")
.arg(listListbox->text(listListbox->currentItem()));
if(QMessageBox::warning(this,tr("Confirm"),s,
QMessageBox::Yes,QMessageBox::No
) != QMessageBox::Yes)
return;
if(_pppdata->deleteAccount(listListbox->text(listListbox->currentItem())))
listListbox->removeItem(listListbox->currentItem());
// emit resetaccounts();
// _pppdata->save();
slotListBoxSelect(listListbox->currentItem());
}
int AccountWidget::doTab()
{
QDialog *dlg = new QDialog( 0, "newAccount", true, Qt::WStyle_ContextHelp );
QVBoxLayout *layout = new QVBoxLayout( dlg );
layout->setSpacing( 0 );
layout->setMargin( 1 );
QTabWidget *tabWindow = new QTabWidget( dlg, "tabWindow" );
layout->addWidget( tabWindow );
bool isnewaccount;
if(_pppdata->accname().isEmpty())
{
dlg->setCaption(tr("New Account"));
isnewaccount = true;
}
else
{
QString tit = tr("Edit Account: ");
tit += _pppdata->accname();
dlg->setCaption(tit);
isnewaccount = false;
}
// // DIAL WIDGET
dial_w = new DialWidget( _pppdata, tabWindow, isnewaccount, "Dial Setup");
tabWindow->addTab( dial_w, tr("Dial") );
// // AUTH WIDGET
auth_w = new AuthWidget( _pppdata, tabWindow, isnewaccount, tr("Edit Login Script"));
tabWindow->addTab( auth_w, tr("Authentication") );
// // IP WIDGET
ip_w = new IPWidget( _pppdata, tabWindow, isnewaccount, tr("IP Setup"));
diff --git a/noncore/settings/networksettings/ppp/authwidget.cpp b/noncore/settings/networksettings/ppp/authwidget.cpp
index fa2b164..f3d842f 100644
--- a/noncore/settings/networksettings/ppp/authwidget.cpp
+++ b/noncore/settings/networksettings/ppp/authwidget.cpp
@@ -49,149 +49,149 @@ AuthWidget::AuthWidget(PPPData *pd, QWidget *parent, bool isnewaccount, const ch
auth->insertItem(tr("Terminal-based"));
auth->insertItem(tr("CHAP"));
auth->insertItem(tr("PAP/CHAP"));
layout->addWidget(auth, 0, 1);
connect( auth, SIGNAL(activated(const QString&)),
SLOT(authChanged(const QString&)));
QString tmp = tr("<p>Specifies the method used to identify yourself to\n"
"the PPP server. Most universities still use\n"
"<b>Terminal</b>- or <b>Script</b>-based authentication,\n"
"while most ISP use <b>PAP</b> and/or <b>CHAP</b>. If\n"
"unsure, contact your ISP.\n"
"\n"
"If you can choose between PAP and CHAP,\n"
"choose CHAP, because it's much safer. If you don't know\n"
"whether PAP or CHAP is right, choose PAP/CHAP.");
QWhatsThis::add(auth_l,tmp);
QWhatsThis::add(auth,tmp);
user_l = new QLabel( tr("Username: "), this);
layout->addWidget( user_l, 1, 0 );
userName = new QLineEdit( this, "usernameEdit" );
layout->addWidget( userName, 1, 1 );
tmp = tr("Enter your username here...");
QWhatsThis::add( user_l, tmp );
QWhatsThis::add( userName, tmp );
pw_l = new QLabel( tr("Password: "), this);
layout->addWidget( pw_l, 2, 0 );
passWord = new QLineEdit( this, "pw" );
passWord->setAutoMask( true );
passWord->setEchoMode( QLineEdit::Password );
layout->addWidget( passWord, 2, 1 );
hidePw = new QToolButton( this );
hidePw->setPixmap( QPixmap( ( const char** ) image0_data ) );
hidePw->setToggleButton( true );
layout->addWidget( hidePw, 2, 2 );
connect(hidePw, SIGNAL(toggled(bool)), SLOT(toggleEchoMode(bool)));
tmp = tr("Enter your password here");
QWhatsThis::add( pw_l, tmp );
QWhatsThis::add( passWord, tmp );
store_password = new QCheckBox(tr("Store password"), this);
layout->addMultiCellWidget(store_password, 3, 3, 0, 1, AlignRight);
QWhatsThis::add(store_password,
tr("<p>When this is turned on, your ISP password\n"
"will be saved in <i>kppp</i>'s config file, so\n"
"you do not need to type it in every time.\n"
"\n"
"<b><font color=\"red\">Warning:</font> your password will be stored as\n"
"plain text in the config file, which is\n"
"readable only to you. Make sure nobody\n"
"gains access to this file!"));
if (isNewAccount){
// select PAP/CHAP as default
auth->setCurrentItem(AUTH_PAPCHAP);
store_password->setChecked(true);
}else{
auth->setCurrentItem(_pppdata->authMethod());
authChanged( auth->currentText() );
userName->setText( _pppdata->storedUsername() );
store_password->setChecked(_pppdata->storePassword());
if (store_password->isChecked())
passWord->setText( _pppdata->storedPassword() );
}
}
bool AuthWidget::check()
{
bool ret = true;
if (scriptWidget){
if (!scriptWidget->check()){
QMessageBox::critical(this, tr("error"), tr("<qt>Login script has unbalanced loop Start/End<qt>"));
ret = false;
}
}
return ret;
}
void AuthWidget::save()
{
_pppdata->setAuthMethod(auth->currentItem());
if (scriptWidget) scriptWidget->save();
_pppdata->setStoredUsername( userName->text() );
_pppdata->setStorePassword(store_password->isChecked());
if (store_password->isChecked())
_pppdata->setStoredPassword( passWord->text() );
}
void AuthWidget::authChanged( const QString &authStr )
{
- qDebug("AuthWidget::authChanged( %s )", authStr.latin1() );
+ odebug << "AuthWidget::authChanged( " << authStr.latin1() << " )" << oendl;
if ( authStr.contains( tr("Script-based") ) ){
showUsernamePassword( false );
showScriptWindow( true );
} else if ( authStr.contains( tr("PAP") ) ||
authStr.contains( tr("CHAP") ) ){
showUsernamePassword( true );
showScriptWindow( false );
} else {
- qDebug("do not really know how to handle");
+ odebug << "do not really know how to handle" << oendl;
showUsernamePassword( false );
showScriptWindow( false );
}
}
void AuthWidget::showUsernamePassword( bool show )
{
if (show){
user_l->show();
userName->show();
pw_l->show();
passWord->show();
store_password->show();
hidePw->show();
}else{//!show
user_l->hide();
userName->hide();
pw_l->hide();
passWord->hide();
store_password->hide();
hidePw->hide();
}
}
void AuthWidget::showScriptWindow( bool show )
{
if (show){
if (!scriptWidget){
scriptWidget = new ScriptWidget( _pppdata, this, isNewAccount, "scriptWid");
layout->addMultiCellWidget( scriptWidget, 1, 4, 0, 1 );
}
scriptWidget->show();
}else{ // !show
if (scriptWidget) scriptWidget->hide();
}
}
void AuthWidget::toggleEchoMode( bool t )
{
passWord->setEchoMode( t ? QLineEdit::Normal : QLineEdit::Password );
}
diff --git a/noncore/settings/networksettings/ppp/connect.cpp b/noncore/settings/networksettings/ppp/connect.cpp
index e3fab24..b75410c 100644
--- a/noncore/settings/networksettings/ppp/connect.cpp
+++ b/noncore/settings/networksettings/ppp/connect.cpp
@@ -379,193 +379,193 @@ void ConnectWidget::timerEvent(QTimerEvent *) {
QString bm = QObject::tr("Dialing %1").arg(bmarg);
messg->setText(bm);
emit debugMessage(bm);
QString pn = _ifaceppp->data()->modemDialStr();
pn += _ifaceppp->data()->dialPrefix();
pn += *plist.at(dialnumber);
if(++dialnumber >= plist.count())
dialnumber = 0;
writeline(pn);
setExpect(_ifaceppp->data()->modemConnectResp());
vmain = 100;
return;
}
}
// wait for connect, but redial if BUSY or wait for user cancel
// if NO CARRIER or NO DIALTONE
if(vmain == 100) {
if(!expecting) {
myreadbuffer = _ifaceppp->data()->modemConnectResp();
setExpect("\n");
vmain = 101;
return;
}
if(readbuffer.contains(_ifaceppp->data()->modemBusyResp())) {
timeout_timer->stop();
timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000);
messg->setText(QObject::tr("Line busy. Hanging up..."));
emit debugPutChar('\n');
_ifaceppp->modem()->hangup();
if(_ifaceppp->data()->busyWait() > 0) {
QString bm = QObject::tr("Line busy. Waiting: %1 seconds").arg(_ifaceppp->data()->busyWait());
messg->setText(bm);
emit debugMessage(bm);
pausing = true;
pausetimer->start(_ifaceppp->data()->busyWait()*1000, true);
timeout_timer->stop();
}
_ifaceppp->modem()->setDataMode(false);
vmain = 0;
substate = -1;
return;
}
if(readbuffer.contains(_ifaceppp->data()->modemNoDialtoneResp())) {
timeout_timer->stop();
messg->setText(QObject::tr("No Dialtone"));
vmain = 20;
_ifaceppp->modem()->unlockdevice();
return;
}
if(readbuffer.contains(_ifaceppp->data()->modemNoCarrierResp())) {
timeout_timer->stop();
messg->setText(QObject::tr("No Carrier"));
vmain = 20;
_ifaceppp->modem()->unlockdevice();
return;
}
}
// wait for newline after CONNECT response (so we get the speed)
if(vmain == 101) {
if(!expecting) {
_ifaceppp->modem()->setDataMode(true); // modem will no longer respond to AT commands
emit startAccounting();
// p_kppp->con_win->startClock();
vmain = 2;
scriptTimeout=_ifaceppp->data()->modemTimeout()*1000;
return;
}
}
// execute the script
if(vmain == 2) {
if(!expecting && !pausing && !scanning) {
timeout_timer->stop();
timeout_timer->start(scriptTimeout);
if((unsigned) scriptindex < comlist->count()) {
scriptCommand = *(comlist->at(scriptindex));
scriptArgument = *(arglist->at(scriptindex));
} else {
- qDebug( "End of script" );
+ odebug << "End of script" << oendl;
vmain = 10;
return;
}
if (scriptCommand == "Scan") {
QString bm = QObject::tr("Scanning %1").arg(scriptArgument);
messg->setText(bm);
emit debugMessage(bm);
setScan(scriptArgument);
scriptindex++;
return;
}
if (scriptCommand == "Save") {
QString bm = QObject::tr("Saving %1").arg(scriptArgument);
messg->setText(bm);
emit debugMessage(bm);
if (scriptArgument.lower() == "password") {
_ifaceppp->data()->setPassword(scanvar);
// p_kppp->setPW_Edit(scanvar);
if(_ifaceppp->data()->storePassword())
_ifaceppp->data()->setStoredPassword(scanvar);
firstrunPW = true;
}
scriptindex++;
return;
}
if (scriptCommand == "Send" || scriptCommand == "SendNoEcho") {
QString bm = QObject::tr("Sending %1");
// replace %USERNAME% and %PASSWORD%
QString arg = scriptArgument;
QRegExp re1("%USERNAME%");
QRegExp re2("%PASSWORD%");
arg = arg.replace(re1, _ifaceppp->data()->storedUsername());
arg = arg.replace(re2, _ifaceppp->data()->storedPassword());
if (scriptCommand == "Send")
bm = bm.arg(scriptArgument);
else {
for(uint i = 0; i < scriptArgument.length(); i++)
bm = bm.arg("*");
}
messg->setText(bm);
emit debugMessage(bm);
writeline(scriptArgument);
scriptindex++;
return;
}
if (scriptCommand == "Expect") {
QString bm = QObject::tr("Expecting %1").arg(scriptArgument);
messg->setText(bm);
emit debugMessage(bm);
// The incrementing of the scriptindex MUST be before the
// call to setExpect otherwise the expect will miss a string that is
// already in the buffer.
scriptindex++;
setExpect(scriptArgument);
return;
}
if (scriptCommand == "Pause") {
QString bm = QObject::tr("Pause %1 seconds").arg(scriptArgument);
messg->setText(bm);
emit debugMessage(bm);
pausing = true;
pausetimer->start(scriptArgument.toInt()*1000, true);
timeout_timer->stop();
scriptindex++;
return;
}
if (scriptCommand == "Timeout") {
timeout_timer->stop();
QString bm = QObject::tr("Timeout %1 seconds").arg(scriptArgument);
messg->setText(bm);
emit debugMessage(bm);
scriptTimeout=scriptArgument.toInt()*1000;
timeout_timer->start(scriptTimeout);
@@ -745,203 +745,203 @@ void ConnectWidget::timerEvent(QTimerEvent *) {
cancelbutton();
QMessageBox::critical(0, "error", QObject::tr("Loops nested too deeply!"));
} else {
setExpect(scriptArgument);
loopstartindex[loopnest] = scriptindex;
loopstr[loopnest] = scriptArgument;
loopend = false;
loopnest++;
}
messg->setText(bm);
emit debugMessage(bm);
}
if (scriptCommand == "LoopEnd") {
QString bm = QObject::tr("Loop End %1").arg(scriptArgument);
if ( loopnest <= 0 ) {
bm = QObject::tr("LoopEnd without matching Start! Line: %1").arg(bm);
vmain=20;
cancelbutton();
QMessageBox::critical(0, "error", bm);
return;
} else {
// NB! The incrementing of the scriptindex MUST be before the
// call to setExpect otherwise the expect will miss a string
// that is already in the buffer.
scriptindex++;
setExpect(scriptArgument);
loopnest--;
loopend = true;
}
messg->setText(bm);
emit debugMessage(bm);
}
}
}
// this is a subroutine for the "Answer" script option
if(vmain == 150) {
if(!expecting) {
writeline(_ifaceppp->data()->modemAnswerStr());
setExpect(_ifaceppp->data()->modemAnswerResp());
vmain = 2;
scriptindex++;
return;
}
}
if(vmain == 30) {
// if (termwindow->isVisible())
// return;
// if (termwindow->pressedContinue())
// vmain = 10;
// else
cancelbutton();
}
if(vmain == 10) {
if(!expecting) {
int result;
timeout_timer->stop();
if_timeout_timer->stop(); // better be sure.
// stop reading of data
_ifaceppp->modem()->stop();
if(_ifaceppp->data()->authMethod() == AUTH_TERMINAL) {
// if (termwindow) {
// delete termwindow;
// termwindow = 0L;
// this->show();
// } else {
// termwindow = new LoginTerm(0L, 0L);
// hide();
// termwindow->show();
// vmain = 30;
// return;
// }
}
// Close the tty. This prevents the QTimer::singleShot() in
// Modem::readtty() from re-enabling the socket notifier.
// The port is still held open by the helper process.
/* Er, there _is_ not QTimer::singleShot() in Modem::readtty(),
and closing the thing prevents pppd from using it later. */
//_ifaceppp->modem()->closetty();
killTimer( main_timer_ID );
if_timeout_timer->start(_ifaceppp->data()->pppdTimeout()*1000);
- qDebug( "started if timeout timer with %i", _ifaceppp->data()->pppdTimeout()*1000);
+ odebug << "started if timeout timer with " << _ifaceppp->data()->pppdTimeout()*1000 << "" << oendl;
// find out PPP interface and notify the stats module
// stats->setUnit(pppInterfaceNumber());
qApp->flushX();
semaphore = true;
result = execppp();
emit debugMessage(QObject::tr("Starting pppd..."));
- qDebug("execppp() returned with return-code %i", result );
+ odebug << "execppp() returned with return-code " << result << "" << oendl;
if(result) {
if(!_ifaceppp->data()->autoDNS())
adddns( _ifaceppp );
// O.K we are done here, let's change over to the if_waiting loop
// where we wait for the ppp if (interface) to come up.
emit if_waiting_signal();
} else {
// starting pppd wasn't successful. Error messages were
// handled by execppp();
if_timeout_timer->stop();
this->hide();
messg->setText("");
// p_kppp->quit_b->setFocus();
// p_kppp->show();
qApp->processEvents();
_ifaceppp->modem()->hangup();
emit stopAccounting();
// p_kppp->con_win->stopClock();
_ifaceppp->modem()->closetty();
_ifaceppp->modem()->unlockdevice();
}
return;
}
}
// this is a "wait until cancel" entry
if(vmain == 20) {
}
}
void ConnectWidget::set_con_speed_string() {
// Here we are trying to determine the speed at which we are connected.
// Usually the modem responds after connect with something like
// CONNECT 115200, so all we need to do is find the number after CONNECT
// or whatever the modemConnectResp() is.
// p_kppp->con_speed = _ifaceppp->modem()->parseModemSpeed(myreadbuffer);
}
void ConnectWidget::readChar(unsigned char c) {
if(semaphore)
return;
readbuffer += c;
myreadbuffer += c;
// While in scanning mode store each char to the scan buffer
// for use in the prompt command
if( scanning )
scanbuffer += c;
// add to debug window
emit debugPutChar(c);
checkBuffers();
}
void ConnectWidget::checkBuffers() {
// Let's check if we are finished with scanning:
// The scanstring have to be in the buffer and the latest character
// was a carriage return or an linefeed (depending on modem setup)
if( scanning && scanbuffer.contains(scanstr) &&
( scanbuffer.right(1) == "\n" || scanbuffer.right(1) == "\r") ) {
scanning = false;
int vstart = scanbuffer.find( scanstr ) + scanstr.length();
scanvar = scanbuffer.mid( vstart, scanbuffer.length() - vstart);
scanvar = scanvar.stripWhiteSpace();
// Show the Variabel content in the debug window
QString sv = QObject::tr("Scan Var: %1").arg(scanvar);
emit debugMessage(sv);
}
if(expecting) {
if(readbuffer.contains(expectstr)) {
expecting = false;
// keep everything after the expected string
readbuffer.remove(0, readbuffer.find(expectstr) + expectstr.length());
QString ts = QObject::tr("Found: %1").arg(expectstr);
emit debugMessage(ts);
if (loopend) {
loopend=false;
}
@@ -971,193 +971,193 @@ void ConnectWidget::pause() {
void ConnectWidget::cancelbutton() {
_ifaceppp->modem()->stop();
killTimer(main_timer_ID);
timeout_timer->stop();
if_timer->stop();
if_timeout_timer->stop();
// if (termwindow) {
// delete termwindow;
// termwindow = 0L;
// this->show();
// }
messg->setText(QObject::tr("One moment please..."));
// just to be sure
_ifaceppp->modem()->removeSecret(AUTH_PAP);
_ifaceppp->modem()->removeSecret(AUTH_CHAP);
removedns(_ifaceppp);
qApp->processEvents();
_ifaceppp->modem()->killPPPDaemon();
_ifaceppp->modem()->hangup();
// p_kppp->quit_b->setFocus();
// p_kppp->show();
// emit stopAccounting(); // just to be sure
// p_kppp->con_win->stopClock();
_ifaceppp->modem()->closetty();
_ifaceppp->modem()->unlockdevice();
//abort prompt window...
if (prompt->isVisible()) {
prompt->hide();
}
prompt->setConsumed();
_ifaceppp->setStatus( false );
_ifaceppp->refresh();
// messg->setText(tr("offline"));
refresh();
}
void ConnectWidget::script_timed_out() {
if(vmain == 20) { // we are in the 'wait for the user to cancel' state
timeout_timer->stop();
emit stopAccounting();
// p_kppp->con_win->stopClock();
return;
}
if (prompt->isVisible())
prompt->hide();
prompt->setConsumed();
messg->setText(QObject::tr("Script timed out!"));
_ifaceppp->modem()->hangup();
emit stopAccounting();
// p_kppp->con_win->stopClock();
vmain = 0; // let's try again.
substate = -1;
}
void ConnectWidget::setScan(const QString &n) {
scanning = true;
scanstr = n;
scanbuffer = "";
QString ts = QObject::tr("Scanning: %1").arg(n);
emit debugMessage(ts);
}
void ConnectWidget::setExpect(const QString &n) {
expecting = true;
expectstr = n;
QString ts = QObject::tr("Expecting: %1").arg(n);
ts.replace(QRegExp("\n"), "<LF>");
emit debugMessage(ts);
// check if the expected string is in the read buffer already.
checkBuffers();
}
void ConnectWidget::if_waiting_timed_out() {
if_timer->stop();
if_timeout_timer->stop();
- qDebug("if_waiting_timed_out()");
+ odebug << "if_waiting_timed_out()" << oendl;
_ifaceppp->data()->setpppdError(E_IF_TIMEOUT);
// let's kill the stuck pppd
_ifaceppp->modem()->killPPPDaemon();
emit stopAccounting();
// p_kppp->con_win->stopClock();
// killing ppp will generate a SIGCHLD which will be caught in pppdie()
// in main.cpp what happens next will depend on the boolean
// reconnect_on_disconnect which is set in ConnectWidget::init();
}
void ConnectWidget::pppdDied()
{
if_timer->stop();
if_timeout_timer->stop();
}
void ConnectWidget::if_waiting_slot() {
messg->setText(QObject::tr("Logging on to network..."));
// if(!stats->ifIsUp()) {
// if(_ifaceppp->data()->pppdError() != 0) {
// // we are here if pppd died immediately after starting it.
// pppdDied();
// // error message handled in main.cpp: sigPPPDDied()
// return;
// }
// if_timer->start(100, TRUE); // single shot
// return;
// }
// O.K the ppp interface is up and running
// give it a few time to come up completly (0.2 seconds)
if_timeout_timer->stop();
if_timer->stop();
usleep(200000);
if(_ifaceppp->data()->autoDNS())
addpeerdns( _ifaceppp );
// Close the debugging window. If we are connected, we
// are not really interested in debug output
emit closeDebugWindow();
// p_kppp->statdlg->take_stats(); // start taking ppp statistics
auto_hostname(_ifaceppp);
if(!_ifaceppp->data()->command_on_connect().isEmpty()) {
messg->setText(QObject::tr("Running startup command..."));
// make sure that we don't get any async errors
qApp->flushX();
execute_command(_ifaceppp->data()->command_on_connect());
messg->setText(QObject::tr("Done"));
}
// remove the authentication file
_ifaceppp->modem()->removeSecret(AUTH_PAP);
_ifaceppp->modem()->removeSecret(AUTH_CHAP);
emit debugMessage(QObject::tr("Done"));
set_con_speed_string();
// p_kppp->con_win->setConnectionSpeed(p_kppp->con_speed);
// this->hide();
// messg->setText("");
_ifaceppp->setStatus( true );
m_refreshTimer = new QTimer( this );
connect( m_refreshTimer, SIGNAL( timeout() ), this, SLOT( refresh() ) );
m_refreshTimer->start( 3000 );
//_ifaceppp->refresh();
// emit _ifaceppp->updateInterface(_ifaceppp);
// prepare the con_win so as to have the right size for
// accounting / non-accounting mode
// if(p_kppp->acct != 0)
// p_kppp->con_win->accounting(p_kppp->acct->running());
// else
// p_kppp->con_win->accounting(false);
// if (_ifaceppp->data()->get_dock_into_panel()) {
// // DockWidget::dock_widget->show();
// // DockWidget::dock_widget->take_stats();
// // this->hide();
// }
// else {
// // p_kppp->con_win->show();
// if(_ifaceppp->data()->get_iconify_on_connect()) {
@@ -1178,193 +1178,193 @@ void ConnectWidget::refresh() {
}
bool ConnectWidget::execppp() {
QString command;
command = "pppd";
// as of version 2.3.6 pppd falls back to the real user rights when
// opening a device given in a command line. To avoid permission conflicts
// we'll simply leave this argument away. pppd will then use the default tty
// which is the serial port we connected stdin/stdout to in opener.cpp.
// command += " ";
// command += _ifaceppp->data()->modemDevice();
command += " " + _ifaceppp->data()->speed();
command += " -detach";
if(_ifaceppp->data()->ipaddr() != "0.0.0.0" ||
_ifaceppp->data()->gateway() != "0.0.0.0") {
if(_ifaceppp->data()->ipaddr() != "0.0.0.0") {
command += " ";
command += _ifaceppp->data()->ipaddr();
command += ":";
}
else {
command += " ";
command += ":";
}
if(_ifaceppp->data()->gateway() != "0.0.0.0")
command += _ifaceppp->data()->gateway();
}
if(_ifaceppp->data()->subnetmask() != "0.0.0.0")
command += " netmask " + _ifaceppp->data()->subnetmask();
if(_ifaceppp->data()->flowcontrol() != "None") {
if(_ifaceppp->data()->flowcontrol() == "CRTSCTS")
command += " crtscts";
else
command += " xonxoff";
}
if(_ifaceppp->data()->defaultroute())
command += " defaultroute";
if(_ifaceppp->data()->autoDNS())
command += " usepeerdns";
// PAP settings
if(_ifaceppp->data()->authMethod() == AUTH_PAP) {
command += " -chap user ";
command = command + _ifaceppp->data()->storedUsername();
}
// CHAP settings
if(_ifaceppp->data()->authMethod() == AUTH_CHAP) {
command += " -pap user ";
command = command + _ifaceppp->data()->storedUsername();
}
// PAP/CHAP settings
if(_ifaceppp->data()->authMethod() == AUTH_PAPCHAP) {
QString tmpName = _ifaceppp->data()->storedUsername();
if ( !tmpName.isEmpty() ) {
command += " user ";
command = command + tmpName;
}
}
// check for debug
if(_ifaceppp->data()->getPPPDebug())
command += " debug";
QStringList &arglist = _ifaceppp->data()->pppdArgument();
for ( QStringList::Iterator it = arglist.begin();
it != arglist.end();
++it )
{
command += " " + *it;
}
command += " call opie-kppp logfd 11";
if (command.length() > MAX_CMDLEN) {
QMessageBox::critical(this, "error", QObject::tr(
"pppd command + command-line arguments exceed "
"2024 characters in length."
));
return false; // nonsensically long command which would bust my buffer buf.
}
- qWarning("Command IS: %s",command.latin1() );
+ owarn << "Command IS: " << command.latin1() << "" << oendl;
qApp->flushX();
return _ifaceppp->modem()->execPPPDaemon(command);
}
void ConnectWidget::closeEvent( QCloseEvent *e ) {
e->ignore();
emit cancelbutton();
}
void ConnectWidget::setMsg(const QString &msg) {
messg->setText(msg);
}
void ConnectWidget::writeline(const QString &s) {
_ifaceppp->modem()->writeLine(s.local8Bit());
}
// Set the hostname and domain from DNS Server
void auto_hostname(InterfacePPP *_ifaceppp) {
struct in_addr local_ip;
struct hostent *hostname_entry;
QString new_hostname;
int dot;
char tmp_str[100]; // buffer overflow safe
gethostname(tmp_str, sizeof(tmp_str));
tmp_str[sizeof(tmp_str)-1]=0; // panic
old_hostname=tmp_str; // copy to QString
// if (!p_kppp->stats->local_ip_address.isEmpty() && _ifaceppp->data()->autoname()) {
if ( _ifaceppp->data()->autoname()) {
// local_ip.s_addr=inet_addr(p_kppp->stats->local_ip_address.ascii());
hostname_entry=gethostbyaddr((const char *)&local_ip,sizeof(in_addr),AF_INET);
if (hostname_entry != 0L) {
new_hostname=hostname_entry->h_name;
dot=new_hostname.find('.');
new_hostname=new_hostname.remove(dot,new_hostname.length()-dot);
_ifaceppp->modem()->setHostname(new_hostname);
modified_hostname = TRUE;
new_hostname=hostname_entry->h_name;
new_hostname.remove(0,dot+1);
add_domain(new_hostname, _ifaceppp);
}
}
}
// Replace the DNS domain entry in the /etc/resolv.conf file and
// disable the nameserver entries if option is enabled
void add_domain(const QString &domain, InterfacePPP *_ifaceppp) {
int fd;
char c;
QString resolv[MAX_RESOLVCONF_LINES];
if (domain.isEmpty())
return;
if((fd = _ifaceppp->modem()->openResolv(O_RDONLY)) >= 0) {
int i=0;
while((read(fd, &c, 1) == 1) && (i < MAX_RESOLVCONF_LINES)) {
if(c == '\n') {
i++;
}
else {
resolv[i] += c;
}
}
close(fd);
if ((c != '\n') && (i < MAX_RESOLVCONF_LINES)) i++;
if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_TRUNC)) >= 0) {
QCString tmp = "domain " + domain.local8Bit() +
" \t\t#kppp temp entry\n";
write(fd, tmp.data(), tmp.length());
for(int j=0; j < i; j++) {
if((resolv[j].contains("domain") ||
( resolv[j].contains("nameserver")
&& !resolv[j].contains("#kppp temp entry")
&& _ifaceppp->data()->exDNSDisabled()))
&& !resolv[j].contains("#entry disabled by kppp")) {
QCString tmp = "# " + resolv[j].local8Bit() +
" \t#entry disabled by kppp\n";
write(fd, tmp, tmp.length());
}
else {
QCString tmp = resolv[j].local8Bit() + "\n";
diff --git a/noncore/settings/networksettings/ppp/devices.cpp b/noncore/settings/networksettings/ppp/devices.cpp
index 9da090d..350ff32 100644
--- a/noncore/settings/networksettings/ppp/devices.cpp
+++ b/noncore/settings/networksettings/ppp/devices.cpp
@@ -1,175 +1,175 @@
/*
* kPPP: A pppd front end for the KDE project
*
* $Id$
*
* Copyright (C) 1997 Bernd Johannes Wuebben
* wuebben@math.cornell.edu
*
* based on EzPPP:
* Copyright (C) 1997 Jay Painter
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "interfaceppp.h"
#include "devices.h"
#include "authwidget.h"
#include "pppdata.h"
#include "edit.h"
#include "general.h"
/* OPIE */
#include <qpe/qpeapplication.h>
/* QT */
#include <qdir.h>
#include <qlayout.h>
#include <qtabwidget.h>
#include <qtabdialog.h>
#include <qwhatsthis.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include <qbuttongroup.h>
#include <qmessagebox.h>
#include <qvgroupbox.h>
/* STD */
#include <stdlib.h>
void parseargs(char* buf, char** args);
DevicesWidget::DevicesWidget( InterfacePPP* ip, QWidget *parent, const char *name, WFlags f )
: ChooserWidget(ip->data(), parent, name, f)
{
_ifaceppp = ip;
QWhatsThis::add(edit_b, tr("Allows you to modify the selected device"));
QWhatsThis::add(new_b, tr("Create a new device") );
QWhatsThis::add(copy_b,
tr("Makes a copy of the selected device. All\n"
"settings of the selected device are copied\n"
"to a new device, that you can modify to fit your\n"
"needs"));
QWhatsThis::add(delete_b,
tr("<p>Deletes the selected device\n\n"
"<font color=\"red\"><b>Use with care!</b></font>"));
copy_b->setEnabled( false ); //FIXME
// delete_b->setEnabled( false ); //FIXME
QStringList tmp = _pppdata->getDevicesNamesList();
- qDebug("DevicesWidget::DevicesWidget got devices %s",tmp.join("--").latin1());
+ odebug << "DevicesWidget::DevicesWidget got devices " << tmp.join("--").latin1() << "" << oendl;
listListbox->insertStringList(tmp);
for (uint i = 0; i < listListbox->count(); i++){
- qDebug("listListbox->text(i) %s == _pppdata->devname() %s",listListbox->text(i).latin1(), _pppdata->devname().latin1());
+ odebug << "listListbox->text(i) " << listListbox->text(i).latin1() << " == _pppdata->devname() " << _pppdata->devname().latin1() << "" << oendl;
if ( listListbox->text(i) == _pppdata->devname() )
listListbox->setCurrentItem( i );
}
}
void DevicesWidget::slotListBoxSelect(int idx) {
bool ok = _pppdata->setDevice( listListbox->text(idx) );
delete_b->setEnabled((bool)(idx != -1));
edit_b->setEnabled((bool)(idx != -1));
//FIXME copy_b->setEnabled((bool)(idx != -1));
}
void DevicesWidget::edit() {
_pppdata->setDevice(listListbox->text(listListbox->currentItem()));
int result = doTab();
if(result == QDialog::Accepted) {
listListbox->changeItem(_pppdata->devname(),listListbox->currentItem());
_pppdata->save();
}
}
void DevicesWidget::create() {
// if(listListbox->count() == MAX_ACCOUNTS) {
// QMessageBox::information(this, "sorry",
// tr("Maximum number of accounts reached."));
// return;
// }
int result;
if (_pppdata->newdevice() == -1){
return;
}
result = doTab();
if(result == QDialog::Accepted) {
listListbox->insertItem(_pppdata->devname());
listListbox->setSelected(listListbox->findItem(_pppdata->devname()),true );
_pppdata->save();
} else
_pppdata->deleteDevice();
}
void DevicesWidget::copy() {
// if(listListbox->count() == MAX_ACCOUNTS) {
// QMessageBox::information(this, "sorry", tr("Maximum number of accounts reached."));
// return;
// }
if(listListbox->currentItem()<0) {
QMessageBox::information(this, "sorry", tr("No devices selected."));
return;
}
_pppdata->copydevice(listListbox->currentText());
listListbox->insertItem(_pppdata->devname());
_pppdata->save();
}
void DevicesWidget::remove() {
QString s = tr("Are you sure you want to delete\nthe device \"%1\"?")
.arg(listListbox->text(listListbox->currentItem()));
if(QMessageBox::warning(this,tr("Confirm"),s,
QMessageBox::Yes,QMessageBox::No
) != QMessageBox::Yes)
return;
if(_pppdata->deleteDevice(listListbox->text(listListbox->currentItem())))
listListbox->removeItem(listListbox->currentItem());
// _pppdata->save();
slotListBoxSelect(listListbox->currentItem());
}
int DevicesWidget::doTab(){
QDialog *dlg = new QDialog( 0, "newDevice", true, Qt::WStyle_ContextHelp );
QVBoxLayout *layout = new QVBoxLayout( dlg );
layout->setSpacing( 0 );
layout->setMargin( 1 );
diff --git a/noncore/settings/networksettings/ppp/general.cpp b/noncore/settings/networksettings/ppp/general.cpp
index 81dab38..69bb682 100644
--- a/noncore/settings/networksettings/ppp/general.cpp
+++ b/noncore/settings/networksettings/ppp/general.cpp
@@ -242,193 +242,193 @@ ModemWidget::ModemWidget( PPPData *pd, QWidget *parent, const char *name )
{
if(_pppdata->enter() == enter->text(i))
enter->setCurrentItem(i);
}
for(int i=0; i <= modemdevice->count()-1; i++)
{
if(_pppdata->modemDevice() == modemdevice->text(i))
modemdevice->setCurrentItem(i);
}
for(int i=0; i <= flowcontrol->count()-1; i++)
{
if(_pppdata->flowcontrol() == flowcontrol->text(i))
flowcontrol->setCurrentItem(i);
}
//set the modem speed
for(int i=0; i < baud_c->count(); i++)
if(baud_c->text(i) == _pppdata->speed())
baud_c->setCurrentItem(i);
tl->setRowStretch(1, 1);
}
ModemWidget::~ModemWidget()
{
QStringList devs;
for (int i=0;i<modemdevice->count();i++)
{
QString s = modemdevice->text(i);
s.simplifyWhiteSpace();
if (! s.isEmpty() ) devs << s;
}
QString edited = modemdevice->currentText();
if ( !( edited ).isEmpty() )
{
edited.simplifyWhiteSpace();
if ( devs.contains( edited ) == 0 )
{
devs << edited;
}
_pppdata->setModemDevice( edited );
}
Config cfg("NetworkSetupPPP");
cfg.setGroup("Devices_General");
cfg.writeEntry("devices",devs,',');
}
// void ModemWidget::speed_selection(int) {
// _pppdata->setSpeed(baud_c->text(baud_c->currentItem()));
// }
// void ModemWidget::setenter(int ) {
// _pppdata->setEnter(enter->text(enter->currentItem()));
// }
// void ModemWidget::setmodemdc(int i) {
// _pppdata->setModemDevice(modemdevice->text(i));
// }
// void ModemWidget::setmodemdc( const QString &string ) {
// _pppdata->setModemDevice( string );
// }
// void ModemWidget::setflowcontrol(int i) {
// _pppdata->setFlowcontrol(flowcontrol->text(i));
// }
// void ModemWidget::modemlockfilechanged(bool set) {
// _pppdata->setModemLockFile(set);
// }
// void ModemWidget::modemtimeoutchanged(int n) {
// _pppdata->setModemTimeout(n);
// }
bool ModemWidget::save()
{
//first check to make sure that the device name is unique!
if(modemname->text().isEmpty() ||
!_pppdata->isUniqueDevname(modemname->text()))
return false;
- qDebug("ModemWidget::save saving modem1 data");
+ odebug << "ModemWidget::save saving modem1 data" << oendl;
_pppdata->setDevname( modemname->text() );
_pppdata->setModemDevice( modemdevice->currentText() );
_pppdata->setFlowcontrol(flowcontrol->currentText());
_pppdata->setFlowcontrol(flowcontrol->currentText());
_pppdata->setSpeed(baud_c->currentText());
_pppdata->setModemLockFile( modemlockfile->isChecked());
_pppdata->setModemTimeout( modemtimeout->value() );
return true;
}
ModemWidget2::ModemWidget2( PPPData *pd, InterfacePPP *ip, QWidget *parent,
const char *name)
: QWidget(parent, name), _pppdata(pd), _ifaceppp(ip)
{
QVBoxLayout *l1 = new QVBoxLayout(this, 0 );//, KDialog::spacingHint());
waitfordt = new QCheckBox(tr("&Wait for dial tone before dialing"), this);
waitfordt->setChecked(_pppdata->waitForDialTone());
// connect(waitfordt, SIGNAL(toggled(bool)), SLOT(waitfordtchanged(bool)));
l1->addWidget(waitfordt);
QWhatsThis::add(waitfordt,
tr("<p>Normally the modem waits for a dial tone\n"
"from your phone line, indicating that it can\n"
"start to dial a number. If your modem does not\n"
"recognize this sound, or your local phone system\n"
"does not emit such a tone, uncheck this option\n"
"\n"
"<b>Default:</b>: On"));
QHBoxLayout *waitLayout = new QHBoxLayout( this );
QLabel *waitLabel = new QLabel( tr("Busy wait:"), this, "busyWait" );
busywait = new QSpinBox( 0, 300, 5, this, "busyWait" );
// busywait = new KIntNumInput(_pppdata->busyWait(), this);
// busywait->setLabel(tr("B&usy wait:"));
// busywait->setRange(0, 300, 5, true);
busywait->setSuffix(tr(" sec"));
// connect(busywait, SIGNAL(valueChanged(int)), SLOT(busywaitchanged(int)));
waitLayout->addWidget(waitLabel);
waitLayout->addWidget(busywait);
l1->addLayout( waitLayout );
QWhatsThis::add(busywait,
tr("Specifies the number of seconds to wait before\n"
"redial if all dialed numbers are busy. This is\n"
"necessary because some modems get stuck if the\n"
"same number is busy too often.\n"
"\n"
"The default is 0 seconds, you should not change\n"
"this unless you need to."));
l1->addSpacing(10);
QHBoxLayout *hbl = new QHBoxLayout;
hbl->setSpacing(2);//KDialog::spacingHint());
QLabel *volumeLabel = new QLabel(tr("Modem &volume:"), this);
hbl->addWidget(volumeLabel);
volume = new QSlider(0, 2, 1, _pppdata->volume(),
QSlider::Horizontal, this);
volumeLabel->setBuddy(volume);
volume->setTickmarks(QSlider::Below);
hbl->addWidget(volume);
l1->addLayout(hbl);
// connect(volume, SIGNAL(valueChanged(int)),
// this, SLOT(volumeChanged(int)));
QString tmp = tr("Most modems have a speaker which makes\n"
"a lot of noise when dialing. Here you can\n"
"either turn this completely off or select a\n"
"lower volume.\n"
"\n"
"If this does not work for your modem,\n"
"you must modify the modem volume command.");
QWhatsThis::add(volumeLabel,tmp);
QWhatsThis::add(volume, tmp);
l1->addSpacing(20);
#if 0
chkbox1 = new QCheckBox(tr("Modem asserts CD line"), this);
chkbox1->setChecked(_pppdata->UseCDLine());
connect(chkbox1,SIGNAL(toggled(bool)),
this,SLOT(use_cdline_toggled(bool)));
l12->addWidget(chkbox1);
l12->addStretch(1);
l1->addStretch(1);
QWhatsThis::add(chkbox1,
tr("This controls how <i>kppp</i> detects that the modem\n"
"is not responding. Unless you are having\n"
"problems with this, do not modify this setting.\n"
"\n"
"<b>Default</b>: Off"));
diff --git a/noncore/settings/networksettings/ppp/interfaceinformationppp.cpp b/noncore/settings/networksettings/ppp/interfaceinformationppp.cpp
index 6b158b9..5a76293 100644
--- a/noncore/settings/networksettings/ppp/interfaceinformationppp.cpp
+++ b/noncore/settings/networksettings/ppp/interfaceinformationppp.cpp
@@ -1,41 +1,41 @@
#include "interfaceinformationppp.h"
#include <qpushbutton.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <qabstractlayout.h>
#include "connect.h"
#include "conwindow.h"
#ifdef QWS
#else
#define showMaximized show
#endif
/**
* Constructor for the InterfaceInformationImp class. This class pretty much
* just display's information about the interface that is passed to it.
*/
InterfaceInformationPPP::InterfaceInformationPPP(QWidget *parent, const char *name, Interface *i, WFlags f)
:InterfaceInformationImp(parent, name, i, Qt::WStyle_ContextHelp)
{
- qDebug("InterfaceInformationPPP::InterfaceInformationPPP %s", name);
+ odebug << "InterfaceInformationPPP::InterfaceInformationPPP " << name << "" << oendl;
con = new ConnectWidget( (InterfacePPP*)i, this, "con" );
con->setSizePolicy( QSizePolicy(QSizePolicy::MinimumExpanding,
QSizePolicy::Fixed) );
macAddressLabel->hide();
subnetMaskLabel->hide();
broadcastLabel->hide();
TextLabel23->hide();
TextLabel21->hide();
TextLabel24->hide();
InterfaceInformationLayout->addWidget( con, 1, 0 );
connect(i, SIGNAL(begin_connect()),con, SLOT(preinit()));
connect(i, SIGNAL(hangup_now() ), con, SLOT(cancelbutton() ) );
}
diff --git a/noncore/settings/networksettings/ppp/interfaceppp.cpp b/noncore/settings/networksettings/ppp/interfaceppp.cpp
index f443f3c..5cc6f70 100644
--- a/noncore/settings/networksettings/ppp/interfaceppp.cpp
+++ b/noncore/settings/networksettings/ppp/interfaceppp.cpp
@@ -1,174 +1,174 @@
#include <qmessagebox.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qlabel.h>
#include "auth.h"
#include "interfaceppp.h"
#include "modem.h"
#include "pppdata.h"
InterfacePPP::InterfacePPP(QObject *parent, const char *name, bool status)
: Interface(parent, name, status),
_modemPtr(0),
_dataPtr(0)
{
- qDebug("InterfacePPP::InterfacePPP(");
+ odebug << "InterfacePPP::InterfacePPP(" << oendl;
}
PPPData* InterfacePPP::data()const
{
if (!_dataPtr){
- qDebug("creating new Data obj");
+ odebug << "creating new Data obj" << oendl;
_dataPtr = new PPPData();
_dataPtr->setDevice( getInterfaceName() );
_dataPtr->setAccount( getHardwareName() );
}
return _dataPtr;
}
Modem* InterfacePPP::modem()const
{
if (!_modemPtr){
- qDebug("creating new modem obj");
+ odebug << "creating new modem obj" << oendl;
_modemPtr = new Modem( data() );
}
return _modemPtr;
}
bool InterfacePPP::refresh()
{
- qDebug("InterfacePPP::refresh()");
+ odebug << "InterfacePPP::refresh()" << oendl;
QString old = getInterfaceName();
setInterfaceName( modem()->pppDevice() );
(void)Interface::refresh();
setInterfaceName( old );
emit updateInterface(this);
return true;
}
void InterfacePPP::start()
{
- qDebug("InterfacePPP::start");
+ odebug << "InterfacePPP::start" << oendl;
if (data()->password().isEmpty() && !data()->storedUsername().isEmpty() ) {
QDialog mb( 0, "Dialog", true );
mb.setCaption( tr( "No password" ) );
QVBoxLayout layout( &mb );
QLabel text ( &mb );
text.setText( tr("Username defined but no password\n Please enter a password") );
QLineEdit lineedit( &mb );
lineedit.setEchoMode( QLineEdit::Password );
layout.addWidget( &text );
layout.addWidget( &lineedit );
if ( mb.exec() == QDialog::Accepted ) {
data()->setPassword( lineedit.text() );
}
}
QFileInfo info(pppdPath());
if(!info.exists()){
QMessageBox::warning(0, tr("Error"),
QObject::tr("<qt>Cannot find the PPP daemon!<br>"
"Make sure that pppd is installed and "
"that you have entered the correct path.</qt>"));
return;
}
//#if 0
if(!info.isExecutable()){
QString string;
string = QObject::tr( "<qt>Cannot execute:<br> %1<br>"
"Please make sure that you have given "
"setuid permission and that "
"pppd is executable.<br>").arg(pppdPath());
QMessageBox::warning(0, tr("Error"), string);
return;
}
//#endif
QFileInfo info2(data()->modemDevice());
if(!info2.exists()){
QString string;
string = QObject::tr( "<qt>Cannot find:<br> %1<br>"
"Please make sure you have setup "
"your modem device properly "
"and/or adjust the location of the modem device on "
"the modem tab of "
"the setup dialog.</qt>").arg(data()->modemDevice());
QMessageBox::warning(0, tr("Error"), string);
return;
}
// if this is a PAP or CHAP account, ensure that username is
// supplied
if(data()->authMethod() == AUTH_PAP ||
data()->authMethod() == AUTH_CHAP ||
data()->authMethod() == AUTH_PAPCHAP ) {
if(false){ //FIXME: ID_Edit->text().isEmpty()) {
QMessageBox::warning(0,tr("Error"),
QObject::tr("<qt>You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!</qt>"));
// FIXME: return;
} else {
if(!modem()->setSecret(data()->authMethod(),
PPPData::encodeWord(data()->storedUsername()),
PPPData::encodeWord(data()->password()))
) {
QString s;
s = QObject::tr("<qt>Cannot create PAP/CHAP authentication<br>"
"file \"%1\"</qt>").arg(PAP_AUTH_FILE);
QMessageBox::warning(0, tr("Error"), s);
return;
}
}
}
if (data()->phonenumber().isEmpty()) {
QString s = QObject::tr("You must specify a telephone number!");
QMessageBox::warning(0, tr("Error"), s);
return;
}
// SEGFAULTS:
// setStatus( true );
// emit updateInterface((Interface*) this);
emit begin_connect();
- qDebug("InterfacePPP::start END");
+ odebug << "InterfacePPP::start END" << oendl;
}
void InterfacePPP::stop()
{
- qDebug("InterfacePPP::stop");
+ odebug << "InterfacePPP::stop" << oendl;
// emit hangup_now();
status = false; // not connected
setStatus( false );
emit hangup_now();
refresh();
}
void InterfacePPP::save()
{
data()->save();
emit updateInterface((Interface*) this);
}
QString InterfacePPP::pppDev()const {
return modem()->pppDevice();
}
pid_t InterfacePPP::pppPID()const{
return modem()->pppPID();
}
void InterfacePPP::setPPPDpid( pid_t pid) {
setStatus( true );
modem()->setPPPDPid( pid );
}
diff --git a/noncore/settings/networksettings/ppp/kpppwidget.cpp b/noncore/settings/networksettings/ppp/kpppwidget.cpp
index e21bbc7..fd09332 100644
--- a/noncore/settings/networksettings/ppp/kpppwidget.cpp
+++ b/noncore/settings/networksettings/ppp/kpppwidget.cpp
@@ -1,179 +1,179 @@
/*
*
* kPPP: A pppd front end for the KDE project
*
* $Id$
*
* Copyright (C) 1997 Bernd Johannes Wuebben
* wuebben@math.cornell.edu
*
* Copyright (C) 1998-2002 Harri Porten <porten@kde.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "kpppwidget.h"
#include <qapplication.h>
#include <qcombobox.h>
#include <qdir.h>
#include <qevent.h>
#include <qdialog.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qregexp.h>
#include <qtabwidget.h>
#include <qdialog.h>
#include <qwhatsthis.h>
#include <qcheckbox.h>
// #include <kaboutdata.h>
// #include <kapplication.h>
#include <qbuttongroup.h>
#include <qmessagebox.h>
#include <qpushbutton.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include "runtests.h"
//#include "main.h"
#include "auth.h"
#include "modem.h"
//#include "ppplog.h"
//#include "opener.h"
//#include "requester.h"
//#include "pppstats.h"
#include "pppdata.h"
#include "general.h"
#include "interface.h"
#define execute_command system
KPPPWidget *p_kppp = 0;
KPPPWidget::KPPPWidget(PPPData*pd, Interface *i, QWidget *parent, const char *name, bool modal, WFlags fl )
: QDialog(parent, name, modal, Qt::WStyle_ContextHelp ), _pppdata(pd)
{
// tabWindow = 0;
p_kppp = this;
// before doing anything else, run a few tests
if (!_pppdata->setModemDevice( i->getInterfaceName() ))
_pppdata->setModemDevice("/dev/modem");
- qDebug("PPPConfigWidget::PPPConfigWidget");
- qDebug(" interface->getHardwareName >%s<", i->getHardwareName().latin1());
+ odebug << "PPPConfigWidget::PPPConfigWidget" << oendl;
+ odebug << " interface->getHardwareName >" << i->getHardwareName().latin1() << "<" << oendl;
if (!_pppdata->setAccount( i->getHardwareName() ))
_pppdata->setAccount( 0 );
- qDebug(" _pppdata->accname >%s<",_pppdata->accname().latin1());
- qDebug(" _pppdata->currentAccountID() >%i<",_pppdata->currentAccountID());
+ odebug << " _pppdata->accname >" << _pppdata->accname().latin1() << "<" << oendl;
+ odebug << " _pppdata->currentAccountID() >" << _pppdata->currentAccountID() << "<" << oendl;
int result = runTests();
if(result == TEST_CRITICAL)
exit(4);
// installEventFilter(this);
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QGridLayout *l1 = new QGridLayout(3, 4);
tl->addLayout(l1);
l1->addColSpacing(0, 10);
l1->addColSpacing(3, 10);
l1->setColStretch(1, 3);
l1->setColStretch(2, 4);
label1 = new QLabel(QObject::tr("C&onnect to: "), this);
l1->addWidget(label1, 0, 1);
connectto_c = new QComboBox(false, this);
label1->setBuddy(connectto_c);
connect(connectto_c, SIGNAL(activated(int)),
SLOT(newdefaultaccount(int)));
l1->addWidget(connectto_c, 0, 2);
ID_Label = new QLabel(QObject::tr("&Login ID:"), this);
l1->addWidget(ID_Label, 1, 1);
// the entry line for usernames
ID_Edit = new QLineEdit(this);
ID_Label->setBuddy(ID_Edit);
l1->addWidget(ID_Edit, 1, 2);
connect(ID_Edit, SIGNAL(returnPressed()),
this, SLOT(enterPressedInID()));
QString tmp = QObject::tr("<p>Type in the username that you got from your\n"
"ISP. This is especially important for PAP\n"
"and CHAP. You may omit this when you use\n"
"terminal-based or script-based authentication.\n"
"\n"
"<b>Important</b>: case is important here:\n"
"<i>myusername</i> is not the same as <i>MyUserName</i>!");
QWhatsThis::add(ID_Label,tmp);
QWhatsThis::add(ID_Edit,tmp);
PW_Label = new QLabel(QObject::tr("&Password:"), this);
l1->addWidget(PW_Label, 2, 1);
PW_Edit= new QLineEdit(this);
PW_Label->setBuddy(PW_Edit);
PW_Edit->setEchoMode(QLineEdit::Password);
l1->addWidget(PW_Edit, 2, 2);
connect(PW_Edit, SIGNAL(returnPressed()),
this, SLOT(enterPressedInPW()));
tmp = QObject::tr("<p>Type in the password that you got from your\n"
"ISP. This is especially important for PAP\n"
"and CHAP. You may omit this when you use\n"
"terminal-based or script-based authentication.\n"
"\n"
"<b>Important</b>: case is important here:\n"
"<i>mypassword</i> is not the same as <i>MyPassword</i>!");
QWhatsThis::add(PW_Label,tmp);
QWhatsThis::add(PW_Edit,tmp);
QHBoxLayout *l3 = new QHBoxLayout;
tl->addSpacing(5);
tl->addLayout(l3);
tl->addSpacing(5);
l3->addSpacing(10);
log = new QCheckBox(QObject::tr("Show lo&g window"), this);
connect(log, SIGNAL(toggled(bool)),
this, SLOT(log_window_toggled(bool)));
log->setChecked(_pppdata->get_show_log_window());
l3->addWidget(log);
QWhatsThis::add(log,
QObject::tr("<p>This controls whether a log window is shown.\n"
"A log window shows the communication between\n"
"<i>kppp</i> and your modem. This will help you\n"
"in tracking down problems.\n"
"\n"
"Turn it off if <i>kppp</i> routinely connects without\n"
"problems"));
// fline = new QSeparator( KSeparator::HLine, this);
// tl->addWidget(fline);
QHBoxLayout *l2 = new QHBoxLayout(this);
tl->addLayout(l2);
int minw = 0;
quit_b = new QPushButton(QObject::tr("&Quit"), this);
// quit_b-> setGuiItem (KGuiItem(QObject::tr("&Quit"), "exit" ) );
@@ -212,399 +212,399 @@ KPPPWidget::KPPPWidget(PPPData*pd, Interface *i, QWidget *parent, const char *na
quit_b->setFixedWidth(minw);
setup_b->setFixedWidth(minw);
// help_b->setFixedWidth(help_b->sizeHint().width());
connect_b->setFixedWidth(minw);
l2->addWidget(quit_b);
l2->addWidget(setup_b);
// l2->addWidget(help_b);
l2->addSpacing(20);
l2->addWidget(connect_b);
setFixedSize(sizeHint());
(void)new Modem(_pppdata);
// we also connect cmld_start to the beginConnect so that I can run
// the dialer through a command line argument
connect(this,SIGNAL(cmdl_start()),this,SLOT(beginConnect()));
// stats = new PPPStats;
// KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());
// constructor of con_win reads position from config file
con_win = new ConWindow(_pppdata, 0, "conw", this);
// KWin::setIcons(con_win->winId(), kapp->icon(), kapp->miniIcon());
// statdlg = new PPPStatsDlg(0, "stats", this, stats);
// statdlg->hide();
// load up the accounts combo box
// resetaccounts();
con = new ConnectWidget(_pppdata, 0, "con");
//KWin::setIcons(con->winId(), kapp->icon(), kapp->miniIcon() );
connect(this, SIGNAL(begin_connect()),con, SLOT(preinit()));
// Is this the best we can do here? it's not right.
// QRect desk = QApplication::desktop()->screenGeometry(
// QApplication::desktop()->screenNumber(topLevelWidget()));
// con->setGeometry(desk.center().x()-175, desk.center().y()-55, 350,110);
// connect the ConnectWidgets various signals
connect(con, SIGNAL(startAccounting()),
this, SLOT(startAccounting()));
connect(con, SIGNAL(stopAccounting()),
this, SLOT(stopAccounting()));
connect(qApp, SIGNAL(saveYourself()),
this, SLOT(saveMyself()));
connect(qApp, SIGNAL(shutDown()),
this, SLOT(shutDown()));
// KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
// m_strCmdlAccount = args->getOption("c");
// m_bQuitOnDisconnect = args->isSet("q");
// if(!m_strCmdlAccount.isEmpty()) {
// m_bCmdlAccount = true;
// kdDebug(5002) << "cmdl_account: " << m_bCmdlAccount << endl;
// }
// if(m_bCmdlAccount){
// bool result = _pppdata->setAccount(m_strCmdlAccount);
// if (!result){
// QString string;
// string = QObject::tr("No such Account:\n%1").arg(m_strCmdlAccount);
// KMessageBox::error(this, string);
// m_bCmdlAccount = false;
// this->show();
// } else {
// beginConnect();
// }
// } else
// expandbutton();
// show();
//#define KPPP_SHOW_NEWS
#ifdef KPPP_SHOW_NEWS
// keep user informed about recent changes
if(!m_bCmdlAccount)
showNews();
#endif
}
KPPPWidget::~KPPPWidget()
{
p_kppp = 0;
// delete stats;
}
// bool KPPPWidget::eventFilter(QObject *o, QEvent *e) {
// if(e->type() == QEvent::User) {
// switch(((SignalEvent*)e)->sigType()) {
// case SIGINT:
-// qDebug( "Received a SIGINT" );
+// odebug << "Received a SIGINT" << oendl;
// interruptConnection();
// break;
// case SIGCHLD:
// sigChld();
// break;
// case SIGUSR1:
// sigPPPDDied();
// break;
// }
// return true;
// }
// if(o == connect_b) {
// if(e->type() == QEvent::KeyPress) {
// if(connect_b->hasFocus() && ((QKeyEvent *)e)->key() == Qt::Key_Return) {
// beginConnect();
// return true;
// }
// }
// }
// return false;
// }
void KPPPWidget::enterPressedInID() {
PW_Edit->setFocus();
}
void KPPPWidget::enterPressedInPW() {
connect_b->setFocus();
}
// triggered by the session manager
void KPPPWidget::saveMyself() {
_pppdata->save();
}
void KPPPWidget::shutDown() {
interruptConnection();
saveMyself();
}
void KPPPWidget::log_window_toggled(bool on) {
_pppdata->set_show_log_window(on);
}
// void KPPPWidget::resetaccounts() {
// connectto_c->clear();
// int count = _pppdata->count();
// // enable/disable controls
// connectto_c->setEnabled(count > 0);
// connect_b->setEnabled(count > 0);
// log->setEnabled(count > 0);
// ID_Edit->setEnabled(count > 0);
// PW_Edit->setEnabled(count > 0);
// //load the accounts
// for(int i=0; i < count; i++) {
// _pppdata->setAccountbyIndex(i);
// connectto_c->insertItem(_pppdata->accname());
// }
// //set the default account
// if(!_pppdata->defaultAccount().isEmpty()) {
// for(int i=0; i < count; i++)
// if(_pppdata->defaultAccount() == connectto_c->text(i)) {
// connectto_c->setCurrentItem(i);
// _pppdata->setAccountbyIndex(i);
// ID_Edit->setText(_pppdata->storedUsername());
// PW_Edit->setText(_pppdata->storedPassword());
// }
// }
// else
// if(count > 0) {
// _pppdata->setDefaultAccount(connectto_c->text(0));
// _pppdata->save();
// ID_Edit->setText(_pppdata->storedUsername());
// PW_Edit->setText(_pppdata->storedPassword());
// }
// connect(ID_Edit, SIGNAL(textChanged(const QString&)),
// this, SLOT(usernameChanged(const QString&)));
// connect(PW_Edit, SIGNAL(textChanged(const QString&)),
// this, SLOT(passwordChanged(const QString&)));
// if (ID_Edit->text().isEmpty())
// ID_Edit->setFocus();
// else if (PW_Edit->text().isEmpty())
// PW_Edit->setFocus();
// }
void KPPPWidget::interruptConnection() {
// interrupt dial up
//
if (con->isVisible())
emit con->cancelbutton();
// disconnect if online
if (_pppdata->pppdRunning())
emit disconnect();
}
void KPPPWidget::sigPPPDDied() {
- qDebug( "Received a SIGUSR1" );
+ odebug << "Received a SIGUSR1" << oendl;
// if we are not connected pppdpid is -1 so have have to check for that
// in the followin line to make sure that we don't raise a false alarm
// such as would be the case when the log file viewer exits.
if(_pppdata->pppdRunning() || _pppdata->pppdError()) {
- qDebug( "It was pppd that died" );
+ odebug << "It was pppd that died" << oendl;
// when we killpppd() on Cancel in ConnectWidget
// we set pppid to -1 so we won't
// enter this block
// just to be sure
Modem::modem->removeSecret(AUTH_PAP);
Modem::modem->removeSecret(AUTH_CHAP);
_pppdata->setpppdRunning(false);
- qDebug( "Executing command on disconnect since pppd has died." );
+ odebug << "Executing command on disconnect since pppd has died." << oendl;
QApplication::flushX();
execute_command(_pppdata->command_on_disconnect());
// stopAccounting();
con_win->stopClock();
// DockWidget::dock_widget->stop_stats();
// DockWidget::dock_widget->hide();
if(!_pppdata->pppdError())
_pppdata->setpppdError(E_PPPD_DIED);
removedns();
Modem::modem->unlockdevice();
//
con->pppdDied();
if(!_pppdata->automatic_redial()) {
quit_b->setFocus();
show();
con_win->stopClock();
// stopAccounting();
con_win->hide();
con->hide();
_pppdata->setpppdRunning(false);
// // not in a signal handler !!! KNotifyClient::beep();
QString msg;
if (_pppdata->pppdError() == E_IF_TIMEOUT)
msg = QObject::tr("Timeout expired while waiting for the PPP interface "
"to come up!");
else {
msg = QObject::tr("<p>The pppd daemon died unexpectedly!</p>");
Modem::modem->pppdExitStatus();
if (Modem::modem->lastStatus != 99) { // more recent pppds only
msg += QObject::tr("<p>Exit status: %1").arg(Modem::modem->lastStatus);
msg += QObject::tr("</p><p>See 'man pppd' for an explanation of the error "
"codes or take a look at the kppp FAQ on "
" <a href=http://devel-home.kde.org/~kppp/index.html>"
"http://devel-home.kde.org/~kppp/index.html</a></p>");
}
}
// if(QMessageBox::warning(0, msg, QObject::tr("Error"), QObject::tr("&OK"), QObject::tr("&Details...")) == QMessageBox::No)
// // PPPL_ShowLog();
// } else { /* reconnect on disconnect */
if (false){
- qDebug( "Trying to reconnect... " );
+ odebug << "Trying to reconnect... " << oendl;
if(_pppdata->authMethod() == AUTH_PAP ||
_pppdata->authMethod() == AUTH_CHAP ||
_pppdata->authMethod() == AUTH_PAPCHAP)
Modem::modem->setSecret(_pppdata->authMethod(),
encodeWord(_pppdata->storedUsername()),
encodeWord(_pppdata->password()));
con_win->hide();
con_win->stopClock();
// stopAccounting();
_pppdata->setpppdRunning(false);
// not in a signal handler !!! KNotifyClient::beep();
emit cmdl_start();
}
}
_pppdata->setpppdError(0);
}
}
// void KPPPWidget::sigChld() {
-// qDebug( "sigchld()" );
+// odebug << "sigchld()" << oendl;
// // pid_t id = wait(0L);
// // if(id == helperPid && helperPid != -1) {
// // kdDebug(5002) << "It was the setuid child that died" << endl;
// // helperPid = -1;
// QString msg = QObject::tr("kppp's helper process just died.\n"
// "Since a further execution would be pointless, "
// "kppp will shut down now.");
// QMessageBox::warning(0L,"error", msg);
// //remove_pidfile();
// exit(1);
// // }
// }
void KPPPWidget::newdefaultaccount(int i) {
_pppdata->setDefaultAccount(connectto_c->text(i));
_pppdata->save();
ID_Edit->setText(_pppdata->storedUsername());
PW_Edit->setText(_pppdata->storedPassword());
}
void KPPPWidget::beginConnect() {
// make sure to connect to the account that is selected in the combo box
// (exeption: an account given by a command line argument)
// if(!m_bCmdlAccount) {
// _pppdata->setAccount(connectto_c->currentText());
// _pppdata->setPassword(PW_Edit->text());
// } else {
_pppdata->setPassword(_pppdata->storedPassword());
// }
QFileInfo info(pppdPath());
if(!info.exists()){
QMessageBox::warning(this, "error", QObject::tr("Cannot find the PPP daemon!\n"
"Make sure that pppd is installed and "
"that you have entered the correct path."));
return;
}
#if 0
if(!info.isExecutable()){
QString string;
string = QObject::tr("kppp cannot execute:\n %1\n"
"Please make sure that you have given kppp "
"setuid permission and that "
"pppd is executable.").arg(_pppdata->pppdPath());
KMessageBox::error(this, string);
return;
}
#endif
QFileInfo info2(_pppdata->modemDevice());
if(!info2.exists()){
QString string;
string = QObject::tr("kppp can not find:\n %1\nPlease make sure you have setup "
"your modem device properly "
"and/or adjust the location of the modem device on "
"the modem tab of "
"the setup dialog.").arg(_pppdata->modemDevice());
QMessageBox::warning(this, "error", string);
return;
}
// if this is a PAP or CHAP account, ensure that username is
// supplied
if(_pppdata->authMethod() == AUTH_PAP ||
_pppdata->authMethod() == AUTH_CHAP ||
_pppdata->authMethod() == AUTH_PAPCHAP ) {
if(ID_Edit->text().isEmpty()) {
QMessageBox::warning(this,"error",
QObject::tr("You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!"));
return;
} else {
if(!Modem::modem->setSecret(_pppdata->authMethod(),
encodeWord(_pppdata->storedUsername()),
encodeWord(_pppdata->password()))) {
QString s;
s = QObject::tr("Cannot create PAP/CHAP authentication\n"
"file \"%1\"").arg(PAP_AUTH_FILE);
QMessageBox::warning(this, "error", s);
return;
}
}
}
if (_pppdata->phonenumber().isEmpty()) {
QString s = QObject::tr("You must specify a telephone number!");
QMessageBox::warning(this, "error", s);
return;
}
diff --git a/noncore/settings/networksettings/ppp/modem.cpp b/noncore/settings/networksettings/ppp/modem.cpp
index 3dbc8c3..f3f2639 100644
--- a/noncore/settings/networksettings/ppp/modem.cpp
+++ b/noncore/settings/networksettings/ppp/modem.cpp
@@ -1,765 +1,765 @@
/*
* kPPP: A pppd Front End for the KDE project
*
* $Id$
*
* Copyright (C) 1997 Bernd Johannes Wuebben
* wuebben@math.cornell.edu
*
* This file was added by Harri Porten <porten@tu-harburg.de>
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <setjmp.h>
#include <regex.h>
#include <qregexp.h>
#include <assert.h>
#include <string.h>
#ifdef HAVE_RESOLV_H
# include <arpa/nameser.h>
# include <resolv.h>
#endif
#ifndef _PATH_RESCONF
#define _PATH_RESCONF "/etc/resolv.conf"
#endif
#define strlcpy strcpy
#include "auth.h"
#include "modem.h"
#include "pppdata.h"
#define qError qDebug
#define MY_ASSERT(x) if (!(x)) { \
- qFatal( "ASSERT: \"%s\" in %s (%d)\n",#x,__FILE__,__LINE__); \
+ ofatal << "ASSERT: \"" << #x << "\" in " << __FILE__ << " (" << __LINE__ << ")\n" << oendl; \
exit(1); }
static sigjmp_buf jmp_buffer;
//Modem *Modem::modem = 0;
const char* pppdPath() {
// wasting a few bytes
static char buffer[sizeof(PPPDSEARCHPATH)+sizeof(PPPDNAME)];
static char *pppdPath = 0L;
char *p;
if(pppdPath == 0L) {
const char *c = PPPDSEARCHPATH;
while(*c != '\0') {
while(*c == ':')
c++;
p = buffer;
while(*c != '\0' && *c != ':')
*p++ = *c++;
*p = '\0';
strcat(p, "/");
strcat(p, PPPDNAME);
if(access(buffer, F_OK) == 0)
return (pppdPath = buffer);
}
}
return pppdPath;
}
Modem::Modem( PPPData* pd )
{
_pppdata = pd;
modemfd = -1;
_pppdExitStatus = -1;
pppdPid = -1;
sn = m_modemDebug = 0L;
data_mode = false;
modem_is_locked = false;
lockfile[0] = '\0';
device = "/dev/modem";
}
Modem::~Modem()
{
}
speed_t Modem::modemspeed() {
// convert the string modem speed int the gpppdata object to a t_speed type
// to set the modem. The constants here should all be ifdef'd because
// other systems may not have them
int i = _pppdata->speed().toInt()/100;
switch(i) {
case 24:
return B2400;
break;
case 96:
return B9600;
break;
case 192:
return B19200;
break;
case 384:
return B38400;
break;
#ifdef B57600
case 576:
return B57600;
break;
#endif
#ifdef B115200
case 1152:
return B115200;
break;
#endif
#ifdef B230400
case 2304:
return B230400;
break;
#endif
#ifdef B460800
case 4608:
return B460800;
break;
#endif
default:
return B38400;
break;
}
}
bool Modem::opentty() {
// int flags;
//begin if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) {
close(modemfd);
device = _pppdata->modemDevice();
if ((modemfd = open(device, O_RDWR|O_NDELAY|O_NOCTTY)) == -1) {
- qDebug("error opening modem device !");
+ odebug << "error opening modem device !" << oendl;
errmsg = QObject::tr("Unable to open modem.");
return false;
}
//bend if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) {
//}
#if 0
if(_pppdata->UseCDLine()) {
if(ioctl(modemfd, TIOCMGET, &flags) == -1) {
errmsg = QObject::tr("Unable to detect state of CD line.");
::close(modemfd);
modemfd = -1;
return false;
}
if ((flags&TIOCM_CD) == 0) {
errmsg = QObject::tr("The modem is not ready.");
::close(modemfd);
modemfd = -1;
return false;
}
}
#endif
tcdrain (modemfd);
tcflush (modemfd, TCIOFLUSH);
if(tcgetattr(modemfd, &tty) < 0){
// this helps in some cases
tcsendbreak(modemfd, 0);
sleep(1);
if(tcgetattr(modemfd, &tty) < 0){
errmsg = QObject::tr("The modem is busy.");
::close(modemfd);
modemfd = -1;
return false;
}
}
memset(&initial_tty,'\0',sizeof(initial_tty));
initial_tty = tty;
tty.c_cc[VMIN] = 0; // nonblocking
tty.c_cc[VTIME] = 0;
tty.c_oflag = 0;
tty.c_lflag = 0;
tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB);
tty.c_cflag |= CS8 | CREAD;
tty.c_cflag |= CLOCAL; // ignore modem status lines
tty.c_iflag = IGNBRK | IGNPAR /* | ISTRIP */ ;
tty.c_lflag &= ~ICANON; // non-canonical mode
tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE);
if(_pppdata->flowcontrol() != "None") {
if(_pppdata->flowcontrol() == "CRTSCTS") {
tty.c_cflag |= CRTSCTS;
}
else {
tty.c_iflag |= IXON | IXOFF;
tty.c_cc[VSTOP] = 0x13; /* DC3 = XOFF = ^S */
tty.c_cc[VSTART] = 0x11; /* DC1 = XON = ^Q */
}
}
else {
tty.c_cflag &= ~CRTSCTS;
tty.c_iflag &= ~(IXON | IXOFF);
}
cfsetospeed(&tty, modemspeed());
cfsetispeed(&tty, modemspeed());
tcdrain(modemfd);
if(tcsetattr(modemfd, TCSANOW, &tty) < 0){
errmsg = QObject::tr("The modem is busy.");
::close(modemfd);
modemfd=-1;
return false;
}
errmsg = QObject::tr("Modem Ready.");
return true;
}
bool Modem::closetty() {
if(modemfd >=0 ) {
stop();
/* discard data not read or transmitted */
tcflush(modemfd, TCIOFLUSH);
if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){
errmsg = QObject::tr("Can't restore tty settings: tcsetattr()\n");
::close(modemfd);
modemfd = -1;
return false;
}
::close(modemfd);
modemfd = -1;
}
return true;
}
void Modem::readtty(int) {
char buffer[200];
unsigned char c;
int len;
// read data in chunks of up to 200 bytes
if((len = ::read(modemfd, buffer, 200)) > 0) {
// split buffer into single characters for further processing
for(int i = 0; i < len; i++) {
c = buffer[i] & 0x7F;
emit charWaiting(c);
}
}
}
void Modem::notify(const QObject *receiver, const char *member) {
connect(this, SIGNAL(charWaiting(unsigned char)), receiver, member);
startNotifier();
}
void Modem::stop() {
disconnect(SIGNAL(charWaiting(unsigned char)));
stopNotifier();
}
void Modem::startNotifier() {
if(modemfd >= 0) {
if(sn == 0) {
sn = new QSocketNotifier(modemfd, QSocketNotifier::Read, this);
connect(sn, SIGNAL(activated(int)), SLOT(readtty(int)));
- qDebug("QSocketNotifier started!");
+ odebug << "QSocketNotifier started!" << oendl;
} else {
- qDebug("QSocketNotifier re-enabled!");
+ odebug << "QSocketNotifier re-enabled!" << oendl;
sn->setEnabled(true);
}
}
}
void Modem::stopNotifier() {
if(sn != 0) {
sn->setEnabled(false);
disconnect(sn);
delete sn;
sn = 0;
- qDebug( "QSocketNotifier stopped!" );
+ odebug << "QSocketNotifier stopped!" << oendl;
}
}
void Modem::flush() {
char c;
while(read(modemfd, &c, 1) == 1);
}
bool Modem::writeChar(unsigned char c) {
int s;
do {
s = write(modemfd, &c, 1);
if (s < 0) {
- qError( "write() in Modem::writeChar failed" );
+ oerr << "write() in Modem::writeChar failed" << oendl;
return false;
}
} while(s == 0);
return true;
}
bool Modem::writeLine(const char *buf) {
int len = strlen(buf);
char *b = new char[len+2];
memcpy(b, buf, len);
// different modems seem to need different line terminations
QString term = _pppdata->enter();
if(term == "LF")
b[len++]='\n';
else if(term == "CR")
b[len++]='\r';
else if(term == "CR/LF") {
b[len++]='\r';
b[len++]='\n';
}
int l = len;
while(l) {
int wr = write(modemfd, &b[len-l], l);
if(wr < 0) {
// TODO do something meaningful with the error code (or ignore it
- qError( "write() in Modem::writeLine failed" );
+ oerr << "write() in Modem::writeLine failed" << oendl;
delete[] b;
return false;
}
l -= wr;
}
delete[] b;
return true;
}
bool Modem::hangup() {
// this should really get the modem to hang up and go into command mode
// If anyone sees a fault in the following please let me know, since
// this is probably the most imporant snippet of code in the whole of
// kppp. If people complain about kppp being stuck, this piece of code
// is most likely the reason.
struct termios temptty;
if(modemfd >= 0) {
// is this Escape & HangupStr stuff really necessary ? (Harri)
if (data_mode) escape_to_command_mode();
// Then hangup command
writeLine(_pppdata->modemHangupStr().local8Bit());
usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 sec
#ifndef DEBUG_WO_DIALING
if (sigsetjmp(jmp_buffer, 1) == 0) {
// set alarm in case tcsendbreak() hangs
signal(SIGALRM, alarm_handler);
alarm(2);
tcsendbreak(modemfd, 0);
alarm(0);
signal(SIGALRM, SIG_IGN);
} else {
// we reach this point if the alarm handler got called
closetty();
close(modemfd);
modemfd = -1;
errmsg = QObject::tr("The modem does not respond.");
return false;
}
#ifndef __svr4__ // drops DTR but doesn't set it afterwards again. not good for init.
tcgetattr(modemfd, &temptty);
cfsetospeed(&temptty, B0);
cfsetispeed(&temptty, B0);
tcsetattr(modemfd, TCSAFLUSH, &temptty);
#else
int modemstat;
ioctl(modemfd, TIOCMGET, &modemstat);
modemstat &= ~TIOCM_DTR;
ioctl(modemfd, TIOCMSET, &modemstat);
ioctl(modemfd, TIOCMGET, &modemstat);
modemstat |= TIOCM_DTR;
ioctl(modemfd, TIOCMSET, &modemstat);
#endif
usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 secs
cfsetospeed(&temptty, modemspeed());
cfsetispeed(&temptty, modemspeed());
tcsetattr(modemfd, TCSAFLUSH, &temptty);
#endif
return true;
} else
return false;
}
void Modem::escape_to_command_mode() {
// Send Properly bracketed escape code to put the modem back into command state.
// A modem will accept AT commands only when it is in command state.
// When a modem sends the host the CONNECT string, that signals
// that the modem is now in the connect state (no long accepts AT commands.)
// Need to send properly timed escape sequence to put modem in command state.
// Escape codes and guard times are controlled by S2 and S12 values.
//
tcflush(modemfd, TCIOFLUSH);
// +3 because quiet time must be greater than guard time.
usleep((_pppdata->modemEscapeGuardTime()+3)*20000);
QCString tmp = _pppdata->modemEscapeStr().local8Bit();
write(modemfd, tmp.data(), tmp.length());
tcflush(modemfd, TCIOFLUSH);
usleep((_pppdata->modemEscapeGuardTime()+3)*20000);
data_mode = false;
}
const QString Modem::modemMessage() {
return errmsg;
}
QString Modem::parseModemSpeed(const QString &s) {
// this is a small (and bad) parser for modem speeds
int rx = -1;
int tx = -1;
int i;
QString result;
- qDebug( "Modem reported result string: %s", s.latin1());
+ odebug << "Modem reported result string: " << s.latin1() << "" << oendl;
const int RXMAX = 7;
const int TXMAX = 2;
QRegExp rrx[RXMAX] = {
QRegExp("[0-9]+[:/ ]RX", false),
QRegExp("[0-9]+RX", false),
QRegExp("[/: -][0-9]+[/: ]", false),
QRegExp("[/: -][0-9]+$", false),
QRegExp("CARRIER [^0-9]*[0-9]+", false),
QRegExp("CONNECT [^0-9]*[0-9]+", false),
QRegExp("[0-9]+") // panic mode
};
QRegExp trx[TXMAX] = {
QRegExp("[0-9]+[:/ ]TX", false),
QRegExp("[0-9]+TX", false)
};
for(i = 0; i < RXMAX; i++) {
int len, idx, result;
if((idx = rrx[i].match(s,0,&len)) > -1) {
// if((idx = rrx[i].search(s)) > -1) {
// len = rrx[i].matchedLength();
//
// rrx[i] has been matched, idx contains the start of the match
// and len contains how long the match is. Extract the match.
//
QString sub = s.mid(idx, len);
//
// Now extract the digits only from the match, which will
// then be converted to an int.
//
if ((idx = rrx[RXMAX-1].match( sub,0,&len )) > -1) {
// if ((idx = rrx[RXMAX-1].search( sub )) > -1) {
// len = rrx[RXMAX-1].matchedLength();
sub = sub.mid(idx, len);
result = sub.toInt();
if(result > 0) {
rx = result;
break;
}
}
}
}
for(i = 0; i < TXMAX; i++) {
int len, idx, result;
if((idx = trx[i].match(s,0,&len)) > -1) {
// if((idx = trx[i].search(s)) > -1) {
// len = trx[i].matchedLength();
//
// trx[i] has been matched, idx contains the start of the match
// and len contains how long the match is. Extract the match.
//
QString sub = s.mid(idx, len);
//
// Now extract the digits only from the match, which will then
// be converted to an int.
//
if((idx = rrx[RXMAX-1].match(sub,0,&len)) > -1) {
// if((idx = rrx[RXMAX-1].search(sub)) > -1) {
// len = rrx[RXMAX-1].matchedLength();
sub = sub.mid(idx, len);
result = sub.toInt();
if(result > 0) {
tx = result;
break;
}
}
}
}
if(rx == -1 && tx == -1)
result = QObject::tr("Unknown speed");
else if(tx == -1)
result.setNum(rx);
else if(rx == -1) // should not happen
result.setNum(tx);
else
result.sprintf("%d/%d", rx, tx);
- qDebug( "The parsed result is: %s", result.latin1());
+ odebug << "The parsed result is: " << result.latin1() << "" << oendl;
return result;
}
// Lock modem device. Returns 0 on success 1 if the modem is locked and -1 if
// a lock file can't be created ( permission problem )
int Modem::lockdevice() {
int fd;
char newlock[80]=""; // safe
if(!_pppdata->modemLockFile()) {
- qDebug("The user doesn't want a lockfile.");
+ odebug << "The user doesn't want a lockfile." << oendl;
return 0;
}
if (modem_is_locked)
return 1;
QString lockfile = LOCK_DIR"/LCK..";
lockfile += _pppdata->modemDevice().mid(5); // append everything after /dev/
if(access(QFile::encodeName(lockfile), F_OK) == 0) {
// if ((fd = Requester::rq->
if ((fd = openLockfile(QFile::encodeName(lockfile), O_RDONLY)) >= 0) {
// Mario: it's not necessary to read more than lets say 32 bytes. If
// file has more than 32 bytes, skip the rest
char oldlock[33]; // safe
int sz = read(fd, &oldlock, 32);
close (fd);
if (sz <= 0)
return 1;
oldlock[sz] = '\0';
- qDebug( "Device is locked by: %s", oldlock);
+ odebug << "Device is locked by: " << oldlock << "" << oendl;
int oldpid;
int match = sscanf(oldlock, "%d", &oldpid);
// found a pid in lockfile ?
if (match < 1 || oldpid <= 0)
return 1;
// check if process exists
if (kill((pid_t)oldpid, 0) == 0 || errno != ESRCH)
return 1;
- qDebug( "lockfile is stale" );
+ odebug << "lockfile is stale" << oendl;
}
}
fd = openLockfile(_pppdata->modemDevice(),O_WRONLY|O_TRUNC|O_CREAT);
if(fd >= 0) {
sprintf(newlock,"%010d\n", getpid());
- qDebug("Locking Device: %s", newlock);
+ odebug << "Locking Device: " << newlock << "" << oendl;
write(fd, newlock, strlen(newlock));
close(fd);
modem_is_locked=true;
return 0;
}
return -1;
}
// UnLock modem device
void Modem::unlockdevice() {
if (modem_is_locked) {
- qDebug( "UnLocking Modem Device" );
+ odebug << "UnLocking Modem Device" << oendl;
close(modemfd);
modemfd = -1;
unlink(lockfile);
lockfile[0] = '\0';
modem_is_locked=false;
}
}
int Modem::openLockfile( QString lockfile, int flags)
{
int fd;
int mode;
flags = O_RDONLY;
if(flags == O_WRONLY|O_TRUNC|O_CREAT)
mode = 0644;
else
mode = 0;
lockfile = LOCK_DIR;
lockfile += "/LCK..";
lockfile += device.right( device.length() - device.findRev("/") -1 );
- qDebug("lockfile >%s<",lockfile.latin1());
+ odebug << "lockfile >" << lockfile.latin1() << "<" << oendl;
// TODO:
// struct stat st;
// if(stat(lockfile.data(), &st) == -1) {
// if(errno == EBADF)
// return -1;
// } else {
// // make sure that this is a regular file
// if(!S_ISREG(st.st_mode))
// return -1;
// }
if ((fd = open(lockfile, flags, mode)) == -1) {
- qDebug("error opening lockfile!");
+ odebug << "error opening lockfile!" << oendl;
lockfile = QString::null;
fd = open(DEVNULL, O_RDONLY);
} else
fchown(fd, 0, 0);
return fd;
}
void alarm_handler(int) {
// fprintf(stderr, "alarm_handler(): Received SIGALRM\n");
// jump
siglongjmp(jmp_buffer, 1);
}
const char* Modem::authFile(Auth method, int version) {
switch(method|version) {
case PAP|Original:
return PAP_AUTH_FILE;
break;
case PAP|New:
return PAP_AUTH_FILE".new";
break;
case PAP|Old:
return PAP_AUTH_FILE".old";
break;
case CHAP|Original:
return CHAP_AUTH_FILE;
break;
case CHAP|New:
return CHAP_AUTH_FILE".new";
break;
case CHAP|Old:
return CHAP_AUTH_FILE".old";
break;
default:
return 0L;
}
}
bool Modem::createAuthFile(Auth method, const char *username, const char *password) {
const char *authfile, *oldName, *newName;
char line[100];
char regexp[2*MaxStrLen+30];
regex_t preg;
if(!(authfile = authFile(method)))
return false;
if(!(newName = authFile(method, New)))
return false;
// look for username, "username" or 'username'
// if you modify this RE you have to adapt regexp's size above
snprintf(regexp, sizeof(regexp), "^[ \t]*%s[ \t]\\|^[ \t]*[\"\']%s[\"\']",
username,username);
MY_ASSERT(regcomp(&preg, regexp, 0) == 0);
// copy to new file pap- or chap-secrets
int old_umask = umask(0077);
FILE *fout = fopen(newName, "w");
if(fout) {
// copy old file
FILE *fin = fopen(authfile, "r");
if(fin) {
while(fgets(line, sizeof(line), fin)) {
if(regexec(&preg, line, 0, 0L, 0) == 0)
continue;
fputs(line, fout);
}
fclose(fin);
}
// append user/pass pair
fprintf(fout, "\"%s\"\t*\t\"%s\"\n", username, password);
fclose(fout);
}
// restore umask
umask(old_umask);
// free memory allocated by regcomp
regfree(&preg);
if(!(oldName = authFile(method, Old)))
return false;
// delete old file if any
unlink(oldName);
rename(authfile, oldName);
rename(newName, authfile);
@@ -834,247 +834,247 @@ int checkForInterface()
// extern char *no_ppp_msg;
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
return 1; /* can't tell */
strlcpy(ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name));
ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0;
close(s);
if (ok == -1) {
// This is ifdef'd FreeBSD, because FreeBSD is the only BSD that supports
// KLDs, the old LKM interface couldn't handle loading devices
// dynamically, and thus can't load ppp support on the fly
#ifdef __FreeBSD__
// If we failed to load ppp support and don't have it already.
if (kldload("if_ppp") == -1) {
return -1;
}
return 0;
#else
return -1;
#endif
}
return 0;
#else
// We attempt to use the SunOS/SysVr4 method and stat /dev/ppp
struct stat buf;
memset(&buf, 0, sizeof(buf));
return stat("/dev/ppp", &buf);
#endif
}
bool Modem::execpppd(const char *arguments) {
char buf[MAX_CMDLEN];
char *args[MaxArgs];
pid_t pgrpid;
if(modemfd<0)
return false;
_pppdExitStatus = -1;
(void)::pipe( m_pppdLOG );
switch(pppdPid = fork())
{
case -1:
fprintf(stderr,"In parent: fork() failed\n");
::close( m_pppdLOG[0] );
::close( m_pppdLOG[1] );
return false;
break;
case 0:
// let's parse the arguments the user supplied into UNIX suitable form
// that is a list of pointers each pointing to exactly one word
strlcpy(buf, arguments);
parseargs(buf, args);
// become a session leader and let /dev/ttySx
// be the controlling terminal.
pgrpid = setsid();
#ifdef TIOCSCTTY
if(ioctl(modemfd, TIOCSCTTY, 0)<0)
fprintf(stderr, "ioctl() failed.\n");
#elif defined (TIOCSPGRP)
if(ioctl(modemfd, TIOCSPGRP, &pgrpid)<0)
fprintf(stderr, "ioctl() failed.\n");
#endif
if(tcsetpgrp(modemfd, pgrpid)<0)
fprintf(stderr, "tcsetpgrp() failed.\n");
::close( m_pppdLOG[0] );
::setenv( "LANG", "C", 1 ); // overwrite
dup2(m_pppdLOG[1], 11 ); // for logfd 11
dup2(modemfd, 0);
dup2(modemfd, 1);
switch (checkForInterface()) {
case 1:
fprintf(stderr, "Cannot determine if kernel supports ppp.\n");
break;
case -1:
fprintf(stderr, "Kernel does not support ppp, oops.\n");
break;
case 0:
fprintf(stderr, "Kernel supports ppp alright.\n");
break;
}
execve(pppdPath(), args, 0L);
_exit(0);
break;
default:
- qDebug("In parent: pppd pid %d\n",pppdPid);
+ odebug << "In parent: pppd pid " << pppdPid << "\n" << oendl;
close(modemfd);
::close( m_pppdLOG[1] );
// set it to nonblocking io
int flag = ::fcntl( m_pppdLOG[0], F_GETFL );
if ( !(flag & O_NONBLOCK) ) {
- qDebug("Setting nonblocking io");
+ odebug << "Setting nonblocking io" << oendl;
flag |= O_NONBLOCK;
::fcntl(m_pppdLOG[0], F_SETFL, flag );
}
delete m_modemDebug;
m_modemDebug = new QSocketNotifier(m_pppdLOG[0], QSocketNotifier::Read, this );
connect(m_modemDebug, SIGNAL(activated(int) ),
this, SLOT(slotModemDebug(int) ) );
modemfd = -1;
m_pppdDev = QString::fromLatin1("ppp0");
return true;
break;
}
}
bool Modem::killpppd() {
- qDebug("In killpppd and pid is %d", pppdPid );
+ odebug << "In killpppd and pid is " << pppdPid << "" << oendl;
if(pppdPid > 0) {
delete m_modemDebug;
m_modemDebug = 0;
- qDebug("In killpppd(): Sending SIGTERM to %d\n", pppdPid);
+ odebug << "In killpppd(): Sending SIGTERM to " << pppdPid << "\n" << oendl;
if(kill(pppdPid, SIGTERM) < 0) {
- qDebug("Error terminating %d. Sending SIGKILL\n", pppdPid);
+ odebug << "Error terminating " << pppdPid << ". Sending SIGKILL\n" << oendl;
if(kill(pppdPid, SIGKILL) < 0) {
- qDebug("Error killing %d\n", pppdPid);
+ odebug << "Error killing " << pppdPid << "\n" << oendl;
return false;
}
}
}
return true;
}
void Modem::parseargs(char* buf, char** args) {
int nargs = 0;
int quotes;
while(nargs < MaxArgs-1 && *buf != '\0') {
quotes = 0;
// Strip whitespace. Use nulls, so that the previous argument is
// terminated automatically.
while ((*buf == ' ' ) || (*buf == '\t' ) || (*buf == '\n' ) )
*buf++ = '\0';
// detect begin of quoted argument
if (*buf == '"' || *buf == '\'') {
quotes = *buf;
*buf++ = '\0';
}
// save the argument
if(*buf != '\0') {
*args++ = buf;
nargs++;
}
if (!quotes)
while ((*buf != '\0') && (*buf != '\n') &&
(*buf != '\t') && (*buf != ' '))
buf++;
else {
while ((*buf != '\0') && (*buf != quotes))
buf++;
*buf++ = '\0';
}
}
*args = 0L;
}
bool Modem::execPPPDaemon(const QString & arguments)
{
if(execpppd(arguments)) {
_pppdata->setpppdRunning(true);
return true;
} else
return false;
}
void Modem::killPPPDaemon()
{
_pppdata->setpppdRunning(false);
killpppd();
}
int Modem::pppdExitStatus()
{
return _pppdExitStatus;
}
int Modem::openResolv(int flags)
{
int fd;
if ((fd = open(_PATH_RESCONF, flags)) == -1) {
- qDebug("error opening resolv.conf!");
+ odebug << "error opening resolv.conf!" << oendl;
fd = open(DEVNULL, O_RDONLY);
}
return fd;
}
bool Modem::setHostname(const QString & name)
{
return sethostname(name, name.length()) == 0;
}
QString Modem::pppDevice()const {
return m_pppdDev;
}
void Modem::setPPPDevice( const QString& dev ) {
m_pppdDev = dev;
}
pid_t Modem::pppPID()const {
return pppdPid;
}
void Modem::setPPPDPid( pid_t pid ) {
- qDebug("Modem setting pid");
+ odebug << "Modem setting pid" << oendl;
_pppdExitStatus = -1;
pppdPid = pid;
modemfd = -1;
}
void Modem::slotModemDebug(int fd) {
char buf[2049];
int len;
// read in pppd data look for Using interface
// then read the interface
// we limit to 10 device now 0-9
if((len = ::read(fd, buf, 2048)) > 0) {
buf[len+1] = '\0';
char *found;
if ( (found = ::strstr(buf, "Using interface ") ) ) {
found += 16;
m_pppdDev = QString::fromLatin1(found, 5 );
m_pppdDev = m_pppdDev.simplifyWhiteSpace();
}
}
}
diff --git a/noncore/settings/networksettings/ppp/pppconfig.cpp b/noncore/settings/networksettings/ppp/pppconfig.cpp
index 97baf31..a8c99fd 100644
--- a/noncore/settings/networksettings/ppp/pppconfig.cpp
+++ b/noncore/settings/networksettings/ppp/pppconfig.cpp
@@ -1,75 +1,75 @@
#include <qlayout.h>
#include <qmessagebox.h>
#include <qtabwidget.h>
#include "accounts.h"
#include "devices.h"
#include "general.h"
#include "interfaceppp.h"
#include "modem.h"
#include "pppconfig.h"
#include "pppdata.h"
#include "runtests.h"
PPPConfigWidget::PPPConfigWidget( InterfacePPP* iface, QWidget *parent,
const char *name,
bool modal, WFlags fl )
: QDialog(parent, name, modal, fl)
{
setCaption(tr("Configure Modem"));
int result = runTests();
if(result == TEST_CRITICAL){
QMessageBox::critical(0, tr("Modem failure"), tr("A critical failure appeard while testing the modem") );
return;
}
interface = iface;
- qDebug("PPPConfigWidget::PPPConfigWidget");
- qDebug(" interface->getHardwareName >%s<", interface->getHardwareName().latin1());
+ odebug << "PPPConfigWidget::PPPConfigWidget" << oendl;
+ odebug << " interface->getHardwareName >" << interface->getHardwareName().latin1() << "<" << oendl;
- qDebug(" _pppdata->accname >%s<",interface->data()->accname().latin1());
+ odebug << " _pppdata->accname >" << interface->data()->accname().latin1() << "<" << oendl;
QVBoxLayout *layout = new QVBoxLayout( this );
layout->setSpacing( 0 );
layout->setMargin( 1 );
tabWindow = new QTabWidget( this, "tabWidget" );
layout->addWidget( tabWindow );
accounts = new AccountWidget( interface->data(), tabWindow, "accounts", Qt::WStyle_ContextHelp );
tabWindow->addTab( accounts, tr("&Accounts") );
devices = new DevicesWidget( interface, tabWindow, "devices", Qt::WStyle_ContextHelp );
tabWindow->addTab( devices, tr("&Devices") );
//OLD:
// modem1 = new ModemWidget( interface, tabWindow, "modem1" );
// tabWindow->addTab( modem1, tr("&Device") );
// modem2 = new ModemWidget2( interface, tabWindow, "modem2" );
// tabWindow->addTab( modem2, tr("&Modem") );
}
PPPConfigWidget::~PPPConfigWidget()
{
}
void PPPConfigWidget::accept()
{
- qDebug("PPPConfigWidget::accept");
- qDebug(" _pppdata->accname >%s<",interface->data()->accname().latin1());
- qDebug(" interface->getHardwareName >%s<", interface->getHardwareName().latin1());
+ odebug << "PPPConfigWidget::accept" << oendl;
+ odebug << " _pppdata->accname >" << interface->data()->accname().latin1() << "<" << oendl;
+ odebug << " interface->getHardwareName >" << interface->getHardwareName().latin1() << "<" << oendl;
interface->setInterfaceName( interface->data()->devname() );
interface->setHardwareName( interface->data()->accname() );
interface->save();
QDialog::accept();
}
void PPPConfigWidget::reject()
{
interface->data()->cancel();
QDialog::reject();
}
diff --git a/noncore/settings/networksettings/ppp/pppdata.cpp b/noncore/settings/networksettings/ppp/pppdata.cpp
index f4727c1..567ccf8 100644
--- a/noncore/settings/networksettings/ppp/pppdata.cpp
+++ b/noncore/settings/networksettings/ppp/pppdata.cpp
@@ -1,241 +1,241 @@
/*
* kPPP: A pppd front end for the KDE project
*
* $Id$
*
* Copyright (C) 1997 Bernd Johannes Wuebben
* wuebben@math.cornell.edu
*
* based on EzPPP:
* Copyright (C) 1997 Jay Painter
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "pppdata.h"
#include "runtests.h"
//#include "devices.h"
//#include <klocale.h>
#include <qpe/config.h>
#include <qmessagebox.h>
#include <qapplication.h>
// #include <klocale.h>
// #include <kconfig.h>
// #include <kmessagebox.h>
// #include <kapplication.h>
#include <assert.h>
#define SEPARATOR -sseepp-
#define SEP QString("%1SEPARATOR%1")
PPPData::PPPData()
: passwd(""),
_modemName(""),
highcount(-1), // start out with no entries
highcountdev(-1), // start out with no entries
// caccount(-1), // set the current account index also
suidprocessid(-1), // process ID of setuid child
pppdisrunning(false),
pppderror(0)
{
highcount = readNumConfig(GENERAL_GRP, NUMACCOUNTS_KEY, 0) - 1;
highcountdev = readNumConfig(GENERAL_GRP, NUMDEVICES_KEY, 0) - 1;
Config cfg = config();
cfg.setGroup(GENERAL_GRP);
accountList = cfg.readListEntry(ACCOUNT_LIST, ',' );
deviceList = cfg.readListEntry(DEVICESNAMES_LIST, ',' );
- qDebug("PPPData::PPPData has a accountList %s", accountList.join("---").latin1());
- qDebug("PPPData::PPPData has a deviceList %s", deviceList.join("---").latin1());
+ odebug << "PPPData::PPPData has a accountList " << accountList.join("---").latin1() << "" << oendl;
+ odebug << "PPPData::PPPData has a deviceList " << deviceList.join("---").latin1() << "" << oendl;
// if (highcount > MAX_ACCOUNTS)
// highcount = MAX_ACCOUNTS;
// if(highcount >= 0 && defaultAccount().isEmpty()) {
// setAccountbyIndex(0);
// setDefaultAccount(accname());
// } else if(!setAccount(defaultAccount()))
setDefaultAccount(accname());
// start out with internal debugging disabled
// the user is still free to specify `debug' on his own
setPPPDebug(false);
::pppdVersion(&pppdVer, &pppdMod, &pppdPatch);
}
Config PPPData::config()
{
return Config("NetworkSetupPPP");
}
//
// save configuration
//
void PPPData::save()
{
- qDebug("PPPData saving data");
+ odebug << "PPPData saving data" << oendl;
writeConfig(GENERAL_GRP, NUMACCOUNTS_KEY, count());
writeConfig(GENERAL_GRP, NUMDEVICES_KEY, highcountdev + 1);
QString key;
QStringList keys;
Config cfg = config();
cfg.setGroup(GENERAL_GRP);
cfg.writeEntry(ACCOUNT_LIST, accountList, ',' );
cfg.writeEntry(DEVICESNAMES_LIST, deviceList, ',' );
for( QMap<QString,QString>::Iterator it = stringEntries.begin();
it != stringEntries.end(); ++it ){
QString val = it.data();
key = it.key();
-// qDebug("saving %s -> %s", key.latin1(), val.latin1() );
+// odebug << "saving " << key.latin1() << " -> " << val.latin1() << "" << oendl;
keys = QStringList::split( "SEPARATOR", key );
- //qDebug("group >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.latin1() );
+ //odebug << "group >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl;
cfg.setGroup(keys[0]);
cfg.writeEntry(keys[1], val);
}
for( QMap<QString,int>::Iterator it = intEntries.begin();
it != intEntries.end(); ++it ){
int val = it.data();
key = it.key();
-// qDebug("saving %s -> %i", key.latin1(), val );
+// odebug << "saving " << key.latin1() << " -> " << val << "" << oendl;
keys = QStringList::split( "SEPARATOR", key );
- //qDebug("group >%s< key >%s< val %i", keys[0].latin1(), keys[1].latin1(), val );
+ //odebug << "group >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< val " << val << "" << oendl;
cfg.setGroup(keys[0]);
cfg.writeEntry(keys[1], val);
}
for( QMap<QString,QStringList>::Iterator it = listEntries.begin();
it != listEntries.end(); ++it ){
QStringList val = it.data();
key = it.key();
QChar sep = sepEntries[key];
-// qDebug("saving %s -> %s", key.latin1(), val.join(sep).latin1() );
+// odebug << "saving " << key.latin1() << " -> " << val.join(sep).latin1() << "" << oendl;
keys = QStringList::split( "SEPARATOR", key );
cfg.setGroup(keys[0]);
cfg.writeEntry(keys[1], val, sep);
}
}
//
// cancel changes
//
void PPPData::cancel() {
stringEntries.clear();
intEntries.clear();
listEntries.clear();
}
// functions to read/write date to configuration file
QString PPPData::readConfig(const QString &group, const QString &key,
const QString &defvalue = "")
{
-// qDebug("PPPData::readConfig key >%s< group >%s<",key.latin1(), group.latin1());
+// odebug << "PPPData::readConfig key >" << key.latin1() << "< group >" << group.latin1() << "<" << oendl;
QString idx = SEP.arg(group).arg(key);
if (stringEntries.find(idx) != stringEntries.end())
return stringEntries[idx];
Config cfg = config();
cfg.setGroup(group);
return cfg.readEntry(key, defvalue);
}
int PPPData::readNumConfig(const QString &group, const QString &key,
int defvalue)
{
QString idx = SEP.arg(group).arg(key);
if (intEntries.find(idx) != intEntries.end())
return intEntries[idx];
Config cfg = config();
cfg.setGroup(group);
return cfg.readNumEntry(key, defvalue);
// if (config) {
// config->setGroup(group);
// return config->readNumEntry(key, defvalue);
// } else
// return defvalue;
}
bool PPPData::readListConfig(const QString &group, const QString &key,
QStringList &list, char sep) {
list.clear();
QString idx = SEP.arg(group).arg(key);
if (listEntries.find(idx) != listEntries.end()){
list = listEntries[idx];
return true;
}
Config cfg = config();
cfg.setGroup(group);
list = cfg.readListEntry(key, sep);
if (list.count() > 0) return true;
return false;
// if (config) {
// config->setGroup(group);
// list = config->readListEntry(key, sep);
// return true;
// } else
// return false;
}
void PPPData::writeConfig(const QString &group, const QString &key,
const QString &value) {
stringEntries.insert( SEP.arg(group).arg(key), value );
// if (config) {
// config->setGroup(group);
// config->writeEntry(key, value);
// }
}
void PPPData::writeConfig(const QString &group, const QString &key, int value)
{
intEntries.insert( SEP.arg(group).arg(key), value );
// if (config) {
// config->setGroup(group);
// config->writeEntry(key, value);
// }
}
void PPPData::writeListConfig(const QString &group, const QString &key,
QStringList &list, char sep)
{
listEntries.insert( SEP.arg(group).arg(key), list );
sepEntries.insert( SEP.arg(group).arg(key), sep );
// if (config) {
// config->setGroup(group);
// config->writeEntry(key, list, sep);
// }
}
//
// functions to set/return general information
//
QString PPPData::password(){
if ( storePassword() ) return storedPassword();
else return passwd;
}
void PPPData::setPassword(const QString &pw) {
passwd = pw;
}
@@ -272,207 +272,207 @@ void PPPData::setPPPDebug(bool set) {
writeConfig(GENERAL_GRP, PPP_DEBUG_OPTION, (int)set);
}
bool PPPData::getPPPDebug() {
return (bool)readNumConfig(GENERAL_GRP, PPP_DEBUG_OPTION, false);
}
void PPPData::set_xserver_exit_disconnect(bool set) {
writeConfig(GENERAL_GRP, DISCONNECT_KEY, (int) set);
}
bool PPPData::quit_on_disconnect() {
return (bool) readNumConfig(GENERAL_GRP, QUITONDISCONNECT_KEY, false);
}
void PPPData::set_quit_on_disconnect(bool set) {
writeConfig(GENERAL_GRP, QUITONDISCONNECT_KEY, (int) set);
}
bool PPPData::get_show_log_window() {
return (bool) readNumConfig (GENERAL_GRP, SHOWLOGWIN_KEY, false);
}
void PPPData::set_show_log_window(bool set) {
writeConfig(GENERAL_GRP, SHOWLOGWIN_KEY, (int) set);
}
bool PPPData::automatic_redial() {
return (bool) readNumConfig(GENERAL_GRP, AUTOREDIAL_KEY, FALSE);
}
void PPPData::set_automatic_redial(bool set) {
writeConfig(GENERAL_GRP, AUTOREDIAL_KEY, (int) set);
}
// bool PPPData::get_iconify_on_connect() {
// return (bool) readNumConfig(GENERAL_GRP, ICONIFY_ON_CONNECT_KEY, TRUE);
// }
// void PPPData::set_iconify_on_connect(bool set) {
// writeConfig(GENERAL_GRP, ICONIFY_ON_CONNECT_KEY, (int) set);
// }
// bool PPPData::get_dock_into_panel() {
// return (bool) readNumConfig(GENERAL_GRP, DOCKING_KEY, false);
// }
// void PPPData::set_dock_into_panel(bool set) {
// writeConfig(GENERAL_GRP, DOCKING_KEY, (int) set);
// }
QString PPPData::pppdVersion() {
return QString("%1.%2.%3").arg(pppdVer).arg(pppdMod).arg(pppdPatch);
}
bool PPPData::pppdVersionMin(int ver, int mod, int patch) {
// check if pppd version fulfills minimum requirement
return (pppdVer > ver
|| (pppdVer == ver && pppdMod > mod)
|| (pppdVer == ver && pppdMod == mod && pppdPatch >= patch));
}
int PPPData::pppdTimeout() {
return readNumConfig(GENERAL_GRP, PPPDTIMEOUT_KEY, PPPD_TIMEOUT);
}
void PPPData::setpppdTimeout(int n) {
writeConfig(GENERAL_GRP, PPPDTIMEOUT_KEY, n);
}
const QString PPPData::modemDevice() {
return readConfig (modemGroup(), MODEMDEV_KEY, "/dev/modem" );
}
// const QString PPPData::modemName()
// {
// return readConfig(modemGroup(), MODEMNAME_KEY);
// }
// bool PPPData::setModemName(const QString &n) {
-// qDebug("Setting modem name to >%s<", n.latin1());
+// odebug << "Setting modem name to >" << n.latin1() << "<" << oendl;
// _modemName = n;
// writeConfig(cgroup, MODEMNAME_KEY, n);
// return true; //FIXME
// }
// bool PPPData::changeModemName(const QString &n) {
-// qDebug("Setting modem name to >%s<", n.latin1());
+// odebug << "Setting modem name to >" << n.latin1() << "<" << oendl;
// _modemName = n;
// writeConfig(modemGroup(), MODEMNAME_KEY, n);
// return true; //FIXME
// }
bool PPPData::setModemDevice(const QString &n) {
- qDebug("Setting modem dev to >%s<", n.latin1());
+ odebug << "Setting modem dev to >" << n.latin1() << "<" << oendl;
writeConfig(modemGroup(), MODEMDEV_KEY, n);
return true; //FIXME
}
const QString PPPData::flowcontrol() {
return readConfig(modemGroup(), FLOWCONTROL_KEY, "CRTSCTS");
}
void PPPData::setFlowcontrol(const QString &n) {
writeConfig(modemGroup(), FLOWCONTROL_KEY, n);
}
const QString PPPData::speed() {
QString s = readConfig(modemGroup(), SPEED_KEY, "57600");
// undo the damage of a bug in former versions. It left an empty Speed=
// entry in kppprc. kppp did set the serial port to 57600 as default but
// pppd wouldn't receive the speed via the command line.
if(s.toUInt() == 0)
s = "57600";
return s;
}
void PPPData::setSpeed(const QString &n) {
writeConfig(modemGroup(), SPEED_KEY, n);
}
#if 0
void PPPData::setUseCDLine(const int n) {
writeConfig(modemGroup(),USECDLINE_KEY,n);
}
int PPPData::UseCDLine() {
return readNumConfig(modemGroup(),USECDLINE_KEY,0);
}
#endif
const QString PPPData::modemEscapeStr() {
return readConfig(modemGroup(),ESCAPESTR_KEY,"+++");
}
void PPPData::setModemEscapeStr(const QString &n) {
writeConfig(modemGroup(),ESCAPESTR_KEY,n);
}
const QString PPPData::modemEscapeResp() {
return readConfig(modemGroup(),ESCAPERESP_KEY,"OK");
}
void PPPData::setModemEscapeResp(const QString &n) {
writeConfig(modemGroup(),ESCAPERESP_KEY,n);
}
int PPPData::modemEscapeGuardTime() {
return readNumConfig(modemGroup(),ESCAPEGUARDTIME_KEY,50);
}
void PPPData::setModemEscapeGuardTime(int n) {
writeConfig(modemGroup(),ESCAPEGUARDTIME_KEY,n);
}
bool PPPData::modemLockFile() {
return readNumConfig(modemGroup(), LOCKFILE_KEY, 1);
}
void PPPData::setModemLockFile(bool set) {
writeConfig(modemGroup(), LOCKFILE_KEY, set);
}
int PPPData::modemTimeout() {
return readNumConfig(modemGroup(), TIMEOUT_KEY, MODEM_TIMEOUT);
}
void PPPData::setModemTimeout(int n) {
writeConfig(modemGroup(), TIMEOUT_KEY, n);
}
int PPPData::modemToneDuration() {
return readNumConfig(modemGroup(), TONEDURATION_KEY,MODEM_TONEDURATION);
}
@@ -646,421 +646,421 @@ QString PPPData::volumeHigh() {
QString tmp = readConfig(modemGroup(), VOLUME_HIGH, "M1L3");
if(tmp == "M1L4")
tmp = "M1L3";
return tmp;
}
void PPPData::setVolumeHigh(const QString &s) {
writeConfig(modemGroup(), VOLUME_HIGH, s);
}
QString PPPData::volumeInitString() {
QString s;
switch(volume()) {
case 0:
s = volumeOff();
break;
case 1:
s = volumeMedium();
break;
case 2:
s = volumeHigh();
break;
default:
s = volumeMedium();
}
return s;
}
int PPPData::volume() {
return readNumConfig(modemGroup(), VOLUME_KEY, 1);
}
void PPPData::setVolume(int i) {
writeConfig(modemGroup(), VOLUME_KEY, i);
}
int PPPData::waitForDialTone() {
return readNumConfig(modemGroup(), DIALTONEWAIT_KEY, 1);
}
void PPPData::setWaitForDialTone(int i) {
writeConfig(modemGroup(), DIALTONEWAIT_KEY, i);
}
void PPPData::setModemAnswerStr(const QString &n) {
writeConfig(modemGroup(), ANSWERSTR_KEY, n);
}
const QString PPPData::modemRingResp() {
return readConfig(modemGroup(), RINGRESP_KEY, "RING");
}
void PPPData::setModemRingResp(const QString &n) {
writeConfig(modemGroup(), RINGRESP_KEY, n);
}
const QString PPPData::modemAnswerResp() {
return readConfig(modemGroup(), ANSWERRESP_KEY, "CONNECT");
}
void PPPData::setModemAnswerResp(const QString &n) {
writeConfig(modemGroup(), ANSWERRESP_KEY, n);
}
const QString PPPData::enter() {
return readConfig(modemGroup(), ENTER_KEY, "CR");
}
void PPPData::setEnter(const QString &n) {
writeConfig(modemGroup(), ENTER_KEY, n);
}
//
// functions to set/return account information
//
//returns number of accounts
int PPPData::count() const {
return highcount + 1;
}
bool PPPData::setAccount(const QString &aname) {
- qDebug("setting account to >%s<", aname.latin1());
+ odebug << "setting account to >" << aname.latin1() << "<" << oendl;
for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) {
cgroup = *it;
- qDebug("PPPData::setAccount %s", cgroup.latin1());
- qDebug( "iterator %s", (*it).latin1() );
+ odebug << "PPPData::setAccount " << cgroup.latin1() << "" << oendl;
+ odebug << "iterator " << (*it).latin1() << "" << oendl;
if(accname() == aname) {
- qDebug("SUCCESS");
+ odebug << "SUCCESS" << oendl;
return true;
}
}
- qDebug("FAILURE");
+ odebug << "FAILURE" << oendl;
return false;
}
/*
bool PPPData::setAccountbyIndex(int i) {
if(i >= 0 && i <= highcount) {
QString tmp;
tmp.sprintf("%s%i", ACCOUNT_GRP, i);
if (_deleted.find(tmp)!=_deleted.end()) return false;
caccount = i;
cgroup = tmp;
return true;
}
return false;
}
*/
bool PPPData::isUniqueAccname(const QString &n) {
QString save_cgroup = cgroup;
for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) {
cgroup = *it;
- qDebug("PPPData::setAccount %s", cgroup.latin1());
- qDebug( "%s \n", (*it).latin1() );
+ odebug << "PPPData::setAccount " << cgroup.latin1() << "" << oendl;
+ odebug << "" << (*it).latin1() << " \n" << oendl;
if(accname() == n && cgroup != save_cgroup) {
cgroup = save_cgroup;
- qDebug("SUCCESS");
+ odebug << "SUCCESS" << oendl;
return false;
}
}
cgroup = save_cgroup;
return true;
}
bool PPPData::isUniqueDevname(const QString &n) {
QString save_mName = _modemName;
- qDebug("PPPData::isUniqueDevname checking if %s is unique", n.latin1());
+ odebug << "PPPData::isUniqueDevname checking if " << n.latin1() << " is unique" << oendl;
for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) {
_modemName = *it;
- qDebug("PPPData::isUniqueDevname %s == %s", n.latin1() , devname().latin1());
+ odebug << "PPPData::isUniqueDevname " << n.latin1() << " == " << devname().latin1() << "" << oendl;
if(devname() == n && _modemName != save_mName) {
_modemName = save_mName;
- qDebug("NOT UNIQUE");
+ odebug << "NOT UNIQUE" << oendl;
return false;
}
}
_modemName = save_mName;
return true;
}
bool PPPData::deleteAccount() {
// FIXME: check if this account exists in a config...
Config cfg = PPPData::config();
cfg.setGroup(cgroup);
cfg.clearGroup();
accountList.remove(cgroup);
QString key;
QStringList keys;
for( QMap<QString,QString>::Iterator it = stringEntries.begin();
it != stringEntries.end(); ++it ){
QString val = it.data();
key = it.key();
keys = QStringList::split( "SEPARATOR", key );
if(keys[0]==cgroup){
stringEntries.remove( it );
- qDebug("deleting >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.latin1() );
+ odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl;
}
}
for( QMap<QString,int>::Iterator it = intEntries.begin();
it != intEntries.end(); ++it ){
int val = it.data();
key = it.key();
keys = QStringList::split( "SEPARATOR", key );
if(keys[0]==cgroup){
intEntries.remove( it );
- qDebug("deleting >%s< key >%s< value >%i<", keys[0].latin1(), keys[1].latin1(), val );
+ odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val << "<" << oendl;
}
}
for( QMap<QString,QStringList>::Iterator it = listEntries.begin();
it != listEntries.end(); ++it ){
QStringList val = it.data();
key = it.key();
if(keys[0]==cgroup){
listEntries.remove( it );
sepEntries.remove( key );
- qDebug("deleting >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.join("").latin1() );
+ odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.join("").latin1() << "<" << oendl;
}
}
return true;
}
bool PPPData::deleteAccount(const QString &aname) {
if(!setAccount(aname))
return false;
deleteAccount();
return true;
}
int PPPData::newaccount() {
- qDebug("PPPData::newaccount highcount %i/%i",highcount,MAX_ACCOUNTS);
+ odebug << "PPPData::newaccount highcount " << highcount << "/" << MAX_ACCOUNTS << "" << oendl;
// if(!config) open();
// if (highcount >= MAX_ACCOUNTS) return -1;
QString tmp;
tmp.sprintf("%s%i", ACCOUNT_GRP, ++highcount);
cgroup = QString(tmp);
accountList << tmp;
- qDebug("PPPData::newaccount() Group: >%s<",cgroup.latin1());
+ odebug << "PPPData::newaccount() Group: >" << cgroup.latin1() << "<" << oendl;
setpppdArgumentDefaults();
return highcount;
}
int PPPData::copyaccount(const QString&) {
// FIXME: PPPData::copyaccount
// if(highcount >= MAX_ACCOUNTS)
return -1;
// setAccountbyIndex(i);
// QMap <QString, QString> map = config->entryMap(cgroup);
// QMap <QString, QString>::ConstIterator it = map.begin();
// QString newname = QObject::tr("%1_copy").arg(accname());
// newaccount();
// while (it != map.end()) {
// config->writeEntry(it.key(), *it);
// it++;
// }
// setAccname(newname);
// return caccount;
}
const QString PPPData::accname() {
return readConfig(cgroup, NAME_KEY);
}
void PPPData::setAccname(const QString &n) {
if(!cgroup.isNull()) {
// are we manipulating the default account's name ? then change it, too.
bool def = accname() == defaultAccount();
writeConfig(cgroup, NAME_KEY, n);
if (def)
setDefaultAccount(n);
}
writeConfig(cgroup, NAME_KEY, n);
}
#define SEPARATOR_CHAR '&'
QStringList &PPPData::phonenumbers() {
readListConfig(cgroup, PHONENUMBER_KEY, phonelist, SEPARATOR_CHAR);
return phonelist;
}
const QString PPPData::phonenumber() {
return readConfig(cgroup, PHONENUMBER_KEY);
}
void PPPData::setPhonenumber(const QString &n) {
writeConfig(cgroup, PHONENUMBER_KEY, n);
}
const QString PPPData::dialPrefix() {
return readConfig(cgroup, DIAL_PREFIX_KEY, "");
}
void PPPData::setDialPrefix(const QString &s) {
writeConfig(cgroup, DIAL_PREFIX_KEY, s);
}
int PPPData::authMethod() {
return readNumConfig(cgroup, AUTH_KEY, 0);
}
void PPPData::setAuthMethod(int value) {
writeConfig(cgroup, AUTH_KEY, value);
}
const QString PPPData::storedUsername() {
return readConfig(cgroup, STORED_USERNAME_KEY, "");
}
void PPPData::setStoredUsername(const QString &b) {
writeConfig(cgroup, STORED_USERNAME_KEY, b);
}
const QString PPPData::storedPassword() {
- qDebug("getting stored pw");
- qDebug("g %s", cgroup.latin1() );
- qDebug("k %s", STORED_PASSWORD_KEY);
+ odebug << "getting stored pw" << oendl;
+ odebug << "g " << cgroup.latin1() << "" << oendl;
+ odebug << "k " << STORED_PASSWORD_KEY << "" << oendl;
return readConfig(cgroup, STORED_PASSWORD_KEY, "");
}
void PPPData::setStoredPassword(const QString &b) {
writeConfig(cgroup, STORED_PASSWORD_KEY, b);
}
bool PPPData::storePassword() {
return (bool)readNumConfig(cgroup, STORE_PASSWORD_KEY, 1);
}
const QString PPPData::command_before_connect() {
return readConfig(cgroup, BEFORE_CONNECT_KEY);
}
void PPPData::setCommand_before_connect(const QString &n) {
writeConfig(cgroup, BEFORE_CONNECT_KEY, n);
}
void PPPData::setStorePassword(bool b) {
writeConfig(cgroup, STORE_PASSWORD_KEY, (int)b);
}
const QString PPPData::command_on_connect() {
return readConfig(cgroup, COMMAND_KEY);
}
void PPPData::setCommand_on_connect(const QString &n) {
writeConfig(cgroup, COMMAND_KEY, n);
}
const QString PPPData::command_on_disconnect() {
return readConfig(cgroup, DISCONNECT_COMMAND_KEY);
}
void PPPData::setCommand_on_disconnect(const QString &n) {
writeConfig(cgroup, DISCONNECT_COMMAND_KEY, n);
}
const QString PPPData::command_before_disconnect() {
return readConfig(cgroup, BEFORE_DISCONNECT_KEY);
}
void PPPData::setCommand_before_disconnect(const QString &n) {
writeConfig(cgroup, BEFORE_DISCONNECT_KEY, n);
}
const QString PPPData::ipaddr() {
return readConfig(cgroup, IPADDR_KEY);
}
void PPPData::setIpaddr(const QString &n) {
writeConfig(cgroup, IPADDR_KEY, n);
}
const QString PPPData::subnetmask() {
return readConfig(cgroup, SUBNETMASK_KEY);
}
void PPPData::setSubnetmask(const QString &n) {
writeConfig(cgroup, SUBNETMASK_KEY, n);
}
bool PPPData::autoname() {
return (bool) readNumConfig(cgroup, AUTONAME_KEY, false);
}
void PPPData::setAutoname(bool set) {
writeConfig(cgroup, AUTONAME_KEY, (int) set);
}
bool PPPData::AcctEnabled() {
return (bool) readNumConfig(cgroup, ACCTENABLED_KEY, false);
}
void PPPData::setAcctEnabled(bool set) {
writeConfig(cgroup, ACCTENABLED_KEY, (int) set);
@@ -1236,260 +1236,260 @@ void PPPData::setpppdArgumentDefaults() {
// QColor in,
// QColor out)
// {
// if(config) {
// config->setGroup(GRAPH_GRP);
// config->writeEntry(GENABLED, enable);
// // config->writeEntry(GCOLOR_BG, bg);
// // config->writeEntry(GCOLOR_TEXT, text);
// // config->writeEntry(GCOLOR_IN, in);
// // config->writeEntry(GCOLOR_OUT, out);
// }
// }
// void PPPData::graphingOptions(bool &enable,
// QColor &bg,
// QColor &text,
// QColor &in,
// QColor &out)
// {
// QColor c;
// if(config) {
// config->setGroup(GRAPH_GRP);
// enable = config->readBoolEntry(GENABLED, true);
// bg = Qt::white;
// //bg = config->readColorEntry(GCOLOR_BG, &c);
// text = Qt::black;
// //text = config->readColorEntry(GCOLOR_TEXT, &c);
// in = Qt::blue;
// //in = config->readColorEntry(GCOLOR_IN, &c);
// out = Qt::red;
// //out = config->readColorEntry(GCOLOR_OUT, &c);
// }
// }
// bool PPPData::graphingEnabled() {
// return (bool) readNumConfig(GRAPH_GRP, GENABLED, true);
// }
//
//functions to change/set the child pppd process info
//
bool PPPData::pppdRunning() const {
return pppdisrunning;
}
void PPPData::setpppdRunning(bool set) {
pppdisrunning = set;
}
int PPPData::pppdError() const {
return pppderror;
}
void PPPData::setpppdError(int err) {
pppderror = err;
}
QString PPPData::modemGroup()
{
if (_modemName.isEmpty())
_modemName = deviceList[0];
return _modemName;
}
QMap<QString,QString> PPPData::getConfiguredInterfaces()
{
QMap<QString,QString> ifaces;
Config config = PPPData::config();
config.setGroup(ACCLIST_GRP);
int count = config.readNumEntry( ACCOUNTS_COUNT, -1 );
QString accGrp, dev, acc;
for (int i = 0; i < count; i++){
accGrp = QString("%1_%1").arg(ACCLIST_GRP).arg(i);
config.setGroup(accGrp);
dev = config.readEntry( ACOUNTS_DEV, "error" );
acc = config.readEntry( ACOUNTS_ACC, "error" );
ifaces.insert( dev, acc );
}
return ifaces;
}
void PPPData::setConfiguredInterfaces( QMap<QString,QString> ifaces )
{
QMap<QString,QString>::Iterator it;
int i = 0;
Config cfg = config();
for( it = ifaces.begin(); it != ifaces.end(); ++it ){
cfg.setGroup(QString("%1_%1").arg(ACCLIST_GRP).arg(i++));
cfg.writeEntry( ACOUNTS_DEV, it.key() );
cfg.writeEntry( ACOUNTS_ACC, it.data() );
- qDebug("I %i",i);
+ odebug << "I " << i << "" << oendl;
}
cfg.setGroup( ACCLIST_GRP );
- qDebug("saved %i account settings", i);
+ odebug << "saved " << i << " account settings" << oendl;
cfg.writeEntry( ACCOUNTS_COUNT, i );
}
/**
* pppd's getword() function knows about escape characters.
* If we write the username and password to the secrets file
* we'll therefore have to escape back slashes.
*/
QString PPPData::encodeWord(const QString &s) {
QString r = s;
r.replace(QRegExp("\\"), "\\\\");
return r;
}
QStringList PPPData::getDevicesList()
{
Config cfg("NetworkSetupPPP");
cfg.setGroup("Devices_General");
return cfg.readListEntry(DEVICES_LIST,DEVICES_LIST_SEP);
}
QStringList PPPData::getAccountList()
{
QStringList list;
QString save_cgroup;
save_cgroup = cgroup;
for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) {
cgroup = *it;
list << accname();
}
cgroup = save_cgroup;
return list;
};
const QString PPPData::devname()
{
QString tmp = readConfig(modemGroup(), MODEMNAME_KEY );
- qDebug("PPPData::devname() of %s is %s", modemGroup().latin1(), tmp.latin1());
+ odebug << "PPPData::devname() of " << modemGroup().latin1() << " is " << tmp.latin1() << "" << oendl;
return tmp;
}
void PPPData::setDevname(const QString &n) {
// if(!cgroup.isNull()) {
// // are we manipulating the default account's name ? then change it, too.
// bool def = accname() == defaultAccount();
// writeConfig(cgroup, NAME_KEY, n);
// if (def)
// setDefaultAccount(n);
// }
writeConfig(modemGroup(), MODEMNAME_KEY, n );
}
bool PPPData::setDevice(const QString &dev )
{
- qDebug("setting device to >%s<", dev.latin1());
+ odebug << "setting device to >" << dev.latin1() << "<" << oendl;
QString save_mName = _modemName;
for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) {
_modemName = *it;
- qDebug("PPPData::setDevice %s is named %s", _modemName.latin1(), devname().latin1() );
- qDebug( "iterator %s", (*it).latin1() );
+ odebug << "PPPData::setDevice " << _modemName.latin1() << " is named " << devname().latin1() << "" << oendl;
+ odebug << "iterator " << (*it).latin1() << "" << oendl;
if(devname() == dev) {
- qDebug("SUCCESS");
+ odebug << "SUCCESS" << oendl;
return true;
}
}
_modemName = save_mName;
- qDebug("FAILURE");
+ odebug << "FAILURE" << oendl;
return false;
}
bool PPPData::deleteDevice()
{
// FIXME: check if this account exists in a config...
Config cfg = PPPData::config();
cfg.setGroup(modemGroup());
cfg.clearGroup();
deviceList.remove(modemGroup());
QString key;
QStringList keys;
for( QMap<QString,QString>::Iterator it = stringEntries.begin();
it != stringEntries.end(); ++it ){
QString val = it.data();
key = it.key();
keys = QStringList::split( "SEPARATOR", key );
if(keys[0]==modemGroup()){
stringEntries.remove( it );
- qDebug("deleting >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.latin1() );
+ odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl;
}
}
for( QMap<QString,int>::Iterator it = intEntries.begin();
it != intEntries.end(); ++it ){
int val = it.data();
key = it.key();
keys = QStringList::split( "SEPARATOR", key );
if(keys[0]==modemGroup()){
intEntries.remove( it );
- qDebug("deleting >%s< key >%s< value >%i<", keys[0].latin1(), keys[1].latin1(), val );
+ odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val << "<" << oendl;
}
}
for( QMap<QString,QStringList>::Iterator it = listEntries.begin();
it != listEntries.end(); ++it ){
QStringList val = it.data();
key = it.key();
if(keys[0]==modemGroup()){
listEntries.remove( it );
sepEntries.remove( key );
- qDebug("deleting >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.join("").latin1() );
+ odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.join("").latin1() << "<" << oendl;
}
}
return true;
}
bool PPPData::deleteDevice(const QString &dev)
{
if(!setDevice(dev))
return false;
return deleteDevice();
}
int PPPData::newdevice()
{
- qDebug("PPPData::newdevice highcount %i",highcountdev);
+ odebug << "PPPData::newdevice highcount " << highcountdev << "" << oendl;
QString tmp;
tmp.sprintf("%s%i", MODEM_GRP, ++highcountdev);
_modemName = QString(tmp);
deviceList << tmp;
- qDebug("PPPData::newdevice() Group: >%s<",cgroup.latin1());
+ odebug << "PPPData::newdevice() Group: >" << cgroup.latin1() << "<" << oendl;
return highcountdev;
}
int PPPData::copydevice(const QString&)
{
return false;
}
QStringList PPPData::getDevicesNamesList()
{
QStringList list;
QString save_mName = _modemName;
- qDebug("PPPData::getDevicesNamesList has %s", deviceList.join("---").latin1());
+ odebug << "PPPData::getDevicesNamesList has " << deviceList.join("---").latin1() << "" << oendl;
for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) {
_modemName = *it;
- qDebug("PPPData::getDevicesNamesList adding %s as %s",_modemName.latin1(), devname().latin1());
+ odebug << "PPPData::getDevicesNamesList adding " << _modemName.latin1() << " as " << devname().latin1() << "" << oendl;
list << devname();
}
_modemName = save_mName;
return list;
};
diff --git a/noncore/settings/networksettings/ppp/pppmodule.cpp b/noncore/settings/networksettings/ppp/pppmodule.cpp
index a7caffe..2291e8a 100644
--- a/noncore/settings/networksettings/ppp/pppmodule.cpp
+++ b/noncore/settings/networksettings/ppp/pppmodule.cpp
@@ -1,283 +1,283 @@
#include "modem.h"
#include "pppconfig.h"
#include "pppmodule.h"
#include "pppdata.h"
#include "interfaceinformationppp.h"
#include "interfaceppp.h"
/* OPIE */
#include <qpe/config.h>
#include <qpe/qpeapplication.h>
/* QT */
/* STD */
#include <errno.h>
#include <signal.h>
// don't polute global namespace
namespace
{
/*
* If network settings is qutting and we've ppp
* devices open we need to save the pid_t the PPData
* and the interface number
*/
struct Connection
{
pid_t pid;
QString device;
QString name;
};
class InterfaceKeeper
{
public:
InterfaceKeeper();
~InterfaceKeeper();
void addInterface( pid_t, const QString& pppDev, const QString& name );
QMap<QString, Connection> interfaces()const; // will check if still available
private:
bool isAvailable( pid_t )const;
QMap<QString, Connection> m_interfaces;
};
}
/**
* Constructor, find all of the possible interfaces
* We also need to restore the state.. it could be that
* an interface was up while closing the application
* we need to be able to shut it down...
*/
PPPModule::PPPModule() : Module()
{
InterfaceKeeper inFace;
QMap<QString,Connection> running = inFace.interfaces();
QStringList handledInterfaceNames;
QMap<QString,QString> ifaces = PPPData::getConfiguredInterfaces();
QMap<QString,QString>::Iterator it;
InterfacePPP *iface;
- qDebug("getting interfaces");
+ odebug << "getting interfaces" << oendl;
for( it = ifaces.begin(); it != ifaces.end(); ++it )
{
- qDebug("ifaces %s %s", it.key().latin1(), it.data().latin1() );
+ odebug << "ifaces " << it.key().latin1() << " " << it.data().latin1() << "" << oendl;
iface = new InterfacePPP( 0, it.key() );
iface->setHardwareName( it.data() );
list.append( (Interface*)iface );
// check if (*it) is one of the running ifaces
if ( running.contains( it.data() ) )
{
- qDebug("iface is running %s", it.key().latin1() );
+ odebug << "iface is running " << it.key().latin1() << "" << oendl;
handledInterfaceNames << running[it.data()].device;
iface->setStatus( true );
iface->setPPPDpid( running[it.data()].pid );
iface->modem()->setPPPDevice( running[it.data()].device );
iface->refresh();
}
}
setHandledInterfaceNames( handledInterfaceNames );
}
/**
* Delete any interfaces that we own.
*/
PPPModule::~PPPModule()
{
- qDebug("PPPModule::~PPPModule() " );
+ odebug << "PPPModule::~PPPModule() " << oendl;
QMap<QString,QString> ifaces;
InterfaceKeeper keeper;
Interface *i;
for ( i=list.first(); i != 0; i=list.next() )
{
/* if online save the state */
if ( i->getStatus() )
{
- qDebug("Iface %s is still up", i->getHardwareName().latin1() );
+ odebug << "Iface " << i->getHardwareName().latin1() << " is still up" << oendl;
InterfacePPP* ppp = static_cast<InterfacePPP*>(i);
keeper.addInterface( ppp->pppPID(), ppp->pppDev(), ppp->getHardwareName() );
}
ifaces.insert( i->getInterfaceName(), i->getHardwareName() );
delete i;
}
PPPData::setConfiguredInterfaces( ifaces );
}
/**
* Change the current profile
*/
void PPPModule::setProfile(const QString &newProfile)
{
profile = newProfile;
}
/**
* get the icon name for this device.
* @param Interface* can be used in determining the icon.
* @return QString the icon name (minus .png, .gif etc)
*/
QString PPPModule::getPixmapName(Interface* )
{
return "ppp";
}
/**
* Check to see if the interface i is owned by this module.
* @param Interface* interface to check against
* @return bool true if i is owned by this module, false otherwise.
*/
bool PPPModule::isOwner(Interface *i)
{
return list.find( i ) != -1;
}
/**
* Create, and return the WLANConfigure Module
* @return QWidget* pointer to this modules configure.
*/
QWidget *PPPModule::configure(Interface *i)
{
- qDebug("return ModemWidget");
+ odebug << "return ModemWidget" << oendl;
PPPConfigWidget *pppconfig = new PPPConfigWidget( (InterfacePPP*)i,
0, "PPPConfig", false,
(Qt::WDestructiveClose | Qt::WStyle_ContextHelp));
return pppconfig;
}
/**
* Create, and return the Information Module
* @return QWidget* pointer to this modules info.
*/
QWidget *PPPModule::information(Interface *i)
{
// We don't have any advanced pppd information widget yet :-D
// TODO ^
return new InterfaceInformationPPP( 0, "InterfaceInformationPPP", i );
}
/**
* Get all active (up or down) interfaces
* @return QList<Interface> A list of interfaces that exsist that havn't
* been called by isOwner()
*/
QList<Interface> PPPModule::getInterfaces()
{
// List all of the files in the peer directory
- qDebug("PPPModule::getInterfaces");
+ odebug << "PPPModule::getInterfaces" << oendl;
return list;
}
/**
* Attempt to add a new interface as defined by name
* @param name the name of the type of interface that should be created given
* by possibleNewInterfaces();
* @return Interface* NULL if it was unable to be created.
*/
Interface *PPPModule::addNewInterface(const QString &newInterface)
{
InterfacePPP *ifaceppp;
Interface *iface;
ifaceppp = new InterfacePPP();
PPPConfigWidget imp(ifaceppp, 0, "PPPConfigImp", true);
if( QPEApplication::execDialog( &imp ) == QDialog::Accepted )
{
iface = (InterfacePPP*) ifaceppp;
iface->setModuleOwner( this );
list.append( iface );
return iface;
}
else
{
delete ifaceppp;
iface = NULL;
}
return iface;
}
/**
* Attempts to remove the interface, doesn't delete i
* @return bool true if successful, false otherwise.
*/
bool PPPModule::remove(Interface *i)
{
return list.remove(i);
}
void PPPModule::possibleNewInterfaces(QMap<QString, QString> &newIfaces)
{
newIfaces.insert(QObject::tr("PPP") ,
QObject::tr("generic ppp device"));
}
namespace
{
InterfaceKeeper::InterfaceKeeper( )
{}
InterfaceKeeper::~InterfaceKeeper()
{
Config cfg("ppp_plugin_keeper");
QStringList lst = cfg.groupList();
for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
{
Connection con;
cfg.setGroup( (*it) );
cfg.clearGroup();
}
for (QMap<QString, Connection>::Iterator it = m_interfaces.begin(); it != m_interfaces.end(); ++it )
{
Connection con = it.data();
cfg.setGroup( con.name );
cfg.writeEntry( "pid", con.pid );
cfg.writeEntry( "device", con.device );
}
}
void InterfaceKeeper::addInterface(pid_t pid, const QString& dev, const QString& name )
{
Connection con;
con.pid = pid;
con.device = dev;
con.name = name;
m_interfaces.insert( name, con );
}
QMap<QString, Connection> InterfaceKeeper::interfaces()const
{
Config cfg("ppp_plugin_keeper");
QMap<QString, Connection> ifaces;
QStringList lst = cfg.groupList();
for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
{
Connection con;
cfg.setGroup( (*it) );
con.name = (*it);
con.pid = cfg.readNumEntry("pid");
con.device = cfg.readEntry("device");
- qDebug(" %s %s %d", con.name.latin1(), con.device.latin1(), con.pid );
+ odebug << " " << con.name.latin1() << " " << con.device.latin1() << " " << con.pid << "" << oendl;
if ( con.pid != -1 && isAvailable( con.pid ) )
ifaces.insert( con.name, con );
}
return ifaces;
}
bool InterfaceKeeper::isAvailable( pid_t p)const
{
if (::kill(p, 0 ) == 0 || errno != ESRCH )
{
- qDebug("isAvailable %d", p);
+ odebug << "isAvailable " << p << "" << oendl;
return true;
}
- qDebug("notAvailable %d", p);
+ odebug << "notAvailable " << p << "" << oendl;
return false;
}
}
diff --git a/noncore/settings/networksettings/wlan/infoimp.cpp b/noncore/settings/networksettings/wlan/infoimp.cpp
index bd56678..c558f5e 100644
--- a/noncore/settings/networksettings/wlan/infoimp.cpp
+++ b/noncore/settings/networksettings/wlan/infoimp.cpp
@@ -1,56 +1,56 @@
#include "infoimp.h"
#include "wextensions.h"
#include <qtimer.h>
#include <qprogressbar.h>
#include <qlabel.h>
/**
* Constructor. If wireless extensions are enabled on device name then
* start a timer that every second will update the information.
*/
WlanInfoImp::WlanInfoImp( QWidget* parent, const char* name, WFlags fl): WlanInfo(parent, name, fl){
WExtensions *wExtensions = new WExtensions(name);
if(!wExtensions->doesHaveWirelessExtensions()){
delete wExtensions;
- qDebug("WlanInfoImp::No wireless extension");
+ odebug << "WlanInfoImp::No wireless extension" << oendl;
return;
}
delete wExtensions;
timer = new QTimer( this );
connect( timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start( 1000, false );
}
/**
* Updates the information about the wireless device.
*/
void WlanInfoImp::update(){
WExtensions *wExtensions = new WExtensions(this->name());
if(!wExtensions->doesHaveWirelessExtensions()){
- qDebug("No extension");
+ odebug << "No extension" << oendl;
delete wExtensions;
timer->stop();
return;
}
essidLabel->setText(wExtensions->essid());
apLabel->setText(wExtensions->ap());
stationLabel->setText(wExtensions->station());
modeLabel->setText(wExtensions->mode());
channelLabel->setText(QString("%1").arg(wExtensions->channel()));
int signal = 0;
int noise = 0;
int quality = 0;
wExtensions->stats(signal, noise, quality);
if(signalProgressBar->progress() != signal)
signalProgressBar->setProgress(signal);
if(noiseProgressBar->progress() != noise)
noiseProgressBar->setProgress(noise);
if(qualityProgressBar->progress() != quality)
qualityProgressBar->setProgress(quality);
rateLabel->setText(QString("%1 Mb/s").arg(wExtensions->rate()));
delete wExtensions;
}
// infoimp.cpp
diff --git a/noncore/settings/networksettings/wlan/wextensions.cpp b/noncore/settings/networksettings/wlan/wextensions.cpp
index d1fff88..9c64323 100644
--- a/noncore/settings/networksettings/wlan/wextensions.cpp
+++ b/noncore/settings/networksettings/wlan/wextensions.cpp
@@ -19,182 +19,182 @@
WExtensions::WExtensions(QString interfaceName): hasWirelessExtensions(false), interface(interfaceName) {
fd = socket( AF_INET, SOCK_DGRAM, 0 );
if(fd == -1)
return;
const char* buffer[200];
memset( &iwr, 0, sizeof( iwr ) );
iwr.u.essid.pointer = (caddr_t) buffer;
iwr.u.essid.length = IW_ESSID_MAX_SIZE;
iwr.u.essid.flags = 0;
// check if it is an IEEE 802.11 standard conform
// wireless device by sending SIOCGIWESSID
// which also gives back the Extended Service Set ID
// (see IEEE 802.11 for more information)
const char* iname = interface.latin1();
strcpy( iwr.ifr_ifrn.ifrn_name, (const char *)iname );
if ( 0 == ioctl( fd, SIOCGIWESSID, &iwr ) )
hasWirelessExtensions = true;
}
/**
* @return QString the station name of the access point.
*/
QString WExtensions::station(){
if(!hasWirelessExtensions)
return QString();
const char* buffer[200];
iwr.u.data.pointer = (caddr_t) buffer;
iwr.u.data.length = IW_ESSID_MAX_SIZE;
iwr.u.data.flags = 0;
if ( 0 == ioctl( fd, SIOCGIWNICKN, &iwr )){
iwr.u.data.pointer[(unsigned int) iwr.u.data.length-1] = '\0';
return QString(iwr.u.data.pointer);
}
return QString();
}
/**
* @return QString the essid of the host 802.11 access point.
*/
QString WExtensions::essid(){
if(!hasWirelessExtensions)
return QString();
if ( 0 == ioctl( fd, SIOCGIWESSID, &iwr )){
iwr.u.essid.pointer[(unsigned int) iwr.u.essid.length] = '\0';
return QString(iwr.u.essid.pointer);
}
return QString();
}
/**
* @return QString the mode of interface
*/
QString WExtensions::mode(){
if(!hasWirelessExtensions)
return QString();
if ( 0 == ioctl( fd, SIOCGIWMODE, &iwr ) )
return QString("%1").arg(iwr.u.mode == IW_MODE_ADHOC ? "Ad-Hoc" : "Managed");
return QString();
}
/**
* Get the frequency that the interface is running at.
* @return int the frequency that the interfacae is running at.
*/
double WExtensions::frequency(){
if(!hasWirelessExtensions)
return 0;
if ( 0 == ioctl( fd, SIOCGIWFREQ, &iwr ))
return (double( iwr.u.freq.m ) * pow( 10, iwr.u.freq.e ) / 1000000000);
return 0;
}
/**
* Get the channel that the interface is running at.
* @return int the channel that the interfacae is running at.
*/
int WExtensions::channel(){
if(!hasWirelessExtensions)
return 0;
if ( 0 != ioctl( fd, SIOCGIWFREQ, &iwr ))
return 0;
// http://www.elanix.com/pdf/an137e.pdf
double num = (double( iwr.u.freq.m ) * pow( 10, iwr.u.freq.e ) / 1000000000);
double left = 2.401;
double right = 2.416;
for(int channel = 1; channel<= 15; channel++){
if( num >= left && num <= right )
return channel;
left += 0.005;
right += 0.005;
}
- qDebug(QString("Unknown frequency: %1, returning -1 for the channel.").arg(num).latin1());
+ odebug << QString("Unknown frequency: %1, returning -1 for the channel.").arg(num).latin1() << oendl;
return -1;
}
/***
* Get the current rate that the card is transmiting at.
* @return double the rate, 0 if error.
*/
double WExtensions::rate(){
if(!hasWirelessExtensions)
return 0;
if(0 == ioctl(fd, SIOCGIWRATE, &iwr)){
return ((double)iwr.u.bitrate.value)/1000000;
}
return 0;
}
/**
* @return QString the AccessPoint that the interface is connected to.
*/
QString WExtensions::ap(){
if(!hasWirelessExtensions)
return QString();
if ( 0 == ioctl( fd, SIOCGIWAP, &iwr )){
QString ap;
ap = ap.sprintf( "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X",
iwr.u.ap_addr.sa_data[0]&0xff,
iwr.u.ap_addr.sa_data[1]&0xff,
iwr.u.ap_addr.sa_data[2]&0xff,
iwr.u.ap_addr.sa_data[3]&0xff,
iwr.u.ap_addr.sa_data[4]&0xff,
iwr.u.ap_addr.sa_data[5]&0xff );
return ap;
}
else return QString();
}
/**
* Get the stats for interfaces
* @param signal the signal strength of interface
* @param noise the noise level of the interface
* @param quality the quality level of the interface
* @return bool true if successful
*/
bool WExtensions::stats(int &signal, int &noise, int &quality){
// gather link quality from /proc/net/wireless
if(!QFile::exists(PROCNETWIRELESS))
return false;
char c;
QString status;
QString name;
QFile wfile( PROCNETWIRELESS );
if(!wfile.open( IO_ReadOnly ))
return false;
QTextStream wstream( &wfile );
wstream.readLine(); // skip the first two lines
wstream.readLine(); // because they only contain headers
while(!wstream.atEnd()){
wstream >> name >> status >> quality >> c >> signal >> c >> noise;
if(name == QString("%1:").arg(interface)){
if ( quality > 92 )
- qDebug( "WIFIAPPLET: D'oh! Quality %d > estimated max!\n", quality );
+ odebug << "WIFIAPPLET: D'oh! Quality " << quality << " > estimated max!\n" << oendl;
if ( ( signal > IW_UPPER ) || ( signal < IW_LOWER ) )
- qDebug( "WIFIAPPLET: Doh! Strength %d > estimated max!\n", signal );
+ odebug << "WIFIAPPLET: Doh! Strength " << signal << " > estimated max!\n" << oendl;
if ( ( noise > IW_UPPER ) || ( noise < IW_LOWER ) )
- qDebug( "WIFIAPPLET: Doh! Noise %d > estimated max!\n", noise );
- //qDebug(QString("q:%1, s:%2, n:%3").arg(quality).arg(signal).arg(noise).latin1());
+ odebug << "WIFIAPPLET: Doh! Noise " << noise << " > estimated max!\n" << oendl;
+ //odebug << QString("q:%1, s:%2, n:%3").arg(quality).arg(signal).arg(noise).latin1() << oendl;
signal = ( ( signal-IW_LOWER ) * 100 ) / IW_UPPER;
noise = ( ( noise-IW_LOWER ) * 100 ) / IW_UPPER;
quality = ( quality*100 ) / 92;
return true;
}
}
- qDebug("WExtensions::statsCard no longer present.");
+ odebug << "WExtensions::statsCard no longer present." << oendl;
quality = -1;
signal = IW_LOWER;
noise = IW_LOWER;
return false;
}
// wextensions.cpp
diff --git a/noncore/settings/networksettings/wlan/wlanimp.cpp b/noncore/settings/networksettings/wlan/wlanimp.cpp
index 80a9927..fe7941d 100644
--- a/noncore/settings/networksettings/wlan/wlanimp.cpp
+++ b/noncore/settings/networksettings/wlan/wlanimp.cpp
@@ -1,245 +1,245 @@
#include "wlanimp.h"
#include "interfacesetupimp.h"
#include <qfile.h>
#include <qdir.h>
#include <qtextstream.h>
#include <qmessagebox.h>
#include <qlineedit.h>
#include <qlabel.h>
#include <qspinbox.h>
#include <qradiobutton.h>
#include <qcheckbox.h>
#include <qtabwidget.h>
#include <qcombobox.h>
#ifdef QWS
#include <opie2/oprocess.h>
#else
#define OProcess KProcess
#include <kprocess.h>
#endif
#define WIRELESS_OPTS "/etc/pcmcia/wireless.opts"
/**
* Constructor, read in the wireless.opts file for parsing later.
*/
using namespace Opie::Core;
WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl):WLAN(parent, name, modal, fl), currentProfile("*") {
interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i);
tabWidget->insertTab(interfaceSetup, "TCP/IP");
// Read in the config file.
QString wlanFile = WIRELESS_OPTS;
QFile file(wlanFile);
if (file.open(IO_ReadOnly)){
QTextStream stream( &file );
QString line = "";
while ( !stream.eof() ) {
line += stream.readLine();
line += "\n";
}
file.close();
settingsFileText = QStringList::split("\n", line, true);
parseSettingFile();
}
else
- qDebug(QString("WLANImp: Can't open file: %1 for reading.").arg(wlanFile).latin1());
+ odebug << QString("WLANImp: Can't open file: %1 for reading.").arg(wlanFile).latin1() << oendl;
connect(networkType, SIGNAL(activated(int)), this, SLOT(typeChanged(int)));
}
void WLANImp::typeChanged(int mod){
networkChannel->setEnabled(mod);
channelLabel->setEnabled(mod);
}
/**
* Change the profile for both wireless settings and network settings.
*/
void WLANImp::setProfile(const QString &profile){
interfaceSetup->setProfile(profile);
parseSettingFile();
}
/**
* Parses the settings file that was read in and gets any setting from it.
*/
void WLANImp::parseSettingFile(){
bool foundCase = false;
bool found = false;
for ( QStringList::Iterator it = settingsFileText.begin(); it != settingsFileText.end(); ++it ) {
QString line = (*it).simplifyWhiteSpace();
if(line.contains("case"))
foundCase = true;
// See if we found our scheme to write or the sceme couldn't be found
if((foundCase && line.contains("esac")) ||
(foundCase && line.left(currentProfile.length()+7) == currentProfile + ",*,*,*)" && line.at(0) != '#'))
found = true;
if(line.contains(";;"))
found = false;
if(found){
// write out scheme
if(line.contains("ESSID=")){
QString id = line.mid(line.find("ESSID=")+6, line.length());
if(id == "any"){
essAny->setChecked(false);
}else{
essAny->setChecked(true);
essSpecificLineEdit->setText(id);
}
}
if(line.contains("MODE=")){
QString mode = line.mid(line.find("MODE=")+5, line.length());
if(mode == "Managed"){
networkType->setCurrentItem(0);
channelLabel->setEnabled(false);
networkChannel->setEnabled(false);
}
else{
networkType->setCurrentItem(1);
networkChannel->setEnabled(true);
channelLabel->setEnabled(true);
}
}
if(line.contains("#KEY0="))
keyLineEdit0->setText(line.mid(6, line.length()));
if(line.contains("#KEY1="))
keyLineEdit1->setText(line.mid(6, line.length()));
if(line.contains("#KEY2="))
keyLineEdit2->setText(line.mid(6, line.length()));
if(line.contains("#KEY3="))
keyLineEdit3->setText(line.mid(6, line.length()));
if(line.contains("KEY=")){
wepEnabled->setChecked(true);
QString key;
if(line.right(5) == (" open")){
key = line.mid(4, line.length()-5);
authOpen->setChecked(true);
authShared->setChecked(false);
}
else{
authOpen->setChecked(false);
authShared->setChecked(true);
key = line.mid(4, line.length());
}
if(key == keyLineEdit0->text()) keyRadio0->setChecked(true);
if(key == keyLineEdit1->text()) keyRadio1->setChecked(true);
if(key == keyLineEdit2->text()) keyRadio2->setChecked(true);
if(key == keyLineEdit3->text()) keyRadio3->setChecked(true);
}
if(line.contains("CHANNEL=")){
networkChannel->setValue(line.mid(line.find("CHANNEL=")+8, line.length()).toInt());
}
}
}
}
/**
* Saves settings to the wireless.opts file using the current profile
*/
void WLANImp::changeAndSaveSettingFile(){
QString wlanFile = WIRELESS_OPTS;
QFile::remove(wlanFile);
QFile file(wlanFile);
if (!file.open(IO_ReadWrite)){
- qDebug(QString("WLANImp::changeAndSaveSettingFile(): Can't open file: %1 for writing.").arg(wlanFile).latin1());
+ odebug << QString("WLANImp::changeAndSaveSettingFile(): Can't open file: %1 for writing.").arg(wlanFile).latin1() << oendl;
return;
}
QTextStream stream( &file );
bool foundCase = false;
bool found = false;
bool output = true;
for ( QStringList::Iterator it = settingsFileText.begin(); it != settingsFileText.end(); ++it ) {
QString line = (*it).simplifyWhiteSpace();
if(line.contains("case"))
foundCase = true;
// See if we found our scheme to write or the sceme couldn't be found
if((foundCase && line.contains("esac") && !found) ||
(foundCase && line.left(currentProfile.length()+7) == currentProfile + ",*,*,*)" && line.at(0) != '#')){
// write out scheme
found = true;
output = false;
if(!line.contains("esac"))
stream << line << "\n";
if(!essAny->isChecked() == true){
stream << "\tESSID=any\n";
stream << "\tMODE=Managed\n";
}
else{
stream << "\tESSID=" << essSpecificLineEdit->text() << '\n';
stream << "\tMODE=" << ( networkType->currentItem() == 0 ? "Managed" : "ad-hoc") << '\n';
stream << "\tCHANNEL=" << networkChannel->value() << "\n";
}
stream << "\t#KEY0=" << keyLineEdit0->text() << "\n";
stream << "\t#KEY1=" << keyLineEdit1->text() << "\n";
stream << "\t#KEY2=" << keyLineEdit2->text() << "\n";
stream << "\t#KEY3=" << keyLineEdit3->text() << "\n";
if(wepEnabled->isChecked()){
stream << "\tKEY=\"";
if(keyRadio0->isChecked()) stream << keyLineEdit0->text();
if(keyRadio1->isChecked()) stream << keyLineEdit1->text();
if(keyRadio2->isChecked()) stream << keyLineEdit2->text();
if(keyRadio3->isChecked()) stream << keyLineEdit3->text();
if(authOpen->isChecked())
stream << " open";
else
stream << " restricted";
stream << "\"\n";
}
stream << "\tRATE=auto\n";
if(line.contains("esac"))
stream << line << "\n";
}
if(line.contains(";;"))
output = true;
if(output && (*it).length() )
stream << (*it) << '\n';
}
file.close();
}
/**
* Check to see if the current config is valid
* Save wireless.opts, save interfaces
*/
void WLANImp::accept(){
if(wepEnabled->isChecked()){
if(keyLineEdit0->text().isEmpty() && keyLineEdit1->text().isEmpty() && keyLineEdit2->text().isEmpty() && keyLineEdit3->text().isEmpty() ){
QMessageBox::information(this, "Error", "Please enter a key for WEP.", QMessageBox::Ok);
return;
}
}
if(essAny->isChecked() && essSpecificLineEdit->text().isEmpty()){
QMessageBox::information(this, "Error", "Please enter a SSID.", QMessageBox::Ok);
return;
}
// Ok settings are good here, save
changeAndSaveSettingFile();
// Try to save the interfaces settings.
if(!interfaceSetup->saveChanges())
return;
OProcess insert;
insert << "sh";
insert << "-c";
insert << "cardctl eject && cardctl insert";
if (!insert.start(OProcess::DontCare, OProcess::NoCommunication) ) {
- qWarning("could not start cardctl");
+ owarn << "could not start cardctl" << oendl;
}
// Close out the dialog
QDialog::accept();
}
diff --git a/noncore/settings/networksettings/wlan/wlanimp2.cpp b/noncore/settings/networksettings/wlan/wlanimp2.cpp
index eeebe7f..e483efe 100644
--- a/noncore/settings/networksettings/wlan/wlanimp2.cpp
+++ b/noncore/settings/networksettings/wlan/wlanimp2.cpp
@@ -1,492 +1,492 @@
#include "wlanimp2.h"
#include "keyedit.h"
#include "interfacesetupimp.h"
#include "../interfaces/interface.h"
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <qapplication.h>
#include <qfile.h>
#include <qdir.h>
#include <qdialog.h>
#include <qtextstream.h>
#include <qmessagebox.h>
#include <qlineedit.h>
#include <qlabel.h>
#include <qspinbox.h>
#include <qradiobutton.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qtabwidget.h>
#include <qcombobox.h>
#include <qlistview.h>
#include <qvbox.h>
#include <qprogressbar.h>
#ifdef QWS
#include <qpe/resource.h>
#include <opie2/oprocess.h>
#include <opie2/onetwork.h>
#include <opie2/opcap.h>
#else
#define OProcess KProcess
#include <kprocess.h>
#endif
#define WIRELESS_OPTS "/etc/pcmcia/wireless.opts"
#define PREUP "/etc/network/if-pre-up.d/wireless-tools"
/**
* Constructor, read in the wireless.opts file for parsing later.
*/
using namespace Opie::Net;
using namespace Opie::Core;
WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl) : WLAN(parent, name, modal, fl), interface(i), currentProfile("*") {
interfaces = new Interfaces();
interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i, interfaces);
tabWidget->insertTab(interfaceSetup, "TCP/IP");
// Check sanity - the existance of the wireless-tools if-pre-up script
QFile file(QString(PREUP));
if (file.exists()) {
- qWarning(QString("WLANImp: Unable to open /etc/network/if-pre-up.d/wireless-tools"));
+ owarn << QString("WLANImp: Unable to open /etc/network/if-pre-up.d/wireless-tools") << oendl;
}
connect( rescanButton, SIGNAL( clicked() ), this, SLOT( rescanNeighbourhood() ) );
connect( netView, SIGNAL( clicked(QListViewItem*) ), this, SLOT( selectNetwork(QListViewItem*) ) );
netView->setColumnAlignment( col_chn, AlignCenter );
netView->setItemMargin( 3 );
netView->setAllColumnsShowFocus( true );
}
WLANImp::~WLANImp() {
//FIXME: delete interfaces;
}
/**
* Change the profile for both wireless settings and network settings.
*/
void WLANImp::setProfile(const QString &profile){
interfaceSetup->setProfile(profile);
parseOpts();
}
void WLANImp::parseOpts() {
bool error;
QString opt;
if (! interfaces->isInterfaceSet())
return;
opt = interfaces->getInterfaceOption("wireless_essid", error);
if(opt == "any" || opt == "off" || opt.isNull()){
essid->setEditText("any");
} else {
essid->setEditText(opt);
}
opt = interfaces->getInterfaceOption("wireless_mode", error).simplifyWhiteSpace();
for ( int i = 0; i < mode->count(); i++)
if ( mode->text( i ) == opt ) mode->setCurrentItem( i );
opt = interfaces->getInterfaceOption("wireless_ap", error).simplifyWhiteSpace();
if (! opt.isNull()) {
specifyAp->setChecked(true);
macEdit->setText(opt);
}
opt = interfaces->getInterfaceOption("wireless_channel", error).simplifyWhiteSpace();
if (! opt.isNull()) {
specifyChan->setChecked(true);
networkChannel->setValue(opt.toInt());
}
opt = interfaces->getInterfaceOption("wireless_key", error).simplifyWhiteSpace();
if (opt.isNull())
opt = interfaces->getInterfaceOption("wireless_enc", error).simplifyWhiteSpace();
parseKeyStr(opt);
}
void WLANImp::parseKeyStr(QString keystr) {
int loc = 0;
int index = 1;
QString key;
QStringList keys = QStringList::split(QRegExp("\\s+"), keystr);
int enc = -1; // encryption state
for (QStringList::Iterator it = keys.begin(); it != keys.end(); ++it) {
if ((*it).left(3) == "off") {
// encryption disabled
enc = 0;
} else if ((*it).left(2) == "on") {
// encryption enabled
enc = 1;
} else if ((*it).left(4) == "open") {
// open mode, accept non encrypted packets
acceptNonEnc->setChecked(true);
} else if ((*it).left(10) == "restricted") {
// restricted mode, only accept encrypted packets
rejectNonEnc->setChecked(true);
} else if ((*it).left(3) == "key") {
// new set of options
} else if ((*it).left(1) == "[") {
index = (*it).mid(1, 1).toInt();
// switch current key to index
switch (index) {
case 1:
keyRadio0->setChecked(true);
break;
case 2:
keyRadio1->setChecked(true);
break;
case 3:
keyRadio2->setChecked(true);
break;
case 4:
keyRadio3->setChecked(true);
break;
}
} else {
// key
key = (*it);
}
if (! key.isNull()) {
if (enc == -1)
enc = 1;
QStringList::Iterator next = ++it;
if (it == keys.end()) {
break;
}
if ((*(next)).left(1) == "[") {
// set key at index
index = (*(next)).mid(1, 1).toInt();
} else {
index = 1;
}
switch (index) {
case 1:
keyLineEdit0->setText(key);
break;
case 2:
keyLineEdit1->setText(key);
break;
case 3:
keyLineEdit2->setText(key);
break;
case 4:
keyLineEdit3->setText(key);
break;
}
key = QString::null;
}
}
if (enc == 1) {
wepEnabled->setChecked(true);
} else {
wepEnabled->setChecked(false);
}
}
/**
* Check to see if the current config is valid
* Save interfaces
*/
void WLANImp::accept() {
if (wepEnabled->isChecked()) {
if ((keyRadio0->isChecked() && keyLineEdit0->text().isEmpty()) ||
(keyRadio1->isChecked() && keyLineEdit1->text().isEmpty()) ||
(keyRadio2->isChecked() && keyLineEdit2->text().isEmpty()) ||
(keyRadio3->isChecked() && keyLineEdit3->text().isEmpty())) {
QMessageBox::information(this, "Error", "Please enter a WEP key.", QMessageBox::Ok);
return;
}
}
if (essid->currentText().isEmpty()) {
QMessageBox::information(this, "Error", "Please select/enter an ESSID.", QMessageBox::Ok);
return;
}
if (specifyAp->isChecked() && macEdit->text().isEmpty()) {
QMessageBox::information(this, "Error", "Please enter the MAC address of the Access Point.", QMessageBox::Ok);
return;
}
// Try to save the interfaces settings.
writeOpts();
// Close out the dialog
// FIXME: QDialog::accept();
}
void WLANImp::writeOpts() {
// eh can't really do anything about it other then return. :-D
if(!interfaces->isInterfaceSet()){
QMessageBox::warning(0,"Inface not set","should not happen!!!");
return;
}
bool error = false;
- qDebug("setting wlan interface %s", interfaces->getInterfaceName( error ).latin1() );
+ odebug << "setting wlan interface " << interfaces->getInterfaceName( error ).latin1() << "" << oendl;
if (error) QMessageBox::warning(0,"Inface not set","should not happen!!!");
interfaces->setInterfaceOption(QString("wireless_mode"), mode->currentText());
interfaces->setInterfaceOption(QString("wireless_essid"), essid->currentText());
if (specifyAp->isChecked()) {
interfaces->setInterfaceOption(QString("wireless_ap"), macEdit->text());
} else {
interfaces->removeInterfaceOption(QString("wireless_ap"));
}
if (specifyChan->isChecked()) {
interfaces->setInterfaceOption(QString("wireless_channel"), networkChannel->text());
} else {
interfaces->removeInterfaceOption(QString("wireless_channel"));
}
if (wepEnabled->isChecked()) {
QStringList keyList;
if (! keyLineEdit0->text().isNull()) {
keyList += keyLineEdit0->text();
keyList += "[1]";
} //else
if (! keyLineEdit1->text().isNull()) {
keyList += keyLineEdit1->text();
keyList += "[2]";
} //else
if (! keyLineEdit2->text().isNull()) {
keyList += keyLineEdit2->text();
keyList += "[3]";
} //else
if (! keyLineEdit3->text().isNull()) {
keyList += keyLineEdit3->text();
keyList += "[4]";
}
if (acceptNonEnc->isChecked()) {
keyList += "open";
} else {
keyList += "restricted";
}
keyList += "key";
if (keyRadio0->isChecked()) {
keyList += "[1]";
} else if (keyRadio1->isChecked()) {
keyList += "[2]";
} else if (keyRadio2->isChecked()) {
keyList += "[3]";
} else if (keyRadio3->isChecked()) {
keyList += "[4]";
}
interfaces->setInterfaceOption(QString("wireless_key"), keyList.join(QString(" ")));
} else {
interfaces->removeInterfaceOption(QString("wireless_key"));
}
interfaces->removeInterfaceOption(QString("wireless_enc"));
if(!interfaceSetup->saveChanges())
return;
QDialog::accept();
}
/*
* Scan for possible wireless networks around...
* ... powered by Wellenreiter II technology (C) Michael 'Mickey' Lauer <mickeyl@handhelds.org>
*/
void WLANImp::rescanNeighbourhood()
{
QString name = interface->getInterfaceName();
- qDebug( "rescanNeighbourhood via '%s'", (const char*) name );
+ odebug << "rescanNeighbourhood via '" << (const char*) name << "'" << oendl;
OWirelessNetworkInterface* wiface = static_cast<OWirelessNetworkInterface*>( ONetwork::instance()->interface( name ) );
assert( wiface );
// try to guess device type
QString devicetype;
QFile m( "/proc/modules" );
if ( m.open( IO_ReadOnly ) )
{
QString line;
QTextStream modules( &m );
while( !modules.atEnd() && !devicetype )
{
modules >> line;
if ( line.contains( "cisco" ) ) devicetype = "cisco";
else if ( line.contains( "hostap" ) ) devicetype = "hostap";
else if ( line.contains( "prism" ) ) devicetype = "wlan-ng"; /* puke */
else if ( line.contains( "orinoco" ) ) devicetype = "orinoco";
}
}
if ( devicetype.isEmpty() )
{
- qWarning( "rescanNeighbourhood(): couldn't guess device type :(" );
+ owarn << "rescanNeighbourhood(): couldn't guess device type :(" << oendl;
return;
}
else
{
- qDebug( "rescanNeighbourhood(): device type seems to be '%s'", (const char*) devicetype );
+ odebug << "rescanNeighbourhood(): device type seems to be '" << (const char*) devicetype << "'" << oendl;
}
// configure interface to receive 802.11 management frames
wiface->setUp( true );
wiface->setPromiscuousMode( true );
if ( devicetype == "cisco" ) wiface->setMonitoring( new OCiscoMonitoringInterface( wiface, false ) );
else if ( devicetype == "hostap" ) wiface->setMonitoring( new OHostAPMonitoringInterface( wiface, false ) );
else if ( devicetype == "wlan-ng" ) wiface->setMonitoring( new OWlanNGMonitoringInterface( wiface, false ) );
else if ( devicetype == "orinoco" ) wiface->setMonitoring( new OOrinocoMonitoringInterface( wiface, false ) );
else
{
- qDebug( "rescanNeighbourhood(): unsupported device type for monitoring :(" );
+ odebug << "rescanNeighbourhood(): unsupported device type for monitoring :(" << oendl;
return;
}
wiface->setMode( "monitor" );
if ( wiface->mode() != "monitor" )
{
- qWarning( "rescanNeighbourhood(): Unable to bring device into monitor mode (%s).", strerror( errno ) );
+ owarn << "rescanNeighbourhood(): Unable to bring device into monitor mode (" << strerror( errno ) << ")." << oendl;
return;
}
// open a packet capturer
OPacketCapturer* cap = new OPacketCapturer();
cap->open( name );
if ( !cap->isOpen() )
{
- qWarning( "rescanNeighbourhood(): Unable to open libpcap (%s).", strerror( errno ) );
+ owarn << "rescanNeighbourhood(): Unable to open libpcap (" << strerror( errno ) << ")." << oendl;
return;
}
// display splash screen
QFrame* splash = new QFrame( this, "splash", false, WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_Customize );
splash->setLineWidth( 2 );
splash->setFrameStyle( QFrame::Panel | QFrame::Raised );
QVBoxLayout* vbox = new QVBoxLayout( splash, 4, 4 );
QLabel* lab = new QLabel( "<center><b>Scanning...</b><br>Please Wait...</center>", splash );
QProgressBar* pb = new QProgressBar( wiface->channels(), splash );
vbox->addWidget( lab );
vbox->addWidget( pb );
pb->setCenterIndicator( true );
pb->setFixedHeight( pb->sizeHint().height() );
QWidget* widgetDesktop = qApp->desktop();
int dw = widgetDesktop->width();
int dh = widgetDesktop->height();
int pw = vbox->sizeHint().width();
int ph = vbox->sizeHint().height();
splash->setGeometry((dw-pw)/2,(dh-ph)/2,pw,ph);
splash->show();
splash->raise();
qApp->processEvents();
// set capturer to non-blocking mode
cap->setBlocking( false );
for ( int i = 1; i <= wiface->channels(); ++i )
{
wiface->setChannel( i );
pb->setProgress( i );
qApp->processEvents();
- qDebug( "rescanNeighbourhood(): listening on channel %d...", i );
+ odebug << "rescanNeighbourhood(): listening on channel " << i << "..." << oendl;
OPacket* p = cap->next( 1000 );
if ( !p )
{
- qDebug( "rescanNeighbourhood(): nothing received on channel %d", i );
+ odebug << "rescanNeighbourhood(): nothing received on channel " << i << "" << oendl;
}
else
{
- qDebug( "rescanNeighbourhood(): TADAA - something came in on channel %d", i );
+ odebug << "rescanNeighbourhood(): TADAA - something came in on channel " << i << "" << oendl;
handlePacket( p );
}
}
cap->close();
wiface->setMode( "managed" ); // TODO: use previous mode
wiface->setPromiscuousMode( false );
splash->hide();
delete splash;
}
void WLANImp::handlePacket( OPacket* p )
{
// check if we received a beacon frame
OWaveLanManagementPacket* beacon = static_cast<OWaveLanManagementPacket*>( p->child( "802.11 Management" ) );
if ( beacon && beacon->managementType() == "Beacon" )
{
QString type;
if ( beacon->canIBSS() )
{
type = "adhoc";
}
else if ( beacon->canESS() )
{
type = "managed";
}
else
{
- qWarning( "handlePacket(): invalid frame [possibly noise] detected!" );
+ owarn << "handlePacket(): invalid frame [possibly noise] detected!" << oendl;
return;
}
OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) );
QString essid = ssid ? ssid->ID() : QString("<unknown>");
OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) );
int channel = ds ? ds->channel() : -1;
OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
displayFoundNetwork( type, channel, essid, header->macAddress2() );
}
}
void WLANImp::displayFoundNetwork( const QString& mode, int channel, const QString& ssid, const OMacAddress& mac )
{
qDebug( "found network: <%s>, chn %d, ssid '%s', mac '%s'", (const char*) mode, channel,
(const char*) ssid,
(const char*) mac.toString() );
QListViewItemIterator it( netView );
while ( it.current() && it.current()->text( col_ssid ) != ssid ) ++it;
if ( !it.current() ) // ssid didn't show up yet
{
QListViewItem* item = new QListViewItem( netView, mode.left( 1 ).upper(), ssid, QString::number( channel ), mac.toString() );
QString name;
name.sprintf( "networksettings/%s", (const char*) mode );
item->setPixmap( col_mode, Resource::loadPixmap( name ) );
qApp->processEvents();
}
}
void WLANImp::selectNetwork( QListViewItem* item )
{
bool ok;
if ( item )
{
specifyAp->setChecked(true);
macEdit->setText( item->text( col_mac ) );
specifyChan->setChecked( item->text( col_mode ) == "A" );
networkChannel->setValue( item->text( col_chn ).toInt( &ok ) );
essid->setEditText( item->text( col_ssid ) );
if ( item->text( col_mode ) == "A" )
mode->setCurrentItem( 3 );
else
mode->setCurrentItem( 2 );
}
}
diff --git a/noncore/settings/networksettings/wlan/wlanmodule.cpp b/noncore/settings/networksettings/wlan/wlanmodule.cpp
index 74d7f8e..886af10 100644
--- a/noncore/settings/networksettings/wlan/wlanmodule.cpp
+++ b/noncore/settings/networksettings/wlan/wlanmodule.cpp
@@ -29,227 +29,227 @@ WLANModule::WLANModule()
/**
* Delete any interfaces that we own.
*/
WLANModule::~WLANModule(){
Interface *i;
for ( i=list.first(); i != 0; i=list.next() )
delete i;
}
/**
* Change the current profile
*/
void WLANModule::setProfile(const QString &newProfile){
profile = newProfile;
}
/**
* get the icon name for this device.
* @param Interface* can be used in determining the icon.
* @return QString the icon name (minus .png, .gif etc)
*/
QString WLANModule::getPixmapName(Interface* ){
return "wlan";
}
/**
* Check to see if the interface i is owned by this module.
* @param Interface* interface to check against
* @return bool true if i is owned by this module, false otherwise.
*/
bool WLANModule::isOwner(Interface *i){
WExtensions we(i->getInterfaceName());
if(!we.doesHaveWirelessExtensions())
return false;
i->setHardwareName("802.11b");
list.append(i);
return true;
}
/**
* Create, and return the WLANConfigure Module
* @return QWidget* pointer to this modules configure.
*/
QWidget *WLANModule::configure(Interface *i){
WLANImp *wlanconfig = new WLANImp(0, "WlanConfig", i, true, Qt::WDestructiveClose);
wlanconfig->setProfile(profile);
return wlanconfig;
}
/**
* Create, and return the Information Module
* @return QWidget* pointer to this modules info.
*/
QWidget *WLANModule::information(Interface *i){
WExtensions we(i->getInterfaceName());
if(!we.doesHaveWirelessExtensions())
return NULL;
return getInfo( i );
}
/**
* Get all active (up or down) interfaces
* @return QList<Interface> A list of interfaces that exsist that havn't
* been called by isOwner()
*/
QList<Interface> WLANModule::getInterfaces(){
return list;
}
/**
* Attempt to add a new interface as defined by name
* @param name the name of the type of interface that should be created given
* by possibleNewInterfaces();
* @return Interface* NULL if it was unable to be created.
*/
Interface *WLANModule::addNewInterface(const QString &){
// We can't add a 802.11 interface, either the hardware will be there
// or it wont.
return NULL;
}
/**
* Attempts to remove the interface, doesn't delete i
* @return bool true if successful, false otherwise.
*/
bool WLANModule::remove(Interface*){
// Can't remove a hardware device, you can stop it though.
return false;
}
void WLANModule::receive(const QCString &param, const QByteArray &arg)
{
- qDebug("WLANModule::receive "+param);
+ odebug << "WLANModule::receive "+param << oendl;
QStringList params = QStringList::split(",",param);
int count = params.count();
- qDebug("WLANModule got %i params", count );
+ odebug << "WLANModule got " << count << " params" << oendl;
if (count < 2){
- qDebug("Erorr less than 2 parameter");
- qDebug("RETURNING");
+ odebug << "Erorr less than 2 parameter" << oendl;
+ odebug << "RETURNING" << oendl;
return;
}
QDataStream stream(arg,IO_ReadOnly);
QString interface;
QString action;
int countMsgs = 0;
stream >> interface;
- qDebug("got count? >%s<",interface.latin1());
+ odebug << "got count? >" << interface.latin1() << "<" << oendl;
if (interface == "count"){
- qDebug("got count");
+ odebug << "got count" << oendl;
stream >> action;
- qDebug("Got count num >%s<", action.latin1());
+ odebug << "Got count num >" << action.latin1() << "<" << oendl;
countMsgs = action.toInt();
}
QDialog *toShow;
//while (! stream.atEnd() ){
for (int i = 0; i < countMsgs; i++){
- qDebug("start stream %d/%d",i,countMsgs);
+ odebug << "start stream " << i << "/" << countMsgs << "" << oendl;
if (stream.atEnd()){
- qDebug("end of stream");
+ odebug << "end of stream" << oendl;
return;
}
stream >> interface;
- qDebug("got iface");
+ odebug << "got iface" << oendl;
stream >> action;
- qDebug("WLANModule got interface %s and acion %s", interface.latin1(), action.latin1());
+ odebug << "WLANModule got interface " << interface.latin1() << " and acion " << action.latin1() << "" << oendl;
// find interfaces
Interface *ifa=0;
for ( Interface *i=list.first(); i != 0; i=list.next() ){
if (i->getInterfaceName() == interface){
- qDebug("WLANModule found interface %s",interface.latin1());
+ odebug << "WLANModule found interface " << interface.latin1() << "" << oendl;
ifa = i;
}
}
if (ifa == 0){
- qDebug("WLANModule Did not find %s",interface.latin1());
- qDebug("skipping");
+ odebug << "WLANModule Did not find " << interface.latin1() << "" << oendl;
+ odebug << "skipping" << oendl;
count = 0;
}
if (count == 2){
// those should call the interface directly
QWidget *info = getInfo( ifa );
QPEApplication::showWidget( info );
if ( action.contains("start" ) ){
ifa->start();
} else if ( action.contains("restart" ) ){
ifa->restart();
} else if ( action.contains("stop" ) ){
ifa->stop();
}else if ( action.contains("refresh" ) ){
ifa->refresh();
}
}else if (count == 3){
QString value;
if (!wlanconfigWiget){
//FIXME: what if it got closed meanwhile?
wlanconfigWiget = (WLANImp*) configure(ifa);
toShow = (QDialog*) wlanconfigWiget;
}
QPEApplication::showWidget( wlanconfigWiget );
stream >> value;
- qDebug("WLANModule (build 4) is setting %s of %s to %s", action.latin1(), interface.latin1(), value.latin1() );
+ odebug << "WLANModule (build 4) is setting " << action.latin1() << " of " << interface.latin1() << " to " << value.latin1() << "" << oendl;
if (value.isEmpty()){
- qDebug("value is empty!!!\nreturning");
+ odebug << "value is empty!!!\nreturning" << oendl;
return;
}
if ( action.contains("ESSID") ){
QComboBox *combo = wlanconfigWiget->essid;
bool found = false;
for ( int i = 0; i < combo->count(); i++)
if ( combo->text( i ) == value ){
combo->setCurrentItem( i );
found = true;
}
if (!found) combo->insertItem( value, 0 );
}else if ( action.contains("Mode") ){
QComboBox *combo = wlanconfigWiget->mode;
for ( int i = 0; i < combo->count(); i++)
if ( combo->text( i ) == value ){
combo->setCurrentItem( i );
}
}else if (action.contains("Channel")){
bool ok;
- qDebug("converting channel");
+ odebug << "converting channel" << oendl;
int chan = value.toInt( &ok );
if (ok){
- qDebug("ok setting channel");
+ odebug << "ok setting channel" << oendl;
wlanconfigWiget->specifyChan->setChecked( true );
wlanconfigWiget->networkChannel->setValue( chan );
}
}else if (action.contains("MacAddr")){
wlanconfigWiget->specifyAp->setChecked( true );
wlanconfigWiget->macEdit->setText( value );
}else
- qDebug("wlan plugin has no clue");
+ odebug << "wlan plugin has no clue" << oendl;
}
- qDebug("next stream");
+ odebug << "next stream" << oendl;
}// while stream
- qDebug("end of stream");
+ odebug << "end of stream" << oendl;
if (toShow) toShow->exec();
- qDebug("returning");
+ odebug << "returning" << oendl;
}
QWidget *WLANModule::getInfo( Interface *i)
{
- qDebug("WLANModule::getInfo start");
+ odebug << "WLANModule::getInfo start" << oendl;
WlanInfoImp *info = new WlanInfoImp(0, i->getInterfaceName(), Qt::WDestructiveClose);
InterfaceInformationImp *information = new InterfaceInformationImp(info->tabWidget, "InterfaceSetupImp", i);
info->tabWidget->insertTab(information, "TCP/IP", 0);
info->tabWidget->setCurrentPage( 0 );
info->tabWidget->showPage( information );
- if (info->tabWidget->currentPage() == information ) qDebug("infotab OK");
- else qDebug("infotab NOT OK");
- qDebug("current idx %d", info->tabWidget->currentPageIndex());
- qDebug("WLANModule::getInfo return");
+ if (info->tabWidget->currentPage() == information ) odebug << "infotab OK" << oendl;
+ else odebug << "infotab NOT OK" << oendl;
+ odebug << "current idx " << info->tabWidget->currentPageIndex() << "" << oendl;
+ odebug << "WLANModule::getInfo return" << oendl;
return info;
}
diff --git a/noncore/settings/sound/sound.pro b/noncore/settings/sound/sound.pro
index a3804c3..58e94f3 100644
--- a/noncore/settings/sound/sound.pro
+++ b/noncore/settings/sound/sound.pro
@@ -1,10 +1,9 @@
-CONFIG += qt warn_on quick-app
-HEADERS = soundsettings.h soundsettingsbase.h
-SOURCES = soundsettings.cpp soundsettingsbase.cpp main.cpp
-#INTERFACES = soundsettingsbase.ui
+CONFIG += qt warn_on quick-app
+HEADERS = soundsettings.h soundsettingsbase.h
+SOURCES = soundsettings.cpp soundsettingsbase.cpp main.cpp
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lopiecore2
-TARGET = sound
+LIBS += -lqpe -lopiecore2
+TARGET = sound
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/settings/sound/soundsettings.cpp b/noncore/settings/sound/soundsettings.cpp
index 8ad0a3f..d55a751 100644
--- a/noncore/settings/sound/soundsettings.cpp
+++ b/noncore/settings/sound/soundsettings.cpp
@@ -1,220 +1,224 @@
/**********************************************************************
** 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.
**
**********************************************************************/
// parts copyright 2002 L.J. Potter
#include "soundsettings.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/storage.h>
+using namespace Opie::Core;
+/* QT */
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qlabel.h>
+/* STD */
#include <sys/utsname.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
-#include <stdio.h>
#include <sys/stat.h>
SoundSettings::SoundSettings( QWidget* parent, const char* objname, WFlags fl )
: SoundSettingsBase( parent, objname, TRUE, fl )
{
keyReset=FALSE;
noWarning=false;
Config config( "qpe");
config.setGroup( "Volume" );
Config cfg("Vmemo");
connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
AlertCheckBox->setChecked(cfg.readBoolEntry("Alert"));
cfg.setGroup("Record");
int rate=config.readNumEntry("SampleRate", 22050);
if(rate == 8000)
sampleRate->setCurrentItem(0);
else if(rate == 11025)
sampleRate->setCurrentItem(1);
else if(rate == 22050)
sampleRate->setCurrentItem(2);
else if(rate == 33075)
sampleRate->setCurrentItem(3);
else if(rate==44100)
sampleRate->setCurrentItem(4);
stereoCheckBox->setChecked(cfg.readNumEntry("Stereo", 0));
//TODO hide if zaurus- mono only
#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX)
//since ipaq and zaurus have particular
//devices
bool systemZaurus=FALSE;
struct utsname name; /* check for embedix kernel running on the zaurus*/
if (uname(&name) != -1) {// TODO change this here,...
QString release=name.release;
if( release.find("embedix",0,TRUE) != -1) {
- qDebug("IS System Zaurus");
+ odebug << "IS System Zaurus" << oendl;
systemZaurus=TRUE;
}
}
if(!systemZaurus) {
stereoCheckBox->setChecked(TRUE);
}
stereoCheckBox->setEnabled(FALSE);
sixteenBitCheckBox->setEnabled(FALSE);
#else
#endif
int sRate=cfg.readNumEntry("SizeLimit", 30);
- qDebug("%d",sRate);
+ odebug << "" << sRate << "" << oendl;
if(sRate ==30)
timeLimitComboBox->setCurrentItem(0);
else if(sRate==20)
timeLimitComboBox->setCurrentItem(1);
else if(sRate == 15)
timeLimitComboBox->setCurrentItem(2);
else if(sRate == 10)
timeLimitComboBox->setCurrentItem(3);
else if(sRate == 5)
timeLimitComboBox->setCurrentItem(4);
else
timeLimitComboBox->setCurrentItem(5);
sixteenBitCheckBox->setChecked(cfg.readNumEntry("SixteenBit", 1));
cfg.setGroup("Defaults");
keyComboBox->setCurrentItem(cfg.readNumEntry("toggleKey") );
updateStorageCombo();
Config vmCfg("Vmemo");
vmCfg.setGroup("Defaults");
adpcmCheckBox->setChecked( vmCfg.readBoolEntry("use_ADPCM", 0));
connect( LocationComboBox,SIGNAL(activated(const QString&)), this,
SLOT( setLocation(const QString&)));
connect( keyComboBox,SIGNAL(activated(int)), this,
SLOT( setKeyButton(int)));
connect( timeLimitComboBox,SIGNAL(activated(const QString&)), this,
SLOT( setSizeLimitButton(const QString&)));
connect( restartCheckBox,SIGNAL( toggled(bool)), this,
SLOT( restartOpie(bool)));
connect( adpcmCheckBox,SIGNAL( toggled(bool)), this,
SLOT( slotAdpcm(bool)));
// connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
}
void SoundSettings::updateStorageCombo() {
Config config( "Vmemo" );
config.setGroup( "System" );
QString loc = config.readEntry("RecLocation","/");
int i=0;
int set=0;
StorageInfo storageInfo;
QString sName, sPath;
QStringList list;
list << "Documents : "+QPEApplication::documentDir();
list << "tmp : /tmp";
const QList<FileSystem> &fs = storageInfo.fileSystems();
QListIterator<FileSystem> it ( fs );
for( ; it.current(); ++it ){
const QString name = (*it)->name();
const QString path = (*it)->path();
- qDebug("storage name "+name +" storage path is "+path);
+ odebug << "storage name "+name +" storage path is "+path << oendl;
list << name + ": " +path;
if( loc.find( path,0,TRUE) != -1)
set = i;
// if(dit.current()->file().find(path) != -1 ) storage=name;
i++;
}
LocationComboBox->insertStringList(list);
- qDebug("set item %d", set);
+ odebug << "set item " << set << "" << oendl;
LocationComboBox->setCurrentItem(set);
}
void SoundSettings::setLocation(const QString & string) {
Config config( "Vmemo" );
config.setGroup( "System" );
config.writeEntry("RecLocation",string);
- qDebug("set location "+string);
+ odebug << "set location "+string << oendl;
config.write();
}
void SoundSettings::cleanUp() {
Config cfg("Vmemo");
cfg.writeEntry("Alert",AlertCheckBox->isChecked());
cfg.setGroup("Record");
cfg.writeEntry("SampleRate",sampleRate->currentText());
cfg.writeEntry("Stereo",stereoCheckBox->isChecked());
cfg.writeEntry("SixteenBit",sixteenBitCheckBox->isChecked());
if(keyReset && noWarning) {
QCopEnvelope ("QPE/System", "restart()");
}
}
void SoundSettings::setKeyButton( int index) {
Config cfg("Vmemo");
cfg.setGroup("Defaults");
cfg.writeEntry( "toggleKey", index );
keyReset = TRUE;
if( index == 1) {
cfg.writeEntry( "hideIcon", 0 );
keyLabel->setText(tr("Shows icon"));
}
else {
cfg.writeEntry( "hideIcon", 1);
keyLabel->setText(tr("Hides icon"));
}
cfg.write();
}
void SoundSettings::updateLocationCombo() {
}
void SoundSettings::setSizeLimitButton(const QString &index) {
Config cfg("Vmemo");
cfg.setGroup("Record");
if(index.find("Unlimited",0,TRUE) != -1)
cfg.writeEntry("SizeLimit", -1);
else
cfg.writeEntry("SizeLimit", index);
cfg.write();
}
void SoundSettings::restartOpie(bool b) {
noWarning=b;
}
void SoundSettings::slotAdpcm(bool b) {
Config vmCfg("Vmemo");
vmCfg.setGroup("Defaults");
vmCfg.writeEntry("use_ADPCM", b);
vmCfg.write();
}
diff --git a/noncore/settings/sysinfo/benchmarkinfo.cpp b/noncore/settings/sysinfo/benchmarkinfo.cpp
index 96bcdfc..4163fb2 100644
--- a/noncore/settings/sysinfo/benchmarkinfo.cpp
+++ b/noncore/settings/sysinfo/benchmarkinfo.cpp
@@ -1,272 +1,272 @@
/**********************************************************************
** BenchmarkInfo
**
** A benchmark for Qt/Embedded
**
** Copyright (C) 2004 Michael Lauer <mickey@vanille.de>
** Inspired by ZBench (C) 2002 Satoshi <af230533@im07.alpha-net.ne.jp>
**
** 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.
**
**********************************************************************/
#include "benchmarkinfo.h"
/* OPIE */
+#include <opie2/odebug.h>
#include <opie2/ostorageinfo.h>
#include <opie2/olistview.h>
#include <qpe/qpeapplication.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/qpedecoration_qws.h>
#include <qpe/resource.h>
#include <qpe/config.h>
+using namespace Opie::Core;
+using namespace Opie::Ui;
/* QT */
#include <qclipboard.h>
#include <qcolor.h>
#include <qcombobox.h>
#include <qdirectpainter_qws.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qfiledialog.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpainter.h>
#include <qpushbutton.h>
#include <qtimer.h>
#include <qwhatsthis.h>
/* STD */
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#if defined (__GNUC__) && (__GNUC__ < 3)
#define round qRound
#endif
-using namespace Opie::Ui;
-using namespace Opie::Core;
extern "C"
-
{
void BenchFFT( void );
double dhry_main( int );
}
#define DHRYSTONE_RUNS 20000000
#define TEST_DURATION 3
#define BUFF_SIZE 8192
#define FILE_SIZE 1024 * 1024 // 1Mb
//===========================================================================
class BenchmarkPaintWidget : public QWidget
{
public:
BenchmarkPaintWidget() : QWidget( 0, "Benchmark Paint Widget", WStyle_Customize|WStyle_StaysOnTop|WPaintUnclipped|WPaintClever )
{
resize( QApplication::desktop()->size() );
show();
p.begin( this );
};
~BenchmarkPaintWidget()
{
p.end();
hide();
};
QPainter p;
};
//===========================================================================
BenchmarkInfo::BenchmarkInfo( QWidget *parent, const char *name, int wFlags )
: QWidget( parent, name, wFlags )
{
setMinimumSize( 200, 150 );
QVBoxLayout* vb = new QVBoxLayout( this );
vb->setSpacing( 4 );
vb->setMargin( 4 );
tests = new OListView( this );
QWhatsThis::add( tests->viewport(), tr( "This area shows the available tests, the results for which the tests "
"have been performed, and comparison values for one selected device. "
"Use the checkboxes to define which tests you want to perform." ) );
tests->setMargin( 0 );
tests->addColumn( tr( "Tests" ) );
tests->addColumn( tr( "Results" ) );
tests->addColumn( tr( "Comparison" ) );
tests->setShowSortIndicator( true );
test_alu = new OCheckListItem( tests, tr( "1. Integer Arithmetic " ), OCheckListItem::CheckBox );
test_fpu = new OCheckListItem( tests, tr( "2. Floating Point Unit " ), OCheckListItem::CheckBox );
test_txt = new OCheckListItem( tests, tr( "3. Text Rendering " ), OCheckListItem::CheckBox );
test_gfx = new OCheckListItem( tests, tr( "4. Gfx Rendering " ), OCheckListItem::CheckBox );
test_ram = new OCheckListItem( tests, tr( "5. RAM Performance " ), OCheckListItem::CheckBox );
test_sd = new OCheckListItem( tests, tr( "6. SD Card Performance " ), OCheckListItem::CheckBox );
test_cf = new OCheckListItem( tests, tr( "7. CF Card Performance " ), OCheckListItem::CheckBox );
test_alu->setText( 1, "n/a" );
test_fpu->setText( 1, "n/a" );
test_txt->setText( 1, "n/a" );
test_gfx->setText( 1, "n/a" );
test_ram->setText( 1, "n/a" );
test_sd->setText( 1, "n/a" );
test_cf->setText( 1, "n/a" );
test_alu->setText( 2, "n/a" );
test_fpu->setText( 2, "n/a" );
test_txt->setText( 2, "n/a" );
test_gfx->setText( 2, "n/a" );
test_ram->setText( 2, "n/a" );
test_sd->setText( 2, "n/a" );
test_cf->setText( 2, "n/a" );
startButton = new QPushButton( tr( "&Start Tests!" ), this );
QWhatsThis::add( startButton, tr( "Click here to perform the selected tests." ) );
connect( startButton, SIGNAL( clicked() ), this, SLOT( run() ) );
vb->addWidget( tests, 2 );
QFile f( QPEApplication::qpeDir() + "/share/sysinfo/results" );
if ( f.open( IO_ReadOnly ) )
{
machineCombo = new QComboBox( this );
QWhatsThis::add( machineCombo, tr( "Choose a model to compare your results with." ) );
QTextStream ts( &f );
while( !ts.eof() )
{
QString machline = ts.readLine();
- qDebug( "sysinfo: parsing benchmark results for '%s'", (const char*) machline );
+ odebug << "sysinfo: parsing benchmark results for '" << (const char*) machline << "'" << oendl;
QString resline = ts.readLine();
machines.insert( machline, new QStringList( QStringList::split( ",", resline ) ) );
machineCombo->insertItem( machline );
}
QHBoxLayout* hb = new QHBoxLayout( vb );
hb->addWidget( new QLabel( tr( "Compare To:" ), this ) );
hb->addWidget( machineCombo, 2 );
connect( machineCombo, SIGNAL( activated(int) ), this, SLOT( machineActivated(int) ) );
}
vb->addWidget( startButton, 2 );
}
BenchmarkInfo::~BenchmarkInfo()
{}
void BenchmarkInfo::machineActivated( int index )
{
QStringList* results = machines[ machineCombo->text( index ) ];
if ( !results )
{
- qDebug( "sysinfo: no results available." );
+ odebug << "sysinfo: no results available." << oendl;
return;
}
QStringList::Iterator it = results->begin();
test_alu->setText( 2, *(it++) );
test_fpu->setText( 2, *(it++) );
test_txt->setText( 2, *(it++) );
test_gfx->setText( 2, *(it++) );
test_ram->setText( 2, *(it++) );
test_sd->setText( 2, *(it++) );
test_cf->setText( 2, *(it++) );
}
void BenchmarkInfo::run()
{
startButton->setText( "> Don't touch! Running Tests! Don't touch! <" );
qApp->processEvents();
QTime t;
if ( test_alu->isOn() )
{
int d = round( dhry_main( DHRYSTONE_RUNS ) );
test_alu->setText( 1, QString( "%1 dhrys" ).arg( QString::number( d ) ) );
test_alu->setOn( false );
}
if ( test_fpu->isOn() )
{
t.start();
BenchFFT();
test_fpu->setText( 1, QString( "%1 secs" ).arg( QString::number( t.elapsed() / 1000.0 ) ) );
test_fpu->setOn( false );
}
if ( test_txt->isOn() )
{
int value = textRendering( TEST_DURATION );
test_txt->setText( 1, QString( "%1 chars/sec" ).arg( QString::number( value / TEST_DURATION ) ) );
test_txt->setOn( false );
}
if ( test_gfx->isOn() )
{
int value = gfxRendering( TEST_DURATION );
test_gfx->setText( 1, QString( "%1 gops/sec" ).arg( QString::number( value / 4 / TEST_DURATION ) ) ); // 4 tests
test_gfx->setOn( false );
}
if ( test_ram->isOn() ) // /tmp is supposed to be in RAM on a PDA
{
performFileTest( "/tmp/benchmarkFile.dat", test_ram );
}
if ( test_cf->isOn() )
{
OStorageInfo storage;
performFileTest( storage.cfPath() + "/benchmarkFile.dat", test_cf );
}
if ( test_sd->isOn() )
{
OStorageInfo storage;
performFileTest( storage.sdPath() + "/benchmarkFile.dat", test_sd );
}
startButton->setText( tr( "&Start Tests!" ) );
}
int BenchmarkInfo::textRendering( int seconds )
{
QTime t;
t.start();
int stop = t.elapsed() + seconds * 1000;
int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 };
int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 };
int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 };
const QString text( "Opie Benchmark Test" );
int w = QApplication::desktop()->width();
int h = QApplication::desktop()->height();
srand( time( NULL ) );
BenchmarkPaintWidget bpw;
int loops = 0;
while ( t.elapsed() < stop )
{
int k = rand() % 9;
int s = rand() % 100;
bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
bpw.p.setFont( QFont( "Vera", s ) );
bpw.p.drawText( rand() % w, rand() % h, text, text.length() );
diff --git a/noncore/settings/tabmanager/tabmanager.cpp b/noncore/settings/tabmanager/tabmanager.cpp
index 15aeaf5..4274203 100644
--- a/noncore/settings/tabmanager/tabmanager.cpp
+++ b/noncore/settings/tabmanager/tabmanager.cpp
@@ -1,508 +1,508 @@
#include "tabmanager.h"
#include "app.h"
#include "wait.h"
#include "tabapplnk.h"
#include <qpe/applnk.h>
#include <qdir.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qlistview.h>
#include <qheader.h>
#include <qcombobox.h>
#include <qlineedit.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <stdlib.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
#define HOME_APP_DIR QPEApplication::qpeDir()+"/apps"
#define HOME_APP_INSTALL_DIR "/usr/lib/ipkg/info"
#define NEW_FOLDER "EmptyTab"
#define NEW_APPLICATION "NewApp"
#define APPLICATION_EXTENSION ".desktop"
#define APPLICATION_EXTENSION_LENGTH 8
/**
* Constructor. Sets up signals. Performs initial scan of applications
* and tabs
*/
TabManager::TabManager( QWidget* parent, const char* name):TabManagerBase(parent, name), changed(false), application(NULL){
rescanFolder(HOME_APP_DIR);
// Connect the signals and slots
connect(tabList, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(editItem(QListViewItem*)));
(tabList->header())->hide();
connect(tabList, SIGNAL(moveItem(QListViewItem*,QListViewItem*)), this, SLOT(moveApplication(QListViewItem*,QListViewItem*)));
}
/**
* If anything in the tab's have been changed then update the system or alert
* the user.
*/
TabManager::~TabManager(){
if(changed){
// Prompt.
//int answer = QMessageBox::warning(this, "Message", "Should your desktop be","Yes", "Cancel", 0, 1 );
//if (answer)
// return;
QCopEnvelope e("QPE/System", "linkChanged(QString)");
QString link; //we'll just send an empty string
e << link;
}
}
/**
* Scans root directory for any tabs or applications. Will recursivly go down,
* but will not follow symlinks.
* @param directory - the directory to look in.
* @param parent - the parent to place any new tabs or apps into. If parent is
* NULL then the item is a tab and should be placed as a child of the window.
*/
void TabManager::rescanFolder(QString directory, QListViewItem* parent){
- //qDebug(QString("rescanFolder: ") + directory.latin1());
+ //odebug << QString("rescanFolder: ") + directory.latin1() << oendl;
QDir d;
d.setPath(directory);
// Show hidden files for .directories
d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs);
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list ); // create list iterator
QFileInfo *fi; // pointer for traversing
while ( (fi=it.current()) ) { // for each file...
// If it is a dir and not .. or . then add it as a tab and go down.
if(fi->isDir()){
if(fi->fileName() != ".." && fi->fileName() != ".") {
QListViewItem* newItem;
if(!parent)
newItem = new QListViewItem(tabList, fi->fileName());
else
newItem = new QListViewItem(parent, fi->fileName());
itemList.insert(newItem, directory + "/" + fi->fileName() + "/.directory" );
rescanFolder(directory + "/" + fi->fileName(), newItem);
}
}
else{
// it is a file, if not a .directory add to parent.
// Change parents name and icon to reflect icon.
if(fi->fileName() == ".directory"){
AppLnk app(directory + "/" + fi->fileName());
if(parent){
parent->setPixmap(0,app.pixmap());
parent->setText(0, app.name());
}
}
else{
// Add any desktop files found.
QListViewItem* newItem;
if(directory != HOME_APP_DIR){
if(!parent)
newItem = new QListViewItem(tabList, fi->fileName());
else
newItem = new QListViewItem(parent, fi->fileName());
if(fi->fileName().right(APPLICATION_EXTENSION_LENGTH) == APPLICATION_EXTENSION){
AppLnk app(directory + "/" + fi->fileName());
newItem->setPixmap(0,app.pixmap());
newItem->setText(0, app.name());
itemList.insert(newItem, directory + "/" + fi->fileName());
}
}
}
}
++it; // goto next list element
}
}
/**
* Create a new blank Tab.
* Create a physical folder with .directory file
* Create a item on the list
*/
void TabManager::newFolder(){
QDir r;
r.mkdir(QString(HOME_APP_DIR) + "/" + NEW_FOLDER);
system((QString("echo [Desktop Entry] | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1());
system((QString("echo Name=" NEW_FOLDER " | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1());
QString homeLocation = QString(HOME_APP_DIR) + "/" + NEW_FOLDER + "/.directory";
QListViewItem *newItem = new QListViewItem(tabList, NEW_FOLDER);
itemList.insert(newItem, homeLocation );
// We have changed something.
changed = true;
}
/**
* Create a new blank application
* Make sure a tab is selected
* create physical file
* fill file with default information (entry, name, type).
*/
void TabManager::newApplication(){
QListViewItem *item = tabList->currentItem();
if(!item || item->parent())
return;
QString parentDir = itemList[item].mid(0,itemList[item].length()-11);
QString homeLocation = parentDir + "/" NEW_APPLICATION APPLICATION_EXTENSION;
system((QString("echo [Desktop Entry] | cat >> ") + homeLocation).latin1());
system((QString("echo Name=" NEW_APPLICATION " | cat >> ") + homeLocation).latin1());
int slash = parentDir.findRev('/', -1);
QString folderName = parentDir.mid(slash+1, parentDir.length());
system((QString("echo Type=") + folderName + " | cat >> " + homeLocation).latin1());
// Insert into the tree
QListViewItem *newItem = new QListViewItem(item, NEW_APPLICATION);
itemList.insert(newItem, homeLocation );
// We have changed something.
changed = true;
}
/**
* Remove the item.
* Check if we can
* Prompt user
* Delete physical file (Dir, remove .dir, then dir. File, remove file)
* Remove from installer if need too.
*/
void TabManager::removeItem(){
// Make sure we can delete
QListViewItem *item = tabList->currentItem();
if(!item)
return;
if(item->childCount() > 0){
QMessageBox::critical(this, tr("Message"), tr("Can't remove with applications\nstill in the group."), tr("Ok") );
return;
}
// Prompt.
int answer = QMessageBox::warning(this, tr("Message"), tr("Are you sure you want to delete?"), tr("Yes"), tr("Cancel"), 0, 1 );
if (answer)
return;
bool removeSuccessful = true;
QString location = itemList[item];
// Remove file (.directory in a Directory case)
if(!QFile::remove(location))
removeSuccessful = false;
// Remove directory
if(item->parent() == NULL){
// Remove .directory file string
location = location.mid(0,location.length()-10);
QDir dir;
if(!dir.rmdir(location))
removeSuccessful = false;
else
removeSuccessful = true;
}
// If removing failed.
if(!removeSuccessful){
- qDebug((QString("removeItem: ") + location).latin1());
+ odebug << (QString("removeItem: ") + location).latin1() << oendl;
QMessageBox::critical(this, tr("Message"), tr("Can't remove."), tr("Ok") );
return;
}
// Remove from the installer so it wont fail.
// Don't need to do this sense the current install uses rm -f so no error
// Remove from the gui list.
itemList.remove(item);
if(item->parent())
item->parent()->takeItem(item);
delete item;
// We have changed something.
changed = true;
}
/**
* Helper function. Edits the current item.
* calls editItem with the currently selected item.
*/
void TabManager::editCurrentItem(){
editItem(tabList->currentItem());
}
/**
* Edit the item that is passed in.
* Show application dialog and if anything changed
* @param item the item to edit.
*/
void TabManager::editItem( QListViewItem * item){
if(!item)
return;
TabAppLnk app(itemList[item]);
if(!app.isValid()){
- qDebug(QString("editItem: Not a valid applnk file: ") + itemList[item].latin1());
+ odebug << QString("editItem: Not a valid applnk file: ") + itemList[item].latin1() << oendl;
return;
}
// Fill with all of the icons
if(!application){
Wait waitDialog(this, "Wait dialog");
waitDialog.waitLabel->setText(tr("Gathering icons..."));
waitDialog.show();
qApp->processEvents();
application = new AppEdit(this, "Application edit", true);
QDir d(QPEApplication::qpeDir() + "/pics/");
d.setFilter( QDir::Files);
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list ); // create list iterator
QFileInfo *fi; // pointer for traversing
while ( (fi=it.current()) ) { // for each file...
QString fileName = fi->fileName();
if(fileName.right(4) == ".png"){
fileName = fileName.mid(0,fileName.length()-4);
QPixmap imageOfFile(Resource::loadPixmap(fileName));
QImage foo = imageOfFile.convertToImage();
foo = foo.smoothScale(16,16);
imageOfFile.convertFromImage(foo);
application->iconLineEdit->insertItem(imageOfFile,fileName);
}
- //qDebug(fi->fileName().latin1());
+ //odebug << fi->fileName().latin1() << oendl;
++it;
}
waitDialog.hide();
}
int pixmap = -1;
QString pixmapText = app.pixmapString();
QComboBox *f = application->iconLineEdit;
for(int i = 0; i < application->iconLineEdit->count(); i++){
if(f->text(i) == pixmapText){
pixmap = i;
break;
}
}
if(pixmap != -1)
application->iconLineEdit->setCurrentItem(pixmap);
else if(pixmapText.isEmpty()){
application->iconLineEdit->setCurrentItem(0);
}
else{
QPixmap imageOfFile(Resource::loadPixmap(pixmapText));
QImage foo = imageOfFile.convertToImage();
foo = foo.smoothScale(16,16);
imageOfFile.convertFromImage(foo);
application->iconLineEdit->insertItem(imageOfFile,pixmapText,0);
application->iconLineEdit->setCurrentItem(0);
}
application->nameLineEdit->setText(app.name());
application->execLineEdit->setText(app.exec());
application->commentLineEdit->setText(app.comment());
if(item->parent() == NULL){
application->execLineEdit->setEnabled(false);
application->TextLabel3->setEnabled(false);
application->setCaption(tr("Tab"));
}
else{
application->execLineEdit->setEnabled(true);
application->TextLabel3->setEnabled(true);
application->setCaption(tr("Application"));
}
// Only do somthing if they hit OK
application->showMaximized();
if(application->exec() == 0)
return;
// If nothing has changed exit (hmmm why did they hit ok?)
if(app.name() == application->nameLineEdit->text() &&
app.pixmapString() == application->iconLineEdit->currentText() &&
app.comment() == application->commentLineEdit->text() &&
app.exec() == application->execLineEdit->text())
return;
// Change the applnk file
QString oldName = app.name();
app.setName(application->nameLineEdit->text());
app.setIcon(application->iconLineEdit->currentText());
app.setComment(application->commentLineEdit->text());
app.setExec(application->execLineEdit->text());
if(!app.writeLink()){
QMessageBox::critical(this, tr("Message"), "Can't save.", tr("Ok") );
return;
}
// Update the gui icon and name
item->setText(0,app.name());
item->setPixmap(0,app.pixmap());
// We have changed something.
changed = true;
// If we were dealing with a new folder or new application change
// the file names. Also change the item location in itemList
if(oldName == NEW_FOLDER){
QDir r;
QString oldName = itemList[item];
oldName = oldName.mid(0,oldName.length()-11);
QString newName = oldName.mid(0,oldName.length()-9);
newName = newName + "/" + app.name();
r.rename(oldName, newName);
itemList.remove(item);
itemList.insert(item, newName + "/.directory" );
}
else if(oldName == NEW_APPLICATION){
if(!item->parent())
return;
QString parentDir = itemList[item->parent()];
QDir r;
QString oldName = itemList[item];
QString newName = oldName.mid(0, parentDir.length()-10);
newName = newName + app.name() + APPLICATION_EXTENSION;
r.rename(oldName, newName);
itemList.remove(item);
itemList.insert(item, newName);
}
}
/**
* Move an application from one directory to another.
* Move in the gui, move in the applnk file, move in the installer.
* @param item the application to move
* @pearam newGroup the new parent of this application
*/
void TabManager::moveApplication(QListViewItem *item, QListViewItem *newGroup){
// Can we even move it?
if(!item || !item->parent() || newGroup->parent())
return;
if(item->parent() == newGroup)
return;
// Get the new folder, new file name,
QString newFolder = itemList[newGroup];
newFolder = newFolder.mid(0,newFolder.length()-11);
int slash = newFolder.findRev('/', -1);
QString folderName = newFolder.mid(slash+1, newFolder.length());
QString desktopFile = itemList[item];
slash = desktopFile.findRev('/', -1);
desktopFile = desktopFile.mid(slash, desktopFile.length());
newFolder = newFolder + desktopFile;
// Move file
QDir r;
if(!r.rename(itemList[item], newFolder)){
QMessageBox::critical(this, tr("Message"), "Can't move application.", tr("Ok") );
return;
}
- //qDebug((QString("moveApplication: ") + itemList[item]).latin1());
- //qDebug((QString("moveApplication: ") + newFolder).latin1());
+ //odebug << (QString("moveApplication: ") + itemList[item]).latin1() << oendl;
+ //odebug << (QString("moveApplication: ") + newFolder).latin1() << oendl;
// Move in the gui
item->parent()->takeItem(item);
newGroup->insertItem(item);
newGroup->setOpen(true);
// Move file in the installer
QString installedAppFile;
if(findInstalledApplication(desktopFile, installedAppFile))
swapInstalledLocation(installedAppFile, desktopFile, newFolder);
else
- qDebug("moveApplication: No installed app found for dekstop file");
+ odebug << "moveApplication: No installed app found for dekstop file" << oendl;
// Move application type
AppLnk app(newFolder);
app.setType(folderName);
app.writeLink();
// Move in our internal list
itemList.remove(item);
itemList.insert(item, newFolder);
// We have changed something.
changed = true;
}
/**
* File the installed application that has this desktop file.
* Go through each file in HOME_APP_INSTALL_DIR and see if it contains desktop
* file
* @param desktopFile - the .desktop file to search for [foo.desktop]
* @param installedAppFile - location of the app install list
* @return true if successful, false if file not found.
*/
bool TabManager::findInstalledApplication(QString desktopFile, QString &installedAppFile){
QDir d;
d.setPath(HOME_APP_INSTALL_DIR);
d.setFilter( QDir::Files );
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list ); // create list iterator
QFileInfo *fi; // pointer for traversing
while ( (fi=it.current()) ) { // for each file...
QFile file(QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName());
if ( file.open(IO_ReadOnly) ) { // file opened successfully
QTextStream stream( &file ); // use a text stream
QString line;
while ( !stream.eof() ) { // until end of file...
line = stream.readLine(); // line of text excluding '\n'
if(line.contains(desktopFile)){
installedAppFile = QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName();
file.close();
return true;
}
}
file.close();
}
else
- qDebug((QString("findInstalledApplication: Can't open file") + HOME_APP_INSTALL_DIR + "/" + fi->fileName()).latin1());
+ odebug << (QString("findInstalledApplication: Can't open file") + HOME_APP_INSTALL_DIR + "/" + fi->fileName()).latin1() << oendl;
++it; // goto next list element
}
return false;
}
/**
* Open a file and replace a file containing the old desktop file with the new.
* @param installedAppFile application installed list
* @param desktopFile old .desktop file
* @param newLocation new .desktop file
*/
void TabManager::swapInstalledLocation( QString installedAppFile, QString desktopFile, QString newLocation ){
QFile file(installedAppFile);
if ( !file.open(IO_ReadOnly) ){
- qDebug(QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1());
+ odebug << QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1() << oendl;
return;
}
QTextStream stream( &file ); // use a text stream
QString allLines;
while ( !stream.eof() ) { // until end of file...
QString line = stream.readLine(); // line of text excluding '\n'
if(line.contains(desktopFile))
allLines += newLocation;
else
allLines += line;
allLines += '\n';
}
file.close();
if ( !file.open(IO_ReadWrite) ){
- qDebug(QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1());
+ odebug << QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1() << oendl;
return;
}
QTextStream streamOut( &file );
streamOut << allLines;
file.close();
}
// tabmanager.cpp
diff --git a/noncore/settings/usermanager/userdialog.cpp b/noncore/settings/usermanager/userdialog.cpp
index 5854fe0..3616507 100644
--- a/noncore/settings/usermanager/userdialog.cpp
+++ b/noncore/settings/usermanager/userdialog.cpp
@@ -1,133 +1,131 @@
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "userdialog.h"
#include "passwd.h"
/* OPIE */
+#include <opie2/odebug.h>
#include <opie2/odevice.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
+using namespace Opie::Ui;
/* QT */
#include <qlayout.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <qfile.h>
/* STD */
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
-
-using namespace Opie::Core;
-
-
/**
* UserDialog constructor. Setup the dialog, fill the groupComboBox & groupsListView with all groups.
*
*/
-using namespace Opie::Ui;
UserDialog::UserDialog(int viewmode, QWidget* parent, const char* name, bool modal, WFlags fl) : QDialog(parent, name, modal, fl)
{
vm=viewmode;
QVBoxLayout *layout = new QVBoxLayout(this);
myTabWidget=new QTabWidget(this,"User Tab Widget");
layout->addWidget(myTabWidget);
setupTab1();
setupTab2();
accounts->groupStringList.sort();
// And also fill the listview & the combobox with all available groups.
for( QStringList::Iterator it = accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it)
{
accounts->splitGroupEntry(*it);
if(accounts->gr_name.find(QRegExp("^#"),0))
{ // Skip commented lines.
new QCheckListItem(groupsListView,accounts->gr_name,QCheckListItem::CheckBox);
groupComboBox->insertItem(accounts->gr_name);
}
}
QPEApplication::showDialog( this );
}
/**
* Empty destructor.
*
*/
UserDialog::~UserDialog()
{}
/**
* Creates the first tab, all userinfo is here.
*
*/
void UserDialog::setupTab1()
{
QPixmap mypixmap;
QWidget *tabpage = new QWidget(myTabWidget,"page1");
QVBoxLayout *layout = new QVBoxLayout(tabpage);
layout->setMargin(5);
// Picture
picturePushButton = new QPushButton(tabpage,"Label");
picturePushButton->setMinimumSize(48,48);
picturePushButton->setMaximumSize(48,48);
picturePushButton->setPixmap(Resource::loadPixmap("usermanager/usericon")); // Load default usericon.
connect(picturePushButton,SIGNAL(clicked()),this,SLOT(clickedPicture())); // Clicking the picture should invoke pictureselector.
// Login
QLabel *loginLabel=new QLabel(tabpage,"Login: ");
loginLabel->setText("Login: ");
loginLineEdit=new QLineEdit(tabpage,"Login: ");
// UID
QLabel *uidLabel=new QLabel(tabpage,"uid: ");
uidLabel->setText("UserID: ");
uidLineEdit=new QLineEdit(tabpage,"uid: ");
uidLineEdit->setEnabled(false);
// Username (gecos)
QLabel *gecosLabel=new QLabel(tabpage,"gecos");
gecosLabel->setText("Username: ");
gecosLineEdit=new QLineEdit(tabpage,"gecos");
// Password
QLabel *passwordLabel=new QLabel(tabpage,"password");
passwordLabel->setText("Password: ");
passwordLineEdit=new QLineEdit(tabpage,"password");
passwordLineEdit->setEchoMode(QLineEdit::Password);
// Shell
QLabel *shellLabel=new QLabel(tabpage,"shell");
shellLabel->setText("Shell: ");
shellComboBox=new QComboBox(tabpage,"shell");
shellComboBox->setEditable(true);
shellComboBox->insertItem("/bin/sh");
shellComboBox->insertItem("/bin/ash");
shellComboBox->insertItem("/bin/false");
// Primary Group
QLabel *groupLabel=new QLabel(tabpage,"group");
groupLabel->setText("Primary group: ");
groupComboBox=new QComboBox(tabpage,"PrimaryGroup");
if(vm==VIEWMODE_NEW)
{
// Copy /etc/skel
skelLabel=new QLabel(tabpage,"skel");
skelLabel->setText("Copy /etc/skel: ");
skelCheckBox=new QCheckBox(tabpage);
skelCheckBox->setChecked(true);
}
// Widget layout
QHBoxLayout *hlayout=new QHBoxLayout(-1,"hlayout");
layout->addWidget(picturePushButton);
@@ -152,337 +150,337 @@ void UserDialog::setupTab1()
vlayout1->addSpacing(5);
vlayout1->addWidget(skelLabel);
}
// Second column, data
vlayout2->addWidget(loginLineEdit);
vlayout2->addSpacing(5);
vlayout2->addWidget(uidLineEdit);
vlayout2->addSpacing(5);
vlayout2->addWidget(gecosLineEdit);
vlayout2->addSpacing(5);
vlayout2->addWidget(passwordLineEdit);
vlayout2->addSpacing(5);
vlayout2->addWidget(shellComboBox);
vlayout2->addSpacing(5);
vlayout2->addWidget(groupComboBox);
if(vm==VIEWMODE_NEW)
{
vlayout2->addSpacing(5);
vlayout2->addWidget(skelCheckBox);
}
hlayout->addLayout(vlayout1);
hlayout->addLayout(vlayout2);
myTabWidget->addTab(tabpage,"User Info");
}
/**
* Creates the second tab containing additional groups for the user.
*
*/
void UserDialog::setupTab2()
{
QWidget *tabpage = new QWidget(myTabWidget,"page2");
QVBoxLayout *layout = new QVBoxLayout(tabpage);
layout->setMargin(5);
// Additional groups
groupsListView=new QListView(tabpage,"groups");
groupsListView->addColumn("Additional groups");
groupsListView->setColumnWidthMode(0,QListView::Maximum);
groupsListView->setMultiSelection(false);
groupsListView->setAllColumnsShowFocus(false);
layout->addSpacing(5);
// Grouplist
layout->addWidget(groupsListView);
myTabWidget->addTab(tabpage,"User Groups");
}
/**
* Static function that creates the userinfo dialog.
* The user will be prompted to add a user.
*
* @param uid This is a suggested available UID.
* @param gid This is a suggested available GID.
*
* @return <code>true</code> if the user was successfully added, otherwise <code>false</code>.
*
*/
bool UserDialog::addUser(int uid, int gid)
{
QCheckListItem *temp;
QFile ozTest;
int oz=false;
if(ODevice::inst()->system()==System_OpenZaurus) oz=true;
// viewmode is a workaround for a bug in qte-2.3.4 that gives bus error on manipulating adduserDialog's widgets here.
UserDialog *adduserDialog=new UserDialog(VIEWMODE_NEW);
adduserDialog->setCaption(tr("Add User"));
adduserDialog->userID=uid; // Set next available UID as default uid.
adduserDialog->groupID=gid; // Set next available GID as default gid.
// Insert default group into groupComboBox
adduserDialog->groupComboBox->insertItem("<create new group>",0);
adduserDialog->uidLineEdit->setText(QString::number(uid));
// If we're running on OZ, add new users to some default groups.
if(oz)
{
QListViewItemIterator iter( adduserDialog->groupsListView );
for ( ; iter.current(); ++iter )
{
temp=(QCheckListItem*)iter.current();
if (temp->text()=="video") temp->setOn(true);
if (temp->text()=="audio") temp->setOn(true);
if (temp->text()=="time") temp->setOn(true);
if (temp->text()=="power") temp->setOn(true);
if (temp->text()=="input") temp->setOn(true);
if (temp->text()=="sharp") temp->setOn(true);
if (temp->text()=="tty") temp->setOn(true);
}
}
// Show the dialog!
if(!(adduserDialog->exec())) return false;
if((adduserDialog->groupComboBox->currentItem()!=0))
{
accounts->findGroup(adduserDialog->groupComboBox->currentText());
adduserDialog->groupID=accounts->gr_gid;
- qWarning(QString::number(accounts->gr_gid));
+ owarn << QString::number(accounts->gr_gid) << oendl;
}
if(!(accounts->addUser(adduserDialog->loginLineEdit->text(), adduserDialog->passwordLineEdit->text(),
adduserDialog->uidLineEdit->text().toInt(), adduserDialog->groupID, adduserDialog->gecosLineEdit->text(),
QString("/home/")+adduserDialog->loginLineEdit->text() , adduserDialog->shellComboBox->currentText())))
{
QMessageBox::information(0,"Ooops!","Something went wrong!\nUnable to add user.");
return false;
}
// Add User to additional groups.
QListViewItemIterator it( adduserDialog->groupsListView );
for ( ; it.current(); ++it )
{
temp=(QCheckListItem*)it.current();
if (temp->isOn() )
accounts->addGroupMember(it.current()->text(0),adduserDialog->loginLineEdit->text());
}
// Copy image to pics/users/
if(!(adduserDialog->userImage.isNull()))
{
QDir d;
if(!(d.exists("/opt/QtPalmtop/pics/users")))
{
d.mkdir("/opt/QtPalmtop/pics/users");
}
QString filename="/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png";
// adduserDialog->userImage=adduserDialog->userImage.smoothScale(48,48);
adduserDialog->userImage.save(filename,"PNG");
}
// Should we copy the skeleton homedirectory /etc/skel to the user's homedirectory?
accounts->findUser(adduserDialog->loginLineEdit->text());
if(adduserDialog->skelCheckBox->isChecked())
{
QString command_cp;
QString command_chown;
command_cp.sprintf("cp -a /etc/skel/* %s/",accounts->pw_dir.latin1());
system(command_cp);
command_cp.sprintf("cp -a /etc/skel/.[!.]* %s/",accounts->pw_dir.latin1()); // Bug in busybox, ".*" includes parent directory, does this work as a workaround?
system(command_cp);
command_chown.sprintf("chown -R %d:%d %s",accounts->pw_uid,accounts->pw_gid,accounts->pw_dir.latin1());
system(command_chown);
}
return true;
}
/**
* Deletes the user account.
*
* @param username User to be deleted.
*
* @return <code>true</code> if the user was successfully deleted, otherwise <code>false</code>.
*
*/
bool UserDialog::delUser(const char *username)
{
if((accounts->findUser(username)))
{ // Does that user exist?
if(!(accounts->delUser(username)))
{ // Delete the user.
QMessageBox::information(0,"Ooops!","Something went wrong\nUnable to delete user: "+QString(username)+".");
}
}
else
{
QMessageBox::information(0,"Invalid Username","That username ("+QString(username)+")does not exist.");
return false;
}
return true;
}
/**
* This displays a confirmation dialog wether a user should be deleted or not.
* (And also deletes the account)
*
* @param username User to be deleted.
*
* @return <code>true</code> if the user was successfully deleted, otherwise <code>false</code>.
*
*/
bool UserDialog::editUser(const char *username)
{
int invalid_group=0;
// viewmode is a workaround for a bug in qte-2.3.4 that gives bus error on manipulating edituserDialog's widgets here.
UserDialog *edituserDialog=new UserDialog(VIEWMODE_EDIT); // Create Dialog
edituserDialog->setCaption(tr("Edit User"));
accounts->findUser(username); // Locate user in database and fill variables in 'accounts' object.
if(!(accounts->findGroup(accounts->pw_gid)))
{ // Locate the user's primary group, and fill group variables in 'accounts' object.
invalid_group=1;
}
// Fill widgets with userinfo.
edituserDialog->loginLineEdit->setText(accounts->pw_name);
edituserDialog->uidLineEdit->setText(QString::number(accounts->pw_uid));
edituserDialog->gecosLineEdit->setText(accounts->pw_gecos);
// Set password to '........', we will later check if this still is the contents, if not, the password has been changed.
edituserDialog->passwordLineEdit->setText("........");
// If this user is not using /bin/sh,/bin/ash or /bin/false as shell, add that entry to the shell-combobox.
if(accounts->pw_shell!="/bin/sh" && accounts->pw_shell!="/bin/ash" && accounts->pw_shell!="/bin/false")
{
edituserDialog->shellComboBox->insertItem(accounts->pw_shell,0);
edituserDialog->shellComboBox->setCurrentItem(0);
}
// Select the primary group for this user.
for(int i=0;i<edituserDialog->groupComboBox->count();++i)
{
if(accounts->gr_name==edituserDialog->groupComboBox->text(i))
{
edituserDialog->groupComboBox->setCurrentItem(i);
break;
}
}
if(invalid_group)
{
edituserDialog->groupComboBox->insertItem("<Undefined group>",0);
edituserDialog->groupComboBox->setCurrentItem(0);
}
// Select the groups in the listview, to which the user belongs.
QCheckListItem *temp;
// BAH!!! QRegExp in qt2 sucks... or maybe I do... can't figure out how to check for EITHER end of input ($) OR a comma, so here we do two different QRegExps instead.
QRegExp userRegExp(QString("[:,]%1$").arg(username)); // The end of line variant.
QStringList tempList=accounts->groupStringList.grep(userRegExp); // Find all entries in the group database, that the user is a member of.
for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it)
{ // Iterate over all of them.
- qWarning(*it);
+ owarn << *it << oendl;
QListViewItemIterator lvit( edituserDialog->groupsListView ); // Compare to all groups.
for ( ; lvit.current(); ++lvit )
{
if(lvit.current()->text(0)==(*it).left((*it).find(":")))
{
temp=(QCheckListItem*)lvit.current();
temp->setOn(true); // If we find a line with that groupname, select it.;
}
}
}
userRegExp=QRegExp(QString("[:,]%1,").arg(username)); // And the other one. (not end of line.)
tempList=accounts->groupStringList.grep(userRegExp); // Find all entries in the group database, that the user is a member of.
for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it)
{ // Iterate over all of them.
- qWarning(*it);
+ owarn << *it << oendl;
QListViewItemIterator lvit( edituserDialog->groupsListView ); // Compare to all groups.
for ( ; lvit.current(); ++lvit )
{
if(lvit.current()->text(0)==(*it).left((*it).find(":")))
{
temp=(QCheckListItem*)lvit.current();
temp->setOn(true); // If we find a line with that groupname, select it.;
}
}
}
if(!(edituserDialog->exec())) return false; // SHOW THE DIALOG!
accounts->findUser(username); // Fill user variables in 'acccounts' object.
accounts->pw_name=edituserDialog->loginLineEdit->text();
// Has the password been changed ? Make a new "crypt":ed password.
if(edituserDialog->passwordLineEdit->text()!="........") accounts->pw_passwd=crypt(edituserDialog->passwordLineEdit->text(), accounts->crypt_make_salt());
// Set all variables in accounts object, that will be used when calling 'updateUser()'
accounts->pw_uid=edituserDialog->uidLineEdit->text().toInt();
if(accounts->findGroup(edituserDialog->groupComboBox->currentText()))
{ // Fill all group variables in 'accounts' object.
accounts->pw_gid=accounts->gr_gid; // Only do this if the group is a valid group (ie. "<Undefined group>"), otherwise keep the old group.
}
accounts->pw_gecos=edituserDialog->gecosLineEdit->text();
accounts->pw_shell=edituserDialog->shellComboBox->currentText();
// Update userinfo, using the information stored in the user variables stored in the accounts object.
accounts->updateUser(username);
// Remove user from all groups he/she is a member of. (could be done in a better way I guess, this was simple though.)
for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it)
{
accounts->delGroupMember((*it).left((*it).find(":")),username);
}
// Add User to additional groups that he/she is a member of.
QListViewItemIterator it( edituserDialog->groupsListView );
for ( ; it.current(); ++it )
{
temp=(QCheckListItem*)it.current();
if ( temp->isOn() )
accounts->addGroupMember(it.current()->text(0),edituserDialog->loginLineEdit->text());
}
// Copy image to pics/users/
if(!(edituserDialog->userImage.isNull()))
{
QDir d;
if(!(d.exists("/opt/QtPalmtop/pics/users")))
{
d.mkdir("/opt/QtPalmtop/pics/users");
}
QString filename="/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png";
// edituserDialog->userImage=edituserDialog->userImage.smoothScale(48,48);
edituserDialog->userImage.save(filename,"PNG");
}
return true;
}
/**
* "OK" has been clicked. Verify some information before closing the dialog.
*
*/
void UserDialog::accept()
{
// Add checking... valid username? username taken?
if(loginLineEdit->text().isEmpty())
{
QMessageBox::information(0,"Empty Login","Please enter a login.");
return;
}
QDialog::accept();
}
/**
* This slot is called when the usericon is clicked, this loads (should) the iconselector.
*
*/
void UserDialog::clickedPicture()
{
QString filename=OFileDialog::getOpenFileName(OFileSelector::EXTENDED, QString::null);
if(!(filename.isEmpty()))
{
userImage.reset();
if(!(userImage.load(filename)))
{
QMessageBox::information(0,"Sorry!","That icon could not be loaded.\nLoading failed on: "+filename);
}
else
{
// userImage=userImage.smoothScale(48,48);
QPixmap *picture;
picture=(QPixmap *)picturePushButton->pixmap();
picture->convertFromImage(userImage,0);
picturePushButton->update();
}
diff --git a/noncore/settings/usermanager/usermanager.cpp b/noncore/settings/usermanager/usermanager.cpp
index a1130d4..1d345ee 100644
--- a/noncore/settings/usermanager/usermanager.cpp
+++ b/noncore/settings/usermanager/usermanager.cpp
@@ -1,113 +1,116 @@
/***************************************************************************
* *
* 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 "usermanager.h"
-#include <qlayout.h>
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/resource.h>
+using namespace Opie::Core;
+/* QT */
+#include <qlayout.h>
#include <qmessagebox.h>
#include <qfile.h>
-#include <qpe/resource.h>
-
#include <qregexp.h>
/**
* The mainwindow constructor.
*
* @param QWidget *parent
* @param const char *name
* @ param WFlags fl
*
*/
UserConfig::UserConfig(QWidget* parent, const char* name, WFlags fl) : QMainWindow(parent, name, fl) {
setCaption(tr("Opie User Manager"));
// Create an instance of the global object 'accounts'. This holds all user/group info, and functions to modify them.
accounts=new Passwd();
accounts->open(); // This actually loads the files /etc/passwd & /etc/group into memory.
// Create the toolbar.
QToolBar *toolbar = new QToolBar(this,"Toolbar");
toolbar->setHorizontalStretchable(1); // Is there any other way to get the toolbar to stretch of the full screen!?
adduserToolButton = new QToolButton(Resource::loadPixmap("usermanager/adduser"),"Add User",0,this,SLOT(addUser()),toolbar,"Add User");
edituserToolButton = new QToolButton(Resource::loadPixmap("usermanager/edituser"),"Edit User",0,this,SLOT(editUser()),toolbar,"Edit User");
deleteuserToolButton = new QToolButton(Resource::loadPixmap("usermanager/deleteuser"),"Delete User",0,this,SLOT(delUser()),toolbar,"Delete User");
QToolButton *userstext = new QToolButton(0,"User",0,0,0,toolbar,"User");
userstext->setUsesTextLabel(true);
toolbar->addSeparator();
addgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/addgroup"),"Add Group",0,this,SLOT(addGroup()),toolbar,"Add Group");
editgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/editgroup"),"Edit Group",0,this,SLOT(editGroup()),toolbar,"Edit Group");
deletegroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/deletegroup"),"Delete Group",0,this,SLOT(delGroup()),toolbar,"Delete Group");
QToolButton *groupstext = new QToolButton(0,"Group",0,0,0,toolbar,"Group");
groupstext->setUsesTextLabel(true);
addToolBar(toolbar,"myToolBar");
// Add a tabwidget and all the tabs.
myTabWidget = new QTabWidget(this,"My Tab Widget");
setupTabAccounts();
setupTabAllUsers();
setupTabAllGroups();
userPopupMenu.insertItem("Copy",0);
getUsers(); // Fill out the iconview & listview with all users.
getGroups(); // Fill out the group listview with all groups.
setCentralWidget(myTabWidget);
}
UserConfig::~UserConfig() {
accounts->close();
delete accounts;
}
void UserConfig::setupTabAccounts() {
QWidget *tabpage = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(tabpage);
layout->setMargin(5);
usersIconView=new QListView(tabpage,"users");
usersIconView->addColumn("Icon");
usersIconView->addColumn("Username");
usersIconView->setAllColumnsShowFocus(true);
layout->addWidget(usersIconView);
connect(usersIconView,SIGNAL(returnPressed(QListViewItem*)),this,SLOT(showUserMenu(QListViewItem*)));
myTabWidget->addTab(tabpage,"Users");
}
void UserConfig::setupTabAllUsers() {
QWidget *tabpage = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(tabpage);
layout->setMargin(5);
usersListView=new QListView(tabpage,"allusers");
usersListView->addColumn("UID");
usersListView->addColumn("Login");
usersListView->addColumn("Username");
layout->addWidget(usersListView);
usersListView->setSorting(1,1);
usersListView->setAllColumnsShowFocus(true);
myTabWidget->addTab(tabpage,"All Users");
}
void UserConfig::setupTabAllGroups() {
QWidget *tabpage = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(tabpage);
layout->setMargin(5);
groupsListView=new QListView(tabpage,"groups");
groupsListView->addColumn("GID");
groupsListView->addColumn("Groupname");
layout->addWidget(groupsListView);
groupsListView->setSorting(1,1);
groupsListView->setAllColumnsShowFocus(true);
myTabWidget->addTab(tabpage,"All Groups");
@@ -160,98 +163,98 @@ void UserConfig::editUser() {
getGroups();
}
} else {
QMessageBox::information(this,"No selection.","No user has been selected.");
}
}
if(myTabWidget->currentPageIndex()==1) { // All users
if(usersListView->currentItem()) { // Anything changed!?
username=usersListView->currentItem()->text(1); // Get the username.
if(UserDialog::editUser(username)) { // Bring up the userinfo dialog.
// And again update the views if there were any changes.
getUsers();
getGroups();
}
} else {
QMessageBox::information(this,"No selection.","No user has been selected.");
}
}
}
void UserConfig::delUser() {
QString username;
if(myTabWidget->currentPageIndex()==0) { // Users, Iconview.
if(usersIconView->currentItem()) { // Anything selected?
username=usersIconView->currentItem()->text(1); // Get string associated with icon.
username=username.left(username.find(" - (",0,true)); // Strip out the username.
if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) {
if(UserDialog::delUser(username)) { // Delete the user if possible.
// Update views.
getUsers();
getGroups();
}
}
} else {
QMessageBox::information(this,"No selection","No user has been selected.");
}
}
if(myTabWidget->currentPageIndex()==1) { // All users
if(usersListView->currentItem()) { // Anything changed!?
username=usersListView->currentItem()->text(1); // Get the username.
if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) {
if(UserDialog::delUser(username)) { // Try to delete the user.
// Update views.
getUsers();
getGroups();
}
}
} else {
QMessageBox::information(this,"No selection","No user has been selected.");
}
}
}
void UserConfig::getGroups() {
groupsListView->clear(); // Empty the listview.
availableGID=500; // We need to find the next free GID, and are only interested in values between 500 & 65000.
for(QStringList::Iterator it=accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it) { // Split the list into lines.
accounts->splitGroupEntry(*it); // Split the line into its components and fill the variables of 'accounts'. (gr_name, gr_uid & gr_mem).
if(accounts->gr_name.find(QRegExp("^#"),0)) { // Skip commented lines.
new QListViewItem(groupsListView,QString::number(accounts->gr_gid),accounts->gr_name);
if((accounts->gr_gid>=availableGID) && (accounts->gr_gid<65000)) availableGID=accounts->gr_gid+1; // Maybe a new free GID.
}
}
}
void UserConfig::addGroup() {
if(GroupDialog::addGroup(availableGID)) getGroups(); // Bring up the add group dialog.
}
void UserConfig::editGroup() {
int gid;
if(groupsListView->currentItem()) { // Any group selected?
gid=groupsListView->currentItem()->text(0).toInt(); // Get the GID from the listview.
if(GroupDialog::editGroup(gid)) getGroups(); // Bring up the edit group dialog.
} else {
QMessageBox::information(this,"No selection","No group has been selected.");
}
}
void UserConfig::delGroup() {
const char *groupname;
if(groupsListView->currentItem()) { // Any group selected?
groupname=groupsListView->currentItem()->text(1); // Get the groupname from the listview.
if(QMessageBox::warning(this,"Delete group","Are you sure you want to\ndelete the group \""+QString(groupname)+"\" ?","&No","&Yes",0,0,1)) {
// If confirmed, try to delete the group.
if(GroupDialog::delGroup(groupname)) getGroups(); // And also update the view afterwards if the user was deleted.
}
} else {
QMessageBox::information(this,"No selection","No group has been selected.");
}
}
void UserConfig::showUserMenu(QListViewItem *item) {
// userPopupMenu.exec(item->mapToGlobal(QPoint(0,0)));
- qWarning("Pressed!");
+ owarn << "Pressed!" << oendl;
}
diff --git a/noncore/settings/usermanager/usermanager.pro b/noncore/settings/usermanager/usermanager.pro
index d0647dd..31f52a6 100644
--- a/noncore/settings/usermanager/usermanager.pro
+++ b/noncore/settings/usermanager/usermanager.pro
@@ -1,10 +1,9 @@
-#CONFIG = qt warn_on
-CONFIG = qt warn_on quick-app
+CONFIG = qt warn_on quick-app
HEADERS = usermanager.h userdialog.h groupdialog.h passwd.h
SOURCES = usermanager.cpp userdialog.cpp groupdialog.cpp passwd.cpp main.cpp
INCLUDEPATH += $(OPIEDIR)/include
-DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lopiecore2 -lopieui2 -lcrypt
-TARGET = usermanager
+DEPENDPATH += $(OPIEDIR)/include
+LIBS += -lqpe -lopiecore2 -lopieui2 -lcrypt
+TARGET = usermanager
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/styles/liquid/config.in b/noncore/styles/liquid/config.in
index 23f8637..cffdb39 100644
--- a/noncore/styles/liquid/config.in
+++ b/noncore/styles/liquid/config.in
@@ -1,4 +1,4 @@
config LIQUID
boolean "opie-liquid (Mosfet's well known Liquid GUI style from KDE)"
default "y"
- depends ( LIBQPE || LIBQPE-X11 ) && LIBQTAUX
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBQTAUX && LIBOPIE2CORE
diff --git a/noncore/styles/liquid/liquid.cpp b/noncore/styles/liquid/liquid.cpp
index bac882c..51814e7 100644
--- a/noncore/styles/liquid/liquid.cpp
+++ b/noncore/styles/liquid/liquid.cpp
@@ -1,248 +1,253 @@
/*-
* Copyright (C)QPL 2001 Daniel M. Duley. All rights reserved.
*/
//
// (c) 2002 Robert 'sandman' Griebl
//
#ifndef INCLUDE_MENUITEM_DEF
#define INCLUDE_MENUITEM_DEF
#endif
-#include <qmenudata.h>
#include "liquid.h"
-//#include "liquiddeco.h"
-#include <qapplication.h>
+#include "effects.h"
+#include "htmlmasks.h"
+#include "embeddata.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/config.h>
-#include "effects.h"
+using namespace Opie::Core;
+
+/* QT */
+#include <qmenudata.h>
+#include <qapplication.h>
#include <qpalette.h>
#include <qbitmap.h>
#include <qtabbar.h>
#include <qpopupmenu.h>
#include <qobjectlist.h>
#include <qimage.h>
#include <qtimer.h>
#include <qpixmapcache.h>
#include <qradiobutton.h>
#include <qcombobox.h>
#include <qdrawutil.h>
#include <qwidgetlist.h>
#include <qtoolbutton.h>
#include <qheader.h>
-#include <unistd.h>
#include <qmenubar.h>
#include <qprogressbar.h>
#include <qlineedit.h>
#include <qlistbox.h>
+/* STD */
+#include <unistd.h>
#include <stdio.h>
-#include "htmlmasks.h"
-#include "embeddata.h"
-
typedef void (QStyle::*QDrawMenuBarItemImpl) (QPainter *, int, int, int, int, QMenuItem *,
QColorGroup &, bool, bool);
QDrawMenuBarItemImpl qt_set_draw_menu_bar_impl(QDrawMenuBarItemImpl impl);
void TransMenuHandler::stripePixmap(QPixmap &pix, const QColor &color)
{
QImage img(pix.convertToImage());
QImageEffect::fade(img, 0.9, color);
int x, y;
int r, g, b;
for(y=0; y < img.height(); y+=3){
unsigned int *data = (unsigned int *) img.scanLine(y);
for(x=0; x < img.width(); ++x){
r = qRed(data[x]);
g = qGreen(data[x]);
b = qBlue(data[x]);
if(r-10)
r-=10;
if(g-10)
g-=10;
if(b-10)
b-=10;
data[x] = qRgb(r, g, b);
}
}
pix.convertFromImage(img);
}
TransMenuHandler::TransMenuHandler(QObject *parent)
: QObject(parent)
{
pixDict.setAutoDelete(true);
reloadSettings();
}
void TransMenuHandler::reloadSettings()
{
pixDict.clear();
Config config ( "qpe" );
config. setGroup ( "Liquid-Style" );
type = config. readNumEntry("Type", TransStippleBg);
color = QColor ( config. readEntry("Color", QApplication::palette().active().button().name()));
fgColor = QColor ( config. readEntry("TextColor", QApplication::palette().active().text().name()));
opacity = config. readNumEntry("Opacity", 10);
if ( opacity < -20 )
opacity = 20;
else if ( opacity > 20 )
opacity = 20;
shadowText = config. readBoolEntry("ShadowText", true);
}
bool TransMenuHandler::eventFilter(QObject *obj, QEvent *ev)
{
QWidget *p = (QWidget *)obj;
if(ev->type() == QEvent::Show){
if(type == TransStippleBg || type == TransStippleBtn ||
type == Custom){
QApplication::syncX();
QPixmap *pix = new QPixmap;
if(p->testWFlags(Qt::WType_Popup)){
QRect r(p->x(), p->y(), p->width(), p->height());
QRect deskR = QApplication::desktop()->rect();
if(r.right() > deskR.right() || r.bottom() > deskR.bottom()){
r.setBottom(deskR.bottom());
r.setRight(deskR.right());
}
*pix = QPixmap::grabWindow(QApplication::desktop()-> winId(), r.x(), r.y(),
r.width(), r.height());
}
else{ // tear off menu
pix->resize(p->width(), p->height());
pix->fill(Qt::black.rgb());
}
if(type == TransStippleBg){
stripePixmap(*pix, p->colorGroup().background());
}
else if(type == TransStippleBtn){
stripePixmap(*pix, p->colorGroup().button());
}
else{
QPixmapEffect::fade(*pix, (((float)opacity)+80)*0.01, color);
}
pixDict.insert(p->winId(), pix);
if ( !p->inherits("QPopupMenu"))
p->setBackgroundPixmap(*pix);
QObjectList *ol = p-> queryList("QWidget");
for ( QObjectListIt it( *ol ); it. current ( ); ++it ) {
QWidget *wid = (QWidget *) it.current ( );
wid-> setBackgroundPixmap(*pix);
wid-> setBackgroundOrigin(QWidget::ParentOrigin);
}
delete ol;
}
}
else if(ev->type() == QEvent::Hide){
if(type == TransStippleBg || type == TransStippleBtn ||
type == Custom){
-// qWarning("Deleting menu pixmap, width %d", pixDict.find(p->winId())->width());
+// owarn << "Deleting menu pixmap, width " << pixDict.find(p->winId())->width() << "" << oendl;
pixDict.remove(p->winId());
if ( !p->inherits("QPopupMenu"))
p->setBackgroundMode(QWidget::PaletteBackground);
QObjectList *ol = p-> queryList("QWidget");
for ( QObjectListIt it( *ol ); it. current ( ); ++it ) {
QWidget *wid = (QWidget *) it.current ( );
wid-> setBackgroundMode( QWidget::PaletteBackground );
}
delete ol;
}
}
return(false);
}
LiquidStyle::LiquidStyle()
:QWindowsStyle()
{
setName ( "LiquidStyle" );
flatTBButtons = false;
currentHeader = 0;
btnMaskBmp = QBitmap(37, 26, buttonmask_bits, true);
btnMaskBmp.setMask(btnMaskBmp);
htmlBtnMaskBmp = QBitmap(37, 26, htmlbuttonmask_bits, true);
htmlBtnMaskBmp.setMask(htmlBtnMaskBmp);
headerHoverID = -1;
highlightWidget = NULL;
setButtonDefaultIndicatorWidth(0);
btnDict.setAutoDelete(true);
bevelFillDict.setAutoDelete(true);
smallBevelFillDict.setAutoDelete(true);
rMatrix.rotate(270.0);
btnBorderPix = new QPixmap;
btnBorderPix->convertFromImage(qembed_findImage("buttonfill"));
btnBlendPix = new QPixmap;
btnBlendPix->convertFromImage(qembed_findImage("buttonborder"));
bevelFillPix = new QPixmap;
bevelFillPix->convertFromImage(qembed_findImage("clear_fill_large"));
smallBevelFillPix = new QPixmap;
smallBevelFillPix->convertFromImage(qembed_findImage("clear_fill_small"));
// new stuff
vsbSliderFillPix = menuPix = NULL;
menuHandler = new TransMenuHandler(this);
setScrollBarExtent(15, 15);
int i;
for(i=0; i < BITMAP_ITEMS; ++i){
pixmaps[i] = NULL;
}
oldSliderThickness = sliderThickness();
setSliderThickness(11);
}
LiquidStyle::~LiquidStyle()
{
if(btnBorderPix)
delete btnBorderPix;
if(btnBlendPix)
delete btnBlendPix;
if(bevelFillPix)
delete bevelFillPix;
if(smallBevelFillPix)
delete smallBevelFillPix;
if(vsbSliderFillPix)
delete vsbSliderFillPix;
if(menuPix)
delete menuPix;
setScrollBarExtent(16, 16);
setSliderThickness(oldSliderThickness);
int i;
for(i=0; i < BITMAP_ITEMS; ++i){
if(pixmaps[i])
delete pixmaps[i];
}
}
void LiquidStyle::drawClearBevel(QPainter *p, int x, int y, int w, int h,
const QColor &c, const QColor &bg)
{
QPen oldPen = p->pen(); // headers need this
int x2 = x+w-1;
int y2 = y+h-1;
// outer dark rect
p->setPen(c.dark(130));
p->drawLine(x, y+2, x, y2-2); // l
p->drawLine(x2, y+2, x2, y2-2); // r
p->drawLine(x+2, y, x2-2, y); // t
@@ -401,193 +406,193 @@ void LiquidStyle::drawRoundButton(QPainter *painter, const QColor &c,
//r = (int)(qRed(bgRgb)*0.75 + qRed(fgRgb)*0.25);
//g = (int)(qGreen(bgRgb)*0.75 + qGreen(fgRgb)*0.25);
//b = (int)(qBlue(bgRgb)*0.75 + qBlue(fgRgb)*0.25);
//QColor blendColor(r, g, b);
int hue, sat, v1, v2;
QColor blendColor(autoDefault ? c : back);
back.hsv(&hue, &sat, &v1);
blendColor.hsv(&hue, &sat, &v2);
if(v2 > v1)
blendColor.setHsv(hue, sat, (int)(v1*0.75 + v2*0.25));
pix = btnBorderDict.find(blendColor.rgb());
if(!pix){
int h, s, v;
blendColor.hsv(&h, &s, &v);
pix = new QPixmap(*btnBlendPix);
adjustHSV(*pix, h, s, v);
btnBorderDict.insert(blendColor.rgb(), pix);
}
}
else{
pix = pushedDown ? getPixmap(HTMLBtnBorderDown) :
getPixmap(HTMLBtnBorder);
}
p.drawPixmap(0, 0, *pix, 0, 0, 10, 10); // tl
p.drawPixmap(x2-9, 0, *pix, bx2-9, 0, 10, 10); // tr
p.drawPixmap(0, y2-9, *pix, 0, by2-9, 10, 10); // bl
p.drawPixmap(x2-9, y2-9, *pix, bx2-9, by2-9, 10, 10); // br
// edges
tilePix.resize(pix->width()-20, 10);
blendMask.resize(pix->width()-20, 10);
// top
bitBlt(&tilePix, 0, 0, pix, 10, 0, pix->width()-20, 10);
bitBlt(&blendMask, 0, 0, pix->mask(), 10, 0, pix->width()-20, 10);
tilePix.setMask(blendMask);
p.drawTiledPixmap(10, 0, w-20, 10, tilePix);
// bottom
bitBlt(&tilePix, 0, 0, pix, 10, by2-9, pix->width()-20, 20);
bitBlt(&blendMask, 0, 0, pix->mask(), 10, by2-9, pix->width()-20, 20);
tilePix.setMask(blendMask);
p.drawTiledPixmap(10, y2-9, w-20, 10, tilePix);
// left
tilePix.resize(10, pix->height()-20);
blendMask.resize(10, pix->height()-20);
bitBlt(&tilePix, 0, 0, pix, 0, 10, 10, pix->height()-20);
bitBlt(&blendMask, 0, 0, pix->mask(), 0, 10, 10, pix->height()-20);
tilePix.setMask(blendMask);
p.drawTiledPixmap(0, 10, 10, h-20, tilePix);
// right
bitBlt(&tilePix, 0, 0, pix, bx2-9, 10, 10, pix->height()-20);
bitBlt(&blendMask, 0, 0, pix->mask(), bx2-9, 10, 10, pix->height()-20);
tilePix.setMask(blendMask);
p.drawTiledPixmap(x2-9, 10, 10, h-20, tilePix);
p.end();
// do the button mask - we don't automask buttons
QBitmap btnMask(w, h);
QBitmap *mask = isMasked ? &htmlBtnMaskBmp : &btnMaskBmp;
p.begin(&btnMask);
p.fillRect(0, 0, w, h, Qt::color0);
p.drawPixmap(0, 0, *mask, 0, 0, 10, 10); // tl
p.drawPixmap(x2-9, 0, *mask, bx2-9, 0, 10, 10); // tr
p.drawPixmap(0, y2-9, *mask, 0, by2-9, 10, 10); // bl
p.drawPixmap(x2-9, y2-9, *mask, bx2-9, by2-9, 10, 10); // br
// fills
p.fillRect(10, 0, w-20, 10, Qt::color1); // top
p.fillRect(10, y2-9, w-20, 10, Qt::color1); // bottom
p.fillRect(0, 10, w, h-20, Qt::color1); // middle
p.end();
tmpPix.setMask(btnMask);
/*if(autoDefault){
if(supportPushDown && pushedDown){
painter->drawPixmap(x+3, y+3, tmpPix);
}
else{
painter->drawPixmap(x+2, y+2, tmpPix);
}
}
else */if(supportPushDown && pushedDown)
painter->drawPixmap(x+1, y+1, tmpPix);
else
painter->drawPixmap(x, y, tmpPix);
}
QPixmap* LiquidStyle::processEmbedded(const char *label, int h, int s, int v,
bool blend)
{
QImage img(qembed_findImage(label));
img.detach();
if(img.isNull()){ // shouldn't happen, been tested
- qWarning("Invalid embedded label %s", label);
+ owarn << "Invalid embedded label " << label << "" << oendl;
return(NULL);
}
if(img.depth() != 32)
img = img.convertDepth(32);
unsigned int *data = (unsigned int *)img.bits();
int total = img.width()*img.height();
int current;
QColor c;
int oldH, oldS, oldV;
int alpha;
if(v < 235)
v += 20;
else
v = 255;
float intensity = v/255.0;
for(current=0; current<total; ++current){
alpha = qAlpha(data[current]);
c.setRgb(data[current]);
c.hsv(&oldH, &oldS, &oldV);
oldV = (int)(oldV*intensity);
c.setHsv(h, s, oldV);
if(blend && alpha != 255 && alpha != 0){
float srcPercent = ((float)alpha)/255.0;
float destPercent = 1.0-srcPercent;
oldH = (int)((srcPercent*h) + (destPercent*bH));
oldS = (int)((srcPercent*s) + (destPercent*bS));
oldV = (int)((srcPercent*oldV) + (destPercent*bV));
c.setHsv(oldH, oldS, oldV);
alpha = 255;
}
data[current] = qRgba(c.red(), c.green(), c.blue(), alpha);
}
QPixmap *pix = new QPixmap;
pix->convertFromImage(img);
return(pix);
}
QPixmap* LiquidStyle::getPixmap(BitmapData item)
{
if(pixmaps[item])
return(pixmaps[item]);
switch(item){
case HTMLBtnBorder:
pixmaps[HTMLBtnBorder] = processEmbedded("htmlbtnborder", btnH, btnS, btnV);
break;
case HTMLBtnBorderDown:
pixmaps[HTMLBtnBorderDown] = processEmbedded("htmlbtnborder", btnHoverH, btnHoverS, btnHoverV);
break;
case HTMLCB:
pixmaps[HTMLCB] = processEmbedded("htmlcheckbox", bH, bS, bV);
break;
case HTMLCBHover:
pixmaps[HTMLCBHover] = processEmbedded("htmlcheckbox", btnHoverH, btnHoverS, btnHoverV);
break;
case HTMLCBDown:
pixmaps[HTMLCBDown] = processEmbedded("htmlcheckboxdown", btnH, btnS, btnV);
break;
case HTMLCBDownHover:
pixmaps[HTMLCBDownHover] = processEmbedded("htmlcheckboxdown", btnHoverH, btnHoverS, btnHoverV);
break;
case HTMLRadio:
pixmaps[HTMLRadio] = processEmbedded("htmlradio", bH, bS, bV);
break;
case HTMLRadioHover:
pixmaps[HTMLRadioHover] = processEmbedded("htmlradio", btnHoverH, btnHoverS, btnHoverV);
break;
case HTMLRadioDown:
pixmaps[HTMLRadioDown] = processEmbedded("htmlradiodown", btnH, btnS, btnV);
break;
case HTMLRadioDownHover:
pixmaps[HTMLRadioDownHover] = processEmbedded("htmlradiodown", btnHoverH, btnHoverS, btnHoverV);
break;
case RadioOff:
pixmaps[RadioOff] = processEmbedded("radio", bH, bS, bV /*, true*/);
break;
case RadioOffHover:
pixmaps[RadioOffHover] = processEmbedded("radio", btnHoverH, btnHoverS, btnHoverV /*, true*/);
break;
case RadioOn:
pixmaps[RadioOn] = processEmbedded("radio_down", btnH, btnS, btnV /*, true*/);
break;
case RadioOnHover:
pixmaps[RadioOnHover] = processEmbedded("radio_down", btnHoverH, btnHoverS, btnHoverV /*, true*/);
break;
case Tab:
pixmaps[Tab] = processEmbedded("tab", bH, bS, bV /*, true*/);
@@ -767,193 +772,193 @@ void LiquidStyle::polish(QPalette &appPal)
// background brush
QPixmap wallPaper(32, 32);
wallPaper.fill(c.rgb());
painter.begin(&wallPaper);
for(i=0; i < 32; i+=4){
painter.setPen(c.dark(100 + contrast));
painter.drawLine(0, i, 32, i);
painter.setPen(c.dark(100 + 3 * contrast / 5 ) );
painter.drawLine(0, i+1, 32, i+1);
};
painter.end();
bgBrush.setColor(c);
bgBrush.setPixmap(wallPaper);
appPal.setBrush(QColorGroup::Background, bgBrush);
}
void LiquidStyle::polish(QWidget *w)
{
if(w->inherits("QMenuBar")){
//((QFrame*)w)->setLineWidth(0);
w->setBackgroundMode(QWidget::PaletteBackground);
w->setBackgroundOrigin(QWidget::ParentOrigin);
return;
}
if(w->inherits("QToolBar")){
w->installEventFilter(this);
w->setBackgroundMode(QWidget::PaletteBackground);
w->setBackgroundOrigin(QWidget::WidgetOrigin);
return;
}
if(w->inherits("QPopupMenu"))
w->setBackgroundMode(QWidget::NoBackground);
else if(w-> testWFlags(Qt::WType_Popup) &&
!w->inherits("QListBox") &&
( qstrcmp ( w-> name(), "automatic what's this? widget" ) != 0 )) {
w->installEventFilter(menuHandler);
}
if(w->isTopLevel()){
return;
}
if(w->inherits("QRadioButton") || w->inherits("QCheckBox") || w->inherits("QProgressBar")) {
w->installEventFilter(this);
}
if(w->inherits("QButton") || w-> inherits("QComboBox")){
w-> setBackgroundMode ( QWidget::PaletteBackground );
w->setBackgroundOrigin ( QWidget::ParentOrigin);
}
bool isViewport = qstrcmp(w->name(), "qt_viewport") == 0 ||
qstrcmp(w->name(), "qt_clipped_viewport") == 0;
bool isViewportChild = w->parent() &&
((qstrcmp(w->parent()->name(), "qt_viewport") == 0) ||
(qstrcmp(w->parent()->name(), "qt_clipped_viewport") == 0));
if(isViewport && w->parent() && qstrcmp(w->parent()->name(), "proxyview") == 0){
w->setBackgroundMode(QWidget::X11ParentRelative);
return;
}
if(isViewportChild){
if(w->inherits("QButton") || w->inherits("QComboBox")){
if(w->parent()){ // heh, only way to test for KHTML children ;-)
if(w->parent()->parent()){
if(w->parent()->parent()->parent() &&
w->parent()->parent()->parent()->inherits("KHTMLView")){
w->setAutoMask(true);
w->setBackgroundMode(QWidget::NoBackground);
}
}
}
return;
}
}
if(w->inherits("QHeader")){
w->setMouseTracking(true);
w->installEventFilter(this);
}
if(w-> inherits("QToolButton")) {
if (w->parent()->inherits("QToolBar")) {
((QToolButton*)w)->setAutoRaise (flatTBButtons);
if ( flatTBButtons )
w->setBackgroundOrigin(QWidget::ParentOrigin);
}
w-> installEventFilter ( this );
}
if(w-> inherits("QToolBarSeparator")&&w->parent()->inherits("QToolBar")) {
((QFrame *) w)-> setFrameShape ( QFrame::NoFrame );
}
if(w->ownPalette() && !w->inherits("QButton") && !w->inherits("QComboBox")){
return;
}
if(w->parent() && w->parent()->isWidgetType() && !((QWidget*)w->parent())->
palette().active().brush(QColorGroup::Background).pixmap()){
- qWarning("No parent pixmap for child widget %s", w->className());
+ owarn << "No parent pixmap for child widget " << w->className() << "" << oendl;
return;
}
if(!isViewport && !isViewportChild && !w->testWFlags(WType_Popup) &&
!( !w-> inherits("QLineEdit") && w-> parent() && w-> parent()-> isWidgetType ( ) && w-> parent()-> inherits ( "QMultiLineEdit" ))) {
if(w->backgroundMode() == QWidget::PaletteBackground ||
w->backgroundMode() == QWidget::PaletteButton){
w->setBackgroundMode(w->parentWidget()->backgroundMode( )/*QWidget::X11ParentRelative*/);
w->setBackgroundOrigin(QWidget::ParentOrigin);
// w->setBackgroundMode(QWidget::NoBackground);
}
}
if ( !w-> inherits("QFrame") || (((QFrame*) w)-> frameShape () == QFrame::NoFrame ))
w-> setBackgroundOrigin ( QWidget::ParentOrigin );
else if ( w-> inherits("QFrame") )
w->setBackgroundOrigin ( QWidget::WidgetOrigin );
if ( w->parentWidget()->inherits ( "QWidgetStack" )) {
w->setBackgroundOrigin ( QWidget::WidgetOrigin );
}
}
void LiquidStyle::unPolish(QWidget *w)
{
if(w->inherits("QMenuBar")){
((QFrame *)w)->setLineWidth(1);
w->setBackgroundMode(QWidget::PaletteBackground);
return;
}
if(w->inherits("QPopupMenu"))
w->setBackgroundMode(QWidget::PaletteButton);
else if(w-> testWFlags(Qt::WType_Popup) &&
!w->inherits("QListBox") &&
( qstrcmp ( w-> name(), "automatic what's this? widget" ) != 0 )) {
w->removeEventFilter(menuHandler);
}
if(w->isTopLevel())
return;
// for viewport children, don't just check for NoBackground....
bool isViewportChild = w->parent() &&
((qstrcmp(w->parent()->name(), "qt_viewport") == 0) ||
(qstrcmp(w->parent()->name(), "qt_clipped_viewport") == 0));
w->unsetPalette();
if(w->backgroundMode() == QWidget::X11ParentRelative || isViewportChild){
if(w->inherits("QPushButton"))
w->setBackgroundMode(QWidget::PaletteButton);
else
w->setBackgroundMode(QWidget::PaletteBackground);
}
if(isViewportChild)
w->setAutoMask(false);
/*
if(w->inherits("QPushButton") || w-> inherits("QComboBox")){
w-> setBackgroundMode ( PaletteBackground );
}
*/
if( w->inherits("QRadioButton") || w->inherits("QCheckBox") || w->inherits("QProgressBar")) {
w->removeEventFilter(this);
}
if(w->inherits("QButton") || w->inherits("QComboBox")){
if(w->parent() && w->parent()->inherits("KHTMLPart")){
w->setAutoMask(false);
}
}
if(w-> inherits("QToolButton")) {
w-> removeEventFilter ( this );
}
if(w->inherits("QToolBar")){
w->removeEventFilter(this);
w->setBackgroundMode(QWidget::PaletteBackground);
return;
}
if(w->inherits("QHeader")){
w->setMouseTracking(false);
w->removeEventFilter(this);
}
}
void LiquidStyle::polish(QApplication *app)
{
QWindowsStyle::polish(app);
menuAni = app->isEffectEnabled(UI_AnimateMenu);
menuFade = app->isEffectEnabled(UI_FadeMenu);
if(menuAni)
app->setEffectEnabled(UI_AnimateMenu, false);
if(menuFade)
app->setEffectEnabled(UI_FadeMenu, false);
qt_set_draw_menu_bar_impl((QDrawMenuBarItemImpl) &LiquidStyle::drawMenuBarItem);
diff --git a/noncore/styles/liquid/liquid.pro b/noncore/styles/liquid/liquid.pro
index 7fe2829..767007f 100644
--- a/noncore/styles/liquid/liquid.pro
+++ b/noncore/styles/liquid/liquid.pro
@@ -1,19 +1,19 @@
TEMPLATE = lib
-CONFIG = qt plugin embedded warn_on
+CONFIG = qt plugin embedded warn_on
SOURCES = liquid.cpp \
effects.cpp \
liquidset.cpp \
plugin.cpp
HEADERS = liquid.h \
effects.h \
liquidset.h \
plugin.h
-LIBS += -lqpe -lqtaux2
+LIBS += -lqpe -lqtaux2 -lopiecore2
INCLUDEPATH += $(OPIEDIR)/include
DESTDIR = $(OPIEDIR)/plugins/styles
TARGET = liquid
-VERSION = 1.0.0
+VERSION = 1.0.1
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/styles/theme/othemebase.cpp b/noncore/styles/theme/othemebase.cpp
index 62b3a11..7ce4e5a 100644
--- a/noncore/styles/theme/othemebase.cpp
+++ b/noncore/styles/theme/othemebase.cpp
@@ -1,131 +1,133 @@
/* This file is part of the KDE libraries
Copyright (C) 1999 Daniel M. Duley <mosfet@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
+
#include "othemebase.h"
#include "ogfxeffect.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
-//#include <kdebug.h>
-//#include <klocale.h>
-#include <qpe/config.h>
-//#include <kglobal.h>
-//#include <kglobalsettings.h>
-//#include <kstddirs.h>
+#include <qpe/config.h>
+using namespace Opie::Core;
+
+/* QT */
#include <qfile.h>
#include <qtextstream.h>
#include <qdir.h>
#include <qpainter.h>
#include <qbitmap.h>
-#include <stdlib.h>
#include <qstringlist.h>
-#include <stdio.h>
+/* STD */
+#include <stdlib.h>
template class QIntCache<OThemePixmap>
;
static const char *widgetEntries[] =
{ // unsunken widgets (see header)
"PushButton", "ComboBox", "HSBarSlider", "VSBarSlider", "Bevel", "ToolButton",
"ScrollButton", "HScrollDeco", "VScrollDeco", "ComboDeco", "MenuItem", "Tab",
"ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight",
// sunken widgets
"PushButtonDown", "ComboBoxDown", "HSBarSliderDown", "VSBarSliderDown",
"BevelDown", "ToolButtonDown", "ScrollButtonDown", "HScrollDecoDown",
"VScrollDecoDown", "ComboDecoDown", "MenuItemDown", "TabDown", "SunkenArrowUp",
"SunkenArrowDown", "SunkenArrowLeft", "SunkenArrowRight",
// everything else
"HScrollGroove", "VScrollGroove", "Slider", "SliderGroove", "CheckBoxDown",
"CheckBox", "RadioDown", "Radio", "HBarHandle", "VBarHandle",
"ToolBar", "Splitter", "CheckMark", "MenuBar", "DisableArrowUp",
"DisableArrowDown", "DisableArrowLeft", "DisableArrowRight", "ProgressBar",
"ProgressBackground", "MenuBarItem", "Background"
};
#define INHERIT_ITEMS 16
// This is used to encode the keys. I used to use masks but I think this
// bitfield is nicer :) I don't know why C++ coders don't use these more..
// (mosfet)
struct kthemeKeyData
{
unsigned int id :
6;
unsigned int width :
12;
unsigned int height :
12;
unsigned int border :
1;
unsigned int mask :
1;
};
union kthemeKey{
kthemeKeyData data;
unsigned int cacheKey;
};
void OThemeBase::generateBorderPix( int i )
{
// separate pixmap into separate components
if ( pbPixmaps[ i ] ) {
// evidently I have to do masks manually...
const QBitmap * srcMask = pbPixmaps[ i ] ->mask();
QBitmap destMask( pbWidth[ i ], pbWidth[ i ] );
QPixmap tmp( pbWidth[ i ], pbWidth[ i ] );
bitBlt( &tmp, 0, 0, pbPixmaps[ i ], 0, 0, pbWidth[ i ], pbWidth[ i ],
Qt::CopyROP, false );
if ( srcMask ) {
bitBlt( &destMask, 0, 0, srcMask, 0, 0, pbWidth[ i ], pbWidth[ i ],
Qt::CopyROP, false );
tmp.setMask( destMask );
}
pbPixmaps[ i ] ->setBorder( OThemePixmap::TopLeft, tmp );
bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbPixmaps[ i ] ->width() - pbWidth[ i ], 0,
pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false );
if ( srcMask ) {
bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ],
0, pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false );
tmp.setMask( destMask );
}
pbPixmaps[ i ] ->setBorder( OThemePixmap::TopRight, tmp );
bitBlt( &tmp, 0, 0, pbPixmaps[ i ], 0, pbPixmaps[ i ] ->height() - pbWidth[ i ],
pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false );
if ( srcMask ) {
bitBlt( &destMask, 0, 0, srcMask, 0, pbPixmaps[ i ] ->height() - pbWidth[ i ],
pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false );
tmp.setMask( destMask );
}
pbPixmaps[ i ] ->setBorder( OThemePixmap::BottomLeft, tmp );
bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbPixmaps[ i ] ->width() - pbWidth[ i ],
pbPixmaps[ i ] ->height() - pbWidth[ i ], pbWidth[ i ], pbWidth[ i ],
Qt::CopyROP, false );
if ( srcMask ) {
bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ],
pbPixmaps[ i ] ->height() - pbWidth[ i ], pbWidth[ i ], pbWidth[ i ],
Qt::CopyROP, false );
tmp.setMask( destMask );
}
pbPixmaps[ i ] ->setBorder( OThemePixmap::BottomRight, tmp );
@@ -169,338 +171,331 @@ void OThemeBase::generateBorderPix( int i )
Qt::CopyROP, false );
if ( srcMask ) {
bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ],
pbWidth[ i ], pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2,
Qt::CopyROP, false );
tmp.setMask( destMask );
}
pbPixmaps[ i ] ->setBorder( OThemePixmap::Right, tmp );
}
else
qDebug ( "OThemeBase: Tried making border from empty pixmap" );
}
void OThemeBase::copyWidgetConfig( int sourceID, int destID, QString *pixnames,
QString *brdnames )
{
scaleHints[ destID ] = scaleHints[ sourceID ];
gradients[ destID ] = gradients[ sourceID ];
blends[ destID ] = blends[ sourceID ];
bContrasts[ destID ] = bContrasts[ sourceID ];
borders[ destID ] = borders[ sourceID ];
highlights[ destID ] = highlights[ sourceID ];
if ( grLowColors[ sourceID ] )
grLowColors[ destID ] = new QColor( *grLowColors[ sourceID ] );
else
grLowColors[ destID ] = NULL;
if ( grHighColors[ sourceID ] )
grHighColors[ destID ] = new QColor( *grHighColors[ sourceID ] );
else
grHighColors[ destID ] = NULL;
if ( colors[ sourceID ] )
colors[ destID ] = new QColorGroup( *colors[ sourceID ] );
else
colors[ destID ] = NULL;
// pixmap
pixnames[ destID ] = pixnames[ sourceID ];
duplicate[ destID ] = false;
pixmaps[ destID ] = NULL;
images[ destID ] = NULL;
if ( !pixnames[ destID ].isEmpty() ) {
if ( scaleHints[ sourceID ] == TileScale && blends[ sourceID ] == 0.0 ) {
pixmaps[ destID ] = pixmaps[ sourceID ];
duplicate[ destID ] = true;
}
if ( !duplicate[ destID ] ) {
pixmaps[ destID ] = loadPixmap( pixnames[ destID ] );
if ( scaleHints[ destID ] == TileScale && blends[ destID ] == 0.0 )
images[ destID ] = NULL;
else
images[ destID ] = loadImage( pixnames[ destID ] );
}
}
// border pixmap
pbDuplicate[ destID ] = false;
pbPixmaps[ destID ] = NULL;
pbWidth[ destID ] = pbWidth[ sourceID ];
brdnames[ destID ] = brdnames[ sourceID ];
if ( !brdnames[ destID ].isEmpty() ) {
pbPixmaps[ destID ] = pbPixmaps[ sourceID ];
pbDuplicate[ destID ] = true;
}
if ( sourceID == ActiveTab && destID == InactiveTab )
aTabLine = iTabLine;
else if ( sourceID == InactiveTab && destID == ActiveTab )
iTabLine = aTabLine;
}
void OThemeBase::readConfig( Qt::GUIStyle /*style*/ )
{
#define PREBLEND_ITEMS 12
static WidgetType preBlend[] = {Slider, IndicatorOn, IndicatorOff,
ExIndicatorOn, ExIndicatorOff, HScrollDeco, VScrollDeco, HScrollDecoDown,
VScrollDecoDown, ComboDeco, ComboDecoDown, CheckMark};
int i;
QString tmpStr;
QString copyfrom[ WIDGETS ];
QString pixnames[ WIDGETS ]; // used for duplicate check
QString brdnames[ WIDGETS ];
bool loaded[ WIDGETS ]; // used for preloading for CopyWidget
if ( configFileName.isEmpty() ) {
Config cfg ( "qpe" );
cfg. setGroup ( "Appearance" );
configFileName = cfg. readEntry ( "Theme", "default" );
}
Config config( configFilePath + "/themes/" + configFileName + ".themerc" , Config::File );
-// printf ( "Opened config file: %s\n", ( configFilePath + "/themes/" + configFileName + ".themerc" ). ascii());
-
// Are we initalized?
applyMiscResourceGroup( &config );
for ( i = 0; i < INHERIT_ITEMS; ++i ) {
applyResourceGroup( &config, i, copyfrom, pixnames, brdnames );
-// printf ( "%d [%s]: copy=%s, pix=%s, brd=%s\n", i, widgetEntries [i], copyfrom [i].latin1(), pixnames[i].latin1(),brdnames[i].latin1() );
}
for ( ; i < INHERIT_ITEMS*2; ++i ) {
if ( config.hasGroup( QString( widgetEntries[ i ] ) ) ) {
applyResourceGroup( &config, i, copyfrom, pixnames, brdnames );
-// printf ( "%d [%s]: copy=%s, pix=%s, brd=%s\n", i, widgetEntries [i], copyfrom [i].latin1(), pixnames[i].latin1(),brdnames[i].latin1() );
}
else {
copyfrom [ i ] = widgetEntries[ i - INHERIT_ITEMS ];
-// printf ( "%d [%s]: copy=%s\n", i, widgetEntries [i], copyfrom [i].latin1());
}
}
for ( ; i < WIDGETS; ++i ) {
applyResourceGroup( &config, i, copyfrom, pixnames, brdnames );
-// printf ( "%d [%s]: copy=%s, pix=%s, brd=%s\n", i, widgetEntries [i], copyfrom [i].latin1(), pixnames[i].latin1(),brdnames[i].latin1() );
}
// initalize defaults that may not be read
for ( i = 0; i < WIDGETS; ++i )
loaded[ i ] = false;
btnXShift = btnYShift = focus3DOffset = 0;
aTabLine = iTabLine = true;
roundedButton = roundedCombo = roundedSlider = focus3D = false;
splitterWidth = 10;
for ( i = 0; i < WIDGETS; ++i ) {
readResourceGroup( i, copyfrom, pixnames, brdnames, loaded );
-// printf ( "%d [%s]: copy=%s, pix=%s, brd=%s, colors=%s\n", i, widgetEntries [i], copyfrom [i].latin1(), pixnames[i].latin1(),brdnames[i].latin1(), (colors[i]?colors[i]->background().name().latin1():"<none)" ));
}
// misc items
readMiscResourceGroup();
// Handle preblend items
for ( i = 0; i < PREBLEND_ITEMS; ++i ) {
if ( pixmaps[ preBlend[ i ] ] != NULL && blends[ preBlend[ i ] ] != 0.0 )
blend( preBlend[ i ] );
}
}
OThemeBase::OThemeBase( const QString & configFile )
: QWindowsStyle()
{
configFilePath = QPEApplication::qpeDir ( ) + "/plugins/styles/";
configFileName = configFile;
readConfig( Qt::WindowsStyle );
cache = new OThemeCache( cacheSize );
}
void OThemeBase::applyConfigFile( const QString &/*file*/ )
{
#if 0
// handle std color scheme
Config inConfig( file, Config::File );
Config globalConfig ( "qpe" );
globalConfig. setGroup ( "Apperance" );
inConfig. setGroup( "General" );
if ( inConfig.hasKey( "foreground" ) )
globalConfig.writeEntry( "Text", inConfig.readEntry( "foreground", " " ) );
if ( inConfig.hasKey( "background" ) )
globalConfig.writeEntry( "Background", inConfig.readEntry( "background", " " ) );
if ( inConfig.hasKey( "selectForeground" ) )
globalConfig.writeEntry( "HighlightedText", inConfig.readEntry( "selectForeground", " " ) );
if ( inConfig.hasKey( "selectBackground" ) )
globalConfig.writeEntry( "Highlight", inConfig.readEntry( "selectBackground", " " ) );
if ( inConfig.hasKey( "windowForeground" ) )
globalConfig.writeEntry( "Text", inConfig.readEntry( "windowForeground", " " ) );
if ( inConfig.hasKey( "windowBackground" ) )
globalConfig.writeEntry( "Base", inConfig.readEntry( "windowBackground", " " ) );
// Keep track of the current theme so that we can select the right one
// in the KControl module.
globalConfig.writeEntry ( "CurrentTheme", file );
globalConfig.write();
#endif
}
OThemeBase::~OThemeBase()
{
int i;
for ( i = 0; i < WIDGETS; ++i ) {
if ( !duplicate[ i ] ) {
if ( images[ i ] )
delete images[ i ];
if ( pixmaps[ i ] )
delete pixmaps[ i ];
}
if ( !pbDuplicate[ i ] && pbPixmaps[ i ] )
delete pbPixmaps[ i ];
if ( colors[ i ] )
delete( colors[ i ] );
if ( grLowColors[ i ] )
delete( grLowColors[ i ] );
if ( grHighColors[ i ] )
delete( grHighColors[ i ] );
}
delete cache;
}
QImage* OThemeBase::loadImage( QString &name )
{
QImage * image = new QImage;
QString path = configFilePath + "/pixmaps/" + name;
image->load( path );
if ( !image->isNull() )
return ( image );
qDebug ( "OThemeBase: Unable to load image %s\n", name.ascii ( ) );
delete image;
return ( NULL );
}
OThemePixmap* OThemeBase::loadPixmap( QString &name )
{
OThemePixmap * pixmap = new OThemePixmap( false );
QString path = configFilePath + "/pixmaps/" + name;
pixmap->load( path );
if ( !pixmap->isNull() )
return pixmap;
qDebug ( "OThemeBase: Unable to load pixmap %s\n", name.ascii() );
delete pixmap;
return ( NULL );
}
OThemePixmap* OThemeBase::scale( int w, int h, WidgetType widget )
{
if ( scaleHints[ widget ] == FullScale ) {
if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w ||
pixmaps[ widget ] ->height() != h ) {
OThemePixmap * cachePix = cache->pixmap( w, h, widget );
if ( cachePix ) {
cachePix = new OThemePixmap( *cachePix );
if ( pixmaps[ widget ] )
cache->insert( pixmaps[ widget ], OThemeCache::FullScale,
widget );
else
- qDebug( "We would have inserted a null pixmap!\n" );
+ odebug << "We would have inserted a null pixmap!\n" << oendl;
pixmaps[ widget ] = cachePix;
}
else {
cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget );
QImage tmpImg = images[ widget ] ->smoothScale( w, h );
pixmaps[ widget ] = new OThemePixmap;
pixmaps[ widget ] ->convertFromImage( tmpImg );
if ( blends[ widget ] != 0.0 )
blend( widget );
}
}
}
else if ( scaleHints[ widget ] == HorizontalScale ) {
if ( pixmaps[ widget ] ->width() != w ) {
OThemePixmap * cachePix = cache->horizontalPixmap( w, widget );
if ( cachePix ) {
cachePix = new OThemePixmap( *cachePix );
if ( pixmaps[ widget ] )
cache->insert( pixmaps[ widget ], OThemeCache::HorizontalScale, widget );
else
qDebug ( "We would have inserted a null pixmap!\n" );
pixmaps[ widget ] = cachePix;
}
else {
cache->insert( pixmaps[ widget ], OThemeCache::HorizontalScale, widget );
QImage tmpImg = images[ widget ] ->
smoothScale( w, images[ widget ] ->height() );
pixmaps[ widget ] = new OThemePixmap;
pixmaps[ widget ] ->convertFromImage( tmpImg );
if ( blends[ widget ] != 0.0 )
blend( widget );
}
}
}
else if ( scaleHints[ widget ] == VerticalScale ) {
if ( pixmaps[ widget ] ->height() != h ) {
OThemePixmap * cachePix = cache->verticalPixmap( w, widget );
if ( cachePix ) {
cachePix = new OThemePixmap( *cachePix );
if ( pixmaps[ widget ] )
cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale, widget );
else
qDebug ( "We would have inserted a null pixmap!\n" );
pixmaps[ widget ] = cachePix;
}
else {
cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale, widget );
QImage tmpImg =
images[ widget ] ->smoothScale( images[ widget ] ->width(), h );
pixmaps[ widget ] = new OThemePixmap;
pixmaps[ widget ] ->convertFromImage( tmpImg );
if ( blends[ widget ] != 0.0 )
blend( widget );
}
}
}
// If blended tile here so the blend is scaled properly
else if ( scaleHints[ widget ] == TileScale && blends[ widget ] != 0.0 ) {
if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w ||
pixmaps[ widget ] ->height() != h ) {
OThemePixmap * cachePix = cache->pixmap( w, h, widget );
if ( cachePix ) {
cachePix = new OThemePixmap( *cachePix );
cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget );
pixmaps[ widget ] = cachePix;
}
else {
cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget );
QPixmap tile;
tile.convertFromImage( *images[ widget ] );
pixmaps[ widget ] = new OThemePixmap;
pixmaps[ widget ] ->resize( w, h );
QPainter p( pixmaps[ widget ] );
p.drawTiledPixmap( 0, 0, w, h, tile );
if ( blends[ widget ] != 0.0 )
blend( widget );
}
}
}
return ( pixmaps[ widget ] );
}
OThemePixmap* OThemeBase::scaleBorder( int w, int h, WidgetType widget )
{
OThemePixmap * pixmap = NULL;
if ( !pbPixmaps[ widget ] && !pbWidth[ widget ] )
return ( NULL );
pixmap = cache->pixmap( w, h, widget, true );
if ( pixmap ) {
pixmap = new OThemePixmap( *pixmap );
}
else {
pixmap = new OThemePixmap();
pixmap->resize( w, h );
QBitmap mask;
mask.resize( w, h );
diff --git a/noncore/todayplugins/fortune/fortune.pro b/noncore/todayplugins/fortune/fortune.pro
index 2e4b4b3..74c60b1 100644
--- a/noncore/todayplugins/fortune/fortune.pro
+++ b/noncore/todayplugins/fortune/fortune.pro
@@ -1,21 +1,20 @@
TEMPLATE = lib
-#CONFIG -= moc
CONFIG += qt plugin
# Input
HEADERS = fortuneplugin.h fortunepluginimpl.h \
fortunepluginwidget.h
SOURCES = fortuneplugin.cpp fortunepluginimpl.cpp \
fortunepluginwidget.cpp
INCLUDEPATH += $(OPIEDIR)/include \
../ ../library
DEPENDPATH += $(OPIEDIR)/include \
../ ../library
LIBS+= -lqpe -lopiecore2 -lopiepim2 -lopieui2
DESTDIR = $(OPIEDIR)/plugins/today
TARGET = todayfortuneplugin
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/todayplugins/fortune/fortunepluginwidget.cpp b/noncore/todayplugins/fortune/fortunepluginwidget.cpp
index c3ee546..c147567 100644
--- a/noncore/todayplugins/fortune/fortunepluginwidget.cpp
+++ b/noncore/todayplugins/fortune/fortunepluginwidget.cpp
@@ -1,83 +1,86 @@
/*
* fortunepluginwidget.cpp
*
* copyright : (c) 2002 by Maximilian Reiß
* email : harlekin@handhelds.org
*
*/
/***************************************************************************
* *
* 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 "fortunepluginwidget.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/config.h>
#include <qpe/qcopenvelope_qws.h>
+using namespace Opie::Core;
+using namespace Opie::Ui;
+/* QT */
#include <qvaluelist.h>
#include <qtl.h>
#include <qstring.h>
#include <qscrollview.h>
#include <qobject.h>
#include <qlayout.h>
-using namespace Opie::Core;
-using namespace Opie::Ui;
FortunePluginWidget::FortunePluginWidget( QWidget *parent, const char* name )
: QWidget( parent, name )
{
fortune = NULL;
getFortune();
}
FortunePluginWidget::~FortunePluginWidget() {
if( fortuneProcess ){
delete fortuneProcess;
}
}
/**
* Get the fortunes
*/
void FortunePluginWidget::getFortune() {
QVBoxLayout* layoutFortune = new QVBoxLayout( this );
if ( fortune ) {
delete fortune;
}
fortune = new OTicker( this );
// fortune->setReadOnly( TRUE );
// fortune->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) );
fortune->setText( QString("Obtaining fortune...") );
layoutFortune->addWidget( fortune );
fortuneProcess = new OProcess();
*fortuneProcess << "fortune";
connect(fortuneProcess, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int) ),
this, SLOT(slotStdOut(Opie::Core::OProcess*,char*,int) ) );
if(!fortuneProcess->start(OProcess::NotifyOnExit, OProcess::AllOutput) ) {
- qWarning("could not start :(");
+ owarn << "could not start :(" << oendl;
fortune->setText( QString("Failed to obtain fortune.") );
delete fortuneProcess;
fortuneProcess = 0;
}
}
void FortunePluginWidget::slotStdOut( OProcess* /*proc*/, char* buf, int len )
{
QCString s( buf, len );
s.replace( QRegExp("\n"), "" );
fortune->setText( s );
}
diff --git a/noncore/todayplugins/stockticker/stockticker/inputDialog.cpp b/noncore/todayplugins/stockticker/stockticker/inputDialog.cpp
index ce35256..ae219d7 100644
--- a/noncore/todayplugins/stockticker/stockticker/inputDialog.cpp
+++ b/noncore/todayplugins/stockticker/stockticker/inputDialog.cpp
@@ -1,88 +1,90 @@
#include "inputDialog.h"
+#include "helpwindow.h"
+
+/* OPIE */
+#include <opie2/odebug.h>
+#include <qpe/config.h>
+using namespace Opie::Core;
+/* QT */
#include <qapplication.h>
#include <qlayout.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qvariant.h>
#include <qpushbutton.h>
#include <qwhatsthis.h>
#include <qlabel.h>
#include <qlayout.h>
-#include <qpe/config.h>
#include <qstringlist.h>
-using namespace Opie::Core;
-using namespace Opie::Core;
#include <qmainwindow.h>
-#include "helpwindow.h"
+/* STD */
#include <stdlib.h>
-// #include <sys/stat.h>
-// #include <unistd.h>
InputDialog::InputDialog( )
: QMainWindow( 0x0, 0x0, WStyle_ContextHelp ) {
setCaption( tr("Symbol Lookup"));
QGridLayout *layout = new QGridLayout( this );
layout->setSpacing(6);
layout->setMargin( 2);
LineEdit1 = new QLineEdit( this, "LineEdit1" );
LineEdit1->setFocus();
layout->addMultiCellWidget( LineEdit1, 0, 0, 0, 3);
QLabel *label;
label = new QLabel(this);
label->setText( tr("Enter something to lookup / search."));
label->setMaximumHeight(60);
layout->addMultiCellWidget( label, 1, 1, 0, 3);
connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(doLookup()));
QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Expanding );
layout->addItem( spacer, 8, 0 );
}
InputDialog::~InputDialog() {
}
void InputDialog::doLookup() {
// http://finance.yahoo.com/l?m=&s=siemens&t=
QString url = "\"http://finance.yahoo.com/l?m=&s="+LineEdit1->text()+"\"";
QString tempHtml = "/tmp/stockticker.html";
QString cmd = "wget -O "+tempHtml+" "+url;
- qDebug(cmd);
+ odebug << cmd << oendl;
/*
OProcess proc;
proc << "/usr/bin/wget";
proc<<"-O"<< tempHtml<< url;
connect( &proc, SIGNAL( processExited(Opie::Core::OProcess*)),this, SLOT( showBrowser(Opie::Core::OProcess*)));
proc.start( OProcess::NotifyOnExit);
*/
system(cmd.latin1());
HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup");
StockLookup->setCaption("Symbol");
StockLookup->showMaximized();
StockLookup->show();
LineEdit1->text();
}
void InputDialog::showBrowser(OProcess*) {
- qDebug("BLAH");
+ odebug << "BLAH" << oendl;
QString tempHtml = "/tmp/stockticker.html";
HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup");
StockLookup->setCaption("Symbol");
StockLookup->showMaximized();
StockLookup->show();
LineEdit1->text();
}
diff --git a/noncore/todayplugins/stockticker/stocktickerlib/config.in b/noncore/todayplugins/stockticker/stocktickerlib/config.in
index 4d589f9..7dbe03a 100644
--- a/noncore/todayplugins/stockticker/stocktickerlib/config.in
+++ b/noncore/todayplugins/stockticker/stocktickerlib/config.in
@@ -1,4 +1,4 @@
config TODAY_STOCKTICKERLIB
boolean
default "y" if TODAY_STOCKTICKER
- depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI && LIBOPIE2PIM && TODAY
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && LIBOPIE2UI && LIBOPIE2PIM && TODAY
diff --git a/noncore/todayplugins/stockticker/stocktickerlib/stocktickerlib.pro b/noncore/todayplugins/stockticker/stocktickerlib/stocktickerlib.pro
index e70d1c0..6dcf945 100644
--- a/noncore/todayplugins/stockticker/stocktickerlib/stocktickerlib.pro
+++ b/noncore/todayplugins/stockticker/stocktickerlib/stocktickerlib.pro
@@ -1,29 +1,28 @@
TEMPLATE = lib
-CONFIG -= moc
CONFIG += qt plugin
HEADERS = stocktickerplugin.h stocktickerpluginimpl.h stocktickerpluginwidget.h stocktickerconfig.h \
../libstocks/csv.h \
../libstocks/http.h \
../libstocks/lists.h \
../libstocks/stocks.h
SOURCES = stocktickerplugin.cpp stocktickerpluginimpl.cpp stocktickerpluginwidget.cpp stocktickerconfig.cpp \
../libstocks/csv.c \
../libstocks/currency.c \
../libstocks/history.c \
../libstocks/http.c \
../libstocks/lists.c \
../libstocks/stocks.c
INCLUDEPATH += $(OPIEDIR)/include \
../ ../library
DEPENDPATH += $(OPIEDIR)/include \
../ ../library
-LIBS+= -lqpe -lopieui2 -lopiepim2 -lpthread
-TMAKE_CFLAGS += -D__UNIX__
+LIBS += -lqpe -lopiecore2 -lopieui2 -lopiepim2 -lpthread
+DEFINES += __UNIX__
DESTDIR = $(OPIEDIR)/plugins/today
TARGET = todaystocktickerplugin
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/todayplugins/stockticker/stocktickerlib/stocktickerpluginwidget.cpp b/noncore/todayplugins/stockticker/stocktickerlib/stocktickerpluginwidget.cpp
index aaeb5ee..4855ac6 100644
--- a/noncore/todayplugins/stockticker/stocktickerlib/stocktickerpluginwidget.cpp
+++ b/noncore/todayplugins/stockticker/stocktickerlib/stocktickerpluginwidget.cpp
@@ -1,144 +1,144 @@
/*
* stocktickerpluginwidget.cpp
*
* copyright : (c) 2002 by L.J. Potter
* email : llornkcor@handhelds.org
*
*/
/***************************************************************************
* *
* 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 <opie2/oticker.h>
#include <qpe/config.h>
#include <qlayout.h>
using namespace Opie::Ui;
using namespace Opie::Ui;
extern "C" {
#include "libstocks/stocks.h"
}
#include <pthread.h>
#include "stocktickerpluginwidget.h"
QString output;
OTicker *stocktickerTicker;
QCString stock_liste;
bool dotimeCheck, dodateCheck, dosymbolCheck, donameCheck;
bool docurrentPriceCheck, dolastPriceCheck, doopenPriceCheck;
bool dominPriceCheck, domaxPriceCheck, dovariationCheck, dovolumeCheck;
void getStocks(char *blah) {
// stocktickerTicker->setText( "Downloading stock data.");
stock *stocks_quotes=NULL;
stock *stocks_tmp;
stock_liste = blah;
::free ( blah );
// char *stock_liste = (char *)blah->latin1();
- // qDebug("%s", stock_liste.data() );
+ // odebug << "" << stock_liste.data() << "" << oendl;
output = "";
QString tempString;
libstocks_return_code error;
// Config cfg( "stockticker");
// cfg.setGroup( "Fields" );
// bool dotimeCheck, dodateCheck, dosymbolCheck, donameCheck;
// bool docurrentPriceCheck, dolastPriceCheck, doopenPriceCheck;
// bool dominPriceCheck, domaxPriceCheck, dovariationCheck, dovolumeCheck;
dotimeCheck=dodateCheck=dosymbolCheck=donameCheck= docurrentPriceCheck=dolastPriceCheck=doopenPriceCheck=dominPriceCheck=domaxPriceCheck=dovariationCheck=dovolumeCheck=false;
dotimeCheck=1;
dodateCheck=1;
dosymbolCheck=1;
donameCheck=1;
docurrentPriceCheck=1;
dolastPriceCheck=1;
doopenPriceCheck=1;
dominPriceCheck=1;
domaxPriceCheck=1;
dovariationCheck=1;
dovolumeCheck=1;
// dotimeCheck=cfg.readBoolEntry("timeCheck",1);
// dodateCheck=cfg.readBoolEntry("dateCheck",1);
// dosymbolCheck=cfg.readBoolEntry("symbolCheck",1);
// donameCheck=cfg.readBoolEntry("nameCheck",1);
// docurrentPriceCheck=cfg.readBoolEntry("currentPriceCheck",1);
// dolastPriceCheck=cfg.readBoolEntry("lastPriceCheck",1);
// doopenPriceCheck=cfg.readBoolEntry("openPriceCheck",1);
// dominPriceCheck=cfg.readBoolEntry("minPriceCheck",1);
// domaxPriceCheck=cfg.readBoolEntry("maxPriceCheck",1);
// dovariationCheck=cfg.readBoolEntry("variationCheck",1);
// dovolumeCheck=cfg.readBoolEntry("volumeCheck",1);
// DefProxy();
// {
char *proxy;
// libstocks_return_code error;
/* Proxy support */
/* Checks for "http_proxy" environment variable */
proxy = getenv("http_proxy");
if(proxy) {
/* printf("proxy set\n"); */
error = set_proxy(proxy);
if (error) {
// printf("Proxy error (%d)\n", error);
// QString tempString2;
// tempString2.sprintf("Proxy error (%d)\n", error);
// output = tempString2;
// delete tempString2;
return;
// exit(1);
}
}
::free(proxy);
// }
/* Get the stocks and process errors */
error = get_stocks( stock_liste.data(), &stocks_quotes);
if (error) {
printf("Error in getting stocks (%d)\n", error);
tempString.sprintf("Error in getting stocks (%d)\n", error);
output =tempString;
return;
}
stocks_tmp = stocks_quotes;
/* Displays the stocks */
while(stocks_tmp!=0){
if (stocks_tmp->Time) {
// printf("%s ", stocks_tmp->Time);
tempString.sprintf("| %s ", stocks_tmp->Time);
tempString.replace(QRegExp("\""),"");
if( dotimeCheck)
output +=tempString;
}
if (stocks_tmp->Date) {
// printf("%s ", stocks_tmp->Date);
tempString.sprintf("| %s ", stocks_tmp->Date);
tempString.replace(QRegExp("\""),"");
if(dodateCheck)
output +=tempString;
}
// printf("\n");
// printf("----------------------------------------\n");
if ( strlen(stocks_tmp->Symbol) > 20 ) {
// printf("| Symbol | %.20s |\n",stocks_tmp->Symbol);
tempString.sprintf("| Symbol %s ",stocks_tmp->Symbol);
if(dosymbolCheck)
@@ -185,145 +185,145 @@ void getStocks(char *blah) {
// printf("| Open | %-7.2f |\n",stocks_tmp->OpenPrice);
tempString.sprintf("| Open %-7.2f ",stocks_tmp->OpenPrice);
if(doopenPriceCheck)
output +=tempString;
// printf("| Min | %-7.2f |\n", stocks_tmp->MinPrice);
tempString.sprintf("| Min %-7.2f ", stocks_tmp->MinPrice);
if(dominPriceCheck)
output +=tempString;
// printf("| Max | %-7.2f |\n",stocks_tmp->MaxPrice);
tempString.sprintf("| Max %-7.2f ",stocks_tmp->MaxPrice);
if(domaxPriceCheck)
output +=tempString;
// printf("| Var | %-6.2f (%5.2f %%) |\n", stocks_tmp->Variation, stocks_tmp->Pourcentage);
tempString.sprintf("| Var %-6.2f (%5.2f %%) ", stocks_tmp->Variation, stocks_tmp->Pourcentage);
if(dovariationCheck)
output +=tempString;
// printf("| Volume | %-9d |\n", stocks_tmp->Volume);
tempString.sprintf("| Volume %-9d ", stocks_tmp->Volume);
if(dovolumeCheck)
output +=tempString;
// printf("----------------------------------------\n\n");
tempString.sprintf("||==++==|");
output +=tempString;
/* Simple function which help to browse in the stocks list */
stocks_tmp = next_stock(stocks_tmp);
}
stocktickerTicker->setText( output.latin1() );
/* frees stocks */
free_stocks(stocks_quotes);
free_stocks(stocks_tmp);
stock_liste="";
//delete stock_liste;
tempString="";
output="";
}
StockTickerPluginWidget::StockTickerPluginWidget( QWidget *parent, const char* name)
: QWidget(parent, name ) {
init();
startTimer(1000);
stocktickerTicker->setTextFormat(Qt::RichText);
// checkConnection();
}
StockTickerPluginWidget::~StockTickerPluginWidget() {
}
void StockTickerPluginWidget::init() {
QHBoxLayout* layout = new QHBoxLayout( this );
stocktickerTicker = new OTicker(this);
// stocktickerTicker->setMinimumHeight(15);
connect( stocktickerTicker, SIGNAL( mousePressed()), this, SLOT( checkConnection() ));
layout->addWidget( stocktickerTicker);
wasError = true;
}
void StockTickerPluginWidget::doStocks() {
Config cfg( "stockticker");
cfg.setGroup( "Symbols" );
symbollist="";
symbollist = cfg.readEntry("Symbols", "");
symbollist.replace(QRegExp(" "),"+");//seperated by +
cfg.setGroup("Timer");
stocktickerTicker->setUpdateTime( cfg.readNumEntry("ScrollSpeed",50));
stocktickerTicker->setScrollLength( cfg.readNumEntry("ScrollLength",10));
if (!symbollist.isEmpty()) {
pthread_t thread1;
char *blah = ::strdup(symbollist.latin1());
pthread_create( &thread1, NULL, (void * (*)(void *))getStocks, (void *) blah);
pthread_detach( thread1);
//::free((void*)thread1);
//getStocks(blah);
}
}
void StockTickerPluginWidget::timerEvent( QTimerEvent *e ) {
killTimer(e->timerId());
checkConnection();
}
void StockTickerPluginWidget::checkConnection() {
- // qDebug("checking connection");
+ // odebug << "checking connection" << oendl;
// Sock = new QSocket( this );
// if( wasError)
// stocktickerTicker->setText("Checking connection");
// if(Sock->state() == QSocket::Idle) {
// Sock->connectToHost("finance.yahoo.com", 80);
// connect( Sock, SIGNAL( error(int) ), SLOT(socketError(int)) );
// connect( Sock, SIGNAL( hostFound() ), SLOT(isConnected()) );
// } else {
- // qDebug("State is not Idle");
+ // odebug << "State is not Idle" << oendl;
isConnected();
// }
}
void StockTickerPluginWidget::isConnected() {
- // qDebug("We connect, so ok to grab stocks");
+ // odebug << "We connect, so ok to grab stocks" << oendl;
if(this->isVisible())
doStocks();
Config cfg( "stockticker");
cfg.setGroup("Timer");
timerDelay= cfg.readNumEntry("Delay",0);
if(timerDelay > 0)
startTimer(timerDelay*60000);
- // qDebug("timer set for %d",(timerDelay*60000)/60000);
+ // odebug << "timer set for " << (timerDelay*60000)/60000 << "" << oendl;
wasError = false;
// Sock->close();
}
void StockTickerPluginWidget::socketError(int errcode) {
switch(errcode) {
case QSocket::ErrConnectionRefused:
output = tr("Connection refused.");
break;
case QSocket::ErrHostNotFound:
output = tr("Could not find server.");
break;
case QSocket::ErrSocketRead :
output = tr("Socket read error.");
break;
};
stocktickerTicker->setText( output );
wasError = true;
// Sock->close();
}
diff --git a/noncore/tools/calc2/engine.cpp b/noncore/tools/calc2/engine.cpp
index a9a47c4..e843e29 100644
--- a/noncore/tools/calc2/engine.cpp
+++ b/noncore/tools/calc2/engine.cpp
@@ -8,207 +8,207 @@
** 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 "engine.h"
#include <qstring.h>
#include <math.h>
#include <qlcdnumber.h>
Data Engine::evalStack (Data num, bool inbrace = FALSE)
{
if (state != sError) {
Instruction *i;
// Pop the next op from the stack
while (!stack.isEmpty () && (braces || !inbrace)) {
i = stack.pop ();
// Check this ops prec vs next ops prec
if (!stack.isEmpty ())
if (i->precedence <= stack.top()->precedence)
i->acc = evalStack (i->acc, inbrace);
// Evaluate this instruction
num = i->eval (num);
// Error-check ( change this to work for all types )
if (isnan (num.dbl) || isinf (num.dbl)) {
qDebug ("bad result from operation");
state = sError;
clearData(&num);
return num;
}
}
}
return num;
}
// Plugins call this to request the stack be evaluated
void Engine::eval ()
{
num = evalStack (num);
if (state != sError) {
displayData(num);
state = sStart;
}
// if the user didnt close all their braces, its no big deal
braces = 0;
}
void Engine::immediateInstruction (Instruction * i)
{
if (state != sError) {
i->setRep(currentRep);
num = i->eval (num);
displayData(num);
state = sStart;
}
}
void Engine::pushInstruction (Instruction * i)
{
if (state != sError) {
i->setRep(currentRep);
i->acc = num;
stack.push (i);
state = sStart;
}
}
void Engine::pushValue (char v)
{
if (state == sAppend) {
bool ok = FALSE;
switch (currentRep) {
case rDouble:
displayString.append(v);
num.dbl=displayString.toDouble(&ok);
break;
case rFraction:
break;
default:
displayString.append(v);
num.i=displayString.toInt(&ok, calcBase());
};
if (!ok) {
state = sError;
- qDebug("pushValue() - num->string conversion");
+ odebug << "pushValue() - num->string conversion" << oendl;
} else {
const QString constString = displayString;
emit(display(constString));
};
} else if (state == sStart) {
softReset();
displayString.truncate(0);
state = sAppend;
pushValue (v);
} else if (state == sError) {
qDebug ("in error state");
return;
}
}
void Engine::del ()
{
bool ok;
switch (currentRep) {
case rDouble:
displayString.truncate(displayString.length());
num.dbl=displayString.toDouble(&ok);
break;
case rFraction:
- qDebug("not available");
+ odebug << "not available" << oendl;
break;
default:
displayString.truncate(displayString.length());
num.i = displayString.toInt(&ok, calcBase());
};
if (!ok) {
state = sError;
- qDebug("del() - num->string conversion");
+ odebug << "del() - num->string conversion" << oendl;
} else {
const QString constString = displayString;
emit(display(constString));
};
}
void Engine::displayData(Data d) {
switch (currentRep) {
case rDouble:
displayString.setNum(d.dbl);
break;
case rFraction:
- qDebug("fractional display not yet impl");
+ odebug << "fractional display not yet impl" << oendl;
break;
default:
displayString.setNum(d.i, calcBase());
break;
};
const QString constString= displayString;
emit(display(constString));
}
// Returns the base when Rep is an integer type
int Engine::calcBase () {
switch (currentRep) {
case rBin:
return 2;
case rOct:
return 8;
case rDec:
return 10;
case rHex:
return 16;
default:
state = sError;
- qDebug("Error - attempt to calc base for non-integer");
+ odebug << "Error - attempt to calc base for non-integer" << oendl;
return 10;
};
}
// Special instruction for internal use only
class iOpenBrace:public Instruction {
public:
iOpenBrace (Engine *e):Instruction (100) {engine = e;};
~iOpenBrace () {};
Data eval (Data num) {
engine->decBraces();
return num;
};
private:
Engine *engine;
};
void Engine::openBrace() {
pushInstruction(new iOpenBrace(this));
}
void Engine::closeBrace() {
braces++;evalStack(num,TRUE);
}
// will need to show and hide display widgets
void Engine::setRepresentation(Representation r) {
currentRep = r;
clearData(&num);
clearData(&mem);
state = sStart;
}
void Engine::clearData(Data *d) {
d->i = d->fraction.numerator = d->fraction.denominator = 0;
d->dbl = 0;
}
diff --git a/noncore/tools/calculator/calculator.pro b/noncore/tools/calculator/calculator.pro
index ae6a666..78d4519 100644
--- a/noncore/tools/calculator/calculator.pro
+++ b/noncore/tools/calculator/calculator.pro
@@ -1,11 +1,11 @@
-CONFIG = qt warn_on quick-app
+CONFIG = qt warn_on quick-app
HEADERS = calculatorimpl.h
SOURCES = calculatorimpl.cpp \
main.cpp
-INCLUDEPATH += $(OPIEDIR)/include
+INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
LIBS += -lqpe -lopiecore2
INTERFACES = calculator.ui
TARGET = calculator
include ( $(OPIEDIR)/include.pro )
diff --git a/noncore/tools/calculator/calculatorimpl.cpp b/noncore/tools/calculator/calculatorimpl.cpp
index dead03d..05cb9b5 100644
--- a/noncore/tools/calculator/calculatorimpl.cpp
+++ b/noncore/tools/calculator/calculatorimpl.cpp
@@ -1,138 +1,145 @@
/**********************************************************************
** 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.
**
**********************************************************************/
/*
* 01/14/2002 Charles-Edouard Ruault <ce@ruault.com>
* Added support for Temperature conversions.
*/
// Sat 03-09-2002 L.J. Potter added the inlined pixmaps here
#include "calculatorimpl.h"
+/* OPIE */
+#include <opie2/odebug.h>
#include <qpe/resource.h>
#include <qpe/qmath.h>
#include <qpe/qpeapplication.h>
+using namespace Opie::Core;
+/* QT */
#include <qpushbutton.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <qfont.h>
#include <qlayout.h>
#include <qstringlist.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qmessagebox.h>
+
+/* STD */
#include <math.h>
+
/* XPM */
static char *oneoverx_xpm[] = {
/* width height num_colors chars_per_pixel */
" 13 11 2 1",
/* colors */
". c None",
"# c #000000",
/* pixels */
"......#......",
".....##......",
"......#......"
".....###.....",
".............",
"..#########..",
".............",
"....##.##....",
"......#......",
"......#......",
"....##.##....",
};
/* XPM */
static char *ythrootofx_xpm[] = {
/* width height num_colors chars_per_pixel */
" 13 11 2 1",
/* colors */
". c None",
"# c #000000",
/* pixels */
"#.#..........",
"#.#..........",
"###...#######",
"..#..#.......",
"###..#.......",
".....#.#...#.",
".#..#...#.#..",
"#.#.#....#...",
"..#.#...#.#..",
"...#...#...#.",
"...#........."
};
/* XPM */
static char *xtopowerofy_xpm[] = {
/* width height num_colors chars_per_pixel */
" 9 8 2 1",
/* colors */
". c None",
"# c #000000",
/* pixels */
"......#.#",
"......#.#",
"......###",
"#...#...#",
".#.#..###",
"..#......",
".#.#.....",
"#...#...."
};
CalculatorImpl::CalculatorImpl( QWidget * parent, const char * name,
WFlags f )
: Calculator( parent, name, f )
{
// xtopowerofy = Resource::loadPixmap("xtopowerofy");
// ythrootofx = Resource::loadPixmap("ythrootofx");
// oneoverx = Resource::loadPixmap("oneoverx");
memMark = new QLabel( "m", LCD );
memMark->setFont( QFont( "helvetica", 12, QFont::Bold, TRUE ) );
memMark->resize( 12, 12 );
memMark->move( 4, 2 );
memMark->hide();
mem = 0;
PushButtonMR->setEnabled( FALSE );
current_mode = max_mode = conversion_mode_count = 0;
last_conversion = -1;
// translation trick mode - with this stuff parsed in from a file is translatable
QObject::tr("Standard");
QObject::tr("Weight");
QObject::tr("Distance");
QObject::tr("Area");
QObject::tr("Temperatures");
QObject::tr("Volume");
QObject::tr("acres");
QObject::tr("°C");
QObject::tr("carats");
QObject::tr("cm");
QObject::tr("cu cm");
QObject::tr("cu ft");
QObject::tr("cu in");
QObject::tr("°F");
QObject::tr("fl oz (US)");
QObject::tr("ft");
QObject::tr("g");
@@ -140,193 +147,193 @@ CalculatorImpl::CalculatorImpl( QWidget * parent, const char * name,
QObject::tr("hectares");
QObject::tr("in");
QObject::tr("kg");
QObject::tr("km");
QObject::tr("l");
QObject::tr("lb");
QObject::tr("Lg tons");
QObject::tr("m");
QObject::tr("mg");
QObject::tr("mi");
QObject::tr("ml");
QObject::tr("mm");
QObject::tr("naut. mi");
QObject::tr("oz");
QObject::tr("points");
QObject::tr("pt");
QObject::tr("qt");
QObject::tr("sq cm");
QObject::tr("sq ft");
QObject::tr("sq in");
QObject::tr("sq km");
QObject::tr("sq m");
QObject::tr("sq mi");
QObject::tr("sq mm");
QObject::tr("sq yd");
QObject::tr("st");
QObject::tr("St tons");
QObject::tr("tblspoon");
QObject::tr("teaspoons");
QObject::tr("tonnes");
QObject::tr("yd");
//bgr_command.insert( PushButtonFunction);
bgr_command.insert( PushButtonMPlus);
bgr_command.insert( PushButtonMR);
bgr_command.insert( PushButtonMC);
bgr_command.insert( PushButtonCE);
connect( &bgr_command, SIGNAL(clicked(int) ), this, SLOT(command_buttons(int)));
bgr_digits.insert(PushButton0);
bgr_digits.insert(PushButton1);
bgr_digits.insert(PushButton2);
bgr_digits.insert(PushButton3);
bgr_digits.insert(PushButton4);
bgr_digits.insert(PushButton5);
bgr_digits.insert(PushButton6);
bgr_digits.insert(PushButton7);
bgr_digits.insert(PushButton8);
bgr_digits.insert(PushButton9);
connect( &bgr_digits, SIGNAL(clicked(int) ), this, SLOT(enterNumber(int)));
bgr_std.insert(PushButtonEquals);
bgr_std.insert(PushButtonDecimal);
bgr_std.insert(PushButtonAdd);
bgr_std.insert(PushButtonMinus);
bgr_std.insert(PushButtonDivide);
bgr_std.insert(PushButtonTimes);
connect( &bgr_std, SIGNAL(clicked(int) ), this, SLOT(std_buttons(int)));
// change the / to a proper division signal
PushButtonDivide->setText(QChar(0xF7));
func_buttons[0] = PushButtonF1;
func_buttons[1] = PushButtonF2;
func_buttons[2] = PushButtonF3;
func_buttons[3] = PushButtonF4;
func_buttons[4] = PushButtonF5;
func_buttons[5] = PushButtonF6;
func_buttons[6] = PushButtonF7;
func_buttons[7] = PushButtonF8;
func_buttons[8] = PushButtonF9;
func_buttons[9] = PushButtonF10;
func_buttons[10] = PushButtonF11;
func_buttons[11] = PushButtonF12;
for ( int x = 0 ; x < func_button_count ; x++ ) {
QPushButton* tmpbutton = func_buttons[x];
faces << tmpbutton->text();
bgr_function.insert(tmpbutton);
}
connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(do_convert(int) ) );
connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(std_funcs(int) ) );
connect(ComboBoxFunction, SIGNAL(activated(int) ), this, SLOT(function_button(int) ) );
captions.append(tr("Standard"));
ComboBoxFunction->insertItem(captions.last());
// now add in the conversion modes
// when the menu gets done, these should be in a submenu
QString tmp = QPEApplication::qpeDir();
tmp += "etc/unit_conversion.dat";
QFile myfile(tmp);
if ( !myfile.open( IO_Translate | IO_ReadOnly ) ) {
- qDebug("Data file unit_conversion.dat not found\nNo conversion features will be available\n"+tmp);
+ odebug << "Data file unit_conversion.dat not found\nNo conversion features will be available\n"+tmp << oendl;
// disable the f button if no conv file available
ComboBoxFunction->setEnabled(FALSE);
}
else {
QString line, line2;
QTextStream ts(&myfile);
// first pass, see how many conversion types there are in order to allocate for them
while ( ! ts.eof() ) {
line = ts.readLine();
if ( line.contains ("STARTTYPE" ) )
conversion_mode_count++;
}
entry_list = new double[conversion_mode_count*func_button_count];
preoffset_list = new double[conversion_mode_count*func_button_count];
postoffset_list = new double[conversion_mode_count*func_button_count];
myfile.close();
myfile.open( IO_Translate | IO_ReadOnly );
QTextStream ts2(&myfile);
// second pass, read in values
int x = 0;
while ( ! ts2.eof() ) {
line = ts2.readLine();
if ( line.contains("STARTTYPE") ) {
captions << tr( line.remove(0,10) );
ComboBoxFunction->insertItem(captions.last());
while ( !line.contains("ENDTYPE") ) {
line = ts2.readLine();
if ( line.contains("NAME") ) {
faces << tr( line.remove(0,5) );
line2 = ts2.readLine();
line2.remove(0,6);
entry_list[x] = line2.toDouble();
line2 = ts2.readLine();
line2.remove(0,7);
preoffset_list[x] = line2.toDouble();
line2 = ts2.readLine();
line2.remove(0,8);
postoffset_list[x] = line2.toDouble();
x++;
}
}
}
}
}
myfile.close();
clear();
max_mode = pre_conv_modes_count + conversion_mode_count + post_conv_modes_count - 1;
display_pixmap_faces();
qApp->installEventFilter( this );
}
bool CalculatorImpl::eventFilter( QObject *o, QEvent *e )
{
if ( e->type() == QEvent::KeyPress && state != sError ) {
QKeyEvent *k = (QKeyEvent*)e;
if ( k->key() >= Key_0 && k->key() <= Key_9 ) {
enterNumber( k->key() - Key_0 );
return true;
} else {
switch ( k->key() ) {
case Key_Equal:
std_buttons(0);
return true;
case Key_Period:
std_buttons(1);
return true;
case Key_Plus:
std_buttons(2);
return true;
case Key_Minus:
std_buttons(3);
return true;
case Key_Slash:
std_buttons(4);
return true;
case Key_Asterisk:
std_buttons(5);
return true;
case Key_Percent:
execOp( oPercent );
return true;
case Key_ParenLeft:
if ( current_mode < pre_conv_modes_count )
execOp( oOpenBrace );
return true;
case Key_ParenRight:
if ( current_mode < pre_conv_modes_count )
execOp( oCloseBrace );
return true;
default:
break;
}
@@ -414,193 +421,193 @@ void CalculatorImpl::display_pixmap_faces() {
void CalculatorImpl::clear() {
acc = num = 0;
operationStack.clear();
state = sStart;
numDecimals = 0;
numOpenBraces = 0;
flPoint = FALSE;
LCD->display( 0 );
fake = QString::null;
reset_conv();
}
void CalculatorImpl::reset_conv() {
for ( int x = 0 ; x < changeable_func_button_count ; x++ ) {
QPushButton* tmpbutton = func_buttons[x];
// dont carry any selections into the next mode
if ( tmpbutton->state() == QPushButton::On ) {
tmpbutton->toggle();
}
}
last_conversion = -1;
}
void CalculatorImpl::std_buttons(int button)
{
if ( state == sError )
return;
execOp( (Operation)(button + oSum) );
}
void CalculatorImpl::std_funcs(int button) {
if ( state == sError )
return;
if ( current_mode < pre_conv_modes_count ||
button > changeable_func_button_count-1 ) {
Operation op;
if ( button < 10 )
op = (Operation)(button + oSin);
else if ( button == 10 )
op = oOpenBrace;
else
op = oCloseBrace;
execOp( op );
}
}
void CalculatorImpl::execOp( Operation i )
{
switch (i) {
// these operators only affect the current number.
case oDivX:
case oLog:
case oLn:
case oSin:
case oCos:
case oTan:
num = evalExpr(i);
break;
case oAdd:
case oSub: {
processStack( oAdd );
Op op( num, i );
operationStack.push( op );
break;
}
case oDiv:
case oMult:
case oRoot:
case oXsquared: {
processStack( oDiv );
Op op( num, i );
operationStack.push( op );
break;
}
case oChSign:
num = -num;
LCD->display(num);
return;
case oOpenBrace: {
Op op( 0, oOpenBrace );
operationStack.push( op );
numOpenBraces++;
state = sNewNumber;
return;
}
case oCloseBrace: {
if ( numOpenBraces == 0 )
return;
processStack( oAdd );
if ( operationStack.top().operation != oOpenBrace )
- qDebug( "Calculator: internal Error" );
+ odebug << "Calculator: internal Error" << oendl;
operationStack.pop();
state = sNewNumber;
numOpenBraces--;
break;
}
case oPoint:
flPoint = TRUE;
return;
case oPercent:
processStack( oPercent );
break;
case oSum:
processStack( oSum );
break;
default:
return;
};
if ( state == sError ) {
LCD->display( "Error" );
return;
} else {
LCD->display(num);
}
state = sNewNumber;
numDecimals = 0;
flPoint = FALSE;
}
void CalculatorImpl::processStack( int op )
{
//dubious percent hack, since the changeable operator precedences are
//pretty much hardwired to be less than the non-changeable
bool percent = FALSE;
if ( op == oPercent ) {
percent = TRUE;
op = oSum;
}
while( !operationStack.isEmpty() && operationStack.top().operation >= op ) {
Op operation = operationStack.pop();
acc = operation.number;
if ( percent ) {
if ( operation.operation == oAdd || operation.operation == oSub )
num = acc*num/100;
else
num = num / 100;
}
num = evalExpr( operation.operation );
percent = FALSE;
}
}
double CalculatorImpl::evalExpr( int op ) {
double sum = 0;
switch( op ){
case oPercent: sum = num / 100.; break;
case oDivX:
if (num == 0)
state = sError;
else
sum = 1 / num;
break;
case oXsquared:
sum = pow(acc,num);
break;
case oChSign: (state == sStart) ? sum = -num : sum = -acc; break;
case oSub: sum = acc - num; break;
case oMult: sum = acc * num; break;
case oAdd: sum = acc + num; break;
case oDiv: {
if (num == 0) {
state = sError;
} else {
sum = acc / num;
}
break;
}
case oRoot:
/* the linux library is dumb, and can't to -x to 1/n
when n is odd. (even and error of course is acceptable */
if((acc < 0) && (int(num) == num) && (int(num) % 2 == 1 )) {
sum = pow(-acc, 1 / num);
sum = -sum;
} else {
sum = pow(acc, 1 / num);
}
break;
case oLog:
diff --git a/noncore/tools/formatter/formatter.cpp b/noncore/tools/formatter/formatter.cpp
index 4204d73..642196e 100644
--- a/noncore/tools/formatter/formatter.cpp
+++ b/noncore/tools/formatter/formatter.cpp
@@ -1,133 +1,135 @@
/****************************************************************************
** formatter.cpp
**
** Copyright: Thu Apr 11 11:01:13 2002
** by: L. J. Potter
**
****************************************************************************/
#include "formatter.h"
#include "inputDialog.h"
#include "output.h"
/* OPIE */
-#include <qtoolbar.h>
+#include <opie2/odebug.h>
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
#include <qpe/config.h>
#include <qpe/mimetype.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/storage.h>
+using namespace Opie::Core;
/* QT */
#include <qmenubar.h>
#include <qmultilineedit.h>
#include <qstring.h>
#include <qlist.h>
#include <qstringlist.h>
#include <qdir.h>
#include <qfile.h>
#include <qtstream.h>
#include <qcombobox.h>
#include <qpopupmenu.h>
#include <qmessagebox.h>
#include <qregexp.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
+#include <qtoolbar.h>
#include <qtabwidget.h>
#include <qwidget.h>
#include <qlayout.h>
#include <qvariant.h>
/* STD */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/vfs.h>
#include <mntent.h>
#include <string.h>
#include <errno.h>
#define BLANK ' '
#define DELIMITER '#'
/*
Blah blah blah blah */
FormatterApp::FormatterApp( QWidget* parent, const char* name, WFlags fl, bool modal )
: QMainWindow( parent, name, fl )
// : QDialog( parent, name, modal, fl )
{
if ( !name )
setName( "FormatterApp" );
connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
setCaption( tr( "Formatter" ) );
FormatterAppLayout = new QGridLayout( this );
FormatterAppLayout->setSpacing( 2);
FormatterAppLayout->setMargin( 2 );
TabWidget = new QTabWidget( this, "TabWidget" );
tab = new QWidget( TabWidget, "tab" );
tabLayout = new QGridLayout( tab );
tabLayout->setSpacing( 3);
tabLayout->setMargin( 2);
storageComboBox = new QComboBox( FALSE, tab, "storageComboBox" );
storageComboBox->setMaximumWidth(220);
tabLayout->addMultiCellWidget( storageComboBox, 0, 0, 0, 1);
TextLabel4 = new QLabel( tab, "TextLabel4" );
TextLabel4->setText( tr( "Storage Type" ) );
tabLayout->addMultiCellWidget( TextLabel4, 1, 1, 0, 1);
TextLabel2 = new QLabel( tab, "TextLabel2" );
TextLabel2->setText( tr( "File Systems" ) );
tabLayout->addMultiCellWidget( TextLabel2, 4, 4, 0, 1);
fileSystemsCombo = new QComboBox( FALSE, tab, "fileSystemsCombo" );
fileSystemsCombo->setMaximumWidth(220);
tabLayout->addMultiCellWidget( fileSystemsCombo, 3, 3, 0, 1);
QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum );
tabLayout->addItem( spacer, 2, 0 );
formatPushButton = new QPushButton( tab, "formatPushButton" );
formatPushButton->setText( tr( "Format" ) );
formatPushButton->setMaximumWidth(170);
tabLayout->addMultiCellWidget( formatPushButton, 6, 6, 0, 1);
QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum );
tabLayout->addItem( spacer_2, 5, 0 );
TabWidget->insertTab( tab, tr( "Main" ) );
tab_2 = new QWidget( TabWidget, "tab_2" );
tabLayout_2 = new QGridLayout( tab_2 );
tabLayout_2->setSpacing(3);
tabLayout_2->setMargin(2);
mountPointLineEdit = new QLineEdit( tab_2, "mountPointLineEdit" );
tabLayout_2->addMultiCellWidget( mountPointLineEdit, 0, 0, 0, 1);
deviceComboBox = new QComboBox( FALSE, tab_2, "deviceComboBox" );
tabLayout_2->addMultiCellWidget( deviceComboBox, 3, 3, 0, 1);
TextLabel5 = new QLabel( tab_2, "TextLabel5" );
TextLabel5->setText( tr( "CAUTION:\n"
"Changing parameters on this\n"
"page may cause your system\n"
"to stop functioning properly!" ) );//idiot message
tabLayout_2->addMultiCellWidget( TextLabel5, 6, 6, 0, 1);
editPushButton = new QPushButton( tab_2, "editPushButton" );
editPushButton->setText( tr( "Edit fstab" ) );
editPushButton->setMaximumWidth(100);
@@ -145,488 +147,488 @@ FormatterApp::FormatterApp( QWidget* parent, const char* name, WFlags fl, bool
tabLayout_2->addMultiCellWidget( TextLabel3, 4, 4, 0, 1 );
QSpacerItem* spacer_3 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
tabLayout_2->addItem( spacer_3, 5, 0 );
TextLabel1 = new QLabel( tab_2, "TextLabel1" );
TextLabel1->setText( tr( "Mount Point" ) );
tabLayout_2->addMultiCellWidget( TextLabel1, 1, 1, 0, 1 );
QSpacerItem* spacer_4 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
tabLayout_2->addItem( spacer_4, 2, 1 );
TabWidget->insertTab( tab_2, tr( "Advanced" ) );
FormatterAppLayout->addWidget( TabWidget, 0, 1 );
connect( formatPushButton ,SIGNAL(released()),this,SLOT( doFormat()) );
connect( editPushButton ,SIGNAL(released()),this,SLOT( editFstab()) );
connect( fsckButton ,SIGNAL(released()),this,SLOT( doFsck()) );
connect( fileSystemsCombo,SIGNAL(activated(int)),this,SLOT( fsComboSelected(int) ));
connect( storageComboBox,SIGNAL(activated(int)),this,SLOT( storageComboSelected(int) ));
connect( deviceComboBox,SIGNAL(activated(int)),this,SLOT( deviceComboSelected(int) ));
fillCombos();
}
FormatterApp::~FormatterApp()
{}
void FormatterApp::doFormat()
{
int err=0;
Output *outDlg;
QString umountS, remountS;
QString text = storageComboBox->currentText();
QString currentText = storageComboBox->currentText();
QString cmd;
QString diskDevice = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4);
QString diskName = currentText.left(currentText.find(" -> ",0,TRUE));
QString fs = fileSystemsCombo->currentText();
#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) // lets test on something cheap
#else
currentText = diskDevice = "/dev/fd0";
umountS = "umount -v /floppy 2>&1";
remountS = "mount -v /floppy 2>&1";
#endif
if( currentText.find("CF",0,TRUE) != -1)
{
umountS = "umount ";
remountS = "mount ";
// umountS = "/sbin/cardctl eject";
// remountS = "/sbin/cardctl insert";
}
if( currentText.find("SD",0,TRUE) != -1)
{
umountS = "umount ";
remountS = "mount ";
// umountS = "/etc/sdcontrol compeject";
// remountS = "/etc/sdcontrol insert";
}
switch ( QMessageBox::warning(this,tr("Format?")
, tr("Really format\n") +diskName+" "+ currentText +
tr("\nwith %1 filesystem?\nYou will loose all data!!").arg( fs )
,tr("Yes")
,tr("No")
,0
,1
,1) )
{
case 0:
{
if(fs == "vfat")
cmd = "mkdosfs -v " + diskDevice+" 2>&1";
else if(fs == "ext2")
cmd = "mke2fs -v " + diskDevice+" 2>&1";
else
{
QMessageBox::warning(this, tr("Formatter"),tr("Could not format.\nUnknown type"), tr("Ok"));
break;
}
// cmd = "ls -l";
outDlg = new Output(this, tr("Formatter Output"),FALSE);
QPEApplication::showDialog( outDlg);
qApp->processEvents();
FILE *fp;
char line[130];
outDlg->OutputEdit->append( tr("Trying to umount %1.").arg( currentText) );
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
sleep(1);
- qDebug("Command is "+umountS);
+ odebug << "Command is "+umountS << oendl;
fp = popen( (const char *) umountS, "r");
- // qDebug("%d", fp);
+ // odebug << "" << fp << "" << oendl;
if ( !fp )
{
- qDebug("Could not execute '" + umountS + "'! err=%d\n" +(QString)strerror(errno), err);
+ odebug << "Could not execute '" + umountS + "'! err=" << err << "\n" +(QString)strerror(errno) << oendl;
QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") );
pclose(fp);
return;
}
else
{
// outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted."));
// outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
while ( fgets( line, sizeof line, fp))
{
if( ((QString)line).find("busy",0,TRUE) != -1)
{
- qDebug("Could not find '" + umountS);
+ odebug << "Could not find '" + umountS << oendl;
QMessageBox::warning( this, tr("Formatter"), tr("Could not umount.\nDevice is busy!"), tr("&OK") );
pclose(fp);
return;
}
else
{
QString lineStr = line;
lineStr=lineStr.left(lineStr.length()-1);
outDlg->OutputEdit->append(lineStr);
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
}
}
}
pclose(fp);
- qDebug("Command would be: "+cmd);
+ odebug << "Command would be: "+cmd << oendl;
outDlg->OutputEdit->append( tr("Trying to format.") );
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
fp = popen( (const char *) cmd, "r");
while ( fgets( line, sizeof line, fp))
{
if( ((QString)line).find("No such device",0,TRUE) != -1)
{
- qDebug("No such device '" + umountS);
+ odebug << "No such device '" + umountS << oendl;
QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") );
pclose(fp);
// outDlg->OutputEdit->append("No such device");
// outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
return;
}
else
{
QString lineStr = line;
lineStr=lineStr.left(lineStr.length()-1);
outDlg->OutputEdit->append(lineStr);
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
}
}
outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted."));
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
pclose(fp);
outDlg->OutputEdit->append( tr("Trying to mount %1.").arg( currentText) );
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
fp = popen( (const char *) remountS, "r");
if ( !fp)
{
- qDebug("Could not execute '" + remountS + "'! err=%d\n" +(QString)strerror(errno), err);
+ odebug << "Could not execute '" + remountS + "'! err=" << err << "\n" +(QString)strerror(errno) << oendl;
QMessageBox::warning( this, tr("Formatter"), tr("Card mount failed!"), tr("&OK") );
}
else
{
outDlg->OutputEdit->append(tr("%1\nhas been successfully mounted.").arg( currentText ));
while ( fgets( line, sizeof line, fp))
{
QString lineStr = line;
lineStr=lineStr.left(lineStr.length()-1);
outDlg->OutputEdit->append(lineStr);
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
}
}
pclose(fp);
sleep(1);
outDlg->OutputEdit->append(tr("You can now close the output window."));
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
// outDlg->close();
// if(outDlg)
// delete outDlg;
}
break;
};
}
bool FormatterApp::doFdisk()
{
return FALSE;
}
void FormatterApp::fillCombos()
{
StorageInfo storageInfo;
const QList<FileSystem> &fs = storageInfo.fileSystems();
QListIterator<FileSystem> it ( fs );
QString storage;
for( ; it.current(); ++it )
{
const QString name = (*it)->name();
const QString path = (*it)->path();
const QString disk = (*it)->disk();
const QString options = (*it)->options();
if( name.find( tr("Internal"),0,TRUE) == -1)
{
storageComboBox->insertItem(name +" -> "+disk);
}
// deviceComboBox->insertItem(disk);
}
parsetab("/etc/mtab");
// parsetab("/etc/fstab");
fileSystemsCombo->insertStringList( fsList,-1);
deviceComboBox->insertStringList( deviceList,-1);
storageComboSelected(0);
deviceComboSelected(0);
}
void FormatterApp::fsComboSelected(int )
{}
void FormatterApp::storageComboSelected(int index )
{
QString currentText = storageComboBox->text(index);
QString nameS = currentText.left( currentText.find("->",0,TRUE));
TextLabel4->setText( tr( "Storage Type: %1").arg( nameS) );
currentText = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4);
QString fsType = getFileSystemType((const QString &) currentText);
- // qDebug(fsType);
+ // odebug << fsType << oendl;
for(int i = 0; i < fileSystemsCombo->count(); i++)
{
if( fsType == fileSystemsCombo->text(i))
fileSystemsCombo->setCurrentItem(i);
}
// deviceComboSelected(index);
}
void FormatterApp::deviceComboSelected(int index)
{
StorageInfo storageInfo;
QString totalS, usedS, avS, diskS, nameS, fsType, selectedText;
selectedText = deviceComboBox->text(index);
const QList<FileSystem> &fs = storageInfo.fileSystems();
QListIterator<FileSystem> it ( fs );
QString storage;
for( ; it.current(); ++it )
{
const QString name = (*it)->name();
const QString path = (*it)->path();
const QString disk = (*it)->disk();
// const QString options = (*it)->options();
if( selectedText == disk)
{
diskS = disk; nameS= name;
mountPointLineEdit->setText(path);
long mult = (*it)->blockSize() / 1024;
long div = 1024 / (*it)->blockSize();
if ( !mult ) mult = 1;
if ( !div ) div = 1;
long total = (*it)->totalBlocks() * mult / div;
long totalMb = total/1024;
long avail = (*it)->availBlocks() * mult / div;
long availMb = avail/1024;
long used = total - avail;
long usedMb = used/1024;
totalS.sprintf(tr("Total: %1 kB ( %d mB)\n").arg( total ), totalMb );
usedS.sprintf(tr("Used: %1 kB ( %d mB)\n").arg(used) ,usedMb);
avS.sprintf( tr("Available: %1 kB ( %d mB)").arg(avail), availMb );
}
}
fsType = getFileSystemType((const QString &)selectedText);
TextLabel5->setText(tr("Type: %1\nFormatted with %2\n%3, %4, %5").arg( nameS).arg( fsType).arg(totalS).arg( usedS).arg( avS ));
TextLabel5->setTextFormat( Qt::RichText );
// storageComboSelected(0);
}
void FormatterApp::cleanUp()
{}
void FormatterApp::editFstab()
{
QCopEnvelope e("QPE/Application/textedit","setDocument(QString)");
e << (const QString &)"/etc/fstab";
}
void FormatterApp::parsetab(const QString &fileName)
{
fileSystemTypeList.clear();
fsList.clear();
struct mntent *me;
// if(fileName == "/etc/mtab") {
FILE *mntfp = setmntent( fileName.latin1(), "r" );
if ( mntfp )
{
while ( (me = getmntent( mntfp )) != 0 )
{
QString deviceName = me->mnt_fsname;
QString filesystemType = me->mnt_type;
if(deviceName != "none")
{
if( fsList.contains(filesystemType) == 0
& filesystemType.find("proc",0,TRUE) == -1
& filesystemType.find("cramfs",0,TRUE) == -1
& filesystemType.find("auto",0,TRUE) == -1)
fsList << filesystemType;
deviceList << deviceName;
- qDebug(deviceName+"::"+filesystemType);
+ odebug << deviceName+"::"+filesystemType << oendl;
fileSystemTypeList << deviceName+"::"+filesystemType;
}
}
}
endmntent( mntfp );
// } else if(fileName == "/etc/fstab") {
// QFile f("/etc/fstab");
// if ( f.open(IO_ReadOnly) ) {
// QTextStream t (&f);
// QString s;
// while (! t.eof()) {
// s=t.readLine();
// s=s.simplifyWhiteSpace();
// if ( (!s.isEmpty() ) && (s.find(" ")!=0) ) {
// // = me->mnt_fsname;
// QString filesystemType = me->mnt_type;
// QString deviceName = s.left(0,s.find(BLANK) );
// s=s.remove(0,s.find(BLANK)+1 ); // devicename
// s=s.remove(0,s.find(BLANK)+1 ); // mountpoint
// QStringt mountPoint= s.left(0,s.find(BLANK) );
// s=s.remove(0,s.find(BLANK)+1 ); // fs
// QString filesystemType= s.left(0,s.find(BLANK) );
// }
// }
// }
// f.close();
// }
}
QString FormatterApp::getFileSystemType(const QString &currentText)
{
parsetab("/etc/mtab"); //why did TT forget filesystem type?
for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it )
{
QString temp = (*it);
if( temp.find( currentText,0,TRUE) != -1)
{
return temp.right( temp.length() - temp.find("::",0,TRUE) - 2);
- // qDebug(fsType);
+ // odebug << fsType << oendl;
}
}
return "";
}
bool FormatterApp::doFsck()
{
Output *outDlg;
QString selectedDevice;
// #if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX)
selectedDevice = deviceComboBox->currentText();
QString mountPoint = mountPointLineEdit->text();
QString umountS = "umount -v "+mountPoint+" 2>&1";
QString remountS = "mount -v "+mountPoint+" 2>&1";
// #else
// // for testing
// // currentText = diskDevice = "/dev/fd0";
// QString umountS = "umount -v /floppy 2>&1";
// QString remountS = "mount -v /floppy 2>&1";
// selectedDevice ="/dev/fd0";
// #endif
QString fsType = getFileSystemType((const QString &)selectedDevice);
QString cmd;
- qDebug( selectedDevice +" "+ fsType);
+ odebug << selectedDevice +" "+ fsType << oendl;
if(fsType == "vfat") cmd = "dosfsck -vy ";
if(fsType == "ext2") cmd = "e2fsck -cpvy ";
cmd += selectedDevice + " 2>&1";
outDlg = new Output(this, tr("Formatter Output"),FALSE);
QPEApplication::showDialog( outDlg );
qApp->processEvents();
FILE *fp;
char line[130];
outDlg->OutputEdit->append( tr("Trying to umount."));
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
sleep(1);
- // qDebug("Command is "+umountS);
+ // odebug << "Command is "+umountS << oendl;
fp = popen( (const char *) umountS, "r");
- // qDebug("%d", fp);
+ // odebug << "" << fp << "" << oendl;
if ( !fp )
{
- qDebug("Could not execute '" + umountS + "'!\n" +(QString)strerror(errno));
+ odebug << "Could not execute '" + umountS + "'!\n" +(QString)strerror(errno) << oendl;
QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") );
pclose(fp);
return false;
}
else
{
// outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted."));
// outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
while ( fgets( line, sizeof line, fp))
{
if( ((QString)line).find("busy",0,TRUE) != -1)
{
- qDebug("Could not find '" + umountS);
+ odebug << "Could not find '" + umountS << oendl;
QMessageBox::warning( this, tr("Formatter"),
tr("Could not umount.\nDevice is busy!"), tr("&OK") );
pclose(fp);
return false;
}
else
{
QString lineStr = line;
lineStr=lineStr.left(lineStr.length()-1);
outDlg->OutputEdit->append(lineStr);
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
}
}
}
pclose(fp);
/////////////////////////////////////
fp = popen( (const char *) cmd, "r");
while ( fgets( line, sizeof line, fp))
{
if( ((QString)line).find("No such device",0,TRUE) != -1)
{
- qDebug("No such device '" + umountS);
+ odebug << "No such device '" + umountS << oendl;
QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") );
pclose(fp);
// outDlg->OutputEdit->append("No such device");
// outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
return false;
}
else
{
QString lineStr = line;
lineStr=lineStr.left(lineStr.length()-1);
outDlg->OutputEdit->append(lineStr);
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
}
}
outDlg->OutputEdit->append(tr("You can now close the output window."));
outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
// outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted."));
// outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
pclose(fp);
/////////////////////////////////////////
return true;
}
bool FormatterApp::doFsckCheck()
{
return FALSE;
}
int FormatterApp::formatCheck(const QString &)
{
return -1;
}
int FormatterApp::runCommand(const QString &)
{
return -1;
}
diff --git a/noncore/tools/formatter/formatter.pro b/noncore/tools/formatter/formatter.pro
index 913cca8..f6d34c7 100644
--- a/noncore/tools/formatter/formatter.pro
+++ b/noncore/tools/formatter/formatter.pro
@@ -1,9 +1,9 @@
-CONFIG += qt warn_on quick-app
-HEADERS = formatter.h inputDialog.h output.h
-SOURCES = formatter.cpp inputDialog.cpp output.cpp main.cpp
-TARGET = formatter
+CONFIG += qt warn_on quick-app
+HEADERS = formatter.h inputDialog.h output.h
+SOURCES = formatter.cpp inputDialog.cpp output.cpp main.cpp
+TARGET = formatter
INCLUDEPATH += $(OPIEDIR)/include
DEPENDPATH += $(OPIEDIR)/include
-LIBS += -lqpe -lopiecore2
+LIBS += -lqpe -lopiecore2
include ( $(OPIEDIR)/include.pro )