summaryrefslogtreecommitdiff
Unidiff
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 @@
1/* 1/*
2 * copyright : (c) 2003 by Greg Gilbert 2 * copyright : (c) 2003 by Greg Gilbert
3 * email : greg@treke.net 3 * email : greg@treke.net
4 * based on the cardmon applet by Max Reiss 4 * based on the cardmon applet by Max Reiss
5 * * 5 * *
6 * This program is free software; you can redistribute it and/or modify * 6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by * 7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or * 8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. * 9 * (at your option) any later version. *
10 * * 10 * *
11 *************************************************************************/ 11 *************************************************************************/
12 12
13#include "autorotate.h" 13#include "autorotate.h"
14 14
15/* OPIE */ 15/* OPIE */
16#include <opie2/odevice.h> 16#include <opie2/odebug.h>
17#include <opie2/otaskbarapplet.h> 17#include <opie2/otaskbarapplet.h>
18#include <qpe/applnk.h> 18#include <qpe/applnk.h>
19#include <qpe/config.h> 19#include <qpe/config.h>
20#include <qpe/resource.h> 20#include <qpe/resource.h>
21using namespace Opie::Core;
21 22
22/* QT */ 23/* QT */
23#include <qpainter.h> 24#include <qpainter.h>
24 25
25using namespace Opie::Ui;
26AutoRotate::AutoRotate(QWidget * parent):QWidget(parent) 26AutoRotate::AutoRotate(QWidget * parent):QWidget(parent)
27{ 27{
28 setFixedWidth( AppLnk::smallIconSize() ); 28 setFixedWidth( AppLnk::smallIconSize() );
29 setFixedHeight( AppLnk::smallIconSize() ); 29 setFixedHeight( AppLnk::smallIconSize() );
30 30
31 enabledPm.convertFromImage( Resource::loadImage("autorotate/rotate").smoothScale( height(), width() ) ); 31 enabledPm.convertFromImage( Resource::loadImage("autorotate/rotate").smoothScale( height(), width() ) );
32 disabledPm.convertFromImage( Resource::loadImage("autorotate/norotate").smoothScale( height(), width() ) ); 32 disabledPm.convertFromImage( Resource::loadImage("autorotate/norotate").smoothScale( height(), width() ) );
33 33
34 repaint(true); 34 repaint(true);
35 popupMenu = 0; 35 popupMenu = 0;
36 show(); 36 show();
37} 37}
38 38
39AutoRotate::~AutoRotate() 39AutoRotate::~AutoRotate()
40{ 40{
41 if (popupMenu) { 41 if (popupMenu) {
42 delete popupMenu; 42 delete popupMenu;
43 } 43 }
44} 44}
45 45
46int AutoRotate::position() 46int AutoRotate::position()
47{ 47{
48 return 7; 48 return 7;
49} 49}
50 50
51void AutoRotate::mousePressEvent(QMouseEvent *) 51void AutoRotate::mousePressEvent(QMouseEvent *)
52{ 52{
53 QPopupMenu *menu = new QPopupMenu(this); 53 QPopupMenu *menu = new QPopupMenu(this);
54 menu->insertItem( isRotateEnabled()? "Disable Rotation" : "Enable Rotation" ,1 ); 54 menu->insertItem( isRotateEnabled()? "Disable Rotation" : "Enable Rotation" ,1 );
55 55
56 QPoint p = mapToGlobal(QPoint(0, 0)); 56 QPoint p = mapToGlobal(QPoint(0, 0));
57 QSize s = menu->sizeHint(); 57 QSize s = menu->sizeHint();
58 int opt = menu->exec(QPoint(p.x() + (width() / 2) - (s.width() / 2), p.y() - s.height()), 0); 58 int opt = menu->exec(QPoint(p.x() + (width() / 2) - (s.width() / 2), p.y() - s.height()), 0);
59 59
60 if (opt==1) 60 if (opt==1)
61 { 61 {
62 setRotateEnabled( !isRotateEnabled() ); 62 setRotateEnabled( !isRotateEnabled() );
63 repaint(true); 63 repaint(true);
64 } 64 }
65 65
66 delete menu; 66 delete menu;
67} 67}
68 68
69void AutoRotate::paintEvent(QPaintEvent *) 69void AutoRotate::paintEvent(QPaintEvent *)
70{ 70{
71 QPainter p(this); 71 QPainter p(this);
72 p.drawPixmap( 0, 0, isRotateEnabled()? enabledPm : disabledPm ); 72 p.drawPixmap( 0, 0, isRotateEnabled()? enabledPm : disabledPm );
73} 73}
74 74
75void AutoRotate::setRotateEnabled(bool status) 75void AutoRotate::setRotateEnabled(bool status)
76{ 76{
77 Config cfg( "qpe" ); 77 Config cfg( "qpe" );
78 cfg.setGroup( "Appearance" ); 78 cfg.setGroup( "Appearance" );
79 cfg.writeEntry( "rotateEnabled", status ); 79 cfg.writeEntry( "rotateEnabled", status );
80 80
81} 81}
82bool AutoRotate::isRotateEnabled() 82bool AutoRotate::isRotateEnabled()
83{ 83{
84 Config cfg( "qpe" ); 84 Config cfg( "qpe" );
85 cfg.setGroup( "Appearance" ); 85 cfg.setGroup( "Appearance" );
86 86
87 bool res = cfg.readBoolEntry( "rotateEnabled" ); 87 bool res = cfg.readBoolEntry( "rotateEnabled" );
88 88
89 if (res ) 89 if (res )
90 qDebug("Enabled"); 90 odebug << "Enabled" << oendl;
91 else 91 else
92 qDebug("Disabled"); 92 odebug << "Disabled" << oendl;
93 return res; 93 return res;
94} 94}
95 95
96EXPORT_OPIE_APPLET_v1( AutoRotate ) 96EXPORT_OPIE_APPLET_v1( AutoRotate )
97 97
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include "swapfile.h" 21#include "swapfile.h"
22 22
23/* OPIE */
24#include <opie2/odebug.h>
25#include <qpe/resource.h>
26using namespace Opie::Core;
27
28/* QT */
23#include <qfile.h> 29#include <qfile.h>
24#include <qtextstream.h> 30#include <qtextstream.h>
25#include <qlabel.h> 31#include <qlabel.h>
26#include <qtimer.h> 32#include <qtimer.h>
27#include <qlayout.h> 33#include <qlayout.h>
28#include <qpushbutton.h> 34#include <qpushbutton.h>
29#include <qhbuttongroup.h> 35#include <qhbuttongroup.h>
30#include <qradiobutton.h> 36#include <qradiobutton.h>
31#include <qlineedit.h> 37#include <qlineedit.h>
32#include <qprogressbar.h> 38#include <qprogressbar.h>
33#include <qcombobox.h> 39#include <qcombobox.h>
34#include <qvgroupbox.h> 40#include <qvgroupbox.h>
35#include <qhbox.h> 41#include <qhbox.h>
36#include <qmessagebox.h> 42#include <qmessagebox.h>
43#include <qcopchannel_qws.h>
44
45/* STD */
37#include <stdio.h> 46#include <stdio.h>
38#include <stdlib.h> 47#include <stdlib.h>
39#include <string.h> 48#include <string.h>
40
41#include <qcopchannel_qws.h>
42#include <qpe/resource.h>
43
44#include <unistd.h> 49#include <unistd.h>
45#include <fcntl.h> 50#include <fcntl.h>
46#include <sys/vfs.h> 51#include <sys/vfs.h>
47#include <mntent.h> 52#include <mntent.h>
48#include <unistd.h> 53#include <unistd.h>
49#include <sys/types.h> 54#include <sys/types.h>
50 55
51Swapfile::Swapfile( QWidget *parent, const char *name, WFlags f ) 56Swapfile::Swapfile( QWidget *parent, const char *name, WFlags f )
52 : QWidget( parent, name, f ) 57 : QWidget( parent, name, f )
53{ 58{
54 // are we running as root? 59 // are we running as root?
55 isRoot = geteuid() == 0; 60 isRoot = geteuid() == 0;
56 61
57 QVBoxLayout* vb = new QVBoxLayout(this, 5); 62 QVBoxLayout* vb = new QVBoxLayout(this, 5);
58 63
59 QHButtonGroup* cfsdRBG = new QHButtonGroup(tr("Swapfile location"), this); 64 QHButtonGroup* cfsdRBG = new QHButtonGroup(tr("Swapfile location"), this);
60 cfsdRBG->setRadioButtonExclusive(true); 65 cfsdRBG->setRadioButtonExclusive(true);
61 vb->addWidget(cfsdRBG); 66 vb->addWidget(cfsdRBG);
62 67
63 ramRB = new QRadioButton(tr("RAM"), cfsdRBG); 68 ramRB = new QRadioButton(tr("RAM"), cfsdRBG);
64 cfRB = new QRadioButton(tr("CF Card"), cfsdRBG); 69 cfRB = new QRadioButton(tr("CF Card"), cfsdRBG);
65 sdRB = new QRadioButton(tr("SD Card"), cfsdRBG); 70 sdRB = new QRadioButton(tr("SD Card"), cfsdRBG);
66 71
67 QHBox *hb1 = new QHBox(this); 72 QHBox *hb1 = new QHBox(this);
68 hb1->setSpacing(5); 73 hb1->setSpacing(5);
69 74
70 swapPath1 = new QLineEdit(hb1); 75 swapPath1 = new QLineEdit(hb1);
71 swapPath1->setEnabled(false); 76 swapPath1->setEnabled(false);
72 77
73 QPushButton* swapOn = new QPushButton(tr(" On "), hb1); 78 QPushButton* swapOn = new QPushButton(tr(" On "), hb1);
74 QPushButton* swapOff = new QPushButton(tr(" Off "), hb1); 79 QPushButton* swapOff = new QPushButton(tr(" Off "), hb1);
75 vb->addWidget(hb1); 80 vb->addWidget(hb1);
76 81
77 QVGroupBox* box1 = new QVGroupBox(tr("Manage Swapfile"), this); 82 QVGroupBox* box1 = new QVGroupBox(tr("Manage Swapfile"), this);
78 vb->addWidget(box1); 83 vb->addWidget(box1);
79 84
80 QHBox *hb2 = new QHBox(box1); 85 QHBox *hb2 = new QHBox(box1);
81 hb2->setSpacing(5); 86 hb2->setSpacing(5);
82 QPushButton* mkSwap = new QPushButton(tr("Generate"), hb2); 87 QPushButton* mkSwap = new QPushButton(tr("Generate"), hb2);
83 QPushButton* rmSwap = new QPushButton(tr("Remove"), hb2); 88 QPushButton* rmSwap = new QPushButton(tr("Remove"), hb2);
84 89
85 QHBox *hb3 = new QHBox(box1); 90 QHBox *hb3 = new QHBox(box1);
86 hb3->setSpacing(5); 91 hb3->setSpacing(5);
87 swapSize = new QComboBox(hb3); 92 swapSize = new QComboBox(hb3);
88 swapSize->insertStringList(QStringList::split(",", tr("2 Mb,4 Mb,6 Mb,8 Mb"))); 93 swapSize->insertStringList(QStringList::split(",", tr("2 Mb,4 Mb,6 Mb,8 Mb")));
89 94
90 mkswapProgress = new QProgressBar(3, hb3); 95 mkswapProgress = new QProgressBar(3, hb3);
91 mkswapProgress->setCenterIndicator(true); 96 mkswapProgress->setCenterIndicator(true);
92 97
93 QHBox *hb4 = new QHBox(this); 98 QHBox *hb4 = new QHBox(this);
94 hb4->setSpacing(5); 99 hb4->setSpacing(5);
95 100
96 swapStatusIcon = new QLabel(hb4); 101 swapStatusIcon = new QLabel(hb4);
97 swapStatus = new QLabel(tr(""), hb4); 102 swapStatus = new QLabel(tr(""), hb4);
98 hb4->setStretchFactor(swapStatus, 99); 103 hb4->setStretchFactor(swapStatus, 99);
99 vb->addWidget(hb4); 104 vb->addWidget(hb4);
100 105
101 connect(swapOn, SIGNAL(clicked()), this, SLOT(swapon())); 106 connect(swapOn, SIGNAL(clicked()), this, SLOT(swapon()));
102 connect(swapOff, SIGNAL(clicked()), this, SLOT(swapoff())); 107 connect(swapOff, SIGNAL(clicked()), this, SLOT(swapoff()));
103 connect(cfRB, SIGNAL(clicked()), this, SLOT(cfsdchecked())); 108 connect(cfRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
104 connect(sdRB, SIGNAL(clicked()), this, SLOT(cfsdchecked())); 109 connect(sdRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
105 connect(ramRB, SIGNAL(clicked()), this, SLOT(cfsdchecked())); 110 connect(ramRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
106 connect(mkSwap, SIGNAL(clicked()), this, SLOT(makeswapfile())); 111 connect(mkSwap, SIGNAL(clicked()), this, SLOT(makeswapfile()));
107 connect(rmSwap, SIGNAL(clicked()), this, SLOT(removeswapfile())); 112 connect(rmSwap, SIGNAL(clicked()), this, SLOT(removeswapfile()));
108 113
109 cfRB->setEnabled(FALSE); 114 cfRB->setEnabled(FALSE);
110 sdRB->setEnabled(FALSE); 115 sdRB->setEnabled(FALSE);
111 116
112 QCopChannel *pcmciaChannel = new QCopChannel("QPE/Card", this); 117 QCopChannel *pcmciaChannel = new QCopChannel("QPE/Card", this);
113 connect(pcmciaChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(cardnotify(const QCString&,const QByteArray&))); 118 connect(pcmciaChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(cardnotify(const QCString&,const QByteArray&)));
114 QCopChannel *sdChannel = new QCopChannel("QPE/Card", this); 119 QCopChannel *sdChannel = new QCopChannel("QPE/Card", this);
115 connect(sdChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(cardnotify(const QCString&,const QByteArray&))); 120 connect(sdChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(cardnotify(const QCString&,const QByteArray&)));
116 121
117 cardInPcmcia0 = FALSE; 122 cardInPcmcia0 = FALSE;
118 cardInPcmcia1 = FALSE; 123 cardInPcmcia1 = FALSE;
119 cardInSd = FALSE; 124 cardInSd = FALSE;
120 125
121 Swapfile::status(); 126 Swapfile::status();
122 Swapfile::getStatusPcmcia(); 127 Swapfile::getStatusPcmcia();
123 Swapfile::getStatusSd(); 128 Swapfile::getStatusSd();
124} 129}
125 130
126int Swapfile::exec(const QString& arg) 131int Swapfile::exec(const QString& arg)
127{ 132{
128 return system((!isRoot ? "sudo " : "") + arg); 133 return system((!isRoot ? "sudo " : "") + arg);
129} 134}
130 135
131 136
132Swapfile::~Swapfile() 137Swapfile::~Swapfile()
133{ 138{
134} 139}
135 140
136void Swapfile::cardnotify(const QCString & msg, const QByteArray &) 141void Swapfile::cardnotify(const QCString & msg, const QByteArray &)
137{ 142{
138 if (msg == "stabChanged()") 143 if (msg == "stabChanged()")
139 { 144 {
140 getStatusPcmcia(); 145 getStatusPcmcia();
141 } 146 }
142 else if (msg == "mtabChanged()") 147 else if (msg == "mtabChanged()")
143 { 148 {
144 getStatusSd(); 149 getStatusSd();
145 } 150 }
146} 151}
147 152
148void Swapfile::getStatusPcmcia() 153void Swapfile::getStatusPcmcia()
149{ 154{
150 155
151 bool cardWas0 = cardInPcmcia0;// remember last state 156 bool cardWas0 = cardInPcmcia0;// remember last state
152 bool cardWas1 = cardInPcmcia1; 157 bool cardWas1 = cardInPcmcia1;
153 158
154 QString fileName; 159 QString fileName;
155 160
156 // one of these 3 files should exist 161 // one of these 3 files should exist
157 if (QFile::exists("/var/run/stab")) { 162 if (QFile::exists("/var/run/stab")) {
158 fileName = "/var/run/stab"; 163 fileName = "/var/run/stab";
159 } else if (QFile::exists("/var/state/pcmcia/stab")) { 164 } else if (QFile::exists("/var/state/pcmcia/stab")) {
160 fileName = "/var/state/pcmcia/stab"; 165 fileName = "/var/state/pcmcia/stab";
161 } else { 166 } else {
162 fileName = "/var/lib/pcmcia/stab"; 167 fileName = "/var/lib/pcmcia/stab";
163 } 168 }
164 169
165 QFile f(fileName); 170 QFile f(fileName);
166 171
167 if (f.open(IO_ReadOnly)) { 172 if (f.open(IO_ReadOnly)) {
168 QStringList list; 173 QStringList list;
169 QTextStream stream(&f); 174 QTextStream stream(&f);
170 QString streamIn; 175 QString streamIn;
171 streamIn = stream.read(); 176 streamIn = stream.read();
172 list = QStringList::split("\n", streamIn); 177 list = QStringList::split("\n", streamIn);
173 for (QStringList::Iterator line = list.begin(); line != list.end(); 178 for (QStringList::Iterator line = list.begin(); line != list.end();
174 line++) { 179 line++) {
175 if ((*line).startsWith("Socket 0:")) { 180 if ((*line).startsWith("Socket 0:")) {
176 if ((*line).startsWith("Socket 0: empty") && cardInPcmcia0) { 181 if ((*line).startsWith("Socket 0: empty") && cardInPcmcia0) {
177 cardInPcmcia0 = FALSE; 182 cardInPcmcia0 = FALSE;
178 } else if (!(*line).startsWith("Socket 0: empty") 183 } else if (!(*line).startsWith("Socket 0: empty")
179 && !cardInPcmcia0) { 184 && !cardInPcmcia0) {
180 cardInPcmcia0 = TRUE; 185 cardInPcmcia0 = TRUE;
181 } 186 }
182 } else if ((*line).startsWith("Socket 1:")) { 187 } else if ((*line).startsWith("Socket 1:")) {
183 if ((*line).startsWith("Socket 1: empty") && cardInPcmcia1) { 188 if ((*line).startsWith("Socket 1: empty") && cardInPcmcia1) {
184 cardInPcmcia1 = FALSE; 189 cardInPcmcia1 = FALSE;
185 } else if (!(*line).startsWith("Socket 1: empty") 190 } else if (!(*line).startsWith("Socket 1: empty")
186 && !cardInPcmcia1) { 191 && !cardInPcmcia1) {
187 cardInPcmcia1 = TRUE; 192 cardInPcmcia1 = TRUE;
188 } 193 }
189 } 194 }
190 } 195 }
191 f.close(); 196 f.close();
192 197
193 if (cardWas0 != cardInPcmcia0 || cardWas1 != cardInPcmcia1) { 198 if (cardWas0 != cardInPcmcia0 || cardWas1 != cardInPcmcia1) {
194 QString text = QString::null; 199 QString text = QString::null;
195 QString what = QString::null; 200 QString what = QString::null;
196 if (cardWas0 != cardInPcmcia0) { 201 if (cardWas0 != cardInPcmcia0) {
197 if (cardInPcmcia0) { 202 if (cardInPcmcia0) {
198 cfRB->setEnabled(TRUE); 203 cfRB->setEnabled(TRUE);
199 } else { 204 } else {
200 cfRB->setChecked(FALSE); 205 cfRB->setChecked(FALSE);
201 cfRB->setEnabled(FALSE); 206 cfRB->setEnabled(FALSE);
202 } 207 }
203 } 208 }
204 209
205 if (cardWas1 != cardInPcmcia1) { 210 if (cardWas1 != cardInPcmcia1) {
206 if (cardInPcmcia1) { 211 if (cardInPcmcia1) {
207 cfRB->setEnabled(TRUE); 212 cfRB->setEnabled(TRUE);
208 } else { 213 } else {
209 cfRB->setChecked(FALSE); 214 cfRB->setChecked(FALSE);
210 cfRB->setEnabled(FALSE); 215 cfRB->setEnabled(FALSE);
211 } 216 }
212 } 217 }
213 } 218 }
214 } else { 219 } else {
215 // no file found 220 // no file found
216 qDebug("no file found"); 221 odebug << "no file found" << oendl;
217 cardInPcmcia0 = FALSE; 222 cardInPcmcia0 = FALSE;
218 cardInPcmcia1 = FALSE; 223 cardInPcmcia1 = FALSE;
219 } 224 }
220 Swapfile::cfsdchecked(); 225 Swapfile::cfsdchecked();
221} 226}
222 227
223 228
224void Swapfile::getStatusSd() 229void Swapfile::getStatusSd()
225{ 230{
226 231
227 bool cardWas = cardInSd;// remember last state 232 bool cardWas = cardInSd;// remember last state
228 cardInSd = FALSE; 233 cardInSd = FALSE;
229 234
230#if defined(_OS_LINUX_) || defined(Q_OS_LINUX) 235#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
231 struct mntent *me; 236 struct mntent *me;
232 FILE *mntfp = setmntent("/etc/mtab", "r"); 237 FILE *mntfp = setmntent("/etc/mtab", "r");
233 238
234 if (mntfp) { 239 if (mntfp) {
235 while ((me = getmntent(mntfp)) != 0) { 240 while ((me = getmntent(mntfp)) != 0) {
236 QString fs = me->mnt_fsname; 241 QString fs = me->mnt_fsname;
237 if (fs.left(14) == "/dev/mmc/part1" || fs.left(7) == "/dev/sd" 242 if (fs.left(14) == "/dev/mmc/part1" || fs.left(7) == "/dev/sd"
238 || fs.left(9) == "/dev/mmcd") { 243 || fs.left(9) == "/dev/mmcd") {
239 cardInSd = TRUE; 244 cardInSd = TRUE;
240 show(); 245 show();
241 } 246 }
242 } 247 }
243 endmntent(mntfp); 248 endmntent(mntfp);
244 } 249 }
245 250
246 if (cardWas != cardInSd) { 251 if (cardWas != cardInSd) {
247 QString text = QString::null; 252 QString text = QString::null;
248 QString what = QString::null; 253 QString what = QString::null;
249 if (cardInSd) { 254 if (cardInSd) {
250 sdRB->setEnabled(TRUE); 255 sdRB->setEnabled(TRUE);
251 } else { 256 } else {
252 sdRB->setChecked(FALSE); 257 sdRB->setChecked(FALSE);
253 sdRB->setEnabled(FALSE); 258 sdRB->setEnabled(FALSE);
254 } 259 }
255 } 260 }
256#else 261#else
257#error "Not on Linux" 262#error "Not on Linux"
258#endif 263#endif
259 Swapfile::cfsdchecked(); 264 Swapfile::cfsdchecked();
260} 265}
261 266
262int rc=0; 267int rc=0;
263 268
264void Swapfile::swapon() 269void Swapfile::swapon()
265{ 270{
266 char swapcmd[128] ="swapon "; 271 char swapcmd[128] ="swapon ";
267 Swapfile::cfsdchecked(); 272 Swapfile::cfsdchecked();
268 strcat(swapcmd,swapPath1->text()); 273 strcat(swapcmd,swapPath1->text());
269 char *runcmd = swapcmd; 274 char *runcmd = swapcmd;
270 rc = exec(QString("%1").arg(runcmd)); 275 rc = exec(QString("%1").arg(runcmd));
271 if (rc != 0) { 276 if (rc != 0) {
272 setStatusMessage("Failed to attach swapfile.", true); 277 setStatusMessage("Failed to attach swapfile.", true);
273 } 278 }
274 else { 279 else {
275 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 280 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
276 setStatusMessage("Swapfile activated."); 281 setStatusMessage("Swapfile activated.");
277 } 282 }
278 Swapfile::status(); 283 Swapfile::status();
279} 284}
280 285
281 286
282void Swapfile::setStatusMessage(const QString& text, bool error /* = false */) 287void Swapfile::setStatusMessage(const QString& text, bool error /* = false */)
283{ 288{
284 swapStatus->setText("<b>" + text + "</b>"); 289 swapStatus->setText("<b>" + text + "</b>");
285 swapStatusIcon->setPixmap(Resource::loadPixmap(error ? "close" : "done")); 290 swapStatusIcon->setPixmap(Resource::loadPixmap(error ? "close" : "done"));
286} 291}
287 292
288 293
289void Swapfile::swapoff() 294void Swapfile::swapoff()
290{ 295{
291 char swapcmd[128] ="swapoff "; 296 char swapcmd[128] ="swapoff ";
292 if (Swapfile::cfRB->isChecked() == TRUE) 297 if (Swapfile::cfRB->isChecked() == TRUE)
293 Swapfile::cfsdchecked(); 298 Swapfile::cfsdchecked();
294 strcat(swapcmd,swapPath1->text()); 299 strcat(swapcmd,swapPath1->text());
295 char *runcmd = swapcmd; 300 char *runcmd = swapcmd;
296 rc = exec(QString("%1").arg(runcmd)); 301 rc = exec(QString("%1").arg(runcmd));
297 if (rc != 0) { 302 if (rc != 0) {
298 setStatusMessage(tr("Failed to detach swapfile."), true); 303 setStatusMessage(tr("Failed to detach swapfile."), true);
299 } 304 }
300 else { 305 else {
301 /* QMessageBox::information(this, "Information", "Swapfile is inactive!"); */ 306 /* QMessageBox::information(this, "Information", "Swapfile is inactive!"); */
302 setStatusMessage(tr("Swapfile deactivated.")); 307 setStatusMessage(tr("Swapfile deactivated."));
303 /* Swapfile::swapPath->clear();*/ 308 /* Swapfile::swapPath->clear();*/
304 } 309 }
305 Swapfile::status(); 310 Swapfile::status();
306} 311}
307 312
308void Swapfile::cfsdchecked() 313void Swapfile::cfsdchecked()
309{ 314{
310 /* Swapfile::swapPath->clear();*/ 315 /* Swapfile::swapPath->clear();*/
311 Swapfile::swapPath1->clear(); 316 Swapfile::swapPath1->clear();
312 if (Swapfile::ramRB->isChecked() == TRUE) 317 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 @@
1/* 1/*
2                 This file is part of the Opie Project 2                 This file is part of the Opie Project
3 3
4 =. (C) 2003 Michael 'Mickey' Lauer <mickey@tm.informatik.uni-frankfurt.de> 4 =. (C) 2003 Michael 'Mickey' Lauer <mickey@tm.informatik.uni-frankfurt.de>
5 .=l. 5 .=l.
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This program is free software; you can 7 _;:,     .>    :=|. This program is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU Library General Public 9:`=1 )Y*s>-.--   : the terms of the GNU Library General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This program is distributed in the hope that 14    .i_,=:_.      -<s. This program is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
19..}^=.=       =       ; Library General Public License for more 19..}^=.=       =       ; Library General Public License for more
20++=   -.     .`     .: details. 20++=   -.     .`     .: details.
21 :     =  ...= . :.=- 21 :     =  ...= . :.=-
22 -.   .:....=;==+<; You should have received a copy of the GNU 22 -.   .:....=;==+<; You should have received a copy of the GNU
23  -_. . .   )=.  = Library General Public License along with 23  -_. . .   )=.  = Library General Public License along with
24    --        :-=` this library; see the file COPYING.LIB. 24    --        :-=` this library; see the file COPYING.LIB.
25 If not, write to the Free Software Foundation, 25 If not, write to the Free Software Foundation,
26 Inc., 59 Temple Place - Suite 330, 26 Inc., 59 Temple Place - Suite 330,
27 Boston, MA 02111-1307, USA. 27 Boston, MA 02111-1307, USA.
28 28
29*/ 29*/
30 30
31#include "networkapplet.h" 31#include "networkapplet.h"
32 32
33/* OPIE */ 33/* OPIE */
34#include <opie2/odebug.h> 34#include <opie2/odebug.h>
35#include <opie2/onetwork.h> 35#include <opie2/onetwork.h>
36#include <opie2/otaskbarapplet.h> 36#include <opie2/otaskbarapplet.h>
37#include <qpe/applnk.h> 37#include <qpe/applnk.h>
38#include <qpe/resource.h> 38#include <qpe/resource.h>
39#include <qpainter.h> 39using namespace Opie::Core;
40using namespace Opie::Ui;
41using namespace Opie::Net;
40 42
41/* QT */ 43/* QT */
44#include <qpainter.h>
42#include <qlabel.h> 45#include <qlabel.h>
43#include <qlayout.h> 46#include <qlayout.h>
44#include <qobjectlist.h> 47#include <qobjectlist.h>
45 48
49/* STD */
46#include <assert.h> 50#include <assert.h>
47 51
48using namespace Opie::Ui;
49using namespace Opie::Net;
50IfaceUpDownButton::IfaceUpDownButton( QWidget* parent, const char* name ) 52IfaceUpDownButton::IfaceUpDownButton( QWidget* parent, const char* name )
51 :QToolButton( parent, name ) 53 :QToolButton( parent, name )
52{ 54{
53 _iface = ONetwork::instance()->interface( name ); 55 _iface = ONetwork::instance()->interface( name );
54 assert( _iface ); 56 assert( _iface );
55 setToggleButton( true ); 57 setToggleButton( true );
56 //setAutoRaise( true ); 58 //setAutoRaise( true );
57 setOnIconSet( QIconSet( Resource::loadPixmap( "up" ) ) ); 59 setOnIconSet( QIconSet( Resource::loadPixmap( "up" ) ) );
58 setOffIconSet( QIconSet( Resource::loadPixmap( "down" ) ) ); 60 setOffIconSet( QIconSet( Resource::loadPixmap( "down" ) ) );
59 setOn( _iface->isUp() ); 61 setOn( _iface->isUp() );
60 //setFixedWidth( 16 ); 62 //setFixedWidth( 16 );
61 connect( this, SIGNAL( clicked() ), this, SLOT( clicked() ) ); 63 connect( this, SIGNAL( clicked() ), this, SLOT( clicked() ) );
62} 64}
63 65
64 66
65IfaceUpDownButton::~IfaceUpDownButton() 67IfaceUpDownButton::~IfaceUpDownButton()
66{ 68{
67} 69}
68 70
69 71
70void IfaceUpDownButton::clicked() 72void IfaceUpDownButton::clicked()
71{ 73{
72 _iface->setUp( isOn() ); 74 _iface->setUp( isOn() );
73 setOn( _iface->isUp() ); // it might not have worked... 75 setOn( _iface->isUp() ); // it might not have worked...
74 repaint(); 76 repaint();
75} 77}
76 78
77 79
78IfaceIPAddress::IfaceIPAddress( QWidget* parent, const char* name ) 80IfaceIPAddress::IfaceIPAddress( QWidget* parent, const char* name )
79 :QLineEdit( parent, name ) 81 :QLineEdit( parent, name )
80{ 82{
81 setFont( QFont( "fixed" ) ); 83 setFont( QFont( "fixed" ) );
82 _iface = ONetwork::instance()->interface( name ); 84 _iface = ONetwork::instance()->interface( name );
83 setFixedWidth( 105 ); 85 setFixedWidth( 105 );
84 setText( _iface->ipV4Address() ); 86 setText( _iface->ipV4Address() );
85 connect( this, SIGNAL( returnPressed() ), this, SLOT( returnPressed() ) ); 87 connect( this, SIGNAL( returnPressed() ), this, SLOT( returnPressed() ) );
86} 88}
87 89
88 90
89IfaceIPAddress::~IfaceIPAddress() 91IfaceIPAddress::~IfaceIPAddress()
90{ 92{
91} 93}
92 94
93 95
94void IfaceIPAddress::returnPressed() 96void IfaceIPAddress::returnPressed()
95{ 97{
96 QHostAddress a; 98 QHostAddress a;
97 a.setAddress( text() ); 99 a.setAddress( text() );
98 QHostAddress mask; 100 QHostAddress mask;
99 mask.setAddress( _iface->ipV4Netmask() ); // setIPV4Address destroys the netmask... 101 mask.setAddress( _iface->ipV4Netmask() ); // setIPV4Address destroys the netmask...
100 _iface->setIPV4Address( a ); 102 _iface->setIPV4Address( a );
101 _iface->setIPV4Netmask( mask ); // recover the old netmask 103 _iface->setIPV4Netmask( mask ); // recover the old netmask
102 setText( _iface->ipV4Address() ); 104 setText( _iface->ipV4Address() );
103 repaint(); 105 repaint();
104} 106}
105 107
106 108
107NetworkAppletControl::NetworkAppletControl( OTaskbarApplet* parent, const char* name ) 109NetworkAppletControl::NetworkAppletControl( OTaskbarApplet* parent, const char* name )
108 :QFrame( parent, name, WStyle_StaysOnTop | WType_Popup ), l(0) 110 :QFrame( parent, name, WStyle_StaysOnTop | WType_Popup ), l(0)
109{ 111{
110 setFrameStyle( QFrame::PopupPanel | QFrame::Raised ); 112 setFrameStyle( QFrame::PopupPanel | QFrame::Raised );
111 l = new QVBoxLayout( this, 4, 2 ); 113 l = new QVBoxLayout( this, 4, 2 );
112} 114}
113 115
114 116
115void NetworkAppletControl::build() 117void NetworkAppletControl::build()
116{ 118{
117 ONetwork::InterfaceIterator it = ONetwork::instance()->iterator(); 119 ONetwork::InterfaceIterator it = ONetwork::instance()->iterator();
118 while ( it.current() ) 120 while ( it.current() )
119 { 121 {
120 QHBoxLayout* h = new QHBoxLayout( l ); 122 QHBoxLayout* h = new QHBoxLayout( l );
121 QLabel* symbol = new QLabel( this ); 123 QLabel* symbol = new QLabel( this );
122 symbol->setPixmap( Resource::loadPixmap( guessDevice( it.current() ) ) ); 124 symbol->setPixmap( Resource::loadPixmap( guessDevice( it.current() ) ) );
123 h->addWidget( symbol ); 125 h->addWidget( symbol );
124 symbol->show(); 126 symbol->show();
125 127
126 QLabel* name = new QLabel( it.current()->name(), this ); 128 QLabel* name = new QLabel( it.current()->name(), this );
127 name->setFixedWidth( 35 ); 129 name->setFixedWidth( 35 );
128 h->addWidget( name ); 130 h->addWidget( name );
129 name->show(); 131 name->show();
130 132
131 IfaceIPAddress* ip = new IfaceIPAddress( this, it.current()->name() ); 133 IfaceIPAddress* ip = new IfaceIPAddress( this, it.current()->name() );
132 h->addWidget( ip ); 134 h->addWidget( ip );
133 ip->show(); 135 ip->show();
134 136
135 IfaceUpDownButton* tb = new IfaceUpDownButton( this, it.current()->name() ); 137 IfaceUpDownButton* tb = new IfaceUpDownButton( this, it.current()->name() );
136 tb->show(); 138 tb->show();
137 139
138 h->addWidget( tb ); 140 h->addWidget( tb );
139 141
140 ++it; 142 ++it;
141 } 143 }
142} 144}
143 145
144 146
145NetworkAppletControl::~NetworkAppletControl() 147NetworkAppletControl::~NetworkAppletControl()
146{ 148{
147} 149}
148 150
149 151
150QString NetworkAppletControl::guessDevice( ONetworkInterface* iface ) 152QString NetworkAppletControl::guessDevice( ONetworkInterface* iface )
151{ 153{
152 if ( iface->isWireless() ) 154 if ( iface->isWireless() )
153 return "networksettings/wlan"; 155 return "networksettings/wlan";
154 if ( iface->isLoopback() ) 156 if ( iface->isLoopback() )
155 return "networksettings/lo"; 157 return "networksettings/lo";
156 if ( QString( iface->name() ).contains( "usb" ) ) 158 if ( QString( iface->name() ).contains( "usb" ) )
157 return "networksettings/usb"; 159 return "networksettings/usb";
158 if ( QString( iface->name() ).contains( "ir" ) ) 160 if ( QString( iface->name() ).contains( "ir" ) )
159 return "networksettings/irda"; 161 return "networksettings/irda";
160 162
161 //TODO: Insert neat symbol and check for tunnel devices 163 //TODO: Insert neat symbol and check for tunnel devices
162 164
163 return "networksettings/lan"; 165 return "networksettings/lan";
164 166
165} 167}
166 168
167 169
168void NetworkAppletControl::showEvent( QShowEvent* e ) 170void NetworkAppletControl::showEvent( QShowEvent* e )
169{ 171{
170 qDebug( "showEvent" ); 172 odebug << "showEvent" << oendl;
171 build(); 173 build();
172 QWidget::showEvent( e ); 174 QWidget::showEvent( e );
173} 175}
174 176
175 177
176void NetworkAppletControl::hideEvent( QHideEvent* e ) 178void NetworkAppletControl::hideEvent( QHideEvent* e )
177{ 179{
178 qDebug( "hideEvent" ); 180 odebug << "hideEvent" << oendl;
179 QWidget::hideEvent( e ); 181 QWidget::hideEvent( e );
180 182
181 delete l; 183 delete l;
182 184
183 // delete all child widgets from this frame 185 // delete all child widgets from this frame
184 QObjectList* list = const_cast<QObjectList*>( children() ); 186 QObjectList* list = const_cast<QObjectList*>( children() );
185 QObjectListIt it(*list); 187 QObjectListIt it(*list);
186 QObject* obj; 188 QObject* obj;
187 while ( (obj=it.current()) ) 189 while ( (obj=it.current()) )
188 { 190 {
189 ++it; 191 ++it;
190 delete obj; 192 delete obj;
191 } 193 }
192 194
193 list = const_cast<QObjectList*>( children() ); 195 list = const_cast<QObjectList*>( children() );
194 if ( list ) 196 if ( list )
195 qWarning( "D'oh! We still have %d children...", list->count() ); 197 owarn << "D'oh! We still have " << list->count() << " children..." << oendl;
196 198
197 // renew layout 199 // renew layout
198 l = new QVBoxLayout( this, 4, 2 ); 200 l = new QVBoxLayout( this, 4, 2 );
199 resize( 0, 0 ); 201 resize( 0, 0 );
200} 202}
201 203
202 204
203QSize NetworkAppletControl::sizeHint() const 205QSize NetworkAppletControl::sizeHint() const
204{ 206{
205 ONetwork::instance()->synchronize(); // rebuild interface database 207 ONetwork::instance()->synchronize(); // rebuild interface database
206 qDebug( "sizeHint (#ifaces=%d)", ONetwork::instance()->count() ); 208 odebug << "sizeHint (#ifaces=" << ONetwork::instance()->count() << ")" << oendl;
207 return QSize( 14+35+105+14 + 8, ONetwork::instance()->count() * 26 ); 209 return QSize( 14+35+105+14 + 8, ONetwork::instance()->count() * 26 );
208} 210}
209 211
210 212
211NetworkApplet::NetworkApplet( QWidget *parent, const char *name ) 213NetworkApplet::NetworkApplet( QWidget *parent, const char *name )
212 :OTaskbarApplet( parent, name ) 214 :OTaskbarApplet( parent, name )
213{ 215{
214 setFixedHeight( AppLnk::smallIconSize() ); 216 setFixedHeight( AppLnk::smallIconSize() );
215 setFixedWidth( AppLnk::smallIconSize() ); 217 setFixedWidth( AppLnk::smallIconSize() );
216 _pixmap.convertFromImage( Resource::loadImage( "networkapplet/network" ).smoothScale( height(), width() ) ); 218 _pixmap.convertFromImage( Resource::loadImage( "networkapplet/network" ).smoothScale( height(), width() ) );
217 _control = new NetworkAppletControl( this, "control" ); 219 _control = new NetworkAppletControl( this, "control" );
218} 220}
219 221
220 222
221NetworkApplet::~NetworkApplet() 223NetworkApplet::~NetworkApplet()
222{ 224{
223} 225}
224 226
225 227
226int NetworkApplet::position() 228int NetworkApplet::position()
227{ 229{
228 return 4; 230 return 4;
229} 231}
230 232
231 233
232void NetworkApplet::paintEvent( QPaintEvent* ) 234void NetworkApplet::paintEvent( QPaintEvent* )
233{ 235{
234 QPainter p(this); 236 QPainter p(this);
235 p.drawPixmap(0, 2, _pixmap ); 237 p.drawPixmap(0, 2, _pixmap );
236} 238}
237 239
238 240
239void NetworkApplet::mousePressEvent( QMouseEvent* ) 241void NetworkApplet::mousePressEvent( QMouseEvent* )
240{ 242{
241 if ( !_control->isVisible() ) 243 if ( !_control->isVisible() )
242 { 244 {
243 popup( _control ); 245 popup( _control );
244 } 246 }
245 else 247 else
246 { 248 {
247 _control->hide(); 249 _control->hide();
248 } 250 }
249} 251}
250 252
251EXPORT_OPIE_APPLET_v1( NetworkApplet ) 253EXPORT_OPIE_APPLET_v1( NetworkApplet )
252 254
253 255
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 @@
1 config NOTESAPPLET 1 config NOTESAPPLET
2 boolean "opie-notesapplet (quick note taking applet)" 2 boolean "opie-notesapplet (quick note taking applet)"
3 default "y" 3 default "y"
4 depends ( LIBQPE || LIBQPE-X11 ) 4 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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002 L.J. Potter <llornkcor@handhelds.org> 2** Copyright (C) 2002 L.J. Potter <llornkcor@handhelds.org>
3 3
4** All rights reserved. 4** All rights reserved.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "notes.h" 16#include "notes.h"
17 17
18#include <qapplication.h> 18/* OPIE */
19#include <stdlib.h> 19#include <opie2/odebug.h>
20#include <qstringlist.h>
21
22#include <opie2/otaskbarapplet.h> 20#include <opie2/otaskbarapplet.h>
23#include <qpe/filemanager.h> 21#include <qpe/filemanager.h>
24#include <qpe/qpeapplication.h> 22#include <qpe/qpeapplication.h>
25#include <qpe/timestring.h> 23#include <qpe/timestring.h>
26#include <qpe/applnk.h> 24#include <qpe/applnk.h>
27#include <qpe/ir.h> 25#include <qpe/ir.h>
28#include <qpe/config.h> 26#include <qpe/config.h>
27using namespace Opie::Core;
28using namespace Opie::Ui;
29 29
30// #include <qsocket.h> 30/* QT */
31// #include <qclipboard.h>
32#include <qmultilineedit.h> 31#include <qmultilineedit.h>
33#include <qlistbox.h> 32#include <qlistbox.h>
34#include <qpopupmenu.h> 33#include <qpopupmenu.h>
35#include <qmessagebox.h> 34#include <qmessagebox.h>
36 35#include <qapplication.h>
37#include <qdir.h> 36#include <qdir.h>
38#include <qfile.h> 37#include <qfile.h>
39#include <qpoint.h> 38#include <qpoint.h>
40#include <qpushbutton.h> 39#include <qpushbutton.h>
41#include <qpainter.h> 40#include <qpainter.h>
42#include <qlayout.h> 41#include <qlayout.h>
43#include <qframe.h> 42#include <qframe.h>
44#include <qpixmap.h> 43#include <qpixmap.h>
45#include <qstring.h> 44#include <qstring.h>
45#include <qstringlist.h>
46#include <qtimer.h> 46#include <qtimer.h>
47 47
48/* STD */
49#include <stdlib.h>
50
48/* XPM */ 51/* XPM */
49using namespace Opie::Ui;
50static char * notes_xpm[] = { 52static char * notes_xpm[] = {
51"16 16 11 1", 53"16 16 11 1",
52" c None", 54" c None",
53". c #000000", 55". c #000000",
54"+ c #7F7F7F", 56"+ c #7F7F7F",
55"@ c #BFBFBF", 57"@ c #BFBFBF",
56"# c #BFC1FF", 58"# c #BFC1FF",
57"$ c #FF0000", 59"$ c #FF0000",
58"% c #FFFFFF", 60"% c #FFFFFF",
59"& c #00037F", 61"& c #00037F",
60"* c #0006FF", 62"* c #0006FF",
61"= c #0005BF", 63"= c #0005BF",
62"- c #7F0000", 64"- c #7F0000",
63" .. ", 65" .. ",
64" .. ", 66" .. ",
65" ... ", 67" ... ",
66" .+ ", 68" .+ ",
67" .@. ", 69" .@. ",
68" . .+ ", 70" . .+ ",
69" ..#.@. ", 71" ..#.@. ",
70" ..###.+.. ", 72" ..###.+.. ",
71" ..###$...##.. ", 73" ..###$...##.. ",
72"..###$$$%+$$##&.", 74"..###$$$%+$$##&.",
73".*=####$-###&=&.", 75".*=####$-###&=&.",
74".=**=###==&=&=..", 76".=**=###==&=&=..",
75" ..=**=#&=&=.. ", 77" ..=**=#&=&=.. ",
76" ..=*=&=.. ", 78" ..=*=&=.. ",
77" ..=.. ", 79" ..=.. ",
78" . "}; 80" . "};
79 81
80 82
81NotesControl::NotesControl( QWidget *, const char * ) 83NotesControl::NotesControl( QWidget *, const char * )
82 : QVBox( 0, "NotesControl",/* WDestructiveClose | */WStyle_StaysOnTop ) 84 : QVBox( 0, "NotesControl",/* WDestructiveClose | */WStyle_StaysOnTop )
83// : QFrame( parent, name, WDestructiveClose | WStyle_StaysOnTop | WType_Popup ) 85// : QFrame( parent, name, WDestructiveClose | WStyle_StaysOnTop | WType_Popup )
84{ 86{
85 QDir d( QDir::homeDirPath()+"/notes"); 87 QDir d( QDir::homeDirPath()+"/notes");
86 if( !d.exists()) { 88 if( !d.exists()) {
87 qDebug("make dir"); 89 odebug << "make dir" << oendl;
88 if(!d.mkdir( QDir::homeDirPath()+"/notes", true)) 90 if(!d.mkdir( QDir::homeDirPath()+"/notes", true))
89 qDebug("<<<<<<<<<<<<<<<<<<<<<<<<<<<make dir failed"); 91 odebug << "<<<<<<<<<<<<<<<<<<<<<<<<<<<make dir failed" << oendl;
90 } 92 }
91 Config cfg("Notes"); 93 Config cfg("Notes");
92 cfg.setGroup("Options"); 94 cfg.setGroup("Options");
93 showMax = cfg.readBoolEntry("ShowMax", false); 95 showMax = cfg.readBoolEntry("ShowMax", false);
94 96
95 setFrameStyle( QFrame::PopupPanel | QFrame::Raised ); 97 setFrameStyle( QFrame::PopupPanel | QFrame::Raised );
96 loaded=false; 98 loaded=false;
97 edited=false; 99 edited=false;
98 doPopulate=true; 100 doPopulate=true;
99 isNew=false; 101 isNew=false;
100 QVBox *vbox = new QVBox( this, "Vlayout" ); 102 QVBox *vbox = new QVBox( this, "Vlayout" );
101 QHBox *hbox = new QHBox( this, "HLayout" ); 103 QHBox *hbox = new QHBox( this, "HLayout" );
102 104
103 view = new QMultiLineEdit(vbox, "OpieNotesView"); 105 view = new QMultiLineEdit(vbox, "OpieNotesView");
104 106
105 box = new QListBox(vbox, "OpieNotesBox"); 107 box = new QListBox(vbox, "OpieNotesBox");
106 108
107 QPEApplication::setStylusOperation( box->viewport(),QPEApplication::RightOnHold); 109 QPEApplication::setStylusOperation( box->viewport(),QPEApplication::RightOnHold);
108 110
109 box->setFixedHeight(50); 111 box->setFixedHeight(50);
110 112
111 vbox->setMargin( 6 ); 113 vbox->setMargin( 6 );
112 vbox->setSpacing( 3 ); 114 vbox->setSpacing( 3 );
113 115
114 116
115 117
116 setFocusPolicy(QWidget::StrongFocus); 118 setFocusPolicy(QWidget::StrongFocus);
117 119
118 newButton= new QPushButton( hbox, "newButton" ); 120 newButton= new QPushButton( hbox, "newButton" );
119 newButton->setText(tr("New")); 121 newButton->setText(tr("New"));
120 122
121 123
122 saveButton= new QPushButton( hbox, "saveButton" ); 124 saveButton= new QPushButton( hbox, "saveButton" );
123 saveButton->setText(tr("Save")); 125 saveButton->setText(tr("Save"));
124 126
125 127
126 deleteButton= new QPushButton( hbox, "deleteButton" ); 128 deleteButton= new QPushButton( hbox, "deleteButton" );
127 deleteButton->setText(tr("Delete")); 129 deleteButton->setText(tr("Delete"));
128 130
129 131
130 132
131 connect( box, SIGNAL( mouseButtonPressed(int,QListBoxItem*,const QPoint&)), 133 connect( box, SIGNAL( mouseButtonPressed(int,QListBoxItem*,const QPoint&)),
132 this,SLOT( boxPressed(int,QListBoxItem*,const QPoint&)) ); 134 this,SLOT( boxPressed(int,QListBoxItem*,const QPoint&)) );
133 135
134 connect(box, SIGNAL(highlighted(const QString&)), this, SLOT(slotBoxSelected(const QString&))); 136 connect(box, SIGNAL(highlighted(const QString&)), this, SLOT(slotBoxSelected(const QString&)));
135 137
136 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showMenu() ) ); 138 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showMenu() ) );
137 139
138 connect(view,SIGNAL( textChanged() ), this, SLOT(slotViewEdited() ) ); 140 connect(view,SIGNAL( textChanged() ), this, SLOT(slotViewEdited() ) );
139 141
140 connect(newButton, SIGNAL(clicked()), this, SLOT(slotNewButton())); 142 connect(newButton, SIGNAL(clicked()), this, SLOT(slotNewButton()));
141 connect(saveButton, SIGNAL(clicked()), this, SLOT(slotSaveButton())); 143 connect(saveButton, SIGNAL(clicked()), this, SLOT(slotSaveButton()));
142 connect(deleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteButtonClicked())); 144 connect(deleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteButtonClicked()));
143 145
144 populateBox(); 146 populateBox();
145 load(); 147 load();
146 setCaption("Notes"); 148 setCaption("Notes");
147 // parent->setFocus(); 149 // parent->setFocus();
148} 150}
149 151
150void NotesControl::slotSaveButton() { 152void NotesControl::slotSaveButton() {
151 slotNewButton(); 153 slotNewButton();
152 populateBox(); 154 populateBox();
153} 155}
154 156
155void NotesControl::slotDeleteButtonClicked() { 157void NotesControl::slotDeleteButtonClicked() {
156 switch ( QMessageBox::warning(this,tr("Delete?") 158 switch ( QMessageBox::warning(this,tr("Delete?")
157 ,tr("Do you really want to<BR><B> delete</B> this note ?") 159 ,tr("Do you really want to<BR><B> delete</B> this note ?")
158 ,tr("Yes"),tr("No"),0,1,1) ) { 160 ,tr("Yes"),tr("No"),0,1,1) ) {
159 case 0: 161 case 0:
160 slotDeleteButton(); 162 slotDeleteButton();
161 break; 163 break;
162 }; 164 };
163} 165}
164 166
165void NotesControl::slotDeleteButton() { 167void NotesControl::slotDeleteButton() {
166 168
167 QString selectedText = box->currentText(); 169 QString selectedText = box->currentText();
168 qDebug("deleting "+selectedText); 170 odebug << "deleting "+selectedText << oendl;
169 171
170 if( !selectedText.isEmpty()) { 172 if( !selectedText.isEmpty()) {
171 173
172 Config cfg("Notes"); 174 Config cfg("Notes");
173 cfg.setGroup("Docs"); 175 cfg.setGroup("Docs");
174 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); 176 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
175 QString entryName, entryName2;; 177 QString entryName, entryName2;;
176 for ( int i = 0; i < noOfFiles; i++ ) { 178 for ( int i = 0; i < noOfFiles; i++ ) {
177 entryName.sprintf( "File%i", i + 1 ); 179 entryName.sprintf( "File%i", i + 1 );
178 if(selectedText == cfg.readEntry( entryName )) { 180 if(selectedText == cfg.readEntry( entryName )) {
179 qDebug("removing %s, %d", selectedText.latin1(), i); 181 odebug << "removing " << selectedText.latin1() << ", " << i << "" << oendl;
180 for ( int j = i; j < noOfFiles; j++ ) { 182 for ( int j = i; j < noOfFiles; j++ ) {
181 entryName.sprintf( "File%i", i + 1 ); 183 entryName.sprintf( "File%i", i + 1 );
182 entryName2.sprintf( "File%i", i + 2 ); 184 entryName2.sprintf( "File%i", i + 2 );
183 QString temp = cfg.readEntry(entryName2); 185 QString temp = cfg.readEntry(entryName2);
184 qDebug("move "+temp); 186 odebug << "move "+temp << oendl;
185 cfg.writeEntry(entryName, temp); 187 cfg.writeEntry(entryName, temp);
186 i++; 188 i++;
187 } 189 }
188 cfg.writeEntry("NumberOfFiles", noOfFiles-1 ); 190 cfg.writeEntry("NumberOfFiles", noOfFiles-1 );
189 entryName.sprintf( "File%i", noOfFiles ); 191 entryName.sprintf( "File%i", noOfFiles );
190 cfg.removeEntry(entryName); 192 cfg.removeEntry(entryName);
191 cfg.write(); 193 cfg.write();
192 DocLnk nf(selectedText); 194 DocLnk nf(selectedText);
193 nf.removeFiles(); 195 nf.removeFiles();
194 QString fi=QPEApplication::documentDir()+"/text/plain/"+selectedText+".desktop"; 196 QString fi=QPEApplication::documentDir()+"/text/plain/"+selectedText+".desktop";
195 qDebug(fi); 197 odebug << fi << oendl;
196 198
197 QFile f( fi); 199 QFile f( fi);
198 if( !f.remove()) qDebug(".desktop file not removed"); 200 if( !f.remove()) odebug << ".desktop file not removed" << oendl;
199 201
200 } 202 }
201 } 203 }
202 view->clear(); 204 view->clear();
203 205
204 populateBox(); 206 populateBox();
205 } 207 }
206} 208}
207 209
208void NotesControl::slotNewButton() { 210void NotesControl::slotNewButton() {
209 if(edited) save(); 211 if(edited) save();
210 view->clear(); 212 view->clear();
211 view->setFocus(); 213 view->setFocus();
212 edited=false; 214 edited=false;
213 isNew=false; 215 isNew=false;
214} 216}
215 217
216void NotesControl::slotBeamButton() { 218void NotesControl::slotBeamButton() {
217 Ir ir; 219 Ir ir;
218 if(!ir.supported()){ 220 if(!ir.supported()){
219 } else { 221 } else {
220 this->hide(); 222 this->hide();
221 QString selectedText = box->currentText(); 223 QString selectedText = box->currentText();
222 if( !selectedText.isEmpty()) { 224 if( !selectedText.isEmpty()) {
223 QString file = QDir::homeDirPath()+"/"+selectedText; 225 QString file = QDir::homeDirPath()+"/"+selectedText;
224 QFile f(file); 226 QFile f(file);
225 Ir *irFile = new Ir(this, "IR"); 227 Ir *irFile = new Ir(this, "IR");
226 connect( irFile, SIGNAL(done(Ir*)), this, SLOT( slotBeamFinished(Ir*))); 228 connect( irFile, SIGNAL(done(Ir*)), this, SLOT( slotBeamFinished(Ir*)));
227 irFile->send( file, "Note", "text/plain" ); 229 irFile->send( file, "Note", "text/plain" );
228 } 230 }
229 } 231 }
230} 232}
231 233
232void NotesControl::slotBeamFinished(Ir *) { 234void NotesControl::slotBeamFinished(Ir *) {
233 this->show(); 235 this->show();
234} 236}
235 237
236void NotesControl::boxPressed(int mouse, QListBoxItem *, const QPoint&) { 238void NotesControl::boxPressed(int mouse, QListBoxItem *, const QPoint&) {
237 switch (mouse) { 239 switch (mouse) {
238 case 1:{ 240 case 1:{
239 } 241 }
240 break; 242 break;
241 case 2: 243 case 2:
242 menuTimer.start( 500, TRUE ); 244 menuTimer.start( 500, TRUE );
243 break; 245 break;
244 }; 246 };
245} 247}
246 248
247void NotesControl::slotBoxSelected(const QString &itemString) { 249void NotesControl::slotBoxSelected(const QString &itemString) {
248 if(edited) { 250 if(edited) {
249 save(); 251 save();
250 } 252 }
251 loaded=false; 253 loaded=false;
252 edited=false; 254 edited=false;
253 load(itemString); 255 load(itemString);
254} 256}
255 257
256 258
257void NotesControl::showMenu() { 259void NotesControl::showMenu() {
258 QPopupMenu *m = new QPopupMenu(0); 260 QPopupMenu *m = new QPopupMenu(0);
259 m->insertItem( tr( "Beam Out" ), this, SLOT( slotBeamButton() )); 261 m->insertItem( tr( "Beam Out" ), this, SLOT( slotBeamButton() ));
260 m->insertItem( tr( "Search For..." ), this, SLOT( slotSearch() )); 262 m->insertItem( tr( "Search For..." ), this, SLOT( slotSearch() ));
261 m->insertItem( tr( "Toggle Maximized" ), this, SLOT( slotShowMax() )); 263 m->insertItem( tr( "Toggle Maximized" ), this, SLOT( slotShowMax() ));
262 m->insertSeparator(); 264 m->insertSeparator();
263 m->insertItem( tr( "Delete" ), this, SLOT( slotDeleteButton() )); 265 m->insertItem( tr( "Delete" ), this, SLOT( slotDeleteButton() ));
264 m->setFocus(); 266 m->setFocus();
265 m->exec( QCursor::pos() ); 267 m->exec( QCursor::pos() );
266 268
267 if(m) delete m; 269 if(m) delete m;
268} 270}
269 271
270void NotesControl::focusOutEvent ( QFocusEvent * e) { 272void NotesControl::focusOutEvent ( QFocusEvent * e) {
271 if( e->reason() == QFocusEvent::Popup) 273 if( e->reason() == QFocusEvent::Popup)
272 save(); 274 save();
273 else { 275 else {
274 if(!loaded) { 276 if(!loaded) {
275 populateBox(); 277 populateBox();
276 load(); 278 load();
277 } 279 }
278 } 280 }
279 QWidget::focusOutEvent(e); 281 QWidget::focusOutEvent(e);
280} 282}
281 283
282void NotesControl::save() { 284void NotesControl::save() {
283 Config cfg("Notes"); 285 Config cfg("Notes");
284 cfg.setGroup("Docs"); 286 cfg.setGroup("Docs");
285 if( edited) { 287 if( edited) {
286// qDebug("is edited"); 288// odebug << "is edited" << oendl;
287 QString rt = view->text(); 289 QString rt = view->text();
288 if( rt.length()>1) { 290 if( rt.length()>1) {
289 QString pt = rt.simplifyWhiteSpace(); 291 QString pt = rt.simplifyWhiteSpace();
290 int i = pt.find( ' ', pt.find( ' ' )+2 ); 292 int i = pt.find( ' ', pt.find( ' ' )+2 );
291 QString docname = pt; 293 QString docname = pt;
292 if ( i > 0 ) 294 if ( i > 0 )
293 docname = pt.left(i); 295 docname = pt.left(i);
294 // remove "." at the beginning 296 // remove "." at the beginning
295 while( docname.startsWith( "." ) ) 297 while( docname.startsWith( "." ) )
296 docname = docname.mid( 1 ); 298 docname = docname.mid( 1 );
297 docname.replace( QRegExp("/"), "_" ); 299 docname.replace( QRegExp("/"), "_" );
298 // cut the length. filenames longer than that don't make sense 300 // cut the length. filenames longer than that don't make sense
299 // and something goes wrong when they get too long. 301 // and something goes wrong when they get too long.
300 if ( docname.length() > 40 ) 302 if ( docname.length() > 40 )
301 docname = docname.left(40); 303 docname = docname.left(40);
302 if ( docname.isEmpty() ) 304 if ( docname.isEmpty() )
303 docname = "Empty Text"; 305 docname = "Empty Text";
304// qDebug(docname); 306// odebug << docname << oendl;
305 307
306 if( oldDocName != docname) { 308 if( oldDocName != docname) {
307 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); 309 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
308 QString entryName; 310 QString entryName;
309 entryName.sprintf( "File%i", noOfFiles + 1 ); 311 entryName.sprintf( "File%i", noOfFiles + 1 );
310 cfg.writeEntry( entryName,docname ); 312 cfg.writeEntry( entryName,docname );
311 cfg.writeEntry("NumberOfFiles", noOfFiles+1 ); 313 cfg.writeEntry("NumberOfFiles", noOfFiles+1 );
312 cfg.write(); 314 cfg.write();
313 } 315 }
314// else 316// else
315// qDebug("oldname equals docname"); 317// odebug << "oldname equals docname" << oendl;
316 318
317 doc = new DocLnk(docname); 319 doc = new DocLnk(docname);
318 if(QFile(doc->linkFile()).exists()) 320 if(QFile(doc->linkFile()).exists())
319 qDebug("puppie"); 321 odebug << "puppie" << oendl;
320 doc->setType("text/plain"); 322 doc->setType("text/plain");
321 doc->setName(docname); 323 doc->setName(docname);
322 QString temp = docname.replace( QRegExp(" "), "_" ); 324 QString temp = docname.replace( QRegExp(" "), "_" );
323 doc->setFile( QDir::homeDirPath()+"/notes/"+temp); 325 doc->setFile( QDir::homeDirPath()+"/notes/"+temp);
324 FileManager fm; 326 FileManager fm;
325 if ( !fm.saveFile( *doc, rt ) ) { 327 if ( !fm.saveFile( *doc, rt ) ) {
326 } 328 }
327 329
328 oldDocName=docname; 330 oldDocName=docname;
329 edited=false; 331 edited=false;
330// qDebug("save"); 332// odebug << "save" << oendl;
331 if (doPopulate) 333 if (doPopulate)
332 populateBox(); 334 populateBox();
333 } 335 }
334 cfg.writeEntry( "LastDoc",oldDocName ); 336 cfg.writeEntry( "LastDoc",oldDocName );
335 cfg.write(); 337 cfg.write();
336 338
337 } 339 }
338} 340}
339 341
340void NotesControl::populateBox() { 342void NotesControl::populateBox() {
341 box->clear(); 343 box->clear();
342// qDebug("populate"); 344// odebug << "populate" << oendl;
343 Config cfg("Notes"); 345 Config cfg("Notes");
344 cfg.setGroup("Docs"); 346 cfg.setGroup("Docs");
345 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); 347 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
346 QStringList list; 348 QStringList list;
347 QString entryName; 349 QString entryName;
348 for ( int i = 0; i < noOfFiles; i++ ) { 350 for ( int i = 0; i < noOfFiles; i++ ) {
349 entryName.sprintf( "File%i", i + 1 ); 351 entryName.sprintf( "File%i", i + 1 );
350 list.append(cfg.readEntry( entryName )); 352 list.append(cfg.readEntry( entryName ));
351 } 353 }
352 list.sort(); 354 list.sort();
353 box->insertStringList(list,-1); 355 box->insertStringList(list,-1);
354 doPopulate=false; 356 doPopulate=false;
355 update(); 357 update();
356} 358}
357 359
358void NotesControl::load() { 360void NotesControl::load() {
359 361
360 if(!loaded) { 362 if(!loaded) {
361 Config cfg("Notes"); 363 Config cfg("Notes");
362 cfg.setGroup("Docs"); 364 cfg.setGroup("Docs");
363 QString lastDoc=cfg.readEntry( "LastDoc","notes"); 365 QString lastDoc=cfg.readEntry( "LastDoc","notes");
364 DocLnk nf; 366 DocLnk nf;
365 nf.setType("text/plain"); 367 nf.setType("text/plain");
366 nf.setFile(lastDoc); 368 nf.setFile(lastDoc);
367 369
368 loadDoc(nf); 370 loadDoc(nf);
369 loaded=true; 371 loaded=true;
370 oldDocName=lastDoc; 372 oldDocName=lastDoc;
371 cfg.writeEntry( "LastDoc",oldDocName ); 373 cfg.writeEntry( "LastDoc",oldDocName );
372 cfg.write(); 374 cfg.write();
373 } 375 }
374} 376}
375 377
376void NotesControl::load(const QString & file) { 378void NotesControl::load(const QString & file) {
377 qDebug("loading "+file); 379 odebug << "loading "+file << oendl;
378 QString name = file; 380 QString name = file;
379 QString temp; 381 QString temp;
380 if( !QFile( QDir::homeDirPath()+"/"+file).exists() ) 382 if( !QFile( QDir::homeDirPath()+"/"+file).exists() )
381 temp = QDir::homeDirPath()+"/notes/"+ name.replace( QRegExp(" "), "_" ); 383 temp = QDir::homeDirPath()+"/notes/"+ name.replace( QRegExp(" "), "_" );
382 else 384 else
383 temp = name; 385 temp = name;
384 if(!loaded) { 386 if(!loaded) {
385 DocLnk nf; 387 DocLnk nf;
386 nf.setType("text/plain"); 388 nf.setType("text/plain");
387 nf.setFile( temp); 389 nf.setFile( temp);
388 if(!temp.isEmpty()) 390 if(!temp.isEmpty())
389 loadDoc(nf); 391 loadDoc(nf);
390 loaded=true; 392 loaded=true;
391 } 393 }
392// view->setFocus(); 394// view->setFocus();
393 oldDocName=file; 395 oldDocName=file;
394 Config cfg("Notes"); 396 Config cfg("Notes");
395 cfg.setGroup("Docs"); 397 cfg.setGroup("Docs");
396 cfg.writeEntry( "LastDoc",oldDocName ); 398 cfg.writeEntry( "LastDoc",oldDocName );
397 cfg.write(); 399 cfg.write();
398} 400}
399 401
400void NotesControl::loadDoc( const DocLnk &f) { 402void NotesControl::loadDoc( const DocLnk &f) {
401 FileManager fm; 403 FileManager fm;
402 QString txt; 404 QString txt;
403 if ( !fm.loadFile( f, txt ) ) { 405 if ( !fm.loadFile( f, txt ) ) {
404 qDebug("could not load file "+f.file()); 406 odebug << "could not load file "+f.file() << oendl;
405 return; 407 return;
406 } 408 }
407 view->setText(txt); 409 view->setText(txt);
408} 410}
409 411
410void NotesControl::slotViewEdited() { 412void NotesControl::slotViewEdited() {
411 if(loaded) { 413 if(loaded) {
412 edited=true; 414 edited=true;
413 } 415 }
414} 416}
415 417
416 418
417void NotesControl::slotShowMax() { 419void NotesControl::slotShowMax() {
418 Config cfg("Notes"); 420 Config cfg("Notes");
419 cfg.setGroup("Options"); 421 cfg.setGroup("Options");
420 showMax=!showMax; 422 showMax=!showMax;
421 cfg.writeEntry("ShowMax", showMax); 423 cfg.writeEntry("ShowMax", showMax);
422 cfg.write(); 424 cfg.write();
423 hide(); 425 hide();
424} 426}
425 427
426void NotesControl::slotSearch() { 428void NotesControl::slotSearch() {
427 int boxCount = box->count(); 429 int boxCount = box->count();
428 for(int i=0;i< boxCount;i++) { 430 for(int i=0;i< boxCount;i++) {
429 431
430 } 432 }
431} 433}
432 434
433// void NotesControl::keyReleaseEvent( QKeyEvent *e) { 435// void NotesControl::keyReleaseEvent( QKeyEvent *e) {
434 436
435// switch ( e->state() ) { 437// switch ( e->state() ) {
436// case ControlButton: 438// case ControlButton:
437// if(e->key() == Key_C) { //copy 439// if(e->key() == Key_C) { //copy
438// qDebug("copy"); 440// odebug << "copy" << oendl;
439// QClipboard *cb = QApplication::clipboard(); 441// QClipboard *cb = QApplication::clipboard();
440// QString text; 442// QString text;
441 443
442// // Copy text from the clipboard (paste) 444// // Copy text from the clipboard (paste)
443// text = cb->text(); 445// text = cb->text();
444// } 446// }
445// if(e->key() == Key_X) { //cut 447// if(e->key() == Key_X) { //cut
446// } 448// }
447// if(e->key() == Key_V) { //paste 449// if(e->key() == Key_V) { //paste
448// QClipboard *cb = QApplication::clipboard(); 450// QClipboard *cb = QApplication::clipboard();
449// QString text; 451// QString text;
450// //view 452// //view
451// cb->setText(); 453// cb->setText();
452// } 454// }
453// break; 455// break;
454// }; 456// };
455// QWidget::keyReleaseEvent(e); 457// QWidget::keyReleaseEvent(e);
456// } 458// }
457 459
458//=========================================================================== 460//===========================================================================
459 461
460NotesApplet::NotesApplet( QWidget *parent, const char *name ) 462NotesApplet::NotesApplet( QWidget *parent, const char *name )
461 : QWidget( parent, name ) { 463 : QWidget( parent, name ) {
462 setFixedHeight( 18 ); 464 setFixedHeight( 18 );
463 setFixedWidth( 14 ); 465 setFixedWidth( 14 );
464 vc = new NotesControl; 466 vc = new NotesControl;
465} 467}
466 468
467NotesApplet::~NotesApplet() { 469NotesApplet::~NotesApplet() {
468 delete vc; 470 delete vc;
469} 471}
470 472
471int NotesApplet::position() 473int NotesApplet::position()
472{ 474{
473 return 6; 475 return 6;
474} 476}
475 477
476void NotesApplet::mousePressEvent( QMouseEvent *) { 478void NotesApplet::mousePressEvent( QMouseEvent *) {
477 if( !vc->isHidden()) { 479 if( !vc->isHidden()) {
478 vc->doPopulate=false; 480 vc->doPopulate=false;
479 vc->save(); 481 vc->save();
480 vc->close(); 482 vc->close();
481 } else { 483 } else {
482// vc = new NotesControl; 484// vc = new NotesControl;
483// QPoint curPos = mapToGlobal( rect().topLeft() ); 485// QPoint curPos = mapToGlobal( rect().topLeft() );
484 if(vc->showMax) { 486 if(vc->showMax) {
485 qDebug("show max"); 487 odebug << "show max" << oendl;
486 vc->showMaximized(); 488 vc->showMaximized();
487 } else { 489 } else {
488 qDebug("no show max"); 490 odebug << "no show max" << oendl;
489 QWidget *wid = QPEApplication::desktop(); 491 QWidget *wid = QPEApplication::desktop();
490 QRect rect = QApplication::desktop()->geometry(); 492 QRect rect = QApplication::desktop()->geometry();
491 vc->setGeometry( ( wid->width() / 2) - ( vc->width() / 2 ) , 28 , wid->width() -10 , 180); 493 vc->setGeometry( ( wid->width() / 2) - ( vc->width() / 2 ) , 28 , wid->width() -10 , 180);
492 vc->move ( (rect.center()/2) - (vc->rect().center()/2)); 494 vc->move ( (rect.center()/2) - (vc->rect().center()/2));
493// vc->move( (( wid->width() / 2) - ( vc->width() / 2 ))-4, 28); 495// vc->move( (( wid->width() / 2) - ( vc->width() / 2 ))-4, 28);
494 } 496 }
495 vc->show(); 497 vc->show();
496 vc->doPopulate=true; 498 vc->doPopulate=true;
497 vc->populateBox(); 499 vc->populateBox();
498 vc->doPopulate=false; 500 vc->doPopulate=false;
499 vc->loaded=false; 501 vc->loaded=false;
500 502
501 vc->load(); 503 vc->load();
502// this->setFocus(); 504// this->setFocus();
503 vc->view->setFocus(); 505 vc->view->setFocus();
504 } 506 }
505} 507}
506 508
507void NotesApplet::paintEvent( QPaintEvent* ) { 509void NotesApplet::paintEvent( QPaintEvent* ) {
508 QPainter p(this); 510 QPainter p(this);
509 p.drawPixmap( 0, 1, ( const char** ) notes_xpm ); 511 p.drawPixmap( 0, 1, ( const char** ) notes_xpm );
510} 512}
511 513
512 514
513EXPORT_OPIE_APPLET_v1( NotesApplet ) 515EXPORT_OPIE_APPLET_v1( NotesApplet )
514 516
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 @@
1TEMPLATE = lib 1TEMPLATE = lib
2CONFIG += qt plugin warn_on 2CONFIG += qt plugin warn_on
3HEADERS = notes.h 3HEADERS = notes.h
4SOURCES = notes.cpp 4SOURCES = notes.cpp
5TARGET = notesapplet 5TARGET = notesapplet
6DESTDIR = $(OPIEDIR)/plugins/applets 6DESTDIR = $(OPIEDIR)/plugins/applets
7INCLUDEPATH += $(OPIEDIR)/include 7INCLUDEPATH += $(OPIEDIR)/include
8DEPENDPATH += $(OPIEDIR)/include 8DEPENDPATH += $(OPIEDIR)/include
9LIBS += -lqpe 9LIBS += -lqpe -lopiecore2
10VERSION = 1.0.0 10VERSION = 1.0.1
11 11
12include ( $(OPIEDIR)/include.pro ) 12include ( $(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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer <mickey@vanille.de> 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer <mickey@vanille.de>
3** 3**
4** This file may be distributed and/or modified under the terms of the 4** This file may be distributed and/or modified under the terms of the
5** GNU General Public License version 2 as published by the Free Software 5** GNU General Public License version 2 as published by the Free Software
6** Foundation and appearing in the file LICENSE.GPL included in the 6** Foundation and appearing in the file LICENSE.GPL included in the
7** packaging of this file. 7** packaging of this file.
8** 8**
9** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 9** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
10** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 10** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
11** 11**
12**********************************************************************/ 12**********************************************************************/
13 13
14#include "wireless.h" 14#include "wireless.h"
15#include "mgraph.h" 15#include "mgraph.h"
16#include "advancedconfig.h" 16#include "advancedconfig.h"
17 17
18/* OPIE */ 18/* OPIE */
19#include <opie2/odebug.h>
19#include <opie2/onetwork.h> 20#include <opie2/onetwork.h>
20#include <opie2/otaskbarapplet.h> 21#include <opie2/otaskbarapplet.h>
21#include <qpe/config.h> 22#include <qpe/config.h>
22#include <qpe/qpeapplication.h> 23#include <qpe/qpeapplication.h>
24using namespace Opie::Core;
25using namespace Opie::Ui;
26using namespace Opie::Net;
23 27
24/* QT */ 28/* QT */
25#include <qradiobutton.h> 29#include <qradiobutton.h>
26#include <qpushbutton.h> 30#include <qpushbutton.h>
27#include <qpainter.h> 31#include <qpainter.h>
28#include <qlabel.h> 32#include <qlabel.h>
29#include <qslider.h> 33#include <qslider.h>
30#include <qbuttongroup.h> 34#include <qbuttongroup.h>
31#include <qlayout.h> 35#include <qlayout.h>
32#include <qfile.h> 36#include <qfile.h>
33#include <qtextstream.h> 37#include <qtextstream.h>
34 38
35/* STD */ 39/* STD */
36#include <math.h> 40#include <math.h>
37#include <sys/types.h> 41#include <sys/types.h>
38#include <signal.h> 42#include <signal.h>
39#if defined (__GNUC__) && (__GNUC__ < 3) 43#if defined (__GNUC__) && (__GNUC__ < 3)
40#define round qRound 44#define round qRound
41#endif 45#endif
42 46
43//#define MDEBUG 47//#define MDEBUG
44#undef MDEBUG 48#undef MDEBUG
45 49
46using namespace Opie::Ui;
47using namespace Opie::Net;
48WirelessControl::WirelessControl( WirelessApplet *applet, QWidget *parent, const char *name ) 50WirelessControl::WirelessControl( WirelessApplet *applet, QWidget *parent, const char *name )
49 : QFrame( parent, name, WStyle_StaysOnTop | WType_Popup ), applet( applet ) 51 : QFrame( parent, name, WStyle_StaysOnTop | WType_Popup ), applet( applet )
50{ 52{
51 53
52 readConfig(); 54 readConfig();
53 writeConfigEntry( "UpdateFrequency", updateFrequency ); 55 writeConfigEntry( "UpdateFrequency", updateFrequency );
54 56
55 setFrameStyle( QFrame::PopupPanel | QFrame::Raised ); 57 setFrameStyle( QFrame::PopupPanel | QFrame::Raised );
56 QGridLayout *grid = new QGridLayout( this, 3, 2, 6, 2, "top layout" ); 58 QGridLayout *grid = new QGridLayout( this, 3, 2, 6, 2, "top layout" );
57 59
58 /* status label */ 60 /* status label */
59 61
60 statusLabel = new QLabel( this, "statuslabel" ); 62 statusLabel = new QLabel( this, "statuslabel" );
61 QString text( "Wireless Status:<br>" 63 QString text( "Wireless Status:<br>"
62 "*** Unknown ***<br>" 64 "*** Unknown ***<br>"
63 "Card not inserted ?<br>" 65 "Card not inserted ?<br>"
64 "Or Sharp ROM ?<br>" 66 "Or Sharp ROM ?<br>"
65 "CELL: 00:00:00:00:00:00" ); 67 "CELL: 00:00:00:00:00:00" );
66 /* QString text( "Station: Unknown<br>" 68 /* QString text( "Station: Unknown<br>"
67 "ESSID: Unknown<br>" 69 "ESSID: Unknown<br>"
68 "MODE: Unknown<br>" 70 "MODE: Unknown<br>"
69 "FREQ: Unknown<br>" 71 "FREQ: Unknown<br>"
70 "CELL: AA:BB:CC:DD:EE:FF" ); */ 72 "CELL: AA:BB:CC:DD:EE:FF" ); */
71 statusLabel->setText( text ); 73 statusLabel->setText( text );
72 statusLabel->setFixedSize( statusLabel->sizeHint() ); 74 statusLabel->setFixedSize( statusLabel->sizeHint() );
73 grid->addWidget( statusLabel, 0, 0 ); 75 grid->addWidget( statusLabel, 0, 0 );
74 76
75 /* visualization group box */ 77 /* visualization group box */
76 78
77 /* quality graph */ 79 /* quality graph */
78 80
79 mgraph = new MGraph( this ); 81 mgraph = new MGraph( this );
80 mgraph->setFrameStyle( QFrame::Panel | QFrame::Sunken ); 82 mgraph->setFrameStyle( QFrame::Panel | QFrame::Sunken );
81 mgraph->setMin( 0 ); 83 mgraph->setMin( 0 );
82 mgraph->setMax( 92 ); 84 mgraph->setMax( 92 );
83 grid->addWidget( mgraph, 1, 0 ); 85 grid->addWidget( mgraph, 1, 0 );
84 mgraph->setFocusPolicy( QWidget::NoFocus ); 86 mgraph->setFocusPolicy( QWidget::NoFocus );
85 87
86 /* advanced configuration Button */ 88 /* advanced configuration Button */
87 89
88 QPushButton* advanced = new QPushButton( "Advanced...", this ); 90 QPushButton* advanced = new QPushButton( "Advanced...", this );
89 advanced->setFocusPolicy( QWidget::NoFocus ); 91 advanced->setFocusPolicy( QWidget::NoFocus );
90 grid->addWidget( advanced, 2, 0, Qt::AlignCenter ); 92 grid->addWidget( advanced, 2, 0, Qt::AlignCenter );
91 connect( advanced, SIGNAL( clicked() ), 93 connect( advanced, SIGNAL( clicked() ),
92 this, SLOT( advancedConfigClicked() ) ); 94 this, SLOT( advancedConfigClicked() ) );
93 95
94 /* update Frequency Label */ 96 /* update Frequency Label */
95 97
96 updateLabel = new QLabel( this ); 98 updateLabel = new QLabel( this );
97 text.sprintf( "Update every %d s", updateFrequency ); 99 text.sprintf( "Update every %d s", updateFrequency );
98 updateLabel->setText( text ); 100 updateLabel->setText( text );
99 grid->addWidget( updateLabel, 2, 1 ); 101 grid->addWidget( updateLabel, 2, 1 );
100 102
101 /* update Frequency Slider */ 103 /* update Frequency Slider */
102 104
103 QSlider* updateSlider = new QSlider( QSlider::Horizontal, this ); 105 QSlider* updateSlider = new QSlider( QSlider::Horizontal, this );
104 updateSlider->setRange( 0, 9 ); 106 updateSlider->setRange( 0, 9 );
105 updateSlider->setValue( updateFrequency ); 107 updateSlider->setValue( updateFrequency );
106 updateSlider->setTickmarks( QSlider::Both ); 108 updateSlider->setTickmarks( QSlider::Both );
107 updateSlider->setTickInterval( 1 ); 109 updateSlider->setTickInterval( 1 );
108 updateSlider->setSteps( 1, 1 ); 110 updateSlider->setSteps( 1, 1 );
109 updateSlider->setFocusPolicy( QWidget::NoFocus ); 111 updateSlider->setFocusPolicy( QWidget::NoFocus );
110 grid->addWidget( updateSlider, 1, 1 ); 112 grid->addWidget( updateSlider, 1, 1 );
111 connect( updateSlider, SIGNAL( valueChanged(int) ), 113 connect( updateSlider, SIGNAL( valueChanged(int) ),
112 this, SLOT( updateDelayChange(int) ) ); 114 this, SLOT( updateDelayChange(int) ) );
113 115
114 setFixedSize( sizeHint() ); 116 setFixedSize( sizeHint() );
115 setFocusPolicy( QWidget::NoFocus ); 117 setFocusPolicy( QWidget::NoFocus );
116 118
117 applet->updateDelayChange( updateFrequency ); 119 applet->updateDelayChange( updateFrequency );
118 120
119 applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE ); 121 applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE );
120} 122}
121 123
122void WirelessControl::advancedConfigClicked() 124void WirelessControl::advancedConfigClicked()
123{ 125{
124 AdvancedConfig * a = new AdvancedConfig( this, "dialog", TRUE ); 126 AdvancedConfig * a = new AdvancedConfig( this, "dialog", TRUE );
125 int result = a->exec(); 127 int result = a->exec();
126 a->hide(); 128 a->hide();
127 delete a; 129 delete a;
128 if ( result == QDialog::Accepted ) 130 if ( result == QDialog::Accepted )
129 { 131 {
130 readConfig(); 132 readConfig();
131 applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE ); 133 applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE );
132 } 134 }
133} 135}
134 136
135void WirelessControl::updateDelayChange( int delay ) 137void WirelessControl::updateDelayChange( int delay )
136{ 138{
137 QString text; 139 QString text;
138 text.sprintf( "Update every %d s", delay ); 140 text.sprintf( "Update every %d s", delay );
139 updateLabel->setText( text ); 141 updateLabel->setText( text );
140 applet->updateDelayChange( delay ); 142 applet->updateDelayChange( delay );
141 writeConfigEntry( "UpdateFrequency", delay ); 143 writeConfigEntry( "UpdateFrequency", delay );
142} 144}
143 145
144void WirelessControl::displayStyleChange( int style ) 146void WirelessControl::displayStyleChange( int style )
145{ 147{
146 applet->displayStyleChange( style ); 148 applet->displayStyleChange( style );
147 writeConfigEntry( "DisplayStyle", style ); 149 writeConfigEntry( "DisplayStyle", style );
148} 150}
149 151
150void WirelessControl::show ( bool ) 152void WirelessControl::show ( bool )
151{ 153{
152 QPoint curPos = applet->mapToGlobal( QPoint ( 0, 0 ) ); 154 QPoint curPos = applet->mapToGlobal( QPoint ( 0, 0 ) );
153 155
154 int w = sizeHint().width(); 156 int w = sizeHint().width();
155 int x = curPos.x() - ( w / 2 ); 157 int x = curPos.x() - ( w / 2 );
156 158
157 if ( ( x + w ) > QPEApplication::desktop() ->width() ) 159 if ( ( x + w ) > QPEApplication::desktop() ->width() )
158 x = QPEApplication::desktop ( ) -> width ( ) - w; 160 x = QPEApplication::desktop ( ) -> width ( ) - w;
159 161
160 move( x, curPos.y () - sizeHint().height () ); 162 move( x, curPos.y () - sizeHint().height () );
161 QFrame::show(); 163 QFrame::show();
162} 164}
163 165
164void WirelessControl::readConfig() 166void WirelessControl::readConfig()
165{ 167{
166 Config cfg( "qpe" ); 168 Config cfg( "qpe" );
167 cfg.setGroup( "Wireless" ); 169 cfg.setGroup( "Wireless" );
168 170
169 updateFrequency = cfg.readNumEntry( "UpdateFrequency", 2 ); 171 updateFrequency = cfg.readNumEntry( "UpdateFrequency", 2 );
170 rocESSID = cfg.readBoolEntry( "renew_dhcp_on_essid_change", false ); 172 rocESSID = cfg.readBoolEntry( "renew_dhcp_on_essid_change", false );
171 rocFREQ = cfg.readBoolEntry( "renew_dhcp_on_freq_change", false ); 173 rocFREQ = cfg.readBoolEntry( "renew_dhcp_on_freq_change", false );
172 rocAP = cfg.readBoolEntry( "renew_dhcp_on_ap_change", false ); 174 rocAP = cfg.readBoolEntry( "renew_dhcp_on_ap_change", false );
173 rocMODE = cfg.readBoolEntry( "renew_dhcp_on_mode_change", false ); 175 rocMODE = cfg.readBoolEntry( "renew_dhcp_on_mode_change", false );
174} 176}
175 177
176void WirelessControl::writeConfigEntry( const char *entry, int val ) 178void WirelessControl::writeConfigEntry( const char *entry, int val )
177{ 179{
178 Config cfg( "qpe" ); 180 Config cfg( "qpe" );
179 cfg.setGroup( "Wireless" ); 181 cfg.setGroup( "Wireless" );
180 cfg.writeEntry( entry, val ); 182 cfg.writeEntry( entry, val );
181} 183}
182 184
183//=========================================================================== 185//===========================================================================
184 186
185WirelessApplet::WirelessApplet( QWidget *parent, const char *name ) 187WirelessApplet::WirelessApplet( QWidget *parent, const char *name )
186 : QWidget( parent, name ), 188 : QWidget( parent, name ),
187 timer( 0 ), interface( 0 ), oldiface( 0 ), 189 timer( 0 ), interface( 0 ), oldiface( 0 ),
188 rocESSID( false ), rocFREQ( false ), rocAP( false ), rocMODE( false ) 190 rocESSID( false ), rocFREQ( false ), rocAP( false ), rocMODE( false )
189{ 191{
190 setFixedHeight( 18 ); 192 setFixedHeight( 18 );
191 setFixedWidth( 14 ); 193 setFixedWidth( 14 );
192 status = new WirelessControl( this, this, "wireless status" ); 194 status = new WirelessControl( this, this, "wireless status" );
193} 195}
194 196
195void WirelessApplet::checkInterface() 197void WirelessApplet::checkInterface()
196{ 198{
197 interface = 0L; 199 interface = 0L;
198 ONetwork* net = ONetwork::instance(); 200 ONetwork* net = ONetwork::instance();
199 net->synchronize(); 201 net->synchronize();
200 ONetwork::InterfaceIterator it = net->iterator(); 202 ONetwork::InterfaceIterator it = net->iterator();
201 203
202 while ( it.current() && !it.current()->isWireless() ) ++it; 204 while ( it.current() && !it.current()->isWireless() ) ++it;
203 205
204 if ( it.current() && it.current()->isWireless() ) 206 if ( it.current() && it.current()->isWireless() )
205 interface = static_cast<OWirelessNetworkInterface*>( it.current() ); 207 interface = static_cast<OWirelessNetworkInterface*>( it.current() );
206 208
207 if ( interface ) 209 if ( interface )
208 { 210 {
209#ifdef MDEBUG 211#ifdef MDEBUG
210 qDebug( "WIFIAPPLET: using interface '%s'", ( const char* ) interface->name() ); 212 odebug << "WIFIAPPLET: using interface '" << ( const char* ) interface->name() << "'" << oendl;
211#endif 213#endif
212 214
213 } 215 }
214 else 216 else
215 { 217 {
216#ifdef MDEBUG 218#ifdef MDEBUG
217 qDebug( "WIFIAPPLET: D'oh! No Wireless interface present... :(" ); 219 odebug << "WIFIAPPLET: D'oh! No Wireless interface present... :(" << oendl;
218#endif 220#endif
219 hide(); 221 hide();
220 } 222 }
221} 223}
222 224
223void WirelessApplet::renewDHCP() 225void WirelessApplet::renewDHCP()
224{ 226{
225#ifdef MDEBUG 227#ifdef MDEBUG
226 qDebug( "WIFIAPPLET: Going to request a DHCP configuration renew." ); 228 odebug << "WIFIAPPLET: Going to request a DHCP configuration renew." << oendl;
227#endif 229#endif
228 230
229 QString pidfile; 231 QString pidfile;
230 if ( !interface ) 232 if ( !interface )
231 return ; 233 return ;
232 QString ifacename( interface->name() ); 234 QString ifacename( interface->name() );
233 235
234 // At first we are trying dhcpcd 236 // At first we are trying dhcpcd
235 237
236 pidfile.sprintf( "/var/run/dhcpcd-%s.pid", ( const char* ) ifacename ); 238 pidfile.sprintf( "/var/run/dhcpcd-%s.pid", ( const char* ) ifacename );
237#ifdef MDEBUG 239#ifdef MDEBUG
238 qDebug( "WIFIAPPLET: dhcpcd pidfile is '%s'", ( const char* ) pidfile ); 240 odebug << "WIFIAPPLET: dhcpcd pidfile is '" << ( const char* ) pidfile << "'" << oendl;
239#endif 241#endif
240 int pid; 242 int pid;
241 QFile pfile( pidfile ); 243 QFile pfile( pidfile );
242 bool hasFile = pfile.open( IO_ReadOnly ); 244 bool hasFile = pfile.open( IO_ReadOnly );
243 QTextStream s( &pfile ); 245 QTextStream s( &pfile );
244 if ( hasFile ) 246 if ( hasFile )
245 { 247 {
246 s >> pid; 248 s >> pid;
247#ifdef MDEBUG 249#ifdef MDEBUG
248 qDebug( "WIFIAPPLET: sent SIGALARM to pid %d", pid ); 250 odebug << "WIFIAPPLET: sent SIGALARM to pid " << pid << "" << oendl;
249#endif 251#endif
250 kill( pid, SIGALRM ); 252 kill( pid, SIGALRM );
251 return ; 253 return ;
252 } 254 }
253 255
254 // No dhcpcd, so we are trying udhcpc 256 // No dhcpcd, so we are trying udhcpc
255#ifdef MDEBUG 257#ifdef MDEBUG
256 qDebug( "WIFIAPPLET: dhcpcd not available." ); 258 odebug << "WIFIAPPLET: dhcpcd not available." << oendl;
257#endif 259#endif
258 pidfile.sprintf( "/var/run/udhcpc.%s.pid", ( const char* ) ifacename ); 260 pidfile.sprintf( "/var/run/udhcpc.%s.pid", ( const char* ) ifacename );
259#ifdef MDEBUG 261#ifdef MDEBUG
260 qDebug( "WIFIAPPLET: udhcpc pidfile is '%s'", ( const char* ) pidfile ); 262 odebug << "WIFIAPPLET: udhcpc pidfile is '" << ( const char* ) pidfile << "'" << oendl;
261#endif 263#endif
262 QFile pfile2( pidfile ); 264 QFile pfile2( pidfile );
263 hasFile = pfile2.open( IO_ReadOnly ); 265 hasFile = pfile2.open( IO_ReadOnly );
264 QTextStream s2( &pfile2 ); 266 QTextStream s2( &pfile2 );
265 if ( hasFile ) 267 if ( hasFile )
266 { 268 {
267 s2 >> pid; 269 s2 >> pid;
268#ifdef MDEBUG 270#ifdef MDEBUG
269 qDebug( "WIFIAPPLET: sent SIGUSR1 to pid %d", pid ); 271 odebug << "WIFIAPPLET: sent SIGUSR1 to pid " << pid << "" << oendl;
270#endif 272#endif
271 kill( pid, SIGUSR1 ); 273 kill( pid, SIGUSR1 );
272 return ; 274 return ;
273 } 275 }
274} 276}
275 277
276void WirelessApplet::updateDHCPConfig( bool ESSID, bool FREQ, bool AP, bool MODE ) 278void WirelessApplet::updateDHCPConfig( bool ESSID, bool FREQ, bool AP, bool MODE )
277{ 279{
278 rocESSID = ESSID; 280 rocESSID = ESSID;
279 rocFREQ = FREQ; 281 rocFREQ = FREQ;
280 rocAP = AP; 282 rocAP = AP;
281 rocMODE = MODE; 283 rocMODE = MODE;
282} 284}
283 285
284void WirelessApplet::updateDelayChange( int delay ) 286void WirelessApplet::updateDelayChange( int delay )
285{ 287{
286 if ( timer ) 288 if ( timer )
287 killTimer( timer ); 289 killTimer( timer );
288 delay *= 1000; 290 delay *= 1000;
289 if ( delay == 0 ) 291 if ( delay == 0 )
290 delay = 50; 292 delay = 50;
291 timer = startTimer( delay ); 293 timer = startTimer( delay );
292} 294}
293 295
294void WirelessApplet::displayStyleChange( int style ) 296void WirelessApplet::displayStyleChange( int style )
295{ 297{
296 visualStyle = style; 298 visualStyle = style;
297 repaint(); 299 repaint();
298} 300}
299 301
300WirelessApplet::~WirelessApplet() 302WirelessApplet::~WirelessApplet()
301{} 303{}
302 304
303void WirelessApplet::timerEvent( QTimerEvent* ) 305void WirelessApplet::timerEvent( QTimerEvent* )
304{ 306{
305#ifdef MDEBUG 307#ifdef MDEBUG
306 qDebug( "WirelessApplet::timerEvent" ); 308 odebug << "WirelessApplet::timerEvent" << oendl;
307#endif 309#endif
308 if ( interface ) 310 if ( interface )
309 { 311 {
310 if ( !ONetwork::instance()->isPresent( (const char*) interface->name() ) ) 312 if ( !ONetwork::instance()->isPresent( (const char*) interface->name() ) )
311 { 313 {
312#ifdef MDEBUG 314#ifdef MDEBUG
313 qDebug( "WIFIAPPLET: Interface no longer present." ); 315 odebug << "WIFIAPPLET: Interface no longer present." << oendl;
314#endif 316#endif
315 interface = 0L; 317 interface = 0L;
316 mustRepaint(); 318 mustRepaint();
317 return; 319 return;
318 } 320 }
319 321
320 if ( mustRepaint() ) 322 if ( mustRepaint() )
321 { 323 {
322#ifdef MDEBUG 324#ifdef MDEBUG
323 qDebug( "WIFIAPPLET: A value has changed -> repainting." ); 325 odebug << "WIFIAPPLET: A value has changed -> repainting." << oendl;
324#endif 326#endif
325 repaint(); 327 repaint();
326 } 328 }
327 329
328 if ( status->isVisible() ) 330 if ( status->isVisible() )
329 { 331 {
330 updatePopupWindow(); 332 updatePopupWindow();
331 } 333 }
332 } 334 }
333 else 335 else
334 { 336 {
335 checkInterface(); 337 checkInterface();
336 } 338 }
337} 339}
338 340
339void WirelessApplet::mousePressEvent( QMouseEvent * ) 341void WirelessApplet::mousePressEvent( QMouseEvent * )
340{ 342{
341 if ( status->isVisible() ) 343 if ( status->isVisible() )
342 status->hide(); 344 status->hide();
343 else 345 else
344 status->show( true ); 346 status->show( true );
345} 347}
346 348
347bool WirelessApplet::mustRepaint() 349bool WirelessApplet::mustRepaint()
348{ 350{
349 // check if there are enough changes to justify a (flickering) repaint 351 // check if there are enough changes to justify a (flickering) repaint
350 352
351 // has the interface changed? 353 // has the interface changed?
352 354
353 if ( interface != oldiface ) 355 if ( interface != oldiface )
354 { 356 {
355 oldiface = interface; 357 oldiface = interface;
356 if ( interface ) 358 if ( interface )
357 { 359 {
358#ifdef MDEBUG 360#ifdef MDEBUG
359 qDebug( "WIFIAPPLET: We had no interface but now we have one! :-)" ); 361 odebug << "WIFIAPPLET: We had no interface but now we have one! :-)" << oendl;
360#endif 362#endif
361 show(); 363 show();
362 } 364 }
363 else 365 else
364 { 366 {
365#ifdef MDEBUG 367#ifdef MDEBUG
366 qDebug( "WIFIAPPLET: We had a interface but now we don't have one! ;-(" ); 368 odebug << "WIFIAPPLET: We had a interface but now we don't have one! ;-(" << oendl;
367#endif 369#endif
368 hide(); 370 hide();
369 return true; 371 return true;
370 } 372 }
371 } 373 }
372 374
373 int rings = numberOfRings(); 375 int rings = numberOfRings();
374 376
375 if ( rings != oldrings ) 377 if ( rings != oldrings )
376 { 378 {
377 oldrings = rings; 379 oldrings = rings;
378 return true; 380 return true;
379 } 381 }
380 382
381 int noiseH = 50; // iface->noisePercent() * ( height() - 3 ) / 100; 383 int noiseH = 50; // iface->noisePercent() * ( height() - 3 ) / 100;
382 int signalH = interface->signalStrength() * ( height() - 3 ) / 100; 384 int signalH = interface->signalStrength() * ( height() - 3 ) / 100;
383 int qualityH = 50; // iface->qualityPercent() * ( height() - 3 ) / 100; 385 int qualityH = 50; // iface->qualityPercent() * ( height() - 3 ) / 100;
384 386
385 if ( ( noiseH != oldnoiseH ) 387 if ( ( noiseH != oldnoiseH )
386 || ( signalH != oldsignalH ) 388 || ( signalH != oldsignalH )
387 || ( qualityH != oldqualityH ) ) 389 || ( qualityH != oldqualityH ) )
388 { 390 {
389 oldnoiseH = noiseH; 391 oldnoiseH = noiseH;
390 oldsignalH = signalH; 392 oldsignalH = signalH;
391 oldqualityH = qualityH; 393 oldqualityH = qualityH;
392 return true; 394 return true;
393 } 395 }
394 396
395 if ( rocESSID && ( oldESSID != interface->SSID() ) ) 397 if ( rocESSID && ( oldESSID != interface->SSID() ) )
396 { 398 {
397#ifdef MDEBUG 399#ifdef MDEBUG
398 qDebug( "WIFIAPPLET: ESSID has changed." ); 400 odebug << "WIFIAPPLET: ESSID has changed." << oendl;
399#endif 401#endif
400 renewDHCP(); 402 renewDHCP();
401 } 403 }
402 else if ( rocFREQ && ( oldFREQ != interface->frequency() ) ) 404 else if ( rocFREQ && ( oldFREQ != interface->frequency() ) )
403 { 405 {
404#ifdef MDEBUG 406#ifdef MDEBUG
405 qDebug( "WIFIAPPLET: FREQ has changed." ); 407 odebug << "WIFIAPPLET: FREQ has changed." << oendl;
406#endif 408#endif
407 renewDHCP(); 409 renewDHCP();
408 } 410 }
409 else if ( rocAP && ( oldAP != interface->associatedAP().toString() ) ) 411 else if ( rocAP && ( oldAP != interface->associatedAP().toString() ) )
410 { 412 {
411#ifdef MDEBUG 413#ifdef MDEBUG
412 qDebug( "WIFIAPPLET: AP has changed." ); 414 odebug << "WIFIAPPLET: AP has changed." << oendl;
413#endif 415#endif
414 renewDHCP(); 416 renewDHCP();
415 } 417 }
416 else if ( rocMODE && ( oldMODE != interface->mode() ) ) 418 else if ( rocMODE && ( oldMODE != interface->mode() ) )
417 { 419 {
418#ifdef MDEBUG 420#ifdef MDEBUG
419 qDebug( "WIFIAPPLET: MODE has changed." ); 421 odebug << "WIFIAPPLET: MODE has changed." << oendl;
420#endif 422#endif
421 renewDHCP(); 423 renewDHCP();
422 } 424 }
423 425
424 oldESSID = interface->SSID(); 426 oldESSID = interface->SSID();
425 oldMODE = interface->mode(); 427 oldMODE = interface->mode();
426 oldFREQ = interface->frequency(); 428 oldFREQ = interface->frequency();
427 oldAP = interface->associatedAP().toString(); 429 oldAP = interface->associatedAP().toString();
428 430
429 return false; 431 return false;
430} 432}
431 433
432void WirelessApplet::updatePopupWindow() 434void WirelessApplet::updatePopupWindow()
433{ 435{
434 int qualityH = interface->signalStrength(); 436 int qualityH = interface->signalStrength();
435 437
436 if ( status->mgraph ) 438 if ( status->mgraph )
437 status->mgraph->addValue( qualityH, false ); 439 status->mgraph->addValue( qualityH, false );
438 440
439 QString freqString; 441 QString freqString;
440 QString cell = ( interface->mode() == "Managed" ) ? "AP: " : "Cell: "; 442 QString cell = ( interface->mode() == "Managed" ) ? "AP: " : "Cell: ";
441 freqString.sprintf( "%.3f GHz", interface->frequency() ); 443 freqString.sprintf( "%.3f GHz", interface->frequency() );
442 status->statusLabel->setText( "Station: " + interface->nickName() + "<br>" + 444 status->statusLabel->setText( "Station: " + interface->nickName() + "<br>" +
443 "ESSID: " + interface->SSID() + "<br>" + 445 "ESSID: " + interface->SSID() + "<br>" +
444 "MODE: " + interface->mode() + "<br>" + 446 "MODE: " + interface->mode() + "<br>" +
445 "FREQ: " + freqString + "<br>" + 447 "FREQ: " + freqString + "<br>" +
446 cell + " " + interface->associatedAP().toString() ); 448 cell + " " + interface->associatedAP().toString() );
447} 449}
448 450
449int WirelessApplet::numberOfRings() 451int WirelessApplet::numberOfRings()
450{ 452{
451 if ( !interface ) return -1; 453 if ( !interface ) return -1;
452 int qualityH = interface->signalStrength(); 454 int qualityH = interface->signalStrength();
453 qDebug( "quality = %d", qualityH ); 455 odebug << "quality = " << qualityH << "" << oendl;
454 if ( qualityH < 1 ) return -1; 456 if ( qualityH < 1 ) return -1;
455 if ( qualityH < 20 ) return 0; 457 if ( qualityH < 20 ) return 0;
456 if ( qualityH < 40 ) return 1; 458 if ( qualityH < 40 ) return 1;
457 if ( qualityH < 60 ) return 2; 459 if ( qualityH < 60 ) return 2;
458 if ( qualityH < 65 ) return 3; 460 if ( qualityH < 65 ) return 3;
459 return 4; 461 return 4;
460} 462}
461 463
462void WirelessApplet::paintEvent( QPaintEvent* ) 464void WirelessApplet::paintEvent( QPaintEvent* )
463{ 465{
464 QPainter p( this ); 466 QPainter p( this );
465 int h = height(); 467 int h = height();
466 int w = width(); 468 int w = width();
467 int m = 2; 469 int m = 2;
468 470
469 p.drawLine( m, h-m-1, round( w/2.0 ), round( 0+h/3.0 ) ); 471 p.drawLine( m, h-m-1, round( w/2.0 ), round( 0+h/3.0 ) );
470 p.drawLine( round( w/2.0 ), round( 0+h/3.0 ), w-m, h-m-1 ); 472 p.drawLine( round( w/2.0 ), round( 0+h/3.0 ), w-m, h-m-1 );
471 p.setPen( QColor( 150, 150, 150 ) ); 473 p.setPen( QColor( 150, 150, 150 ) );
472 p.drawLine( w-m, h-m-1, m, h-m-1 ); 474 p.drawLine( w-m, h-m-1, m, h-m-1 );
473 475
474 int rings = numberOfRings(); 476 int rings = numberOfRings();
475 477
476 if ( rings == -1 ) 478 if ( rings == -1 )
477 { 479 {
478 p.setPen( QPen( QColor( 200, 20, 20 ), 2 ) ); 480 p.setPen( QPen( QColor( 200, 20, 20 ), 2 ) );
479 p.drawLine( w/2-m-m, h/2-m-m, w/2+m+m, h/2+m+m ); 481 p.drawLine( w/2-m-m, h/2-m-m, w/2+m+m, h/2+m+m );
480 p.drawLine( w/2+m+m, h/2-m-m, w/2-m-m, h/2+m+m ); 482 p.drawLine( w/2+m+m, h/2-m-m, w/2-m-m, h/2+m+m );
481 return; 483 return;
482 } 484 }
483 485
484 qDebug( "WirelessApplet: painting %d rings", rings ); 486 odebug << "WirelessApplet: painting " << rings << " rings" << oendl;
485 int radius = 2; 487 int radius = 2;
486 int rstep = 4; 488 int rstep = 4;
487 int maxrings = w/rstep; 489 int maxrings = w/rstep;
488 490
489 p.setPen( QColor( 200, 20, 20 ) ); 491 p.setPen( QColor( 200, 20, 20 ) );
490 for ( int i = 0; i < rings; ++i ) 492 for ( int i = 0; i < rings; ++i )
491 { 493 {
492 p.drawEllipse( w/2 - radius/2, h/3 - radius/2, radius, radius ); 494 p.drawEllipse( w/2 - radius/2, h/3 - radius/2, radius, radius );
493 radius += rstep; 495 radius += rstep;
494 }; 496 };
495 497
496 498
497 499
498} 500}
499 501
500 502
501int WirelessApplet::position() 503int WirelessApplet::position()
502{ 504{
503 return 6; 505 return 6;
504} 506}
505 507
506EXPORT_OPIE_APPLET_v1( WirelessApplet ) 508EXPORT_OPIE_APPLET_v1( WirelessApplet )
507 509
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 @@
1#include <opie2/otaskbarapplet.h> 1#include <opie2/otaskbarapplet.h>
2#include <qpe/qcopenvelope_qws.h> 2#include <qpe/qcopenvelope_qws.h>
3#include <qpe/applnk.h> 3#include <qpe/applnk.h>
4#include <qpe/qpeapplication.h> 4#include <qpe/qpeapplication.h>
5#include <qpe/resource.h> 5#include <qpe/resource.h>
6#include <stdio.h> 6#include <stdio.h>
7#include <unistd.h> 7#include <unistd.h>
8#include "zkbwidget.h" 8#include "zkbwidget.h"
9#include "zkbcfg.h" 9#include "zkbcfg.h"
10 10
11using namespace Opie::Ui; 11using namespace Opie::Ui;
12ZkbWidget::ZkbWidget(QWidget* parent):QLabel(parent),keymap(0), 12ZkbWidget::ZkbWidget(QWidget* parent):QLabel(parent),keymap(0),
13 disabled(Resource::loadPixmap("zkb-disabled")) { 13 disabled(Resource::loadPixmap("zkb-disabled")) {
14 14
15 labels = new QPopupMenu(); 15 labels = new QPopupMenu();
16 connect(labels, SIGNAL(activated(int)), this, 16 connect(labels, SIGNAL(activated(int)), this,
17 SLOT(labelChanged(int))); 17 SLOT(labelChanged(int)));
18 18
19 loadKeymap(); 19 loadKeymap();
20 20
21 channel = new QCopChannel("QPE/zkb", this); 21 channel = new QCopChannel("QPE/zkb", this);
22 connect(channel, SIGNAL(received(const QCString&,const QByteArray&)), 22 connect(channel, SIGNAL(received(const QCString&,const QByteArray&)),
23 this, SLOT(signalReceived(const QCString&,const QByteArray&))); 23 this, SLOT(signalReceived(const QCString&,const QByteArray&)));
24 setFixedWidth ( AppLnk::smallIconSize() ); 24 setFixedWidth ( AppLnk::smallIconSize() );
25 setFixedHeight ( AppLnk::smallIconSize() ); 25 setFixedHeight ( AppLnk::smallIconSize() );
26} 26}
27 27
28ZkbWidget::~ZkbWidget() { 28ZkbWidget::~ZkbWidget() {
29} 29}
30 30
31int ZkbWidget::position() 31int ZkbWidget::position()
32{ 32{
33 return 8; 33 return 8;
34} 34}
35 35
36bool ZkbWidget::loadKeymap() { 36bool ZkbWidget::loadKeymap() {
37 ZkbConfig c(QPEApplication::qpeDir()+"/share/zkb"); 37 ZkbConfig c(QPEApplication::qpeDir()+"/share/zkb");
38 QFontMetrics fm(font()); 38 QFontMetrics fm(font());
39 39
40 if (keymap != 0) { 40 if (keymap != 0) {
41 delete keymap; 41 delete keymap;
42 keymap = 0; 42 keymap = 0;
43 } 43 }
44 44
45 Keymap* km = new Keymap(); 45 Keymap* km = new Keymap();
46 46
47 if (!c.load("zkb.xml", *km, "")) { 47 if (!c.load("zkb.xml", *km, "")) {
48 delete km; 48 delete km;
49 setPixmap(disabled); 49 setPixmap(disabled);
50 return false; 50 return false;
51 } 51 }
52 52
53 connect(km, SIGNAL(stateChanged(const QString&)), 53 connect(km, SIGNAL(stateChanged(const QString&)),
54 this, SLOT(stateChanged(const QString&))); 54 this, SLOT(stateChanged(const QString&)));
55 55
56 qwsServer->setKeyboardFilter(km); 56 qwsServer->setKeyboardFilter(km);
57 57
58 Keymap* oldkm = keymap; 58 Keymap* oldkm = keymap;
59 keymap = km; 59 keymap = km;
60 60
61 if (oldkm != 0) { 61 if (oldkm != 0) {
62 delete oldkm; 62 delete oldkm;
63 } 63 }
64 64
65 setText(keymap->getCurrentLabel()); 65 setText(keymap->getCurrentLabel());
66 66
67 labels->clear(); 67 labels->clear();
68 QStringList l = keymap->listLabels(); 68 QStringList l = keymap->listLabels();
69 labels->insertItem(disabled, 0, 0); 69 labels->insertItem(disabled, 0, 0);
70 int n = 1; 70 int n = 1;
71 w = 0; 71 w = 0;
72 for(QStringList::Iterator it = l.begin(); it != l.end(); 72 for(QStringList::Iterator it = l.begin(); it != l.end();
73 ++it, n++) { 73 ++it, n++) {
74 74
75 // printf("label: %s\n", (const char*) (*it).utf8()); 75 // printf("label: %s\n", (const char*) (*it).utf8());
76 76
77 labels->insertItem(*it, n, n); 77 labels->insertItem(*it, n, n);
78 int lw = fm.width(*it); 78 int lw = fm.width(*it);
79 if (lw > w) { 79 if (lw > w) {
80 w = lw; 80 w = lw;
81 } 81 }
82 } 82 }
83 83
84 if (w == 0) { 84 if (w == 0) {
85 hide(); 85 hide();
86 } else { 86 } else {
87 show(); 87 show();
88 } 88 }
89 return true; 89 return true;
90} 90}
91 91
92QSize ZkbWidget::sizeHint() const { 92QSize ZkbWidget::sizeHint() const {
93 return QSize(AppLnk::smallIconSize(),AppLnk::smallIconSize()); 93 return QSize(AppLnk::smallIconSize(),AppLnk::smallIconSize());
94} 94}
95 95
96void ZkbWidget::stateChanged(const QString& s) { 96void ZkbWidget::stateChanged(const QString& s) {
97 //qDebug("stateChanged: %s\n", (const char*) s.utf8()); 97 //odebug << "stateChanged: " << (const char*) s.utf8() << "\n" << oendl;
98 setText(s); 98 setText(s);
99} 99}
100 100
101void ZkbWidget::labelChanged(int id) { 101void ZkbWidget::labelChanged(int id) {
102 if (id == 0) { 102 if (id == 0) {
103 keymap->disable(); 103 keymap->disable();
104 setPixmap(disabled); 104 setPixmap(disabled);
105 return; 105 return;
106 } 106 }
107 107
108 keymap->enable(); 108 keymap->enable();
109 109
110 QStringList l = keymap->listLabels(); 110 QStringList l = keymap->listLabels();
111 QString lbl = l[id-1]; 111 QString lbl = l[id-1];
112 112
113 //printf("labelChanged: %s\n", (const char*) lbl.utf8()); 113 //printf("labelChanged: %s\n", (const char*) lbl.utf8());
114 State* state = keymap->getStateByLabel(lbl); 114 State* state = keymap->getStateByLabel(lbl);
115 if (state != 0) { 115 if (state != 0) {
116 keymap->setCurrentState(state); 116 keymap->setCurrentState(state);
117 setText(lbl); 117 setText(lbl);
118 } 118 }
119} 119}
120 120
121void ZkbWidget::mouseReleaseEvent(QMouseEvent*) { 121void ZkbWidget::mouseReleaseEvent(QMouseEvent*) {
122 QSize sh = labels->sizeHint(); 122 QSize sh = labels->sizeHint();
123 QPoint p = mapToGlobal(QPoint((width()-sh.width())/2,-sh.height())); 123 QPoint p = mapToGlobal(QPoint((width()-sh.width())/2,-sh.height()));
124 labels->exec(p); 124 labels->exec(p);
125} 125}
126 126
127void ZkbWidget::signalReceived(const QCString& msg, const QByteArray& data) { 127void ZkbWidget::signalReceived(const QCString& msg, const QByteArray& data) {
128 QDataStream stream(data, IO_ReadOnly); 128 QDataStream stream(data, IO_ReadOnly);
129 129
130 if (msg == "enable()") { 130 if (msg == "enable()") {
131 keymap->enable(); 131 keymap->enable();
132 } else if (msg == "disable()") { 132 } else if (msg == "disable()") {
133 keymap->disable(); 133 keymap->disable();
134 } else if (msg == "reload()") { 134 } else if (msg == "reload()") {
135 QCopEnvelope("QPE/System", "busy()"); 135 QCopEnvelope("QPE/System", "busy()");
136 QTimer::singleShot(0, this, SLOT(reload())); 136 QTimer::singleShot(0, this, SLOT(reload()));
137 } else if (msg == "switch(QString)") { 137 } else if (msg == "switch(QString)") {
138 QString lbl; 138 QString lbl;
139 stream >> lbl; 139 stream >> lbl;
140 140
141 if (keymap != 0) { 141 if (keymap != 0) {
142 State* state = keymap->getStateByLabel(lbl); 142 State* state = keymap->getStateByLabel(lbl);
143 if (state != 0) { 143 if (state != 0) {
144 keymap->setCurrentState(state); 144 keymap->setCurrentState(state);
145 setText(lbl); 145 setText(lbl);
146 } 146 }
147 } 147 }
148 } else if (msg == "debug(QString)") { 148 } else if (msg == "debug(QString)") {
149 QString flag; 149 QString flag;
150 stream >> flag; 150 stream >> flag;
151 } 151 }
152} 152}
153 153
154void ZkbWidget::reload() { 154void ZkbWidget::reload() {
155 loadKeymap(); 155 loadKeymap();
156 QCopEnvelope("QPE/System", "notBusy()"); 156 QCopEnvelope("QPE/System", "notBusy()");
157} 157}
158 158
159EXPORT_OPIE_APPLET_v1( ZkbWidget ) 159EXPORT_OPIE_APPLET_v1( ZkbWidget )
160 160
161 161
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 @@
1/*************************************************************************** 1/***************************************************************************
2 AdvancedFm.cpp 2 AdvancedFm.cpp
3 ------------------- 3 -------------------
4 ** Created: Sat Mar 9 23:33:09 2002 4 ** Created: Sat Mar 9 23:33:09 2002
5 copyright : (C) 2002 by ljp 5 copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12#define DEVELOPERS_VERSION 12#define DEVELOPERS_VERSION
13#include "advancedfm.h" 13#include "advancedfm.h"
14 14
15#include <qpe/qpeapplication.h> 15#include <qpe/qpeapplication.h>
16#include <qpe/config.h> 16#include <qpe/config.h>
17#include <qpe/mimetype.h> 17#include <qpe/mimetype.h>
18#include <qpe/applnk.h> 18#include <qpe/applnk.h>
19#include <qpe/resource.h> 19#include <qpe/resource.h>
20#include <qpe/menubutton.h> 20#include <qpe/menubutton.h>
21 21
22#include <qcombobox.h> 22#include <qcombobox.h>
23#include <qpopupmenu.h> 23#include <qpopupmenu.h>
24#include <qlistview.h> 24#include <qlistview.h>
25#include <qmessagebox.h> 25#include <qmessagebox.h>
26#include <qlineedit.h> 26#include <qlineedit.h>
27 27
28 28
29#include <sys/stat.h> 29#include <sys/stat.h>
30#include <time.h> 30#include <time.h>
31#include <dirent.h> 31#include <dirent.h>
32#include <fcntl.h> 32#include <fcntl.h>
33#include <sys/vfs.h> 33#include <sys/vfs.h>
34#include <mntent.h> 34#include <mntent.h>
35 35
36using namespace Opie::Ui; 36using namespace Opie::Ui;
37 37
38#ifdef NOQUICKLAUNCH 38#ifdef NOQUICKLAUNCH
39AdvancedFm::AdvancedFm( ) 39AdvancedFm::AdvancedFm( )
40#else 40#else
41AdvancedFm::AdvancedFm(QWidget *,const char*, WFlags ) 41AdvancedFm::AdvancedFm(QWidget *,const char*, WFlags )
42#endif 42#endif
43 : QMainWindow( ) { 43 : QMainWindow( ) {
44 init(); 44 init();
45 renameBox = 0; 45 renameBox = 0;
46 46
47 unknownXpm = Resource::loadImage( "UnknownDocument" ).smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ); 47 unknownXpm = Resource::loadImage( "UnknownDocument" ).smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() );
48 48
49 initConnections(); 49 initConnections();
50 whichTab=1; 50 whichTab=1;
51 rePopulate(); 51 rePopulate();
52 currentPathCombo->setFocus(); 52 currentPathCombo->setFocus();
53 channel = new QCopChannel( "QPE/Application/advancedfm", this ); 53 channel = new QCopChannel( "QPE/Application/advancedfm", this );
54 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), 54 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
55 this, SLOT( qcopReceive(const QCString&,const QByteArray&)) ); 55 this, SLOT( qcopReceive(const QCString&,const QByteArray&)) );
56} 56}
57 57
58AdvancedFm::~AdvancedFm() { 58AdvancedFm::~AdvancedFm() {
59} 59}
60 60
61 61
62void AdvancedFm::cleanUp() { 62void AdvancedFm::cleanUp() {
63 QString sfile=QDir::homeDirPath(); 63 QString sfile=QDir::homeDirPath();
64 if(sfile.right(1) != "/") 64 if(sfile.right(1) != "/")
65 sfile+="/._temp"; 65 sfile+="/._temp";
66 else 66 else
67 sfile+="._temp"; 67 sfile+="._temp";
68 QFile file( sfile); 68 QFile file( sfile);
69 if(file.exists()) 69 if(file.exists())
70 file.remove(); 70 file.remove();
71} 71}
72 72
73void AdvancedFm::tabChanged(QWidget *) { 73void AdvancedFm::tabChanged(QWidget *) {
74// qWarning("tab changed"); 74// owarn << "tab changed" << oendl;
75 QString path = CurrentDir()->canonicalPath(); 75 QString path = CurrentDir()->canonicalPath();
76 currentPathCombo->lineEdit()->setText( path ); 76 currentPathCombo->lineEdit()->setText( path );
77 77
78 if(whichTab == 1) { 78 if(whichTab == 1) {
79 viewMenu->setItemChecked(viewMenu->idAt(0), true); 79 viewMenu->setItemChecked(viewMenu->idAt(0), true);
80 viewMenu->setItemChecked(viewMenu->idAt(1), false); 80 viewMenu->setItemChecked(viewMenu->idAt(1), false);
81 } else { 81 } else {
82 viewMenu->setItemChecked(viewMenu->idAt(0), false); 82 viewMenu->setItemChecked(viewMenu->idAt(0), false);
83 viewMenu->setItemChecked(viewMenu->idAt(1), true); 83 viewMenu->setItemChecked(viewMenu->idAt(1), true);
84 } 84 }
85 85
86 QString fs= getFileSystemType( (const QString &) path); 86 QString fs= getFileSystemType( (const QString &) path);
87 87
88 setCaption(tr("AdvancedFm :: ")+fs+" :: " 88 setCaption(tr("AdvancedFm :: ")+fs+" :: "
89 +checkDiskSpace( (const QString &) path )+ tr(" kB free") ); 89 +checkDiskSpace( (const QString &) path )+ tr(" kB free") );
90 chdir( path.latin1()); 90 chdir( path.latin1());
91} 91}
92 92
93 93
94void AdvancedFm::populateView() { 94void AdvancedFm::populateView() {
95 95
96// qWarning("PopulateView"); 96// owarn << "PopulateView" << oendl;
97 QPixmap pm; 97 QPixmap pm;
98 QListView *thisView = CurrentView(); 98 QListView *thisView = CurrentView();
99 QDir *thisDir = CurrentDir(); 99 QDir *thisDir = CurrentDir();
100 QString path = thisDir->canonicalPath(); 100 QString path = thisDir->canonicalPath();
101 101
102//qWarning("path is "+path); 102//owarn << "path is "+path << oendl;
103 thisView->clear(); 103 thisView->clear();
104 thisDir->setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 104 thisDir->setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
105 thisDir->setMatchAllDirs(TRUE); 105 thisDir->setMatchAllDirs(TRUE);
106 thisDir->setNameFilter(filterStr); 106 thisDir->setNameFilter(filterStr);
107 QString fileL, fileS, fileDate; 107 QString fileL, fileS, fileDate;
108 QString fs= getFileSystemType((const QString &) path); 108 QString fs= getFileSystemType((const QString &) path);
109 setCaption(tr("AdvancedFm :: ")+fs+" :: " 109 setCaption(tr("AdvancedFm :: ")+fs+" :: "
110 +checkDiskSpace((const QString &) path)+ tr(" kB free") ); 110 +checkDiskSpace((const QString &) path)+ tr(" kB free") );
111 bool isDir=FALSE; 111 bool isDir=FALSE;
112 const QFileInfoList *list = thisDir->entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/); 112 const QFileInfoList *list = thisDir->entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/);
113 QFileInfoListIterator it(*list); 113 QFileInfoListIterator it(*list);
114 QFileInfo *fi; 114 QFileInfo *fi;
115 while ( (fi=it.current()) ) { 115 while ( (fi=it.current()) ) {
116 if (fi->isSymLink() ) { 116 if (fi->isSymLink() ) {
117 QString symLink=fi->readLink(); 117 QString symLink=fi->readLink();
118 QFileInfo sym( symLink); 118 QFileInfo sym( symLink);
119 fileS.sprintf( "%10i", sym.size() ); 119 fileS.sprintf( "%10i", sym.size() );
120 fileL = fi->fileName() +" -> " + sym.filePath().data(); 120 fileL = fi->fileName() +" -> " + sym.filePath().data();
121 fileDate = sym.lastModified().toString(); 121 fileDate = sym.lastModified().toString();
122 } else { 122 } else {
123 fileS.sprintf( "%10i", fi->size() ); 123 fileS.sprintf( "%10i", fi->size() );
124 fileL = fi->fileName(); 124 fileL = fi->fileName();
125 fileDate= fi->lastModified().toString(); 125 fileDate= fi->lastModified().toString();
126 if( QDir(QDir::cleanDirPath( path +"/"+fileL)).exists() ) { 126 if( QDir(QDir::cleanDirPath( path +"/"+fileL)).exists() ) {
127// if(fileL == "..") 127// if(fileL == "..")
128 fileL += "/"; 128 fileL += "/";
129 isDir=TRUE; 129 isDir=TRUE;
130 } 130 }
131 } 131 }
132 QFileInfo fileInfo( path + "/" + fileL); 132 QFileInfo fileInfo( path + "/" + fileL);
133 133
134 if(fileL !="./" && fi->exists()) { 134 if(fileL !="./" && fi->exists()) {
135 item = new QListViewItem( thisView, fileL, fileS , fileDate); 135 item = new QListViewItem( thisView, fileL, fileS , fileDate);
136 136
137 if(isDir || fileL.find("/",0,TRUE) != -1) { 137 if(isDir || fileL.find("/",0,TRUE) != -1) {
138 138
139 if( !QDir( fi->filePath() ).isReadable()) //is directory 139 if( !QDir( fi->filePath() ).isReadable()) //is directory
140 pm = Resource::loadPixmap( "lockedfolder" ); 140 pm = Resource::loadPixmap( "lockedfolder" );
141 else 141 else
142 pm= Resource::loadPixmap( "folder" ); 142 pm= Resource::loadPixmap( "folder" );
143 } 143 }
144 else if ( fs == "vfat" && fileInfo.filePath().contains("/bin") ) { 144 else if ( fs == "vfat" && fileInfo.filePath().contains("/bin") ) {
145 pm = Resource::loadPixmap( "exec"); 145 pm = Resource::loadPixmap( "exec");
146 } 146 }
147 else if( (fileInfo.permission( QFileInfo::ExeUser) 147 else if( (fileInfo.permission( QFileInfo::ExeUser)
148 | fileInfo.permission( QFileInfo::ExeGroup) 148 | fileInfo.permission( QFileInfo::ExeGroup)
149 | fileInfo.permission( QFileInfo::ExeOther)) && fs != "vfat" ) { 149 | fileInfo.permission( QFileInfo::ExeOther)) && fs != "vfat" ) {
150 pm = Resource::loadPixmap( "exec"); 150 pm = Resource::loadPixmap( "exec");
151 } 151 }
152 else if( !fi->isReadable() ) { 152 else if( !fi->isReadable() ) {
153 pm = Resource::loadPixmap( "locked" ); 153 pm = Resource::loadPixmap( "locked" );
154 } 154 }
155 else { //everything else goes by mimetype 155 else { //everything else goes by mimetype
156 MimeType mt(fi->filePath()); 156 MimeType mt(fi->filePath());
157 pm=mt.pixmap(); //sets the correct pixmap for mimetype 157 pm=mt.pixmap(); //sets the correct pixmap for mimetype
158 if(pm.isNull()) { 158 if(pm.isNull()) {
159 pm = unknownXpm; 159 pm = unknownXpm;
160 } 160 }
161 } 161 }
162 if( fi->isSymLink() || fileL.find("->",0,TRUE) != -1) { 162 if( fi->isSymLink() || fileL.find("->",0,TRUE) != -1) {
163 // qDebug(" overlay link image"); 163 // odebug << " overlay link image" << oendl;
164 pm= Resource::loadPixmap( "advancedfm/symlink" ); 164 pm= Resource::loadPixmap( "advancedfm/symlink" );
165 // pm= Resource::loadPixmap( "folder" ); 165 // pm= Resource::loadPixmap( "folder" );
166// QPixmap lnk = Resource::loadPixmap( "opie/symlink" ); 166// QPixmap lnk = Resource::loadPixmap( "opie/symlink" );
167// QPainter painter( &pm ); 167// QPainter painter( &pm );
168// painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk ); 168// painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk );
169// pm.setMask( pm.createHeuristicMask( FALSE ) ); 169// pm.setMask( pm.createHeuristicMask( FALSE ) );
170 } 170 }
171 item->setPixmap( 0,pm); 171 item->setPixmap( 0,pm);
172 172
173 } 173 }
174 isDir=FALSE; 174 isDir=FALSE;
175 ++it; 175 ++it;
176 } 176 }
177 177
178 if( path.find("dev",0,TRUE) != -1) { 178 if( path.find("dev",0,TRUE) != -1) {
179 struct stat buf; 179 struct stat buf;
180 dev_t devT; 180 dev_t devT;
181 DIR *dir; 181 DIR *dir;
182 struct dirent *mydirent; 182 struct dirent *mydirent;
183 183
184 if((dir = opendir( path.latin1())) != NULL) 184 if((dir = opendir( path.latin1())) != NULL)
185 while ((mydirent = readdir(dir)) != NULL) { 185 while ((mydirent = readdir(dir)) != NULL) {
186 lstat( mydirent->d_name, &buf); 186 lstat( mydirent->d_name, &buf);
187// qDebug(mydirent->d_name); 187// odebug << mydirent->d_name << oendl;
188 fileL.sprintf("%s", mydirent->d_name); 188 fileL.sprintf("%s", mydirent->d_name);
189 devT = buf.st_dev; 189 devT = buf.st_dev;
190 fileS.sprintf("%d, %d", (int) ( devT >>8) &0xFF, (int)devT &0xFF); 190 fileS.sprintf("%d, %d", (int) ( devT >>8) &0xFF, (int)devT &0xFF);
191 fileDate.sprintf("%s", ctime( &buf.st_mtime)); 191 fileDate.sprintf("%s", ctime( &buf.st_mtime));
192 if( fileL.find(".") == -1 ) { 192 if( fileL.find(".") == -1 ) {
193 item= new QListViewItem( thisView, fileL, fileS, fileDate); 193 item= new QListViewItem( thisView, fileL, fileS, fileDate);
194 pm = unknownXpm; 194 pm = unknownXpm;
195 item->setPixmap( 0,pm); 195 item->setPixmap( 0,pm);
196 } 196 }
197 } 197 }
198 198
199 closedir(dir); 199 closedir(dir);
200 } 200 }
201 201
202 thisView->setSorting( 3,FALSE); 202 thisView->setSorting( 3,FALSE);
203 fillCombo( (const QString &) path ); 203 fillCombo( (const QString &) path );
204} 204}
205 205
206void AdvancedFm::rePopulate() { 206void AdvancedFm::rePopulate() {
207 populateView(); 207 populateView();
208 setOtherTabCurrent(); 208 setOtherTabCurrent();
209 populateView(); 209 populateView();
210 210
211// int tmpTab = whichTab; 211// int tmpTab = whichTab;
212// // qDebug("%d", tmpTab); 212// // odebug << "" << tmpTab << "" << oendl;
213 213
214// for(int i =1; i < 3; i++) { 214// for(int i =1; i < 3; i++) {
215// TabWidget->setCurrentWidget(i - 1); 215// TabWidget->setCurrentWidget(i - 1);
216// populateView(); 216// populateView();
217// } 217// }
218// TabWidget->setCurrentWidget( tmpTab - 1); 218// TabWidget->setCurrentWidget( tmpTab - 1);
219} 219}
220 220
221void AdvancedFm::ListClicked(QListViewItem *selectedItem) { 221void AdvancedFm::ListClicked(QListViewItem *selectedItem) {
222//qWarning("listclicked"); 222//owarn << "listclicked" << oendl;
223 if(selectedItem) { 223 if(selectedItem) {
224 QString strItem=selectedItem->text(0); 224 QString strItem=selectedItem->text(0);
225// qWarning(strItem); 225// owarn << strItem << oendl;
226 QString strSize=selectedItem->text(1); 226 QString strSize=selectedItem->text(1);
227 strSize=strSize.stripWhiteSpace(); 227 strSize=strSize.stripWhiteSpace();
228 bool isDirectory = false; 228 bool isDirectory = false;
229 QString strItem2; 229 QString strItem2;
230 230
231 if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) {//if symlink 231 if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) {//if symlink
232 strItem2 = dealWithSymName((const QString&)strItem); 232 strItem2 = dealWithSymName((const QString&)strItem);
233 if(QDir(strItem2).exists() ) 233 if(QDir(strItem2).exists() )
234 strItem = strItem2; 234 strItem = strItem2;
235 } 235 }
236 236
237 if( strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) { 237 if( strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) {
238 238
239 if(QDir(strItem).exists()) 239 if(QDir(strItem).exists())
240 isDirectory = true; 240 isDirectory = true;
241 } 241 }
242 242
243 if( isDirectory ) { 243 if( isDirectory ) {
244 CurrentDir()->cd( strItem, TRUE); 244 CurrentDir()->cd( strItem, TRUE);
245 populateView(); 245 populateView();
246 CurrentView()->ensureItemVisible( CurrentView()->firstChild()); 246 CurrentView()->ensureItemVisible( CurrentView()->firstChild());
247 } 247 }
248 chdir( strItem.latin1()); 248 chdir( strItem.latin1());
249 } 249 }
250} 250}
251 251
252void AdvancedFm::ListPressed( int mouse, QListViewItem *item, const QPoint& , int ) { 252void AdvancedFm::ListPressed( int mouse, QListViewItem *item, const QPoint& , int ) {
253 dealWithSchmooSchmaa( item->listView()); 253 dealWithSchmooSchmaa( item->listView());
254 switch (mouse) { 254 switch (mouse) {
255 case 1: 255 case 1:
256 { 256 {
257 if(renameBox != 0 ) { 257 if(renameBox != 0 ) {
258 cancelRename(); 258 cancelRename();
259 } 259 }
260 } 260 }
261 break; 261 break;
262 case 2: 262 case 2:
263 menuTimer.start( 500, TRUE ); 263 menuTimer.start( 500, TRUE );
264 break; 264 break;
265 }; 265 };
266} 266}
267 267
268 268
269void AdvancedFm::switchToLocalTab() { 269void AdvancedFm::switchToLocalTab() {
270//qWarning("switch to local view"); 270//owarn << "switch to local view" << oendl;
271 TabWidget->setCurrentWidget(0); 271 TabWidget->setCurrentWidget(0);
272 Local_View->setFocus(); 272 Local_View->setFocus();
273} 273}
274 274
275void AdvancedFm::switchToRemoteTab() { 275void AdvancedFm::switchToRemoteTab() {
276//qWarning("switch to local view"); 276//owarn << "switch to local view" << oendl;
277 TabWidget->setCurrentWidget(1); 277 TabWidget->setCurrentWidget(1);
278 Remote_View->setFocus(); 278 Remote_View->setFocus();
279} 279}
280 280
281void AdvancedFm::readConfig() { 281void AdvancedFm::readConfig() {
282 Config cfg("AdvancedFm"); 282 Config cfg("AdvancedFm");
283} 283}
284 284
285void AdvancedFm::writeConfig() { 285void AdvancedFm::writeConfig() {
286 Config cfg("AdvancedFm"); 286 Config cfg("AdvancedFm");
287} 287}
288 288
289void AdvancedFm::currentPathComboChanged() { 289void AdvancedFm::currentPathComboChanged() {
290 if(QDir( currentPathCombo->lineEdit()->text()).exists()) { 290 if(QDir( currentPathCombo->lineEdit()->text()).exists()) {
291 CurrentDir()->setPath( currentPathCombo->lineEdit()->text() ); 291 CurrentDir()->setPath( currentPathCombo->lineEdit()->text() );
292 populateView(); 292 populateView();
293 } else { 293 } else {
294 QMessageBox::message(tr("Note"),tr("That directory does not exist")); 294 QMessageBox::message(tr("Note"),tr("That directory does not exist"));
295 } 295 }
296} 296}
297 297
298void AdvancedFm::fillCombo(const QString &currentPath) { 298void AdvancedFm::fillCombo(const QString &currentPath) {
299 299
300 if ( whichTab == 1) { 300 if ( whichTab == 1) {
301 currentPathCombo->lineEdit()->setText( currentPath); 301 currentPathCombo->lineEdit()->setText( currentPath);
302 if( localDirPathStringList.grep( currentPath,TRUE).isEmpty() ) { 302 if( localDirPathStringList.grep( currentPath,TRUE).isEmpty() ) {
303 currentPathCombo->clear(); 303 currentPathCombo->clear();
304 localDirPathStringList.prepend( currentPath ); 304 localDirPathStringList.prepend( currentPath );
305 currentPathCombo->insertStringList( localDirPathStringList,-1); 305 currentPathCombo->insertStringList( localDirPathStringList,-1);
306 } 306 }
307 } else { 307 } else {
308 currentPathCombo->lineEdit()->setText( currentPath); 308 currentPathCombo->lineEdit()->setText( currentPath);
309 if( remoteDirPathStringList.grep( currentPath,TRUE).isEmpty() ) { 309 if( remoteDirPathStringList.grep( currentPath,TRUE).isEmpty() ) {
310 currentPathCombo->clear(); 310 currentPathCombo->clear();
311 remoteDirPathStringList.prepend( currentPath ); 311 remoteDirPathStringList.prepend( currentPath );
312 currentPathCombo->insertStringList( remoteDirPathStringList,-1); 312 currentPathCombo->insertStringList( remoteDirPathStringList,-1);
313 } 313 }
314 } 314 }
315} 315}
316 316
317void AdvancedFm::currentPathComboActivated(const QString & currentPath) { 317void AdvancedFm::currentPathComboActivated(const QString & currentPath) {
318 chdir( currentPath.latin1() ); 318 chdir( currentPath.latin1() );
319 CurrentDir()->cd( currentPath, TRUE); 319 CurrentDir()->cd( currentPath, TRUE);
320 populateView(); 320 populateView();
321 update(); 321 update();
322} 322}
323 323
324QStringList AdvancedFm::getPath() { 324QStringList AdvancedFm::getPath() {
325 QStringList strList; 325 QStringList strList;
326 QListView *thisView=CurrentView(); 326 QListView *thisView=CurrentView();
327 QList<QListViewItem> * getSelectedItems( QListView * thisView ); 327 QList<QListViewItem> * getSelectedItems( QListView * thisView );
328 QListViewItemIterator it( thisView ); 328 QListViewItemIterator it( thisView );
329 for ( ; it.current(); ++it ) { 329 for ( ; it.current(); ++it ) {
330 if ( it.current()->isSelected() ) { 330 if ( it.current()->isSelected() ) {
331 strList << it.current()->text(0); 331 strList << it.current()->text(0);
332// qDebug(it.current()->text(0)); 332// odebug << it.current()->text(0) << oendl;
333 } 333 }
334 } 334 }
335 return strList; 335 return strList;
336} 336}
337 337
338void AdvancedFm::homeButtonPushed() { 338void AdvancedFm::homeButtonPushed() {
339 QString current = QDir::homeDirPath(); 339 QString current = QDir::homeDirPath();
340 chdir( current.latin1() ); 340 chdir( current.latin1() );
341 CurrentDir()->cd( current, TRUE); 341 CurrentDir()->cd( current, TRUE);
342 populateView(); 342 populateView();
343 update(); 343 update();
344} 344}
345 345
346void AdvancedFm::docButtonPushed() { 346void AdvancedFm::docButtonPushed() {
347 QString current = QPEApplication::documentDir(); 347 QString current = QPEApplication::documentDir();
348 chdir( current.latin1() ); 348 chdir( current.latin1() );
349 CurrentDir()->cd( current, TRUE); 349 CurrentDir()->cd( current, TRUE);
350 populateView(); 350 populateView();
351 update(); 351 update();
352} 352}
353 353
354void AdvancedFm::SDButtonPushed() { 354void AdvancedFm::SDButtonPushed() {
355 QString current = "/mnt/card";// this can change so fix 355 QString current = "/mnt/card";// this can change so fix
356 chdir( current.latin1() ); 356 chdir( current.latin1() );
357 CurrentDir()->cd( current, TRUE); 357 CurrentDir()->cd( current, TRUE);
358 populateView(); 358 populateView();
359 update(); 359 update();
360} 360}
361 361
362void AdvancedFm::CFButtonPushed() { 362void AdvancedFm::CFButtonPushed() {
363 QString current; 363 QString current;
364 if(zaurusDevice) 364 if(zaurusDevice)
365 current= "/mnt/cf"; //zaurus 365 current= "/mnt/cf"; //zaurus
366 else 366 else
367 current = "/mnt/hda"; //ipaq 367 current = "/mnt/hda"; //ipaq
368 chdir( current.latin1() ); 368 chdir( current.latin1() );
369 CurrentDir()->cd( current, TRUE); 369 CurrentDir()->cd( current, TRUE);
370 populateView(); 370 populateView();
371 update(); 371 update();
372} 372}
373 373
374 374
375void AdvancedFm::doAbout() { 375void AdvancedFm::doAbout() {
376 QMessageBox::message("AdvancedFm",tr("Advanced FileManager\n" 376 QMessageBox::message("AdvancedFm",tr("Advanced FileManager\n"
377 "is copyright 2002-2003 by\n" 377 "is copyright 2002-2003 by\n"
378 "L.J.Potter<llornkcor@handhelds.org>\n" 378 "L.J.Potter<llornkcor@handhelds.org>\n"
379 "and is licensed by the GPL")); 379 "and is licensed by the GPL"));
380} 380}
381 381
382void AdvancedFm::keyPressEvent( QKeyEvent *e) { 382void AdvancedFm::keyPressEvent( QKeyEvent *e) {
383// qWarning("key %d", e->key()); 383// owarn << "key " << e->key() << "" << oendl;
384// if( CurrentView()->hasFocus() ) 384// if( CurrentView()->hasFocus() )
385 { 385 {
386 switch ( e->key() ) { 386 switch ( e->key() ) {
387 case Key_Left: 387 case Key_Left:
388 upDir(); 388 upDir();
389 break; 389 break;
390 case Key_Next: 390 case Key_Next:
391 break; 391 break;
392 case Key_Return: 392 case Key_Return:
393 case Key_Enter: 393 case Key_Enter:
394 navigateToSelected(); 394 navigateToSelected();
395 break; 395 break;
396 case Key_Tab: { 396 case Key_Tab: {
397 setOtherTabCurrent(); 397 setOtherTabCurrent();
398 } 398 }
399 break; 399 break;
400 case Key_Delete: 400 case Key_Delete:
401 del(); 401 del();
402 break; 402 break;
403 case Key_A: 403 case Key_A:
404 copyAs(); 404 copyAs();
405 break; 405 break;
406 case Key_C: 406 case Key_C:
407 copy(); 407 copy();
408 break; 408 break;
409 case Key_E: 409 case Key_E:
410 runThis(); 410 runThis();
411 break; 411 break;
412 case Key_G: 412 case Key_G:
413 { 413 {
414 currentPathCombo->lineEdit()->setFocus(); 414 currentPathCombo->lineEdit()->setFocus();
415 } 415 }
416 break; 416 break;
417 417
418 case Key_H: 418 case Key_H:
419 showHidden(); 419 showHidden();
420 break; 420 break;
421 case Key_I: 421 case Key_I:
422 fileStatus(); 422 fileStatus();
423 break; 423 break;
424 case Key_M: 424 case Key_M:
425 move(); 425 move();
426 break; 426 break;
427 case Key_N: 427 case Key_N:
428 mkDir(); 428 mkDir();
429 break; 429 break;
430 case Key_P: 430 case Key_P:
431 filePerms(); 431 filePerms();
432 break; 432 break;
433 case Key_R: 433 case Key_R:
434 rn(); 434 rn();
435 break; 435 break;
436 case Key_U: 436 case Key_U:
437 upDir(); 437 upDir();
438 break; 438 break;
439 case Key_1: 439 case Key_1:
440 switchToLocalTab(); 440 switchToLocalTab();
441 break; 441 break;
442 case Key_2: 442 case Key_2:
443 switchToRemoteTab(); 443 switchToRemoteTab();
444 break; 444 break;
445 case Key_3: 445 case Key_3:
446 CFButtonPushed(); 446 CFButtonPushed();
447 break; 447 break;
448 case Key_4: 448 case Key_4:
449 SDButtonPushed(); 449 SDButtonPushed();
450 break; 450 break;
451 case Key_5: 451 case Key_5:
452 homeButtonPushed(); 452 homeButtonPushed();
453 break; 453 break;
454 case Key_6: 454 case Key_6:
455 docButtonPushed(); 455 docButtonPushed();
456 break; 456 break;
457 case Key_7: 457 case Key_7:
458 break; 458 break;
459 case Key_8: 459 case Key_8:
460 break; 460 break;
461 case Key_9: 461 case Key_9:
462 break; 462 break;
463 case Key_0: 463 case Key_0:
464 break; 464 break;
465 }; 465 };
466 e->accept(); 466 e->accept();
467 } 467 }
468} 468}
469 469
470void AdvancedFm::keyReleaseEvent( QKeyEvent *e) { 470void AdvancedFm::keyReleaseEvent( QKeyEvent *e) {
471 if( CurrentView()->hasFocus() ) 471 if( CurrentView()->hasFocus() )
472 e->ignore(); 472 e->ignore();
473} 473}
474 474
475 475
476void AdvancedFm::QPEButtonPushed() { 476void AdvancedFm::QPEButtonPushed() {
477 QString current = QPEApplication::qpeDir(); 477 QString current = QPEApplication::qpeDir();
478 chdir( current.latin1() ); 478 chdir( current.latin1() );
479 CurrentDir()->cd( current, TRUE); 479 CurrentDir()->cd( current, TRUE);
@@ -545,341 +545,341 @@ void AdvancedFm::showFileMenu() {
545 545
546 MimeType mt( curApp ); 546 MimeType mt( curApp );
547 const AppLnk* app = mt.application(); 547 const AppLnk* app = mt.application();
548 QFile fi(curApp); 548 QFile fi(curApp);
549 QPopupMenu *m = new QPopupMenu(0); 549 QPopupMenu *m = new QPopupMenu(0);
550 QPopupMenu *n = new QPopupMenu(0); 550 QPopupMenu *n = new QPopupMenu(0);
551 // QPopupMenu *o = new QPopupMenu(0); 551 // QPopupMenu *o = new QPopupMenu(0);
552 m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() )); 552 m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() ));
553 553
554 if ( QFileInfo(fi).isDir() ) { 554 if ( QFileInfo(fi).isDir() ) {
555 m->insertSeparator(); 555 m->insertSeparator();
556 m->insertItem( tr( "Change Directory" ), this, SLOT( doDirChange() )); 556 m->insertItem( tr( "Change Directory" ), this, SLOT( doDirChange() ));
557 } else { 557 } else {
558 558
559 if ( app ) 559 if ( app )
560 m->insertItem( app->pixmap(), tr( "Open in " 560 m->insertItem( app->pixmap(), tr( "Open in "
561 + app->name() ), this, SLOT( runThis() ) ); 561 + app->name() ), this, SLOT( runThis() ) );
562 else if( QFileInfo(fi).isExecutable() ) //damn opie doesnt like this 562 else if( QFileInfo(fi).isExecutable() ) //damn opie doesnt like this
563 m->insertItem( tr( "Execute" ), this, SLOT( runThis() ) ); 563 m->insertItem( tr( "Execute" ), this, SLOT( runThis() ) );
564 m->insertItem( Resource::loadPixmap( "txt" ), tr( "Open as text" ),this, SLOT( runText() ) ); 564 m->insertItem( Resource::loadPixmap( "txt" ), tr( "Open as text" ),this, SLOT( runText() ) );
565 } 565 }
566 566
567 m->insertItem(tr("Actions"),n); 567 m->insertItem(tr("Actions"),n);
568 n->insertItem( tr( "Make Directory" ), this, SLOT( makeDir() )); 568 n->insertItem( tr( "Make Directory" ), this, SLOT( makeDir() ));
569 569
570 n->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() )); 570 n->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() ));
571 571
572 n->insertSeparator(); 572 n->insertSeparator();
573 n->insertItem( tr( "Rename" ), this, SLOT( renameIt() )); 573 n->insertItem( tr( "Rename" ), this, SLOT( renameIt() ));
574 574
575 n->insertItem( tr( "Copy" ), this, SLOT( copy() )); 575 n->insertItem( tr( "Copy" ), this, SLOT( copy() ));
576 n->insertItem( tr( "Copy As" ), this, SLOT( copyAs() )); 576 n->insertItem( tr( "Copy As" ), this, SLOT( copyAs() ));
577 n->insertItem( tr( "Copy Same Dir" ), this, SLOT( copySameDir() )); 577 n->insertItem( tr( "Copy Same Dir" ), this, SLOT( copySameDir() ));
578 n->insertItem( tr( "Move" ), this, SLOT( move() )); 578 n->insertItem( tr( "Move" ), this, SLOT( move() ));
579 579
580 n->insertSeparator(); 580 n->insertSeparator();
581 n->insertItem( tr( "Delete" ), this, SLOT( doDelete() )); 581 n->insertItem( tr( "Delete" ), this, SLOT( doDelete() ));
582 m->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() )); 582 m->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() ));
583 583
584 m->insertItem( tr( "Run Command" ), this, SLOT( runCommand() )); 584 m->insertItem( tr( "Run Command" ), this, SLOT( runCommand() ));
585 m->insertItem( tr( "File Info" ), this, SLOT( fileStatus() )); 585 m->insertItem( tr( "File Info" ), this, SLOT( fileStatus() ));
586 586
587 m->insertSeparator(); 587 m->insertSeparator();
588 m->insertItem( tr( "Set Permissions" ), this, SLOT( filePerms() )); 588 m->insertItem( tr( "Set Permissions" ), this, SLOT( filePerms() ));
589 589
590#if defined(QT_QWS_OPIE) 590#if defined(QT_QWS_OPIE)
591 m->insertItem( tr( "Properties" ), this, SLOT( doProperties() )); 591 m->insertItem( tr( "Properties" ), this, SLOT( doProperties() ));
592#endif 592#endif
593 m->setCheckable(TRUE); 593 m->setCheckable(TRUE);
594 if (!b) 594 if (!b)
595 m->setItemChecked(m->idAt(0),TRUE); 595 m->setItemChecked(m->idAt(0),TRUE);
596 else 596 else
597 m->setItemChecked(m->idAt(0),FALSE); 597 m->setItemChecked(m->idAt(0),FALSE);
598 598
599 if(Ir::supported()) 599 if(Ir::supported())
600 m->insertItem( tr( "Beam File" ), this, SLOT( doBeam() )); 600 m->insertItem( tr( "Beam File" ), this, SLOT( doBeam() ));
601 m->setFocus(); 601 m->setFocus();
602 602
603 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) ); 603 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) );
604 604
605 if(m) delete m; 605 if(m) delete m;
606} 606}
607 607
608 608
609void AdvancedFm::cancelMenuTimer() { 609void AdvancedFm::cancelMenuTimer() {
610 610
611 if( menuTimer.isActive() ) 611 if( menuTimer.isActive() )
612 menuTimer.stop(); 612 menuTimer.stop();
613} 613}
614 614
615QString AdvancedFm::checkDiskSpace(const QString &path) { 615QString AdvancedFm::checkDiskSpace(const QString &path) {
616 struct statfs fss; 616 struct statfs fss;
617 if ( !statfs( path.latin1(), &fss ) ) { 617 if ( !statfs( path.latin1(), &fss ) ) {
618 int blkSize = fss.f_bsize; 618 int blkSize = fss.f_bsize;
619// int totalBlks = fs.f_blocks; 619// int totalBlks = fs.f_blocks;
620 int availBlks = fss.f_bavail; 620 int availBlks = fss.f_bavail;
621 621
622 long mult = blkSize / 1024; 622 long mult = blkSize / 1024;
623 long div = 1024 / blkSize; 623 long div = 1024 / blkSize;
624 if ( !mult ) mult = 1; 624 if ( !mult ) mult = 1;
625 if ( !div ) div = 1; 625 if ( !div ) div = 1;
626 626
627 627
628 return QString::number(availBlks * mult / div); 628 return QString::number(availBlks * mult / div);
629 } 629 }
630 return ""; 630 return "";
631} 631}
632 632
633void AdvancedFm::addToDocs() { 633void AdvancedFm::addToDocs() {
634 QStringList strListPaths = getPath(); 634 QStringList strListPaths = getPath();
635 QDir *thisDir = CurrentDir(); 635 QDir *thisDir = CurrentDir();
636 636
637 if( strListPaths.count() > 0) { 637 if( strListPaths.count() > 0) {
638 QString curFile; 638 QString curFile;
639 for ( QStringList::Iterator it = strListPaths.begin(); it != strListPaths.end(); ++it ) { 639 for ( QStringList::Iterator it = strListPaths.begin(); it != strListPaths.end(); ++it ) {
640 curFile = thisDir->canonicalPath()+"/"+(*it); 640 curFile = thisDir->canonicalPath()+"/"+(*it);
641// qDebug(curFile); 641// odebug << curFile << oendl;
642 QFileInfo fi(curFile); 642 QFileInfo fi(curFile);
643 DocLnk f; 643 DocLnk f;
644// curFile.replace(QRegExp("\\..*"),""); 644// curFile.replace(QRegExp("\\..*"),"");
645 f.setName(fi.baseName() ); 645 f.setName(fi.baseName() );
646 f.setFile( curFile); 646 f.setFile( curFile);
647 f.writeLink(); 647 f.writeLink();
648 } 648 }
649 } 649 }
650} 650}
651 651
652 652
653void AdvancedFm::customDirsToMenu() { 653void AdvancedFm::customDirsToMenu() {
654 654
655 Config cfg("AdvancedFm"); 655 Config cfg("AdvancedFm");
656 cfg.setGroup("Menu"); 656 cfg.setGroup("Menu");
657 657
658 QStringList list = cfg.readListEntry( "CustomDir", ','); 658 QStringList list = cfg.readListEntry( "CustomDir", ',');
659 menuButton->insertItems(list ); 659 menuButton->insertItems(list );
660 660
661// for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) 661// for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
662// { 662// {
663// customDirMenu->insertItem(*it ); 663// customDirMenu->insertItem(*it );
664// } 664// }
665} 665}
666 666
667void AdvancedFm::dirMenuSelected(int item) { 667void AdvancedFm::dirMenuSelected(int item) {
668 switch(item) 668 switch(item)
669 { 669 {
670 670
671 case -21: 671 case -21:
672 case 0: 672 case 0:
673 addCustomDir(); 673 addCustomDir();
674 break; 674 break;
675 case -22: 675 case -22:
676 case 1: 676 case 1:
677 removeCustomDir(); 677 removeCustomDir();
678 break; 678 break;
679 default: 679 default:
680 { 680 {
681// gotoCustomDir( menuButton->text(item)); 681// gotoCustomDir( menuButton->text(item));
682// gotoCustomDir( customDirMenu->text(item)); 682// gotoCustomDir( customDirMenu->text(item));
683 } 683 }
684 break; 684 break;
685 685
686 }; 686 };
687} 687}
688 688
689void AdvancedFm::addCustomDir() { 689void AdvancedFm::addCustomDir() {
690 Config cfg("AdvancedFm"); 690 Config cfg("AdvancedFm");
691 cfg.setGroup("Menu"); 691 cfg.setGroup("Menu");
692 QString dir; 692 QString dir;
693 QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)','); 693 QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)',');
694 694
695 dir = CurrentDir()->canonicalPath(); 695 dir = CurrentDir()->canonicalPath();
696 696
697 bool addIt=true; 697 bool addIt=true;
698 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { 698 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
699 if( dir == (*it)) { 699 if( dir == (*it)) {
700 addIt=false; 700 addIt=false;
701 } 701 }
702 } 702 }
703 if(addIt) { 703 if(addIt) {
704 menuButton->insertItem(dir); 704 menuButton->insertItem(dir);
705// customDirMenu->insertItem(dir); 705// customDirMenu->insertItem(dir);
706 list << dir; 706 list << dir;
707 } 707 }
708 708
709 cfg.writeEntry("CustomDir", list, ','); 709 cfg.writeEntry("CustomDir", list, ',');
710 cfg.write(); 710 cfg.write();
711} 711}
712 712
713void AdvancedFm::removeCustomDir() { 713void AdvancedFm::removeCustomDir() {
714// qDebug("remove custom dir"); 714// odebug << "remove custom dir" << oendl;
715 Config cfg("AdvancedFm"); 715 Config cfg("AdvancedFm");
716 cfg.setGroup("Menu"); 716 cfg.setGroup("Menu");
717 QString dir; 717 QString dir;
718 QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)','); 718 QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)',');
719 QStringList list2; 719 QStringList list2;
720 dir = CurrentDir()->canonicalPath(); 720 dir = CurrentDir()->canonicalPath();
721 int ramble=2; 721 int ramble=2;
722// int ramble=-24; 722// int ramble=-24;
723//first remove list 723//first remove list
724 if(list.grep(dir,true).isEmpty()) { 724 if(list.grep(dir,true).isEmpty()) {
725 QMessageBox::message(tr( "AdvancedFm" ), 725 QMessageBox::message(tr( "AdvancedFm" ),
726 tr("Cannot remove current directory\nfrom bookmarks.\nIt is not bookmarked!")); 726 tr("Cannot remove current directory\nfrom bookmarks.\nIt is not bookmarked!"));
727 } else { 727 } else {
728 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { 728 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
729 if((*it) != dir) { 729 if((*it) != dir) {
730//current item is not our current dir, so add it to temp list 730//current item is not our current dir, so add it to temp list
731 list2 <<(*it); 731 list2 <<(*it);
732 } else { 732 } else {
733// customDirMenu->removeItem( ramble); 733// customDirMenu->removeItem( ramble);
734 menuButton->remove( ramble); 734 menuButton->remove( ramble);
735 735
736 } 736 }
737 ramble++; 737 ramble++;
738// ramble--; 738// ramble--;
739 } 739 }
740 740
741 cfg.writeEntry("CustomDir", list2, ','); 741 cfg.writeEntry("CustomDir", list2, ',');
742 cfg.write(); 742 cfg.write();
743 } 743 }
744// customDirsToMenu(); 744// customDirsToMenu();
745 745
746} 746}
747 747
748void AdvancedFm::gotoCustomDir(const QString &dir) { 748void AdvancedFm::gotoCustomDir(const QString &dir) {
749// qDebug("gotoCustomDir(const QString &dir) " +dir ); 749// odebug << "gotoCustomDir(const QString &dir) " +dir << oendl;
750// QString curDir = dir; 750// QString curDir = dir;
751// QDir *thisDir = CurrentDir(); 751// QDir *thisDir = CurrentDir();
752// if( curDir.isEmpty()) { 752// if( curDir.isEmpty()) {
753// } 753// }
754 if( dir == s_addBookmark) { 754 if( dir == s_addBookmark) {
755 addCustomDir(); 755 addCustomDir();
756 } 756 }
757 if( dir == s_removeBookmark) { 757 if( dir == s_removeBookmark) {
758 removeCustomDir( ); 758 removeCustomDir( );
759 } else { 759 } else {
760 gotoDirectory( dir); 760 gotoDirectory( dir);
761// if(QDir( curDir).exists() ) 761// if(QDir( curDir).exists() )
762// { 762// {
763// thisDir->setPath( curDir ); 763// thisDir->setPath( curDir );
764// chdir( curDir.latin1() ); 764// chdir( curDir.latin1() );
765// thisDir->cd( curDir, TRUE); 765// thisDir->cd( curDir, TRUE);
766// populateView(); 766// populateView();
767// } 767// }
768 } 768 }
769} 769}
770 770
771QDir *AdvancedFm::CurrentDir() { 771QDir *AdvancedFm::CurrentDir() {
772 772
773 if ( whichTab == 1) { 773 if ( whichTab == 1) {
774 return &currentDir; 774 return &currentDir;
775 } else { 775 } else {
776 return &currentRemoteDir; 776 return &currentRemoteDir;
777 } 777 }
778} 778}
779 779
780QDir *AdvancedFm::OtherDir() { 780QDir *AdvancedFm::OtherDir() {
781 if ( whichTab == 1) { 781 if ( whichTab == 1) {
782 return &currentRemoteDir; 782 return &currentRemoteDir;
783 } else { 783 } else {
784 return &currentDir; 784 return &currentDir;
785 } 785 }
786} 786}
787 787
788QListView * AdvancedFm::CurrentView() { 788QListView * AdvancedFm::CurrentView() {
789 if ( whichTab == 1) { 789 if ( whichTab == 1) {
790// qWarning("CurrentView Tab 1"); 790// owarn << "CurrentView Tab 1" << oendl;
791 return Local_View; 791 return Local_View;
792 } else { 792 } else {
793// qWarning("CurrentView Tab 2"); 793// owarn << "CurrentView Tab 2" << oendl;
794 return Remote_View; 794 return Remote_View;
795 } 795 }
796} 796}
797 797
798QListView * AdvancedFm::OtherView() { 798QListView * AdvancedFm::OtherView() {
799 if ( whichTab == 1) 799 if ( whichTab == 1)
800 return Remote_View; 800 return Remote_View;
801 else 801 else
802 return Local_View; 802 return Local_View;
803} 803}
804 804
805void AdvancedFm::setOtherTabCurrent() { 805void AdvancedFm::setOtherTabCurrent() {
806// qWarning("setOtherTabCurrent() %d", whichTab); 806// owarn << "setOtherTabCurrent() " << whichTab << "" << oendl;
807 if ( whichTab == 1) { 807 if ( whichTab == 1) {
808 TabWidget->setCurrentWidget(1); 808 TabWidget->setCurrentWidget(1);
809 } else { 809 } else {
810 TabWidget->setCurrentWidget(0); 810 TabWidget->setCurrentWidget(0);
811 } 811 }
812 OtherView()->setFocus(); 812 OtherView()->setFocus();
813 OtherView()->setSelected( CurrentView()->firstChild(), true); 813 OtherView()->setSelected( CurrentView()->firstChild(), true);
814} 814}
815 815
816void AdvancedFm::qcopReceive(const QCString &msg, const QByteArray &data) { 816void AdvancedFm::qcopReceive(const QCString &msg, const QByteArray &data) {
817// qDebug("qcop message "+msg ); 817// odebug << "qcop message "+msg << oendl;
818 QDataStream stream ( data, IO_ReadOnly ); 818 QDataStream stream ( data, IO_ReadOnly );
819 if ( msg == "openDirectory(QString)" ) { 819 if ( msg == "openDirectory(QString)" ) {
820// qDebug("received"); 820// odebug << "received" << oendl;
821 QString file; 821 QString file;
822 stream >> file; 822 stream >> file;
823 gotoDirectory( (const QString &) file); 823 gotoDirectory( (const QString &) file);
824 } 824 }
825} 825}
826 826
827void AdvancedFm::setDocument(const QString &file) { 827void AdvancedFm::setDocument(const QString &file) {
828 gotoDirectory( file); 828 gotoDirectory( file);
829 829
830} 830}
831 831
832void AdvancedFm::gotoDirectory(const QString &file) { 832void AdvancedFm::gotoDirectory(const QString &file) {
833// qWarning("goto dir "+file); 833// owarn << "goto dir "+file << oendl;
834 QString curDir = file; 834 QString curDir = file;
835 QDir *thisDir = CurrentDir(); 835 QDir *thisDir = CurrentDir();
836 if(QDir( curDir).exists() ) { 836 if(QDir( curDir).exists() ) {
837 thisDir->setPath( curDir ); 837 thisDir->setPath( curDir );
838 chdir( curDir.latin1() ); 838 chdir( curDir.latin1() );
839 thisDir->cd( curDir, TRUE); 839 thisDir->cd( curDir, TRUE);
840 populateView(); 840 populateView();
841 } 841 }
842 else if(QFileInfo(curDir).exists()) { 842 else if(QFileInfo(curDir).exists()) {
843 QFileInfo fileInfo(curDir); 843 QFileInfo fileInfo(curDir);
844 curDir=fileInfo.dirPath(); 844 curDir=fileInfo.dirPath();
845 if(QDir( curDir).exists() ) { 845 if(QDir( curDir).exists() ) {
846 thisDir->setPath( curDir ); 846 thisDir->setPath( curDir );
847 chdir( curDir.latin1() ); 847 chdir( curDir.latin1() );
848 thisDir->cd( curDir, TRUE); 848 thisDir->cd( curDir, TRUE);
849 populateView(); 849 populateView();
850 } 850 }
851 findFile(file); 851 findFile(file);
852 } 852 }
853 853
854} 854}
855 855
856void AdvancedFm::findFile(const QString &fileName) { 856void AdvancedFm::findFile(const QString &fileName) {
857 QFileInfo fi(fileName); 857 QFileInfo fi(fileName);
858 QListView *thisView = CurrentView(); 858 QListView *thisView = CurrentView();
859 QListViewItemIterator it( thisView ); 859 QListViewItemIterator it( thisView );
860 for ( ; it.current(); ++it ) { 860 for ( ; it.current(); ++it ) {
861 if(it.current()->text(0) == fi.fileName()) { 861 if(it.current()->text(0) == fi.fileName()) {
862 it.current()->setSelected(true); 862 it.current()->setSelected(true);
863 thisView->ensureItemVisible(it.current()); 863 thisView->ensureItemVisible(it.current());
864 } 864 }
865 } 865 }
866} 866}
867 867
868void AdvancedFm::slotSwitchMenu(int ) { 868void AdvancedFm::slotSwitchMenu(int ) {
869// qDebug("Switch %d", item); 869// odebug << "Switch " << item << "" << oendl;
870 // viewMenu->setItemChecked(item, true); 870 // viewMenu->setItemChecked(item, true);
871} 871}
872 872
873void AdvancedFm::dealWithSchmooSchmaa(QWidget *w) { 873void AdvancedFm::dealWithSchmooSchmaa(QWidget *w) {
874 tabChanged( w); 874 tabChanged( w);
875 if( w == Local_View) { 875 if( w == Local_View) {
876 Remote_View->clearFocus(); 876 Remote_View->clearFocus();
877 } else { 877 } else {
878 Local_View->clearFocus(); 878 Local_View->clearFocus();
879 } 879 }
880} 880}
881 881
882void AdvancedFm::navigateToSelected() { 882void AdvancedFm::navigateToSelected() {
883 if( !CurrentView()->currentItem()) return; 883 if( !CurrentView()->currentItem()) return;
884 doDirChange(); 884 doDirChange();
885} 885}
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 @@
1TEMPLATE = app 1TEMPLATE = app
2CONFIG += qt warn_on quick-app 2CONFIG += qt warn_on quick-app
3# CONFIG += qt warn_on
4HEADERS = advancedfm.h filePermissions.h output.h 3HEADERS = advancedfm.h filePermissions.h output.h
5SOURCES = advancedfm.cpp advancedfmData.cpp advancedfmMenu.cpp filePermissions.cpp output.cpp main.cpp 4SOURCES = advancedfm.cpp advancedfmData.cpp advancedfmMenu.cpp filePermissions.cpp output.cpp main.cpp
6TARGET = advancedfm 5TARGET = advancedfm
7INCLUDEPATH += $(OPIEDIR)/include 6INCLUDEPATH += $(OPIEDIR)/include
8DEPENDPATH += $(OPIEDIR)/include 7DEPENDPATH += $(OPIEDIR)/include
9LIBS += -lqpe -lopiecore2 -lopieui2 8LIBS += -lqpe -lopiecore2 -lopieui2
10
11TRANSLATIONS = ../../../i18n/de/advancedfm.ts \
12 ../../../i18n/nl/advancedfm.ts \
13 ../../../i18n/da/advancedfm.ts \
14 ../../../i18n/xx/advancedfm.ts \
15 ../../../i18n/en/advancedfm.ts \
16 ../../../i18n/es/advancedfm.ts \
17 ../../../i18n/fr/advancedfm.ts \
18 ../../../i18n/hu/advancedfm.ts \
19 ../../../i18n/ja/advancedfm.ts \
20 ../../../i18n/ko/advancedfm.ts \
21 ../../../i18n/no/advancedfm.ts \
22 ../../../i18n/pl/advancedfm.ts \
23 ../../../i18n/pt/advancedfm.ts \
24 ../../../i18n/pt_BR/advancedfm.ts \
25 ../../../i18n/sl/advancedfm.ts \
26 ../../../i18n/zh_CN/advancedfm.ts \
27 ../../../i18n/zh_TW/advancedfm.ts
28
29 9
30!contains(CONFIG,quick-app) { 10!contains(CONFIG,quick-app) {
31 DESTDIR = $(OPIEDIR)/bin 11 DESTDIR = $(OPIEDIR)/bin
32 DEFINES += NOQUICKLAUNCH 12 DEFINES += NOQUICKLAUNCH
33} 13}
34 14
35include ( $(OPIEDIR)/include.pro ) 15include ( $(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 @@
1/*************************************************************************** 1/***************************************************************************
2 advancedfmData.cpp 2 advancedfmData.cpp
3 ------------------- 3 -------------------
4** Created: Mon 09-23-2002 13:24:11 4** Created: Mon 09-23-2002 13:24:11
5 copyright : (C) 2002 by ljp 5 copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12#include "advancedfm.h" 12#include "advancedfm.h"
13 13
14/* OPIE */
15#include <opie2/odebug.h>
14#include <qpe/storage.h> 16#include <qpe/storage.h>
15#include <qpe/qpeapplication.h> 17#include <qpe/qpeapplication.h>
16#include <qpe/resource.h> 18#include <qpe/resource.h>
17#include <qpe/menubutton.h> 19#include <qpe/menubutton.h>
20using namespace Opie::Core;
21using namespace Opie::Ui;
18 22
23/* QT */
19#include <qlayout.h> 24#include <qlayout.h>
20#include <qhbox.h> 25#include <qhbox.h>
21#include <qmenubar.h> 26#include <qmenubar.h>
22#include <qcombobox.h> 27#include <qcombobox.h>
23#include <qtoolbutton.h> 28#include <qtoolbutton.h>
24#include <qlineedit.h> 29#include <qlineedit.h>
25#include <qlistview.h> 30#include <qlistview.h>
26 31
32/* STD */
27#include <sys/utsname.h> 33#include <sys/utsname.h>
28 34
29
30using namespace Opie::Ui;
31void AdvancedFm::init() { 35void AdvancedFm::init() {
32 b = false; 36 b = false;
33 setCaption( tr( "AdvancedFm" ) ); 37 setCaption( tr( "AdvancedFm" ) );
34 38
35 QVBoxLayout *layout = new QVBoxLayout( this ); 39 QVBoxLayout *layout = new QVBoxLayout( this );
36 layout->setSpacing( 2); 40 layout->setSpacing( 2);
37 layout->setMargin( 0); // squeeze 41 layout->setMargin( 0); // squeeze
38 42
39 QMenuBar *menuBar = new QMenuBar(this); 43 QMenuBar *menuBar = new QMenuBar(this);
40 menuBar->setMargin( 0 ); // squeeze 44 menuBar->setMargin( 0 ); // squeeze
41 fileMenu = new QPopupMenu( this ); 45 fileMenu = new QPopupMenu( this );
42 viewMenu = new QPopupMenu( this ); 46 viewMenu = new QPopupMenu( this );
43// customDirMenu = new QPopupMenu( this ); 47// customDirMenu = new QPopupMenu( this );
44 48
45 layout->addWidget( menuBar ); 49 layout->addWidget( menuBar );
46 50
47 menuBar->insertItem( tr( "File" ), fileMenu); 51 menuBar->insertItem( tr( "File" ), fileMenu);
48 menuBar->insertItem( tr( "View" ), viewMenu); 52 menuBar->insertItem( tr( "View" ), viewMenu);
49 53
50 cdUpButton = new QToolButton( 0,"cdUpButton"); 54 cdUpButton = new QToolButton( 0,"cdUpButton");
51 cdUpButton->setPixmap(Resource::loadPixmap("up")); 55 cdUpButton->setPixmap(Resource::loadPixmap("up"));
52 cdUpButton->setAutoRaise( true ); 56 cdUpButton->setAutoRaise( true );
53 menuBar->insertItem( cdUpButton ); 57 menuBar->insertItem( cdUpButton );
54 58
55 59
56 60
57 qpeDirButton= new QToolButton( 0,"QPEButton"); 61 qpeDirButton= new QToolButton( 0,"QPEButton");
58 qpeDirButton->setPixmap( Resource::loadPixmap("launcher/opielogo16x16"));//,"",this,"QPEButton"); 62 qpeDirButton->setPixmap( Resource::loadPixmap("launcher/opielogo16x16"));//,"",this,"QPEButton");
59 qpeDirButton->setAutoRaise( true ); 63 qpeDirButton->setAutoRaise( true );
60 menuBar->insertItem( qpeDirButton ); 64 menuBar->insertItem( qpeDirButton );
61 65
62 cfButton = new QToolButton( 0, "CFButton"); 66 cfButton = new QToolButton( 0, "CFButton");
63 cfButton->setPixmap(Resource::loadPixmap("cardmon/pcmcia")); 67 cfButton->setPixmap(Resource::loadPixmap("cardmon/pcmcia"));
64 cfButton->setAutoRaise( true ); 68 cfButton->setAutoRaise( true );
65 menuBar->insertItem( cfButton ); 69 menuBar->insertItem( cfButton );
66 70
67 sdButton = new QToolButton( 0, "SDButton"); 71 sdButton = new QToolButton( 0, "SDButton");
68 sdButton->setPixmap(Resource::loadPixmap("advancedfm/sdcard")); 72 sdButton->setPixmap(Resource::loadPixmap("advancedfm/sdcard"));
69 sdButton->setAutoRaise( true ); 73 sdButton->setAutoRaise( true );
70 menuBar->insertItem( sdButton ); 74 menuBar->insertItem( sdButton );
71 75
72 docButton = new QToolButton( 0,"docsButton"); 76 docButton = new QToolButton( 0,"docsButton");
73 docButton->setPixmap(Resource::loadPixmap("DocsIcon")); 77 docButton->setPixmap(Resource::loadPixmap("DocsIcon"));
74 docButton->setAutoRaise( true ); 78 docButton->setAutoRaise( true );
75 menuBar->insertItem( docButton ); 79 menuBar->insertItem( docButton );
76 80
77 homeButton = new QToolButton( 0, "homeButton"); 81 homeButton = new QToolButton( 0, "homeButton");
78 homeButton->setPixmap(Resource::loadPixmap("home")); 82 homeButton->setPixmap(Resource::loadPixmap("home"));
79 homeButton->setAutoRaise( true ); 83 homeButton->setAutoRaise( true );
80 menuBar->insertItem( homeButton ); 84 menuBar->insertItem( homeButton );
81 85
82 fileMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showMenuHidden() )); 86 fileMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showMenuHidden() ));
83 fileMenu->setItemChecked( fileMenu->idAt(0),TRUE); 87 fileMenu->setItemChecked( fileMenu->idAt(0),TRUE);
84 fileMenu->insertSeparator(); 88 fileMenu->insertSeparator();
85 fileMenu->insertItem( tr( "File Search" ), this, SLOT( openSearch() )); 89 fileMenu->insertItem( tr( "File Search" ), this, SLOT( openSearch() ));
86 fileMenu->insertSeparator(); 90 fileMenu->insertSeparator();
87 fileMenu->insertItem( tr( "Make Directory" ), this, SLOT( mkDir() )); 91 fileMenu->insertItem( tr( "Make Directory" ), this, SLOT( mkDir() ));
88 fileMenu->insertItem( tr( "Rename" ), this, SLOT( rn() )); 92 fileMenu->insertItem( tr( "Rename" ), this, SLOT( rn() ));
89 fileMenu->insertItem( tr( "Run Command" ), this, SLOT( runCommandStd() )); 93 fileMenu->insertItem( tr( "Run Command" ), this, SLOT( runCommandStd() ));
90 fileMenu->insertItem( tr( "Run Command with Output" ), this, SLOT( runCommand() )); 94 fileMenu->insertItem( tr( "Run Command with Output" ), this, SLOT( runCommand() ));
91 fileMenu->insertSeparator(); 95 fileMenu->insertSeparator();
92 fileMenu->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() )); 96 fileMenu->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() ));
93 fileMenu->insertItem( tr( "Select All" ), this, SLOT( selectAll() )); 97 fileMenu->insertItem( tr( "Select All" ), this, SLOT( selectAll() ));
94 fileMenu->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() )); 98 fileMenu->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() ));
95 fileMenu->insertItem( tr( "Delete" ), this, SLOT( del() )); 99 fileMenu->insertItem( tr( "Delete" ), this, SLOT( del() ));
96 fileMenu->setCheckable(TRUE); 100 fileMenu->setCheckable(TRUE);
97 101
98 viewMenu->insertItem( tr( "Switch to View 1" ), this, SLOT( switchToLocalTab())); 102 viewMenu->insertItem( tr( "Switch to View 1" ), this, SLOT( switchToLocalTab()));
99 viewMenu->insertItem( tr( "Switch to View 2" ), this, SLOT( switchToRemoteTab())); 103 viewMenu->insertItem( tr( "Switch to View 2" ), this, SLOT( switchToRemoteTab()));
100// viewMenu->insertSeparator(); 104// viewMenu->insertSeparator();
101// viewMenu->insertItem( tr( "About" ), this, SLOT( doAbout() )); 105// viewMenu->insertItem( tr( "About" ), this, SLOT( doAbout() ));
102 viewMenu->setCheckable(true); 106 viewMenu->setCheckable(true);
103 viewMenu->setItemChecked( viewMenu->idAt(0), true); 107 viewMenu->setItemChecked( viewMenu->idAt(0), true);
104 viewMenu->setItemChecked( viewMenu->idAt(1), false); 108 viewMenu->setItemChecked( viewMenu->idAt(1), false);
105 109
106 s_addBookmark = tr("Bookmark Directory"); 110 s_addBookmark = tr("Bookmark Directory");
107 s_removeBookmark = tr("Remove Current Directory from Bookmarks"); 111 s_removeBookmark = tr("Remove Current Directory from Bookmarks");
108 112
109// menuButton->insertItem(""); 113// menuButton->insertItem("");
110 114
111// customDirMenu->insertItem(tr("Add This Directory")); 115// customDirMenu->insertItem(tr("Add This Directory"));
112// customDirMenu->insertItem(tr("Remove This Directory")); 116// customDirMenu->insertItem(tr("Remove This Directory"));
113// customDirMenu->insertSeparator(); 117// customDirMenu->insertSeparator();
114 118
115 QHBoxLayout *CBHB = new QHBoxLayout(); // parent layout will be set later 119 QHBoxLayout *CBHB = new QHBoxLayout(); // parent layout will be set later
116 CBHB->setMargin( 0 ); 120 CBHB->setMargin( 0 );
117 CBHB->setSpacing( 1 ); 121 CBHB->setSpacing( 1 );
118 122
119 menuButton = new MenuButton( this ); 123 menuButton = new MenuButton( this );
120 124
121 menuButton->setUseLabel(false); 125 menuButton->setUseLabel(false);
122 menuButton->setMaximumWidth( 20 ); 126 menuButton->setMaximumWidth( 20 );
123 menuButton->insertItem( s_addBookmark); 127 menuButton->insertItem( s_addBookmark);
124 menuButton->insertItem( s_removeBookmark); 128 menuButton->insertItem( s_removeBookmark);
125 menuButton->insertSeparator(); 129 menuButton->insertSeparator();
126 menuButton->setFocusPolicy(NoFocus); 130 menuButton->setFocusPolicy(NoFocus);
127 CBHB->addWidget( menuButton ); 131 CBHB->addWidget( menuButton );
128 132
129 customDirsToMenu(); 133 customDirsToMenu();
130 134
131 currentPathCombo = new QComboBox( FALSE, this, "currentPathCombo" ); 135 currentPathCombo = new QComboBox( FALSE, this, "currentPathCombo" );
132 currentPathCombo->setEditable(TRUE); 136 currentPathCombo->setEditable(TRUE);
133 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath()); 137 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath());
134 currentPathCombo->setFocusPolicy(NoFocus); 138 currentPathCombo->setFocusPolicy(NoFocus);
135 CBHB->addWidget( currentPathCombo ); 139 CBHB->addWidget( currentPathCombo );
136 140
137 layout->addLayout( CBHB ); 141 layout->addLayout( CBHB );
138 142
139 TabWidget = new OSplitter( Horizontal, this, "TabWidget" ); 143 TabWidget = new OSplitter( Horizontal, this, "TabWidget" );
140// TabWidget = new QTabWidget( this, "TabWidget" ); 144// TabWidget = new QTabWidget( this, "TabWidget" );
141 layout->addWidget( TabWidget, 4 ); 145 layout->addWidget( TabWidget, 4 );
142 146
143 tab = new QWidget( TabWidget, "tab" ); 147 tab = new QWidget( TabWidget, "tab" );
144 tabLayout = new QGridLayout( tab ); 148 tabLayout = new QGridLayout( tab );
145 tabLayout->setSpacing( 2); 149 tabLayout->setSpacing( 2);
146 tabLayout->setMargin( 2); 150 tabLayout->setMargin( 2);
147 151
148 Local_View = new QListView( tab, "Local_View" ); 152 Local_View = new QListView( tab, "Local_View" );
149 Local_View->addColumn( tr("File"),130); 153 Local_View->addColumn( tr("File"),130);
150 Local_View->addColumn( tr("Size"),-1); 154 Local_View->addColumn( tr("Size"),-1);
151 Local_View->setColumnAlignment(1,QListView::AlignRight); 155 Local_View->setColumnAlignment(1,QListView::AlignRight);
152 Local_View->addColumn( tr("Date"),-1); 156 Local_View->addColumn( tr("Date"),-1);
153 Local_View->setColumnAlignment(2,QListView::AlignRight); 157 Local_View->setColumnAlignment(2,QListView::AlignRight);
154 Local_View->setAllColumnsShowFocus(TRUE); 158 Local_View->setAllColumnsShowFocus(TRUE);
155 Local_View->setMultiSelection( TRUE ); 159 Local_View->setMultiSelection( TRUE );
156 Local_View->setSelectionMode(QListView::Extended); 160 Local_View->setSelectionMode(QListView::Extended);
157 Local_View->setFocusPolicy(StrongFocus); 161 Local_View->setFocusPolicy(StrongFocus);
158 Local_View->installEventFilter( this ); 162 Local_View->installEventFilter( this );
159 163
160 QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold); 164 QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold);
161 165
162 tabLayout->addWidget( Local_View, 0, 0 ); 166 tabLayout->addWidget( Local_View, 0, 0 );
163 167
164 TabWidget->addWidget( tab,"advancedfm/smFileBrowser.png", tr("1")); 168 TabWidget->addWidget( tab,"advancedfm/smFileBrowser.png", tr("1"));
165// TabWidget->insertTab( tab, tr("1")); 169// TabWidget->insertTab( tab, tr("1"));
166 170
167 tab_2 = new QWidget( TabWidget, "tab_2" ); 171 tab_2 = new QWidget( TabWidget, "tab_2" );
168 tabLayout_2 = new QGridLayout( tab_2 ); 172 tabLayout_2 = new QGridLayout( tab_2 );
169 tabLayout_2->setSpacing( 2); 173 tabLayout_2->setSpacing( 2);
170 tabLayout_2->setMargin( 2); 174 tabLayout_2->setMargin( 2);
171 175
172 Remote_View = new QListView( tab_2, "Remote_View" ); 176 Remote_View = new QListView( tab_2, "Remote_View" );
173 Remote_View->addColumn( tr("File"),130); 177 Remote_View->addColumn( tr("File"),130);
174 Remote_View->addColumn( tr("Size"),-1); 178 Remote_View->addColumn( tr("Size"),-1);
175 Remote_View->setColumnAlignment(1,QListView::AlignRight); 179 Remote_View->setColumnAlignment(1,QListView::AlignRight);
176 Remote_View->addColumn( tr("Date"),-1); 180 Remote_View->addColumn( tr("Date"),-1);
177 Remote_View->setColumnAlignment(2,QListView::AlignRight); 181 Remote_View->setColumnAlignment(2,QListView::AlignRight);
178 Remote_View->setAllColumnsShowFocus(TRUE); 182 Remote_View->setAllColumnsShowFocus(TRUE);
179 Remote_View->setMultiSelection( TRUE ); 183 Remote_View->setMultiSelection( TRUE );
180 Remote_View->setSelectionMode(QListView::Extended); 184 Remote_View->setSelectionMode(QListView::Extended);
181 Remote_View->setFocusPolicy(StrongFocus); 185 Remote_View->setFocusPolicy(StrongFocus);
182 Remote_View->installEventFilter( this ); 186 Remote_View->installEventFilter( this );
183 187
184 QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold); 188 QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold);
185 189
186 tabLayout_2->addWidget( Remote_View, 0, 0 ); 190 tabLayout_2->addWidget( Remote_View, 0, 0 );
187 191
188 TabWidget->addWidget( tab_2, "advancedfm/smFileBrowser.png",tr( "2")); 192 TabWidget->addWidget( tab_2, "advancedfm/smFileBrowser.png",tr( "2"));
189 TabWidget->setSizeChange( 370 ); 193 TabWidget->setSizeChange( 370 );
190// TabWidget->insertTab( tab_2, tr( "2")); 194// TabWidget->insertTab( tab_2, tr( "2"));
191 195
192 /* tab_3 = new QWidget( TabWidget, "tab_3" ); 196 /* tab_3 = new QWidget( TabWidget, "tab_3" );
193 tabLayout_3 = new QGridLayout( tab_3 ); 197 tabLayout_3 = new QGridLayout( tab_3 );
194 tabLayout_3->setSpacing( 2); 198 tabLayout_3->setSpacing( 2);
195 tabLayout_3->setMargin( 2); 199 tabLayout_3->setMargin( 2);
196 200
197 201
198 // OFileDialog fileDialog; 202 // OFileDialog fileDialog;
199 // fileDialog; 203 // fileDialog;
200 // fileSelector = new FileSelector( "*",tab_3, "fileselector" , FALSE, FALSE); //buggy 204 // fileSelector = new FileSelector( "*",tab_3, "fileselector" , FALSE, FALSE); //buggy
201 // fileDialog = new OFileDialog("bangalow", tab_3, 4, 2, "Bungalow"); 205 // fileDialog = new OFileDialog("bangalow", tab_3, 4, 2, "Bungalow");
202 // OFileSelector fileDialog = new OFileSelector( tab_3, 4, 2,"/"); 206 // OFileSelector fileDialog = new OFileSelector( tab_3, 4, 2,"/");
203 207
204 QListView *fileTree; 208 QListView *fileTree;
205 fileTree = new QListView( tab_3, "tree" ); 209 fileTree = new QListView( tab_3, "tree" );
206 210
207 211
208 tabLayout_3->addMultiCellWidget( fileTree, 0, 0, 0, 3 ); 212 tabLayout_3->addMultiCellWidget( fileTree, 0, 0, 0, 3 );
209 213
210 TabWidget->insertTab( tab_3, tr( "Remote" ) ); 214 TabWidget->insertTab( tab_3, tr( "Remote" ) );
211 */ 215 */
212 216
213 /////////////// 217 ///////////////
214 218
215 if ( QFile::exists ( "/dev/sharp_buz" ) || QFile::exists ( "/dev/sharp_led" )) 219 if ( QFile::exists ( "/dev/sharp_buz" ) || QFile::exists ( "/dev/sharp_led" ))
216 zaurusDevice=TRUE; 220 zaurusDevice=TRUE;
217 else 221 else
218 zaurusDevice=FALSE; 222 zaurusDevice=FALSE;
219 223
220 224
221 if( !StorageInfo::hasSd() || !StorageInfo::hasMmc()) { 225 if( !StorageInfo::hasSd() || !StorageInfo::hasMmc()) {
222 qDebug("not have sd"); 226 odebug << "not have sd" << oendl;
223 sdButton->hide(); 227 sdButton->hide();
224 } 228 }
225 if( !StorageInfo::hasCf() ) { 229 if( !StorageInfo::hasCf() ) {
226 qDebug("not have cf"); 230 odebug << "not have cf" << oendl;
227 cfButton->hide(); 231 cfButton->hide();
228 } 232 }
229 currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 233 currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
230 currentDir.setPath( QDir::currentDirPath()); 234 currentDir.setPath( QDir::currentDirPath());
231 235
232 currentRemoteDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 236 currentRemoteDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
233 currentRemoteDir.setPath( QDir::currentDirPath()); 237 currentRemoteDir.setPath( QDir::currentDirPath());
234 238
235 // b = TRUE; 239 // b = TRUE;
236 240
237 filterStr="*"; 241 filterStr="*";
238 showMenuHidden(); 242 showMenuHidden();
239 TabWidget->setCurrentWidget(0); 243 TabWidget->setCurrentWidget(0);
240 244
241} 245}
242 246
243void AdvancedFm::initConnections() 247void AdvancedFm::initConnections()
244{ 248{
245 249
246 connect( qApp,SIGNAL( aboutToQuit()), 250 connect( qApp,SIGNAL( aboutToQuit()),
247 this, SLOT( cleanUp()) ); 251 this, SLOT( cleanUp()) );
248 connect( qpeDirButton ,SIGNAL(released()), 252 connect( qpeDirButton ,SIGNAL(released()),
249 this,SLOT( QPEButtonPushed()) ); 253 this,SLOT( QPEButtonPushed()) );
250 connect( cfButton ,SIGNAL(released()), 254 connect( cfButton ,SIGNAL(released()),
251 this,SLOT( CFButtonPushed()) ); 255 this,SLOT( CFButtonPushed()) );
252 connect( sdButton ,SIGNAL(released()), 256 connect( sdButton ,SIGNAL(released()),
253 this,SLOT( SDButtonPushed()) ); 257 this,SLOT( SDButtonPushed()) );
254 connect( cdUpButton ,SIGNAL(released()), 258 connect( cdUpButton ,SIGNAL(released()),
255 this,SLOT( upDir()) ); 259 this,SLOT( upDir()) );
256 connect( docButton,SIGNAL(released()), 260 connect( docButton,SIGNAL(released()),
257 this,SLOT( docButtonPushed()) ); 261 this,SLOT( docButtonPushed()) );
258 connect( homeButton,SIGNAL(released()), 262 connect( homeButton,SIGNAL(released()),
259 this,SLOT( homeButtonPushed()) ); 263 this,SLOT( homeButtonPushed()) );
260 connect( currentPathCombo, SIGNAL( activated(const QString&) ), 264 connect( currentPathCombo, SIGNAL( activated(const QString&) ),
261 this, SLOT( currentPathComboActivated(const QString&) ) ); 265 this, SLOT( currentPathComboActivated(const QString&) ) );
262 266
263 connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()), 267 connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()),
264 this,SLOT(currentPathComboChanged())); 268 this,SLOT(currentPathComboChanged()));
265 269
266 connect( Local_View, SIGNAL( clicked(QListViewItem*)), 270 connect( Local_View, SIGNAL( clicked(QListViewItem*)),
267 this,SLOT( ListClicked(QListViewItem*)) ); 271 this,SLOT( ListClicked(QListViewItem*)) );
268 272
269 connect( Local_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), 273 connect( Local_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
270 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) ); 274 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) );
271 275
272 connect( Local_View, SIGNAL( selectionChanged() ), SLOT( cancelMenuTimer() ) ); 276 connect( Local_View, SIGNAL( selectionChanged() ), SLOT( cancelMenuTimer() ) );
273 277
274 connect( Remote_View, SIGNAL( clicked(QListViewItem*)), 278 connect( Remote_View, SIGNAL( clicked(QListViewItem*)),
275 this,SLOT( ListClicked(QListViewItem*)) ); 279 this,SLOT( ListClicked(QListViewItem*)) );
276 connect( Remote_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), 280 connect( Remote_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
277 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) ); 281 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) );
278 282
279 connect( TabWidget,SIGNAL(currentChanged(QWidget*)), 283 connect( TabWidget,SIGNAL(currentChanged(QWidget*)),
280 this,SLOT(tabChanged(QWidget*))); 284 this,SLOT(tabChanged(QWidget*)));
281 285
282 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showFileMenu() ) ); 286 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showFileMenu() ) );
283 287
284 connect( menuButton, SIGNAL( selected(const QString&)), SLOT(gotoCustomDir(const QString&))); 288 connect( menuButton, SIGNAL( selected(const QString&)), SLOT(gotoCustomDir(const QString&)));
285// connect( menuButton, SIGNAL( selected(int)), SLOT( dirMenuSelected(int))); 289// connect( menuButton, SIGNAL( selected(int)), SLOT( dirMenuSelected(int)));
286 connect( viewMenu, SIGNAL( activated(int)), this, SLOT(slotSwitchMenu(int))); 290 connect( viewMenu, SIGNAL( activated(int)), this, SLOT(slotSwitchMenu(int)));
287// connect( customDirMenu, SIGNAL( activated(int)), this, SLOT( dirMenuSelected(int))); 291// connect( customDirMenu, SIGNAL( activated(int)), this, SLOT( dirMenuSelected(int)));
288 292
289} 293}
290 294
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 @@
1/*************************************************************************** 1/***************************************************************************
2 AdvancedFm.cpp 2 AdvancedFm.cpp
3 ------------------- 3 -------------------
4 ** Created: Sat Mar 9 23:33:09 2002 4 ** Created: Sat Mar 9 23:33:09 2002
5 copyright : (C) 2002 by ljp 5 copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12#include "advancedfm.h" 12
13#include "output.h" 13#include "advancedfm.h"
14#include "filePermissions.h" 14#include "output.h"
15 15#include "filePermissions.h"
16#include <qpe/lnkproperties.h> 16
17#include <qpe/qpeapplication.h> 17/* OPIE */
18#include <qpe/applnk.h> 18#include <opie2/odebug.h>
19 19#include <qpe/lnkproperties.h>
20#include <qmessagebox.h> 20#include <qpe/qpeapplication.h>
21 21#include <qpe/applnk.h>
22 22using namespace Opie::Core;
23#include <qpopupmenu.h> 23
24#include <qlistview.h> 24/* QT*/
25 25
26#include <errno.h> 26#include <qmessagebox.h>
27#include <stdlib.h> 27#include <qpopupmenu.h>
28#include <unistd.h> 28#include <qlistview.h>
29#include <sys/stat.h> 29
30#include <dirent.h> 30/* STD */
31#include <sys/sendfile.h> 31
32#include <fcntl.h> 32#include <errno.h>
33 33#include <stdlib.h>
34 34#include <unistd.h>
35using namespace Opie::Core; 35#include <sys/stat.h>
36using namespace Opie::Core; 36#include <dirent.h>
37void AdvancedFm::doDirChange() { 37#include <sys/sendfile.h>
38 QString pathItem = CurrentView()->currentItem()->text(0); 38#include <fcntl.h>
39 if( pathItem == "../") { 39
40 ListClicked( CurrentView()->currentItem()); 40void AdvancedFm::doDirChange() {
41 } else { 41 QString pathItem = CurrentView()->currentItem()->text(0);
42 if( pathItem.find(" -> ",0,TRUE) != -1) 42 if( pathItem == "../") {
43 pathItem = dealWithSymName((const QString&)pathItem)+"/"; 43 ListClicked( CurrentView()->currentItem());
44// qWarning(pathItem); 44 } else {
45 gotoDirectory( CurrentDir()->path()+"/"+pathItem.left( pathItem.length() - 1) ); 45 if( pathItem.find(" -> ",0,TRUE) != -1)
46 } 46 pathItem = dealWithSymName((const QString&)pathItem)+"/";
47} 47// owarn << pathItem << oendl;
48 48 gotoDirectory( CurrentDir()->path()+"/"+pathItem.left( pathItem.length() - 1) );
49void AdvancedFm::showMenuHidden() { 49 }
50 if (b) { 50}
51 CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 51
52 OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 52void AdvancedFm::showMenuHidden() {
53 fileMenu->setItemChecked( fileMenu->idAt(0),TRUE); 53 if (b) {
54 } else { 54 CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
55 CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 55 OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
56 OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 56 fileMenu->setItemChecked( fileMenu->idAt(0),TRUE);
57 fileMenu->setItemChecked( fileMenu->idAt(0),FALSE); 57 } else {
58 } 58 CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
59 b = !b; 59 OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
60 populateView(); 60 fileMenu->setItemChecked( fileMenu->idAt(0),FALSE);
61} 61 }
62 62 b = !b;
63void AdvancedFm::showHidden() { 63 populateView();
64 if (b) { 64}
65 CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 65
66 OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 66void AdvancedFm::showHidden() {
67 } else { 67 if (b) {
68 CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 68 CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
69 OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 69 OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
70 } 70 } else {
71 populateView(); 71 CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
72} 72 OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
73 73 }
74QString AdvancedFm::dealWithSymName(const QString &fileName) { 74 populateView();
75 QString strItem = fileName; 75}
76 return strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4); 76
77} 77QString AdvancedFm::dealWithSymName(const QString &fileName) {
78 78 QString strItem = fileName;
79void AdvancedFm::runThis() { 79 return strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4);
80 if( !CurrentView()->currentItem()) return; 80}
81 QString fs; 81
82 QDir *thisDir = CurrentDir(); 82void AdvancedFm::runThis() {
83 83 if( !CurrentView()->currentItem()) return;
84 QString curFile = CurrentView()->currentItem()->text(0); 84 QString fs;
85 QString path = thisDir->canonicalPath(); 85 QDir *thisDir = CurrentDir();
86 86
87 if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink 87 QString curFile = CurrentView()->currentItem()->text(0);
88 88 QString path = thisDir->canonicalPath();
89 curFile = dealWithSymName((const QString&)curFile); 89
90 90 if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink
91 if(curFile != "../") { 91
92 92 curFile = dealWithSymName((const QString&)curFile);
93 fs = getFileSystemType((const QString &) path); 93
94 QFileInfo fileInfo( path + "/" + curFile); 94 if(curFile != "../") {
95// qDebug( fileInfo.owner()); 95
96 96 fs = getFileSystemType((const QString &) path);
97 if( (fileInfo.permission( QFileInfo::ExeUser) 97 QFileInfo fileInfo( path + "/" + curFile);
98 | fileInfo.permission( QFileInfo::ExeGroup) 98// odebug << fileInfo.owner() << oendl;
99 | fileInfo.permission( QFileInfo::ExeOther)) // & fs.find("vfat",0,TRUE) == -1) { 99
100 | fs == "vfat" && fileInfo.filePath().contains("/bin") ) { 100 if( (fileInfo.permission( QFileInfo::ExeUser)
101 QCopEnvelope e("QPE/System", "execute(QString)" ); 101 | fileInfo.permission( QFileInfo::ExeGroup)
102 e << curFile; 102 | fileInfo.permission( QFileInfo::ExeOther)) // & fs.find("vfat",0,TRUE) == -1) {
103 } else { 103 | fs == "vfat" && fileInfo.filePath().contains("/bin") ) {
104 curFile = path + "/" + curFile; 104 QCopEnvelope e("QPE/System", "execute(QString)" );
105 DocLnk nf(curFile); 105 e << curFile;
106 QString execStr = nf.exec(); 106 } else {
107// qDebug( execStr); 107 curFile = path + "/" + curFile;
108 if( execStr.isEmpty() ) { 108 DocLnk nf(curFile);
109 } else { 109 QString execStr = nf.exec();
110 nf.execute(); 110// odebug << execStr << oendl;
111 } 111 if( execStr.isEmpty() ) {
112 } 112 } else {
113 } 113 nf.execute();
114} 114 }
115 115 }
116void AdvancedFm::runText() { 116 }
117 if( !CurrentView()->currentItem()) return; 117}
118 QString curFile = CurrentView()->currentItem()->text(0); 118
119 if(curFile != "../") { 119void AdvancedFm::runText() {
120 if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink 120 if( !CurrentView()->currentItem()) return;
121 curFile = dealWithSymName((const QString&)curFile); 121 QString curFile = CurrentView()->currentItem()->text(0);
122 curFile = CurrentDir()->canonicalPath()+"/"+curFile; 122 if(curFile != "../") {
123 QCopEnvelope e("QPE/Application/textedit", "setDocument(QString)" ); 123 if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink
124 e << curFile; 124 curFile = dealWithSymName((const QString&)curFile);
125 } 125 curFile = CurrentDir()->canonicalPath()+"/"+curFile;
126} 126 QCopEnvelope e("QPE/Application/textedit", "setDocument(QString)" );
127 127 e << curFile;
128void AdvancedFm::makeDir() { 128 }
129 InputDialog *fileDlg; 129}
130 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); 130
131 fileDlg->exec(); 131void AdvancedFm::makeDir() {
132 if( fileDlg->result() == 1 ) { 132 InputDialog *fileDlg;
133 QDir *thisDir = CurrentDir(); 133 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0);
134 QString filename = fileDlg->LineEdit1->text(); 134 fileDlg->exec();
135 thisDir->mkdir( thisDir->canonicalPath()+"/"+filename); 135 if( fileDlg->result() == 1 ) {
136 } 136 QDir *thisDir = CurrentDir();
137 populateView(); 137 QString filename = fileDlg->LineEdit1->text();
138} 138 thisDir->mkdir( thisDir->canonicalPath()+"/"+filename);
139 139 }
140void AdvancedFm::doDelete() { 140 populateView();
141 QStringList curFileList = getPath(); 141}
142 bool doMsg=true; 142
143 int count = curFileList.count(); 143void AdvancedFm::doDelete() {
144 if( count > 0) { 144 QStringList curFileList = getPath();
145 if(count > 1 ) { 145 bool doMsg=true;
146 QString msg; 146 int count = curFileList.count();
147 msg=tr("Really delete\n%1 files?").arg(count); 147 if( count > 0) {
148 switch ( QMessageBox::warning(this,tr("Delete"),msg 148 if(count > 1 ) {
149 ,tr("Yes"),tr("No"),0,0,1) ) 149 QString msg;
150 { 150 msg=tr("Really delete\n%1 files?").arg(count);
151 case 0: 151 switch ( QMessageBox::warning(this,tr("Delete"),msg
152 doMsg=false; 152 ,tr("Yes"),tr("No"),0,0,1) )
153 break; 153 {
154 case 1: 154 case 0:
155 return; 155 doMsg=false;
156 break; 156 break;
157 }; 157 case 1:
158 } 158 return;
159 159 break;
160 QString myFile; 160 };
161 161 }
162 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 162
163 myFile = (*it); 163 QString myFile;
164 if( myFile.find(" -> ",0,TRUE) != -1) 164
165 myFile = myFile.left( myFile.find(" -> ",0,TRUE)); 165 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
166 166 myFile = (*it);
167 QString f = CurrentDir()->canonicalPath(); 167 if( myFile.find(" -> ",0,TRUE) != -1)
168 if(f.right(1).find("/",0,TRUE) == -1) 168 myFile = myFile.left( myFile.find(" -> ",0,TRUE));
169 f += "/"; 169
170 f += myFile; 170 QString f = CurrentDir()->canonicalPath();
171 if(QDir(f).exists() && !QFileInfo(f).isSymLink() ) { 171 if(f.right(1).find("/",0,TRUE) == -1)
172 //if file is a directory 172 f += "/";
173 173 f += myFile;
174 switch ( QMessageBox::warning( this, tr("Delete Directory?"), 174 if(QDir(f).exists() && !QFileInfo(f).isSymLink() ) {
175 tr("Really delete %1\nand all it's contents ?" ).arg( f ) , 175 //if file is a directory
176 tr("Yes"), tr("No"), 0, 0, 1) ) { 176
177 case 0: 177 switch ( QMessageBox::warning( this, tr("Delete Directory?"),
178 { 178 tr("Really delete %1\nand all it's contents ?" ).arg( f ) ,
179 f=f.left(f.length()-1); 179 tr("Yes"), tr("No"), 0, 0, 1) ) {
180 QString cmd="rm -rf "+f; 180 case 0:
181 startProcess( (const QString)cmd.latin1() ); 181 {
182 populateView(); 182 f=f.left(f.length()-1);
183 } 183 QString cmd="rm -rf "+f;
184 break; 184 startProcess( (const QString)cmd.latin1() );
185 case 1: 185 populateView();
186 // exit 186 }
187 break; 187 break;
188 }; 188 case 1:
189 189 // exit
190 } else { 190 break;
191 if(doMsg) { 191 };
192 switch ( QMessageBox::warning(this,tr("Delete"), 192
193 tr("Really delete\n%1?").arg( myFile ), 193 } else {
194 tr("Yes"), tr("No"), 0, 0, 1) ) { 194 if(doMsg) {
195 case 1: 195 switch ( QMessageBox::warning(this,tr("Delete"),
196 return; 196 tr("Really delete\n%1?").arg( myFile ),
197 break; 197 tr("Yes"), tr("No"), 0, 0, 1) ) {
198 }; 198 case 1:
199 } 199 return;
200 200 break;
201 QString cmd="rm "+f; 201 };
202 QFile file(f); 202 }
203 QFileInfo fi(myFile); 203
204 if( fi.fileName().find("../",0,TRUE)==-1) { 204 QString cmd="rm "+f;
205// qDebug("remove link files "+myFile); 205 QFile file(f);
206 206 QFileInfo fi(myFile);
207// DocLnk lnk(f); 207 if( fi.fileName().find("../",0,TRUE)==-1) {
208 DocLnk *lnk; 208// odebug << "remove link files "+myFile << oendl;
209 lnk = new DocLnk(f); 209
210// qDebug("Deleting doclnk " + lnk->linkFile()); 210// DocLnk lnk(f);
211 if(lnk->isValid()) 211 DocLnk *lnk;
212 lnk->removeLinkFile(); 212 lnk = new DocLnk(f);
213 // delete lnk; 213// odebug << "Deleting doclnk " + lnk->linkFile() << oendl;
214 file.remove(); 214 if(lnk->isValid())
215 } 215 lnk->removeLinkFile();
216 } 216 // delete lnk;
217 } 217 file.remove();
218 } 218 }
219 populateView(); 219 }
220} 220 }
221 221 }
222void AdvancedFm::filePerms() { 222 populateView();
223 QStringList curFileList = getPath(); 223}
224 QString filePath; 224
225 225void AdvancedFm::filePerms() {
226 filePath = CurrentDir()->canonicalPath()+"/"; 226 QStringList curFileList = getPath();
227 227 QString filePath;
228 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 228
229 filePermissions *filePerm; 229 filePath = CurrentDir()->canonicalPath()+"/";
230 filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(filePath+*it)); 230
231 QPEApplication::execDialog( filePerm ); 231 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
232 if( filePerm ) 232 filePermissions *filePerm;
233 delete filePerm; 233 filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(filePath+*it));
234 } 234 QPEApplication::execDialog( filePerm );
235 populateView(); 235 if( filePerm )
236} 236 delete filePerm;
237 237 }
238void AdvancedFm::doProperties() { 238 populateView();
239#if defined(QT_QWS_OPIE) 239}
240 240
241 QStringList curFileList = getPath(); 241void AdvancedFm::doProperties() {
242 242#if defined(QT_QWS_OPIE)
243 QString filePath; 243
244 filePath = CurrentDir()->canonicalPath()+"/"; 244 QStringList curFileList = getPath();
245 245
246// qDebug("%d",curFileList.count()); 246 QString filePath;
247 247 filePath = CurrentDir()->canonicalPath()+"/";
248 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 248
249// qDebug((filePath+*it)); 249// odebug << "" << curFileList.count() << "" << oendl;
250 DocLnk lnk( (filePath+*it)); 250
251 LnkProperties prop( &lnk ); 251 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
252 QPEApplication::execDialog( &prop ); 252// odebug << (filePath+*it) << oendl;
253 } 253 DocLnk lnk( (filePath+*it));
254#endif 254 LnkProperties prop( &lnk );
255 255 QPEApplication::execDialog( &prop );
256} 256 }
257 257#endif
258void AdvancedFm::upDir() { 258
259 QDir *thisDir = CurrentDir(); 259}
260 QString current = thisDir->canonicalPath(); 260
261 QDir dir(current); 261void AdvancedFm::upDir() {
262 dir.cdUp(); 262 QDir *thisDir = CurrentDir();
263 current = dir.canonicalPath(); 263 QString current = thisDir->canonicalPath();
264 chdir( current.latin1() ); 264 QDir dir(current);
265 thisDir->cd( current, TRUE); 265 dir.cdUp();
266 266 current = dir.canonicalPath();
267 populateView(); 267 chdir( current.latin1() );
268 update(); 268 thisDir->cd( current, TRUE);
269} 269
270 270 populateView();
271void AdvancedFm::copy() { 271 update();
272 qApp->processEvents(); 272}
273 QStringList curFileList = getPath(); 273
274 274void AdvancedFm::copy() {
275 QDir *thisDir = CurrentDir(); 275 qApp->processEvents();
276 QDir *thatDir = OtherDir(); 276 QStringList curFileList = getPath();
277 277
278 bool doMsg=true; 278 QDir *thisDir = CurrentDir();
279 int count=curFileList.count(); 279 QDir *thatDir = OtherDir();
280 if( count > 0) { 280
281 if(count > 1 ){ 281 bool doMsg=true;
282 QString msg; 282 int count=curFileList.count();
283 msg=tr("Really copy\n%1 files?").arg(count); 283 if( count > 0) {
284 switch ( QMessageBox::warning(this,tr("Copy"),msg 284 if(count > 1 ){
285 ,tr("Yes"),tr("No"),0,0,1) ) 285 QString msg;
286 { 286 msg=tr("Really copy\n%1 files?").arg(count);
287 case 0: 287 switch ( QMessageBox::warning(this,tr("Copy"),msg
288 doMsg=false; 288 ,tr("Yes"),tr("No"),0,0,1) )
289 break; 289 {
290 case 1: 290 case 0:
291 return; 291 doMsg=false;
292 break; 292 break;
293 }; 293 case 1:
294 } 294 return;
295 295 break;
296 QString curFile, item, destFile; 296 };
297 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 297 }
298 item=(*it); 298
299 if(item.find("->",0,TRUE)) //symlink 299 QString curFile, item, destFile;
300 item = item.left(item.find("->",0,TRUE)); 300 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
301 301 item=(*it);
302 curFile = thisDir->canonicalPath()+"/"+ item; 302 if(item.find("->",0,TRUE)) //symlink
303 destFile = thatDir->canonicalPath()+"/"+ item; 303 item = item.left(item.find("->",0,TRUE));
304 304
305// qDebug("Destination file is "+destFile); 305 curFile = thisDir->canonicalPath()+"/"+ item;
306// qDebug("CurrentFile file is " + curFile); 306 destFile = thatDir->canonicalPath()+"/"+ item;
307 307
308 QFile f(destFile); 308// odebug << "Destination file is "+destFile << oendl;
309 if( f.exists()) { 309// odebug << "CurrentFile file is " + curFile << oendl;
310 if(doMsg) { 310
311 switch ( QMessageBox::warning(this,tr("File Exists!"), 311 QFile f(destFile);
312 tr("%1 exists. Ok to overwrite?").arg( item ), 312 if( f.exists()) {
313 tr("Yes"),tr("No"),0,0,1) ) { 313 if(doMsg) {
314 case 1: 314 switch ( QMessageBox::warning(this,tr("File Exists!"),
315 return; 315 tr("%1 exists. Ok to overwrite?").arg( item ),
316 break; 316 tr("Yes"),tr("No"),0,0,1) ) {
317 }; 317 case 1:
318 } 318 return;
319 f.remove(); 319 break;
320 } 320 };
321 321 }
322 if( !copyFile( curFile, destFile) ) { 322 f.remove();
323 QMessageBox::message("AdvancedFm", 323 }
324 tr( "Could not copy %1 to %2").arg( curFile ).arg( destFile ) ); 324
325 return; 325 if( !copyFile( curFile, destFile) ) {
326 } 326 QMessageBox::message("AdvancedFm",
327 } 327 tr( "Could not copy %1 to %2").arg( curFile ).arg( destFile ) );
328 setOtherTabCurrent(); 328 return;
329 rePopulate(); 329 }
330 } 330 }
331} 331 setOtherTabCurrent();
332 332 rePopulate();
333void AdvancedFm::copyAs() { 333 }
334 qApp->processEvents(); 334}
335 335
336 QStringList curFileList = getPath(); 336void AdvancedFm::copyAs() {
337 QString curFile, item; 337 qApp->processEvents();
338 InputDialog *fileDlg; 338
339 339 QStringList curFileList = getPath();
340 QDir *thisDir = CurrentDir(); 340 QString curFile, item;
341 QDir *thatDir = OtherDir(); 341 InputDialog *fileDlg;
342 342
343 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 343 QDir *thisDir = CurrentDir();
344 QString destFile; 344 QDir *thatDir = OtherDir();
345 item=(*it); 345
346 curFile = thisDir->canonicalPath()+"/"+(*it); 346 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
347 fileDlg = new InputDialog( this, tr("Copy "+curFile+" As"), TRUE, 0); 347 QString destFile;
348 348 item=(*it);
349 fileDlg->setInputText((const QString &) destFile ); 349 curFile = thisDir->canonicalPath()+"/"+(*it);
350 fileDlg->exec(); 350 fileDlg = new InputDialog( this, tr("Copy "+curFile+" As"), TRUE, 0);
351 351
352 if( fileDlg->result() == 1 ) { 352 fileDlg->setInputText((const QString &) destFile );
353 QString filename = fileDlg->LineEdit1->text(); 353 fileDlg->exec();
354 destFile = thatDir->canonicalPath()+"/"+filename; 354
355 355 if( fileDlg->result() == 1 ) {
356 QFile f( destFile); 356 QString filename = fileDlg->LineEdit1->text();
357 if( f.exists()) { 357 destFile = thatDir->canonicalPath()+"/"+filename;
358 switch (QMessageBox::warning(this,tr("File Exists!"), 358
359 item+tr("\nexists. Ok to overwrite?"), 359 QFile f( destFile);
360 tr("Yes"),tr("No"),0,0,1) ) { 360 if( f.exists()) {
361 case 0: 361 switch (QMessageBox::warning(this,tr("File Exists!"),
362 f.remove(); 362 item+tr("\nexists. Ok to overwrite?"),
363 break; 363 tr("Yes"),tr("No"),0,0,1) ) {
364 case 1: 364 case 0:
365 return; 365 f.remove();
366 break; 366 break;
367 }; 367 case 1:
368 } 368 return;
369 if( !copyFile( curFile, destFile) ) { 369 break;
370 QMessageBox::message("AdvancedFm",tr("Could not copy\n") 370 };
371 +curFile +tr("to\n")+destFile); 371 }
372 return; 372 if( !copyFile( curFile, destFile) ) {
373 } 373 QMessageBox::message("AdvancedFm",tr("Could not copy\n")
374 } 374 +curFile +tr("to\n")+destFile);
375 delete fileDlg; 375 return;
376 376 }
377 } 377 }
378 rePopulate(); 378 delete fileDlg;
379 setOtherTabCurrent(); 379
380} 380 }
381 381 rePopulate();
382void AdvancedFm::copySameDir() { 382 setOtherTabCurrent();
383 qApp->processEvents(); 383}
384 QStringList curFileList = getPath(); 384
385 QString curFile, item, destFile; 385void AdvancedFm::copySameDir() {
386 InputDialog *fileDlg; 386 qApp->processEvents();
387 387 QStringList curFileList = getPath();
388 QDir *thisDir = CurrentDir(); 388 QString curFile, item, destFile;
389 389 InputDialog *fileDlg;
390 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 390
391 item=(*it); 391 QDir *thisDir = CurrentDir();
392 curFile = thisDir->canonicalPath()+"/"+ item; 392
393 393 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
394 fileDlg = new InputDialog(this,tr("Copy ")+curFile+tr(" As"),TRUE, 0); 394 item=(*it);
395 fileDlg->setInputText((const QString &) destFile ); 395 curFile = thisDir->canonicalPath()+"/"+ item;
396 fileDlg->exec(); 396
397 397 fileDlg = new InputDialog(this,tr("Copy ")+curFile+tr(" As"),TRUE, 0);
398 if( fileDlg->result() == 1 ) { 398 fileDlg->setInputText((const QString &) destFile );
399 399 fileDlg->exec();
400 QString filename = fileDlg->LineEdit1->text(); 400
401 destFile = thisDir->canonicalPath()+"/"+filename; 401 if( fileDlg->result() == 1 ) {
402 402
403 QFile f(destFile); 403 QString filename = fileDlg->LineEdit1->text();
404 if( f.exists()) { 404 destFile = thisDir->canonicalPath()+"/"+filename;
405 switch (QMessageBox::warning(this,tr("Delete"), 405
406 destFile+tr(" already exists.\nDo you really want to delete it?"), 406 QFile f(destFile);
407 tr("Yes"),tr("No"),0,0,1) ) { 407 if( f.exists()) {
408 case 0: 408 switch (QMessageBox::warning(this,tr("Delete"),
409 409 destFile+tr(" already exists.\nDo you really want to delete it?"),
410 f.remove(); 410 tr("Yes"),tr("No"),0,0,1) ) {
411 break; 411 case 0:
412 case 1: 412
413 return; 413 f.remove();
414 break; 414 break;
415 }; 415 case 1:
416 } 416 return;
417 if(!copyFile( curFile,destFile) ) { 417 break;
418 QMessageBox::message("AdvancedFm",tr("Could not copy\n") 418 };
419 +curFile +tr("to\n")+destFile); 419 }
420 return; 420 if(!copyFile( curFile,destFile) ) {
421 } 421 QMessageBox::message("AdvancedFm",tr("Could not copy\n")
422 422 +curFile +tr("to\n")+destFile);
423// qDebug("copy "+curFile+" as "+destFile); 423 return;
424 } 424 }
425 delete fileDlg; 425
426 } 426// odebug << "copy "+curFile+" as "+destFile << oendl;
427 rePopulate(); 427 }
428} 428 delete fileDlg;
429 429 }
430void AdvancedFm::move() { 430 rePopulate();
431 qApp->processEvents(); 431}
432 432
433 QStringList curFileList = getPath(); 433void AdvancedFm::move() {
434 if( curFileList.count() > 0) { 434 qApp->processEvents();
435 QString curFile, destFile, item; 435
436 436 QStringList curFileList = getPath();
437 QDir *thisDir = CurrentDir(); 437 if( curFileList.count() > 0) {
438 QDir *thatDir = OtherDir(); 438 QString curFile, destFile, item;
439 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 439
440 item=(*it); 440 QDir *thisDir = CurrentDir();
441 QString destFile = thatDir->canonicalPath(); 441 QDir *thatDir = OtherDir();
442 442 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
443 if(destFile.right(1).find("/",0,TRUE) == -1) 443 item=(*it);
444 destFile+="/"; 444 QString destFile = thatDir->canonicalPath();
445 destFile += item; 445
446// qDebug("Destination file is "+destFile); 446 if(destFile.right(1).find("/",0,TRUE) == -1)
447 447 destFile+="/";
448 curFile = thisDir->canonicalPath(); 448 destFile += item;
449 if(curFile.right(1).find("/",0,TRUE) == -1) 449// odebug << "Destination file is "+destFile << oendl;
450 curFile +="/"; 450
451 curFile+= item; 451 curFile = thisDir->canonicalPath();
452// qDebug("CurrentFile file is " + curFile); 452 if(curFile.right(1).find("/",0,TRUE) == -1)
453 453 curFile +="/";
454 if(QFileInfo(curFile).isDir()) { 454 curFile+= item;
455 moveDirectory( curFile, destFile ); 455// odebug << "CurrentFile file is " + curFile << oendl;
456 rePopulate(); 456
457 return; 457 if(QFileInfo(curFile).isDir()) {
458 } 458 moveDirectory( curFile, destFile );
459 459 rePopulate();
460 QFile f( curFile); 460 return;
461 if( f.exists()) { 461 }
462 if( !copyFile( curFile, destFile) ) { 462
463 QMessageBox::message(tr("Note"),tr("Could not move\n")+curFile); 463 QFile f( curFile);
464 return; 464 if( f.exists()) {
465 } else 465 if( !copyFile( curFile, destFile) ) {
466 QFile::remove(curFile); 466 QMessageBox::message(tr("Note"),tr("Could not move\n")+curFile);
467 } 467 return;
468 } 468 } else
469 469 QFile::remove(curFile);
470 } 470 }
471 rePopulate(); 471 }
472 setOtherTabCurrent(); 472
473} 473 }
474 474 rePopulate();
475bool AdvancedFm::moveDirectory( const QString & src, const QString & dest ) { 475 setOtherTabCurrent();
476 int err = 0; 476}
477 if( copyDirectory( src, dest ) ) { QString cmd = "rm -rf " + src; 477
478 err = system((const char*)cmd); 478bool AdvancedFm::moveDirectory( const QString & src, const QString & dest ) {
479 } else 479 int err = 0;
480 err = -1; 480 if( copyDirectory( src, dest ) ) { QString cmd = "rm -rf " + src;
481 481 err = system((const char*)cmd);
482 if(err!=0) { 482 } else
483 QMessageBox::message(tr("Note"),tr("Could not move\n") + src); 483 err = -1;
484 return false; 484
485 } 485 if(err!=0) {
486 return true; 486 QMessageBox::message(tr("Note"),tr("Could not move\n") + src);
487} 487 return false;
488 488 }
489bool AdvancedFm::copyDirectory( const QString & src, const QString & dest ) { 489 return true;
490 490}
491 QString cmd = "/bin/cp -fpR " + src + " " + dest; 491
492 qWarning(cmd); 492bool AdvancedFm::copyDirectory( const QString & src, const QString & dest ) {
493 int err = system( (const char *) cmd ); 493
494 if ( err != 0 ) { 494 QString cmd = "/bin/cp -fpR " + src + " " + dest;
495 QMessageBox::message("AdvancedFm", 495 owarn << cmd << oendl;
496 tr( "Could not copy \n%1 \nto \n%2").arg( src ).arg( dest ) ); 496 int err = system( (const char *) cmd );
497 return false; 497 if ( err != 0 ) {
498 } 498 QMessageBox::message("AdvancedFm",
499 499 tr( "Could not copy \n%1 \nto \n%2").arg( src ).arg( dest ) );
500 return true; 500 return false;
501} 501 }
502 502
503 503 return true;
504bool AdvancedFm::copyFile( const QString & src, const QString & dest ) { 504}
505 505
506 506
507 if(QFileInfo(src).isDir()) { 507bool AdvancedFm::copyFile( const QString & src, const QString & dest ) {
508 if( copyDirectory( src, dest )) { 508
509 setOtherTabCurrent(); 509
510 populateView(); 510 if(QFileInfo(src).isDir()) {
511 return true; 511 if( copyDirectory( src, dest )) {
512 } 512 setOtherTabCurrent();
513 else 513 populateView();
514 return false; 514 return true;
515 } 515 }
516 516 else
517 517 return false;
518 bool success = true; 518 }
519 struct stat status; 519
520 QFile srcFile(src); 520
521 QFile destFile(dest); 521 bool success = true;
522 int err=0; 522 struct stat status;
523 int read_fd=0; 523 QFile srcFile(src);
524 int write_fd=0; 524 QFile destFile(dest);
525 struct stat stat_buf; 525 int err=0;
526 off_t offset = 0; 526 int read_fd=0;
527 if(!srcFile.open( IO_ReadOnly|IO_Raw)) { 527 int write_fd=0;
528// qWarning("open failed"); 528 struct stat stat_buf;
529 return success = false; 529 off_t offset = 0;
530 } 530 if(!srcFile.open( IO_ReadOnly|IO_Raw)) {
531 read_fd = srcFile.handle(); 531// owarn << "open failed" << oendl;
532 if(read_fd != -1) { 532 return success = false;
533 fstat (read_fd, &stat_buf); 533 }
534 if( !destFile.open( IO_WriteOnly|IO_Raw ) ) { 534 read_fd = srcFile.handle();
535// qWarning("destfile open failed"); 535 if(read_fd != -1) {
536 return success = false; 536 fstat (read_fd, &stat_buf);
537 } 537 if( !destFile.open( IO_WriteOnly|IO_Raw ) ) {
538 write_fd = destFile.handle(); 538// owarn << "destfile open failed" << oendl;
539 if(write_fd != -1) { 539 return success = false;
540 err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size); 540 }
541 if( err == -1) { 541 write_fd = destFile.handle();
542 QString msg; 542 if(write_fd != -1) {
543 switch(err) { 543 err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size);
544 case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. "; 544 if( err == -1) {
545 case EINVAL: msg = "Descriptor is not valid or locked. "; 545 QString msg;
546 case ENOMEM: msg = "Insufficient memory to read from in_fd."; 546 switch(err) {
547 case EIO: msg = "Unspecified error while reading from in_fd."; 547 case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. ";
548 }; 548 case EINVAL: msg = "Descriptor is not valid or locked. ";
549 success = false; 549 case ENOMEM: msg = "Insufficient memory to read from in_fd.";
550// qWarning(msg); 550 case EIO: msg = "Unspecified error while reading from in_fd.";
551 } 551 };
552 } else { 552 success = false;
553 success = false; 553// owarn << msg << oendl;
554 } 554 }
555 } else { 555 } else {
556 success = false; 556 success = false;
557 } 557 }
558 srcFile.close(); 558 } else {
559 destFile.close(); 559 success = false;
560 // Set file permissions 560 }
561 if( stat( (const char *) src, &status ) == 0 ) { 561 srcFile.close();
562 chmod( (const char *) dest, status.st_mode ); 562 destFile.close();
563 } 563 // Set file permissions
564 564 if( stat( (const char *) src, &status ) == 0 ) {
565 return success; 565 chmod( (const char *) dest, status.st_mode );
566} 566 }
567 567
568void AdvancedFm::runCommand() { 568 return success;
569 if( !CurrentView()->currentItem()) return; 569}
570 QDir *thisDir = CurrentDir(); 570
571 571void AdvancedFm::runCommand() {
572 QString curFile; 572 if( !CurrentView()->currentItem()) return;
573 curFile = thisDir->canonicalPath() +"/"+ CurrentView()->currentItem()->text(0); 573 QDir *thisDir = CurrentDir();
574 574
575 InputDialog *fileDlg; 575 QString curFile;
576 fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0); 576 curFile = thisDir->canonicalPath() +"/"+ CurrentView()->currentItem()->text(0);
577 fileDlg->setInputText(curFile); 577
578 fileDlg->exec(); 578 InputDialog *fileDlg;
579 //QString command; 579 fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0);
580 580 fileDlg->setInputText(curFile);
581 if( fileDlg->result() == 1 ) { 581 fileDlg->exec();
582// qDebug(fileDlg->LineEdit1->text()); 582 //QString command;
583 QStringList command; 583
584 584 if( fileDlg->result() == 1 ) {
585 command << "/bin/sh"; 585// odebug << fileDlg->LineEdit1->text() << oendl;
586 command << "-c"; 586 QStringList command;
587 command << fileDlg->LineEdit1->text(); 587
588 Output *outDlg; 588 command << "/bin/sh";
589 outDlg = new Output( command, this, tr("AdvancedFm Output"), true); 589 command << "-c";
590 QPEApplication::execDialog( outDlg ); 590 command << fileDlg->LineEdit1->text();
591 qApp->processEvents(); 591 Output *outDlg;
592 592 outDlg = new Output( command, this, tr("AdvancedFm Output"), true);
593 } 593 QPEApplication::execDialog( outDlg );
594} 594 qApp->processEvents();
595 595
596void AdvancedFm::runCommandStd() { 596 }
597 if( !CurrentView()->currentItem()) return; 597}
598 QString curFile; 598
599 QDir *thisDir = CurrentDir(); 599void AdvancedFm::runCommandStd() {
600 QListView *thisView = CurrentView(); 600 if( !CurrentView()->currentItem()) return;
601 if( thisView->currentItem()) 601 QString curFile;
602 curFile = thisDir->canonicalPath() +"/"+ thisView->currentItem()->text(0); 602 QDir *thisDir = CurrentDir();
603 603 QListView *thisView = CurrentView();
604 InputDialog *fileDlg; 604 if( thisView->currentItem())
605 fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0); 605 curFile = thisDir->canonicalPath() +"/"+ thisView->currentItem()->text(0);
606 fileDlg->setInputText(curFile); 606
607 fileDlg->exec(); 607 InputDialog *fileDlg;
608 608 fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0);
609 if( fileDlg->result() == 1 ) { 609 fileDlg->setInputText(curFile);
610 qApp->processEvents(); 610 fileDlg->exec();
611 startProcess( (const QString)fileDlg->LineEdit1->text().latin1()); 611
612 } 612 if( fileDlg->result() == 1 ) {
613} 613 qApp->processEvents();
614 614 startProcess( (const QString)fileDlg->LineEdit1->text().latin1());
615void AdvancedFm::fileStatus() { 615 }
616 if( !CurrentView()->currentItem()) return; 616}
617 QString curFile; 617
618 curFile = CurrentView()->currentItem()->text(0); 618void AdvancedFm::fileStatus() {
619 619 if( !CurrentView()->currentItem()) return;
620 QStringList command; 620 QString curFile;
621 command << "/bin/sh"; 621 curFile = CurrentView()->currentItem()->text(0);
622 command << "-c"; 622
623 command << "stat -l "+ curFile; 623 QStringList command;
624 624 command << "/bin/sh";
625 Output *outDlg; 625 command << "-c";
626 outDlg = new Output( command, this, tr("AdvancedFm Output"), true); 626 command << "stat -l "+ curFile;
627 QPEApplication::execDialog( outDlg ); 627
628 qApp->processEvents(); 628 Output *outDlg;
629} 629 outDlg = new Output( command, this, tr("AdvancedFm Output"), true);
630 630 QPEApplication::execDialog( outDlg );
631 631 qApp->processEvents();
632void AdvancedFm::mkDir() { 632}
633 makeDir(); 633
634} 634
635 635void AdvancedFm::mkDir() {
636void AdvancedFm::rn() { 636 makeDir();
637 renameIt(); 637}
638} 638
639 639void AdvancedFm::rn() {
640void AdvancedFm::del() { 640 renameIt();
641 doDelete(); 641}
642} 642
643 643void AdvancedFm::del() {
644void AdvancedFm::mkSym() { 644 doDelete();
645 QString cmd; 645}
646 QStringList curFileList = getPath(); 646
647 if( curFileList.count() > 0) { 647void AdvancedFm::mkSym() {
648 QDir *thisDir = CurrentDir(); 648 QString cmd;
649 QDir * thatDir = OtherDir(); 649 QStringList curFileList = getPath();
650 650 if( curFileList.count() > 0) {
651 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 651 QDir *thisDir = CurrentDir();
652 652 QDir * thatDir = OtherDir();
653 QString destName = thatDir->canonicalPath()+"/"+(*it); 653
654 if(destName.right(1) == "/") { 654 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
655 destName = destName.left( destName.length() -1); 655
656 } 656 QString destName = thatDir->canonicalPath()+"/"+(*it);
657 657 if(destName.right(1) == "/") {
658 QString curFile = thisDir->canonicalPath()+"/"+(*it); 658 destName = destName.left( destName.length() -1);
659 659 }
660 if( curFile.right(1) == "/") { 660
661 curFile = curFile.left( curFile.length() -1); 661 QString curFile = thisDir->canonicalPath()+"/"+(*it);
662 } 662
663 663 if( curFile.right(1) == "/") {
664 cmd = "ln -s "+curFile+" "+destName; 664 curFile = curFile.left( curFile.length() -1);
665// qDebug(cmd); 665 }
666 startProcess( (const QString)cmd ); 666
667 } 667 cmd = "ln -s "+curFile+" "+destName;
668 rePopulate(); 668// odebug << cmd << oendl;
669 setOtherTabCurrent(); 669 startProcess( (const QString)cmd );
670 } 670 }
671} 671 rePopulate();
672 672 setOtherTabCurrent();
673void AdvancedFm::doBeam() { 673 }
674 Ir ir; 674}
675 if(!ir.supported()) { 675
676 } else { 676void AdvancedFm::doBeam() {
677 QStringList curFileList = getPath(); 677 Ir ir;
678 if( curFileList.count() > 0) { 678 if(!ir.supported()) {
679 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 679 } else {
680 QString curFile = (*it); 680 QStringList curFileList = getPath();
681 QString curFilePath = CurrentDir()->canonicalPath()+"/"+curFile; 681 if( curFileList.count() > 0) {
682 if( curFilePath.right(1) == "/") { 682 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
683 curFilePath = curFilePath.left( curFilePath.length() -1); 683 QString curFile = (*it);
684 } 684 QString curFilePath = CurrentDir()->canonicalPath()+"/"+curFile;
685 Ir *file = new Ir(this, "IR"); 685 if( curFilePath.right(1) == "/") {
686 connect(file, SIGNAL(done(Ir*)), this, SLOT( fileBeamFinished(Ir*))); 686 curFilePath = curFilePath.left( curFilePath.length() -1);
687 file->send( curFilePath, curFile ); 687 }
688 } 688 Ir *file = new Ir(this, "IR");
689 } 689 connect(file, SIGNAL(done(Ir*)), this, SLOT( fileBeamFinished(Ir*)));
690 } 690 file->send( curFilePath, curFile );
691} 691 }
692 692 }
693void AdvancedFm::fileBeamFinished( Ir *) { 693 }
694 QMessageBox::message( tr("Advancedfm Beam out"), tr("Ir sent.") ,tr("Ok") ); 694}
695} 695
696 696void AdvancedFm::fileBeamFinished( Ir *) {
697void AdvancedFm::selectAll() { 697 QMessageBox::message( tr("Advancedfm Beam out"), tr("Ir sent.") ,tr("Ok") );
698 QListView *thisView = CurrentView(); 698}
699 thisView->selectAll(true); 699
700 thisView->setSelected( thisView->firstChild(),false); 700void AdvancedFm::selectAll() {
701} 701 QListView *thisView = CurrentView();
702 702 thisView->selectAll(true);
703void AdvancedFm::startProcess(const QString & cmd) { 703 thisView->setSelected( thisView->firstChild(),false);
704 QStringList command; 704}
705 OProcess *process; 705
706 process = new OProcess(); 706void AdvancedFm::startProcess(const QString & cmd) {
707 connect(process, SIGNAL(processExited(Opie::Core::OProcess*)), 707 QStringList command;
708 this, SLOT( processEnded(Opie::Core::OProcess*))); 708 OProcess *process;
709 709 process = new OProcess();
710 connect(process, SIGNAL( receivedStderr(Opie::Core::OProcess*,char*,int)), 710 connect(process, SIGNAL(processExited(Opie::Core::OProcess*)),
711 this, SLOT( oprocessStderr(Opie::Core::OProcess*,char*,int))); 711 this, SLOT( processEnded(Opie::Core::OProcess*)));
712 712
713 command << "/bin/sh"; 713 connect(process, SIGNAL( receivedStderr(Opie::Core::OProcess*,char*,int)),
714 command << "-c"; 714 this, SLOT( oprocessStderr(Opie::Core::OProcess*,char*,int)));
715 command << cmd.latin1(); 715
716 *process << command; 716 command << "/bin/sh";
717 if(!process->start(OProcess::NotifyOnExit, OProcess::All) ) 717 command << "-c";
718 qDebug("could not start process"); 718 command << cmd.latin1();
719} 719 *process << command;
720 720 if(!process->start(OProcess::NotifyOnExit, OProcess::All) )
721void AdvancedFm::processEnded(OProcess *) { 721 odebug << "could not start process" << oendl;
722 rePopulate(); 722}
723} 723
724 724void AdvancedFm::processEnded(OProcess *) {
725void AdvancedFm::oprocessStderr(OProcess*, char *buffer, int ) { 725 rePopulate();
726// qWarning("received stderrt %d bytes", buflen); 726}
727 727
728 QString lineStr = buffer; 728void AdvancedFm::oprocessStderr(OProcess*, char *buffer, int ) {
729 QMessageBox::warning( this, tr("Error"), lineStr ,tr("Ok") ); 729// owarn << "received stderrt " << buflen << " bytes" << oendl;
730} 730
731 731 QString lineStr = buffer;
732bool AdvancedFm::eventFilter( QObject * o, QEvent * e ) { 732 QMessageBox::warning( this, tr("Error"), lineStr ,tr("Ok") );
733 if ( o->inherits( "QLineEdit" ) ) { 733}
734 if ( e->type() == QEvent::KeyPress ) { 734
735 QKeyEvent *ke = (QKeyEvent*)e; 735bool AdvancedFm::eventFilter( QObject * o, QEvent * e ) {
736 if ( ke->key() == Key_Return || 736 if ( o->inherits( "QLineEdit" ) ) {
737 ke->key() == Key_Enter ) { 737 if ( e->type() == QEvent::KeyPress ) {
738 okRename(); 738 QKeyEvent *ke = (QKeyEvent*)e;
739 return true; 739 if ( ke->key() == Key_Return ||
740 } 740 ke->key() == Key_Enter ) {
741 else if ( ke->key() == Key_Escape ) { 741 okRename();
742 cancelRename(); 742 return true;
743 return true; 743 }
744 } 744 else if ( ke->key() == Key_Escape ) {
745 } 745 cancelRename();
746 else if ( e->type() == QEvent::FocusOut ) { 746 return true;
747 cancelRename(); 747 }
748 return true; 748 }
749 } 749 else if ( e->type() == QEvent::FocusOut ) {
750 } 750 cancelRename();
751 if ( o->inherits( "QListView" ) ) { 751 return true;
752 if ( e->type() == QEvent::FocusIn ) { 752 }
753 if( o == Local_View) { //keep track of which view 753 }
754 whichTab=1; 754 if ( o->inherits( "QListView" ) ) {
755 } 755 if ( e->type() == QEvent::FocusIn ) {
756 else { 756 if( o == Local_View) { //keep track of which view
757 whichTab=2; 757 whichTab=1;
758 } 758 }
759 } 759 else {
760 OtherView()->setSelected( OtherView()->currentItem(), FALSE );//make sure there's correct selection 760 whichTab=2;
761 } 761 }
762 762 }
763 return QWidget::eventFilter( o, e ); 763 OtherView()->setSelected( OtherView()->currentItem(), FALSE );//make sure there's correct selection
764} 764 }
765 765
766 766 return QWidget::eventFilter( o, e );
767void AdvancedFm::cancelRename() { 767}
768// qDebug("cancel rename"); 768
769 QListView * view; 769
770 view = CurrentView(); 770void AdvancedFm::cancelRename() {
771 771// odebug << "cancel rename" << oendl;
772 bool resetFocus = view->viewport()->focusProxy() == renameBox; 772 QListView * view;
773 delete renameBox; 773 view = CurrentView();
774 renameBox = 0; 774
775 if ( resetFocus ) { 775 bool resetFocus = view->viewport()->focusProxy() == renameBox;
776 view->viewport()->setFocusProxy( view); 776 delete renameBox;
777 view->setFocus(); 777 renameBox = 0;
778 } 778 if ( resetFocus ) {
779} 779 view->viewport()->setFocusProxy( view);
780 780 view->setFocus();
781void AdvancedFm::doRename(QListView * view) { 781 }
782 if( !CurrentView()->currentItem()) return; 782}
783 783
784 QRect r = view->itemRect( view->currentItem( )); 784void AdvancedFm::doRename(QListView * view) {
785 r = QRect( view->viewportToContents( r.topLeft() ), r.size() ); 785 if( !CurrentView()->currentItem()) return;
786 r.setX( view->contentsX() ); 786
787 787 QRect r = view->itemRect( view->currentItem( ));
788 if ( r.width() > view->visibleWidth() ) 788 r = QRect( view->viewportToContents( r.topLeft() ), r.size() );
789 r.setWidth( view->visibleWidth() ); 789 r.setX( view->contentsX() );
790 790
791 renameBox = new QLineEdit( view->viewport(), "qt_renamebox" ); 791 if ( r.width() > view->visibleWidth() )
792 renameBox->setFrame(true); 792 r.setWidth( view->visibleWidth() );
793 793
794 renameBox->setText( view->currentItem()->text(0) ); 794 renameBox = new QLineEdit( view->viewport(), "qt_renamebox" );
795 795 renameBox->setFrame(true);
796 renameBox->selectAll(); 796
797 renameBox->installEventFilter( this ); 797 renameBox->setText( view->currentItem()->text(0) );
798 798
799 view->addChild( renameBox, r.x(), r.y() ); 799 renameBox->selectAll();
800 800 renameBox->installEventFilter( this );
801 renameBox->resize( r.size() ); 801
802 802 view->addChild( renameBox, r.x(), r.y() );
803 view->viewport()->setFocusProxy( renameBox ); 803
804 804 renameBox->resize( r.size() );
805 renameBox->setFocus(); 805
806 renameBox->show(); 806 view->viewport()->setFocusProxy( renameBox );
807} 807
808 808 renameBox->setFocus();
809 809 renameBox->show();
810void AdvancedFm::renameIt() { 810}
811 if( !CurrentView()->currentItem()) return; 811
812 812
813 QListView *thisView = CurrentView(); 813void AdvancedFm::renameIt() {
814 oldName = thisView->currentItem()->text(0); 814 if( !CurrentView()->currentItem()) return;
815 doRename( thisView ); 815
816} 816 QListView *thisView = CurrentView();
817 817 oldName = thisView->currentItem()->text(0);
818void AdvancedFm::okRename() { 818 doRename( thisView );
819 if( !renameBox) return; 819}
820 820
821 QString newName = renameBox->text(); 821void AdvancedFm::okRename() {
822 cancelRename(); 822 if( !renameBox) return;
823 QListView * view = CurrentView(); 823
824 QString path = CurrentDir()->canonicalPath() + "/"; 824 QString newName = renameBox->text();
825 oldName = path + oldName; 825 cancelRename();
826 newName = path + newName; 826 QListView * view = CurrentView();
827 if( rename( oldName.latin1(), newName.latin1())== -1) 827 QString path = CurrentDir()->canonicalPath() + "/";
828 QMessageBox::message(tr("Note"),tr("Could not rename")); 828 oldName = path + oldName;
829 else 829 newName = path + newName;
830 oldName = ""; 830 if( rename( oldName.latin1(), newName.latin1())== -1)
831 QListViewItem *item = view->currentItem(); 831 QMessageBox::message(tr("Note"),tr("Could not rename"));
832 view->takeItem( item ); 832 else
833 delete item; 833 oldName = "";
834 rePopulate(); 834 QListViewItem *item = view->currentItem();
835} 835 view->takeItem( item );
836 836 delete item;
837void AdvancedFm::openSearch() { 837 rePopulate();
838 QMessageBox::message(tr("Note"),tr("Not Yet Implemented")); 838}
839} 839
840void AdvancedFm::openSearch() {
841 QMessageBox::message(tr("Note"),tr("Not Yet Implemented"));
842}
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 @@
1/**************************************************************************** 1/****************************************************************************
2** copyright 2002 ljp ljp@llornkcor.com 2** copyright 2002 ljp ljp@llornkcor.com
3** Created: Sat Feb 23 19:44:40 2002 L.J. Potter 3** Created: Sat Feb 23 19:44:40 2002 L.J. Potter
4** 4**
5** This file may be distributed and/or modified under the terms of the 5** This file may be distributed and/or modified under the terms of the
6** GNU General Public License version 2 as published by the Free Software 6** GNU General Public License version 2 as published by the Free Software
7** Foundation and appearing in the file LICENSE.GPL included in the 7** Foundation and appearing in the file LICENSE.GPL included in the
8** packaging of this file. 8** packaging of this file.
9** 9**
10** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 10** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
11** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 11** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
12** 12**
13****************************************************************************/ 13****************************************************************************/
14#include "filePermissions.h" 14#include "filePermissions.h"
15 15
16#include <qfileinfo.h> 16#include <qfileinfo.h>
17 17
18#include <qcheckbox.h> 18#include <qcheckbox.h>
19#include <qlabel.h> 19#include <qlabel.h>
20#include <qlineedit.h> 20#include <qlineedit.h>
21#include <qmessagebox.h> 21#include <qmessagebox.h>
22 22
23#include <unistd.h> 23#include <unistd.h>
24#include <sys/stat.h> 24#include <sys/stat.h>
25#include <stdlib.h> 25#include <stdlib.h>
26#include <sys/types.h> 26#include <sys/types.h>
27#include <pwd.h> 27#include <pwd.h>
28#include <grp.h> 28#include <grp.h>
29 29
30filePermissions::filePermissions( QWidget* parent, const char* name, bool modal, WFlags fl, const QString &fileName ) 30filePermissions::filePermissions( QWidget* parent, const char* name, bool modal, WFlags fl, const QString &fileName )
31 : QDialog( parent, name, modal, fl ) 31 : QDialog( parent, name, modal, fl )
32{ 32{
33 if ( !name ) 33 if ( !name )
34 setName( tr("filePermissions") ); 34 setName( tr("filePermissions") );
35// qDebug("FilePermissions "+fileName); 35// odebug << "FilePermissions "+fileName << oendl;
36/* resize( 236, 210 ); 36/* resize( 236, 210 );
37 setMaximumSize( QSize( 236, 210 ) ); 37 setMaximumSize( QSize( 236, 210 ) );
38*/ setCaption( tr( "Set File Permissions" ) ); 38*/ setCaption( tr( "Set File Permissions" ) );
39 39
40 TextLabel1 = new QLabel( this, "TextLabel1" ); 40 TextLabel1 = new QLabel( this, "TextLabel1" );
41 TextLabel1->setGeometry( QRect( 25, 5, 175, 20 ) ); 41 TextLabel1->setGeometry( QRect( 25, 5, 175, 20 ) );
42 TextLabel1->setText( tr( "Set file permissions for:" ) ); 42 TextLabel1->setText( tr( "Set file permissions for:" ) );
43 43
44 LineEdit1 = new QLineEdit( this, "LineEdit1" ); 44 LineEdit1 = new QLineEdit( this, "LineEdit1" );
45 LineEdit1->setGeometry( QRect( 10, 25, 218, 22 ) ); 45 LineEdit1->setGeometry( QRect( 10, 25, 218, 22 ) );
46 LineEdit1->setReadOnly(true); 46 LineEdit1->setReadOnly(true);
47 47
48 TextLabel4 = new QLabel( this, "TextLabel4" ); 48 TextLabel4 = new QLabel( this, "TextLabel4" );
49 TextLabel4->setGeometry( QRect( 5, 85, 50, 15 ) ); 49 TextLabel4->setGeometry( QRect( 5, 85, 50, 15 ) );
50 TextLabel4->setText( tr( "owner" ) ); 50 TextLabel4->setText( tr( "owner" ) );
51 51
52 TextLabel4_2 = new QLabel( this, "TextLabel4_2" ); 52 TextLabel4_2 = new QLabel( this, "TextLabel4_2" );
53 TextLabel4_2->setGeometry( QRect( 5, 105, 50, 15 ) ); 53 TextLabel4_2->setGeometry( QRect( 5, 105, 50, 15 ) );
54 TextLabel4_2->setText( tr( "group" ) ); 54 TextLabel4_2->setText( tr( "group" ) );
55 55
56 TextLabel4_3 = new QLabel( this, "TextLabel4_3" ); 56 TextLabel4_3 = new QLabel( this, "TextLabel4_3" );
57 TextLabel4_3->setGeometry( QRect( 5, 125, 50, 15 ) ); 57 TextLabel4_3->setGeometry( QRect( 5, 125, 50, 15 ) );
58 TextLabel4_3->setText( tr( "others" ) ); 58 TextLabel4_3->setText( tr( "others" ) );
59 59
60 CheckBox1 = new QCheckBox( this, "CheckBox1" ); 60 CheckBox1 = new QCheckBox( this, "CheckBox1" );
61 CheckBox1->setGeometry( QRect( 75, 85, 20, 16 ) ); 61 CheckBox1->setGeometry( QRect( 75, 85, 20, 16 ) );
62 connect(CheckBox1, SIGNAL(released()),this,SLOT(ownReadCheck())); 62 connect(CheckBox1, SIGNAL(released()),this,SLOT(ownReadCheck()));
63 63
64 CheckBox1_2 = new QCheckBox( this, "CheckBox1_2" ); 64 CheckBox1_2 = new QCheckBox( this, "CheckBox1_2" );
65 CheckBox1_2->setGeometry( QRect( 135, 85, 20, 16 ) ); 65 CheckBox1_2->setGeometry( QRect( 135, 85, 20, 16 ) );
66 connect(CheckBox1_2, SIGNAL(released()),this,SLOT(ownWriteCheck())); 66 connect(CheckBox1_2, SIGNAL(released()),this,SLOT(ownWriteCheck()));
67 67
68 CheckBox1_3 = new QCheckBox( this, "CheckBox1_3" ); 68 CheckBox1_3 = new QCheckBox( this, "CheckBox1_3" );
69 CheckBox1_3->setGeometry( QRect( 195, 85, 20, 16 ) ); 69 CheckBox1_3->setGeometry( QRect( 195, 85, 20, 16 ) );
70 connect(CheckBox1_3, SIGNAL(released()),this,SLOT(ownExeCheck())); 70 connect(CheckBox1_3, SIGNAL(released()),this,SLOT(ownExeCheck()));
71 71
72 CheckBox1_4 = new QCheckBox( this, "CheckBox1_4" ); 72 CheckBox1_4 = new QCheckBox( this, "CheckBox1_4" );
73 CheckBox1_4->setGeometry( QRect( 75, 105, 20, 16 ) ); 73 CheckBox1_4->setGeometry( QRect( 75, 105, 20, 16 ) );
74 connect(CheckBox1_4, SIGNAL(released()),this,SLOT(grpReadCheck())); 74 connect(CheckBox1_4, SIGNAL(released()),this,SLOT(grpReadCheck()));
75 75
76 CheckBox1_5 = new QCheckBox( this, "CheckBox1_5" ); 76 CheckBox1_5 = new QCheckBox( this, "CheckBox1_5" );
77 CheckBox1_5->setGeometry( QRect( 135, 105, 20, 16 ) ); 77 CheckBox1_5->setGeometry( QRect( 135, 105, 20, 16 ) );
78 connect(CheckBox1_5, SIGNAL(released()),this,SLOT(grpWriteCheck())); 78 connect(CheckBox1_5, SIGNAL(released()),this,SLOT(grpWriteCheck()));
79 79
80 CheckBox1_6 = new QCheckBox( this, "CheckBox1_6" ); 80 CheckBox1_6 = new QCheckBox( this, "CheckBox1_6" );
81 CheckBox1_6->setGeometry( QRect( 195, 105, 20, 16 ) ); 81 CheckBox1_6->setGeometry( QRect( 195, 105, 20, 16 ) );
82 connect(CheckBox1_6, SIGNAL(released()),this,SLOT(grpExeCheck())); 82 connect(CheckBox1_6, SIGNAL(released()),this,SLOT(grpExeCheck()));
83 83
84 CheckBox1_7 = new QCheckBox( this, "CheckBox1_7" ); 84 CheckBox1_7 = new QCheckBox( this, "CheckBox1_7" );
85 CheckBox1_7->setGeometry( QRect( 75, 125, 16, 16 ) ); 85 CheckBox1_7->setGeometry( QRect( 75, 125, 16, 16 ) );
86 connect(CheckBox1_7, SIGNAL(released()),this,SLOT(wrldReadCheck())); 86 connect(CheckBox1_7, SIGNAL(released()),this,SLOT(wrldReadCheck()));
87 87
88 CheckBox1_8 = new QCheckBox( this, "CheckBox1_8" ); 88 CheckBox1_8 = new QCheckBox( this, "CheckBox1_8" );
89 CheckBox1_8->setGeometry( QRect( 135, 125, 20, 16 ) ); 89 CheckBox1_8->setGeometry( QRect( 135, 125, 20, 16 ) );
90 connect(CheckBox1_8, SIGNAL(released()),this,SLOT(wrldWriteCheck())); 90 connect(CheckBox1_8, SIGNAL(released()),this,SLOT(wrldWriteCheck()));
91 91
92 CheckBox1_8_2 = new QCheckBox( this, "CheckBox1_8_2" ); 92 CheckBox1_8_2 = new QCheckBox( this, "CheckBox1_8_2" );
93 CheckBox1_8_2->setGeometry( QRect( 195, 125, 20, 16 ) ); 93 CheckBox1_8_2->setGeometry( QRect( 195, 125, 20, 16 ) );
94 connect(CheckBox1_8_2, SIGNAL(released()),this,SLOT(wrldExeCheck())); 94 connect(CheckBox1_8_2, SIGNAL(released()),this,SLOT(wrldExeCheck()));
95 95
96 GroupLineEdit = new QLineEdit( this, "GroupLineEdit" ); 96 GroupLineEdit = new QLineEdit( this, "GroupLineEdit" );
97 GroupLineEdit->setGeometry( QRect( 125, 155, 106, 22 ) ); 97 GroupLineEdit->setGeometry( QRect( 125, 155, 106, 22 ) );
98 98
99 OwnerLineEdit = new QLineEdit( this, "OwnerLineEdit" ); 99 OwnerLineEdit = new QLineEdit( this, "OwnerLineEdit" );
100 OwnerLineEdit->setGeometry( QRect( 10, 155, 106, 22 ) ); 100 OwnerLineEdit->setGeometry( QRect( 10, 155, 106, 22 ) );
101 101
102 TextLabel5 = new QLabel( this, "TextLabel5" ); 102 TextLabel5 = new QLabel( this, "TextLabel5" );
103 TextLabel5->setGeometry( QRect( 45, 180, 40, 16 ) ); 103 TextLabel5->setGeometry( QRect( 45, 180, 40, 16 ) );
104 TextLabel5->setText( tr( "Owner" ) ); 104 TextLabel5->setText( tr( "Owner" ) );
105 105
106 TextLabel5_2 = new QLabel( this, "TextLabel5_2" ); 106 TextLabel5_2 = new QLabel( this, "TextLabel5_2" );
107 TextLabel5_2->setGeometry( QRect( 155, 180, 40, 16 ) ); 107 TextLabel5_2->setGeometry( QRect( 155, 180, 40, 16 ) );
108 TextLabel5_2->setText( tr( "Group" ) ); 108 TextLabel5_2->setText( tr( "Group" ) );
109 109
110 ModeLine = new QLineEdit( this, "TextLabelMode" ); 110 ModeLine = new QLineEdit( this, "TextLabelMode" );
111 ModeLine->setGeometry( QRect( 10, 60, 40, 15 ) ); 111 ModeLine->setGeometry( QRect( 10, 60, 40, 15 ) );
112 112
113 TextLabel3_2 = new QLabel( this, "TextLabel3_2" ); 113 TextLabel3_2 = new QLabel( this, "TextLabel3_2" );
114 TextLabel3_2->setGeometry( QRect( 60, 55, 50, 20 ) ); 114 TextLabel3_2->setGeometry( QRect( 60, 55, 50, 20 ) );
115 TextLabel3_2->setText( tr( "read" ) ); 115 TextLabel3_2->setText( tr( "read" ) );
116 TextLabel3_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) ); 116 TextLabel3_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
117 117
118 TextLabel3_2_2 = new QLabel( this, "TextLabel3_2_2" ); 118 TextLabel3_2_2 = new QLabel( this, "TextLabel3_2_2" );
119 TextLabel3_2_2->setGeometry( QRect( 120, 55, 50, 20 ) ); 119 TextLabel3_2_2->setGeometry( QRect( 120, 55, 50, 20 ) );
120 TextLabel3_2_2->setText( tr( "write" ) ); 120 TextLabel3_2_2->setText( tr( "write" ) );
121 TextLabel3_2_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) ); 121 TextLabel3_2_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
122 122
123 TextLabel3 = new QLabel( this, "TextLabel3" ); 123 TextLabel3 = new QLabel( this, "TextLabel3" );
124 TextLabel3->setGeometry( QRect( 180, 55, 50, 20 ) ); 124 TextLabel3->setGeometry( QRect( 180, 55, 50, 20 ) );
125 TextLabel3->setText( tr( "execute" ) ); 125 TextLabel3->setText( tr( "execute" ) );
126 TextLabel3->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) ); 126 TextLabel3->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
127 127
128 struct stat buf; 128 struct stat buf;
129 mode_t mode; 129 mode_t mode;
130 file = fileName; 130 file = fileName;
131 QFileInfo fi(file); 131 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 @@
1/**************************************************************************** 1/****************************************************************************
2** outputEdit.cpp 2** outputEdit.cpp
3** 3**
4** Copyright: Fri Apr 12 15:12:58 2002 L.J. Potter <ljp@llornkcor.com> 4** Copyright: Fri Apr 12 15:12:58 2002 L.J. Potter <ljp@llornkcor.com>
5****************************************************************************/ 5****************************************************************************/
6#include "output.h" 6#include "output.h"
7 7
8/* OPIE */
9#include <opie2/odebug.h>
8#include <qpe/qpeapplication.h> 10#include <qpe/qpeapplication.h>
9#include <qpe/applnk.h> 11#include <qpe/applnk.h>
12using namespace Opie::Core;
10 13
14/* QT */
11#include <qfile.h> 15#include <qfile.h>
12#include <qmultilineedit.h> 16#include <qmultilineedit.h>
13#include <qpushbutton.h> 17#include <qpushbutton.h>
14#include <qlayout.h> 18#include <qlayout.h>
15 19
20/* STD */
16#include <errno.h> 21#include <errno.h>
17 22
18/* XPM */ 23/* XPM */
19using namespace Opie::Core;
20using namespace Opie::Core;
21static char * filesave_xpm[] = { 24static char * filesave_xpm[] = {
22"16 16 78 1", 25"16 16 78 1",
23" c None", 26" c None",
24". c #343434", 27". c #343434",
25"+ c #A0A0A0", 28"+ c #A0A0A0",
26"@ c #565656", 29"@ c #565656",
27"# c #9E9E9E", 30"# c #9E9E9E",
28"$ c #525252", 31"$ c #525252",
29"% c #929292", 32"% c #929292",
30"& c #676767", 33"& c #676767",
31"* c #848484", 34"* c #848484",
32"= c #666666", 35"= c #666666",
33"- c #D8D8D8", 36"- c #D8D8D8",
34"; c #FFFFFF", 37"; c #FFFFFF",
35"> c #DBDBDB", 38"> c #DBDBDB",
36", c #636363", 39", c #636363",
37"' c #989898", 40"' c #989898",
38") c #2D2D2D", 41") c #2D2D2D",
39"! c #909090", 42"! c #909090",
40"~ c #AEAEAE", 43"~ c #AEAEAE",
41"{ c #EAEAEA", 44"{ c #EAEAEA",
42"] c #575757", 45"] c #575757",
43"^ c #585858", 46"^ c #585858",
44"/ c #8A8A8A", 47"/ c #8A8A8A",
45"( c #828282", 48"( c #828282",
46"_ c #6F6F6F", 49"_ c #6F6F6F",
47": c #C9C9C9", 50": c #C9C9C9",
48"< c #050505", 51"< c #050505",
49"[ c #292929", 52"[ c #292929",
50"} c #777777", 53"} c #777777",
51"| c #616161", 54"| c #616161",
52"1 c #3A3A3A", 55"1 c #3A3A3A",
53"2 c #BEBEBE", 56"2 c #BEBEBE",
54"3 c #2C2C2C", 57"3 c #2C2C2C",
55"4 c #7C7C7C", 58"4 c #7C7C7C",
56"5 c #F6F6F6", 59"5 c #F6F6F6",
57"6 c #FCFCFC", 60"6 c #FCFCFC",
58"7 c #6B6B6B", 61"7 c #6B6B6B",
59"8 c #959595", 62"8 c #959595",
60"9 c #4F4F4F", 63"9 c #4F4F4F",
61"0 c #808080", 64"0 c #808080",
62"a c #767676", 65"a c #767676",
63"b c #818181", 66"b c #818181",
64"c c #B8B8B8", 67"c c #B8B8B8",
65"d c #FBFBFB", 68"d c #FBFBFB",
66"e c #F9F9F9", 69"e c #F9F9F9",
67"f c #CCCCCC", 70"f c #CCCCCC",
68"g c #030303", 71"g c #030303",
69"h c #737373", 72"h c #737373",
70"i c #7A7A7A", 73"i c #7A7A7A",
71"j c #7E7E7E", 74"j c #7E7E7E",
72"k c #6A6A6A", 75"k c #6A6A6A",
73"l c #FAFAFA", 76"l c #FAFAFA",
74"m c #505050", 77"m c #505050",
75"n c #9D9D9D", 78"n c #9D9D9D",
76"o c #333333", 79"o c #333333",
77"p c #7B7B7B", 80"p c #7B7B7B",
78"q c #787878", 81"q c #787878",
79"r c #696969", 82"r c #696969",
80"s c #494949", 83"s c #494949",
81"t c #555555", 84"t c #555555",
82"u c #949494", 85"u c #949494",
83"v c #E6E6E6", 86"v c #E6E6E6",
84"w c #424242", 87"w c #424242",
85"x c #515151", 88"x c #515151",
86"y c #535353", 89"y c #535353",
87"z c #3E3E3E", 90"z c #3E3E3E",
88"A c #D4D4D4", 91"A c #D4D4D4",
89"B c #0C0C0C", 92"B c #0C0C0C",
90"C c #353535", 93"C c #353535",
91"D c #474747", 94"D c #474747",
92"E c #ECECEC", 95"E c #ECECEC",
93"F c #919191", 96"F c #919191",
94"G c #7D7D7D", 97"G c #7D7D7D",
95"H c #000000", 98"H c #000000",
96"I c #404040", 99"I c #404040",
97"J c #858585", 100"J c #858585",
98"K c #323232", 101"K c #323232",
99"L c #D0D0D0", 102"L c #D0D0D0",
100"M c #1C1C1C", 103"M c #1C1C1C",
101" ...+ ", 104" ...+ ",
102" @#$%&..+ ", 105" @#$%&..+ ",
103" .*=-;;>,..+ ", 106" .*=-;;>,..+ ",
104" ')!~;;;;;;{]..", 107" ')!~;;;;;;{]..",
105" ^/(-;;;;;;;_:<", 108" ^/(-;;;;;;;_:<",
106" [}|;;;;;;;{12$", 109" [}|;;;;;;;{12$",
107" #34-55;;;;678$+", 110" #34-55;;;;678$+",
108" 90ab=c;dd;e1fg ", 111" 90ab=c;dd;e1fg ",
109" [ahij((kbl0mn$ ", 112" [ahij((kbl0mn$ ",
110" op^q^^7r&]s/$+ ", 113" op^q^^7r&]s/$+ ",
111"@btu;vbwxy]zAB ", 114"@btu;vbwxy]zAB ",
112"CzDEvEv;;DssF$ ", 115"CzDEvEv;;DssF$ ",
113"G.H{E{E{IxsJ$+ ", 116"G.H{E{E{IxsJ$+ ",
114" +...vEKxzLM ", 117" +...vEKxzLM ",
115" +...z]n$ ", 118" +...z]n$ ",
116" +... "}; 119" +... "};
117 120
118Output::Output( const QStringList commands, QWidget* parent, const char* name, bool modal, WFlags fl) 121Output::Output( const QStringList commands, QWidget* parent, const char* name, bool modal, WFlags fl)
119 : QDialog( parent, name, modal, fl ) 122 : QDialog( parent, name, modal, fl )
120{ 123{
121 QStringList cmmds; 124 QStringList cmmds;
122// cmmds=QStringList::split( " ", commands, false); 125// cmmds=QStringList::split( " ", commands, false);
123 cmmds=commands; 126 cmmds=commands;
124// qDebug("count %d", cmmds.count()); 127// odebug << "count " << cmmds.count() << "" << oendl;
125 if ( !name ) 128 if ( !name )
126 setName( tr("Output")); 129 setName( tr("Output"));
127 resize( 196, 269 ); 130 resize( 196, 269 );
128 setCaption( name ); 131 setCaption( name );
129 132
130 OutputLayout = new QGridLayout( this ); 133 OutputLayout = new QGridLayout( this );
131 OutputLayout->setSpacing( 2); 134 OutputLayout->setSpacing( 2);
132 OutputLayout->setMargin( 2); 135 OutputLayout->setMargin( 2);
133 136
134 QPushButton *docButton; 137 QPushButton *docButton;
135 docButton = new QPushButton( QPixmap(( const char** ) filesave_xpm ) ,"",this,"saveButton"); 138 docButton = new QPushButton( QPixmap(( const char** ) filesave_xpm ) ,"",this,"saveButton");
136 docButton->setFixedSize( QSize( 20, 20 ) ); 139 docButton->setFixedSize( QSize( 20, 20 ) );
137 connect( docButton,SIGNAL(released()),this,SLOT( saveOutput() )); 140 connect( docButton,SIGNAL(released()),this,SLOT( saveOutput() ));
138 // docButton->setFlat(TRUE); 141 // docButton->setFlat(TRUE);
139 OutputLayout->addMultiCellWidget( docButton, 0,0,3,3 ); 142 OutputLayout->addMultiCellWidget( docButton, 0,0,3,3 );
140 143
141 OutputEdit = new QMultiLineEdit( this, "OutputEdit" ); 144 OutputEdit = new QMultiLineEdit( this, "OutputEdit" );
142 OutputLayout->addMultiCellWidget( OutputEdit, 1,1,0,3 ); 145 OutputLayout->addMultiCellWidget( OutputEdit, 1,1,0,3 );
143 146
144 proc = new OProcess(); 147 proc = new OProcess();
145 148
146 connect(proc, SIGNAL(processExited(Opie::Core::OProcess*)), 149 connect(proc, SIGNAL(processExited(Opie::Core::OProcess*)),
147 this, SLOT( processFinished())); 150 this, SLOT( processFinished()));
148 151
149 connect(proc, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)), 152 connect(proc, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)),
150 this, SLOT(commandStdout(Opie::Core::OProcess*,char*,int))); 153 this, SLOT(commandStdout(Opie::Core::OProcess*,char*,int)));
151 154
152 connect(proc, SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)), 155 connect(proc, SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)),
153 this, SLOT(commandStderr(Opie::Core::OProcess*,char*,int))); 156 this, SLOT(commandStderr(Opie::Core::OProcess*,char*,int)));
154 157
155// connect( , SIGNAL(received(const QByteArray&)), 158// connect( , SIGNAL(received(const QByteArray&)),
156// this, SLOT(commandStdin(const QByteArray&))); 159// this, SLOT(commandStdin(const QByteArray&)));
157 160
158// * proc << commands.latin1(); 161// * proc << commands.latin1();
159 for ( QStringList::Iterator it = cmmds.begin(); it != cmmds.end(); ++it ) { 162 for ( QStringList::Iterator it = cmmds.begin(); it != cmmds.end(); ++it ) {
160 qDebug( "%s", (*it).latin1() ); 163 odebug << "" << (*it).latin1() << "" << oendl;
161 * proc << (*it).latin1(); 164 * proc << (*it).latin1();
162 } 165 }
163 166
164 if(!proc->start(OProcess::NotifyOnExit, OProcess::All)) { 167 if(!proc->start(OProcess::NotifyOnExit, OProcess::All)) {
165 168
166 OutputEdit->append(tr("Process could not start") ); 169 OutputEdit->append(tr("Process could not start") );
167 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 170 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
168 perror("Error: "); 171 perror("Error: ");
169 QString errorMsg=tr("Error\n")+(QString)strerror(errno); 172 QString errorMsg=tr("Error\n")+(QString)strerror(errno);
170 OutputEdit->append( errorMsg); 173 OutputEdit->append( errorMsg);
171 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 174 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
172 } 175 }
173} 176}
174 177
175Output::~Output() { 178Output::~Output() {
176} 179}
177 180
178void Output::saveOutput() { 181void Output::saveOutput() {
179 182
180 InputDialog *fileDlg; 183 InputDialog *fileDlg;
181 fileDlg = new InputDialog(this,tr("Save output to file (name only)"),TRUE, 0); 184 fileDlg = new InputDialog(this,tr("Save output to file (name only)"),TRUE, 0);
182 fileDlg->exec(); 185 fileDlg->exec();
183 if( fileDlg->result() == 1 ) { 186 if( fileDlg->result() == 1 ) {
184 QString filename = QPEApplication::documentDir(); 187 QString filename = QPEApplication::documentDir();
185 if(filename.right(1).find('/') == -1) 188 if(filename.right(1).find('/') == -1)
186 filename+="/"; 189 filename+="/";
187 QString name = fileDlg->LineEdit1->text(); 190 QString name = fileDlg->LineEdit1->text();
188 filename+="text/plain/"+name; 191 filename+="text/plain/"+name;
189 qDebug(filename); 192 odebug << filename << oendl;
190 193
191 QFile f(filename); 194 QFile f(filename);
192 f.open( IO_WriteOnly); 195 f.open( IO_WriteOnly);
193 if( f.writeBlock( OutputEdit->text(), qstrlen( OutputEdit->text()) ) != -1) { 196 if( f.writeBlock( OutputEdit->text(), qstrlen( OutputEdit->text()) ) != -1) {
194 DocLnk lnk; 197 DocLnk lnk;
195 lnk.setName(name); //sets file name 198 lnk.setName(name); //sets file name
196 lnk.setFile(filename); //sets File property 199 lnk.setFile(filename); //sets File property
197 lnk.setType("text/plain"); 200 lnk.setType("text/plain");
198 if(!lnk.writeLink()) { 201 if(!lnk.writeLink()) {
199 qDebug("Writing doclink did not work"); 202 odebug << "Writing doclink did not work" << oendl;
200 } 203 }
201 } else 204 } else
202 qWarning("Could not write file"); 205 owarn << "Could not write file" << oendl;
203 f.close(); 206 f.close();
204 } 207 }
205} 208}
206 209
207void Output::commandStdout(OProcess*, char *buffer, int buflen) { 210void Output::commandStdout(OProcess*, char *buffer, int buflen) {
208 qWarning("received stdout %d bytes", buflen); 211 owarn << "received stdout " << buflen << " bytes" << oendl;
209 212
210// QByteArray data(buflen); 213// QByteArray data(buflen);
211// data.fill(*buffer, buflen); 214// data.fill(*buffer, buflen);
212// for (uint i = 0; i < data.count(); i++ ) { 215// for (uint i = 0; i < data.count(); i++ ) {
213// printf("%c", buffer[i] ); 216// printf("%c", buffer[i] );
214// } 217// }
215// printf("\n"); 218// printf("\n");
216 219
217 QString lineStr = buffer; 220 QString lineStr = buffer;
218 lineStr=lineStr.left(lineStr.length()-1); 221 lineStr=lineStr.left(lineStr.length()-1);
219 OutputEdit->append(lineStr); 222 OutputEdit->append(lineStr);
220 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 223 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
221} 224}
222 225
223 226
224void Output::commandStdin( const QByteArray &data) { 227void Output::commandStdin( const QByteArray &data) {
225 qWarning("received stdin %d bytes", data.size()); 228 owarn << "received stdin " << data.size() << " bytes" << oendl;
226 // recieved data from the io layer goes to sz 229 // recieved data from the io layer goes to sz
227 proc->writeStdin(data.data(), data.size()); 230 proc->writeStdin(data.data(), data.size());
228} 231}
229 232
230void Output::commandStderr(OProcess*, char *buffer, int buflen) { 233void Output::commandStderr(OProcess*, char *buffer, int buflen) {
231 qWarning("received stderrt %d bytes", buflen); 234 owarn << "received stderrt " << buflen << " bytes" << oendl;
232 235
233 QString lineStr = buffer; 236 QString lineStr = buffer;
234// lineStr=lineStr.left(lineStr.length()-1); 237// lineStr=lineStr.left(lineStr.length()-1);
235 OutputEdit->append(lineStr); 238 OutputEdit->append(lineStr);
236 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 239 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
237} 240}
238 241
239void Output::processFinished() { 242void Output::processFinished() {
240 243
241 delete proc; 244 delete proc;
242 OutputEdit->append( tr("\nFinished\n") ); 245 OutputEdit->append( tr("\nFinished\n") );
243 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 246 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
244// close(); 247// close();
245// disconnect( layer(), SIGNAL(received(const QByteArray&)), 248// disconnect( layer(), SIGNAL(received(const QByteArray&)),
246// this, SLOT(commandStdin(const QByteArray&))); 249// this, SLOT(commandStdin(const QByteArray&)));
247} 250}
248 251
249//============================== 252//==============================
250 253
251InputDialog::InputDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) 254InputDialog::InputDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
252 : QDialog( parent, name, modal, fl ) 255 : QDialog( parent, name, modal, fl )
253{ 256{
254 if ( !name ) 257 if ( !name )
255 setName( "InputDialog" ); 258 setName( "InputDialog" );
256 resize( 234, 50 ); 259 resize( 234, 50 );
257 setMaximumSize( QSize( 240, 50 ) ); 260 setMaximumSize( QSize( 240, 50 ) );
258 setCaption( tr(name ) ); 261 setCaption( tr(name ) );
259 262
260 LineEdit1 = new QLineEdit( this, "LineEdit1" ); 263 LineEdit1 = new QLineEdit( this, "LineEdit1" );
261 LineEdit1->setGeometry( QRect( 10, 10, 216, 22 ) ); 264 LineEdit1->setGeometry( QRect( 10, 10, 216, 22 ) );
262 LineEdit1->setFocus(); 265 LineEdit1->setFocus();
263 LineEdit1->setFocus(); 266 LineEdit1->setFocus();
264 connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(returned() )); 267 connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(returned() ));
265} 268}
266 269
267InputDialog::~InputDialog() { 270InputDialog::~InputDialog() {
268 inputText = LineEdit1->text(); 271 inputText = LineEdit1->text();
269} 272}
270 273
271void InputDialog::setInputText(const QString &string) { 274void InputDialog::setInputText(const QString &string) {
272 LineEdit1->setText( string); 275 LineEdit1->setText( string);
273} 276}
274 277
275void InputDialog::returned() { 278void InputDialog::returned() {
276 inputText = LineEdit1->text(); 279 inputText = LineEdit1->text();
277 this->accept(); 280 this->accept();
278} 281}
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 @@
1CONFIG = qt warn_on quick-app 1CONFIG = qt warn_on quick-app
2HEADERS = mainwindow.h \ 2HEADERS = mainwindow.h \
3 cbinfo.h \ 3 cbinfo.h \
4 traninfo.h \ 4 traninfo.h \
5 graphinfo.h \ 5 graphinfo.h \
6 configuration.h \ 6 configuration.h \
7 password.h \ 7 password.h \
8 checkbook.h \ 8 checkbook.h \
9 transaction.h \ 9 transaction.h \
10 tabledef.h \ 10 tabledef.h \
11 listedit.h \ 11 listedit.h \
12 cfg.h \ 12 cfg.h \
13 graph.h 13 graph.h
14SOURCES = main.cpp \ 14SOURCES = main.cpp \
15 mainwindow.cpp \ 15 mainwindow.cpp \
16 cbinfo.cpp \ 16 cbinfo.cpp \
17 traninfo.cpp \ 17 traninfo.cpp \
18 graphinfo.cpp \ 18 graphinfo.cpp \
19 configuration.cpp \ 19 configuration.cpp \
20 password.cpp \ 20 password.cpp \
21 checkbook.cpp \ 21 checkbook.cpp \
22 transaction.cpp \ 22 transaction.cpp \
23 tabledef.cpp \ 23 tabledef.cpp \
24 listedit.cpp \ 24 listedit.cpp \
25 cfg.cpp \ 25 cfg.cpp \
26 graph.cpp 26 graph.cpp
27INCLUDEPATH += $(OPIEDIR)/include 27INCLUDEPATH += $(OPIEDIR)/include
28DEPENDPATH += $(OPIEDIR)/include 28DEPENDPATH += $(OPIEDIR)/include
29LIBS += -lqpe -lopiecore2 -lopieui2 29LIBS += -lqpe -lopiecore2 -lopieui2
30TARGET = checkbook 30TARGET = checkbook
31 31
32include ( $(OPIEDIR)/include.pro ) 32include ( $(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 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> 4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "listedit.h" 29#include "listedit.h"
30
31/* OPIE */
32#include <opie2/odebug.h>
33#include <qpe/resource.h>
34using namespace Opie::Core;
35
36/* QT */
30#include <qlayout.h> 37#include <qlayout.h>
31#include <qlineedit.h> 38#include <qlineedit.h>
32#include <qlistview.h> 39#include <qlistview.h>
33#include <qwidgetstack.h> 40#include <qwidgetstack.h>
34#include <qcombobox.h> 41#include <qcombobox.h>
35#include <qpushbutton.h> 42#include <qpushbutton.h>
36#include <qpe/resource.h>
37
38 43
39// --- ListEdit --------------------------------------------------------------- 44// --- ListEdit ---------------------------------------------------------------
40ListEdit::ListEdit( QWidget *parent, const char *sName ) 45ListEdit::ListEdit( QWidget *parent, const char *sName )
41 : QWidget(parent, sName), TableDef(sName) 46 : QWidget(parent, sName), TableDef(sName)
42{ 47{
43 // get font height 48 // get font height
44 int fh = fontMetrics().height(); 49 int fh = fontMetrics().height();
45 50
46 // create layout 51 // create layout
47 QGridLayout *layout=new QGridLayout(this); 52 QGridLayout *layout=new QGridLayout(this);
48 layout->setSpacing( 2 ); 53 layout->setSpacing( 2 );
49 layout->setMargin( 4 ); 54 layout->setMargin( 4 );
50 55
51 // type table 56 // type table
52 _typeTable = new QListView( this ); 57 _typeTable = new QListView( this );
53 ColumnDef *def=first(); 58 ColumnDef *def=first();
54 while( def ) { 59 while( def ) {
55 _typeTable->addColumn( def->getName() ); 60 _typeTable->addColumn( def->getName() );
56 def=next(); 61 def=next();
57 } 62 }
58 connect( _typeTable, SIGNAL( clicked(QListViewItem*,const QPoint&,int) ), this, SLOT( slotClick(QListViewItem*,const QPoint&,int) ) ); 63 connect( _typeTable, SIGNAL( clicked(QListViewItem*,const QPoint&,int) ), this, SLOT( slotClick(QListViewItem*,const QPoint&,int) ) );
59 layout->addMultiCellWidget(_typeTable, 0,4,0,4); 64 layout->addMultiCellWidget(_typeTable, 0,4,0,4);
60 _currentItem=NULL; 65 _currentItem=NULL;
61 66
62 // edit field 67 // edit field
63 _stack=new QWidgetStack( this ); 68 _stack=new QWidgetStack( this );
64 _stack->setMaximumHeight(fh+5); 69 _stack->setMaximumHeight(fh+5);
65 layout->addMultiCellWidget(_stack, 5,5,0,2); 70 layout->addMultiCellWidget(_stack, 5,5,0,2);
66 _typeEdit = new QLineEdit( _stack ); 71 _typeEdit = new QLineEdit( _stack );
67 _stack->raiseWidget(_typeEdit ); 72 _stack->raiseWidget(_typeEdit );
68 connect( _typeEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotEditChanged(const QString&) ) ); 73 connect( _typeEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotEditChanged(const QString&) ) );
69 74
70 // combo box 75 // combo box
71 _box=new QComboBox( _stack ); 76 _box=new QComboBox( _stack );
72 connect( _box, SIGNAL( activated(const QString&) ), this, SLOT( slotActivated(const QString&) ) ); 77 connect( _box, SIGNAL( activated(const QString&) ), this, SLOT( slotActivated(const QString&) ) );
73 78
74 79
75 // add button 80 // add button
76 QPushButton *btn = new QPushButton( Resource::loadPixmap( "checkbook/add" ), tr( "Add" ), this ); 81 QPushButton *btn = new QPushButton( Resource::loadPixmap( "checkbook/add" ), tr( "Add" ), this );
77 connect( btn, SIGNAL( clicked() ), this, SLOT( slotAdd() ) ); 82 connect( btn, SIGNAL( clicked() ), this, SLOT( slotAdd() ) );
78 layout->addWidget( btn, 5, 3 ); 83 layout->addWidget( btn, 5, 3 );
79 84
80 // delete button 85 // delete button
81 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), this ); 86 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), this );
82 connect( btn, SIGNAL( clicked() ), this, SLOT( slotDel() ) ); 87 connect( btn, SIGNAL( clicked() ), this, SLOT( slotDel() ) );
83 layout->addWidget( btn, 5, 4 ); 88 layout->addWidget( btn, 5, 4 );
84} 89}
85 90
86// --- ~ListEdit -------------------------------------------------------------- 91// --- ~ListEdit --------------------------------------------------------------
87ListEdit::~ListEdit() 92ListEdit::~ListEdit()
88{ 93{
89} 94}
90 95
91 96
92// --- slotEditTypeChanged ---------------------------------------------------- 97// --- slotEditTypeChanged ----------------------------------------------------
93void ListEdit::slotEditChanged(const QString &str) 98void ListEdit::slotEditChanged(const QString &str)
94{ 99{
95 if( !_currentItem || _currentColumn<0 ) return; 100 if( !_currentItem || _currentColumn<0 ) return;
96 _currentItem->setText(_currentColumn, str); 101 _currentItem->setText(_currentColumn, str);
97} 102}
98 103
99// --- slotAddType ------------------------------------------------------------ 104// --- slotAddType ------------------------------------------------------------
100void ListEdit::slotAdd() 105void ListEdit::slotAdd()
101{ 106{
102 // construct new row 107 // construct new row
103 QString args[8]; 108 QString args[8];
104 ColumnDef *pCol=this->first(); 109 ColumnDef *pCol=this->first();
105 int i=0; 110 int i=0;
106 while( pCol && i<8 ) { 111 while( pCol && i<8 ) {
107 args[i++]=pCol->getNewValue(); 112 args[i++]=pCol->getNewValue();
108 pCol=this->next(); 113 pCol=this->next();
109 } 114 }
110 _currentItem=new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7] ); 115 _currentItem=new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7] );
111 116
112 // fix uniques 117 // fix uniques
113 fixTypes(); 118 fixTypes();
114 119
115 // display col 0 of new value 120 // display col 0 of new value
116 QPoint pnt; 121 QPoint pnt;
117 slotClick(_currentItem, pnt, 0); 122 slotClick(_currentItem, pnt, 0);
118 _typeTable->setSelected( _currentItem, true ); 123 _typeTable->setSelected( _currentItem, true );
119 124
120 // make it selected 125 // make it selected
121 _typeEdit->setCursorPosition(0); 126 _typeEdit->setCursorPosition(0);
122 _typeEdit->setSelection(0, _typeEdit->text().length() ); 127 _typeEdit->setSelection(0, _typeEdit->text().length() );
123} 128}
124 129
125// --- slotDel ------------------------------------------------------------- 130// --- slotDel -------------------------------------------------------------
126void ListEdit::slotDel() 131void ListEdit::slotDel()
127{ 132{
128 if( !_currentItem ) return; 133 if( !_currentItem ) return;
129 delete _currentItem; 134 delete _currentItem;
130 _currentItem=NULL; 135 _currentItem=NULL;
131 _typeEdit->setText(""); 136 _typeEdit->setText("");
132 _stack->raiseWidget(_typeEdit); 137 _stack->raiseWidget(_typeEdit);
133} 138}
@@ -209,136 +214,136 @@ void ListEdit::fixTypes(int iColumn)
209 bDup=true; 214 bDup=true;
210 break; 215 break;
211 } 216 }
212 iChk++; 217 iChk++;
213 } 218 }
214 if( !bDup ) { 219 if( !bDup ) {
215 *lst.at(iNext)=repl; 220 *lst.at(iNext)=repl;
216 break; 221 break;
217 } 222 }
218 } 223 }
219 } 224 }
220 } 225 }
221 lst.sort(); 226 lst.sort();
222 227
223 // copy back clean up col map 228 // copy back clean up col map
224 for(int i=0; i<_typeTable->childCount(); i++) { 229 for(int i=0; i<_typeTable->childCount(); i++) {
225 colMap[i]->getItem()->setText(iColumn, colMap[i]->getValue()); 230 colMap[i]->getItem()->setText(iColumn, colMap[i]->getValue());
226 delete colMap[i]; 231 delete colMap[i];
227 } 232 }
228 delete colMap; 233 delete colMap;
229} 234}
230 235
231void ListEdit::fixTypes() 236void ListEdit::fixTypes()
232{ 237{
233 int i; 238 int i;
234 ColumnDef *pDef; 239 ColumnDef *pDef;
235 for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) { 240 for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) {
236 if( pDef->hasFlag(ColumnDef::typeUnique) ) 241 if( pDef->hasFlag(ColumnDef::typeUnique) )
237 fixTypes(i); 242 fixTypes(i);
238 } 243 }
239 _typeTable->sort(); 244 _typeTable->sort();
240} 245}
241 246
242 247
243// --- storeInList ------------------------------------------------------------ 248// --- storeInList ------------------------------------------------------------
244void ListEdit::storeInList(QStringList &lst) 249void ListEdit::storeInList(QStringList &lst)
245{ 250{
246 // delete old content 251 // delete old content
247 lst.clear(); 252 lst.clear();
248 253
249 // add new one 254 // add new one
250 fixTypes(); 255 fixTypes();
251 QListViewItem *itm=_typeTable->firstChild(); 256 QListViewItem *itm=_typeTable->firstChild();
252 while( itm ) { 257 while( itm ) {
253 int i=0; 258 int i=0;
254 QString sAdd; 259 QString sAdd;
255 ColumnDef *pDef; 260 ColumnDef *pDef;
256 for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) { 261 for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) {
257 if( i>=1 ) sAdd+=";"; 262 if( i>=1 ) sAdd+=";";
258 sAdd += itm->text(i); 263 sAdd += itm->text(i);
259 } 264 }
260 lst.append( sAdd ); 265 lst.append( sAdd );
261 itm=itm->nextSibling(); 266 itm=itm->nextSibling();
262 } 267 }
263} 268}
264 269
265 270
266// --- slotClicked ------------------------------------------------------------ 271// --- slotClicked ------------------------------------------------------------
267void ListEdit::slotClick(QListViewItem *itm, const QPoint &pnt, int col) 272void ListEdit::slotClick(QListViewItem *itm, const QPoint &pnt, int col)
268{ 273{
269 (void)pnt; // get rid of unused warning; 274 (void)pnt; // get rid of unused warning;
270 275
271 // save values 276 // save values
272 _currentItem=itm; 277 _currentItem=itm;
273 _currentColumn=col; 278 _currentColumn=col;
274 if( itm==NULL ) { 279 if( itm==NULL ) {
275 _typeEdit->setText(""); 280 _typeEdit->setText("");
276 _stack->raiseWidget(_typeEdit); 281 _stack->raiseWidget(_typeEdit);
277 return; 282 return;
278 } 283 }
279 284
280 // display value 285 // display value
281 if( _currentColumn<0 ) _currentColumn=0; 286 if( _currentColumn<0 ) _currentColumn=0;
282 ColumnDef *pDef=this->at(_currentColumn); 287 ColumnDef *pDef=this->at(_currentColumn);
283 if( pDef->isType(ColumnDef::typeString) ) { 288 if( pDef->isType(ColumnDef::typeString) ) {
284 _typeEdit->setText( _currentItem->text(_currentColumn) ); 289 _typeEdit->setText( _currentItem->text(_currentColumn) );
285 _stack->raiseWidget(_typeEdit); 290 _stack->raiseWidget(_typeEdit);
286 } else if( pDef->isType(ColumnDef::typeList) ){ 291 } else if( pDef->isType(ColumnDef::typeList) ){
287 _box->clear(); 292 _box->clear();
288 _box->insertStringList( pDef->getValueList() ); 293 _box->insertStringList( pDef->getValueList() );
289 QStringList::Iterator itr; 294 QStringList::Iterator itr;
290 int i=0; 295 int i=0;
291 for(itr=pDef->getValueList().begin(); itr!=pDef->getValueList().end(); itr++) { 296 for(itr=pDef->getValueList().begin(); itr!=pDef->getValueList().end(); itr++) {
292 if( (*itr)==_currentItem->text(_currentColumn) ) { 297 if( (*itr)==_currentItem->text(_currentColumn) ) {
293 _box->setCurrentItem(i); 298 _box->setCurrentItem(i);
294 i=-1; 299 i=-1;
295 break; 300 break;
296 } 301 }
297 i++; 302 i++;
298 } 303 }
299 if( i>=0 ) { 304 if( i>=0 ) {
300 _box->insertItem( _currentItem->text(_currentColumn) ); 305 _box->insertItem( _currentItem->text(_currentColumn) );
301 _box->setCurrentItem(i); 306 _box->setCurrentItem(i);
302 } 307 }
303 _stack->raiseWidget(_box); 308 _stack->raiseWidget(_box);
304 } else { 309 } else {
305 qDebug( "Unsupported column type for column %s", (const char *)pDef->getName() ); 310 odebug << "Unsupported column type for column " << (const char *)pDef->getName() << "" << oendl;
306 _typeEdit->setText(""); 311 _typeEdit->setText("");
307 _stack->raiseWidget(_typeEdit); 312 _stack->raiseWidget(_typeEdit);
308 } 313 }
309} 314}
310 315
311 316
312// --- addColumnDef ----------------------------------------------------------- 317// --- addColumnDef -----------------------------------------------------------
313void ListEdit::addColumnDef(ColumnDef *pDef) 318void ListEdit::addColumnDef(ColumnDef *pDef)
314{ 319{
315 _typeTable->addColumn( pDef->getName() ); 320 _typeTable->addColumn( pDef->getName() );
316 _vColumns.append(pDef); 321 _vColumns.append(pDef);
317} 322}
318 323
319// --- addData ---------------------------------------------------------------- 324// --- addData ----------------------------------------------------------------
320void ListEdit::addData(QStringList &lst) 325void ListEdit::addData(QStringList &lst)
321{ 326{
322 // run through list 327 // run through list
323 QStringList::Iterator itr; 328 QStringList::Iterator itr;
324 for(itr=lst.begin(); itr!=lst.end(); itr++) { 329 for(itr=lst.begin(); itr!=lst.end(); itr++) {
325 QStringList split=QStringList::split(";", *itr, true); 330 QStringList split=QStringList::split(";", *itr, true);
326 QStringList::Iterator entry; 331 QStringList::Iterator entry;
327 QString args[8]; 332 QString args[8];
328 int i=0; 333 int i=0;
329 for(entry=split.begin(); entry!=split.end() && i<8; entry++, i++) { 334 for(entry=split.begin(); entry!=split.end() && i<8; entry++, i++) {
330 args[i]= (*entry); 335 args[i]= (*entry);
331 } 336 }
332 while(i<8) { 337 while(i<8) {
333 args[i++]=""; 338 args[i++]="";
334 } 339 }
335 new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); 340 new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
336 } 341 }
337} 342}
338 343
339// --- slotActivated ---------------------------------------------------------- 344// --- slotActivated ----------------------------------------------------------
340void ListEdit::slotActivated(const QString &str) 345void ListEdit::slotActivated(const QString &str)
341{ 346{
342 if( _currentItem==NULL || _currentColumn<0 ) return; 347 if( _currentItem==NULL || _currentColumn<0 ) return;
343 _currentItem->setText(_currentColumn, str); 348 _currentItem->setText(_currentColumn, str);
344} 349}
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 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> 4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "tabledef.h" 29#include "tabledef.h"
30 30
31#include <opie2/odebug.h>
32using namespace Opie::Core;
31 33
32// --- ColumnDef -------------------------------------------------------------- 34// --- ColumnDef --------------------------------------------------------------
33ColumnDef::ColumnDef(const char *sName, ColumnType type, const char *sNewValue) 35ColumnDef::ColumnDef(const char *sName, ColumnType type, const char *sNewValue)
34{ 36{
35 _sName=sName; 37 _sName=sName;
36 _type=type; 38 _type=type;
37 _sNewValue=sNewValue; 39 _sNewValue=sNewValue;
38} 40}
39 41
40 42
41// --- addColumnValue --------------------------------------------------------- 43// --- addColumnValue ---------------------------------------------------------
42void ColumnDef::addColumnValue(const QString &sValue) 44void ColumnDef::addColumnValue(const QString &sValue)
43{ 45{
44 if( (_type & 0x00ffffff) !=typeList ) 46 if( (_type & 0x00ffffff) !=typeList )
45 qDebug("Column %s is not a list", (const char *)_sName); 47 odebug << "Column " << (const char *)_sName << " is not a list" << oendl;
46 else 48 else
47 _valueList.append(sValue); 49 _valueList.append(sValue);
48} 50}
49void ColumnDef::addColumnValue(const char *sValue) 51void ColumnDef::addColumnValue(const char *sValue)
50{ 52{
51 if( (_type & 0x00ffffff)!=typeList ) 53 if( (_type & 0x00ffffff)!=typeList )
52 qDebug("Column %s is not a list", (const char *)_sName); 54 odebug << "Column " << (const char *)_sName << " is not a list" << oendl;
53 else 55 else
54 _valueList.append(sValue); 56 _valueList.append(sValue);
55} 57}
56 58
57// --- TableDef --------------------------------------------------------------- 59// --- TableDef ---------------------------------------------------------------
58TableDef::TableDef(const char *sName) 60TableDef::TableDef(const char *sName)
59{ 61{
60 _sName=sName; 62 _sName=sName;
61 _vColumns.setAutoDelete(TRUE); 63 _vColumns.setAutoDelete(TRUE);
62} 64}
63 65
64 66
65// --- ~TableDef -------------------------------------------------------------- 67// --- ~TableDef --------------------------------------------------------------
66TableDef::~TableDef() 68TableDef::~TableDef()
67{ 69{
68} 70}
69 71
70// --- addColumnDef ----------------------------------------------------------- 72// --- addColumnDef -----------------------------------------------------------
71void TableDef::addColumnDef(ColumnDef *pDef) 73void TableDef::addColumnDef(ColumnDef *pDef)
72{ 74{
73 _vColumns.append(pDef); 75 _vColumns.append(pDef);
74} 76}
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 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> 4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "transaction.h" 29#include "transaction.h"
30#include "traninfo.h" 30#include "traninfo.h"
31#include "cfg.h" 31#include "cfg.h"
32#include "checkbook.h" 32#include "checkbook.h"
33 33
34/* OPIE */
35#include <opie2/odebug.h>
34#include <qpe/datebookmonth.h> 36#include <qpe/datebookmonth.h>
37using namespace Opie::Core;
35 38
39/* QT */
36#include <qbuttongroup.h> 40#include <qbuttongroup.h>
37#include <qcombobox.h> 41#include <qcombobox.h>
38#include <qlabel.h> 42#include <qlabel.h>
39#include <qlayout.h> 43#include <qlayout.h>
40#include <qlineedit.h> 44#include <qlineedit.h>
41#include <qmultilineedit.h> 45#include <qmultilineedit.h>
42#include <qradiobutton.h> 46#include <qradiobutton.h>
43#include <qwhatsthis.h> 47#include <qwhatsthis.h>
44 48
45Transaction::Transaction( QWidget *parent, bool bNew, const QString &acctname, 49Transaction::Transaction( QWidget *parent, bool bNew, const QString &acctname,
46 TranInfo *info, Cfg *pCfg ) 50 TranInfo *info, Cfg *pCfg )
47 : QDialog( parent, 0, TRUE, WStyle_ContextHelp ) 51 : QDialog( parent, 0, TRUE, WStyle_ContextHelp )
48{ 52{
49 QString tempstr = tr( "Transaction for " ); 53 QString tempstr = tr( "Transaction for " );
50 tempstr.append( acctname ); 54 tempstr.append( acctname );
51 setCaption( tempstr ); 55 setCaption( tempstr );
52 56
53 _bNew=bNew; 57 _bNew=bNew;
54 tran = info; 58 tran = info;
55 _pCfg=pCfg; 59 _pCfg=pCfg;
56 60
57 QVBoxLayout *vb = new QVBoxLayout( this ); 61 QVBoxLayout *vb = new QVBoxLayout( this );
58 62
59 QScrollView *sv = new QScrollView( this ); 63 QScrollView *sv = new QScrollView( this );
60 vb->addWidget( sv, 0, 0 ); 64 vb->addWidget( sv, 0, 0 );
61 sv->setResizePolicy( QScrollView::AutoOneFit ); 65 sv->setResizePolicy( QScrollView::AutoOneFit );
62 sv->setFrameStyle( QFrame::NoFrame ); 66 sv->setFrameStyle( QFrame::NoFrame );
63 67
64 QWidget *container = new QWidget( sv->viewport() ); 68 QWidget *container = new QWidget( sv->viewport() );
65 sv->addChild( container ); 69 sv->addChild( container );
66 70
67 QGridLayout *layout = new QGridLayout( container ); 71 QGridLayout *layout = new QGridLayout( container );
68 layout->setSpacing( 2 ); 72 layout->setSpacing( 2 );
69 layout->setMargin( 4 ); 73 layout->setMargin( 4 );
70 74
71 // Withdrawal/Deposit 75 // Withdrawal/Deposit
72 QButtonGroup *btngrp = new QButtonGroup( container ); 76 QButtonGroup *btngrp = new QButtonGroup( container );
73 btngrp->setColumnLayout(0, Qt::Vertical ); 77 btngrp->setColumnLayout(0, Qt::Vertical );
74 btngrp->layout()->setSpacing( 0 ); 78 btngrp->layout()->setSpacing( 0 );
75 btngrp->layout()->setMargin( 0 ); 79 btngrp->layout()->setMargin( 0 );
76 btngrp->setMaximumWidth( 220 ); 80 btngrp->setMaximumWidth( 220 );
77 QGridLayout *layout2 = new QGridLayout( btngrp->layout() ); 81 QGridLayout *layout2 = new QGridLayout( btngrp->layout() );
78 layout2->setSpacing( 2 ); 82 layout2->setSpacing( 2 );
79 layout2->setMargin( 2 ); 83 layout2->setMargin( 2 );
80 withBtn = new QRadioButton( tr( "Withdrawal" ), btngrp ); 84 withBtn = new QRadioButton( tr( "Withdrawal" ), btngrp );
81 QWhatsThis::add( withBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) ); 85 QWhatsThis::add( withBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) );
82 layout2->addWidget( withBtn, 0, 0 ); 86 layout2->addWidget( withBtn, 0, 0 );
83 connect( withBtn, SIGNAL( clicked() ), this, SLOT( slotWithdrawalClicked() ) ); 87 connect( withBtn, SIGNAL( clicked() ), this, SLOT( slotWithdrawalClicked() ) );
84 depBtn = new QRadioButton( tr( "Deposit" ), btngrp ); 88 depBtn = new QRadioButton( tr( "Deposit" ), btngrp );
85 QWhatsThis::add( depBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) ); 89 QWhatsThis::add( depBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) );
86 layout2->addWidget( depBtn, 0, 1 ); 90 layout2->addWidget( depBtn, 0, 1 );
87 btngrp->setMaximumSize( 320, withBtn->height() ); 91 btngrp->setMaximumSize( 320, withBtn->height() );
88 connect( depBtn, SIGNAL( clicked() ), this, SLOT( slotDepositClicked() ) ); 92 connect( depBtn, SIGNAL( clicked() ), this, SLOT( slotDepositClicked() ) );
89 layout->addMultiCellWidget( btngrp, 0, 0, 0, 3 ); 93 layout->addMultiCellWidget( btngrp, 0, 0, 0, 3 );
90 94
91 // Date 95 // Date
92 QLabel *label = new QLabel( tr( "Date:" ), container ); 96 QLabel *label = new QLabel( tr( "Date:" ), container );
93 QWhatsThis::add( label, tr( "Select date of transaction here." ) ); 97 QWhatsThis::add( label, tr( "Select date of transaction here." ) );
94 layout->addWidget( label, 1, 0 ); 98 layout->addWidget( label, 1, 0 );
95 dateBtn = new QPushButton( TimeString::shortDate( QDate::currentDate() ), 99 dateBtn = new QPushButton( TimeString::shortDate( QDate::currentDate() ),
96 container ); 100 container );
97 QWhatsThis::add( dateBtn, tr( "Select date of transaction here." ) ); 101 QWhatsThis::add( dateBtn, tr( "Select date of transaction here." ) );
98 QPopupMenu *m1 = new QPopupMenu( container ); 102 QPopupMenu *m1 = new QPopupMenu( container );
99 datePicker = new DateBookMonth( m1, 0, TRUE ); 103 datePicker = new DateBookMonth( m1, 0, TRUE );
100 m1->insertItem( datePicker ); 104 m1->insertItem( datePicker );
101 dateBtn->setPopup( m1 ); 105 dateBtn->setPopup( m1 );
102 connect( datePicker, SIGNAL( dateClicked(int,int,int) ), 106 connect( datePicker, SIGNAL( dateClicked(int,int,int) ),
103 this, SLOT( slotDateChanged(int,int,int) ) ); 107 this, SLOT( slotDateChanged(int,int,int) ) );
104 layout->addWidget( dateBtn, 1, 1 ); 108 layout->addWidget( dateBtn, 1, 1 );
105 109
106 // Check number 110 // Check number
107 label = new QLabel( tr( "Number:" ), container ); 111 label = new QLabel( tr( "Number:" ), container );
108 QWhatsThis::add( label, tr( "Enter check number here." ) ); 112 QWhatsThis::add( label, tr( "Enter check number here." ) );
109 layout->addWidget( label, 1, 2 ); 113 layout->addWidget( label, 1, 2 );
110 numEdit = new QLineEdit( container ); 114 numEdit = new QLineEdit( container );
111 QWhatsThis::add( numEdit, tr( "Enter check number here." ) ); 115 QWhatsThis::add( numEdit, tr( "Enter check number here." ) );
112 numEdit->setMaximumWidth( 40 ); 116 numEdit->setMaximumWidth( 40 );
113 layout->addWidget( numEdit, 1, 3 ); 117 layout->addWidget( numEdit, 1, 3 );
114 118
115 // Description 119 // Description
116 label = new QLabel( tr( "Description:" ), container ); 120 label = new QLabel( tr( "Description:" ), container );
117 QWhatsThis::add( label, tr( "Enter description of transaction here." ) ); 121 QWhatsThis::add( label, tr( "Enter description of transaction here." ) );
118 layout->addWidget( label, 2, 0 ); 122 layout->addWidget( label, 2, 0 );
119 _cbDesc=new QComboBox( true, container ); 123 _cbDesc=new QComboBox( true, container );
120 _cbDesc->insertStringList( _pCfg->getPayees() ); 124 _cbDesc->insertStringList( _pCfg->getPayees() );
121 QWhatsThis::add( _cbDesc, tr( "Enter description of transaction here." ) ); 125 QWhatsThis::add( _cbDesc, tr( "Enter description of transaction here." ) );
122 layout->addMultiCellWidget( _cbDesc, 2, 2, 1, 3 ); 126 layout->addMultiCellWidget( _cbDesc, 2, 2, 1, 3 );
123 connect( _cbDesc, SIGNAL( activated(const QString&) ), this, SLOT( slotActivated(const QString&) ) ); 127 connect( _cbDesc, SIGNAL( activated(const QString&) ), this, SLOT( slotActivated(const QString&) ) );
124 128
125 129
126 // Category 130 // Category
127 label = new QLabel( tr( "Category:" ), container ); 131 label = new QLabel( tr( "Category:" ), container );
128 QWhatsThis::add( label, tr( "Select transaction category here." ) ); 132 QWhatsThis::add( label, tr( "Select transaction category here." ) );
129 layout->addWidget( label, 3, 0 ); 133 layout->addWidget( label, 3, 0 );
130 catList = new QComboBox( container ); 134 catList = new QComboBox( container );
131 QWhatsThis::add( catList, tr( "Select transaction category here." ) ); 135 QWhatsThis::add( catList, tr( "Select transaction category here." ) );
@@ -239,99 +243,99 @@ void Transaction::initFromInfo(TranInfo *info, bool bPopulateOld)
239 noteEdit->setText( info->notes() ); 243 noteEdit->setText( info->notes() );
240 } 244 }
241 else 245 else
242 { 246 {
243 withBtn->setChecked( TRUE ); 247 withBtn->setChecked( TRUE );
244 } 248 }
245} 249}
246 250
247 251
248// --- ~Transaction ----------------------------------------------------------- 252// --- ~Transaction -----------------------------------------------------------
249Transaction::~Transaction() 253Transaction::~Transaction()
250{ 254{
251} 255}
252 256
253// --- accept ----------------------------------------------------------------- 257// --- accept -----------------------------------------------------------------
254void Transaction::accept() 258void Transaction::accept()
255{ 259{
256 tran->setDesc( _cbDesc->currentText() ); 260 tran->setDesc( _cbDesc->currentText() );
257 tran->setDate( datePicker->selectedDate() ); 261 tran->setDate( datePicker->selectedDate() );
258 tran->setWithdrawal( withBtn->isChecked() ); 262 tran->setWithdrawal( withBtn->isChecked() );
259 tran->setType( typeList->currentText() ); 263 tran->setType( typeList->currentText() );
260 tran->setCategory( catList->currentText() ); 264 tran->setCategory( catList->currentText() );
261 bool ok; 265 bool ok;
262 tran->setAmount( amtEdit->text().toFloat( &ok ) ); 266 tran->setAmount( amtEdit->text().toFloat( &ok ) );
263 tran->setFee( feeEdit->text().toFloat( &ok ) ); 267 tran->setFee( feeEdit->text().toFloat( &ok ) );
264 tran->setNumber( numEdit->text() ); 268 tran->setNumber( numEdit->text() );
265 tran->setNotes( noteEdit->text() ); 269 tran->setNotes( noteEdit->text() );
266 270
267 QDialog::accept(); 271 QDialog::accept();
268} 272}
269 273
270void Transaction::slotWithdrawalClicked() 274void Transaction::slotWithdrawalClicked()
271{ 275{
272 catList->clear(); 276 catList->clear();
273 CategoryList *pCatList=_pCfg->getCategoryList(); 277 CategoryList *pCatList=_pCfg->getCategoryList();
274 for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) { 278 for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) {
275 if( !pCat->isIncome() ) 279 if( !pCat->isIncome() )
276 catList->insertItem( pCat->getName() ); 280 catList->insertItem( pCat->getName() );
277 } 281 }
278 catList->setCurrentItem(0); 282 catList->setCurrentItem(0);
279 283
280 typeList->clear(); 284 typeList->clear();
281 typeList->insertItem( tr( "Debit Charge" ) ); 285 typeList->insertItem( tr( "Debit Charge" ) );
282 typeList->insertItem( tr( "Written Check" ) ); 286 typeList->insertItem( tr( "Written Check" ) );
283 typeList->insertItem( tr( "Transfer" ) ); 287 typeList->insertItem( tr( "Transfer" ) );
284 typeList->insertItem( tr( "Credit Card" ) ); 288 typeList->insertItem( tr( "Credit Card" ) );
285} 289}
286 290
287void Transaction::slotDepositClicked() 291void Transaction::slotDepositClicked()
288{ 292{
289 catList->clear(); 293 catList->clear();
290 CategoryList *pCatList=_pCfg->getCategoryList(); 294 CategoryList *pCatList=_pCfg->getCategoryList();
291 for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) { 295 for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) {
292 if( pCat->isIncome() ) 296 if( pCat->isIncome() )
293 catList->insertItem( pCat->getName() ); 297 catList->insertItem( pCat->getName() );
294 } 298 }
295 catList->setCurrentItem( 0 ); 299 catList->setCurrentItem( 0 );
296 300
297 typeList->clear(); 301 typeList->clear();
298 typeList->insertItem( tr( "Written Check" ) ); 302 typeList->insertItem( tr( "Written Check" ) );
299 typeList->insertItem( tr( "Automatic Payment" ) ); 303 typeList->insertItem( tr( "Automatic Payment" ) );
300 typeList->insertItem( tr( "Transfer" ) ); 304 typeList->insertItem( tr( "Transfer" ) );
301 typeList->insertItem( tr( "Cash" ) ); 305 typeList->insertItem( tr( "Cash" ) );
302} 306}
303 307
304// --- slotDateChanged -------------------------------------------------------- 308// --- slotDateChanged --------------------------------------------------------
305void Transaction::slotDateChanged( int y, int m, int d ) 309void Transaction::slotDateChanged( int y, int m, int d )
306{ 310{
307 QDate date; 311 QDate date;
308 date.setYMD( y, m, d ); 312 date.setYMD( y, m, d );
309 dateBtn->setText( TimeString::shortDate( date ) ); 313 dateBtn->setText( TimeString::shortDate( date ) );
310} 314}
311 315
312 316
313 317
314// --- slotActivated ---------------------------------------------------------- 318// --- slotActivated ----------------------------------------------------------
315// Search for the most recent transaction with this description/payee and 319// Search for the most recent transaction with this description/payee and
316// fill amount etc here, as long the new flag is set 320// fill amount etc here, as long the new flag is set
317void Transaction::slotActivated(const QString &arg ) 321void Transaction::slotActivated(const QString &arg )
318{ 322{
319 if( !_bNew ) return; 323 if( !_bNew ) return;
320 TranInfoList *pTl=((Checkbook *)parentWidget())->getTranList(); 324 TranInfoList *pTl=((Checkbook *)parentWidget())->getTranList();
321 if( pTl ) { 325 if( pTl ) {
322 TranInfo *pTi=pTl->findMostRecentByDesc( arg ); 326 TranInfo *pTi=pTl->findMostRecentByDesc( arg );
323 if( pTi ) { 327 if( pTi ) {
324 initFromInfo( pTi, true ); 328 initFromInfo( pTi, true );
325 amtEdit->setFocus(); 329 amtEdit->setFocus();
326 amtEdit->setSelection(0, amtEdit->text().length() ); 330 amtEdit->setSelection(0, amtEdit->text().length() );
327 amtEdit->setCursorPosition(0); 331 amtEdit->setCursorPosition(0);
328 } 332 }
329 } 333 }
330} 334}
331 335
332// slotNotNew ----------------------------------------------------------------- 336// slotNotNew -----------------------------------------------------------------
333void Transaction::slotNotNew() 337void Transaction::slotNotNew()
334{ 338{
335 qDebug("Not new"); 339 odebug << "Not new" << oendl;
336 _bNew=false; 340 _bNew=false;
337} 341}
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 @@
1CONFIG = qt warn_on quick-app 1CONFIG = qt warn_on quick-app
2HEADERS = mainwindow.h listviewconfdir.h listviewitemconffile.h listviewitemconfigentry.h editwidget.h listviewitemconf.h 2HEADERS = mainwindow.h listviewconfdir.h listviewitemconffile.h listviewitemconfigentry.h editwidget.h listviewitemconf.h
3SOURCES = main.cpp mainwindow.cpp listviewconfdir.cpp listviewitemconffile.cpp listviewitemconfigentry.cpp editwidget.cpp listviewitemconf.cpp 3SOURCES = main.cpp mainwindow.cpp listviewconfdir.cpp listviewitemconffile.cpp listviewitemconfigentry.cpp editwidget.cpp listviewitemconf.cpp
4INCLUDEPATH += $(OPIEDIR)/include 4INCLUDEPATH += $(OPIEDIR)/include
5DEPENDPATH += $(OPIEDIR)/include 5DEPENDPATH += $(OPIEDIR)/include
6INTERFACES = 6LIBS += -lqpe -lopiecore2
7LIBS += -lopiecore2
8TARGET = confedit 7TARGET = confedit
9 8
10!contains( platform, x11 ) { 9include ( $(OPIEDIR)/include.pro )
11
12 include ( $(OPIEDIR)/include.pro )
13 LIBS += -lqpe
14}
15
16contains( platform, x11 ) {
17 LIBS += -L$(OPIEDIR)/lib -Wl,-rpath,$(OPIEDIR)/lib
18}
19
20
21
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 @@
1 config CONFEDIT 1 config CONFEDIT
2 boolean "opie-confeditor (generic editor for all Opie settings)" 2 boolean "opie-confedit (generic editor for all Opie settings)"
3 default "y" 3 default "y"
4 depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE 4 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 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9 // (c) 2002 Patrick S. Vogtp <tille@handhelds.org> 9 // (c) 2002 Patrick S. Vogtp <tille@handhelds.org>
10 10
11#include "listviewconfdir.h" 11#include "listviewconfdir.h"
12#include "listviewitemconffile.h"
12 13
13#include <qmessagebox.h> 14/* OPIE */
15#include <opie2/odebug.h>
16using namespace Opie::Core;
14 17
15#include "listviewitemconffile.h" 18/* QT */
19#include <qmessagebox.h>
16 20
17ListViewConfDir::ListViewConfDir(QString settingsPath, QWidget *parent, const char *name ) 21ListViewConfDir::ListViewConfDir(QString settingsPath, QWidget *parent, const char *name )
18 : QListView(parent,name), confDir(settingsPath) 22 : QListView(parent,name), confDir(settingsPath)
19{ 23{
20 24
21 setRootIsDecorated( true ); 25 setRootIsDecorated( true );
22 addColumn(tr("Files")); 26 addColumn(tr("Files"));
23 27
24 if (!confDir.isReadable()) 28 if (!confDir.isReadable())
25 QMessageBox::critical(this,tr("Could not open"),tr("The directory ")+settingsPath+tr(" could not be opened."),1,0); 29 QMessageBox::critical(this,tr("Could not open"),tr("The directory ")+settingsPath+tr(" could not be opened."),1,0);
26 readConfFiles(); 30 readConfFiles();
27 31
28 connect( this, SIGNAL(expanded(QListViewItem*)), SLOT(expand(QListViewItem*))); 32 connect( this, SIGNAL(expanded(QListViewItem*)), SLOT(expand(QListViewItem*)));
29} 33}
30 34
31 35
32ListViewConfDir::~ListViewConfDir() 36ListViewConfDir::~ListViewConfDir()
33{ 37{
34} 38}
35 39
36void ListViewConfDir::readConfFiles() 40void ListViewConfDir::readConfFiles()
37{ 41{
38 42
39 confDir.setFilter( QDir::Files | QDir::NoSymLinks ); 43 confDir.setFilter( QDir::Files | QDir::NoSymLinks );
40 confDir.setSorting( QDir::Name ); 44 confDir.setSorting( QDir::Name );
41 confDir.setNameFilter("*.conf"); 45 confDir.setNameFilter("*.conf");
42 const QFileInfoList *list = confDir.entryInfoList(); 46 const QFileInfoList *list = confDir.entryInfoList();
43 QFileInfoListIterator it( *list ); 47 QFileInfoListIterator it( *list );
44 QFileInfo *fi; 48 QFileInfo *fi;
45 49
46 ListViewItemConfFile *fileEntry; 50 ListViewItemConfFile *fileEntry;
47 51
48 while ( (fi=it.current()) ) 52 while ( (fi=it.current()) )
49 { 53 {
50 qDebug( "opening: >%s<", fi->fileName().data() ); 54 odebug << "opening: >" << fi->fileName().data() << "<" << oendl;
51 fileEntry = new ListViewItemConfFile( fi, this ); 55 fileEntry = new ListViewItemConfFile( fi, this );
52 QListViewItem *dummy = new QListViewItem(fileEntry, "dummy"); 56 QListViewItem *dummy = new QListViewItem(fileEntry, "dummy");
53 ++it; 57 ++it;
54 } 58 }
55} 59}
56 60
57void ListViewConfDir::expand(QListViewItem *item) 61void ListViewConfDir::expand(QListViewItem *item)
58{ 62{
59 ((ListViewItemConf*)item)->expand(); 63 ((ListViewItemConf*)item)->expand();
60} 64}
61 65
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 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9// (c) 2002 Patrick S. Vogt <tille@handhelds.org> 9// (c) 2002 Patrick S. Vogt <tille@handhelds.org>
10 10
11#include "listviewitemconffile.h" 11#include "listviewitemconffile.h"
12#include "listviewitemconfigentry.h"
13
14/* OPIE */
15#include <opie2/odebug.h>
16using namespace Opie::Core;
17
18/* QT */
12#include <qmessagebox.h> 19#include <qmessagebox.h>
13#include <qtextstream.h> 20#include <qtextstream.h>
14#include "listviewitemconfigentry.h"
15 21
16#define tr QObject::tr 22#define tr QObject::tr
17 23
18ListViewItemConfFile::ListViewItemConfFile(QFileInfo *file, QListView *parent) 24ListViewItemConfFile::ListViewItemConfFile(QFileInfo *file, QListView *parent)
19 : ListViewItemConf(parent), _valid(false) 25 : ListViewItemConf(parent), _valid(false)
20{ 26{
21 confFileInfo = file; 27 confFileInfo = file;
22// parseFile(); 28 // parseFile();
23 displayText(); 29 displayText();
24} 30}
25 31
26ListViewItemConfFile::~ListViewItemConfFile() 32ListViewItemConfFile::~ListViewItemConfFile()
27{ 33{
28} 34}
29 35
30 36
31void ListViewItemConfFile::displayText() 37void ListViewItemConfFile::displayText()
32{ 38{
33 setText(0,(_changed?"*":"")+confFileInfo->fileName()); 39 setText(0,(_changed?"*":"")+confFileInfo->fileName());
34} 40}
35 41
36QString ListViewItemConfFile::fileName() 42QString ListViewItemConfFile::fileName()
37{ 43{
38 return confFileInfo->fileName(); 44 return confFileInfo->fileName();
39} 45}
40 46
41void ListViewItemConfFile::parseFile() 47void ListViewItemConfFile::parseFile()
42{ 48{
43 //qDebug("ListViewItemConfFile::parseFile BEGIN"); 49 //odebug << "ListViewItemConfFile::parseFile BEGIN" << oendl;
44 QFile confFile(confFileInfo->absFilePath()); 50 QFile confFile(confFileInfo->absFilePath());
45 if(! confFile.open(IO_ReadOnly)) 51 if(! confFile.open(IO_ReadOnly))
46 QMessageBox::critical(0,tr("Could not open"),tr("The file ")+confFileInfo->fileName()+tr(" could not be opened."),1,0); 52 QMessageBox::critical(0,tr("Could not open"),tr("The file ")+confFileInfo->fileName()+tr(" could not be opened."),1,0);
47 QTextStream t( &confFile ); 53 QTextStream t( &confFile );
48 QString s; 54 QString s;
49 QString group; 55 QString group;
50 ListViewItemConfigEntry *groupItem; 56 ListViewItemConfigEntry *groupItem;
51 ListViewItemConfigEntry *item; 57 ListViewItemConfigEntry *item;
52 while ( !t.atEnd() ) 58 while ( !t.atEnd() )
53 { 59 {
54 s = t.readLine().stripWhiteSpace(); 60 s = t.readLine().stripWhiteSpace();
55 //qDebug( "line: >%s<\n", s.latin1() ); 61 //odebug << "line: >" << s.latin1() << "<\n" << oendl;
56 if (s.contains("<?xml")) 62 if (s.contains("<?xml"))
57 { 63 {
58 _valid = false; 64 _valid = false;
59 break; 65 break;
60 }else 66 }else
61 if ( s[0] == '[' && s[s.length()-1] == ']' ) 67 if ( s[0] == '[' && s[s.length()-1] == ']' )
62 { 68 {
63 // qDebug("got group"+s); 69 // odebug << "got group"+s << oendl;
64 group = s.mid(1,s.length()-2); 70 group = s.mid(1,s.length()-2);
65 if (!groupItem) groupItem = new ListViewItemConfigEntry(this, tr("no group") ); 71 if (!groupItem) groupItem = new ListViewItemConfigEntry(this, tr("no group") );
66 groupItem = new ListViewItemConfigEntry(this, group ); 72 groupItem = new ListViewItemConfigEntry(this, group );
67 insertItem( groupItem ); 73 insertItem( groupItem );
68 } else 74 } else
69 if ( int pos = s.find('=') ) 75 if ( int pos = s.find('=') )
70 { 76 {
71// qDebug("got key"+s); 77// odebug << "got key"+s << oendl;
72 if (!groupItem) qDebug("PANIK NO GROUP! >%s<",group.latin1()); 78 if (!groupItem) odebug << "PANIK NO GROUP! >" << group.latin1() << "<" << oendl;
73 item = new ListViewItemConfigEntry(this, group, s ); 79 item = new ListViewItemConfigEntry(this, group, s );
74 groupItem->insertItem( item ); 80 groupItem->insertItem( item );
75 } 81 }
76 } 82 }
77 confFile.close(); 83 confFile.close();
78 setExpandable( _valid ); 84 setExpandable( _valid );
79 //qDebug("ListViewItemConfFile::parseFile END"); 85 //odebug << "ListViewItemConfFile::parseFile END" << oendl;
80} 86}
81 87
82 88
83void ListViewItemConfFile::remove() 89void ListViewItemConfFile::remove()
84{ 90{
85 QFile::remove(confFileInfo->absFilePath()); 91 QFile::remove(confFileInfo->absFilePath());
86 QFile::remove(backupFileName()); 92 QFile::remove(backupFileName());
87 delete this; 93 delete this;
88} 94}
89 95
90void ListViewItemConfFile::revert() 96void ListViewItemConfFile::revert()
91{ 97{
92 if (!_changed) 98 if (!_changed)
93 { 99 {
94 // read the backup file 100 // read the backup file
95 QFile conf(confFileInfo->absFilePath()); 101 QFile conf(confFileInfo->absFilePath());
96 QFile back(backupFileName()); 102 QFile back(backupFileName());
97 103
98 if (!back.open(IO_ReadOnly)) return; 104 if (!back.open(IO_ReadOnly)) return;
99 if (!conf.open(IO_WriteOnly)) return; 105 if (!conf.open(IO_WriteOnly)) return;
100 106
101 #define SIZE 124 107 #define SIZE 124
102 char buf[SIZE]; 108 char buf[SIZE];
103 while (int c = back.readBlock(buf, SIZE) ) conf.writeBlock(buf,c); 109 while (int c = back.readBlock(buf, SIZE) ) conf.writeBlock(buf,c);
104 conf.close(); 110 conf.close();
105 back.close(); 111 back.close();
106 } 112 }
107 parseFile(); 113 parseFile();
108 expand(); 114 expand();
109} 115}
110 116
111void ListViewItemConfFile::save() 117void ListViewItemConfFile::save()
112{ 118{
113 if (!_changed) return; 119 if (!_changed) return;
114 QFile conf(confFileInfo->absFilePath()); 120 QFile conf(confFileInfo->absFilePath());
115 QFile back(backupFileName()); 121 QFile back(backupFileName());
116 122
117 if (!conf.open(IO_ReadOnly)) return; 123 if (!conf.open(IO_ReadOnly)) return;
118 if (!back.open(IO_WriteOnly)) return; 124 if (!back.open(IO_WriteOnly)) return;
119 125
120 char buf[SIZE]; 126 char buf[SIZE];
121 while (int c = conf.readBlock(buf, SIZE) ) back.writeBlock(buf,c); 127 while (int c = conf.readBlock(buf, SIZE) ) back.writeBlock(buf,c);
122 conf.close(); 128 conf.close();
123 back.close(); 129 back.close();
124 130
125 131
126 if (!conf.open(IO_WriteOnly)) return; 132 if (!conf.open(IO_WriteOnly)) return;
127 QTextStream *t = new QTextStream( &conf ); 133 QTextStream *t = new QTextStream( &conf );
128 for (QListViewItem *it = firstChild(); it!=0;it = it->nextSibling()) 134 for (QListViewItem *it = firstChild(); it!=0;it = it->nextSibling())
129 { 135 {
130 ((ListViewItemConfigEntry*)it)->save(t); 136 ((ListViewItemConfigEntry*)it)->save(t);
131 } 137 }
132 conf.close(); 138 conf.close();
133 unchanged(); 139 unchanged();
134} 140}
135 141
136 142
137bool ListViewItemConfFile::revertable() 143bool ListViewItemConfFile::revertable()
138{ 144{
139 return _changed || QFile(backupFileName()).exists(); 145 return _changed || QFile(backupFileName()).exists();
140} 146}
141 147
142QString ListViewItemConfFile::backupFileName() 148QString ListViewItemConfFile::backupFileName()
143{ 149{
144 return confFileInfo->absFilePath()+"~"; 150 return confFileInfo->absFilePath()+"~";
145} 151}
146 152
147 153
148void ListViewItemConfFile::expand() 154void ListViewItemConfFile::expand()
149{ 155{
150 QListViewItem *subItem = firstChild(); 156 QListViewItem *subItem = firstChild();
151 QListViewItem *toDel; 157 QListViewItem *toDel;
152 while(subItem) 158 while(subItem)
153 { 159 {
154 toDel = subItem; 160 toDel = subItem;
155 subItem = subItem->nextSibling(); 161 subItem = subItem->nextSibling();
156 delete toDel; 162 delete toDel;
157 } 163 }
158 parseFile(); 164 parseFile();
159} 165}
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 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9 9
10// (c) 2002 Patrick S. Vogt <tille@handhelds.org> 10// (c) 2002 Patrick S. Vogt <tille@handhelds.org>
11 11
12 12
13#include "mainwindow.h" 13#include "mainwindow.h"
14#include "listviewconfdir.h"
15#include "listviewitemconfigentry.h"
14 16
17/* OPIE */
18#include <opie2/odebug.h>
19using namespace Opie::Core;
20
21/* QT */
15#include <qlabel.h> 22#include <qlabel.h>
16#include <qlayout.h> 23#include <qlayout.h>
17#include <qlineedit.h> 24#include <qlineedit.h>
18 25
19#include "listviewconfdir.h"
20#include "listviewitemconfigentry.h"
21
22
23MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) : 26MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) :
24 QMainWindow( parent, name, f ), _currentItem(0), _fileItem(0) 27 QMainWindow( parent, name, f ), _currentItem(0), _fileItem(0)
25{ 28{
26 setCaption( tr("Conf File Editor") ); 29 setCaption( tr("Conf File Editor") );
27 30
28 //setBaseSize( qApp->globalStrut() ); 31 //setBaseSize( qApp->globalStrut() );
29 setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) ); 32 setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) );
30 33
31 mainLayout = new QVBoxLayout( this ); 34 mainLayout = new QVBoxLayout( this );
32 mainLayout->setSpacing( 0 ); 35 mainLayout->setSpacing( 0 );
33 mainLayout->setMargin( 0 ); 36 mainLayout->setMargin( 0 );
34 37
35 38
36 qDebug("creating settingList"); 39 odebug << "creating settingList" << oendl;
37 settingList = new ListViewConfDir( QDir::homeDirPath() + "/Settings", this, "settingslist"); 40 settingList = new ListViewConfDir( QDir::homeDirPath() + "/Settings", this, "settingslist");
38 settingList->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) ); 41 settingList->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) );
39 mainLayout->addWidget( settingList, 0); 42 mainLayout->addWidget( settingList, 0);
40 43
41 qDebug("creating editor"); 44 odebug << "creating editor" << oendl;
42 editor = new EditWidget(this); 45 editor = new EditWidget(this);
43 editor->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Maximum));//, sizePolicy().hasHeightForWidth() ) ); 46 editor->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Maximum));//, sizePolicy().hasHeightForWidth() ) );
44 mainLayout->addWidget( editor, 1 ); 47 mainLayout->addWidget( editor, 1 );
45 editor->layoutType( ListViewItemConf::File ); 48 editor->layoutType( ListViewItemConf::File );
46 49
47 makeMenu(); 50 makeMenu();
48 51
49 connect(settingList, SIGNAL( pressed(QListViewItem*) ), 52 connect(settingList, SIGNAL( pressed(QListViewItem*) ),
50 this, SLOT(setCurrent(QListViewItem*))); 53 this, SLOT(setCurrent(QListViewItem*)));
51 connect( settingList, SIGNAL( clicked(QListViewItem*) ), 54 connect( settingList, SIGNAL( clicked(QListViewItem*) ),
52 this, SLOT( stopTimer(QListViewItem*) ) ); 55 this, SLOT( stopTimer(QListViewItem*) ) );
53 56
54 connect( editor->LineEditGroup, SIGNAL( textChanged(const QString&) ), 57 connect( editor->LineEditGroup, SIGNAL( textChanged(const QString&) ),
55 SLOT( groupChanged(const QString&) ) ); 58 SLOT( groupChanged(const QString&) ) );
56 connect( editor->LineEditKey, SIGNAL( textChanged(const QString&) ), 59 connect( editor->LineEditKey, SIGNAL( textChanged(const QString&) ),
57 SLOT( keyChanged(const QString&) ) ); 60 SLOT( keyChanged(const QString&) ) );
58 connect( editor->LineEditValue, SIGNAL( textChanged(const QString&) ), 61 connect( editor->LineEditValue, SIGNAL( textChanged(const QString&) ),
59 SLOT( valueChanged(const QString&) ) ); 62 SLOT( valueChanged(const QString&) ) );
60 63
61 setCurrent(0); 64 setCurrent(0);
62 editor->layoutType(EditWidget::File); 65 editor->layoutType(EditWidget::File);
63} 66}
64 67
65void MainWindow::makeMenu() 68void MainWindow::makeMenu()
66{ 69{
67 popupTimer = new QTimer(this); 70 popupTimer = new QTimer(this);
68 popupMenuFile = new QPopupMenu(this); 71 popupMenuFile = new QPopupMenu(this);
69 popupMenuEntry = new QPopupMenu(this); 72 popupMenuEntry = new QPopupMenu(this);
70 73
71 popupActionSave = new QAction( tr("Save"),QString::null, 0, this, 0 ); 74 popupActionSave = new QAction( tr("Save"),QString::null, 0, this, 0 );
72 popupActionSave->addTo( popupMenuFile ); 75 popupActionSave->addTo( popupMenuFile );
73 // popupActionSave->addTo( popupMenuEntry ); 76 // popupActionSave->addTo( popupMenuEntry );
74 connect( popupActionSave, SIGNAL( activated() ), 77 connect( popupActionSave, SIGNAL( activated() ),
75 this , SLOT( saveConfFile() ) ); 78 this , SLOT( saveConfFile() ) );
76 79
77 popupActionRevert = new QAction( tr("Revert"),QString::null, 0, this, 0 ); 80 popupActionRevert = new QAction( tr("Revert"),QString::null, 0, this, 0 );
78 popupActionRevert->addTo( popupMenuFile ); 81 popupActionRevert->addTo( popupMenuFile );
79 popupActionRevert->addTo( popupMenuEntry ); 82 popupActionRevert->addTo( popupMenuEntry );
80 connect( popupActionRevert, SIGNAL( activated() ), 83 connect( popupActionRevert, SIGNAL( activated() ),
81 this , SLOT( revertConfFile() ) ); 84 this , SLOT( revertConfFile() ) );
82 85
83 popupActionDelete = new QAction( tr("Delete"),QString::null, 0, this, 0 ); 86 popupActionDelete = new QAction( tr("Delete"),QString::null, 0, this, 0 );
84 popupActionDelete->addTo( popupMenuFile ); 87 popupActionDelete->addTo( popupMenuFile );
85 popupActionDelete->addTo( popupMenuEntry ); 88 popupActionDelete->addTo( popupMenuEntry );
86 connect( popupActionDelete, SIGNAL( activated() ), 89 connect( popupActionDelete, SIGNAL( activated() ),
87 this , SLOT( removeConfFile() ) ); 90 this , SLOT( removeConfFile() ) );
88 91
89 connect( popupTimer, SIGNAL(timeout()), 92 connect( popupTimer, SIGNAL(timeout()),
90 this, SLOT(showPopup()) ); 93 this, SLOT(showPopup()) );
91} 94}
92 95
93MainWindow::~MainWindow() 96MainWindow::~MainWindow()
94{ 97{
95} 98}
96 99
97 100
98 101
99void MainWindow::setCurrent(QListViewItem *item) 102void MainWindow::setCurrent(QListViewItem *item)
100{ 103{
101 //qDebug("MainWindow::setCurrent"); 104 //odebug << "MainWindow::setCurrent" << oendl;
102 if (!item) return; 105 if (!item) return;
103 _item = (ListViewItemConf*) item; 106 _item = (ListViewItemConf*) item;
104 if (!_item) return; 107 if (!_item) return;
105 popupTimer->start( 750, true ); 108 popupTimer->start( 750, true );
106 if (_item->getType() == ListViewItemConf::File) 109 if (_item->getType() == ListViewItemConf::File)
107 { 110 {
108 editor->layoutType(EditWidget::File); 111 editor->layoutType(EditWidget::File);
109 _currentItem=0; 112 _currentItem=0;
110 _fileItem = (ListViewItemConfFile*)item; 113 _fileItem = (ListViewItemConfFile*)item;
111 return; 114 return;
112 } 115 }
113 _fileItem = 0; 116 _fileItem = 0;
114 _currentItem = (ListViewItemConfigEntry*)item; 117 _currentItem = (ListViewItemConfigEntry*)item;
115 if (!_currentItem) return; 118 if (!_currentItem) return;
116 QString file = _currentItem->getFile(); 119 QString file = _currentItem->getFile();
117 QString group = _currentItem->getGroup(); 120 QString group = _currentItem->getGroup();
118 QString key = _currentItem->getKey(); 121 QString key = _currentItem->getKey();
119 QString val = _currentItem->getValue(); 122 QString val = _currentItem->getValue();
120 editor->TextFileName->setText(file); 123 editor->TextFileName->setText(file);
121 editor->LineEditGroup->setText(group); 124 editor->LineEditGroup->setText(group);
122 if (!key.isEmpty()) 125 if (!key.isEmpty())
123 { 126 {
124 editor->layoutType(EditWidget::Entry); 127 editor->layoutType(EditWidget::Entry);
125 editor->LineEditKey->setText(key); 128 editor->LineEditKey->setText(key);
126 editor->LineEditValue->setText(val); 129 editor->LineEditValue->setText(val);
127 }else{ 130 }else{
128 editor->layoutType(EditWidget::Group); 131 editor->layoutType(EditWidget::Group);
129 } 132 }
130} 133}
131 134
132 135
133void MainWindow::groupChanged(const QString &g) 136void MainWindow::groupChanged(const QString &g)
134{ 137{
135 if (!_currentItem) return; 138 if (!_currentItem) return;
136 _currentItem->setGroup(g); 139 _currentItem->setGroup(g);
137} 140}
138 141
139void MainWindow::keyChanged(const QString &k) 142void MainWindow::keyChanged(const QString &k)
140{ 143{
141 if (!_currentItem) return; 144 if (!_currentItem) return;
142 _currentItem->keyChanged(k); 145 _currentItem->keyChanged(k);
143} 146}
144 147
145void MainWindow::valueChanged(const QString &v) 148void MainWindow::valueChanged(const QString &v)
146{ 149{
147 if (!_currentItem) return; 150 if (!_currentItem) return;
148 _currentItem->valueChanged(v); 151 _currentItem->valueChanged(v);
149} 152}
150 153
151 154
152void MainWindow::stopTimer( QListViewItem* ) 155void MainWindow::stopTimer( QListViewItem* )
153{ 156{
154 popupTimer->stop(); 157 popupTimer->stop();
155} 158}
156 159
157void MainWindow::saveConfFile() 160void MainWindow::saveConfFile()
158{ 161{
159 if (!_fileItem) return; 162 if (!_fileItem) return;
160 _fileItem->save(); 163 _fileItem->save();
161} 164}
162 165
163void MainWindow::revertConfFile() 166void MainWindow::revertConfFile()
164{ 167{
165 if (!_item) return; 168 if (!_item) return;
166 _item->revert(); 169 _item->revert();
167} 170}
168 171
169void MainWindow::removeConfFile() 172void MainWindow::removeConfFile()
170{ 173{
171 if (!_item) return; 174 if (!_item) return;
172 _item->remove(); 175 _item->remove();
173} 176}
174 177
175void MainWindow::showPopup() 178void MainWindow::showPopup()
176{ 179{
177qDebug("showPopup"); 180odebug << "showPopup" << oendl;
178 if (!_item) return; 181 if (!_item) return;
179 popupActionRevert->setEnabled(_item->revertable()); 182 popupActionRevert->setEnabled(_item->revertable());
180 popupActionSave->setEnabled(_item->isChanged()); 183 popupActionSave->setEnabled(_item->isChanged());
181 if (_fileItem) 184 if (_fileItem)
182 { 185 {
183 popupActionSave->setEnabled(_fileItem->isChanged()); 186 popupActionSave->setEnabled(_fileItem->isChanged());
184 popupMenuFile->popup( QCursor::pos() ); 187 popupMenuFile->popup( QCursor::pos() );
185 }else if(_currentItem) 188 }else if(_currentItem)
186 { 189 {
187 popupMenuEntry->popup( QCursor::pos() ); 190 popupMenuEntry->popup( QCursor::pos() );
188 } 191 }
189} 192}
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 @@
1#include <qmessagebox.h>
2#include "cfgfile.h" 1#include "cfgfile.h"
3 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
7/* QT */
8#include <qmessagebox.h>
9
4// CfgEntry implementation 10// CfgEntry implementation
5CfgEntry::CfgEntry() { 11CfgEntry::CfgEntry() {
6} 12}
7 13
8CfgEntry::CfgEntry(const QString& f, const QString& l): 14CfgEntry::CfgEntry(const QString& f, const QString& l):
9 file(f), label(l) { 15 file(f), label(l) {
10} 16}
11 17
12const QString& CfgEntry::getFile() const { 18const QString& CfgEntry::getFile() const {
13 return file; 19 return file;
14} 20}
15 21
16void CfgEntry::setFile(const QString& f) { 22void CfgEntry::setFile(const QString& f) {
17 file = f; 23 file = f;
18} 24}
19 25
20const QString& CfgEntry::getLabel() const { 26const QString& CfgEntry::getLabel() const {
21 return label; 27 return label;
22} 28}
23 29
24void CfgEntry::setLabel(const QString& f) { 30void CfgEntry::setLabel(const QString& f) {
25 label = f; 31 label = f;
26} 32}
27 33
28// CfgFile implementation 34// CfgFile implementation
29CfgFile::CfgFile():ardelay(400), arperiod(80) { 35CfgFile::CfgFile():ardelay(400), arperiod(80) {
30} 36}
31 37
32CfgFile::~CfgFile() { 38CfgFile::~CfgFile() {
33} 39}
34 40
35QList<CfgEntry>& CfgFile::getEntries() { 41QList<CfgEntry>& CfgFile::getEntries() {
36 return entries; 42 return entries;
37} 43}
38 44
39bool CfgFile::replaceEntry(const QString& file, const QString& label, int index) { 45bool CfgFile::replaceEntry(const QString& file, const QString& label, int index) {
40 deleteEntry(file); 46 deleteEntry(file);
41 47
42 CfgEntry* entry = new CfgEntry(file, label); 48 CfgEntry* entry = new CfgEntry(file, label);
43 if (index >= 0) { 49 if (index >= 0) {
44 entries.insert(index, entry); 50 entries.insert(index, entry);
45 } else { 51 } else {
46 entries.append(entry); 52 entries.append(entry);
47 } 53 }
48 54
49 return true; 55 return true;
50} 56}
51 57
52bool CfgFile::deleteEntry(const QString& file) { 58bool CfgFile::deleteEntry(const QString& file) {
53 for(int i = 0; i < (int) entries.count(); i++) { 59 for(int i = 0; i < (int) entries.count(); i++) {
54 CfgEntry* entry = entries.at(i); 60 CfgEntry* entry = entries.at(i);
55 if (entry->getFile() == file) { 61 if (entry->getFile() == file) {
56 entries.remove(i); 62 entries.remove(i);
57 return true; 63 return true;
58 } 64 }
59 } 65 }
60 return false; 66 return false;
61} 67}
62 68
63int CfgFile::getAutorepeatDelay() const { 69int CfgFile::getAutorepeatDelay() const {
64 return ardelay; 70 return ardelay;
65} 71}
66 72
67void CfgFile::setAutorepeatDelay(int n) { 73void CfgFile::setAutorepeatDelay(int n) {
68 ardelay = n; 74 ardelay = n;
69} 75}
70 76
71int CfgFile::getAutorepeatPeriod() const { 77int CfgFile::getAutorepeatPeriod() const {
72 return arperiod; 78 return arperiod;
73} 79}
74 80
75void CfgFile::setAutorepeatPeriod(int n) { 81void CfgFile::setAutorepeatPeriod(int n) {
76 arperiod = n; 82 arperiod = n;
77} 83}
78 84
79// CfgParser implementation 85// CfgParser implementation
80CfgParser::CfgParser() { 86CfgParser::CfgParser() {
81} 87}
82 88
83bool CfgParser::load(QString file, CfgFile& cfg) { 89bool CfgParser::load(QString file, CfgFile& cfg) {
84 QFile f(file); 90 QFile f(file);
85 QXmlInputSource is(f); 91 QXmlInputSource is(f);
86 QXmlSimpleReader reader; 92 QXmlSimpleReader reader;
87 CfgHandler p(*this); 93 CfgHandler p(*this);
88 94
89 reader.setErrorHandler(this); 95 reader.setErrorHandler(this);
90 reader.setContentHandler(&p); 96 reader.setContentHandler(&p);
91 97
92 err = ""; 98 err = "";
93 ardelay = -1; 99 ardelay = -1;
94 arperiod = -1; 100 arperiod = -1;
95 reader.parse(is); 101 reader.parse(is);
96 102
97 if (!err.isEmpty()) { 103 if (!err.isEmpty()) {
98 qDebug(err); 104 odebug << err << oendl;
99 return false; 105 return false;
100 } 106 }
101 107
102 QMap<QString, QString>::Iterator fit, lit; 108 QMap<QString, QString>::Iterator fit, lit;
103 for(uint i = 0; i < includeList.count(); i++) { 109 for(uint i = 0; i < includeList.count(); i++) {
104 QString file = *includeList.at(i); 110 QString file = *includeList.at(i);
105 fit = includes.find(file); 111 fit = includes.find(file);
106 QString prefix = fit.data(); 112 QString prefix = fit.data();
107 QString label = ""; 113 QString label = "";
108 114
109 qDebug("include: file=" + fit.key() + ", prefix=" + fit.data()); 115 odebug << "include: file=" + fit.key() + ", prefix=" + fit.data() << oendl;
110 lit = labels.find(prefix+":*"); 116 lit = labels.find(prefix+":*");
111 if (lit != labels.end()) { 117 if (lit != labels.end()) {
112 label = lit.data(); 118 label = lit.data();
113 } 119 }
114 120
115 cfg.replaceEntry(file, label); 121 cfg.replaceEntry(file, label);
116 } 122 }
117 123
118 if (ardelay != -1) { 124 if (ardelay != -1) {
119 cfg.setAutorepeatDelay(ardelay); 125 cfg.setAutorepeatDelay(ardelay);
120 } 126 }
121 127
122 if (arperiod != -1) { 128 if (arperiod != -1) {
123 cfg.setAutorepeatPeriod(arperiod); 129 cfg.setAutorepeatPeriod(arperiod);
124 } 130 }
125 131
126 return true; 132 return true;
127} 133}
128 134
129bool CfgParser::save(QString file, CfgFile& cfg) { 135bool CfgParser::save(QString file, CfgFile& cfg) {
130 FILE* f = fopen((const char*) file.local8Bit(), "w"); 136 FILE* f = fopen((const char*) file.local8Bit(), "w");
131 137
132 fprintf(f, "<keymap autorepeat-delay=\"%d\" autorepeat-period=\"%d\" " 138 fprintf(f, "<keymap autorepeat-delay=\"%d\" autorepeat-period=\"%d\" "
133 "author=\"keyzcfg\">\n", cfg.getAutorepeatDelay(), 139 "author=\"keyzcfg\">\n", cfg.getAutorepeatDelay(),
134 cfg.getAutorepeatPeriod()); 140 cfg.getAutorepeatPeriod());
135 141
136 QList<CfgEntry>& entries = cfg.getEntries(); 142 QList<CfgEntry>& entries = cfg.getEntries();
137 int n; 143 int n;
138 144
139 for(n=0; n < (int) entries.count(); n++) { 145 for(n=0; n < (int) entries.count(); n++) {
140 CfgEntry* entry = entries.at(n); 146 CfgEntry* entry = entries.at(n);
141 QString l = entry->getLabel(); 147 QString l = entry->getLabel();
142 if (!l.isEmpty()) { 148 if (!l.isEmpty()) {
143 fprintf(f, "\t<label name=\"%s\" state=\"km%d:*\"/>\n", 149 fprintf(f, "\t<label name=\"%s\" state=\"km%d:*\"/>\n",
144 (const char*) l.utf8(), n); 150 (const char*) l.utf8(), n);
145 } 151 }
146 } 152 }
147 153
148 for(n=0; n < (int) entries.count(); n++) { 154 for(n=0; n < (int) entries.count(); n++) {
149 CfgEntry* entry = entries.at(n); 155 CfgEntry* entry = entries.at(n);
150 fprintf(f, "\t<include file=\"%s\" prefix=\"km%d\"/>\n", 156 fprintf(f, "\t<include file=\"%s\" prefix=\"km%d\"/>\n",
151 (const char*) entry->getFile().utf8(), n); 157 (const char*) entry->getFile().utf8(), n);
152 } 158 }
153 159
154 int k = n-1; 160 int k = n-1;
155 char* states[] = { "LShift", "LShift-Caps", "LShift-Num", 161 char* states[] = { "LShift", "LShift-Caps", "LShift-Num",
156 "LShift-Num-Caps", 0}; 162 "LShift-Num-Caps", 0};
157 163
158 for(n=0; n < (int) entries.count(); n++) { 164 for(n=0; n < (int) entries.count(); n++) {
159 QString nstate = "km" + QString::number(n+1); 165 QString nstate = "km" + QString::number(n+1);
160 if (n == k) { 166 if (n == k) {
161 nstate = "km" + QString::number(0); 167 nstate = "km" + QString::number(0);
162 } 168 }
163 169
164 for(int i = 0; states[i] != 0; i++) { 170 for(int i = 0; states[i] != 0; i++) {
165 fprintf(f, "\t<state name=\"km%d:%s\">\n", 171 fprintf(f, "\t<state name=\"km%d:%s\">\n",
166 n, states[i]); 172 n, states[i]);
167 fprintf(f, "\t\t<map keycode=\"Middle\" pressed=\"true\">\n"); 173 fprintf(f, "\t\t<map keycode=\"Middle\" pressed=\"true\">\n");
168 fprintf(f, "\t\t\t<next-state name=\"%s:%s\"/>\n", 174 fprintf(f, "\t\t\t<next-state name=\"%s:%s\"/>\n",
169 (const char*) nstate.utf8(), states[i]); 175 (const char*) nstate.utf8(), states[i]);
170 fprintf(f, "\t\t</map>\n\t</state>\n\n"); 176 fprintf(f, "\t\t</map>\n\t</state>\n\n");
171 } 177 }
172 } 178 }
173 179
174 fprintf(f, "\t<state name=\"km0:Normal\" default=\"true\"/>\n"); 180 fprintf(f, "\t<state name=\"km0:Normal\" default=\"true\"/>\n");
175 181
176 fprintf(f, "</keymap>"); 182 fprintf(f, "</keymap>");
177 fclose(f); 183 fclose(f);
178 return true; 184 return true;
179} 185}
180 186
181CfgParser::~CfgParser() { 187CfgParser::~CfgParser() {
182} 188}
183 189
184int CfgParser::getAutorepeatDelay() const { 190int CfgParser::getAutorepeatDelay() const {
185 return ardelay; 191 return ardelay;
186} 192}
187 193
188void CfgParser::setAutorepeatDelay(int n) { 194void CfgParser::setAutorepeatDelay(int n) {
189 ardelay = n; 195 ardelay = n;
190} 196}
191 197
192int CfgParser::getAutorepeatPeriod() const { 198int CfgParser::getAutorepeatPeriod() const {
193 return arperiod; 199 return arperiod;
194} 200}
195 201
196void CfgParser::setAutorepeatPeriod(int n) { 202void CfgParser::setAutorepeatPeriod(int n) {
197 arperiod = n; 203 arperiod = n;
198} 204}
199 205
200void CfgParser::addLabel(const QString& name, const QString& state) { 206void CfgParser::addLabel(const QString& name, const QString& state) {
201 labels.insert(state, name); 207 labels.insert(state, name);
202 labelList.append(&labels.find(state).data()); 208 labelList.append(&labels.find(state).data());
203} 209}
204 210
205void CfgParser::addFile(const QString& file, const QString& prefix) { 211void 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 @@
1 config KEYZCFG 1 config KEYZCFG
2 boolean "keyz-cfg (configuration tool for keyz applet)" 2 boolean "keyz-cfg (configuration tool for keyz applet)"
3 default "n" 3 default "n"
4 depends ( LIBQPE || LIBQPE-X11 ) 4 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 @@
1TEMPLATE = app 1TEMPLATE = app
2DESTDIR = $(OPIEDIR)/bin 2DESTDIR = $(OPIEDIR)/bin
3 CONFIG = qt warn_on 3 CONFIG = qt warn_on
4 HEADERS = zkb.h \ 4 HEADERS = zkb.h \
5 zkbcfg.h \ 5 zkbcfg.h \
6 zkbnames.h \ 6 zkbnames.h \
7 zkbxml.h \ 7 zkbxml.h \
8 cfgdlg.h \ 8 cfgdlg.h \
9 cfgfile.h 9 cfgfile.h
10 10
11 SOURCES = main.cpp \ 11 SOURCES = main.cpp \
12 cfgdlg.cpp \ 12 cfgdlg.cpp \
13 cfgfile.cpp \ 13 cfgfile.cpp \
14 zkb.cpp \ 14 zkb.cpp \
15 zkbcfg.cpp \ 15 zkbcfg.cpp \
16 zkbnames.cpp \ 16 zkbnames.cpp \
17 zkbxml.cpp 17 zkbxml.cpp
18 18
19INCLUDEPATH += $(OPIEDIR)/include 19INCLUDEPATH += $(OPIEDIR)/include
20DEPENDPATH += $(OPIEDIR)/include 20DEPENDPATH += $(OPIEDIR)/include
21 LIBS += -lqpe 21 LIBS += -lqpe -lopiecore2
22 TARGET = keyz-cfg 22 TARGET = keyz-cfg
23 23
24include ( $(OPIEDIR)/include.pro ) 24include ( $(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,
271 271
272 Action* action = currentState->get(keycode, isPress, true); 272 Action* action = currentState->get(keycode, isPress, true);
273 if (action==0 || !action->isDefined()) { 273 if (action==0 || !action->isDefined()) {
274 return true; 274 return true;
275 } 275 }
276 276
277 if (action->hasEvent()) { 277 if (action->hasEvent()) {
278 qDebug("filter:<<< unicode=%x, keycode=%x, modifiers=%x, " 278 qDebug("filter:<<< unicode=%x, keycode=%x, modifiers=%x, "
279 "ispressed=%x\n", action->getUnicode(), 279 "ispressed=%x\n", action->getUnicode(),
280 action->getKeycode(), action->getModifiers(), 280 action->getKeycode(), action->getModifiers(),
281 action->isPressed()); 281 action->isPressed());
282 282
283 QWSServer::sendKeyEvent(action->getUnicode(), 283 QWSServer::sendKeyEvent(action->getUnicode(),
284 action->getKeycode(), action->getModifiers(), 284 action->getKeycode(), action->getModifiers(),
285 action->isPressed(), false); 285 action->isPressed(), false);
286 } 286 }
287 287
288 if (action->isAutorepeat()) { 288 if (action->isAutorepeat()) {
289 autoRepeatAction = action; 289 autoRepeatAction = action;
290 repeater.start(repeatDelay, TRUE); 290 repeater.start(repeatDelay, TRUE);
291 } else { 291 } else {
292 autoRepeatAction = 0; 292 autoRepeatAction = 0;
293 } 293 }
294 294
295 State* nstate = action->getState(); 295 State* nstate = action->getState();
296 if (nstate != 0) { 296 if (nstate != 0) {
297 setCurrentState(nstate); 297 setCurrentState(nstate);
298 QString lbl = getCurrentLabel(); 298 QString lbl = getCurrentLabel();
299 if (!lbl.isEmpty()) { 299 if (!lbl.isEmpty()) {
300 emit stateChanged(lbl); 300 emit stateChanged(lbl);
301 } 301 }
302 } 302 }
303 303
304 304
305 return true; 305 return true;
306} 306}
307 307
308void Keymap::enable() { 308void Keymap::enable() {
309 enabled = true; 309 enabled = true;
310} 310}
311 311
312void Keymap::disable() { 312void Keymap::disable() {
313 enabled = false; 313 enabled = false;
314} 314}
315 315
316QStringList Keymap::listStates() { 316QStringList Keymap::listStates() {
317 QStringList ret; 317 QStringList ret;
318 318
319 QMap<QString, State*>::Iterator it; 319 QMap<QString, State*>::Iterator it;
320 for(it = states.begin(); it != states.end(); ++it) { 320 for(it = states.begin(); it != states.end(); ++it) {
321 ret.append(it.key()); 321 ret.append(it.key());
322 } 322 }
323 323
324 return ret; 324 return ret;
325} 325}
326 326
327State* Keymap::getStateByName(const QString& name) { 327State* Keymap::getStateByName(const QString& name) {
328 QMap<QString, State*>::Iterator it = states.find(name); 328 QMap<QString, State*>::Iterator it = states.find(name);
329 329
330 if (it == states.end()) { 330 if (it == states.end()) {
331 return 0; 331 return 0;
332 } 332 }
333 333
334 return it.data(); 334 return it.data();
335} 335}
336 336
337QStringList Keymap::listLabels() { 337QStringList Keymap::listLabels() {
338 QStringList ret; 338 QStringList ret;
339 339
340 for(uint i = 0; i < labelList.count(); i++) { 340 for(uint i = 0; i < labelList.count(); i++) {
341 ret.append(*labelList.at(i)); 341 ret.append(*labelList.at(i));
342 } 342 }
343 343
344 return ret; 344 return ret;
345} 345}
346 346
347State* Keymap::getStateByLabel(const QString& label) { 347State* Keymap::getStateByLabel(const QString& label) {
348 QMap<QString, QString>::Iterator lit = labels.find(label); 348 QMap<QString, QString>::Iterator lit = labels.find(label);
349 State* state = 0; 349 State* state = 0;
350 350
351 if (lit == labels.end()) { 351 if (lit == labels.end()) {
352 return 0; 352 return 0;
353 } 353 }
354 354
355 QString name = lit.data(); 355 QString name = lit.data();
356 356
357 int n = name.find(":*"); 357 int n = name.find(":*");
358 if (n>=0 && n==(int)(name.length()-2)) { 358 if (n>=0 && n==(int)(name.length()-2)) {
359 name=name.left(name.length() - 1); 359 name=name.left(name.length() - 1);
360 360
361 n = currentStateName.findRev(":"); 361 n = currentStateName.findRev(":");
362 if (n >= 0) { 362 if (n >= 0) {
363 name += currentStateName.mid(n+1); 363 name += currentStateName.mid(n+1);
364 } 364 }
365 } 365 }
366 366
367 //qDebug("look for: %s\n", (const char*) name.utf8()); 367 //odebug << "look for: " << (const char*) name.utf8() << "\n" << oendl;
368 QMap<QString, State*>::Iterator sit = states.find(name); 368 QMap<QString, State*>::Iterator sit = states.find(name);
369 if (sit != states.end()) { 369 if (sit != states.end()) {
370 state = sit.data(); 370 state = sit.data();
371 } 371 }
372 372
373 return state; 373 return state;
374} 374}
375 375
376bool Keymap::addState(const QString& name, State* state) { 376bool Keymap::addState(const QString& name, State* state) {
377 if (states.find(name) != states.end()) { 377 if (states.find(name) != states.end()) {
378 return false; 378 return false;
379 } 379 }
380 380
381 states.insert(name, state); 381 states.insert(name, state);
382 lsmapInSync = false; 382 lsmapInSync = false;
383 383
384 if (currentState == 0) { 384 if (currentState == 0) {
385 setCurrentState(state); 385 setCurrentState(state);
386 } 386 }
387 387
388 return true; 388 return true;
389} 389}
390 390
391State* Keymap::getCurrentState() const { 391State* Keymap::getCurrentState() const {
392 return currentState; 392 return currentState;
393} 393}
394 394
395QString Keymap::getCurrentLabel() { 395QString Keymap::getCurrentLabel() {
396 return currentLabel; 396 return currentLabel;
397} 397}
398 398
399bool Keymap::setCurrentState(State* state) { 399bool Keymap::setCurrentState(State* state) {
400 QMap<QString, State*>::Iterator it; 400 QMap<QString, State*>::Iterator it;
401 for(it = states.begin(); it != states.end(); ++it) { 401 for(it = states.begin(); it != states.end(); ++it) {
402 State* s = it.data(); 402 State* s = it.data();
403 if (s == state) { 403 if (s == state) {
404 currentState = s; 404 currentState = s;
405 currentStateName = it.key(); 405 currentStateName = it.key();
406 406
407 qDebug("state changed: %s\n", (const char*) 407 qDebug("state changed: %s\n", (const char*)
408 currentStateName.utf8()); 408 currentStateName.utf8());
409 409
410 if (!lsmapInSync) { 410 if (!lsmapInSync) {
411 generateLabelStateMaps(); 411 generateLabelStateMaps();
412 } 412 }
413 413
414 QMap<State*, QString>::Iterator tit; 414 QMap<State*, QString>::Iterator tit;
415 tit = stateLabelMap.find(state); 415 tit = stateLabelMap.find(state);
416 if (tit != stateLabelMap.end()) { 416 if (tit != stateLabelMap.end()) {
417 currentLabel = tit.data(); 417 currentLabel = tit.data();
418 } else { 418 } else {
419 // qDebug("no label for: " + currentStateName + "\n"); 419 // odebug << "no label for: " + currentStateName + "\n" << oendl;
420 currentLabel = ""; 420 currentLabel = "";
421 } 421 }
422 422
423 return true; 423 return true;
424 } 424 }
425 } 425 }
426 426
427 return false; 427 return false;
428} 428}
429 429
430bool Keymap::removeState(const QString& name, bool force) { 430bool Keymap::removeState(const QString& name, bool force) {
431 QMap<QString, State*>::Iterator it = states.find(name); 431 QMap<QString, State*>::Iterator it = states.find(name);
432 432
433 if (it == states.end()) { 433 if (it == states.end()) {
434 return false; 434 return false;
435 } 435 }
436 436
437 State* state = it.data(); 437 State* state = it.data();
438 QList<Action> acts = findStateUsage(state); 438 QList<Action> acts = findStateUsage(state);
439 439
440 if (!acts.isEmpty()) { 440 if (!acts.isEmpty()) {
441 if (!force) { 441 if (!force) {
442 return false; 442 return false;
443 } else { 443 } else {
444 for(Action* a = acts.first(); a != 0; a = acts.next()) { 444 for(Action* a = acts.first(); a != 0; a = acts.next()) {
445 a->setState(0); 445 a->setState(0);
446 } 446 }
447 } 447 }
448 } 448 }
449 449
450 if (state == currentState) { 450 if (state == currentState) {
451 if (states.begin() != states.end()) { 451 if (states.begin() != states.end()) {
452 setCurrentState(states.begin().data()); 452 setCurrentState(states.begin().data());
453 } 453 }
454 } 454 }
455 455
456 states.remove(it); 456 states.remove(it);
457 delete state; 457 delete state;
458 458
459 lsmapInSync = false; 459 lsmapInSync = false;
460 460
461 return true; 461 return true;
462} 462}
463 463
464void Keymap::autoRepeat() { 464void Keymap::autoRepeat() {
465 if (autoRepeatAction != 0) { 465 if (autoRepeatAction != 0) {
466 qDebug("filter:<<< unicode=%x, keycode=%x, modifiers=%x, " 466 qDebug("filter:<<< unicode=%x, keycode=%x, modifiers=%x, "
467 "ispressed=%x\n", autoRepeatAction->getUnicode(), 467 "ispressed=%x\n", autoRepeatAction->getUnicode(),
468 autoRepeatAction->getKeycode(), 468 autoRepeatAction->getKeycode(),
469 autoRepeatAction->getModifiers(), 469 autoRepeatAction->getModifiers(),
470 autoRepeatAction->isPressed()); 470 autoRepeatAction->isPressed());
471 471
472 QWSServer::sendKeyEvent(autoRepeatAction->getUnicode(), 472 QWSServer::sendKeyEvent(autoRepeatAction->getUnicode(),
473 autoRepeatAction->getKeycode(), 473 autoRepeatAction->getKeycode(),
474 autoRepeatAction->getModifiers(), 474 autoRepeatAction->getModifiers(),
475 autoRepeatAction->isPressed(), true); 475 autoRepeatAction->isPressed(), true);
476 } 476 }
477 477
478 repeater.start(repeatPeriod, TRUE); 478 repeater.start(repeatPeriod, TRUE);
479} 479}
480 480
481bool Keymap::addLabel(const QString& label, const QString& state, int index) { 481bool Keymap::addLabel(const QString& label, const QString& state, int index) {
482 if (labels.find(label) != labels.end()) { 482 if (labels.find(label) != labels.end()) {
483 return false; 483 return false;
484 } 484 }
485 485
486 labels.insert(label, state); 486 labels.insert(label, state);
487 const QString& l = labels.find(label).key(); 487 const QString& l = labels.find(label).key();
488 if (index == -1) { 488 if (index == -1) {
489 labelList.append(l); 489 labelList.append(l);
490 } else { 490 } else {
491 labelList.insert(labelList.at(index), l); 491 labelList.insert(labelList.at(index), l);
492 } 492 }
493 493
494 lsmapInSync = false; 494 lsmapInSync = false;
495 495
496 return true; 496 return true;
497} 497}
498 498
499bool Keymap::removeLabel(const QString& label) { 499bool Keymap::removeLabel(const QString& label) {
500 500
501 if (labels.find(label) == labels.end()) { 501 if (labels.find(label) == labels.end()) {
502 return false; 502 return false;
503 } 503 }
504 504
505 labels.remove(label); 505 labels.remove(label);
506 labelList.remove(label); 506 labelList.remove(label);
507 lsmapInSync = false; 507 lsmapInSync = false;
508 508
509 if (label == currentLabel) { 509 if (label == currentLabel) {
510 currentLabel = ""; 510 currentLabel = "";
511 } 511 }
512 512
513 return true; 513 return true;
514} 514}
515 515
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 @@
1#include <qfileinfo.h>
2
3#include "zkbcfg.h" 1#include "zkbcfg.h"
4 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
7/* QT */
8#include <qfileinfo.h>
5 9
6// Implementation of XkbConfig class 10// Implementation of XkbConfig class
7ZkbConfig::ZkbConfig(const QString& dir):path(dir) { 11ZkbConfig::ZkbConfig(const QString& dir):path(dir) {
8} 12}
9 13
10ZkbConfig::~ZkbConfig() { 14ZkbConfig::~ZkbConfig() {
11} 15}
12 16
13bool ZkbConfig::load(const QString& file, Keymap& keymap, const QString& prefix) { 17bool ZkbConfig::load(const QString& file, Keymap& keymap, const QString& prefix) {
14 bool ret; 18 bool ret;
15 QFile f(path+"/"+file); 19 QFile f(path+"/"+file);
16 QFileInfo fi(f); 20 QFileInfo fi(f);
17 21
18 qDebug("start loading file=%s\n", (const char*) file.utf8()); 22 odebug << "start loading file=" << (const char*) file.utf8() << "\n" << oendl;
19 if (includedFiles.find(fi.absFilePath()) != includedFiles.end()) { 23 if (includedFiles.find(fi.absFilePath()) != includedFiles.end()) {
20 return false; 24 return false;
21 } 25 }
22 26
23 includedFiles.insert(fi.absFilePath(), 1); 27 includedFiles.insert(fi.absFilePath(), 1);
24 QXmlInputSource is(f); 28 QXmlInputSource is(f);
25 QXmlSimpleReader reader; 29 QXmlSimpleReader reader;
26 ZkbHandler h(*this, keymap, prefix); 30 ZkbHandler h(*this, keymap, prefix);
27 31
28 reader.setContentHandler(&h); 32 reader.setContentHandler(&h);
29 reader.setErrorHandler(this); 33 reader.setErrorHandler(this);
30 ret = reader.parse(is); 34 ret = reader.parse(is);
31 includedFiles.remove(fi.absFilePath()); 35 includedFiles.remove(fi.absFilePath());
32 36
33 qDebug("end loading file=%s : status=%s\n", (const char*) file.utf8(), 37 odebug << "end loading file=" << file.utf8() << ": status=" << err.utf8() << oendl;
34 (const char*) err.utf8());
35 return ret; 38 return ret;
36} 39}
37 40
38bool ZkbConfig::warning(const QXmlParseException& e) { 41bool ZkbConfig::warning(const QXmlParseException& e) {
39 QString tmp; 42 QString tmp;
40 43
41 tmp.sprintf("%d: warning: %s\n", e.lineNumber(), 44 tmp.sprintf("%d: warning: %s\n", e.lineNumber(),
42 (const char*) e.message().utf8()); 45 (const char*) e.message().utf8());
43 46
44 err += tmp; 47 err += tmp;
45 48
46 return true; 49 return true;
47} 50}
48 51
49bool ZkbConfig::error(const QXmlParseException& e) { 52bool ZkbConfig::error(const QXmlParseException& e) {
50 QString tmp; 53 QString tmp;
51 54
52 tmp.sprintf("%d: error: %s\n", e.lineNumber(), 55 tmp.sprintf("%d: error: %s\n", e.lineNumber(),
53 (const char*) e.message().utf8()); 56 (const char*) e.message().utf8());
54 57
55 err += tmp; 58 err += tmp;
56 59
57 return true; 60 return true;
58} 61}
59 62
60bool ZkbConfig::fatalError(const QXmlParseException& e) { 63bool ZkbConfig::fatalError(const QXmlParseException& e) {
61 QString tmp; 64 QString tmp;
62 65
63 tmp.sprintf("%d: fatal error: %s\n", e.lineNumber(), 66 tmp.sprintf("%d: fatal error: %s\n", e.lineNumber(),
64 (const char*) e.message().utf8()); 67 (const char*) e.message().utf8());
65 68
66 err += tmp; 69 err += tmp;
67 70
68 return false; 71 return false;
69} 72}
70 73
71QString ZkbConfig::errorString() { 74QString ZkbConfig::errorString() {
72 return err; 75 return err;
73} 76}
74 77
75// Implementation of ZkbHandler 78// Implementation of ZkbHandler
76ZkbHandler::ZkbHandler(ZkbConfig& z, Keymap& k, const QString& p):zkc(z), keymap(k), 79ZkbHandler::ZkbHandler(ZkbConfig& z, Keymap& k, const QString& p):zkc(z), keymap(k),
77 prefix(p), ardelay(-1), arperiod(-1), currentState(0), currentAction(0) { 80 prefix(p), ardelay(-1), arperiod(-1), currentState(0), currentAction(0) {
78} 81}
79 82
80ZkbHandler::~ZkbHandler() { 83ZkbHandler::~ZkbHandler() {
81} 84}
82 85
83bool ZkbHandler::startKeymapElement(int ard, int arp, const QString&) { 86bool ZkbHandler::startKeymapElement(int ard, int arp, const QString&) {
84 ardelay = ard; 87 ardelay = ard;
85 arperiod = arp; 88 arperiod = arp;
86 89
87 return true; 90 return true;
88} 91}
89 92
90bool ZkbHandler::startIncludeElement(const QString& file, 93bool ZkbHandler::startIncludeElement(const QString& file,
91 const QString& pref) { 94 const QString& pref) {
92 95
93 QString p = prefix; 96 QString p = prefix;
94 97
95 if (!pref.isNull()) { 98 if (!pref.isNull()) {
96 p += pref + ":"; 99 p += pref + ":";
97 } 100 }
98 101
99 102
100 bool ret = zkc.load(file, keymap, p); 103 bool ret = zkc.load(file, keymap, p);
101 if (!ret) { 104 if (!ret) {
102 setError("Error including file: " + file); 105 setError("Error including file: " + file);
103 } 106 }
104 107
105 return ret; 108 return ret;
106} 109}
107 110
108bool ZkbHandler::startLabelElement(const QString& label, 111bool ZkbHandler::startLabelElement(const QString& label,
109 const QString& state) { 112 const QString& state) {
110 113
111 if (!keymap.addLabel(label, prefix + state)) { 114 if (!keymap.addLabel(label, prefix + state)) {
112 err = "label " + label + " already defined"; 115 err = "label " + label + " already defined";
113 return false; 116 return false;
114 } 117 }
115 118
116 return true; 119 return true;
117} 120}
118 121
119bool ZkbHandler::startStateElement(const QString& name, 122bool ZkbHandler::startStateElement(const QString& name,
120 const QString& parentName, bool dflt) { 123 const QString& parentName, bool dflt) {
121 124
122 currentStateName = prefix + name; 125 currentStateName = prefix + name;
123 currentState = keymap.getStateByName(currentStateName); 126 currentState = keymap.getStateByName(currentStateName);
124 127
125 //qDebug("state name=%s\n", (const char*) currentStateName.utf8()); 128 //odebug << "state name=" << (const char*) currentStateName.utf8() << "\n" << oendl;
126 129
127 State* parent = 0; 130 State* parent = 0;
128 if (!parentName.isEmpty()) { 131 if (!parentName.isEmpty()) {
129 QString pn = prefix + parentName; 132 QString pn = prefix + parentName;
130 parent = keymap.getStateByName(pn); 133 parent = keymap.getStateByName(pn);
131 if (parent == 0) { 134 if (parent == 0) {
132 err = currentStateName + 135 err = currentStateName +
133 ": undefined parent state: " + pn; 136 ": undefined parent state: " + pn;
134 return false; 137 return false;
135 } 138 }
136 } 139 }
137 140
138 if (currentState == 0) { 141 if (currentState == 0) {
139 currentState = new State(parent); 142 currentState = new State(parent);
140 keymap.addState(currentStateName, currentState); 143 keymap.addState(currentStateName, currentState);
141 } else { 144 } else {
142 if (parent!=0) { 145 if (parent!=0) {
143 currentState->setParent(parent); 146 currentState->setParent(parent);
144 } 147 }
145 } 148 }
146 149
147 if (dflt) { 150 if (dflt) {
148 keymap.setCurrentState(currentState); 151 keymap.setCurrentState(currentState);
149 } 152 }
150 153
151 return true; 154 return true;
152} 155}
153 156
154bool ZkbHandler::startMapElement(int keycode, bool pressed) { 157bool ZkbHandler::startMapElement(int keycode, bool pressed) {
155 currentAction = currentState->get(keycode, pressed); 158 currentAction = currentState->get(keycode, pressed);
156 if (currentAction == 0) { 159 if (currentAction == 0) {
157 setError("keycode " + QString::number(keycode) + " not supported"); 160 setError("keycode " + QString::number(keycode) + " not supported");
158 return false; 161 return false;
159 } 162 }
160 163
161 currentAction->setEvent(false); 164 currentAction->setEvent(false);
162 currentAction->setState(0); 165 currentAction->setState(0);
163 166
164 return true; 167 return true;
165} 168}
166 169
167bool ZkbHandler::startEventElement(int keycode, int unicode, int modifiers, 170bool ZkbHandler::startEventElement(int keycode, int unicode, int modifiers,
168 bool pressed, bool autorepeat) { 171 bool pressed, bool autorepeat) {
169 172
170 currentAction->setEvent(true); 173 currentAction->setEvent(true);
171 currentAction->setKeycode(keycode); 174 currentAction->setKeycode(keycode);
172 currentAction->setUnicode(unicode); 175 currentAction->setUnicode(unicode);
173 currentAction->setModifiers(modifiers); 176 currentAction->setModifiers(modifiers);
174 currentAction->setPressed(pressed); 177 currentAction->setPressed(pressed);
175 currentAction->setAutorepeat(autorepeat); 178 currentAction->setAutorepeat(autorepeat);
176 179
177 return true; 180 return true;
178} 181}
179 182
180bool ZkbHandler::startNextStateElement(const QString& state) { 183bool ZkbHandler::startNextStateElement(const QString& state) {
181 State* s = keymap.getStateByName(prefix + state); 184 State* s = keymap.getStateByName(prefix + state);
182 if (s == 0) { 185 if (s == 0) {
183 setError("undefine state: " + prefix + state); 186 setError("undefine state: " + prefix + state);
184 return false; 187 return false;
185 } 188 }
186 189
187 currentAction->setState(s); 190 currentAction->setState(s);
188 return true; 191 return true;
189} 192}
190 193
191 194
192bool ZkbHandler::endKeymapElement() { 195bool ZkbHandler::endKeymapElement() {
193 if (ardelay > 0) { 196 if (ardelay > 0) {
194 keymap.setAutorepeatDelay(ardelay); 197 keymap.setAutorepeatDelay(ardelay);
195 } 198 }
196 199
197 if (arperiod > 0) { 200 if (arperiod > 0) {
198 keymap.setAutorepeatPeriod(arperiod); 201 keymap.setAutorepeatPeriod(arperiod);
199 } 202 }
200 203
201 return true; 204 return true;
202} 205}
203 206
204bool ZkbHandler::endIncludeElement() { 207bool ZkbHandler::endIncludeElement() {
205 return true; 208 return true;
206} 209}
207 210
208bool ZkbHandler::endLabelElement() { 211bool ZkbHandler::endLabelElement() {
209 return true; 212 return true;
210} 213}
211 214
212bool ZkbHandler::endStateElement() { 215bool ZkbHandler::endStateElement() {
213 currentState = 0; 216 currentState = 0;
214 return true; 217 return true;
215} 218}
216 219
217bool ZkbHandler::endMapElement() { 220bool ZkbHandler::endMapElement() {
218 currentAction = 0; 221 currentAction = 0;
219 return true; 222 return true;
220} 223}
221 224
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 @@
1/**************************************************************************** 1/****************************************************************************
2** 2**
3** Created: Sat Jul 20 08:10:53 2002 3** Created: Sat Jul 20 08:10:53 2002
4** by: L.J. Potter <ljp@llornkcor.com> 4** by: L.J. Potter <ljp@llornkcor.com>
5** copyright : (C) 2002 by ljp 5** copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12 12
13#include "bartender.h" 13#include "bartender.h"
14#include "showdrinks.h" 14#include "showdrinks.h"
15#include "inputDialog.h" 15#include "inputDialog.h"
16#include "searchresults.h" 16#include "searchresults.h"
17#include "bac.h" 17#include "bac.h"
18 18
19#include <qtoolbar.h> 19/* OPIE */
20#include <qmenubar.h> 20#include <opie2/odebug.h>
21//#include <opie2/colorpopupmenu.h>
22#include <qpe/qpeapplication.h> 21#include <qpe/qpeapplication.h>
23#include <qpe/resource.h> 22#include <qpe/resource.h>
23using namespace Opie::Core;
24 24
25/* QT */
25#include <qlineedit.h> 26#include <qlineedit.h>
26#include <qdir.h> 27#include <qdir.h>
27#include <qpushbutton.h> 28#include <qpushbutton.h>
28#include <qlistbox.h> 29#include <qlistbox.h>
29#include <qmultilineedit.h> 30#include <qmultilineedit.h>
30#include <qmessagebox.h> 31#include <qmessagebox.h>
31#include <qtextstream.h> 32#include <qtextstream.h>
32#include <qaction.h> 33#include <qaction.h>
33#include <qheader.h> 34#include <qheader.h>
34#include <qlistview.h> 35#include <qlistview.h>
35#include <qlayout.h> 36#include <qlayout.h>
37#include <qtoolbar.h>
38#include <qmenubar.h>
36 39
40/* STD */
37#include <fcntl.h> 41#include <fcntl.h>
38#include <unistd.h> 42#include <unistd.h>
39#include <stdlib.h> 43#include <stdlib.h>
40#include <stdio.h> 44#include <stdio.h>
41#include <errno.h> 45#include <errno.h>
42 46
43
44Bartender::Bartender( QWidget* parent, const char* name, WFlags fl ) 47Bartender::Bartender( QWidget* parent, const char* name, WFlags fl )
45 : QMainWindow( parent, name, fl ) { 48 : QMainWindow( parent, name, fl ) {
46 if ( !name ) 49 if ( !name )
47 setName( "Bartender" ); 50 setName( "Bartender" );
48 QGridLayout *layout = new QGridLayout( this ); 51 QGridLayout *layout = new QGridLayout( this );
49 layout->setSpacing( 2); 52 layout->setSpacing( 2);
50 layout->setMargin( 2); 53 layout->setMargin( 2);
51 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 54 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
52 55
53 setCaption( tr( "Bartender" ) ); 56 setCaption( tr( "Bartender" ) );
54 57
55 ToolBar1 = new QToolBar( this, "ToolBar1" ); 58 ToolBar1 = new QToolBar( this, "ToolBar1" );
56 ToolBar1->setFixedHeight(22); 59 ToolBar1->setFixedHeight(22);
57 layout->addMultiCellWidget( ToolBar1, 0, 0, 0, 4 ); 60 layout->addMultiCellWidget( ToolBar1, 0, 0, 0, 4 );
58 61
59 QMenuBar *menuBar = new QMenuBar( ToolBar1 ); 62 QMenuBar *menuBar = new QMenuBar( ToolBar1 );
60 QPopupMenu *fileMenu; 63 QPopupMenu *fileMenu;
61 fileMenu = new QPopupMenu( this); 64 fileMenu = new QPopupMenu( this);
62 menuBar->insertItem( tr("File"), fileMenu ); 65 menuBar->insertItem( tr("File"), fileMenu );
63 66
64 fileMenu->insertItem(tr("New Drink")); 67 fileMenu->insertItem(tr("New Drink"));
65 fileMenu->insertItem(tr("Open Drink")); 68 fileMenu->insertItem(tr("Open Drink"));
66 fileMenu->insertItem(tr("Find by Drink Name")); 69 fileMenu->insertItem(tr("Find by Drink Name"));
67 fileMenu->insertItem(tr("Find by Alcohol")); 70 fileMenu->insertItem(tr("Find by Alcohol"));
68 71
69 QPopupMenu *editMenu; 72 QPopupMenu *editMenu;
70 editMenu = new QPopupMenu( this); 73 editMenu = new QPopupMenu( this);
71 menuBar->insertItem( tr("Edit"), editMenu ); 74 menuBar->insertItem( tr("Edit"), editMenu );
72 editMenu->insertItem(tr("edit")); 75 editMenu->insertItem(tr("edit"));
73 76
74 connect( fileMenu, SIGNAL( activated(int) ), this, SLOT( fileMenuActivated(int) )); 77 connect( fileMenu, SIGNAL( activated(int) ), this, SLOT( fileMenuActivated(int) ));
75 connect( editMenu, SIGNAL( activated(int) ), this, SLOT( editMenuActivated(int) )); 78 connect( editMenu, SIGNAL( activated(int) ), this, SLOT( editMenuActivated(int) ));
76 79
77 80
78 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), "New", 0, this, 0 ); 81 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), "New", 0, this, 0 );
79 connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); 82 connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) );
80 a->addTo( ToolBar1 ); 83 a->addTo( ToolBar1 );
81 84
82 a = new QAction( tr( "Open" ), Resource::loadPixmap( "bartender/bartender_sm" ), "open", 0, this, 0 ); 85 a = new QAction( tr( "Open" ), Resource::loadPixmap( "bartender/bartender_sm" ), "open", 0, this, 0 );
83 connect( a, SIGNAL( activated() ), this, SLOT( openCurrentDrink() ) ); 86 connect( a, SIGNAL( activated() ), this, SLOT( openCurrentDrink() ) );
84 a->addTo( ToolBar1 ); 87 a->addTo( ToolBar1 );
85 88
86 a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), "Find", 0, this, 0 ); 89 a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), "Find", 0, this, 0 );
87 connect( a, SIGNAL( activated() ), this, SLOT( askSearch() ) ); 90 connect( a, SIGNAL( activated() ), this, SLOT( askSearch() ) );
88 a->addTo( ToolBar1 ); 91 a->addTo( ToolBar1 );
89 92
90 a = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ),"Edit", 0, this, 0 ); 93 a = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ),"Edit", 0, this, 0 );
91 connect( a, SIGNAL( activated() ), this, SLOT( doEdit() ) ); 94 connect( a, SIGNAL( activated() ), this, SLOT( doEdit() ) );
92 a->addTo( ToolBar1 ); 95 a->addTo( ToolBar1 );
93 96
94 QPushButton *t; 97 QPushButton *t;
95 t= new QPushButton( "BAC", ToolBar1, "bacButtin"); 98 t= new QPushButton( "BAC", ToolBar1, "bacButtin");
96 connect( t, SIGNAL( clicked() ), this, SLOT( doBac() ) ); 99 connect( t, SIGNAL( clicked() ), this, SLOT( doBac() ) );
97 100
98 DrinkView = new QListView( this, "DrinkView" ); 101 DrinkView = new QListView( this, "DrinkView" );
99 DrinkView->addColumn( tr( "Name of Drink" ) ); 102 DrinkView->addColumn( tr( "Name of Drink" ) );
100// DrinkView->setRootIsDecorated( TRUE ); 103// DrinkView->setRootIsDecorated( TRUE );
101 DrinkView->header()->hide(); 104 DrinkView->header()->hide();
102 105
103 QPEApplication::setStylusOperation( DrinkView->viewport(),QPEApplication::RightOnHold); 106 QPEApplication::setStylusOperation( DrinkView->viewport(),QPEApplication::RightOnHold);
104 107
105 connect(DrinkView, SIGNAL( doubleClicked(QListViewItem*)),this,SLOT(showDrink(QListViewItem*))); 108 connect(DrinkView, SIGNAL( doubleClicked(QListViewItem*)),this,SLOT(showDrink(QListViewItem*)));
106 connect(DrinkView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), 109 connect(DrinkView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
107 this,SLOT( showDrink(int,QListViewItem*,const QPoint&,int))); 110 this,SLOT( showDrink(int,QListViewItem*,const QPoint&,int)));
108 111
109 layout->addMultiCellWidget( DrinkView, 1, 2, 0, 4 ); 112 layout->addMultiCellWidget( DrinkView, 1, 2, 0, 4 );
110 if(QDir("db").exists()) { 113 if(QDir("db").exists()) {
111 dbFile.setName( "db/drinkdb.txt"); 114 dbFile.setName( "db/drinkdb.txt");
112 } else 115 } else
113 dbFile.setName( QPEApplication::qpeDir()+"/etc/bartender/drinkdb.txt"); 116 dbFile.setName( QPEApplication::qpeDir()+"/etc/bartender/drinkdb.txt");
114 initDrinkDb(); 117 initDrinkDb();
115} 118}
116 119
117Bartender::~Bartender() { 120Bartender::~Bartender() {
118} 121}
119 122
120/* 123/*
121this happens right before exit */ 124this happens right before exit */
122void Bartender::cleanUp() { 125void Bartender::cleanUp() {
123 dbFile.close(); 126 dbFile.close();
124 127
125} 128}
126 129
127void Bartender::initDrinkDb() { 130void Bartender::initDrinkDb() {
128 131
129 if(!dbFile.isOpen()) 132 if(!dbFile.isOpen())
130 if ( !dbFile.open( IO_ReadOnly)) { 133 if ( !dbFile.open( IO_ReadOnly)) {
131 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); 134 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) );
132 return; 135 return;
133 } 136 }
134 fillList(); 137 fillList();
135} 138}
136 139
137void Bartender::fillList() { 140void Bartender::fillList() {
138 dbFile.at(1); 141 dbFile.at(1);
139 DrinkView->clear(); 142 DrinkView->clear();
140 int i=0; 143 int i=0;
141 QListViewItem * item ; 144 QListViewItem * item ;
142 QTextStream t( &dbFile); 145 QTextStream t( &dbFile);
143 QString s; 146 QString s;
144 while ( !t.eof()) { 147 while ( !t.eof()) {
145 s = t.readLine(); 148 s = t.readLine();
146 if(s.find("#",0,TRUE) != -1) { 149 if(s.find("#",0,TRUE) != -1) {
147// qDebug(s.right(s.length()-2)); 150// odebug << s.right(s.length()-2) << oendl;
148 item= new QListViewItem( DrinkView, 0 ); 151 item= new QListViewItem( DrinkView, 0 );
149 item->setText( 0, s.right(s.length()-2)); 152 item->setText( 0, s.right(s.length()-2));
150 i++; 153 i++;
151 } 154 }
152 } 155 }
153 qDebug("there are currently %d of drinks", i); 156 odebug << "there are currently " << i << " of drinks" << oendl;
154} 157}
155 158
156void Bartender::fileNew() { 159void Bartender::fileNew() {
157 160
158 New_Drink *newDrinks; 161 New_Drink *newDrinks;
159 newDrinks = new New_Drink(this,"New Drink....", TRUE); 162 newDrinks = new New_Drink(this,"New Drink....", TRUE);
160 QString newName, newIng; 163 QString newName, newIng;
161 QPEApplication::execDialog( newDrinks ); 164 QPEApplication::execDialog( newDrinks );
162 newName = newDrinks->LineEdit1->text(); 165 newName = newDrinks->LineEdit1->text();
163 newIng= newDrinks->MultiLineEdit1->text(); 166 newIng= newDrinks->MultiLineEdit1->text();
164 167
165 if(dbFile.isOpen()) 168 if(dbFile.isOpen())
166 dbFile.close(); 169 dbFile.close();
167 if ( !dbFile.open( IO_WriteOnly| IO_Append)) { 170 if ( !dbFile.open( IO_WriteOnly| IO_Append)) {
168 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); 171 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) );
169 return; 172 return;
170 } 173 }
171 if(newDrinks ->result() == 1 ) { 174 if(newDrinks ->result() == 1 ) {
172 QString newDrink="\n# "+newName+"\n"; 175 QString newDrink="\n# "+newName+"\n";
173 newDrink.append(newIng+"\n"); 176 newDrink.append(newIng+"\n");
174 qDebug("writing "+newDrink); 177 odebug << "writing "+newDrink << oendl;
175 dbFile.writeBlock( newDrink.latin1(), newDrink.length()); 178 dbFile.writeBlock( newDrink.latin1(), newDrink.length());
176 clearList(); 179 clearList();
177 dbFile.close(); 180 dbFile.close();
178 181
179 initDrinkDb(); 182 initDrinkDb();
180 } 183 }
181 delete newDrinks; 184 delete newDrinks;
182} 185}
183 186
184void Bartender::showDrink(int mouse, QListViewItem * item, const QPoint&, int) { 187void Bartender::showDrink(int mouse, QListViewItem * item, const QPoint&, int) {
185 switch (mouse) { 188 switch (mouse) {
186 case 1: 189 case 1:
187// showDrink(item); 190// showDrink(item);
188 break; 191 break;
189 case 2: 192 case 2:
190 showDrink(item); 193 showDrink(item);
191 break; 194 break;
192 } 195 }
193} 196}
194 197
195void Bartender::showDrink( QListViewItem *item) { 198void Bartender::showDrink( QListViewItem *item) {
196 if(item==NULL) return; 199 if(item==NULL) return;
197 dbFile.at(0); 200 dbFile.at(0);
198 Show_Drink *showDrinks; 201 Show_Drink *showDrinks;
199 QString myDrink=item->text(0); 202 QString myDrink=item->text(0);
200 showDrinks = new Show_Drink(this, myDrink, TRUE); 203 showDrinks = new Show_Drink(this, myDrink, TRUE);
201 QTextStream t( &dbFile); 204 QTextStream t( &dbFile);
202 205
203 QString s, s2; 206 QString s, s2;
204 while ( !t.eof()) { 207 while ( !t.eof()) {
205 s = t.readLine(); 208 s = t.readLine();
206 if(s.find( myDrink, 0, TRUE) != -1) { 209 if(s.find( myDrink, 0, TRUE) != -1) {
207 for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) { 210 for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) {
208 s2 = t.readLine(); 211 s2 = t.readLine();
209 if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) { 212 if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) {
210// qDebug(s2); 213// odebug << s2 << oendl;
211 showDrinks->MultiLineEdit1->append(s2); 214 showDrinks->MultiLineEdit1->append(s2);
212 } 215 }
213 if( dbFile.atEnd() ) break; 216 if( dbFile.atEnd() ) break;
214 } 217 }
215 } 218 }
216 } 219 }
217 QPEApplication::execDialog( showDrinks ); 220 QPEApplication::execDialog( showDrinks );
218 221
219 if(showDrinks ->result() ==0) { 222 if(showDrinks ->result() ==0) {
220 doEdit(); 223 doEdit();
221 } 224 }
222 delete showDrinks; 225 delete showDrinks;
223} 226}
224 227
225void Bartender::askSearch() { 228void Bartender::askSearch() {
226 switch ( QMessageBox::warning(this,tr("Find"),tr("Search by drink name\n")+ 229 switch ( QMessageBox::warning(this,tr("Find"),tr("Search by drink name\n")+
227 "\nor alcohol ?" 230 "\nor alcohol ?"
228 ,tr("Drink Name"),tr("Alcohol"),0,0,1) ) { 231 ,tr("Drink Name"),tr("Alcohol"),0,0,1) ) {
229 case 0: 232 case 0:
230 doSearchByName(); 233 doSearchByName();
231 break; 234 break;
232 case 1: 235 case 1:
233 doSearchByDrink(); 236 doSearchByDrink();
234 break; 237 break;
235 }; 238 };
236} 239}
237 240
238/* search by name */ 241/* search by name */
239void Bartender::doSearchByName() { 242void Bartender::doSearchByName() {
240// if( DrinkView->currentItem() == NULL) return; 243// if( DrinkView->currentItem() == NULL) return;
241 QStringList searchList; 244 QStringList searchList;
242 QString searchForDrinkName; 245 QString searchForDrinkName;
243 InputDialog *fileDlg; 246 InputDialog *fileDlg;
244 fileDlg = new InputDialog(this,tr("Find by Drink Name"),TRUE, 0); 247 fileDlg = new InputDialog(this,tr("Find by Drink Name"),TRUE, 0);
245 fileDlg->exec(); 248 fileDlg->exec();
246 if( fileDlg->result() == 1 ) { 249 if( fileDlg->result() == 1 ) {
247 searchForDrinkName = fileDlg->LineEdit1->text(); 250 searchForDrinkName = fileDlg->LineEdit1->text();
248 QListViewItemIterator it( DrinkView ); 251 QListViewItemIterator it( DrinkView );
249 for ( ; it.current(); ++it ) { 252 for ( ; it.current(); ++it ) {
250 if ( it.current()->text(0).find( searchForDrinkName, 0, TRUE) != -1 ) { 253 if ( it.current()->text(0).find( searchForDrinkName, 0, TRUE) != -1 ) {
251// qDebug( it.current()->text(0)); 254// odebug << it.current()->text(0) << oendl;
252 searchList.append(it.current()->text(0)); 255 searchList.append(it.current()->text(0));
253 } 256 }
254 } 257 }
255 if(searchList.count() >0) 258 if(searchList.count() >0)
256 showSearchResult(searchList); 259 showSearchResult(searchList);
257 else 260 else
258 QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+searchForDrinkName); 261 QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+searchForDrinkName);
259 }//end Inputdialog 262 }//end Inputdialog
260 delete fileDlg; 263 delete fileDlg;
261} 264}
262 265
263void Bartender::doSearchByDrink() { 266void Bartender::doSearchByDrink() {
264// if( DrinkView->currentItem() == NULL) return; 267// if( DrinkView->currentItem() == NULL) return;
265 QStringList searchList; 268 QStringList searchList;
266 QString searchForDrinkName, lastDrinkName, tempName; 269 QString searchForDrinkName, lastDrinkName, tempName;
267 270
268 InputDialog *fileDlg; 271 InputDialog *fileDlg;
269 fileDlg = new InputDialog(this,tr("Find by Alcohol"),TRUE, 0); 272 fileDlg = new InputDialog(this,tr("Find by Alcohol"),TRUE, 0);
270 fileDlg->exec(); 273 fileDlg->exec();
271 if( fileDlg->result() == 1 ) { 274 if( fileDlg->result() == 1 ) {
272 searchForDrinkName = fileDlg->LineEdit1->text(); 275 searchForDrinkName = fileDlg->LineEdit1->text();
273 276
274 dbFile.at(0); 277 dbFile.at(0);
275 QTextStream t( &dbFile); 278 QTextStream t( &dbFile);
276 279
277 QString s, s2; 280 QString s, s2;
278 while ( !t.eof()) { 281 while ( !t.eof()) {
279 s = t.readLine(); 282 s = t.readLine();
280 if(s.find("#",0,TRUE) != -1) { 283 if(s.find("#",0,TRUE) != -1) {
281 lastDrinkName=s.right(s.length()-2); 284 lastDrinkName=s.right(s.length()-2);
282// qDebug("last drink name "+lastDrinkName); 285// odebug << "last drink name "+lastDrinkName << oendl;
283 } 286 }
284 else if( s.find( searchForDrinkName ,0, FALSE) != -1 && lastDrinkName != tempName ) { 287 else if( s.find( searchForDrinkName ,0, FALSE) != -1 && lastDrinkName != tempName ) {
285// qDebug("appending "+lastDrinkName); 288// odebug << "appending "+lastDrinkName << oendl;
286 searchList.append( lastDrinkName); 289 searchList.append( lastDrinkName);
287 tempName=lastDrinkName; 290 tempName=lastDrinkName;
288 } 291 }
289// if( dbFile.atEnd() ) break; 292// if( dbFile.atEnd() ) break;
290 293
291 } //oef 294 } //oef
292 if(searchList.count() >0) 295 if(searchList.count() >0)
293 showSearchResult(searchList); 296 showSearchResult(searchList);
294 else 297 else
295 QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+ searchForDrinkName); 298 QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+ searchForDrinkName);
296 } 299 }
297 delete fileDlg; 300 delete fileDlg;
298} 301}
299 302
300void Bartender::showSearchResult(QStringList &searchList) { 303void Bartender::showSearchResult(QStringList &searchList) {
301 QString result; 304 QString result;
302 Search_Results *searchDlg; 305 Search_Results *searchDlg;
303 306
304 searchList.sort(); 307 searchList.sort();
305 308
306 searchDlg = new Search_Results(this, "Search Results", TRUE); 309 searchDlg = new Search_Results(this, "Search Results", TRUE);
307 searchDlg->ListBox1->insertStringList( searchList,-1); 310 searchDlg->ListBox1->insertStringList( searchList,-1);
308 QPEApplication::execDialog( searchDlg ); 311 QPEApplication::execDialog( searchDlg );
309 312
310 if( searchDlg->result() == 1 ) { 313 if( searchDlg->result() == 1 ) {
311 result= searchDlg->ListBox1->currentText(); 314 result= searchDlg->ListBox1->currentText();
312 } 315 }
313 QListViewItemIterator it2( DrinkView ); 316 QListViewItemIterator it2( DrinkView );
314 for ( ; it2.current(); ++it2 ) { 317 for ( ; it2.current(); ++it2 ) {
315 if ( it2.current()->text(0)== result ) { 318 if ( it2.current()->text(0)== result ) {
316// qDebug( it2.current()->text(0)); 319// odebug << it2.current()->text(0) << oendl;
317 showDrink(it2.current()); 320 showDrink(it2.current());
318 } 321 }
319 } 322 }
320delete searchDlg; 323delete searchDlg;
321} 324}
322 325
323void Bartender::doEdit() { 326void Bartender::doEdit() {
324 if(DrinkView->currentItem() == NULL) { 327 if(DrinkView->currentItem() == NULL) {
325 fileNew(); 328 fileNew();
326 } 329 }
327 330
328 QString myDrink; 331 QString myDrink;
329 myDrink= DrinkView->currentItem()->text(0); 332 myDrink= DrinkView->currentItem()->text(0);
330 dbFile.at(0); 333 dbFile.at(0);
331 int foundAt=0; 334 int foundAt=0;
332 New_Drink *newDrinks; 335 New_Drink *newDrinks;
333 newDrinks = new New_Drink(this,"Edit Drink....", TRUE); 336 newDrinks = new New_Drink(this,"Edit Drink....", TRUE);
334 QString newName, newIng; 337 QString newName, newIng;
335 QPEApplication::showDialog( newDrinks ); 338 QPEApplication::showDialog( newDrinks );
336 QTextStream t( &dbFile); 339 QTextStream t( &dbFile);
337 340
338 QString s, s2; 341 QString s, s2;
339 while ( !t.eof()) { 342 while ( !t.eof()) {
340 s = t.readLine(); 343 s = t.readLine();
341 if(s.find( myDrink, 0, TRUE) != -1) { 344 if(s.find( myDrink, 0, TRUE) != -1) {
342 foundAt = dbFile.at() - (s.length()+1); 345 foundAt = dbFile.at() - (s.length()+1);
343 for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) { 346 for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) {
344 s2 = t.readLine(); 347 s2 = t.readLine();
345 if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) { 348 if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) {
346// qDebug(s2); 349// odebug << s2 << oendl;
347 newDrinks->MultiLineEdit1->append(s2); 350 newDrinks->MultiLineEdit1->append(s2);
348 newDrinks->LineEdit1->setText(myDrink); 351 newDrinks->LineEdit1->setText(myDrink);
349 } 352 }
350 if( dbFile.atEnd() ) break; 353 if( dbFile.atEnd() ) break;
351 } 354 }
352 } 355 }
353 } 356 }
354 newDrinks->exec(); 357 newDrinks->exec();
355 newName = newDrinks->LineEdit1->text(); 358 newName = newDrinks->LineEdit1->text();
356 newIng= newDrinks->MultiLineEdit1->text(); 359 newIng= newDrinks->MultiLineEdit1->text();
357 360
358 if( newDrinks ->result() == 1 ) { 361 if( newDrinks ->result() == 1 ) {
359 if(dbFile.isOpen()) 362 if(dbFile.isOpen())
360 dbFile.close(); 363 dbFile.close();
361 if ( !dbFile.open( IO_ReadWrite )) { 364 if ( !dbFile.open( IO_ReadWrite )) {
362 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); 365 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) );
363 return; 366 return;
364 } 367 }
365 int fd = dbFile.handle(); 368 int fd = dbFile.handle();
366 lseek( fd, foundAt, SEEK_SET); 369 lseek( fd, foundAt, SEEK_SET);
367 370
368// dbFile.at( foundAt); 371// dbFile.at( foundAt);
369#warning FIXME problems with editing drinks db 372#warning FIXME problems with editing drinks db
370 ////////// FIXME write to user file 373 ////////// FIXME write to user file
371 QString newDrink="# "+newName+"\n"; 374 QString newDrink="# "+newName+"\n";
372 newDrink.append(newIng+"\n"); 375 newDrink.append(newIng+"\n");
373 qDebug("writing "+newDrink); 376 odebug << "writing "+newDrink << oendl;
374 dbFile.writeBlock( newDrink.latin1(), newDrink.length()); 377 dbFile.writeBlock( newDrink.latin1(), newDrink.length());
375 clearList(); 378 clearList();
376 379
377 dbFile.flush(); 380 dbFile.flush();
378 381
379 initDrinkDb(); 382 initDrinkDb();
380 } 383 }
381} 384}
382 385
383void Bartender::clearList() { 386void Bartender::clearList() {
384 DrinkView->clear(); 387 DrinkView->clear();
385} 388}
386 389
387void Bartender::doBac() { 390void Bartender::doBac() {
388 BacDialog *bacDlg; 391 BacDialog *bacDlg;
389 bacDlg = new BacDialog(this,"BAC",TRUE); 392 bacDlg = new BacDialog(this,"BAC",TRUE);
390 QPEApplication::execDialog( bacDlg ); 393 QPEApplication::execDialog( bacDlg );
391 delete bacDlg; 394 delete bacDlg;
392} 395}
393 396
394void Bartender::openCurrentDrink() { 397void Bartender::openCurrentDrink() {
395 if(DrinkView->currentItem() == NULL) return; 398 if(DrinkView->currentItem() == NULL) return;
396 showDrink(DrinkView->currentItem()); 399 showDrink(DrinkView->currentItem());
397} 400}
398 401
399void Bartender::fileMenuActivated( int item) { 402void Bartender::fileMenuActivated( int item) {
400 qDebug("Item %d", item); 403 odebug << "Item " << item << "" << oendl;
401 switch(item) { 404 switch(item) {
402 case -3: // new -3 405 case -3: // new -3
403 fileNew(); 406 fileNew();
404 break; 407 break;
405 case -4:// open -4 408 case -4:// open -4
406 openCurrentDrink(); 409 openCurrentDrink();
407 break; 410 break;
408 case -5:// drink -5 411 case -5:// drink -5
409 doSearchByName(); 412 doSearchByName();
410 413
411 break; 414 break;
412 case -6:// alcohol -6 415 case -6:// alcohol -6
413 doSearchByDrink(); 416 doSearchByDrink();
414 417
415 break; 418 break;
416 419
417 } 420 }
418} 421}
419 422
420void Bartender::editMenuActivated(int item) { 423void Bartender::editMenuActivated(int item) {
421 qDebug("Item %d", item); 424 odebug << "Item " << item << "" << oendl;
422 /* 425 /*
423 edit -8 426 edit -8
424 */ 427 */
425 switch(item) { 428 switch(item) {
426 case -8: 429 case -8:
427 doEdit() ; 430 doEdit() ;
428 break; 431 break;
429 432
430 } 433 }
431} 434}
432 435
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 @@
1TEMPLATE = app 1TEMPLATE = app
2#CONFIG = qt warn_on
3CONFIG = qt warn_on 2CONFIG = qt warn_on
4HEADERS = bartender.h newdrinks.h showdrinks.h inputDialog.h searchresults.h bac.h 3HEADERS = bartender.h newdrinks.h showdrinks.h inputDialog.h searchresults.h bac.h
5SOURCES = main.cpp bartender.cpp newdrinks.cpp showdrinks.cpp inputDialog.cpp searchresults.cpp bac.cpp 4SOURCES = main.cpp bartender.cpp newdrinks.cpp showdrinks.cpp inputDialog.cpp searchresults.cpp bac.cpp
6INCLUDEPATH += $(OPIEDIR)/include 5INCLUDEPATH += $(OPIEDIR)/include
7DEPENDPATH += $(OPIEDIR)/include 6DEPENDPATH += $(OPIEDIR)/include
8LIBS += -lqpe 7LIBS += -lqpe -lopiecore2
9DESTDIR = $(OPIEDIR)/bin 8DESTDIR = $(OPIEDIR)/bin
10TARGET = bartender 9TARGET = bartender
11 10
12include ( $(OPIEDIR)/include.pro ) 11include ( $(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 @@
1 config BARTENDER 1 config BARTENDER
2 boolean "bartender - bar receipe and blood alcohol estimator" 2 boolean "bartender - bar receipe and blood alcohol estimator"
3 default "n" 3 default "n"
4 depends ( LIBQPE || LIBQPE-X11 ) 4 depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
5
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 @@
1/* -------------------------------------------------------------------------- */ 1/* -------------------------------------------------------------------------- */
2/* */ 2/* */
3/* [MyPty.C] Pseudo Terminal Device */ 3/* [MyPty.C] Pseudo Terminal Device */
4/* */ 4/* */
5/* -------------------------------------------------------------------------- */ 5/* -------------------------------------------------------------------------- */
6/* */ 6/* */
7/* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */ 7/* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */
8/* */ 8/* */
9/* This file is part of Konsole - an X terminal for KDE */ 9/* This file is part of Konsole - an X terminal for KDE */
10/* -------------------------------------------------------------------------- */ 10/* -------------------------------------------------------------------------- */
11 /* */ 11 /* */
12/* Ported Konsole to Qt/Embedded */ 12/* Ported Konsole to Qt/Embedded */
13 /* */ 13 /* */
14/* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */ 14/* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */
15 /* */ 15 /* */
16/* -------------------------------------------------------------------------- */ 16/* -------------------------------------------------------------------------- */
17 17
18/* If you're compiling konsole on non-Linux platforms and find 18/* If you're compiling konsole on non-Linux platforms and find
19 problems that you can track down to this file, please have 19 problems that you can track down to this file, please have
20 a look into ../README.ports, too. 20 a look into ../README.ports, too.
21*/ 21*/
22 22
23/*! \file 23/*! \file
24*/ 24*/
25 25
26/*! \class TEPty 26/*! \class TEPty
27 27
28 \brief Ptys provide a pseudo terminal connection to a program. 28 \brief Ptys provide a pseudo terminal connection to a program.
29 29
30 Although closely related to pipes, these pseudo terminal connections have 30 Although closely related to pipes, these pseudo terminal connections have
31 some ability, that makes it nessesary to uses them. Most importent, they 31 some ability, that makes it nessesary to uses them. Most importent, they
32 know about changing screen sizes and UNIX job control. 32 know about changing screen sizes and UNIX job control.
33 33
34 Within the terminal emulation framework, this class represents the 34 Within the terminal emulation framework, this class represents the
35 host side of the terminal together with the connecting serial line. 35 host side of the terminal together with the connecting serial line.
36 36
37 One can create many instances of this class within a program. 37 One can create many instances of this class within a program.
38 As a side effect of using this class, a signal(2) handler is 38 As a side effect of using this class, a signal(2) handler is
39 installed on SIGCHLD. 39 installed on SIGCHLD.
40 40
41 \par FIXME 41 \par FIXME
42 42
43 [NOTE: much of the technical stuff below will be replaced by forkpty.] 43 [NOTE: much of the technical stuff below will be replaced by forkpty.]
44 44
45 publish the SIGCHLD signal if not related to an instance. 45 publish the SIGCHLD signal if not related to an instance.
46 46
47 clearify TEPty::done vs. TEPty::~TEPty semantics. 47 clearify TEPty::done vs. TEPty::~TEPty semantics.
48 check if pty is restartable via run after done. 48 check if pty is restartable via run after done.
49 49
50 \par Pseudo terminals 50 \par Pseudo terminals
51 51
52 Pseudo terminals are a unique feature of UNIX, and always come in form of 52 Pseudo terminals are a unique feature of UNIX, and always come in form of
53 pairs of devices (/dev/ptyXX and /dev/ttyXX), which are connected to each 53 pairs of devices (/dev/ptyXX and /dev/ttyXX), which are connected to each
54 other by the operating system. One may think of them as two serial devices 54 other by the operating system. One may think of them as two serial devices
55 linked by a null-modem cable. Being based on devices the number of 55 linked by a null-modem cable. Being based on devices the number of
56 simultanous instances of this class is (globally) limited by the number of 56 simultanous instances of this class is (globally) limited by the number of
57 those device pairs, which is 256. 57 those device pairs, which is 256.
58 58
59 Another technic are UNIX 98 PTY's. These are supported also, and prefered 59 Another technic are UNIX 98 PTY's. These are supported also, and prefered
60 over the (obsolete) predecessor. 60 over the (obsolete) predecessor.
61 61
62 There's a sinister ioctl(2), signal(2) and job control stuff 62 There's a sinister ioctl(2), signal(2) and job control stuff
63 nessesary to make everything work as it should. 63 nessesary to make everything work as it should.
64*/ 64*/
65 65
66#include "procctl.h"
67#include "MyPty.h"
66 68
69/* OPIE */
70#include <opie2/odebug.h>
71using namespace Opie::Core;
72
73/* QT */
67#include <qsocketnotifier.h> 74#include <qsocketnotifier.h>
68#include <qfile.h> 75#include <qfile.h>
69 76
77/* STD */
70#include <stdlib.h> 78#include <stdlib.h>
71#include <stdio.h> 79#include <stdio.h>
72#include <signal.h> 80#include <signal.h>
73#include <fcntl.h> 81#include <fcntl.h>
74#include <unistd.h> 82#include <unistd.h>
75#include <termios.h> 83#include <termios.h>
76#include <sys/types.h> 84#include <sys/types.h>
77#include <sys/ioctl.h> 85#include <sys/ioctl.h>
78#include <sys/wait.h> 86#include <sys/wait.h>
79 87
80#ifdef HAVE_OPENPTY 88#ifdef HAVE_OPENPTY
81#include <pty.h> 89#include <pty.h>
82#endif 90#endif
83 91
84#include "procctl.h"
85#include "MyPty.h"
86
87
88#undef VERBOSE_DEBUG 92#undef VERBOSE_DEBUG
89 93
90 94
91/* -------------------------------------------------------------------------- */ 95/* -------------------------------------------------------------------------- */
92 96
93/*! 97/*!
94 Informs the client program about the 98 Informs the client program about the
95 actual size of the window. 99 actual size of the window.
96*/ 100*/
97 101
98void MyPty::setSize(int lines, int columns) 102void MyPty::setSize(int lines, int columns)
99{ 103{
100 qWarning("setting size"); 104 owarn << "setting size" << oendl;
101 struct winsize wsize; 105 struct winsize wsize;
102 wsize.ws_row = (unsigned short)lines; 106 wsize.ws_row = (unsigned short)lines;
103 wsize.ws_col = (unsigned short)columns; 107 wsize.ws_col = (unsigned short)columns;
104 if(m_fd < 0) return; 108 if(m_fd < 0) return;
105 ioctl(m_fd,TIOCSWINSZ,(char *)&wsize); 109 ioctl(m_fd,TIOCSWINSZ,(char *)&wsize);
106} 110}
107 111
108 112
109void MyPty::donePty() 113void MyPty::donePty()
110{ 114{
111 // This is code from the Qt DumbTerminal example 115 // This is code from the Qt DumbTerminal example
112 116
113 ::close(m_fd); 117 ::close(m_fd);
114 118
115 if (m_cpid) { 119 if (m_cpid) {
116 kill(m_cpid, SIGHUP); 120 kill(m_cpid, SIGHUP);
117 //waitpid(m_cpid, &status, 0); 121 //waitpid(m_cpid, &status, 0);
118 delete m_sn_e; 122 delete m_sn_e;
119 delete m_sn_r; 123 delete m_sn_r;
120 m_sn_e = 0l; 124 m_sn_e = 0l;
121 m_sn_r = 0l; 125 m_sn_r = 0l;
122 } 126 }
123 127
124 m_cpid = 0; 128 m_cpid = 0;
125 m_fd = -1; 129 m_fd = -1;
126// emit done(status); 130// emit done(status);
127} 131}
128 132
129 133
130const char* MyPty::deviceName() 134const char* MyPty::deviceName()
131{ 135{
132 return m_ttynam; 136 return m_ttynam;
133} 137}
134 138
135 139
136void MyPty::error() 140void MyPty::error()
137{ 141{
138 // This is code from the Qt DumbTerminal example 142 // This is code from the Qt DumbTerminal example
139 donePty(); 143 donePty();
140} 144}
141 145
142void MyPty::start() { 146void MyPty::start() {
143 QStrList lis; 147 QStrList lis;
144 int r =run(m_cmd.latin1(), lis, 0, 0); 148 int r =run(m_cmd.latin1(), lis, 0, 0);
145 r = r; 149 r = r;
146} 150}
147/*! 151/*!
148 start the client program. 152 start the client program.
149*/ 153*/
150int MyPty::run(const char* cmd, QStrList &, const char*, int) 154int MyPty::run(const char* cmd, QStrList &, const char*, int)
151{ 155{
152 // This is code from the Qt DumbTerminal example 156 // This is code from the Qt DumbTerminal example
153 m_cpid = fork(); 157 m_cpid = fork();
154 158
155 if ( !m_cpid ) { 159 if ( !m_cpid ) {
156 // child - exec shell on tty 160 // child - exec shell on tty
157 for (int sig = 1; sig < NSIG; sig++) signal(sig,SIG_DFL); 161 for (int sig = 1; sig < NSIG; sig++) signal(sig,SIG_DFL);
158 int ttyfd = ::open(m_ttynam, O_RDWR); 162 int ttyfd = ::open(m_ttynam, O_RDWR);
159 dup2(ttyfd, STDIN_FILENO); 163 dup2(ttyfd, STDIN_FILENO);
160 dup2(ttyfd, STDOUT_FILENO); 164 dup2(ttyfd, STDOUT_FILENO);
161 dup2(ttyfd, STDERR_FILENO); 165 dup2(ttyfd, STDERR_FILENO);
162 // should be done with tty, so close it 166 // should be done with tty, so close it
163 ::close(ttyfd); 167 ::close(ttyfd);
164 static struct termios ttmode; 168 static struct termios ttmode;
165 if ( setsid() < 0 ) 169 if ( setsid() < 0 )
166 perror( "failed to set process group" ); 170 perror( "failed to set process group" );
167#if defined (TIOCSCTTY) 171#if defined (TIOCSCTTY)
168 // grabbed from APUE by Stevens 172 // grabbed from APUE by Stevens
169 ioctl(STDIN_FILENO, TIOCSCTTY, 0); 173 ioctl(STDIN_FILENO, TIOCSCTTY, 0);
170#endif 174#endif
171 tcgetattr( STDIN_FILENO, &ttmode ); 175 tcgetattr( STDIN_FILENO, &ttmode );
172 ttmode.c_cc[VINTR] = 3; 176 ttmode.c_cc[VINTR] = 3;
173 ttmode.c_cc[VERASE] = 8; 177 ttmode.c_cc[VERASE] = 8;
174 tcsetattr( STDIN_FILENO, TCSANOW, &ttmode ); 178 tcsetattr( STDIN_FILENO, TCSANOW, &ttmode );
175 setenv("TERM",m_term,1); 179 setenv("TERM",m_term,1);
176 setenv("COLORTERM","0",1); 180 setenv("COLORTERM","0",1);
177 EnvironmentMap::Iterator it; 181 EnvironmentMap::Iterator it;
178 for (it = m_env.begin(); it != m_env.end(); it++) { 182 for (it = m_env.begin(); it != m_env.end(); it++) {
179 setenv(it.key().latin1(), it.data().latin1(), 1); 183 setenv(it.key().latin1(), it.data().latin1(), 1);
180 } 184 }
181 if (getuid() == 0) { 185 if (getuid() == 0) {
182 char msg[] = "WARNING: You are running this shell as root!\n"; 186 char msg[] = "WARNING: You are running this shell as root!\n";
183 write(ttyfd, msg, sizeof(msg)); 187 write(ttyfd, msg, sizeof(msg));
184 } 188 }
185 execl(cmd, cmd, 0); 189 execl(cmd, cmd, 0);
186 190
187 donePty(); 191 donePty();
188 exit(-1); 192 exit(-1);
189 } 193 }
190 194
191 // parent - continue as a widget 195 // parent - continue as a widget
192 delete m_sn_r; 196 delete m_sn_r;
193 m_sn_r = new QSocketNotifier(m_fd,QSocketNotifier::Read,this); 197 m_sn_r = new QSocketNotifier(m_fd,QSocketNotifier::Read,this);
194 delete m_sn_e; 198 delete m_sn_e;
195 m_sn_e = new QSocketNotifier(m_fd,QSocketNotifier::Exception,this); 199 m_sn_e = new QSocketNotifier(m_fd,QSocketNotifier::Exception,this);
196 connect(m_sn_r,SIGNAL(activated(int)),this,SLOT(readPty())); 200 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)
936 936
937/* ------------------------------------------------------------------------- */ 937/* ------------------------------------------------------------------------- */
938/* */ 938/* */
939/* Clipboard */ 939/* Clipboard */
940/* */ 940/* */
941/* ------------------------------------------------------------------------- */ 941/* ------------------------------------------------------------------------- */
942 942
943#undef KeyPress 943#undef KeyPress
944 944
945void TEWidget::emitSelection() 945void TEWidget::emitSelection()
946// Paste Clipboard by simulating keypress events 946// Paste Clipboard by simulating keypress events
947{ 947{
948#ifndef QT_NO_CLIPBOARD 948#ifndef QT_NO_CLIPBOARD
949 QString text = QApplication::clipboard()->text(); 949 QString text = QApplication::clipboard()->text();
950 if ( ! text.isNull() ) 950 if ( ! text.isNull() )
951 { 951 {
952 text.replace(QRegExp("\n"), "\r"); 952 text.replace(QRegExp("\n"), "\r");
953 QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text); 953 QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text);
954 emit keyPressedSignal(&e); // expose as a big fat keypress event 954 emit keyPressedSignal(&e); // expose as a big fat keypress event
955 emit clearSelectionSignal(); 955 emit clearSelectionSignal();
956 } 956 }
957#endif 957#endif
958} 958}
959 959
960void TEWidget::emitText(QString text) 960void TEWidget::emitText(QString text)
961{ 961{
962 QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text); 962 QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text);
963 emit keyPressedSignal(&e); // expose as a big fat keypress event 963 emit keyPressedSignal(&e); // expose as a big fat keypress event
964} 964}
965 965
966void TEWidget::pasteClipboard( ) 966void TEWidget::pasteClipboard( )
967{ 967{
968 emitSelection(); 968 emitSelection();
969} 969}
970 970
971void TEWidget::setSelection(const QString& t) 971void TEWidget::setSelection(const QString& t)
972{ 972{
973#ifndef QT_NO_CLIPBOARD 973#ifndef QT_NO_CLIPBOARD
974 // Disconnect signal while WE set the clipboard 974 // Disconnect signal while WE set the clipboard
975 QObject *cb = QApplication::clipboard(); 975 QObject *cb = QApplication::clipboard();
976 QObject::disconnect( cb, SIGNAL(dataChanged()), 976 QObject::disconnect( cb, SIGNAL(dataChanged()),
977 this, SLOT(onClearSelection()) ); 977 this, SLOT(onClearSelection()) );
978 978
979 QApplication::clipboard()->setText(t); 979 QApplication::clipboard()->setText(t);
980 980
981 QObject::connect( cb, SIGNAL(dataChanged()), 981 QObject::connect( cb, SIGNAL(dataChanged()),
982 this, SLOT(onClearSelection()) ); 982 this, SLOT(onClearSelection()) );
983#endif 983#endif
984} 984}
985 985
986void TEWidget::onClearSelection() 986void TEWidget::onClearSelection()
987{ 987{
988 emit clearSelectionSignal(); 988 emit clearSelectionSignal();
989} 989}
990 990
991/* ------------------------------------------------------------------------- */ 991/* ------------------------------------------------------------------------- */
992/* */ 992/* */
993/* Keyboard */ 993/* Keyboard */
994/* */ 994/* */
995/* ------------------------------------------------------------------------- */ 995/* ------------------------------------------------------------------------- */
996 996
997//FIXME: an `eventFilter' has been installed instead of a `keyPressEvent' 997//FIXME: an `eventFilter' has been installed instead of a `keyPressEvent'
998// due to a bug in `QT' or the ignorance of the author to prevent 998// due to a bug in `QT' or the ignorance of the author to prevent
999// repaint events being emitted to the screen whenever one leaves 999// repaint events being emitted to the screen whenever one leaves
1000// or reenters the screen to/from another application. 1000// or reenters the screen to/from another application.
1001// 1001//
1002// Troll says one needs to change focusInEvent() and focusOutEvent(), 1002// Troll says one needs to change focusInEvent() and focusOutEvent(),
1003// which would also let you have an in-focus cursor and an out-focus 1003// which would also let you have an in-focus cursor and an out-focus
1004// cursor like xterm does. 1004// cursor like xterm does.
1005 1005
1006// for the auto-hide cursor feature, I added empty focusInEvent() and 1006// for the auto-hide cursor feature, I added empty focusInEvent() and
1007// focusOutEvent() so that update() isn't called. 1007// focusOutEvent() so that update() isn't called.
1008// For auto-hide, we need to get keypress-events, but we only get them when 1008// For auto-hide, we need to get keypress-events, but we only get them when
1009// we have focus. 1009// we have focus.
1010 1010
1011void TEWidget::doScroll(int lines) 1011void TEWidget::doScroll(int lines)
1012{ 1012{
1013 scrollbar->setValue(scrollbar->value()+lines); 1013 scrollbar->setValue(scrollbar->value()+lines);
1014} 1014}
1015 1015
1016bool TEWidget::eventFilter( QObject *obj, QEvent *e ) 1016bool TEWidget::eventFilter( QObject *obj, QEvent *e )
1017{ 1017{
1018 if ( (e->type() == QEvent::Accel || 1018 if ( (e->type() == QEvent::Accel ||
1019 e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) { 1019 e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) {
1020 static_cast<QKeyEvent *>( e )->ignore(); 1020 static_cast<QKeyEvent *>( e )->ignore();
1021 return true; 1021 return true;
1022 } 1022 }
1023 if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ ) 1023 if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ )
1024 return FALSE; // not us 1024 return FALSE; // not us
1025 if ( e->type() == QEvent::Wheel) { 1025 if ( e->type() == QEvent::Wheel) {
1026 QApplication::sendEvent(scrollbar, e); 1026 QApplication::sendEvent(scrollbar, e);
1027 } 1027 }
1028 1028
1029#ifdef FAKE_CTRL_AND_ALT 1029#ifdef FAKE_CTRL_AND_ALT
1030 static bool control = FALSE; 1030 static bool control = FALSE;
1031 static bool alt = FALSE; 1031 static bool alt = FALSE;
1032// qDebug(" Has a keyboard with no CTRL and ALT keys, but we fake it:"); 1032// odebug << " Has a keyboard with no CTRL and ALT keys, but we fake it:" << oendl;
1033 bool dele=FALSE; 1033 bool dele=FALSE;
1034 if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { 1034 if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
1035 QKeyEvent* ke = (QKeyEvent*)e; 1035 QKeyEvent* ke = (QKeyEvent*)e;
1036 bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat(); 1036 bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat();
1037 switch (ke->key()) { 1037 switch (ke->key()) {
1038 case Key_F9: // let this be "Control" 1038 case Key_F9: // let this be "Control"
1039 control = keydown; 1039 control = keydown;
1040 e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state()); 1040 e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state());
1041 dele=TRUE; 1041 dele=TRUE;
1042 break; 1042 break;
1043 case Key_F13: // let this be "Alt" 1043 case Key_F13: // let this be "Alt"
1044 alt = keydown; 1044 alt = keydown;
1045 e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state()); 1045 e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state());
1046 dele=TRUE; 1046 dele=TRUE;
1047 break; 1047 break;
1048 default: 1048 default:
1049 if ( control ) { 1049 if ( control ) {
1050 int a = toupper(ke->ascii())-64; 1050 int a = toupper(ke->ascii())-64;
1051 if ( a >= 0 && a < ' ' ) { 1051 if ( a >= 0 && a < ' ' ) {
1052 e = new QKeyEvent(e->type(), ke->key(), 1052 e = new QKeyEvent(e->type(), ke->key(),
1053 a, ke->state()|ControlButton, QChar(a,0)); 1053 a, ke->state()|ControlButton, QChar(a,0));
1054 dele=TRUE; 1054 dele=TRUE;
1055 } 1055 }
1056 } 1056 }
1057 if ( alt ) { 1057 if ( alt ) {
1058 e = new QKeyEvent(e->type(), ke->key(), 1058 e = new QKeyEvent(e->type(), ke->key(),
1059 ke->ascii(), ke->state()|AltButton, ke->text()); 1059 ke->ascii(), ke->state()|AltButton, ke->text());
1060 dele=TRUE; 1060 dele=TRUE;
1061 } 1061 }
1062 } 1062 }
1063 } 1063 }
1064#endif 1064#endif
1065 1065
1066 if ( e->type() == QEvent::KeyPress ) { 1066 if ( e->type() == QEvent::KeyPress ) {
1067 QKeyEvent* ke = (QKeyEvent*)e; 1067 QKeyEvent* ke = (QKeyEvent*)e;
1068 actSel=0; // Key stroke implies a screen update, so TEWidget won't 1068 actSel=0; // Key stroke implies a screen update, so TEWidget won't
1069 // know where the current selection is. 1069 // know where the current selection is.
1070 1070
1071// qDebug("key pressed is 0x%x",ke->key()); 1071// odebug << "key pressed is 0x" << ke->key() << "" << oendl;
1072 1072
1073 if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker 1073 if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker
1074 1074
1075// qDebug("key pressed 2 is 0x%x",ke->key()); 1075// odebug << "key pressed 2 is 0x" << ke->key() << "" << oendl;
1076 emitText("\\"); // expose 1076 emitText("\\"); // expose
1077 } else 1077 } else
1078 emit keyPressedSignal(ke); // expose 1078 emit keyPressedSignal(ke); // expose
1079 ke->accept(); 1079 ke->accept();
1080#ifdef FAKE_CTRL_AND_ALT 1080#ifdef FAKE_CTRL_AND_ALT
1081 if ( dele ) delete e; 1081 if ( dele ) delete e;
1082#endif 1082#endif
1083 return true; // stop the event 1083 return true; // stop the event
1084 } 1084 }
1085 if ( e->type() == QEvent::Enter ) { 1085 if ( e->type() == QEvent::Enter ) {
1086 QObject::disconnect( (QObject*)cb, SIGNAL(dataChanged()), 1086 QObject::disconnect( (QObject*)cb, SIGNAL(dataChanged()),
1087 this, SLOT(onClearSelection()) ); 1087 this, SLOT(onClearSelection()) );
1088 } 1088 }
1089 if ( e->type() == QEvent::Leave ) { 1089 if ( e->type() == QEvent::Leave ) {
1090 QObject::connect( (QObject*)cb, SIGNAL(dataChanged()), 1090 QObject::connect( (QObject*)cb, SIGNAL(dataChanged()),
1091 this, SLOT(onClearSelection()) ); 1091 this, SLOT(onClearSelection()) );
1092 } 1092 }
1093 return QFrame::eventFilter( obj, e ); 1093 return QFrame::eventFilter( obj, e );
1094} 1094}
1095 1095
1096/* ------------------------------------------------------------------------- */ 1096/* ------------------------------------------------------------------------- */
1097/* */ 1097/* */
1098/* Frame */ 1098/* Frame */
1099/* */ 1099/* */
1100/* ------------------------------------------------------------------------- */ 1100/* ------------------------------------------------------------------------- */
1101 1101
1102void TEWidget::frameChanged() 1102void TEWidget::frameChanged()
1103{ 1103{
1104 propagateSize(); 1104 propagateSize();
1105 update(); 1105 update();
1106} 1106}
1107 1107
1108/* ------------------------------------------------------------------------- */ 1108/* ------------------------------------------------------------------------- */
1109/* */ 1109/* */
1110/* Sound */ 1110/* Sound */
1111/* */ 1111/* */
1112/* ------------------------------------------------------------------------- */ 1112/* ------------------------------------------------------------------------- */
1113 1113
1114void TEWidget::Bell() 1114void TEWidget::Bell()
1115{ 1115{
1116 QApplication::beep(); 1116 QApplication::beep();
1117} 1117}
1118 1118
1119/* ------------------------------------------------------------------------- */ 1119/* ------------------------------------------------------------------------- */
1120/* */ 1120/* */
1121/* Auxiluary */ 1121/* Auxiluary */
1122/* */ 1122/* */
1123/* ------------------------------------------------------------------------- */ 1123/* ------------------------------------------------------------------------- */
1124 1124
1125void TEWidget::clearImage() 1125void TEWidget::clearImage()
1126// initialize the image 1126// initialize the image
1127// for internal use only 1127// for internal use only
1128{ 1128{
1129 for (int y = 0; y < lines; y++) 1129 for (int y = 0; y < lines; y++)
1130 for (int x = 0; x < columns; x++) 1130 for (int x = 0; x < columns; x++)
1131 { 1131 {
1132 image[loc(x,y)].c = 0xff; //' '; 1132 image[loc(x,y)].c = 0xff; //' ';
1133 image[loc(x,y)].f = 0xff; //DEFAULT_FORE_COLOR; 1133 image[loc(x,y)].f = 0xff; //DEFAULT_FORE_COLOR;
1134 image[loc(x,y)].b = 0xff; //DEFAULT_BACK_COLOR; 1134 image[loc(x,y)].b = 0xff; //DEFAULT_BACK_COLOR;
1135 image[loc(x,y)].r = 0xff; //DEFAULT_RENDITION; 1135 image[loc(x,y)].r = 0xff; //DEFAULT_RENDITION;
1136 } 1136 }
1137} 1137}
1138 1138
1139// Create Image /////////////////////////////////////////////////////// 1139// Create Image ///////////////////////////////////////////////////////
1140 1140
1141void TEWidget::calcGeometry() 1141void TEWidget::calcGeometry()
1142{ 1142{
1143 //FIXME: set rimX == rimY == 0 when running in full screen mode. 1143 //FIXME: set rimX == rimY == 0 when running in full screen mode.
1144 1144
1145 int showhscrollbar = 1; 1145 int showhscrollbar = 1;
1146 int hwidth = 0; 1146 int hwidth = 0;
1147 int dcolumns; 1147 int dcolumns;
1148 1148
1149 if(vcolumns == 0) showhscrollbar = 0; 1149 if(vcolumns == 0) showhscrollbar = 0;
1150 if(showhscrollbar == 1) hwidth = QApplication::style().scrollBarExtent().width(); 1150 if(showhscrollbar == 1) hwidth = QApplication::style().scrollBarExtent().width();
1151 1151
1152 scrollbar->resize(QApplication::style().scrollBarExtent().width(), 1152 scrollbar->resize(QApplication::style().scrollBarExtent().width(),
1153 contentsRect().height() - hwidth); 1153 contentsRect().height() - hwidth);
1154 1154
1155 if(!showhscrollbar) cornerButton()->move(0, 0); 1155 if(!showhscrollbar) cornerButton()->move(0, 0);
1156 else cornerButton()->move(contentsRect().width() - hwidth, contentsRect().height() - hwidth); 1156 else cornerButton()->move(contentsRect().width() - hwidth, contentsRect().height() - hwidth);
1157 1157
1158 1158
1159 switch(scrollLoc) 1159 switch(scrollLoc)
1160 { 1160 {
1161 case SCRNONE : 1161 case SCRNONE :
1162 columns = ( contentsRect().width() - 2 * rimX ) / font_w; 1162 columns = ( contentsRect().width() - 2 * rimX ) / font_w;
1163 dcolumns = columns; 1163 dcolumns = columns;
1164 if(vcolumns) columns = vcolumns; 1164 if(vcolumns) columns = vcolumns;
1165 blX = (contentsRect().width() - (columns*font_w) ) / 2; 1165 blX = (contentsRect().width() - (columns*font_w) ) / 2;
1166 if(showhscrollbar) 1166 if(showhscrollbar)
1167 blX = -hposition * font_w; 1167 blX = -hposition * font_w;
1168 brX = blX; 1168 brX = blX;
1169 scrollbar->hide(); 1169 scrollbar->hide();
1170 break; 1170 break;
1171 case SCRLEFT : 1171 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 @@
1/* -------------------------------------------------------------------------- */ 1/* -------------------------------------------------------------------------- */
2/* */ 2/* */
3/* [TEmulation.cpp] Terminal Emulation Decoder */ 3/* [TEmulation.cpp] Terminal Emulation Decoder */
4/* */ 4/* */
5/* -------------------------------------------------------------------------- */ 5/* -------------------------------------------------------------------------- */
6/* */ 6/* */
7/* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */ 7/* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */
8/* */ 8/* */
9/* This file is part of Konsole - an X terminal for KDE */ 9/* This file is part of Konsole - an X terminal for KDE */
10/* */ 10/* */
11/* -------------------------------------------------------------------------- */ 11/* -------------------------------------------------------------------------- */
12 /* */ 12 /* */
13/* Ported Konsole to Qt/Embedded */ 13/* Ported Konsole to Qt/Embedded */
14 /* */ 14 /* */
15/* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */ 15/* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */
16 /* */ 16 /* */
17/* -------------------------------------------------------------------------- */ 17/* -------------------------------------------------------------------------- */
18 18
19/*! \class TEmulation 19/*! \class TEmulation
20 20
21 \brief Mediator between TEWidget and TEScreen. 21 \brief Mediator between TEWidget and TEScreen.
22 22
23 This class is responsible to scan the escapes sequences of the terminal 23 This class is responsible to scan the escapes sequences of the terminal
24 emulation and to map it to their corresponding semantic complements. 24 emulation and to map it to their corresponding semantic complements.
25 Thus this module knows mainly about decoding escapes sequences and 25 Thus this module knows mainly about decoding escapes sequences and
26 is a stateless device w.r.t. the semantics. 26 is a stateless device w.r.t. the semantics.
27 27
28 It is also responsible to refresh the TEWidget by certain rules. 28 It is also responsible to refresh the TEWidget by certain rules.
29 29
30 \sa TEWidget \sa TEScreen 30 \sa TEWidget \sa TEScreen
31 31
32 \par A note on refreshing 32 \par A note on refreshing
33 33
34 Although the modifications to the current screen image could immediately 34 Although the modifications to the current screen image could immediately
35 be propagated via `TEWidget' to the graphical surface, we have chosen 35 be propagated via `TEWidget' to the graphical surface, we have chosen
36 another way here. 36 another way here.
37 37
38 The reason for doing so is twofold. 38 The reason for doing so is twofold.
39 39
40 First, experiments show that directly displaying the operation results 40 First, experiments show that directly displaying the operation results
41 in slowing down the overall performance of emulations. Displaying 41 in slowing down the overall performance of emulations. Displaying
42 individual characters using X11 creates a lot of overhead. 42 individual characters using X11 creates a lot of overhead.
43 43
44 Second, by using the following refreshing method, the screen operations 44 Second, by using the following refreshing method, the screen operations
45 can be completely separated from the displaying. This greatly simplifies 45 can be completely separated from the displaying. This greatly simplifies
46 the programmer's task of coding and maintaining the screen operations, 46 the programmer's task of coding and maintaining the screen operations,
47 since one need not worry about differential modifications on the 47 since one need not worry about differential modifications on the
48 display affecting the operation of concern. 48 display affecting the operation of concern.
49 49
50 We use a refreshing algorithm here that has been adoped from rxvt/kvt. 50 We use a refreshing algorithm here that has been adoped from rxvt/kvt.
51 51
52 By this, refreshing is driven by a timer, which is (re)started whenever 52 By this, refreshing is driven by a timer, which is (re)started whenever
53 a new bunch of data to be interpreted by the emulation arives at `onRcvBlock'. 53 a new bunch of data to be interpreted by the emulation arives at `onRcvBlock'.
54 As soon as no more data arrive for `BULK_TIMEOUT' milliseconds, we trigger 54 As soon as no more data arrive for `BULK_TIMEOUT' milliseconds, we trigger
55 refresh. This rule suits both bulk display operation as done by curses as 55 refresh. This rule suits both bulk display operation as done by curses as
56 well as individual characters typed. 56 well as individual characters typed.
57 (BULK_TIMEOUT < 1000 / max characters received from keyboard per second). 57 (BULK_TIMEOUT < 1000 / max characters received from keyboard per second).
58 58
59 Additionally, we trigger refreshing by newlines comming in to make visual 59 Additionally, we trigger refreshing by newlines comming in to make visual
60 snapshots of lists as produced by `cat', `ls' and likely programs, thereby 60 snapshots of lists as produced by `cat', `ls' and likely programs, thereby
61 producing the illusion of a permanent and immediate display operation. 61 producing the illusion of a permanent and immediate display operation.
62 62
63 As a sort of catch-all needed for cases where none of the above 63 As a sort of catch-all needed for cases where none of the above
64 conditions catch, the screen refresh is also triggered by a count 64 conditions catch, the screen refresh is also triggered by a count
65 of incoming bulks (`bulk_incnt'). 65 of incoming bulks (`bulk_incnt').
66*/ 66*/
67 67
68/* FIXME 68/* FIXME
69 - evtl. the bulk operations could be made more transparent. 69 - evtl. the bulk operations could be made more transparent.
70*/ 70*/
71 71
72#include "TEmulation.h" 72#include "TEmulation.h"
73
74/* OPIE */
75#include <opie2/odebug.h>
76using namespace Opie::Core;
77
78/* STD */
73#include <stdio.h> 79#include <stdio.h>
74#include <stdlib.h> 80#include <stdlib.h>
75#include <unistd.h> 81#include <unistd.h>
76 82
77 83
78/* ------------------------------------------------------------------------- */ 84/* ------------------------------------------------------------------------- */
79/* */ 85/* */
80/* TEmulation */ 86/* TEmulation */
81/* */ 87/* */
82/* ------------------------------------------------------------------------- */ 88/* ------------------------------------------------------------------------- */
83 89
84#define CNTL(c) ((c)-'@') 90#define CNTL(c) ((c)-'@')
85 91
86/*! 92/*!
87*/ 93*/
88 94
89TEmulation::TEmulation(TEWidget* gui) 95TEmulation::TEmulation(TEWidget* gui)
90: decoder((QTextDecoder*)NULL) 96: decoder((QTextDecoder*)NULL)
91{ 97{
92 this->gui = gui; 98 this->gui = gui;
93 99
94 screen[0] = new TEScreen(gui->Lines(),gui->Columns()); 100 screen[0] = new TEScreen(gui->Lines(),gui->Columns());
95 screen[1] = new TEScreen(gui->Lines(),gui->Columns()); 101 screen[1] = new TEScreen(gui->Lines(),gui->Columns());
96 scr = screen[0]; 102 scr = screen[0];
97 103
98 bulk_nlcnt = 0; // reset bulk newline counter 104 bulk_nlcnt = 0; // reset bulk newline counter
99 bulk_incnt = 0; // reset bulk counter 105 bulk_incnt = 0; // reset bulk counter
100 connected = FALSE; 106 connected = FALSE;
101 107
102 QObject::connect(&bulk_timer, SIGNAL(timeout()), this, SLOT(showBulk()) ); 108 QObject::connect(&bulk_timer, SIGNAL(timeout()), this, SLOT(showBulk()) );
103 QObject::connect(gui,SIGNAL(changedImageSizeSignal(int,int)), 109 QObject::connect(gui,SIGNAL(changedImageSizeSignal(int,int)),
104 this,SLOT(onImageSizeChange(int,int))); 110 this,SLOT(onImageSizeChange(int,int)));
105 QObject::connect(gui,SIGNAL(changedHistoryCursor(int)), 111 QObject::connect(gui,SIGNAL(changedHistoryCursor(int)),
106 this,SLOT(onHistoryCursorChange(int))); 112 this,SLOT(onHistoryCursorChange(int)));
107 QObject::connect(gui,SIGNAL(keyPressedSignal(QKeyEvent*)), 113 QObject::connect(gui,SIGNAL(keyPressedSignal(QKeyEvent*)),
108 this,SLOT(onKeyPress(QKeyEvent*))); 114 this,SLOT(onKeyPress(QKeyEvent*)));
109 QObject::connect(gui,SIGNAL(beginSelectionSignal(const int,const int)), 115 QObject::connect(gui,SIGNAL(beginSelectionSignal(const int,const int)),
110 this,SLOT(onSelectionBegin(const int,const int)) ); 116 this,SLOT(onSelectionBegin(const int,const int)) );
111 QObject::connect(gui,SIGNAL(extendSelectionSignal(const int,const int)), 117 QObject::connect(gui,SIGNAL(extendSelectionSignal(const int,const int)),
112 this,SLOT(onSelectionExtend(const int,const int)) ); 118 this,SLOT(onSelectionExtend(const int,const int)) );
113 QObject::connect(gui,SIGNAL(endSelectionSignal(const BOOL)), 119 QObject::connect(gui,SIGNAL(endSelectionSignal(const BOOL)),
114 this,SLOT(setSelection(const BOOL)) ); 120 this,SLOT(setSelection(const BOOL)) );
115 QObject::connect(gui,SIGNAL(clearSelectionSignal()), 121 QObject::connect(gui,SIGNAL(clearSelectionSignal()),
116 this,SLOT(clearSelection()) ); 122 this,SLOT(clearSelection()) );
117} 123}
118 124
119/*! 125/*!
120*/ 126*/
121 127
122TEmulation::~TEmulation() 128TEmulation::~TEmulation()
123{ 129{
124 delete screen[0]; 130 delete screen[0];
125 delete screen[1]; 131 delete screen[1];
126 bulk_timer.stop(); 132 bulk_timer.stop();
127} 133}
128 134
129/*! change between primary and alternate screen 135/*! change between primary and alternate screen
130*/ 136*/
131 137
132void TEmulation::setScreen(int n) 138void TEmulation::setScreen(int n)
133{ 139{
134 scr = screen[n&1]; 140 scr = screen[n&1];
135} 141}
136 142
137void TEmulation::setHistory(bool on) 143void TEmulation::setHistory(bool on)
138{ 144{
139 screen[0]->setScroll(on); 145 screen[0]->setScroll(on);
140 if (!connected) return; 146 if (!connected) return;
141 showBulk(); 147 showBulk();
142} 148}
143 149
144bool TEmulation::history() 150bool TEmulation::history()
145{ 151{
146 return screen[0]->hasScroll(); 152 return screen[0]->hasScroll();
147} 153}
148 154
149void TEmulation::setCodec(int c) 155void TEmulation::setCodec(int c)
150{ 156{
151 //FIXME: check whether we have to free codec 157 //FIXME: check whether we have to free codec
152 codec = c ? QTextCodec::codecForName("utf8") 158 codec = c ? QTextCodec::codecForName("utf8")
153 : QTextCodec::codecForLocale(); 159 : QTextCodec::codecForLocale();
154 if (decoder) delete decoder; 160 if (decoder) delete decoder;
155 decoder = codec->makeDecoder(); 161 decoder = codec->makeDecoder();
156} 162}
157 163
158void TEmulation::setKeytrans(int no) 164void TEmulation::setKeytrans(int no)
159{ 165{
160 keytrans = KeyTrans::find(no); 166 keytrans = KeyTrans::find(no);
161} 167}
162 168
163void TEmulation::setKeytrans(const char * no) 169void TEmulation::setKeytrans(const char * no)
164{ 170{
165 keytrans = KeyTrans::find(no); 171 keytrans = KeyTrans::find(no);
166} 172}
167 173
168// Interpreting Codes --------------------------------------------------------- 174// Interpreting Codes ---------------------------------------------------------
169 175
170/* 176/*
171 This section deals with decoding the incoming character stream. 177 This section deals with decoding the incoming character stream.
172 Decoding means here, that the stream is first seperated into `tokens' 178 Decoding means here, that the stream is first seperated into `tokens'
173 which are then mapped to a `meaning' provided as operations by the 179 which are then mapped to a `meaning' provided as operations by the
174 `Screen' class. 180 `Screen' class.
175*/ 181*/
176 182
177/*! 183/*!
178*/ 184*/
179 185
180void TEmulation::onRcvChar(int c) 186void TEmulation::onRcvChar(int c)
181// process application unicode input to terminal 187// process application unicode input to terminal
182// this is a trivial scanner 188// this is a trivial scanner
183{ 189{
184 c &= 0xff; 190 c &= 0xff;
185 switch (c) 191 switch (c)
186 { 192 {
187 case '\b' : scr->BackSpace(); break; 193 case '\b' : scr->BackSpace(); break;
188 case '\t' : scr->Tabulate(); break; 194 case '\t' : scr->Tabulate(); break;
189 case '\n' : scr->NewLine(); break; 195 case '\n' : scr->NewLine(); break;
190 case '\r' : scr->Return(); break; 196 case '\r' : scr->Return(); break;
191 case 0x07 : gui->Bell(); break; 197 case 0x07 : gui->Bell(); break;
192 default : scr->ShowCharacter(c); break; 198 default : scr->ShowCharacter(c); break;
193 }; 199 };
194} 200}
195 201
196/* ------------------------------------------------------------------------- */ 202/* ------------------------------------------------------------------------- */
197/* */ 203/* */
198/* Keyboard Handling */ 204/* Keyboard Handling */
199/* */ 205/* */
200/* ------------------------------------------------------------------------- */ 206/* ------------------------------------------------------------------------- */
201 207
202/*! 208/*!
203*/ 209*/
204 210
205void TEmulation::onKeyPress( QKeyEvent* ev ) 211void TEmulation::onKeyPress( QKeyEvent* ev )
206{ 212{
207 qWarning("onKeyPress,...."); 213 owarn << "onKeyPress,...." << oendl;
208 if (!connected) return; // someone else gets the keys 214 if (!connected) return; // someone else gets the keys
209 if (scr->getHistCursor() != scr->getHistLines()); 215 if (scr->getHistCursor() != scr->getHistLines());
210 scr->setHistCursor(scr->getHistLines()); 216 scr->setHistCursor(scr->getHistLines());
211 if (!ev->text().isEmpty()) 217 if (!ev->text().isEmpty())
212 { // A block of text 218 { // A block of text
213 // Note that the text is proper unicode. 219 // Note that the text is proper unicode.
214 // We should do a conversion here, but since this 220 // We should do a conversion here, but since this
215 // routine will never be used, we simply emit plain ascii. 221 // routine will never be used, we simply emit plain ascii.
216 emit sndBlock(ev->text().ascii(),ev->text().length()); 222 emit sndBlock(ev->text().ascii(),ev->text().length());
217 } 223 }
218 else if (ev->ascii()>0) 224 else if (ev->ascii()>0)
219 { unsigned char c[1]; 225 { unsigned char c[1];
220 c[0] = ev->ascii(); 226 c[0] = ev->ascii();
221 emit sndBlock((char*)c,1); 227 emit sndBlock((char*)c,1);
222 } 228 }
223} 229}
224 230
225// Unblocking, Byte to Unicode translation --------------------------------- -- 231// Unblocking, Byte to Unicode translation --------------------------------- --
226 232
227/* 233/*
228 We are doing code conversion from locale to unicode first. 234 We are doing code conversion from locale to unicode first.
229*/ 235*/
230 236
231void TEmulation::onRcvBlock(const char *s, int len) 237void TEmulation::onRcvBlock(const char *s, int len)
232{ 238{
233 bulkStart(); 239 bulkStart();
234 bulk_incnt += 1; 240 bulk_incnt += 1;
235 for (int i = 0; i < len; i++) 241 for (int i = 0; i < len; i++)
236 { 242 {
237 QString result = decoder->toUnicode(&s[i],1); 243 QString result = decoder->toUnicode(&s[i],1);
238 int reslen = result.length(); 244 int reslen = result.length();
239 for (int j = 0; j < reslen; j++) 245 for (int j = 0; j < reslen; j++)
240 onRcvChar(result[j].unicode()); 246 onRcvChar(result[j].unicode());
241 if (s[i] == '\n') bulkNewline(); 247 if (s[i] == '\n') bulkNewline();
242 } 248 }
243 bulkEnd(); 249 bulkEnd();
244} 250}
245 251
246// Selection --------------------------------------------------------------- -- 252// Selection --------------------------------------------------------------- --
247 253
248void TEmulation::onSelectionBegin(const int x, const int y) { 254void TEmulation::onSelectionBegin(const int x, const int y) {
249 if (!connected) return; 255 if (!connected) return;
250 scr->setSelBeginXY(x,y); 256 scr->setSelBeginXY(x,y);
251 showBulk(); 257 showBulk();
252} 258}
253 259
254void TEmulation::onSelectionExtend(const int x, const int y) { 260void TEmulation::onSelectionExtend(const int x, const int y) {
255 if (!connected) return; 261 if (!connected) return;
256 scr->setSelExtentXY(x,y); 262 scr->setSelExtentXY(x,y);
257 showBulk(); 263 showBulk();
258} 264}
259 265
260void TEmulation::setSelection(const BOOL preserve_line_breaks) { 266void TEmulation::setSelection(const BOOL preserve_line_breaks) {
261 if (!connected) return; 267 if (!connected) return;
262 QString t = scr->getSelText(preserve_line_breaks); 268 QString t = scr->getSelText(preserve_line_breaks);
263 if (!t.isNull()) gui->setSelection(t); 269 if (!t.isNull()) gui->setSelection(t);
264} 270}
265 271
266void TEmulation::clearSelection() { 272void TEmulation::clearSelection() {
267 if (!connected) return; 273 if (!connected) return;
268 scr->clearSelection(); 274 scr->clearSelection();
269 showBulk(); 275 showBulk();
270} 276}
271void TEmulation::streamHistory(QTextStream* stream) { 277void TEmulation::streamHistory(QTextStream* stream) {
272 *stream << scr->getHistory(); 278 *stream << scr->getHistory();
273} 279}
274// Refreshing -------------------------------------------------------------- -- 280// Refreshing -------------------------------------------------------------- --
275 281
276#define BULK_TIMEOUT 20 282#define BULK_TIMEOUT 20
277 283
278/*! 284/*!
279 called when \n comes in. Evtl. triggers showBulk at endBulk 285 called when \n comes in. Evtl. triggers showBulk at endBulk
280*/ 286*/
281 287
282void TEmulation::bulkNewline() 288void TEmulation::bulkNewline()
283{ 289{
284 bulk_nlcnt += 1; 290 bulk_nlcnt += 1;
285 bulk_incnt = 0; // reset bulk counter since `nl' rule applies 291 bulk_incnt = 0; // reset bulk counter since `nl' rule applies
286} 292}
287 293
288/*! 294/*!
289*/ 295*/
290 296
291void TEmulation::showBulk() 297void TEmulation::showBulk()
292{ 298{
293 bulk_nlcnt = 0; // reset bulk newline counter 299 bulk_nlcnt = 0; // reset bulk newline counter
294 bulk_incnt = 0; // reset bulk counter 300 bulk_incnt = 0; // reset bulk counter
295 if (connected) 301 if (connected)
296 { 302 {
297 ca* image = scr->getCookedImage(); // get the image 303 ca* image = scr->getCookedImage(); // get the image
298 gui->setImage(image, 304 gui->setImage(image,
299 scr->getLines(), 305 scr->getLines(),
300 scr->getColumns()); // actual refresh 306 scr->getColumns()); // actual refresh
301 free(image); 307 free(image);
302 //FIXME: check that we do not trigger other draw event here. 308 //FIXME: check that we do not trigger other draw event here.
303 gui->setScroll(scr->getHistCursor(),scr->getHistLines()); 309 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 @@
1#include "atconfigdialog.h"
2#include "io_modem.h"
1 3
4/* OPIE */
5#include <opie2/odebug.h>
6using namespace Opie::Core;
7
8/* QT */
2#include <qlineedit.h> 9#include <qlineedit.h>
3#include <qspinbox.h> 10#include <qspinbox.h>
4#include <qlayout.h> 11#include <qlayout.h>
5#include <qcombobox.h> 12#include <qcombobox.h>
6#include <qtabwidget.h> 13#include <qtabwidget.h>
7#include <qlabel.h> 14#include <qlabel.h>
8#include <qscrollview.h> 15#include <qscrollview.h>
9 16
10#include "atconfigdialog.h"
11#include "io_modem.h"
12
13
14ATConfigDialog::ATConfigDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) 17ATConfigDialog::ATConfigDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
15 : QDialog( parent, name, modal, fl ) { 18 : QDialog( parent, name, modal, fl ) {
16 19
17 20
18 setCaption( tr( "Dialing parameter setup" ) ); 21 setCaption( tr( "Dialing parameter setup" ) );
19 22
20 QVBoxLayout *layout = new QVBoxLayout( this ); 23 QVBoxLayout *layout = new QVBoxLayout( this );
21 QTabWidget *tabWidget = new QTabWidget( this ); 24 QTabWidget *tabWidget = new QTabWidget( this );
22 25
23 tabWidget->addTab( tab0( this ), tr("Settings1") ); 26 tabWidget->addTab( tab0( this ), tr("Settings1") );
24 tabWidget->addTab( tab1( this ), tr("Settings2") ); 27 tabWidget->addTab( tab1( this ), tr("Settings2") );
25 28
26 layout->addWidget( tabWidget ); 29 layout->addWidget( tabWidget );
27 30
28} 31}
29 32
30QWidget* ATConfigDialog::tab0( QWidget* parent) { 33QWidget* ATConfigDialog::tab0( QWidget* parent) {
31 34
32 35
33 QScrollView* sv = new QScrollView( parent ); 36 QScrollView* sv = new QScrollView( parent );
34 37
35 QWidget *returnWidget = new QWidget( sv->viewport() ); 38 QWidget *returnWidget = new QWidget( sv->viewport() );
36 sv->setResizePolicy( QScrollView::AutoOneFit ); 39 sv->setResizePolicy( QScrollView::AutoOneFit );
37// sv->setHScrollBarMode( QScrollView::AlwaysOff ); 40// sv->setHScrollBarMode( QScrollView::AlwaysOff );
38// sv->setFrameShape( QFrame::NoFrame ); 41// sv->setFrameShape( QFrame::NoFrame );
39 42
40 43
41 44
42 45
43 QGridLayout *layout = new QGridLayout( returnWidget, 10, 2 ); 46 QGridLayout *layout = new QGridLayout( returnWidget, 10, 2 );
44 47
45 QLabel *initStringLabel = new QLabel( tr("Init string "), returnWidget ); 48 QLabel *initStringLabel = new QLabel( tr("Init string "), returnWidget );
46 initStringLine = new QLineEdit( returnWidget ); 49 initStringLine = new QLineEdit( returnWidget );
47 layout->addWidget( initStringLabel, 0, 0 ); 50 layout->addWidget( initStringLabel, 0, 0 );
48 layout->addWidget( initStringLine, 0, 1 ); 51 layout->addWidget( initStringLine, 0, 1 );
49 52
50 QLabel *resetStringLabel = new QLabel( tr("Reset string "), returnWidget ); 53 QLabel *resetStringLabel = new QLabel( tr("Reset string "), returnWidget );
51 resetStringLine = new QLineEdit( returnWidget ); 54 resetStringLine = new QLineEdit( returnWidget );
52 layout->addWidget( resetStringLabel, 1, 0 ); 55 layout->addWidget( resetStringLabel, 1, 0 );
53 layout->addWidget( resetStringLine, 1, 1 ); 56 layout->addWidget( resetStringLine, 1, 1 );
54 57
55 QLabel *dialPref1Label = new QLabel( tr("Dialing prefix #1 " ), returnWidget ); 58 QLabel *dialPref1Label = new QLabel( tr("Dialing prefix #1 " ), returnWidget );
56 dialPref1Line = new QLineEdit( returnWidget ); 59 dialPref1Line = new QLineEdit( returnWidget );
57 layout->addWidget( dialPref1Label, 2, 0 ); 60 layout->addWidget( dialPref1Label, 2, 0 );
58 layout->addWidget( dialPref1Line, 2, 1 ); 61 layout->addWidget( dialPref1Line, 2, 1 );
59 62
60 QLabel *dialSuf1Label = new QLabel( tr("Dialing suffix #1 " ), returnWidget ); 63 QLabel *dialSuf1Label = new QLabel( tr("Dialing suffix #1 " ), returnWidget );
61 dialSuf1Line = new QLineEdit( returnWidget ); 64 dialSuf1Line = new QLineEdit( returnWidget );
62 layout->addWidget( dialSuf1Label, 3, 0 ); 65 layout->addWidget( dialSuf1Label, 3, 0 );
63 layout->addWidget( dialSuf1Line, 3, 1 ); 66 layout->addWidget( dialSuf1Line, 3, 1 );
64 67
65 QLabel *dialPref2Label = new QLabel( tr("Dialing prefix #2 " ), returnWidget ); 68 QLabel *dialPref2Label = new QLabel( tr("Dialing prefix #2 " ), returnWidget );
66 dialPref2Line = new QLineEdit( returnWidget ); 69 dialPref2Line = new QLineEdit( returnWidget );
67 layout->addWidget( dialPref2Label, 4, 0 ); 70 layout->addWidget( dialPref2Label, 4, 0 );
68 layout->addWidget( dialPref2Line, 4, 1 ); 71 layout->addWidget( dialPref2Line, 4, 1 );
69 72
70 QLabel *dialSuf2Label = new QLabel( tr("Dialing suffix #2 " ), returnWidget ); 73 QLabel *dialSuf2Label = new QLabel( tr("Dialing suffix #2 " ), returnWidget );
71 dialSuf2Line = new QLineEdit( returnWidget ); 74 dialSuf2Line = new QLineEdit( returnWidget );
72 layout->addWidget( dialSuf2Label, 5, 0 ); 75 layout->addWidget( dialSuf2Label, 5, 0 );
73 layout->addWidget( dialSuf2Line, 5, 1 ); 76 layout->addWidget( dialSuf2Line, 5, 1 );
74 77
75 QLabel *dialPref3Label = new QLabel( tr("Dialing prefix #3 " ), returnWidget ); 78 QLabel *dialPref3Label = new QLabel( tr("Dialing prefix #3 " ), returnWidget );
76 dialPref3Line = new QLineEdit( returnWidget ); 79 dialPref3Line = new QLineEdit( returnWidget );
77 layout->addWidget( dialPref3Label, 6, 0 ); 80 layout->addWidget( dialPref3Label, 6, 0 );
78 layout->addWidget( dialPref3Line, 6, 1 ); 81 layout->addWidget( dialPref3Line, 6, 1 );
79 82
80 QLabel *dialSuf3Label = new QLabel( tr("Dialing suffix #3 " ), returnWidget ); 83 QLabel *dialSuf3Label = new QLabel( tr("Dialing suffix #3 " ), returnWidget );
81 dialSuf3Line = new QLineEdit( returnWidget ); 84 dialSuf3Line = new QLineEdit( returnWidget );
82 layout->addWidget( dialSuf3Label, 7, 0 ); 85 layout->addWidget( dialSuf3Label, 7, 0 );
83 layout->addWidget( dialSuf3Line, 7, 1 ); 86 layout->addWidget( dialSuf3Line, 7, 1 );
84 87
85 QLabel *connectLabel = new QLabel( tr("Connect string " ), returnWidget ); 88 QLabel *connectLabel = new QLabel( tr("Connect string " ), returnWidget );
86 connectLine = new QLineEdit( returnWidget ); 89 connectLine = new QLineEdit( returnWidget );
87 layout->addWidget( connectLabel, 8, 0 ); 90 layout->addWidget( connectLabel, 8, 0 );
88 layout->addWidget( connectLine, 8, 1 ); 91 layout->addWidget( connectLine, 8, 1 );
89 92
90 QLabel *hangupLabel = new QLabel( tr("Hang-up string " ), returnWidget ); 93 QLabel *hangupLabel = new QLabel( tr("Hang-up string " ), returnWidget );
91 hangupLine = new QLineEdit( returnWidget ); 94 hangupLine = new QLineEdit( returnWidget );
92 layout->addWidget( hangupLabel, 9, 0 ); 95 layout->addWidget( hangupLabel, 9, 0 );
93 layout->addWidget( hangupLine, 9, 1 ); 96 layout->addWidget( hangupLine, 9, 1 );
94 97
95 sv->addChild( returnWidget ); 98 sv->addChild( returnWidget );
96 99
97 return sv; 100 return sv;
98 101
99} 102}
100 103
101QWidget* ATConfigDialog::tab1( QWidget* parent ) { 104QWidget* ATConfigDialog::tab1( QWidget* parent ) {
102 105
103 106
104 QWidget *returnWidget = new QWidget( parent ); 107 QWidget *returnWidget = new QWidget( parent );
105 108
106 QGridLayout *layout = new QGridLayout( returnWidget, 8, 2 ); 109 QGridLayout *layout = new QGridLayout( returnWidget, 8, 2 );
107 110
108 QLabel *dialTimeLabel = new QLabel( tr("Dial time " ), returnWidget ); 111 QLabel *dialTimeLabel = new QLabel( tr("Dial time " ), returnWidget );
109 dialTimeSpin = new QSpinBox( returnWidget ); 112 dialTimeSpin = new QSpinBox( returnWidget );
110 layout->addWidget( dialTimeLabel, 0, 0 ); 113 layout->addWidget( dialTimeLabel, 0, 0 );
111 layout->addWidget( dialTimeSpin, 0, 1 ); 114 layout->addWidget( dialTimeSpin, 0, 1 );
112 115
113 QLabel *delayRedialLabel = new QLabel( tr("Delay before redial " ), returnWidget ); 116 QLabel *delayRedialLabel = new QLabel( tr("Delay before redial " ), returnWidget );
114 delayRedialSpin = new QSpinBox( returnWidget ); 117 delayRedialSpin = new QSpinBox( returnWidget );
115 layout->addWidget( delayRedialLabel, 1, 0 ); 118 layout->addWidget( delayRedialLabel, 1, 0 );
116 layout->addWidget( delayRedialSpin, 1, 1 ); 119 layout->addWidget( delayRedialSpin, 1, 1 );
117 120
118 QLabel *numberTriesLabel = new QLabel( tr("Number of tries " ), returnWidget ); 121 QLabel *numberTriesLabel = new QLabel( tr("Number of tries " ), returnWidget );
119 numberTriesSpin = new QSpinBox( returnWidget ); 122 numberTriesSpin = new QSpinBox( returnWidget );
120 layout->addWidget( numberTriesLabel, 2, 0 ); 123 layout->addWidget( numberTriesLabel, 2, 0 );
121 layout->addWidget( numberTriesSpin, 2, 1 ); 124 layout->addWidget( numberTriesSpin, 2, 1 );
122 125
123 QLabel *dtrDropTimeLabel = new QLabel( tr("DTR drop time (0=no) " ), returnWidget ); 126 QLabel *dtrDropTimeLabel = new QLabel( tr("DTR drop time (0=no) " ), returnWidget );
124 dtrDropTimeSpin = new QSpinBox( returnWidget ); 127 dtrDropTimeSpin = new QSpinBox( returnWidget );
125 layout->addWidget( dtrDropTimeLabel, 3, 0 ); 128 layout->addWidget( dtrDropTimeLabel, 3, 0 );
126 layout->addWidget( dtrDropTimeSpin, 3, 1 ); 129 layout->addWidget( dtrDropTimeSpin, 3, 1 );
127 130
128 QLabel *bpsDetectLabel = new QLabel( tr("Auto bps detect " ), returnWidget ); 131 QLabel *bpsDetectLabel = new QLabel( tr("Auto bps detect " ), returnWidget );
129 bpsDetectBox = new QComboBox( returnWidget ); 132 bpsDetectBox = new QComboBox( returnWidget );
130 layout->addWidget( bpsDetectLabel, 4, 0 ); 133 layout->addWidget( bpsDetectLabel, 4, 0 );
131 layout->addWidget( bpsDetectBox, 4, 1 ); 134 layout->addWidget( bpsDetectBox, 4, 1 );
132 bpsDetectBox->insertItem( tr("No") ); 135 bpsDetectBox->insertItem( tr("No") );
133 bpsDetectBox->insertItem( tr("Yes") ); 136 bpsDetectBox->insertItem( tr("Yes") );
134 137
135 QLabel *dcdLinesLabel = new QLabel( tr("Modem has DCD line " ), returnWidget ); 138 QLabel *dcdLinesLabel = new QLabel( tr("Modem has DCD line " ), returnWidget );
136 dcdLinesBox = new QComboBox( returnWidget ); 139 dcdLinesBox = new QComboBox( returnWidget );
137 layout->addWidget( dcdLinesLabel, 5, 0 ); 140 layout->addWidget( dcdLinesLabel, 5, 0 );
138 layout->addWidget( dcdLinesBox, 5, 1 ); 141 layout->addWidget( dcdLinesBox, 5, 1 );
139 dcdLinesBox->insertItem( tr("No") ); 142 dcdLinesBox->insertItem( tr("No") );
140 dcdLinesBox->insertItem( tr("Yes") ); 143 dcdLinesBox->insertItem( tr("Yes") );
141 144
142 QLabel *multiLineUntagLabel = new QLabel( tr("Multi-line untag " ), returnWidget ); 145 QLabel *multiLineUntagLabel = new QLabel( tr("Multi-line untag " ), returnWidget );
143 multiLineUntagBox = new QComboBox( returnWidget ); 146 multiLineUntagBox = new QComboBox( returnWidget );
144 layout->addWidget( multiLineUntagLabel, 6, 0 ); 147 layout->addWidget( multiLineUntagLabel, 6, 0 );
145 layout->addWidget( multiLineUntagBox, 6, 1 ); 148 layout->addWidget( multiLineUntagBox, 6, 1 );
146 multiLineUntagBox->insertItem( tr("No") ); 149 multiLineUntagBox->insertItem( tr("No") );
147 multiLineUntagBox->insertItem( tr("Yes") ); 150 multiLineUntagBox->insertItem( tr("Yes") );
148 151
149 return returnWidget; 152 return returnWidget;
150 153
151} 154}
152 155
153 156
154void ATConfigDialog::readConfig( const Profile& config ) { 157void ATConfigDialog::readConfig( const Profile& config ) {
155 qWarning("config in atconfigdialog"); 158 owarn << "config in atconfigdialog" << oendl;
156 159
157 initStringLine->setText( config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING ) ); 160 initStringLine->setText( config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING ) );
158 resetStringLine->setText( config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING ) ); 161 resetStringLine->setText( config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING ) );
159 dialPref1Line->setText( config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ) ); 162 dialPref1Line->setText( config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ) );
160 dialSuf1Line->setText( config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 ) ); 163 dialSuf1Line->setText( config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
161 dialPref2Line->setText( config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 ) ); 164 dialPref2Line->setText( config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 ) );
162 dialSuf2Line->setText( config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 ) ); 165 dialSuf2Line->setText( config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
163 dialPref3Line->setText( config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 ) ); 166 dialPref3Line->setText( config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 ) );
164 dialSuf3Line->setText( config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 ) ); 167 dialSuf3Line->setText( config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
165 connectLine->setText( config.readEntry("DefaultConnect", MODEM_DEFAULT_CONNECT_STRING ) ); 168 connectLine->setText( config.readEntry("DefaultConnect", MODEM_DEFAULT_CONNECT_STRING ) );
166 hangupLine->setText( config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) ); 169 hangupLine->setText( config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) );
167 dialTimeSpin->setValue( config.readNumEntry("DialTime", MODEM_DEFAULT_DIAL_TIME ) ); 170 dialTimeSpin->setValue( config.readNumEntry("DialTime", MODEM_DEFAULT_DIAL_TIME ) );
168 delayRedialSpin->setValue( config.readNumEntry("DelayRedial", MODEM_DEFAULT_DELAY_REDIAL ) ); 171 delayRedialSpin->setValue( config.readNumEntry("DelayRedial", MODEM_DEFAULT_DELAY_REDIAL ) );
169 numberTriesSpin->setValue( config.readNumEntry("NumberTries", MODEM_DEFAULT_NUMBER_TRIES ) ); 172 numberTriesSpin->setValue( config.readNumEntry("NumberTries", MODEM_DEFAULT_NUMBER_TRIES ) );
170 dtrDropTimeSpin->setValue( config.readNumEntry("DTRDRopTime", MODEM_DEFAULT_DTR_DROP_TIME ) ); 173 dtrDropTimeSpin->setValue( config.readNumEntry("DTRDRopTime", MODEM_DEFAULT_DTR_DROP_TIME ) );
171 bpsDetectBox->setCurrentItem( config.readBoolEntry("BPSDetect", MODEM_DEFAULT_BPS_DETECT ) ); 174 bpsDetectBox->setCurrentItem( config.readBoolEntry("BPSDetect", MODEM_DEFAULT_BPS_DETECT ) );
172 dcdLinesBox->setCurrentItem( config.readBoolEntry("DCDLines", MODEM_DEFAULT_DCD_LINES ) ); 175 dcdLinesBox->setCurrentItem( config.readBoolEntry("DCDLines", MODEM_DEFAULT_DCD_LINES ) );
173 multiLineUntagBox->setCurrentItem( config.readBoolEntry("MultiLineUntag", MODEM_DEFAULT_MULTI_LINE_UNTAG ) ); 176 multiLineUntagBox->setCurrentItem( config.readBoolEntry("MultiLineUntag", MODEM_DEFAULT_MULTI_LINE_UNTAG ) );
174 177
175 // Not implemented yet 178 // Not implemented yet
176 resetStringLine->setEnabled(false); 179 resetStringLine->setEnabled(false);
177 dialSuf1Line->setEnabled(false); 180 dialSuf1Line->setEnabled(false);
178 dialPref2Line->setEnabled(false); 181 dialPref2Line->setEnabled(false);
179 dialSuf2Line->setEnabled(false); 182 dialSuf2Line->setEnabled(false);
180 dialPref3Line->setEnabled(false); 183 dialPref3Line->setEnabled(false);
181 dialSuf3Line->setEnabled(false); 184 dialSuf3Line->setEnabled(false);
182 dialTimeSpin->setEnabled(false); 185 dialTimeSpin->setEnabled(false);
183 delayRedialSpin->setEnabled(false); 186 delayRedialSpin->setEnabled(false);
184 numberTriesSpin->setEnabled(false); 187 numberTriesSpin->setEnabled(false);
185 dtrDropTimeSpin->setEnabled(false); 188 dtrDropTimeSpin->setEnabled(false);
186 bpsDetectBox->setEnabled(false); 189 bpsDetectBox->setEnabled(false);
187 dcdLinesBox->setEnabled(false); 190 dcdLinesBox->setEnabled(false);
188 multiLineUntagBox->setEnabled(false); 191 multiLineUntagBox->setEnabled(false);
189} 192}
190 193
191void ATConfigDialog::writeConfig( Profile& config ) { 194void ATConfigDialog::writeConfig( Profile& config ) {
192 195
193 config.writeEntry( "InitString", initStringLine->text() ); 196 config.writeEntry( "InitString", initStringLine->text() );
194 config.writeEntry( "ResetString", resetStringLine->text() ); 197 config.writeEntry( "ResetString", resetStringLine->text() );
195 config.writeEntry( "DialPrefix1", dialPref1Line->text() ); 198 config.writeEntry( "DialPrefix1", dialPref1Line->text() );
196 config.writeEntry( "DialSuffix1", dialSuf1Line->text() ); 199 config.writeEntry( "DialSuffix1", dialSuf1Line->text() );
197 config.writeEntry( "DialPrefix2", dialPref2Line->text() ); 200 config.writeEntry( "DialPrefix2", dialPref2Line->text() );
198 config.writeEntry( "DialSuffix2", dialSuf2Line->text() ); 201 config.writeEntry( "DialSuffix2", dialSuf2Line->text() );
199 config.writeEntry( "DialPrefix3", dialPref3Line->text() ); 202 config.writeEntry( "DialPrefix3", dialPref3Line->text() );
200 config.writeEntry( "DialSuffix3", dialSuf3Line->text() ); 203 config.writeEntry( "DialSuffix3", dialSuf3Line->text() );
201 config.writeEntry( "DefaultConnect", connectLine->text() ); 204 config.writeEntry( "DefaultConnect", connectLine->text() );
202 config.writeEntry( "HangupString", hangupLine->text() ); 205 config.writeEntry( "HangupString", hangupLine->text() );
203 config.writeEntry( "DialTime", dialTimeSpin->value() ); 206 config.writeEntry( "DialTime", dialTimeSpin->value() );
204 config.writeEntry( "DelayRedial", delayRedialSpin->value() ); 207 config.writeEntry( "DelayRedial", delayRedialSpin->value() );
205 config.writeEntry( "NumberTries", numberTriesSpin->value() ); 208 config.writeEntry( "NumberTries", numberTriesSpin->value() );
206 config.writeEntry( "DTRDRopTime", dtrDropTimeSpin->value() ); 209 config.writeEntry( "DTRDRopTime", dtrDropTimeSpin->value() );
207 config.writeEntry( "BPSDetect", bpsDetectBox->currentItem() ); 210 config.writeEntry( "BPSDetect", bpsDetectBox->currentItem() );
208 config.writeEntry( "DCDLines", dcdLinesBox->currentItem() ); 211 config.writeEntry( "DCDLines", dcdLinesBox->currentItem() );
209 config.writeEntry( "MultiLineUntag", multiLineUntagBox->currentItem() ); 212 config.writeEntry( "MultiLineUntag", multiLineUntagBox->currentItem() );
210 213
211} 214}
212 215
213 216
214ATConfigDialog::~ATConfigDialog() { 217ATConfigDialog::~ATConfigDialog() {
215} 218}
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 @@
1#include "dialer.h" 1#include "dialer.h"
2#include "io_modem.h"
3
4/* OPIE */
5#include <opie2/odebug.h>
6using namespace Opie::Core;
2 7
8/* QT */
3#include <qlayout.h> 9#include <qlayout.h>
4#include <qprogressbar.h> 10#include <qprogressbar.h>
5#include <qlabel.h> 11#include <qlabel.h>
6#include <qpushbutton.h> 12#include <qpushbutton.h>
7#include <qapp.h> 13#include <qapp.h>
8#include <qtimer.h> 14#include <qtimer.h>
9#include <qmessagebox.h> 15#include <qmessagebox.h>
10 16
17/* STD */
11#include <unistd.h> 18#include <unistd.h>
12#include <string.h> 19#include <string.h>
13#include <fcntl.h> 20#include <fcntl.h>
14#include <errno.h> 21#include <errno.h>
15 22
16#include "io_modem.h"
17
18// State machine: | When an error occurs, we don't have to 23// State machine: | When an error occurs, we don't have to
19// | reset everything. 24// | reset everything.
20// (init) <------+ | But if the user wants to reset, 25// (init) <------+ | But if the user wants to reset,
21// | | | we stop dialing immediately. 26// | | | we stop dialing immediately.
22// v | | 27// v | |
23// (options) ----+ | Following the state machine is necessary 28// (options) ----+ | Following the state machine is necessary
24// | \ | to get determinable results. 29// | \ | to get determinable results.
25// v ^ | 30// v ^ |
26// (dial) ----+ | 31// (dial) ----+ |
27// | ^ | 32// | ^ |
28// v | | 33// v | |
29// (online) --+ | 34// (online) --+ |
30// | | 35// | |
31// v | 36// v |
32 37
33 38
34// from atconfigdialog 39// from atconfigdialog
35//initStringLine->setText( config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING ) ); 40//initStringLine->setText( config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING ) );
36//resetStringLine->setText( config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING ) ); 41//resetStringLine->setText( config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING ) );
37//dialPref1Line->setText( config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ) ); 42//dialPref1Line->setText( config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ) );
38//dialSuf1Line->setText( config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 ) ); 43//dialSuf1Line->setText( config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
39//dialPref2Line->setText( config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 ) ); 44//dialPref2Line->setText( config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 ) );
40//dialSuf2Line->setText( config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 ) ); 45//dialSuf2Line->setText( config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
41//dialPref3Line->setText( config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 ) ); 46//dialPref3Line->setText( config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 ) );
42//dialSuf3Line->setText( config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 ) ); 47//dialSuf3Line->setText( config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 ) );
43//connectLine->setText( config.readEntry("DefaultConnect" MODEM_DEFAULT_CONNECT_STRING ) ); 48//connectLine->setText( config.readEntry("DefaultConnect" MODEM_DEFAULT_CONNECT_STRING ) );
44//hangupLine->setText( config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) ); 49//hangupLine->setText( config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) );
45 50
46// from modemconfigwidget 51// from modemconfigwidget
47//int rad_flow = prof.readNumEntry("Flow"); 52//int rad_flow = prof.readNumEntry("Flow");
48//int rad_parity = prof.readNumEntry("Parity"); 53//int rad_parity = prof.readNumEntry("Parity");
49//int speed = prof.readNumEntry("Speed"); 54//int speed = prof.readNumEntry("Speed");
50//QString number = prof.readEntry("Number"); 55//QString number = prof.readEntry("Number");
51 56
52Dialer::Dialer(const Profile& profile, int fd, QWidget *parent, const char *name) 57Dialer::Dialer(const Profile& profile, int fd, QWidget *parent, const char *name)
53: QDialog(parent, name, true), m_fd(fd), m_profile(profile) 58: QDialog(parent, name, true), m_fd(fd), m_profile(profile)
54{ 59{
55 QVBoxLayout *vbox; 60 QVBoxLayout *vbox;
56 QLabel *desc; 61 QLabel *desc;
57 62
58 63
59 usercancel = 0; 64 usercancel = 0;
60 cleanshutdown = 0; 65 cleanshutdown = 0;
61 66
62 67
63 desc = new QLabel(QObject::tr("Dialing number: %1").arg(m_profile.readEntry("Number")), this); 68 desc = new QLabel(QObject::tr("Dialing number: %1").arg(m_profile.readEntry("Number")), this);
64 progress = new QProgressBar(this); 69 progress = new QProgressBar(this);
65 status = new QLabel("", this); 70 status = new QLabel("", this);
66 status->setFrameStyle(QFrame::Panel | QFrame::Sunken); 71 status->setFrameStyle(QFrame::Panel | QFrame::Sunken);
67 cancel = new QPushButton(QObject::tr("Cancel"), this); 72 cancel = new QPushButton(QObject::tr("Cancel"), this);
68 73
69 vbox = new QVBoxLayout(this, 2); 74 vbox = new QVBoxLayout(this, 2);
70 vbox->add(desc); 75 vbox->add(desc);
71 vbox->add(progress); 76 vbox->add(progress);
72 vbox->add(status); 77 vbox->add(status);
73 vbox->add(cancel); 78 vbox->add(cancel);
74 79
75 connect(cancel, SIGNAL(clicked()), SLOT(slotCancel())); 80 connect(cancel, SIGNAL(clicked()), SLOT(slotCancel()));
76 81
77 show(); 82 show();
78 83
79 QTimer::singleShot(500, this, SLOT(slotAutostart())); 84 QTimer::singleShot(500, this, SLOT(slotAutostart()));
80} 85}
81 86
82Dialer::~Dialer() 87Dialer::~Dialer()
83{ 88{
84} 89}
85 90
86void Dialer::setHangupOnly() 91void Dialer::setHangupOnly()
87{ 92{
88 state = state_cancel; 93 state = state_cancel;
89 usercancel = 1; 94 usercancel = 1;
90 send( m_profile.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING )+"\r" ); 95 send( m_profile.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING )+"\r" );
91} 96}
92 97
93void Dialer::slotCancel() 98void Dialer::slotCancel()
94{ 99{
95 if(state != state_online) 100 if(state != state_online)
96 { 101 {
97 usercancel = 1; 102 usercancel = 1;
98 reset(); 103 reset();
99 } 104 }
100 else { 105 else {
101 accept(); 106 accept();
102 } 107 }
103} 108}
104 109
105void Dialer::reset() 110void Dialer::reset()
106{ 111{
107 qWarning("reset"); 112 owarn << "reset" << oendl;
108 switchState(state_cancel); 113 switchState(state_cancel);
109} 114}
110 115
111void Dialer::slotAutostart() 116void Dialer::slotAutostart()
112{ 117{
113 //state = state_preinit; 118 //state = state_preinit;
114 dial(m_profile.readEntry("Number")); 119 dial(m_profile.readEntry("Number"));
115} 120}
116 121
117void Dialer::dial(const QString& number) 122void Dialer::dial(const QString& number)
118{ 123{
119 while(state != state_online) 124 while(state != state_online)
120 { 125 {
121 if(!usercancel) 126 if(!usercancel)
122 { 127 {
123 state = state_preinit; 128 state = state_preinit;
124 trydial(number); 129 trydial(number);
125 } 130 }
126 else break; 131 else break;
127 } 132 }
128 133
129 if(usercancel) 134 if(usercancel)
130 { 135 {
131 // modem hangup 136 // modem hangup
132 trydial(QString::null); 137 trydial(QString::null);
133 reject(); 138 reject();
134 } 139 }
135} 140}
136 141
137void Dialer::trydial(const QString& number) 142void Dialer::trydial(const QString& number)
138{ 143{
139 qWarning("TryDial:%s", number.latin1() ); 144 owarn << "TryDial:" << number.latin1() << "" << oendl;
140 if(state != state_cancel) switchState(state_preinit); 145 if(state != state_cancel) switchState(state_preinit);
141 if(cleanshutdown) 146 if(cleanshutdown)
142 { 147 {
143 qWarning("HangupString " + m_profile.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING)); 148 owarn << "HangupString " << m_profile.readEntry("HangupString") << oendl;
144 send(m_profile.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) + "\r"); 149 send(m_profile.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ) + "\r");
145 } 150 }
146 151
147 if(state != state_cancel) 152 if(state != state_cancel)
148 { 153 {
149 switchState(state_init); 154 switchState(state_init);
150// qWarning("Init String " + m_profile.readEntry("InitString") ); 155// owarn << "Init String " + m_profile.readEntry("InitString") << oendl;
151 send(m_profile.readEntry("InitString",MODEM_DEFAULT_INIT_STRING ) + "\r"); 156 send(m_profile.readEntry("InitString",MODEM_DEFAULT_INIT_STRING ) + "\r");
152 QString response2 = receive(); 157 QString response2 = receive();
153 if(!response2.contains("\nOK\r")) 158 if(!response2.contains("\nOK\r"))
154 reset(); 159 reset();
155 } 160 }
156 161
157 /*if(state != state_cancel) 162 /*if(state != state_cancel)
158 { 163 {
159 switchState(state_options); 164 switchState(state_options);
160 165
161 qWarning("ATM3l3"); 166 owarn << "ATM3l3" << oendl;
162 send("ATM3L3\r"); 167 send("ATM3L3\r");
163 QString response3 = receive(); 168 QString response3 = receive();
164 if(!response3.contains("\nOK\r")) 169 if(!response3.contains("\nOK\r"))
165 reset(); 170 reset();
166 } 171 }
167*/ 172*/
168 173
169 if(state != state_cancel) 174 if(state != state_cancel)
170 { 175 {
171 switchState(state_dialtone); 176 switchState(state_dialtone);
172 177
173 send("ATX1\r"); 178 send("ATX1\r");
174 QString response4 = receive(); 179 QString response4 = receive();
175 if(!response4.contains("\nOK\r")) 180 if(!response4.contains("\nOK\r"))
176 reset(); 181 reset();
177 } 182 }
178 183
179 if(state != state_cancel) 184 if(state != state_cancel)
180 { 185 {
181 qWarning("progress"); 186 owarn << "progress" << oendl;
182 switchState(state_dialing); 187 switchState(state_dialing);
183 188
184 // send(QString("ATDT %1\r").arg(number)); 189 // send(QString("ATDT %1\r").arg(number));
185 send(QString("%1 %2\r").arg(m_profile.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 )) 190 send(QString("%1 %2\r").arg(m_profile.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ))
186 .arg(number)); 191 .arg(number));
187 192
188 QString response5 = receive(); 193 QString response5 = receive();
189 if(!response5.contains("CONNECT") ) 194 if(!response5.contains("CONNECT") )
190 { 195 {
191 if(response5.contains("BUSY")) 196 if(response5.contains("BUSY"))
192 switchState(state_dialing); 197 switchState(state_dialing);
193 else 198 else
194 { 199 {
195 QMessageBox::warning(this, 200 QMessageBox::warning(this,
196 QObject::tr("Failure"), 201 QObject::tr("Failure"),
197 QObject::tr("Dialing the number failed.")); 202 QObject::tr("Dialing the number failed."));
198 slotCancel(); 203 slotCancel();
199 } 204 }
200 } 205 }
201 } 206 }
202 207
203 208
204 if(state != state_cancel) 209 if(state != state_cancel)
205 { 210 {
206 state = state_online; 211 state = state_online;
207 slotCancel(); 212 slotCancel();
208 } 213 }
209} 214}
210 215
211void Dialer::send(const QString& msg) 216void Dialer::send(const QString& msg)
212{ 217{
213 QString m = msg; 218 QString m = msg;
214 int bytes; 219 int bytes;
215 QString termination; 220 QString termination;
216 221
217 qWarning("Sending: %s", m.latin1()); 222 owarn << "Sending: " << m.latin1() << "" << oendl;
218 223
219 /*termination = "\r"; 224 /*termination = "\r";
220 //termination = m_profile.readEntry("Termination"); 225 //termination = m_profile.readEntry("Termination");
221 if(termination == "\n") m = m + "\n"; 226 if(termination == "\n") m = m + "\n";
222 else if(termination == "\r") m = m + "\r"; 227 else if(termination == "\r") m = m + "\r";
223 else m = m + "\r\n"; 228 else m = m + "\r\n";
224*/ 229*/
225 m = m.replace(QRegExp("\n"), "\r"); 230 m = m.replace(QRegExp("\n"), "\r");
226 231
227 bytes = ::write(m_fd, m.local8Bit(), strlen(m.local8Bit())); 232 bytes = ::write(m_fd, m.local8Bit(), strlen(m.local8Bit()));
228 if(bytes < 0) 233 if(bytes < 0)
229 { 234 {
230 reset(); 235 reset();
231 } 236 }
232} 237}
233 238
234QString Dialer::receive() 239QString Dialer::receive()
235{ 240{
236 QString buf; 241 QString buf;
237 char buffer[1024]; 242 char buffer[1024];
238 int ret; 243 int ret;
239 int counter = 0; 244 int counter = 0;
240 245
241 while(1) 246 while(1)
242 { 247 {
243 ret = ::read(m_fd, buffer, sizeof(buffer)); 248 ret = ::read(m_fd, buffer, sizeof(buffer));
244 249
245 if(ret > 0) 250 if(ret > 0)
246 { 251 {
247 for(int i = 0; i < ret; i++) 252 for(int i = 0; i < ret; i++)
248 buffer[i] = buffer[i] & 0x7F; 253 buffer[i] = buffer[i] & 0x7F;
249 buffer[ret] = 0; 254 buffer[ret] = 0;
250 qWarning("Got: %s", buffer); 255 owarn << "Got: " << buffer << "" << oendl;
251 buf.append(QString(buffer)); 256 buf.append(QString(buffer));
252 if(buf.contains("OK") || buf.contains("ERROR") || buf.contains("CONNECT") || (buf.contains("BUSY"))) 257 if(buf.contains("OK") || buf.contains("ERROR") || buf.contains("CONNECT") || (buf.contains("BUSY")))
253 { 258 {
254 //qWarning("Receiving: '%s'", buf.latin1()); 259 //owarn << "Receiving: '" << buf.latin1() << "'" << oendl;
255 cleanshutdown = 1; 260 cleanshutdown = 1;
256 return buf; 261 return buf;
257 }else if (buf.contains("NO CARRIER") || buf.contains("NO DIALTONE") ) { 262 }else if (buf.contains("NO CARRIER") || buf.contains("NO DIALTONE") ) {
258 cleanshutdown = 1; 263 cleanshutdown = 1;
259 return QString::null; 264 return QString::null;
260 } 265 }
261 } 266 }
262 else if(ret < 0) 267 else if(ret < 0)
263 { 268 {
264 if(errno != EAGAIN) reset(); 269 if(errno != EAGAIN) reset();
265 else if(!(counter++ % 100)) qApp->processEvents(); 270 else if(!(counter++ % 100)) qApp->processEvents();
266 } 271 }
267 else if(!(counter++ % 100)) qApp->processEvents(); 272 else if(!(counter++ % 100)) qApp->processEvents();
268 273
269 if(usercancel) return QString::null; 274 if(usercancel) return QString::null;
270 } 275 }
271 276
272 cleanshutdown = 1; 277 cleanshutdown = 1;
273 return QString::null; 278 return QString::null;
274} 279}
275 280
276void Dialer::switchState(int newstate) 281void Dialer::switchState(int newstate)
277{ 282{
278 int oldstate = state; 283 int oldstate = state;
279 state = newstate; 284 state = newstate;
280 285
281 switch(state) 286 switch(state)
282 { 287 {
283 case state_cancel: 288 case state_cancel:
284 status->setText(QObject::tr("Cancelling...")); 289 status->setText(QObject::tr("Cancelling..."));
285 progress->setProgress(0); 290 progress->setProgress(0);
286 break; 291 break;
287 case state_preinit: 292 case state_preinit:
288 status->setText(QObject::tr("Searching modem")); 293 status->setText(QObject::tr("Searching modem"));
289 progress->setProgress(10); 294 progress->setProgress(10);
290 break; 295 break;
291 case state_init: 296 case state_init:
292 status->setText(QObject::tr("Initializing...")); 297 status->setText(QObject::tr("Initializing..."));
293 progress->setProgress(20); 298 progress->setProgress(20);
294 break; 299 break;
295 case state_options: 300 case state_options:
296 status->setText(QObject::tr("Reset speakers")); 301 status->setText(QObject::tr("Reset speakers"));
297 progress->setProgress(30); 302 progress->setProgress(30);
298 break; 303 break;
299 case state_dialtone: 304 case state_dialtone:
300 status->setText(QObject::tr("Turning off dialtone")); 305 status->setText(QObject::tr("Turning off dialtone"));
301 progress->setProgress(40); 306 progress->setProgress(40);
302 break; 307 break;
303 case state_dialing: 308 case state_dialing:
304 if(oldstate != state_dialing) status->setText(QObject::tr("Dial number")); 309 if(oldstate != state_dialing) status->setText(QObject::tr("Dial number"));
305 else status->setText(QObject::tr("Line busy, redialing number")); 310 else status->setText(QObject::tr("Line busy, redialing number"));
306 progress->setProgress(50); 311 progress->setProgress(50);
307 break; 312 break;
308 case state_online: 313 case state_online:
309 status->setText(QObject::tr("Connection established")); 314 status->setText(QObject::tr("Connection established"));
310 progress->setProgress(100); 315 progress->setProgress(100);
311 cancel->setText(QObject::tr("Dismiss")); 316 cancel->setText(QObject::tr("Dismiss"));
312 break; 317 break;
313 } 318 }
314} 319}
315 320
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 @@
1
2#include "TEmuVt102.h" 1#include "TEmuVt102.h"
3
4#include "profile.h" 2#include "profile.h"
5#include "emulation_handler.h" 3#include "emulation_handler.h"
6#include "script.h" 4#include "script.h"
7 5
6/* OPIE */
7#include <opie2/odebug.h>
8using namespace Opie::Core;
9
8EmulationHandler::EmulationHandler( const Profile& prof, QWidget* parent,const char* name ) 10EmulationHandler::EmulationHandler( const Profile& prof, QWidget* parent,const char* name )
9 : QObject(0, name ) 11 : QObject(0, name )
10{ 12{
11 m_teWid = new TEWidget( parent, "TerminalMain"); 13 m_teWid = new TEWidget( parent, "TerminalMain");
12 // use setWrapAt(0) for classic behaviour (wrap at screen width, no scrollbar) 14 // use setWrapAt(0) for classic behaviour (wrap at screen width, no scrollbar)
13 // use setWrapAt(80) for normal console with scrollbar 15 // use setWrapAt(80) for normal console with scrollbar
14 setWrap(prof.readNumEntry("Wrap", 0) ? 0 : 80); 16 setWrap(prof.readNumEntry("Wrap", 0) ? 0 : 80);
15 m_teWid->setMinimumSize(150, 70 ); 17 m_teWid->setMinimumSize(150, 70 );
16 m_script = 0; 18 m_script = 0;
17 parent->resize( m_teWid->calcSize(80, 24 ) ); 19 parent->resize( m_teWid->calcSize(80, 24 ) );
18 m_teEmu = new TEmuVt102(m_teWid ); 20 m_teEmu = new TEmuVt102(m_teWid );
19 21
20 connect(m_teEmu,SIGNAL(ImageSizeChanged(int,int) ), 22 connect(m_teEmu,SIGNAL(ImageSizeChanged(int,int) ),
21 this, SIGNAL(changeSize(int,int) ) ); 23 this, SIGNAL(changeSize(int,int) ) );
22 connect(m_teEmu, SIGNAL(sndBlock(const char*,int) ), 24 connect(m_teEmu, SIGNAL(sndBlock(const char*,int) ),
23 this, SLOT(recvEmulation(const char*,int) ) ); 25 this, SLOT(recvEmulation(const char*,int) ) );
24 m_teEmu->setConnect( true ); 26 m_teEmu->setConnect( true );
25 m_teEmu->setHistory( TRUE ); 27 m_teEmu->setHistory( TRUE );
26 load( prof ); 28 load( prof );
27 29
28 30
29 31
30} 32}
31TEmulation* EmulationHandler::emulation() { 33TEmulation* EmulationHandler::emulation() {
32 return m_teEmu; 34 return m_teEmu;
33} 35}
34EmulationHandler::~EmulationHandler() { 36EmulationHandler::~EmulationHandler() {
35 if (isRecording()) 37 if (isRecording())
36 clearScript(); 38 clearScript();
37 delete m_teEmu; 39 delete m_teEmu;
38 delete m_teWid; 40 delete m_teWid;
39} 41}
40 42
41void EmulationHandler::load( const Profile& prof) { 43void EmulationHandler::load( const Profile& prof) {
42 m_teWid->setVTFont( font( prof.readNumEntry("Font") ) ); 44 m_teWid->setVTFont( font( prof.readNumEntry("Font") ) );
43 int num = prof.readNumEntry("Color"); 45 int num = prof.readNumEntry("Color");
44 setColor( foreColor(num), backColor(num) ); 46 setColor( foreColor(num), backColor(num) );
45 m_teWid->setBackgroundColor(backColor(num) ); 47 m_teWid->setBackgroundColor(backColor(num) );
46 48
47 int term = prof.readNumEntry("Terminal", 0) ; 49 int term = prof.readNumEntry("Terminal", 0) ;
48 switch(term) { 50 switch(term) {
49 default: 51 default:
50 case Profile::VT102: 52 case Profile::VT102:
51 case Profile::VT100: 53 case Profile::VT100:
52 m_teEmu->setKeytrans("vt100.keytab"); 54 m_teEmu->setKeytrans("vt100.keytab");
53 break; 55 break;
54 case Profile::Linux: 56 case Profile::Linux:
55 m_teEmu->setKeytrans("linux.keytab"); 57 m_teEmu->setKeytrans("linux.keytab");
56 break; 58 break;
57 case Profile::XTerm: 59 case Profile::XTerm:
58 m_teEmu->setKeytrans("default.Keytab"); 60 m_teEmu->setKeytrans("default.Keytab");
59 break; 61 break;
60 } 62 }
61} 63}
62void EmulationHandler::recv( const QByteArray& ar) { 64void EmulationHandler::recv( const QByteArray& ar) {
63 m_teEmu->onRcvBlock(ar.data(), ar.count() ); 65 m_teEmu->onRcvBlock(ar.data(), ar.count() );
64} 66}
65void EmulationHandler::recvEmulation(const char* src, int len ) { 67void EmulationHandler::recvEmulation(const char* src, int len ) {
66 QByteArray ar(len); 68 QByteArray ar(len);
67 69
68 memcpy(ar.data(), src, sizeof(char) * len ); 70 memcpy(ar.data(), src, sizeof(char) * len );
69 if (isRecording()) 71 if (isRecording())
70 m_script->append(ar); 72 m_script->append(ar);
71 emit send(ar); 73 emit send(ar);
72} 74}
73QWidget* EmulationHandler::widget() { 75QWidget* EmulationHandler::widget() {
74 return m_teWid; 76 return m_teWid;
75} 77}
76/* 78/*
77 * allocate a new table of colors 79 * allocate a new table of colors
78 */ 80 */
79void EmulationHandler::setColor( const QColor& fore, const QColor& back ) { 81void EmulationHandler::setColor( const QColor& fore, const QColor& back ) {
80 ColorEntry table[TABLE_COLORS]; 82 ColorEntry table[TABLE_COLORS];
81 const ColorEntry *defaultCt = m_teWid->getdefaultColorTable(); 83 const ColorEntry *defaultCt = m_teWid->getdefaultColorTable();
82 84
83 for (int i = 0; i < TABLE_COLORS; i++ ) { 85 for (int i = 0; i < TABLE_COLORS; i++ ) {
84 if ( i == 0 || i == 10 ) { 86 if ( i == 0 || i == 10 ) {
85 table[i].color = fore; 87 table[i].color = fore;
86 }else if ( i == 1 || i == 11 ) { 88 }else if ( i == 1 || i == 11 ) {
87 table[i].color = back; 89 table[i].color = back;
88 table[i].transparent = 0; 90 table[i].transparent = 0;
89 }else { 91 }else {
90 table[i].color = defaultCt[i].color; 92 table[i].color = defaultCt[i].color;
91 } 93 }
92 } 94 }
93 m_teWid->setColorTable(table ); 95 m_teWid->setColorTable(table );
94 m_teWid->update(); 96 m_teWid->update();
95} 97}
96QFont EmulationHandler::font( int id ) { 98QFont EmulationHandler::font( int id ) {
97 QString name; 99 QString name;
98 int size = 0; 100 int size = 0;
99 switch(id ) { 101 switch(id ) {
100 default: // fall through 102 default: // fall through
101 case 0: 103 case 0:
102 name = QString::fromLatin1("Micro"); 104 name = QString::fromLatin1("Micro");
103 size = 4; 105 size = 4;
104 break; 106 break;
105 case 1: 107 case 1:
106 name = QString::fromLatin1("Fixed"); 108 name = QString::fromLatin1("Fixed");
107 size = 7; 109 size = 7;
108 break; 110 break;
109 case 2: 111 case 2:
110 name = QString::fromLatin1("Fixed"); 112 name = QString::fromLatin1("Fixed");
111 size = 12; 113 size = 12;
112 break; 114 break;
113 } 115 }
114 QFont font(name, size, QFont::Normal ); 116 QFont font(name, size, QFont::Normal );
115 font.setFixedPitch(TRUE ); 117 font.setFixedPitch(TRUE );
116 return font; 118 return font;
117} 119}
118QColor EmulationHandler::foreColor(int col) { 120QColor EmulationHandler::foreColor(int col) {
119 QColor co; 121 QColor co;
120 /* we need to switch it */ 122 /* we need to switch it */
121 switch( col ) { 123 switch( col ) {
122 default: 124 default:
123 case Profile::White: 125 case Profile::White:
124 /* color is black */ 126 /* color is black */
125 co = Qt::white; 127 co = Qt::white;
126 break; 128 break;
127 case Profile::Black: 129 case Profile::Black:
128 co = Qt::black; 130 co = Qt::black;
129 break; 131 break;
130 case Profile::Green: 132 case Profile::Green:
131 qWarning("Foreground green"); 133 owarn << "Foreground green" << oendl;
132 co = Qt::green; 134 co = Qt::green;
133 break; 135 break;
134 case Profile::Orange: 136 case Profile::Orange:
135 qWarning("Foreground orange"); 137 owarn << "Foreground orange" << oendl;
136 co.setRgb( 231, 184, 98 ); 138 co.setRgb( 231, 184, 98 );
137 break; 139 break;
138 } 140 }
139 141
140 return co; 142 return co;
141} 143}
142QColor EmulationHandler::backColor(int col ) { 144QColor EmulationHandler::backColor(int col ) {
143 QColor co; 145 QColor co;
144 /* we need to switch it */ 146 /* we need to switch it */
145 switch( col ) { 147 switch( col ) {
146 default: 148 default:
147 case Profile::White: 149 case Profile::White:
148 /* color is white */ 150 /* color is white */
149 co = Qt::black; 151 co = Qt::black;
150 break; 152 break;
151 case Profile::Black: 153 case Profile::Black:
152 co = Qt::white; 154 co = Qt::white;
153 break; 155 break;
154 case Profile::Green: 156 case Profile::Green:
155 qWarning("Background black"); 157 owarn << "Background black" << oendl;
156 co = Qt::black; 158 co = Qt::black;
157 break; 159 break;
158 case Profile::Orange: 160 case Profile::Orange:
159 qWarning("Background black"); 161 owarn << "Background black" << oendl;
160 co = Qt::black; 162 co = Qt::black;
161 break; 163 break;
162 } 164 }
163 165
164 return co; 166 return co;
165} 167}
166 168
167QPushButton* EmulationHandler::cornerButton() { 169QPushButton* EmulationHandler::cornerButton() {
168 return m_teWid->cornerButton(); 170 return m_teWid->cornerButton();
169} 171}
170 172
171 173
172Script *EmulationHandler::script() { 174Script *EmulationHandler::script() {
173 return m_script; 175 return m_script;
174} 176}
175 177
176bool EmulationHandler::isRecording() { 178bool EmulationHandler::isRecording() {
177 return (m_script != 0); 179 return (m_script != 0);
178} 180}
179 181
180void EmulationHandler::startRecording() { 182void EmulationHandler::startRecording() {
181 if (!isRecording()) 183 if (!isRecording())
182 m_script = new Script(); 184 m_script = new Script();
183} 185}
184 186
185void EmulationHandler::clearScript() { 187void EmulationHandler::clearScript() {
186 if (isRecording()) { 188 if (isRecording()) {
187 delete m_script; 189 delete m_script;
188 m_script = 0; 190 m_script = 0;
189 } 191 }
190} 192}
191 193
192void EmulationHandler::runScript(const Script *script) { 194void EmulationHandler::runScript(const Script *script) {
193 emit send(script->script()); 195 emit send(script->script());
194} 196}
195 197
196void EmulationHandler::copy() { 198void EmulationHandler::copy() {
197 m_teWid->emitSelection(); 199 m_teWid->emitSelection();
198} 200}
199void EmulationHandler::paste() { 201void EmulationHandler::paste() {
200 m_teWid->pasteClipboard(); 202 m_teWid->pasteClipboard();
201} 203}
202 204
203void EmulationHandler::setWrap(int columns) { 205void EmulationHandler::setWrap(int columns) {
204 m_teWid->setWrapAt(columns); 206 m_teWid->setWrapAt(columns);
205} 207}
206 208
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
131 for ( int y = 0; y < lins; ++y ) 131 for ( int y = 0; y < lins; ++y )
132 {int len; 132 {int len;
133 const Character* lcl = &m_image[y * m_columns]; 133 const Character* lcl = &m_image[y * m_columns];
134 const Character* ext = &newimg[y * m_columns]; 134 const Character* ext = &newimg[y * m_columns];
135 if ( ! m_resizing ) 135 if ( ! m_resizing )
136 for ( int x = 0; x < cols; ++x ) 136 for ( int x = 0; x < cols; ++x )
137 { 137 {
138 // disable, till widget works, WITHOUT blinking 138 // disable, till widget works, WITHOUT blinking
139 //hasBlinker |= ( ext[x].r & RE_BLINK ); 139 //hasBlinker |= ( ext[x].r & RE_BLINK );
140 140
141 if ( ext[x] != lcl[x] ) 141 if ( ext[x] != lcl[x] )
142 { 142 {
143 cr = ext[x].r; 143 cr = ext[x].r;
144 cb = ext[x].b; 144 cb = ext[x].b;
145 if ( ext[x].f != cf ) cf = ext[x].f; 145 if ( ext[x].f != cf ) cf = ext[x].f;
146 int lln = cols - x; 146 int lln = cols - x;
147 disstrU[0] = vt100extended( ext[x+0].c ); 147 disstrU[0] = vt100extended( ext[x+0].c );
148 for ( len = 1; len < lln; ++len ) 148 for ( len = 1; len < lln; ++len )
149 { 149 {
150 if ( ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr || ext[x+len] == lcl[x+len] ) 150 if ( ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr || ext[x+len] == lcl[x+len] )
151 break; 151 break;
152 disstrU[len] = vt100extended( ext[x+len].c ); 152 disstrU[len] = vt100extended( ext[x+len].c );
153 } 153 }
154 QString unistr( disstrU, len ); 154 QString unistr( disstrU, len );
155 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 ); 155 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 );
156 x += len -1; 156 x += len -1;
157 } 157 }
158 } 158 }
159 // make image become newimg 159 // make image become newimg
160 memcpy( (void*) lcl, (const void*) ext, cols*sizeof( Character ) ); 160 memcpy( (void*) lcl, (const void*) ext, cols*sizeof( Character ) );
161 } 161 }
162 drawFrame( &paint ); 162 drawFrame( &paint );
163 paint.end(); 163 paint.end();
164 setUpdatesEnabled( true ); 164 setUpdatesEnabled( true );
165 165
166 /*if ( hasBlinker && !blinkT->isActive() ) 166 /*if ( hasBlinker && !blinkT->isActive() )
167 blinkT->start(1000); //ms 167 blinkT->start(1000); //ms
168 if ( ! hasBlinker && blinkT->isActive() ) 168 if ( ! hasBlinker && blinkT->isActive() )
169 { 169 {
170 blinkT->stop(); 170 blinkT->stop();
171 blinking = false; 171 blinking = false;
172 }*/ 172 }*/
173 173
174 delete [] disstrU; 174 delete [] disstrU;
175} 175}
176 176
177 177
178void EmulationWidget::paintEvent( QPaintEvent* pe ) 178void EmulationWidget::paintEvent( QPaintEvent* pe )
179{ 179{
180 QPainter painter; 180 QPainter painter;
181 const QPixmap* pm = backgroundPixmap(); 181 const QPixmap* pm = backgroundPixmap();
182 182
183 painter.begin( this ); 183 painter.begin( this );
184 painter.setBackgroundMode( TransparentMode ); 184 painter.setBackgroundMode( TransparentMode );
185 185
186 QRect rect = pe->rect().intersect( contentsRect() ); 186 QRect rect = pe->rect().intersect( contentsRect() );
187 QPoint tL = contentsRect().topLeft(); 187 QPoint tL = contentsRect().topLeft();
188 int tLx = tL.x(); 188 int tLx = tL.x();
189 int tLy = tL.y(); 189 int tLy = tL.y();
190 190
191 int lux = QMIN(m_columns-1, QMAX(0,(rect.left() - tLx - m_blX ) / f_width)); 191 int lux = QMIN(m_columns-1, QMAX(0,(rect.left() - tLx - m_blX ) / f_width));
192 int luy = QMIN(m_lines-1, QMAX(0,(rect.top() - tLy - m_bY ) / f_height)); 192 int luy = QMIN(m_lines-1, QMAX(0,(rect.top() - tLy - m_bY ) / f_height));
193 int rlx = QMIN(m_columns-1, QMAX(0,(rect.right() - tLx - m_blX ) / f_width)); 193 int rlx = QMIN(m_columns-1, QMAX(0,(rect.right() - tLx - m_blX ) / f_width));
194 int rly = QMIN(m_lines-1, QMAX(0,(rect.bottom() - tLy - m_bY ) / f_height)); 194 int rly = QMIN(m_lines-1, QMAX(0,(rect.bottom() - tLy - m_bY ) / f_height));
195 195
196 QChar *disstrU = new QChar[m_columns]; 196 QChar *disstrU = new QChar[m_columns];
197 for (int y = luy; y <= rly; y++) 197 for (int y = luy; y <= rly; y++)
198 for (int x = lux; x <= rlx; x++) 198 for (int x = lux; x <= rlx; x++)
199 { 199 {
200 int len = 1; 200 int len = 1;
201 disstrU[0] = vt100extended(m_image[loc(x,y)].c); 201 disstrU[0] = vt100extended(m_image[loc(x,y)].c);
202 int cf = m_image[loc(x,y)].f; 202 int cf = m_image[loc(x,y)].f;
203 int cb = m_image[loc(x,y)].b; 203 int cb = m_image[loc(x,y)].b;
204 int cr = m_image[loc(x,y)].r; 204 int cr = m_image[loc(x,y)].r;
205 while (x+len <= rlx && 205 while (x+len <= rlx &&
206 m_image[loc(x+len,y)].f == cf && 206 m_image[loc(x+len,y)].f == cf &&
207 m_image[loc(x+len,y)].b == cb && 207 m_image[loc(x+len,y)].b == cb &&
208 m_image[loc(x+len,y)].r == cr ) 208 m_image[loc(x+len,y)].r == cr )
209 { 209 {
210 disstrU[len] = vt100extended(m_image[loc(x+len,y)].c); 210 disstrU[len] = vt100extended(m_image[loc(x+len,y)].c);
211 len += 1; 211 len += 1;
212 } 212 }
213 QString unistr(disstrU,len); 213 QString unistr(disstrU,len);
214 214
215 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 ); 215 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 );
216 x +=len -1; 216 x +=len -1;
217 } 217 }
218 delete [] disstrU; 218 delete [] disstrU;
219 drawFrame( &painter ); 219 drawFrame( &painter );
220 painter.end(); 220 painter.end();
221} 221}
222 222
223void EmulationWidget::calcGeometry() 223void EmulationWidget::calcGeometry()
224{ 224{
225 m_scrollbar->resize(QApplication::style().scrollBarExtent().width(), contentsRect().height() ); 225 m_scrollbar->resize(QApplication::style().scrollBarExtent().width(), contentsRect().height() );
226 226
227 qDebug( QString(" TEST").arg( contentsRect().width() ) ); 227 odebug << QString(" TEST").arg( contentsRect().width() ) << oendl;
228 qDebug( QString(" TEST").arg( contentsRect().height() ) ); 228 odebug << QString(" TEST").arg( contentsRect().height() ) << oendl;
229 qDebug("NEUER TESTT!!!!!!!!"); 229 odebug << "NEUER TESTT!!!!!!!!" << oendl;
230 230
231 switch( scrollLoc ) 231 switch( scrollLoc )
232 { 232 {
233 case SCRNONE : 233 case SCRNONE :
234 m_columns = ( contentsRect().width() -2 * rimX ) / f_width; 234 m_columns = ( contentsRect().width() -2 * rimX ) / f_width;
235 m_blX = ( contentsRect().width() - ( m_columns*f_width ) ) / 2; 235 m_blX = ( contentsRect().width() - ( m_columns*f_width ) ) / 2;
236 m_brX = m_blX; 236 m_brX = m_blX;
237 m_scrollbar->hide(); 237 m_scrollbar->hide();
238 break; 238 break;
239 case SCRLEFT : 239 case SCRLEFT :
240 m_columns = ( contentsRect().width() - 2 * rimX - m_scrollbar->width() ) / f_width; 240 m_columns = ( contentsRect().width() - 2 * rimX - m_scrollbar->width() ) / f_width;
241 m_brX = ( contentsRect().width() - ( m_columns*f_width ) - m_scrollbar->width() ) / 2; 241 m_brX = ( contentsRect().width() - ( m_columns*f_width ) - m_scrollbar->width() ) / 2;
242 m_blX = m_brX + m_scrollbar->width(); 242 m_blX = m_brX + m_scrollbar->width();
243 m_scrollbar->move( contentsRect().topLeft() ); 243 m_scrollbar->move( contentsRect().topLeft() );
244 m_scrollbar->show(); 244 m_scrollbar->show();
245 break; 245 break;
246 case SCRIGHT: 246 case SCRIGHT:
247 m_columns = ( contentsRect().width() - 2 * rimX - m_scrollbar->width() ) / f_width; 247 m_columns = ( contentsRect().width() - 2 * rimX - m_scrollbar->width() ) / f_width;
248 m_blX = ( contentsRect().width() - ( m_columns*f_width ) - m_scrollbar->width() ) / 2; 248 m_blX = ( contentsRect().width() - ( m_columns*f_width ) - m_scrollbar->width() ) / 2;
249 m_brX = m_blX; 249 m_brX = m_blX;
250 m_scrollbar->move( contentsRect().topRight() - QPoint (m_scrollbar->width()-1,0 ) ); 250 m_scrollbar->move( contentsRect().topRight() - QPoint (m_scrollbar->width()-1,0 ) );
251 m_scrollbar->show(); 251 m_scrollbar->show();
252 break; 252 break;
253 } 253 }
254 254
255 m_lines = ( contentsRect().height() - 2 * rimY ) / f_height; 255 m_lines = ( contentsRect().height() - 2 * rimY ) / f_height;
256 m_bY = ( contentsRect().height() - (m_lines * f_height ) ) / 2; 256 m_bY = ( contentsRect().height() - (m_lines * f_height ) ) / 2;
257} 257}
258 258
259void EmulationWidget::drawAttrString( QString& string, QPainter &painter, QRect rect, Character attr, bool usePixmap, bool clear ) 259void EmulationWidget::drawAttrString( QString& string, QPainter &painter, QRect rect, Character attr, bool usePixmap, bool clear )
260{ 260{
261 qWarning("Color1 %s", color_table[attr.b].color.name().latin1() ); 261 owarn << "Color1 " << color_table[attr.b].color.name().latin1() << "" << oendl;
262 if ( usePixmap && color_table[attr.b].transparent ) 262 if ( usePixmap && color_table[attr.b].transparent )
263 { 263 {
264 painter.setBackgroundMode( TransparentMode ); 264 painter.setBackgroundMode( TransparentMode );
265 if ( clear ) 265 if ( clear )
266 erase( rect ); 266 erase( rect );
267 } 267 }
268 else 268 else
269 { 269 {
270 if ( blinking ) 270 if ( blinking )
271 painter.fillRect( rect, color_table[attr.b].color ); 271 painter.fillRect( rect, color_table[attr.b].color );
272 else 272 else
273 { 273 {
274 painter.setBackgroundMode( OpaqueMode ); 274 painter.setBackgroundMode( OpaqueMode );
275 qWarning("Color %s", color_table[attr.b].color.name().latin1() ); 275 owarn << "Color " << color_table[attr.b].color.name().latin1() << "" << oendl;
276 painter.setBackgroundColor( color_table[attr.b].color ); 276 painter.setBackgroundColor( color_table[attr.b].color );
277 } 277 }
278 } 278 }
279 if ( color_table[attr.f].bold ) 279 if ( color_table[attr.f].bold )
280 painter.setPen( QColor( 0x8F, 0x00, 0x00 ) ); 280 painter.setPen( QColor( 0x8F, 0x00, 0x00 ) );
281 else 281 else
282 painter.setPen( color_table[attr.f].color ); 282 painter.setPen( color_table[attr.f].color );
283 painter.drawText( rect.x(), rect.y() + f_ascent, string ); 283 painter.drawText( rect.x(), rect.y() + f_ascent, string );
284 284
285} 285}
286 286
287 287
288/////////////////////// 288///////////////////////
289// scrollbar 289// scrollbar
290// //////////////////// 290// ////////////////////
291 291
292void EmulationWidget::scroll( int value ) 292void EmulationWidget::scroll( int value )
293{ 293{
294} 294}
295 295
296void EmulationWidget::setScroll( int cursor, int slines ) 296void EmulationWidget::setScroll( int cursor, int slines )
297{ 297{
298} 298}
299 299
300 300
301 301
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 @@
1#include "function_keyboard.h" 1#include "function_keyboard.h"
2 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
7/* QT */
3#include <qlayout.h> 8#include <qlayout.h>
4#include <qlistbox.h> 9#include <qlistbox.h>
5#include <qlabel.h> 10#include <qlabel.h>
6#include <qdir.h> 11#include <qdir.h>
7 12
8#define DEFAULT_ROWS 2 13#define DEFAULT_ROWS 2
9#define DEFAULT_COLS 12 14#define DEFAULT_COLS 12
10 15
11/* FunctionKeyboard {{{1 */ 16/* FunctionKeyboard {{{1 */
12 17
13FunctionKeyboard::FunctionKeyboard(QWidget *parent) : 18FunctionKeyboard::FunctionKeyboard(QWidget *parent) :
14 QFrame(parent), numRows(DEFAULT_ROWS), numCols(DEFAULT_COLS), 19 QFrame(parent), numRows(DEFAULT_ROWS), numCols(DEFAULT_COLS),
15 pressedRow(0), pressedCol(0) { 20 pressedRow(0), pressedCol(0) {
16 21
17 setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed)); 22 setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed));
18 23
19 /* 24 /*
20 * all the saving/loading is now done in a profile. downside is that you cant modify 25 * all the saving/loading is now done in a profile. downside is that you cant modify
21 * the keyboard for all profiles, but must do it on a profile-basis 26 * the keyboard for all profiles, but must do it on a profile-basis
22 * 27 *
23 28
24 Config conf("opie-console-keys"); 29 Config conf("opie-console-keys");
25 conf.setGroup("keys"); 30 conf.setGroup("keys");
26 for (uint r = 0; r < numRows; r++) 31 for (uint r = 0; r < numRows; r++)
27 for (uint c = 0; c < numCols; c++) { 32 for (uint c = 0; c < numCols; c++) {
28 33
29 QString handle = "r" + QString::number(r) + "c" + QString::number(c); 34 QString handle = "r" + QString::number(r) + "c" + QString::number(c);
30 QStringList value_list = conf.readListEntry( handle, '|'); 35 QStringList value_list = conf.readListEntry( handle, '|');
31 36
32 if (value_list.isEmpty()) continue; 37 if (value_list.isEmpty()) continue;
33 38
34 keys.insert( 39 keys.insert(
35 40
36 handle, 41 handle,
37 FKey (value_list[0], value_list[1], value_list[2].toUShort(), value_list[3].toUShort()) 42 FKey (value_list[0], value_list[1], value_list[2].toUShort(), value_list[3].toUShort())
38 ); 43 );
39 } 44 }
40 //qWarning("loaded %d keys", keys.count()); 45 //owarn << "loaded " << keys.count() << " keys" << oendl;
41 */ 46 */
42 if (keys.isEmpty()) loadDefaults(); 47 if (keys.isEmpty()) loadDefaults();
43 48
44 49
45 50
46} 51}
47 52
48FunctionKeyboard::~FunctionKeyboard() {} 53FunctionKeyboard::~FunctionKeyboard() {}
49 54
50void FunctionKeyboard::changeRows(int r) { 55void FunctionKeyboard::changeRows(int r) {
51 56
52 numRows = r; 57 numRows = r;
53 58
54 // have to do this so the whole thing gets redrawn 59 // have to do this so the whole thing gets redrawn
55 hide(); show(); 60 hide(); show();
56} 61}
57void FunctionKeyboard::changeCols(int c) { 62void FunctionKeyboard::changeCols(int c) {
58 63
59 numCols = c; 64 numCols = c;
60 keyWidth = (double)width()/numCols; // have to reset this thing too 65 keyWidth = (double)width()/numCols; // have to reset this thing too
61 repaint(false); 66 repaint(false);
62} 67}
63void FunctionKeyboard::load (const Profile& prof) { 68void FunctionKeyboard::load (const Profile& prof) {
64 69
65 keys.clear(); 70 keys.clear();
66 71
67 numRows = prof.readNumEntry("keb_rows", 2); 72 numRows = prof.readNumEntry("keb_rows", 2);
68 numCols = prof.readNumEntry("keb_cols", 10); 73 numCols = prof.readNumEntry("keb_cols", 10);
69 keyWidth = (double)width()/numCols; // have to reset this thing too 74 keyWidth = (double)width()/numCols; // have to reset this thing too
70 75
71 /* load all the keys to the keyboard */ 76 /* load all the keys to the keyboard */
72 for (ushort i = 0; i <= numRows - 1; i++) 77 for (ushort i = 0; i <= numRows - 1; i++)
73 for (ushort j = 0; j <= numCols - 1; j++) { 78 for (ushort j = 0; j <= numCols - 1; j++) {
74 79
75 QString h = "r" + QString::number(i) + "c" + QString::number(j); 80 QString h = "r" + QString::number(i) + "c" + QString::number(j);
76 QString values = prof.readEntry("keb_" + h); 81 QString values = prof.readEntry("keb_" + h);
77 82
78 if (!values.isEmpty()) { 83 if (!values.isEmpty()) {
79 84
80 QStringList l = QStringList::split(QChar('|'), values, TRUE); 85 QStringList l = QStringList::split(QChar('|'), values, TRUE);
81 keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt()); 86 keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt());
82 87
83 // load pixmap if used 88 // load pixmap if used
84 if (!l[1].isEmpty()) { 89 if (!l[1].isEmpty()) {
85 90
86 keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) ); 91 keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) );
87 } 92 }
88 } 93 }
89 } 94 }
90 95
91 if (keys.isEmpty()) loadDefaults(); 96 if (keys.isEmpty()) loadDefaults();
92 97
93 hide(); 98 hide();
94 show(); 99 show();
95 100
96} 101}
97 102
98void FunctionKeyboard::paintEvent(QPaintEvent *e) { 103void FunctionKeyboard::paintEvent(QPaintEvent *e) {
99 104
100 QPainter p(this); 105 QPainter p(this);
101 p.setClipRect(e->rect()); 106 p.setClipRect(e->rect());
102 p.fillRect(0, 0, width(), height(), QColor(255,255,255)); 107 p.fillRect(0, 0, width(), height(), QColor(255,255,255));
103 108
104 p.setPen(QColor(0,0,0)); 109 p.setPen(QColor(0,0,0));
105 110
106 /* those decimals do count! becomes short if use plain int */ 111 /* those decimals do count! becomes short if use plain int */
107 for (double i = 0; i <= width(); i += keyWidth) { 112 for (double i = 0; i <= width(); i += keyWidth) {
108 113
109 p.drawLine((int)i, 0, (int)i, height()); 114 p.drawLine((int)i, 0, (int)i, height());
110 } 115 }
111 116
112 // sometimes the last line doesnt get drawn 117 // sometimes the last line doesnt get drawn
113 p.drawLine(width() -1, 0, width() -1, height()); 118 p.drawLine(width() -1, 0, width() -1, height());
114 119
115 for (int i = 0; i <= height(); i += keyHeight) { 120 for (int i = 0; i <= height(); i += keyHeight) {
116 121
117 p.drawLine(0, i, width(), i); 122 p.drawLine(0, i, width(), i);
118 } 123 }
119 124
120 for (uint r = 0; r < numRows; r++) { 125 for (uint r = 0; r < numRows; r++) {
121 for (uint c = 0; c < numCols; c++) { 126 for (uint c = 0; c < numCols; c++) {
122 127
123 QString handle = "r" + QString::number(r) + "c" + QString::number(c); 128 QString handle = "r" + QString::number(r) + "c" + QString::number(c);
124 if (keys.contains(handle)) { 129 if (keys.contains(handle)) {
125 130
126 if (keys[handle].pixFile.isEmpty()) 131 if (keys[handle].pixFile.isEmpty())
127 p.drawText( c * keyWidth + 1, r * keyHeight + 1, 132 p.drawText( c * keyWidth + 1, r * keyHeight + 1,
128 keyWidth, keyHeight, 133 keyWidth, keyHeight,
129 Qt::AlignHCenter | Qt::AlignVCenter, 134 Qt::AlignHCenter | Qt::AlignVCenter,
130 keys[handle].label 135 keys[handle].label
131 ); 136 );
132 else { 137 else {
133 138
134 ushort centerX = (ushort)(c *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2; 139 ushort centerX = (ushort)(c *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2;
135 ushort centerY = r * keyHeight + (keyHeight - keys[handle].pix->height()) / 2; 140 ushort centerY = r * keyHeight + (keyHeight - keys[handle].pix->height()) / 2;
136 p.drawPixmap(centerX, centerY, *keys[handle].pix); 141 p.drawPixmap(centerX, centerY, *keys[handle].pix);
@@ -163,193 +168,193 @@ void FunctionKeyboard::paintKey(uint row, uint col) {
163 p.drawPixmap(centerX, centerY, *keys[handle].pix); 168 p.drawPixmap(centerX, centerY, *keys[handle].pix);
164 } 169 }
165 170
166 if (col == numCols - 1) { 171 if (col == numCols - 1) {
167 172
168 // sometimes it doesnt draw the last line 173 // sometimes it doesnt draw the last line
169 174
170 p.drawLine((col+1) * keyWidth -1, row * keyHeight, 175 p.drawLine((col+1) * keyWidth -1, row * keyHeight,
171 (col+1) * keyWidth -1, (row + 1) * keyHeight 176 (col+1) * keyWidth -1, (row + 1) * keyHeight
172 ); 177 );
173 } 178 }
174 179
175} 180}
176 181
177void FunctionKeyboard::mousePressEvent(QMouseEvent *e) { 182void FunctionKeyboard::mousePressEvent(QMouseEvent *e) {
178 183
179 pressedRow = e->y() / keyHeight; 184 pressedRow = e->y() / keyHeight;
180 pressedCol = (int) (e->x() / keyWidth); 185 pressedCol = (int) (e->x() / keyWidth);
181 186
182 paintKey(pressedRow, pressedCol); 187 paintKey(pressedRow, pressedCol);
183 188
184 // emit that sucker! 189 // emit that sucker!
185 FKey k = keys["r" + QString::number(pressedRow) + "c" + QString::number(pressedCol)]; 190 FKey k = keys["r" + QString::number(pressedRow) + "c" + QString::number(pressedCol)];
186 emit keyPressed(k, pressedRow, pressedCol, 1); 191 emit keyPressed(k, pressedRow, pressedCol, 1);
187 192
188} 193}
189 194
190void FunctionKeyboard::mouseReleaseEvent(QMouseEvent *) { 195void FunctionKeyboard::mouseReleaseEvent(QMouseEvent *) {
191 196
192 if (pressedRow != -1 && pressedRow != -1) { 197 if (pressedRow != -1 && pressedRow != -1) {
193 198
194 int row = pressedRow; pressedRow = -1; 199 int row = pressedRow; pressedRow = -1;
195 int col = pressedCol; pressedCol = -1; 200 int col = pressedCol; pressedCol = -1;
196 paintKey(row, col); 201 paintKey(row, col);
197 202
198 FKey k = keys["r" + QString::number(row) + "c" + QString::number(col)]; 203 FKey k = keys["r" + QString::number(row) + "c" + QString::number(col)];
199 emit keyPressed(k, row, col, 0); 204 emit keyPressed(k, row, col, 0);
200 } 205 }
201 206
202} 207}
203 208
204 209
205void FunctionKeyboard::resizeEvent(QResizeEvent*) { 210void FunctionKeyboard::resizeEvent(QResizeEvent*) {
206 211
207 /* set he default font height/width */ 212 /* set he default font height/width */
208 QFontMetrics fm=fontMetrics(); 213 QFontMetrics fm=fontMetrics();
209 keyHeight = fm.lineSpacing() + 2; 214 keyHeight = fm.lineSpacing() + 2;
210 keyWidth = (double)width()/numCols; 215 keyWidth = (double)width()/numCols;
211 216
212} 217}
213 218
214QSize FunctionKeyboard::sizeHint() const { 219QSize FunctionKeyboard::sizeHint() const {
215 220
216 return QSize(width(), keyHeight * numRows + 1); 221 return QSize(width(), keyHeight * numRows + 1);
217} 222}
218 223
219void FunctionKeyboard::loadDefaults() { 224void FunctionKeyboard::loadDefaults() {
220 225
221 numRows = DEFAULT_ROWS; 226 numRows = DEFAULT_ROWS;
222 numCols = DEFAULT_COLS; 227 numCols = DEFAULT_COLS;
223 keyWidth = (double)width()/numCols; // have to reset this thing too 228 keyWidth = (double)width()/numCols; // have to reset this thing too
224 229
225 keys.insert( "r0c0", FKey ("Enter", "enter", Qt::Key_Enter, 0)); 230 keys.insert( "r0c0", FKey ("Enter", "enter", Qt::Key_Enter, 0));
226 keys.insert( "r0c1", FKey ("Space", "space", Qt::Key_Space, Qt::Key_Space)); 231 keys.insert( "r0c1", FKey ("Space", "space", Qt::Key_Space, Qt::Key_Space));
227 keys.insert( "r0c2", FKey ("Tab", "tab", Qt::Key_Tab, 0)); 232 keys.insert( "r0c2", FKey ("Tab", "tab", Qt::Key_Tab, 0));
228 keys.insert( "r0c3", FKey ("Up", "up", Qt::Key_Up, 0)); 233 keys.insert( "r0c3", FKey ("Up", "up", Qt::Key_Up, 0));
229 keys.insert( "r0c4", FKey ("Down", "down", Qt::Key_Down, 0)); 234 keys.insert( "r0c4", FKey ("Down", "down", Qt::Key_Down, 0));
230 235
231 keys.insert( "r0c7", FKey ("Ho", 0, 4112, 0)); 236 keys.insert( "r0c7", FKey ("Ho", 0, 4112, 0));
232 keys.insert( "r0c8", FKey ("End", 0, 4113, 0)); 237 keys.insert( "r0c8", FKey ("End", 0, 4113, 0));
233 keys.insert( "r0c9", FKey ("Pu", 0, 4118, 0)); 238 keys.insert( "r0c9", FKey ("Pu", 0, 4118, 0));
234 keys.insert( "r0c10", FKey ("Pd", 0, 4119, 0)); 239 keys.insert( "r0c10", FKey ("Pd", 0, 4119, 0));
235 keys.insert( "r0c11", FKey ("Esc", 0, Qt::Key_Escape, 0xfff)); 240 keys.insert( "r0c11", FKey ("Esc", 0, Qt::Key_Escape, 0xfff));
236 241
237 keys.insert( "r1c0", FKey ("F1", 0, 4144, 0)); 242 keys.insert( "r1c0", FKey ("F1", 0, 4144, 0));
238 keys.insert( "r1c1", FKey ("F2", 0, 4145, 0)); 243 keys.insert( "r1c1", FKey ("F2", 0, 4145, 0));
239 keys.insert( "r1c2", FKey ("F3", 0, 4146, 0)); 244 keys.insert( "r1c2", FKey ("F3", 0, 4146, 0));
240 keys.insert( "r1c3", FKey ("F4", 0, 4147, 0)); 245 keys.insert( "r1c3", FKey ("F4", 0, 4147, 0));
241 keys.insert( "r1c4", FKey ("F5", 0, 4148, 0)); 246 keys.insert( "r1c4", FKey ("F5", 0, 4148, 0));
242 keys.insert( "r1c5", FKey ("F6", 0, 4149, 0)); 247 keys.insert( "r1c5", FKey ("F6", 0, 4149, 0));
243 keys.insert( "r1c6", FKey ("F7", 0, 4150, 0)); 248 keys.insert( "r1c6", FKey ("F7", 0, 4150, 0));
244 keys.insert( "r1c7", FKey ("F8", 0, 4151, 0)); 249 keys.insert( "r1c7", FKey ("F8", 0, 4151, 0));
245 keys.insert( "r1c8", FKey ("F9", 0, 4152, 0)); 250 keys.insert( "r1c8", FKey ("F9", 0, 4152, 0));
246 keys.insert( "r1c9", FKey ("F10", 0, 4153, 0)); 251 keys.insert( "r1c9", FKey ("F10", 0, 4153, 0));
247 keys.insert( "r1c10", FKey ("F11", 0, 4154, 0)); 252 keys.insert( "r1c10", FKey ("F11", 0, 4154, 0));
248 keys.insert( "r1c11", FKey ("F12", 0, 4155, 0)); 253 keys.insert( "r1c11", FKey ("F12", 0, 4155, 0));
249 254
250 255
251} 256}
252 257
253/* FunctionKeyboardConfig {{{1 */ 258/* FunctionKeyboardConfig {{{1 */
254 259
255FunctionKeyboardConfig::FunctionKeyboardConfig(const QString& name, QWidget* parent, const char* na ) 260FunctionKeyboardConfig::FunctionKeyboardConfig(const QString& name, QWidget* parent, const char* na )
256 : ProfileDialogKeyWidget(name, parent, na), 261 : ProfileDialogKeyWidget(name, parent, na),
257 selectedRow(0), selectedCol(0) 262 selectedRow(0), selectedCol(0)
258{ 263{
259 qWarning("FunctionKeyboardConfig"); 264 owarn << "FunctionKeyboardConfig" << oendl;
260 265
261 266
262 kb = new FunctionKeyboard(this); 267 kb = new FunctionKeyboard(this);
263 connect (kb, SIGNAL(keyPressed(FKey,ushort,ushort,bool)), 268 connect (kb, SIGNAL(keyPressed(FKey,ushort,ushort,bool)),
264 this, SLOT(slotKeyPressed(FKey,ushort,ushort,bool))); 269 this, SLOT(slotKeyPressed(FKey,ushort,ushort,bool)));
265 270
266 QGroupBox *dimentions = new QGroupBox(2, Qt::Horizontal, tr("Dimensions"), this); 271 QGroupBox *dimentions = new QGroupBox(2, Qt::Horizontal, tr("Dimensions"), this);
267 QLabel *l = new QLabel("Rows", dimentions); 272 QLabel *l = new QLabel("Rows", dimentions);
268 m_rowBox = new QSpinBox(1, 15, 1, dimentions); 273 m_rowBox = new QSpinBox(1, 15, 1, dimentions);
269 connect (m_rowBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeRows(int))); 274 connect (m_rowBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeRows(int)));
270 l = new QLabel("Columns", dimentions); 275 l = new QLabel("Columns", dimentions);
271 m_colBox = new QSpinBox(1, 15, 1, dimentions); 276 m_colBox = new QSpinBox(1, 15, 1, dimentions);
272 connect (m_colBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeCols(int))); 277 connect (m_colBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeCols(int)));
273 278
274 QGroupBox *editKey = new QGroupBox(2, Qt::Horizontal, tr("Edit Key"), this); 279 QGroupBox *editKey = new QGroupBox(2, Qt::Horizontal, tr("Edit Key"), this);
275 l = new QLabel("Label", editKey); 280 l = new QLabel("Label", editKey);
276 m_labels = new QComboBox(true, editKey); 281 m_labels = new QComboBox(true, editKey);
277 m_labels->setInsertionPolicy(QComboBox::AtCurrent); 282 m_labels->setInsertionPolicy(QComboBox::AtCurrent);
278 m_labels->insertItem(""); 283 m_labels->insertItem("");
279 284
280 QStringList files = QDir( QPEApplication::qpeDir() + "pics/console/keys/", "*.png").entryList(); 285 QStringList files = QDir( QPEApplication::qpeDir() + "pics/console/keys/", "*.png").entryList();
281 286
282 for (uint i = 0; i < files.count(); i++) { 287 for (uint i = 0; i < files.count(); i++) {
283 288
284 m_labels->insertItem( Resource::loadPixmap("console/keys/" + files[i]), files[i]); 289 m_labels->insertItem( Resource::loadPixmap("console/keys/" + files[i]), files[i]);
285 } 290 }
286 connect (m_labels, SIGNAL(activated(int)), this, SLOT(slotChangeIcon(int))); 291 connect (m_labels, SIGNAL(activated(int)), this, SLOT(slotChangeIcon(int)));
287 connect (m_labels, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeLabelText(const QString&))); 292 connect (m_labels, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeLabelText(const QString&)));
288 293
289 l = new QLabel("Q Keycode", editKey); 294 l = new QLabel("Q Keycode", editKey);
290 m_qvalues = new QComboBox(true, editKey); 295 m_qvalues = new QComboBox(true, editKey);
291 m_qvalues->setInsertionPolicy(QComboBox::AtTop); 296 m_qvalues->setInsertionPolicy(QComboBox::AtTop);
292 m_qvalues->setDuplicatesEnabled(false); 297 m_qvalues->setDuplicatesEnabled(false);
293 m_qvalues->insertItem(""); 298 m_qvalues->insertItem("");
294 connect (m_qvalues, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeQCode(const QString&))); 299 connect (m_qvalues, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeQCode(const QString&)));
295 300
296 l = new QLabel("Unicode Value", editKey); 301 l = new QLabel("Unicode Value", editKey);
297 m_uniValues = new QComboBox(true, editKey); 302 m_uniValues = new QComboBox(true, editKey);
298 m_uniValues->setInsertionPolicy(QComboBox::AtTop); 303 m_uniValues->setInsertionPolicy(QComboBox::AtTop);
299 m_uniValues->setDuplicatesEnabled(false); 304 m_uniValues->setDuplicatesEnabled(false);
300 m_uniValues->insertItem(""); 305 m_uniValues->insertItem("");
301 connect (m_uniValues, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeUnicode(const QString&))); 306 connect (m_uniValues, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeUnicode(const QString&)));
302 307
303 QVBoxLayout *root = new QVBoxLayout(this, 2); 308 QVBoxLayout *root = new QVBoxLayout(this, 2);
304 root->addWidget(kb); 309 root->addWidget(kb);
305 root->addWidget(dimentions); 310 root->addWidget(dimentions);
306 root->addWidget(editKey); 311 root->addWidget(editKey);
307} 312}
308FunctionKeyboardConfig::~FunctionKeyboardConfig() { 313FunctionKeyboardConfig::~FunctionKeyboardConfig() {
309 314
310} 315}
311void FunctionKeyboardConfig::load (const Profile& prof) { 316void FunctionKeyboardConfig::load (const Profile& prof) {
312 317
313 kb->keys.clear(); 318 kb->keys.clear();
314 kb->loadDefaults(); 319 kb->loadDefaults();
315 320
316 m_rowBox->setValue(prof.readNumEntry("keb_rows", 2)); 321 m_rowBox->setValue(prof.readNumEntry("keb_rows", 2));
317 m_colBox->setValue(prof.readNumEntry("keb_cols", 10)); 322 m_colBox->setValue(prof.readNumEntry("keb_cols", 10));
318 323
319 /* load all the keys to the keyboard */ 324 /* load all the keys to the keyboard */
320 for (int i = 0; i <= m_rowBox->value() -1; i++) 325 for (int i = 0; i <= m_rowBox->value() -1; i++)
321 for (int j = 0; j <= m_colBox->value() -1; j++) { 326 for (int j = 0; j <= m_colBox->value() -1; j++) {
322 327
323 QString h = "r" + QString::number(i) + "c" + QString::number(j); 328 QString h = "r" + QString::number(i) + "c" + QString::number(j);
324 QString values = prof.readEntry("keb_" + h); 329 QString values = prof.readEntry("keb_" + h);
325 330
326 if (!values.isEmpty()) { 331 if (!values.isEmpty()) {
327 332
328 QStringList l = QStringList::split(QChar('|'), values, TRUE); 333 QStringList l = QStringList::split(QChar('|'), values, TRUE);
329 kb->keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt()); 334 kb->keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt());
330 335
331 // load pixmap if used 336 // load pixmap if used
332 if (!l[1].isEmpty()) { 337 if (!l[1].isEmpty()) {
333 338
334 kb->keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) ); 339 kb->keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) );
335 } 340 }
336 } 341 }
337 } 342 }
338 343
339} 344}
340void FunctionKeyboardConfig::save (Profile& prof) { 345void FunctionKeyboardConfig::save (Profile& prof) {
341 346
342 prof.writeEntry("keb_rows", m_rowBox->value()); 347 prof.writeEntry("keb_rows", m_rowBox->value());
343 prof.writeEntry("keb_cols", m_colBox->value()); 348 prof.writeEntry("keb_cols", m_colBox->value());
344 349
345 QMap<QString, FKey>::Iterator it; 350 QMap<QString, FKey>::Iterator it;
346 for ( it = kb->keys.begin(); it != kb->keys.end(); it++) { 351 for ( it = kb->keys.begin(); it != kb->keys.end(); it++) {
347 352
348 FKey k = it.data(); 353 FKey k = it.data();
349 QString entry = k.label + "|" 354 QString entry = k.label + "|"
350 + k.pixFile + "|" 355 + k.pixFile + "|"
351 + QString::number(k.qcode) + "|" 356 + QString::number(k.qcode) + "|"
352 + QString::number(k.unicode); 357 + QString::number(k.unicode);
353 358
354 prof.writeEntry("keb_" + it.key(), entry); 359 prof.writeEntry("keb_" + it.key(), entry);
355 360
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 @@
1 1
2#include "io_bt.h" 2#include "io_bt.h"
3 3
4/* OPIE */
5#include <opie2/odebug.h>
4using namespace Opie::Core; 6using namespace Opie::Core;
7
5IOBt::IOBt( const Profile &config ) : IOSerial( config ) { 8IOBt::IOBt( const Profile &config ) : IOSerial( config ) {
6 m_attach = 0; 9 m_attach = 0;
7} 10}
8 11
9 12
10IOBt::~IOBt() { 13IOBt::~IOBt() {
11 if ( m_attach ) { 14 if ( m_attach ) {
12 delete m_attach; 15 delete m_attach;
13 } 16 }
14} 17}
15 18
16 19
17void IOBt::close() { 20void IOBt::close() {
18 21
19 IOSerial::close(); 22 IOSerial::close();
20 // still need error handling 23 // still need error handling
21 if ( m_attach ) { 24 if ( m_attach ) {
22 delete m_attach; 25 delete m_attach;
23 m_attach = 0; 26 m_attach = 0;
24 } 27 }
25} 28}
26 29
27bool IOBt::open() { 30bool IOBt::open() {
28 bool ret = false; 31 bool ret = false;
29 32
30 // only set up bt stuff if mac address was set, otherwise use the device set 33 // only set up bt stuff if mac address was set, otherwise use the device set
31 if ( !m_mac.isEmpty() ) { 34 if ( !m_mac.isEmpty() ) {
32 35
33 // now it should also be checked, if there is a connection to the device with that mac allready 36 // now it should also be checked, if there is a connection to the device with that mac allready
34 // hciattach here 37 // hciattach here
35 m_attach = new OProcess(); 38 m_attach = new OProcess();
36 *m_attach << "hciattach /dev/ttyS2 any 57600"; 39 *m_attach << "hciattach /dev/ttyS2 any 57600";
37 40
38 // then start hcid, then rcfomm handling (m_mac) 41 // then start hcid, then rcfomm handling (m_mac)
39 42
40 connect( m_attach, SIGNAL( processExited(Opie::Core::OProcess*) ), 43 connect( m_attach, SIGNAL( processExited(Opie::Core::OProcess*) ),
41 this, SLOT( slotExited(Opie::Core::OProcess*) ) ); 44 this, SLOT( slotExited(Opie::Core::OProcess*) ) );
42 45
43 if ( m_attach->start() ) { 46 if ( m_attach->start() ) {
44 ret = IOSerial::open(); 47 ret = IOSerial::open();
45 } else { 48 } else {
46 qWarning("could not attach to device"); 49 owarn << "could not attach to device" << oendl;
47 delete m_attach; 50 delete m_attach;
48 m_attach = 0; 51 m_attach = 0;
49 } 52 }
50 } else { 53 } else {
51 // directly to the normal serial 54 // directly to the normal serial
52 // TODO: look first if the connection really exists. ( is set up ) 55 // TODO: look first if the connection really exists. ( is set up )
53 56
54 ret =IOSerial::open(); 57 ret =IOSerial::open();
55 } 58 }
56 return ret; 59 return ret;
57} 60}
58 61
59void IOBt::reload( const Profile &config ) { 62void IOBt::reload( const Profile &config ) {
60 m_device = config.readEntry("Device", BT_DEFAULT_DEVICE); 63 m_device = config.readEntry("Device", BT_DEFAULT_DEVICE);
61 m_mac = config.readEntry("Mac", BT_DEFAULT_MAC); 64 m_mac = config.readEntry("Mac", BT_DEFAULT_MAC);
62 m_baud = config.readNumEntry("Baud", BT_DEFAULT_BAUD); 65 m_baud = config.readNumEntry("Baud", BT_DEFAULT_BAUD);
63 m_parity = config.readNumEntry("Parity", BT_DEFAULT_PARITY); 66 m_parity = config.readNumEntry("Parity", BT_DEFAULT_PARITY);
64 m_dbits = config.readNumEntry("DataBits", BT_DEFAULT_DBITS); 67 m_dbits = config.readNumEntry("DataBits", BT_DEFAULT_DBITS);
65 m_sbits = config.readNumEntry("StopBits", BT_DEFAULT_SBITS); 68 m_sbits = config.readNumEntry("StopBits", BT_DEFAULT_SBITS);
66 m_flow = config.readNumEntry("Flow", BT_DEFAULT_FLOW); 69 m_flow = config.readNumEntry("Flow", BT_DEFAULT_FLOW);
67} 70}
68 71
69 72
70QString IOBt::identifier() const { 73QString IOBt::identifier() const {
71 return "bluetooth"; 74 return "bluetooth";
72} 75}
73 76
74QString IOBt::name() const { 77QString IOBt::name() const {
75 return "BLuetooth IO Layer"; 78 return "BLuetooth IO Layer";
76} 79}
77 80
78void IOBt::slotExited( OProcess* proc ){ 81void IOBt::slotExited( OProcess* proc ){
79 close(); 82 close();
80 delete proc; 83 delete proc;
81} 84}
82 85
83QBitArray IOBt::supports() const { 86QBitArray IOBt::supports() const {
84 return QBitArray( 3 ); 87 return QBitArray( 3 );
85} 88}
86 89
87bool IOBt::isConnected() { 90bool IOBt::isConnected() {
88 return false; 91 return false;
89} 92}
90 93
91void IOBt::send(const QByteArray &data) { 94void IOBt::send(const QByteArray &data) {
92 qDebug( "Please overload me..." ); 95 odebug << "Please overload me..." << oendl;
93} 96}
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 @@
1
2#include "io_irda.h" 1#include "io_irda.h"
3 2
3/* OPIE */
4#include <opie2/odebug.h>
4using namespace Opie::Core; 5using namespace Opie::Core;
6
5IOIrda::IOIrda( const Profile &config ) : IOSerial( config ) { 7IOIrda::IOIrda( const Profile &config ) : IOSerial( config ) {
6 m_attach = 0; 8 m_attach = 0;
7} 9}
8 10
9 11
10IOIrda::~IOIrda() { 12IOIrda::~IOIrda() {
11 if ( m_attach ) { 13 if ( m_attach ) {
12 delete m_attach; 14 delete m_attach;
13 } 15 }
14} 16}
15 17
16 18
17void IOIrda::close() { 19void IOIrda::close() {
18 20
19 IOSerial::close(); 21 IOSerial::close();
20 // still need error handling 22 // still need error handling
21 delete m_attach; 23 delete m_attach;
22} 24}
23 25
24bool IOIrda::open() { 26bool IOIrda::open() {
25 bool ret; 27 bool ret;
26 28
27 // irdaattach here 29 // irdaattach here
28 m_attach = new OProcess(); 30 m_attach = new OProcess();
29 *m_attach << "irattach /dev/ttyS2 -s"; 31 *m_attach << "irattach /dev/ttyS2 -s";
30 32
31 connect( m_attach, SIGNAL( processExited(Opie::Core::OProcess*) ), 33 connect( m_attach, SIGNAL( processExited(Opie::Core::OProcess*) ),
32 this, SLOT( slotExited(Opie::Core::OProcess*) ) ); 34 this, SLOT( slotExited(Opie::Core::OProcess*) ) );
33 35
34 if ( m_attach->start() ) { 36 if ( m_attach->start() ) {
35 ret= IOSerial::open(); 37 ret= IOSerial::open();
36 } else { 38 } else {
37 // emit error!!! 39 // emit error!!!
38 qWarning("could not attach to device"); 40 owarn << "could not attach to device" << oendl;
39 delete m_attach; 41 delete m_attach;
40 m_attach = 0l; 42 m_attach = 0l;
41 } 43 }
42 return ret; 44 return ret;
43} 45}
44 46
45void IOIrda::reload( const Profile &config ) { 47void IOIrda::reload( const Profile &config ) {
46 m_device = config.readEntry("Device", IRDA_DEFAULT_DEVICE); 48 m_device = config.readEntry("Device", IRDA_DEFAULT_DEVICE);
47 m_baud = config.readNumEntry("Baud", IRDA_DEFAULT_BAUD); 49 m_baud = config.readNumEntry("Baud", IRDA_DEFAULT_BAUD);
48 m_parity = config.readNumEntry("Parity", IRDA_DEFAULT_PARITY); 50 m_parity = config.readNumEntry("Parity", IRDA_DEFAULT_PARITY);
49 m_dbits = config.readNumEntry("DataBits", IRDA_DEFAULT_DBITS); 51 m_dbits = config.readNumEntry("DataBits", IRDA_DEFAULT_DBITS);
50 m_sbits = config.readNumEntry("StopBits", IRDA_DEFAULT_SBITS); 52 m_sbits = config.readNumEntry("StopBits", IRDA_DEFAULT_SBITS);
51 m_flow = config.readNumEntry("Flow", IRDA_DEFAULT_FLOW); 53 m_flow = config.readNumEntry("Flow", IRDA_DEFAULT_FLOW);
52} 54}
53 55
54 56
55QString IOIrda::identifier() const { 57QString IOIrda::identifier() const {
56 return "irda"; 58 return "irda";
57} 59}
58 60
59QString IOIrda::name() const { 61QString IOIrda::name() const {
60 return "Irda IO Layer"; 62 return "Irda IO Layer";
61} 63}
62 64
63void IOIrda::slotExited(OProcess* proc ){ 65void IOIrda::slotExited(OProcess* proc ){
64 close(); 66 close();
65 delete proc; 67 delete proc;
66} 68}
67 69
68QBitArray IOIrda::supports()const { 70QBitArray IOIrda::supports()const {
69 return QBitArray( 3 ); 71 return QBitArray( 3 );
70} 72}
71 73
72bool IOIrda::isConnected() { 74bool IOIrda::isConnected() {
73 return false; 75 return false;
74} 76}
75 77
76void IOIrda::send(const QByteArray &data) { 78void IOIrda::send(const QByteArray &data) {
77 qDebug( "Please overload me..." ); 79 odebug << "Please overload me..." << oendl;
78} 80}
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 @@
1 1
2#include "io_modem.h" 2#include "io_modem.h"
3
4#include "dialer.h" 3#include "dialer.h"
5 4
5/* OPIE */
6#include <opie2/odebug.h>
6using namespace Opie::Core; 7using namespace Opie::Core;
7using namespace Opie::Core; 8
8IOModem::IOModem( const Profile &profile ) 9IOModem::IOModem( const Profile &profile )
9 : IOSerial( profile ) { 10 : IOSerial( profile ) {
10 m_profile = profile; 11 m_profile = profile;
11} 12}
12 13
13 14
14IOModem::~IOModem() { 15IOModem::~IOModem() {
15
16} 16}
17 17
18 18
19void IOModem::close() { 19void IOModem::close() {
20 // Hangup, discarding result 20 // Hangup, discarding result
21 //int fd = rawIO(); 21 //int fd = rawIO();
22 internDetach(); 22 internDetach();
23 Dialer d(m_profile, m_fd); 23 Dialer d(m_profile, m_fd);
24 d.setHangupOnly(); 24 d.setHangupOnly();
25 //d.exec(); 25 //d.exec();
26 internAttach(); 26 internAttach();
27 //closeRawIO(fd); 27 //closeRawIO(fd);
28 28
29 IOSerial::close(); 29 IOSerial::close();
30} 30}
31 31
32bool IOModem::open() { 32bool IOModem::open() {
33 bool ret = IOSerial::open(); 33 bool ret = IOSerial::open();
34 if(!ret) return false; 34 if(!ret) return false;
35 35
36 //int fd = rawIO(); 36 //int fd = rawIO();
37 internDetach(); 37 internDetach();
38 Dialer d(m_profile, m_fd); 38 Dialer d(m_profile, m_fd);
39 39
40 int result = d.exec(); 40 int result = d.exec();
41 internAttach(); 41 internAttach();
42 //closeRawIO(fd); 42 //closeRawIO(fd);
43 if(result == QDialog::Accepted) 43 if(result == QDialog::Accepted)
44 { 44 {
45 return true; 45 return true;
46 } 46 }
47 else 47 else
48 { 48 {
49 close(); 49 close();
50 return false; 50 return false;
51 } 51 }
52} 52}
53 53
54void IOModem::reload( const Profile &config ) { 54void IOModem::reload( const Profile &config ) {
55 55
56 m_device = config.readEntry("Device", MODEM_DEFAULT_DEVICE); 56 m_device = config.readEntry("Device", MODEM_DEFAULT_DEVICE);
57 m_baud = config.readNumEntry("Baud", MODEM_DEFAULT_BAUD); 57 m_baud = config.readNumEntry("Baud", MODEM_DEFAULT_BAUD);
58 m_parity = config.readNumEntry("Parity", MODEM_DEFAULT_PARITY); 58 m_parity = config.readNumEntry("Parity", MODEM_DEFAULT_PARITY);
59 m_dbits = config.readNumEntry("DataBits", MODEM_DEFAULT_DBITS); 59 m_dbits = config.readNumEntry("DataBits", MODEM_DEFAULT_DBITS);
60 m_sbits = config.readNumEntry("StopBits", MODEM_DEFAULT_SBITS); 60 m_sbits = config.readNumEntry("StopBits", MODEM_DEFAULT_SBITS);
61 m_flow = config.readNumEntry("Flow", MODEM_DEFAULT_FLOW); 61 m_flow = config.readNumEntry("Flow", MODEM_DEFAULT_FLOW);
62 62
63 m_initString = config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING ); 63 m_initString = config.readEntry("InitString", MODEM_DEFAULT_INIT_STRING );
64 m_resetString = config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING ); 64 m_resetString = config.readEntry("ResetString", MODEM_DEFAULT_RESET_STRING );
65 m_dialPref1 = config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 ); 65 m_dialPref1 = config.readEntry("DialPrefix1", MODEM_DEFAULT_DIAL_PREFIX1 );
66 m_dialSuf1 = config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 ); 66 m_dialSuf1 = config.readEntry("DialSuffix1", MODEM_DEFAULT_DIAL_SUFFIX1 );
67 m_dialPref2 = config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 ); 67 m_dialPref2 = config.readEntry("DialPrefix2", MODEM_DEFAULT_DIAL_PREFIX1 );
68 m_dialSuf2 = config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 ); 68 m_dialSuf2 = config.readEntry("DialSuffix2", MODEM_DEFAULT_DIAL_SUFFIX1 );
69 m_dialPref3 = config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 ); 69 m_dialPref3 = config.readEntry("DialPrefix3", MODEM_DEFAULT_DIAL_PREFIX1 );
70 m_dialSuf3 = config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 ); 70 m_dialSuf3 = config.readEntry("DialSuffix3", MODEM_DEFAULT_DIAL_SUFFIX1 );
71 m_connect = config.readEntry("DefaultConnect" MODEM_DEFAULT_CONNECT_STRING ); 71 m_connect = config.readEntry("DefaultConnect" MODEM_DEFAULT_CONNECT_STRING );
72 m_hangup = config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING ); 72 m_hangup = config.readEntry("HangupString", MODEM_DEFAULT_HANGUP_STRING );
73 m_cancel = config.readEntry("CancelString", MODEM_DEFAULT_CANCEL_STRING ); 73 m_cancel = config.readEntry("CancelString", MODEM_DEFAULT_CANCEL_STRING );
74 m_dialTime = config.readNumEntry("DialTime", MODEM_DEFAULT_DIAL_TIME ); 74 m_dialTime = config.readNumEntry("DialTime", MODEM_DEFAULT_DIAL_TIME );
75 m_delayRedial = config.readNumEntry("DelayRedial", MODEM_DEFAULT_DELAY_REDIAL ); 75 m_delayRedial = config.readNumEntry("DelayRedial", MODEM_DEFAULT_DELAY_REDIAL );
76 m_numberTries = config.readNumEntry("NumberTries", MODEM_DEFAULT_NUMBER_TRIES ); 76 m_numberTries = config.readNumEntry("NumberTries", MODEM_DEFAULT_NUMBER_TRIES );
77 m_dtrDropTime = config.readNumEntry("DTRDRopTime", MODEM_DEFAULT_DTR_DROP_TIME ); 77 m_dtrDropTime = config.readNumEntry("DTRDRopTime", MODEM_DEFAULT_DTR_DROP_TIME );
78 m_bpsDetect = config.readBoolEntry("BPSDetect", MODEM_DEFAULT_BPS_DETECT ); 78 m_bpsDetect = config.readBoolEntry("BPSDetect", MODEM_DEFAULT_BPS_DETECT );
79 m_dcdLines = config.readBoolEntry("DCDLines", MODEM_DEFAULT_DCD_LINES ); 79 m_dcdLines = config.readBoolEntry("DCDLines", MODEM_DEFAULT_DCD_LINES );
80 m_multiLineUntag = config.readBoolEntry("MultiLineUntag", MODEM_DEFAULT_MULTI_LINE_UNTAG ); 80 m_multiLineUntag = config.readBoolEntry("MultiLineUntag", MODEM_DEFAULT_MULTI_LINE_UNTAG );
81} 81}
82 82
83 83
84QString IOModem::identifier() const { 84QString IOModem::identifier() const {
85 return "modem"; 85 return "modem";
86} 86}
87 87
88QString IOModem::name() const { 88QString IOModem::name() const {
89 return "Modem IO Layer"; 89 return "Modem IO Layer";
90} 90}
91 91
92void IOModem::slotExited(OProcess* proc ){ 92void IOModem::slotExited(OProcess* proc ){
93 close(); 93 close();
94 /* delete it afterwards */ 94 /* delete it afterwards */
95 delete proc; 95 delete proc;
96} 96}
97 97
98QBitArray IOModem::supports()const { 98QBitArray IOModem::supports()const {
99 return QBitArray( 3 ); 99 return QBitArray( 3 );
100} 100}
101 101
102bool IOModem::isConnected() { 102bool IOModem::isConnected() {
103 return false; 103 return false;
104} 104}
105 105
106void IOModem::send(const QByteArray &data) { 106void IOModem::send(const QByteArray &data) {
107 qDebug( "Please overload me..." ); 107 odebug << "Please overload me..." << oendl;
108} 108}
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 @@
1#include <sys/types.h> 1#include <sys/types.h>
2 2
3#include <stdio.h> 3#include <stdio.h>
4#include <stdlib.h> 4#include <stdlib.h>
5#include <signal.h> 5#include <signal.h>
6 6
7 7
8#include <qpe/qpeapplication.h> 8#include <qpe/qpeapplication.h>
9 9
10#include "mainwindow.h" 10#include "mainwindow.h"
11 11
12//#define FSCKED_DISTRIBUTION 1 12//#define FSCKED_DISTRIBUTION 1
13#ifdef FSCKED_DISTRIBUTION 13#ifdef FSCKED_DISTRIBUTION
14/* 14/*
15 * The Zaurus rom 15 * The Zaurus rom
16 */ 16 */
17class FixIt { 17class FixIt {
18public: 18public:
19 FixIt(); 19 FixIt();
20 ~FixIt(); 20 ~FixIt();
21 void fixIt(); 21 void fixIt();
22 /* no real interested in implementing it */ 22 /* no real interested in implementing it */
23 void breakIt() { 23 void breakIt() {
24 24
25 }; 25 };
26 char* m_file; 26 char* m_file;
27}; 27};
28 28
29FixIt::FixIt() { 29FixIt::FixIt() {
30 /* the new inittab */ 30 /* the new inittab */
31 m_file = "#\n# /etc/inittab" 31 m_file = "#\n# /etc/inittab"
32"#" 32"#"
33"" 33""
34"# 0 - halt (Do NOT set initdefault to this)" 34"# 0 - halt (Do NOT set initdefault to this)"
35"# 1 - Single user mode" 35"# 1 - Single user mode"
36"# 2 - Multiuser, without NFS (The same as 3, if you do not have networking)" 36"# 2 - Multiuser, without NFS (The same as 3, if you do not have networking)"
37"# 3 - Full multiuser mode" 37"# 3 - Full multiuser mode"
38"# 4 - JavaVM(Intent) developer mode" 38"# 4 - JavaVM(Intent) developer mode"
39"# 5 - JavaVM(Intent)" 39"# 5 - JavaVM(Intent)"
40"# 6 - reboot (Do NOT set initdefault to this)" 40"# 6 - reboot (Do NOT set initdefault to this)"
41"#" 41"#"
42"id:5:initdefault:" 42"id:5:initdefault:"
43"" 43""
44"# Specify things to do when starting" 44"# Specify things to do when starting"
45"si::sysinit:/etc/rc.d/rc.sysinit" 45"si::sysinit:/etc/rc.d/rc.sysinit"
46"" 46""
47"l0:0:wait:/root/etc/rc.d/rc 0" 47"l0:0:wait:/root/etc/rc.d/rc 0"
48"l1:1:wait:/etc/rc.d/rc 1" 48"l1:1:wait:/etc/rc.d/rc 1"
49"l2:2:wait:/etc/rc.d/rc 2" 49"l2:2:wait:/etc/rc.d/rc 2"
50"l3:3:wait:/etc/rc.d/rc 3" 50"l3:3:wait:/etc/rc.d/rc 3"
51"l4:4:wait:/etc/rc.d/rc 4" 51"l4:4:wait:/etc/rc.d/rc 4"
52"l5:5:wait:/etc/rc.d/rc 5" 52"l5:5:wait:/etc/rc.d/rc 5"
53"l6:6:wait:/root/etc/rc.d/rc 6" 53"l6:6:wait:/root/etc/rc.d/rc 6"
54"" 54""
55"# Specify things to do before rebooting" 55"# Specify things to do before rebooting"
56"um::ctrlaltdel:/bin/umount -a -r > /dev/null 2>&1" 56"um::ctrlaltdel:/bin/umount -a -r > /dev/null 2>&1"
57"sw::ctrlaltdel:/sbin/swapoff -a > /dev/null 2>&1" 57"sw::ctrlaltdel:/sbin/swapoff -a > /dev/null 2>&1"
58"" 58""
59"# Specify program to run on ttyS0" 59"# Specify program to run on ttyS0"
60"s0:24:respawn:/sbin/getty 9600 ttyS0" 60"s0:24:respawn:/sbin/getty 9600 ttyS0"
61"#pd:5:respawn:/etc/sync/serialctl" 61"#pd:5:respawn:/etc/sync/serialctl"
62"" 62""
63"# Specify program to run on tty1" 63"# Specify program to run on tty1"
64"1:2:respawn:/sbin/getty 9600 tty1" 64"1:2:respawn:/sbin/getty 9600 tty1"
65"ln:345:respawn:survive -l 6 /sbin/launch" 65"ln:345:respawn:survive -l 6 /sbin/launch"
66"#qt:5:respawn:/sbin/qt" 66"#qt:5:respawn:/sbin/qt"
67"" 67""
68"# collie sp." 68"# collie sp."
69"sy::respawn:/sbin/shsync\n"; 69"sy::respawn:/sbin/shsync\n";
70} 70}
71FixIt::~FixIt() { 71FixIt::~FixIt() {
72} 72}
73/* 73/*
74 * the retail Zaurus is broken in many ways 74 * the retail Zaurus is broken in many ways
75 * one is that pppd is listening on our port... 75 * one is that pppd is listening on our port...
76 * we've to stop it from that and then do kill(SIGHUP,1); 76 * we've to stop it from that and then do kill(SIGHUP,1);
77 */ 77 */
78void FixIt::fixIt() { 78void FixIt::fixIt() {
79 ::rename("/etc/inittab", QPEApplication::qpeDir() + "/etc/inittab" ); 79 ::rename("/etc/inittab", QPEApplication::qpeDir() + "/etc/inittab" );
80 QFile file( "/etc/inittab" ); 80 QFile file( "/etc/inittab" );
81 if ( file.open(IO_WriteOnly | IO_Raw ) ) { 81 if ( file.open(IO_WriteOnly | IO_Raw ) ) {
82 file.writeBlock(m_file,strlen(m_file) ); 82 file.writeBlock(m_file,strlen(m_file) );
83 } 83 }
84 file.close(); 84 file.close();
85 ::kill( SIGHUP, 1 ); 85 ::kill( SIGHUP, 1 );
86} 86}
87#endif 87#endif
88 88
89int main(int argc, char **argv) { 89int main(int argc, char **argv) {
90// too bad this gives us trouble the taskbar... argv[0]="embeddedkonsole"; 90// too bad this gives us trouble the taskbar... argv[0]="embeddedkonsole";
91 QPEApplication app( argc, argv ); 91 QPEApplication app( argc, argv );
92 92
93#ifdef FSCKED_DISTRIBUTION 93#ifdef FSCKED_DISTRIBUTION
94 qWarning("fscked"); 94 owarn << "fscked" << oendl;
95 FixIt it; 95 FixIt it;
96 it.fixIt(); 96 it.fixIt();
97#endif 97#endif
98 98
99 MainWindow mw; 99 MainWindow mw;
100 mw.setCaption(QObject::tr("Opie Console") ); 100 mw.setCaption(QObject::tr("Opie Console") );
101 app.showMainWidget( &mw ); 101 app.showMainWidget( &mw );
102 102
103 int ap = app.exec(); 103 int ap = app.exec();
104 104
105#ifdef FSCKED_DISTRIBUTION 105#ifdef FSCKED_DISTRIBUTION
106 /* should add a signal handler too */ 106 /* should add a signal handler too */
107 it.breakIt(); 107 it.breakIt();
108#endif 108#endif
109 return ap; 109 return ap;
110} 110}
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 @@
1#include <assert.h>
2
3#include <qaction.h>
4#include <qmenubar.h>
5#include <qtoolbar.h>
6#include <qmessagebox.h>
7#include <qwhatsthis.h>
8#include <qfileinfo.h>
9
10#include <qpe/filemanager.h>
11
12#include <opie2/ofiledialog.h>
13
14#include "TEmulation.h" 1#include "TEmulation.h"
15#include "profileeditordialog.h" 2#include "profileeditordialog.h"
16#include "configdialog.h" 3#include "configdialog.h"
17#include "default.h" 4#include "default.h"
18#include "profilemanager.h" 5#include "profilemanager.h"
19#include "mainwindow.h" 6#include "mainwindow.h"
20#include "tabwidget.h" 7#include "tabwidget.h"
21#include "transferdialog.h" 8#include "transferdialog.h"
22#include "function_keyboard.h" 9#include "function_keyboard.h"
23#include "emulation_handler.h" 10#include "emulation_handler.h"
24#include "script.h" 11#include "script.h"
25 12
26 13/* OPIE */
14#include <opie2/odebug.h>
15#include <opie2/ofiledialog.h>
16#include <qpe/filemanager.h>
17using namespace Opie::Core;
27using namespace Opie::Ui; 18using namespace Opie::Ui;
19
20/* QT */
21#include <qaction.h>
22#include <qmenubar.h>
23#include <qtoolbar.h>
24#include <qmessagebox.h>
25#include <qwhatsthis.h>
26#include <qfileinfo.h>
27
28/* STD */
29#include <assert.h>
30
28MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) { 31MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) {
29 KeyTrans::loadAll(); 32 KeyTrans::loadAll();
30 for (int i = 0; i < KeyTrans::count(); i++ ) { 33 for (int i = 0; i < KeyTrans::count(); i++ ) {
31 KeyTrans* s = KeyTrans::find(i ); 34 KeyTrans* s = KeyTrans::find(i );
32 assert( s ); 35 assert( s );
33 } 36 }
34 m_factory = new MetaFactory(); 37 m_factory = new MetaFactory();
35 Default def(m_factory); 38 Default def(m_factory);
36 m_sessions.setAutoDelete( TRUE ); 39 m_sessions.setAutoDelete( TRUE );
37 m_curSession = 0; 40 m_curSession = 0;
38 m_manager = new ProfileManager( m_factory ); 41 m_manager = new ProfileManager( m_factory );
39 m_manager->load(); 42 m_manager->load();
40 m_scriptsData.setAutoDelete(TRUE); 43 m_scriptsData.setAutoDelete(TRUE);
41 44
42 initUI(); 45 initUI();
43 populateProfiles(); 46 populateProfiles();
44 populateScripts(); 47 populateScripts();
45} 48}
46 49
47void MainWindow::initUI() { 50void MainWindow::initUI() {
48 51
49 setToolBarsMovable( FALSE ); 52 setToolBarsMovable( FALSE );
50 53
51 /* tool bar for the menu */ 54 /* tool bar for the menu */
52 m_tool = new QToolBar( this ); 55 m_tool = new QToolBar( this );
53 m_tool->setHorizontalStretchable( TRUE ); 56 m_tool->setHorizontalStretchable( TRUE );
54 57
55 m_bar = new QMenuBar( m_tool ); 58 m_bar = new QMenuBar( m_tool );
56 m_console = new QPopupMenu( this ); 59 m_console = new QPopupMenu( this );
57 m_scripts = new QPopupMenu( this ); 60 m_scripts = new QPopupMenu( this );
58 m_sessionsPop= new QPopupMenu( this ); 61 m_sessionsPop= new QPopupMenu( this );
59 m_scriptsPop = new QPopupMenu( this ); 62 m_scriptsPop = new QPopupMenu( this );
60 63
61 /* add a toolbar for icons */ 64 /* add a toolbar for icons */
62 m_icons = new QToolBar(this); 65 m_icons = new QToolBar(this);
63 66
64 /* 67 /*
65 * the settings action 68 * the settings action
66 */ 69 */
67 m_setProfiles = new QAction(tr("Configure Profiles"), 70 m_setProfiles = new QAction(tr("Configure Profiles"),
68 Resource::loadPixmap( "SettingsIcon" ), 71 Resource::loadPixmap( "SettingsIcon" ),
69 QString::null, 0, this, 0); 72 QString::null, 0, this, 0);
70 m_setProfiles->addTo( m_console ); 73 m_setProfiles->addTo( m_console );
71 connect( m_setProfiles, SIGNAL(activated() ), 74 connect( m_setProfiles, SIGNAL(activated() ),
72 this, SLOT(slotConfigure() ) ); 75 this, SLOT(slotConfigure() ) );
73 76
74 m_console->insertSeparator(); 77 m_console->insertSeparator();
75 /* 78 /*
76 * new Action for new sessions 79 * new Action for new sessions
77 */ 80 */
78 QAction* newCon = new QAction(tr("New Profile"), 81 QAction* newCon = new QAction(tr("New Profile"),
79 Resource::loadPixmap( "new" ), 82 Resource::loadPixmap( "new" ),
80 QString::null, 0, this, 0); 83 QString::null, 0, this, 0);
81 newCon->addTo( m_console ); 84 newCon->addTo( m_console );
82 connect( newCon, SIGNAL(activated() ), 85 connect( newCon, SIGNAL(activated() ),
83 this, SLOT(slotNew() ) ); 86 this, SLOT(slotNew() ) );
84 87
85 m_console->insertSeparator(); 88 m_console->insertSeparator();
86 89
87 QAction *saveCon = new QAction( tr("Save Profile" ), 90 QAction *saveCon = new QAction( tr("Save Profile" ),
88 Resource::loadPixmap( "save" ), QString::null, 91 Resource::loadPixmap( "save" ), QString::null,
89 0, this, 0 ); 92 0, this, 0 );
90 saveCon->addTo( m_console ); 93 saveCon->addTo( m_console );
91 connect( saveCon, SIGNAL(activated() ), 94 connect( saveCon, SIGNAL(activated() ),
92 this, SLOT(slotSaveSession() ) ); 95 this, SLOT(slotSaveSession() ) );
93 m_console->insertSeparator(); 96 m_console->insertSeparator();
94 97
95 /* 98 /*
96 * connect action 99 * connect action
97 */ 100 */
98 m_connect = new QAction( tr("Connect"), Resource::loadPixmap("console/connected"), 101 m_connect = new QAction( tr("Connect"), Resource::loadPixmap("console/connected"),
99 QString::null, 0, this, 0 ); 102 QString::null, 0, this, 0 );
100 m_connect->addTo( m_console ); 103 m_connect->addTo( m_console );
101 connect(m_connect, SIGNAL(activated() ), 104 connect(m_connect, SIGNAL(activated() ),
102 this, SLOT(slotConnect() ) ); 105 this, SLOT(slotConnect() ) );
103 106
104 /* 107 /*
105 * disconnect action 108 * disconnect action
106 */ 109 */
107 m_disconnect = new QAction( tr("Disconnect"), Resource::loadPixmap("console/notconnected"), 110 m_disconnect = new QAction( tr("Disconnect"), Resource::loadPixmap("console/notconnected"),
108 QString::null, 0, this, 0 ); 111 QString::null, 0, this, 0 );
109 m_disconnect->addTo( m_console ); 112 m_disconnect->addTo( m_console );
110 connect(m_disconnect, SIGNAL(activated() ), 113 connect(m_disconnect, SIGNAL(activated() ),
111 this, SLOT(slotDisconnect() ) ); 114 this, SLOT(slotDisconnect() ) );
112 115
113 m_console->insertSeparator(); 116 m_console->insertSeparator();
114 117
115 118
116 m_quickLaunch = new QAction( tr("QuickLaunch"), Resource::loadPixmap("console/konsole_mini"), QString::null, 0, this, 0 ); 119 m_quickLaunch = new QAction( tr("QuickLaunch"), Resource::loadPixmap("console/konsole_mini"), QString::null, 0, this, 0 );
117 m_quickLaunch->addTo( m_icons ); 120 m_quickLaunch->addTo( m_icons );
118 connect( m_quickLaunch, SIGNAL( activated() ), 121 connect( m_quickLaunch, SIGNAL( activated() ),
119 this, SLOT( slotQuickLaunch() ) ); 122 this, SLOT( slotQuickLaunch() ) );
120 123
121 QWhatsThis::add( m_icons, tr( "The shell button launches the \"default\" profile. If there is none default values are taken" ) ); 124 QWhatsThis::add( m_icons, tr( "The shell button launches the \"default\" profile. If there is none default values are taken" ) );
122 125
123 m_transfer = new QAction( tr("Transfer file..."), Resource::loadPixmap("pass") , QString::null, 126 m_transfer = new QAction( tr("Transfer file..."), Resource::loadPixmap("pass") , QString::null,
@@ -353,326 +356,326 @@ void MainWindow::slotSaveScript() {
353} 356}
354 357
355void MainWindow::slotRunScript(int id) { 358void MainWindow::slotRunScript(int id) {
356 if (currentSession()) { 359 if (currentSession()) {
357 int index = m_scriptsPop->indexOf(id); 360 int index = m_scriptsPop->indexOf(id);
358 DocLnk *lnk = m_scriptsData.at(index); 361 DocLnk *lnk = m_scriptsData.at(index);
359 QString filePath = lnk->file(); 362 QString filePath = lnk->file();
360 Script script(filePath); 363 Script script(filePath);
361 currentSession()->emulationHandler()->runScript(&script); 364 currentSession()->emulationHandler()->runScript(&script);
362 } 365 }
363} 366}
364 367
365void MainWindow::slotConnect() { 368void MainWindow::slotConnect() {
366 if ( currentSession() ) { 369 if ( currentSession() ) {
367 bool ret = currentSession()->layer()->open(); 370 bool ret = currentSession()->layer()->open();
368 if(!ret) QMessageBox::warning(currentSession()->widgetStack(), 371 if(!ret) QMessageBox::warning(currentSession()->widgetStack(),
369 QObject::tr("Failed"), 372 QObject::tr("Failed"),
370 QObject::tr("Connecting failed for this session.")); 373 QObject::tr("Connecting failed for this session."));
371 else { 374 else {
372 m_connect->setEnabled( false ); 375 m_connect->setEnabled( false );
373 m_disconnect->setEnabled( true ); 376 m_disconnect->setEnabled( true );
374 377
375 // if it does not support file transfer, disable the menu entry 378 // if it does not support file transfer, disable the menu entry
376 if ( ( m_curSession->layer() )->supports()[1] == 0 ) { 379 if ( ( m_curSession->layer() )->supports()[1] == 0 ) {
377 m_transfer->setEnabled( false ); 380 m_transfer->setEnabled( false );
378 } else { 381 } else {
379 m_transfer->setEnabled( true ); 382 m_transfer->setEnabled( true );
380 } 383 }
381 384
382 m_recordScript->setEnabled( true ); 385 m_recordScript->setEnabled( true );
383 m_scripts->setItemEnabled(m_runScript_id, true); 386 m_scripts->setItemEnabled(m_runScript_id, true);
384 } 387 }
385 } 388 }
386} 389}
387 390
388void MainWindow::slotDisconnect() { 391void MainWindow::slotDisconnect() {
389 if ( currentSession() ) { 392 if ( currentSession() ) {
390 currentSession()->layer()->close(); 393 currentSession()->layer()->close();
391 m_connect->setEnabled( true ); 394 m_connect->setEnabled( true );
392 m_disconnect->setEnabled( false ); 395 m_disconnect->setEnabled( false );
393 m_transfer->setEnabled( false ); 396 m_transfer->setEnabled( false );
394 m_recordScript->setEnabled( false); 397 m_recordScript->setEnabled( false);
395 m_saveScript->setEnabled( false ); 398 m_saveScript->setEnabled( false );
396 m_scripts->setItemEnabled(m_runScript_id, false); 399 m_scripts->setItemEnabled(m_runScript_id, false);
397 } 400 }
398} 401}
399 402
400void MainWindow::slotTerminate() { 403void MainWindow::slotTerminate() {
401 if ( currentSession() ) 404 if ( currentSession() )
402 currentSession()->layer()->close(); 405 currentSession()->layer()->close();
403 406
404 slotClose(); 407 slotClose();
405 /* FIXME move to the next session */ 408 /* FIXME move to the next session */
406} 409}
407 410
408 411
409 412
410 413
411 414
412 415
413void MainWindow::slotQuickLaunch() { 416void MainWindow::slotQuickLaunch() {
414 Profile prof = manager()->profile( "default" ); 417 Profile prof = manager()->profile( "default" );
415 if ( prof.name() == "default" ) { 418 if ( prof.name() == "default" ) {
416 create( prof ); 419 create( prof );
417 } else { 420 } else {
418 Profile newProf = Profile( "default", "console", "default" , 0, 3, 0 ); 421 Profile newProf = Profile( "default", "console", "default" , 0, 3, 0 );
419 newProf.setAutoConnect( true ); 422 newProf.setAutoConnect( true );
420 create( newProf ); 423 create( newProf );
421 slotSaveSession(); 424 slotSaveSession();
422 } 425 }
423 426
424} 427}
425 428
426void MainWindow::slotConfigure() { 429void MainWindow::slotConfigure() {
427 ConfigDialog conf( manager()->all(), factory() ); 430 ConfigDialog conf( manager()->all(), factory() );
428 431
429 int ret = QPEApplication::execDialog( &conf ); 432 int ret = QPEApplication::execDialog( &conf );
430 433
431 if ( QDialog::Accepted == ret ) { 434 if ( QDialog::Accepted == ret ) {
432 manager()->setProfiles( conf.list() ); 435 manager()->setProfiles( conf.list() );
433 manager()->save(); 436 manager()->save();
434 populateProfiles(); 437 populateProfiles();
435 } 438 }
436} 439}
437/* 440/*
438 * we will remove 441 * we will remove
439 * this window from the tabwidget 442 * this window from the tabwidget
440 * remove it from the list 443 * remove it from the list
441 * delete it 444 * delete it
442 * and set the currentSession() 445 * and set the currentSession()
443 */ 446 */
444void MainWindow::slotClose() { 447void MainWindow::slotClose() {
445 if (!currentSession() ) 448 if (!currentSession() )
446 return; 449 return;
447 450
448 Session* ses = currentSession(); 451 Session* ses = currentSession();
449 qWarning("removing! currentSession %s", currentSession()->name().latin1() ); 452 owarn << "removing! currentSession " << currentSession()->name().latin1() << "" << oendl;
450 /* set to NULL to be safe, if its needed slotSessionChanged resets it automatically */ 453 /* set to NULL to be safe, if its needed slotSessionChanged resets it automatically */
451 m_curSession = NULL; 454 m_curSession = NULL;
452 tabWidget()->remove( /*currentSession()*/ses ); 455 tabWidget()->remove( /*currentSession()*/ses );
453 /*it's autodelete */ 456 /*it's autodelete */
454 m_sessions.remove( ses ); 457 m_sessions.remove( ses );
455 qWarning("after remove!!"); 458 owarn << "after remove!!" << oendl;
456 459
457 if (!currentSession() ) { 460 if (!currentSession() ) {
458 m_connect->setEnabled( false ); 461 m_connect->setEnabled( false );
459 m_disconnect->setEnabled( false ); 462 m_disconnect->setEnabled( false );
460 m_terminate->setEnabled( false ); 463 m_terminate->setEnabled( false );
461 m_transfer->setEnabled( false ); 464 m_transfer->setEnabled( false );
462 m_recordScript->setEnabled( false ); 465 m_recordScript->setEnabled( false );
463 m_saveScript->setEnabled( false ); 466 m_saveScript->setEnabled( false );
464 m_scripts->setItemEnabled(m_runScript_id, false); 467 m_scripts->setItemEnabled(m_runScript_id, false);
465 m_fullscreen->setEnabled( false ); 468 m_fullscreen->setEnabled( false );
466 m_wrap->setEnabled( false ); 469 m_wrap->setEnabled( false );
467 m_closewindow->setEnabled( false ); 470 m_closewindow->setEnabled( false );
468 } 471 }
469 472
470 m_kb->loadDefaults(); 473 m_kb->loadDefaults();
471} 474}
472 475
473/* 476/*
474 * We will get the name 477 * We will get the name
475 * Then the profile 478 * Then the profile
476 * and then we will make a profile 479 * and then we will make a profile
477 */ 480 */
478void MainWindow::slotProfile( int id) { 481void MainWindow::slotProfile( int id) {
479 Profile prof = manager()->profile( m_sessionsPop->text( id) ); 482 Profile prof = manager()->profile( m_sessionsPop->text( id) );
480 create( prof ); 483 create( prof );
481} 484}
482 485
483 486
484 487
485void MainWindow::create( const Profile& prof ) { 488void MainWindow::create( const Profile& prof ) {
486 if(m_curSession) 489 if(m_curSession)
487 if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide(); 490 if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide();
488 491
489 Session *ses = manager()->fromProfile( prof, tabWidget() ); 492 Session *ses = manager()->fromProfile( prof, tabWidget() );
490 493
491 if((!ses) || (!ses->layer()) || (!ses->widgetStack())) 494 if((!ses) || (!ses->layer()) || (!ses->widgetStack()))
492 { 495 {
493 QMessageBox::warning(this, 496 QMessageBox::warning(this,
494 QObject::tr("Session failed"), 497 QObject::tr("Session failed"),
495 QObject::tr("<qt>Cannot open session: Not all components were found.</qt>")); 498 QObject::tr("<qt>Cannot open session: Not all components were found.</qt>"));
496 //if(ses) delete ses; 499 //if(ses) delete ses;
497 return; 500 return;
498 } 501 }
499 502
500 m_sessions.append( ses ); 503 m_sessions.append( ses );
501 tabWidget()->add( ses ); 504 tabWidget()->add( ses );
502 tabWidget()->repaint(); 505 tabWidget()->repaint();
503 m_curSession = ses; 506 m_curSession = ses;
504 507
505 // dicide if its a local term ( then no connction and no tranfer), maybe make a wrapper method out of it 508 // dicide if its a local term ( then no connction and no tranfer), maybe make a wrapper method out of it
506 m_connect->setEnabled( true ); 509 m_connect->setEnabled( true );
507 m_disconnect->setEnabled( false ); 510 m_disconnect->setEnabled( false );
508 m_terminate->setEnabled( true ); 511 m_terminate->setEnabled( true );
509 m_fullscreen->setEnabled( true ); 512 m_fullscreen->setEnabled( true );
510 m_wrap->setEnabled( true ); 513 m_wrap->setEnabled( true );
511 m_closewindow->setEnabled( true ); 514 m_closewindow->setEnabled( true );
512 m_transfer->setEnabled( false ); 515 m_transfer->setEnabled( false );
513 m_recordScript->setEnabled( false ); 516 m_recordScript->setEnabled( false );
514 m_saveScript->setEnabled( false ); 517 m_saveScript->setEnabled( false );
515 m_scripts->setItemEnabled(m_runScript_id, false); 518 m_scripts->setItemEnabled(m_runScript_id, false);
516 519
517 // is io_layer wants direct connection, then autoconnect 520 // is io_layer wants direct connection, then autoconnect
518 //if ( ( m_curSession->layer() )->supports()[0] == 1 ) { 521 //if ( ( m_curSession->layer() )->supports()[0] == 1 ) {
519 if (prof.autoConnect()) { 522 if (prof.autoConnect()) {
520 slotConnect(); 523 slotConnect();
521 } 524 }
522 525
523 526
524 QWidget *w = currentSession()->widget(); 527 QWidget *w = currentSession()->widget();
525 if(w) w->setFocus(); 528 if(w) w->setFocus();
526 529
527 if(currentSession()->profile().readNumEntry("Wrap", 80)){ 530 if(currentSession()->profile().readNumEntry("Wrap", 80)){
528 m_isWrapped = true; 531 m_isWrapped = true;
529 } else { 532 } else {
530 m_isWrapped = false; 533 m_isWrapped = false;
531 } 534 }
532 535
533 m_kb->load(currentSession()->profile()); 536 m_kb->load(currentSession()->profile());
534} 537}
535 538
536void MainWindow::slotTransfer() 539void MainWindow::slotTransfer()
537{ 540{
538 if ( currentSession() ) { 541 if ( currentSession() ) {
539 Session *mysession = currentSession(); 542 Session *mysession = currentSession();
540 TransferDialog dlg(/*mysession->widgetStack()*/this, this); 543 TransferDialog dlg(/*mysession->widgetStack()*/this, this);
541 mysession->setTransferDialog(&dlg); 544 mysession->setTransferDialog(&dlg);
542 //dlg.reparent(mysession->widgetStack(), QPoint(0, 0)); 545 //dlg.reparent(mysession->widgetStack(), QPoint(0, 0));
543 //dlg.showMaximized(); 546 //dlg.showMaximized();
544 currentSession()->widgetStack()->addWidget(&dlg, -1); 547 currentSession()->widgetStack()->addWidget(&dlg, -1);
545 dlg.show(); 548 dlg.show();
546 //dlg.exec(); 549 //dlg.exec();
547 while(dlg.isRunning()) qApp->processEvents(); 550 while(dlg.isRunning()) qApp->processEvents();
548 mysession->setTransferDialog(0l); 551 mysession->setTransferDialog(0l);
549 } 552 }
550} 553}
551 554
552 555
553void MainWindow::slotOpenKeb(bool state) { 556void MainWindow::slotOpenKeb(bool state) {
554 557
555 if (state) m_keyBar->show(); 558 if (state) m_keyBar->show();
556 else m_keyBar->hide(); 559 else m_keyBar->hide();
557 560
558} 561}
559 562
560 563
561void MainWindow::slotOpenButtons( bool state ) { 564void MainWindow::slotOpenButtons( bool state ) {
562 565
563 if ( state ) { 566 if ( state ) {
564 m_buttonBar->show(); 567 m_buttonBar->show();
565 } else { 568 } else {
566 m_buttonBar->hide(); 569 m_buttonBar->hide();
567 } 570 }
568} 571}
569 572
570 573
571 574
572void MainWindow::slotSessionChanged( Session* ses ) { 575void MainWindow::slotSessionChanged( Session* ses ) {
573 qWarning("changed!"); 576 owarn << "changed!" << oendl;
574 577
575 if(m_curSession) 578 if(m_curSession)
576 if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide(); 579 if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide();
577 if(ses) 580 if(ses)
578 if(ses->transferDialog()) ses->transferDialog()->show(); 581 if(ses->transferDialog()) ses->transferDialog()->show();
579 582
580 if ( ses ) { 583 if ( ses ) {
581 m_curSession = ses; 584 m_curSession = ses;
582 qDebug(QString("is connected : %1").arg( m_curSession->layer()->isConnected() ) ); 585 odebug << QString("is connected : %1").arg( m_curSession->layer()->isConnected() ) << oendl;
583 if ( m_curSession->layer()->isConnected() ) { 586 if ( m_curSession->layer()->isConnected() ) {
584 m_connect->setEnabled( false ); 587 m_connect->setEnabled( false );
585 m_disconnect->setEnabled( true ); 588 m_disconnect->setEnabled( true );
586 m_recordScript->setEnabled(!m_curSession->emulationHandler()->isRecording()); 589 m_recordScript->setEnabled(!m_curSession->emulationHandler()->isRecording());
587 m_saveScript->setEnabled(m_curSession->emulationHandler()->isRecording()); 590 m_saveScript->setEnabled(m_curSession->emulationHandler()->isRecording());
588 m_scripts->setItemEnabled(m_runScript_id, true); 591 m_scripts->setItemEnabled(m_runScript_id, true);
589 } else { 592 } else {
590 m_connect->setEnabled( true ); 593 m_connect->setEnabled( true );
591 m_disconnect->setEnabled( false ); 594 m_disconnect->setEnabled( false );
592 m_recordScript->setEnabled( false ); 595 m_recordScript->setEnabled( false );
593 m_saveScript->setEnabled( false ); 596 m_saveScript->setEnabled( false );
594 m_scripts->setItemEnabled(m_runScript_id, false); 597 m_scripts->setItemEnabled(m_runScript_id, false);
595 } 598 }
596 599
597 if ( ( m_curSession->layer() )->supports()[1] == 0 ) { 600 if ( ( m_curSession->layer() )->supports()[1] == 0 ) {
598 m_transfer->setEnabled( false ); 601 m_transfer->setEnabled( false );
599 } else { 602 } else {
600 m_transfer->setEnabled( true ); 603 m_transfer->setEnabled( true );
601 } 604 }
602 605
603 QWidget *w = m_curSession->widget(); 606 QWidget *w = m_curSession->widget();
604 if(w) w->setFocus(); 607 if(w) w->setFocus();
605 608
606 if(currentSession()->profile().readNumEntry("Wrap", 80)){ 609 if(currentSession()->profile().readNumEntry("Wrap", 80)){
607 m_isWrapped = true; 610 m_isWrapped = true;
608 } else { 611 } else {
609 m_isWrapped = false; 612 m_isWrapped = false;
610 } 613 }
611 614
612 m_kb->load(currentSession()->profile()); 615 m_kb->load(currentSession()->profile());
613 } 616 }
614} 617}
615 618
616void MainWindow::slotWrap() 619void MainWindow::slotWrap()
617{ 620{
618 if(m_curSession) 621 if(m_curSession)
619 { 622 {
620 EmulationHandler *e = m_curSession->emulationHandler(); 623 EmulationHandler *e = m_curSession->emulationHandler();
621 if(e) 624 if(e)
622 { 625 {
623 if(m_isWrapped) 626 if(m_isWrapped)
624 { 627 {
625 e->setWrap(80); 628 e->setWrap(80);
626 m_isWrapped = false; 629 m_isWrapped = false;
627 } 630 }
628 else 631 else
629 { 632 {
630 e->setWrap(0); 633 e->setWrap(0);
631 m_isWrapped = true; 634 m_isWrapped = true;
632 } 635 }
633 } 636 }
634 } 637 }
635} 638}
636 639
637void MainWindow::slotFullscreen() { 640void MainWindow::slotFullscreen() {
638 641
639 642
640 643
641 if ( m_isFullscreen ) { 644 if ( m_isFullscreen ) {
642 ( m_curSession->widgetStack() )->reparent( savedParentFullscreen, 0, QPoint(0,0), true ); 645 ( m_curSession->widgetStack() )->reparent( savedParentFullscreen, 0, QPoint(0,0), true );
643 ( m_curSession->widgetStack() )->resize( savedParentFullscreen->width(), savedParentFullscreen->height() ); 646 ( m_curSession->widgetStack() )->resize( savedParentFullscreen->width(), savedParentFullscreen->height() );
644 ( m_curSession->emulationHandler() )->cornerButton()->hide(); 647 ( m_curSession->emulationHandler() )->cornerButton()->hide();
645 disconnect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) ); 648 disconnect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) );
646 649
647 } else { 650 } else {
648 savedParentFullscreen = ( m_curSession->widgetStack() )->parentWidget(); 651 savedParentFullscreen = ( m_curSession->widgetStack() )->parentWidget();
649 ( m_curSession->widgetStack() )->setFrameStyle( QFrame::NoFrame ); 652 ( m_curSession->widgetStack() )->setFrameStyle( QFrame::NoFrame );
650 ( m_curSession->widgetStack() )->reparent( 0, WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop 653 ( m_curSession->widgetStack() )->reparent( 0, WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop
651 , QPoint(0,0), false ); 654 , QPoint(0,0), false );
652 ( m_curSession->widgetStack() )->resize( qApp->desktop()->width(), qApp->desktop()->height() ); 655 ( m_curSession->widgetStack() )->resize( qApp->desktop()->width(), qApp->desktop()->height() );
653 ( m_curSession->widgetStack() )->setFocus(); 656 ( m_curSession->widgetStack() )->setFocus();
654 ( m_curSession->widgetStack() )->show(); 657 ( m_curSession->widgetStack() )->show();
655 658
656 ( ( m_curSession->emulationHandler() )->cornerButton() )->show(); 659 ( ( m_curSession->emulationHandler() )->cornerButton() )->show();
657 660
658 connect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) ); 661 connect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) );
659 } 662 }
660 663
661 m_isFullscreen = !m_isFullscreen; 664 m_isFullscreen = !m_isFullscreen;
662} 665}
663 666
664 667
665void MainWindow::slotKeyReceived(FKey k, ushort, ushort, bool pressed) { 668void MainWindow::slotKeyReceived(FKey k, ushort, ushort, bool pressed) {
666 669
667 if ( m_curSession ) { 670 if ( m_curSession ) {
668 671
669 QEvent::Type state; 672 QEvent::Type state;
670 673
671 if (pressed) state = QEvent::KeyPress; 674 if (pressed) state = QEvent::KeyPress;
672 else state = QEvent::KeyRelease; 675 else state = QEvent::KeyRelease;
673 676
674 QKeyEvent ke(state, k.qcode, k.unicode, 0, QString(QChar(k.unicode))); 677 QKeyEvent ke(state, k.qcode, k.unicode, 0, QString(QChar(k.unicode)));
675 678
676 // is this the best way to do this? cant figure out any other way to work 679 // is this the best way to do this? cant figure out any other way to work
677 QApplication::sendEvent((QObject *)m_curSession->widget(), &ke); 680 QApplication::sendEvent((QObject *)m_curSession->widget(), &ke);
678 ke.ignore(); 681 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 @@
1#include "modemconfigwidget.h"
2#include "dialdialog.h"
1 3
4/* OPIE */
5#include <opie2/odebug.h>
2#include <qpe/qpeapplication.h> 6#include <qpe/qpeapplication.h>
7using namespace Opie::Core;
3 8
9/* QT */
4#include <qlabel.h> 10#include <qlabel.h>
5#include <qlayout.h> 11#include <qlayout.h>
6#include <qcombobox.h> 12#include <qcombobox.h>
7#include <qpushbutton.h> 13#include <qpushbutton.h>
8#include <qhbox.h> 14#include <qhbox.h>
9 15
10#include "modemconfigwidget.h"
11#include "dialdialog.h"
12
13namespace { 16namespace {
14 void setCurrent( const QString& str, QComboBox* bo ) { 17 void setCurrent( const QString& str, QComboBox* bo ) {
15 uint b = bo->count(); 18 uint b = bo->count();
16 for (int i = 0; i < bo->count(); i++ ) { 19 for (int i = 0; i < bo->count(); i++ ) {
17 if ( bo->text(i) == str ) { 20 if ( bo->text(i) == str ) {
18 bo->setCurrentItem( i ); 21 bo->setCurrentItem( i );
19 return; 22 return;
20 } 23 }
21 } 24 }
22 bo->insertItem( str ); 25 bo->insertItem( str );
23 bo->setCurrentItem( b ); 26 bo->setCurrentItem( b );
24 } 27 }
25} 28}
26 29
27ModemConfigWidget::ModemConfigWidget( const QString& name, QWidget* parent, 30ModemConfigWidget::ModemConfigWidget( const QString& name, QWidget* parent,
28 const char* na ) 31 const char* na )
29 : ProfileDialogConnectionWidget( name, parent, na ) { 32 : ProfileDialogConnectionWidget( name, parent, na ) {
30 33
31 m_lay = new QVBoxLayout( this ); 34 m_lay = new QVBoxLayout( this );
32 m_device = new QLabel(tr( "Modem is attached to:" ), this ); 35 m_device = new QLabel(tr( "Modem is attached to:" ), this );
33 m_deviceCmb = new QComboBox(this ); 36 m_deviceCmb = new QComboBox(this );
34 m_deviceCmb->setEditable( TRUE ); 37 m_deviceCmb->setEditable( TRUE );
35 38
36 QLabel* telLabel = new QLabel( this ); 39 QLabel* telLabel = new QLabel( this );
37 telLabel->setText( tr( "Enter telefon number here:" ) ); 40 telLabel->setText( tr( "Enter telefon number here:" ) );
38 QHBox *buttonBox = new QHBox( this ); 41 QHBox *buttonBox = new QHBox( this );
39 m_telNumber = new QLineEdit( buttonBox ); 42 m_telNumber = new QLineEdit( buttonBox );
40 QPushButton *atButton = new QPushButton( buttonBox ); 43 QPushButton *atButton = new QPushButton( buttonBox );
41 atButton->setText( tr( "AT commands" ) ); 44 atButton->setText( tr( "AT commands" ) );
42 connect( atButton, SIGNAL( clicked() ), this, SLOT( slotAT() ) ); 45 connect( atButton, SIGNAL( clicked() ), this, SLOT( slotAT() ) );
43 46
44 QPushButton *dialButton = new QPushButton( buttonBox ); 47 QPushButton *dialButton = new QPushButton( buttonBox );
45 dialButton->setText( tr( "Enter number" ) ); 48 dialButton->setText( tr( "Enter number" ) );
46 connect( dialButton, SIGNAL( clicked() ), this, SLOT( slotDial() ) ); 49 connect( dialButton, SIGNAL( clicked() ), this, SLOT( slotDial() ) );
47 50
48 m_base = new IOLayerBase( this, "base" ); 51 m_base = new IOLayerBase( this, "base" );
49 52
50 m_lay->addWidget( m_device ); 53 m_lay->addWidget( m_device );
51 m_lay->addWidget( m_deviceCmb ); 54 m_lay->addWidget( m_deviceCmb );
52 m_lay->addWidget( telLabel ); 55 m_lay->addWidget( telLabel );
53 m_lay->addWidget( buttonBox ); 56 m_lay->addWidget( buttonBox );
54 m_lay->addWidget( m_base ); 57 m_lay->addWidget( m_base );
55 m_lay->addStretch( 0 ); 58 m_lay->addStretch( 0 );
56 59
57 m_deviceCmb->insertItem( "/dev/ttyS0" ); 60 m_deviceCmb->insertItem( "/dev/ttyS0" );
58 m_deviceCmb->insertItem( "/dev/ttyS1" ); 61 m_deviceCmb->insertItem( "/dev/ttyS1" );
59 m_deviceCmb->insertItem( "/dev/ttyS2" ); 62 m_deviceCmb->insertItem( "/dev/ttyS2" );
60 63
61 atConf = new ATConfigDialog( this, "ATConfig", true ); 64 atConf = new ATConfigDialog( this, "ATConfig", true );
62} 65}
63 66
64ModemConfigWidget::~ModemConfigWidget() { 67ModemConfigWidget::~ModemConfigWidget() {
65 68
66} 69}
67void ModemConfigWidget::load( const Profile& prof ) { 70void ModemConfigWidget::load( const Profile& prof ) {
68 71
69 int rad_flow = prof.readNumEntry( "Flow" ); 72 int rad_flow = prof.readNumEntry( "Flow" );
70 int rad_parity = prof.readNumEntry( "Parity" ); 73 int rad_parity = prof.readNumEntry( "Parity" );
71 int speed = prof.readNumEntry( "Speed" ); 74 int speed = prof.readNumEntry( "Speed" );
72 int dbits = prof.readNumEntry("DataBits"); 75 int dbits = prof.readNumEntry("DataBits");
73 int sbits = prof.readNumEntry("StopBits"); 76 int sbits = prof.readNumEntry("StopBits");
74 QString number = prof.readEntry( "Number" ); 77 QString number = prof.readEntry( "Number" );
75 78
76 if ( !number.isEmpty() ) { 79 if ( !number.isEmpty() ) {
77 m_telNumber->setText( number ); 80 m_telNumber->setText( number );
78 } 81 }
79 82
80 if ( rad_flow == 1 ) { 83 if ( rad_flow == 1 ) {
81 m_base->setFlow( IOLayerBase::Hardware ); 84 m_base->setFlow( IOLayerBase::Hardware );
82 } else if (rad_flow == 2) { 85 } else if (rad_flow == 2) {
83 m_base->setFlow( IOLayerBase::Software ); 86 m_base->setFlow( IOLayerBase::Software );
84 } else if (rad_flow == 0) { 87 } else if (rad_flow == 0) {
85 m_base->setFlow( IOLayerBase::None ); 88 m_base->setFlow( IOLayerBase::None );
86 } 89 }
87 90
88 91
89 if ( rad_parity == 1 ) { 92 if ( rad_parity == 1 ) {
90 m_base->setParity( IOLayerBase::Even ); 93 m_base->setParity( IOLayerBase::Even );
91 } else if ( rad_parity == 2 ){ 94 } else if ( rad_parity == 2 ){
92 m_base->setParity( IOLayerBase::Odd ); 95 m_base->setParity( IOLayerBase::Odd );
93 } else { 96 } else {
94 m_base->setParity( IOLayerBase::NonePar ); 97 m_base->setParity( IOLayerBase::NonePar );
95 } 98 }
96 99
97 switch( speed ) { 100 switch( speed ) {
98 case 115200: 101 case 115200:
99 m_base->setSpeed( IOLayerBase::Baud_115200 ); 102 m_base->setSpeed( IOLayerBase::Baud_115200 );
100 break; 103 break;
101 case 57600: 104 case 57600:
102 m_base->setSpeed( IOLayerBase::Baud_57600 ); 105 m_base->setSpeed( IOLayerBase::Baud_57600 );
103 break; 106 break;
104 case 38400: 107 case 38400:
105 m_base->setSpeed( IOLayerBase::Baud_38400 ); 108 m_base->setSpeed( IOLayerBase::Baud_38400 );
106 break; 109 break;
107 case 19200: 110 case 19200:
108 m_base->setSpeed( IOLayerBase::Baud_19200 ); 111 m_base->setSpeed( IOLayerBase::Baud_19200 );
109 break; 112 break;
110 case 9600: 113 case 9600:
111 default: 114 default:
112 m_base->setSpeed( IOLayerBase::Baud_9600 ); 115 m_base->setSpeed( IOLayerBase::Baud_9600 );
113 break; 116 break;
114 } 117 }
115 118
116 119
117 if ( dbits == 5) { 120 if ( dbits == 5) {
118 m_base->setData( IOLayerBase::Data_Five ); 121 m_base->setData( IOLayerBase::Data_Five );
119 } else if (rad_flow == 6) { 122 } else if (rad_flow == 6) {
120 m_base->setData( IOLayerBase::Data_Six ); 123 m_base->setData( IOLayerBase::Data_Six );
121 } else if (rad_flow == 7) { 124 } else if (rad_flow == 7) {
122 m_base->setData( IOLayerBase::Data_Seven ); 125 m_base->setData( IOLayerBase::Data_Seven );
123 } else { 126 } else {
124 m_base->setData( IOLayerBase::Data_Eight ); 127 m_base->setData( IOLayerBase::Data_Eight );
125 } 128 }
126 129
127 if ( sbits == 2) { 130 if ( sbits == 2) {
128 m_base->setStop( IOLayerBase::Stop_Two ); 131 m_base->setStop( IOLayerBase::Stop_Two );
129 } else if ( sbits == 15 ) { 132 } else if ( sbits == 15 ) {
130 m_base->setStop( IOLayerBase::Stop_OnePointFive ); 133 m_base->setStop( IOLayerBase::Stop_OnePointFive );
131 } else { 134 } else {
132 m_base->setStop( IOLayerBase::Stop_One ); 135 m_base->setStop( IOLayerBase::Stop_One );
133 } 136 }
134 137
135 138
136 atConf->readConfig( prof ); 139 atConf->readConfig( prof );
137 if ( prof.readEntry( "Device" ).isEmpty() ) { 140 if ( prof.readEntry( "Device" ).isEmpty() ) {
138 qWarning("device empty!"); 141 owarn << "device empty!" << oendl;
139 return; 142 return;
140 } 143 }
141 setCurrent( prof.readEntry( "Device" ), m_deviceCmb ); 144 setCurrent( prof.readEntry( "Device" ), m_deviceCmb );
142 145
143 146
144} 147}
145 148
146/* 149/*
147 * save speed, 150 * save speed,
148 * flow, 151 * flow,
149 * parity 152 * parity
150 */ 153 */
151void ModemConfigWidget::save( Profile& prof ) { 154void ModemConfigWidget::save( Profile& prof ) {
152 int flow, parity, speed, data, stop; 155 int flow, parity, speed, data, stop;
153 flow = parity = speed = data = stop = 0; 156 flow = parity = speed = data = stop = 0;
154 prof.writeEntry( "Device", m_deviceCmb->currentText() ); 157 prof.writeEntry( "Device", m_deviceCmb->currentText() );
155 158
156 159
157 switch( m_base->flow() ) { 160 switch( m_base->flow() ) {
158 case IOLayerBase::None: 161 case IOLayerBase::None:
159 flow = 0; 162 flow = 0;
160 break; 163 break;
161 case IOLayerBase::Software: 164 case IOLayerBase::Software:
162 flow = 2; 165 flow = 2;
163 break; 166 break;
164 case IOLayerBase::Hardware: 167 case IOLayerBase::Hardware:
165 flow = 1; 168 flow = 1;
166 break; 169 break;
167 } 170 }
168 171
169 switch( m_base->parity() ) { 172 switch( m_base->parity() ) {
170 case IOLayerBase::Odd: 173 case IOLayerBase::Odd:
171 parity = 2; 174 parity = 2;
172 break; 175 break;
173 case IOLayerBase::Even: 176 case IOLayerBase::Even:
174 parity = 1; 177 parity = 1;
175 break; 178 break;
176 case IOLayerBase::NonePar: 179 case IOLayerBase::NonePar:
177 parity = 0; 180 parity = 0;
178 break; 181 break;
179 } 182 }
180 183
181 switch( m_base->speed() ) { 184 switch( m_base->speed() ) {
182 case IOLayerBase::Baud_115200: 185 case IOLayerBase::Baud_115200:
183 speed = 115200; 186 speed = 115200;
184 break; 187 break;
185 case IOLayerBase::Baud_57600: 188 case IOLayerBase::Baud_57600:
186 speed = 57600; 189 speed = 57600;
187 break; 190 break;
188 case IOLayerBase::Baud_38400: 191 case IOLayerBase::Baud_38400:
189 speed = 38400; 192 speed = 38400;
190 break; 193 break;
191 case IOLayerBase::Baud_19200: 194 case IOLayerBase::Baud_19200:
192 speed = 19200; 195 speed = 19200;
193 break; 196 break;
194 case IOLayerBase::Baud_9600: 197 case IOLayerBase::Baud_9600:
195 speed = 9600; 198 speed = 9600;
196 break; 199 break;
197 } 200 }
198 201
199 switch( m_base->data() ) { 202 switch( m_base->data() ) {
200 case IOLayerBase::Data_Five: 203 case IOLayerBase::Data_Five:
201 data = 5; 204 data = 5;
202 break; 205 break;
203 case IOLayerBase::Data_Six: 206 case IOLayerBase::Data_Six:
204 data = 6; 207 data = 6;
205 break; 208 break;
206 case IOLayerBase::Data_Seven: 209 case IOLayerBase::Data_Seven:
207 data = 7; 210 data = 7;
208 break; 211 break;
209 case IOLayerBase::Data_Eight: 212 case IOLayerBase::Data_Eight:
210 data = 8; 213 data = 8;
211 break; 214 break;
212 } 215 }
213 216
214 switch( m_base->stop() ) { 217 switch( m_base->stop() ) {
215 case IOLayerBase::Stop_One: 218 case IOLayerBase::Stop_One:
216 stop = 1; 219 stop = 1;
217 break; 220 break;
218 case IOLayerBase::Stop_OnePointFive: 221 case IOLayerBase::Stop_OnePointFive:
219 stop = 15; 222 stop = 15;
220 break; 223 break;
221 case IOLayerBase::Stop_Two: 224 case IOLayerBase::Stop_Two:
222 stop = 2; 225 stop = 2;
223 break; 226 break;
224 } 227 }
225 228
226 prof.writeEntry( "Flow", flow ); 229 prof.writeEntry( "Flow", flow );
227 prof.writeEntry( "Parity", parity ); 230 prof.writeEntry( "Parity", parity );
228 prof.writeEntry( "Speed", speed ); 231 prof.writeEntry( "Speed", speed );
229 prof.writeEntry("DataBits", data); 232 prof.writeEntry("DataBits", data);
230 prof.writeEntry("StopBits", stop); 233 prof.writeEntry("StopBits", stop);
231 prof.writeEntry( "Number", m_telNumber->text() ); 234 prof.writeEntry( "Number", m_telNumber->text() );
232 235
233 236
234 atConf->writeConfig(prof); 237 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 @@
1TEMPLATE = app 1TEMPLATE = app
2TMAKE_CXXFLAGS += -DHAVE_OPENPTY
3CONFIG += qt warn_on 2CONFIG += qt warn_on
4#CONFIG = qt
5DESTDIR = $(OPIEDIR)/bin 3DESTDIR = $(OPIEDIR)/bin
6HEADERS = io_layer.h io_serial.h io_irda.h io_bt.h io_modem.h \ 4HEADERS = io_layer.h io_serial.h io_irda.h io_bt.h io_modem.h \
7 file_layer.h filetransfer.h \ 5 file_layer.h filetransfer.h \
8 metafactory.h \ 6 metafactory.h \
9 session.h \ 7 session.h \
10 mainwindow.h \ 8 mainwindow.h \
11 profile.h \ 9 profile.h \
12 profileconfig.h \ 10 profileconfig.h \
13 profilemanager.h \ 11 profilemanager.h \
14 tabwidget.h \ 12 tabwidget.h \
15 configdialog.h \ 13 configdialog.h \
16 keytrans.h \ 14 keytrans.h \
17 transferdialog.h \ 15 transferdialog.h \
18 profiledialogwidget.h \ 16 profiledialogwidget.h \
19 profileeditordialog.h \ 17 profileeditordialog.h \
20 default.h \ 18 default.h \
21 iolayerbase.h \ 19 iolayerbase.h \
22 serialconfigwidget.h irdaconfigwidget.h \ 20 serialconfigwidget.h irdaconfigwidget.h \
23 btconfigwidget.h modemconfigwidget.h \ 21 btconfigwidget.h modemconfigwidget.h \
24 atconfigdialog.h dialdialog.h \ 22 atconfigdialog.h dialdialog.h \
25 procctl.h \ 23 procctl.h \
26 function_keyboard.h \ 24 function_keyboard.h \
27 receive_layer.h filereceive.h \ 25 receive_layer.h filereceive.h \
28 script.h \ 26 script.h \
29 dialer.h \ 27 dialer.h \
30 terminalwidget.h \ 28 terminalwidget.h \
31 emulation_handler.h TECommon.h \ 29 emulation_handler.h TECommon.h \
32 TEHistory.h TEScreen.h TEWidget.h \ 30 TEHistory.h TEScreen.h TEWidget.h \
33 TEmuVt102.h TEmulation.h MyPty.h \ 31 TEmuVt102.h TEmulation.h MyPty.h \
34 consoleconfigwidget.h 32 consoleconfigwidget.h
35 33
36SOURCES = io_layer.cpp io_serial.cpp io_irda.cpp io_bt.cpp io_modem.cpp \ 34SOURCES = io_layer.cpp io_serial.cpp io_irda.cpp io_bt.cpp io_modem.cpp \
37 file_layer.cpp filetransfer.cpp \ 35 file_layer.cpp filetransfer.cpp \
38 main.cpp \ 36 main.cpp \
39 metafactory.cpp \ 37 metafactory.cpp \
40 session.cpp \ 38 session.cpp \
41 mainwindow.cpp \ 39 mainwindow.cpp \
42 profile.cpp \ 40 profile.cpp \
43 profileconfig.cpp \ 41 profileconfig.cpp \
44 profilemanager.cpp \ 42 profilemanager.cpp \
45 tabwidget.cpp \ 43 tabwidget.cpp \
46 configdialog.cpp \ 44 configdialog.cpp \
47 keytrans.cpp \ 45 keytrans.cpp \
48 transferdialog.cpp \ 46 transferdialog.cpp \
49 profiledialogwidget.cpp \ 47 profiledialogwidget.cpp \
50 profileeditordialog.cpp \ 48 profileeditordialog.cpp \
51 iolayerbase.cpp \ 49 iolayerbase.cpp \
52 serialconfigwidget.cpp irdaconfigwidget.cpp \ 50 serialconfigwidget.cpp irdaconfigwidget.cpp \
53 btconfigwidget.cpp modemconfigwidget.cpp \ 51 btconfigwidget.cpp modemconfigwidget.cpp \
54 atconfigdialog.cpp dialdialog.cpp \ 52 atconfigdialog.cpp dialdialog.cpp \
55 default.cpp procctl.cpp \ 53 default.cpp procctl.cpp \
56 function_keyboard.cpp \ 54 function_keyboard.cpp \
57 receive_layer.cpp filereceive.cpp \ 55 receive_layer.cpp filereceive.cpp \
58 script.cpp \ 56 script.cpp \
59 dialer.cpp \ 57 dialer.cpp \
60 terminalwidget.cpp \ 58 terminalwidget.cpp \
61 emulation_handler.cpp TEHistory.cpp \ 59 emulation_handler.cpp TEHistory.cpp \
62 TEScreen.cpp TEWidget.cpp \ 60 TEScreen.cpp TEWidget.cpp \
63 TEmuVt102.cpp TEmulation.cpp MyPty.cpp \ 61 TEmuVt102.cpp TEmulation.cpp MyPty.cpp \
64 consoleconfigwidget.cpp 62 consoleconfigwidget.cpp
65 63
66 64
67INTERFACES = configurebase.ui editbase.ui 65INTERFACES = configurebase.ui editbase.ui
68INCLUDEPATH += $(OPIEDIR)/include 66INCLUDEPATH += $(OPIEDIR)/include
69DEPENDPATH += $(OPIEDIR)/include 67DEPENDPATH += $(OPIEDIR)/include
70LIBS += -lqpe -lopiecore2 -lopieui2 -lutil 68LIBS += -lqpe -lopiecore2 -lopieui2 -lutil
71TARGET = opie-console 69TARGET = opie-console
72 70
73 71DEFINES += HAVE_OPENPTY
74 72
75 73
76include ( $(OPIEDIR)/include.pro ) 74include ( $(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 @@
1 1
2#include "sz_transfer.h" 2#include "sz_transfer.h"
3#include <qfile.h> 3#include <qfile.h>
4#include <stdio.h> 4#include <stdio.h>
5#include <sys/termios.h> 5#include <sys/termios.h>
6 6
7 7
8 8
9using namespace Opie::Core; 9using namespace Opie::Core;
10using namespace Opie::Core; 10using namespace Opie::Core;
11SzTransfer::SzTransfer(Type t, IOLayer *layer) : FileTransferLayer(layer), m_t(t) 11SzTransfer::SzTransfer(Type t, IOLayer *layer) : FileTransferLayer(layer), m_t(t)
12{ 12{
13} 13}
14 14
15SzTransfer::~SzTransfer() { 15SzTransfer::~SzTransfer() {
16} 16}
17 17
18void SzTransfer::sendFile(const QFile& file) { 18void SzTransfer::sendFile(const QFile& file) {
19 19
20 sendFile(file.name()); 20 sendFile(file.name());
21} 21}
22 22
23void SzTransfer::sendFile(const QString& file) { 23void SzTransfer::sendFile(const QString& file) {
24 24
25 //setcbreak(2); /* raw no echo */ 25 //setcbreak(2); /* raw no echo */
26 26
27 proc = new OProcess; 27 proc = new OProcess;
28 *proc << "sz"; 28 *proc << "sz";
29 *proc << "-v" << "-v" << "-b" << file; 29 *proc << "-v" << "-v" << "-b" << file;
30 connect(proc, SIGNAL(processExited(Opie::Core::OProcess*)), 30 connect(proc, SIGNAL(processExited(Opie::Core::OProcess*)),
31 this, SLOT(sent())); 31 this, SLOT(sent()));
32 connect(proc, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)), 32 connect(proc, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)),
33 this, SLOT(SzReceivedStdout(Opie::Core::OProcess*,char*,int))); 33 this, SLOT(SzReceivedStdout(Opie::Core::OProcess*,char*,int)));
34 connect(proc, SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)), 34 connect(proc, SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)),
35 this, SLOT(SzReceivedStderr(Opie::Core::OProcess*,char*,int))); 35 this, SLOT(SzReceivedStderr(Opie::Core::OProcess*,char*,int)));
36 connect(layer(), SIGNAL(received(const QByteArray&)), 36 connect(layer(), SIGNAL(received(const QByteArray&)),
37 this, SLOT(receivedStdin(const QByteArray&))); 37 this, SLOT(receivedStdin(const QByteArray&)));
38 proc->start(OProcess::NotifyOnExit, OProcess::All); 38 proc->start(OProcess::NotifyOnExit, OProcess::All);
39 39
40} 40}
41 41
42void SzTransfer::SzReceivedStdout(OProcess *, char *buffer, int buflen) { 42void SzTransfer::SzReceivedStdout(OProcess *, char *buffer, int buflen) {
43 43
44 qWarning("recieved from sz on stdout %d bytes", buflen); 44 owarn << "recieved from sz on stdout " << buflen << " bytes" << oendl;
45 45
46 QByteArray data(buflen); 46 QByteArray data(buflen);
47 data.fill(*buffer, buflen); 47 data.fill(*buffer, buflen);
48 for (uint i = 0; i < data.count(); i++ ) { 48 for (uint i = 0; i < data.count(); i++ ) {
49 printf("%c", buffer[i] ); 49 printf("%c", buffer[i] );
50 } 50 }
51 printf("\n"); 51 printf("\n");
52 52
53 // send out through the io layer 53 // send out through the io layer
54 layer()->send(data); 54 layer()->send(data);
55} 55}
56 56
57void SzTransfer::SzReceivedStderr(OProcess *, char *buffer, int length) { 57void SzTransfer::SzReceivedStderr(OProcess *, char *buffer, int length) {
58 58
59 // parse and show data in a progress dialog/widget 59 // parse and show data in a progress dialog/widget
60 printf("stderr:\n"); 60 printf("stderr:\n");
61 //for (int i = 0; i < length; i++) 61 //for (int i = 0; i < length; i++)
62 // printf("%c", buffer[i]); 62 // printf("%c", buffer[i]);
63 //printf("\n"); 63 //printf("\n");
64} 64}
65 65
66void SzTransfer::receivedStdin(const QByteArray &data) { 66void SzTransfer::receivedStdin(const QByteArray &data) {
67 67
68 qWarning("recieved from io_serial %d bytes", data.size()); 68 owarn << "recieved from io_serial " << data.size() << " bytes" << oendl;
69 69
70 // recieved data from the io layer goes to sz 70 // recieved data from the io layer goes to sz
71 proc->writeStdin(data.data(), data.size()); 71 proc->writeStdin(data.data(), data.size());
72 72
73} 73}
74 74
75void SzTransfer::sent() { 75void SzTransfer::sent() {
76 76
77 qWarning("sent file"); 77 owarn << "sent file" << oendl;
78 78
79 //setcbreak(0); /* default */ 79 //setcbreak(0); /* default */
80 80
81 81
82 delete proc; 82 delete proc;
83 disconnect(layer(), SIGNAL(received(const QByteArray&)), 83 disconnect(layer(), SIGNAL(received(const QByteArray&)),
84 this, SLOT(receivedStdin(const QByteArray&))); 84 this, SLOT(receivedStdin(const QByteArray&)));
85 85
86} 86}
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 @@
1
2#include "tabwidget.h" 1#include "tabwidget.h"
3 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
4using namespace Opie::Ui; 6using namespace Opie::Ui;
7
5TabWidget::TabWidget( QWidget* parent, const char* name ) 8TabWidget::TabWidget( QWidget* parent, const char* name )
6 : OTabWidget( parent, name ) { 9 : OTabWidget( parent, name ) {
7 connect(this, SIGNAL( currentChanged(QWidget*) ), 10 connect(this, SIGNAL( currentChanged(QWidget*) ),
8 this, SLOT( slotCurChanged(QWidget*) ) ); 11 this, SLOT( slotCurChanged(QWidget*) ) );
9} 12}
10 13
11TabWidget::~TabWidget() { 14TabWidget::~TabWidget() {
12} 15}
13 16
14void TabWidget::add( Session* ses ) { 17void TabWidget::add( Session* ses ) {
15 qWarning("session ses " + ses->name() ); 18 owarn << "session ses " + ses->name() << oendl;
16 if ( !ses->widgetStack() ) return; 19 if ( !ses->widgetStack() ) return;
17 //reparent( ses->widgetStack(), QPoint() ); 20 //reparent( ses->widgetStack(), QPoint() );
18 addTab( ses->widgetStack(), "console/konsole", ses->name() ); 21 addTab( ses->widgetStack(), "console/konsole", ses->name() );
19 //addTab( ses->widgetStack(), ses->name() ); 22 //addTab( ses->widgetStack(), ses->name() );
20 m_map.insert( ses->widgetStack(), ses ); 23 m_map.insert( ses->widgetStack(), ses );
21} 24}
22 25
23void TabWidget::remove( Session* ses ) { 26void TabWidget::remove( Session* ses ) {
24 m_map.remove( ses->widgetStack() ); 27 m_map.remove( ses->widgetStack() );
25 removePage( ses->widgetStack() ); 28 removePage( ses->widgetStack() );
26} 29}
27 30
28void TabWidget::slotCurChanged( QWidget* wid ) { 31void TabWidget::slotCurChanged( QWidget* wid ) {
29 QMap<QWidget*, Session*>::Iterator it; 32 QMap<QWidget*, Session*>::Iterator it;
30 it = m_map.find( wid ); 33 it = m_map.find( wid );
31 if ( it == m_map.end() ) { 34 if ( it == m_map.end() ) {
32 return; 35 return;
33 } 36 }
34 37
35 emit activated( it.data() ); 38 emit activated( it.data() );
36} 39}
37void TabWidget::setCurrent( Session* ses ) { 40void TabWidget::setCurrent( Session* ses ) {
38 if (!ses ) 41 if (!ses )
39 return; 42 return;
40 43
41 //showPage( ses->widgetStack() ); 44 //showPage( ses->widgetStack() );
42 setCurrentTab( ses->widgetStack() ); 45 setCurrentTab( ses->widgetStack() );
43} 46}
44 47
45 48
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 @@
1#include "terminalwidget.h"
2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
7/* QT */
1#include <qlabel.h> 8#include <qlabel.h>
2#include <qcheckbox.h> 9#include <qcheckbox.h>
3#include <qcombobox.h> 10#include <qcombobox.h>
4#include <qradiobutton.h> 11#include <qradiobutton.h>
5#include <qhgroupbox.h> 12#include <qhgroupbox.h>
6#include <qhbuttongroup.h> 13#include <qhbuttongroup.h>
7#include <qlayout.h> 14#include <qlayout.h>
8 15
9#include "terminalwidget.h"
10
11namespace { 16namespace {
12 enum TermIds { 17 enum TermIds {
13 id_term_vt100 = 0, 18 id_term_vt100 = 0,
14 id_term_vt102, 19 id_term_vt102,
15 id_term_linux, 20 id_term_linux,
16 id_term_xterm 21 id_term_xterm
17 }; 22 };
18 23
19 enum ColourIds { 24 enum ColourIds {
20 id_term_black, 25 id_term_black,
21 id_term_white, 26 id_term_white,
22 id_term_green, 27 id_term_green,
23 id_term_orange 28 id_term_orange
24 }; 29 };
25 30
26 enum FontIds { 31 enum FontIds {
27 id_size_small, 32 id_size_small,
28 id_size_medium, 33 id_size_medium,
29 id_size_large 34 id_size_large
30 }; 35 };
31}; 36};
32 37
33TerminalWidget::TerminalWidget( const QString& name, QWidget* parent, 38TerminalWidget::TerminalWidget( const QString& name, QWidget* parent,
34 const char* na ) 39 const char* na )
35 : ProfileDialogTerminalWidget( name, parent, na ) { 40 : ProfileDialogTerminalWidget( name, parent, na ) {
36 41
37 m_terminal = new QLabel(tr("Terminal Type"), this ); 42 m_terminal = new QLabel(tr("Terminal Type"), this );
38 m_terminalBox = new QComboBox(this); 43 m_terminalBox = new QComboBox(this);
39 m_colorLabel = new QLabel(tr("Color scheme"), this); 44 m_colorLabel = new QLabel(tr("Color scheme"), this);
40 m_colorCmb = new QComboBox(this ); 45 m_colorCmb = new QComboBox(this );
41 46
42 m_groupSize = new QHButtonGroup(tr("Font size"), this ); 47 m_groupSize = new QHButtonGroup(tr("Font size"), this );
43 m_sizeSmall = new QRadioButton(tr("small"), m_groupSize ); 48 m_sizeSmall = new QRadioButton(tr("small"), m_groupSize );
44 m_sizeMedium = new QRadioButton(tr("medium"), m_groupSize ); 49 m_sizeMedium = new QRadioButton(tr("medium"), m_groupSize );
45 m_sizeLarge = new QRadioButton(tr("large"), m_groupSize ); 50 m_sizeLarge = new QRadioButton(tr("large"), m_groupSize );
46 51
47 m_groupConv = new QHGroupBox( tr("Line-break conversions"), this ); 52 m_groupConv = new QHGroupBox( tr("Line-break conversions"), this );
48 m_convInbound = new QCheckBox( tr("Inbound"), m_groupConv ); 53 m_convInbound = new QCheckBox( tr("Inbound"), m_groupConv );
49 m_convOutbound = new QCheckBox( tr("Outbound"), m_groupConv ); 54 m_convOutbound = new QCheckBox( tr("Outbound"), m_groupConv );
50 55
51 m_groupOptions = new QHGroupBox( tr("Options"), this ); 56 m_groupOptions = new QHGroupBox( tr("Options"), this );
52 m_optionEcho = new QCheckBox( tr("Local echo"), m_groupOptions ); 57 m_optionEcho = new QCheckBox( tr("Local echo"), m_groupOptions );
53 m_optionWrap = new QCheckBox( tr("Line wrap"), m_groupOptions ); 58 m_optionWrap = new QCheckBox( tr("Line wrap"), m_groupOptions );
54 59
55 m_lroot = new QVBoxLayout( this ); 60 m_lroot = new QVBoxLayout( this );
56 m_typeBox = new QVBoxLayout( m_lroot ); 61 m_typeBox = new QVBoxLayout( m_lroot );
57 m_colorBox = new QVBoxLayout( m_lroot ); 62 m_colorBox = new QVBoxLayout( m_lroot );
58 63
59 // Layout 64 // Layout
60 m_typeBox->add( m_terminal ); 65 m_typeBox->add( m_terminal );
61 m_typeBox->add( m_terminalBox ); 66 m_typeBox->add( m_terminalBox );
62 m_lroot->add( m_groupSize ); 67 m_lroot->add( m_groupSize );
63 68
64 m_colorBox->add( m_colorLabel ); 69 m_colorBox->add( m_colorLabel );
65 m_colorBox->add( m_colorCmb ); 70 m_colorBox->add( m_colorCmb );
66 71
67 m_lroot->add( m_groupConv ); 72 m_lroot->add( m_groupConv );
68 m_lroot->add( m_groupOptions ); 73 m_lroot->add( m_groupOptions );
69 m_lroot->addStretch( 0 ); 74 m_lroot->addStretch( 0 );
70 75
71 // Fill in some options 76 // Fill in some options
72 qWarning("Options for terminal box"); 77 owarn << "Options for terminal box" << oendl;
73 m_terminalBox->insertItem( tr("VT 100"), 0 ); // /*, id_term_vt100*/ ); 78 m_terminalBox->insertItem( tr("VT 100"), 0 ); // /*, id_term_vt100*/ );
74 m_terminalBox->insertItem( tr("VT 102"), 1 ); // /* , id_term_vt102 */); 79 m_terminalBox->insertItem( tr("VT 102"), 1 ); // /* , id_term_vt102 */);
75 m_terminalBox->insertItem( tr("Linux Console"), 2 ); //, id_term_linux ); 80 m_terminalBox->insertItem( tr("Linux Console"), 2 ); //, id_term_linux );
76 m_terminalBox->insertItem( tr("X-Terminal"), 3 ); //, id_term_xterm ); 81 m_terminalBox->insertItem( tr("X-Terminal"), 3 ); //, id_term_xterm );
77 //m_terminalBox->insertItem( tr("ANSI"), id_term_ansi ); 82 //m_terminalBox->insertItem( tr("ANSI"), id_term_ansi );
78 83
79 m_colorCmb->insertItem( tr("black on white"), id_term_black ); 84 m_colorCmb->insertItem( tr("black on white"), id_term_black );
80 m_colorCmb->insertItem( tr("white on black"), id_term_white ); 85 m_colorCmb->insertItem( tr("white on black"), id_term_white );
81 m_colorCmb->insertItem( tr("green on black"), id_term_green ); 86 m_colorCmb->insertItem( tr("green on black"), id_term_green );
82 m_colorCmb->insertItem( tr("orange on black"), id_term_orange ); 87 m_colorCmb->insertItem( tr("orange on black"), id_term_orange );
83 88
84 // signals + slots 89 // signals + slots
85 /* 90 /*
86 connect(m_terminalBox, SIGNAL(activated(int) ), 91 connect(m_terminalBox, SIGNAL(activated(int) ),
87 this, SLOT(slotTermTerm(int) ) ); 92 this, SLOT(slotTermTerm(int) ) );
88 connect(m_colorBox, SIGNAL(activated(int) ), 93 connect(m_colorBox, SIGNAL(activated(int) ),
89 tis, SLOT(slotTermColor(int) ) ); 94 tis, SLOT(slotTermColor(int) ) );
90 connect(m_groupSize, SIGNAL(activated(int) ), 95 connect(m_groupSize, SIGNAL(activated(int) ),
91 this, SLOT(slotTermFont(int) ) ); 96 this, SLOT(slotTermFont(int) ) );
92 97
93 connect(m_optionEcho, SIGNAL(toggled(bool) ), 98 connect(m_optionEcho, SIGNAL(toggled(bool) ),
94 this, SLOT(slotTermEcho(bool) ) ); 99 this, SLOT(slotTermEcho(bool) ) );
95 connect(m_optionWrap, SIGNAL(toggled(bool) ), 100 connect(m_optionWrap, SIGNAL(toggled(bool) ),
96 this, SLOT(slotTermWrap(bool) ) ); 101 this, SLOT(slotTermWrap(bool) ) );
97 connect(m_convInbound, SIGNAL(toggled(bool) ), 102 connect(m_convInbound, SIGNAL(toggled(bool) ),
98 this, SLOT(slotTermInbound(bool) ) ); 103 this, SLOT(slotTermInbound(bool) ) );
99 connect(m_convOutbound, SIGNAL(toggled(bool) ), 104 connect(m_convOutbound, SIGNAL(toggled(bool) ),
100 this, SLOT(slotTermOutbound(bool) ) ); 105 this, SLOT(slotTermOutbound(bool) ) );
101*/ 106*/
102} 107}
103TerminalWidget::~TerminalWidget() { 108TerminalWidget::~TerminalWidget() {
104} 109}
105void TerminalWidget::load( const Profile& prof ) { 110void TerminalWidget::load( const Profile& prof ) {
106 int term = prof.readNumEntry("Terminal"); 111 int term = prof.readNumEntry("Terminal");
107 int color = prof.readNumEntry("Color"); 112 int color = prof.readNumEntry("Color");
108 int fontsize = prof.readNumEntry("Font"); 113 int fontsize = prof.readNumEntry("Font");
109 int opt_echo = prof.readNumEntry("Echo"); 114 int opt_echo = prof.readNumEntry("Echo");
110 int opt_wrap = prof.readNumEntry("Wrap"); 115 int opt_wrap = prof.readNumEntry("Wrap");
111 int opt_inbound = prof.readNumEntry("Inbound"); 116 int opt_inbound = prof.readNumEntry("Inbound");
112 int opt_outbound = prof.readNumEntry("Outbound"); 117 int opt_outbound = prof.readNumEntry("Outbound");
113 118
114 switch( term ) { 119 switch( term ) {
115 case Profile::VT100: 120 case Profile::VT100:
116 m_terminalBox->setCurrentItem(id_term_vt100 ); 121 m_terminalBox->setCurrentItem(id_term_vt100 );
117 break; 122 break;
118 case Profile::VT102: 123 case Profile::VT102:
119 m_terminalBox->setCurrentItem(id_term_vt102 ); 124 m_terminalBox->setCurrentItem(id_term_vt102 );
120 break; 125 break;
121 case Profile::Linux: 126 case Profile::Linux:
122 m_terminalBox->setCurrentItem(id_term_linux ); 127 m_terminalBox->setCurrentItem(id_term_linux );
123 break; 128 break;
124 case Profile::XTerm: 129 case Profile::XTerm:
125 m_terminalBox->setCurrentItem(id_term_xterm ); 130 m_terminalBox->setCurrentItem(id_term_xterm );
126 break; 131 break;
127 default: 132 default:
128 m_terminalBox->setCurrentItem(id_term_vt102 ); 133 m_terminalBox->setCurrentItem(id_term_vt102 );
129 break; 134 break;
130 }; 135 };
131 136
132 switch( color ) { 137 switch( color ) {
133 case Profile::Black: 138 case Profile::Black:
134 m_colorCmb->setCurrentItem(id_term_black ); 139 m_colorCmb->setCurrentItem(id_term_black );
135 break; 140 break;
136 case Profile::White: 141 case Profile::White:
137 m_colorCmb->setCurrentItem(id_term_white ); 142 m_colorCmb->setCurrentItem(id_term_white );
138 break; 143 break;
139 case Profile::Green: 144 case Profile::Green:
140 m_colorCmb->setCurrentItem(id_term_green ); 145 m_colorCmb->setCurrentItem(id_term_green );
141 break; 146 break;
142 case Profile::Orange: 147 case Profile::Orange:
143 m_colorCmb->setCurrentItem(id_term_orange ); 148 m_colorCmb->setCurrentItem(id_term_orange );
144 break; 149 break;
145 default: 150 default:
146 break; 151 break;
147 }; 152 };
148 153
149 switch( fontsize ) { 154 switch( fontsize ) {
150 case Profile::Micro: 155 case Profile::Micro:
151 m_sizeSmall->setChecked(true ); 156 m_sizeSmall->setChecked(true );
152 break; 157 break;
153 case Profile::Small: 158 case Profile::Small:
154 m_sizeMedium->setChecked(true ); 159 m_sizeMedium->setChecked(true );
155 break; 160 break;
156 case Profile::Medium: 161 case Profile::Medium:
157 m_sizeLarge->setChecked( true ); 162 m_sizeLarge->setChecked( true );
158 break; 163 break;
159 default: 164 default:
160 m_sizeMedium->setChecked(true ); 165 m_sizeMedium->setChecked(true );
161 break; 166 break;
162 }; 167 };
163 168
164 if (opt_echo) m_optionEcho->setChecked( true ); 169 if (opt_echo) m_optionEcho->setChecked( true );
165 if (opt_wrap) m_optionWrap->setChecked( true ); 170 if (opt_wrap) m_optionWrap->setChecked( true );
166 if (opt_inbound) m_convInbound->setChecked( true ); 171 if (opt_inbound) m_convInbound->setChecked( true );
167 if (opt_outbound) m_convOutbound->setChecked( true ); 172 if (opt_outbound) m_convOutbound->setChecked( true );
168 173
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 @@
1#include <stdlib.h> 1#include <stdlib.h>
2#include <stdio.h> 2#include <stdio.h>
3#include <fcntl.h> 3#include <fcntl.h>
4#include <sys/termios.h> 4#include <sys/termios.h>
5 5
6#include <qmultilineedit.h> 6#include <qmultilineedit.h>
7#include <qsocketnotifier.h> 7#include <qsocketnotifier.h>
8 8
9#include "../profile.h" 9#include "../profile.h"
10#include "../io_serial.h" 10#include "../io_serial.h"
11#include "../filetransfer.h" 11#include "../filetransfer.h"
12#include "../filereceive.h" 12#include "../filereceive.h"
13 13
14#include <opie2/oprocess.h> 14#include <opie2/oprocess.h>
15 15
16#include "senderui.h" 16#include "senderui.h"
17 17
18using namespace Opie::Core; 18using namespace Opie::Core;
19using namespace Opie::Core; 19using namespace Opie::Core;
20SenderUI::SenderUI() 20SenderUI::SenderUI()
21 : Sender() { 21 : Sender() {
22 22
23 /* we do that manually */ 23 /* we do that manually */
24 Profile prof; 24 Profile prof;
25 QString str = "/dev/bty0"; 25 QString str = "/dev/bty0";
26 prof.writeEntry("Device",str ); 26 prof.writeEntry("Device",str );
27 prof.writeEntry("Baud", 19200 ); 27 prof.writeEntry("Baud", 19200 );
28 28
29 qWarning("prof " + prof.readEntry("Device") + " " + str); 29 owarn << "prof " + prof.readEntry("Device") + " " + str << oendl;
30 ser = new IOSerial(prof); 30 ser = new IOSerial(prof);
31 connect(ser, SIGNAL(received(const QByteArray&) ), 31 connect(ser, SIGNAL(received(const QByteArray&) ),
32 this, SLOT(got(const QByteArray&) ) ); 32 this, SLOT(got(const QByteArray&) ) );
33 33
34 if ( ser->open() ) 34 if ( ser->open() )
35 qWarning("opened!!!"); 35 owarn << "opened!!!" << oendl;
36 else 36 else
37 qWarning("could not open"); 37 owarn << "could not open" << oendl;
38 38
39 39
40} 40}
41SenderUI::~SenderUI() { 41SenderUI::~SenderUI() {
42 42
43} 43}
44void SenderUI::slotSendFile() { 44void SenderUI::slotSendFile() {
45 45
46 sz = new FileTransfer(FileTransfer::SY, ser); 46 sz = new FileTransfer(FileTransfer::SY, ser);
47 sz->sendFile("/home/ich/bootopie-v06-13.jffs2"); 47 sz->sendFile("/home/ich/bootopie-v06-13.jffs2");
48 48
49 connect (sz, SIGNAL(sent()), 49 connect (sz, SIGNAL(sent()),
50 this, SLOT(fileTransComplete())); 50 this, SLOT(fileTransComplete()));
51} 51}
52 52
53void SenderUI::slotSend() { 53void SenderUI::slotSend() {
54 QCString str = MultiLineEdit1->text().utf8(); 54 QCString str = MultiLineEdit1->text().utf8();
55 qWarning("sending: %s", str.data() ); 55 owarn << "sending: " << str.data() << "" << oendl;
56 str = str.replace( QRegExp("\n"), "\r"); 56 str = str.replace( QRegExp("\n"), "\r");
57 ser->send( str ); 57 ser->send( str );
58} 58}
59void SenderUI::got(const QByteArray& ar) { 59void SenderUI::got(const QByteArray& ar) {
60 qWarning("got:"); 60 owarn << "got:" << oendl;
61 for ( uint i = 0; i < ar.count(); i++ ) { 61 for ( uint i = 0; i < ar.count(); i++ ) {
62 printf("%c", ar[i] ); 62 printf("%c", ar[i] );
63 } 63 }
64 printf("\n"); 64 printf("\n");
65} 65}
66 66
67void SenderUI::fileTransComplete() { 67void SenderUI::fileTransComplete() {
68 68
69 qWarning("file transfer complete"); 69 owarn << "file transfer complete" << oendl;
70} 70}
71void SenderUI::send() { 71void SenderUI::send() {
72 72
73} 73}
74void SenderUI::slotRev(){ 74void SenderUI::slotRev(){
75qWarning("Going to receive!"); 75owarn << "Going to receive!" << oendl;
76FileReceive *rev = new FileReceive( FileReceive::SZ, ser ); 76FileReceive *rev = new FileReceive( FileReceive::SZ, ser );
77rev->receive(); 77rev->receive();
78 78
79} 79}
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)
902 902
903/* ------------------------------------------------------------------------- */ 903/* ------------------------------------------------------------------------- */
904/* */ 904/* */
905/* Clipboard */ 905/* Clipboard */
906/* */ 906/* */
907/* ------------------------------------------------------------------------- */ 907/* ------------------------------------------------------------------------- */
908 908
909#undef KeyPress 909#undef KeyPress
910 910
911void Widget::emitSelection() 911void Widget::emitSelection()
912// Paste Clipboard by simulating keypress events 912// Paste Clipboard by simulating keypress events
913{ 913{
914#ifndef QT_NO_CLIPBOARD 914#ifndef QT_NO_CLIPBOARD
915 QString text = QApplication::clipboard()->text(); 915 QString text = QApplication::clipboard()->text();
916 if ( ! text.isNull() ) 916 if ( ! text.isNull() )
917 { 917 {
918 text.replace(QRegExp("\n"), "\r"); 918 text.replace(QRegExp("\n"), "\r");
919 QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text); 919 QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text);
920 emit keyPressedSignal(&e); // expose as a big fat keypress event 920 emit keyPressedSignal(&e); // expose as a big fat keypress event
921 emit clearSelectionSignal(); 921 emit clearSelectionSignal();
922 } 922 }
923#endif 923#endif
924} 924}
925 925
926void Widget::emitText(QString text) 926void Widget::emitText(QString text)
927{ 927{
928 QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text); 928 QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text);
929 emit keyPressedSignal(&e); // expose as a big fat keypress event 929 emit keyPressedSignal(&e); // expose as a big fat keypress event
930} 930}
931 931
932void Widget::pasteClipboard( ) 932void Widget::pasteClipboard( )
933{ 933{
934 emitSelection(); 934 emitSelection();
935} 935}
936 936
937void Widget::setSelection(const QString& t) 937void Widget::setSelection(const QString& t)
938{ 938{
939#ifndef QT_NO_CLIPBOARD 939#ifndef QT_NO_CLIPBOARD
940 // Disconnect signal while WE set the clipboard 940 // Disconnect signal while WE set the clipboard
941 QObject *cb = QApplication::clipboard(); 941 QObject *cb = QApplication::clipboard();
942 QObject::disconnect( cb, SIGNAL(dataChanged()), 942 QObject::disconnect( cb, SIGNAL(dataChanged()),
943 this, SLOT(onClearSelection()) ); 943 this, SLOT(onClearSelection()) );
944 944
945 QApplication::clipboard()->setText(t); 945 QApplication::clipboard()->setText(t);
946 946
947 QObject::connect( cb, SIGNAL(dataChanged()), 947 QObject::connect( cb, SIGNAL(dataChanged()),
948 this, SLOT(onClearSelection()) ); 948 this, SLOT(onClearSelection()) );
949#endif 949#endif
950} 950}
951 951
952void Widget::onClearSelection() 952void Widget::onClearSelection()
953{ 953{
954 emit clearSelectionSignal(); 954 emit clearSelectionSignal();
955} 955}
956 956
957/* ------------------------------------------------------------------------- */ 957/* ------------------------------------------------------------------------- */
958/* */ 958/* */
959/* Keyboard */ 959/* Keyboard */
960/* */ 960/* */
961/* ------------------------------------------------------------------------- */ 961/* ------------------------------------------------------------------------- */
962 962
963//FIXME: an `eventFilter' has been installed instead of a `keyPressEvent' 963//FIXME: an `eventFilter' has been installed instead of a `keyPressEvent'
964// due to a bug in `QT' or the ignorance of the author to prevent 964// due to a bug in `QT' or the ignorance of the author to prevent
965// repaint events being emitted to the screen whenever one leaves 965// repaint events being emitted to the screen whenever one leaves
966// or reenters the screen to/from another application. 966// or reenters the screen to/from another application.
967// 967//
968// Troll says one needs to change focusInEvent() and focusOutEvent(), 968// Troll says one needs to change focusInEvent() and focusOutEvent(),
969// which would also let you have an in-focus cursor and an out-focus 969// which would also let you have an in-focus cursor and an out-focus
970// cursor like xterm does. 970// cursor like xterm does.
971 971
972// for the auto-hide cursor feature, I added empty focusInEvent() and 972// for the auto-hide cursor feature, I added empty focusInEvent() and
973// focusOutEvent() so that update() isn't called. 973// focusOutEvent() so that update() isn't called.
974// For auto-hide, we need to get keypress-events, but we only get them when 974// For auto-hide, we need to get keypress-events, but we only get them when
975// we have focus. 975// we have focus.
976 976
977void Widget::doScroll(int lines) 977void Widget::doScroll(int lines)
978{ 978{
979 scrollbar->setValue(scrollbar->value()+lines); 979 scrollbar->setValue(scrollbar->value()+lines);
980} 980}
981 981
982bool Widget::eventFilter( QObject *obj, QEvent *e ) 982bool Widget::eventFilter( QObject *obj, QEvent *e )
983{ 983{
984 if ( (e->type() == QEvent::Accel || 984 if ( (e->type() == QEvent::Accel ||
985 e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) { 985 e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) {
986 static_cast<QKeyEvent *>( e )->ignore(); 986 static_cast<QKeyEvent *>( e )->ignore();
987 return true; 987 return true;
988 } 988 }
989 if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ ) 989 if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ )
990 return FALSE; // not us 990 return FALSE; // not us
991 if ( e->type() == QEvent::Wheel) { 991 if ( e->type() == QEvent::Wheel) {
992 QApplication::sendEvent(scrollbar, e); 992 QApplication::sendEvent(scrollbar, e);
993 } 993 }
994 994
995#ifdef FAKE_CTRL_AND_ALT 995#ifdef FAKE_CTRL_AND_ALT
996 static bool control = FALSE; 996 static bool control = FALSE;
997 static bool alt = FALSE; 997 static bool alt = FALSE;
998// qDebug(" Has a keyboard with no CTRL and ALT keys, but we fake it:"); 998// odebug << " Has a keyboard with no CTRL and ALT keys, but we fake it:" << oendl;
999 bool dele=FALSE; 999 bool dele=FALSE;
1000 if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { 1000 if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
1001 QKeyEvent* ke = (QKeyEvent*)e; 1001 QKeyEvent* ke = (QKeyEvent*)e;
1002 bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat(); 1002 bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat();
1003 switch (ke->key()) { 1003 switch (ke->key()) {
1004 case Key_F9: // let this be "Control" 1004 case Key_F9: // let this be "Control"
1005 control = keydown; 1005 control = keydown;
1006 e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state()); 1006 e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state());
1007 dele=TRUE; 1007 dele=TRUE;
1008 break; 1008 break;
1009 case Key_F13: // let this be "Alt" 1009 case Key_F13: // let this be "Alt"
1010 alt = keydown; 1010 alt = keydown;
1011 e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state()); 1011 e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state());
1012 dele=TRUE; 1012 dele=TRUE;
1013 break; 1013 break;
1014 default: 1014 default:
1015 if ( control ) { 1015 if ( control ) {
1016 int a = toupper(ke->ascii())-64; 1016 int a = toupper(ke->ascii())-64;
1017 if ( a >= 0 && a < ' ' ) { 1017 if ( a >= 0 && a < ' ' ) {
1018 e = new QKeyEvent(e->type(), ke->key(), 1018 e = new QKeyEvent(e->type(), ke->key(),
1019 a, ke->state()|ControlButton, QChar(a,0)); 1019 a, ke->state()|ControlButton, QChar(a,0));
1020 dele=TRUE; 1020 dele=TRUE;
1021 } 1021 }
1022 } 1022 }
1023 if ( alt ) { 1023 if ( alt ) {
1024 e = new QKeyEvent(e->type(), ke->key(), 1024 e = new QKeyEvent(e->type(), ke->key(),
1025 ke->ascii(), ke->state()|AltButton, ke->text()); 1025 ke->ascii(), ke->state()|AltButton, ke->text());
1026 dele=TRUE; 1026 dele=TRUE;
1027 } 1027 }
1028 } 1028 }
1029 } 1029 }
1030#endif 1030#endif
1031 1031
1032 if ( e->type() == QEvent::KeyPress ) { 1032 if ( e->type() == QEvent::KeyPress ) {
1033 QKeyEvent* ke = (QKeyEvent*)e; 1033 QKeyEvent* ke = (QKeyEvent*)e;
1034 actSel=0; // Key stroke implies a screen update, so Widget won't 1034 actSel=0; // Key stroke implies a screen update, so Widget won't
1035 // know where the current selection is. 1035 // know where the current selection is.
1036 1036
1037// qDebug("key pressed is 0x%x",ke->key()); 1037// odebug << "key pressed is 0x" << ke->key() << "" << oendl;
1038 1038
1039 if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker 1039 if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker
1040 1040
1041// qDebug("key pressed 2 is 0x%x",ke->key()); 1041// odebug << "key pressed 2 is 0x" << ke->key() << "" << oendl;
1042 emitText("\\"); // expose 1042 emitText("\\"); // expose
1043 } else 1043 } else
1044 emit keyPressedSignal(ke); // expose 1044 emit keyPressedSignal(ke); // expose
1045 ke->accept(); 1045 ke->accept();
1046#ifdef FAKE_CTRL_AND_ALT 1046#ifdef FAKE_CTRL_AND_ALT
1047 if ( dele ) delete e; 1047 if ( dele ) delete e;
1048#endif 1048#endif
1049 return true; // stop the event 1049 return true; // stop the event
1050 } 1050 }
1051 if ( e->type() == QEvent::Enter ) { 1051 if ( e->type() == QEvent::Enter ) {
1052 QObject::disconnect( (QObject*)cb, SIGNAL(dataChanged()), 1052 QObject::disconnect( (QObject*)cb, SIGNAL(dataChanged()),
1053 this, SLOT(onClearSelection()) ); 1053 this, SLOT(onClearSelection()) );
1054 } 1054 }
1055 if ( e->type() == QEvent::Leave ) { 1055 if ( e->type() == QEvent::Leave ) {
1056 QObject::connect( (QObject*)cb, SIGNAL(dataChanged()), 1056 QObject::connect( (QObject*)cb, SIGNAL(dataChanged()),
1057 this, SLOT(onClearSelection()) ); 1057 this, SLOT(onClearSelection()) );
1058 } 1058 }
1059 return QFrame::eventFilter( obj, e ); 1059 return QFrame::eventFilter( obj, e );
1060} 1060}
1061 1061
1062/* ------------------------------------------------------------------------- */ 1062/* ------------------------------------------------------------------------- */
1063/* */ 1063/* */
1064/* Frame */ 1064/* Frame */
1065/* */ 1065/* */
1066/* ------------------------------------------------------------------------- */ 1066/* ------------------------------------------------------------------------- */
1067 1067
1068void Widget::frameChanged() 1068void Widget::frameChanged()
1069{ 1069{
1070 propagateSize(); 1070 propagateSize();
1071 update(); 1071 update();
1072} 1072}
1073 1073
1074/* ------------------------------------------------------------------------- */ 1074/* ------------------------------------------------------------------------- */
1075/* */ 1075/* */
1076/* Sound */ 1076/* Sound */
1077/* */ 1077/* */
1078/* ------------------------------------------------------------------------- */ 1078/* ------------------------------------------------------------------------- */
1079 1079
1080void Widget::Bell() 1080void Widget::Bell()
1081{ 1081{
1082 QApplication::beep(); 1082 QApplication::beep();
1083} 1083}
1084 1084
1085/* ------------------------------------------------------------------------- */ 1085/* ------------------------------------------------------------------------- */
1086/* */ 1086/* */
1087/* Auxiluary */ 1087/* Auxiluary */
1088/* */ 1088/* */
1089/* ------------------------------------------------------------------------- */ 1089/* ------------------------------------------------------------------------- */
1090 1090
1091void Widget::clearImage() 1091void Widget::clearImage()
1092// initialize the image 1092// initialize the image
1093// for internal use only 1093// for internal use only
1094{ 1094{
1095 for (int y = 0; y < lines; y++) 1095 for (int y = 0; y < lines; y++)
1096 for (int x = 0; x < columns; x++) 1096 for (int x = 0; x < columns; x++)
1097 { 1097 {
1098 image[loc(x,y)].c = 0xff; //' '; 1098 image[loc(x,y)].c = 0xff; //' ';
1099 image[loc(x,y)].f = 0xff; //DEFAULT_FORE_COLOR; 1099 image[loc(x,y)].f = 0xff; //DEFAULT_FORE_COLOR;
1100 image[loc(x,y)].b = 0xff; //DEFAULT_BACK_COLOR; 1100 image[loc(x,y)].b = 0xff; //DEFAULT_BACK_COLOR;
1101 image[loc(x,y)].r = 0xff; //DEFAULT_RENDITION; 1101 image[loc(x,y)].r = 0xff; //DEFAULT_RENDITION;
1102 } 1102 }
1103} 1103}
1104 1104
1105// Create Image /////////////////////////////////////////////////////// 1105// Create Image ///////////////////////////////////////////////////////
1106 1106
1107void Widget::calcGeometry() 1107void Widget::calcGeometry()
1108{ 1108{
1109 //FIXME: set rimX == rimY == 0 when running in full screen mode. 1109 //FIXME: set rimX == rimY == 0 when running in full screen mode.
1110 1110
1111 scrollbar->resize(QApplication::style().scrollBarExtent().width(), 1111 scrollbar->resize(QApplication::style().scrollBarExtent().width(),
1112 contentsRect().height()); 1112 contentsRect().height());
1113 switch(scrollLoc) 1113 switch(scrollLoc)
1114 { 1114 {
1115 case SCRNONE : 1115 case SCRNONE :
1116 columns = ( contentsRect().width() - 2 * rimX ) / font_w; 1116 columns = ( contentsRect().width() - 2 * rimX ) / font_w;
1117 blX = (contentsRect().width() - (columns*font_w) ) / 2; 1117 blX = (contentsRect().width() - (columns*font_w) ) / 2;
1118 brX = blX; 1118 brX = blX;
1119 scrollbar->hide(); 1119 scrollbar->hide();
1120 break; 1120 break;
1121 case SCRLEFT : 1121 case SCRLEFT :
1122 columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w; 1122 columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w;
1123 brX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2; 1123 brX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2;
1124 blX = brX + scrollbar->width(); 1124 blX = brX + scrollbar->width();
1125 scrollbar->move(contentsRect().topLeft()); 1125 scrollbar->move(contentsRect().topLeft());
1126 scrollbar->show(); 1126 scrollbar->show();
1127 break; 1127 break;
1128 case SCRRIGHT: 1128 case SCRRIGHT:
1129 columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w; 1129 columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w;
1130 blX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2; 1130 blX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2;
1131 brX = blX; 1131 brX = blX;
1132 scrollbar->move(contentsRect().topRight() - QPoint(scrollbar->width()-1,0)); 1132 scrollbar->move(contentsRect().topRight() - QPoint(scrollbar->width()-1,0));
1133 scrollbar->show(); 1133 scrollbar->show();
1134 break; 1134 break;
1135 } 1135 }
1136 //FIXME: support 'rounding' styles 1136 //FIXME: support 'rounding' styles
1137 lines = ( contentsRect().height() - 2 * rimY ) / font_h; 1137 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 @@
1/* ------------------------------------------------------------------------- */ 1/* ------------------------------------------------------------------------- */
2/* */ 2/* */
3/* widget_layer.cpp Widget Layer */ 3/* widget_layer.cpp Widget Layer */
4/* */ 4/* */
5/* opie developers <opie@handhelds.org> */ 5/* opie developers <opie@handhelds.org> */
6/* */ 6/* */
7/* ------------------------------------------------------------------------- */ 7/* ------------------------------------------------------------------------- */
8 8
9 9
10 10
11#include "widget_layer.h" 11#include "widget_layer.h"
12 12
13 13
14#include <string.h> 14#include <string.h>
15//#include < 15//#include <
16 16
17 17
18 18
19 19
20WidgetLayer::WidgetLayer( const Profile &config, QWidget *parent, const char *name ) : QFrame( parent, name ) 20WidgetLayer::WidgetLayer( const Profile &config, QWidget *parent, const char *name ) : QFrame( parent, name )
21{ 21{
22 // get the clipboard 22 // get the clipboard
23 m_clipboard = QApplication::clipboard(); 23 m_clipboard = QApplication::clipboard();
24 24
25 // when data on clipboard changes, clear selection 25 // when data on clipboard changes, clear selection
26 QObject::connect( (QObject*) m_clipboard, SIGNAL( dataChanged() ), 26 QObject::connect( (QObject*) m_clipboard, SIGNAL( dataChanged() ),
27 (QObject*)this, SLOT( onClearSelection() ) ); 27 (QObject*)this, SLOT( onClearSelection() ) );
28 28
29 // initialize vars: 29 // initialize vars:
30 m_lines = 1; 30 m_lines = 1;
31 m_columns = 1; 31 m_columns = 1;
32 m_resizing = false; 32 m_resizing = false;
33 33
34 // just for demonstrating 34 // just for demonstrating
35 //m_image = QArray<Character>( m_lines * m_columns ); 35 //m_image = QArray<Character>( m_lines * m_columns );
36 m_image = QArray<Character>( 1 ); 36 m_image = QArray<Character>( 1 );
37 37
38 // we need to install an event filter, 38 // we need to install an event filter,
39 // to emit keypresses. 39 // to emit keypresses.
40 qApp->installEventFilter( this ); 40 qApp->installEventFilter( this );
41 41
42} 42}
43 43
44 44
45WidgetLayer::~WidgetLayer() 45WidgetLayer::~WidgetLayer()
46{ 46{
47 // clean up 47 // clean up
48 delete m_image; 48 delete m_image;
49} 49}
50 50
51 51
52QSize WidgetLayer::sizeHint() 52QSize WidgetLayer::sizeHint()
53{ 53{
54 return size(); 54 return size();
55} 55}
56 56
57 57
58/* --------------------------------- audio ---------------------------------- */ 58/* --------------------------------- audio ---------------------------------- */
59 59
60void WidgetLayer::bell() 60void WidgetLayer::bell()
61{ 61{
62 QApplication::beep(); 62 QApplication::beep();
63} 63}
64 64
65bool WidgetLayer::eventFilter( QObject *obj, QEvent *e ) 65bool WidgetLayer::eventFilter( QObject *obj, QEvent *e )
66{ 66{
67 if ( (e->type() == QEvent::Accel || 67 if ( (e->type() == QEvent::Accel ||
68 e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) { 68 e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) {
69 static_cast<QKeyEvent *>( e )->ignore(); 69 static_cast<QKeyEvent *>( e )->ignore();
70 return true; 70 return true;
71 } 71 }
72 if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ ) 72 if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ )
73 return false; // not us 73 return false; // not us
74 74
75#ifdef FAKE_CTRL_AND_ALT 75#ifdef FAKE_CTRL_AND_ALT
76 static bool control = false; 76 static bool control = false;
77 static bool alt = false; 77 static bool alt = false;
78// qDebug(" Has a keyboard with no CTRL and ALT keys, but we fake it:"); 78// odebug << " Has a keyboard with no CTRL and ALT keys, but we fake it:" << oendl;
79 bool dele = false; 79 bool dele = false;
80 if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { 80 if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
81 QKeyEvent* ke = (QKeyEvent*)e; 81 QKeyEvent* ke = (QKeyEvent*)e;
82 bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat(); 82 bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat();
83 switch (ke->key()) { 83 switch (ke->key()) {
84 case Key_F9: // let this be "Control" 84 case Key_F9: // let this be "Control"
85 control = keydown; 85 control = keydown;
86 e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state()); 86 e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state());
87 dele=TRUE; 87 dele=TRUE;
88 break; 88 break;
89 case Key_F13: // let this be "Alt" 89 case Key_F13: // let this be "Alt"
90 alt = keydown; 90 alt = keydown;
91 e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state()); 91 e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state());
92 dele=TRUE; 92 dele=TRUE;
93 break; 93 break;
94 default: 94 default:
95 if ( control ) { 95 if ( control ) {
96 int a = toupper(ke->ascii())-64; 96 int a = toupper(ke->ascii())-64;
97 if ( a >= 0 && a < ' ' ) { 97 if ( a >= 0 && a < ' ' ) {
98 e = new QKeyEvent(e->type(), ke->key(), 98 e = new QKeyEvent(e->type(), ke->key(),
99 a, ke->state()|ControlButton, 99 a, ke->state()|ControlButton,
100QChar(a,0)); 100QChar(a,0));
101 dele=TRUE; 101 dele=TRUE;
102 } 102 }
103 } 103 }
104 if ( alt ) { 104 if ( alt ) {
105 e = new QKeyEvent(e->type(), ke->key(), 105 e = new QKeyEvent(e->type(), ke->key(),
106 ke->ascii(), ke->state()|AltButton, ke->text()); 106 ke->ascii(), ke->state()|AltButton, ke->text());
107 dele=TRUE; 107 dele=TRUE;
108 } 108 }
109 } 109 }
110 } 110 }
111#endif 111#endif
112 112
113 if ( e->type() == QEvent::KeyPress ) { 113 if ( e->type() == QEvent::KeyPress ) {
114 QKeyEvent* ke = (QKeyEvent*)e; 114 QKeyEvent* ke = (QKeyEvent*)e;
115 //actSel=0; // Key stroke implies a screen update, so Widget won't 115 //actSel=0; // Key stroke implies a screen update, so Widget won't
116 // know where the current selection is. 116 // know where the current selection is.
117 117
118// qDebug("key pressed is 0x%x",ke->key()); 118// odebug << "key pressed is 0x" << ke->key() << "" << oendl;
119 119
120 if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker 120 if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker
121 insertText("\\"); // expose 121 insertText("\\"); // expose
122 } else 122 } else
123 emit keyPressed( ke ); // expose 123 emit keyPressed( ke ); // expose
124 ke->accept(); 124 ke->accept();
125#ifdef FAKE_CTRL_AND_ALT 125#ifdef FAKE_CTRL_AND_ALT
126 if ( dele ) delete e; 126 if ( dele ) delete e;
127#endif 127#endif
128 return true; // stop the event 128 return true; // stop the event
129 } 129 }
130 return QFrame::eventFilter( obj, e ); 130 return QFrame::eventFilter( obj, e );
131} 131}
132 132
133 133
134/* --------------------------------- screen --------------------------------- */ 134/* --------------------------------- screen --------------------------------- */
135 135
136 136
137void WidgetLayer::propagateSize() 137void WidgetLayer::propagateSize()
138{ 138{
139 QArray<Character> oldimage = m_image.copy(); 139 QArray<Character> oldimage = m_image.copy();
140 int oldlines = m_lines; 140 int oldlines = m_lines;
141 int oldcolumns = m_columns; 141 int oldcolumns = m_columns;
142 142
143 makeImage(); 143 makeImage();
144 144
145 // copy old image, to reduce flicker 145 // copy old image, to reduce flicker
146 if ( ! oldimage.isEmpty() ) 146 if ( ! oldimage.isEmpty() )
147 { 147 {
148 int lins = QMIN( oldlines, m_lines ); 148 int lins = QMIN( oldlines, m_lines );
149 int cols = QMIN( oldcolumns, m_columns ); 149 int cols = QMIN( oldcolumns, m_columns );
150 for ( int lin = 0; lin < lins; ++lin ) 150 for ( int lin = 0; lin < lins; ++lin )
151 { 151 {
152 memcpy( (void*) &m_image[m_columns*lin], 152 memcpy( (void*) &m_image[m_columns*lin],
153 (void*) &oldimage[oldcolumns*lin], 153 (void*) &oldimage[oldcolumns*lin],
154 cols*sizeof( Character ) ); 154 cols*sizeof( Character ) );
155 } 155 }
156 } 156 }
157 else 157 else
158 clearImage(); 158 clearImage();
159 159
160 delete oldimage; 160 delete oldimage;
161 161
162 m_resizing = true; 162 m_resizing = true;
163 emit imageSizeChanged( m_lines, m_columns ); 163 emit imageSizeChanged( m_lines, m_columns );
164 m_resizing = false; 164 m_resizing = false;
165} 165}
166 166
167void WidgetLayer::makeImage() 167void WidgetLayer::makeImage()
168{ 168{
169 calcGeometry(); 169 calcGeometry();
170 m_image = QArray<Character>( m_columns * m_lines ); 170 m_image = QArray<Character>( m_columns * m_lines );
171 clearImage(); 171 clearImage();
172} 172}
173 173
174void WidgetLayer::clearImage() 174void WidgetLayer::clearImage()
175{ 175{
176 //should this belong here?? 176 //should this belong here??
177 for ( int y = 0; y < m_lines; y++ ) 177 for ( int y = 0; y < m_lines; y++ )
178 for ( int x = 0; x < m_columns; x++ ) 178 for ( int x = 0; x < m_columns; x++ )
179 { 179 {
180 m_image[loc(x,y)].c = 0xff; 180 m_image[loc(x,y)].c = 0xff;
181 m_image[loc(x,y)].f = 0xff; 181 m_image[loc(x,y)].f = 0xff;
182 m_image[loc(x,y)].b = 0xff; 182 m_image[loc(x,y)].b = 0xff;
183 m_image[loc(x,y)].r = 0xff; 183 m_image[loc(x,y)].r = 0xff;
184 } 184 }
185} 185}
186 186
187/* --------------------------------- selection ------------------------------ */ 187/* --------------------------------- selection ------------------------------ */
188 188
189void WidgetLayer::pasteClipboard() 189void WidgetLayer::pasteClipboard()
190{ 190{
191 insertSelection(); 191 insertSelection();
192} 192}
193 193
194 194
195void WidgetLayer::insertSelection() 195void WidgetLayer::insertSelection()
196{ 196{
197 QString text = QApplication::clipboard()->text(); 197 QString text = QApplication::clipboard()->text();
198 if ( ! text.isNull() ) 198 if ( ! text.isNull() )
199 { 199 {
200 text.replace( QRegExp( "\n" ), "\r" ); 200 text.replace( QRegExp( "\n" ), "\r" );
201 insertText( text ); 201 insertText( text );
202 // selection should be unselected 202 // selection should be unselected
203 emit selectionCleared(); 203 emit selectionCleared();
204 } 204 }
205} 205}
206 206
207void WidgetLayer::insertText( QString text ) 207void WidgetLayer::insertText( QString text )
208{ 208{
209 // text is inserted as key event 209 // text is inserted as key event
210 QKeyEvent e( QEvent::KeyPress, 0, -1, 0, text); 210 QKeyEvent e( QEvent::KeyPress, 0, -1, 0, text);
211 emit keyPressed( &e ); 211 emit keyPressed( &e );
212} 212}
213 213
214void WidgetLayer::onClearSelection() 214void 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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** Licensees holding valid Qtopia Developer license may use this 6** Licensees holding valid Qtopia Developer license may use this
7** file in accordance with the Qtopia Developer License Agreement 7** file in accordance with the Qtopia Developer License Agreement
8** provided with the Software. 8** provided with the Software.
9** 9**
10** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING 10** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
11** THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR 11** THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
12** PURPOSE. 12** PURPOSE.
13** 13**
14** email sales@trolltech.com for information about Qtopia License 14** email sales@trolltech.com for information about Qtopia License
15** Agreements. 15** Agreements.
16** 16**
17** Contact info@trolltech.com if any conditions of this licensing are 17** Contact info@trolltech.com if any conditions of this licensing are
18** not clear to you. 18** not clear to you.
19** 19**
20**********************************************************************/ 20**********************************************************************/
21 21
22#include "mainwindow.h" 22#include "mainwindow.h"
23
24/* OPIE */
25#include <opie2/odebug.h>
23#include <qpe/fileselector.h> 26#include <qpe/fileselector.h>
24#include <qpe/applnk.h> 27#include <qpe/applnk.h>
25#include <qpe/resource.h> 28#include <qpe/resource.h>
26#include <qpe/fontdatabase.h> 29#include <qpe/fontdatabase.h>
30using namespace Opie::Core;
27 31
28//#include "qspellchecker.h" 32/* QT */
29#include "qtextedit.h" 33#include "qtextedit.h"
30#include <qaction.h> 34#include <qaction.h>
31#include <qtoolbar.h> 35#include <qtoolbar.h>
32#include <qtoolbutton.h> 36#include <qtoolbutton.h>
33#include <qtabwidget.h> 37#include <qtabwidget.h>
34#include <qapplication.h> 38#include <qapplication.h>
35#include <qfontdatabase.h> 39#include <qfontdatabase.h>
36#include <qcombobox.h> 40#include <qcombobox.h>
37#include <qlineedit.h> 41#include <qlineedit.h>
38#include <qfileinfo.h> 42#include <qfileinfo.h>
39#include <qfile.h> 43#include <qfile.h>
40#include <qfiledialog.h> 44#include <qfiledialog.h>
41#include <qprinter.h> 45#include <qprinter.h>
42#include <qpaintdevicemetrics.h> 46#include <qpaintdevicemetrics.h>
43#include <qmenubar.h> 47#include <qmenubar.h>
44#include <qpopupmenu.h> 48#include <qpopupmenu.h>
45#include <qcolordialog.h> 49#include <qcolordialog.h>
46#include <qpainter.h> 50#include <qpainter.h>
47#include <qstyle.h> 51#include <qstyle.h>
48 52
49class ButtonMenu : public QToolButton 53class ButtonMenu : public QToolButton
50{ 54{
51 Q_OBJECT 55 Q_OBJECT
52public: 56public:
53 ButtonMenu( QWidget *parent, const char *name=0 ) 57 ButtonMenu( QWidget *parent, const char *name=0 )
54 : QToolButton( parent, name ), current(0) 58 : QToolButton( parent, name ), current(0)
55 { 59 {
56 setPopup( new QPopupMenu( this ) ); 60 setPopup( new QPopupMenu( this ) );
57 setPopupDelay( 1 ); 61 setPopupDelay( 1 );
58 connect( popup(), SIGNAL(activated(int)), this, SLOT(selected(int)) ); 62 connect( popup(), SIGNAL(activated(int)), this, SLOT(selected(int)) );
59 } 63 }
60 64
61 int insertItem(const QIconSet &icon, const QString &text, int id ) { 65 int insertItem(const QIconSet &icon, const QString &text, int id ) {
62 if ( !popup()->count() ) { 66 if ( !popup()->count() ) {
63 setIconSet( icon ); 67 setIconSet( icon );
64 current = id; 68 current = id;
65 } 69 }
66 return popup()->insertItem( icon, text, id ); 70 return popup()->insertItem( icon, text, id );
67 } 71 }
68 72
69 void setCurrentItem( int id ) { 73 void setCurrentItem( int id ) {
70 if ( id != current ) { 74 if ( id != current ) {
71 current = id; 75 current = id;
72 setIconSet( *popup()->iconSet( id ) ); 76 setIconSet( *popup()->iconSet( id ) );
73 } 77 }
74 } 78 }
75 79
76 virtual QSize sizeHint() const { 80 virtual QSize sizeHint() const {
77 return QToolButton::sizeHint() + QSize( 4, 0 ); 81 return QToolButton::sizeHint() + QSize( 4, 0 );
78 } 82 }
79 83
80signals: 84signals:
81 void activated( int id ); 85 void activated( int id );
82 86
83protected slots: 87protected slots:
84 void selected( int id ) { 88 void selected( int id ) {
85 current = id; 89 current = id;
86 setIconSet( *popup()->iconSet( id ) ); 90 setIconSet( *popup()->iconSet( id ) );
87 emit activated( id ); 91 emit activated( id );
88 } 92 }
89 93
90protected: 94protected:
91 virtual void drawButtonLabel( QPainter *p ) { 95 virtual void drawButtonLabel( QPainter *p ) {
92 p->translate( -4, 0 ); 96 p->translate( -4, 0 );
93 QToolButton::drawButtonLabel( p ); 97 QToolButton::drawButtonLabel( p );
94 p->translate( 4, 0 ); 98 p->translate( 4, 0 );
95 } 99 }
96 100
97private: 101private:
98 int current; 102 int current;
99}; 103};
100 104
101//=========================================================================== 105//===========================================================================
102 106
103MainWindow::MainWindow( QWidget *parent, const char *name, WFlags fl ) 107MainWindow::MainWindow( QWidget *parent, const char *name, WFlags fl )
104 : QMainWindow( parent, name, fl ), 108 : QMainWindow( parent, name, fl ),
105 doc( 0 ) 109 doc( 0 )
106{ 110{
107 setRightJustification(TRUE); 111 setRightJustification(TRUE);
108 112
109 editorStack = new QWidgetStack( this ); 113 editorStack = new QWidgetStack( this );
110 114
111 fileSelector = new FileSelector( "text/html", 115 fileSelector = new FileSelector( "text/html",
112 editorStack, "fileselector" ); 116 editorStack, "fileselector" );
113 117
114 118
115 fileSelector->setCloseVisible( FALSE ); 119 fileSelector->setCloseVisible( FALSE );
116 editorStack->addWidget( fileSelector, 0 ); 120 editorStack->addWidget( fileSelector, 0 );
117 121
118 editor = new Qt3::QTextEdit( editorStack ); 122 editor = new Qt3::QTextEdit( editorStack );
119 editor->setTextFormat( Qt::RichText ); 123 editor->setTextFormat( Qt::RichText );
120 editorStack->addWidget( editor, 1 ); 124 editorStack->addWidget( editor, 1 );
121 125
122 setupActions(); 126 setupActions();
123 127
124 QObject::connect( fileSelector, SIGNAL(closeMe()), 128 QObject::connect( fileSelector, SIGNAL(closeMe()),
@@ -351,224 +355,224 @@ void MainWindow::textFamily( const QString &f )
351 currentEditor()->setFamily( f ); 355 currentEditor()->setFamily( f );
352 currentEditor()->viewport()->setFocus(); 356 currentEditor()->viewport()->setFocus();
353} 357}
354 358
355void MainWindow::textSize( const QString &p ) 359void MainWindow::textSize( const QString &p )
356{ 360{
357 if ( !currentEditor() ) 361 if ( !currentEditor() )
358 return; 362 return;
359 currentEditor()->setPointSize( p.toInt() ); 363 currentEditor()->setPointSize( p.toInt() );
360 currentEditor()->viewport()->setFocus(); 364 currentEditor()->viewport()->setFocus();
361} 365}
362 366
363void MainWindow::textStyle( int i ) 367void MainWindow::textStyle( int i )
364{ 368{
365 if ( !currentEditor() ) 369 if ( !currentEditor() )
366 return; 370 return;
367 if ( i == 0 ) 371 if ( i == 0 )
368 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayBlock, 372 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayBlock,
369 Qt3::QStyleSheetItem::ListDisc ); 373 Qt3::QStyleSheetItem::ListDisc );
370 else if ( i == 1 ) 374 else if ( i == 1 )
371 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 375 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
372 Qt3::QStyleSheetItem::ListDisc ); 376 Qt3::QStyleSheetItem::ListDisc );
373 else if ( i == 2 ) 377 else if ( i == 2 )
374 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 378 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
375 Qt3::QStyleSheetItem::ListCircle ); 379 Qt3::QStyleSheetItem::ListCircle );
376 else if ( i == 3 ) 380 else if ( i == 3 )
377 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 381 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
378 Qt3::QStyleSheetItem::ListSquare ); 382 Qt3::QStyleSheetItem::ListSquare );
379 else if ( i == 4 ) 383 else if ( i == 4 )
380 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 384 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
381 Qt3::QStyleSheetItem::ListDecimal ); 385 Qt3::QStyleSheetItem::ListDecimal );
382 else if ( i == 5 ) 386 else if ( i == 5 )
383 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 387 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
384 Qt3::QStyleSheetItem::ListLowerAlpha ); 388 Qt3::QStyleSheetItem::ListLowerAlpha );
385 else if ( i == 6 ) 389 else if ( i == 6 )
386 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 390 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
387 Qt3::QStyleSheetItem::ListUpperAlpha ); 391 Qt3::QStyleSheetItem::ListUpperAlpha );
388 currentEditor()->viewport()->setFocus(); 392 currentEditor()->viewport()->setFocus();
389} 393}
390 394
391void MainWindow::textAlign( int a ) 395void MainWindow::textAlign( int a )
392{ 396{
393 if ( !currentEditor() ) 397 if ( !currentEditor() )
394 return; 398 return;
395 editor->setAlignment( a ); 399 editor->setAlignment( a );
396} 400}
397 401
398void MainWindow::fontChanged( const QFont &f ) 402void MainWindow::fontChanged( const QFont &f )
399{ 403{
400 comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( f.family() ) ) ); 404 comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( f.family() ) ) );
401 updateFontSizeCombo( f ); 405 updateFontSizeCombo( f );
402 comboSize->lineEdit()->setText( QString::number( f.pointSize() ) ); 406 comboSize->lineEdit()->setText( QString::number( f.pointSize() ) );
403 actionTextBold->setOn( f.bold() ); 407 actionTextBold->setOn( f.bold() );
404 actionTextItalic->setOn( f.italic() ); 408 actionTextItalic->setOn( f.italic() );
405 actionTextUnderline->setOn( f.underline() ); 409 actionTextUnderline->setOn( f.underline() );
406} 410}
407 411
408void MainWindow::colorChanged( const QColor & ) 412void MainWindow::colorChanged( const QColor & )
409{ 413{
410} 414}
411 415
412void MainWindow::alignmentChanged( int a ) 416void MainWindow::alignmentChanged( int a )
413{ 417{
414 if ( ( a == Qt3::AlignAuto ) || ( a & AlignLeft )) { 418 if ( ( a == Qt3::AlignAuto ) || ( a & AlignLeft )) {
415 alignMenu->setCurrentItem(AlignLeft); 419 alignMenu->setCurrentItem(AlignLeft);
416 } else if ( ( a & AlignCenter ) ) { 420 } else if ( ( a & AlignCenter ) ) {
417 alignMenu->setCurrentItem(AlignCenter); 421 alignMenu->setCurrentItem(AlignCenter);
418 } else if ( ( a & AlignRight ) ) { 422 } else if ( ( a & AlignRight ) ) {
419 alignMenu->setCurrentItem(AlignRight); 423 alignMenu->setCurrentItem(AlignRight);
420 } else if ( ( a & Qt3::AlignJustify ) ) { 424 } else if ( ( a & Qt3::AlignJustify ) ) {
421 alignMenu->setCurrentItem(Qt3::AlignJustify); 425 alignMenu->setCurrentItem(Qt3::AlignJustify);
422 } 426 }
423} 427}
424 428
425void MainWindow::editorChanged( QWidget * ) 429void MainWindow::editorChanged( QWidget * )
426{ 430{
427 if ( !currentEditor() ) 431 if ( !currentEditor() )
428 return; 432 return;
429 fontChanged( currentEditor()->font() ); 433 fontChanged( currentEditor()->font() );
430 colorChanged( currentEditor()->color() ); 434 colorChanged( currentEditor()->color() );
431 alignmentChanged( currentEditor()->alignment() ); 435 alignmentChanged( currentEditor()->alignment() );
432} 436}
433 437
434void MainWindow::fileOpen() 438void MainWindow::fileOpen()
435{ 439{
436 save(); 440 save();
437 editorStack->raiseWidget( fileSelector ); 441 editorStack->raiseWidget( fileSelector );
438 fileSelector->reread(); 442 fileSelector->reread();
439 hideEditTools(); 443 hideEditTools();
440 fileSelector->setNewVisible( TRUE ); 444 fileSelector->setNewVisible( TRUE );
441 clear(); 445 clear();
442 updateCaption(); 446 updateCaption();
443} 447}
444 448
445void MainWindow::fileRevert() 449void MainWindow::fileRevert()
446{ 450{
447 qDebug( "QMainWindow::fileRevert needs to be done" ); 451 odebug << "QMainWindow::fileRevert needs to be done" << oendl;
448} 452}
449 453
450void MainWindow::fileNew() 454void MainWindow::fileNew()
451{ 455{
452 editor->setTextFormat( Qt::RichText ); 456 editor->setTextFormat( Qt::RichText );
453 save(); 457 save();
454 newFile(DocLnk()); 458 newFile(DocLnk());
455} 459}
456 460
457void MainWindow::insertTable() 461void MainWindow::insertTable()
458{ 462{
459 qDebug( "MainWindow::insertTable() needs to be done" ); 463 odebug << "MainWindow::insertTable() needs to be done" << oendl;
460} 464}
461 465
462void MainWindow::newFile( const DocLnk &dl ) 466void MainWindow::newFile( const DocLnk &dl )
463{ 467{
464 DocLnk nf = dl; 468 DocLnk nf = dl;
465 nf.setType( "text/html" ); 469 nf.setType( "text/html" );
466 clear(); 470 clear();
467 editorStack->raiseWidget( editor ); 471 editorStack->raiseWidget( editor );
468 editor->viewport()->setFocus(); 472 editor->viewport()->setFocus();
469 doc = new DocLnk( nf ); 473 doc = new DocLnk( nf );
470 updateCaption(); 474 updateCaption();
471} 475}
472 476
473void MainWindow::openFile( const DocLnk &dl ) 477void MainWindow::openFile( const DocLnk &dl )
474{ 478{
475 FileManager fm; 479 FileManager fm;
476 QString txt; 480 QString txt;
477 if ( !fm.loadFile( dl, txt ) ) 481 if ( !fm.loadFile( dl, txt ) )
478 qDebug( "couldn't open file" ); 482 odebug << "couldn't open file" << oendl;
479 clear(); 483 clear();
480 editorStack->raiseWidget( editor ); 484 editorStack->raiseWidget( editor );
481 editor->viewport()->setFocus(); 485 editor->viewport()->setFocus();
482 doc = new DocLnk( dl ); 486 doc = new DocLnk( dl );
483 editor->setText( txt ); 487 editor->setText( txt );
484 editor->setModified( FALSE ); 488 editor->setModified( FALSE );
485 updateCaption(); 489 updateCaption();
486} 490}
487 491
488void MainWindow::showEditTools( void ) 492void MainWindow::showEditTools( void )
489{ 493{
490 tbMenu->show(); 494 tbMenu->show();
491 tbEdit->show(); 495 tbEdit->show();
492 tbFont->show(); 496 tbFont->show();
493 tbStyle->show(); 497 tbStyle->show();
494} 498}
495 499
496void MainWindow::hideEditTools( void ) 500void MainWindow::hideEditTools( void )
497{ 501{
498 // let's reset the buttons... 502 // let's reset the buttons...
499 actionTextBold->setOn( FALSE ); 503 actionTextBold->setOn( FALSE );
500 actionTextItalic->setOn( FALSE ); 504 actionTextItalic->setOn( FALSE );
501 actionTextUnderline->setOn( FALSE ); 505 actionTextUnderline->setOn( FALSE );
502 //comboFont->setCurrentText( QApplication::font().family() ); 506 //comboFont->setCurrentText( QApplication::font().family() );
503 comboSize->lineEdit()->setText( QString::number(QApplication::font().pointSize() ) ); 507 comboSize->lineEdit()->setText( QString::number(QApplication::font().pointSize() ) );
504 tbMenu->hide(); 508 tbMenu->hide();
505 tbEdit->hide(); 509 tbEdit->hide();
506 tbFont->hide(); 510 tbFont->hide();
507 tbStyle->hide(); 511 tbStyle->hide();
508} 512}
509 513
510 514
511void MainWindow::save() 515void MainWindow::save()
512{ 516{
513 if ( !doc ) 517 if ( !doc )
514 return; 518 return;
515 if ( !editor->isModified() ) 519 if ( !editor->isModified() )
516 return; 520 return;
517 521
518 QString rt = editor->text(); 522 QString rt = editor->text();
519 523
520 // quick hack to get around formatting... 524 // quick hack to get around formatting...
521 editor->setTextFormat( Qt::PlainText ); 525 editor->setTextFormat( Qt::PlainText );
522 QString pt = editor->text(); 526 QString pt = editor->text();
523 editor->setTextFormat( Qt::RichText ); 527 editor->setTextFormat( Qt::RichText );
524 528
525 if ( doc->name().isEmpty() ) { 529 if ( doc->name().isEmpty() ) {
526 unsigned ispace = pt.find( ' ' ); 530 unsigned ispace = pt.find( ' ' );
527 unsigned ienter = pt.find( '\n' ); 531 unsigned ienter = pt.find( '\n' );
528 int i = (ispace < ienter) ? ispace : ienter; 532 int i = (ispace < ienter) ? ispace : ienter;
529 QString docname; 533 QString docname;
530 if ( i == -1 ) { 534 if ( i == -1 ) {
531 if ( pt.isEmpty() ) 535 if ( pt.isEmpty() )
532 docname = "Empty Text"; 536 docname = "Empty Text";
533 else 537 else
534 docname = pt; 538 docname = pt;
535 } else { 539 } else {
536 docname = pt.left( i ); 540 docname = pt.left( i );
537 } 541 }
538 doc->setName(docname); 542 doc->setName(docname);
539 } 543 }
540 FileManager fm; 544 FileManager fm;
541 fm.saveFile( *doc, rt ); 545 fm.saveFile( *doc, rt );
542} 546}
543 547
544void MainWindow::clear() 548void MainWindow::clear()
545{ 549{
546 delete doc; 550 delete doc;
547 doc = 0; 551 doc = 0;
548 editor->clear(); 552 editor->clear();
549} 553}
550 554
551void MainWindow::updateCaption() 555void MainWindow::updateCaption()
552{ 556{
553 if ( !doc ) 557 if ( !doc )
554 setCaption( tr("Rich Text Editor") ); 558 setCaption( tr("Rich Text Editor") );
555 else { 559 else {
556 QString s = doc->name(); 560 QString s = doc->name();
557 if ( s.isEmpty() ) 561 if ( s.isEmpty() )
558 s = tr( "Unnamed" ); 562 s = tr( "Unnamed" );
559 setCaption( s + " - " + tr("Rich Text Editor") ); 563 setCaption( s + " - " + tr("Rich Text Editor") );
560 } 564 }
561} 565}
562 566
563void MainWindow::closeEvent( QCloseEvent *e ) 567void MainWindow::closeEvent( QCloseEvent *e )
564{ 568{
565 if ( editorStack->visibleWidget() == editor ) { 569 if ( editorStack->visibleWidget() == editor ) {
566 // call fileOpen instead, don't close it 570 // call fileOpen instead, don't close it
567 fileOpen(); 571 fileOpen();
568 e->ignore(); 572 e->ignore();
569 } else { 573 } else {
570 e->accept(); 574 e->accept();
571 } 575 }
572} 576}
573 577
574#include "mainwindow.moc" 578#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 @@
1 1
2CONFIG += qt warn on quick-app 2CONFIG += qt warn on quick-app
3
4 3
5HEADERS = qcleanuphandler.h \ 4HEADERS = qcleanuphandler.h \
6 qcomplextext_p.h \ 5 qcomplextext_p.h \
7 qrichtext_p.h \ 6 qrichtext_p.h \
8 qstylesheet.h \ 7 qstylesheet.h \
9 qtextedit.h \ 8 qtextedit.h \
10 mainwindow.h 9 mainwindow.h
11 10
12SOURCES = qcomplextext.cpp \ 11SOURCES = qcomplextext.cpp \
13 qstylesheet.cpp \ 12 qstylesheet.cpp \
14 qrichtext_p.cpp \ 13 qrichtext_p.cpp \
15 qrichtext.cpp \ 14 qrichtext.cpp \
16 qtextedit.cpp \ 15 qtextedit.cpp \
17 main.cpp \ 16 main.cpp \
18 mainwindow.cpp 17 mainwindow.cpp
19 18
20INCLUDEPATH += $(OPIEDIR)/include 19INCLUDEPATH += $(OPIEDIR)/include
21DEPENDPATH += $(OPIEDIR)/include 20DEPENDPATH += $(OPIEDIR)/include
22LIBS += -lqpe -lopiecore2 21LIBS += -lqpe -lopiecore2
23 22
24TARGET = opie-write 23TARGET = opie-write
25 24
26 25
27include ( $(OPIEDIR)/include.pro ) 26include ( $(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 @@
13** as defined by Trolltech AS of Norway and appearing in the file 13** as defined by Trolltech AS of Norway and appearing in the file
14** LICENSE.QPL included in the packaging of this file. 14** LICENSE.QPL included in the packaging of this file.
15** 15**
16** This file may be distributed and/or modified under the terms of the 16** This file may be distributed and/or modified under the terms of the
17** GNU General Public License version 2 as published by the Free Software 17** GNU General Public License version 2 as published by the Free Software
18** Foundation and appearing in the file LICENSE.GPL included in the 18** Foundation and appearing in the file LICENSE.GPL included in the
19** packaging of this file. 19** packaging of this file.
20** 20**
21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition 21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
22** licenses may use this file in accordance with the Qt Commercial License 22** licenses may use this file in accordance with the Qt Commercial License
23** Agreement provided with the Software. 23** Agreement provided with the Software.
24** 24**
25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27** 27**
28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for 28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
29** information about Qt Commercial License Agreements. 29** information about Qt Commercial License Agreements.
30** See http://www.trolltech.com/qpl/ for QPL licensing information. 30** See http://www.trolltech.com/qpl/ for QPL licensing information.
31** See http://www.trolltech.com/gpl/ for GPL licensing information. 31** See http://www.trolltech.com/gpl/ for GPL licensing information.
32** 32**
33** Contact info@trolltech.com if any conditions of this licensing are 33** Contact info@trolltech.com if any conditions of this licensing are
34** not clear to you. 34** not clear to you.
35** 35**
36**********************************************************************/ 36**********************************************************************/
37 37
38 38
39#include "qrichtext_p.h" 39#include "qrichtext_p.h"
40 40
41#include <stdlib.h> 41#include <stdlib.h>
42 42
43using namespace Qt3; 43using namespace Qt3;
44 44
45// ----------------------------------------------------- 45// -----------------------------------------------------
46 46
47/* a small helper class used internally to resolve Bidi embedding levels. 47/* a small helper class used internally to resolve Bidi embedding levels.
48 Each line of text caches the embedding level at the start of the line for faster 48 Each line of text caches the embedding level at the start of the line for faster
49 relayouting 49 relayouting
50*/ 50*/
51QBidiContext::QBidiContext( uchar l, QChar::Direction e, QBidiContext *p, bool o ) 51QBidiContext::QBidiContext( uchar l, QChar::Direction e, QBidiContext *p, bool o )
52 : level(l) , override(o), dir(e) 52 : level(l) , override(o), dir(e)
53{ 53{
54 if ( p ) 54 if ( p )
55 p->ref(); 55 p->ref();
56 parent = p; 56 parent = p;
57 count = 0; 57 count = 0;
58} 58}
59 59
60QBidiContext::~QBidiContext() 60QBidiContext::~QBidiContext()
61{ 61{
62 if( parent && parent->deref() ) 62 if( parent && parent->deref() )
63 delete parent; 63 delete parent;
64} 64}
65 65
66/* 66/*
67 Arabic shaping obeys a number of rules according to the joining classes (see Unicode book, section on 67 Arabic shaping obeys a number of rules according to the joining classes (see Unicode book, section on
68 arabic). 68 arabic).
69 69
70 Each unicode char has a joining class (right, dual (left&right), center (joincausing) or transparent). 70 Each unicode char has a joining class (right, dual (left&right), center (joincausing) or transparent).
71 transparent joining is not encoded in QChar::joining(), but applies to all combining marks and format marks. 71 transparent joining is not encoded in QChar::joining(), but applies to all combining marks and format marks.
72 72
73 Right join-causing: dual + center 73 Right join-causing: dual + center
74 Left join-causing: dual + right + center 74 Left join-causing: dual + right + center
75 75
76 Rules are as follows (for a string already in visual order, as we have it here): 76 Rules are as follows (for a string already in visual order, as we have it here):
77 77
78 R1 Transparent characters do not affect joining behaviour. 78 R1 Transparent characters do not affect joining behaviour.
79 R2 A right joining character, that has a right join-causing char on the right will get form XRight 79 R2 A right joining character, that has a right join-causing char on the right will get form XRight
80 (R3 A left joining character, that has a left join-causing char on the left will get form XLeft) 80 (R3 A left joining character, that has a left join-causing char on the left will get form XLeft)
81 Note: the above rule is meaningless, as there are no pure left joining characters defined in Unicode 81 Note: the above rule is meaningless, as there are no pure left joining characters defined in Unicode
82 R4 A dual joining character, that has a left join-causing char on the left and a right join-causing char on 82 R4 A dual joining character, that has a left join-causing char on the left and a right join-causing char on
83 the right will get form XMedial 83 the right will get form XMedial
84 R5 A dual joining character, that has a right join causing char on the right, and no left join causing char on the left 84 R5 A dual joining character, that has a right join causing char on the right, and no left join causing char on the left
85 will get form XRight 85 will get form XRight
86 R6 A dual joining character, that has a left join causing char on the left, and no right join causing char on the right 86 R6 A dual joining character, that has a left join causing char on the left, and no right join causing char on the right
87 will get form XLeft 87 will get form XLeft
88 R7 Otherwise the character will get form XIsolated 88 R7 Otherwise the character will get form XIsolated
89 89
90 Additionally we have to do the minimal ligature support for lam-alef ligatures: 90 Additionally we have to do the minimal ligature support for lam-alef ligatures:
91 91
92 L1 Transparent characters do not affect ligature behaviour. 92 L1 Transparent characters do not affect ligature behaviour.
93 L2 Any sequence of Alef(XRight) + Lam(XMedial) will form the ligature Alef.Lam(XLeft) 93 L2 Any sequence of Alef(XRight) + Lam(XMedial) will form the ligature Alef.Lam(XLeft)
94 L3 Any sequence of Alef(XRight) + Lam(XLeft) will form the ligature Alef.Lam(XIsolated) 94 L3 Any sequence of Alef(XRight) + Lam(XLeft) will form the ligature Alef.Lam(XIsolated)
95 95
96 The two functions defined in this class do shaping in visual and logical order. For logical order just replace right with 96 The two functions defined in this class do shaping in visual and logical order. For logical order just replace right with
97 previous and left with next in the above rules ;-) 97 previous and left with next in the above rules ;-)
98*/ 98*/
99 99
100/* 100/*
101 Two small helper functions for arabic shaping. They get the next shape causing character on either 101 Two small helper functions for arabic shaping. They get the next shape causing character on either
102 side of the char in question. Implements rule R1. 102 side of the char in question. Implements rule R1.
103 103
104 leftChar() returns true if the char to the left is a left join-causing char 104 leftChar() returns true if the char to the left is a left join-causing char
105 rightChar() returns true if the char to the right is a right join-causing char 105 rightChar() returns true if the char to the right is a right join-causing char
106*/ 106*/
107static inline const QChar *prevChar( const QString &str, int pos ) 107static inline const QChar *prevChar( const QString &str, int pos )
108{ 108{
109 //qDebug("leftChar: pos=%d", pos); 109 //odebug << "leftChar: pos=" << pos << "" << oendl;
110 pos--; 110 pos--;
111 const QChar *ch = str.unicode() + pos; 111 const QChar *ch = str.unicode() + pos;
112 while( pos > -1 ) { 112 while( pos > -1 ) {
113 if( !ch->isMark() ) 113 if( !ch->isMark() )
114 return ch; 114 return ch;
115 pos--; 115 pos--;
116 ch--; 116 ch--;
117 } 117 }
118 return &QChar::replacement; 118 return &QChar::replacement;
119} 119}
120 120
121static inline const QChar *nextChar( const QString &str, int pos) 121static inline const QChar *nextChar( const QString &str, int pos)
122{ 122{
123 pos++; 123 pos++;
124 int len = str.length(); 124 int len = str.length();
125 const QChar *ch = str.unicode() + pos; 125 const QChar *ch = str.unicode() + pos;
126 while( pos < len ) { 126 while( pos < len ) {
127 //qDebug("rightChar: %d isLetter=%d, joining=%d", pos, ch.isLetter(), ch.joining()); 127 //odebug << "rightChar: " << pos << " isLetter=" << ch.isLetter() << ", joining=" << ch.joining() << "" << oendl;
128 if( !ch->isMark() ) 128 if( !ch->isMark() )
129 return ch; 129 return ch;
130 // assume it's a transparent char, this might not be 100% correct 130 // assume it's a transparent char, this might not be 100% correct
131 pos++; 131 pos++;
132 ch++; 132 ch++;
133 } 133 }
134 return &QChar::replacement; 134 return &QChar::replacement;
135} 135}
136 136
137static inline bool prevVisualCharJoins( const QString &str, int pos) 137static inline bool prevVisualCharJoins( const QString &str, int pos)
138{ 138{
139 return ( prevChar( str, pos )->joining() != QChar::OtherJoining ); 139 return ( prevChar( str, pos )->joining() != QChar::OtherJoining );
140} 140}
141 141
142static inline bool nextVisualCharJoins( const QString &str, int pos) 142static inline bool nextVisualCharJoins( const QString &str, int pos)
143{ 143{
144 QChar::Joining join = nextChar( str, pos )->joining(); 144 QChar::Joining join = nextChar( str, pos )->joining();
145 return ( join == QChar::Dual || join == QChar::Center ); 145 return ( join == QChar::Dual || join == QChar::Center );
146} 146}
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 @@
1/**************************************************************************** 1/****************************************************************************
2** $Id$ 2** $Id$
3** 3**
4** Implementation of the internal Qt classes dealing with rich text 4** Implementation of the internal Qt classes dealing with rich text
5** 5**
6** Created : 990101 6** Created : 990101
7** 7**
8** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. 8** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
9** 9**
10** This file is part of the kernel module of the Qt GUI Toolkit. 10** This file is part of the kernel module of the Qt GUI Toolkit.
11** 11**
12** This file may be distributed under the terms of the Q Public License 12** This file may be distributed under the terms of the Q Public License
13** as defined by Trolltech AS of Norway and appearing in the file 13** as defined by Trolltech AS of Norway and appearing in the file
14** LICENSE.QPL included in the packaging of this file. 14** LICENSE.QPL included in the packaging of this file.
15** 15**
16** This file may be distributed and/or modified under the terms of the 16** This file may be distributed and/or modified under the terms of the
17** GNU General Public License version 2 as published by the Free Software 17** GNU General Public License version 2 as published by the Free Software
18** Foundation and appearing in the file LICENSE.GPL included in the 18** Foundation and appearing in the file LICENSE.GPL included in the
19** packaging of this file. 19** packaging of this file.
20** 20**
21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition 21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
22** licenses may use this file in accordance with the Qt Commercial License 22** licenses may use this file in accordance with the Qt Commercial License
23** Agreement provided with the Software. 23** Agreement provided with the Software.
24** 24**
25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27** 27**
28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for 28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
29** information about Qt Commercial License Agreements. 29** information about Qt Commercial License Agreements.
30** See http://www.trolltech.com/qpl/ for QPL licensing information. 30** See http://www.trolltech.com/qpl/ for QPL licensing information.
31** See http://www.trolltech.com/gpl/ for GPL licensing information. 31** See http://www.trolltech.com/gpl/ for GPL licensing information.
32** 32**
33** Contact info@trolltech.com if any conditions of this licensing are 33** Contact info@trolltech.com if any conditions of this licensing are
34** not clear to you. 34** not clear to you.
35** 35**
36**********************************************************************/ 36**********************************************************************/
37 37
38#include "qrichtext_p.h" 38#include "qrichtext_p.h"
39 39
40/* OPIE */
41#include <opie2/odebug.h>
42using namespace Opie::Core;
43
44/* QT */
40#include "qdragobject.h" 45#include "qdragobject.h"
41#include "qpaintdevicemetrics.h" 46#include "qpaintdevicemetrics.h"
42#include "qdrawutil.h" 47#include "qdrawutil.h"
43#include "qcleanuphandler.h" 48#include "qcleanuphandler.h"
44 49
50/* STD */
45#include <stdlib.h> 51#include <stdlib.h>
46 52
47using namespace Qt3; 53using namespace Qt3;
48 54
49static QTextCursor* richTextExportStart = 0; 55static QTextCursor* richTextExportStart = 0;
50static QTextCursor* richTextExportEnd = 0; 56static QTextCursor* richTextExportEnd = 0;
51 57
52static QTextFormatCollection *qFormatCollection = 0; 58static QTextFormatCollection *qFormatCollection = 0;
53 59
54const int border_tolerance = 2; 60const int border_tolerance = 2;
55 61
56#ifdef Q_WS_WIN 62#ifdef Q_WS_WIN
57#include "qt_windows.h" 63#include "qt_windows.h"
58#endif 64#endif
59 65
60#define QChar_linesep QChar(0x2028U) 66#define QChar_linesep QChar(0x2028U)
61 67
62static inline bool is_printer( QPainter *p ) 68static inline bool is_printer( QPainter *p )
63{ 69{
64 if ( !p || !p->device() ) 70 if ( !p || !p->device() )
65 return FALSE; 71 return FALSE;
66 return p->device()->devType() == QInternal::Printer; 72 return p->device()->devType() == QInternal::Printer;
67} 73}
68 74
69static inline int scale( int value, QPainter *painter ) 75static inline int scale( int value, QPainter *painter )
70{ 76{
71 if ( is_printer( painter ) ) { 77 if ( is_printer( painter ) ) {
72 QPaintDeviceMetrics metrics( painter->device() ); 78 QPaintDeviceMetrics metrics( painter->device() );
73#if defined(Q_WS_X11) 79#if defined(Q_WS_X11)
74 value = value * metrics.logicalDpiY() / QPaintDevice::x11AppDpiY(); 80 value = value * metrics.logicalDpiY() / QPaintDevice::x11AppDpiY();
75#elif defined (Q_WS_WIN) 81#elif defined (Q_WS_WIN)
76 HDC hdc = GetDC( 0 ); 82 HDC hdc = GetDC( 0 );
77 int gdc = GetDeviceCaps( hdc, LOGPIXELSY ); 83 int gdc = GetDeviceCaps( hdc, LOGPIXELSY );
78 if ( gdc ) 84 if ( gdc )
79 value = value * metrics.logicalDpiY() / gdc; 85 value = value * metrics.logicalDpiY() / gdc;
80 ReleaseDC( 0, hdc ); 86 ReleaseDC( 0, hdc );
81#elif defined (Q_WS_MAC) 87#elif defined (Q_WS_MAC)
82 value = value * metrics.logicalDpiY() / 75; // ##### FIXME 88 value = value * metrics.logicalDpiY() / 75; // ##### FIXME
83#elif defined (Q_WS_QWS) 89#elif defined (Q_WS_QWS)
84 value = value * metrics.logicalDpiY() / 75; 90 value = value * metrics.logicalDpiY() / 75;
85#endif 91#endif
86 } 92 }
87 return value; 93 return value;
88} 94}
89 95
90// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 96// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
91 97
92void QTextCommandHistory::addCommand( QTextCommand *cmd ) 98void QTextCommandHistory::addCommand( QTextCommand *cmd )
93{ 99{
94 if ( current < (int)history.count() - 1 ) { 100 if ( current < (int)history.count() - 1 ) {
95 QPtrList<QTextCommand> commands; 101 QPtrList<QTextCommand> commands;
96 commands.setAutoDelete( FALSE ); 102 commands.setAutoDelete( FALSE );
97 103
98 for( int i = 0; i <= current; ++i ) { 104 for( int i = 0; i <= current; ++i ) {
99 commands.insert( i, history.at( 0 ) ); 105 commands.insert( i, history.at( 0 ) );
100 history.take( 0 ); 106 history.take( 0 );
101 } 107 }
102 108
103 commands.append( cmd ); 109 commands.append( cmd );
104 history.clear(); 110 history.clear();
105 history = commands; 111 history = commands;
106 history.setAutoDelete( TRUE ); 112 history.setAutoDelete( TRUE );
107 } else { 113 } else {
108 history.append( cmd ); 114 history.append( cmd );
109 } 115 }
110 116
111 if ( (int)history.count() > steps ) 117 if ( (int)history.count() > steps )
112 history.removeFirst(); 118 history.removeFirst();
113 else 119 else
114 ++current; 120 ++current;
115} 121}
116 122
117QTextCursor *QTextCommandHistory::undo( QTextCursor *c ) 123QTextCursor *QTextCommandHistory::undo( QTextCursor *c )
118{ 124{
119 if ( current > -1 ) { 125 if ( current > -1 ) {
120 QTextCursor *c2 = history.at( current )->unexecute( c ); 126 QTextCursor *c2 = history.at( current )->unexecute( c );
121 --current; 127 --current;
122 return c2; 128 return c2;
123 } 129 }
124 return 0; 130 return 0;
125} 131}
126 132
127QTextCursor *QTextCommandHistory::redo( QTextCursor *c ) 133QTextCursor *QTextCommandHistory::redo( QTextCursor *c )
128{ 134{
129 if ( current > -1 ) { 135 if ( current > -1 ) {
130 if ( current < (int)history.count() - 1 ) { 136 if ( current < (int)history.count() - 1 ) {
131 ++current; 137 ++current;
132 return history.at( current )->execute( c ); 138 return history.at( current )->execute( c );
133 } 139 }
134 } else { 140 } else {
135 if ( history.count() > 0 ) { 141 if ( history.count() > 0 ) {
136 ++current; 142 ++current;
137 return history.at( current )->execute( c ); 143 return history.at( current )->execute( c );
138 } 144 }
139 } 145 }
140 return 0; 146 return 0;
141} 147}
142 148
143bool QTextCommandHistory::isUndoAvailable() 149bool QTextCommandHistory::isUndoAvailable()
144{ 150{
145 return current > -1; 151 return current > -1;
146} 152}
147 153
148bool QTextCommandHistory::isRedoAvailable() 154bool QTextCommandHistory::isRedoAvailable()
149{ 155{
150 return current > -1 && current < (int)history.count() - 1 || current == -1 && history.count() > 0; 156 return current > -1 && current < (int)history.count() - 1 || current == -1 && history.count() > 0;
151} 157}
152 158
153// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 159// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
154 160
155QTextDeleteCommand::QTextDeleteCommand( QTextDocument *d, int i, int idx, const QMemArray<QTextStringChar> &str, 161QTextDeleteCommand::QTextDeleteCommand( QTextDocument *d, int i, int idx, const QMemArray<QTextStringChar> &str,
156 const QByteArray& oldStyleInfo ) 162 const QByteArray& oldStyleInfo )
157 : QTextCommand( d ), id( i ), index( idx ), parag( 0 ), text( str ), styleInformation( oldStyleInfo ) 163 : QTextCommand( d ), id( i ), index( idx ), parag( 0 ), text( str ), styleInformation( oldStyleInfo )
158{ 164{
159 for ( int j = 0; j < (int)text.size(); ++j ) { 165 for ( int j = 0; j < (int)text.size(); ++j ) {
160 if ( text[ j ].format() ) 166 if ( text[ j ].format() )
161 text[ j ].format()->addRef(); 167 text[ j ].format()->addRef();
162 } 168 }
163} 169}
164 170
165QTextDeleteCommand::QTextDeleteCommand( QTextParagraph *p, int idx, const QMemArray<QTextStringChar> &str ) 171QTextDeleteCommand::QTextDeleteCommand( QTextParagraph *p, int idx, const QMemArray<QTextStringChar> &str )
166 : QTextCommand( 0 ), id( -1 ), index( idx ), parag( p ), text( str ) 172 : QTextCommand( 0 ), id( -1 ), index( idx ), parag( p ), text( str )
167{ 173{
168 for ( int i = 0; i < (int)text.size(); ++i ) { 174 for ( int i = 0; i < (int)text.size(); ++i ) {
169 if ( text[ i ].format() ) 175 if ( text[ i ].format() )
170 text[ i ].format()->addRef(); 176 text[ i ].format()->addRef();
171 } 177 }
172} 178}
173 179
174QTextDeleteCommand::~QTextDeleteCommand() 180QTextDeleteCommand::~QTextDeleteCommand()
175{ 181{
176 for ( int i = 0; i < (int)text.size(); ++i ) { 182 for ( int i = 0; i < (int)text.size(); ++i ) {
177 if ( text[ i ].format() ) 183 if ( text[ i ].format() )
178 text[ i ].format()->removeRef(); 184 text[ i ].format()->removeRef();
179 } 185 }
180 text.resize( 0 ); 186 text.resize( 0 );
181} 187}
182 188
183QTextCursor *QTextDeleteCommand::execute( QTextCursor *c ) 189QTextCursor *QTextDeleteCommand::execute( QTextCursor *c )
184{ 190{
185 QTextParagraph *s = doc ? doc->paragAt( id ) : parag; 191 QTextParagraph *s = doc ? doc->paragAt( id ) : parag;
186 if ( !s ) { 192 if ( !s ) {
187 qWarning( "can't locate parag at %d, last parag: %d", id, doc->lastParagraph()->paragId() ); 193 owarn << "can't locate parag at " << id << ", last parag: " << doc->lastParagraph()->paragId() << "" << oendl;
188 return 0; 194 return 0;
189 } 195 }
190 196
191 cursor.setParagraph( s ); 197 cursor.setParagraph( s );
192 cursor.setIndex( index ); 198 cursor.setIndex( index );
193 int len = text.size(); 199 int len = text.size();
194 if ( c ) 200 if ( c )
195 *c = cursor; 201 *c = cursor;
196 if ( doc ) { 202 if ( doc ) {
197 doc->setSelectionStart( QTextDocument::Temp, cursor ); 203 doc->setSelectionStart( QTextDocument::Temp, cursor );
198 for ( int i = 0; i < len; ++i ) 204 for ( int i = 0; i < len; ++i )
199 cursor.gotoNextLetter(); 205 cursor.gotoNextLetter();
200 doc->setSelectionEnd( QTextDocument::Temp, cursor ); 206 doc->setSelectionEnd( QTextDocument::Temp, cursor );
201 doc->removeSelectedText( QTextDocument::Temp, &cursor ); 207 doc->removeSelectedText( QTextDocument::Temp, &cursor );
202 if ( c ) 208 if ( c )
203 *c = cursor; 209 *c = cursor;
204 } else { 210 } else {
205 s->remove( index, len ); 211 s->remove( index, len );
206 } 212 }
207 213
208 return c; 214 return c;
209} 215}
210 216
211QTextCursor *QTextDeleteCommand::unexecute( QTextCursor *c ) 217QTextCursor *QTextDeleteCommand::unexecute( QTextCursor *c )
212{ 218{
213 QTextParagraph *s = doc ? doc->paragAt( id ) : parag; 219 QTextParagraph *s = doc ? doc->paragAt( id ) : parag;
214 if ( !s ) { 220 if ( !s ) {
215 qWarning( "can't locate parag at %d, last parag: %d", id, doc->lastParagraph()->paragId() ); 221 owarn << "can't locate parag at " << id << ", last parag: " << doc->lastParagraph()->paragId() << "" << oendl;
216 return 0; 222 return 0;
217 } 223 }
218 224
219 cursor.setParagraph( s ); 225 cursor.setParagraph( s );
220 cursor.setIndex( index ); 226 cursor.setIndex( index );
221 QString str = QTextString::toString( text ); 227 QString str = QTextString::toString( text );
222 cursor.insert( str, TRUE, &text ); 228 cursor.insert( str, TRUE, &text );
223 cursor.setParagraph( s ); 229 cursor.setParagraph( s );
224 cursor.setIndex( index ); 230 cursor.setIndex( index );
225 if ( c ) { 231 if ( c ) {
226 c->setParagraph( s ); 232 c->setParagraph( s );
227 c->setIndex( index ); 233 c->setIndex( index );
228 for ( int i = 0; i < (int)text.size(); ++i ) 234 for ( int i = 0; i < (int)text.size(); ++i )
229 c->gotoNextLetter(); 235 c->gotoNextLetter();
230 } 236 }
231 237
232 if ( !styleInformation.isEmpty() ) { 238 if ( !styleInformation.isEmpty() ) {
233 QDataStream styleStream( styleInformation, IO_ReadOnly ); 239 QDataStream styleStream( styleInformation, IO_ReadOnly );
234 int num; 240 int num;
235 styleStream >> num; 241 styleStream >> num;
236 QTextParagraph *p = s; 242 QTextParagraph *p = s;
237 while ( num-- && p ) { 243 while ( num-- && p ) {
238 p->readStyleInformation( styleStream ); 244 p->readStyleInformation( styleStream );
239 p = p->next(); 245 p = p->next();
240 } 246 }
241 } 247 }
242 s = cursor.paragraph(); 248 s = cursor.paragraph();
243 while ( s ) { 249 while ( s ) {
244 s->format(); 250 s->format();
245 s->setChanged( TRUE ); 251 s->setChanged( TRUE );
246 if ( s == c->paragraph() ) 252 if ( s == c->paragraph() )
247 break; 253 break;
248 s = s->next(); 254 s = s->next();
249 } 255 }
250 256
251 return &cursor; 257 return &cursor;
252} 258}
253 259
254QTextFormatCommand::QTextFormatCommand( QTextDocument *d, int sid, int sidx, int eid, int eidx, 260QTextFormatCommand::QTextFormatCommand( QTextDocument *d, int sid, int sidx, int eid, int eidx,
255 const QMemArray<QTextStringChar> &old, QTextFormat *f, int fl ) 261 const QMemArray<QTextStringChar> &old, QTextFormat *f, int fl )
256 : QTextCommand( d ), startId( sid ), startIndex( sidx ), endId( eid ), endIndex( eidx ), format( f ), oldFormats( old ), flags( fl ) 262 : QTextCommand( d ), startId( sid ), startIndex( sidx ), endId( eid ), endIndex( eidx ), format( f ), oldFormats( old ), flags( fl )
257{ 263{
258 format = d->formatCollection()->format( f ); 264 format = d->formatCollection()->format( f );
259 for ( int j = 0; j < (int)oldFormats.size(); ++j ) { 265 for ( int j = 0; j < (int)oldFormats.size(); ++j ) {
260 if ( oldFormats[ j ].format() ) 266 if ( oldFormats[ j ].format() )
261 oldFormats[ j ].format()->addRef(); 267 oldFormats[ j ].format()->addRef();
262 } 268 }
263} 269}
264 270
265QTextFormatCommand::~QTextFormatCommand() 271QTextFormatCommand::~QTextFormatCommand()
266{ 272{
267 format->removeRef(); 273 format->removeRef();
268 for ( int j = 0; j < (int)oldFormats.size(); ++j ) { 274 for ( int j = 0; j < (int)oldFormats.size(); ++j ) {
269 if ( oldFormats[ j ].format() ) 275 if ( oldFormats[ j ].format() )
270 oldFormats[ j ].format()->removeRef(); 276 oldFormats[ j ].format()->removeRef();
271 } 277 }
272} 278}
273 279
274QTextCursor *QTextFormatCommand::execute( QTextCursor *c ) 280QTextCursor *QTextFormatCommand::execute( QTextCursor *c )
275{ 281{
276 QTextParagraph *sp = doc->paragAt( startId ); 282 QTextParagraph *sp = doc->paragAt( startId );
277 QTextParagraph *ep = doc->paragAt( endId ); 283 QTextParagraph *ep = doc->paragAt( endId );
278 if ( !sp || !ep ) 284 if ( !sp || !ep )
279 return c; 285 return c;
280 286
281 QTextCursor start( doc ); 287 QTextCursor start( doc );
282 start.setParagraph( sp ); 288 start.setParagraph( sp );
283 start.setIndex( startIndex ); 289 start.setIndex( startIndex );
284 QTextCursor end( doc ); 290 QTextCursor end( doc );
285 end.setParagraph( ep ); 291 end.setParagraph( ep );
286 end.setIndex( endIndex ); 292 end.setIndex( endIndex );
287 293
288 doc->setSelectionStart( QTextDocument::Temp, start ); 294 doc->setSelectionStart( QTextDocument::Temp, start );
289 doc->setSelectionEnd( QTextDocument::Temp, end ); 295 doc->setSelectionEnd( QTextDocument::Temp, end );
290 doc->setFormat( QTextDocument::Temp, format, flags ); 296 doc->setFormat( QTextDocument::Temp, format, flags );
291 doc->removeSelection( QTextDocument::Temp ); 297 doc->removeSelection( QTextDocument::Temp );
292 if ( endIndex == ep->length() ) 298 if ( endIndex == ep->length() )
293 end.gotoLeft(); 299 end.gotoLeft();
294 *c = end; 300 *c = end;
295 return c; 301 return c;
296} 302}
297 303
298QTextCursor *QTextFormatCommand::unexecute( QTextCursor *c ) 304QTextCursor *QTextFormatCommand::unexecute( QTextCursor *c )
299{ 305{
300 QTextParagraph *sp = doc->paragAt( startId ); 306 QTextParagraph *sp = doc->paragAt( startId );
301 QTextParagraph *ep = doc->paragAt( endId ); 307 QTextParagraph *ep = doc->paragAt( endId );
302 if ( !sp || !ep ) 308 if ( !sp || !ep )
303 return 0; 309 return 0;
304 310
305 int idx = startIndex; 311 int idx = startIndex;
306 int fIndex = 0; 312 int fIndex = 0;
307 for ( ;; ) { 313 for ( ;; ) {
308 if ( oldFormats.at( fIndex ).c == '\n' ) { 314 if ( oldFormats.at( fIndex ).c == '\n' ) {
309 if ( idx > 0 ) { 315 if ( idx > 0 ) {
310 if ( idx < sp->length() && fIndex > 0 ) 316 if ( idx < sp->length() && fIndex > 0 )
311 sp->setFormat( idx, 1, oldFormats.at( fIndex - 1 ).format() ); 317 sp->setFormat( idx, 1, oldFormats.at( fIndex - 1 ).format() );
@@ -1451,196 +1457,196 @@ void QTextDocument::setRichTextInternal( const QString &text, QTextCursor* curso
1451 NEWPAR; 1457 NEWPAR;
1452 } 1458 }
1453 1459
1454 // set rtext spacing to FALSE for the initial paragraph. 1460 // set rtext spacing to FALSE for the initial paragraph.
1455 curpar->rtext = FALSE; 1461 curpar->rtext = FALSE;
1456 1462
1457 QString wellKnownTags = "br hr wsp table qt body meta title"; 1463 QString wellKnownTags = "br hr wsp table qt body meta title";
1458 1464
1459 while ( pos < length ) { 1465 while ( pos < length ) {
1460 if ( hasPrefix(doc, length, pos, '<' ) ){ 1466 if ( hasPrefix(doc, length, pos, '<' ) ){
1461 if ( !hasPrefix( doc, length, pos+1, QChar('/') ) ) { 1467 if ( !hasPrefix( doc, length, pos+1, QChar('/') ) ) {
1462 // open tag 1468 // open tag
1463 QMap<QString, QString> attr; 1469 QMap<QString, QString> attr;
1464 bool emptyTag = FALSE; 1470 bool emptyTag = FALSE;
1465 QString tagname = parseOpenTag(doc, length, pos, attr, emptyTag); 1471 QString tagname = parseOpenTag(doc, length, pos, attr, emptyTag);
1466 if ( tagname.isEmpty() ) 1472 if ( tagname.isEmpty() )
1467 continue; // nothing we could do with this, probably parse error 1473 continue; // nothing we could do with this, probably parse error
1468 1474
1469 const QStyleSheetItem* nstyle = sheet_->item(tagname); 1475 const QStyleSheetItem* nstyle = sheet_->item(tagname);
1470 1476
1471 if ( nstyle ) { 1477 if ( nstyle ) {
1472 // we might have to close some 'forgotten' tags 1478 // we might have to close some 'forgotten' tags
1473 while ( !nstyle->allowedInContext( curtag.style ) ) { 1479 while ( !nstyle->allowedInContext( curtag.style ) ) {
1474 QString msg; 1480 QString msg;
1475 msg.sprintf( "QText Warning: Document not valid ( '%s' not allowed in '%s' #%d)", 1481 msg.sprintf( "QText Warning: Document not valid ( '%s' not allowed in '%s' #%d)",
1476 tagname.ascii(), curtag.style->name().ascii(), pos); 1482 tagname.ascii(), curtag.style->name().ascii(), pos);
1477 sheet_->error( msg ); 1483 sheet_->error( msg );
1478 if ( tags.isEmpty() ) 1484 if ( tags.isEmpty() )
1479 break; 1485 break;
1480 curtag = tags.pop(); 1486 curtag = tags.pop();
1481 } 1487 }
1482 1488
1483 /* special handling for p and li for HTML 1489 /* special handling for p and li for HTML
1484 compatibility. We do not want to embed blocks in 1490 compatibility. We do not want to embed blocks in
1485 p, and we do not want new blocks inside non-empty 1491 p, and we do not want new blocks inside non-empty
1486 lis. Plus we want to merge empty lis sometimes. */ 1492 lis. Plus we want to merge empty lis sometimes. */
1487 if( nstyle->displayMode() == QStyleSheetItem::DisplayListItem ) { 1493 if( nstyle->displayMode() == QStyleSheetItem::DisplayListItem ) {
1488 canMergeLi = TRUE; 1494 canMergeLi = TRUE;
1489 } else if ( nstyle->displayMode() == QStyleSheetItem::DisplayBlock ) { 1495 } else if ( nstyle->displayMode() == QStyleSheetItem::DisplayBlock ) {
1490 while ( curtag.style->name() == "p" ) { 1496 while ( curtag.style->name() == "p" ) {
1491 if ( tags.isEmpty() ) 1497 if ( tags.isEmpty() )
1492 break; 1498 break;
1493 curtag = tags.pop(); 1499 curtag = tags.pop();
1494 } 1500 }
1495 1501
1496 if ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ) { 1502 if ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ) {
1497 // we are in a li and a new block comes along 1503 // we are in a li and a new block comes along
1498 if ( nstyle->name() == "ul" || nstyle->name() == "ol" ) 1504 if ( nstyle->name() == "ul" || nstyle->name() == "ol" )
1499 hasNewPar = FALSE; // we want an empty li (like most browsers) 1505 hasNewPar = FALSE; // we want an empty li (like most browsers)
1500 if ( !hasNewPar ) { 1506 if ( !hasNewPar ) {
1501 /* do not add new blocks inside 1507 /* do not add new blocks inside
1502 non-empty lis */ 1508 non-empty lis */
1503 while ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ) { 1509 while ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ) {
1504 if ( tags.isEmpty() ) 1510 if ( tags.isEmpty() )
1505 break; 1511 break;
1506 curtag = tags.pop(); 1512 curtag = tags.pop();
1507 } 1513 }
1508 } else if ( canMergeLi ) { 1514 } else if ( canMergeLi ) {
1509 /* we have an empty li and a block 1515 /* we have an empty li and a block
1510 comes along, merge them */ 1516 comes along, merge them */
1511 nstyle = curtag.style; 1517 nstyle = curtag.style;
1512 } 1518 }
1513 canMergeLi = FALSE; 1519 canMergeLi = FALSE;
1514 } 1520 }
1515 } 1521 }
1516 } 1522 }
1517 1523
1518 QTextCustomItem* custom = 0; 1524 QTextCustomItem* custom = 0;
1519 1525
1520 // some well-known tags, some have a nstyle, some not 1526 // some well-known tags, some have a nstyle, some not
1521 if ( wellKnownTags.find( tagname ) != -1 ) { 1527 if ( wellKnownTags.find( tagname ) != -1 ) {
1522 if ( tagname == "br" ) { 1528 if ( tagname == "br" ) {
1523 emptyTag = space = TRUE; 1529 emptyTag = space = TRUE;
1524 int index = QMAX( curpar->length(),1) - 1; 1530 int index = QMAX( curpar->length(),1) - 1;
1525 QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor ); 1531 QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor );
1526 curpar->append( QChar_linesep ); 1532 curpar->append( QChar_linesep );
1527 curpar->setFormat( index, 1, &format ); 1533 curpar->setFormat( index, 1, &format );
1528 } else if ( tagname == "hr" ) { 1534 } else if ( tagname == "hr" ) {
1529 emptyTag = space = TRUE; 1535 emptyTag = space = TRUE;
1530 custom = sheet_->tag( tagname, attr, contxt, *factory_ , emptyTag, this ); 1536 custom = sheet_->tag( tagname, attr, contxt, *factory_ , emptyTag, this );
1531 NEWPAR; 1537 NEWPAR;
1532 } else if ( tagname == "table" ) { 1538 } else if ( tagname == "table" ) {
1533 emptyTag = space = TRUE; 1539 emptyTag = space = TRUE;
1534 QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor ); 1540 QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor );
1535 curpar->setAlignment( curtag.alignment ); 1541 curpar->setAlignment( curtag.alignment );
1536 custom = parseTable( attr, format, doc, length, pos, curpar ); 1542 custom = parseTable( attr, format, doc, length, pos, curpar );
1537 } else if ( tagname == "qt" || tagname == "body" ) { 1543 } else if ( tagname == "qt" || tagname == "body" ) {
1538 if ( attr.contains( "bgcolor" ) ) { 1544 if ( attr.contains( "bgcolor" ) ) {
1539 QBrush *b = new QBrush( QColor( attr["bgcolor"] ) ); 1545 QBrush *b = new QBrush( QColor( attr["bgcolor"] ) );
1540 setPaper( b ); 1546 setPaper( b );
1541 } 1547 }
1542 if ( attr.contains( "background" ) ) { 1548 if ( attr.contains( "background" ) ) {
1543 QImage img; 1549 QImage img;
1544 QString bg = attr["background"]; 1550 QString bg = attr["background"];
1545 const QMimeSource* m = factory_->data( bg, contxt ); 1551 const QMimeSource* m = factory_->data( bg, contxt );
1546 if ( !m ) { 1552 if ( !m ) {
1547 qWarning("QRichText: no mimesource for %s", bg.latin1() ); 1553 owarn << "QRichText: no mimesource for " << bg.latin1() << "" << oendl;
1548 } else { 1554 } else {
1549 if ( !QImageDrag::decode( m, img ) ) { 1555 if ( !QImageDrag::decode( m, img ) ) {
1550 qWarning("QTextImage: cannot decode %s", bg.latin1() ); 1556 owarn << "QTextImage: cannot decode " << bg.latin1() << "" << oendl;
1551 } 1557 }
1552 } 1558 }
1553 if ( !img.isNull() ) { 1559 if ( !img.isNull() ) {
1554 QPixmap pm; 1560 QPixmap pm;
1555 pm.convertFromImage( img ); 1561 pm.convertFromImage( img );
1556 QBrush *b = new QBrush( QColor(), pm ); 1562 QBrush *b = new QBrush( QColor(), pm );
1557 setPaper( b ); 1563 setPaper( b );
1558 } 1564 }
1559 } 1565 }
1560 if ( attr.contains( "text" ) ) { 1566 if ( attr.contains( "text" ) ) {
1561 QColor c( attr["text"] ); 1567 QColor c( attr["text"] );
1562 if ( formatCollection()->defaultFormat()->color() != c ) { 1568 if ( formatCollection()->defaultFormat()->color() != c ) {
1563 QDict<QTextFormat> formats = formatCollection()->dict(); 1569 QDict<QTextFormat> formats = formatCollection()->dict();
1564 QDictIterator<QTextFormat> it( formats ); 1570 QDictIterator<QTextFormat> it( formats );
1565 while ( it.current() ) { 1571 while ( it.current() ) {
1566 if ( it.current() == formatCollection()->defaultFormat() ) { 1572 if ( it.current() == formatCollection()->defaultFormat() ) {
1567 ++it; 1573 ++it;
1568 continue; 1574 continue;
1569 } 1575 }
1570 it.current()->setColor( c ); 1576 it.current()->setColor( c );
1571 ++it; 1577 ++it;
1572 } 1578 }
1573 formatCollection()->defaultFormat()->setColor( c ); 1579 formatCollection()->defaultFormat()->setColor( c );
1574 curtag.format.setColor( c ); 1580 curtag.format.setColor( c );
1575 } 1581 }
1576 } 1582 }
1577 if ( attr.contains( "link" ) ) 1583 if ( attr.contains( "link" ) )
1578 linkColor = QColor( attr["link"] ); 1584 linkColor = QColor( attr["link"] );
1579 if ( attr.contains( "title" ) ) 1585 if ( attr.contains( "title" ) )
1580 attribs.replace( "title", attr["title"] ); 1586 attribs.replace( "title", attr["title"] );
1581 1587
1582 if ( textEditMode ) { 1588 if ( textEditMode ) {
1583 if ( attr.contains("style" ) ) { 1589 if ( attr.contains("style" ) ) {
1584 QString a = attr["style"]; 1590 QString a = attr["style"];
1585 for ( int s = 0; s < a.contains(';')+1; s++ ) { 1591 for ( int s = 0; s < a.contains(';')+1; s++ ) {
1586 QString style = QTextDocument::section( a, ";", s, s ); 1592 QString style = QTextDocument::section( a, ";", s, s );
1587 if ( style.startsWith("font-size:" ) && QTextDocument::endsWith(style, "pt") ) { 1593 if ( style.startsWith("font-size:" ) && QTextDocument::endsWith(style, "pt") ) {
1588 scaleFontsFactor = double( formatCollection()->defaultFormat()->fn.pointSize() ) / 1594 scaleFontsFactor = double( formatCollection()->defaultFormat()->fn.pointSize() ) /
1589 style.mid( 10, style.length() - 12 ).toInt(); 1595 style.mid( 10, style.length() - 12 ).toInt();
1590 } 1596 }
1591 } 1597 }
1592 } 1598 }
1593 nstyle = 0; // ignore body in textEditMode 1599 nstyle = 0; // ignore body in textEditMode
1594 } 1600 }
1595 // end qt- and body-tag handling 1601 // end qt- and body-tag handling
1596 } else if ( tagname == "meta" ) { 1602 } else if ( tagname == "meta" ) {
1597 if ( attr["name"] == "qrichtext" && attr["content"] == "1" ) 1603 if ( attr["name"] == "qrichtext" && attr["content"] == "1" )
1598 textEditMode = TRUE; 1604 textEditMode = TRUE;
1599 } else if ( tagname == "title" ) { 1605 } else if ( tagname == "title" ) {
1600 QString title; 1606 QString title;
1601 while ( pos < length ) { 1607 while ( pos < length ) {
1602 if ( hasPrefix( doc, length, pos, QChar('<') ) && hasPrefix( doc, length, pos+1, QChar('/') ) && 1608 if ( hasPrefix( doc, length, pos, QChar('<') ) && hasPrefix( doc, length, pos+1, QChar('/') ) &&
1603 parseCloseTag( doc, length, pos ) == "title" ) 1609 parseCloseTag( doc, length, pos ) == "title" )
1604 break; 1610 break;
1605 title += doc[ pos ]; 1611 title += doc[ pos ];
1606 ++pos; 1612 ++pos;
1607 } 1613 }
1608 attribs.replace( "title", title ); 1614 attribs.replace( "title", title );
1609 } 1615 }
1610 } // end of well-known tag handling 1616 } // end of well-known tag handling
1611 1617
1612 if ( !custom ) // try generic custom item 1618 if ( !custom ) // try generic custom item
1613 custom = sheet_->tag( tagname, attr, contxt, *factory_ , emptyTag, this ); 1619 custom = sheet_->tag( tagname, attr, contxt, *factory_ , emptyTag, this );
1614 1620
1615 if ( !nstyle && !custom ) // we have no clue what this tag could be, ignore it 1621 if ( !nstyle && !custom ) // we have no clue what this tag could be, ignore it
1616 continue; 1622 continue;
1617 1623
1618 if ( custom ) { 1624 if ( custom ) {
1619 int index = QMAX( curpar->length(),1) - 1; 1625 int index = QMAX( curpar->length(),1) - 1;
1620 QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor ); 1626 QTextFormat format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor );
1621 curpar->append( QChar('*') ); 1627 curpar->append( QChar('*') );
1622 curpar->setFormat( index, 1, &format ); 1628 curpar->setFormat( index, 1, &format );
1623 curpar->at( index )->setCustomItem( custom ); 1629 curpar->at( index )->setCustomItem( custom );
1624 if ( !curtag.anchorHref.isEmpty() ) 1630 if ( !curtag.anchorHref.isEmpty() )
1625 curpar->at(index)->setAnchor( QString::null, curtag.anchorHref ); 1631 curpar->at(index)->setAnchor( QString::null, curtag.anchorHref );
1626 if ( !anchorName.isEmpty() ) { 1632 if ( !anchorName.isEmpty() ) {
1627 curpar->at(index)->setAnchor( anchorName, curpar->at(index)->anchorHref() ); 1633 curpar->at(index)->setAnchor( anchorName, curpar->at(index)->anchorHref() );
1628 anchorName = QString::null; 1634 anchorName = QString::null;
1629 } 1635 }
1630 registerCustomItem( custom, curpar ); 1636 registerCustomItem( custom, curpar );
1631 hasNewPar = FALSE; 1637 hasNewPar = FALSE;
1632 } else if ( !emptyTag ) { 1638 } else if ( !emptyTag ) {
1633 /* if we do nesting, push curtag on the stack, 1639 /* if we do nesting, push curtag on the stack,
1634 otherwise reinint curag. */ 1640 otherwise reinint curag. */
1635 if ( curtag.style->name() != tagname || nstyle->selfNesting() ) { 1641 if ( curtag.style->name() != tagname || nstyle->selfNesting() ) {
1636 tags.push( curtag ); 1642 tags.push( curtag );
1637 } else { 1643 } else {
1638 if ( !tags.isEmpty() ) 1644 if ( !tags.isEmpty() )
1639 curtag = tags.top(); 1645 curtag = tags.top();
1640 else 1646 else
1641 curtag = initag; 1647 curtag = initag;
1642 } 1648 }
1643 1649
1644 curtag.name = tagname; 1650 curtag.name = tagname;
1645 curtag.style = nstyle; 1651 curtag.style = nstyle;
1646 curtag.name = tagname; 1652 curtag.name = tagname;
@@ -2059,193 +2065,193 @@ QString QTextDocument::plainText() const
2059 } else { 2065 } else {
2060 s += p->at( i )->c; 2066 s += p->at( i )->c;
2061 } 2067 }
2062 } 2068 }
2063 } 2069 }
2064 s.remove( s.length() - 1, 1 ); 2070 s.remove( s.length() - 1, 1 );
2065 if ( p->next() ) 2071 if ( p->next() )
2066 s += "\n"; 2072 s += "\n";
2067 buffer += s; 2073 buffer += s;
2068 p = p->next(); 2074 p = p->next();
2069 } 2075 }
2070 return buffer; 2076 return buffer;
2071} 2077}
2072 2078
2073static QString align_to_string( int a ) 2079static QString align_to_string( int a )
2074{ 2080{
2075 if ( a & Qt::AlignRight ) 2081 if ( a & Qt::AlignRight )
2076 return " align=\"right\""; 2082 return " align=\"right\"";
2077 if ( a & Qt::AlignHCenter ) 2083 if ( a & Qt::AlignHCenter )
2078 return " align=\"center\""; 2084 return " align=\"center\"";
2079 if ( a & Qt3::AlignJustify ) 2085 if ( a & Qt3::AlignJustify )
2080 return " align=\"justify\""; 2086 return " align=\"justify\"";
2081 return QString::null; 2087 return QString::null;
2082} 2088}
2083 2089
2084static QString direction_to_string( int d ) 2090static QString direction_to_string( int d )
2085{ 2091{
2086 if ( d != QChar::DirON ) 2092 if ( d != QChar::DirON )
2087 return ( d == QChar::DirL? " dir=\"ltr\"" : " dir=\"rtl\"" ); 2093 return ( d == QChar::DirL? " dir=\"ltr\"" : " dir=\"rtl\"" );
2088 return QString::null; 2094 return QString::null;
2089} 2095}
2090 2096
2091static QString list_value_to_string( int v ) 2097static QString list_value_to_string( int v )
2092{ 2098{
2093 if ( v != -1 ) 2099 if ( v != -1 )
2094 return " listvalue=\"" + QString::number( v ) + "\""; 2100 return " listvalue=\"" + QString::number( v ) + "\"";
2095 return QString::null; 2101 return QString::null;
2096} 2102}
2097 2103
2098static QString list_style_to_string( int v ) 2104static QString list_style_to_string( int v )
2099{ 2105{
2100 switch( v ) { 2106 switch( v ) {
2101 case QStyleSheetItem::ListDecimal: return "\"1\""; 2107 case QStyleSheetItem::ListDecimal: return "\"1\"";
2102 case QStyleSheetItem::ListLowerAlpha: return "\"a\""; 2108 case QStyleSheetItem::ListLowerAlpha: return "\"a\"";
2103 case QStyleSheetItem::ListUpperAlpha: return "\"A\""; 2109 case QStyleSheetItem::ListUpperAlpha: return "\"A\"";
2104 case QStyleSheetItem::ListDisc: return "\"disc\""; 2110 case QStyleSheetItem::ListDisc: return "\"disc\"";
2105 case QStyleSheetItem::ListSquare: return "\"square\""; 2111 case QStyleSheetItem::ListSquare: return "\"square\"";
2106 case QStyleSheetItem::ListCircle: return "\"circle\""; 2112 case QStyleSheetItem::ListCircle: return "\"circle\"";
2107 default: 2113 default:
2108 return QString::null; 2114 return QString::null;
2109 } 2115 }
2110} 2116}
2111 2117
2112static inline bool list_is_ordered( int v ) 2118static inline bool list_is_ordered( int v )
2113{ 2119{
2114 return v == QStyleSheetItem::ListDecimal || 2120 return v == QStyleSheetItem::ListDecimal ||
2115 v == QStyleSheetItem::ListLowerAlpha || 2121 v == QStyleSheetItem::ListLowerAlpha ||
2116 v == QStyleSheetItem::ListUpperAlpha; 2122 v == QStyleSheetItem::ListUpperAlpha;
2117} 2123}
2118 2124
2119 2125
2120static QString margin_to_string( QStyleSheetItem* style, int t, int b, int l, int r, int fl ) 2126static QString margin_to_string( QStyleSheetItem* style, int t, int b, int l, int r, int fl )
2121{ 2127{
2122 QString s; 2128 QString s;
2123 if ( l > 0 ) 2129 if ( l > 0 )
2124 s += QString(!!s?";":"") + "margin-left:" + QString::number(l+QMAX(0,style->margin(QStyleSheetItem::MarginLeft))) + "px"; 2130 s += QString(!!s?";":"") + "margin-left:" + QString::number(l+QMAX(0,style->margin(QStyleSheetItem::MarginLeft))) + "px";
2125 if ( r > 0 ) 2131 if ( r > 0 )
2126 s += QString(!!s?";":"") + "margin-right:" + QString::number(r+QMAX(0,style->margin(QStyleSheetItem::MarginRight))) + "px"; 2132 s += QString(!!s?";":"") + "margin-right:" + QString::number(r+QMAX(0,style->margin(QStyleSheetItem::MarginRight))) + "px";
2127 if ( t > 0 ) 2133 if ( t > 0 )
2128 s += QString(!!s?";":"") + "margin-top:" + QString::number(t+QMAX(0,style->margin(QStyleSheetItem::MarginTop))) + "px"; 2134 s += QString(!!s?";":"") + "margin-top:" + QString::number(t+QMAX(0,style->margin(QStyleSheetItem::MarginTop))) + "px";
2129 if ( b > 0 ) 2135 if ( b > 0 )
2130 s += QString(!!s?";":"") + "margin-bottom:" + QString::number(b+QMAX(0,style->margin(QStyleSheetItem::MarginBottom))) + "px"; 2136 s += QString(!!s?";":"") + "margin-bottom:" + QString::number(b+QMAX(0,style->margin(QStyleSheetItem::MarginBottom))) + "px";
2131 if ( fl > 0 ) 2137 if ( fl > 0 )
2132 s += QString(!!s?";":"") + "text-indent:" + QString::number(fl+QMAX(0,style->margin(QStyleSheetItem::MarginFirstLine))) + "px"; 2138 s += QString(!!s?";":"") + "text-indent:" + QString::number(fl+QMAX(0,style->margin(QStyleSheetItem::MarginFirstLine))) + "px";
2133 if ( !!s ) 2139 if ( !!s )
2134 return " style=\"" + s + "\""; 2140 return " style=\"" + s + "\"";
2135 return QString::null; 2141 return QString::null;
2136} 2142}
2137 2143
2138QString QTextDocument::richText() const 2144QString QTextDocument::richText() const
2139{ 2145{
2140 QString s = ""; 2146 QString s = "";
2141 if ( !par ) { 2147 if ( !par ) {
2142 s += "<html><head><meta name=\"qrichtext\" content=\"1\" /></head><body style=\"font-size:" ; 2148 s += "<html><head><meta name=\"qrichtext\" content=\"1\" /></head><body style=\"font-size:" ;
2143 s += QString::number( formatCollection()->defaultFormat()->font().pointSize() ); 2149 s += QString::number( formatCollection()->defaultFormat()->font().pointSize() );
2144 s += "pt;font-family:"; 2150 s += "pt;font-family:";
2145 s += formatCollection()->defaultFormat()->font().family(); 2151 s += formatCollection()->defaultFormat()->font().family();
2146 s +="\">"; 2152 s +="\">";
2147 } 2153 }
2148 QTextParagraph* p = fParag; 2154 QTextParagraph* p = fParag;
2149 2155
2150 QStyleSheetItem* item_p = styleSheet()->item("p"); 2156 QStyleSheetItem* item_p = styleSheet()->item("p");
2151 QStyleSheetItem* item_ul = styleSheet()->item("ul"); 2157 QStyleSheetItem* item_ul = styleSheet()->item("ul");
2152 QStyleSheetItem* item_ol = styleSheet()->item("ol"); 2158 QStyleSheetItem* item_ol = styleSheet()->item("ol");
2153 QStyleSheetItem* item_li = styleSheet()->item("li"); 2159 QStyleSheetItem* item_li = styleSheet()->item("li");
2154 if ( !item_p || !item_ul || !item_ol || !item_li ) { 2160 if ( !item_p || !item_ul || !item_ol || !item_li ) {
2155 qWarning( "QTextEdit: cannot export HTML due to insufficient stylesheet (lack of p, ul, ol, or li)" ); 2161 owarn << "QTextEdit: cannot export HTML due to insufficient stylesheet (lack of p, ul, ol, or li)" << oendl;
2156 return QString::null; 2162 return QString::null;
2157 } 2163 }
2158 int pastListDepth = 0; 2164 int pastListDepth = 0;
2159 int listDepth = 0; 2165 int listDepth = 0;
2160 int futureListDepth = 0; 2166 int futureListDepth = 0;
2161 QMemArray<int> listStyles(10); 2167 QMemArray<int> listStyles(10);
2162 2168
2163 while ( p ) { 2169 while ( p ) {
2164 listDepth = p->listDepth(); 2170 listDepth = p->listDepth();
2165 if ( listDepth < pastListDepth ) { 2171 if ( listDepth < pastListDepth ) {
2166 for ( int i = listDepth+1; i <= pastListDepth; i++ ) 2172 for ( int i = listDepth+1; i <= pastListDepth; i++ )
2167 s += list_is_ordered( listStyles[i] ) ? "</ol>" : "</ul>"; 2173 s += list_is_ordered( listStyles[i] ) ? "</ol>" : "</ul>";
2168 s += '\n'; 2174 s += '\n';
2169 } else if ( listDepth > pastListDepth ) { 2175 } else if ( listDepth > pastListDepth ) {
2170 s += '\n'; 2176 s += '\n';
2171 listStyles.resize( QMAX( (int)listStyles.size(), listDepth+1 ) ); 2177 listStyles.resize( QMAX( (int)listStyles.size(), listDepth+1 ) );
2172 QString list_type; 2178 QString list_type;
2173 listStyles[listDepth] = p->listStyle(); 2179 listStyles[listDepth] = p->listStyle();
2174 if ( !list_is_ordered( p->listStyle() ) || item_ol->listStyle() != p->listStyle() ) 2180 if ( !list_is_ordered( p->listStyle() ) || item_ol->listStyle() != p->listStyle() )
2175 list_type = " type=" + list_style_to_string( p->listStyle() ); 2181 list_type = " type=" + list_style_to_string( p->listStyle() );
2176 for ( int i = pastListDepth; i < listDepth; i++ ) { 2182 for ( int i = pastListDepth; i < listDepth; i++ ) {
2177 s += list_is_ordered( p->listStyle() ) ? "<ol" : "<ul" ; 2183 s += list_is_ordered( p->listStyle() ) ? "<ol" : "<ul" ;
2178 s += list_type + ">"; 2184 s += list_type + ">";
2179 } 2185 }
2180 } else { 2186 } else {
2181 s += '\n'; 2187 s += '\n';
2182 } 2188 }
2183 2189
2184 QString ps = p->richText(); 2190 QString ps = p->richText();
2185 2191
2186 // for the bottom margin we need to know whether we are at the end of a list 2192 // for the bottom margin we need to know whether we are at the end of a list
2187 futureListDepth = 0; 2193 futureListDepth = 0;
2188 if ( listDepth > 0 && p->next() ) 2194 if ( listDepth > 0 && p->next() )
2189 futureListDepth = p->next()->listDepth(); 2195 futureListDepth = p->next()->listDepth();
2190 2196
2191 if ( richTextExportStart && richTextExportStart->paragraph() ==p && 2197 if ( richTextExportStart && richTextExportStart->paragraph() ==p &&
2192 richTextExportStart->index() == 0 ) 2198 richTextExportStart->index() == 0 )
2193 s += "<selstart/>"; 2199 s += "<selstart/>";
2194 2200
2195 if ( p->isListItem() ) { 2201 if ( p->isListItem() ) {
2196 s += "<li"; 2202 s += "<li";
2197 if ( p->listStyle() != listStyles[listDepth] ) 2203 if ( p->listStyle() != listStyles[listDepth] )
2198 s += " type=" + list_style_to_string( p->listStyle() ); 2204 s += " type=" + list_style_to_string( p->listStyle() );
2199 s +=align_to_string( p->alignment() ); 2205 s +=align_to_string( p->alignment() );
2200 s += margin_to_string( item_li, p->utm, p->ubm, p->ulm, p->urm, p->uflm ); 2206 s += margin_to_string( item_li, p->utm, p->ubm, p->ulm, p->urm, p->uflm );
2201 s += list_value_to_string( p->listValue() ); 2207 s += list_value_to_string( p->listValue() );
2202 s += direction_to_string( p->direction() ); 2208 s += direction_to_string( p->direction() );
2203 s +=">"; 2209 s +=">";
2204 s += ps; 2210 s += ps;
2205 s += "</li>"; 2211 s += "</li>";
2206 } else { 2212 } else {
2207 // normal paragraph item 2213 // normal paragraph item
2208 s += "<p"; 2214 s += "<p";
2209 s += align_to_string( p->alignment() ); 2215 s += align_to_string( p->alignment() );
2210 s += margin_to_string( item_p, p->utm, p->ubm, p->ulm, p->urm, p->uflm ); 2216 s += margin_to_string( item_p, p->utm, p->ubm, p->ulm, p->urm, p->uflm );
2211 s +=direction_to_string( p->direction() ); 2217 s +=direction_to_string( p->direction() );
2212 s += ">"; 2218 s += ">";
2213 s += ps; 2219 s += ps;
2214 s += "</p>"; 2220 s += "</p>";
2215 } 2221 }
2216 pastListDepth = listDepth; 2222 pastListDepth = listDepth;
2217 p = p->next(); 2223 p = p->next();
2218 } 2224 }
2219 while ( listDepth > 0 ) { 2225 while ( listDepth > 0 ) {
2220 s += list_is_ordered( listStyles[listDepth] ) ? "</ol>" : "</ul>"; 2226 s += list_is_ordered( listStyles[listDepth] ) ? "</ol>" : "</ul>";
2221 listDepth--; 2227 listDepth--;
2222 } 2228 }
2223 2229
2224 if ( !par ) 2230 if ( !par )
2225 s += "\n</body></html>\n"; 2231 s += "\n</body></html>\n";
2226 2232
2227 return s; 2233 return s;
2228} 2234}
2229 2235
2230QString QTextDocument::text() const 2236QString QTextDocument::text() const
2231{ 2237{
2232 if ( txtFormat == Qt::AutoText && preferRichText || txtFormat == Qt::RichText ) 2238 if ( txtFormat == Qt::AutoText && preferRichText || txtFormat == Qt::RichText )
2233 return richText(); 2239 return richText();
2234 return plainText(); 2240 return plainText();
2235} 2241}
2236 2242
2237QString QTextDocument::text( int parag ) const 2243QString QTextDocument::text( int parag ) const
2238{ 2244{
2239 QTextParagraph *p = paragAt( parag ); 2245 QTextParagraph *p = paragAt( parag );
2240 if ( !p ) 2246 if ( !p )
2241 return QString::null; 2247 return QString::null;
2242 2248
2243 if ( txtFormat == Qt::AutoText && preferRichText || txtFormat == Qt::RichText ) 2249 if ( txtFormat == Qt::AutoText && preferRichText || txtFormat == Qt::RichText )
2244 return p->richText(); 2250 return p->richText();
2245 else 2251 else
2246 return p->string()->toString(); 2252 return p->string()->toString();
2247} 2253}
2248 2254
2249void QTextDocument::invalidate() 2255void QTextDocument::invalidate()
2250{ 2256{
2251 QTextParagraph *s = fParag; 2257 QTextParagraph *s = fParag;
@@ -4003,246 +4009,246 @@ void QTextParagraph::format( int start, bool doMove )
4003 // with has to be the full document width on mac as the selections 4009 // with has to be the full document width on mac as the selections
4004 // always extend completely to the right. This is a bit unefficient, 4010 // always extend completely to the right. This is a bit unefficient,
4005 // as this results in a bigger double buffer than needed but ok for 4011 // as this results in a bigger double buffer than needed but ok for
4006 // now. 4012 // now.
4007 if ( lineStarts.count() == 1 ) { 4013 if ( lineStarts.count() == 1 ) {
4008 if ( !string()->isBidi() ) { 4014 if ( !string()->isBidi() ) {
4009 c = &str->at( str->length() - 1 ); 4015 c = &str->at( str->length() - 1 );
4010 r.setWidth( c->x + str->width( str->length() - 1 ) ); 4016 r.setWidth( c->x + str->width( str->length() - 1 ) );
4011 } else { 4017 } else {
4012 r.setWidth( lineStarts[0]->w ); 4018 r.setWidth( lineStarts[0]->w );
4013 } 4019 }
4014 } 4020 }
4015 4021
4016 if ( !hasdoc ) { // qt_format_text bounding rect handling 4022 if ( !hasdoc ) { // qt_format_text bounding rect handling
4017 it = lineStarts.begin(); 4023 it = lineStarts.begin();
4018 int usedw = 0; 4024 int usedw = 0;
4019 for ( ; it != lineStarts.end(); ++it ) 4025 for ( ; it != lineStarts.end(); ++it )
4020 usedw = QMAX( usedw, (*it)->w ); 4026 usedw = QMAX( usedw, (*it)->w );
4021 if ( r.width() <= 0 ) { 4027 if ( r.width() <= 0 ) {
4022 // if the user specifies an invalid rect, this means that the 4028 // if the user specifies an invalid rect, this means that the
4023 // bounding box should grow to the width that the text actually 4029 // bounding box should grow to the width that the text actually
4024 // needs 4030 // needs
4025 r.setWidth( usedw ); 4031 r.setWidth( usedw );
4026 } else { 4032 } else {
4027 r.setWidth( QMIN( usedw, r.width() ) ); 4033 r.setWidth( QMIN( usedw, r.width() ) );
4028 } 4034 }
4029 } 4035 }
4030 4036
4031 if ( y != r.height() ) 4037 if ( y != r.height() )
4032 r.setHeight( y ); 4038 r.setHeight( y );
4033 4039
4034 if ( !visible ) { 4040 if ( !visible ) {
4035 r.setHeight( 0 ); 4041 r.setHeight( 0 );
4036 } else { 4042 } else {
4037 int minw = formatter()->minimumWidth(); 4043 int minw = formatter()->minimumWidth();
4038 int wused = formatter()->widthUsed(); 4044 int wused = formatter()->widthUsed();
4039 wused = QMAX( minw, wused ); 4045 wused = QMAX( minw, wused );
4040 if ( hasdoc ) { 4046 if ( hasdoc ) {
4041 document()->setMinimumWidth( minw, wused, this ); 4047 document()->setMinimumWidth( minw, wused, this );
4042 } else { 4048 } else {
4043 pseudoDocument()->minw = QMAX( pseudoDocument()->minw, minw ); 4049 pseudoDocument()->minw = QMAX( pseudoDocument()->minw, minw );
4044 pseudoDocument()->wused = QMAX( pseudoDocument()->wused, wused ); 4050 pseudoDocument()->wused = QMAX( pseudoDocument()->wused, wused );
4045 } 4051 }
4046 } 4052 }
4047 4053
4048 // do page breaks if required 4054 // do page breaks if required
4049 if ( hasdoc && document()->isPageBreakEnabled() ) { 4055 if ( hasdoc && document()->isPageBreakEnabled() ) {
4050 int shift = document()->formatter()->formatVertically( document(), this ); 4056 int shift = document()->formatter()->formatVertically( document(), this );
4051 if ( shift && !formattedAgain ) { 4057 if ( shift && !formattedAgain ) {
4052 formattedAgain = TRUE; 4058 formattedAgain = TRUE;
4053 goto formatAgain; 4059 goto formatAgain;
4054 } 4060 }
4055 } 4061 }
4056 4062
4057 if ( n && doMove && n->invalid == -1 && r.y() + r.height() != n->r.y() ) { 4063 if ( n && doMove && n->invalid == -1 && r.y() + r.height() != n->r.y() ) {
4058 int dy = ( r.y() + r.height() ) - n->r.y(); 4064 int dy = ( r.y() + r.height() ) - n->r.y();
4059 QTextParagraph *s = n; 4065 QTextParagraph *s = n;
4060 bool makeInvalid = p && p->lastInFrame; 4066 bool makeInvalid = p && p->lastInFrame;
4061 while ( s && dy ) { 4067 while ( s && dy ) {
4062 if ( !s->isFullWidth() ) 4068 if ( !s->isFullWidth() )
4063 makeInvalid = TRUE; 4069 makeInvalid = TRUE;
4064 if ( makeInvalid ) 4070 if ( makeInvalid )
4065 s->invalidate( 0 ); 4071 s->invalidate( 0 );
4066 s->move( dy ); 4072 s->move( dy );
4067 if ( s->lastInFrame ) 4073 if ( s->lastInFrame )
4068 makeInvalid = TRUE; 4074 makeInvalid = TRUE;
4069 s = s->n; 4075 s = s->n;
4070 } 4076 }
4071 } 4077 }
4072 4078
4073 firstFormat = FALSE; 4079 firstFormat = FALSE;
4074 changed = TRUE; 4080 changed = TRUE;
4075 invalid = -1; 4081 invalid = -1;
4076 //##### string()->setTextChanged( FALSE ); 4082 //##### string()->setTextChanged( FALSE );
4077} 4083}
4078 4084
4079int QTextParagraph::lineHeightOfChar( int i, int *bl, int *y ) const 4085int QTextParagraph::lineHeightOfChar( int i, int *bl, int *y ) const
4080{ 4086{
4081 if ( !isValid() ) 4087 if ( !isValid() )
4082 ( (QTextParagraph*)this )->format(); 4088 ( (QTextParagraph*)this )->format();
4083 4089
4084 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.end(); 4090 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.end();
4085 --it; 4091 --it;
4086 for ( ;; ) { 4092 for ( ;; ) {
4087 if ( i >= it.key() ) { 4093 if ( i >= it.key() ) {
4088 if ( bl ) 4094 if ( bl )
4089 *bl = ( *it )->baseLine; 4095 *bl = ( *it )->baseLine;
4090 if ( y ) 4096 if ( y )
4091 *y = ( *it )->y; 4097 *y = ( *it )->y;
4092 return ( *it )->h; 4098 return ( *it )->h;
4093 } 4099 }
4094 if ( it == lineStarts.begin() ) 4100 if ( it == lineStarts.begin() )
4095 break; 4101 break;
4096 --it; 4102 --it;
4097 } 4103 }
4098 4104
4099 qWarning( "QTextParagraph::lineHeightOfChar: couldn't find lh for %d", i ); 4105 owarn << "QTextParagraph::lineHeightOfChar: couldn't find lh for " << i << "" << oendl;
4100 return 15; 4106 return 15;
4101} 4107}
4102 4108
4103QTextStringChar *QTextParagraph::lineStartOfChar( int i, int *index, int *line ) const 4109QTextStringChar *QTextParagraph::lineStartOfChar( int i, int *index, int *line ) const
4104{ 4110{
4105 if ( !isValid() ) 4111 if ( !isValid() )
4106 ( (QTextParagraph*)this )->format(); 4112 ( (QTextParagraph*)this )->format();
4107 4113
4108 int l = (int)lineStarts.count() - 1; 4114 int l = (int)lineStarts.count() - 1;
4109 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.end(); 4115 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.end();
4110 --it; 4116 --it;
4111 for ( ;; ) { 4117 for ( ;; ) {
4112 if ( i >= it.key() ) { 4118 if ( i >= it.key() ) {
4113 if ( index ) 4119 if ( index )
4114 *index = it.key(); 4120 *index = it.key();
4115 if ( line ) 4121 if ( line )
4116 *line = l; 4122 *line = l;
4117 return &str->at( it.key() ); 4123 return &str->at( it.key() );
4118 } 4124 }
4119 if ( it == lineStarts.begin() ) 4125 if ( it == lineStarts.begin() )
4120 break; 4126 break;
4121 --it; 4127 --it;
4122 --l; 4128 --l;
4123 } 4129 }
4124 4130
4125 qWarning( "QTextParagraph::lineStartOfChar: couldn't find %d", i ); 4131 owarn << "QTextParagraph::lineStartOfChar: couldn't find " << i << "" << oendl;
4126 return 0; 4132 return 0;
4127} 4133}
4128 4134
4129int QTextParagraph::lines() const 4135int QTextParagraph::lines() const
4130{ 4136{
4131 if ( !isValid() ) 4137 if ( !isValid() )
4132 ( (QTextParagraph*)this )->format(); 4138 ( (QTextParagraph*)this )->format();
4133 4139
4134 return (int)lineStarts.count(); 4140 return (int)lineStarts.count();
4135} 4141}
4136 4142
4137QTextStringChar *QTextParagraph::lineStartOfLine( int line, int *index ) const 4143QTextStringChar *QTextParagraph::lineStartOfLine( int line, int *index ) const
4138{ 4144{
4139 if ( !isValid() ) 4145 if ( !isValid() )
4140 ( (QTextParagraph*)this )->format(); 4146 ( (QTextParagraph*)this )->format();
4141 4147
4142 if ( line >= 0 && line < (int)lineStarts.count() ) { 4148 if ( line >= 0 && line < (int)lineStarts.count() ) {
4143 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin(); 4149 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
4144 while ( line-- > 0 ) 4150 while ( line-- > 0 )
4145 ++it; 4151 ++it;
4146 int i = it.key(); 4152 int i = it.key();
4147 if ( index ) 4153 if ( index )
4148 *index = i; 4154 *index = i;
4149 return &str->at( i ); 4155 return &str->at( i );
4150 } 4156 }
4151 4157
4152 qWarning( "QTextParagraph::lineStartOfLine: couldn't find %d", line ); 4158 owarn << "QTextParagraph::lineStartOfLine: couldn't find " << line << "" << oendl;
4153 return 0; 4159 return 0;
4154} 4160}
4155 4161
4156int QTextParagraph::leftGap() const 4162int QTextParagraph::leftGap() const
4157{ 4163{
4158 if ( !isValid() ) 4164 if ( !isValid() )
4159 ( (QTextParagraph*)this )->format(); 4165 ( (QTextParagraph*)this )->format();
4160 4166
4161 int line = 0; 4167 int line = 0;
4162 int x = str->at(0).x; /* set x to x of first char */ 4168 int x = str->at(0).x; /* set x to x of first char */
4163 if ( str->isBidi() ) { 4169 if ( str->isBidi() ) {
4164 for ( int i = 1; i < str->length()-1; ++i ) 4170 for ( int i = 1; i < str->length()-1; ++i )
4165 x = QMIN(x, str->at(i).x); 4171 x = QMIN(x, str->at(i).x);
4166 return x; 4172 return x;
4167 } 4173 }
4168 4174
4169 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin(); 4175 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
4170 while (line < (int)lineStarts.count()) { 4176 while (line < (int)lineStarts.count()) {
4171 int i = it.key(); /* char index */ 4177 int i = it.key(); /* char index */
4172 x = QMIN(x, str->at(i).x); 4178 x = QMIN(x, str->at(i).x);
4173 ++it; 4179 ++it;
4174 ++line; 4180 ++line;
4175 } 4181 }
4176 return x; 4182 return x;
4177} 4183}
4178 4184
4179void QTextParagraph::setFormat( int index, int len, QTextFormat *f, bool useCollection, int flags ) 4185void QTextParagraph::setFormat( int index, int len, QTextFormat *f, bool useCollection, int flags )
4180{ 4186{
4181 if ( !f ) 4187 if ( !f )
4182 return; 4188 return;
4183 if ( index < 0 ) 4189 if ( index < 0 )
4184 index = 0; 4190 index = 0;
4185 if ( index > str->length() - 1 ) 4191 if ( index > str->length() - 1 )
4186 index = str->length() - 1; 4192 index = str->length() - 1;
4187 if ( index + len >= str->length() ) 4193 if ( index + len >= str->length() )
4188 len = str->length() - index; 4194 len = str->length() - index;
4189 4195
4190 QTextFormatCollection *fc = 0; 4196 QTextFormatCollection *fc = 0;
4191 if ( useCollection ) 4197 if ( useCollection )
4192 fc = formatCollection(); 4198 fc = formatCollection();
4193 QTextFormat *of; 4199 QTextFormat *of;
4194 for ( int i = 0; i < len; ++i ) { 4200 for ( int i = 0; i < len; ++i ) {
4195 of = str->at( i + index ).format(); 4201 of = str->at( i + index ).format();
4196 if ( !changed && f->key() != of->key() ) 4202 if ( !changed && f->key() != of->key() )
4197 changed = TRUE; 4203 changed = TRUE;
4198 if ( invalid == -1 && 4204 if ( invalid == -1 &&
4199 ( f->font().family() != of->font().family() || 4205 ( f->font().family() != of->font().family() ||
4200 f->font().pointSize() != of->font().pointSize() || 4206 f->font().pointSize() != of->font().pointSize() ||
4201 f->font().weight() != of->font().weight() || 4207 f->font().weight() != of->font().weight() ||
4202 f->font().italic() != of->font().italic() || 4208 f->font().italic() != of->font().italic() ||
4203 f->vAlign() != of->vAlign() ) ) { 4209 f->vAlign() != of->vAlign() ) ) {
4204 invalidate( 0 ); 4210 invalidate( 0 );
4205 } 4211 }
4206 if ( flags == -1 || flags == QTextFormat::Format || !fc ) { 4212 if ( flags == -1 || flags == QTextFormat::Format || !fc ) {
4207 if ( fc ) 4213 if ( fc )
4208 f = fc->format( f ); 4214 f = fc->format( f );
4209 str->setFormat( i + index, f, useCollection ); 4215 str->setFormat( i + index, f, useCollection );
4210 } else { 4216 } else {
4211 QTextFormat *fm = fc->format( of, f, flags ); 4217 QTextFormat *fm = fc->format( of, f, flags );
4212 str->setFormat( i + index, fm, useCollection ); 4218 str->setFormat( i + index, fm, useCollection );
4213 } 4219 }
4214 } 4220 }
4215} 4221}
4216 4222
4217void QTextParagraph::indent( int *oldIndent, int *newIndent ) 4223void QTextParagraph::indent( int *oldIndent, int *newIndent )
4218{ 4224{
4219 if ( !hasdoc || !document()->indent() || isListItem() ) { 4225 if ( !hasdoc || !document()->indent() || isListItem() ) {
4220 if ( oldIndent ) 4226 if ( oldIndent )
4221 *oldIndent = 0; 4227 *oldIndent = 0;
4222 if ( newIndent ) 4228 if ( newIndent )
4223 *newIndent = 0; 4229 *newIndent = 0;
4224 if ( oldIndent && newIndent ) 4230 if ( oldIndent && newIndent )
4225 *newIndent = *oldIndent; 4231 *newIndent = *oldIndent;
4226 return; 4232 return;
4227 } 4233 }
4228 document()->indent()->indent( document(), this, oldIndent, newIndent ); 4234 document()->indent()->indent( document(), this, oldIndent, newIndent );
4229} 4235}
4230 4236
4231void QTextParagraph::paint( QPainter &painter, const QColorGroup &cg, QTextCursor *cursor, bool drawSelections, 4237void QTextParagraph::paint( QPainter &painter, const QColorGroup &cg, QTextCursor *cursor, bool drawSelections,
4232 int clipx, int clipy, int clipw, int cliph ) 4238 int clipx, int clipy, int clipw, int cliph )
4233{ 4239{
4234 if ( !visible ) 4240 if ( !visible )
4235 return; 4241 return;
4236 QTextStringChar *chr = 0; 4242 QTextStringChar *chr = 0;
4237 int i, y, h, baseLine, xstart, xend; 4243 int i, y, h, baseLine, xstart, xend;
4238 i = y =h = baseLine = 0; 4244 i = y =h = baseLine = 0;
4239 QRect cursorRect; 4245 QRect cursorRect;
4240 drawSelections &= ( mSelections != 0 ); 4246 drawSelections &= ( mSelections != 0 );
4241 // macintosh full-width selection style 4247 // macintosh full-width selection style
4242 bool fullWidthStyle = FALSE; 4248 bool fullWidthStyle = FALSE;
4243 int fullSelectionWidth = 0; 4249 int fullSelectionWidth = 0;
4244 if ( drawSelections && fullWidthStyle ) 4250 if ( drawSelections && fullWidthStyle )
4245 fullSelectionWidth = (hasdoc ? document()->width() : r.width()); 4251 fullSelectionWidth = (hasdoc ? document()->width() : r.width());
4246 4252
4247 QString qstr = str->toString(); 4253 QString qstr = str->toString();
4248 // ### workaround so that \n are not drawn, actually this should 4254 // ### workaround so that \n are not drawn, actually this should
@@ -5604,193 +5610,193 @@ QTextFormat *QTextFormatCollection::format( QTextFormat *f )
5604 return lastFormat; 5610 return lastFormat;
5605 } 5611 }
5606 5612
5607 if ( f == lastFormat || ( lastFormat && f->key() == lastFormat->key() ) ) { 5613 if ( f == lastFormat || ( lastFormat && f->key() == lastFormat->key() ) ) {
5608 lastFormat->addRef(); 5614 lastFormat->addRef();
5609 return lastFormat; 5615 return lastFormat;
5610 } 5616 }
5611 5617
5612 QTextFormat *fm = cKey.find( f->key() ); 5618 QTextFormat *fm = cKey.find( f->key() );
5613 if ( fm ) { 5619 if ( fm ) {
5614 lastFormat = fm; 5620 lastFormat = fm;
5615 lastFormat->addRef(); 5621 lastFormat->addRef();
5616 return lastFormat; 5622 return lastFormat;
5617 } 5623 }
5618 5624
5619 if ( f->key() == defFormat->key() ) 5625 if ( f->key() == defFormat->key() )
5620 return defFormat; 5626 return defFormat;
5621 5627
5622 lastFormat = createFormat( *f ); 5628 lastFormat = createFormat( *f );
5623 lastFormat->collection = this; 5629 lastFormat->collection = this;
5624 cKey.insert( lastFormat->key(), lastFormat ); 5630 cKey.insert( lastFormat->key(), lastFormat );
5625 return lastFormat; 5631 return lastFormat;
5626} 5632}
5627 5633
5628QTextFormat *QTextFormatCollection::format( QTextFormat *of, QTextFormat *nf, int flags ) 5634QTextFormat *QTextFormatCollection::format( QTextFormat *of, QTextFormat *nf, int flags )
5629{ 5635{
5630 if ( cres && kof == of->key() && knf == nf->key() && cflags == flags ) { 5636 if ( cres && kof == of->key() && knf == nf->key() && cflags == flags ) {
5631 cres->addRef(); 5637 cres->addRef();
5632 return cres; 5638 return cres;
5633 } 5639 }
5634 5640
5635 cres = createFormat( *of ); 5641 cres = createFormat( *of );
5636 kof = of->key(); 5642 kof = of->key();
5637 knf = nf->key(); 5643 knf = nf->key();
5638 cflags = flags; 5644 cflags = flags;
5639 if ( flags & QTextFormat::Bold ) 5645 if ( flags & QTextFormat::Bold )
5640 cres->fn.setBold( nf->fn.bold() ); 5646 cres->fn.setBold( nf->fn.bold() );
5641 if ( flags & QTextFormat::Italic ) 5647 if ( flags & QTextFormat::Italic )
5642 cres->fn.setItalic( nf->fn.italic() ); 5648 cres->fn.setItalic( nf->fn.italic() );
5643 if ( flags & QTextFormat::Underline ) 5649 if ( flags & QTextFormat::Underline )
5644 cres->fn.setUnderline( nf->fn.underline() ); 5650 cres->fn.setUnderline( nf->fn.underline() );
5645 if ( flags & QTextFormat::StrikeOut ) 5651 if ( flags & QTextFormat::StrikeOut )
5646 cres->fn.setStrikeOut( nf->fn.strikeOut() ); 5652 cres->fn.setStrikeOut( nf->fn.strikeOut() );
5647 if ( flags & QTextFormat::Family ) 5653 if ( flags & QTextFormat::Family )
5648 cres->fn.setFamily( nf->fn.family() ); 5654 cres->fn.setFamily( nf->fn.family() );
5649 if ( flags & QTextFormat::Size ) { 5655 if ( flags & QTextFormat::Size ) {
5650 if ( of->usePixelSizes ) 5656 if ( of->usePixelSizes )
5651 cres->fn.setPixelSize( nf->fn.pixelSize() ); 5657 cres->fn.setPixelSize( nf->fn.pixelSize() );
5652 else 5658 else
5653 cres->fn.setPointSize( nf->fn.pointSize() ); 5659 cres->fn.setPointSize( nf->fn.pointSize() );
5654 } 5660 }
5655 if ( flags & QTextFormat::Color ) 5661 if ( flags & QTextFormat::Color )
5656 cres->col = nf->col; 5662 cres->col = nf->col;
5657 if ( flags & QTextFormat::Misspelled ) 5663 if ( flags & QTextFormat::Misspelled )
5658 cres->missp = nf->missp; 5664 cres->missp = nf->missp;
5659 if ( flags & QTextFormat::VAlign ) 5665 if ( flags & QTextFormat::VAlign )
5660 cres->ha = nf->ha; 5666 cres->ha = nf->ha;
5661 cres->update(); 5667 cres->update();
5662 5668
5663 QTextFormat *fm = cKey.find( cres->key() ); 5669 QTextFormat *fm = cKey.find( cres->key() );
5664 if ( !fm ) { 5670 if ( !fm ) {
5665 cres->collection = this; 5671 cres->collection = this;
5666 cKey.insert( cres->key(), cres ); 5672 cKey.insert( cres->key(), cres );
5667 } else { 5673 } else {
5668 delete cres; 5674 delete cres;
5669 cres = fm; 5675 cres = fm;
5670 cres->addRef(); 5676 cres->addRef();
5671 } 5677 }
5672 5678
5673 return cres; 5679 return cres;
5674} 5680}
5675 5681
5676QTextFormat *QTextFormatCollection::format( const QFont &f, const QColor &c ) 5682QTextFormat *QTextFormatCollection::format( const QFont &f, const QColor &c )
5677{ 5683{
5678 if ( cachedFormat && cfont == f && ccol == c ) { 5684 if ( cachedFormat && cfont == f && ccol == c ) {
5679 cachedFormat->addRef(); 5685 cachedFormat->addRef();
5680 return cachedFormat; 5686 return cachedFormat;
5681 } 5687 }
5682 5688
5683 QString key = QTextFormat::getKey( f, c, FALSE, QTextFormat::AlignNormal ); 5689 QString key = QTextFormat::getKey( f, c, FALSE, QTextFormat::AlignNormal );
5684 cachedFormat = cKey.find( key ); 5690 cachedFormat = cKey.find( key );
5685 cfont = f; 5691 cfont = f;
5686 ccol = c; 5692 ccol = c;
5687 5693
5688 if ( cachedFormat ) { 5694 if ( cachedFormat ) {
5689 cachedFormat->addRef(); 5695 cachedFormat->addRef();
5690 return cachedFormat; 5696 return cachedFormat;
5691 } 5697 }
5692 5698
5693 if ( key == defFormat->key() ) 5699 if ( key == defFormat->key() )
5694 return defFormat; 5700 return defFormat;
5695 5701
5696 cachedFormat = createFormat( f, c ); 5702 cachedFormat = createFormat( f, c );
5697 cachedFormat->collection = this; 5703 cachedFormat->collection = this;
5698 cKey.insert( cachedFormat->key(), cachedFormat ); 5704 cKey.insert( cachedFormat->key(), cachedFormat );
5699 if ( cachedFormat->key() != key ) 5705 if ( cachedFormat->key() != key )
5700 qWarning("ASSERT: keys for format not identical: '%s '%s'", cachedFormat->key().latin1(), key.latin1() ); 5706 owarn << "ASSERT: keys for format not identical: '" << cachedFormat->key().latin1() << " '" << key.latin1() << "'" << oendl;
5701 return cachedFormat; 5707 return cachedFormat;
5702} 5708}
5703 5709
5704void QTextFormatCollection::remove( QTextFormat *f ) 5710void QTextFormatCollection::remove( QTextFormat *f )
5705{ 5711{
5706 if ( lastFormat == f ) 5712 if ( lastFormat == f )
5707 lastFormat = 0; 5713 lastFormat = 0;
5708 if ( cres == f ) 5714 if ( cres == f )
5709 cres = 0; 5715 cres = 0;
5710 if ( cachedFormat == f ) 5716 if ( cachedFormat == f )
5711 cachedFormat = 0; 5717 cachedFormat = 0;
5712 cKey.remove( f->key() ); 5718 cKey.remove( f->key() );
5713} 5719}
5714 5720
5715#define UPDATE( up, lo, rest ) \ 5721#define UPDATE( up, lo, rest ) \
5716 if ( font.lo##rest() != defFormat->fn.lo##rest() && fm->fn.lo##rest() == defFormat->fn.lo##rest() ) \ 5722 if ( font.lo##rest() != defFormat->fn.lo##rest() && fm->fn.lo##rest() == defFormat->fn.lo##rest() ) \
5717 fm->fn.set##up##rest( font.lo##rest() ) 5723 fm->fn.set##up##rest( font.lo##rest() )
5718 5724
5719void QTextFormatCollection::updateDefaultFormat( const QFont &font, const QColor &color, QStyleSheet *sheet ) 5725void QTextFormatCollection::updateDefaultFormat( const QFont &font, const QColor &color, QStyleSheet *sheet )
5720{ 5726{
5721 QDictIterator<QTextFormat> it( cKey ); 5727 QDictIterator<QTextFormat> it( cKey );
5722 QTextFormat *fm; 5728 QTextFormat *fm;
5723 bool usePixels = font.pointSize() == -1; 5729 bool usePixels = font.pointSize() == -1;
5724 bool changeSize = usePixels ? font.pixelSize() != defFormat->fn.pixelSize() : 5730 bool changeSize = usePixels ? font.pixelSize() != defFormat->fn.pixelSize() :
5725 font.pointSize() != defFormat->fn.pointSize(); 5731 font.pointSize() != defFormat->fn.pointSize();
5726 int base = usePixels ? font.pixelSize() : font.pointSize(); 5732 int base = usePixels ? font.pixelSize() : font.pointSize();
5727 while ( ( fm = it.current() ) ) { 5733 while ( ( fm = it.current() ) ) {
5728 ++it; 5734 ++it;
5729 UPDATE( F, f, amily ); 5735 UPDATE( F, f, amily );
5730 UPDATE( W, w, eight ); 5736 UPDATE( W, w, eight );
5731 UPDATE( B, b, old ); 5737 UPDATE( B, b, old );
5732 UPDATE( I, i, talic ); 5738 UPDATE( I, i, talic );
5733 UPDATE( U, u, nderline ); 5739 UPDATE( U, u, nderline );
5734 if ( changeSize ) { 5740 if ( changeSize ) {
5735 fm->stdSize = base; 5741 fm->stdSize = base;
5736 fm->usePixelSizes = usePixels; 5742 fm->usePixelSizes = usePixels;
5737 if ( usePixels ) 5743 if ( usePixels )
5738 fm->fn.setPixelSize( fm->stdSize ); 5744 fm->fn.setPixelSize( fm->stdSize );
5739 else 5745 else
5740 fm->fn.setPointSize( fm->stdSize ); 5746 fm->fn.setPointSize( fm->stdSize );
5741 sheet->scaleFont( fm->fn, fm->logicalFontSize ); 5747 sheet->scaleFont( fm->fn, fm->logicalFontSize );
5742 } 5748 }
5743 if ( color.isValid() && color != defFormat->col && fm->col == defFormat->col ) 5749 if ( color.isValid() && color != defFormat->col && fm->col == defFormat->col )
5744 fm->col = color; 5750 fm->col = color;
5745 fm->update(); 5751 fm->update();
5746 } 5752 }
5747 5753
5748 defFormat->fn = font; 5754 defFormat->fn = font;
5749 defFormat->col = color; 5755 defFormat->col = color;
5750 defFormat->update(); 5756 defFormat->update();
5751 defFormat->stdSize = base; 5757 defFormat->stdSize = base;
5752 defFormat->usePixelSizes = usePixels; 5758 defFormat->usePixelSizes = usePixels;
5753 5759
5754 updateKeys(); 5760 updateKeys();
5755} 5761}
5756 5762
5757// the keys in cKey have changed, rebuild the hashtable 5763// the keys in cKey have changed, rebuild the hashtable
5758void QTextFormatCollection::updateKeys() 5764void QTextFormatCollection::updateKeys()
5759{ 5765{
5760 if ( cKey.isEmpty() ) 5766 if ( cKey.isEmpty() )
5761 return; 5767 return;
5762 cKey.setAutoDelete( FALSE ); 5768 cKey.setAutoDelete( FALSE );
5763 QTextFormat** formats = new QTextFormat*[ cKey.count() + 1 ]; 5769 QTextFormat** formats = new QTextFormat*[ cKey.count() + 1 ];
5764 QTextFormat **f = formats; 5770 QTextFormat **f = formats;
5765 QDictIterator<QTextFormat> it( cKey ); 5771 QDictIterator<QTextFormat> it( cKey );
5766 while ( ( *f = it.current() ) ) { 5772 while ( ( *f = it.current() ) ) {
5767 ++it; 5773 ++it;
5768 ++f; 5774 ++f;
5769 } 5775 }
5770 cKey.clear(); 5776 cKey.clear();
5771 for ( f = formats; *f; f++ ) 5777 for ( f = formats; *f; f++ )
5772 cKey.insert( (*f)->key(), *f ); 5778 cKey.insert( (*f)->key(), *f );
5773 cKey.setAutoDelete( TRUE ); 5779 cKey.setAutoDelete( TRUE );
5774 delete [] formats; 5780 delete [] formats;
5775} 5781}
5776 5782
5777 5783
5778 5784
5779// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5785// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5780 5786
5781void QTextFormat::setBold( bool b ) 5787void QTextFormat::setBold( bool b )
5782{ 5788{
5783 if ( b == fn.bold() ) 5789 if ( b == fn.bold() )
5784 return; 5790 return;
5785 fn.setBold( b ); 5791 fn.setBold( b );
5786 update(); 5792 update();
5787} 5793}
5788 5794
5789void QTextFormat::setMisspelled( bool b ) 5795void QTextFormat::setMisspelled( bool b )
5790{ 5796{
5791 if ( b == (bool)missp ) 5797 if ( b == (bool)missp )
5792 return; 5798 return;
5793 missp = b; 5799 missp = b;
5794 update(); 5800 update();
5795} 5801}
5796 5802
@@ -5990,197 +5996,197 @@ QTextFormat QTextFormat::makeTextFormat( const QStyleSheetItem *style, const QMa
5990 if ( attr.contains("size") ) { 5996 if ( attr.contains("size") ) {
5991 QString a = attr["size"]; 5997 QString a = attr["size"];
5992 int n = a.toInt(); 5998 int n = a.toInt();
5993 if ( a[0] == '+' || a[0] == '-' ) 5999 if ( a[0] == '+' || a[0] == '-' )
5994 n += format.logicalFontSize; 6000 n += format.logicalFontSize;
5995 format.logicalFontSize = n; 6001 format.logicalFontSize = n;
5996 if ( format.usePixelSizes ) 6002 if ( format.usePixelSizes )
5997 format.fn.setPixelSize( format.stdSize ); 6003 format.fn.setPixelSize( format.stdSize );
5998 else 6004 else
5999 format.fn.setPointSize( format.stdSize ); 6005 format.fn.setPointSize( format.stdSize );
6000 style->styleSheet()->scaleFont( format.fn, format.logicalFontSize ); 6006 style->styleSheet()->scaleFont( format.fn, format.logicalFontSize );
6001 } 6007 }
6002 } 6008 }
6003 if ( attr.contains("style" ) ) { 6009 if ( attr.contains("style" ) ) {
6004 QString a = attr["style"]; 6010 QString a = attr["style"];
6005 for ( int s = 0; s < a.contains(';')+1; s++ ) { 6011 for ( int s = 0; s < a.contains(';')+1; s++ ) {
6006 QString style = QTextDocument::section( a, ";", s, s ); 6012 QString style = QTextDocument::section( a, ";", s, s );
6007 if ( style.startsWith("font-size:" ) && QTextDocument::endsWith(style, "pt") ) { 6013 if ( style.startsWith("font-size:" ) && QTextDocument::endsWith(style, "pt") ) {
6008 format.logicalFontSize = 0; 6014 format.logicalFontSize = 0;
6009 format.setPointSize( int( scaleFontsFactor * style.mid( 10, style.length() - 12 ).toInt() ) ); 6015 format.setPointSize( int( scaleFontsFactor * style.mid( 10, style.length() - 12 ).toInt() ) );
6010 } if ( style.startsWith("font-style:" ) ) { 6016 } if ( style.startsWith("font-style:" ) ) {
6011 QString s = style.mid( 11 ).stripWhiteSpace(); 6017 QString s = style.mid( 11 ).stripWhiteSpace();
6012 if ( s == "normal" ) 6018 if ( s == "normal" )
6013 format.fn.setItalic( FALSE ); 6019 format.fn.setItalic( FALSE );
6014 else if ( s == "italic" || s == "oblique" ) 6020 else if ( s == "italic" || s == "oblique" )
6015 format.fn.setItalic( TRUE ); 6021 format.fn.setItalic( TRUE );
6016 } else if ( style.startsWith("font-weight:" ) ) { 6022 } else if ( style.startsWith("font-weight:" ) ) {
6017 QString s = style.mid( 12 ); 6023 QString s = style.mid( 12 );
6018 bool ok = TRUE; 6024 bool ok = TRUE;
6019 int n = s.toInt( &ok ); 6025 int n = s.toInt( &ok );
6020 if ( ok ) 6026 if ( ok )
6021 format.fn.setWeight( n/8 ); 6027 format.fn.setWeight( n/8 );
6022 } else if ( style.startsWith("font-family:" ) ) { 6028 } else if ( style.startsWith("font-family:" ) ) {
6023 format.fn.setFamily( QTextDocument::section(style.mid(12),",",0,0).stripWhiteSpace() ); 6029 format.fn.setFamily( QTextDocument::section(style.mid(12),",",0,0).stripWhiteSpace() );
6024 } else if ( style.startsWith("text-decoration:" ) ) { 6030 } else if ( style.startsWith("text-decoration:" ) ) {
6025 QString s = style.mid( 16 ).stripWhiteSpace(); 6031 QString s = style.mid( 16 ).stripWhiteSpace();
6026 format.fn.setUnderline( s == "underline" ); 6032 format.fn.setUnderline( s == "underline" );
6027 } else if ( style.startsWith("vertical-align:" ) ) { 6033 } else if ( style.startsWith("vertical-align:" ) ) {
6028 QString s = style.mid( 15 ).stripWhiteSpace(); 6034 QString s = style.mid( 15 ).stripWhiteSpace();
6029 if ( s == "sub" ) 6035 if ( s == "sub" )
6030 format.setVAlign( QTextFormat::AlignSubScript ); 6036 format.setVAlign( QTextFormat::AlignSubScript );
6031 else if ( s == "super" ) 6037 else if ( s == "super" )
6032 format.setVAlign( QTextFormat::AlignSuperScript ); 6038 format.setVAlign( QTextFormat::AlignSuperScript );
6033 else 6039 else
6034 format.setVAlign( QTextFormat::AlignNormal ); 6040 format.setVAlign( QTextFormat::AlignNormal );
6035 } else if ( style.startsWith("color:" ) ) { 6041 } else if ( style.startsWith("color:" ) ) {
6036 format.col.setNamedColor( style.mid(6) ); 6042 format.col.setNamedColor( style.mid(6) );
6037 format.linkColor = FALSE; 6043 format.linkColor = FALSE;
6038 } 6044 }
6039 } 6045 }
6040 } 6046 }
6041 6047
6042 format.update(); 6048 format.update();
6043 return format; 6049 return format;
6044} 6050}
6045 6051
6046struct QPixmapInt 6052struct QPixmapInt
6047{ 6053{
6048 QPixmapInt() : ref( 0 ) {} 6054 QPixmapInt() : ref( 0 ) {}
6049 QPixmap pm; 6055 QPixmap pm;
6050 int ref; 6056 int ref;
6051}; 6057};
6052 6058
6053static QMap<QString, QPixmapInt> *pixmap_map = 0; 6059static QMap<QString, QPixmapInt> *pixmap_map = 0;
6054 6060
6055QTextImage::QTextImage( QTextDocument *p, const QMap<QString, QString> &attr, const QString& context, 6061QTextImage::QTextImage( QTextDocument *p, const QMap<QString, QString> &attr, const QString& context,
6056 QMimeSourceFactory &factory ) 6062 QMimeSourceFactory &factory )
6057 : QTextCustomItem( p ) 6063 : QTextCustomItem( p )
6058{ 6064{
6059 width = height = 0; 6065 width = height = 0;
6060 if ( attr.contains("width") ) 6066 if ( attr.contains("width") )
6061 width = attr["width"].toInt(); 6067 width = attr["width"].toInt();
6062 if ( attr.contains("height") ) 6068 if ( attr.contains("height") )
6063 height = attr["height"].toInt(); 6069 height = attr["height"].toInt();
6064 6070
6065 reg = 0; 6071 reg = 0;
6066 QString imageName = attr["src"]; 6072 QString imageName = attr["src"];
6067 6073
6068 if (!imageName) 6074 if (!imageName)
6069 imageName = attr["source"]; 6075 imageName = attr["source"];
6070 6076
6071 if ( !imageName.isEmpty() ) { 6077 if ( !imageName.isEmpty() ) {
6072 imgId = QString( "%1,%2,%3,%4" ).arg( imageName ).arg( width ).arg( height ).arg( (ulong)&factory ); 6078 imgId = QString( "%1,%2,%3,%4" ).arg( imageName ).arg( width ).arg( height ).arg( (ulong)&factory );
6073 if ( !pixmap_map ) 6079 if ( !pixmap_map )
6074 pixmap_map = new QMap<QString, QPixmapInt>; 6080 pixmap_map = new QMap<QString, QPixmapInt>;
6075 if ( pixmap_map->contains( imgId ) ) { 6081 if ( pixmap_map->contains( imgId ) ) {
6076 QPixmapInt& pmi = pixmap_map->operator[](imgId); 6082 QPixmapInt& pmi = pixmap_map->operator[](imgId);
6077 pm = pmi.pm; 6083 pm = pmi.pm;
6078 pmi.ref++; 6084 pmi.ref++;
6079 width = pm.width(); 6085 width = pm.width();
6080 height = pm.height(); 6086 height = pm.height();
6081 } else { 6087 } else {
6082 QImage img; 6088 QImage img;
6083 const QMimeSource* m = 6089 const QMimeSource* m =
6084 factory.data( imageName, context ); 6090 factory.data( imageName, context );
6085 if ( !m ) { 6091 if ( !m ) {
6086 qWarning("QTextImage: no mimesource for %s", imageName.latin1() ); 6092 owarn << "QTextImage: no mimesource for " << imageName.latin1() << "" << oendl;
6087 } 6093 }
6088 else { 6094 else {
6089 if ( !QImageDrag::decode( m, img ) ) { 6095 if ( !QImageDrag::decode( m, img ) ) {
6090 qWarning("QTextImage: cannot decode %s", imageName.latin1() ); 6096 owarn << "QTextImage: cannot decode " << imageName.latin1() << "" << oendl;
6091 } 6097 }
6092 } 6098 }
6093 6099
6094 if ( !img.isNull() ) { 6100 if ( !img.isNull() ) {
6095 if ( width == 0 ) { 6101 if ( width == 0 ) {
6096 width = img.width(); 6102 width = img.width();
6097 if ( height != 0 ) { 6103 if ( height != 0 ) {
6098 width = img.width() * height / img.height(); 6104 width = img.width() * height / img.height();
6099 } 6105 }
6100 } 6106 }
6101 if ( height == 0 ) { 6107 if ( height == 0 ) {
6102 height = img.height(); 6108 height = img.height();
6103 if ( width != img.width() ) { 6109 if ( width != img.width() ) {
6104 height = img.height() * width / img.width(); 6110 height = img.height() * width / img.width();
6105 } 6111 }
6106 } 6112 }
6107 if ( img.width() != width || img.height() != height ){ 6113 if ( img.width() != width || img.height() != height ){
6108#ifndef QT_NO_IMAGE_SMOOTHSCALE 6114#ifndef QT_NO_IMAGE_SMOOTHSCALE
6109 img = img.smoothScale(width, height); 6115 img = img.smoothScale(width, height);
6110#endif 6116#endif
6111 width = img.width(); 6117 width = img.width();
6112 height = img.height(); 6118 height = img.height();
6113 } 6119 }
6114 pm.convertFromImage( img ); 6120 pm.convertFromImage( img );
6115 } 6121 }
6116 if ( !pm.isNull() ) { 6122 if ( !pm.isNull() ) {
6117 QPixmapInt& pmi = pixmap_map->operator[](imgId); 6123 QPixmapInt& pmi = pixmap_map->operator[](imgId);
6118 pmi.pm = pm; 6124 pmi.pm = pm;
6119 pmi.ref++; 6125 pmi.ref++;
6120 } 6126 }
6121 } 6127 }
6122 if ( pm.mask() ) { 6128 if ( pm.mask() ) {
6123 QRegion mask( *pm.mask() ); 6129 QRegion mask( *pm.mask() );
6124 QRegion all( 0, 0, pm.width(), pm.height() ); 6130 QRegion all( 0, 0, pm.width(), pm.height() );
6125 reg = new QRegion( all.subtract( mask ) ); 6131 reg = new QRegion( all.subtract( mask ) );
6126 } 6132 }
6127 } 6133 }
6128 6134
6129 if ( pm.isNull() && (width*height)==0 ) 6135 if ( pm.isNull() && (width*height)==0 )
6130 width = height = 50; 6136 width = height = 50;
6131 6137
6132 place = PlaceInline; 6138 place = PlaceInline;
6133 if ( attr["align"] == "left" ) 6139 if ( attr["align"] == "left" )
6134 place = PlaceLeft; 6140 place = PlaceLeft;
6135 else if ( attr["align"] == "right" ) 6141 else if ( attr["align"] == "right" )
6136 place = PlaceRight; 6142 place = PlaceRight;
6137 6143
6138 tmpwidth = width; 6144 tmpwidth = width;
6139 tmpheight = height; 6145 tmpheight = height;
6140 6146
6141 attributes = attr; 6147 attributes = attr;
6142} 6148}
6143 6149
6144QTextImage::~QTextImage() 6150QTextImage::~QTextImage()
6145{ 6151{
6146 if ( pixmap_map && pixmap_map->contains( imgId ) ) { 6152 if ( pixmap_map && pixmap_map->contains( imgId ) ) {
6147 QPixmapInt& pmi = pixmap_map->operator[](imgId); 6153 QPixmapInt& pmi = pixmap_map->operator[](imgId);
6148 pmi.ref--; 6154 pmi.ref--;
6149 if ( !pmi.ref ) { 6155 if ( !pmi.ref ) {
6150 pixmap_map->remove( imgId ); 6156 pixmap_map->remove( imgId );
6151 if ( pixmap_map->isEmpty() ) { 6157 if ( pixmap_map->isEmpty() ) {
6152 delete pixmap_map; 6158 delete pixmap_map;
6153 pixmap_map = 0; 6159 pixmap_map = 0;
6154 } 6160 }
6155 } 6161 }
6156 } 6162 }
6157 delete reg; 6163 delete reg;
6158} 6164}
6159 6165
6160QString QTextImage::richText() const 6166QString QTextImage::richText() const
6161{ 6167{
6162 QString s; 6168 QString s;
6163 s += "<img "; 6169 s += "<img ";
6164 QMap<QString, QString>::ConstIterator it = attributes.begin(); 6170 QMap<QString, QString>::ConstIterator it = attributes.begin();
6165 for ( ; it != attributes.end(); ++it ) 6171 for ( ; it != attributes.end(); ++it )
6166 s += it.key() + "=" + *it + " "; 6172 s += it.key() + "=" + *it + " ";
6167 s += ">"; 6173 s += ">";
6168 return s; 6174 return s;
6169} 6175}
6170 6176
6171void QTextImage::adjustToPainter( QPainter* p ) 6177void QTextImage::adjustToPainter( QPainter* p )
6172{ 6178{
6173 width = scale( tmpwidth, p ); 6179 width = scale( tmpwidth, p );
6174 height = scale( tmpheight, p ); 6180 height = scale( tmpheight, p );
6175} 6181}
6176 6182
6177#if !defined(Q_WS_X11) 6183#if !defined(Q_WS_X11)
6178#include <qbitmap.h> 6184#include <qbitmap.h>
6179#include "qcleanuphandler.h" 6185#include "qcleanuphandler.h"
6180static QPixmap *qrt_selection = 0; 6186static QPixmap *qrt_selection = 0;
6181static QSingleCleanupHandler<QPixmap> qrt_cleanup_pixmap; 6187static QSingleCleanupHandler<QPixmap> qrt_cleanup_pixmap;
6182static void qrt_createSelectionPixmap( const QColorGroup &cg ) 6188static void qrt_createSelectionPixmap( const QColorGroup &cg )
6183{ 6189{
6184 qrt_selection = new QPixmap( 2, 2 ); 6190 qrt_selection = new QPixmap( 2, 2 );
6185 qrt_cleanup_pixmap.set( &qrt_selection ); 6191 qrt_cleanup_pixmap.set( &qrt_selection );
6186 qrt_selection->fill( Qt::color0 ); 6192 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 @@
1/**************************************************************************** 1/****************************************************************************
2** $Id$ 2** $Id$
3** 3**
4** Implementation of the internal Qt classes dealing with rich text 4** Implementation of the internal Qt classes dealing with rich text
5** 5**
6** Created : 990101 6** Created : 990101
7** 7**
8** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. 8** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
9** 9**
10** This file is part of the kernel module of the Qt GUI Toolkit. 10** This file is part of the kernel module of the Qt GUI Toolkit.
11** 11**
12** This file may be distributed under the terms of the Q Public License 12** This file may be distributed under the terms of the Q Public License
13** as defined by Trolltech AS of Norway and appearing in the file 13** as defined by Trolltech AS of Norway and appearing in the file
14** LICENSE.QPL included in the packaging of this file. 14** LICENSE.QPL included in the packaging of this file.
15** 15**
16** This file may be distributed and/or modified under the terms of the 16** This file may be distributed and/or modified under the terms of the
17** GNU General Public License version 2 as published by the Free Software 17** GNU General Public License version 2 as published by the Free Software
18** Foundation and appearing in the file LICENSE.GPL included in the 18** Foundation and appearing in the file LICENSE.GPL included in the
19** packaging of this file. 19** packaging of this file.
20** 20**
21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition 21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
22** licenses may use this file in accordance with the Qt Commercial License 22** licenses may use this file in accordance with the Qt Commercial License
23** Agreement provided with the Software. 23** Agreement provided with the Software.
24** 24**
25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27** 27**
28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for 28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
29** information about Qt Commercial License Agreements. 29** information about Qt Commercial License Agreements.
30** See http://www.trolltech.com/qpl/ for QPL licensing information. 30** See http://www.trolltech.com/qpl/ for QPL licensing information.
31** See http://www.trolltech.com/gpl/ for GPL licensing information. 31** See http://www.trolltech.com/gpl/ for GPL licensing information.
32** 32**
33** Contact info@trolltech.com if any conditions of this licensing are 33** Contact info@trolltech.com if any conditions of this licensing are
34** not clear to you. 34** not clear to you.
35** 35**
36**********************************************************************/ 36**********************************************************************/
37 37
38#include <opie2/odebug.h>
39using namespace Opie::Core;
40
38#include "qrichtext_p.h" 41#include "qrichtext_p.h"
39 42
40using namespace Qt3; 43using namespace Qt3;
41 44
42QTextCommand::~QTextCommand() {} 45QTextCommand::~QTextCommand() {}
43QTextCommand::Commands QTextCommand::type() const { return Invalid; } 46QTextCommand::Commands QTextCommand::type() const { return Invalid; }
44 47
45 48
46QTextCustomItem::~QTextCustomItem() {} 49QTextCustomItem::~QTextCustomItem() {}
47void QTextCustomItem::adjustToPainter( QPainter* p){ if ( p ) width = 0; } 50void QTextCustomItem::adjustToPainter( QPainter* p){ if ( p ) width = 0; }
48QTextCustomItem::Placement QTextCustomItem::placement() const { return PlaceInline; } 51QTextCustomItem::Placement QTextCustomItem::placement() const { return PlaceInline; }
49 52
50bool QTextCustomItem::ownLine() const { return FALSE; } 53bool QTextCustomItem::ownLine() const { return FALSE; }
51void QTextCustomItem::resize( int nwidth ){ width = nwidth; } 54void QTextCustomItem::resize( int nwidth ){ width = nwidth; }
52void QTextCustomItem::invalidate() {} 55void QTextCustomItem::invalidate() {}
53 56
54bool QTextCustomItem::isNested() const { return FALSE; } 57bool QTextCustomItem::isNested() const { return FALSE; }
55int QTextCustomItem::minimumWidth() const { return 0; } 58int QTextCustomItem::minimumWidth() const { return 0; }
56 59
57QString QTextCustomItem::richText() const { return QString::null; } 60QString QTextCustomItem::richText() const { return QString::null; }
58 61
59bool QTextCustomItem::enter( QTextCursor *, QTextDocument*&, QTextParagraph *&, int &, int &, int &, bool ) 62bool QTextCustomItem::enter( QTextCursor *, QTextDocument*&, QTextParagraph *&, int &, int &, int &, bool )
60{ 63{
61 return TRUE; 64 return TRUE;
62} 65}
63bool QTextCustomItem::enterAt( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int &, const QPoint & ) 66bool QTextCustomItem::enterAt( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int &, const QPoint & )
64{ 67{
65 return TRUE; 68 return TRUE;
66} 69}
67bool QTextCustomItem::next( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & ) 70bool QTextCustomItem::next( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & )
68{ 71{
69 return TRUE; 72 return TRUE;
70} 73}
71bool QTextCustomItem::prev( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & ) 74bool QTextCustomItem::prev( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & )
72{ 75{
73 return TRUE; 76 return TRUE;
74} 77}
75bool QTextCustomItem::down( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & ) 78bool QTextCustomItem::down( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & )
76{ 79{
77 return TRUE; 80 return TRUE;
78} 81}
79bool QTextCustomItem::up( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & ) 82bool QTextCustomItem::up( QTextCursor *, QTextDocument *&, QTextParagraph *&, int &, int &, int & )
80{ 83{
81 return TRUE; 84 return TRUE;
82} 85}
83 86
84void QTextFlow::setPageSize( int ps ) { pagesize = ps; } 87void QTextFlow::setPageSize( int ps ) { pagesize = ps; }
85bool QTextFlow::isEmpty() { return leftItems.isEmpty() && rightItems.isEmpty(); } 88bool QTextFlow::isEmpty() { return leftItems.isEmpty() && rightItems.isEmpty(); }
86 89
87void QTextTableCell::invalidate() { cached_width = -1; cached_sizehint = -1; } 90void QTextTableCell::invalidate() { cached_width = -1; cached_sizehint = -1; }
88 91
89void QTextTable::invalidate() { cachewidth = -1; } 92void QTextTable::invalidate() { cachewidth = -1; }
90 93
91QTextParagraphData::~QTextParagraphData() {} 94QTextParagraphData::~QTextParagraphData() {}
92void QTextParagraphData::join( QTextParagraphData * ) {} 95void QTextParagraphData::join( QTextParagraphData * ) {}
93 96
94QTextFormatter::~QTextFormatter() {} 97QTextFormatter::~QTextFormatter() {}
95void QTextFormatter::setWrapEnabled( bool b ) { wrapEnabled = b; } 98void QTextFormatter::setWrapEnabled( bool b ) { wrapEnabled = b; }
96void QTextFormatter::setWrapAtColumn( int c ) { wrapColumn = c; } 99void QTextFormatter::setWrapAtColumn( int c ) { wrapColumn = c; }
97 100
98 101
99 102
100int QTextCursor::x() const 103int QTextCursor::x() const
101{ 104{
102 QTextStringChar *c = para->at( idx ); 105 QTextStringChar *c = para->at( idx );
103 int curx = c->x; 106 int curx = c->x;
104 if ( !c->rightToLeft && 107 if ( !c->rightToLeft &&
105 c->c.isSpace() && 108 c->c.isSpace() &&
106 idx > 0 && 109 idx > 0 &&
107 !c->lineStart && 110 !c->lineStart &&
108 ( para->alignment() & Qt3::AlignJustify ) == Qt3::AlignJustify ) 111 ( para->alignment() & Qt3::AlignJustify ) == Qt3::AlignJustify )
109 curx = para->at( idx - 1 )->x + para->string()->width( idx - 1 ); 112 curx = para->at( idx - 1 )->x + para->string()->width( idx - 1 );
110 if ( c->rightToLeft ) 113 if ( c->rightToLeft )
111 curx += para->string()->width( idx ); 114 curx += para->string()->width( idx );
112 return curx; 115 return curx;
113} 116}
114 117
115int QTextCursor::y() const 118int QTextCursor::y() const
116{ 119{
117 int dummy, line; 120 int dummy, line;
118 para->lineStartOfChar( idx, &dummy, &line ); 121 para->lineStartOfChar( idx, &dummy, &line );
119 return para->lineY( line ); 122 return para->lineY( line );
120} 123}
121 124
122int QTextCursor::globalX() const { return totalOffsetX() + para->rect().x() + x(); } 125int QTextCursor::globalX() const { return totalOffsetX() + para->rect().x() + x(); }
123int QTextCursor::globalY() const { return totalOffsetY() + para->rect().y() + y(); } 126int QTextCursor::globalY() const { return totalOffsetY() + para->rect().y() + y(); }
124 127
125QTextDocument *QTextCursor::document() const 128QTextDocument *QTextCursor::document() const
126{ 129{
127 return para ? para->document() : 0; 130 return para ? para->document() : 0;
128} 131}
129 132
130void QTextCursor::gotoPosition( QTextParagraph* p, int index ) 133void QTextCursor::gotoPosition( QTextParagraph* p, int index )
131{ 134{
132 if ( para && p != para ) { 135 if ( para && p != para ) {
133 while ( para->document() != p->document() && !indices.isEmpty() ) 136 while ( para->document() != p->document() && !indices.isEmpty() )
134 pop(); 137 pop();
135 Q_ASSERT( indices.isEmpty() || para->document() == p->document() ); 138 Q_ASSERT( indices.isEmpty() || para->document() == p->document() );
136 } 139 }
137 para = p; 140 para = p;
138 if ( index < 0 || index >= para->length() ) { 141 if ( index < 0 || index >= para->length() ) {
139#if defined(QT_CHECK_RANGE) 142#if defined(QT_CHECK_RANGE)
140 qWarning( "QTextCursor::gotoParagraph Index: %d out of range", index ); 143 owarn << "QTextCursor::gotoParagraph Index: " << index << " out of range" << oendl;
141#endif 144#endif
142 index = index < 0 ? 0 : para->length() - 1; 145 index = index < 0 ? 0 : para->length() - 1;
143 } 146 }
144 147
145 tmpIndex = -1; 148 tmpIndex = -1;
146 idx = index; 149 idx = index;
147} 150}
148 151
149bool QTextDocument::hasSelection( int id, bool visible ) const 152bool QTextDocument::hasSelection( int id, bool visible ) const
150{ 153{
151 return ( selections.find( id ) != selections.end() && 154 return ( selections.find( id ) != selections.end() &&
152 ( !visible || 155 ( !visible ||
153 ( (QTextDocument*)this )->selectionStartCursor( id ) != 156 ( (QTextDocument*)this )->selectionStartCursor( id ) !=
154 ( (QTextDocument*)this )->selectionEndCursor( id ) ) ); 157 ( (QTextDocument*)this )->selectionEndCursor( id ) ) );
155} 158}
156 159
157void QTextDocument::setSelectionStart( int id, const QTextCursor &cursor ) 160void QTextDocument::setSelectionStart( int id, const QTextCursor &cursor )
158{ 161{
159 QTextDocumentSelection sel; 162 QTextDocumentSelection sel;
160 sel.startCursor = cursor; 163 sel.startCursor = cursor;
161 sel.endCursor = cursor; 164 sel.endCursor = cursor;
162 sel.swapped = FALSE; 165 sel.swapped = FALSE;
163 selections[ id ] = sel; 166 selections[ id ] = sel;
164} 167}
165 168
166QTextParagraph *QTextDocument::paragAt( int i ) const 169QTextParagraph *QTextDocument::paragAt( int i ) const
167{ 170{
168 QTextParagraph* p = curParag; 171 QTextParagraph* p = curParag;
169 if ( !p || p->paragId() > i ) 172 if ( !p || p->paragId() > i )
170 p = fParag; 173 p = fParag;
171 while ( p && p->paragId() != i ) 174 while ( p && p->paragId() != i )
172 p = p->next(); 175 p = p->next();
173 ((QTextDocument*)this)->curParag = p; 176 ((QTextDocument*)this)->curParag = p;
174 return p; 177 return p;
175} 178}
176 179
177 180
178QTextFormat::~QTextFormat() 181QTextFormat::~QTextFormat()
179{ 182{
180} 183}
181 184
182QTextFormat::QTextFormat() 185QTextFormat::QTextFormat()
183 : fm( QFontMetrics( fn ) ), linkColor( TRUE ), logicalFontSize( 3 ), stdSize( qApp->font().pointSize() ) 186 : fm( QFontMetrics( fn ) ), linkColor( TRUE ), logicalFontSize( 3 ), stdSize( qApp->font().pointSize() )
184{ 187{
185 ref = 0; 188 ref = 0;
186 189
187 usePixelSizes = FALSE; 190 usePixelSizes = FALSE;
188 if ( stdSize == -1 ) { 191 if ( stdSize == -1 ) {
189 stdSize = qApp->font().pixelSize(); 192 stdSize = qApp->font().pixelSize();
190 usePixelSizes = TRUE; 193 usePixelSizes = TRUE;
191 } 194 }
192 195
193 missp = FALSE; 196 missp = FALSE;
194 ha = AlignNormal; 197 ha = AlignNormal;
195 collection = 0; 198 collection = 0;
196} 199}
197 200
198QTextFormat::QTextFormat( const QStyleSheetItem *style ) 201QTextFormat::QTextFormat( const QStyleSheetItem *style )
199 : fm( QFontMetrics( fn ) ), linkColor( TRUE ), logicalFontSize( 3 ), stdSize( qApp->font().pointSize() ) 202 : fm( QFontMetrics( fn ) ), linkColor( TRUE ), logicalFontSize( 3 ), stdSize( qApp->font().pointSize() )
200{ 203{
201 ref = 0; 204 ref = 0;
202 205
203 usePixelSizes = FALSE; 206 usePixelSizes = FALSE;
204 if ( stdSize == -1 ) { 207 if ( stdSize == -1 ) {
205 stdSize = qApp->font().pixelSize(); 208 stdSize = qApp->font().pixelSize();
206 usePixelSizes = TRUE; 209 usePixelSizes = TRUE;
207 } 210 }
208 211
209 missp = FALSE; 212 missp = FALSE;
210 ha = AlignNormal; 213 ha = AlignNormal;
211 collection = 0; 214 collection = 0;
212 fn = QFont( style->fontFamily(), 215 fn = QFont( style->fontFamily(),
213 style->fontSize(), 216 style->fontSize(),
214 style->fontWeight(), 217 style->fontWeight(),
215 style->fontItalic() ); 218 style->fontItalic() );
216 fn.setUnderline( style->fontUnderline() ); 219 fn.setUnderline( style->fontUnderline() );
217 fn.setStrikeOut( style->fontStrikeOut() ); 220 fn.setStrikeOut( style->fontStrikeOut() );
218 col = style->color(); 221 col = style->color();
219 fm = QFontMetrics( fn ); 222 fm = QFontMetrics( fn );
220 leftBearing = fm.minLeftBearing(); 223 leftBearing = fm.minLeftBearing();
221 rightBearing = fm.minRightBearing(); 224 rightBearing = fm.minRightBearing();
222 hei = fm.lineSpacing(); 225 hei = fm.lineSpacing();
223 asc = fm.ascent() + (fm.leading()+1)/2; 226 asc = fm.ascent() + (fm.leading()+1)/2;
224 dsc = fm.descent(); 227 dsc = fm.descent();
225 missp = FALSE; 228 missp = FALSE;
226 ha = AlignNormal; 229 ha = AlignNormal;
227 memset( widths, 0, 256 ); 230 memset( widths, 0, 256 );
228 generateKey(); 231 generateKey();
229 addRef(); 232 addRef();
230} 233}
231 234
232QTextFormat::QTextFormat( const QFont &f, const QColor &c, QTextFormatCollection *parent ) 235QTextFormat::QTextFormat( const QFont &f, const QColor &c, QTextFormatCollection *parent )
233 : fn( f ), col( c ), fm( QFontMetrics( f ) ), linkColor( TRUE ), 236 : fn( f ), col( c ), fm( QFontMetrics( f ) ), linkColor( TRUE ),
234 logicalFontSize( 3 ), stdSize( f.pointSize() ) 237 logicalFontSize( 3 ), stdSize( f.pointSize() )
235{ 238{
236 ref = 0; 239 ref = 0;
@@ -384,220 +387,220 @@ QString QTextFormat::getKey( const QFont &fn, const QColor &col, bool misspelled
384 k += '/'; 387 k += '/';
385 k += QString::number( (uint)col.rgb() ); 388 k += QString::number( (uint)col.rgb() );
386 k += '/'; 389 k += '/';
387 k += QString::number( (int)misspelled ); 390 k += QString::number( (int)misspelled );
388 k += '/'; 391 k += '/';
389 k += QString::number( (int)a ); 392 k += QString::number( (int)a );
390 return k; 393 return k;
391} 394}
392 395
393QString QTextString::toString( const QMemArray<QTextStringChar> &data ) 396QString QTextString::toString( const QMemArray<QTextStringChar> &data )
394{ 397{
395 QString s; 398 QString s;
396 int l = data.size(); 399 int l = data.size();
397 s.setUnicode( 0, l ); 400 s.setUnicode( 0, l );
398 QTextStringChar *c = data.data(); 401 QTextStringChar *c = data.data();
399 QChar *uc = (QChar *)s.unicode(); 402 QChar *uc = (QChar *)s.unicode();
400 while ( l-- ) { 403 while ( l-- ) {
401 *uc = c->c; 404 *uc = c->c;
402 // ### workaround so that non-breaking whitespaces are drawn 405 // ### workaround so that non-breaking whitespaces are drawn
403 // properly, actually this should be fixed in QFont somewhere 406 // properly, actually this should be fixed in QFont somewhere
404 if ( *uc == (char)0xa0 ) 407 if ( *uc == (char)0xa0 )
405 *uc = 0x20; 408 *uc = 0x20;
406 uc++; 409 uc++;
407 c++; 410 c++;
408 } 411 }
409 412
410 return s; 413 return s;
411} 414}
412 415
413QString QTextString::toString() const 416QString QTextString::toString() const
414{ 417{
415 return toString( data ); 418 return toString( data );
416} 419}
417 420
418void QTextParagraph::setSelection( int id, int start, int end ) 421void QTextParagraph::setSelection( int id, int start, int end )
419{ 422{
420 QMap<int, QTextParagraphSelection>::ConstIterator it = selections().find( id ); 423 QMap<int, QTextParagraphSelection>::ConstIterator it = selections().find( id );
421 if ( it != mSelections->end() ) { 424 if ( it != mSelections->end() ) {
422 if ( start == ( *it ).start && end == ( *it ).end ) 425 if ( start == ( *it ).start && end == ( *it ).end )
423 return; 426 return;
424 } 427 }
425 428
426 QTextParagraphSelection sel; 429 QTextParagraphSelection sel;
427 sel.start = start; 430 sel.start = start;
428 sel.end = end; 431 sel.end = end;
429 (*mSelections)[ id ] = sel; 432 (*mSelections)[ id ] = sel;
430 setChanged( TRUE, TRUE ); 433 setChanged( TRUE, TRUE );
431} 434}
432 435
433void QTextParagraph::removeSelection( int id ) 436void QTextParagraph::removeSelection( int id )
434{ 437{
435 if ( !hasSelection( id ) ) 438 if ( !hasSelection( id ) )
436 return; 439 return;
437 if ( mSelections ) 440 if ( mSelections )
438 mSelections->remove( id ); 441 mSelections->remove( id );
439 setChanged( TRUE, TRUE ); 442 setChanged( TRUE, TRUE );
440} 443}
441 444
442int QTextParagraph::selectionStart( int id ) const 445int QTextParagraph::selectionStart( int id ) const
443{ 446{
444 if ( !mSelections ) 447 if ( !mSelections )
445 return -1; 448 return -1;
446 QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id ); 449 QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id );
447 if ( it == mSelections->end() ) 450 if ( it == mSelections->end() )
448 return -1; 451 return -1;
449 return ( *it ).start; 452 return ( *it ).start;
450} 453}
451 454
452int QTextParagraph::selectionEnd( int id ) const 455int QTextParagraph::selectionEnd( int id ) const
453{ 456{
454 if ( !mSelections ) 457 if ( !mSelections )
455 return -1; 458 return -1;
456 QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id ); 459 QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id );
457 if ( it == mSelections->end() ) 460 if ( it == mSelections->end() )
458 return -1; 461 return -1;
459 return ( *it ).end; 462 return ( *it ).end;
460} 463}
461 464
462bool QTextParagraph::hasSelection( int id ) const 465bool QTextParagraph::hasSelection( int id ) const
463{ 466{
464 return mSelections ? mSelections->contains( id ) : FALSE; 467 return mSelections ? mSelections->contains( id ) : FALSE;
465} 468}
466 469
467bool QTextParagraph::fullSelected( int id ) const 470bool QTextParagraph::fullSelected( int id ) const
468{ 471{
469 if ( !mSelections ) 472 if ( !mSelections )
470 return FALSE; 473 return FALSE;
471 QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id ); 474 QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->find( id );
472 if ( it == mSelections->end() ) 475 if ( it == mSelections->end() )
473 return FALSE; 476 return FALSE;
474 return ( *it ).start == 0 && ( *it ).end == str->length() - 1; 477 return ( *it ).start == 0 && ( *it ).end == str->length() - 1;
475} 478}
476 479
477int QTextParagraph::lineY( int l ) const 480int QTextParagraph::lineY( int l ) const
478{ 481{
479 if ( l > (int)lineStarts.count() - 1 ) { 482 if ( l > (int)lineStarts.count() - 1 ) {
480 qWarning( "QTextParagraph::lineY: line %d out of range!", l ); 483 owarn << "QTextParagraph::lineY: line " << l << " out of range!" << oendl;
481 return 0; 484 return 0;
482 } 485 }
483 486
484 if ( !isValid() ) 487 if ( !isValid() )
485 ( (QTextParagraph*)this )->format(); 488 ( (QTextParagraph*)this )->format();
486 489
487 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin(); 490 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
488 while ( l-- > 0 ) 491 while ( l-- > 0 )
489 ++it; 492 ++it;
490 return ( *it )->y; 493 return ( *it )->y;
491} 494}
492 495
493int QTextParagraph::lineBaseLine( int l ) const 496int QTextParagraph::lineBaseLine( int l ) const
494{ 497{
495 if ( l > (int)lineStarts.count() - 1 ) { 498 if ( l > (int)lineStarts.count() - 1 ) {
496 qWarning( "QTextParagraph::lineBaseLine: line %d out of range!", l ); 499 owarn << "QTextParagraph::lineBaseLine: line " << l << " out of range!" << oendl;
497 return 10; 500 return 10;
498 } 501 }
499 502
500 if ( !isValid() ) 503 if ( !isValid() )
501 ( (QTextParagraph*)this )->format(); 504 ( (QTextParagraph*)this )->format();
502 505
503 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin(); 506 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
504 while ( l-- > 0 ) 507 while ( l-- > 0 )
505 ++it; 508 ++it;
506 return ( *it )->baseLine; 509 return ( *it )->baseLine;
507} 510}
508 511
509int QTextParagraph::lineHeight( int l ) const 512int QTextParagraph::lineHeight( int l ) const
510{ 513{
511 if ( l > (int)lineStarts.count() - 1 ) { 514 if ( l > (int)lineStarts.count() - 1 ) {
512 qWarning( "QTextParagraph::lineHeight: line %d out of range!", l ); 515 owarn << "QTextParagraph::lineHeight: line " << l << " out of range!" << oendl;
513 return 15; 516 return 15;
514 } 517 }
515 518
516 if ( !isValid() ) 519 if ( !isValid() )
517 ( (QTextParagraph*)this )->format(); 520 ( (QTextParagraph*)this )->format();
518 521
519 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin(); 522 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
520 while ( l-- > 0 ) 523 while ( l-- > 0 )
521 ++it; 524 ++it;
522 return ( *it )->h; 525 return ( *it )->h;
523} 526}
524 527
525void QTextParagraph::lineInfo( int l, int &y, int &h, int &bl ) const 528void QTextParagraph::lineInfo( int l, int &y, int &h, int &bl ) const
526{ 529{
527 if ( l > (int)lineStarts.count() - 1 ) { 530 if ( l > (int)lineStarts.count() - 1 ) {
528 qWarning( "QTextParagraph::lineInfo: line %d out of range!", l ); 531 owarn << "QTextParagraph::lineInfo: line " << l << " out of range!" << oendl;
529 qDebug( "%d %d", (int)lineStarts.count() - 1, l ); 532 odebug << "" << (int)lineStarts.count() - 1 << " " << l << "" << oendl;
530 y = 0; 533 y = 0;
531 h = 15; 534 h = 15;
532 bl = 10; 535 bl = 10;
533 return; 536 return;
534 } 537 }
535 538
536 if ( !isValid() ) 539 if ( !isValid() )
537 ( (QTextParagraph*)this )->format(); 540 ( (QTextParagraph*)this )->format();
538 541
539 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin(); 542 QMap<int, QTextLineStart*>::ConstIterator it = lineStarts.begin();
540 while ( l-- > 0 ) 543 while ( l-- > 0 )
541 ++it; 544 ++it;
542 y = ( *it )->y; 545 y = ( *it )->y;
543 h = ( *it )->h; 546 h = ( *it )->h;
544 bl = ( *it )->baseLine; 547 bl = ( *it )->baseLine;
545} 548}
546 549
547 550
548void QTextParagraph::setAlignment( int a ) 551void QTextParagraph::setAlignment( int a )
549{ 552{
550 if ( a == (int)align ) 553 if ( a == (int)align )
551 return; 554 return;
552 align = a; 555 align = a;
553 invalidate( 0 ); 556 invalidate( 0 );
554} 557}
555 558
556QTextFormatter *QTextParagraph::formatter() const 559QTextFormatter *QTextParagraph::formatter() const
557{ 560{
558 if ( hasdoc ) 561 if ( hasdoc )
559 return document()->formatter(); 562 return document()->formatter();
560 if ( pseudoDocument()->pFormatter ) 563 if ( pseudoDocument()->pFormatter )
561 return pseudoDocument()->pFormatter; 564 return pseudoDocument()->pFormatter;
562 return ( ( (QTextParagraph*)this )->pseudoDocument()->pFormatter = new QTextFormatterBreakWords ); 565 return ( ( (QTextParagraph*)this )->pseudoDocument()->pFormatter = new QTextFormatterBreakWords );
563} 566}
564 567
565void QTextParagraph::setTabArray( int *a ) 568void QTextParagraph::setTabArray( int *a )
566{ 569{
567 delete [] tArray; 570 delete [] tArray;
568 tArray = a; 571 tArray = a;
569} 572}
570 573
571void QTextParagraph::setTabStops( int tw ) 574void QTextParagraph::setTabStops( int tw )
572{ 575{
573 if ( hasdoc ) 576 if ( hasdoc )
574 document()->setTabStops( tw ); 577 document()->setTabStops( tw );
575 else 578 else
576 tabStopWidth = tw; 579 tabStopWidth = tw;
577} 580}
578 581
579QMap<int, QTextParagraphSelection> &QTextParagraph::selections() const 582QMap<int, QTextParagraphSelection> &QTextParagraph::selections() const
580{ 583{
581 if ( !mSelections ) 584 if ( !mSelections )
582 ((QTextParagraph *)this)->mSelections = new QMap<int, QTextParagraphSelection>; 585 ((QTextParagraph *)this)->mSelections = new QMap<int, QTextParagraphSelection>;
583 return *mSelections; 586 return *mSelections;
584} 587}
585 588
586 589
587QPtrList<QTextCustomItem> &QTextParagraph::floatingItems() const 590QPtrList<QTextCustomItem> &QTextParagraph::floatingItems() const
588{ 591{
589 if ( !mFloatingItems ) 592 if ( !mFloatingItems )
590 ((QTextParagraph *)this)->mFloatingItems = new QPtrList<QTextCustomItem>; 593 ((QTextParagraph *)this)->mFloatingItems = new QPtrList<QTextCustomItem>;
591 return *mFloatingItems; 594 return *mFloatingItems;
592} 595}
593 596
594QTextStringChar::~QTextStringChar() 597QTextStringChar::~QTextStringChar()
595{ 598{
596 if ( format() ) 599 if ( format() )
597 format()->removeRef(); 600 format()->removeRef();
598 if ( type ) // not Regular 601 if ( type ) // not Regular
599 delete d.custom; 602 delete d.custom;
600} 603}
601 604
602QTextParagraphPseudoDocument::QTextParagraphPseudoDocument():pFormatter(0),commandHistory(0), minw(0),wused(0){} 605QTextParagraphPseudoDocument::QTextParagraphPseudoDocument():pFormatter(0),commandHistory(0), minw(0),wused(0){}
603QTextParagraphPseudoDocument::~QTextParagraphPseudoDocument(){ delete pFormatter; delete commandHistory; } 606QTextParagraphPseudoDocument::~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 @@
1#include <qmessagebox.h>
2#include <qheader.h>
3
4#include "accountdisplay.h" 1#include "accountdisplay.h"
5#include "newaccount.h" 2#include "newaccount.h"
6#include "transaction.h" 3#include "transaction.h"
7#include "transferdialog.h" 4#include "transferdialog.h"
8#include "transfer.h" 5#include "transfer.h"
9 6
7/* OPIE */
8#include <opie2/odebug.h>
9using namespace Opie::Core;
10
11/* QT */
12#include <qmessagebox.h>
13#include <qheader.h>
14
10extern Account *account; 15extern Account *account;
11extern Transaction *transaction; 16extern Transaction *transaction;
12extern Transfer *transfer; 17extern Transfer *transfer;
13extern Preferences *preferences; 18extern Preferences *preferences;
14 19
15AccountDisplay::AccountDisplay ( QWidget *parent ) : QWidget ( parent ) 20AccountDisplay::AccountDisplay ( QWidget *parent ) : QWidget ( parent )
16 { 21 {
17 cleared = 0; 22 cleared = 0;
18 23
19 firstline = new QHBox ( this ); 24 firstline = new QHBox ( this );
20 firstline->setSpacing ( 2 ); 25 firstline->setSpacing ( 2 );
21 26
22 newaccount = new QPushButton ( firstline ); 27 newaccount = new QPushButton ( firstline );
23 newaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/new.png") ); 28 newaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/new.png") );
24 connect ( newaccount, SIGNAL ( released() ), this, SLOT ( addAccount() ) ); 29 connect ( newaccount, SIGNAL ( released() ), this, SLOT ( addAccount() ) );
25 30
26 editaccount = new QPushButton ( firstline ); 31 editaccount = new QPushButton ( firstline );
27 editaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/edit.png") ); 32 editaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/edit.png") );
28 connect ( editaccount, SIGNAL ( released() ), this, SLOT ( editAccount() ) ); 33 connect ( editaccount, SIGNAL ( released() ), this, SLOT ( editAccount() ) );
29 34
30 deleteaccount = new QPushButton ( firstline ); 35 deleteaccount = new QPushButton ( firstline );
31 deleteaccount->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/delete.png") ); 36 deleteaccount->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/delete.png") );
32 connect ( deleteaccount, SIGNAL ( released() ), this, SLOT ( deleteAccount() ) ); 37 connect ( deleteaccount, SIGNAL ( released() ), this, SLOT ( deleteAccount() ) );
33 38
34 transferbutton = new QPushButton ( firstline ); 39 transferbutton = new QPushButton ( firstline );
35 transferbutton->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/transfer.png") ); 40 transferbutton->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/transfer.png") );
36 transferbutton->setToggleButton ( TRUE ); 41 transferbutton->setToggleButton ( TRUE );
37 connect ( transferbutton, SIGNAL ( toggled(bool) ), this, SLOT ( accountTransfer(bool) ) ); 42 connect ( transferbutton, SIGNAL ( toggled(bool) ), this, SLOT ( accountTransfer(bool) ) );
38 43
39 listview = new QListView ( this ); 44 listview = new QListView ( this );
40 listview->setAllColumnsShowFocus ( TRUE ); 45 listview->setAllColumnsShowFocus ( TRUE );
41 listview->setShowSortIndicator ( TRUE ); 46 listview->setShowSortIndicator ( TRUE );
42 listview->setRootIsDecorated ( TRUE ); 47 listview->setRootIsDecorated ( TRUE );
43 listview->setMultiSelection ( FALSE ); 48 listview->setMultiSelection ( FALSE );
44 connect ( listview, SIGNAL ( expanded(QListViewItem*) ), this, SLOT ( setAccountExpanded(QListViewItem*) ) ); 49 connect ( listview, SIGNAL ( expanded(QListViewItem*) ), this, SLOT ( setAccountExpanded(QListViewItem*) ) );
45 connect ( listview, SIGNAL ( collapsed(QListViewItem*) ), this, SLOT ( setAccountCollapsed(QListViewItem*) ) ); 50 connect ( listview, SIGNAL ( collapsed(QListViewItem*) ), this, SLOT ( setAccountCollapsed(QListViewItem*) ) );
46 51
47 listview->header()->setTracking ( FALSE ); 52 listview->header()->setTracking ( FALSE );
48 connect ( listview->header(), SIGNAL ( sizeChange(int,int,int) ), this, SLOT ( saveColumnSize(int,int,int) ) ); 53 connect ( listview->header(), SIGNAL ( sizeChange(int,int,int) ), this, SLOT ( saveColumnSize(int,int,int) ) );
49 connect ( listview->header(), SIGNAL ( clicked(int) ), this, SLOT ( saveSortingPreference(int) ) ); 54 connect ( listview->header(), SIGNAL ( clicked(int) ), this, SLOT ( saveSortingPreference(int) ) );
50 55
51 layout = new QVBoxLayout ( this, 2, 5 ); 56 layout = new QVBoxLayout ( this, 2, 5 );
52 layout->addWidget ( firstline ); 57 layout->addWidget ( firstline );
53 layout->addWidget ( listview ); 58 layout->addWidget ( listview );
54 } 59 }
55 60
56void AccountDisplay::setTabs ( QWidget *newtab2, QTabWidget *newtabs ) 61void AccountDisplay::setTabs ( QWidget *newtab2, QTabWidget *newtabs )
57 { 62 {
58 tab2 = newtab2; 63 tab2 = newtab2;
59 maintabs = newtabs; 64 maintabs = newtabs;
60 } 65 }
61 66
62void AccountDisplay::addAccount () 67void AccountDisplay::addAccount ()
63 { 68 {
64 // initialize local variables 69 // initialize local variables
65 int parentid = 0; 70 int parentid = 0;
66 type = 0; 71 type = 0;
67 QString parentlist [ listview->childCount() + 1 ] [ 3 ] ; 72 QString parentlist [ listview->childCount() + 1 ] [ 3 ] ;
68 73
69 // create new account window for entering data 74 // create new account window for entering data
70 NewAccount *newaccount = new NewAccount ( this ); 75 NewAccount *newaccount = new NewAccount ( this );
71 int width = this->width(); 76 int width = this->width();
72 newaccount->accountbox->setMaximumWidth ( ( int ) ( width * 0.5 ) ); 77 newaccount->accountbox->setMaximumWidth ( ( int ) ( width * 0.5 ) );
73 newaccount->datebox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 78 newaccount->datebox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
74 newaccount->childbox->setMaximumWidth ( ( int ) ( width * 0.5 ) ); 79 newaccount->childbox->setMaximumWidth ( ( int ) ( width * 0.5 ) );
75 newaccount->balancebox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 80 newaccount->balancebox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
76 newaccount->creditlimitbox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 81 newaccount->creditlimitbox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
77 82
78 // if there are no accounts, disable the child check box 83 // if there are no accounts, disable the child check box
79 if ( account->getNumberOfAccounts () == 0 ) 84 if ( account->getNumberOfAccounts () == 0 )
80 newaccount->childcheckbox->setEnabled ( FALSE ); 85 newaccount->childcheckbox->setEnabled ( FALSE );
81 86
82 // if there are accounts, fill up the pulldown menu for 87 // if there are accounts, fill up the pulldown menu for
83 // selecting a parent account. We should only add those parents without transactions 88 // selecting a parent account. We should only add those parents without transactions
84 else 89 else
85 { 90 {
86 int c = 0; 91 int c = 0;
87 QListViewItemIterator it ( listview ); 92 QListViewItemIterator it ( listview );
88 for ( ; it.current(); ++it ) 93 for ( ; it.current(); ++it )
89 { 94 {
90 int id = it.current()->text ( getIDColumn() ).toInt(); 95 int id = it.current()->text ( getIDColumn() ).toInt();
91 // iterate through accountdisplay listview and add parents with no transactions 96 // iterate through accountdisplay listview and add parents with no transactions
92 // add this item to the list box only if it is a parent and has no transactions 97 // add this item to the list box only if it is a parent and has no transactions
93 if ( transfer->getNumberOfTransfers ( id ) == 0 && transaction->getNumberOfTransactions ( id ) == 0 && it.current()->parent() == 0 ) 98 if ( transfer->getNumberOfTransfers ( id ) == 0 && transaction->getNumberOfTransactions ( id ) == 0 && it.current()->parent() == 0 )
94 { 99 {
95 newaccount->childbox->insertItem ( it.current()->text ( 0 ) ); 100 newaccount->childbox->insertItem ( it.current()->text ( 0 ) );
96 parentlist [ c ] [ 0 ] = it.current()->text ( 0 ); 101 parentlist [ c ] [ 0 ] = it.current()->text ( 0 );
97 parentlist [ c ] [ 1 ] = it.current()->text ( getIDColumn() ); 102 parentlist [ c ] [ 1 ] = it.current()->text ( getIDColumn() );
98 parentlist [ c ] [ 2 ] = QString::number ( c ); 103 parentlist [ c ] [ 2 ] = QString::number ( c );
99 c++; 104 c++;
100 } 105 }
101 } 106 }
102 } 107 }
103 108
104 if ( preferences->getPreference ( 4 ) == 0 ) 109 if ( preferences->getPreference ( 4 ) == 0 )
105 newaccount->currencybox->setEnabled ( FALSE ); 110 newaccount->currencybox->setEnabled ( FALSE );
@@ -174,193 +179,193 @@ void AccountDisplay::deleteAccount ()
174 transfer->deleteAllTransfers ( accountid ); 179 transfer->deleteAllTransfers ( accountid );
175 180
176 // delete the account 181 // delete the account
177 account->deleteAccount ( accountid ); 182 account->deleteAccount ( accountid );
178 183
179 // update account balances 184 // update account balances
180 if ( parentid != -1 ) 185 if ( parentid != -1 )
181 account->changeParentAccountBalance ( parentid ); 186 account->changeParentAccountBalance ( parentid );
182 187
183 //redisplay accounts 188 //redisplay accounts
184 account->displayAccounts ( listview ); 189 account->displayAccounts ( listview );
185 190
186 //remove all the columns from the accountdisplay if there are not any accounts 191 //remove all the columns from the accountdisplay if there are not any accounts
187 if ( account->getNumberOfAccounts() == 0 ) 192 if ( account->getNumberOfAccounts() == 0 )
188 { 193 {
189 int columns = listview->columns(); 194 int columns = listview->columns();
190 int counter; 195 int counter;
191 for ( counter = 0; counter <= columns; counter++ ) 196 for ( counter = 0; counter <= columns; counter++ )
192 listview->removeColumn ( 0 ); 197 listview->removeColumn ( 0 );
193 } 198 }
194 199
195 setToggleButton(); 200 setToggleButton();
196 } 201 }
197 } 202 }
198 maintabs->setTabEnabled ( tab2, FALSE ); 203 maintabs->setTabEnabled ( tab2, FALSE );
199 } 204 }
200 205
201void AccountDisplay::setToggleButton () 206void AccountDisplay::setToggleButton ()
202 { 207 {
203 // iterate through account display and determine how many "transferable" accounts we have 208 // iterate through account display and determine how many "transferable" accounts we have
204 // if there are less than two, disable the transfer button 209 // if there are less than two, disable the transfer button
205 QListViewItemIterator it ( listview ); 210 QListViewItemIterator it ( listview );
206 int counter = 0; 211 int counter = 0;
207 for ( ; it.current(); ++it ) 212 for ( ; it.current(); ++it )
208 { 213 {
209 // add one to counter if we find a transferable account 214 // add one to counter if we find a transferable account
210 if ( it.current()->parent() != 0 || ( it.current()->childCount() ) == 0 ) 215 if ( it.current()->parent() != 0 || ( it.current()->childCount() ) == 0 )
211 counter++; 216 counter++;
212 } 217 }
213 if ( counter > 1 ) 218 if ( counter > 1 )
214 transferbutton->show(); 219 transferbutton->show();
215 else 220 else
216 transferbutton->hide(); 221 transferbutton->hide();
217 } 222 }
218 223
219void AccountDisplay::accountTransfer ( bool state ) 224void AccountDisplay::accountTransfer ( bool state )
220 { 225 {
221 if ( state == TRUE ) 226 if ( state == TRUE )
222 { 227 {
223 firstaccountid = -1; 228 firstaccountid = -1;
224 secondaccountid = -1; 229 secondaccountid = -1;
225 listview->clearSelection (); 230 listview->clearSelection ();
226 listview->setMultiSelection ( TRUE ); 231 listview->setMultiSelection ( TRUE );
227 disableParentsWithChildren (); 232 disableParentsWithChildren ();
228 connect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) ); 233 connect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
229 } 234 }
230 else 235 else
231 { 236 {
232 firstaccountid = -1; 237 firstaccountid = -1;
233 secondaccountid = -1; 238 secondaccountid = -1;
234 listview->clearSelection (); 239 listview->clearSelection ();
235 listview->setMultiSelection ( FALSE ); 240 listview->setMultiSelection ( FALSE );
236 enableAccounts (); 241 enableAccounts ();
237 disconnect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) ); 242 disconnect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
238 } 243 }
239 } 244 }
240 245
241void AccountDisplay::getTransferAccounts ( QListViewItem * item ) 246void AccountDisplay::getTransferAccounts ( QListViewItem * item )
242 { 247 {
243 if ( item->parent() != 0 || item->childCount() == 0 ) // only set an account for transfer if its a child or parent with no children 248 if ( item->parent() != 0 || item->childCount() == 0 ) // only set an account for transfer if its a child or parent with no children
244 { 249 {
245 if ( firstaccountid == -1 ) 250 if ( firstaccountid == -1 )
246 firstaccountid = item->text ( getIDColumn() ).toInt(); // set first account if we've selected a valid account 251 firstaccountid = item->text ( getIDColumn() ).toInt(); // set first account if we've selected a valid account
247 else 252 else
248 if ( item->text ( getIDColumn() ).toInt() != firstaccountid ) // set the second account if its not equal to the first 253 if ( item->text ( getIDColumn() ).toInt() != firstaccountid ) // set the second account if its not equal to the first
249 secondaccountid = item->text ( getIDColumn() ).toInt(); 254 secondaccountid = item->text ( getIDColumn() ).toInt();
250 } 255 }
251 256
252 // open transfer window if both accounts are set 257 // open transfer window if both accounts are set
253 if ( firstaccountid != -1 && secondaccountid != -1 ) 258 if ( firstaccountid != -1 && secondaccountid != -1 )
254 { 259 {
255 // construct the transferdialog window 260 // construct the transferdialog window
256 TransferDialog *td = new TransferDialog ( this, firstaccountid, secondaccountid ); 261 TransferDialog *td = new TransferDialog ( this, firstaccountid, secondaccountid );
257 262
258 // enter today's date in the date box as default 263 // enter today's date in the date box as default
259 QDate today = QDate::currentDate (); 264 QDate today = QDate::currentDate ();
260 int defaultday = today.day(); 265 int defaultday = today.day();
261 int defaultmonth = today.month(); 266 int defaultmonth = today.month();
262 int defaultyear = today.year(); 267 int defaultyear = today.year();
263 td->date->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) ); 268 td->date->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) );
264 269
265 if ( td->exec() == QDialog::Accepted ) 270 if ( td->exec() == QDialog::Accepted )
266 { 271 {
267 // set the cleared integer if the checkbox is checked 272 // set the cleared integer if the checkbox is checked
268 if ( td->clearedcheckbox->isChecked() == TRUE ) 273 if ( td->clearedcheckbox->isChecked() == TRUE )
269 cleared = 1; 274 cleared = 1;
270 qDebug("Year from transferdialog = %i",td->getYear()); 275 odebug << "Year from transferdialog = " << td->getYear() << "" << oendl;
271 // add the transfer with a new date if its been edited or use the default date 276 // add the transfer with a new date if its been edited or use the default date
272 if ( td->getDateEdited () == TRUE ) 277 if ( td->getDateEdited () == TRUE )
273 transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), td->getDay(), td->getMonth(), td->getYear(), td->amount->text().toFloat(), cleared ); 278 transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), td->getDay(), td->getMonth(), td->getYear(), td->amount->text().toFloat(), cleared );
274 else 279 else
275 transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), defaultday, defaultmonth, defaultyear, td->amount->text().toFloat(), cleared ); 280 transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), defaultday, defaultmonth, defaultyear, td->amount->text().toFloat(), cleared );
276 281
277 // update account balances of both accounts and parents if necessary 282 // update account balances of both accounts and parents if necessary
278 account->updateAccountBalance ( firstaccountid ); 283 account->updateAccountBalance ( firstaccountid );
279 if ( account->getParentAccountID ( firstaccountid ) != -1 ) 284 if ( account->getParentAccountID ( firstaccountid ) != -1 )
280 account->changeParentAccountBalance ( account->getParentAccountID ( firstaccountid ) ); 285 account->changeParentAccountBalance ( account->getParentAccountID ( firstaccountid ) );
281 account->updateAccountBalance ( secondaccountid ); 286 account->updateAccountBalance ( secondaccountid );
282 if ( account->getParentAccountID ( secondaccountid ) != -1 ) 287 if ( account->getParentAccountID ( secondaccountid ) != -1 )
283 account->changeParentAccountBalance ( account->getParentAccountID ( secondaccountid ) ); 288 account->changeParentAccountBalance ( account->getParentAccountID ( secondaccountid ) );
284 289
285 // redisplay accounts 290 // redisplay accounts
286 account->displayAccounts ( listview ); 291 account->displayAccounts ( listview );
287 } 292 }
288 else 293 else
289 { 294 {
290 firstaccountid = -1; 295 firstaccountid = -1;
291 secondaccountid = -1; 296 secondaccountid = -1;
292 listview->clearSelection (); 297 listview->clearSelection ();
293 listview->setMultiSelection ( FALSE ); 298 listview->setMultiSelection ( FALSE );
294 disconnect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) ); 299 disconnect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
295 } 300 }
296 301
297 // reset the accounts display window 302 // reset the accounts display window
298 transferbutton->toggle(); // toggling this button with clear the window as well 303 transferbutton->toggle(); // toggling this button with clear the window as well
299 304
300 // reenable all the accounts so the transaction tab will be properly set 305 // reenable all the accounts so the transaction tab will be properly set
301 enableAccounts (); 306 enableAccounts ();
302 } 307 }
303 } 308 }
304 309
305void AccountDisplay::disableParentsWithChildren () 310void AccountDisplay::disableParentsWithChildren ()
306 { 311 {
307 // iterate through accountdisplay listview and disable all the parents that have children 312 // iterate through accountdisplay listview and disable all the parents that have children
308 QListViewItemIterator it ( listview ); 313 QListViewItemIterator it ( listview );
309 for ( ; it.current(); ++it ) 314 for ( ; it.current(); ++it )
310 { 315 {
311 if ( it.current()->parent() == 0 && it.current()->childCount() != 0 ) 316 if ( it.current()->parent() == 0 && it.current()->childCount() != 0 )
312 it.current()->setSelectable ( FALSE ); 317 it.current()->setSelectable ( FALSE );
313 } 318 }
314 } 319 }
315 320
316void AccountDisplay::enableAccounts () 321void AccountDisplay::enableAccounts ()
317 { 322 {
318 // iterate through accountdisplay listview and enable all accounts 323 // iterate through accountdisplay listview and enable all accounts
319 QListViewItemIterator it ( listview ); 324 QListViewItemIterator it ( listview );
320 for ( ; it.current(); ++it ) 325 for ( ; it.current(); ++it )
321 it.current()->setSelectable ( TRUE ); 326 it.current()->setSelectable ( TRUE );
322 } 327 }
323 328
324void AccountDisplay::saveColumnSize ( int column, int oldsize, int newsize ) 329void AccountDisplay::saveColumnSize ( int column, int oldsize, int newsize )
325 { 330 {
326 switch ( column ) 331 switch ( column )
327 { 332 {
328 case 0: 333 case 0:
329 if ( listview->columns() == 3 ) 334 if ( listview->columns() == 3 )
330 preferences->changeColumnPreference ( 1, newsize ); 335 preferences->changeColumnPreference ( 1, newsize );
331 else 336 else
332 preferences->changeColumnPreference ( 10, newsize ); 337 preferences->changeColumnPreference ( 10, newsize );
333 break; 338 break;
334 case 1: 339 case 1:
335 if ( listview->columns() == 3 ) 340 if ( listview->columns() == 3 )
336 preferences->changeColumnPreference ( 2, newsize ); 341 preferences->changeColumnPreference ( 2, newsize );
337 else 342 else
338 preferences->changeColumnPreference ( 11, newsize ); 343 preferences->changeColumnPreference ( 11, newsize );
339 break; 344 break;
340 case 2: 345 case 2:
341 preferences->changeColumnPreference ( 12, newsize ); 346 preferences->changeColumnPreference ( 12, newsize );
342 break; 347 break;
343 } 348 }
344 349
345 } 350 }
346 351
347void AccountDisplay::saveSortingPreference ( int column ) 352void AccountDisplay::saveSortingPreference ( int column )
348 { 353 {
349 preferences->changeSortingPreference ( 1, column ); 354 preferences->changeSortingPreference ( 1, column );
350 } 355 }
351 356
352int AccountDisplay::getIDColumn () 357int AccountDisplay::getIDColumn ()
353 { 358 {
354 int counter; 359 int counter;
355 int columns = listview->columns(); 360 int columns = listview->columns();
356 for ( counter = 0; counter <= columns; counter++ ) 361 for ( counter = 0; counter <= columns; counter++ )
357 if ( listview->header()->label ( counter ).length() == 0 ) 362 if ( listview->header()->label ( counter ).length() == 0 )
358 return counter; 363 return counter;
359 } 364 }
360 365
361void AccountDisplay::editAccount () 366void AccountDisplay::editAccount ()
362 { 367 {
363 if ( listview->selectedItem() == 0 ) 368 if ( listview->selectedItem() == 0 )
364 QMessageBox::warning ( this, "QashMoney", "Please select an account\nto edit."); 369 QMessageBox::warning ( this, "QashMoney", "Please select an account\nto edit.");
365 else 370 else
366 { 371 {
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 @@
1 config QASHMONEY 1 config QASHMONEY
2 boolean "opie-qashmoney (money manager)" 2 boolean "opie-qashmoney (money manager)"
3 default "n" 3 default "n"
4 depends ( LIBQPE || LIBQPE-X11 ) 4 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 @@
1TEMPLATE = app 1TEMPLATE = app
2CONFIG = qt warn_on 2CONFIG = qt warn_on
3 HEADERS =qashmoney.h \ 3 HEADERS =qashmoney.h \
4 accountdisplay.h \ 4 accountdisplay.h \
5 account.h \ 5 account.h \
6 transaction.h \ 6 transaction.h \
7 transactiondisplay.h \ 7 transactiondisplay.h \
8 newtransaction.h \ 8 newtransaction.h \
9 transfer.h \ 9 transfer.h \
10 transferdialog.h \ 10 transferdialog.h \
11 preferences.h \ 11 preferences.h \
12 preferencedialogs.h \ 12 preferencedialogs.h \
13 memory.h \ 13 memory.h \
14 memorydialog.h \ 14 memorydialog.h \
15 newaccount.h \ 15 newaccount.h \
16 calculator.h \ 16 calculator.h \
17 datepicker.h \ 17 datepicker.h \
18 budget.h \ 18 budget.h \
19 budgetdisplay.h \ 19 budgetdisplay.h \
20 currency.h 20 currency.h
21 SOURCES =qashmoney.cpp \ 21 SOURCES =qashmoney.cpp \
22 accountdisplay.cpp \ 22 accountdisplay.cpp \
23 account.cpp \ 23 account.cpp \
24 transaction.cpp \ 24 transaction.cpp \
25 transactiondisplay.cpp \ 25 transactiondisplay.cpp \
26 newtransaction.cpp \ 26 newtransaction.cpp \
27 transfer.cpp \ 27 transfer.cpp \
28 transferdialog.cpp \ 28 transferdialog.cpp \
29 preferences.cpp \ 29 preferences.cpp \
30 preferencedialogs.cpp \ 30 preferencedialogs.cpp \
31 memory.cpp \ 31 memory.cpp \
32 memorydialog.cpp \ 32 memorydialog.cpp \
33 newaccount.cpp \ 33 newaccount.cpp \
34 calculator.cpp \ 34 calculator.cpp \
35 datepicker.cpp \ 35 datepicker.cpp \
36 main.cpp \ 36 main.cpp \
37 budget.cpp \ 37 budget.cpp \
38 budgetdisplay.cpp \ 38 budgetdisplay.cpp \
39 currency.cpp 39 currency.cpp
40INCLUDEPATH = $(OPIEDIR)/include 40INCLUDEPATH = $(OPIEDIR)/include
41DEPENDPATH = $(OPIEDIR)/include 41DEPENDPATH = $(OPIEDIR)/include
42 42
43DESTDIR = $(OPIEDIR)/bin 43DESTDIR = $(OPIEDIR)/bin
44 44
45unix:LIBS += -lm 45unix:LIBS += -lm
46LIBS += -lqpe -lqte -lsqlite 46LIBS += -lqpe -lopiecore2 -lsqlite
47 47
48include ( $(OPIEDIR)/include.pro ) 48include ( $(OPIEDIR)/include.pro )
49 49
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include <stdlib.h> 20#include "common.h"
21#include "datacache.h"
22
23/* OPIE */
24#include <opie2/odebug.h>
25#include <qpe/timestring.h>
26using namespace Opie::Core;
27
28/* QT */
21#include <qstring.h> 29#include <qstring.h>
22#include <qheader.h> 30#include <qheader.h>
23#include <qvector.h> 31#include <qvector.h>
24#include <qdatetime.h> 32#include <qdatetime.h>
25#include <qpe/timestring.h> 33
26#include "common.h" 34/* STD */
27#include "datacache.h"
28#include <assert.h> 35#include <assert.h>
36#include <stdlib.h>
29 37
30static const int del_flag = 0x1; 38static const int del_flag = 0x1;
31static const int new_flag = 0x2; 39static const int new_flag = 0x2;
32 40
33/* Helper function */ 41/* Helper function */
34 42
35int parseNextNumber(QString *q) { 43int parseNextNumber(QString *q) {
36 QChar c; 44 QChar c;
37 uint i; 45 uint i;
38 int result = 0; 46 int result = 0;
39 47
40 bool found_digits = FALSE; 48 bool found_digits = FALSE;
41 for(i = 0; i < q->length(); i++) { 49 for(i = 0; i < q->length(); i++) {
42 c = q->at(i); 50 c = q->at(i);
43 if (c.isDigit()) { 51 if (c.isDigit()) {
44 if (found_digits) 52 if (found_digits)
45 result *= 10; 53 result *= 10;
46 found_digits = TRUE; 54 found_digits = TRUE;
47 result += c.digitValue(); 55 result += c.digitValue();
48 } else { 56 } else {
49 if (found_digits) 57 if (found_digits)
50 break; 58 break;
51 /* just skip this char */ 59 /* just skip this char */
52 } 60 }
53 } 61 }
54 /* now truncate q */ 62 /* now truncate q */
55 if (found_digits) 63 if (found_digits)
56 q->remove(0, i); 64 q->remove(0, i);
57 return result; 65 return result;
58} 66}
59 67
60/*! 68/*!
61 \class QStringVector 69 \class QStringVector
62 \brief A Vector of QStrings that can be sorted and searched 70 \brief A Vector of QStrings that can be sorted and searched
63 71
64 Implmented in order to allow reverse lookup on the string name 72 Implmented in order to allow reverse lookup on the string name
65 73
66*/ 74*/
67 75
68/*! 76/*!
69 This function implements the compare function in order to allow the 77 This function implements the compare function in order to allow the
70 searching and sorting of the QStringVector to occur 78 searching and sorting of the QStringVector to occur
71 79
72 \returns an int which is either 80 \returns an int which is either
73 <UL> 81 <UL>
74 <LI> < 0 if the first string is smaller than the second,</LI> 82 <LI> < 0 if the first string is smaller than the second,</LI>
75 <LI> > 0 if the first string is bigger then the second,</LI> 83 <LI> > 0 if the first string is bigger then the second,</LI>
76 <LI> == 0 if the first string is equal to the second.</LI> 84 <LI> == 0 if the first string is equal to the second.</LI>
77 </UL> 85 </UL>
78*/ 86*/
79int QStringVector::compareItems(Item a, Item b) 87int QStringVector::compareItems(Item a, Item b)
80{ 88{
81 QString *qa = (QString *)a; 89 QString *qa = (QString *)a;
82 QString *qb = (QString *)b; 90 QString *qb = (QString *)b;
83 91
84 return QString::compare(*qa, *qb); 92 return QString::compare(*qa, *qb);
85} 93}
86 94
87/*! 95/*!
88 \class TVVariant 96 \class TVVariant
89 A way of abstracting void * and keeping information on 97 A way of abstracting void * and keeping information on
90 the keytypes and behaviours in one place 98 the keytypes and behaviours in one place
91*/ 99*/
92 100
93TVVariantPrivate::TVVariantPrivate() 101TVVariantPrivate::TVVariantPrivate()
94{ 102{
95 typ = TVVariant::Invalid; 103 typ = TVVariant::Invalid;
96} 104}
97 105
98TVVariantPrivate::TVVariantPrivate( TVVariantPrivate *d) 106TVVariantPrivate::TVVariantPrivate( TVVariantPrivate *d)
99{ 107{
100 switch(d->typ) 108 switch(d->typ)
101 { 109 {
102 case TVVariant::Invalid: 110 case TVVariant::Invalid:
103 break; 111 break;
104 case TVVariant::String: 112 case TVVariant::String:
105 value.ptr = new QString(*((QString *)d->value.ptr)); 113 value.ptr = new QString(*((QString *)d->value.ptr));
106 break; 114 break;
107 case TVVariant::Date: 115 case TVVariant::Date:
108 value.ptr = new QDate(*((QDate *)d->value.ptr)); 116 value.ptr = new QDate(*((QDate *)d->value.ptr));
109 break; 117 break;
110 case TVVariant::Time: 118 case TVVariant::Time:
111 value.ptr = new QTime(*((QTime *)d->value.ptr)); 119 value.ptr = new QTime(*((QTime *)d->value.ptr));
112 break; 120 break;
113 case TVVariant::Int: 121 case TVVariant::Int:
114 value.i = d->value.i; 122 value.i = d->value.i;
115 break; 123 break;
116 default: 124 default:
117 ASSERT( 0 ); 125 ASSERT( 0 );
118 } 126 }
119 127
120 typ = d->typ; 128 typ = d->typ;
121} 129}
122 130
123TVVariantPrivate::~TVVariantPrivate() 131TVVariantPrivate::~TVVariantPrivate()
124{ 132{
@@ -219,193 +227,193 @@ void TVVariant::detach()
219{ 227{
220 if (d->count == 1) 228 if (d->count == 1)
221 return; 229 return;
222 230
223 d->deref(); 231 d->deref();
224 d = new TVVariantPrivate(d); 232 d = new TVVariantPrivate(d);
225} 233}
226 234
227const QString TVVariant::typeName() const 235const QString TVVariant::typeName() const
228{ 236{
229 return typeToName(d->typ); 237 return typeToName(d->typ);
230} 238}
231 239
232void TVVariant::clear() 240void TVVariant::clear()
233{ 241{
234 if (d->count > 1) 242 if (d->count > 1)
235 { 243 {
236 d->deref(); 244 d->deref();
237 d = new TVVariantPrivate; 245 d = new TVVariantPrivate;
238 return; 246 return;
239 } 247 }
240 248
241 d->clear(); 249 d->clear();
242} 250}
243 251
244const QString TVVariant::typeToName(KeyType typ) 252const QString TVVariant::typeToName(KeyType typ)
245{ 253{
246 switch(typ) { 254 switch(typ) {
247 case String: 255 case String:
248 return QString("String"); 256 return QString("String");
249 case Date: 257 case Date:
250 return QString("Date"); 258 return QString("Date");
251 case Time: 259 case Time:
252 return QString("Time"); 260 return QString("Time");
253 case Int: 261 case Int:
254 return QString("Int"); 262 return QString("Int");
255 case Invalid: 263 case Invalid:
256 default: 264 default:
257 return QString("Invalid"); 265 return QString("Invalid");
258 } 266 }
259 return QString("Invalid"); 267 return QString("Invalid");
260} 268}
261 269
262TVVariant::KeyType TVVariant::nameToType(const QString &name) 270TVVariant::KeyType TVVariant::nameToType(const QString &name)
263{ 271{
264 if(!qstrcmp("String", name)) 272 if(!qstrcmp("String", name))
265 return String; 273 return String;
266 if(!qstrcmp("Date", name)) 274 if(!qstrcmp("Date", name))
267 return Date; 275 return Date;
268 if(!qstrcmp("Time", name)) 276 if(!qstrcmp("Time", name))
269 return Time; 277 return Time;
270 if(!qstrcmp("Int", name)) 278 if(!qstrcmp("Int", name))
271 return Int; 279 return Int;
272 280
273 return Invalid; 281 return Invalid;
274} 282}
275 283
276void TVVariant::load(QDataStream &s ) 284void TVVariant::load(QDataStream &s )
277{ 285{
278 KeyType t; 286 KeyType t;
279 s >> t; 287 s >> t;
280 288
281 d->typ = t; 289 d->typ = t;
282 switch(t) { 290 switch(t) {
283 case Invalid: 291 case Invalid:
284 d->typ = t; 292 d->typ = t;
285 break; 293 break;
286 case String: 294 case String:
287 { 295 {
288 QString *x = new QString; 296 QString *x = new QString;
289 s >> *x; 297 s >> *x;
290 d->value.ptr = x; 298 d->value.ptr = x;
291 } 299 }
292 break; 300 break;
293 case Time: 301 case Time:
294 { 302 {
295 QTime *x = new QTime; 303 QTime *x = new QTime;
296 s >> *x; 304 s >> *x;
297 d->value.ptr = x; 305 d->value.ptr = x;
298 } 306 }
299 break; 307 break;
300 case Date: 308 case Date:
301 { 309 {
302 QDate *x = new QDate; 310 QDate *x = new QDate;
303 s >> *x; 311 s >> *x;
304 d->value.ptr = x; 312 d->value.ptr = x;
305 } 313 }
306 break; 314 break;
307 case Int: 315 case Int:
308 { 316 {
309 int x; 317 int x;
310 s >> x; 318 s >> x;
311 d->value.i = x; 319 d->value.i = x;
312 } 320 }
313 break; 321 break;
314 default: 322 default:
315 qFatal("Unrecognized data type"); 323 ofatal << "Unrecognized data type" << oendl;
316 } 324 }
317} 325}
318 326
319void TVVariant::save( QDataStream &s ) const 327void TVVariant::save( QDataStream &s ) const
320{ 328{
321 s << type(); 329 s << type();
322 330
323 switch( d->typ ) { 331 switch( d->typ ) {
324 case String: 332 case String:
325 s << *((QString *)d->value.ptr); 333 s << *((QString *)d->value.ptr);
326 break; 334 break;
327 case Date: 335 case Date:
328 s << *((QDate *)d->value.ptr); 336 s << *((QDate *)d->value.ptr);
329 break; 337 break;
330 case Time: 338 case Time:
331 s << *((QTime *)d->value.ptr); 339 s << *((QTime *)d->value.ptr);
332 break; 340 break;
333 case Int: 341 case Int:
334 s << d->value.i; 342 s << d->value.i;
335 break; 343 break;
336 case Invalid: 344 case Invalid:
337 break; 345 break;
338 } 346 }
339} 347}
340 348
341QDataStream& operator>>(QDataStream& s, TVVariant& p) 349QDataStream& operator>>(QDataStream& s, TVVariant& p)
342{ 350{
343 p.load( s ); 351 p.load( s );
344 return s; 352 return s;
345} 353}
346 354
347QDataStream& operator<<(QDataStream &s, const TVVariant& p) 355QDataStream& operator<<(QDataStream &s, const TVVariant& p)
348{ 356{
349 p.save( s ); 357 p.save( s );
350 return s; 358 return s;
351} 359}
352 360
353QDataStream& operator>> (QDataStream &s, TVVariant::KeyType& p) 361QDataStream& operator>> (QDataStream &s, TVVariant::KeyType& p)
354{ 362{
355 Q_UINT8 u = 0; 363 Q_UINT8 u = 0;
356 s >> u; 364 s >> u;
357 p = (TVVariant::KeyType) u; 365 p = (TVVariant::KeyType) u;
358 366
359 return s; 367 return s;
360} 368}
361 369
362QDataStream& operator<< (QDataStream& s, const TVVariant::KeyType& p) 370QDataStream& operator<< (QDataStream& s, const TVVariant::KeyType& p)
363{ 371{
364 s << (Q_UINT8)p; 372 s << (Q_UINT8)p;
365 return s; 373 return s;
366} 374}
367 375
368const QString TVVariant::toString() const 376const QString TVVariant::toString() const
369{ 377{
370 switch(d->typ) { 378 switch(d->typ) {
371 case String: 379 case String:
372 return *((QString*)d->value.ptr); 380 return *((QString*)d->value.ptr);
373 case Date: 381 case Date:
374 return ((QDate*)d->value.ptr)->toString(); 382 return ((QDate*)d->value.ptr)->toString();
375 case Time: 383 case Time:
376 return ((QTime*)d->value.ptr)->toString(); 384 return ((QTime*)d->value.ptr)->toString();
377 case Int: 385 case Int:
378 return QString::number(d->value.i); 386 return QString::number(d->value.i);
379 case Invalid: 387 case Invalid:
380 default: 388 default:
381 return QString::null; 389 return QString::null;
382 } 390 }
383 return QString::null; 391 return QString::null;
384} 392}
385 393
386// TODO DO, this properly, */ 394// TODO DO, this properly, */
387int TVVariant::toInt() const 395int TVVariant::toInt() const
388{ 396{
389 if(d->typ == Int) 397 if(d->typ == Int)
390 return d->value.i; 398 return d->value.i;
391 399
392 if(d->typ == String) { 400 if(d->typ == String) {
393 QString tmpq(*(QString *)d->value.ptr); 401 QString tmpq(*(QString *)d->value.ptr);
394 return parseNextNumber(&tmpq); 402 return parseNextNumber(&tmpq);
395 } 403 }
396 404
397 return 0; 405 return 0;
398} 406}
399 407
400const QDate TVVariant::toDate() const 408const QDate TVVariant::toDate() const
401{ 409{
402 if(d->typ == Date) 410 if(d->typ == Date)
403 return *((QDate *)d->value.ptr); 411 return *((QDate *)d->value.ptr);
404 412
405 if(d->typ == String) { 413 if(d->typ == String) {
406 QString q = toString(); 414 QString q = toString();
407 415
408 /* date format is day mon d yyyy */ 416 /* date format is day mon d yyyy */
409 /* ignore the first three letters, read the next 417 /* ignore the first three letters, read the next
410 three for month.. etc */ 418 three for month.. etc */
411 419
@@ -985,193 +993,193 @@ bool KeyList::validIndex(int i) const
985 return FALSE; 993 return FALSE;
986 return TRUE; 994 return TRUE;
987} 995}
988 996
989QDataStream &operator<<( QDataStream &s, const KeyList &k) 997QDataStream &operator<<( QDataStream &s, const KeyList &k)
990{ 998{
991 s << k.getNumFields(); 999 s << k.getNumFields();
992 1000
993 KeyListIterator it(k); 1001 KeyListIterator it(k);
994 1002
995 while(it.current()) { 1003 while(it.current()) {
996 s << (Q_UINT16)it.currentKey(); 1004 s << (Q_UINT16)it.currentKey();
997 s << it.current()->name(); 1005 s << it.current()->name();
998 s << it.current()->example(); 1006 s << it.current()->example();
999 s << (Q_UINT16)it.current()->flags(); 1007 s << (Q_UINT16)it.current()->flags();
1000 ++it; 1008 ++it;
1001 } 1009 }
1002 return s; 1010 return s;
1003} 1011}
1004 1012
1005QDataStream &operator>>( QDataStream &s, KeyList &k) 1013QDataStream &operator>>( QDataStream &s, KeyList &k)
1006{ 1014{
1007 int i; 1015 int i;
1008 int size; 1016 int size;
1009 int index = 0; 1017 int index = 0;
1010 int flags = 0; 1018 int flags = 0;
1011 TVVariant type = TVVariant(); 1019 TVVariant type = TVVariant();
1012 QString name; 1020 QString name;
1013 1021
1014 s >> size; 1022 s >> size;
1015 1023
1016 for (i=0; i < size; i++) { 1024 for (i=0; i < size; i++) {
1017 s >> (Q_UINT16 &)index; 1025 s >> (Q_UINT16 &)index;
1018 s >> name; 1026 s >> name;
1019 s >> type; 1027 s >> type;
1020 s >> (Q_UINT16 &)flags; 1028 s >> (Q_UINT16 &)flags;
1021 k.replace(index, new Key(name, type, flags)); 1029 k.replace(index, new Key(name, type, flags));
1022 } 1030 }
1023 return s; 1031 return s;
1024} 1032}
1025 1033
1026/*! 1034/*!
1027 \class DataElem 1035 \class DataElem
1028 \brief A class representing a single row or element of a table in a DBStore 1036 \brief A class representing a single row or element of a table in a DBStore
1029 1037
1030 This class holds the data of a row in a table. 1038 This class holds the data of a row in a table.
1031*/ 1039*/
1032 1040
1033 1041
1034/*! 1042/*!
1035 Constructs a DataElem. This function needs a container because the 1043 Constructs a DataElem. This function needs a container because the
1036 size, types of keys and primary key are all defined by the containing 1044 size, types of keys and primary key are all defined by the containing
1037 database 1045 database
1038*/ 1046*/
1039DataElem::DataElem(DBStore *c) : values(20) 1047DataElem::DataElem(DBStore *c) : values(20)
1040{ 1048{
1041 int size; 1049 int size;
1042 contained = c; 1050 contained = c;
1043 size = c->getNumFields(); 1051 size = c->getNumFields();
1044 values.setAutoDelete(TRUE); 1052 values.setAutoDelete(TRUE);
1045} 1053}
1046 1054
1047/*! 1055/*!
1048 Destroys a DataElem and frees memory used by the DataElem 1056 Destroys a DataElem and frees memory used by the DataElem
1049*/ 1057*/
1050DataElem::~DataElem() { 1058DataElem::~DataElem() {
1051} 1059}
1052 1060
1053 1061
1054 1062
1055QDataStream &operator<<( QDataStream &s, const DataElem &d) 1063QDataStream &operator<<( QDataStream &s, const DataElem &d)
1056{ 1064{
1057 int size = d.getNumFields(); 1065 int size = d.getNumFields();
1058 1066
1059 s << size; /* redundent data but makes streaming easier */ 1067 s << size; /* redundent data but makes streaming easier */
1060 KeyList k = d.getKeys(); 1068 KeyList k = d.getKeys();
1061 1069
1062 KeyListIterator it(k); 1070 KeyListIterator it(k);
1063 1071
1064 while(it.current()) { 1072 while(it.current()) {
1065 s << (Q_UINT16)it.currentKey(); 1073 s << (Q_UINT16)it.currentKey();
1066 s << d.getField(it.currentKey()); 1074 s << d.getField(it.currentKey());
1067 ++it; 1075 ++it;
1068 } 1076 }
1069 return s; 1077 return s;
1070} 1078}
1071 1079
1072QDataStream &operator>>( QDataStream &s, DataElem &d) 1080QDataStream &operator>>( QDataStream &s, DataElem &d)
1073{ 1081{
1074 int i; 1082 int i;
1075 int size; 1083 int size;
1076 TVVariant t; 1084 TVVariant t;
1077 int index = 0; 1085 int index = 0;
1078 1086
1079 s >> size; /* redundent data but makes streaming easier */ 1087 s >> size; /* redundent data but makes streaming easier */
1080 if (size != d.getNumFields()) { 1088 if (size != d.getNumFields()) {
1081 qWarning("DataSize mis-match"); 1089 owarn << "DataSize mis-match" << oendl;
1082 return s; /* sanity check failed.. don't load */ 1090 return s; /* sanity check failed.. don't load */
1083 } 1091 }
1084 1092
1085 for(i = 0; i < size; i++) { 1093 for(i = 0; i < size; i++) {
1086 s >> (Q_UINT16)index; 1094 s >> (Q_UINT16)index;
1087 s >> t; 1095 s >> t;
1088 d.setField(index, t); 1096 d.setField(index, t);
1089 } 1097 }
1090 return s; 1098 return s;
1091} 1099}
1092 1100
1093/*! Returns the number of possible (not valid) fields in the data element */ 1101/*! Returns the number of possible (not valid) fields in the data element */
1094int DataElem::getNumFields() const 1102int DataElem::getNumFields() const
1095{ 1103{
1096 return contained->getNumFields(); 1104 return contained->getNumFields();
1097} 1105}
1098 1106
1099KeyList DataElem::getKeys() const 1107KeyList DataElem::getKeys() const
1100{ 1108{
1101 return *(contained->getKeys()); 1109 return *(contained->getKeys());
1102} 1110}
1103 1111
1104/*! 1112/*!
1105 This function determines whether field index i of the element has been 1113 This function determines whether field index i of the element has been
1106 set yet. 1114 set yet.
1107 1115
1108 \return A boolean value that is TRUE if the specfied field of this 1116 \return A boolean value that is TRUE if the specfied field of this
1109 element has been set and FALSE if the field has not yet been set 1117 element has been set and FALSE if the field has not yet been set
1110*/ 1118*/
1111bool DataElem::hasValidValue(int i) const 1119bool DataElem::hasValidValue(int i) const
1112{ 1120{
1113 if(!values.find(i)) 1121 if(!values.find(i))
1114 return FALSE; 1122 return FALSE;
1115 if(!contained->getKeys()->validIndex(i)) 1123 if(!contained->getKeys()->validIndex(i))
1116 return FALSE; 1124 return FALSE;
1117 return values.find(i)->isValid(); 1125 return values.find(i)->isValid();
1118} 1126}
1119 1127
1120/*! 1128/*!
1121 This function determines whether field name qs of the element has been 1129 This function determines whether field name qs of the element has been
1122 set yet. 1130 set yet.
1123 1131
1124 \return A boolean value that is TRUE if the specfied field of this 1132 \return A boolean value that is TRUE if the specfied field of this
1125 element has been set and FALSE if the field has not yet been set 1133 element has been set and FALSE if the field has not yet been set
1126*/ 1134*/
1127bool DataElem::hasValidValue(QString qs) const 1135bool DataElem::hasValidValue(QString qs) const
1128{ 1136{
1129 int i = contained->getKeyIndex(qs); 1137 int i = contained->getKeyIndex(qs);
1130 return hasValidValue(i); 1138 return hasValidValue(i);
1131} 1139}
1132 1140
1133/*! returns the type of the field specified by index i */ 1141/*! returns the type of the field specified by index i */
1134TVVariant::KeyType DataElem::getFieldType(int i) const 1142TVVariant::KeyType DataElem::getFieldType(int i) const
1135{ 1143{
1136 return contained->getKeyType(i); 1144 return contained->getKeyType(i);
1137} 1145}
1138 1146
1139/*! returns the type of the field specified by name qs */ 1147/*! returns the type of the field specified by name qs */
1140TVVariant::KeyType DataElem::getFieldType(QString qs) const 1148TVVariant::KeyType DataElem::getFieldType(QString qs) const
1141{ 1149{
1142 int i = contained->getKeyIndex(qs); 1150 int i = contained->getKeyIndex(qs);
1143 return contained->getKeyType(i); 1151 return contained->getKeyType(i);
1144} 1152}
1145 1153
1146/*! 1154/*!
1147 returns a pointer to the data stored in field index i for this 1155 returns a pointer to the data stored in field index i for this
1148 data element, (value may not be valid) 1156 data element, (value may not be valid)
1149*/ 1157*/
1150TVVariant DataElem::getField(int i) const 1158TVVariant DataElem::getField(int i) const
1151{ 1159{
1152 if(hasValidValue(i)) 1160 if(hasValidValue(i))
1153 return TVVariant(*values.find(i)); 1161 return TVVariant(*values.find(i));
1154 return TVVariant(); 1162 return TVVariant();
1155} 1163}
1156 1164
1157/*! 1165/*!
1158 returns a pointer to the data stored in field name qs for this 1166 returns a pointer to the data stored in field name qs for this
1159 data element, (value may not be valid) 1167 data element, (value may not be valid)
1160*/ 1168*/
1161TVVariant DataElem::getField(QString qs) const 1169TVVariant DataElem::getField(QString qs) const
1162{ 1170{
1163 int i = contained->getKeyIndex(qs); 1171 int i = contained->getKeyIndex(qs);
1164 return getField(i); 1172 return getField(i);
1165} 1173}
1166 1174
1167/*! 1175/*!
1168 Sets the value of the elements field index i to the value represented in 1176 Sets the value of the elements field index i to the value represented in
1169 the QString q. 1177 the QString q.
1170 1178
1171 \param i index of the field to set 1179 \param i index of the field to set
1172 \param q a string that can be parsed to get the value to be set 1180 \param q a string that can be parsed to get the value to be set
1173*/ 1181*/
1174void DataElem::setField(int i, QString q) 1182void DataElem::setField(int i, QString q)
1175{ 1183{
1176 /* from the type of the field, parse q and store */ 1184 /* from the type of the field, parse q and store */
1177 TVVariant::KeyType kt = contained->getKeyType(i); 1185 TVVariant::KeyType kt = contained->getKeyType(i);
@@ -1284,187 +1292,187 @@ QString DataElem::toQString() const
1284/*! formats individual fields to strings so can be displayed */ 1292/*! formats individual fields to strings so can be displayed */
1285QString DataElem::toQString(int i) const 1293QString DataElem::toQString(int i) const
1286{ 1294{
1287 if(hasValidValue(i)) { 1295 if(hasValidValue(i)) {
1288 return getField(i).toString(); 1296 return getField(i).toString();
1289 } 1297 }
1290 return ""; 1298 return "";
1291} 1299}
1292/*! formats individual fields to strings so can be sorted by QListView */ 1300/*! formats individual fields to strings so can be sorted by QListView */
1293QString DataElem::toSortableQString(int i) const 1301QString DataElem::toSortableQString(int i) const
1294{ 1302{
1295 QString scratch = ""; 1303 QString scratch = "";
1296 if(hasValidValue(i)) { 1304 if(hasValidValue(i)) {
1297 switch (contained->getKeyType(i)) { 1305 switch (contained->getKeyType(i)) {
1298 case TVVariant::String: { 1306 case TVVariant::String: {
1299 scratch += getField(i).toString(); 1307 scratch += getField(i).toString();
1300 break; 1308 break;
1301 } 1309 }
1302 case TVVariant::Int: { 1310 case TVVariant::Int: {
1303 scratch.sprintf("%08d", getField(i).toInt()); 1311 scratch.sprintf("%08d", getField(i).toInt());
1304 break; 1312 break;
1305 } 1313 }
1306 case TVVariant::Date: { 1314 case TVVariant::Date: {
1307 static QDate epochD(1800, 1, 1); 1315 static QDate epochD(1800, 1, 1);
1308 scratch.sprintf("%08d", 1316 scratch.sprintf("%08d",
1309 epochD.daysTo(getField(i).toDate())); 1317 epochD.daysTo(getField(i).toDate()));
1310 break; 1318 break;
1311 } 1319 }
1312 case TVVariant::Time: { 1320 case TVVariant::Time: {
1313 static QTime epochT(0, 0, 0); 1321 static QTime epochT(0, 0, 0);
1314 scratch.sprintf("%08d", 1322 scratch.sprintf("%08d",
1315 epochT.msecsTo(getField(i).toTime())); 1323 epochT.msecsTo(getField(i).toTime()));
1316 break; 1324 break;
1317 } 1325 }
1318 default: 1326 default:
1319 scratch += "Unknown type"; 1327 scratch += "Unknown type";
1320 break; 1328 break;
1321 } 1329 }
1322 } 1330 }
1323 return scratch; 1331 return scratch;
1324} 1332}
1325 1333
1326/* compare functions */ 1334/* compare functions */
1327 1335
1328bool DataElem::lessThan(int i, TVVariant v) const 1336bool DataElem::lessThan(int i, TVVariant v) const
1329{ 1337{
1330 if (!hasValidValue(i)) return FALSE; 1338 if (!hasValidValue(i)) return FALSE;
1331 1339
1332 if (getField(i).type() != v.type()) 1340 if (getField(i).type() != v.type())
1333 return FALSE; 1341 return FALSE;
1334 1342
1335 return (getField(i) < v); 1343 return (getField(i) < v);
1336} 1344}
1337 1345
1338bool DataElem::moreThan(int i, TVVariant v) const 1346bool DataElem::moreThan(int i, TVVariant v) const
1339{ 1347{
1340 if (!hasValidValue(i)) return FALSE; 1348 if (!hasValidValue(i)) return FALSE;
1341 1349
1342 if (getField(i).type() != v.type()) 1350 if (getField(i).type() != v.type())
1343 return FALSE; 1351 return FALSE;
1344 1352
1345 return (getField(i) > v); 1353 return (getField(i) > v);
1346} 1354}
1347 1355
1348bool DataElem::equalTo(int i, TVVariant v) const 1356bool DataElem::equalTo(int i, TVVariant v) const
1349{ 1357{
1350 if (!hasValidValue(i)) return FALSE; 1358 if (!hasValidValue(i)) return FALSE;
1351 1359
1352 if (getField(i).type() != v.type()) 1360 if (getField(i).type() != v.type())
1353 return FALSE; 1361 return FALSE;
1354 1362
1355 return (getField(i) == v); 1363 return (getField(i) == v);
1356} 1364}
1357 1365
1358bool DataElem::contains(int i, TVVariant v) const 1366bool DataElem::contains(int i, TVVariant v) const
1359{ 1367{
1360 if (!hasValidValue(i)) return FALSE; 1368 if (!hasValidValue(i)) return FALSE;
1361 1369
1362 if (getField(i).type() != v.type()) 1370 if (getField(i).type() != v.type())
1363 return FALSE; 1371 return FALSE;
1364 1372
1365 switch(getField(i).type()) { 1373 switch(getField(i).type()) {
1366 case TVVariant::String: { 1374 case TVVariant::String: {
1367 QString qs1 = getField(i).toString().lower(); 1375 QString qs1 = getField(i).toString().lower();
1368 QString qs2 = v.toString().lower(); 1376 QString qs2 = v.toString().lower();
1369 if (qs1.contains(qs2) > 0) return TRUE; 1377 if (qs1.contains(qs2) > 0) return TRUE;
1370 break; 1378 break;
1371 } 1379 }
1372 /* meaningless for ints */ 1380 /* meaningless for ints */
1373 /* meaningless for time */ 1381 /* meaningless for time */
1374 /* meaningless for dates */ 1382 /* meaningless for dates */
1375 case TVVariant::Int: 1383 case TVVariant::Int:
1376 case TVVariant::Time: 1384 case TVVariant::Time:
1377 case TVVariant::Date: 1385 case TVVariant::Date:
1378 break; 1386 break;
1379 default: 1387 default:
1380 qWarning("Tried to compare unknown data type"); 1388 owarn << "Tried to compare unknown data type" << oendl;
1381 } 1389 }
1382 return FALSE; 1390 return FALSE;
1383} 1391}
1384 1392
1385bool DataElem::startsWith(int i, TVVariant v) const 1393bool DataElem::startsWith(int i, TVVariant v) const
1386{ 1394{
1387 if (!hasValidValue(i)) return FALSE; 1395 if (!hasValidValue(i)) return FALSE;
1388 1396
1389 if (getField(i).type() != v.type()) 1397 if (getField(i).type() != v.type())
1390 return FALSE; 1398 return FALSE;
1391 1399
1392 switch(getField(i).type()) { 1400 switch(getField(i).type()) {
1393 case TVVariant::String: { 1401 case TVVariant::String: {
1394 QString qs1 = getField(i).toString().lower(); 1402 QString qs1 = getField(i).toString().lower();
1395 QString qs2 = v.toString().lower(); 1403 QString qs2 = v.toString().lower();
1396 return qs1.startsWith(qs2); 1404 return qs1.startsWith(qs2);
1397 } 1405 }
1398 /* meaningless for ints */ 1406 /* meaningless for ints */
1399 /* meaningless for time */ 1407 /* meaningless for time */
1400 /* meaningless for dates */ 1408 /* meaningless for dates */
1401 case TVVariant::Int: 1409 case TVVariant::Int:
1402 case TVVariant::Time: 1410 case TVVariant::Time:
1403 case TVVariant::Date: 1411 case TVVariant::Date:
1404 return FALSE; 1412 return FALSE;
1405 default: 1413 default:
1406 qWarning("Tried to compare unknown data type"); 1414 owarn << "Tried to compare unknown data type" << oendl;
1407 } 1415 }
1408 return FALSE; 1416 return FALSE;
1409} 1417}
1410 1418
1411bool DataElem::endsWith(int i, TVVariant v) const 1419bool DataElem::endsWith(int i, TVVariant v) const
1412{ 1420{
1413 if (!hasValidValue(i)) return FALSE; 1421 if (!hasValidValue(i)) return FALSE;
1414 1422
1415 if (getField(i).type() != v.type()) 1423 if (getField(i).type() != v.type())
1416 return FALSE; 1424 return FALSE;
1417 1425
1418 switch(getField(i).type()) { 1426 switch(getField(i).type()) {
1419 case TVVariant::String: { 1427 case TVVariant::String: {
1420 QString qs1 = getField(i).toString().lower(); 1428 QString qs1 = getField(i).toString().lower();
1421 QString qs2 = v.toString().lower(); 1429 QString qs2 = v.toString().lower();
1422 return qs1.startsWith(qs2); 1430 return qs1.startsWith(qs2);
1423 } 1431 }
1424 /* meaningless for ints */ 1432 /* meaningless for ints */
1425 /* meaningless for time */ 1433 /* meaningless for time */
1426 /* meaningless for dates */ 1434 /* meaningless for dates */
1427 case TVVariant::Int: 1435 case TVVariant::Int:
1428 case TVVariant::Time: 1436 case TVVariant::Time:
1429 case TVVariant::Date: 1437 case TVVariant::Date:
1430 return FALSE; 1438 return FALSE;
1431 default: 1439 default:
1432 qWarning("Tried to compare unknown data type"); 1440 owarn << "Tried to compare unknown data type" << oendl;
1433 } 1441 }
1434 return FALSE; 1442 return FALSE;
1435} 1443}
1436 1444
1437/*! 1445/*!
1438 Determins which of the first to parameters are closer to the third, target 1446 Determins which of the first to parameters are closer to the third, target
1439 parameter. 1447 parameter.
1440 1448
1441 \return 1449 \return
1442 <UL> 1450 <UL>
1443 <LI>TRUE if the first element is a closer match to the target than the 1451 <LI>TRUE if the first element is a closer match to the target than the
1444 second element</LI> 1452 second element</LI>
1445 <LI>FALSE if the first element is not a closer match to the target than 1453 <LI>FALSE if the first element is not a closer match to the target than
1446 the second element</LI> 1454 the second element</LI>
1447 </UL> 1455 </UL>
1448*/ 1456*/
1449bool DataElem::closer(DataElem*d1, DataElem *d2, TVVariant target, int column) 1457bool DataElem::closer(DataElem*d1, DataElem *d2, TVVariant target, int column)
1450{ 1458{
1451 int type; 1459 int type;
1452 1460
1453 if(!d1) return FALSE; 1461 if(!d1) return FALSE;
1454 1462
1455 if (!d1->hasValidValue(column)) return FALSE; 1463 if (!d1->hasValidValue(column)) return FALSE;
1456 1464
1457 if(!target.isValid()) return FALSE; 1465 if(!target.isValid()) return FALSE;
1458 1466
1459 type = d1->getField(column).type(); 1467 type = d1->getField(column).type();
1460 1468
1461 if(d2) { 1469 if(d2) {
1462 if (type != d2->getField(column).type()) { 1470 if (type != d2->getField(column).type()) {
1463 /* can't do compare */ 1471 /* can't do compare */
1464 qWarning("Tried to compare two incompatable types"); 1472 owarn << "Tried to compare two incompatable types" << oendl;
1465 return FALSE; 1473 return FALSE;
1466 } 1474 }
1467 return target.closer(d1->getField(column), d2->getField(column)); 1475 return target.closer(d1->getField(column), d2->getField(column));
1468 } 1476 }
1469 return target.close(d1->getField(column)); 1477 return target.close(d1->getField(column));
1470} 1478}
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20/* 20/*
21 * This file is used to load the xml files that represent the database. 21 * This file is used to load the xml files that represent the database.
22 * The main requirment for said file is each data entry must contain a key, 22 * The main requirment for said file is each data entry must contain a key,
23 * otherwise any other data headings are allowed. 23 * otherwise any other data headings are allowed.
24 */ 24 */
25 25
26#include "datacache.h" 26#include "datacache.h"
27#include "xmlsource.h" 27#include "xmlsource.h"
28#include "csvsource.h" 28#include "csvsource.h"
29#include <stdlib.h> 29
30/* OPIE */
31#include <opie2/odebug.h>
32using namespace Opie::Core;
33
34/* QT */
30#include <qheader.h> 35#include <qheader.h>
31 36
37/* STD */
38#include <stdlib.h>
39
32#define INIT_TABLE_SIZE 128 40#define INIT_TABLE_SIZE 128
33 41
34/*! 42/*!
35 \class DBStore datastore.h 43 \class DBStore datastore.h
36 44
37 \brief The DBStore class is the class responsible for storing, sorting and 45 \brief The DBStore class is the class responsible for storing, sorting and
38 searching the data loaded by the application 46 searching the data loaded by the application
39 47
40*/ 48*/
41 49
42/*! 50/*!
43 Constructs a DBStore item 51 Constructs a DBStore item
44*/ 52*/
45DBStore::DBStore() 53DBStore::DBStore()
46{ 54{
47 name = ""; 55 name = "";
48 number_elems = 0; 56 number_elems = 0;
49 full = false; 57 full = false;
50 kRep = new KeyList(); 58 kRep = new KeyList();
51 master_table.resize(INIT_TABLE_SIZE); 59 master_table.resize(INIT_TABLE_SIZE);
52 table_size = INIT_TABLE_SIZE; 60 table_size = INIT_TABLE_SIZE;
53 61
54 current_elem = 0; 62 current_elem = 0;
55 archive = 0; 63 archive = 0;
56} 64}
57 65
58//TODO 66//TODO
59/*! 67/*!
60 Reinitializes the table to empty (include a resize of the master table, 68 Reinitializes the table to empty (include a resize of the master table,
61 which should free some memory) 69 which should free some memory)
62*/ 70*/
63void DBStore::freeTable() 71void DBStore::freeTable()
64{ 72{
65 name = ""; 73 name = "";
66 if(archive) { 74 if(archive) {
67 delete archive; 75 delete archive;
68 archive = 0; 76 archive = 0;
69 } 77 }
70 kRep->clear(); /* clear the current key list */ 78 kRep->clear(); /* clear the current key list */
71 79
72 number_elems = 0; 80 number_elems = 0;
73 table_size = INIT_TABLE_SIZE; 81 table_size = INIT_TABLE_SIZE;
74 master_table.resize(table_size); 82 master_table.resize(table_size);
75 full = false; 83 full = false;
76 current_elem = 0; 84 current_elem = 0;
77} 85}
78 86
79/*! 87/*!
80 Removes all items from the DBStore and destroys the DBStore 88 Removes all items from the DBStore and destroys the DBStore
81*/ 89*/
82DBStore::~DBStore() 90DBStore::~DBStore()
83{ 91{
84 freeTable(); 92 freeTable();
85} 93}
86 94
87/*! 95/*!
88 This function opens the given xml file, loads it and sets up the 96 This function opens the given xml file, loads it and sets up the
89 appropriate data structures. 97 appropriate data structures.
90 98
91 \param file_name A string representing the name of the file to be opened 99 \param file_name A string representing the name of the file to be opened
92 \return true if successful, false otherwise. 100 \return true if successful, false otherwise.
93*/ 101*/
94bool DBStore::openSource(QIODevice *inDev, const QString &source) { 102bool DBStore::openSource(QIODevice *inDev, const QString &source) {
95 103
96 /* first check if db is already open, if contains data.. then clear */ 104 /* first check if db is already open, if contains data.. then clear */
97 if(number_elems > 0) { 105 if(number_elems > 0) {
98 freeTable(); 106 freeTable();
99 } 107 }
100 108
101 if (source == "text/x-xml-tableviewer") { 109 if (source == "text/x-xml-tableviewer") {
102 archive = new DBXml(this); 110 archive = new DBXml(this);
103 } else if (source == "text/csv") { 111 } else if (source == "text/csv") {
104 archive = new DBCsv(this); 112 archive = new DBCsv(this);
105 } else 113 } else
106 return false; 114 return false;
107 115
108 return (archive->openSource(inDev)); 116 return (archive->openSource(inDev));
109} 117}
110 118
111bool DBStore::saveSource(QIODevice *outDev, const QString &source) 119bool DBStore::saveSource(QIODevice *outDev, const QString &source)
112{ 120{
113 /* saving a new file */ 121 /* saving a new file */
114 if(!archive) { 122 if(!archive) {
115 if (source == "text/x-xml-tableviewer") { 123 if (source == "text/x-xml-tableviewer") {
116 archive = new DBXml(this); 124 archive = new DBXml(this);
117 } else if (source == "text/x-xml-tableviewer") { 125 } else if (source == "text/x-xml-tableviewer") {
118 archive = new DBCsv(this); 126 archive = new DBCsv(this);
119 } else 127 } else
120 return false; 128 return false;
121 } 129 }
122 130
123 /* changing file type */ 131 /* changing file type */
124 if(archive->type() != source) { 132 if(archive->type() != source) {
125 delete archive; 133 delete archive;
126 if (source == "text/x-xml-tableviewer") { 134 if (source == "text/x-xml-tableviewer") {
127 archive = new DBXml(this); 135 archive = new DBXml(this);
128 } else if (source == "text/x-xml-tableviewer") { 136 } else if (source == "text/x-xml-tableviewer") {
129 archive = new DBCsv(this); 137 archive = new DBCsv(this);
130 } else 138 } else
131 return false; 139 return false;
132 } 140 }
133 141
134 return (archive->saveSource(outDev)); 142 return (archive->saveSource(outDev));
135} 143}
136 144
137/*! 145/*!
138 This function is used to add new elements to the database. If the database 146 This function is used to add new elements to the database. If the database
139 has already reached the maximum allowable size this function does not alter 147 has already reached the maximum allowable size this function does not alter
140 the database. 148 the database.
141 149
142 \param delm An already allocated and initialized data element to be added 150 \param delm An already allocated and initialized data element to be added
143*/ 151*/
144void DBStore::addItem(DataElem *delem) 152void DBStore::addItem(DataElem *delem)
145{ 153{
146 addItemInternal(delem); 154 addItemInternal(delem);
147} 155}
148 156
149void DBStore::addItemInternal(DataElem *delem) 157void DBStore::addItemInternal(DataElem *delem)
150{ 158{
151 /* if already full, don't over fill, do a qWarning though */ 159 /* if already full, don't over fill, do a qWarning though */
152 if (full) { 160 if (full) {
153 qWarning("Attempted to add items to already full table"); 161 owarn << "Attempted to add items to already full table" << oendl;
154 return; 162 return;
155 } 163 }
156 164
157 master_table.insert(number_elems, delem); 165 master_table.insert(number_elems, delem);
158 166
159 current_elem = number_elems; 167 current_elem = number_elems;
160 number_elems++; 168 number_elems++;
161 169
162 if(number_elems >= table_size) { 170 if(number_elems >= table_size) {
163 /* filled current table, double if we can */ 171 /* filled current table, double if we can */
164 table_size = table_size << 1; 172 table_size = table_size << 1;
165 173
166 /* check that the new table size is still valid, i.e. that we didn't 174 /* check that the new table size is still valid, i.e. that we didn't
167 just shift the 1 bit of the end of the int. */ 175 just shift the 1 bit of the end of the int. */
168 if (!table_size) { 176 if (!table_size) {
169 full = true; 177 full = true;
170 /* no point in doing antying else. */ 178 /* no point in doing antying else. */
171 return; 179 return;
172 } 180 }
173 master_table.resize(table_size); 181 master_table.resize(table_size);
174 } 182 }
175} 183}
176 184
177void DBStore::removeItem(DataElem *r) 185void DBStore::removeItem(DataElem *r)
178{ 186{
179 int position = master_table.findRef(r); 187 int position = master_table.findRef(r);
180 if(position != -1) { 188 if(position != -1) {
181 /* there is at least one item, this is it */ 189 /* there is at least one item, this is it */
182 /* replace this with the last element, decrease the element count */ 190 /* replace this with the last element, decrease the element count */
183 master_table.insert(position, master_table.at(--number_elems)); 191 master_table.insert(position, master_table.at(--number_elems));
184 master_table.remove(number_elems); 192 master_table.remove(number_elems);
185 delete r; 193 delete r;
186 } 194 }
187} 195}
188 196
189/*! 197/*!
190 Sets the name of the database 198 Sets the name of the database
191 199
192 \param n A string representing the new name of the database. 200 \param n A string representing the new name of the database.
193*/ 201*/
194void DBStore::setName(const QString &n) 202void DBStore::setName(const QString &n)
195{ 203{
196 name = n; 204 name = n;
197} 205}
198 206
199/*! 207/*!
200 Gets the name of the database 208 Gets the name of the database
201 209
202 \return A string representing the name of the database. 210 \return A string representing the name of the database.
203*/ 211*/
204QString DBStore::getName() 212QString DBStore::getName()
205{ 213{
206 return name; 214 return name;
207} 215}
208 216
209/*! 217/*!
210 Retrieves a pointer to the key representation of the database for 218 Retrieves a pointer to the key representation of the database for
211 other classes to use as reference. 219 other classes to use as reference.
212 220
213 \return a pointer to the databases key representaion 221 \return a pointer to the databases key representaion
214*/ 222*/
215KeyList *DBStore::getKeys() 223KeyList *DBStore::getKeys()
216{ 224{
217 return kRep; 225 return kRep;
218} 226}
219 227
220/*! 228/*!
221 sets the database's key representation the passed pointer 229 sets the database's key representation the passed pointer
222 \param a pointer to a key representaton 230 \param a pointer to a key representaton
223*/ 231*/
224void DBStore::setKeys(KeyList *k) 232void DBStore::setKeys(KeyList *k)
225{ 233{
226 kRep = k; 234 kRep = k;
227} 235}
228 236
229/*! 237/*!
230 Sets the current element to the first element of the database 238 Sets the current element to the first element of the database
231*/ 239*/
232void DBStore::first() 240void DBStore::first()
233{ 241{
234 current_elem = 0; 242 current_elem = 0;
235} 243}
236 244
237/*! 245/*!
238 Sets the current element to the last element of the database 246 Sets the current element to the last element of the database
239*/ 247*/
240void DBStore::last() 248void DBStore::last()
241{ 249{
242 current_elem = number_elems - 1; 250 current_elem = number_elems - 1;
243} 251}
244 252
245/*! 253/*!
246 Sets the current element to the next element of the database if 254 Sets the current element to the next element of the database if
247 there exists an element after the current one. 255 there exists an element after the current one.
248*/ 256*/
249bool DBStore::next() 257bool 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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include "xmlsource.h" 20#include "xmlsource.h"
21#include <qdict.h>
22#include <stdlib.h>
23#include <qtextstream.h>
24#include "../xmlencodeattr.h" 21#include "../xmlencodeattr.h"
25 22
23/* OPIE */
24#include <opie2/odebug.h>
25using namespace Opie::Core;
26 26
27/* QT */
28#include <qdict.h>
29#include <qtextstream.h>
30
31/* STD */
32#include <stdlib.h>
27 33
28DBXml::DBXml(DBStore *d) 34DBXml::DBXml(DBStore *d)
29{ 35{
30 dstore = d; 36 dstore = d;
31} 37}
32 38
33QString DBXml::type() 39QString DBXml::type()
34{ 40{
35 return "xml"; 41 return "xml";
36} 42}
37 43
38bool DBXml::openSource(QIODevice *inDev) 44bool DBXml::openSource(QIODevice *inDev)
39{ 45{
40 bool ok; 46 bool ok;
41 47
42 DBXmlHandler h(dstore); 48 DBXmlHandler h(dstore);
43 49
44 QTextStream tsIn(inDev); 50 QTextStream tsIn(inDev);
45 QXmlInputSource source(tsIn); 51 QXmlInputSource source(tsIn);
46 QXmlSimpleReader reader; 52 QXmlSimpleReader reader;
47 reader.setContentHandler(&h); 53 reader.setContentHandler(&h);
48 reader.setErrorHandler(&h); 54 reader.setErrorHandler(&h);
49 ok = reader.parse(source); 55 ok = reader.parse(source);
50 56
51 return ok; 57 return ok;
52} 58}
53 59
54bool DBXml::saveSource(QIODevice *outDev) 60bool DBXml::saveSource(QIODevice *outDev)
55{ 61{
56 int i; 62 int i;
57 DataElem *elem; 63 DataElem *elem;
58 KeyList *k; 64 KeyList *k;
59 65
60 QTextStream outstream(outDev); 66 QTextStream outstream(outDev);
61 67
62 outstream << "<database name=\"" << dstore->getName() << "\">" << endl; 68 outstream << "<database name=\"" << dstore->getName() << "\">" << endl;
63 outstream << "<header>" << endl; 69 outstream << "<header>" << endl;
64 70
65 k = dstore->getKeys(); 71 k = dstore->getKeys();
66 KeyListIterator it(*k); 72 KeyListIterator it(*k);
67 while(it.current()) { 73 while(it.current()) {
68 if (!it.current()->delFlag()) { 74 if (!it.current()->delFlag()) {
69 outstream << "<key name=\"KEYID" << it.currentKey() << "\" "; 75 outstream << "<key name=\"KEYID" << it.currentKey() << "\" ";
70 outstream << "type=\"" 76 outstream << "type=\""
71 << TVVariant::typeToName(it.current()->type()) 77 << TVVariant::typeToName(it.current()->type())
72 << "\">"; 78 << "\">";
73 outstream << encodeAttr(it.current()->name()) << "</key>" << endl; 79 outstream << encodeAttr(it.current()->name()) << "</key>" << endl;
74 } 80 }
75 ++it; 81 ++it;
76 } 82 }
77 83
78 outstream << "</header>" << endl; 84 outstream << "</header>" << endl;
79 85
80 dstore->first(); 86 dstore->first();
81 87
82 do { 88 do {
83 elem = dstore->getCurrentData(); 89 elem = dstore->getCurrentData();
84 if (!elem) 90 if (!elem)
85 break; 91 break;
86 outstream << "<record>" << endl; 92 outstream << "<record>" << endl;
87 it.toFirst(); 93 it.toFirst();
88 while (it.current()) { 94 while (it.current()) {
89 i = it.currentKey(); 95 i = it.currentKey();
90 if (elem->hasValidValue(i)) { 96 if (elem->hasValidValue(i)) {
91 outstream << "<KEYID" << i << ">"; 97 outstream << "<KEYID" << i << ">";
92 if (dstore->getKeyType(i) == TVVariant::Date) { 98 if (dstore->getKeyType(i) == TVVariant::Date) {
93 // dates in files are different from displayed dates 99 // dates in files are different from displayed dates
94 QDate date = elem->getField(i).toDate(); 100 QDate date = elem->getField(i).toDate();
95 outstream << date.day() << "/" 101 outstream << date.day() << "/"
96 << date.month() << "/" 102 << date.month() << "/"
97 << date.year(); 103 << date.year();
98 } else { 104 } else {
99 outstream << encodeAttr(elem->toQString(i)); 105 outstream << encodeAttr(elem->toQString(i));
100 } 106 }
101 outstream << "</KEYID" << i << ">" << endl; 107 outstream << "</KEYID" << i << ">" << endl;
102 } 108 }
103 ++it; 109 ++it;
104 } 110 }
105 outstream << "</record>" << endl; 111 outstream << "</record>" << endl;
106 } while(dstore->next()); 112 } while(dstore->next());
107 113
108 outstream << "</database>" << endl; 114 outstream << "</database>" << endl;
109 return TRUE; 115 return TRUE;
110} 116}
111 117
112DBXml::~DBXml() {} 118DBXml::~DBXml() {}
113 119
114/*! 120/*!
115 \class DBXmlHandler 121 \class DBXmlHandler
116 \brief An Xml parser for flat tables. 122 \brief An Xml parser for flat tables.
117 123
118 An xml parser for parsing the files used by the table viewer application. 124 An xml parser for parsing the files used by the table viewer application.
119 125
120 The format of the xml files can be found at the front of the file 126 The format of the xml files can be found at the front of the file
121 dataparser.h 127 dataparser.h
122*/ 128*/
123 129
124/*! 130/*!
125 Constructs a new DBXmlHandler, and sets that the table should be 131 Constructs a new DBXmlHandler, and sets that the table should be
126 constructed in the DBStore pointed to by ds. 132 constructed in the DBStore pointed to by ds.
127*/ 133*/
128DBXmlHandler::DBXmlHandler(DBStore *ds) 134DBXmlHandler::DBXmlHandler(DBStore *ds)
129{ 135{
130 data_store = ds; 136 data_store = ds;
131 current_keyrep = 0; 137 current_keyrep = 0;
132} 138}
133 139
134/*! 140/*!
135 Destroys the DBXmlHandler 141 Destroys the DBXmlHandler
136*/ 142*/
137DBXmlHandler::~DBXmlHandler() 143DBXmlHandler::~DBXmlHandler()
138{ 144{
139} 145}
140 146
141QString DBXmlHandler::errorProtocol() 147QString DBXmlHandler::errorProtocol()
142{ 148{
143 qWarning("Error reading file"); 149 owarn << "Error reading file" << oendl;
144 return errorProt; 150 return errorProt;
145} 151}
146 152
147bool DBXmlHandler::startDocument() 153bool DBXmlHandler::startDocument()
148{ 154{
149 errorProt = ""; 155 errorProt = "";
150 state = StateInit; 156 state = StateInit;
151 return TRUE; 157 return TRUE;
152} 158}
153 159
154bool DBXmlHandler::startElement(const QString&, const QString&, 160bool DBXmlHandler::startElement(const QString&, const QString&,
155 const QString& qName, const QXmlAttributes& atts) 161 const QString& qName, const QXmlAttributes& atts)
156{ 162{
157 if (state == StateInit && qName == "database") { 163 if (state == StateInit && qName == "database") {
158 // First thing it expects is a <document name="..."> tag 164 // First thing it expects is a <document name="..."> tag
159 state = StateDocument; 165 state = StateDocument;
160 data_store->setName(atts.value("name")); 166 data_store->setName(atts.value("name"));
161 return TRUE; 167 return TRUE;
162 } 168 }
163 if (state == StateDocument && qName == "header") { 169 if (state == StateDocument && qName == "header") {
164 state = StateHeader; 170 state = StateHeader;
165 if (current_keyrep) delete current_keyrep; 171 if (current_keyrep) delete current_keyrep;
166 current_keyrep = new KeyList(); 172 current_keyrep = new KeyList();
167 return TRUE; 173 return TRUE;
168 } 174 }
169 if (state == StateHeader && qName == "key") { 175 if (state == StateHeader && qName == "key") {
170 /* Ok, adding a new key to our KeyList TODO */ 176 /* Ok, adding a new key to our KeyList TODO */
171 state = StateKey; 177 state = StateKey;
172 last_key_type = TVVariant::String; 178 last_key_type = TVVariant::String;
173 key = atts.value("name"); 179 key = atts.value("name");
174 if (key.isEmpty()) { 180 if (key.isEmpty()) {
175 qWarning("empty key name"); 181 owarn << "empty key name" << oendl;
176 return FALSE; 182 return FALSE;
177 } 183 }
178 if(!atts.value("type").isEmpty()) 184 if(!atts.value("type").isEmpty())
179 last_key_type = TVVariant::nameToType(atts.value("type")); 185 last_key_type = TVVariant::nameToType(atts.value("type"));
180 return TRUE; 186 return TRUE;
181 } 187 }
182 if (state == StateDocument && qName == "record") { 188 if (state == StateDocument && qName == "record") {
183 state = StateRecord; 189 state = StateRecord;
184 current_data = new DataElem(data_store); 190 current_data = new DataElem(data_store);
185 // Now expecting a <record> tag 191 // Now expecting a <record> tag
186 return TRUE; 192 return TRUE;
187 } 193 }
188 if (state == StateRecord) { 194 if (state == StateRecord) {
189 state = StateField; 195 state = StateField;
190 /* the qName is the name of a key */ 196 /* the qName is the name of a key */
191 if (!keyIndexList[qName]) { 197 if (!keyIndexList[qName]) {
192 /* invalid key, we failed */ 198 /* invalid key, we failed */
193 qWarning("Invalid key in record"); 199 owarn << "Invalid key in record" << oendl;
194 return FALSE; 200 return FALSE;
195 } 201 }
196 keyIndex = *keyIndexList[qName]; 202 keyIndex = *keyIndexList[qName];
197 return TRUE; 203 return TRUE;
198 } 204 }
199 qWarning("Unable to determine tag type"); 205 owarn << "Unable to determine tag type" << oendl;
200 return FALSE; 206 return FALSE;
201} 207}
202 208
203bool DBXmlHandler::endElement(const QString&, const QString&, 209bool DBXmlHandler::endElement(const QString&, const QString&,
204 const QString& qName) 210 const QString& qName)
205{ 211{
206 switch(state) { 212 switch(state) {
207 case StateField: 213 case StateField:
208 // TODO checks 'could' be done of the popped value 214 // TODO checks 'could' be done of the popped value
209 state = StateRecord; 215 state = StateRecord;
210 break; 216 break;
211 case StateKey: 217 case StateKey:
212 // TODO checks 'could' be done of the popped value 218 // TODO checks 'could' be done of the popped value
213 state = StateHeader; 219 state = StateHeader;
214 break; 220 break;
215 case StateHeader: 221 case StateHeader:
216 data_store->setKeys(current_keyrep); 222 data_store->setKeys(current_keyrep);
217 state = StateDocument; 223 state = StateDocument;
218 break; 224 break;
219 case StateRecord: 225 case StateRecord:
220 data_store->addItem(current_data); 226 data_store->addItem(current_data);
221 state = StateDocument; 227 state = StateDocument;
222 break; 228 break;
223 case StateDocument: 229 case StateDocument:
224 // we are done... 230 // we are done...
225 break; 231 break;
226 default: 232 default:
227 // should only get a 'endElement' from one of the above states. 233 // should only get a 'endElement' from one of the above states.
228 qWarning("Invalid end tag"); 234 owarn << "Invalid end tag" << oendl;
229 return FALSE; 235 return FALSE;
230 break; 236 break;
231 } 237 }
232 return TRUE; 238 return TRUE;
233} 239}
234 240
235bool DBXmlHandler::characters(const QString& ch) 241bool DBXmlHandler::characters(const QString& ch)
236{ 242{
237 // this is where the 'between tag' stuff happens. 243 // this is where the 'between tag' stuff happens.
238 // e.g. the stuff between tags. 244 // e.g. the stuff between tags.
239 QString ch_simplified = ch.simplifyWhiteSpace(); 245 QString ch_simplified = ch.simplifyWhiteSpace();
240 246
241 if (ch_simplified.isEmpty()) 247 if (ch_simplified.isEmpty())
242 return TRUE; 248 return TRUE;
243 249
244 if (state == StateKey) { 250 if (state == StateKey) {
245 int *tmp_val = new int; 251 int *tmp_val = new int;
246 /* We just grabbed the display name of a key */ 252 /* We just grabbed the display name of a key */
247 *tmp_val = current_keyrep->addKey(ch_simplified, last_key_type); 253 *tmp_val = current_keyrep->addKey(ch_simplified, last_key_type);
248 keyIndexList.insert(key, tmp_val); 254 keyIndexList.insert(key, tmp_val);
249 return TRUE; 255 return TRUE;
250 } 256 }
251 if (state == StateField) { 257 if (state == StateField) {
252 /* Ok, need to add data here */ 258 /* Ok, need to add data here */
253 current_data->setField(keyIndex, ch_simplified); 259 current_data->setField(keyIndex, ch_simplified);
254 return TRUE; 260 return TRUE;
255 } 261 }
256 262
257 qWarning("Junk characters found... ignored"); 263 owarn << "Junk characters found... ignored" << oendl;
258 return TRUE; 264 return TRUE;
259} 265}
260 266
261QString DBXmlHandler::errorString() 267QString DBXmlHandler::errorString()
262{ 268{
263 return "the document is not in the expected file format"; 269 return "the document is not in the expected file format";
264} 270}
265 271
266bool DBXmlHandler::warning(const QXmlParseException& exception) 272bool DBXmlHandler::warning(const QXmlParseException& exception)
267{ 273{
268 errorProt += QString("warning parsing error: %1 in line %2, column %3\n" ) 274 errorProt += QString("warning parsing error: %1 in line %2, column %3\n" )
269 .arg(exception.message()) 275 .arg(exception.message())
270 .arg(exception.lineNumber()) 276 .arg(exception.lineNumber())
271 .arg(exception.columnNumber()); 277 .arg(exception.columnNumber());
272 278
273 qWarning(errorProt); 279 owarn << errorProt << oendl;
274 return QXmlDefaultHandler::fatalError(exception); 280 return QXmlDefaultHandler::fatalError(exception);
275} 281}
276 282
277bool DBXmlHandler::error(const QXmlParseException& exception) 283bool DBXmlHandler::error(const QXmlParseException& exception)
278{ 284{
279 errorProt += QString("error parsing error: %1 in line %2, column %3\n" ) 285 errorProt += QString("error parsing error: %1 in line %2, column %3\n" )
280 .arg(exception.message()) 286 .arg(exception.message())
281 .arg(exception.lineNumber()) 287 .arg(exception.lineNumber())
282 .arg(exception.columnNumber()); 288 .arg(exception.columnNumber());
283 289
284 qWarning(errorProt); 290 owarn << errorProt << oendl;
285 return QXmlDefaultHandler::fatalError(exception); 291 return QXmlDefaultHandler::fatalError(exception);
286} 292}
287 293
288bool DBXmlHandler::fatalError(const QXmlParseException& exception) 294bool DBXmlHandler::fatalError(const QXmlParseException& exception)
289{ 295{
290 errorProt += QString("fatal parsing error: %1 in line %2, column %3\n" ) 296 errorProt += QString("fatal parsing error: %1 in line %2, column %3\n" )
291 .arg(exception.message()) 297 .arg(exception.message())
292 .arg(exception.lineNumber()) 298 .arg(exception.lineNumber())
293 .arg(exception.columnNumber()); 299 .arg(exception.columnNumber());
294 300
295 qWarning(errorProt); 301 owarn << errorProt << oendl;
296 return QXmlDefaultHandler::fatalError(exception); 302 return QXmlDefaultHandler::fatalError(exception);
297} 303}
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21/* local includes */
22#include "tableviewer.h" 21#include "tableviewer.h"
23#include "ui/tvbrowseview.h" 22#include "ui/tvbrowseview.h"
24#include "ui/tvfilterview.h" 23#include "ui/tvfilterview.h"
25#include "ui/tvlistview.h" 24#include "ui/tvlistview.h"
26#include "ui/tveditview.h" 25#include "ui/tveditview.h"
27#include "ui/tvkeyedit.h" 26#include "ui/tvkeyedit.h"
28#include "db/datacache.h" 27#include "db/datacache.h"
29 28
30/* QPE includes */ 29/* OPIE */
30#include <opie2/odebug.h>
31#include <qpe/fileselector.h> 31#include <qpe/fileselector.h>
32#include <qpe/resource.h> 32#include <qpe/resource.h>
33#include <qtoolbar.h> 33using namespace Opie::Core;
34 34
35/* QTE includes */ 35/* QT */
36#include <qmenubar.h> 36#include <qmenubar.h>
37#include <qtoolbar.h>
37#include <qpopupmenu.h> 38#include <qpopupmenu.h>
38#include <qapplication.h> 39#include <qapplication.h>
39#include <qwidgetstack.h> 40#include <qwidgetstack.h>
40#include <qlayout.h> 41#include <qlayout.h>
41#include <qbuffer.h> 42#include <qbuffer.h>
43
42/*! 44/*!
43 \class TableViewerWindow 45 \class TableViewerWindow
44 \brief The main window widget of the application 46 \brief The main window widget of the application
45 47
46 This is the main widget of the table viewer application. 48 This is the main widget of the table viewer application.
47 It is the co-ordination point. 49 It is the co-ordination point.
48*/ 50*/
49 51
50/*! 52/*!
51 Constructs a new TableViewerWindow 53 Constructs a new TableViewerWindow
52*/ 54*/
53TableViewerWindow::TableViewerWindow(QWidget *parent, const char *name, WFlags f) 55TableViewerWindow::TableViewerWindow(QWidget *parent, const char *name, WFlags f)
54 : QMainWindow(parent, name, f) 56 : QMainWindow(parent, name, f)
55{ 57{
56 setCaption(tr("Table Viewer")); 58 setCaption(tr("Table Viewer"));
57 59
58/* Build data */ 60/* Build data */
59 ds = new DBStore(); 61 ds = new DBStore();
60 doc.setType("text/x-xml-tableviewer"); 62 doc.setType("text/x-xml-tableviewer");
61 doc.setName("table"); 63 doc.setName("table");
62 64
63 dirty = FALSE; 65 dirty = FALSE;
64 ts.current_column = 0; 66 ts.current_column = 0;
65 ts.kRep = ds->getKeys(); 67 ts.kRep = ds->getKeys();
66 68
67/* build menus */ 69/* build menus */
68 menu = new QMenuBar(this, 0); 70 menu = new QMenuBar(this, 0);
69 71
70 QPopupMenu *file_menu = new QPopupMenu; 72 QPopupMenu *file_menu = new QPopupMenu;
71 file_menu->insertItem("New", this, SLOT(newDocument())); 73 file_menu->insertItem("New", this, SLOT(newDocument()));
72 74
73 file_menu->insertItem("Open", this, SLOT(selectDocument())); 75 file_menu->insertItem("Open", this, SLOT(selectDocument()));
74 file_menu->insertSeparator(); 76 file_menu->insertSeparator();
75 file_menu->insertItem("Properties"); 77 file_menu->insertItem("Properties");
76 78
77 /* later will want to set this up to clean up first via this, SLOT(quit) */ 79 /* later will want to set this up to clean up first via this, SLOT(quit) */
78 menu->insertItem("Document", file_menu); 80 menu->insertItem("Document", file_menu);
79 81
80 QPopupMenu *edit_menu = new QPopupMenu; 82 QPopupMenu *edit_menu = new QPopupMenu;
81 edit_menu->insertItem("Edit Item", this, SLOT(editItemSlot())); 83 edit_menu->insertItem("Edit Item", this, SLOT(editItemSlot()));
82 edit_menu->insertItem("Edit Keys", this, SLOT(editKeysSlot())); 84 edit_menu->insertItem("Edit Keys", this, SLOT(editKeysSlot()));
83 edit_menu->insertItem("Edit filters", this, SLOT(filterViewSlot())); 85 edit_menu->insertItem("Edit filters", this, SLOT(filterViewSlot()));
84 menu->insertItem("Edit", edit_menu); 86 menu->insertItem("Edit", edit_menu);
85 87
86 QPopupMenu *view_menu = new QPopupMenu; 88 QPopupMenu *view_menu = new QPopupMenu;
87 view_menu->insertItem("Browse View", this, SLOT(browseViewSlot())); 89 view_menu->insertItem("Browse View", this, SLOT(browseViewSlot()));
88 view_menu->insertItem("List View", this, SLOT(listViewSlot())); 90 view_menu->insertItem("List View", this, SLOT(listViewSlot()));
89 menu->insertItem("View", view_menu); 91 menu->insertItem("View", view_menu);
90 92
91 QVBoxLayout *main_layout = new QVBoxLayout; 93 QVBoxLayout *main_layout = new QVBoxLayout;
92 94
93 /* Build tool bar */ 95 /* Build tool bar */
94 navigation = new QToolBar(this, "navigation"); 96 navigation = new QToolBar(this, "navigation");
95 QToolButton *newItemButton = new QToolButton( 97 QToolButton *newItemButton = new QToolButton(
96 QIconSet(Resource::loadPixmap("new")), "New Item", QString::null, 98 QIconSet(Resource::loadPixmap("new")), "New Item", QString::null,
97 this, SLOT(newItemSlot()), navigation, "New Item"); 99 this, SLOT(newItemSlot()), navigation, "New Item");
98 QToolButton *editItemButton = new QToolButton( 100 QToolButton *editItemButton = new QToolButton(
99 QIconSet(Resource::loadPixmap("edit")), "Edit Item", QString::null, 101 QIconSet(Resource::loadPixmap("edit")), "Edit Item", QString::null,
100 this, SLOT(editItemSlot()), navigation, "Edit Item"); 102 this, SLOT(editItemSlot()), navigation, "Edit Item");
101 QToolButton *deleteItemButton = new QToolButton( 103 QToolButton *deleteItemButton = new QToolButton(
102 QIconSet(Resource::loadPixmap("trash")), "Delete Item", 104 QIconSet(Resource::loadPixmap("trash")), "Delete Item",
103 QString::null, this, 105 QString::null, this,
104 SLOT(deleteItemSlot()), navigation, "Delete Item"); 106 SLOT(deleteItemSlot()), navigation, "Delete Item");
105 107
106 navigation->addSeparator(); 108 navigation->addSeparator();
107 109
108 QToolButton *firstItemButton = new QToolButton( 110 QToolButton *firstItemButton = new QToolButton(
109 QIconSet(Resource::loadPixmap("fastback")), "First Item", 111 QIconSet(Resource::loadPixmap("fastback")), "First Item",
110 QString::null, this, 112 QString::null, this,
111 SLOT(firstItem()), navigation, "First Item"); 113 SLOT(firstItem()), navigation, "First Item");
112 QToolButton *previousItemButton = new QToolButton( 114 QToolButton *previousItemButton = new QToolButton(
113 QIconSet(Resource::loadPixmap("back")), "Previous Item", 115 QIconSet(Resource::loadPixmap("back")), "Previous Item",
114 QString::null, this, 116 QString::null, this,
115 SLOT(previousItem()), navigation, "Previous Item"); 117 SLOT(previousItem()), navigation, "Previous Item");
116 QToolButton *nextItemButton = new QToolButton( 118 QToolButton *nextItemButton = new QToolButton(
117 QIconSet(Resource::loadPixmap("forward")), "Next Item", 119 QIconSet(Resource::loadPixmap("forward")), "Next Item",
118 QString::null, this, 120 QString::null, this,
119 SLOT(nextItem()), navigation, "Next Item"); 121 SLOT(nextItem()), navigation, "Next Item");
120 QToolButton *lastItemButton = new QToolButton( 122 QToolButton *lastItemButton = new QToolButton(
121 QIconSet(Resource::loadPixmap("fastforward")), "Last Item", 123 QIconSet(Resource::loadPixmap("fastforward")), "Last Item",
122 QString::null, this, 124 QString::null, this,
123 SLOT(lastItem()), navigation, "Last Item"); 125 SLOT(lastItem()), navigation, "Last Item");
124 126
125 navigation->addSeparator(); 127 navigation->addSeparator();
126 QToolButton *browseButton = new QToolButton( 128 QToolButton *browseButton = new QToolButton(
127 QIconSet(Resource::loadPixmap("day")), "View Single Item", 129 QIconSet(Resource::loadPixmap("day")), "View Single Item",
128 QString::null, this, 130 QString::null, this,
129 SLOT(browseViewSlot()), navigation, "View Single Item"); 131 SLOT(browseViewSlot()), navigation, "View Single Item");
130 QToolButton *listButton = new QToolButton( 132 QToolButton *listButton = new QToolButton(
131 QIconSet(Resource::loadPixmap("month")), "View Multiple Items", 133 QIconSet(Resource::loadPixmap("month")), "View Multiple Items",
132 QString::null, this, 134 QString::null, this,
133 SLOT(listViewSlot()), navigation, "View Multiple Items"); 135 SLOT(listViewSlot()), navigation, "View Multiple Items");
134 136
135 setToolBarsMovable(FALSE); 137 setToolBarsMovable(FALSE);
136 setToolBarsMovable(FALSE); 138 setToolBarsMovable(FALSE);
137 setToolBarsMovable(FALSE); 139 setToolBarsMovable(FALSE);
138 140
139/* Build widgets */ 141/* Build widgets */
140 browseView = new TVBrowseView(&ts, this, 0); 142 browseView = new TVBrowseView(&ts, this, 0);
141 listView = new TVListView(&ts, this, 0); 143 listView = new TVListView(&ts, this, 0);
142 filterView = new TVFilterView(&ts, this, 0); 144 filterView = new TVFilterView(&ts, this, 0);
143 fileSelector = new FileSelector("text/csv;text/x-xml-tableviewer", 145 fileSelector = new FileSelector("text/csv;text/x-xml-tableviewer",
144 this, "fileselector"); 146 this, "fileselector");
145 fileSelector->setNewVisible(FALSE); 147 fileSelector->setNewVisible(FALSE);
146 fileSelector->setCloseVisible(FALSE); 148 fileSelector->setCloseVisible(FALSE);
147 149
148 cw = new QWidgetStack(this, 0); 150 cw = new QWidgetStack(this, 0);
149 cw->addWidget(listView, ListState); 151 cw->addWidget(listView, ListState);
150 cw->addWidget(browseView, BrowseState); 152 cw->addWidget(browseView, BrowseState);
151 cw->addWidget(filterView, FilterState); 153 cw->addWidget(filterView, FilterState);
152 cw->addWidget(fileSelector, FileState); 154 cw->addWidget(fileSelector, FileState);
153 155
154 current_view = FileState; 156 current_view = FileState;
155 cw->raiseWidget(current_view); 157 cw->raiseWidget(current_view);
156 fileSelector->reread(); 158 fileSelector->reread();
157 159
158 connect(browseView, SIGNAL(searchOnKey(int,TVVariant)), 160 connect(browseView, SIGNAL(searchOnKey(int,TVVariant)),
159 this, SLOT(searchOnKey(int,TVVariant))); 161 this, SLOT(searchOnKey(int,TVVariant)));
160 connect(browseView, SIGNAL(sortChanged(int)), 162 connect(browseView, SIGNAL(sortChanged(int)),
161 this, SLOT(setPrimaryKey(int))); 163 this, SLOT(setPrimaryKey(int)));
162 164
163 connect(fileSelector, SIGNAL(closeMe()), this, SLOT(browseViewSlot())); 165 connect(fileSelector, SIGNAL(closeMe()), this, SLOT(browseViewSlot()));
164 connect(fileSelector, SIGNAL(fileSelected(const DocLnk&)), 166 connect(fileSelector, SIGNAL(fileSelected(const DocLnk&)),
165 this, SLOT(openDocument(const DocLnk&))); 167 this, SLOT(openDocument(const DocLnk&)));
166 168
167 main_layout->addWidget(menu); 169 main_layout->addWidget(menu);
168 main_layout->addWidget(cw); 170 main_layout->addWidget(cw);
169 171
170 setCentralWidget(cw); 172 setCentralWidget(cw);
171 173
172} 174}
173 175
174/*! 176/*!
175 Destroys the TableViewerWindow 177 Destroys the TableViewerWindow
176*/ 178*/
177TableViewerWindow::~TableViewerWindow() 179TableViewerWindow::~TableViewerWindow()
178{ 180{
179 if(dirty) 181 if(dirty)
180 saveDocument(); 182 saveDocument();
181} 183}
182 184
183/*! 185/*!
184 Opens a file dialog and loads the file specified by the dialog 186 Opens a file dialog and loads the file specified by the dialog
185*/ 187*/
186void TableViewerWindow::selectDocument() 188void TableViewerWindow::selectDocument()
187{ 189{
188 if(dirty) 190 if(dirty)
189 saveDocument(); 191 saveDocument();
190 current_view = FileState; 192 current_view = FileState;
191 cw->raiseWidget(current_view); 193 cw->raiseWidget(current_view);
192 fileSelector->reread(); 194 fileSelector->reread();
193} 195}
194 196
195void TableViewerWindow::saveDocument() 197void TableViewerWindow::saveDocument()
196{ 198{
197 if(!dirty) 199 if(!dirty)
198 return; 200 return;
199 201
200 FileManager fm; 202 FileManager fm;
201 QIODevice *dev = fm.saveFile(doc); 203 QIODevice *dev = fm.saveFile(doc);
202 204
203 if(!ds->saveSource(dev, doc.type())){ 205 if(!ds->saveSource(dev, doc.type())){
204 qWarning("Save unsuccessful"); 206 owarn << "Save unsuccessful" << oendl;
205 return; 207 return;
206 } 208 }
207 dev->close(); 209 dev->close();
208 dirty = FALSE; 210 dirty = FALSE;
209} 211}
210 212
211void TableViewerWindow::newDocument() 213void TableViewerWindow::newDocument()
212{ 214{
213 DocLnk nf; 215 DocLnk nf;
214 nf.setType("text/x-xml-tableviewer"); 216 nf.setType("text/x-xml-tableviewer");
215 nf.setName("table"); 217 nf.setName("table");
216 218
217 delete ds; 219 delete ds;
218 ds = new DBStore(); 220 ds = new DBStore();
219 221
220 ts.current_column = 0; 222 ts.current_column = 0;
221 ts.kRep = ds->getKeys(); 223 ts.kRep = ds->getKeys();
222 browseView->reset(); 224 browseView->reset();
223 listView->reset(); 225 listView->reset();
224 filterView->reset(); 226 filterView->reset();
225 227
226 doc = nf; 228 doc = nf;
227 dirty = FALSE; 229 dirty = FALSE;
228 230
229 current_view = BrowseState; 231 current_view = BrowseState;
230 cw->raiseWidget(current_view); 232 cw->raiseWidget(current_view);
231 233
232 /* now set up for editing the keys */ 234 /* now set up for editing the keys */
233 ts.kRep->addKey("key", TVVariant::String); 235 ts.kRep->addKey("key", TVVariant::String);
234 editKeysSlot(); 236 editKeysSlot();
235} 237}
236 238
237void TableViewerWindow::setDocument(const QString &f) 239void TableViewerWindow::setDocument(const QString &f)
238{ 240{
239 openDocument(DocLnk(f, TRUE)); 241 openDocument(DocLnk(f, TRUE));
240} 242}
241 243
242void TableViewerWindow::openDocument(const DocLnk &f) 244void TableViewerWindow::openDocument(const DocLnk &f)
243{ 245{
244 246
245 if (!f.isValid()) 247 if (!f.isValid())
246 return; 248 return;
247 249
248 FileManager fm; 250 FileManager fm;
249 QIODevice *dev = fm.openFile(f); 251 QIODevice *dev = fm.openFile(f);
250 doc = f; 252 doc = f;
251 253
252 if(ds->openSource(dev, doc.type())) { 254 if(ds->openSource(dev, doc.type())) {
253 DataElem *d; 255 DataElem *d;
254 256
255 browseView->reset(); 257 browseView->reset();
256 listView->reset(); 258 listView->reset();
257 filterView->reset(); 259 filterView->reset();
258 260
259 current_view = BrowseState; 261 current_view = BrowseState;
260 cw->raiseWidget(current_view); 262 cw->raiseWidget(current_view);
261 263
262 /* set up new table state and ensure sub widgets have a reference */ 264 /* set up new table state and ensure sub widgets have a reference */
263 ts.current_column = 0; 265 ts.current_column = 0;
264 ts.kRep = ds->getKeys(); 266 ts.kRep = ds->getKeys();
265 browseView->rebuildKeys(); 267 browseView->rebuildKeys();
266 listView->rebuildKeys(); 268 listView->rebuildKeys();
267 filterView->rebuildKeys(); 269 filterView->rebuildKeys();
268 270
269 ds->first(); 271 ds->first();
270 /* set up the list view */ 272 /* set up the list view */
271 listView->clearItems(); 273 listView->clearItems();
272 do { 274 do {
273 d = ds->getCurrentData(); 275 d = ds->getCurrentData();
274 if(d) 276 if(d)
275 listView->addItem(d); 277 listView->addItem(d);
276 } while(ds->next()); 278 } while(ds->next());
277 279
278 /* Set up browse view, Will be based of structure of listView */ 280 /* Set up browse view, Will be based of structure of listView */
279 listView->first(); 281 listView->first();
280 ts.current_elem = listView->getCurrentData(); 282 ts.current_elem = listView->getCurrentData();
281 browseView->rebuildData(); 283 browseView->rebuildData();
282 listView->rebuildData(); 284 listView->rebuildData();
283 285
284 QString scratch = "Table Viewer";/* later take from constant */ 286 QString scratch = "Table Viewer";/* later take from constant */
285 scratch += " - "; 287 scratch += " - ";
286 scratch += ds->getName(); 288 scratch += ds->getName();
287 setCaption(tr(scratch)); 289 setCaption(tr(scratch));
288 290
289 dirty = FALSE; 291 dirty = FALSE;
290 } else { 292 } else {
291 qWarning(tr("could not load Document")); 293 owarn << tr("could not load Document") << oendl;
292 } 294 }
293 dev->close(); 295 dev->close();
294} 296}
295 297
296/*! 298/*!
297 Moves to the first item of the current table 299 Moves to the first item of the current table
298*/ 300*/
299void TableViewerWindow::firstItem() 301void TableViewerWindow::firstItem()
300{ 302{
301 listView->first(); 303 listView->first();
302 ts.current_elem = listView->getCurrentData(); 304 ts.current_elem = listView->getCurrentData();
303 browseView->rebuildData(); 305 browseView->rebuildData();
304} 306}
305 307
306/*! 308/*!
307 Moves to the lat item of the current table 309 Moves to the lat item of the current table
308*/ 310*/
309void TableViewerWindow::lastItem() 311void TableViewerWindow::lastItem()
310{ 312{
311 listView->last(); 313 listView->last();
312 ts.current_elem = listView->getCurrentData(); 314 ts.current_elem = listView->getCurrentData();
313 browseView->rebuildData(); 315 browseView->rebuildData();
314} 316}
315 317
316/*! 318/*!
317 Moves to the next item of the current table 319 Moves to the next item of the current table
318*/ 320*/
319void TableViewerWindow::nextItem() 321void TableViewerWindow::nextItem()
320{ 322{
321 listView->next(); 323 listView->next();
322 ts.current_elem = listView->getCurrentData(); 324 ts.current_elem = listView->getCurrentData();
323 browseView->rebuildData(); 325 browseView->rebuildData();
324} 326}
325 327
326/*! 328/*!
327 Moves to the previous item of the current table 329 Moves to the previous item of the current table
328*/ 330*/
329void TableViewerWindow::previousItem() 331void TableViewerWindow::previousItem()
330{ 332{
331 listView->previous(); 333 listView->previous();
332 ts.current_elem = listView->getCurrentData(); 334 ts.current_elem = listView->getCurrentData();
333 browseView->rebuildData(); 335 browseView->rebuildData();
334} 336}
335 337
336/*! 338/*!
337 Raises the List View. This is a mode change for the application. 339 Raises the List View. This is a mode change for the application.
338*/ 340*/
339void TableViewerWindow::listViewSlot() 341void TableViewerWindow::listViewSlot()
340{ 342{
341 if(current_view == FilterState) 343 if(current_view == FilterState)
342 applyFilter(); 344 applyFilter();
343 current_view = ListState; 345 current_view = ListState;
344 cw->raiseWidget(current_view); 346 cw->raiseWidget(current_view);
345} 347}
346 348
347void TableViewerWindow::applyFilter() 349void TableViewerWindow::applyFilter()
348{ 350{
349 DataElem *d; 351 DataElem *d;
350 352
351 listView->clearItems(); 353 listView->clearItems();
352 ds->first(); 354 ds->first();
353 do { 355 do {
354 d = ds->getCurrentData(); 356 d = ds->getCurrentData();
355 if(d) 357 if(d)
356 if(filterView->passesFilter(d)) 358 if(filterView->passesFilter(d))
357 listView->addItem(d); 359 listView->addItem(d);
358 } while(ds->next()); 360 } while(ds->next());
359 listView->first(); 361 listView->first();
360 listView->rebuildData(); 362 listView->rebuildData();
361} 363}
362 364
363/*! 365/*!
364 Raises the Browse View. This is a mode change for the application. 366 Raises the Browse View. This is a mode change for the application.
365*/ 367*/
366void TableViewerWindow::browseViewSlot() 368void TableViewerWindow::browseViewSlot()
367{ 369{
368 if(current_view == FilterState) 370 if(current_view == FilterState)
369 applyFilter(); 371 applyFilter();
370 372
371 ts.current_elem = listView->getCurrentData(); 373 ts.current_elem = listView->getCurrentData();
372 browseView->rebuildData(); 374 browseView->rebuildData();
373 375
374 current_view = BrowseState; 376 current_view = BrowseState;
375 cw->raiseWidget(current_view); 377 cw->raiseWidget(current_view);
376} 378}
377 379
378/*! 380/*!
379 Raises the List View. This is a mode change for the application. 381 Raises the List View. This is a mode change for the application.
380*/ 382*/
381void TableViewerWindow::filterViewSlot() 383void TableViewerWindow::filterViewSlot()
382{ 384{
383 current_view = FilterState; 385 current_view = FilterState;
384 cw->raiseWidget(current_view); 386 cw->raiseWidget(current_view);
385} 387}
386 388
387 389
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 @@
1 CONFIG = qt warn_on quick-app 1 CONFIG = qt warn_on quick-app
2 SUBDIRS = db ui 2 SUBDIRS = db ui
3 HEADERS = tableviewer.h \ 3 HEADERS = tableviewer.h \
4 xmlencodeattr.h \ 4 xmlencodeattr.h \
5 ui/commonwidgets.h \ 5 ui/commonwidgets.h \
6 ui/tvbrowseview.h \ 6 ui/tvbrowseview.h \
7 ui/tvlistview.h \ 7 ui/tvlistview.h \
8 ui/tvfilterview.h \ 8 ui/tvfilterview.h \
9 ui/tveditview.h \ 9 ui/tveditview.h \
10 ui/browsekeyentry.h \ 10 ui/browsekeyentry.h \
11 ui/filterkeyentry.h \ 11 ui/filterkeyentry.h \
12 ui/tvkeyedit.h \ 12 ui/tvkeyedit.h \
13 db/datacache.h \ 13 db/datacache.h \
14 db/common.h \ 14 db/common.h \
15 db/xmlsource.h \ 15 db/xmlsource.h \
16 db/csvsource.h 16 db/csvsource.h
17 SOURCES = main.cpp \ 17 SOURCES = main.cpp \
18 tableviewer.cpp \ 18 tableviewer.cpp \
19 xmlencodeattr.cpp \ 19 xmlencodeattr.cpp \
20 ui/commonwidgets.cpp \ 20 ui/commonwidgets.cpp \
21 ui/tvbrowseview.cpp \ 21 ui/tvbrowseview.cpp \
22 ui/tvfilterview.cpp \ 22 ui/tvfilterview.cpp \
23 ui/browsekeyentry.cpp \ 23 ui/browsekeyentry.cpp \
24 ui/filterkeyentry.cpp \ 24 ui/filterkeyentry.cpp \
25 ui/tvlistview.cpp \ 25 ui/tvlistview.cpp \
26 ui/tveditview.cpp \ 26 ui/tveditview.cpp \
27 ui/tvkeyedit.cpp \ 27 ui/tvkeyedit.cpp \
28 db/datacache.cpp \ 28 db/datacache.cpp \
29 db/xmlsource.cpp \ 29 db/xmlsource.cpp \
30 db/csvsource.cpp \ 30 db/csvsource.cpp \
31 db/common.cpp 31 db/common.cpp
32 INTERFACES= ui/tvkeyedit_gen.ui 32 INTERFACES= ui/tvkeyedit_gen.ui
33 TARGET = tableviewer 33 TARGET = tableviewer
34INCLUDEPATH += $(OPIEDIR)/include 34 INCLUDEPATH+= $(OPIEDIR)/include
35DEPENDPATH += $(OPIEDIR)/include 35 DEPENDPATH+= $(OPIEDIR)/include
36 LIBS += -lqpe -lopiecore2 36 LIBS += -lqpe -lopiecore2
37 37
38include ( $(OPIEDIR)/include.pro ) 38include ( $(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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20
20#include "tvlistview.h" 21#include "tvlistview.h"
21#include "../db/common.h" 22#include "../db/common.h"
23
24/* OPIE */
25#include <opie2/odebug.h>
26using namespace Opie::Core;
27
28/* QT */
22#include <qtoolbutton.h> 29#include <qtoolbutton.h>
23#include <qlistview.h> 30#include <qlistview.h>
24#include <qlayout.h> 31#include <qlayout.h>
25 32
26void TVListViewPrivate::setColumnWidth(int column, int width) 33void TVListViewPrivate::setColumnWidth(int column, int width)
27{ 34{
28 if(width > 70) width = 70; 35 if(width > 70) width = 70;
29 QListView::setColumnWidth(column, width); 36 QListView::setColumnWidth(column, width);
30} 37}
31 38
32void TVListViewPrivate::setSorting(int column, bool increasing) 39void TVListViewPrivate::setSorting(int column, bool increasing)
33{ 40{
34 emit sortChanged(column); 41 emit sortChanged(column);
35 QListView::setSorting(column, increasing); 42 QListView::setSorting(column, increasing);
36} 43}
37 44
38TVListViewPrivate::TVListViewPrivate(QWidget *parent, const char* name, 45TVListViewPrivate::TVListViewPrivate(QWidget *parent, const char* name,
39 WFlags fl) : QListView(parent, name, fl) { 46 WFlags fl) : QListView(parent, name, fl) {
40 ; 47 ;
41} 48}
42 49
43class TVListViewItem : public QListViewItem 50class TVListViewItem : public QListViewItem
44{ 51{
45public: 52public:
46 53
47 TVListViewItem(QListView *parent, DataElem *d); 54 TVListViewItem(QListView *parent, DataElem *d);
48 ~TVListViewItem(); 55 ~TVListViewItem();
49 56
50 QString text(int i) const 57 QString text(int i) const
51 { 58 {
52 return data_reference->toQString(i); 59 return data_reference->toQString(i);
53 } 60 }
54 61
55 /* Do nothing... all data for this item should be generated */ 62 /* Do nothing... all data for this item should be generated */
56 void setText(int i, const QString &) 63 void setText(int i, const QString &)
57 { 64 {
58 ; 65 ;
59 } 66 }
60 QString key(int i, bool a) const 67 QString key(int i, bool a) const
61 { 68 {
62 return data_reference->toSortableQString(i); 69 return data_reference->toSortableQString(i);
63 } 70 }
64 71
65 void setDataElem(DataElem *d) 72 void setDataElem(DataElem *d)
66 { 73 {
67 data_reference = d; 74 data_reference = d;
68 } 75 }
69 76
70 DataElem *getDataElem() { 77 DataElem *getDataElem() {
71 return data_reference; 78 return data_reference;
72 } 79 }
73private: 80private:
74 DataElem *data_reference; 81 DataElem *data_reference;
75}; 82};
76 83
77TVListViewItem::TVListViewItem(QListView *parent, DataElem *d) 84TVListViewItem::TVListViewItem(QListView *parent, DataElem *d)
78 : QListViewItem(parent) 85 : QListViewItem(parent)
79{ 86{
80 data_reference = d; 87 data_reference = d;
81} 88}
82 89
83TVListViewItem::~TVListViewItem() 90TVListViewItem::~TVListViewItem()
84{ 91{
85 data_reference = 0; 92 data_reference = 0;
86} 93}
87 94
88TVListView::TVListView(TableState *t, QWidget* parent, 95TVListView::TVListView(TableState *t, QWidget* parent,
89 const char *name, WFlags fl ) : QWidget(parent, name, fl) 96 const char *name, WFlags fl ) : QWidget(parent, name, fl)
90{ 97{
91 if (!name) 98 if (!name)
92 setName("TVListView"); 99 setName("TVListView");
93 100
94 // the next two lines need to be rationalized. 101 // the next two lines need to be rationalized.
95 resize(318,457); 102 resize(318,457);
96 setSizePolicy(QSizePolicy((QSizePolicy::SizeType)7, 103 setSizePolicy(QSizePolicy((QSizePolicy::SizeType)7,
97 (QSizePolicy::SizeType)7, sizePolicy().hasHeightForWidth())); 104 (QSizePolicy::SizeType)7, sizePolicy().hasHeightForWidth()));
98 setCaption(tr("List View")); 105 setCaption(tr("List View"));
99 106
100 QVBoxLayout *layout = new QVBoxLayout(this); 107 QVBoxLayout *layout = new QVBoxLayout(this);
101 layout->setSpacing(0); 108 layout->setSpacing(0);
102 layout->setMargin(0); 109 layout->setMargin(0);
103 110
104 listViewDisplay = new TVListViewPrivate(this, "listViewDisplay"); 111 listViewDisplay = new TVListViewPrivate(this, "listViewDisplay");
105 layout->addWidget(listViewDisplay); 112 layout->addWidget(listViewDisplay);
106 113
107 connect(listViewDisplay, SIGNAL(currentChanged(QListViewItem*)), this, 114 connect(listViewDisplay, SIGNAL(currentChanged(QListViewItem*)), this,
108 SLOT(setCurrent(QListViewItem*))); 115 SLOT(setCurrent(QListViewItem*)));
109 connect(listViewDisplay, SIGNAL(sortChanged(int)), this, 116 connect(listViewDisplay, SIGNAL(sortChanged(int)), this,
110 SLOT(setSorting(int))); 117 SLOT(setSorting(int)));
111 118
112 listViewDisplay->setShowSortIndicator(true); 119 listViewDisplay->setShowSortIndicator(true);
113 120
114 it = new QListViewItemIterator(listViewDisplay); 121 it = new QListViewItemIterator(listViewDisplay);
115 ts = t; 122 ts = t;
116} 123}
117 124
118TVListView::~TVListView() 125TVListView::~TVListView()
119{ 126{
120} 127}
121 128
122void TVListView::addItem(DataElem *d) 129void TVListView::addItem(DataElem *d)
123{ 130{
124 TVListViewItem *i = new TVListViewItem(listViewDisplay, d); 131 TVListViewItem *i = new TVListViewItem(listViewDisplay, d);
125 132
126 delete it; 133 delete it;
127 it = new QListViewItemIterator(i); 134 it = new QListViewItemIterator(i);
128} 135}
129 136
130/* remove current (it) item */ 137/* remove current (it) item */
131void TVListView::removeItem() 138void TVListView::removeItem()
132{ 139{
133 QListViewItemIterator other(*it); 140 QListViewItemIterator other(*it);
134 141
135 QListViewItemIterator tmp = *it; 142 QListViewItemIterator tmp = *it;
136 (*it)++; 143 (*it)++;
137 if (!it->current()) { 144 if (!it->current()) {
138 *it = tmp; 145 *it = tmp;
139 (*it)--; 146 (*it)--;
140 if (!it->current()) { 147 if (!it->current()) {
141 delete it; 148 delete it;
142 it = 0; 149 it = 0;
143 } 150 }
144 } 151 }
145 152
146 delete other.current(); 153 delete other.current();
147} 154}
148 155
149void TVListView::clearItems() 156void TVListView::clearItems()
150{ 157{
151 /* This is ok since the destructor for TVListItem does not know about 158 /* This is ok since the destructor for TVListItem does not know about
152 the data_reference pointer.. and hence will leave it alone */ 159 the data_reference pointer.. and hence will leave it alone */
153 listViewDisplay->clear(); 160 listViewDisplay->clear();
154 delete it; 161 delete it;
155 it = new QListViewItemIterator(listViewDisplay); 162 it = new QListViewItemIterator(listViewDisplay);
156} 163}
157 164
158void TVListView::first() 165void TVListView::first()
159{ 166{
160 delete it; 167 delete it;
161 it = new QListViewItemIterator(listViewDisplay); 168 it = new QListViewItemIterator(listViewDisplay);
162} 169}
163 170
164void TVListView::last() 171void TVListView::last()
165{ 172{
166 qWarning("TVListView::last not yet implemented"); 173 owarn << "TVListView::last not yet implemented" << oendl;
167} 174}
168 175
169void TVListView::next() 176void TVListView::next()
170{ 177{
171 QListViewItemIterator tmp = *it; 178 QListViewItemIterator tmp = *it;
172 (*it)++; 179 (*it)++;
173 if (!it->current()) { 180 if (!it->current()) {
174 *it = tmp; 181 *it = tmp;
175 } 182 }
176} 183}
177 184
178void TVListView::previous() 185void TVListView::previous()
179{ 186{
180 QListViewItemIterator tmp = *it; 187 QListViewItemIterator tmp = *it;
181 (*it)--; 188 (*it)--;
182 if (!it->current()) { 189 if (!it->current()) {
183 *it = tmp; 190 *it = tmp;
184 } 191 }
185} 192}
186 193
187DataElem *TVListView::getCurrentData() { 194DataElem *TVListView::getCurrentData() {
188 if (it->current()) { 195 if (it->current()) {
189 return ((TVListViewItem *)it->current())->getDataElem(); 196 return ((TVListViewItem *)it->current())->getDataElem();
190 } 197 }
191 return NULL; 198 return NULL;
192} 199}
193 200
194/*! Now to implement the closest match function */ 201/*! Now to implement the closest match function */
195void TVListView::findItem(int keyId, TVVariant value) 202void TVListView::findItem(int keyId, TVVariant value)
196{ 203{
197 QListViewItem *i; 204 QListViewItem *i;
198 TVListViewItem *best_so_far = NULL; 205 TVListViewItem *best_so_far = NULL;
199 /* start at the beginning... go through till find the closest elem */ 206 /* start at the beginning... go through till find the closest elem */
200 i = listViewDisplay->firstChild(); 207 i = listViewDisplay->firstChild();
201 while (i) { 208 while (i) {
202 /* search stuff */ 209 /* search stuff */
203 if(best_so_far) { 210 if(best_so_far) {
204 if (DataElem::closer( 211 if (DataElem::closer(
205 ((TVListViewItem *)i)->getDataElem(), 212 ((TVListViewItem *)i)->getDataElem(),
206 best_so_far->getDataElem(), value, keyId)) 213 best_so_far->getDataElem(), value, keyId))
207 best_so_far = (TVListViewItem *)i; 214 best_so_far = (TVListViewItem *)i;
208 } else { 215 } else {
209 if (DataElem::closer( 216 if (DataElem::closer(
210 ((TVListViewItem *)i)->getDataElem(), 217 ((TVListViewItem *)i)->getDataElem(),
211 NULL, value, keyId)) 218 NULL, value, keyId))
212 best_so_far = (TVListViewItem *)i; 219 best_so_far = (TVListViewItem *)i;
213 } 220 }
214 221
215 i = i->itemBelow(); 222 i = i->itemBelow();
216 } 223 }
217 if (best_so_far) { 224 if (best_so_far) {
218 /* set best_so_far to current element */ 225 /* set best_so_far to current element */
219 delete it; 226 delete it;
220 it = new QListViewItemIterator(best_so_far); 227 it = new QListViewItemIterator(best_so_far);
221 } 228 }
222} 229}
223 230
224void TVListView::rebuildKeys() 231void TVListView::rebuildKeys()
225{ 232{
226 int i; 233 int i;
227 if(!ts) return; 234 if(!ts) return;
228 if(!ts->kRep) return; 235 if(!ts->kRep) return;
229 236
230 i = listViewDisplay->columns(); 237 i = listViewDisplay->columns();
231 238
232 while(i > 0) 239 while(i > 0)
233 listViewDisplay->removeColumn(--i); 240 listViewDisplay->removeColumn(--i);
234 241
235 KeyListIterator kit(*ts->kRep); 242 KeyListIterator kit(*ts->kRep);
236 i = 0; 243 i = 0;
237 while(kit.current()) { 244 while(kit.current()) {
238 if(!kit.current()->delFlag()) { 245 if(!kit.current()->delFlag()) {
239 listViewDisplay->addColumn(kit.current()->name()); 246 listViewDisplay->addColumn(kit.current()->name());
240 keyIds.insert(i, kit.currentKey()); 247 keyIds.insert(i, kit.currentKey());
241 ++i; 248 ++i;
242 } 249 }
243 ++kit; 250 ++kit;
244 } 251 }
245} 252}
246 253
247 254
248void TVListView::setSorting(int column) 255void TVListView::setSorting(int column)
249{ 256{
250 /* Without table state can't do anything */ 257 /* Without table state can't do anything */
251 if (ts == 0) 258 if (ts == 0)
252 return; 259 return;
253 if (keyIds[column] != ts->current_column) { 260 if (keyIds[column] != ts->current_column) {
254 ts->current_column = keyIds[column]; 261 ts->current_column = keyIds[column];
255 } 262 }
256} 263}
257 264
258void TVListView::rebuildData() { 265void TVListView::rebuildData() {
259 int i; 266 int i;
260 QMap<int, int>::Iterator kit; 267 QMap<int, int>::Iterator kit;
261 /* Need to set sort order */ 268 /* Need to set sort order */
262 if(!ts) 269 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 @@
1TEMPLATE = lib 1TEMPLATE = lib
2CONFIG = qt warn_on 2CONFIG = qt warn_on
3HEADERS = microkde/kapplication.h \ 3HEADERS = microkde/kapplication.h \
4 kateconfig.h \ 4 kateconfig.h \
5 microkde/kdebug.h \ 5 microkde/kdebug.h \
6 microkde/kdialog.h \ 6 microkde/kdialog.h \
7 microkde/kdialogbase.h \ 7 microkde/kdialogbase.h \
8 microkde/kfiledialog.h \ 8 microkde/kfiledialog.h \
9 microkde/kglobal.h \ 9 microkde/kglobal.h \
10 microkde/kiconloader.h \ 10 microkde/kiconloader.h \
11 microkde/klineedit.h \ 11 microkde/klineedit.h \
12 microkde/klocale.h \ 12 microkde/klocale.h \
13 microkde/kmessagebox.h \ 13 microkde/kmessagebox.h \
14 microkde/kprinter.h \ 14 microkde/kprinter.h \
15 microkde/krestrictedline.h \ 15 microkde/krestrictedline.h \
16 microkde/kseparator.h \ 16 microkde/kseparator.h \
17 microkde/kstandarddirs.h \ 17 microkde/kstandarddirs.h \
18 microkde/ktempfile.h \ 18 microkde/ktempfile.h \
19 microkde/kunload.h \ 19 microkde/kunload.h \
20 microkde/kurlrequester.h \ 20 microkde/kurlrequester.h \
21 microkde/kfontdialog.h \ 21 microkde/kfontdialog.h \
22 microkde/krun.h \ 22 microkde/krun.h \
23 microkde/knumvalidator.h \ 23 microkde/knumvalidator.h \
24 microkde/kstaticdeleter.h \ 24 microkde/kstaticdeleter.h \
25 microkde/klistview.h \ 25 microkde/klistview.h \
26 microkde/kglobalsettings.h \ 26 microkde/kglobalsettings.h \
27 microkde/kcolorbtn.h \ 27 microkde/kcolorbtn.h \
28 \
29 \ 28 \
30 qt3back/qregexp3.h \ 29 qt3back/qregexp3.h \
31 microkde/ksharedptr.h \ 30 microkde/ksharedptr.h \
32 document/katebuffer.h document/katedialogs.h \ 31 document/katebuffer.h document/katedialogs.h \
33 document/katetextline.h \ 32 document/katetextline.h \
34 document/katecmd.h \ 33 document/katecmd.h \
35 document/katehighlight.h \ 34 document/katehighlight.h \
36 document/katecmds.h document/katedocument.h \ 35 document/katecmds.h document/katedocument.h \
37 document/katesyntaxdocument.h \ 36 document/katesyntaxdocument.h \
38 view/kateundohistory.h \ 37 view/kateundohistory.h \
39 view/kateview.h \ 38 view/kateview.h \
40 view/kateviewdialog.h \ 39 view/kateviewdialog.h \
41 interfaces/view.h \ 40 interfaces/view.h \
42 interfaces/document.h \ 41 interfaces/document.h \
43 ktexteditor/ktexteditor.h 42 ktexteditor/ktexteditor.h
44 43
45SOURCES = microkde/kapplication.cpp \ 44SOURCES = microkde/kapplication.cpp \
46 microkde/kdialogbase.cpp \ 45 microkde/kdialogbase.cpp \
47 kateconfig.cpp \ 46 kateconfig.cpp \
48 microkde/klocale.cpp \ 47 microkde/klocale.cpp \
49 microkde/kmessagebox.cpp \ 48 microkde/kmessagebox.cpp \
50 microkde/kprocess.cpp \ 49 microkde/kprocess.cpp \
51 microkde/kstandarddirs.cpp \ 50 microkde/kstandarddirs.cpp \
52 microkde/ktempfile.cpp \ 51 microkde/ktempfile.cpp \
53 microkde/kurlrequester.cpp \ 52 microkde/kurlrequester.cpp \
54 microkde/kfontdialog.cpp \ 53 microkde/kfontdialog.cpp \
55 microkde/krun.cpp \ 54 microkde/krun.cpp \
56 microkde/knumvalidator.cpp \ 55 microkde/knumvalidator.cpp \
57 microkde/kglobal.cpp \ 56 microkde/kglobal.cpp \
58 microkde/kglobalsettings.cpp \ 57 microkde/kglobalsettings.cpp \
59 microkde/kcolorbtn.cpp \ 58 microkde/kcolorbtn.cpp \
60 \ 59 \
61 \ 60 qt3back/qregexp3.cpp \
62 qt3back/qregexp3.cpp \ 61 ktexteditor/ktexteditor.cpp \
63 ktexteditor/ktexteditor.cpp \ 62 document/katebuffer.cpp document/katedialogs.cpp \
64 document/katebuffer.cpp document/katedialogs.cpp \ 63 document/katehighlight.cpp \
65 document/katehighlight.cpp \ 64 document/katecmd.cpp \
66 document/katecmd.cpp \ 65 document/katesyntaxdocument.cpp document/katecmds.cpp \
67 document/katesyntaxdocument.cpp document/katecmds.cpp \ 66 document/katedocument.cpp document/katetextline.cpp \
68 document/katedocument.cpp document/katetextline.cpp \ 67 view/kateundohistory.cpp \
69 view/kateundohistory.cpp \ 68 view/kateview.cpp \
70 view/kateview.cpp \ 69 view/kateviewdialog.cpp \
71 view/kateviewdialog.cpp \ 70 interfaces/interfaces.cpp
72 interfaces/interfaces.cpp 71INTERFACES =
73 72INCLUDEPATH += $(OPIEDIR)/include \
74INTERFACES =
75INCLUDEPATH += $(OPIEDIR)/include \
76 $(OPIEDIR)/noncore/apps/tinykate/libkate \ 73 $(OPIEDIR)/noncore/apps/tinykate/libkate \
77 $(OPIEDIR)/noncore/apps/tinykate/libkate/microkde \ 74 $(OPIEDIR)/noncore/apps/tinykate/libkate/microkde \
78 $(OPIEDIR)/noncore/apps/tinykate/libkate/document \ 75 $(OPIEDIR)/noncore/apps/tinykate/libkate/document \
79 $(OPIEDIR)/noncore/apps/tinykate/libkate/view \ 76 $(OPIEDIR)/noncore/apps/tinykate/libkate/view \
80 $(OPIEDIR)/noncore/apps/tinykate/libkate/interfaces \ 77 $(OPIEDIR)/noncore/apps/tinykate/libkate/interfaces \
81 $(OPIEDIR)/noncore/apps/tinykate/libkate/ktexteditor \ 78 $(OPIEDIR)/noncore/apps/tinykate/libkate/ktexteditor \
82 $(OPIEDIR)/noncore/apps/tinykate/libkate/qt3back 79 $(OPIEDIR)/noncore/apps/tinykate/libkate/qt3back
83DEPENDPATH += $(OPIEDIR)/include 80DEPENDPATH += $(OPIEDIR)/include
84LIBS += -lqpe -lqtaux2 -lopiecore2 -lopieui2 81LIBS += -lqpe -lqtaux2 -lopiecore2 -lopieui2
85TARGET = tinykate 82TARGET = tinykate
86 83
87INCLUDEPATH += $(OPIEDIR)/include 84INCLUDEPATH += $(OPIEDIR)/include
88DESTDIR = $(OPIEDIR)/lib$(PROJMAK) 85DESTDIR = $(OPIEDIR)/lib$(PROJMAK)
89 86
90include ( $(OPIEDIR)/include.pro ) 87include ( $(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 @@
1TEMPLATE = app 1TEMPLATE = app
2CONFIG = qt warn_on quick-app 2CONFIG = qt warn_on quick-app
3DESTDIR = $(OPIEDIR)/bin 3DESTDIR = $(OPIEDIR)/bin
4HEADERS = tinykate.h 4HEADERS = tinykate.h
5SOURCES = tinykate.cpp main.cpp 5SOURCES = tinykate.cpp main.cpp
6INTERFACES =
7INCLUDEPATH += $(OPIEDIR)/include \ 6INCLUDEPATH += $(OPIEDIR)/include \
8 $(OPIEDIR)/noncore/apps/tinykate/libkate \ 7 $(OPIEDIR)/noncore/apps/tinykate/libkate \
9 $(OPIEDIR)/noncore/apps/tinykate/libkate/microkde \ 8 $(OPIEDIR)/noncore/apps/tinykate/libkate/microkde \
10 $(OPIEDIR)/noncore/apps/tinykate/libkate/document \ 9 $(OPIEDIR)/noncore/apps/tinykate/libkate/document \
11 $(OPIEDIR)/noncore/apps/tinykate/libkate/view \ 10 $(OPIEDIR)/noncore/apps/tinykate/libkate/view \
12 $(OPIEDIR)/noncore/apps/tinykate/libkate/interfaces \ 11 $(OPIEDIR)/noncore/apps/tinykate/libkate/interfaces \
13 $(OPIEDIR)/noncore/apps/tinykate/libkate/ktexteditor \ 12 $(OPIEDIR)/noncore/apps/tinykate/libkate/ktexteditor \
14 $(OPIEDIR)/noncore/apps/tinykate/libkate/qt3back 13 $(OPIEDIR)/noncore/apps/tinykate/libkate/qt3back
15 14DEPENDPATH += $(OPIEDIR)/include
16DEPENDPATH += $(OPIEDIR)/include 15LIBS += -lqpe -ltinykate -lopiecore2 -lopieui2
17LIBS += -lqpe -ltinykate -lopiecore2 -lopieui2 16TARGET = kate
18TARGET = kate
19 17
20 18
21 19
22include ( $(OPIEDIR)/include.pro ) 20include ( $(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 @@
1config ZSAFE 1config ZSAFE
2 boolean "zsafe (Zaurus Password Manager)" 2 boolean "zsafe (Zaurus Password Manager)"
3 default "y" 3 default "y"
4 depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI 4 depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && LIBOPIE2UI
5 5
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 @@
1/****************************************************************************
2** Form implementation generated from reading ui file 'scqtfiledlg.ui'
3**
4** Created: Sun Jun 8 15:51:12 2003
5** by: The User Interface Compiler (uic)
6**
7** WARNING! All changes made in this file will be lost!
8****************************************************************************/
9#include "scqtfiledlg.h" 1#include "scqtfiledlg.h"
10 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
7/* QT */
11#include <qcombobox.h> 8#include <qcombobox.h>
12#include <qlineedit.h> 9#include <qlineedit.h>
13#include <qlistview.h> 10#include <qlistview.h>
14#include <qtoolbutton.h> 11#include <qtoolbutton.h>
15#include <qlayout.h> 12#include <qlayout.h>
16#include <qtooltip.h> 13#include <qtooltip.h>
17#include <qwhatsthis.h> 14#include <qwhatsthis.h>
18 15
19static const char* const image0_data[] = { 16static const char* const image0_data[] = {
20"24 16 3 1", 17"24 16 3 1",
21". c None", 18". c None",
22"# c #000040", 19"# c #000040",
23"a c #808080", 20"a c #808080",
24"........................", 21"........................",
25"........................", 22"........................",
26".................####...", 23".................####...",
27".................####...", 24".................####...",
28".......##........#aa#...", 25".......##........#aa#...",
29"......###........#aa#...", 26"......###........#aa#...",
30".....####........#aa#...", 27".....####........#aa#...",
31"....##############aa#...", 28"....##############aa#...",
32"...###aaaaaaaaaaaaaa#...", 29"...###aaaaaaaaaaaaaa#...",
33"..####aaaaaaaaaaaaaa#...", 30"..####aaaaaaaaaaaaaa#...",
34"...###aaaaaaaaaaaaaa#...", 31"...###aaaaaaaaaaaaaa#...",
35"....#################...", 32"....#################...",
36".....####...............", 33".....####...............",
37"......###...............", 34"......###...............",
38".......##...............", 35".......##...............",
39"........................"}; 36"........................"};
40 37
41static const char* const image1_data[] = { 38static const char* const image1_data[] = {
42"24 16 4 1", 39"24 16 4 1",
43". c None", 40". c None",
44"a c #008080", 41"a c #008080",
45"b c #808080", 42"b c #808080",
46"# c #ff0000", 43"# c #ff0000",
47"........................", 44"........................",
48"........................", 45"........................",
49"...####..........####...", 46"...####..........####...",
50"...#####........#####...", 47"...#####........#####...",
51"....######.....#####a...", 48"....######.....#####a...",
52".....######...#####ba...", 49".....######...#####ba...",
53".....aa###########bba...", 50".....aa###########bba...",
54"....aaaaa#######aabba...", 51"....aaaaa#######aabba...",
55"...aaabbb######bbbbba...", 52"...aaabbb######bbbbba...",
56"..aaaabb########bbbba...", 53"..aaaabb########bbbba...",
57"...aaa############bba...", 54"...aaa############bba...",
58"....a######aaa#####aa...", 55"....a######aaa#####aa...",
59"....######.....######...", 56"....######.....######...",
60"...#####a........####...", 57"...#####a........####...",
61"...####aa.........###...", 58"...####aa.........###...",
62"........................"}; 59"........................"};
63 60
64static const char* const image2_data[] = { 61static const char* const image2_data[] = {
65"17 15 4 1", 62"17 15 4 1",
66"# c #000000", 63"# c #000000",
67". c #dcdcdc", 64". c #dcdcdc",
68"a c #ffff00", 65"a c #ffff00",
69"b c #ffffff", 66"b c #ffffff",
70".................", 67".................",
71"............#....", 68"............#....",
72".................", 69".................",
73"............#....", 70"............#....",
74".........#.....#.", 71".........#.....#.",
75"....####..#.#.#..", 72"....####..#.#.#..",
76"...#abab#..#.#...", 73"...#abab#..#.#...",
77"..##########..#.#", 74"..##########..#.#",
78"..#babababab##...", 75"..#babababab##...",
79"..#ababababa#.#..", 76"..#ababababa#.#..",
80"..#babababab#..#.", 77"..#babababab#..#.",
81"..#ababababa#....", 78"..#ababababa#....",
82"..#babababab#....", 79"..#babababab#....",
83"..#ababababa#....", 80"..#ababababa#....",
84"..###########...."}; 81"..###########...."};
85 82
86 83
87/* 84/*
88 * Constructs a ScQtFileDlg which is a child of 'parent', with the 85 * Constructs a ScQtFileDlg which is a child of 'parent', with the
89 * name 'name' and widget flags set to 'f' 86 * name 'name' and widget flags set to 'f'
90 * 87 *
91 * The dialog will by default be modeless, unless you set 'modal' to 88 * The dialog will by default be modeless, unless you set 'modal' to
92 * TRUE to construct a modal dialog. 89 * TRUE to construct a modal dialog.
93 */ 90 */
94ScQtFileDlg::ScQtFileDlg( QWidget* parent, const char* name, bool modal, WFlags fl ) 91ScQtFileDlg::ScQtFileDlg( QWidget* parent, const char* name, bool modal, WFlags fl )
95 : QDialog( parent, name, modal, fl ) 92 : QDialog( parent, name, modal, fl )
96{ 93{
97 QPixmap image0( ( const char** ) image0_data ); 94 QPixmap image0( ( const char** ) image0_data );
98 QPixmap image1( ( const char** ) image1_data ); 95 QPixmap image1( ( const char** ) image1_data );
99 QPixmap image2( ( const char** ) image2_data ); 96 QPixmap image2( ( const char** ) image2_data );
100 if ( !name ) 97 if ( !name )
101 setName( "ScQtFileDlg" ); 98 setName( "ScQtFileDlg" );
102 resize( 196, 279 ); 99 resize( 196, 279 );
103 if (!name) 100 if (!name)
104 setCaption( tr( "FileDlg" ) ); 101 setCaption( tr( "FileDlg" ) );
105 else 102 else
106 setCaption(name); 103 setCaption(name);
@@ -123,134 +120,134 @@ ScQtFileDlg::ScQtFileDlg( QWidget* parent, const char* name, bool modal, WFlags
123 TypeComboBox = new QComboBox( FALSE, this, "TypeComboBox" ); 120 TypeComboBox = new QComboBox( FALSE, this, "TypeComboBox" );
124 TypeComboBox->setEditable( TRUE ); 121 TypeComboBox->setEditable( TRUE );
125 TypeComboBox->setInsertionPolicy( QComboBox::AtBottom ); 122 TypeComboBox->setInsertionPolicy( QComboBox::AtBottom );
126 TypeComboBox->setAutoCompletion( FALSE ); 123 TypeComboBox->setAutoCompletion( FALSE );
127 TypeComboBox->setDuplicatesEnabled( FALSE ); 124 TypeComboBox->setDuplicatesEnabled( FALSE );
128 QToolTip::add( TypeComboBox, tr( "file type filter" ) ); 125 QToolTip::add( TypeComboBox, tr( "file type filter" ) );
129 QWhatsThis::add( TypeComboBox, tr( "ComboBox FileTypeFilter\n" 126 QWhatsThis::add( TypeComboBox, tr( "ComboBox FileTypeFilter\n"
130"\n" 127"\n"
131"edit or select the filter" ) ); 128"edit or select the filter" ) );
132 Layout3->addWidget( TypeComboBox ); 129 Layout3->addWidget( TypeComboBox );
133 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ); 130 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
134 Layout3->addItem( spacer ); 131 Layout3->addItem( spacer );
135 132
136 OkButton = new QToolButton( this, "OkButton" ); 133 OkButton = new QToolButton( this, "OkButton" );
137 OkButton->setText( tr( "" ) ); 134 OkButton->setText( tr( "" ) );
138 OkButton->setPixmap( image0 ); 135 OkButton->setPixmap( image0 );
139 OkButton->setUsesBigPixmap( FALSE ); 136 OkButton->setUsesBigPixmap( FALSE );
140 QToolTip::add( OkButton, tr( "confirms the selection and closes the form" ) ); 137 QToolTip::add( OkButton, tr( "confirms the selection and closes the form" ) );
141 QWhatsThis::add( OkButton, tr( "OKButton" ) ); 138 QWhatsThis::add( OkButton, tr( "OKButton" ) );
142 Layout3->addWidget( OkButton ); 139 Layout3->addWidget( OkButton );
143 140
144 CancelButton = new QToolButton( this, "CancelButton" ); 141 CancelButton = new QToolButton( this, "CancelButton" );
145 CancelButton->setText( tr( "" ) ); 142 CancelButton->setText( tr( "" ) );
146 CancelButton->setPixmap( image1 ); 143 CancelButton->setPixmap( image1 );
147 CancelButton->setUsesBigPixmap( FALSE ); 144 CancelButton->setUsesBigPixmap( FALSE );
148 QToolTip::add( CancelButton, tr( "cancels the selection and closes the form" ) ); 145 QToolTip::add( CancelButton, tr( "cancels the selection and closes the form" ) );
149 QWhatsThis::add( CancelButton, tr( "CancelButton" ) ); 146 QWhatsThis::add( CancelButton, tr( "CancelButton" ) );
150 Layout3->addWidget( CancelButton ); 147 Layout3->addWidget( CancelButton );
151 Layout4->addLayout( Layout3 ); 148 Layout4->addLayout( Layout3 );
152 149
153 Layout3_2 = new QHBoxLayout; 150 Layout3_2 = new QHBoxLayout;
154 Layout3_2->setSpacing( 6 ); 151 Layout3_2->setSpacing( 6 );
155 Layout3_2->setMargin( 0 ); 152 Layout3_2->setMargin( 0 );
156 153
157 FNameLineEdit = new QLineEdit( this, "FNameLineEdit" ); 154 FNameLineEdit = new QLineEdit( this, "FNameLineEdit" );
158 QToolTip::add( FNameLineEdit, tr( "shows the selected filename" ) ); 155 QToolTip::add( FNameLineEdit, tr( "shows the selected filename" ) );
159 QWhatsThis::add( FNameLineEdit, tr( "Filename LineEdit\n" 156 QWhatsThis::add( FNameLineEdit, tr( "Filename LineEdit\n"
160"\n" 157"\n"
161"shows the selected file\n" 158"shows the selected file\n"
162"and allows the direct filename\n" 159"and allows the direct filename\n"
163"edit" ) ); 160"edit" ) );
164 Layout3_2->addWidget( FNameLineEdit ); 161 Layout3_2->addWidget( FNameLineEdit );
165 162
166 MkDirButton = new QToolButton( this, "MkDirButton" ); 163 MkDirButton = new QToolButton( this, "MkDirButton" );
167 MkDirButton->setText( tr( "" ) ); 164 MkDirButton->setText( tr( "" ) );
168 MkDirButton->setPixmap( image2 ); 165 MkDirButton->setPixmap( image2 );
169 MkDirButton->setUsesBigPixmap( FALSE ); 166 MkDirButton->setUsesBigPixmap( FALSE );
170 QToolTip::add( MkDirButton, tr( "confirms the selection and closes the form" ) ); 167 QToolTip::add( MkDirButton, tr( "confirms the selection and closes the form" ) );
171 QWhatsThis::add( MkDirButton, tr( "OKButton" ) ); 168 QWhatsThis::add( MkDirButton, tr( "OKButton" ) );
172 Layout3_2->addWidget( MkDirButton ); 169 Layout3_2->addWidget( MkDirButton );
173 Layout4->addLayout( Layout3_2 ); 170 Layout4->addLayout( Layout3_2 );
174 171
175 DirComboBox = new QComboBox( FALSE, this, "DirComboBox" ); 172 DirComboBox = new QComboBox( FALSE, this, "DirComboBox" );
176 DirComboBox->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)7, (QSizePolicy::SizeType)0, DirComboBox->sizePolicy().hasHeightForWidth() ) ); 173 DirComboBox->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)7, (QSizePolicy::SizeType)0, DirComboBox->sizePolicy().hasHeightForWidth() ) );
177 DirComboBox->setEditable( TRUE ); 174 DirComboBox->setEditable( TRUE );
178 DirComboBox->setDuplicatesEnabled( FALSE ); 175 DirComboBox->setDuplicatesEnabled( FALSE );
179 QWhatsThis::add( DirComboBox, tr( "ComboBox Directory \n" 176 QWhatsThis::add( DirComboBox, tr( "ComboBox Directory \n"
180"edit or select the directories name" ) ); 177"edit or select the directories name" ) );
181 Layout4->addWidget( DirComboBox ); 178 Layout4->addWidget( DirComboBox );
182 Layout5->addLayout( Layout4 ); 179 Layout5->addLayout( Layout4 );
183 180
184 ListView = new QListView( this, "ListView" ); 181 ListView = new QListView( this, "ListView" );
185 ListView->addColumn( tr( "Name" ) ); 182 ListView->addColumn( tr( "Name" ) );
186 ListView->addColumn( tr( "size" ) ); 183 ListView->addColumn( tr( "size" ) );
187 ListView->addColumn( tr( "type" ) ); 184 ListView->addColumn( tr( "type" ) );
188 ListView->setRootIsDecorated( TRUE ); 185 ListView->setRootIsDecorated( TRUE );
189 QToolTip::add( ListView, tr( "directory listview" ) ); 186 QToolTip::add( ListView, tr( "directory listview" ) );
190 QWhatsThis::add( ListView, tr( "Directory ListView\n" 187 QWhatsThis::add( ListView, tr( "Directory ListView\n"
191"\n" 188"\n"
192"shows the list of dirs and files" ) ); 189"shows the list of dirs and files" ) );
193 Layout5->addWidget( ListView ); 190 Layout5->addWidget( ListView );
194 ScQtFileDlgLayout->addLayout( Layout5 ); 191 ScQtFileDlgLayout->addLayout( Layout5 );
195 192
196 // signals and slots connections 193 // signals and slots connections
197 connect( OkButton, SIGNAL( clicked() ), this, SLOT( slotOK() ) ); 194 connect( OkButton, SIGNAL( clicked() ), this, SLOT( slotOK() ) );
198 connect( DirComboBox, SIGNAL( activated(int) ), this, SLOT( slotDirComboBoxChanged(int) ) ); 195 connect( DirComboBox, SIGNAL( activated(int) ), this, SLOT( slotDirComboBoxChanged(int) ) );
199 connect( TypeComboBox, SIGNAL( activated(int) ), this, SLOT( slotTypeComboBoxChanged(int) ) ); 196 connect( TypeComboBox, SIGNAL( activated(int) ), this, SLOT( slotTypeComboBoxChanged(int) ) );
200 connect( CancelButton, SIGNAL( clicked() ), this, SLOT( slotCancel() ) ); 197 connect( CancelButton, SIGNAL( clicked() ), this, SLOT( slotCancel() ) );
201 connect( ListView, SIGNAL( returnPressed(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem*) ) ); 198 connect( ListView, SIGNAL( returnPressed(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem*) ) );
202 connect( ListView, SIGNAL( selectionChanged(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem*) ) ); 199 connect( ListView, SIGNAL( selectionChanged(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem*) ) );
203 connect( ListView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( slotDoubleClicked(QListViewItem*) ) ); 200 connect( ListView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( slotDoubleClicked(QListViewItem*) ) );
204 connect( FNameLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotFileTextChanged(const QString&) ) ); 201 connect( FNameLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotFileTextChanged(const QString&) ) );
205 connect( FNameLineEdit, SIGNAL( returnPressed() ), this, SLOT( slotOK() ) ); 202 connect( FNameLineEdit, SIGNAL( returnPressed() ), this, SLOT( slotOK() ) );
206 connect( MkDirButton, SIGNAL( clicked() ), this, SLOT( slotMkDir() ) ); 203 connect( MkDirButton, SIGNAL( clicked() ), this, SLOT( slotMkDir() ) );
207} 204}
208 205
209/* 206/*
210 * Destroys the object and frees any allocated resources 207 * Destroys the object and frees any allocated resources
211 */ 208 */
212ScQtFileDlg::~ScQtFileDlg() 209ScQtFileDlg::~ScQtFileDlg()
213{ 210{
214 // no need to delete child widgets, Qt does it all for us 211 // no need to delete child widgets, Qt does it all for us
215} 212}
216 213
217void ScQtFileDlg::slotCancel() 214void ScQtFileDlg::slotCancel()
218{ 215{
219 qWarning( "ScQtFileDlg::slotCancel(): Not implemented yet!" ); 216 owarn << "ScQtFileDlg::slotCancel(): Not implemented yet!" << oendl;
220} 217}
221 218
222void ScQtFileDlg::slotDirComboBoxChanged( int ) 219void ScQtFileDlg::slotDirComboBoxChanged( int )
223{ 220{
224 qWarning( "ScQtFileDlg::slotDirComboBoxChanged( int ): Not implemented yet!" ); 221 owarn << "ScQtFileDlg::slotDirComboBoxChanged( int ): Not implemented yet!" << oendl;
225} 222}
226 223
227void ScQtFileDlg::slotDoubleClicked(QListViewItem *) 224void ScQtFileDlg::slotDoubleClicked(QListViewItem *)
228{ 225{
229 qWarning( "ScQtFileDlg::slotDoubleClicked(QListViewItem *): Not implemented yet!" ); 226 owarn << "ScQtFileDlg::slotDoubleClicked(QListViewItem *): Not implemented yet!" << oendl;
230} 227}
231 228
232void ScQtFileDlg::slotFileTextChanged( const QString & ) 229void ScQtFileDlg::slotFileTextChanged( const QString & )
233{ 230{
234 qWarning( "ScQtFileDlg::slotFileTextChanged( const QString & ): Not implemented yet!" ); 231 owarn << "ScQtFileDlg::slotFileTextChanged( const QString & ): Not implemented yet!" << oendl;
235} 232}
236 233
237void ScQtFileDlg::slotMkDir() 234void ScQtFileDlg::slotMkDir()
238{ 235{
239 qWarning( "ScQtFileDlg::slotMkDir(): Not implemented yet!" ); 236 owarn << "ScQtFileDlg::slotMkDir(): Not implemented yet!" << oendl;
240} 237}
241 238
242void ScQtFileDlg::slotOK() 239void ScQtFileDlg::slotOK()
243{ 240{
244 qWarning( "ScQtFileDlg::slotOK(): Not implemented yet!" ); 241 owarn << "ScQtFileDlg::slotOK(): Not implemented yet!" << oendl;
245} 242}
246 243
247void ScQtFileDlg::slotSelectionChanged(QListViewItem *) 244void ScQtFileDlg::slotSelectionChanged(QListViewItem *)
248{ 245{
249 qWarning( "ScQtFileDlg::slotSelectionChanged(QListViewItem *): Not implemented yet!" ); 246 owarn << "ScQtFileDlg::slotSelectionChanged(QListViewItem *): Not implemented yet!" << oendl;
250} 247}
251 248
252void ScQtFileDlg::slotTypeComboBoxChanged( int ) 249void ScQtFileDlg::slotTypeComboBoxChanged( int )
253{ 250{
254 qWarning( "ScQtFileDlg::slotTypeComboBoxChanged( int ): Not implemented yet!" ); 251 owarn << "ScQtFileDlg::slotTypeComboBoxChanged( int ): Not implemented yet!" << oendl;
255} 252}
256 253
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 @@
1/**************************************************************************** 1/****************************************************************************
2** 2**
3** Created: Sat Apr 6 17:57:45 2002 3** Created: Sat Apr 6 17:57:45 2002
4** 4**
5** Author: Carsten Schneider <CarstenSchneider@t-online.de> 5** Author: Carsten Schneider <CarstenSchneider@t-online.de>
6** 6**
7** $Id$ 7** $Id$
8** 8**
9** Homepage: http://home.t-online.de/home/CarstenSchneider/zsafe/index.html 9** Homepage: http://home.t-online.de/home/CarstenSchneider/zsafe/index.html
10** 10**
11** Compile Flags: 11** Compile Flags:
12** Zaurus arm : -DNO_OPIE 12** Zaurus arm : -DNO_OPIE
13** Zaurus Opie arm: none 13** Zaurus Opie arm: none
14** Linux Desktop : -DDESKTOP 14** Linux Desktop : -DDESKTOP
15** Windows Desktop: -DDESKTOP -DWIN32 15** Windows Desktop: -DDESKTOP -DWIN32
16** 16**
17** for japanese version additional use: -DJPATCH_HDE 17** for japanese version additional use: -DJPATCH_HDE
18** 18**
19****************************************************************************/ 19****************************************************************************/
20#include "zsafe.h" 20#include "zsafe.h"
21#include "newdialog.h" 21#include "newdialog.h"
22#include "searchdialog.h" 22#include "searchdialog.h"
23#include "categorydialog.h" 23#include "categorydialog.h"
24#include "passworddialog.h" 24#include "passworddialog.h"
25#include "infoform.h" 25#include "infoform.h"
26#include "zlistview.h" 26#include "zlistview.h"
27#include "shadedlistitem.h" 27#include "shadedlistitem.h"
28 28
29#ifndef DESKTOP 29#ifndef DESKTOP
30#ifndef NO_OPIE 30#ifndef NO_OPIE
31#include <opie2/ofiledialog.h> 31#include <opie2/ofiledialog.h>
32 32#include <opie2/odebug.h>
33using namespace Opie::Core;
33using namespace Opie::Ui; 34using namespace Opie::Ui;
34#else 35#else
35#include "scqtfileedit.h" 36#include "scqtfileedit.h"
36#endif 37#endif
37#endif 38#endif
38 39
39#include <qclipboard.h> 40#include <qclipboard.h>
40 41
41#include <stdio.h>
42
43#include <sys/types.h> 42#include <sys/types.h>
44#include <sys/stat.h> 43#include <sys/stat.h>
45#include <fcntl.h> 44#include <fcntl.h>
46#include <stdlib.h> 45#include <stdlib.h>
47#ifndef WIN32 46#ifndef WIN32
48#include <unistd.h> 47#include <unistd.h>
49#endif 48#endif
50#include <string.h> 49#include <string.h>
51#include <errno.h> 50#include <errno.h>
52 51
53#include <qmenubar.h> 52#include <qmenubar.h>
54#include <qpopupmenu.h> 53#include <qpopupmenu.h>
55 54
56#ifdef DESKTOP 55#ifdef DESKTOP
57#include <qfiledialog.h> 56#include <qfiledialog.h>
58#ifndef WIN32 57#ifndef WIN32
59#include <qsettings.h> 58#include <qsettings.h>
60#else 59#else
61#include "qsettings.h" 60#include "qsettings.h"
62#endif 61#endif
63#include <qapplication.h> 62#include <qapplication.h>
64#else 63#else
65#include <qfile.h> 64#include <qfile.h>
66#include <qpe/fileselector.h> 65#include <qpe/fileselector.h>
67#include <qpe/global.h> 66#include <qpe/global.h>
68#include <qpe/qpeapplication.h> 67#include <qpe/qpeapplication.h>
69#include <qpe/resource.h> 68#include <qpe/resource.h>
70#include <qpe/config.h> 69#include <qpe/config.h>
71#endif 70#endif
72 71
73#include <qtimer.h> 72#include <qtimer.h>
74#include <qlayout.h> 73#include <qlayout.h>
75#include <qmessagebox.h> 74#include <qmessagebox.h>
76#include <qfile.h> 75#include <qfile.h>
77#include <qtextstream.h> 76#include <qtextstream.h>
78#include <qheader.h> 77#include <qheader.h>
79#include <qlistview.h> 78#include <qlistview.h>
80#include <qtoolbutton.h> 79#include <qtoolbutton.h>
81#include <qvariant.h> 80#include <qvariant.h>
82#include <qtooltip.h> 81#include <qtooltip.h>
83#include <qwhatsthis.h> 82#include <qwhatsthis.h>
84#include <qimage.h> 83#include <qimage.h>
85#include <qpixmap.h> 84#include <qpixmap.h>
86#include <qlineedit.h> 85#include <qlineedit.h>
87#include <qmultilineedit.h> 86#include <qmultilineedit.h>
88#include <qregexp.h> 87#include <qregexp.h>
89#include <qdir.h> 88#include <qdir.h>
90#include <qtextbrowser.h> 89#include <qtextbrowser.h>
91#include <qlabel.h> 90#include <qlabel.h>
92#include <qcombobox.h> 91#include <qcombobox.h>
93 92
94#include "krc2.h" 93#include "krc2.h"
95 94
96#include "wait.h" 95#include "wait.h"
97 96
98extern int DeskW, DeskH; 97extern int DeskW, DeskH;
99#ifdef DESKTOP 98#ifdef DESKTOP
100extern QApplication *appl; 99extern QApplication *appl;
101#else 100#else
102extern QPEApplication *appl; 101extern QPEApplication *appl;
103#endif 102#endif
104 103
105#ifdef JPATCH_HDE 104#ifdef JPATCH_HDE
106#define tr(arg) arg 105#define tr(arg) arg
107#endif 106#endif
108 107
109 108
110#ifdef DESKTOP 109#ifdef DESKTOP
111#ifndef WIN32 110#ifndef WIN32
112const QString APP_KEY="/.zsafe/"; 111const QString APP_KEY="/.zsafe/";
113#else 112#else
114const QString APP_KEY=""; 113const QString APP_KEY="";
115#endif 114#endif
116#else 115#else
117const QString APP_KEY=""; 116const QString APP_KEY="";
118#endif 117#endif
119 118
120// include xmp images 119// include xmp images
121#include "pics/zsafe/copy.xpm" 120#include "pics/zsafe/copy.xpm"
122#include "pics/zsafe/cut.xpm" 121#include "pics/zsafe/cut.xpm"
123#include "pics/zsafe/edit.xpm" 122#include "pics/zsafe/edit.xpm"
124#include "pics/zsafe/editdelete.xpm" 123#include "pics/zsafe/editdelete.xpm"
125#include "pics/zsafe/find.xpm" 124#include "pics/zsafe/find.xpm"
126#include "pics/zsafe/folder_open.xpm" 125#include "pics/zsafe/folder_open.xpm"
127#include "pics/zsafe/help_icon.xpm" 126#include "pics/zsafe/help_icon.xpm"
128#include "pics/zsafe/new.xpm" 127#include "pics/zsafe/new.xpm"
129#include "pics/zsafe/paste.xpm" 128#include "pics/zsafe/paste.xpm"
130#include "pics/zsafe/quit_icon.xpm" 129#include "pics/zsafe/quit_icon.xpm"
131#include "pics/zsafe/save.xpm" 130#include "pics/zsafe/save.xpm"
132#include "pics/zsafe/trash.xpm" 131#include "pics/zsafe/trash.xpm"
133#include "pics/zsafe/expand.xpm" 132#include "pics/zsafe/expand.xpm"
134#include "pics/zsafe/export.xpm" 133#include "pics/zsafe/export.xpm"
135#include "pics/zsafe/import.xpm" 134#include "pics/zsafe/import.xpm"
136#include "pics/zsafe/zsafe.xpm" 135#include "pics/zsafe/zsafe.xpm"
137 136
138static const char* const bank_cards_data[] = { 137static const char* const bank_cards_data[] = {
@@ -1976,436 +1975,434 @@ bool ZSafe::openDocument(const char* _filename, const char* )
1976 1975
1977 Category *c1 = new Category(); 1976 Category *c1 = new Category();
1978 c1->setCategoryName(category); 1977 c1->setCategoryName(category);
1979 1978
1980 QString icon; 1979 QString icon;
1981 QString fullIconPath; 1980 QString fullIconPath;
1982 QPixmap *pix; 1981 QPixmap *pix;
1983// #ifndef WIN32 1982// #ifndef WIN32
1984 icon = conf->readEntry(APP_KEY+category); 1983 icon = conf->readEntry(APP_KEY+category);
1985// #endif 1984// #endif
1986 bool isIconAv = false; 1985 bool isIconAv = false;
1987 if (!icon.isEmpty() && !icon.isNull()) 1986 if (!icon.isEmpty() && !icon.isNull())
1988 { 1987 {
1989 // build the full path 1988 // build the full path
1990 fullIconPath = iconPath + icon; 1989 fullIconPath = iconPath + icon;
1991 pix = new QPixmap (fullIconPath); 1990 pix = new QPixmap (fullIconPath);
1992 if (pix) 1991 if (pix)
1993 { 1992 {
1994 QImage img = pix->convertToImage(); 1993 QImage img = pix->convertToImage();
1995 pix->convertFromImage(img.smoothScale(14,14)); 1994 pix->convertFromImage(img.smoothScale(14,14));
1996 c1->setIconName (icon); 1995 c1->setIconName (icon);
1997 c1->setIcon (*pix); 1996 c1->setIcon (*pix);
1998 isIconAv = true; 1997 isIconAv = true;
1999 } 1998 }
2000 } 1999 }
2001 if (!isIconAv) 2000 if (!isIconAv)
2002 { 2001 {
2003 c1->setIcon (*getPredefinedIcon(category)); 2002 c1->setIcon (*getPredefinedIcon(category));
2004 } 2003 }
2005 2004
2006 c1->setListItem (catI); 2005 c1->setListItem (catI);
2007 c1->initListItem(); 2006 c1->initListItem();
2008 categories.insert (c1->getCategoryName(), c1); 2007 categories.insert (c1->getCategoryName(), c1);
2009 numberOfEntries++; 2008 numberOfEntries++;
2010 } 2009 }
2011 2010
2012 for (int count = 0; count < FIELD_SIZE; count++) { 2011 for (int count = 0; count < FIELD_SIZE; count++) {
2013 free(entry[count]); 2012 free(entry[count]);
2014 } 2013 }
2015 retval = loadEntry(entry); 2014 retval = loadEntry(entry);
2016 if (retval == 2) { 2015 if (retval == 2) {
2017 // m_parent->slotStatusHelpMsg("Last entry loaded"); 2016 // m_parent->slotStatusHelpMsg("Last entry loaded");
2018 } 2017 }
2019 } // end while 2018 } // end while
2020 2019
2021 if (numberOfEntries == 0) 2020 if (numberOfEntries == 0)
2022 { 2021 {
2023 2022
2024 switch( QMessageBox::warning( this, tr("ZSafe"), 2023 switch( QMessageBox::warning( this, tr("ZSafe"),
2025 tr("Empty document or\nwrong password.\nContinue?"), 2024 tr("Empty document or\nwrong password.\nContinue?"),
2026 tr("&No"), tr("&Yes."), 2025 tr("&No"), tr("&Yes."),
2027 0 2026 0
2028 ) ) { 2027 ) ) {
2029 case 0: // No 2028 case 0: // No
2030 retval = loadFinalize(); 2029 retval = loadFinalize();
2031 exitZs (1); 2030 exitZs (1);
2032 break; 2031 break;
2033 case 1: // Yes 2032 case 1: // Yes
2034 break; 2033 break;
2035 } 2034 }
2036 } 2035 }
2037 2036
2038 retval = loadFinalize(); 2037 retval = loadFinalize();
2039 2038
2040 return true; 2039 return true;
2041} 2040}
2042 2041
2043int ZSafe::loadInit(const char* _filename, const char *password) 2042int ZSafe::loadInit(const char* _filename, const char *password)
2044{ 2043{
2045 unsigned int j = 0; 2044 unsigned int j = 0;
2046 unsigned int keylength=0; 2045 unsigned int keylength=0;
2047 int count=0, count2=0, count3=0; 2046 int count=0, count2=0, count3=0;
2048 unsigned char charbuf[8]; 2047 unsigned char charbuf[8];
2049 unsigned short ciphertext[4]; 2048 unsigned short ciphertext[4];
2050 char key[128]; 2049 char key[128];
2051 Krc2* krc2 = new Krc2(); 2050 Krc2* krc2 = new Krc2();
2052 2051
2053 fd = fopen (_filename, "rb"); 2052 fd = fopen (_filename, "rb");
2054 2053
2055 QFileInfo f (_filename); 2054 QFileInfo f (_filename);
2056 load_buffer_length = f.size(); 2055 load_buffer_length = f.size();
2057 load_buffer_length = ((load_buffer_length / 1024)+1) * 1024 * 2; 2056 load_buffer_length = ((load_buffer_length / 1024)+1) * 1024 * 2;
2058 2057
2059 if (fd == NULL) 2058 if (fd == NULL)
2060 return PWERR_OPEN; 2059 return PWERR_OPEN;
2061 2060
2062 buffer = (char *)malloc(load_buffer_length); 2061 buffer = (char *)malloc(load_buffer_length);
2063 for (j = 0; password[j] != '\0'; j++) { 2062 for (j = 0; password[j] != '\0'; j++) {
2064 key[j] = password[j]; 2063 key[j] = password[j];
2065 } 2064 }
2066 keylength = j; 2065 keylength = j;
2067 krc2->rc2_expandkey (key, keylength, 128); 2066 krc2->rc2_expandkey (key, keylength, 128);
2068 2067
2069#ifndef WIN32 2068#ifndef WIN32
2070 size = read(fileno (fd), (unsigned char *) (charbuf + count), 8); 2069 size = read(fileno (fd), (unsigned char *) (charbuf + count), 8);
2071#else 2070#else
2072 printf ("LoadInit() read1");
2073 size = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd); 2071 size = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd);
2074#endif 2072#endif
2075 2073
2076 if (size < 8) 2074 if (size < 8)
2077 return PWERR_DATA; 2075 return PWERR_DATA;
2078 2076
2079 for (count = 0; count < 4; count++) { 2077 for (count = 0; count < 4; count++) {
2080 count2 = count << 1; 2078 count2 = count << 1;
2081 iv[count] = charbuf[count2] << 8; 2079 iv[count] = charbuf[count2] << 8;
2082 iv[count] += charbuf[count2 + 1]; 2080 iv[count] += charbuf[count2 + 1];
2083 } 2081 }
2084 2082
2085 size = 0; 2083 size = 0;
2086 bufferIndex = 0; 2084 bufferIndex = 0;
2087#ifndef WIN32 2085#ifndef WIN32
2088 while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) { 2086 while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) {
2089 while (count < 8) { 2087 while (count < 8) {
2090 count2 = read (fileno (fd), (unsigned char *) (charbuf + count), 8); 2088 count2 = read (fileno (fd), (unsigned char *) (charbuf + count), 8);
2091#else 2089#else
2092 printf ("LoadInit() read2");
2093 while ((count = fread ((unsigned char *) (charbuf), sizeof(unsigned char), 8, fd)) > 0) { 2090 while ((count = fread ((unsigned char *) (charbuf), sizeof(unsigned char), 8, fd)) > 0) {
2094 while (count < 8) { 2091 while (count < 8) {
2095 count2 = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd); 2092 count2 = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd);
2096#endif 2093#endif
2097 if (count2 == 0) { 2094 if (count2 == 0) {
2098 return PWERR_DATA; 2095 return PWERR_DATA;
2099 } 2096 }
2100 count += count2; 2097 count += count2;
2101 } /* while (count < 8) */ 2098 } /* while (count < 8) */
2102 2099
2103 size += 8; 2100 size += 8;
2104 for (count2 = 0; count2 < 8; count2 += 2) { 2101 for (count2 = 0; count2 < 8; count2 += 2) {
2105 count3 = count2 >> 1; 2102 count3 = count2 >> 1;
2106 ciphertext[count3] = charbuf[count2] << 8; 2103 ciphertext[count3] = charbuf[count2] << 8;
2107 ciphertext[count3] += charbuf[count2 + 1]; 2104 ciphertext[count3] += charbuf[count2 + 1];
2108 2105
2109 plaintext[count3] = ciphertext[count3] ^ iv[count3]; 2106 plaintext[count3] = ciphertext[count3] ^ iv[count3];
2110 iv[count3] = plaintext[count3]; 2107 iv[count3] = plaintext[count3];
2111 } /* for (count2) */ 2108 } /* for (count2) */
2112 2109
2113 krc2->rc2_decrypt (plaintext); 2110 krc2->rc2_decrypt (plaintext);
2114 memcpy ((unsigned char *) (buffer + bufferIndex), plaintext, 8); 2111 memcpy ((unsigned char *) (buffer + bufferIndex), plaintext, 8);
2115 bufferIndex += 8; 2112 bufferIndex += 8;
2116 buffer[bufferIndex + 1] = '\0'; 2113 buffer[bufferIndex + 1] = '\0';
2117 } /* while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) */ 2114 } /* while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) */
2118 size -= buffer[size - 1]; 2115 size -= buffer[size - 1];
2119 lastcount = 0; 2116 lastcount = 0;
2120 2117
2121 /* This will point to the starting index */ 2118 /* This will point to the starting index */
2122 bufferIndex = 0; 2119 bufferIndex = 0;
2123 return PWERR_GOOD; 2120 return PWERR_GOOD;
2124} 2121}
2125 2122
2126int ZSafe::loadEntry(char *entry[FIELD_SIZE]) 2123int ZSafe::loadEntry(char *entry[FIELD_SIZE])
2127{ 2124{
2128 /* Strip off PKCS 5 padding 2125 /* Strip off PKCS 5 padding
2129 * Should check to make sure it's good here 2126 * Should check to make sure it's good here
2130 */ 2127 */
2131 int count, count1=0; 2128 int count, count1=0;
2132 2129
2133 for (count = lastcount; count < size; count++) { 2130 for (count = lastcount; count < size; count++) {
2134 if ((unsigned char) (buffer[count]) == 255) { 2131 if ((unsigned char) (buffer[count]) == 255) {
2135 if (buffer[bufferIndex] == '\0') { 2132 if (buffer[bufferIndex] == '\0') {
2136 bufferIndex++; 2133 bufferIndex++;
2137 } 2134 }
2138 entry[count1] = (char *) malloc (count - bufferIndex + 1); 2135 entry[count1] = (char *) malloc (count - bufferIndex + 1);
2139 memcpy (entry[count1], (unsigned char *) (buffer + bufferIndex), count - bufferIndex); 2136 memcpy (entry[count1], (unsigned char *) (buffer + bufferIndex), count - bufferIndex);
2140 entry[count1][count - bufferIndex] = '\0'; 2137 entry[count1][count - bufferIndex] = '\0';
2141 count++; 2138 count++;
2142 bufferIndex = count; 2139 bufferIndex = count;
2143 count1++; 2140 count1++;
2144 if (count1 == FIELD_SIZE) { 2141 if (count1 == FIELD_SIZE) {
2145 lastcount = count; 2142 lastcount = count;
2146 return 1; 2143 return 1;
2147 } 2144 }
2148 } /* if ((unsigned char) (buffer[count]) == 255) */ 2145 } /* if ((unsigned char) (buffer[count]) == 255) */
2149 } /* for (count = 0; count < size; count++) */ 2146 } /* for (count = 0; count < size; count++) */
2150 2147
2151 return 2; 2148 return 2;
2152} 2149}
2153 2150
2154int ZSafe::loadFinalize(void) 2151int ZSafe::loadFinalize(void)
2155{ 2152{
2156 fclose (fd); 2153 fclose (fd);
2157 if (buffer) free(buffer); 2154 if (buffer) free(buffer);
2158 return PWERR_GOOD; 2155 return PWERR_GOOD;
2159} 2156}
2160 2157
2161bool ZSafe::saveDocument(const char* _filename, 2158bool ZSafe::saveDocument(const char* _filename,
2162 bool withPwd, 2159 bool withPwd,
2163 const char* ) 2160 const char* )
2164{ 2161{
2165 if (filename.isEmpty()) 2162 if (filename.isEmpty())
2166 { 2163 {
2167 QMessageBox::critical( 0, tr("ZSafe"), 2164 QMessageBox::critical( 0, tr("ZSafe"),
2168 tr("No document defined.\nYou have to create a new document")); 2165 tr("No document defined.\nYou have to create a new document"));
2169 return false; 2166 return false;
2170 } 2167 }
2171 2168
2172 // if (m_password.isEmpty()) 2169 // if (m_password.isEmpty())
2173 // withPwd = true; // the document must be saved with a valid password 2170 // withPwd = true; // the document must be saved with a valid password
2174 if (withPwd) 2171 if (withPwd)
2175 { 2172 {
2176 bool pwdOk = FALSE; 2173 bool pwdOk = FALSE;
2177 while (!pwdOk) 2174 while (!pwdOk)
2178 { 2175 {
2179 getDocPassword(tr("Enter Password")); 2176 getDocPassword(tr("Enter Password"));
2180 if (m_password.isEmpty()) 2177 if (m_password.isEmpty())
2181 { 2178 {
2182 2179
2183 QMessageBox::critical( 0, tr("ZSafe"), 2180 QMessageBox::critical( 0, tr("ZSafe"),
2184 tr("Password is empty.\nPlease enter again.")); 2181 tr("Password is empty.\nPlease enter again."));
2185 continue; 2182 continue;
2186 } 2183 }
2187 2184
2188 QString firstPasswd = m_password; 2185 QString firstPasswd = m_password;
2189 2186
2190 getDocPassword(tr("Reenter Password")); 2187 getDocPassword(tr("Reenter Password"));
2191 if (m_password.isEmpty()) 2188 if (m_password.isEmpty())
2192 { 2189 {
2193 QMessageBox::critical( 0, tr("ZSafe"), 2190 QMessageBox::critical( 0, tr("ZSafe"),
2194 tr("Password is empty.\nPlease enter again.")); 2191 tr("Password is empty.\nPlease enter again."));
2195 continue; 2192 continue;
2196 } 2193 }
2197 if (firstPasswd != m_password) 2194 if (firstPasswd != m_password)
2198 { 2195 {
2199 2196
2200 QMessageBox::critical( 0, tr("ZSafe"), 2197 QMessageBox::critical( 0, tr("ZSafe"),
2201 tr("Passwords must be identical.\nPlease enter again.")); 2198 tr("Passwords must be identical.\nPlease enter again."));
2202 continue; 2199 continue;
2203 } 2200 }
2204 pwdOk = TRUE; 2201 pwdOk = TRUE;
2205 modified = false; 2202 modified = false;
2206 } 2203 }
2207 } 2204 }
2208 else if (modified) 2205 else if (modified)
2209 { 2206 {
2210 QString fns(_filename); 2207 QString fns(_filename);
2211 fns = fns.right (fns.length() - fns.findRev ('/') - 1); 2208 fns = fns.right (fns.length() - fns.findRev ('/') - 1);
2212 switch( QMessageBox::information( this, tr("ZSafe"), 2209 switch( QMessageBox::information( this, tr("ZSafe"),
2213 tr("Do you want to save ") + fns + tr("\nbefore continuing?"), 2210 tr("Do you want to save ") + fns + tr("\nbefore continuing?"),
2214 tr("&Save"), 2211 tr("&Save"),
2215 tr("&Don't Save"), 2212 tr("&Don't Save"),
2216 0 // Enter == button 0 2213 0 // Enter == button 0
2217 ) ) 2214 ) )
2218 { // Escape == button 2 2215 { // Escape == button 2
2219 case 0: // Save clicked, Alt-S or Enter pressed. 2216 case 0: // Save clicked, Alt-S or Enter pressed.
2220 modified = false; 2217 modified = false;
2221 break; 2218 break;
2222 case 1: // Don't Save clicked or Alt-D pressed 2219 case 1: // Don't Save clicked or Alt-D pressed
2223 modified = false; 2220 modified = false;
2224 return true; 2221 return true;
2225 } 2222 }
2226 } 2223 }
2227 modified = false; 2224 modified = false;
2228 2225
2229 if (m_password.isEmpty()) 2226 if (m_password.isEmpty())
2230 return false; 2227 return false;
2231 2228
2232 int retval = saveInit(_filename, m_password); 2229 int retval = saveInit(_filename, m_password);
2233 // int retval = saveInit(_filename, "test"); 2230 // int retval = saveInit(_filename, "test");
2234 if (retval != PWERR_GOOD) { 2231 if (retval != PWERR_GOOD) {
2235 return false; 2232 return false;
2236 } 2233 }
2237 2234
2238 char* entry[FIELD_SIZE]; 2235 char* entry[FIELD_SIZE];
2239 2236
2240 // save the validation entry 2237 // save the validation entry
2241 { 2238 {
2242 int i=0; 2239 int i=0;
2243 entry[i] = (char*)malloc(strlen("ZSAFECATEGORY")+1); 2240 entry[i] = (char*)malloc(strlen("ZSAFECATEGORY")+1);
2244 strcpy(entry[i++], "ZSAFECATEGORY"); 2241 strcpy(entry[i++], "ZSAFECATEGORY");
2245 entry[i] = (char*)malloc(strlen("name")+1); 2242 entry[i] = (char*)malloc(strlen("name")+1);
2246 strcpy(entry[i++], "name"); 2243 strcpy(entry[i++], "name");
2247 entry[i] = (char*)malloc(strlen("username")+1); 2244 entry[i] = (char*)malloc(strlen("username")+1);
2248 strcpy(entry[i++], "username"); 2245 strcpy(entry[i++], "username");
2249 entry[i] = (char*)malloc(strlen("password")+1); 2246 entry[i] = (char*)malloc(strlen("password")+1);
2250 strcpy(entry[i++], "password"); 2247 strcpy(entry[i++], "password");
2251 entry[i] = (char*)malloc(strlen("comment")+1); 2248 entry[i] = (char*)malloc(strlen("comment")+1);
2252 strcpy(entry[i++], "comment"); 2249 strcpy(entry[i++], "comment");
2253 2250
2254 entry[i] = (char*)malloc(strlen("field5")+1); 2251 entry[i] = (char*)malloc(strlen("field5")+1);
2255 strcpy(entry[i++], "field5"); 2252 strcpy(entry[i++], "field5");
2256 entry[i] = (char*)malloc(strlen("field6")+1); 2253 entry[i] = (char*)malloc(strlen("field6")+1);
2257 strcpy(entry[i++], "field6"); 2254 strcpy(entry[i++], "field6");
2258 2255
2259 retval = saveEntry(entry); 2256 retval = saveEntry(entry);
2260 for (int z=0; z<i; z++) free(entry[z]); 2257 for (int z=0; z<i; z++) free(entry[z]);
2261 if (retval == PWERR_DATA) { 2258 if (retval == PWERR_DATA) {
2262 qWarning("1: Error writing file, contents not saved"); 2259 owarn << "1: Error writing file, contents not saved" << oendl;
2263 saveFinalize(); 2260 saveFinalize();
2264 return false; 2261 return false;
2265 } 2262 }
2266// #ifndef WIN32 2263// #ifndef WIN32
2267 conf->writeEntry(APP_KEY+"valzsafe", 1); 2264 conf->writeEntry(APP_KEY+"valzsafe", 1);
2268// #endif 2265// #endif
2269 saveConf(); 2266 saveConf();
2270 } 2267 }
2271 2268
2272 QListViewItem *i; 2269 QListViewItem *i;
2273 // step through all categories 2270 // step through all categories
2274 for (i = ListView->firstChild(); 2271 for (i = ListView->firstChild();
2275 i != NULL; 2272 i != NULL;
2276 i = i->nextSibling()) 2273 i = i->nextSibling())
2277 { 2274 {
2278 // step through all subitems 2275 // step through all subitems
2279 QListViewItem *si; 2276 QListViewItem *si;
2280 for (si = i->firstChild(); 2277 for (si = i->firstChild();
2281 si != NULL; 2278 si != NULL;
2282 si = si->nextSibling()) 2279 si = si->nextSibling())
2283 { 2280 {
2284 int j=0; 2281 int j=0;
2285 entry[j] = (char*)malloc(strlen(i->text(0).utf8())+1); 2282 entry[j] = (char*)malloc(strlen(i->text(0).utf8())+1);
2286 strcpy(entry[j++], i->text(0).utf8()); 2283 strcpy(entry[j++], i->text(0).utf8());
2287 entry[j] = (char*)malloc(strlen(si->text(0).utf8())+1); 2284 entry[j] = (char*)malloc(strlen(si->text(0).utf8())+1);
2288 strcpy(entry[j++], si->text(0).utf8()); 2285 strcpy(entry[j++], si->text(0).utf8());
2289 entry[j] = (char*)malloc(strlen(si->text(1).utf8())+1); 2286 entry[j] = (char*)malloc(strlen(si->text(1).utf8())+1);
2290 strcpy(entry[j++], si->text(1).utf8()); 2287 strcpy(entry[j++], si->text(1).utf8());
2291 entry[j] = (char*)malloc(strlen(si->text(2).utf8())+1); 2288 entry[j] = (char*)malloc(strlen(si->text(2).utf8())+1);
2292 strcpy(entry[j++], si->text(2).utf8()); 2289 strcpy(entry[j++], si->text(2).utf8());
2293 entry[j] = (char*)malloc(strlen(si->text(3).utf8())+1); 2290 entry[j] = (char*)malloc(strlen(si->text(3).utf8())+1);
2294 strcpy(entry[j++], si->text(3).utf8()); 2291 strcpy(entry[j++], si->text(3).utf8());
2295 entry[j] = (char*)malloc(strlen(si->text(4).utf8())+1); 2292 entry[j] = (char*)malloc(strlen(si->text(4).utf8())+1);
2296 strcpy(entry[j++], si->text(4).utf8()); 2293 strcpy(entry[j++], si->text(4).utf8());
2297 entry[j] = (char*)malloc(strlen(si->text(5).utf8())+1); 2294 entry[j] = (char*)malloc(strlen(si->text(5).utf8())+1);
2298 strcpy(entry[j++], si->text(5).utf8()); 2295 strcpy(entry[j++], si->text(5).utf8());
2299 2296
2300 retval = saveEntry(entry); 2297 retval = saveEntry(entry);
2301 for (int z=0; z<j; z++) 2298 for (int z=0; z<j; z++)
2302 { 2299 {
2303 free(entry[z]); 2300 free(entry[z]);
2304 } 2301 }
2305 if (retval == PWERR_DATA) { 2302 if (retval == PWERR_DATA) {
2306 qWarning("1: Error writing file, contents not saved"); 2303 owarn << "1: Error writing file, contents not saved" << oendl;
2307 saveFinalize(); 2304 saveFinalize();
2308 return false; 2305 return false;
2309 } 2306 }
2310 2307
2311 } 2308 }
2312 } 2309 }
2313 2310
2314 if (saveFinalize() == PWERR_DATA) { 2311 if (saveFinalize() == PWERR_DATA) {
2315 qWarning("2: Error writing file, contents not saved"); 2312 owarn << "2: Error writing file, contents not saved" << oendl;
2316 return false; 2313 return false;
2317 } else { 2314 } else {
2318#ifndef DESKTOP 2315#ifndef DESKTOP
2319 Global::statusMessage (tr("Password file saved.")); 2316 Global::statusMessage (tr("Password file saved."));
2320#endif 2317#endif
2321 modified = false; 2318 modified = false;
2322 return true; 2319 return true;
2323 } 2320 }
2324} 2321}
2325 2322
2326PasswordForm *newPwdDialog; 2323PasswordForm *newPwdDialog;
2327bool newPwdDialogResult = false; 2324bool newPwdDialogResult = false;
2328void ZSafe::setPasswordDialogDone() 2325void ZSafe::setPasswordDialogDone()
2329{ 2326{
2330 newPwdDialogResult = true; 2327 newPwdDialogResult = true;
2331 newPwdDialog->close(); 2328 newPwdDialog->close();
2332} 2329}
2333 2330
2334void ZSafe::getDocPassword(QString title) 2331void ZSafe::getDocPassword(QString title)
2335{ 2332{
2336qWarning ("getDocPassword"); 2333qWarning ("getDocPassword");
2337 // open the 'Password' dialog 2334 // open the 'Password' dialog
2338 PasswordForm *dialog = new PasswordForm(this, title, TRUE); 2335 PasswordForm *dialog = new PasswordForm(this, title, TRUE);
2339 newPwdDialog = dialog; 2336 newPwdDialog = dialog;
2340 newPwdDialogResult = false; 2337 newPwdDialogResult = false;
2341 2338
2342 connect( dialog->PasswordField, SIGNAL( returnPressed() ), 2339 connect( dialog->PasswordField, SIGNAL( returnPressed() ),
2343 this, SLOT( setPasswordDialogDone() ) ); 2340 this, SLOT( setPasswordDialogDone() ) );
2344 2341
2345 // CS: !!! 2342 // CS: !!!
2346 // int pos = filename.findRev ('/'); 2343 // int pos = filename.findRev ('/');
2347 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 2344 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
2348#ifdef WIN32 2345#ifdef WIN32
2349 dialog->setCaption("Qt " + ti); 2346 dialog->setCaption("Qt " + ti);
2350#else 2347#else
2351 dialog->setCaption(ti); 2348 dialog->setCaption(ti);
2352#endif 2349#endif
2353 // dialog->setCaption(title); 2350 // dialog->setCaption(title);
2354 2351
2355 dialog->PasswordField->setFocus(); 2352 dialog->PasswordField->setFocus();
2356 DialogCode result = (DialogCode) dialog->exec(); 2353 DialogCode result = (DialogCode) dialog->exec();
2357#ifdef DESKTOP 2354#ifdef DESKTOP
2358 result = Accepted; 2355 result = Accepted;
2359#endif 2356#endif
2360 2357
2361 QString password; 2358 QString password;
2362 if (result == Accepted || newPwdDialogResult) 2359 if (result == Accepted || newPwdDialogResult)
2363 { 2360 {
2364 m_password = dialog->PasswordField->text(); 2361 m_password = dialog->PasswordField->text();
2365 } 2362 }
2366 else 2363 else
2367 { 2364 {
2368 exitZs (1); 2365 exitZs (1);
2369 } 2366 }
2370} 2367}
2371 2368
2372int ZSafe::saveInit(const char *_filename, const char *password) 2369int ZSafe::saveInit(const char *_filename, const char *password)
2373{ 2370{
2374 char key[128]; 2371 char key[128];
2375 unsigned int j = 0; 2372 unsigned int j = 0;
2376 unsigned int keylength; 2373 unsigned int keylength;
2377 // int val; 2374 // int val;
2378 int count2; 2375 int count2;
2379 Krc2* krc2 = new Krc2(); 2376 Krc2* krc2 = new Krc2();
2380 2377
2381 /* first we should check the permissions of the filename */ 2378 /* first we should check the permissions of the filename */
2382/* 2379/*
2383 if (QFile::exists(_filename)) { 2380 if (QFile::exists(_filename)) {
2384 val = checkFile(_filename); 2381 val = checkFile(_filename);
2385 if (val != PWERR_GOOD) 2382 if (val != PWERR_GOOD)
2386 return val; 2383 return val;
2387 } else 2384 } else
2388 { 2385 {
2389 val = creat (_filename, (S_IRUSR | S_IWUSR)); 2386 val = creat (_filename, (S_IRUSR | S_IWUSR));
2390 if (val == -1) 2387 if (val == -1)
2391 return PWERR_OPEN; 2388 return PWERR_OPEN;
2392 else 2389 else
2393 close(val); 2390 close(val);
2394 } 2391 }
2395*/ 2392*/
2396 QFileInfo f (_filename); 2393 QFileInfo f (_filename);
2397 save_buffer_length = f.size(); 2394 save_buffer_length = f.size();
2398 save_buffer_length = ((save_buffer_length / 1024)+1) * 1024; 2395 save_buffer_length = ((save_buffer_length / 1024)+1) * 1024;
2399 2396
2400 fd = fopen (_filename, "wb"); 2397 fd = fopen (_filename, "wb");
2401 if (fd == NULL) 2398 if (fd == NULL)
2402 return PWERR_OPEN; 2399 return PWERR_OPEN;
2403 2400
2404 buffer = (char*)malloc(save_buffer_length); 2401 buffer = (char*)malloc(save_buffer_length);
2405 2402
2406 /* make the key ready */ 2403 /* make the key ready */
2407 for (j = 0; password[j] != '\0'; j++) { 2404 for (j = 0; password[j] != '\0'; j++) {
2408 key[j] = password[j]; 2405 key[j] = password[j];
2409 } 2406 }
2410 keylength = j; 2407 keylength = j;
2411 krc2->rc2_expandkey (key, keylength, 128); 2408 krc2->rc2_expandkey (key, keylength, 128);
@@ -3097,193 +3094,193 @@ void ZSafe::editCategory()
3097 dialog->IconField->setCurrentItem(0); 3094 dialog->IconField->setCurrentItem(0);
3098 } 3095 }
3099 3096
3100 dialog->IconField->insertItem("predefined"); 3097 dialog->IconField->insertItem("predefined");
3101 while ( (fi=it.current()) ) { // for each file... 3098 while ( (fi=it.current()) ) { // for each file...
3102 QString fileName = fi->fileName(); 3099 QString fileName = fi->fileName();
3103 if(fileName.right(4) == ".png") 3100 if(fileName.right(4) == ".png")
3104 { 3101 {
3105 fileName = fileName.mid(0,fileName.length()-4); 3102 fileName = fileName.mid(0,fileName.length()-4);
3106#ifdef DESKTOP 3103#ifdef DESKTOP
3107 QPixmap imageOfFile; 3104 QPixmap imageOfFile;
3108 imageOfFile.load(iconPath + fi->fileName()); 3105 imageOfFile.load(iconPath + fi->fileName());
3109#else 3106#else
3110 QPixmap imageOfFile(Resource::loadPixmap(fileName)); 3107 QPixmap imageOfFile(Resource::loadPixmap(fileName));
3111#endif 3108#endif
3112 QImage foo = imageOfFile.convertToImage(); 3109 QImage foo = imageOfFile.convertToImage();
3113 foo = foo.smoothScale(16,16); 3110 foo = foo.smoothScale(16,16);
3114 imageOfFile.convertFromImage(foo); 3111 imageOfFile.convertFromImage(foo);
3115 dialog->IconField->insertItem(imageOfFile,fileName); 3112 dialog->IconField->insertItem(imageOfFile,fileName);
3116 if(fileName+".png"==icon) 3113 if(fileName+".png"==icon)
3117 dialog->IconField->setCurrentItem(i+1); 3114 dialog->IconField->setCurrentItem(i+1);
3118 ++i; 3115 ++i;
3119 } 3116 }
3120 ++it; 3117 ++it;
3121 } 3118 }
3122 waitDialog.hide(); 3119 waitDialog.hide();
3123 } 3120 }
3124 else 3121 else
3125 { 3122 {
3126#ifdef DESKTOP 3123#ifdef DESKTOP
3127 // QDir d(QDir::homeDirPath() + "/pics/"); 3124 // QDir d(QDir::homeDirPath() + "/pics/");
3128 QDir d(iconPath); 3125 QDir d(iconPath);
3129#else 3126#else
3130 QDir d(QPEApplication::qpeDir() + "/pics/"); 3127 QDir d(QPEApplication::qpeDir() + "/pics/");
3131#endif 3128#endif
3132 d.setFilter( QDir::Files); 3129 d.setFilter( QDir::Files);
3133 3130
3134 const QFileInfoList *list = d.entryInfoList(); 3131 const QFileInfoList *list = d.entryInfoList();
3135 int i=0; 3132 int i=0;
3136 QFileInfoListIterator it( *list ); // create list iterator 3133 QFileInfoListIterator it( *list ); // create list iterator
3137 QFileInfo *fi; // pointer for traversing 3134 QFileInfo *fi; // pointer for traversing
3138 if (icon.isEmpty() || icon.isNull()) 3135 if (icon.isEmpty() || icon.isNull())
3139 { 3136 {
3140 dialog->IconField->setCurrentItem(0); 3137 dialog->IconField->setCurrentItem(0);
3141 } 3138 }
3142 else 3139 else
3143 { 3140 {
3144 3141
3145 while ( (fi=it.current()) ) 3142 while ( (fi=it.current()) )
3146 { // for each file... 3143 { // for each file...
3147 QString fileName = fi->fileName(); 3144 QString fileName = fi->fileName();
3148 if(fileName.right(4) == ".png") 3145 if(fileName.right(4) == ".png")
3149 { 3146 {
3150 fileName = fileName.mid(0,fileName.length()-4); 3147 fileName = fileName.mid(0,fileName.length()-4);
3151 3148
3152 3149
3153 if(fileName+".png"==icon) 3150 if(fileName+".png"==icon)
3154 { 3151 {
3155 dialog->IconField->setCurrentItem(i+1); 3152 dialog->IconField->setCurrentItem(i+1);
3156 break; 3153 break;
3157 } 3154 }
3158 ++i; 3155 ++i;
3159 } 3156 }
3160 ++it; 3157 ++it;
3161 } 3158 }
3162 } 3159 }
3163 } 3160 }
3164 3161
3165 // dialog->show(); 3162 // dialog->show();
3166#ifndef DESKTOP 3163#ifndef DESKTOP
3167 // dialog->move (20, 100); 3164 // dialog->move (20, 100);
3168#endif 3165#endif
3169 DialogCode result = (DialogCode) dialog->exec(); 3166 DialogCode result = (DialogCode) dialog->exec();
3170#ifdef DESKTOP 3167#ifdef DESKTOP
3171 result = Accepted; 3168 result = Accepted;
3172#endif 3169#endif
3173 3170
3174 QString fullIconPath; 3171 QString fullIconPath;
3175 QPixmap *pix; 3172 QPixmap *pix;
3176 if (result == Accepted) 3173 if (result == Accepted)
3177 { 3174 {
3178 modified = true; 3175 modified = true;
3179 if (category != dialog->CategoryField->currentText()) 3176 if (category != dialog->CategoryField->currentText())
3180 { 3177 {
3181 categories.remove (category); 3178 categories.remove (category);
3182// #ifndef WIN32 3179// #ifndef WIN32
3183 conf->removeEntry(category); 3180 conf->removeEntry(category);
3184// #endif 3181// #endif
3185 saveConf(); 3182 saveConf();
3186 } 3183 }
3187 3184
3188 category = dialog->CategoryField->currentText(); 3185 category = dialog->CategoryField->currentText();
3189 icon = dialog->IconField->currentText()+".png"; 3186 icon = dialog->IconField->currentText()+".png";
3190 3187
3191 if (cat) 3188 if (cat)
3192 { 3189 {
3193 qWarning("Category found"); 3190 owarn << "Category found" << oendl;
3194 3191
3195 // if (!icon.isEmpty() && !icon.isNull()) 3192 // if (!icon.isEmpty() && !icon.isNull())
3196 if (icon != "predefined.png") 3193 if (icon != "predefined.png")
3197 { 3194 {
3198 // build the full path 3195 // build the full path
3199 fullIconPath = iconPath + icon; 3196 fullIconPath = iconPath + icon;
3200 pix = new QPixmap (fullIconPath); 3197 pix = new QPixmap (fullIconPath);
3201 if (pix) 3198 if (pix)
3202 { 3199 {
3203 // save the full pixmap name into the config file 3200 // save the full pixmap name into the config file
3204// #ifndef WIN32 3201// #ifndef WIN32
3205 conf->writeEntry(APP_KEY+category, icon); 3202 conf->writeEntry(APP_KEY+category, icon);
3206// #endif 3203// #endif
3207 saveConf(); 3204 saveConf();
3208 QImage img = pix->convertToImage(); 3205 QImage img = pix->convertToImage();
3209 pix->convertFromImage(img.smoothScale(14,14)); 3206 pix->convertFromImage(img.smoothScale(14,14));
3210 cat->setIconName (icon); 3207 cat->setIconName (icon);
3211 cat->setIcon (*pix); 3208 cat->setIcon (*pix);
3212 } 3209 }
3213 } 3210 }
3214 else 3211 else
3215 { 3212 {
3216// #ifndef WIN32 3213// #ifndef WIN32
3217 conf->removeEntry (category); 3214 conf->removeEntry (category);
3218// #endif 3215// #endif
3219 saveConf(); 3216 saveConf();
3220 cat->setIcon (*getPredefinedIcon(category)); 3217 cat->setIcon (*getPredefinedIcon(category));
3221 } 3218 }
3222 3219
3223 // change the category name of the selected category 3220 // change the category name of the selected category
3224 QListViewItem *catItem = cat->getListItem(); 3221 QListViewItem *catItem = cat->getListItem();
3225 if (catItem) 3222 if (catItem)
3226 { 3223 {
3227 qWarning (category); 3224 qWarning (category);
3228 catItem->setText( 0, tr( category ) ); 3225 catItem->setText( 0, tr( category ) );
3229 cat->setCategoryName (tr(category)); 3226 cat->setCategoryName (tr(category));
3230 3227
3231 cat->initListItem(); 3228 cat->initListItem();
3232 categories.insert (category, cat); 3229 categories.insert (category, cat);
3233 } 3230 }
3234 } 3231 }
3235 saveCategoryDialogFields(dialog); 3232 saveCategoryDialogFields(dialog);
3236 } 3233 }
3237 else 3234 else
3238 { 3235 {
3239 // delete dialog; 3236 // delete dialog;
3240 dialog->hide(); 3237 dialog->hide();
3241 return; 3238 return;
3242 } 3239 }
3243 3240
3244 } 3241 }
3245} 3242}
3246 3243
3247void ZSafe::cutItem() 3244void ZSafe::cutItem()
3248{ 3245{
3249 if (!selectedItem) 3246 if (!selectedItem)
3250 return; 3247 return;
3251 if (!isCategory(selectedItem)) 3248 if (!isCategory(selectedItem))
3252 { 3249 {
3253 IsCut = true; 3250 IsCut = true;
3254 copiedItem = selectedItem; 3251 copiedItem = selectedItem;
3255 } 3252 }
3256} 3253}
3257 3254
3258void ZSafe::copyItem() 3255void ZSafe::copyItem()
3259{ 3256{
3260 if (!selectedItem) 3257 if (!selectedItem)
3261 return; 3258 return;
3262 if (!isCategory(selectedItem)) 3259 if (!isCategory(selectedItem))
3263 { 3260 {
3264 IsCopy = true; 3261 IsCopy = true;
3265 copiedItem = selectedItem; 3262 copiedItem = selectedItem;
3266 } 3263 }
3267} 3264}
3268 3265
3269// paste item into category 3266// paste item into category
3270void ZSafe::pasteItem() 3267void ZSafe::pasteItem()
3271{ 3268{
3272 if (!selectedItem) 3269 if (!selectedItem)
3273 return; 3270 return;
3274 if (isCategory(selectedItem)) 3271 if (isCategory(selectedItem))
3275 { 3272 {
3276 modified = true; 3273 modified = true;
3277 if (IsCut) 3274 if (IsCut)
3278 { 3275 {
3279 if (copiedItem) 3276 if (copiedItem)
3280 { 3277 {
3281 // add the new item 3278 // add the new item
3282 QListViewItem *i = new ShadedListItem (0, selectedItem); 3279 QListViewItem *i = new ShadedListItem (0, selectedItem);
3283 // i->setOpen (TRUE); 3280 // i->setOpen (TRUE);
3284 i->setText (0, copiedItem->text(0)); 3281 i->setText (0, copiedItem->text(0));
3285 i->setText (1, copiedItem->text(1)); 3282 i->setText (1, copiedItem->text(1));
3286 i->setText (2, copiedItem->text(2)); 3283 i->setText (2, copiedItem->text(2));
3287 i->setText (3, copiedItem->text(3)); 3284 i->setText (3, copiedItem->text(3));
3288 i->setText (4, copiedItem->text(4)); 3285 i->setText (4, copiedItem->text(4));
3289 i->setText (5, copiedItem->text(5)); 3286 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 @@
1TEMPLATE = app 1TEMPLATE = app
2CONFIG = qt warn_on 2CONFIG = qt warn_on
3DESTDIR = $(OPIEDIR)/bin 3DESTDIR = $(OPIEDIR)/bin
4HEADERS = zsafe.h krc2.h category.h categorylist.h zlistview.h \ 4HEADERS = zsafe.h krc2.h category.h categorylist.h zlistview.h \
5 scqtfiledlg.h 5 scqtfiledlg.h
6SOURCES = main.cpp zsafe.cpp krc2.cpp category.cpp \ 6SOURCES = main.cpp zsafe.cpp krc2.cpp category.cpp \
7 categorylist.cpp zlistview.cpp shadedlistitem.cpp\ 7 categorylist.cpp zlistview.cpp shadedlistitem.cpp\
8 scqtfileedit.cpp scqtfileedit.moc.cpp \ 8 scqtfileedit.cpp scqtfileedit.moc.cpp \
9 scqtfiledlg.cpp 9 scqtfiledlg.cpp
10INTERFACES = newdialog.ui searchdialog.ui passworddialog.ui categorydialog.ui infoform.ui wait.ui 10INTERFACES = newdialog.ui searchdialog.ui passworddialog.ui categorydialog.ui infoform.ui wait.ui
11INCLUDEPATH += $(OPIEDIR)/include 11INCLUDEPATH += $(OPIEDIR)/include
12DEPENDPATH += $(OPIEDIR)/include 12DEPENDPATH += $(OPIEDIR)/include
13LIBS += -Wl,-rpath,$(OPIEDIR)/lib -L$(OPIEDIR)/lib -lqpe -lopiecore2 -lopieui2 13LIBS += -lqpe -lopiecore2 -lopieui2
14TARGET = zsafe 14TARGET = zsafe
15 15
16include ( $(OPIEDIR)/include.pro ) 16include ( $(OPIEDIR)/include.pro )
17 17
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 @@
1 config KEYPEBBLE 1 config KEYPEBBLE
2 boolean "opie-keypebble (Virtual Network Computing VNC viewer)" 2 boolean "opie-keypebble (Virtual Network Computing VNC viewer)"
3 default "y" 3 default "y"
4 depends ( LIBQPE || LIBQPE-X11 ) 4 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 @@
1CONFIG += qt warn_on quick-app 1CONFIG += qt warn_on quick-app
2 HEADERS = d3des.h \ 2 HEADERS = d3des.h \
3 krfbbuffer.h \ 3 krfbbuffer.h \
4 krfbcanvas.h \ 4 krfbcanvas.h \
5 krfbconnection.h \ 5 krfbconnection.h \
6 krfbdecoder.h \ 6 krfbdecoder.h \
7 krfblogin.h \ 7 krfblogin.h \
8 krfbserver.h \ 8 krfbserver.h \
9 krfbserverinfo.h \ 9 krfbserverinfo.h \
10 kvnc.h \ 10 kvnc.h \
11 kvncconndlg.h \ 11 kvncconndlg.h \
12 kvncbookmarkdlg.h \ 12 kvncbookmarkdlg.h \
13 vncauth.h 13 vncauth.h
14 SOURCES = d3des.c \ 14 SOURCES = d3des.c \
15 vncauth.c \ 15 vncauth.c \
16 krfbbuffer.cpp \ 16 krfbbuffer.cpp \
17 krfbcanvas.cpp \ 17 krfbcanvas.cpp \
18 krfbconnection.cpp \ 18 krfbconnection.cpp \
19 krfbdecoder.cpp \ 19 krfbdecoder.cpp \
20 krfblogin.cpp \ 20 krfblogin.cpp \
21 krfbserver.cpp \ 21 krfbserver.cpp \
22 kvnc.cpp \ 22 kvnc.cpp \
23 kvncconndlg.cpp \ 23 kvncconndlg.cpp \
24 kvncbookmarkdlg.cpp \ 24 kvncbookmarkdlg.cpp \
25 main.cpp 25 main.cpp
26 INTERFACES= kvncconndlgbase.ui \ 26 INTERFACES= kvncconndlgbase.ui kvncbookmarkdlgbase.ui
27 kvncbookmarkdlgbase.ui
28 27
29INCLUDEPATH += $(OPIEDIR)/include 28INCLUDEPATH += $(OPIEDIR)/include
30DEPENDPATH += $(OPIEDIR)/include 29DEPENDPATH += $(OPIEDIR)/include
31LIBS += -lqpe 30LIBS += -lqpe -lopiecore2
32 31
33 TARGET = keypebble 32 TARGET = keypebble
34 33
35include ( $(OPIEDIR)/include.pro ) 34include ( $(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 @@
1#include <assert.h>
2#include <qimage.h>
3#include <qpainter.h>
4#include <qapplication.h>
5#include "krfbdecoder.h" 1#include "krfbdecoder.h"
6#include "krfbbuffer.h" 2#include "krfbbuffer.h"
7#include "krfbconnection.h" 3#include "krfbconnection.h"
8#include "krfbserverinfo.h" 4#include "krfbserverinfo.h"
9 5
6/* OPIE */
7#include <opie2/odebug.h>
8using namespace Opie::Core;
9
10/* QT */
11#include <qimage.h>
12#include <qpainter.h>
13#include <qapplication.h>
14
15/* STD */
16#include <assert.h>
17
10// 18//
11// Endian stuff 19// Endian stuff
12// 20//
13#ifndef KDE_USE_FINAL 21#ifndef OPIE_NO_DEBUG
14const int endianTest = 1; 22const int endianTest = 1;
15#endif 23#endif
16 24
17#define Swap16IfLE(s) \ 25#define Swap16IfLE(s) \
18 (*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s)) 26 (*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s))
19 27
20#define Swap32IfLE(l) \ 28#define Swap32IfLE(l) \
21 (*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \ 29 (*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \
22 (((l) & 0x00ff0000) >> 8) | \ 30 (((l) & 0x00ff0000) >> 8) | \
23 (((l) & 0x0000ff00) << 8) | \ 31 (((l) & 0x0000ff00) << 8) | \
24 (((l) & 0x000000ff) << 24)) : (l)) 32 (((l) & 0x000000ff) << 24)) : (l))
25 33
26KRFBBuffer::KRFBBuffer( KRFBDecoder *decoder, 34KRFBBuffer::KRFBBuffer( KRFBDecoder *decoder,
27 QObject *parent, const char *name ) 35 QObject *parent, const char *name )
28 : QObject( parent, name ) 36 : QObject( parent, name )
29{ 37{
30 assert( decoder ); 38 assert( decoder );
31 this->decoder = decoder; 39 this->decoder = decoder;
32 pix = new QPixmap(); 40 pix = new QPixmap();
33} 41}
34 42
35KRFBBuffer::~KRFBBuffer() 43KRFBBuffer::~KRFBBuffer()
36{ 44{
37 delete pix; 45 delete pix;
38} 46}
39 47
40void KRFBBuffer::resize( int w, int h ) 48void KRFBBuffer::resize( int w, int h )
41{ 49{
42 qWarning( "Resizing buffer" ); 50 owarn << "Resizing buffer" << oendl;
43 51
44 pix->resize( w, h ); 52 pix->resize( w, h );
45 53
46 QPalette pal = qApp->palette(); 54 QPalette pal = qApp->palette();
47 pix->fill( pal.active().base() ); 55 pix->fill( pal.active().base() );
48 56
49 emit sizeChanged( w, h ); 57 emit sizeChanged( w, h );
50} 58}
51 59
52void KRFBBuffer::soundBell() 60void KRFBBuffer::soundBell()
53{ 61{
54 emit bell(); 62 emit bell();
55} 63}
56 64
57void KRFBBuffer::mouseEvent( QMouseEvent *e ) 65void KRFBBuffer::mouseEvent( QMouseEvent *e )
58{ 66{
59 decoder->sendMouseEvent( e ); 67 decoder->sendMouseEvent( e );
60} 68}
61 69
62void KRFBBuffer::keyPressEvent( QKeyEvent *e ) 70void KRFBBuffer::keyPressEvent( QKeyEvent *e )
63{ 71{
64 qWarning( "Buffer got a key" ); 72 owarn << "Buffer got a key" << oendl;
65 73
66 decoder->sendKeyPressEvent( e ); 74 decoder->sendKeyPressEvent( e );
67} 75}
68 76
69void KRFBBuffer::keyReleaseEvent( QKeyEvent *e ) 77void KRFBBuffer::keyReleaseEvent( QKeyEvent *e )
70{ 78{
71 decoder->sendKeyReleaseEvent( e ); 79 decoder->sendKeyReleaseEvent( e );
72} 80}
73 81
74void KRFBBuffer::copyRect( int srcX, int srcY, 82void KRFBBuffer::copyRect( int srcX, int srcY,
75 int destX, int destY, int w, int h ) 83 int destX, int destY, int w, int h )
76{ 84{
77// qWarning( "Got copy rect" ); 85// owarn << "Got copy rect" << oendl;
78 bitBlt( pix, destX, destY, pix, srcX, srcY, w, h, CopyROP ); 86 bitBlt( pix, destX, destY, pix, srcX, srcY, w, h, CopyROP );
79 87
80 emit updated( destX, destY, w, h ); 88 emit updated( destX, destY, w, h );
81} 89}
82 90
83void KRFBBuffer::drawRawRectChunk( void *data, 91void KRFBBuffer::drawRawRectChunk( void *data,
84 int x, int y, int w, int h ) 92 int x, int y, int w, int h )
85{ 93{
86 QImage img( w, h, 32 ); 94 QImage img( w, h, 32 );
87 95
88 int scaleFactor=decoder->con->options()->scaleFactor; 96 int scaleFactor=decoder->con->options()->scaleFactor;
89 int redMax = Swap16IfLE( decoder->format->redMax ); 97 int redMax = Swap16IfLE( decoder->format->redMax );
90 int greenMax = Swap16IfLE( decoder->format->greenMax ); 98 int greenMax = Swap16IfLE( decoder->format->greenMax );
91 int blueMax = Swap16IfLE( decoder->format->blueMax ); 99 int blueMax = Swap16IfLE( decoder->format->blueMax );
92 100
93 QPainter p( pix ); 101 QPainter p( pix );
94 102
95 if ( decoder->format->bpp == 8 ) { 103 if ( decoder->format->bpp == 8 ) {
96 uchar *d = (unsigned char *) data; 104 uchar *d = (unsigned char *) data;
97 105
98 uint r,g,b; 106 uint r,g,b;
99 107
100 108
101 for ( int j = 0; j < h; j++) { 109 for ( int j = 0; j < h; j++) {
102 for ( int i = 0; i < w ; i++ ) { 110 for ( int i = 0; i < w ; i++ ) {
103 r = d[ j * w + i ]; 111 r = d[ j * w + i ];
104 r = r >> decoder->format->redShift; 112 r = r >> decoder->format->redShift;
105 r = r & redMax; 113 r = r & redMax;
106 114
107 g = d[ j * w + i ]; 115 g = d[ j * w + i ];
108 g = g >> decoder->format->greenShift; 116 g = g >> decoder->format->greenShift;
109 g = g & greenMax; 117 g = g & greenMax;
110 118
111 b = d[ j * w + i ]; 119 b = d[ j * w + i ];
112 b = b >> decoder->format->blueShift; 120 b = b >> decoder->format->blueShift;
113 b = b & blueMax; 121 b = b & blueMax;
114 122
115 r = ( r * 255 ) / redMax; 123 r = ( r * 255 ) / redMax;
116 g = ( g * 255 ) / greenMax; 124 g = ( g * 255 ) / greenMax;
117 b = ( b * 255 ) / blueMax; 125 b = ( b * 255 ) / blueMax;
118 126
119 uint *p = ( uint * ) img.scanLine( j ) + i; 127 uint *p = ( uint * ) img.scanLine( j ) + i;
120 *p = qRgb( r,g,b ); 128 *p = qRgb( r,g,b );
121 } 129 }
122 } 130 }
123 } 131 }
124 else if ( decoder->format->bpp == 32 ) { 132 else if ( decoder->format->bpp == 32 ) {
125 ulong *d = (ulong *) data; 133 ulong *d = (ulong *) data;
126 134
127 ulong r,g,b; 135 ulong r,g,b;
128 136
129 for ( int j = 0; j < h; j++ ) { 137 for ( int j = 0; j < h; j++ ) {
130 for ( int i = 0; i < w ; i++ ) { 138 for ( int i = 0; i < w ; i++ ) {
131 ulong pixel = d[ j * w + i ]; 139 ulong pixel = d[ j * w + i ];
132 pixel = Swap32IfLE( pixel ); 140 pixel = Swap32IfLE( pixel );
133 141
134 r = pixel; 142 r = pixel;
135 r = r >> decoder->format->redShift; 143 r = r >> decoder->format->redShift;
136 r = r & redMax; 144 r = r & redMax;
137 145
138 g = pixel; 146 g = pixel;
139 g = g >> decoder->format->greenShift; 147 g = g >> decoder->format->greenShift;
140 g = g & greenMax; 148 g = g & greenMax;
141 149
142 b = pixel; 150 b = pixel;
143 b = b >> decoder->format->blueShift; 151 b = b >> decoder->format->blueShift;
144 b = b & blueMax; 152 b = b & blueMax;
145 153
146 r = ( r * 255 ) / redMax; 154 r = ( r * 255 ) / redMax;
147 g = ( g * 255 ) / greenMax; 155 g = ( g * 255 ) / greenMax;
148 b = ( b * 255 ) / blueMax; 156 b = ( b * 255 ) / blueMax;
149 157
150 uint *p = ( uint * ) img.scanLine( j ) + i; 158 uint *p = ( uint * ) img.scanLine( j ) + i;
151 *p = qRgb( r,g,b ); 159 *p = qRgb( r,g,b );
152 } 160 }
153 } 161 }
154 } else if (decoder->format->bpp == 16 ) { 162 } else if (decoder->format->bpp == 16 ) {
155 163
156 CARD16 *d = (CARD16 *) data; 164 CARD16 *d = (CARD16 *) data;
157 165
158 uint r,g,b; 166 uint r,g,b;
159 167
160 for ( int j = 0; j < h; j++ ) { 168 for ( int j = 0; j < h; j++ ) {
161 for ( int i = 0; i < w ; i++ ) { 169 for ( int i = 0; i < w ; i++ ) {
162 CARD16 pixel = d[ j * w + i ]; 170 CARD16 pixel = d[ j * w + i ];
163 pixel = Swap16IfLE( pixel ); 171 pixel = Swap16IfLE( pixel );
164 172
165 r = pixel; 173 r = pixel;
166 r = r >> decoder->format->redShift; 174 r = r >> decoder->format->redShift;
167 r = r & redMax; 175 r = r & redMax;
168 176
169 g = pixel; 177 g = pixel;
170 g = g >> decoder->format->greenShift; 178 g = g >> decoder->format->greenShift;
171 g = g & greenMax; 179 g = g & greenMax;
172 180
173 b = pixel; 181 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 @@
1#include "krfbconnection.h" 1#include "krfbconnection.h"
2#include "krfbcanvas.h" 2#include "krfbcanvas.h"
3#include "krfbbuffer.h" 3#include "krfbbuffer.h"
4 4
5/* OPIE */
6#include <opie2/odebug.h>
5#include <qpe/qpeapplication.h> 7#include <qpe/qpeapplication.h>
8using namespace Opie::Core;
6 9
10/* QT */
7#include <qclipboard.h> 11#include <qclipboard.h>
8 12
9KRFBCanvas::KRFBCanvas( QWidget *parent, const char *name ) 13KRFBCanvas::KRFBCanvas( QWidget *parent, const char *name )
10 : QScrollView( parent, name ) 14 : QScrollView( parent, name )
11{ 15{
12 connection_ = new KRFBConnection(); 16 connection_ = new KRFBConnection();
13 connect( connection_, SIGNAL( loggedIn() ), 17 connect( connection_, SIGNAL( loggedIn() ),
14 this, SLOT( loggedIn() ) ); 18 this, SLOT( loggedIn() ) );
15 19
16 loggedIn_ = false; 20 loggedIn_ = false;
17 21
18 //QPEApplication::setStylusOperation(viewport(), QPEApplication::RightOnHold); 22 //QPEApplication::setStylusOperation(viewport(), QPEApplication::RightOnHold);
19 23
20 viewport()->setFocusPolicy( QWidget::StrongFocus ); 24 viewport()->setFocusPolicy( QWidget::StrongFocus );
21 viewport()->setFocus(); 25 viewport()->setFocus();
22 26
23 nextRightClick=0; 27 nextRightClick=0;
24 nextDoubleClick=0; 28 nextDoubleClick=0;
25} 29}
26 30
27KRFBCanvas::~KRFBCanvas() 31KRFBCanvas::~KRFBCanvas()
28{ 32{
29} 33}
30 34
31 35
32void KRFBCanvas::openConnection(KRFBServer server) 36void KRFBCanvas::openConnection(KRFBServer server)
33{ 37{
34 38
35 39
36 QCString host = server.hostname.latin1(); 40 QCString host = server.hostname.latin1();
37 password=server.password; 41 password=server.password;
38 connection_->connectTo( server); 42 connection_->connectTo( server);
39} 43}
40 44
41 45
42void KRFBCanvas::openURL( const QUrl &url ) 46void KRFBCanvas::openURL( const QUrl &url )
43{ 47{
44 if ( loggedIn_ ) { 48 if ( loggedIn_ ) {
45 qWarning( "openURL invoked when logged in\n" ); 49 owarn << "openURL invoked when logged in\n" << oendl;
46 return; 50 return;
47 } 51 }
48 52
49 QCString host = url.host().latin1(); 53 QCString host = url.host().latin1();
50 int display = url.port(); 54 int display = url.port();
51 55
52// connection_->connectTo( host, display ); 56// connection_->connectTo( host, display );
53} 57}
54 58
55void KRFBCanvas::closeConnection() 59void KRFBCanvas::closeConnection()
56{ 60{
57 loggedIn_ = false; 61 loggedIn_ = false;
58 connection_->disconnect(); 62 connection_->disconnect();
59 63
60 viewport()->setMouseTracking( false ); 64 viewport()->setMouseTracking( false );
61 viewport()->setBackgroundMode( PaletteDark ); 65 viewport()->setBackgroundMode( PaletteDark );
62 setBackgroundMode( PaletteDark ); 66 setBackgroundMode( PaletteDark );
63 update(); 67 update();
64} 68}
65 69
66 70
67void KRFBCanvas::bell() 71void KRFBCanvas::bell()
68{ 72{
69 if ( connection_->options()->deIconify ) { 73 if ( connection_->options()->deIconify ) {
70 topLevelWidget()->raise(); 74 topLevelWidget()->raise();
71 topLevelWidget()->show(); 75 topLevelWidget()->show();
72 } 76 }
73} 77}
74 78
75void KRFBCanvas::loggedIn() 79void KRFBCanvas::loggedIn()
76{ 80{
77 qWarning( "Ok, we're logged in" ); 81 owarn << "Ok, we're logged in" << oendl;
78 82
79 // 83 //
80 // Get ready for action 84 // Get ready for action
81 // 85 //
82 loggedIn_ = true; 86 loggedIn_ = true;
83 viewport()->setMouseTracking( true ); 87 viewport()->setMouseTracking( true );
84 viewport()->setBackgroundMode( NoBackground ); 88 viewport()->setBackgroundMode( NoBackground );
85 setBackgroundMode( NoBackground ); 89 setBackgroundMode( NoBackground );
86 90
87 // Start using the buffer 91 // Start using the buffer
88 connect( connection_->buffer(), SIGNAL( sizeChanged(int,int) ), 92 connect( connection_->buffer(), SIGNAL( sizeChanged(int,int) ),
89 this, SLOT( resizeContents(int,int) ) ); 93 this, SLOT( resizeContents(int,int) ) );
90 connect( connection_->buffer(), SIGNAL( updated(int,int,int,int) ), 94 connect( connection_->buffer(), SIGNAL( updated(int,int,int,int) ),
91 this, SLOT( viewportUpdate(int,int,int,int) ) ); 95 this, SLOT( viewportUpdate(int,int,int,int) ) );
92 connect( connection_->buffer(), SIGNAL( bell() ), 96 connect( connection_->buffer(), SIGNAL( bell() ),
93 this, SLOT( bell() ) ); 97 this, SLOT( bell() ) );
94 connect( qApp->clipboard(), SIGNAL( dataChanged() ), 98 connect( qApp->clipboard(), SIGNAL( dataChanged() ),
95 this, SLOT( clipboardChanged() ) ); 99 this, SLOT( clipboardChanged() ) );
96} 100}
97 101
98void KRFBCanvas::viewportPaintEvent( QPaintEvent *e ) 102void KRFBCanvas::viewportPaintEvent( QPaintEvent *e )
99{ 103{
100 QRect r = e->rect(); 104 QRect r = e->rect();
101 105
102 if ( loggedIn_ ) { 106 if ( loggedIn_ ) {
103 QPixmap p; 107 QPixmap p;
104 108
105 bitBlt( viewport(), r.x(), r.y(), 109 bitBlt( viewport(), r.x(), r.y(),
106 connection_->buffer()->pixmap(), 110 connection_->buffer()->pixmap(),
107 r.x() + contentsX(), r.y() + contentsY(), 111 r.x() + contentsX(), r.y() + contentsY(),
108 r.width(), r.height() ); 112 r.width(), r.height() );
109 } 113 }
110 else { 114 else {
111 QScrollView::viewportPaintEvent( e ); 115 QScrollView::viewportPaintEvent( e );
112 } 116 }
113} 117}
114 118
115void KRFBCanvas::viewportUpdate( int x, int y, int w, int h ) 119void KRFBCanvas::viewportUpdate( int x, int y, int w, int h )
116{ 120{
117 updateContents( x, y, w, h ); 121 updateContents( x, y, w, h );
118} 122}
119 123
120void KRFBCanvas::contentsMousePressEvent( QMouseEvent *e ) 124void KRFBCanvas::contentsMousePressEvent( QMouseEvent *e )
121{ 125{
122 126
123 if (nextDoubleClick) { 127 if (nextDoubleClick) {
124 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),LeftButton,LeftButton)); 128 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),LeftButton,LeftButton));
125 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0)); 129 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0));
126 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0)); 130 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0));
127 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton)); 131 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton));
128 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0)); 132 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0));
129 } if (nextRightClick) { 133 } if (nextRightClick) {
130 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),RightButton,RightButton)); 134 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),RightButton,RightButton));
131 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),RightButton,0)); 135 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),RightButton,0));
132 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton)); 136 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton));
133 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0)); 137 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0));
134 } else if ( loggedIn_ ) 138 } else if ( loggedIn_ )
135 connection_->buffer()->mouseEvent( e ); 139 connection_->buffer()->mouseEvent( e );
136 140
137} 141}
138 142
139void KRFBCanvas::contentsMouseReleaseEvent( QMouseEvent *e ) 143void KRFBCanvas::contentsMouseReleaseEvent( QMouseEvent *e )
140{ 144{
141 if ( loggedIn_ && !nextRightClick && !nextDoubleClick) { 145 if ( loggedIn_ && !nextRightClick && !nextDoubleClick) {
142 connection_->buffer()->mouseEvent( e ); 146 connection_->buffer()->mouseEvent( e );
143 } 147 }
144 148
145 nextRightClick=0; 149 nextRightClick=0;
146 nextDoubleClick=0; 150 nextDoubleClick=0;
147} 151}
148 152
149void KRFBCanvas::contentsMouseMoveEvent( QMouseEvent *e ) 153void KRFBCanvas::contentsMouseMoveEvent( QMouseEvent *e )
150{ 154{
151 if ( loggedIn_ ) 155 if ( loggedIn_ )
152 connection_->buffer()->mouseEvent( e ); 156 connection_->buffer()->mouseEvent( e );
153} 157}
154 158
155void KRFBCanvas::keyPressEvent( QKeyEvent *e ) 159void KRFBCanvas::keyPressEvent( QKeyEvent *e )
156{ 160{
157 if ( loggedIn_ ) 161 if ( loggedIn_ )
158 connection_->buffer()->keyPressEvent( e ); 162 connection_->buffer()->keyPressEvent( e );
159} 163}
160 164
161void KRFBCanvas::keyReleaseEvent( QKeyEvent *e ) 165void KRFBCanvas::keyReleaseEvent( QKeyEvent *e )
162{ 166{
163 if ( loggedIn_ ) 167 if ( loggedIn_ )
164 connection_->buffer()->keyReleaseEvent( e ); 168 connection_->buffer()->keyReleaseEvent( e );
165} 169}
166 170
167void KRFBCanvas::refresh() 171void KRFBCanvas::refresh()
168{ 172{
169 if ( loggedIn_ ) 173 if ( loggedIn_ )
170 connection_->refresh(); 174 connection_->refresh();
171} 175}
172 176
173void KRFBCanvas::clipboardChanged() 177void 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 @@
1#include <assert.h>
2#include <qsocket.h>
3#include <qtimer.h>
4#include <string.h>
5
6#include "krfbconnection.h" 1#include "krfbconnection.h"
7#include "krfblogin.h" 2#include "krfblogin.h"
8#include "krfbdecoder.h" 3#include "krfbdecoder.h"
9#include "krfbbuffer.h" 4#include "krfbbuffer.h"
10 5
6/* OPIE */
7#include <opie2/odebug.h>
8using namespace Opie::Core;
9
10/* QT */
11#include <qsocket.h>
12#include <qtimer.h>
13
14/* STD */
15#include <assert.h>
16#include <string.h>
17
11KRFBConnection::KRFBConnection( QObject *parent ) 18KRFBConnection::KRFBConnection( QObject *parent )
12 : QObject( parent, "KRFBConnection" ) 19 : QObject( parent, "KRFBConnection" )
13{ 20{
14 portBase_ = 5900; 21 portBase_ = 5900;
15 currentState_ = Disconnected; 22 currentState_ = Disconnected;
16 sock = 0; 23 sock = 0;
17 minData_ = 0; 24 minData_ = 0;
18 options_ = new KRFBServer(); 25 options_ = new KRFBServer();
19 updater = 0; 26 updater = 0;
20 decoder_ = 0; 27 decoder_ = 0;
21 buffer_ = 0; 28 buffer_ = 0;
22} 29}
23 30
24KRFBConnection::~KRFBConnection() 31KRFBConnection::~KRFBConnection()
25{ 32{
26 if ( ( currentState_ != Disconnected ) && ( currentState_ != Disconnecting ) && sock ) { 33 if ( ( currentState_ != Disconnected ) && ( currentState_ != Disconnecting ) && sock ) {
27 disconnectDone(); 34 disconnectDone();
28 } 35 }
29 delete options_; 36 delete options_;
30} 37}
31 38
32void KRFBConnection::connectTo( KRFBServer server) 39void KRFBConnection::connectTo( KRFBServer server)
33{ 40{
34 if ( currentState_ != Disconnected ) 41 if ( currentState_ != Disconnected )
35 disconnect(); 42 disconnect();
36 43
37 (*options_)=server; 44 (*options_)=server;
38 45
39 sock = new QSocket( this, "rfbSocket" ); 46 sock = new QSocket( this, "rfbSocket" );
40 CHECK_PTR( sock ); 47 CHECK_PTR( sock );
41 48
42 // Connect to something to notice connection or error 49 // Connect to something to notice connection or error
43 connect( sock, SIGNAL( error(int) ), SLOT( gotSocketError(int) ) ); 50 connect( sock, SIGNAL( error(int) ), SLOT( gotSocketError(int) ) );
44 connect( sock, SIGNAL( connected() ), SLOT( gotSocketConnection() ) ); 51 connect( sock, SIGNAL( connected() ), SLOT( gotSocketConnection() ) );
45 52
46 qWarning( "Connecting..." ); 53 owarn << "Connecting..." << oendl;
47 54
48 currentState_ = Connecting; 55 currentState_ = Connecting;
49 sock->connectToHost( options_->hostname.latin1(), portBase_ + options_->display ); 56 sock->connectToHost( options_->hostname.latin1(), portBase_ + options_->display );
50} 57}
51 58
52void KRFBConnection::disconnect() 59void KRFBConnection::disconnect()
53{ 60{
54 qWarning( "Disconnecting from server" ); 61 owarn << "Disconnecting from server" << oendl;
55 62
56 if ( ( currentState_ != Disconnected ) 63 if ( ( currentState_ != Disconnected )
57 && ( currentState_ != Disconnecting ) 64 && ( currentState_ != Disconnecting )
58 && sock ) { 65 && sock ) {
59 currentState_ = Disconnecting; 66 currentState_ = Disconnecting;
60 67
61 connect( sock, SIGNAL( delayedCloseFinished() ), SLOT( disconnectDone() ) ); 68 connect( sock, SIGNAL( delayedCloseFinished() ), SLOT( disconnectDone() ) );
62 sock->close(); 69 sock->close();
63 70
64 if ( sock->state() != QSocket::Closing ) 71 if ( sock->state() != QSocket::Closing )
65 disconnectDone(); 72 disconnectDone();
66 } 73 }
67} 74}
68 75
69void KRFBConnection::disconnectDone() 76void KRFBConnection::disconnectDone()
70{ 77{
71 currentState_ = Disconnected; 78 currentState_ = Disconnected;
72 delete sock; 79 delete sock;
73 sock = 0; 80 sock = 0;
74 minData_ = 0; 81 minData_ = 0;
75 delete updater; 82 delete updater;
76 delete decoder_; 83 delete decoder_;
77 delete buffer_; 84 delete buffer_;
78 emit disconnected(); 85 emit disconnected();
79} 86}
80 87
81void KRFBConnection::gotSocketConnection() 88void KRFBConnection::gotSocketConnection()
82{ 89{
83 currentState_ = LoggingIn; 90 currentState_ = LoggingIn;
84 91
85 qWarning( "Connected, logging in..." ); 92 owarn << "Connected, logging in..." << oendl;
86 93
87 static QString statusMsg = tr( "Connected" ); 94 static QString statusMsg = tr( "Connected" );
88 emit statusChanged( statusMsg ); 95 emit statusChanged( statusMsg );
89 96
90 // Do some login stuff 97 // Do some login stuff
91 login = new KRFBLogin( this ); 98 login = new KRFBLogin( this );
92} 99}
93 100
94void KRFBConnection::gotRFBConnection() 101void KRFBConnection::gotRFBConnection()
95{ 102{
96 qWarning( "Logged into server" ); 103 owarn << "Logged into server" << oendl;
97 104
98 currentState_ = Connected; 105 currentState_ = Connected;
99 emit connected(); 106 emit connected();
100 107
101 // Create the decoder and start doing stuff 108 // Create the decoder and start doing stuff
102 decoder_ = new KRFBDecoder( this ); 109 decoder_ = new KRFBDecoder( this );
103 CHECK_PTR( decoder_ ); 110 CHECK_PTR( decoder_ );
104 111
105 buffer_ = new KRFBBuffer( decoder_, this, "RFB Buffer" ); 112 buffer_ = new KRFBBuffer( decoder_, this, "RFB Buffer" );
106 CHECK_PTR( buffer_ ); 113 CHECK_PTR( buffer_ );
107 decoder_->setBuffer( buffer_ ); 114 decoder_->setBuffer( buffer_ );
108 115
109 connect( decoder_, SIGNAL( status(const QString&) ), 116 connect( decoder_, SIGNAL( status(const QString&) ),
110 this, SIGNAL( statusChanged(const QString&) ) ); 117 this, SIGNAL( statusChanged(const QString&) ) );
111 emit loggedIn(); 118 emit loggedIn();
112 119
113 decoder_->start(); 120 decoder_->start();
114 121
115 updater = new QTimer; 122 updater = new QTimer;
116 connect( updater, SIGNAL( timeout() ), SLOT( updateTimer() ) ); 123 connect( updater, SIGNAL( timeout() ), SLOT( updateTimer() ) );
117 updater->start( options_->updateRate ); 124 updater->start( options_->updateRate );
118} 125}
119 126
120void KRFBConnection::gotSocketError( int err ) 127void KRFBConnection::gotSocketError( int err )
121{ 128{
122 currentState_ = Error; 129 currentState_ = Error;
123 130
124 // Do some error handling stuff 131 // Do some error handling stuff
125 qWarning( "KRFBConnection: Socket error %d", err ); 132 owarn << "KRFBConnection: Socket error " << err << "" << oendl;
126 133
127 static QString refused = tr( "Connection Refused" ); 134 static QString refused = tr( "Connection Refused" );
128 static QString host = tr( "Host not found" ); 135 static QString host = tr( "Host not found" );
129 static QString read = tr( "Read Error: QSocket reported an error reading\n" 136 static QString read = tr( "Read Error: QSocket reported an error reading\n"
130 "data, the remote host has probably dropped the\n" 137 "data, the remote host has probably dropped the\n"
131 "connection." ); 138 "connection." );
132 static QString confused = tr( "QSocket reported an invalid error code" ); 139 static QString confused = tr( "QSocket reported an invalid error code" );
133 140
134 QString msg; 141 QString msg;
135 switch ( err ) { 142 switch ( err ) {
136 case QSocket::ErrConnectionRefused: 143 case QSocket::ErrConnectionRefused:
137 msg = refused; 144 msg = refused;
138 break; 145 break;
139 case QSocket::ErrHostNotFound: 146 case QSocket::ErrHostNotFound:
140 msg = host; 147 msg = host;
141 break; 148 break;
142 case QSocket::ErrSocketRead: 149 case QSocket::ErrSocketRead:
143 msg = read; 150 msg = read;
144 break; 151 break;
145 default: 152 default:
146 msg = confused; 153 msg = confused;
147 }; 154 };
148 155
149 QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) ); 156 QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) );
150 delete sock; 157 delete sock;
151 sock = 0; 158 sock = 0;
152 currentState_ = Disconnected; 159 currentState_ = Disconnected;
153 160
154 emit error( msg ); 161 emit error( msg );
155} 162}
156 163
157void KRFBConnection::gotMoreData() 164void KRFBConnection::gotMoreData()
158{ 165{
159 assert( minData_ > 0 ); 166 assert( minData_ > 0 );
160 167
161 if ( sock->size() >= minData_ ) { 168 if ( sock->size() >= minData_ ) {
162 minData_ = 0; 169 minData_ = 0;
163 QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) ); 170 QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) );
164 emit gotEnoughData(); 171 emit gotEnoughData();
165 } 172 }
166} 173}
167 174
168void KRFBConnection::waitForData( unsigned int sz ) 175void KRFBConnection::waitForData( unsigned int sz )
169{ 176{
170 assert( minData_ == 0 ); 177 assert( minData_ == 0 );
171 assert( sz > 0 ); 178 assert( sz > 0 );
172 assert( currentState_ != Error ); 179 assert( currentState_ != Error );
173 180
174 if ( sock->size() >= sz ) { 181 if ( sock->size() >= sz ) {
175 // qWarning( "No need to wait for data" ); 182 // owarn << "No need to wait for data" << oendl;
176 emit gotEnoughData(); 183 emit gotEnoughData();
177 } 184 }
178 else { 185 else {
179 // qWarning( "Waiting for %u bytes", sz ); 186 // owarn << "Waiting for " << sz << " bytes" << oendl;
180 minData_ = sz; 187 minData_ = sz;
181 connect( sock, SIGNAL( readyRead() ), SLOT( gotMoreData() ) ); 188 connect( sock, SIGNAL( readyRead() ), SLOT( gotMoreData() ) );
182 } 189 }
183} 190}
184 191
185int KRFBConnection::read( void *buf, int sz ) 192int KRFBConnection::read( void *buf, int sz )
186{ 193{
187 return sock->readBlock( (char *) buf, sz ); 194 return sock->readBlock( (char *) buf, sz );
188} 195}
189 196
190int KRFBConnection::write( void *buf, int sz ) 197int KRFBConnection::write( void *buf, int sz )
191{ 198{
192 return sock->writeBlock( (const char *) buf, sz ); 199 return sock->writeBlock( (const char *) buf, sz );
193} 200}
194 201
195KRFBConnection::State KRFBConnection::state() const 202KRFBConnection::State KRFBConnection::state() const
196{ 203{
197 return currentState_; 204 return currentState_;
198} 205}
199 206
200void KRFBConnection::setPortBase( int base ) 207void KRFBConnection::setPortBase( int base )
201{ 208{
202 portBase_ = base; 209 portBase_ = base;
203} 210}
204 211
205int KRFBConnection::portBase() const 212int KRFBConnection::portBase() const
206{ 213{
207 return portBase_; 214 return portBase_;
208} 215}
209 216
210void KRFBConnection::updateTimer() 217void KRFBConnection::updateTimer()
211{ 218{
212 decoder_->sendUpdateRequest( true ); 219 decoder_->sendUpdateRequest( true );
213} 220}
214 221
215void KRFBConnection::refresh() 222void KRFBConnection::refresh()
216{ 223{
217 decoder_->sendUpdateRequest( false ); 224 decoder_->sendUpdateRequest( false );
218} 225}
219 226
220void KRFBConnection::sendCutText( const QString &text ) 227void KRFBConnection::sendCutText( const QString &text )
221{ 228{
222 decoder_->sendCutEvent( text ); 229 decoder_->sendCutEvent( text );
223} 230}
224 231
225const QUrl &KRFBConnection::url() 232const QUrl &KRFBConnection::url()
226{ 233{
227 url_.setProtocol( "vnc" ); 234 url_.setProtocol( "vnc" );
228 url_.setPort( display() ); 235 url_.setPort( display() );
229 url_.setHost( host() ); 236 url_.setHost( host() );
230 url_.setPath( "/" ); 237 url_.setPath( "/" );
231 238
232 return url_; 239 return url_;
233} 240}
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 @@
1#include "krfbconnection.h" 1#include "krfbconnection.h"
2#include "krfbserverinfo.h" 2#include "krfbserverinfo.h"
3#include "krfbdecoder.h" 3#include "krfbdecoder.h"
4#include "krfbbuffer.h" 4#include "krfbbuffer.h"
5 5
6/* OPIE */
7#include <opie2/odebug.h>
8using namespace Opie::Core;
6 9
10/* QT */
7#include <qpixmap.h> 11#include <qpixmap.h>
8 12
13/* STD */
9#include <assert.h> 14#include <assert.h>
10 15
11// 16//
12// Endian stuff 17// Endian stuff
13// 18//
14#ifndef KDE_USE_FINAL 19#ifndef OPIE_NO_DEBUG
15const int endianTest = 1; 20const int endianTest = 1;
16#endif 21#endif
17 22
18#define Swap16IfLE(s) \ 23#define Swap16IfLE(s) \
19 (*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s)) 24 (*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s))
20 25
21#define Swap32IfLE(l) \ 26#define Swap32IfLE(l) \
22 (*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \ 27 (*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \
23 (((l) & 0x00ff0000) >> 8) | \ 28 (((l) & 0x00ff0000) >> 8) | \
24 (((l) & 0x0000ff00) << 8) | \ 29 (((l) & 0x0000ff00) << 8) | \
25 (((l) & 0x000000ff) << 24)) : (l)) 30 (((l) & 0x000000ff) << 24)) : (l))
26 31
27// 32//
28// The lengths of the messages we need to wait for 33// The lengths of the messages we need to wait for
29// 34//
30const int ServerInitLength = 24; 35const int ServerInitLength = 24;
31const int UpdateHeaderLength = 4; 36const int UpdateHeaderLength = 4;
32const int RectHeaderLength = 12; 37const int RectHeaderLength = 12;
33const int RectChunkSize = 4; 38const int RectChunkSize = 4;
34const int CopyRectPosLength = 4; 39const int CopyRectPosLength = 4;
35const int ServerCutLenLength = 7; 40const int ServerCutLenLength = 7;
36 41
37// 42//
38// Client -> Server Message Identifiers 43// Client -> Server Message Identifiers
39// 44//
40static CARD8 SetPixelFormatId = 0; 45static CARD8 SetPixelFormatId = 0;
41//static CARD8 FixColourMapEntriesId = 1; // Not used 46//static CARD8 FixColourMapEntriesId = 1; // Not used
42static CARD8 SetEncodingsId = 2; 47static CARD8 SetEncodingsId = 2;
43static CARD8 UpdateRequestId = 3; 48static CARD8 UpdateRequestId = 3;
44static CARD8 KeyEventId = 4; 49static CARD8 KeyEventId = 4;
45static CARD8 PointerEventId = 5; 50static CARD8 PointerEventId = 5;
46static CARD8 ClientCutTextId = 6; 51static CARD8 ClientCutTextId = 6;
47 52
48// 53//
49// Server -> Client Message Identifiers 54// Server -> Client Message Identifiers
50// 55//
51static CARD8 UpdateId = 0; 56static CARD8 UpdateId = 0;
52static CARD8 BellId = 2; 57static CARD8 BellId = 2;
53static CARD8 ServerCutId = 3; 58static CARD8 ServerCutId = 3;
54 59
55// 60//
56// Encoding identifiers 61// Encoding identifiers
57// 62//
58static CARD32 RawEncoding = Swap32IfLE( 0 ); 63static CARD32 RawEncoding = Swap32IfLE( 0 );
59static CARD32 CopyRectEncoding = Swap32IfLE(1 ); 64static CARD32 CopyRectEncoding = Swap32IfLE(1 );
60static CARD32 RreEncoding = Swap32IfLE( 2 ); 65static CARD32 RreEncoding = Swap32IfLE( 2 );
61static CARD32 CorreEncoding = Swap32IfLE( 4 ); 66static CARD32 CorreEncoding = Swap32IfLE( 4 );
62static CARD32 HexTileEncoding = Swap32IfLE( 5 ); 67static CARD32 HexTileEncoding = Swap32IfLE( 5 );
63 68
64static struct { 69static struct {
65 int keysym; 70 int keysym;
66 int keycode; 71 int keycode;
67} keyMap[] = { 72} keyMap[] = {
68 { 0xff08, Qt::Key_Backspace }, 73 { 0xff08, Qt::Key_Backspace },
69 { 0xff09, Qt::Key_Tab }, 74 { 0xff09, Qt::Key_Tab },
70 { 0xff0d, Qt::Key_Return }, 75 { 0xff0d, Qt::Key_Return },
71 { 0xff1b, Qt::Key_Escape }, 76 { 0xff1b, Qt::Key_Escape },
72 { 0xff63, Qt::Key_Insert }, 77 { 0xff63, Qt::Key_Insert },
73 { 0xffff, Qt::Key_Delete }, 78 { 0xffff, Qt::Key_Delete },
74 { 0xff50, Qt::Key_Home }, 79 { 0xff50, Qt::Key_Home },
75 { 0xff57, Qt::Key_End }, 80 { 0xff57, Qt::Key_End },
76 { 0xff55, Qt::Key_Prior }, 81 { 0xff55, Qt::Key_Prior },
77 { 0xff56, Qt::Key_Next }, 82 { 0xff56, Qt::Key_Next },
78 { 0xff51, Qt::Key_Left }, 83 { 0xff51, Qt::Key_Left },
79 { 0xff52, Qt::Key_Up }, 84 { 0xff52, Qt::Key_Up },
80 { 0xff53, Qt::Key_Right }, 85 { 0xff53, Qt::Key_Right },
81 { 0xff54, Qt::Key_Down }, 86 { 0xff54, Qt::Key_Down },
82 { 0xffbe, Qt::Key_F1 }, 87 { 0xffbe, Qt::Key_F1 },
83 { 0xffbf, Qt::Key_F2 }, 88 { 0xffbf, Qt::Key_F2 },
84 { 0xffc0, Qt::Key_F3 }, 89 { 0xffc0, Qt::Key_F3 },
85 { 0xffc1, Qt::Key_F4 }, 90 { 0xffc1, Qt::Key_F4 },
86 { 0xffc2, Qt::Key_F5 }, 91 { 0xffc2, Qt::Key_F5 },
87 { 0xffc3, Qt::Key_F6 }, 92 { 0xffc3, Qt::Key_F6 },
88 { 0xffc4, Qt::Key_F7 }, 93 { 0xffc4, Qt::Key_F7 },
89 { 0xffc5, Qt::Key_F8 }, 94 { 0xffc5, Qt::Key_F8 },
90 { 0xffc6, Qt::Key_F9 }, 95 { 0xffc6, Qt::Key_F9 },
91 { 0xffc7, Qt::Key_F10 }, 96 { 0xffc7, Qt::Key_F10 },
92 { 0xffc8, Qt::Key_F11 }, 97 { 0xffc8, Qt::Key_F11 },
93 { 0xffc9, Qt::Key_F12 }, 98 { 0xffc9, Qt::Key_F12 },
94 { 0xffe1, Qt::Key_Shift }, 99 { 0xffe1, Qt::Key_Shift },
95 { 0xffe2, Qt::Key_Shift }, 100 { 0xffe2, Qt::Key_Shift },
96 { 0xffe3, Qt::Key_Control }, 101 { 0xffe3, Qt::Key_Control },
97 { 0xffe4, Qt::Key_Control }, 102 { 0xffe4, Qt::Key_Control },
98 { 0xffe7, Qt::Key_Meta }, 103 { 0xffe7, Qt::Key_Meta },
99 { 0xffe8, Qt::Key_Meta }, 104 { 0xffe8, Qt::Key_Meta },
100 { 0xffe9, Qt::Key_Alt }, 105 { 0xffe9, Qt::Key_Alt },
101 { 0xffea, Qt::Key_Alt }, 106 { 0xffea, Qt::Key_Alt },
102 { 0, 0 } 107 { 0, 0 }
103}; 108};
104 109
105 110
106KRFBDecoder::KRFBDecoder( KRFBConnection *con ) 111KRFBDecoder::KRFBDecoder( KRFBConnection *con )
107 : QObject( con, "RFB Decoder" ) 112 : QObject( con, "RFB Decoder" )
108{ 113{
109 assert( con ); 114 assert( con );
110 assert( con->state() == KRFBConnection::Connected ); 115 assert( con->state() == KRFBConnection::Connected );
111 116
112 this->con = con; 117 this->con = con;
113 this->buf = 0; 118 this->buf = 0;
114 this->info = 0; 119 this->info = 0;
115 this->format = 0; 120 this->format = 0;
116 this->buttonMask = 0; 121 this->buttonMask = 0;
117 currentState = Idle; 122 currentState = Idle;
118} 123}
119 124
120KRFBDecoder::~KRFBDecoder() 125KRFBDecoder::~KRFBDecoder()
121{ 126{
122 if ( info ) 127 if ( info )
123 delete info; 128 delete info;
124 if ( format ) 129 if ( format )
125 delete format; 130 delete format;
126} 131}
127 132
128void KRFBDecoder::start() 133void KRFBDecoder::start()
129{ 134{
130 sendClientInit(); 135 sendClientInit();
131} 136}
132 137
133void KRFBDecoder::sendClientInit() 138void KRFBDecoder::sendClientInit()
134{ 139{
135 con->write( &( con->options()->shared ), 1 ); 140 con->write( &( con->options()->shared ), 1 );
136 141
137 // Wait for server init 142 // Wait for server init
138 qWarning( "Waiting for server init" ); 143 owarn << "Waiting for server init" << oendl;
139 144
140 static QString statusMsg = tr( "Waiting for server initialization..." ); 145 static QString statusMsg = tr( "Waiting for server initialization..." );
141 emit status( statusMsg ); 146 emit status( statusMsg );
142 147
143 currentState = AwaitingServerInit; 148 currentState = AwaitingServerInit;
144 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerInit() ) ); 149 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerInit() ) );
145 con->waitForData( ServerInitLength ); 150 con->waitForData( ServerInitLength );
146} 151}
147 152
148void KRFBDecoder::gotServerInit() 153void KRFBDecoder::gotServerInit()
149{ 154{
150 qWarning( "Got server init" ); 155 owarn << "Got server init" << oendl;
151 disconnect( con, SIGNAL( gotEnoughData() ), this, SLOT( gotServerInit() ) ); 156 disconnect( con, SIGNAL( gotEnoughData() ), this, SLOT( gotServerInit() ) );
152 157
153 if ( info ) 158 if ( info )
154 delete info; 159 delete info;
155 info = new KRFBServerInfo; 160 info = new KRFBServerInfo;
156 CHECK_PTR( info ); 161 CHECK_PTR( info );
157 162
158 con->read( &(info->width), 2 ); 163 con->read( &(info->width), 2 );
159 info->width = Swap16IfLE( info->width ); 164 info->width = Swap16IfLE( info->width );
160 con->read( &info->height, 2 ); 165 con->read( &info->height, 2 );
161 info->height = Swap16IfLE( info->height ); 166 info->height = Swap16IfLE( info->height );
162 167
163 con->read( &(info->bpp), 1 ); 168 con->read( &(info->bpp), 1 );
164 con->read( &(info->depth), 1 ); 169 con->read( &(info->depth), 1 );
165 con->read( &(info->bigEndian), 1 ); 170 con->read( &(info->bigEndian), 1 );
166 con->read( &(info->trueColor), 1 ); 171 con->read( &(info->trueColor), 1 );
167 172
168 con->read( &(info->redMax), 2 ); 173 con->read( &(info->redMax), 2 );
169 info->redMax = Swap16IfLE( info->redMax ); 174 info->redMax = Swap16IfLE( info->redMax );
170 con->read( &(info->greenMax), 2 ); 175 con->read( &(info->greenMax), 2 );
171 info->greenMax = Swap16IfLE( info->greenMax ); 176 info->greenMax = Swap16IfLE( info->greenMax );
172 con->read( &(info->blueMax), 2 ); 177 con->read( &(info->blueMax), 2 );
173 info->blueMax = Swap16IfLE( info->blueMax ); 178 info->blueMax = Swap16IfLE( info->blueMax );
174 179
175 con->read( &(info->redShift), 1 ); 180 con->read( &(info->redShift), 1 );
176 con->read( &(info->greenShift), 1 ); 181 con->read( &(info->greenShift), 1 );
177 con->read( &(info->blueShift), 1 ); 182 con->read( &(info->blueShift), 1 );
178 183
179 con->read( info->padding, 3 ); 184 con->read( info->padding, 3 );
180 185
181 con->read( &(info->nameLength), 4 ); 186 con->read( &(info->nameLength), 4 );
182 info->nameLength = Swap32IfLE( info->nameLength ); 187 info->nameLength = Swap32IfLE( info->nameLength );
183 188
184 qWarning( "Width = %d, Height = %d", info->width, info->height ); 189 owarn << "Width = " << info->width << ", Height = " << info->height << "" << oendl;
185 qWarning( "Bpp = %d, Depth = %d, Big = %d, True = %d", 190 qWarning( "Bpp = %d, Depth = %d, Big = %d, True = %d",
186 info->bpp, info->depth, info->bigEndian, info->trueColor ); 191 info->bpp, info->depth, info->bigEndian, info->trueColor );
187 qWarning( "RedMax = %d, GreenMax = %d, BlueMax = %d", 192 qWarning( "RedMax = %d, GreenMax = %d, BlueMax = %d",
188 info->redMax, info->greenMax, info->blueMax ); 193 info->redMax, info->greenMax, info->blueMax );
189 qWarning( "RedShift = %d, GreenShift = %d, BlueShift = %d", 194 qWarning( "RedShift = %d, GreenShift = %d, BlueShift = %d",
190 info->redShift, info->greenShift,info-> blueShift ); 195 info->redShift, info->greenShift,info-> blueShift );
191 196
192 buf->resize( info->width/con->options()->scaleFactor, info->height /con->options()->scaleFactor); 197 buf->resize( info->width/con->options()->scaleFactor, info->height /con->options()->scaleFactor);
193 198
194 // Wait for desktop name 199 // Wait for desktop name
195 qWarning( "Waiting for desktop name" ); 200 owarn << "Waiting for desktop name" << oendl;
196 201
197 static QString statusMsg = tr( "Waiting for desktop name..." ); 202 static QString statusMsg = tr( "Waiting for desktop name..." );
198 emit status( statusMsg ); 203 emit status( statusMsg );
199 204
200 currentState = AwaitingDesktopName; 205 currentState = AwaitingDesktopName;
201 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotDesktopName() ) ); 206 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotDesktopName() ) );
202 con->waitForData( info->nameLength ); 207 con->waitForData( info->nameLength );
203} 208}
204 209
205void KRFBDecoder::gotDesktopName() 210void KRFBDecoder::gotDesktopName()
206{ 211{
207 assert( info ); 212 assert( info );
208 assert( currentState == AwaitingDesktopName ); 213 assert( currentState == AwaitingDesktopName );
209 214
210 qWarning( "Got desktop name" ); 215 owarn << "Got desktop name" << oendl;
211 216
212 disconnect( con, SIGNAL( gotEnoughData() ), 217 disconnect( con, SIGNAL( gotEnoughData() ),
213 this, SLOT( gotDesktopName() ) ); 218 this, SLOT( gotDesktopName() ) );
214 219
215 char *buf = new char[ info->nameLength + 1 ]; 220 char *buf = new char[ info->nameLength + 1 ];
216 CHECK_PTR( buf ); 221 CHECK_PTR( buf );
217 222
218 con->read( buf, info->nameLength ); 223 con->read( buf, info->nameLength );
219 buf[ info->nameLength ] = '\0'; 224 buf[ info->nameLength ] = '\0';
220 info->name = buf; 225 info->name = buf;
221 226
222 qWarning( "Desktop: %s", info->name.latin1() ); 227 owarn << "Desktop: " << info->name.latin1() << "" << oendl;
223 228
224 delete buf; 229 delete buf;
225 230
226 // Get the format we'll really use and tell the server 231 // Get the format we'll really use and tell the server
227 decidePixelFormat(); 232 decidePixelFormat();
228 sendPixelFormat(); 233 sendPixelFormat();
229 sendAllowedEncodings(); 234 sendAllowedEncodings();
230 currentState = Idle; 235 currentState = Idle;
231 236
232 QString msg; 237 QString msg;
233 msg = tr( "Connected to %1" ); 238 msg = tr( "Connected to %1" );
234 msg = msg.arg( info->name ); 239 msg = msg.arg( info->name );
235 emit status( msg ); 240 emit status( msg );
236 241
237 sendUpdateRequest( false ); 242 sendUpdateRequest( false );
238} 243}
239 244
240void KRFBDecoder::decidePixelFormat() 245void KRFBDecoder::decidePixelFormat()
241{ 246{
242 assert( info ); 247 assert( info );
243 248
244 if ( format ) 249 if ( format )
245 delete format; 250 delete format;
246 format = new KRFBPixelFormat; 251 format = new KRFBPixelFormat;
247 CHECK_PTR( format ); 252 CHECK_PTR( format );
248 253
249 // What depth do we want? 254 // What depth do we want?
250 // 255 //
251 // We'll use the minimum of the remote and local depths, UNLESS an 256 // We'll use the minimum of the remote and local depths, UNLESS an
252 // eight bit session has been specifically requested by the user. 257 // eight bit session has been specifically requested by the user.
253 int screenDepth = QPixmap::defaultDepth(); 258 int screenDepth = QPixmap::defaultDepth();
254 int bestDepth = ( screenDepth > info->depth ) ? info->depth : screenDepth; 259 int bestDepth = ( screenDepth > info->depth ) ? info->depth : screenDepth;
255 int chosenDepth; 260 int chosenDepth;
256 261
257 if ( con->options()->colors256 ) 262 if ( con->options()->colors256 )
258 chosenDepth = 8; 263 chosenDepth = 8;
259 else 264 else
260 chosenDepth = bestDepth; 265 chosenDepth = bestDepth;
261 266
262 qWarning( "Screen depth=%d, server depth=%d, best depth=%d, " \ 267 qWarning( "Screen depth=%d, server depth=%d, best depth=%d, " \
263 "eight bit %d, chosenDepth=%d", 268 "eight bit %d, chosenDepth=%d",
264 screenDepth, 269 screenDepth,
265 info->depth, 270 info->depth,
266 bestDepth, 271 bestDepth,
267 con->options()->colors256, chosenDepth ); 272 con->options()->colors256, chosenDepth );
268 273
269 format->depth = chosenDepth; 274 format->depth = chosenDepth;
270 275
271 // If we're using the servers native depth 276 // If we're using the servers native depth
272 if ( chosenDepth == info->depth ) { 277 if ( chosenDepth == info->depth ) {
273 // Use the servers native format 278 // Use the servers native format
274 format->bpp = info->bpp; 279 format->bpp = info->bpp;
275 // format->bigEndian = info->bigEndian; 280 // format->bigEndian = info->bigEndian;
276 format->bigEndian = true; 281 format->bigEndian = true;
277 format->trueColor = info->trueColor; 282 format->trueColor = info->trueColor;
278 format->redMax = info->redMax; 283 format->redMax = info->redMax;
279 format->greenMax = info->greenMax; 284 format->greenMax = info->greenMax;
280 format->blueMax = info->blueMax; 285 format->blueMax = info->blueMax;
281 format->redShift = info->redShift; 286 format->redShift = info->redShift;
282 format->greenShift = info->greenShift; 287 format->greenShift = info->greenShift;
283 format->blueShift = info->blueShift; 288 format->blueShift = info->blueShift;
284 } 289 }
285 else { 290 else {
286 if ( chosenDepth == 8 ) { 291 if ( chosenDepth == 8 ) {
287 format->bpp = 8; 292 format->bpp = 8;
288 format->bigEndian = true; 293 format->bigEndian = true;
289 format->trueColor = true; 294 format->trueColor = true;
290 format->redMax = 7; 295 format->redMax = 7;
291 format->greenMax = 7; 296 format->greenMax = 7;
292 format->blueMax = 3; 297 format->blueMax = 3;
293 format->redShift = 0; 298 format->redShift = 0;
294 format->greenShift = 3; 299 format->greenShift = 3;
295 format->blueShift = 6; 300 format->blueShift = 6;
296 } 301 }
297 } 302 }
298 303
299 format->redMax = Swap16IfLE( format->redMax ); 304 format->redMax = Swap16IfLE( format->redMax );
300 format->greenMax = Swap16IfLE( format->greenMax ); 305 format->greenMax = Swap16IfLE( format->greenMax );
301 format->blueMax = Swap16IfLE( format->blueMax ); 306 format->blueMax = Swap16IfLE( format->blueMax );
302} 307}
303 308
304void KRFBDecoder::sendPixelFormat() 309void KRFBDecoder::sendPixelFormat()
305{ 310{
306 static char padding[3]; 311 static char padding[3];
307 con->write( &SetPixelFormatId, 1 ); 312 con->write( &SetPixelFormatId, 1 );
308 con->write( padding, 3 ); 313 con->write( padding, 3 );
309 314
310 con->write( &(format->bpp), 1 ); 315 con->write( &(format->bpp), 1 );
311 con->write( &(format->depth), 1 ); 316 con->write( &(format->depth), 1 );
312 con->write( &(format->bigEndian), 1 ); 317 con->write( &(format->bigEndian), 1 );
313 con->write( &(format->trueColor), 1 ); 318 con->write( &(format->trueColor), 1 );
314 319
315 con->write( &(format->redMax), 2 ); 320 con->write( &(format->redMax), 2 );
316 con->write( &(format->greenMax), 2 ); 321 con->write( &(format->greenMax), 2 );
317 con->write( &(format->blueMax), 2 ); 322 con->write( &(format->blueMax), 2 );
318 323
319 con->write( &(format->redShift), 1 ); 324 con->write( &(format->redShift), 1 );
320 con->write( &(format->greenShift), 1 ); 325 con->write( &(format->greenShift), 1 );
321 con->write( &(format->blueShift), 1 ); 326 con->write( &(format->blueShift), 1 );
322 con->write( format->padding, 3 ); // Padding 327 con->write( format->padding, 3 ); // Padding
323} 328}
324 329
325void KRFBDecoder::sendAllowedEncodings() 330void KRFBDecoder::sendAllowedEncodings()
326{ 331{
327 static CARD8 padding[1]; 332 static CARD8 padding[1];
328 con->write( &SetEncodingsId, 1 ); 333 con->write( &SetEncodingsId, 1 );
329 con->write( padding, 1 ); 334 con->write( padding, 1 );
330 335
331 CARD16 noEncodings = con->options()->encodings(); 336 CARD16 noEncodings = con->options()->encodings();
332 noEncodings = Swap16IfLE( noEncodings ); 337 noEncodings = Swap16IfLE( noEncodings );
333 con->write( &noEncodings, 2 ); 338 con->write( &noEncodings, 2 );
334 339
335 if ( con->options()->corre ) 340 if ( con->options()->corre )
336 con->write( &CorreEncoding, 4 ); 341 con->write( &CorreEncoding, 4 );
337 if ( con->options()->hexTile ) 342 if ( con->options()->hexTile )
338 con->write( &HexTileEncoding, 4 ); 343 con->write( &HexTileEncoding, 4 );
339 if ( con->options()->rre ) 344 if ( con->options()->rre )
340 con->write( &RreEncoding, 4 ); 345 con->write( &RreEncoding, 4 );
341 if ( con->options()->copyrect ) 346 if ( con->options()->copyrect )
342 con->write( &CopyRectEncoding, 4 ); 347 con->write( &CopyRectEncoding, 4 );
343 // We always support this 348 // We always support this
344 con->write( &RawEncoding, 4 ); 349 con->write( &RawEncoding, 4 );
345} 350}
346 351
347void KRFBDecoder::sendUpdateRequest( bool incremental ) 352void KRFBDecoder::sendUpdateRequest( bool incremental )
348{ 353{
349 if ( currentState != Idle ) 354 if ( currentState != Idle )
350 return; 355 return;
351 356
352 con->write( &UpdateRequestId, 1 ); 357 con->write( &UpdateRequestId, 1 );
353 con->write( &incremental, 1 ); 358 con->write( &incremental, 1 );
354 359
355 static CARD16 x = 0, y = 0; 360 static CARD16 x = 0, y = 0;
356 static CARD16 w = Swap16IfLE( info->width ); 361 static CARD16 w = Swap16IfLE( info->width );
357 static CARD16 h = Swap16IfLE( info->height ); 362 static CARD16 h = Swap16IfLE( info->height );
358 363
359 con->write( &x, 2 ); 364 con->write( &x, 2 );
360 con->write( &y, 2 ); 365 con->write( &y, 2 );
361 con->write( &w, 2 ); 366 con->write( &w, 2 );
362 con->write( &h, 2 ); 367 con->write( &h, 2 );
363 368
364 // Now wait for the update 369 // Now wait for the update
365 currentState = AwaitingUpdate; 370 currentState = AwaitingUpdate;
366 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) ); 371 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) );
367 con->waitForData( UpdateHeaderLength ); 372 con->waitForData( UpdateHeaderLength );
368} 373}
369 374
370void KRFBDecoder::gotUpdateHeader() 375void KRFBDecoder::gotUpdateHeader()
371{ 376{
372 assert( currentState == AwaitingUpdate ); 377 assert( currentState == AwaitingUpdate );
373 378
374 // qWarning( "Got update header" ); 379 // owarn << "Got update header" << oendl;
375 380
376 disconnect( con, SIGNAL( gotEnoughData() ), 381 disconnect( con, SIGNAL( gotEnoughData() ),
377 this, SLOT( gotUpdateHeader() ) ); 382 this, SLOT( gotUpdateHeader() ) );
378 383
379 CARD8 msgType; 384 CARD8 msgType;
380 con->read( &msgType, 1 ); 385 con->read( &msgType, 1 );
381 386
382 if ( msgType != UpdateId ) { 387 if ( msgType != UpdateId ) {
383 // We might have a bell or server cut 388 // We might have a bell or server cut
384 if ( msgType == ServerCutId ) { 389 if ( msgType == ServerCutId ) {
385 oldState = currentState; 390 oldState = currentState;
386 gotServerCut(); 391 gotServerCut();
387 } 392 }
388 else if ( msgType == BellId ) { 393 else if ( msgType == BellId ) {
389 oldState = currentState; 394 oldState = currentState;
390 gotBell(); 395 gotBell();
391 } 396 }
392 else { 397 else {
393 int msg = msgType; 398 int msg = msgType;
394 QString protocolError = tr( "Protocol Error: Message Id %1 was " 399 QString protocolError = tr( "Protocol Error: Message Id %1 was "
395 "found when expecting an update " 400 "found when expecting an update "
396 "message." ).arg( msg ); 401 "message." ).arg( msg );
397 currentState = Error; 402 currentState = Error;
398 emit error( protocolError ); 403 emit error( protocolError );
399 } 404 }
400 return; 405 return;
401 } 406 }
402 407
403 CARD8 padding; 408 CARD8 padding;
404 con->read( &padding, 1 ); 409 con->read( &padding, 1 );
405 410
406 con->read( &noRects, 2 ); 411 con->read( &noRects, 2 );
407 noRects = Swap16IfLE( noRects ); 412 noRects = Swap16IfLE( noRects );
408 413
409 // qWarning( "Expecting %d rects", noRects ); 414 // owarn << "Expecting " << noRects << " rects" << oendl;
410 415
411 // Now wait for the data 416 // Now wait for the data
412 currentState = AwaitingRectHeader; 417 currentState = AwaitingRectHeader;
413 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) ); 418 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) );
414 con->waitForData( RectHeaderLength ); 419 con->waitForData( RectHeaderLength );
415} 420}
416 421
417void KRFBDecoder::gotRectHeader() 422void KRFBDecoder::gotRectHeader()
418{ 423{
419 assert( currentState == AwaitingRectHeader ); 424 assert( currentState == AwaitingRectHeader );
420 425
421 // qWarning( "Got rect header" ); 426 // owarn << "Got rect header" << oendl;
422 427
423 disconnect( con, SIGNAL( gotEnoughData() ), 428 disconnect( con, SIGNAL( gotEnoughData() ),
424 this, SLOT( gotRectHeader() ) ); 429 this, SLOT( gotRectHeader() ) );
425 430
426 con->read( &x, 2 ); 431 con->read( &x, 2 );
427 x = Swap16IfLE( x ); 432 x = Swap16IfLE( x );
428 con->read( &y, 2 ); 433 con->read( &y, 2 );
429 y = Swap16IfLE( y ); 434 y = Swap16IfLE( y );
430 435
431 con->read( &w, 2 ); 436 con->read( &w, 2 );
432 w = Swap16IfLE( w ); 437 w = Swap16IfLE( w );
433 con->read( &h, 2 ); 438 con->read( &h, 2 );
434 h = Swap16IfLE( h ); 439 h = Swap16IfLE( h );
435 440
436 con->read( &encoding, 4 ); 441 con->read( &encoding, 4 );
437 442
438 // CARD32 encodingLocal = Swap32IfLE( encoding ); 443 // CARD32 encodingLocal = Swap32IfLE( encoding );
439 // qWarning( "Rect: x=%d, y= %d, w=%d, h=%d, encoding=%ld", 444 // qWarning( "Rect: x=%d, y= %d, w=%d, h=%d, encoding=%ld",
440 // x, y, w, h, encodingLocal ); 445 // x, y, w, h, encodingLocal );
441 446
442 // 447 //
443 // Each encoding needs to be handled differently. Some require 448 // Each encoding needs to be handled differently. Some require
444 // waiting for more data, but others like a copyrect do not. 449 // waiting for more data, but others like a copyrect do not.
445 // Our constants have already been byte swapped, so we use 450 // Our constants have already been byte swapped, so we use
446 // the remote value as is. 451 // the remote value as is.
447 // 452 //
448 if ( encoding == RawEncoding ) { 453 if ( encoding == RawEncoding ) {
449 // qWarning( "Raw encoding" ); 454 // owarn << "Raw encoding" << oendl;
450 handleRawRect(); 455 handleRawRect();
451 } 456 }
452 else if ( encoding == CopyRectEncoding ) { 457 else if ( encoding == CopyRectEncoding ) {
453// qWarning( "CopyRect encoding" ); 458// owarn << "CopyRect encoding" << oendl;
454 handleCopyRect(); 459 handleCopyRect();
455 } 460 }
456 else if ( encoding == RreEncoding ) { 461 else if ( encoding == RreEncoding ) {
457 qWarning( "RRE encoding" ); 462 owarn << "RRE encoding" << oendl;
458 handleRRERect(); 463 handleRRERect();
459 } 464 }
460 else if ( encoding == CorreEncoding ) { 465 else if ( encoding == CorreEncoding ) {
461 qWarning( "CoRRE encoding" ); 466 owarn << "CoRRE encoding" << oendl;
462 handleCoRRERect(); 467 handleCoRRERect();
463 } 468 }
464 else if ( encoding == HexTileEncoding ) { 469 else if ( encoding == HexTileEncoding ) {
465 qWarning( "HexTile encoding" ); 470 owarn << "HexTile encoding" << oendl;
466 handleHexTileRect(); 471 handleHexTileRect();
467 } 472 }
468 else { 473 else {
469 int msg = Swap32IfLE( encoding ); 474 int msg = Swap32IfLE( encoding );
470 QString protocolError = tr( "Protocol Error: An unknown encoding was " 475 QString protocolError = tr( "Protocol Error: An unknown encoding was "
471 "used by the server %1" ).arg( msg ); 476 "used by the server %1" ).arg( msg );
472 currentState = Error; 477 currentState = Error;
473 qWarning( "Unknown encoding, %d", msg ); 478 owarn << "Unknown encoding, " << msg << "" << oendl;
474 emit error( protocolError ); 479 emit error( protocolError );
475 return; 480 return;
476 } 481 }
477} 482}
478 483
479// 484//
480// Raw Encoding 485// Raw Encoding
481// 486//
482 487
483void KRFBDecoder::handleRawRect() 488void KRFBDecoder::handleRawRect()
484{ 489{
485 // We need something a bit cleverer here to handle large 490 // We need something a bit cleverer here to handle large
486 // rectanges nicely. The chunking should be based on the 491 // rectanges nicely. The chunking should be based on the
487 // overall size (but has to be in complete lines). 492 // overall size (but has to be in complete lines).
488 493
489 // qWarning( "Handling a raw rect chunk" ); 494 // owarn << "Handling a raw rect chunk" << oendl;
490 495
491 // CARD32 lineCount = w * format->bpp / 8; 496 // CARD32 lineCount = w * format->bpp / 8;
492 497
493 if ( h > RectChunkSize ) { 498 if ( h > RectChunkSize ) {
494 // if ( con->sock->size() / lineCount ) { 499 // if ( con->sock->size() / lineCount ) {
495 // getRawRectChunk( con->sock->size() / lineCount ); 500 // getRawRectChunk( con->sock->size() / lineCount );
496 // } 501 // }
497 // else { 502 // else {
498 getRawRectChunk( RectChunkSize ); 503 getRawRectChunk( RectChunkSize );
499 // } 504 // }
500 } 505 }
501 else { 506 else {
502 getRawRectChunk( h ); 507 getRawRectChunk( h );
503 } 508 }
504} 509}
505 510
506void KRFBDecoder::getRawRectChunk( int lines ) 511void KRFBDecoder::getRawRectChunk( int lines )
507{ 512{
508 this->lines = lines; 513 this->lines = lines;
509 CARD32 count = lines * w * format->bpp / 8; 514 CARD32 count = lines * w * format->bpp / 8;
510 515
511 // Wait for server init 516 // Wait for server init
512 // qWarning( "Waiting for raw rect chunk, %ld", count ); 517 // owarn << "Waiting for raw rect chunk, " << count << "" << oendl;
513 518
514 currentState = AwaitingRawRectChunk; 519 currentState = AwaitingRawRectChunk;
515 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRawRectChunk() ) ); 520 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRawRectChunk() ) );
516 con->waitForData( count ); 521 con->waitForData( count );
517} 522}
518 523
519void KRFBDecoder::gotRawRectChunk() 524void KRFBDecoder::gotRawRectChunk()
520{ 525{
521 assert( currentState == AwaitingRawRectChunk ); 526 assert( currentState == AwaitingRawRectChunk );
522 527
523 disconnect( con, SIGNAL( gotEnoughData() ), 528 disconnect( con, SIGNAL( gotEnoughData() ),
524 this, SLOT( gotRawRectChunk() ) ); 529 this, SLOT( gotRawRectChunk() ) );
525 530
526 // qWarning( "Got raw rect chunk" ); 531 // owarn << "Got raw rect chunk" << oendl;
527 532
528 // 533 //
529 // Read the rect data and copy it to the buffer. 534 // Read the rect data and copy it to the buffer.
530 // 535 //
531 536
532 // TODO: Replace this! 537 // TODO: Replace this!
533 int count = lines * w * format->bpp / 8; 538 int count = lines * w * format->bpp / 8;
534 char *hack = new char[ count ]; 539 char *hack = new char[ count ];
535 con->read( hack, count ); 540 con->read( hack, count );
536 buf->drawRawRectChunk( hack, x, y, w, lines ); 541 buf->drawRawRectChunk( hack, x, y, w, lines );
537 delete hack; 542 delete hack;
538 // /TODO: 543 // /TODO:
539 544
540 h = h - lines; 545 h = h - lines;
541 y = y + lines; 546 y = y + lines;
542 547
543 if ( h > 0 ) { 548 if ( h > 0 ) {
544 handleRawRect(); 549 handleRawRect();
545 } 550 }
546 else { 551 else {
547 noRects--; 552 noRects--;
548 553
549 // qWarning( "There are %d rects left", noRects ); 554 // owarn << "There are " << noRects << " rects left" << oendl;
550 555
551 if ( noRects ) { 556 if ( noRects ) {
552 currentState = AwaitingRectHeader; 557 currentState = AwaitingRectHeader;
553 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) ); 558 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) );
554 con->waitForData( RectHeaderLength ); 559 con->waitForData( RectHeaderLength );
555 } 560 }
556 else { 561 else {
557 // we are now ready for the next update - no need to wait for the timer 562 // we are now ready for the next update - no need to wait for the timer
558 currentState = Idle; 563 currentState = Idle;
559 sendUpdateRequest (1); 564 sendUpdateRequest (1);
560 } 565 }
561 } 566 }
562} 567}
563 568
564// 569//
565// Copy Rectangle Encoding 570// Copy Rectangle Encoding
566// 571//
567 572
568void KRFBDecoder::handleCopyRect() 573void KRFBDecoder::handleCopyRect()
569{ 574{
570 currentState = AwaitingCopyRectPos; 575 currentState = AwaitingCopyRectPos;
571 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotCopyRectPos() ) ); 576 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotCopyRectPos() ) );
572 con->waitForData( CopyRectPosLength ); 577 con->waitForData( CopyRectPosLength );
573} 578}
574 579
575void KRFBDecoder::gotCopyRectPos() 580void KRFBDecoder::gotCopyRectPos()
576{ 581{
577 disconnect( con, SIGNAL( gotEnoughData() ), 582 disconnect( con, SIGNAL( gotEnoughData() ),
578 this, SLOT( gotCopyRectPos() ) ); 583 this, SLOT( gotCopyRectPos() ) );
579 584
580 CARD16 srcX; 585 CARD16 srcX;
581 CARD16 srcY; 586 CARD16 srcY;
582 587
583 con->read( &srcX, 2 ); 588 con->read( &srcX, 2 );
584 con->read( &srcY, 2 ); 589 con->read( &srcY, 2 );
585 590
586 srcX = Swap16IfLE( srcX ); 591 srcX = Swap16IfLE( srcX );
587 srcY = Swap16IfLE( srcY ); 592 srcY = Swap16IfLE( srcY );
588 593
589 buf->copyRect( srcX, srcY, x, y, w, h ); 594 buf->copyRect( srcX, srcY, x, y, w, h );
590 595
591 noRects--; 596 noRects--;
592 597
593 // qWarning( "There are %d rects left", noRects ); 598 // owarn << "There are " << noRects << " rects left" << oendl;
594 599
595 if ( noRects ) { 600 if ( noRects ) {
596 currentState = AwaitingRectHeader; 601 currentState = AwaitingRectHeader;
597 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) ); 602 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotRectHeader() ) );
598 con->waitForData( RectHeaderLength ); 603 con->waitForData( RectHeaderLength );
599 } 604 }
600 else 605 else
601 currentState = Idle; 606 currentState = Idle;
602} 607}
603 608
604void KRFBDecoder::handleRRERect() 609void KRFBDecoder::handleRRERect()
605{ 610{
606 qWarning( "RRE not implemented" ); 611 owarn << "RRE not implemented" << oendl;
607} 612}
608 613
609void KRFBDecoder::handleCoRRERect() 614void KRFBDecoder::handleCoRRERect()
610{ 615{
611 qWarning( "CoRRE not implemented" ); 616 owarn << "CoRRE not implemented" << oendl;
612} 617}
613 618
614void KRFBDecoder::handleHexTileRect() 619void KRFBDecoder::handleHexTileRect()
615{ 620{
616 qWarning( "HexTile not implemented" ); 621 owarn << "HexTile not implemented" << oendl;
617} 622}
618 623
619void KRFBDecoder::sendMouseEvent( QMouseEvent *e ) 624void KRFBDecoder::sendMouseEvent( QMouseEvent *e )
620{ 625{
621 // Deal with the buttons 626 // Deal with the buttons
622 if ( e->type() != QEvent::MouseMove ) { 627 if ( e->type() != QEvent::MouseMove ) {
623 buttonMask = 0; 628 buttonMask = 0;
624 if ( e->type() == QEvent::MouseButtonPress ) { 629 if ( e->type() == QEvent::MouseButtonPress ) {
625 if ( e->button() & LeftButton ) 630 if ( e->button() & LeftButton )
626 buttonMask |= 0x01; 631 buttonMask |= 0x01;
627 if ( e->button() & MidButton ) 632 if ( e->button() & MidButton )
628 buttonMask |= 0x04; 633 buttonMask |= 0x04;
629 if ( e->button() & RightButton ) 634 if ( e->button() & RightButton )
630 buttonMask |= 0x02; 635 buttonMask |= 0x02;
631 } 636 }
632 else if ( e->type() == QEvent::MouseButtonRelease ) { 637 else if ( e->type() == QEvent::MouseButtonRelease ) {
633 if ( e->button() & LeftButton ) 638 if ( e->button() & LeftButton )
634 buttonMask &= 0x06; 639 buttonMask &= 0x06;
635 if ( e->button() & MidButton ) 640 if ( e->button() & MidButton )
636 buttonMask |= 0x03; 641 buttonMask |= 0x03;
637 if ( e->button() & RightButton ) 642 if ( e->button() & RightButton )
638 buttonMask |= 0x05; 643 buttonMask |= 0x05;
639 } 644 }
640 } 645 }
641 646
642 // HACK: Scaling 647 // HACK: Scaling
643 CARD16 x = Swap16IfLE( e->x() * con->options()->scaleFactor ); 648 CARD16 x = Swap16IfLE( e->x() * con->options()->scaleFactor );
644 CARD16 y = Swap16IfLE( e->y() *con->options()->scaleFactor ); 649 CARD16 y = Swap16IfLE( e->y() *con->options()->scaleFactor );
645 650
646 con->write( &PointerEventId, 1 ); 651 con->write( &PointerEventId, 1 );
647 con->write( &buttonMask, 1 ); 652 con->write( &buttonMask, 1 );
648 con->write( &x, 2 ); 653 con->write( &x, 2 );
649 con->write( &y, 2 ); 654 con->write( &y, 2 );
650} 655}
651 656
652 657
653void KRFBDecoder::sendCutEvent( const QString &unicode ) 658void KRFBDecoder::sendCutEvent( const QString &unicode )
654{ 659{
655 // 660 //
656 // Warning: There is a bug in the RFB protocol because there is no way to find 661 // Warning: There is a bug in the RFB protocol because there is no way to find
657 // out the codepage in use on the remote machine. This could be fixed by requiring 662 // out the codepage in use on the remote machine. This could be fixed by requiring
658 // the remote server to use utf8 etc. but for now we have to assume they're the 663 // the remote server to use utf8 etc. but for now we have to assume they're the
659 // same. I've reported this problem to the ORL guys, but they apparantly have no 664 // same. I've reported this problem to the ORL guys, but they apparantly have no
660 // immediate plans to fix the issue. :-( (rich) 665 // immediate plans to fix the issue. :-( (rich)
661 // 666 //
662 667
663 CARD8 padding[3]; 668 CARD8 padding[3];
664 QCString text = unicode.local8Bit(); 669 QCString text = unicode.local8Bit();
665 CARD32 length = text.length(); 670 CARD32 length = text.length();
666 length = Swap32IfLE( length ); 671 length = Swap32IfLE( length );
667 672
668 con->write( &ClientCutTextId, 1 ); 673 con->write( &ClientCutTextId, 1 );
669 con->write( &padding, 3 ); 674 con->write( &padding, 3 );
670 con->write( &length, 4 ); 675 con->write( &length, 4 );
671 con->write( text.data(), length ); 676 con->write( text.data(), length );
672} 677}
673 678
674void KRFBDecoder::gotServerCut() 679void KRFBDecoder::gotServerCut()
675{ 680{
676 qWarning( "Got server cut" ); 681 owarn << "Got server cut" << oendl;
677 682
678 currentState = AwaitingServerCutLength; 683 currentState = AwaitingServerCutLength;
679 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerCutLength() ) ); 684 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerCutLength() ) );
680 con->waitForData( ServerCutLenLength ); 685 con->waitForData( ServerCutLenLength );
681} 686}
682 687
683void KRFBDecoder::gotServerCutLength() 688void KRFBDecoder::gotServerCutLength()
684{ 689{
685 assert( currentState = AwaitingServerCutLength ); 690 assert( currentState = AwaitingServerCutLength );
686 disconnect( con, SIGNAL( gotEnoughData() ), 691 disconnect( con, SIGNAL( gotEnoughData() ),
687 this, SLOT( gotServerCutLength() ) ); 692 this, SLOT( gotServerCutLength() ) );
688 693
689 CARD8 padding[3]; 694 CARD8 padding[3];
690 con->read( padding, 3 ); 695 con->read( padding, 3 );
691 696
692 con->read( &serverCutTextLen, 4 ); 697 con->read( &serverCutTextLen, 4 );
693 serverCutTextLen = Swap32IfLE( serverCutTextLen ); 698 serverCutTextLen = Swap32IfLE( serverCutTextLen );
694 699
695 currentState = AwaitingServerCutText; 700 currentState = AwaitingServerCutText;
696 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerCutText() ) ); 701 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerCutText() ) );
697 con->waitForData( serverCutTextLen ); 702 con->waitForData( serverCutTextLen );
698} 703}
699 704
700void KRFBDecoder::gotServerCutText() 705void KRFBDecoder::gotServerCutText()
701{ 706{
702 assert( currentState = AwaitingServerCutText ); 707 assert( currentState = AwaitingServerCutText );
703 708
704 disconnect( con, SIGNAL( gotEnoughData() ), 709 disconnect( con, SIGNAL( gotEnoughData() ),
705 this, SLOT( gotServerCutText() ) ); 710 this, SLOT( gotServerCutText() ) );
706 711
707 712
708 // 713 //
709 // Warning: There is a bug in the RFB protocol because there is no way to find 714 // Warning: There is a bug in the RFB protocol because there is no way to find
710 // out the codepage in use on the remote machine. This could be fixed by requiring 715 // out the codepage in use on the remote machine. This could be fixed by requiring
711 // the remote server to use utf8 etc. but for now we have to assume they're the 716 // the remote server to use utf8 etc. but for now we have to assume they're the
712 // same. I've reported this problem to the ORL guys, but they apparantly have no 717 // same. I've reported this problem to the ORL guys, but they apparantly have no
713 // immediate plans to fix the issue. :-( (rich) 718 // immediate plans to fix the issue. :-( (rich)
714 // 719 //
715 720
716 char *cutbuf = new char[ serverCutTextLen + 1 ]; 721 char *cutbuf = new char[ serverCutTextLen + 1 ];
717 CHECK_PTR( cutbuf ); 722 CHECK_PTR( cutbuf );
718 723
719 con->read( cutbuf, serverCutTextLen ); 724 con->read( cutbuf, serverCutTextLen );
720 cutbuf[ serverCutTextLen ] = '\0'; 725 cutbuf[ serverCutTextLen ] = '\0';
721 726
722 /* For some reason QApplication::clipboard()->setText() segfaults when called 727 /* For some reason QApplication::clipboard()->setText() segfaults when called
723 * from within keypebble's mass of signals and slots 728 * from within keypebble's mass of signals and slots
724 qWarning( "Server cut: %s", cutbuf ); 729 owarn << "Server cut: " << cutbuf << "" << oendl;
725 730
726 QString cutText( cutbuf ); // DANGER!! 731 QString cutText( cutbuf ); // DANGER!!
727 qApp->clipboard()->setText( cutText ); 732 qApp->clipboard()->setText( cutText );
728 */ 733 */
729 734
730 delete cutbuf; 735 delete cutbuf;
731 // Now wait for the update (again) 736 // Now wait for the update (again)
732 if ( oldState == AwaitingUpdate ) { 737 if ( oldState == AwaitingUpdate ) {
733 currentState = AwaitingUpdate; 738 currentState = AwaitingUpdate;
734 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) ); 739 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) );
735 con->waitForData( UpdateHeaderLength ); 740 con->waitForData( UpdateHeaderLength );
736 } 741 }
737 else if ( oldState == Idle ) { 742 else if ( oldState == Idle ) {
738 currentState = Idle; 743 currentState = Idle;
739 } 744 }
740 else { 745 else {
741 qWarning( "Async handled in weird state" ); 746 owarn << "Async handled in weird state" << oendl;
742 currentState = oldState; 747 currentState = oldState;
743 }; 748 };
744} 749}
745 750
746void KRFBDecoder::gotBell() 751void KRFBDecoder::gotBell()
747{ 752{
748 qWarning( "Got server bell" ); 753 owarn << "Got server bell" << oendl;
749 buf->soundBell(); 754 buf->soundBell();
750 755
751 // Now wait for the update (again) 756 // Now wait for the update (again)
752 if ( oldState == AwaitingUpdate ) { 757 if ( oldState == AwaitingUpdate ) {
753 currentState = AwaitingUpdate; 758 currentState = AwaitingUpdate;
754 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) ); 759 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotUpdateHeader() ) );
755 con->waitForData( UpdateHeaderLength ); 760 con->waitForData( UpdateHeaderLength );
756 } 761 }
757 else if ( oldState == Idle ) { 762 else if ( oldState == Idle ) {
758 currentState = Idle; 763 currentState = Idle;
759 } 764 }
760 else { 765 else {
761 qWarning( "Async handled in weird state" ); 766 owarn << "Async handled in weird state" << oendl;
762 currentState = oldState; 767 currentState = oldState;
763 }; 768 };
764} 769}
765 770
766void KRFBDecoder::sendKeyPressEvent( QKeyEvent *event ) 771void KRFBDecoder::sendKeyPressEvent( QKeyEvent *event )
767{ 772{
768 int key; 773 int key;
769 key = toKeySym( event ); 774 key = toKeySym( event );
770 if ( key ) { 775 if ( key ) {
771 key = Swap32IfLE( key ); 776 key = Swap32IfLE( key );
772 777
773 CARD8 mask = true; 778 CARD8 mask = true;
774 779
775 CARD16 padding = 0; 780 CARD16 padding = 0;
776 con->write( &KeyEventId, 1 ); 781 con->write( &KeyEventId, 1 );
777 con->write( &mask, 1 ); 782 con->write( &mask, 1 );
778 con->write( &padding, 2 ); 783 con->write( &padding, 2 );
779 con->write( &key, 4 ); 784 con->write( &key, 4 );
780 } 785 }
781} 786}
782 787
783void KRFBDecoder::sendKeyReleaseEvent( QKeyEvent *event ) 788void KRFBDecoder::sendKeyReleaseEvent( QKeyEvent *event )
784{ 789{
785 int key; 790 int key;
786 key = toKeySym( event ); 791 key = toKeySym( event );
787 if ( key ) { 792 if ( key ) {
788 key = Swap32IfLE( key ); 793 key = Swap32IfLE( key );
789 794
790 CARD8 mask = false; 795 CARD8 mask = false;
791 796
792 CARD16 padding = 0; 797 CARD16 padding = 0;
793 con->write( &KeyEventId, 1 ); 798 con->write( &KeyEventId, 1 );
794 con->write( &mask, 1 ); 799 con->write( &mask, 1 );
795 con->write( &padding, 2 ); 800 con->write( &padding, 2 );
796 con->write( &key, 4 ); 801 con->write( &key, 4 );
797 } 802 }
798} 803}
799 804
800 805
801 806
802 807
803// 808//
804// The RFB protocol spec says 'For most ordinary keys, the 'keysym' 809// The RFB protocol spec says 'For most ordinary keys, the 'keysym'
805// is the same as the corresponding ASCII value.', but doesn't 810// is the same as the corresponding ASCII value.', but doesn't
806// elaborate what the most ordinary keys are. The spec also lists 811// elaborate what the most ordinary keys are. The spec also lists
807// a set (possibly subset, it's unspecified) of mappings for 812// a set (possibly subset, it's unspecified) of mappings for
808// "other common keys" (backspace, tab, return, escape, etc). 813// "other common keys" (backspace, tab, return, escape, etc).
809// 814//
810int KRFBDecoder::toKeySym( QKeyEvent *k ) 815int KRFBDecoder::toKeySym( QKeyEvent *k )
811{ 816{
812 817
813 // 818 //
814 // Try and map these "other common keys" first. 819 // Try and map these "other common keys" first.
815 // 820 //
816 if ((k->key() >= Qt::Key_Escape) && (k->key() <= Qt::Key_F12)) { 821 if ((k->key() >= Qt::Key_Escape) && (k->key() <= Qt::Key_F12)) {
817 for(int i = 0; keyMap[i].keycode != 0; i++) { 822 for(int i = 0; keyMap[i].keycode != 0; i++) {
818 if (k->key() == keyMap[i].keycode) { 823 if (k->key() == keyMap[i].keycode) {
819 return keyMap[i].keysym; 824 return keyMap[i].keysym;
820 } 825 }
821 } 826 }
822 } 827 }
823 828
824 // 829 //
825 // If these keys aren't matched, return the ascii code and let the 830 // If these keys aren't matched, return the ascii code and let the
826 // server figure it out. We don't return k->key(), as the data in 831 // server figure it out. We don't return k->key(), as the data in
827 // key differs between input methods, and we don't want special cases. 832 // key differs between input methods, and we don't want special cases.
828 // 833 //
829 return k->ascii(); 834 return k->ascii();
830} 835}
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 @@
1#include <assert.h> 1#include "krfblogin.h"
2#include "krfbconnection.h"
2 3
4/* OPIE */
5#include <opie2/odebug.h>
6using namespace Opie::Core;
7
8/* QT */
9#include <qtimer.h>
3 10
11/* STD */
12#include <assert.h>
4extern "C" { 13extern "C" {
5#include "vncauth.h" 14#include "vncauth.h"
6} 15}
7 16
8#include "krfblogin.h"
9#include "krfbconnection.h"
10#include <qtimer.h>
11
12// The length of the various messages (used to decide how many bytes to 17// The length of the various messages (used to decide how many bytes to
13// wait for). 18// wait for).
14const int ServerVersionLength = 12; 19const int ServerVersionLength = 12;
15const int ClientVersionLength = 12; 20const int ClientVersionLength = 12;
16const int AuthSchemeLength = 4; 21const int AuthSchemeLength = 4;
17const int FailureReasonSizeLength = 4; 22const int FailureReasonSizeLength = 4;
18const int ChallengeLength = 16; 23const int ChallengeLength = 16;
19const int AuthResultLength = 4; 24const int AuthResultLength = 4;
20 25
21// Authentication results 26// Authentication results
22enum AuthResult { 27enum AuthResult {
23 AuthOk, 28 AuthOk,
24 AuthFailed, 29 AuthFailed,
25 AuthTooMany 30 AuthTooMany
26}; 31};
27 32
28typedef unsigned char CARD8; 33typedef unsigned char CARD8;
29typedef unsigned short CARD16; 34typedef unsigned short CARD16;
30typedef unsigned long CARD32; 35typedef unsigned long CARD32;
31 36
32const int endianTest = 1; 37const int endianTest = 1;
33 38
34// Endian stuff 39// Endian stuff
35#define Swap16IfLE(s) \ 40#define Swap16IfLE(s) \
36 (*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s)) 41 (*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s))
37 42
38#define Swap32IfLE(l) \ 43#define Swap32IfLE(l) \
39 (*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \ 44 (*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \
40 (((l) & 0x00ff0000) >> 8) | \ 45 (((l) & 0x00ff0000) >> 8) | \
41 (((l) & 0x0000ff00) << 8) | \ 46 (((l) & 0x0000ff00) << 8) | \
42 (((l) & 0x000000ff) << 24)) : (l)) 47 (((l) & 0x000000ff) << 24)) : (l))
43 48
44KRFBLogin::KRFBLogin( KRFBConnection *con ) 49KRFBLogin::KRFBLogin( KRFBConnection *con )
45 : QObject( con, "RFB login manager" ) 50 : QObject( con, "RFB login manager" )
46{ 51{
47 assert( con ); 52 assert( con );
48 this->con = con; 53 this->con = con;
49 currentState = AwaitingServerVersion; 54 currentState = AwaitingServerVersion;
50 55
51 connect( this, SIGNAL( error(const QString&) ), 56 connect( this, SIGNAL( error(const QString&) ),
52 con, SIGNAL( error(const QString&) ) ); 57 con, SIGNAL( error(const QString&) ) );
53 58
54 59
55 qWarning( "Waiting for server version..." ); 60 owarn << "Waiting for server version..." << oendl;
56 61
57 static QString statusMsg = tr( "Waiting for server version..." ); 62 static QString statusMsg = tr( "Waiting for server version..." );
58 emit status( statusMsg ); 63 emit status( statusMsg );
59 64
60 // Kick off the state machine 65 // Kick off the state machine
61 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerVersion() ) ); 66 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerVersion() ) );
62 con->waitForData( ServerVersionLength ); 67 con->waitForData( ServerVersionLength );
63} 68}
64 69
65KRFBLogin::~KRFBLogin() 70KRFBLogin::~KRFBLogin()
66{ 71{
67 72
68} 73}
69 74
70KRFBLogin::State KRFBLogin::state() const 75KRFBLogin::State KRFBLogin::state() const
71{ 76{
72 return currentState; 77 return currentState;
73} 78}
74 79
75void KRFBLogin::gotServerVersion() 80void KRFBLogin::gotServerVersion()
76{ 81{
77 qWarning( "Got server version" ); 82 owarn << "Got server version" << oendl;
78 83
79 disconnect( con, SIGNAL( gotEnoughData() ), 84 disconnect( con, SIGNAL( gotEnoughData() ),
80 this, SLOT( gotServerVersion() ) ); 85 this, SLOT( gotServerVersion() ) );
81 86
82 // Read the server's version message 87 // Read the server's version message
83 char serverVersion[ ServerVersionLength + 1 ]; 88 char serverVersion[ ServerVersionLength + 1 ];
84 con->read( serverVersion, ServerVersionLength ); 89 con->read( serverVersion, ServerVersionLength );
85 serverVersion[ ServerVersionLength ] = '\0'; 90 serverVersion[ ServerVersionLength ] = '\0';
86 91
87 QCString rfbString( serverVersion, ServerVersionLength + 1 ); 92 QCString rfbString( serverVersion, ServerVersionLength + 1 );
88 versionString = rfbString; 93 versionString = rfbString;
89 94
90 QRegExp regexp( "RFB [0-9][0-9][0-9]\\.[0-9][0-9][0-9]\n" ); 95 QRegExp regexp( "RFB [0-9][0-9][0-9]\\.[0-9][0-9][0-9]\n" );
91 96
92 if ( rfbString.find( regexp ) == -1 ) { 97 if ( rfbString.find( regexp ) == -1 ) {
93 static QString msg = tr( "Error: Invalid server version, %1" ).arg( rfbString ); 98 static QString msg = tr( "Error: Invalid server version, %1" ).arg( rfbString );
94 99
95 qWarning( msg ); 100 owarn << msg << oendl;
96 emit error( msg ); 101 emit error( msg );
97 currentState = Error; 102 currentState = Error;
98 return; 103 return;
99 } 104 }
100 105
101 // Calculate the actual version number 106 // Calculate the actual version number
102 serverMajor = (serverVersion[4] - '0') * 100 107 serverMajor = (serverVersion[4] - '0') * 100
103 + (serverVersion[5] - '0') * 10 108 + (serverVersion[5] - '0') * 10
104 + (serverVersion[6] - '0'); 109 + (serverVersion[6] - '0');
105 serverMinor = (serverVersion[8] - '0') * 100 110 serverMinor = (serverVersion[8] - '0') * 100
106 + (serverVersion[9] - '0') * 10 111 + (serverVersion[9] - '0') * 10
107 + (serverVersion[10] - '0'); 112 + (serverVersion[10] - '0');
108 113
109 qWarning("Server Version: %03d.%03d", serverMajor, serverMinor ); 114 owarn << "Server Version: " << serverMajor << "." << serverMinor << "" << oendl;
110 115
111 if ( serverMajor != 3 ) { 116 if ( serverMajor != 3 ) {
112 QString msg = tr( "Error: Unsupported server version, %1" ) 117 QString msg = tr( "Error: Unsupported server version, %1" )
113 .arg( rfbString ); 118 .arg( rfbString );
114 119
115 qWarning( msg ); 120 owarn << msg << oendl;
116 emit error( msg ); 121 emit error( msg );
117 currentState = Error; 122 currentState = Error;
118 return; 123 return;
119 } 124 }
120 125
121 if ( serverMinor != 3 ) { 126 if ( serverMinor != 3 ) {
122 qWarning( "Minor version mismatch: %d", serverMinor ); 127 owarn << "Minor version mismatch: " << serverMinor << "" << oendl;
123 } 128 }
124 129
125 // Setup for the next state 130 // Setup for the next state
126 sendClientVersion(); 131 sendClientVersion();
127 132
128 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthScheme() ) ); 133 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthScheme() ) );
129 con->waitForData( AuthSchemeLength ); 134 con->waitForData( AuthSchemeLength );
130} 135}
131 136
132void KRFBLogin::gotAuthScheme() 137void KRFBLogin::gotAuthScheme()
133{ 138{
134 disconnect( con, SIGNAL( gotEnoughData() ), 139 disconnect( con, SIGNAL( gotEnoughData() ),
135 this, SLOT( gotAuthScheme() ) ); 140 this, SLOT( gotAuthScheme() ) );
136 141
137 // Got data 142 // Got data
138 CARD32 scheme; 143 CARD32 scheme;
139 con->read( &scheme, AuthSchemeLength ); 144 con->read( &scheme, AuthSchemeLength );
140 scheme = Swap32IfLE( scheme ); 145 scheme = Swap32IfLE( scheme );
141 146
142 static QString statusMsgOk = tr( "Logged in" ); 147 static QString statusMsgOk = tr( "Logged in" );
143 148
144 switch ( scheme ) { 149 switch ( scheme ) {
145 case 0: 150 case 0:
146 qWarning( "Failed" ); 151 owarn << "Failed" << oendl;
147 // Handle failure 152 // Handle failure
148 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotFailureReasonSize() ) ); 153 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotFailureReasonSize() ) );
149 con->waitForData( FailureReasonSizeLength ); 154 con->waitForData( FailureReasonSizeLength );
150 break; 155 break;
151 case 1: 156 case 1:
152 // Handle no auth 157 // Handle no auth
153 emit status( statusMsgOk ); 158 emit status( statusMsgOk );
154 con->gotRFBConnection(); 159 con->gotRFBConnection();
155 break; 160 break;
156 case 2: 161 case 2:
157 // Handle VNC auth 162 // Handle VNC auth
158 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotChallenge() ) ); 163 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotChallenge() ) );
159 con->waitForData( ChallengeLength ); 164 con->waitForData( ChallengeLength );
160 break; 165 break;
161 default: 166 default:
162 qWarning( "Unknown authentication scheme, 0x%08lx", scheme ); 167 owarn << "Unknown authentication scheme, 0x" << scheme << "" << oendl;
163 currentState = Error; 168 currentState = Error;
164 break; 169 break;
165 }; 170 };
166} 171}
167 172
168void KRFBLogin::gotChallenge() 173void KRFBLogin::gotChallenge()
169{ 174{
170 disconnect( con, SIGNAL( gotEnoughData() ), 175 disconnect( con, SIGNAL( gotEnoughData() ),
171 this, SLOT( gotChallenge() ) ); 176 this, SLOT( gotChallenge() ) );
172 177
173 QTimer::singleShot( 0, this, SLOT(getPassword()) ); 178 QTimer::singleShot( 0, this, SLOT(getPassword()) );
174} 179}
175 180
176void KRFBLogin::getPassword() 181void KRFBLogin::getPassword()
177{ 182{
178 // Got data 183 // Got data
179 CARD8 challenge[ ChallengeLength ]; 184 CARD8 challenge[ ChallengeLength ];
180 con->read( challenge, ChallengeLength ); 185 con->read( challenge, ChallengeLength );
181 186
182 // Last chance to enter a password 187 // Last chance to enter a password
183 if ( con->options_->password.isNull() ) { 188 if ( con->options_->password.isNull() ) {
184 qWarning( "krfblogin needs a password" ); 189 owarn << "krfblogin needs a password" << oendl;
185 emit passwordRequired( con ); 190 emit passwordRequired( con );
186 } 191 }
187 192
188 if ( con->options_->password.isNull() ) { 193 if ( con->options_->password.isNull() ) {
189 QString msg = tr( "Error: This server requires a password, but none " 194 QString msg = tr( "Error: This server requires a password, but none "
190 "has been specified.\n" ); 195 "has been specified.\n" );
191 196
192 emit error( msg ); 197 emit error( msg );
193 return; 198 return;
194 } 199 }
195 200
196 vncEncryptBytes( (unsigned char *) challenge, QCString(con->options_->password.latin1()).data() ); 201 vncEncryptBytes( (unsigned char *) challenge, QCString(con->options_->password.latin1()).data() );
197 con->write( challenge, ChallengeLength ); 202 con->write( challenge, ChallengeLength );
198 203
199 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthResult() ) ); 204 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthResult() ) );
200 con->waitForData( AuthResultLength ); 205 con->waitForData( AuthResultLength );
201} 206}
202 207
203void KRFBLogin::gotFailureReasonSize() 208void KRFBLogin::gotFailureReasonSize()
204{ 209{
205 disconnect( con, SIGNAL( gotEnoughData() ), this, 210 disconnect( con, SIGNAL( gotEnoughData() ), this,
206 SLOT( gotFailureReasonSize() ) ); 211 SLOT( gotFailureReasonSize() ) );
207} 212}
208 213
209void KRFBLogin::gotAuthResult() 214void KRFBLogin::gotAuthResult()
210{ 215{
211 // Got data 216 // Got data
212 disconnect( con, SIGNAL( gotEnoughData() ), this, 217 disconnect( con, SIGNAL( gotEnoughData() ), this,
213 SLOT( gotAuthResult() ) ); 218 SLOT( gotAuthResult() ) );
214 219
215 long result; 220 long result;
216 con->read( &result, AuthResultLength ); 221 con->read( &result, AuthResultLength );
217 result = Swap32IfLE( result ); 222 result = Swap32IfLE( result );
218 223
219 qWarning( "Authentication Result is 0x%08lx", result ); 224 owarn << "Authentication Result is 0x" << result << "" << oendl;
220 225
221 static QString failed = tr( "Error: The password you specified was incorrect." ); 226 static QString failed = tr( "Error: The password you specified was incorrect." );
222 static QString tooMany = tr( "Error: Too many invalid login attempts have been made\n" 227 static QString tooMany = tr( "Error: Too many invalid login attempts have been made\n"
223 "to this account, please try later." ); 228 "to this account, please try later." );
224 229
225 static QString statusMsgOk = tr( "Logged in" ); 230 static QString statusMsgOk = tr( "Logged in" );
226 static QString statusMsgFailed = tr( "Login Failed" ); 231 static QString statusMsgFailed = tr( "Login Failed" );
227 static QString statusMsgTooMany = tr( "Too many failures" ); 232 static QString statusMsgTooMany = tr( "Too many failures" );
228 233
229 switch( result ) { 234 switch( result ) {
230 case AuthOk: 235 case AuthOk:
231 emit status( statusMsgOk ); 236 emit status( statusMsgOk );
232 con->gotRFBConnection(); 237 con->gotRFBConnection();
233 break; 238 break;
234 case AuthFailed: 239 case AuthFailed:
235 qWarning( "Dammit" ); 240 owarn << "Dammit" << oendl;
236 emit status( statusMsgFailed ); 241 emit status( statusMsgFailed );
237 emit error( failed ); 242 emit error( failed );
238 break; 243 break;
239 case AuthTooMany: 244 case AuthTooMany:
240 emit status( statusMsgTooMany ); 245 emit status( statusMsgTooMany );
241 emit error( tooMany ); 246 emit error( tooMany );
242 break; 247 break;
243 default: 248 default:
244 qWarning( "Invalid authentication result, %lx", result ); 249 owarn << "Invalid authentication result, " << result << "" << oendl;
245 break; 250 break;
246 } 251 }
247} 252}
248 253
249void KRFBLogin::sendClientVersion() 254void KRFBLogin::sendClientVersion()
250{ 255{
251 qWarning( "Sending client version" ); 256 owarn << "Sending client version" << oendl;
252 con->write( (void*)"RFB 003.003\n", ClientVersionLength ); 257 con->write( (void*)"RFB 003.003\n", ClientVersionLength );
253} 258}
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 @@
1#include "kvncbookmarkdlg.h"
2
3/* OPIE */
4#include <opie2/odebug.h>
5#include <qpe/global.h>
6using namespace Opie::Core;
7
8/* QT */
1#include <qdir.h> 9#include <qdir.h>
2#include <qtextstream.h> 10#include <qtextstream.h>
3#include <qlistbox.h> 11#include <qlistbox.h>
4#include <qpe/global.h>
5#include "kvncbookmarkdlg.h"
6 12
7KVNCBookmarkDlg::KVNCBookmarkDlg( QWidget * parent, const char * name, WFlags f ) 13KVNCBookmarkDlg::KVNCBookmarkDlg( QWidget * parent, const char * name, WFlags f )
8 14
9: KVNCBookmarkDlgBase( parent, name,f) 15: KVNCBookmarkDlgBase( parent, name,f)
10{ 16{
11 readBookmarks(); 17 readBookmarks();
12 refresh(); 18 refresh();
13 19
14} 20}
15 21
16KVNCBookmarkDlg::~KVNCBookmarkDlg() 22KVNCBookmarkDlg::~KVNCBookmarkDlg()
17{ 23{
18} 24}
19 25
20void KVNCBookmarkDlg::addBookmark(KRFBServer * server) 26void KVNCBookmarkDlg::addBookmark(KRFBServer * server)
21{ 27{
22 if (server) { 28 if (server) {
23 servers.append(server); 29 servers.append(server);
24 bookmarkList->insertItem(server->name); 30 bookmarkList->insertItem(server->name);
25 writeBookmarks(); 31 writeBookmarks();
26 refresh(); 32 refresh();
27 } 33 }
28} 34}
29 35
30void KVNCBookmarkDlg::deleteBookmark(QString name) 36void KVNCBookmarkDlg::deleteBookmark(QString name)
31{ 37{
32 KRFBServer * server=0; 38 KRFBServer * server=0;
33 for ( server=servers.first(); server != 0; server=servers.next() ) { 39 for ( server=servers.first(); server != 0; server=servers.next() ) {
34 if (server->name==name) { 40 if (server->name==name) {
35 servers.remove(servers.at()); 41 servers.remove(servers.at());
36 writeBookmarks(); 42 writeBookmarks();
37 refresh(); 43 refresh();
38 return; 44 return;
39 } 45 }
40 } 46 }
41} 47}
42KRFBServer *KVNCBookmarkDlg::getServer(QString name) 48KRFBServer *KVNCBookmarkDlg::getServer(QString name)
43{ 49{
44 KRFBServer * server=0; 50 KRFBServer * server=0;
45 for ( server=servers.first(); server != 0; server=servers.next() ) { 51 for ( server=servers.first(); server != 0; server=servers.next() ) {
46 if (server->name==name) 52 if (server->name==name)
47 53
48 return server; 54 return server;
49 } 55 }
50 return 0; 56 return 0;
51} 57}
52 58
53 59
54/* 60/*
55 Note that the degree of protection offered by the encryption here is 61 Note that the degree of protection offered by the encryption here is
56 only sufficient to avoid the most casual observation of the configuration 62 only sufficient to avoid the most casual observation of the configuration
57 files. People with access to the files can write down the contents and 63 files. People with access to the files can write down the contents and
58 decrypt it using this source code. 64 decrypt it using this source code.
59 65
60 Conceivably, and at some burden to the user, this encryption could 66 Conceivably, and at some burden to the user, this encryption could
61 be improved. 67 be improved.
62*/ 68*/
63QString KVNCBookmarkDlg::encipher(const QString& plain) 69QString KVNCBookmarkDlg::encipher(const QString& plain)
64{ 70{
65 // mainly, we make it long 71 // mainly, we make it long
66 QString cipher; 72 QString cipher;
67 int mix=28730492; 73 int mix=28730492;
68 for (int i=0; i<(int)plain.length(); i++) { 74 for (int i=0; i<(int)plain.length(); i++) {
69 int u = plain[i].unicode(); 75 int u = plain[i].unicode();
70 int c = u ^ mix; 76 int c = u ^ mix;
71 QString x = QString::number(c,36); 77 QString x = QString::number(c,36);
72 cipher.append(QChar('a'+x.length())); 78 cipher.append(QChar('a'+x.length()));
73 cipher.append(x); 79 cipher.append(x);
74 mix *= u; 80 mix *= u;
75 } 81 }
76 return cipher; 82 return cipher;
77} 83}
78 84
79QString KVNCBookmarkDlg::decipher(const QString& cipher) 85QString KVNCBookmarkDlg::decipher(const QString& cipher)
80{ 86{
81 QString plain; 87 QString plain;
82 int mix=28730492; 88 int mix=28730492;
83 for (int i=0; i<(int)cipher.length();) { 89 for (int i=0; i<(int)cipher.length();) {
84 int l = cipher[i].unicode()-'a'; 90 int l = cipher[i].unicode()-'a';
85 QString x = cipher.mid(i+1,l); i+=l+1; 91 QString x = cipher.mid(i+1,l); i+=l+1;
86 int u = x.toInt(0,36) ^ mix; 92 int u = x.toInt(0,36) ^ mix;
87 plain.append(QChar(u)); 93 plain.append(QChar(u));
88 mix *= u; 94 mix *= u;
89 } 95 }
90 return plain; 96 return plain;
91} 97}
92 98
93void KVNCBookmarkDlg::readBookmarks(void) 99void KVNCBookmarkDlg::readBookmarks(void)
94{ 100{
95 QFile f(QDir::homeDirPath() + QString("/Applications/keypebble/bookmarks")); 101 QFile f(QDir::homeDirPath() + QString("/Applications/keypebble/bookmarks"));
96 102
97 QStringList entry; 103 QStringList entry;
98 QString key, val; 104 QString key, val;
99 KRFBServer * server=0; 105 KRFBServer * server=0;
100 106
101 if ( f.open(IO_ReadOnly) ) { 107 if ( f.open(IO_ReadOnly) ) {
102 QTextStream t( &f ); 108 QTextStream t( &f );
103 QString s; 109 QString s;
104 int n = 1; 110 int n = 1;
105 while ( !t.eof() ) { 111 while ( !t.eof() ) {
106 s = t.readLine(); 112 s = t.readLine();
107 113
108 114
109 entry=QStringList::split('=',s); 115 entry=QStringList::split('=',s);
110 key=entry[0].stripWhiteSpace().lower(); 116 key=entry[0].stripWhiteSpace().lower();
111 val=entry[1].stripWhiteSpace(); 117 val=entry[1].stripWhiteSpace();
112 118
113 if (key=="server") { 119 if (key=="server") {
114 120
115 if (server){ 121 if (server){
116 servers.append(server); 122 servers.append(server);
117 server=0; 123 server=0;
118 } 124 }
119 server = new KRFBServer(); 125 server = new KRFBServer();
120 126
121 if (!server) 127 if (!server)
122 return; 128 return;
123 server->name=val; 129 server->name=val;
124 130
125 } 131 }
126 else if (key=="hostname") 132 else if (key=="hostname")
127 server->hostname=val; 133 server->hostname=val;
128 else if (key=="password") 134 else if (key=="password")
129 server->password=decipher(val); 135 server->password=decipher(val);
130 else if (key=="display") 136 else if (key=="display")
131 server->display=val.toInt(); 137 server->display=val.toInt();
132 else if (key=="hextile") 138 else if (key=="hextile")
133 server->hexTile=val.toInt(); 139 server->hexTile=val.toInt();
134 else if (key=="corre") 140 else if (key=="corre")
135 server->corre=val.toInt(); 141 server->corre=val.toInt();
136 else if (key=="rre") 142 else if (key=="rre")
137 server->rre=val.toInt(); 143 server->rre=val.toInt();
138 else if (key=="copyrect") 144 else if (key=="copyrect")
139 server->copyrect=val.toInt(); 145 server->copyrect=val.toInt();
140 else if (key=="colors256") 146 else if (key=="colors256")
141 server->colors256=val.toInt(); 147 server->colors256=val.toInt();
142 else if (key=="shared") 148 else if (key=="shared")
143 server->shared=val.toInt(); 149 server->shared=val.toInt();
144 else if (key=="readonly") 150 else if (key=="readonly")
145 server->readOnly=val.toInt(); 151 server->readOnly=val.toInt();
146 else if (key=="deiconify") 152 else if (key=="deiconify")
147 server->deIconify=val.toInt(); 153 server->deIconify=val.toInt();
148 else if (key=="updaterate") 154 else if (key=="updaterate")
149 server->updateRate=val.toInt(); 155 server->updateRate=val.toInt();
150 else if (key=="scalefactor") 156 else if (key=="scalefactor")
151 server->scaleFactor=val.toInt(); 157 server->scaleFactor=val.toInt();
152 158
153 } 159 }
154 if (server){ 160 if (server){
155 servers.append(server); 161 servers.append(server);
156 server=0; 162 server=0;
157 } 163 }
158 f.close(); 164 f.close();
159 } 165 }
160} 166}
161 167
162void KVNCBookmarkDlg::writeBookmarks(void) 168void KVNCBookmarkDlg::writeBookmarks(void)
163{ 169{
164 QString filename=Global::applicationFileName("keypebble","bookmarks"); 170 QString filename=Global::applicationFileName("keypebble","bookmarks");
165 171
166 QFile f(filename); 172 QFile f(filename);
167 173
168 QString key, val; 174 QString key, val;
169 KRFBServer * server=0; 175 KRFBServer * server=0;
170 176
171 if ( f.open(IO_ReadWrite) ) { 177 if ( f.open(IO_ReadWrite) ) {
172 QTextStream t( &f ); 178 QTextStream t( &f );
173 QString s; 179 QString s;
174 int n = 1; 180 int n = 1;
175 KRFBServer *server; 181 KRFBServer *server;
176 182
177 for ( server=servers.first(); server != 0; server=servers.next() ) { 183 for ( server=servers.first(); server != 0; server=servers.next() ) {
178 qDebug(server->name); 184 odebug << server->name << oendl;
179 t << "server=" << server->name << '\n'; 185 t << "server=" << server->name << '\n';
180 t << "\thostname=" << server->hostname << '\n'; 186 t << "\thostname=" << server->hostname << '\n';
181 t << "\tpassword=" << encipher(server->password )<< '\n'; 187 t << "\tpassword=" << encipher(server->password )<< '\n';
182 t << "\tdisplay=" << server->display << '\n'; 188 t << "\tdisplay=" << server->display << '\n';
183 t << "\thextile=" << server->hexTile << '\n'; 189 t << "\thextile=" << server->hexTile << '\n';
184 t << "\tcorre=" << server->corre << '\n'; 190 t << "\tcorre=" << server->corre << '\n';
185 t << "\trre=" << server->rre << '\n'; 191 t << "\trre=" << server->rre << '\n';
186 t << "\tcopyrect=" << server->copyrect << '\n'; 192 t << "\tcopyrect=" << server->copyrect << '\n';
187 t << "\tshared=" << server->shared << '\n'; 193 t << "\tshared=" << server->shared << '\n';
188 t << "\treadonly=" << server->readOnly << '\n'; 194 t << "\treadonly=" << server->readOnly << '\n';
189 t << "\tdeiconify=" << server->deIconify << '\n'; 195 t << "\tdeiconify=" << server->deIconify << '\n';
190 t << "\tupdaterate=" << server->updateRate << '\n'; 196 t << "\tupdaterate=" << server->updateRate << '\n';
191 t << "\tscalefactor=" << server->scaleFactor << '\n'; 197 t << "\tscalefactor=" << server->scaleFactor << '\n';
192 198
193 } 199 }
194 f.close(); 200 f.close();
195 } 201 }
196} 202}
197void KVNCBookmarkDlg::refresh(void) 203void KVNCBookmarkDlg::refresh(void)
198{ 204{
199 bookmarkList->clear(); 205 bookmarkList->clear();
200 KRFBServer * server=0; 206 KRFBServer * server=0;
201 for ( server=servers.first(); server != 0; server=servers.next() ) { 207 for ( server=servers.first(); server != 0; server=servers.next() ) {
202 bookmarkList->insertItem(server->name); 208 bookmarkList->insertItem(server->name);
203 } 209 }
204} 210}
205 211
206QString KVNCBookmarkDlg::selectedBookmark() 212QString KVNCBookmarkDlg::selectedBookmark()
207{ 213{
208 return bookmarkList->currentText(); 214 return bookmarkList->currentText();
209} 215}
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 @@
1#include "backgammon.h" 1#include "backgammon.h"
2
3#include "aidialog.h" 2#include "aidialog.h"
4#include "filedialog.h" 3#include "filedialog.h"
5#include "playerdialog.h" 4#include "playerdialog.h"
6#include "rulesdialog.h" 5#include "rulesdialog.h"
7#include "themedialog.h" 6#include "themedialog.h"
8 7
8/* OPIE */
9#include <opie2/odebug.h>
10#include <qpe/qpeapplication.h>
11#include <qpe/config.h>
12#include <qpe/resource.h>
13using namespace Opie::Core;
14
15/* QT */
9#include <qfile.h> 16#include <qfile.h>
10#include <qlayout.h> 17#include <qlayout.h>
11#include <qmessagebox.h> 18#include <qmessagebox.h>
12#include <qtimer.h> 19#include <qtimer.h>
13#include <qpe/qpeapplication.h>
14#include <qpe/config.h>
15#include <qmenubar.h> 20#include <qmenubar.h>
16#include <qpe/resource.h>
17 21
18#include <stdlib.h> 22#include <stdlib.h>
19 23
20 24
21BackGammon::BackGammon(QWidget* parent, const char* name, WFlags fl) 25BackGammon::BackGammon(QWidget* parent, const char* name, WFlags fl)
22 : QMainWindow(parent, name, fl) 26 : QMainWindow(parent, name, fl)
23{ 27{
24 if (!name) setName("BackGammon"); 28 if (!name) setName("BackGammon");
25 setCaption(tr( "Backgammon") ); 29 setCaption(tr( "Backgammon") );
26 setIcon( Resource::loadPixmap( "backgammon" ) ); 30 setIcon( Resource::loadPixmap( "backgammon" ) );
27 //general counter varaible 31 //general counter varaible
28 int a=0; 32 int a=0;
29 //the game engine 33 //the game engine
30 move=new MoveEngine(); 34 move=new MoveEngine();
31 35
32 //load the default theme 36 //load the default theme
33 Config conf("backgammon"); 37 Config conf("backgammon");
34 if(!conf.isValid()) 38 if(!conf.isValid())
35 { 39 {
36 qDebug("config file does not exist"); 40 odebug << "config file does not exist" << oendl;
37 conf.setGroup("general"); 41 conf.setGroup("general");
38 conf.writeEntry("theme","default"); 42 conf.writeEntry("theme","default");
39 conf.setGroup("rules"); 43 conf.setGroup("rules");
40 conf.writeEntry("move_with_pieces_out",false); 44 conf.writeEntry("move_with_pieces_out",false);
41 conf.writeEntry("nice_dice",false); 45 conf.writeEntry("nice_dice",false);
42 conf.setGroup("display"); 46 conf.setGroup("display");
43 conf.writeEntry("small",false); 47 conf.writeEntry("small",false);
44 conf.writeEntry("warning",true); 48 conf.writeEntry("warning",true);
45 conf.setGroup("ai"); 49 conf.setGroup("ai");
46 conf.writeEntry("rescue",6); 50 conf.writeEntry("rescue",6);
47 conf.writeEntry("eliminate",4); 51 conf.writeEntry("eliminate",4);
48 conf.writeEntry("expose",1); 52 conf.writeEntry("expose",1);
49 conf.writeEntry("protect",5); 53 conf.writeEntry("protect",5);
50 conf.writeEntry("safe",3); 54 conf.writeEntry("safe",3);
51 conf.writeEntry("empty",2); 55 conf.writeEntry("empty",2);
52 56
53 } 57 }
54 conf.setGroup("general"); 58 conf.setGroup("general");
55 theme_name=conf.readEntry("theme","default"); 59 theme_name=conf.readEntry("theme","default");
56 QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; 60 QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme";
57 61
58 //the rules 62 //the rules
59 conf.setGroup("rules"); 63 conf.setGroup("rules");
60 rules.move_with_pieces_out=conf.readBoolEntry("move_with_pieces_out",false); 64 rules.move_with_pieces_out=conf.readBoolEntry("move_with_pieces_out",false);
61 rules.generous_dice=conf.readBoolEntry("nice_dice",false); 65 rules.generous_dice=conf.readBoolEntry("nice_dice",false);
62 66
63 move->setRules(rules); 67 move->setRules(rules);
64 68
65 //get the AI settings 69 //get the AI settings
66 AISettings ai; 70 AISettings ai;
67 conf.setGroup("ai"); 71 conf.setGroup("ai");
68 ai.rescue=conf.readNumEntry("rescue",6); 72 ai.rescue=conf.readNumEntry("rescue",6);
69 ai.eliminate=conf.readNumEntry("eliminate",4); 73 ai.eliminate=conf.readNumEntry("eliminate",4);
70 ai.expose=conf.readNumEntry("expose",1); 74 ai.expose=conf.readNumEntry("expose",1);
71 ai.protect=conf.readNumEntry("protect",5); 75 ai.protect=conf.readNumEntry("protect",5);
72 ai.safe=conf.readNumEntry("safe",3); 76 ai.safe=conf.readNumEntry("safe",3);
73 ai.empty=conf.readNumEntry("empty",2); 77 ai.empty=conf.readNumEntry("empty",2);
74 move->setAISettings(ai); 78 move->setAISettings(ai);
75 79
76 80
77 //get the theme component names 81 //get the theme component names
78 Config theme(theme_file,Config::File); 82 Config theme(theme_file,Config::File);
79 if(!theme.isValid()) 83 if(!theme.isValid())
80 { 84 {
81 qDebug("theme file does not exist"); 85 odebug << "theme file does not exist" << oendl;
82 theme.setGroup("theme"); 86 theme.setGroup("theme");
83 theme.writeEntry("board","casino_board_1"); 87 theme.writeEntry("board","casino_board_1");
84 theme.writeEntry("pieces1","casino_pieces_blue"); 88 theme.writeEntry("pieces1","casino_pieces_blue");
85 theme.writeEntry("pieces2","casino_pieces_white"); 89 theme.writeEntry("pieces2","casino_pieces_white");
86 theme.writeEntry("dice1","casino_dice"); 90 theme.writeEntry("dice1","casino_dice");
87 theme.writeEntry("dice2","casino_dice"); 91 theme.writeEntry("dice2","casino_dice");
88 theme.writeEntry("table","casino_table_green"); 92 theme.writeEntry("table","casino_table_green");
89 theme.writeEntry("odds","casino_odds"); 93 theme.writeEntry("odds","casino_odds");
90 } 94 }
91 theme.setGroup("theme"); 95 theme.setGroup("theme");
92 board_name=theme.readEntry("board","casino_board_1"); 96 board_name=theme.readEntry("board","casino_board_1");
93 piecesA_name=theme.readEntry("pieces1","casino_pieces_blue"); 97 piecesA_name=theme.readEntry("pieces1","casino_pieces_blue");
94 piecesB_name=theme.readEntry("pieces2","casino_pieces_white"); 98 piecesB_name=theme.readEntry("pieces2","casino_pieces_white");
95 diceA_name=theme.readEntry("dice1","casino_dice"); 99 diceA_name=theme.readEntry("dice1","casino_dice");
96 diceB_name=theme.readEntry("dice2","casino_dice"); 100 diceB_name=theme.readEntry("dice2","casino_dice");
97 table_name=theme.readEntry("table","casino_table_green"); 101 table_name=theme.readEntry("table","casino_table_green");
98 odds_name=theme.readEntry("odds","casino_odds"); 102 odds_name=theme.readEntry("odds","casino_odds");
99 103
100 104
101 //the menu 105 //the menu
102 QMenuBar* menuBar = new QMenuBar(this); 106 QMenuBar* menuBar = new QMenuBar(this);
103 107
104 QPopupMenu* gamemenu= new QPopupMenu(this); 108 QPopupMenu* gamemenu= new QPopupMenu(this);
105 gamemenu->insertItem(tr( "New" ),this,SLOT(newgame())); 109 gamemenu->insertItem(tr( "New" ),this,SLOT(newgame()));
106 gamemenu->insertSeparator(); 110 gamemenu->insertSeparator();
107 gamemenu->insertItem(tr( "Load" ),this,SLOT(loadgame())); 111 gamemenu->insertItem(tr( "Load" ),this,SLOT(loadgame()));
108 gamemenu->insertItem(tr( "Save" ),this,SLOT(savegame())); 112 gamemenu->insertItem(tr( "Save" ),this,SLOT(savegame()));
109 gamemenu->insertSeparator(); 113 gamemenu->insertSeparator();
110 gamemenu->insertItem(tr( "Delete" ),this,SLOT(deletegame())); 114 gamemenu->insertItem(tr( "Delete" ),this,SLOT(deletegame()));
111 menuBar->insertItem(tr( "Game" ),gamemenu); 115 menuBar->insertItem(tr( "Game" ),gamemenu);
112 116
113 QPopupMenu* thememenu= new QPopupMenu(this); 117 QPopupMenu* thememenu= new QPopupMenu(this);
114 thememenu->insertItem(tr( "New" ),this,SLOT(newtheme())); 118 thememenu->insertItem(tr( "New" ),this,SLOT(newtheme()));
115 thememenu->insertSeparator(); 119 thememenu->insertSeparator();
116 thememenu->insertItem(tr( "Load"),this,SLOT(loadtheme())); 120 thememenu->insertItem(tr( "Load"),this,SLOT(loadtheme()));
117 thememenu->insertItem(tr( "Save" ),this,SLOT(savetheme())); 121 thememenu->insertItem(tr( "Save" ),this,SLOT(savetheme()));
118 thememenu->insertSeparator(); 122 thememenu->insertSeparator();
119 thememenu->insertItem(tr( "Default"),this,SLOT(themedefault())); 123 thememenu->insertItem(tr( "Default"),this,SLOT(themedefault()));
120 thememenu->insertItem(tr( "Delete" ),this,SLOT(deletetheme())); 124 thememenu->insertItem(tr( "Delete" ),this,SLOT(deletetheme()));
121 menuBar->insertItem(tr( "Theme" ),thememenu); 125 menuBar->insertItem(tr( "Theme" ),thememenu);
122 126
123 QPopupMenu* optionmenu=new QPopupMenu(this); 127 QPopupMenu* optionmenu=new QPopupMenu(this);
124 optionmenu->insertItem(tr( "Player" ),this,SLOT(playerselect())); 128 optionmenu->insertItem(tr( "Player" ),this,SLOT(playerselect()));
125 optionmenu->insertSeparator(); 129 optionmenu->insertSeparator();
126 optionmenu->insertItem(tr( "AI" ),this,SLOT(modify_AI())); 130 optionmenu->insertItem(tr( "AI" ),this,SLOT(modify_AI()));
127 optionmenu->insertItem(tr( "Rules" ),this,SLOT(setrules())); 131 optionmenu->insertItem(tr( "Rules" ),this,SLOT(setrules()));
128 menuBar->insertItem(tr( "Options"),optionmenu); 132 menuBar->insertItem(tr( "Options"),optionmenu);
129 133
130 QWidget* mainarea=new QWidget(this); 134 QWidget* mainarea=new QWidget(this);
131 setCentralWidget(mainarea); 135 setCentralWidget(mainarea);
132 //the main area 136 //the main area
133 QBoxLayout* layout=new QBoxLayout(mainarea,QBoxLayout::TopToBottom); 137 QBoxLayout* layout=new QBoxLayout(mainarea,QBoxLayout::TopToBottom);
134 area=new QCanvas(235,235); 138 area=new QCanvas(235,235);
135 boardview=new BackGammonView(area,mainarea); 139 boardview=new BackGammonView(area,mainarea);
136 boardview->setMaximumHeight(240); 140 boardview->setMaximumHeight(240);
137 layout->addWidget(boardview); 141 layout->addWidget(boardview);
138 connect(boardview,SIGNAL(mouse(int,int)),this,SLOT(mouse(int,int))); 142 connect(boardview,SIGNAL(mouse(int,int)),this,SLOT(mouse(int,int)));
139 //status bar 143 //status bar
140 message=new QLabel("<b>Backgammon</b>",mainarea); 144 message=new QLabel("<b>Backgammon</b>",mainarea);
141 message->setAlignment(AlignHCenter); 145 message->setAlignment(AlignHCenter);
142 layout->addWidget(message); 146 layout->addWidget(message);
143 147
144 //the marker 148 //the marker
145 marker_current=new QCanvasRectangle(area); 149 marker_current=new QCanvasRectangle(area);
146 marker_current->setBrush(QColor(0,0,255)); 150 marker_current->setBrush(QColor(0,0,255));
147 marker_current->setSize(15,5); 151 marker_current->setSize(15,5);
148 marker_current->setZ(1); 152 marker_current->setZ(1);
149 153
150 for(a=0;a<4;a++) 154 for(a=0;a<4;a++)
151 { 155 {
152 marker_next[a]=new QCanvasRectangle(area); 156 marker_next[a]=new QCanvasRectangle(area);
153 marker_next[a]->setBrush(QColor(0,255,0)); 157 marker_next[a]->setBrush(QColor(0,255,0));
154 marker_next[a]->setSize(15,5); 158 marker_next[a]->setSize(15,5);
155 marker_next[a]->setZ(1); 159 marker_next[a]->setZ(1);
156 } 160 }
157 161
158 connect(move,SIGNAL(done_dice1()),this,SLOT(done_dice1())); 162 connect(move,SIGNAL(done_dice1()),this,SLOT(done_dice1()));
159 connect(move,SIGNAL(done_dice2()),this,SLOT(done_dice2())); 163 connect(move,SIGNAL(done_dice2()),this,SLOT(done_dice2()));
160 connect(move,SIGNAL(done_dice3()),this,SLOT(done_dice3())); 164 connect(move,SIGNAL(done_dice3()),this,SLOT(done_dice3()));
161 connect(move,SIGNAL(done_dice4()),this,SLOT(done_dice4())); 165 connect(move,SIGNAL(done_dice4()),this,SLOT(done_dice4()));
162 connect(move,SIGNAL(nomove()),this,SLOT(nomove())); 166 connect(move,SIGNAL(nomove()),this,SLOT(nomove()));
163 connect(move,SIGNAL(player_finished(int)),this,SLOT(finished(int))); 167 connect(move,SIGNAL(player_finished(int)),this,SLOT(finished(int)));
164 168
165 //the pieces 169 //the pieces
166 p1=new CanvasImageItem*[15]; 170 p1=new CanvasImageItem*[15];
167 p1_side=new CanvasImageItem*[15]; 171 p1_side=new CanvasImageItem*[15];
168 QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name)); 172 QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name));
169 QImage piece_1_front=piece_1_all.copy(0,0,15,15); 173 QImage piece_1_front=piece_1_all.copy(0,0,15,15);
170 QImage piece_1_side=piece_1_all.copy(0,15,15,5); 174 QImage piece_1_side=piece_1_all.copy(0,15,15,5);
171 175
172 p2=new CanvasImageItem*[15]; 176 p2=new CanvasImageItem*[15];
173 p2_side=new CanvasImageItem*[15]; 177 p2_side=new CanvasImageItem*[15];
174 QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name)); 178 QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name));
175 QImage piece_2_front=piece_2_all.copy(0,0,15,15); 179 QImage piece_2_front=piece_2_all.copy(0,0,15,15);
176 QImage piece_2_side=piece_2_all.copy(0,15,15,5); 180 QImage piece_2_side=piece_2_all.copy(0,15,15,5);
177 181
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)
364 364
365int MoveEngine::getPossibleMoves() 365int MoveEngine::getPossibleMoves()
366{ 366{
367 int homezone[]={0,25,0}; 367 int homezone[]={0,25,0};
368 int lastToHomeZone=abs(last_piece[player]-homezone[player]); 368 int lastToHomeZone=abs(last_piece[player]-homezone[player]);
369 for(int field=0;field<26;field++) 369 for(int field=0;field<26;field++)
370 { 370 {
371 371
372 for(int b=0;b<4;b++) 372 for(int b=0;b<4;b++)
373 { 373 {
374 int dice_tmp=dice[b]; 374 int dice_tmp=dice[b];
375 if(dice[b]!=7 && dice[b]> lastToHomeZone) 375 if(dice[b]!=7 && dice[b]> lastToHomeZone)
376 dice_tmp=lastToHomeZone; 376 dice_tmp=lastToHomeZone;
377 377
378 int nextfield=(player==1) ? field+dice_tmp : field-dice_tmp; 378 int nextfield=(player==1) ? field+dice_tmp : field-dice_tmp;
379 379
380 if(nice_dice) 380 if(nice_dice)
381 { 381 {
382 if(player==1 && nextfield>homezone[1]) 382 if(player==1 && nextfield>homezone[1])
383 nextfield=homezone[1]; 383 nextfield=homezone[1];
384 else if(player==2 && nextfield<homezone[2]) 384 else if(player==2 && nextfield<homezone[2])
385 nextfield=homezone[2]; 385 nextfield=homezone[2];
386 } 386 }
387 387
388 moves[field].weight[b]=0; 388 moves[field].weight[b]=0;
389 moves[field].to[b]=nextfield; 389 moves[field].to[b]=nextfield;
390 390
391 int out_of_board[]={-1,0,25}; 391 int out_of_board[]={-1,0,25};
392 if(!move_with_pieces_out && field!=out_of_board[player] && pieces_out[player]) 392 if(!move_with_pieces_out && field!=out_of_board[player] && pieces_out[player])
393 { 393 {
394 continue; 394 continue;
395 } 395 }
396 396
397 397
398 398
399 if(dice[b]!=7 && fieldColor(field)==player ) //player can only move his own pieces 399 if(dice[b]!=7 && fieldColor(field)==player ) //player can only move his own pieces
400 { 400 {
401 if((player==1 && nextfield > homezone[1]) || (player==2 && nextfield < homezone[2])) 401 if((player==1 && nextfield > homezone[1]) || (player==2 && nextfield < homezone[2]))
402 { 402 {
403 moves[field].weight[b]=0; //movement would be far out of board 403 moves[field].weight[b]=0; //movement would be far out of board
404 } 404 }
405 else if(nextfield==homezone[player] && !allclear[player]) 405 else if(nextfield==homezone[player] && !allclear[player])
406 { 406 {
407 moves[field].weight[b]=0; //can not rescue pieces until all are in the endzone 407 moves[field].weight[b]=0; //can not rescue pieces until all are in the endzone
408 } 408 }
409 else if(nextfield==homezone[player] && allclear[player]) 409 else if(nextfield==homezone[player] && allclear[player])
410 { 410 {
411 moves[field].weight[b]=ai.rescue; //rescue your pieces : nuff said ;-) 411 moves[field].weight[b]=ai.rescue; //rescue your pieces : nuff said ;-)
412 } 412 }
413 else if(fieldColor(nextfield)==otherplayer) 413 else if(fieldColor(nextfield)==otherplayer)
414 { 414 {
415 if(abs(population[nextfield].total)>1) //can not move to this field 415 if(abs(population[nextfield].total)>1) //can not move to this field
416 moves[field].weight[b]=0; 416 moves[field].weight[b]=0;
417 else if(abs(population[nextfield].total)==1) //eliminate opponent : very nice 417 else if(abs(population[nextfield].total)==1) //eliminate opponent : very nice
418 moves[field].weight[b]=ai.eliminate; 418 moves[field].weight[b]=ai.eliminate;
419 } 419 }
420 else if(fieldColor(nextfield)==player) //nextfield already occupied by player 420 else if(fieldColor(nextfield)==player) //nextfield already occupied by player
421 { 421 {
422 if(abs(population[field].total)==2) //expose own piece : not diserable 422 if(abs(population[field].total)==2) //expose own piece : not diserable
423 moves[field].weight[b]=ai.expose; 423 moves[field].weight[b]=ai.expose;
424 else if(abs(population[nextfield].total)>1) //own pices already there : safe 424 else if(abs(population[nextfield].total)>1) //own pices already there : safe
425 moves[field].weight[b]=ai.safe; 425 moves[field].weight[b]=ai.safe;
426 else if(abs(population[nextfield].total)==1) //protect own piece : most importatnt 426 else if(abs(population[nextfield].total)==1) //protect own piece : most importatnt
427 moves[field].weight[b]=ai.protect; 427 moves[field].weight[b]=ai.protect;
428 } 428 }
429 else if(population[nextfield].total==0) //nextfield empty 429 else if(population[nextfield].total==0) //nextfield empty
430 { 430 {
431 if(abs(population[field].total)==2) //expose own piece : not diserable 431 if(abs(population[field].total)==2) //expose own piece : not diserable
432 moves[field].weight[b]=ai.expose; 432 moves[field].weight[b]=ai.expose;
433 else 433 else
434 moves[field].weight[b]=ai.empty; 434 moves[field].weight[b]=ai.empty;
435 } 435 }
436 else 436 else
437 moves[field].weight[b]=0; //default. 437 moves[field].weight[b]=0; //default.
438 } 438 }
439 439
440 440
441 441
442 else 442 else
443 moves[field].weight[b]=0; //dice already used or field not used by player 443 moves[field].weight[b]=0; //dice already used or field not used by player
444 } 444 }
445 445
446 446
447 447
448 } 448 }
449 449
450 int total=0; 450 int total=0;
451 for(int field=0;field<26;field++) 451 for(int field=0;field<26;field++)
452 { 452 {
453 total+=moves[field].weight[0]+moves[field].weight[1]+moves[field].weight[2]+moves[field].weight[3]; 453 total+=moves[field].weight[0]+moves[field].weight[1]+moves[field].weight[2]+moves[field].weight[3];
454 } 454 }
455 return total; 455 return total;
456} 456}
457 457
458void MoveEngine::move(const int& from, int to, const int& dice) 458void MoveEngine::move(const int& from, int to, const int& dice)
459{ 459{
460 //qDebug("%d moves from %d to %d (%d) with dice %d",player,from,to,to-from,dice); 460 //odebug << "" << player << " moves from " << from << " to " << to << " (" << to-from << ") with dice " << dice << "" << oendl;
461 461
462 if(player==1 && to==25) 462 if(player==1 && to==25)
463 to=26; 463 to=26;
464 if(player==2 && to==0) 464 if(player==2 && to==0)
465 to=27; 465 to=27;
466 466
467 //if space is occupied by enemy move pieces to startzone 467 //if space is occupied by enemy move pieces to startzone
468 if(fieldColor(to)==otherplayer) 468 if(fieldColor(to)==otherplayer)
469 { 469 {
470 population[to].total=0; 470 population[to].total=0;
471 if(otherplayer==1) 471 if(otherplayer==1)
472 population[0].total++; 472 population[0].total++;
473 else 473 else
474 population[25].total--; 474 population[25].total--;
475 } 475 }
476 476
477 if(player==1) 477 if(player==1)
478 { 478 {
479 population[from].total--; 479 population[from].total--;
480 population[to].total++; 480 population[to].total++;
481 } 481 }
482 else //player=2 482 else //player=2
483 { 483 {
484 population[from].total++; 484 population[from].total++;
485 population[to].total--; 485 population[to].total--;
486 } 486 }
487 487
488 if(dice==1) 488 if(dice==1)
489 emit done_dice1(); 489 emit done_dice1();
490 else if(dice==2) 490 else if(dice==2)
491 emit done_dice2(); 491 emit done_dice2();
492 else if(dice==3) 492 else if(dice==3)
493 emit done_dice3(); 493 emit done_dice3();
494 else 494 else
495 emit done_dice4(); 495 emit done_dice4();
496 496
497 if(abs(population[26].total)==15) 497 if(abs(population[26].total)==15)
498 emit player_finished(1); 498 emit player_finished(1);
499 if(abs(population[27].total)==15) 499 if(abs(population[27].total)==15)
500 emit player_finished(2); 500 emit player_finished(2);
501} 501}
502 502
503void MoveEngine::checkstate() 503void MoveEngine::checkstate()
504{ 504{
505 //check if pieces are out 505 //check if pieces are out
506 pieces_out[1]=(population[0].total>0) ? true : false; 506 pieces_out[1]=(population[0].total>0) ? true : false;
507 pieces_out[2]=(population[25].total<0) ? true : false; 507 pieces_out[2]=(population[25].total<0) ? true : false;
508 508
509 //check if all pieces are in the endzones 509 //check if all pieces are in the endzones
510 allclear[1]=true; 510 allclear[1]=true;
511 allclear[2]=true; 511 allclear[2]=true;
512 512
513 last_piece[1]=25; 513 last_piece[1]=25;
514 bool found_last_piece1=false; 514 bool found_last_piece1=false;
515 last_piece[2]=0; 515 last_piece[2]=0;
516 516
517 for(int a=0;a<26;a++) 517 for(int a=0;a<26;a++)
518 { 518 {
519 if(a<19 && population[a].total>0) 519 if(a<19 && population[a].total>0)
520 allclear[1]=false; 520 allclear[1]=false;
521 if(a>6 && population[a].total<0) 521 if(a>6 && population[a].total<0)
522 allclear[2]=false; 522 allclear[2]=false;
523 523
524 if(population[a].total>0 && !found_last_piece1) 524 if(population[a].total>0 && !found_last_piece1)
525 { 525 {
526 last_piece[1]=a; 526 last_piece[1]=a;
527 found_last_piece1=true; 527 found_last_piece1=true;
528 } 528 }
529 if(population[a].total<0) 529 if(population[a].total<0)
530 last_piece[2]=a; 530 last_piece[2]=a;
531 } 531 }
532} 532}
533 533
534void MoveEngine::nomarker(Marker& marker) 534void MoveEngine::nomarker(Marker& marker)
535{ 535{
536 marker.visible_current=false; 536 marker.visible_current=false;
537 marker_current=-1; 537 marker_current=-1;
538 for(int a=0;a<4;a++) 538 for(int a=0;a<4;a++)
539 { 539 {
540 marker.x_next[a]=0; 540 marker.x_next[a]=0;
541 marker.y_next[a]=0; 541 marker.y_next[a]=0;
542 marker_next[a]=-1; 542 marker_next[a]=-1;
543 marker.visible_next[a]=false; 543 marker.visible_next[a]=false;
544 } 544 }
545} 545}
546 546
547int MoveEngine::fieldColor(const int& index) const 547int MoveEngine::fieldColor(const int& index) const
548{ 548{
549 if(population[index].total>0) 549 if(population[index].total>0)
550 return 1; 550 return 1;
551 else if(population[index].total<0) 551 else if(population[index].total<0)
552 return 2; 552 return 2;
553 else 553 else
554 return 0; 554 return 0;
555} 555}
556 556
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 @@
1 #CONFIG = qt warn_on 1 CONFIG = qt warn_on quick-app
2 CONFIG = qt warn_on quick-app
3 HEADERS = game.h kbounce.h 2 HEADERS = game.h kbounce.h
4 SOURCES = game.cpp kbounce.cpp main.cpp 3 SOURCES = game.cpp kbounce.cpp main.cpp
5 INCLUDEPATH+= $(OPIEDIR)/include 4 INCLUDEPATH+= $(OPIEDIR)/include
6 DEPENDPATH+= $(OPIEDIR)/include 5 DEPENDPATH+= $(OPIEDIR)/include
7LIBS += -lqpe -lopiecore2 6LIBS += -lqpe -lopiecore2
8 TARGET = bounce 7 TARGET = bounce
9 8
10include ( $(OPIEDIR)/include.pro ) 9include ( $(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 @@
1/* 1/*
2 * Copyright (C) 2000 Stefan Schimanski <1Stein@gmx.de> 2 * Copyright (C) 2000 Stefan Schimanski <1Stein@gmx.de>
3 * 3 *
4 * This program is free software; you can redistribute it and/or 4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public 5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either 6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version. 7 * version 2 of the License, or (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details. 12 * Library General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU Library General Public 14 * You should have received a copy of the GNU Library General Public
15 * License along with this program; if not, write to the Free 15 * License along with this program; if not, write to the Free
16 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 16 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */ 17 */
18 18
19 19
20#include <stdlib.h> 20#include "game.h"
21#include <qtimer.h> 21
22/* OPIE */
23#include <opie2/odebug.h>
22#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
25using namespace Opie::Core;
23 26
24#include "game.h" 27/* QT */
28#include <qtimer.h>
29
30/* STD */
31#include <stdlib.h>
25 32
26#define TILE_SIZE 9 33#define TILE_SIZE 9
27 34
28#define TILE_FIRST ((FIELD_WIDTH-2)*(FIELD_HEIGHT-2)) 35#define TILE_FIRST ((FIELD_WIDTH-2)*(FIELD_HEIGHT-2))
29#define TILE_FREE (TILE_FIRST + 0) 36#define TILE_FREE (TILE_FIRST + 0)
30#define TILE_BORDER (TILE_FIRST + 1) 37#define TILE_BORDER (TILE_FIRST + 1)
31#define TILE_WALLEND (TILE_FIRST + 2) 38#define TILE_WALLEND (TILE_FIRST + 2)
32#define TILE_WALLUP (TILE_FIRST + 3) 39#define TILE_WALLUP (TILE_FIRST + 3)
33#define TILE_WALLDOWN (TILE_FIRST + 4) 40#define TILE_WALLDOWN (TILE_FIRST + 4)
34#define TILE_WALLLEFT (TILE_FIRST + 5) 41#define TILE_WALLLEFT (TILE_FIRST + 5)
35#define TILE_WALLRIGHT (TILE_FIRST + 6) 42#define TILE_WALLRIGHT (TILE_FIRST + 6)
36 43
37#define GAME_DELAY 15 44#define GAME_DELAY 15
38#define BALL_ANIM_DELAY 60 45#define BALL_ANIM_DELAY 60
39#define WALL_DELAY 100 46#define WALL_DELAY 100
40 47
41#define MS2TICKS( ms ) ((ms)/GAME_DELAY) 48#define MS2TICKS( ms ) ((ms)/GAME_DELAY)
42 49
43Arrow::Arrow(QCanvasPixmapArray* array, QCanvas* canvas) 50Arrow::Arrow(QCanvasPixmapArray* array, QCanvas* canvas)
44 : QCanvasSprite( array, canvas ) 51 : QCanvasSprite( array, canvas )
45{ 52{
46 m_vertical = true; 53 m_vertical = true;
47 move(3,3); 54 move(3,3);
48} 55}
49 56
50void Arrow::update() 57void Arrow::update()
51{ 58{
52 if ( m_vertical ) 59 if ( m_vertical )
53 setFrame( 0 ); 60 setFrame( 0 );
54 else 61 else
55 setFrame( 1 ); 62 setFrame( 1 );
56} 63}
57 64
58void Arrow::changeDirection() 65void Arrow::changeDirection()
59{ 66{
60 m_vertical = ! m_vertical; 67 m_vertical = ! m_vertical;
61 update(); 68 update();
62} 69}
63 70
64 71
65Ball::Ball(QCanvasPixmapArray* array, QCanvas* canvas) 72Ball::Ball(QCanvasPixmapArray* array, QCanvas* canvas)
66 : QCanvasSprite( array, canvas ), m_animDelay( 0 ), m_soundDelay( MS2TICKS(BALL_ANIM_DELAY)/2 ) 73 : QCanvasSprite( array, canvas ), m_animDelay( 0 ), m_soundDelay( MS2TICKS(BALL_ANIM_DELAY)/2 )
67{ 74{
68} 75}
69 76
70void Ball::update() 77void Ball::update()
71{ 78{
72 m_animDelay--; 79 m_animDelay--;
73 if ( m_animDelay<=0 ) 80 if ( m_animDelay<=0 )
74 { 81 {
75 m_animDelay = MS2TICKS(BALL_ANIM_DELAY); 82 m_animDelay = MS2TICKS(BALL_ANIM_DELAY);
76 int frameNum = frame(); 83 int frameNum = frame();
77 frameNum++; 84 frameNum++;
78 if ( frameNum>=frameCount() ) 85 if ( frameNum>=frameCount() )
79 frameNum = 0; 86 frameNum = 0;
80 setFrame( frameNum ); 87 setFrame( frameNum );
81 } 88 }
82} 89}
83 90
84void Ball::advance(int stage) 91void Ball::advance(int stage)
85{ 92{
86 bool reflectX = false; 93 bool reflectX = false;
87 bool reflectY = false; 94 bool reflectY = false;
88 95
89 // check for collisions 96 // check for collisions
90 if ( collide(xVelocity(), 0) ) reflectX = true; 97 if ( collide(xVelocity(), 0) ) reflectX = true;
91 if ( collide(0, yVelocity()) ) reflectY = true; 98 if ( collide(0, yVelocity()) ) reflectY = true;
92 if ( !reflectX && !reflectY && collide(xVelocity(), yVelocity()) ) reflectX = reflectY = true; 99 if ( !reflectX && !reflectY && collide(xVelocity(), yVelocity()) ) reflectX = reflectY = true;
93 100
94 // emit collision 101 // emit collision
95 QRect r = boundingRect(); 102 QRect r = boundingRect();
96 r.moveBy( xVelocity(), yVelocity() ); 103 r.moveBy( xVelocity(), yVelocity() );
97 JezzField* field = (JezzField *)canvas(); 104 JezzField* field = (JezzField *)canvas();
98 105
99 int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE ); 106 int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE );
100 int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE ); 107 int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE );
101 int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE ); 108 int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE );
102 int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE ); 109 int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE );
103 110
104 if ( ul!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.top() / TILE_SIZE, ul ); else 111 if ( ul!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.top() / TILE_SIZE, ul ); else
105 if ( ur!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.top() / TILE_SIZE, ur ); else 112 if ( ur!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.top() / TILE_SIZE, ur ); else
106 if ( bl!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.bottom() / TILE_SIZE, bl ); else 113 if ( bl!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.bottom() / TILE_SIZE, bl ); else
107 if ( br!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.bottom() / TILE_SIZE, br ); 114 if ( br!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.bottom() / TILE_SIZE, br );
108 115
109 // apply reflection 116 // apply reflection
110 if ( reflectX ) setXVelocity( -xVelocity() ); 117 if ( reflectX ) setXVelocity( -xVelocity() );
111 if ( reflectY ) setYVelocity( -yVelocity() ); 118 if ( reflectY ) setYVelocity( -yVelocity() );
112 119
113 // update field 120 // update field
114 update(); 121 update();
115 QCanvasSprite::advance( stage ); 122 QCanvasSprite::advance( stage );
116} 123}
117 124
118bool Ball::collide( double dx, double dy ) 125bool Ball::collide( double dx, double dy )
119{ 126{
120 QRect r = boundingRect(); 127 QRect r = boundingRect();
@@ -274,193 +281,193 @@ void JezzView::viewportMouseReleaseEvent( QMouseEvent *ev )
274} 281}
275 282
276void JezzView::changeCursor() 283void JezzView::changeCursor()
277{ 284{
278 m_vertical = !m_vertical; 285 m_vertical = !m_vertical;
279 if ( m_vertical ) 286 if ( m_vertical )
280 { 287 {
281 setCursor( sizeVerCursor ); 288 setCursor( sizeVerCursor );
282 } 289 }
283 else 290 else
284 { 291 {
285 setCursor( sizeHorCursor ); 292 setCursor( sizeHorCursor );
286 } 293 }
287} 294}
288 295
289/*************************************************************************/ 296/*************************************************************************/
290 297
291JezzGame::JezzGame( int ballNum, QWidget *parent, const char *name ) 298JezzGame::JezzGame( int ballNum, QWidget *parent, const char *name )
292 : QWidget( parent, name ), m_wall1( 0 ), m_wall2( 0 ), 299 : QWidget( parent, name ), m_wall1( 0 ), m_wall2( 0 ),
293 m_text( 0 ), m_running( false ), m_percent( 0 ), m_pictured( false ) 300 m_text( 0 ), m_running( false ), m_percent( 0 ), m_pictured( false )
294{ 301{
295 QString path = QPEApplication::qpeDir()+"pics/bounce/"; 302 QString path = QPEApplication::qpeDir()+"pics/bounce/";
296 303
297 // load gfx 304 // load gfx
298 m_ballPixmaps = new QCanvasPixmapArray( path + "ball%1.png", 25 ); 305 m_ballPixmaps = new QCanvasPixmapArray( path + "ball%1.png", 25 );
299 for ( unsigned n=0; n < m_ballPixmaps->count(); n++ ) 306 for ( unsigned n=0; n < m_ballPixmaps->count(); n++ )
300 m_ballPixmaps->image(n)->setOffset( 0, 0 ); 307 m_ballPixmaps->image(n)->setOffset( 0, 0 );
301 308
302 m_arrowPixmaps = new QCanvasPixmapArray( path + "arrow%1.png", 2 ); 309 m_arrowPixmaps = new QCanvasPixmapArray( path + "arrow%1.png", 2 );
303 for ( unsigned n=0; n < m_arrowPixmaps->count(); n++ ) 310 for ( unsigned n=0; n < m_arrowPixmaps->count(); n++ )
304 m_arrowPixmaps->image(n)->setOffset( 0, 0 ); 311 m_arrowPixmaps->image(n)->setOffset( 0, 0 );
305 312
306 QPixmap tiles( path + "tiles.png" ); 313 QPixmap tiles( path + "tiles.png" );
307 314
308 // create field 315 // create field
309 m_field = new JezzField( tiles, this, "m_field" ); 316 m_field = new JezzField( tiles, this, "m_field" );
310 m_field->resize( TILE_SIZE*FIELD_WIDTH, TILE_SIZE*FIELD_HEIGHT ); 317 m_field->resize( TILE_SIZE*FIELD_WIDTH, TILE_SIZE*FIELD_HEIGHT );
311 318
312 for ( int x=0; x<FIELD_WIDTH; x++ ) 319 for ( int x=0; x<FIELD_WIDTH; x++ )
313 m_field->setTile( x, 0, TILE_BORDER ); 320 m_field->setTile( x, 0, TILE_BORDER );
314 for ( int y=1; y<FIELD_HEIGHT-1; y++ ) 321 for ( int y=1; y<FIELD_HEIGHT-1; y++ )
315 { 322 {
316 m_field->setTile( 0, y, TILE_BORDER ); 323 m_field->setTile( 0, y, TILE_BORDER );
317 for ( int x=1; x<FIELD_WIDTH-1; x++ ) 324 for ( int x=1; x<FIELD_WIDTH-1; x++ )
318 m_field->setTile( x, y, TILE_FREE ); 325 m_field->setTile( x, y, TILE_FREE );
319 m_field->setTile( FIELD_WIDTH-1, y, TILE_BORDER ); 326 m_field->setTile( FIELD_WIDTH-1, y, TILE_BORDER );
320 } 327 }
321 for ( int x=0; x<FIELD_WIDTH; x++ ) 328 for ( int x=0; x<FIELD_WIDTH; x++ )
322 m_field->setTile( x, FIELD_HEIGHT-1, TILE_BORDER ); 329 m_field->setTile( x, FIELD_HEIGHT-1, TILE_BORDER );
323 330
324 connect( m_field, SIGNAL(ballCollision(Ball*,int,int,int)), this, SLOT(ballCollision(Ball*,int,int,int)) ); 331 connect( m_field, SIGNAL(ballCollision(Ball*,int,int,int)), this, SLOT(ballCollision(Ball*,int,int,int)) );
325 332
326 // create view 333 // create view
327 m_view = new JezzView( m_field, this, "m_view" ); 334 m_view = new JezzView( m_field, this, "m_view" );
328 m_view->move( 0, 0 ); 335 m_view->move( 0, 0 );
329 m_view->adjustSize(); 336 m_view->adjustSize();
330 connect( m_view, SIGNAL(buildWall(int,int,bool)), this, SLOT(buildWall(int,int,bool)) ); 337 connect( m_view, SIGNAL(buildWall(int,int,bool)), this, SLOT(buildWall(int,int,bool)) );
331 338
332 // create balls 339 // create balls
333 for ( int n=0; n<ballNum; n++ ) 340 for ( int n=0; n<ballNum; n++ )
334 { 341 {
335 Ball *ball = new Ball( m_ballPixmaps, m_field ); 342 Ball *ball = new Ball( m_ballPixmaps, m_field );
336 m_balls.append( ball ); 343 m_balls.append( ball );
337 ball->setVelocity( ((rand() & 1)*2-1)*2, ((rand() & 1)*2-1)*2 ); 344 ball->setVelocity( ((rand() & 1)*2-1)*2, ((rand() & 1)*2-1)*2 );
338 ball->setFrame( rand() % 25 ); 345 ball->setFrame( rand() % 25 );
339 ball->move( 4*TILE_SIZE + ( rand() - 50 ) % ( (FIELD_WIDTH-8)*TILE_SIZE ), 346 ball->move( 4*TILE_SIZE + ( rand() - 50 ) % ( (FIELD_WIDTH-8)*TILE_SIZE ),
340 4*TILE_SIZE + rand() % ( (FIELD_HEIGHT-8)*TILE_SIZE ) ); 347 4*TILE_SIZE + rand() % ( (FIELD_HEIGHT-8)*TILE_SIZE ) );
341 ball->show(); 348 ball->show();
342 } 349 }
343 350
344 // create arrow 351 // create arrow
345 arrow = new Arrow( m_arrowPixmaps, m_field ); 352 arrow = new Arrow( m_arrowPixmaps, m_field );
346 arrow->show(); 353 arrow->show();
347 354
348 // create text label 355 // create text label
349 m_text = new QCanvasText( m_field ); 356 m_text = new QCanvasText( m_field );
350 357
351 // create game clock 358 // create game clock
352 m_clock = new QTimer( this ); 359 m_clock = new QTimer( this );
353 connect( m_clock, SIGNAL(timeout()), this, SLOT(tick()) ); 360 connect( m_clock, SIGNAL(timeout()), this, SLOT(tick()) );
354 m_clock->start( GAME_DELAY ); 361 m_clock->start( GAME_DELAY );
355 362
356 // setup geometry 363 // setup geometry
357 setFixedSize( m_view->size() ); 364 setFixedSize( m_view->size() );
358} 365}
359 366
360JezzGame::~JezzGame() 367JezzGame::~JezzGame()
361{ 368{
362 m_balls.clear(); 369 m_balls.clear();
363 delete m_view; 370 delete m_view;
364 delete m_field; 371 delete m_field;
365 delete m_ballPixmaps; 372 delete m_ballPixmaps;
366} 373}
367 374
368void JezzGame::display( QString text, int size ) 375void JezzGame::display( QString text, int size )
369{ 376{
370 qDebug("This function \"display\" shouldn't be called!!!"); 377 odebug << "This function \"display\" shouldn't be called!!!" << oendl;
371 if ( !text.isEmpty() ) 378 if ( !text.isEmpty() )
372 { 379 {
373 QFont font( "Helvetica", size, QFont::Bold ); 380 QFont font( "Helvetica", size, QFont::Bold );
374 font.setStyleHint( QFont::Helvetica ); 381 font.setStyleHint( QFont::Helvetica );
375 m_text->setFont( font ); 382 m_text->setFont( font );
376 m_text->setText( text ); 383 m_text->setText( text );
377 384
378 QRect size = m_text->boundingRect(); 385 QRect size = m_text->boundingRect();
379 m_text->move( ( FIELD_WIDTH*TILE_SIZE - size.width() ) / 2, 386 m_text->move( ( FIELD_WIDTH*TILE_SIZE - size.width() ) / 2,
380 ( FIELD_HEIGHT*TILE_SIZE - size.height() ) / 2 ); 387 ( FIELD_HEIGHT*TILE_SIZE - size.height() ) / 2 );
381 388
382 m_text->show(); 389 m_text->show();
383 } else 390 } else
384 { 391 {
385 m_text->hide(); 392 m_text->hide();
386 } 393 }
387} 394}
388 395
389void JezzGame::start() 396void JezzGame::start()
390{ 397{
391 m_running = true; 398 m_running = true;
392} 399}
393 400
394void JezzGame::stop() 401void JezzGame::stop()
395{ 402{
396 m_running = false; 403 m_running = false;
397} 404}
398 405
399 406
400void JezzGame::makeBlack() 407void JezzGame::makeBlack()
401{ 408{
402 // copy current field into buffer 409 // copy current field into buffer
403 for ( int y=0; y<FIELD_HEIGHT; y++ ) 410 for ( int y=0; y<FIELD_HEIGHT; y++ )
404 for ( int x=0; x<FIELD_WIDTH; x++ ) 411 for ( int x=0; x<FIELD_WIDTH; x++ )
405 m_buf[x][y] = m_field->tile( x, y ); 412 m_buf[x][y] = m_field->tile( x, y );
406 413
407 // fill areas that contains a ball 414 // fill areas that contains a ball
408 for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() ) 415 for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() )
409 fill( ball->x()/TILE_SIZE, ball->y()/TILE_SIZE ); 416 fill( ball->x()/TILE_SIZE, ball->y()/TILE_SIZE );
410 417
411 // areas still free can be blacked now 418 // areas still free can be blacked now
412 for ( int y=0; y<FIELD_HEIGHT; y++ ) 419 for ( int y=0; y<FIELD_HEIGHT; y++ )
413 for ( int x=0; x<FIELD_WIDTH; x++ ) 420 for ( int x=0; x<FIELD_WIDTH; x++ )
414 { 421 {
415 if ( m_buf[x][y]==TILE_FREE ) 422 if ( m_buf[x][y]==TILE_FREE )
416 m_field->setGameTile( x, y, true ); 423 m_field->setGameTile( x, y, true );
417 } 424 }
418 425
419 m_field->update(); 426 m_field->update();
420 m_view->repaint(); 427 m_view->repaint();
421 428
422 // count percent value of occupied area 429 // count percent value of occupied area
423 int p = percent(); 430 int p = percent();
424 if ( p!=m_percent ) 431 if ( p!=m_percent )
425 { 432 {
426 m_percent = p; 433 m_percent = p;
427 emit newPercent( m_percent ); 434 emit newPercent( m_percent );
428 } 435 }
429} 436}
430 437
431int JezzGame::percent() 438int JezzGame::percent()
432{ 439{
433 int notFree = 0; 440 int notFree = 0;
434 for ( int y=1; y<FIELD_HEIGHT-1; y++ ) 441 for ( int y=1; y<FIELD_HEIGHT-1; y++ )
435 for ( int x=1; x<FIELD_WIDTH-1; x++ ) 442 for ( int x=1; x<FIELD_WIDTH-1; x++ )
436 { 443 {
437 if ( m_field->tile(x,y)!=TILE_FREE ) 444 if ( m_field->tile(x,y)!=TILE_FREE )
438 notFree++; 445 notFree++;
439 } 446 }
440 447
441 return 100 * notFree / ( (FIELD_WIDTH-1) * (FIELD_HEIGHT-1) ); 448 return 100 * notFree / ( (FIELD_WIDTH-1) * (FIELD_HEIGHT-1) );
442} 449}
443 450
444void JezzGame::fill( int x, int y ) 451void JezzGame::fill( int x, int y )
445{ 452{
446 if ( m_buf[x][y]!=TILE_FREE) return; 453 if ( m_buf[x][y]!=TILE_FREE) return;
447 454
448 // go left 455 // go left
449 int _x=x; 456 int _x=x;
450 for ( ; m_buf[_x][y]==TILE_FREE; _x-- ) 457 for ( ; m_buf[_x][y]==TILE_FREE; _x-- )
451 m_buf[_x][y] = TILE_BORDER; 458 m_buf[_x][y] = TILE_BORDER;
452 int stopx = _x; 459 int stopx = _x;
453 460
454 // fill above 461 // fill above
455 for ( _x=x; _x>stopx; _x-- ) 462 for ( _x=x; _x>stopx; _x-- )
456 if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 ); 463 if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 );
457 464
458 // fill below 465 // fill below
459 for ( _x=x; _x>stopx; _x-- ) 466 for ( _x=x; _x>stopx; _x-- )
460 if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 ); 467 if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 );
461 468
462 // go right 469 // go right
463 for ( _x=x+1; m_buf[_x][y]==TILE_FREE; _x++ ) 470 for ( _x=x+1; m_buf[_x][y]==TILE_FREE; _x++ )
464 m_buf[_x][y] = TILE_BORDER; 471 m_buf[_x][y] = TILE_BORDER;
465 stopx = _x; 472 stopx = _x;
466 473
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 @@
1 CONFIG = qt warn_on quick-app 1 CONFIG = qt warn_on quick-app
2 HEADERS = amigo.h \ 2 HEADERS = amigo.h \
3 go.h \ 3 go.h \
4 goplayutils.h \ 4 goplayutils.h \
5 gowidget.h 5 gowidget.h
6 SOURCES = amigo.c \ 6 SOURCES = amigo.c \
7 goplayer.c \ 7 goplayer.c \
8 goplayutils.c \ 8 goplayutils.c \
9 killable.c \ 9 killable.c \
10 gowidget.cpp \ 10 gowidget.cpp \
11 main.cpp 11 main.cpp
12INCLUDEPATH += $(OPIEDIR)/include 12INCLUDEPATH += $(OPIEDIR)/include
13 DEPENDPATH+= $(OPIEDIR)/include 13 DEPENDPATH+= $(OPIEDIR)/include
14LIBS += -lqpe -lopiecore2 14LIBS += -lqpe -lopiecore2
15 TARGET = go 15 TARGET = go
16 16
17 17
18
19include ( $(OPIEDIR)/include.pro ) 18include ( $(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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include "gowidget.h" 21#include "gowidget.h"
22 22
23/* OPIE */
24#include <opie2/odebug.h>
23#include <qpe/config.h> 25#include <qpe/config.h>
24#include <qpe/resource.h> 26#include <qpe/resource.h>
27using namespace Opie::Core;
25 28
29/* QT */
26#include <qpainter.h> 30#include <qpainter.h>
27#include <qtoolbar.h> 31#include <qtoolbar.h>
28#include <qmenubar.h> 32#include <qmenubar.h>
29#include <qaction.h> 33#include <qaction.h>
30#include <qapplication.h> //processEvents() 34#include <qapplication.h> //processEvents()
31#include <qlabel.h> 35#include <qlabel.h>
32 36
33//#include <stdio.h>
34
35
36static const enum bVal computer_color = BLACK; 37static const enum bVal computer_color = BLACK;
37 38
38static int current_handicap = 1; 39static int current_handicap = 1;
39 40
40static QBrush *goBrush; 41static QBrush *goBrush;
41//static QImage *newBlackStone; 42//static QImage *newBlackStone;
42//static QImage *blackStone; 43//static QImage *blackStone;
43//static QImage *whiteStone; 44//static QImage *whiteStone;
44static QPixmap *newBlackStone; 45static QPixmap *newBlackStone;
45static QPixmap *blackStone; 46static QPixmap *blackStone;
46static QPixmap *whiteStone; 47static QPixmap *whiteStone;
47 48
48static bool smallStones = FALSE; 49static bool smallStones = FALSE;
49 50
50GoMainWidget::GoMainWidget( QWidget *parent, const char* name, WFlags fl) : 51GoMainWidget::GoMainWidget( QWidget *parent, const char* name, WFlags fl) :
51 QMainWindow( parent, name, fl ) 52 QMainWindow( parent, name, fl )
52{ 53{
53 setToolBarsMovable( FALSE ); 54 setToolBarsMovable( FALSE );
54 GoWidget *go = new GoWidget(this); 55 GoWidget *go = new GoWidget(this);
55 56
56 setCentralWidget(go); 57 setCentralWidget(go);
57 toolbar = new QToolBar(this); 58 toolbar = new QToolBar(this);
58 toolbar->setHorizontalStretchable( TRUE ); 59 toolbar->setHorizontalStretchable( TRUE );
59 addToolBar(toolbar); 60 addToolBar(toolbar);
60 61
61 QMenuBar *mb = new QMenuBar( toolbar ); 62 QMenuBar *mb = new QMenuBar( toolbar );
62 mb->setMargin(0); 63 mb->setMargin(0);
63 QPopupMenu *file = new QPopupMenu( this ); 64 QPopupMenu *file = new QPopupMenu( this );
64 65
65 QAction *a = new QAction( tr( "New Game" ), QString::null, 0, this, 0 ); 66 QAction *a = new QAction( tr( "New Game" ), QString::null, 0, this, 0 );
66 connect( a, SIGNAL( activated() ), go, SLOT( newGame() ) ); 67 connect( a, SIGNAL( activated() ), go, SLOT( newGame() ) );
67 a->addTo( file ); 68 a->addTo( file );
68 69
69 a = new QAction( tr( "Pass" ), Resource::loadPixmap( "pass" ), QString::null, 0, this, 0 ); 70 a = new QAction( tr( "Pass" ), Resource::loadPixmap( "pass" ), QString::null, 0, this, 0 );
70 connect( a, SIGNAL( activated() ), go, SLOT( pass() ) ); 71 connect( a, SIGNAL( activated() ), go, SLOT( pass() ) );
71 a->addTo( file ); 72 a->addTo( file );
72 a->addTo( toolbar ); 73 a->addTo( toolbar );
73 74
74 75
75 a = new QAction( tr( "Resign" ), Resource::loadPixmap( "reset" ), QString::null, 0, this, 0 ); 76 a = new QAction( tr( "Resign" ), Resource::loadPixmap( "reset" ), QString::null, 0, this, 0 );
76 connect( a, SIGNAL( activated() ), go, SLOT( resign() ) ); 77 connect( a, SIGNAL( activated() ), go, SLOT( resign() ) );
77 a->addTo( file ); 78 a->addTo( file );
78 79
79 a = new QAction( tr( "Two player option" ), QString::null, 0, this, 0 ); 80 a = new QAction( tr( "Two player option" ), QString::null, 0, this, 0 );
80 a->setToggleAction( TRUE ); 81 a->setToggleAction( TRUE );
81 connect( a, SIGNAL( toggled(bool) ), go, SLOT( setTwoplayer(bool) ) ); 82 connect( a, SIGNAL( toggled(bool) ), go, SLOT( setTwoplayer(bool) ) );
82 a->addTo( file ); 83 a->addTo( file );
83 84
84 mb->insertItem( tr( "Game" ), file ); 85 mb->insertItem( tr( "Game" ), file );
85 86
86 QLabel *turnLabel = new QLabel( toolbar ); 87 QLabel *turnLabel = new QLabel( toolbar );
87 turnLabel->setBackgroundMode( PaletteButton ); 88 turnLabel->setBackgroundMode( PaletteButton );
88 connect( go, SIGNAL(showTurn(const QPixmap&)), 89 connect( go, SIGNAL(showTurn(const QPixmap&)),
89 turnLabel, SLOT(setPixmap(const QPixmap&)) ); 90 turnLabel, SLOT(setPixmap(const QPixmap&)) );
90 91
91 92
92 QLabel * scoreLabel = new QLabel( toolbar ); 93 QLabel * scoreLabel = new QLabel( toolbar );
93 scoreLabel->setBackgroundMode( PaletteButton ); 94 scoreLabel->setBackgroundMode( PaletteButton );
94 connect( go, SIGNAL(showScore(const QString&)), 95 connect( go, SIGNAL(showScore(const QString&)),
95 scoreLabel, SLOT(setText(const QString&)) ); 96 scoreLabel, SLOT(setText(const QString&)) );
96 97
97 toolbar->setStretchableWidget( scoreLabel ); 98 toolbar->setStretchableWidget( scoreLabel );
98 99
99 go->readConfig(); 100 go->readConfig();
100} 101}
101 102
102void GoMainWidget::resizeEvent( QResizeEvent * ) 103void GoMainWidget::resizeEvent( QResizeEvent * )
103{ 104{
104 //### this won't work because of the text label... 105 //### this won't work because of the text label...
105 /* 106 /*
106 if ( width() > height() ) 107 if ( width() > height() )
107 moveToolBar( toolbar, Left ); 108 moveToolBar( toolbar, Left );
108 else 109 else
109 moveToolBar( toolbar, Top ); 110 moveToolBar( toolbar, Top );
110 */ 111 */
111} 112}
112 113
113GoWidget *GoWidget::self = 0; 114GoWidget *GoWidget::self = 0;
114 115
115GoWidget::GoWidget( QWidget *parent, const char* name) : 116GoWidget::GoWidget( QWidget *parent, const char* name) :
116 QWidget( parent, name ) 117 QWidget( parent, name )
117{ 118{
118 if ( self ) 119 if ( self )
119 fatal( "Only one Go widget allowed" ); 120 fatal( "Only one Go widget allowed" );
120 self = this; 121 self = this;
121 twoplayer = FALSE; 122 twoplayer = FALSE;
122 123
123 124
124 d = bx = by = 1; 125 d = bx = by = 1;
125 126
126 QPixmap pix = Resource::loadPixmap( "go/pine" ); 127 QPixmap pix = Resource::loadPixmap( "go/pine" );
127 goBrush = new QBrush( black, pix ); 128 goBrush = new QBrush( black, pix );
128 /* 129 /*
129 QString fn = Resource::findPixmap("Go-black"); 130 QString fn = Resource::findPixmap("Go-black");
130 blackStone = new QImage( fn ); 131 blackStone = new QImage( fn );
131 fn = Resource::findPixmap("Go-black-highlight"); 132 fn = Resource::findPixmap("Go-black-highlight");
@@ -355,106 +356,106 @@ void GoWidget::doComputerMove()
355 } 356 }
356} 357}
357 358
358void GoWidget::mousePressEvent( QMouseEvent *me ) 359void GoWidget::mousePressEvent( QMouseEvent *me )
359{ 360{
360 if ( !gameActive ) 361 if ( !gameActive )
361 return; 362 return;
362 int x = x2board(me->x()); 363 int x = x2board(me->x());
363 int y = y2board(me->y()); 364 int y = y2board(me->y());
364 showStone(x,y,currentPlayer); 365 showStone(x,y,currentPlayer);
365} 366}
366 367
367void GoWidget::mouseMoveEvent( QMouseEvent *me ) 368void GoWidget::mouseMoveEvent( QMouseEvent *me )
368{ 369{
369 if ( !gameActive ) 370 if ( !gameActive )
370 return; 371 return;
371 int x = x2board(me->x()); 372 int x = x2board(me->x());
372 int y = y2board(me->y()); 373 int y = y2board(me->y());
373 if ( x != newX || y != newY ) 374 if ( x != newX || y != newY )
374 showStone(x,y,currentPlayer); 375 showStone(x,y,currentPlayer);
375} 376}
376 377
377void GoWidget::showStone( int x, int y, enum bVal c ) 378void GoWidget::showStone( int x, int y, enum bVal c )
378{ 379{
379 380
380 if ( newX > -1 ) { 381 if ( newX > -1 ) {
381 refresh( newX, newY ); 382 refresh( newX, newY );
382 newY = newX = -1; 383 newY = newX = -1;
383 } 384 }
384 if ( x < 0 || x > 18 || y < 0 || y > 18 ) { 385 if ( x < 0 || x > 18 || y < 0 || y > 18 ) {
385 newX = newY = -1; 386 newX = newY = -1;
386 return; 387 return;
387 } 388 }
388 if ( board[x][y] == -1 && !Suicide( c, x, y ) ) { 389 if ( board[x][y] == -1 && !Suicide( c, x, y ) ) {
389 newX = x; 390 newX = x;
390 newY = y; 391 newY = y;
391 refresh(x,y); 392 refresh(x,y);
392 } 393 }
393 394
394} 395}
395 396
396void GoWidget::mouseReleaseEvent( QMouseEvent * ) 397void GoWidget::mouseReleaseEvent( QMouseEvent * )
397{ 398{
398 if ( gameActive && newX > -1 ) 399 if ( gameActive && newX > -1 )
399 doMove( newX, newY ); 400 doMove( newX, newY );
400 newX = newY = -1; 401 newX = newY = -1;
401} 402}
402 403
403void GoWidget::refresh( int x, int y ) 404void GoWidget::refresh( int x, int y )
404{ 405{
405 update( bx+d*x-d/2-1, by+d*y-d/2-1, d+2, d+2 ); 406 update( bx+d*x-d/2-1, by+d*y-d/2-1, d+2, d+2 );
406} 407}
407 408
408void GoWidget::removeStone(short x, short y) 409void GoWidget::removeStone(short x, short y)
409{ 410{
410 board[x][y]=-1; 411 board[x][y]=-1;
411 refresh( x, y ); 412 refresh( x, y );
412} 413}
413 414
414void GoWidget::placeStone (enum bVal c, short x, short y ) 415void GoWidget::placeStone (enum bVal c, short x, short y )
415{ 416{
416 board[x][y]=c; 417 board[x][y]=c;
417 refresh( x, y ); 418 refresh( x, y );
418} 419}
419 420
420void GoWidget::reportPrisoners( int blackcnt, int whitecnt ) 421void GoWidget::reportPrisoners( int blackcnt, int whitecnt )
421{ 422{
422 QString s = tr( "Prisoners: black %1, white %2" ).arg(blackcnt).arg(whitecnt); 423 QString s = tr( "Prisoners: black %1, white %2" ).arg(blackcnt).arg(whitecnt);
423 emit showScore( s ); 424 emit showScore( s );
424} 425}
425 426
426void GoWidget::setTwoplayer( bool b ) 427void GoWidget::setTwoplayer( bool b )
427{ 428{
428 twoplayer = b; 429 twoplayer = b;
429} 430}
430 431
431void GoWidget::setHandicap( int h ) 432void GoWidget::setHandicap( int h )
432{ 433{
433 current_handicap = h; 434 current_handicap = h;
434} 435}
435 436
436 437
437extern "C" { 438extern "C" {
438 439
439 voidremovestone(short x, short y) 440 voidremovestone(short x, short y)
440{ 441{
441 GoWidget::self->removeStone(x,y); 442 GoWidget::self->removeStone(x,y);
442} 443}
443 444
444 voidplacestone (enum bVal c, short x, short y ) 445 voidplacestone (enum bVal c, short x, short y )
445{ 446{
446 GoWidget::self->placeStone(c,x,y); 447 GoWidget::self->placeStone(c,x,y);
447} 448}
448 449
449 voidintrMoveReport(enum bVal c ,char *coord ,char *reason ) 450 voidintrMoveReport(enum bVal c ,char *coord ,char *reason )
450{ 451{
451 qDebug( "intrMoveReport colour %d, %s %s", c, coord, reason ); 452 odebug << "intrMoveReport colour " << c << ", " << coord << " " << reason << "" << oendl;
452} 453}
453 454
454 voidintrPrisonerReport( short blackcnt, short whitecnt ) 455 voidintrPrisonerReport( short blackcnt, short whitecnt )
455{ 456{
456 GoWidget::self->reportPrisoners(blackcnt,whitecnt); 457 GoWidget::self->reportPrisoners(blackcnt,whitecnt);
457} 458}
458 459
459} 460}
460 461
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 @@
1 TEMPLATE= app 1 TEMPLATE= app
2 #CONFIG = qt warn_on
3 CONFIG = qt warn_on 2 CONFIG = qt warn_on
4 #TMAKE_CXXFLAGS+=
5 HEADERS = kpacmanwidget.h \ 3 HEADERS = kpacmanwidget.h \
6 referee.h \ 4 referee.h \
7 status.h \ 5 status.h \
8 painter.h \ 6 painter.h \
9 score.h \ 7 score.h \
10 pacman.h \ 8 pacman.h \
11 monster.h \ 9 monster.h \
12 keys.h \ 10 keys.h \
13 fruit.h \ 11 fruit.h \
14 energizer.h \ 12 energizer.h \
15 board.h \ 13 board.h \
16 bitfont.h \ 14 bitfont.h \
17 kpacman.h \ 15 kpacman.h \
18 bitmaps.h \ 16 bitmaps.h \
19 colors.h \ 17 colors.h \
20 portable.h 18 portable.h
21 SOURCES = kpacmanwidget.cpp \ 19 SOURCES = kpacmanwidget.cpp \
22 referee.cpp \ 20 referee.cpp \
23 status.cpp \ 21 status.cpp \
24 painter.cpp \ 22 painter.cpp \
25 score.cpp \ 23 score.cpp \
26 pacman.cpp \ 24 pacman.cpp \
27 monster.cpp \ 25 monster.cpp \
28 keys.cpp \ 26 keys.cpp \
29 fruit.cpp \ 27 fruit.cpp \
30 energizer.cpp \ 28 energizer.cpp \
31 board.cpp \ 29 board.cpp \
32 bitfont.cpp \ 30 bitfont.cpp \
33 kpacman.cpp \ 31 kpacman.cpp \
34 main.cpp 32 main.cpp
35 INCLUDEPATH+= $(OPIEDIR)/include 33 INCLUDEPATH+= $(OPIEDIR)/include
36 DEPENDPATH+= $(OPIEDIR)/include 34 DEPENDPATH+= $(OPIEDIR)/include
37LIBS += -lqpe 35LIBS += -lqpe -lopiecore2
38DESTDIR = $(OPIEDIR)/bin 36DESTDIR = $(OPIEDIR)/bin
39 TARGET = kpacman 37 TARGET = kpacman
40 38
41include ( $(OPIEDIR)/include.pro ) 39include ( $(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 @@
1 1
2#include "portable.h" 2#include "portable.h"
3 3
4#if defined( KDE2_PORT ) 4#if defined( KDE2_PORT )
5#include <kapp.h> 5#include <kapp.h>
6#include <kconfig.h> 6#include <kconfig.h>
7#include <kstddirs.h> 7#include <kstddirs.h>
8#include <kpacmanwidget.h> 8#include <kpacmanwidget.h>
9#include <kpacmanwidget.moc> 9#include <kpacmanwidget.moc>
10#elif defined( QPE_PORT ) 10#elif defined( QPE_PORT )
11#include <qpe/qpeapplication.h> 11#include <qpe/qpeapplication.h>
12#include <qpe/config.h> 12#include <qpe/config.h>
13#include "kpacmanwidget.h" 13#include "kpacmanwidget.h"
14#endif 14#endif
15 15
16 16#include <opie2/odebug.h>
17using namespace Opie::Core;
17 18
18KpacmanWidget::KpacmanWidget( QWidget *parent, const char *name) 19KpacmanWidget::KpacmanWidget( QWidget *parent, const char *name)
19 : QWidget( parent, name ) 20 : QWidget( parent, name )
20{ 21{
21 score = 0l; 22 score = 0l;
22 referee = 0l; 23 referee = 0l;
23 status = 0l; 24 status = 0l;
24 bitfont = NULL; 25 bitfont = NULL;
25 fontName = ""; 26 fontName = "";
26 27
27 scheme = mode = -1; 28 scheme = mode = -1;
28 confScheme(); 29 confScheme();
29 30
30 score = new Score(this, name, scheme, mode, bitfont); 31 score = new Score(this, name, scheme, mode, bitfont);
31 referee = new Referee( this, name, scheme, mode, bitfont); 32 referee = new Referee( this, name, scheme, mode, bitfont);
32 status = new Status(this, name, scheme, mode); 33 status = new Status(this, name, scheme, mode);
33 34
34 setBackgroundColor( black ); 35 setBackgroundColor( black );
35} 36}
36 37
37KpacmanWidget::~KpacmanWidget() 38KpacmanWidget::~KpacmanWidget()
38{ 39{
39} 40}
40 41
41void KpacmanWidget::confMisc(bool defGroup) 42void KpacmanWidget::confMisc(bool defGroup)
42{ 43{
43 APP_CONFIG_BEGIN( cfg ); 44 APP_CONFIG_BEGIN( cfg );
44 //KStandardDirs *dirs = KGlobal::dirs(); 45 //KStandardDirs *dirs = KGlobal::dirs();
45 QString findPath; 46 QString findPath;
46 47
47 if (defGroup || cfg->hasKey("Font")) { 48 if (defGroup || cfg->hasKey("Font")) {
48 fontName = cfg->readEntry("Font"); 49 fontName = cfg->readEntry("Font");
49 50
50 if (fontName.left(1) != "/" && fontName.left(1) != "~") 51 if (fontName.left(1) != "/" && fontName.left(1) != "~")
51 fontName.insert(0, "fonts/"); 52 fontName.insert(0, "fonts/");
52 if (fontName.right(1) == "/") 53 if (fontName.right(1) == "/")
53 fontName.append("font.xbm"); 54 fontName.append("font.xbm");
54 55
55 //findPath = dirs->findResource("appdata", fontName); 56 //findPath = dirs->findResource("appdata", fontName);
56 findPath = FIND_APP_DATA( fontName ); 57 findPath = FIND_APP_DATA( fontName );
57 if (!findPath.isEmpty()) 58 if (!findPath.isEmpty())
58 fontName = findPath; 59 fontName = findPath;
59 60
60 bitfontFirstChar = cfg->readNumEntry("FontFirstChar", 0x0e); 61 bitfontFirstChar = cfg->readNumEntry("FontFirstChar", 0x0e);
61 bitfontLastChar = cfg->readNumEntry("FontLastChar", 0x5f); 62 bitfontLastChar = cfg->readNumEntry("FontLastChar", 0x5f);
62 } 63 }
63 APP_CONFIG_END( cfg ); 64 APP_CONFIG_END( cfg );
64} 65}
65 66
66void KpacmanWidget::confScheme() 67void KpacmanWidget::confScheme()
67{ 68{
68 APP_CONFIG_BEGIN( cfg ); 69 APP_CONFIG_BEGIN( cfg );
69 QString lastFontName = fontName; 70 QString lastFontName = fontName;
70 SAVE_CONFIG_GROUP( cfg, oldgroup ); 71 SAVE_CONFIG_GROUP( cfg, oldgroup );
71 QString newgroup; 72 QString newgroup;
72 73
73 // if not set, read mode and scheme from the configfile 74 // if not set, read mode and scheme from the configfile
74 if (mode == -1 && scheme == -1) { 75 if (mode == -1 && scheme == -1) {
75 scheme = cfg->readNumEntry("Scheme", -1); 76 scheme = cfg->readNumEntry("Scheme", -1);
76 mode = cfg->readNumEntry("Mode", -1); 77 mode = cfg->readNumEntry("Mode", -1);
77 78
78 // if mode is not set in the defGroup-group, lookup the scheme group 79 // if mode is not set in the defGroup-group, lookup the scheme group
79 if (scheme != -1 || mode == -1) { 80 if (scheme != -1 || mode == -1) {
80 newgroup.sprintf("Scheme %d", scheme); 81 newgroup.sprintf("Scheme %d", scheme);
81 cfg->setGroup(newgroup); 82 cfg->setGroup(newgroup);
82 83
83 mode = cfg->readNumEntry("Mode", -1); 84 mode = cfg->readNumEntry("Mode", -1);
84 RESTORE_CONFIG_GROUP( cfg, oldgroup ); 85 RESTORE_CONFIG_GROUP( cfg, oldgroup );
85 } 86 }
86 } 87 }
87 88
88 confMisc(); 89 confMisc();
89 90
90 if (mode != -1) { 91 if (mode != -1) {
91 newgroup.sprintf("Mode %d", mode); 92 newgroup.sprintf("Mode %d", mode);
92 cfg->setGroup(newgroup); 93 cfg->setGroup(newgroup);
93 94
94 confMisc(FALSE); 95 confMisc(FALSE);
95 } 96 }
96 97
97 if (scheme != -1) { 98 if (scheme != -1) {
98 newgroup.sprintf("Scheme %d", scheme); 99 newgroup.sprintf("Scheme %d", scheme);
99 cfg->setGroup(newgroup); 100 cfg->setGroup(newgroup);
100 101
101 confMisc(FALSE); 102 confMisc(FALSE);
102 } 103 }
103 104
104 if (lastFontName != fontName) { 105 if (lastFontName != fontName) {
105 106
106 if (bitfont != 0) 107 if (bitfont != 0)
107 delete bitfont; 108 delete bitfont;
108 109
109 bitfont = new Bitfont(fontName, bitfontFirstChar, bitfontLastChar); 110 bitfont = new Bitfont(fontName, bitfontFirstChar, bitfontLastChar);
110 if (bitfont->width() == 0 || bitfont->height() == 0) { 111 if (bitfont->width() == 0 || bitfont->height() == 0) {
111 QString msg = tr("The bitfont could not be contructed.\n\n" 112 QString msg = tr("The bitfont could not be contructed.\n\n"
112 "The file '@FONTNAME@' does not exist,\n" 113 "The file '@FONTNAME@' does not exist,\n"
113 "or is of an unknown format."); 114 "or is of an unknown format.");
114 msg.replace(QRegExp("@FONTNAME@"), fontName); 115 msg.replace(QRegExp("@FONTNAME@"), fontName);
115 // QMessageBox::critical(this, tr("Initialization Error"), msg); 116 // QMessageBox::critical(this, tr("Initialization Error"), msg);
116 printf("%s\n", msg.data()); 117 printf("%s\n", msg.data());
117 } 118 }
118 } 119 }
119 120
120 RESTORE_CONFIG_GROUP( cfg, oldgroup ); 121 RESTORE_CONFIG_GROUP( cfg, oldgroup );
121 APP_CONFIG_END( cfg ); 122 APP_CONFIG_END( cfg );
122} 123}
123 124
124void KpacmanWidget::setScheme(int Scheme, int Mode) 125void KpacmanWidget::setScheme(int Scheme, int Mode)
125{ 126{
126 mode = Mode; 127 mode = Mode;
127 scheme = Scheme; 128 scheme = Scheme;
128 129
129 confScheme(); 130 confScheme();
130 131
131 score->setScheme(Scheme, Mode, bitfont); 132 score->setScheme(Scheme, Mode, bitfont);
132 referee->setScheme(Scheme, Mode, bitfont); 133 referee->setScheme(Scheme, Mode, bitfont);
133 status->setScheme(Scheme, Mode); 134 status->setScheme(Scheme, Mode);
134 135
135 score->repaint(FALSE); 136 score->repaint(FALSE);
136 referee->repaint(FALSE); 137 referee->repaint(FALSE);
137 status->repaint(FALSE); 138 status->repaint(FALSE);
138} 139}
139 140
140void KpacmanWidget::resizeEvent( QResizeEvent * ) 141void KpacmanWidget::resizeEvent( QResizeEvent * )
141{ 142{
142 qWarning("Resize"); 143 owarn << "Resize" << oendl;
143 referee->setGeometry(0, bitfont->height()*3, referee->width(), referee->height()); 144 referee->setGeometry(0, bitfont->height()*3, referee->width(), referee->height());
144 referee->setBackgroundColor(BLACK); 145 referee->setBackgroundColor(BLACK);
145 146
146 if(!status ) return; 147 if(!status ) return;
147 status->setGeometry(0, bitfont->height()*3+referee->height(), referee->width(), 148 status->setGeometry(0, bitfont->height()*3+referee->height(), referee->width(),
148 status->height()); 149 status->height());
149 status->setBackgroundColor(BLACK); 150 status->setBackgroundColor(BLACK);
150 151
151 score->setGeometry(0, 0, referee->width(), bitfont->height()*3+referee->height()+status->height()); 152 score->setGeometry(0, 0, referee->width(), bitfont->height()*3+referee->height()+status->height());
152 score->setBackgroundColor(BLACK); 153 score->setBackgroundColor(BLACK);
153} 154}
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 @@
1 1
2#include "portable.h" 2#include "portable.h"
3 3
4#if defined( KDE2_PORT ) 4#if defined( KDE2_PORT )
5#include <kapp.h> 5#include <kapp.h>
6#include <klocale.h> 6#include <klocale.h>
7#include <kstddirs.h> 7#include <kstddirs.h>
8#include <status.h> 8#include <status.h>
9#include <status.moc> 9#include <status.moc>
10#elif defined( QPE_PORT ) 10#elif defined( QPE_PORT )
11#include <qpe/qpeapplication.h> 11#include <qpe/qpeapplication.h>
12#include <qpe/config.h> 12#include <qpe/config.h>
13#include "status.h" 13#include "status.h"
14#endif 14#endif
15 15
16#include <opie2/odebug.h>
17using namespace Opie::Core;
18
16#include <qbitmap.h> 19#include <qbitmap.h>
17#include <qmsgbox.h> 20#include <qmsgbox.h>
18#include <qfileinfo.h> 21#include <qfileinfo.h>
19 22
20Status::Status( QWidget *parent, const char *name, int Scheme, int Mode ) : 23Status::Status( QWidget *parent, const char *name, int Scheme, int Mode ) :
21 QWidget( parent, name ) 24 QWidget( parent, name )
22{ 25{
23 qWarning("Status::Status"); 26 owarn << "Status::Status" << oendl;
24 actualLifes = 0; 27 actualLifes = 0;
25 actualLevel = 0; 28 actualLevel = 0;
26 29
27 lifesPix = NULL; 30 lifesPix = NULL;
28 levelPix = NULL; 31 levelPix = NULL;
29 32
30 scheme = Scheme; 33 scheme = Scheme;
31 mode = Mode; 34 mode = Mode;
32 level = 0; 35 level = 0;
33 36
34 confScheme(); 37 confScheme();
35} 38}
36 39
37QList<QPixmap> *Status::loadPixmap(QWidget *parent, QString pixmapName, 40QList<QPixmap> *Status::loadPixmap(QWidget *parent, QString pixmapName,
38 QList<QPixmap> *pixmaps) 41 QList<QPixmap> *pixmaps)
39{ 42{
40 if (pixmaps == NULL) { 43 if (pixmaps == NULL) {
41 pixmaps = new QList<QPixmap>; 44 pixmaps = new QList<QPixmap>;
42 pixmaps->setAutoDelete(TRUE); 45 pixmaps->setAutoDelete(TRUE);
43 } 46 }
44 47
45 if (!pixmaps->isEmpty()) 48 if (!pixmaps->isEmpty())
46 pixmaps->clear(); 49 pixmaps->clear();
47 50
48 QPixmap PIXMAP(pixmapName); 51 QPixmap PIXMAP(pixmapName);
49 if (PIXMAP.isNull() || PIXMAP.mask() == NULL) { 52 if (PIXMAP.isNull() || PIXMAP.mask() == NULL) {
50 QString msg = tr("The pixmap could not be contructed.\n\n" 53 QString msg = tr("The pixmap could not be contructed.\n\n"
51 "The file '@PIXMAPNAME@' does not exist,\n" 54 "The file '@PIXMAPNAME@' does not exist,\n"
52 "or is of an unknown format."); 55 "or is of an unknown format.");
53 msg.replace(QRegExp("@PIXMAPNAME@"), pixmapName); 56 msg.replace(QRegExp("@PIXMAPNAME@"), pixmapName);
54 QMessageBox::information(parent, tr("Initialization Error"), 57 QMessageBox::information(parent, tr("Initialization Error"),
55 (const char *) msg); 58 (const char *) msg);
56 return 0; 59 return 0;
57 } 60 }
58 61
59 int height = PIXMAP.height(); 62 int height = PIXMAP.height();
60 int width = (height == 0) ? 0 : PIXMAP.width()/(PIXMAP.width()/height); 63 int width = (height == 0) ? 0 : PIXMAP.width()/(PIXMAP.width()/height);
61 64
62 QBitmap BITMAP; 65 QBitmap BITMAP;
63 QBitmap MASK; 66 QBitmap MASK;
64 67
65 BITMAP = *PIXMAP.mask(); 68 BITMAP = *PIXMAP.mask();
66 MASK.resize(width, height); 69 MASK.resize(width, height);
67 70
68 for (int x = 0; x < PIXMAP.width()/width; x++) { 71 for (int x = 0; x < PIXMAP.width()/width; x++) {
69 QPixmap *pixmap = new QPixmap(width, height); 72 QPixmap *pixmap = new QPixmap(width, height);
70 pixmaps->append(pixmap); 73 pixmaps->append(pixmap);
71 bitBlt(pixmap, 0, 0, &PIXMAP, x*width, 0, width, height, CopyROP, TRUE); 74 bitBlt(pixmap, 0, 0, &PIXMAP, x*width, 0, width, height, CopyROP, TRUE);
72 bitBlt(&MASK, 0, 0, &BITMAP, x*width, 0, width, height, CopyROP, TRUE); 75 bitBlt(&MASK, 0, 0, &BITMAP, x*width, 0, width, height, CopyROP, TRUE);
73 pixmap->setMask(MASK); 76 pixmap->setMask(MASK);
74 } 77 }
75 78
76 return pixmaps; 79 return pixmaps;
77} 80}
78 81
79void Status::paintEvent( QPaintEvent *) 82void Status::paintEvent( QPaintEvent *)
80{ 83{
81 for (int x = 0; x < actualLifes && !lifesPix->isEmpty(); x++) 84 for (int x = 0; x < actualLifes && !lifesPix->isEmpty(); x++)
82 bitBlt(this, lifesPix->at(0)->width()+(lifesPix->at(0)->width()*x), 85 bitBlt(this, lifesPix->at(0)->width()+(lifesPix->at(0)->width()*x),
83 (height()-lifesPix->at(0)->height())/2, 86 (height()-lifesPix->at(0)->height())/2,
84 lifesPix->at(0), 0, 0, 87 lifesPix->at(0), 0, 0,
85 lifesPix->at(0)->width(), lifesPix->at(0)->height()); 88 lifesPix->at(0)->width(), lifesPix->at(0)->height());
86 89
87 for (int x = 0; x < actualLevel && !levelPix->isEmpty(); x++) { 90 for (int x = 0; x < actualLevel && !levelPix->isEmpty(); x++) {
88 erase((width()-levelPix->at(x)->width()*2)-(levelPix->at(x)->width()*levelPos[x]), 91 erase((width()-levelPix->at(x)->width()*2)-(levelPix->at(x)->width()*levelPos[x]),
89 (height()-levelPix->at(x)->height())/2, 92 (height()-levelPix->at(x)->height())/2,
90 levelPix->at(x)->width(), levelPix->at(x)->height()); 93 levelPix->at(x)->width(), levelPix->at(x)->height());
91 bitBlt(this, (width()-levelPix->at(x)->width()*2)-(levelPix->at(x)->width()*levelPos[x]), 94 bitBlt(this, (width()-levelPix->at(x)->width()*2)-(levelPix->at(x)->width()*levelPos[x]),
92 (height()-levelPix->at(x)->height())/2, 95 (height()-levelPix->at(x)->height())/2,
93 levelPix->at(x), 0, 0, 96 levelPix->at(x), 0, 0,
94 levelPix->at(x)->width(), levelPix->at(x)->height()); 97 levelPix->at(x)->width(), levelPix->at(x)->height());
95 } 98 }
96} 99}
97 100
98void Status::initPixmaps() 101void Status::initPixmaps()
99{ 102{
100 if (lastLifesPixmapName != lifesPixmapName.at(level)) { 103 if (lastLifesPixmapName != lifesPixmapName.at(level)) {
101 lifesPix = loadPixmap(this, lifesPixmapName.at(level), lifesPix); 104 lifesPix = loadPixmap(this, lifesPixmapName.at(level), lifesPix);
102 lastLifesPixmapName = lifesPixmapName.at(level); 105 lastLifesPixmapName = lifesPixmapName.at(level);
103 } 106 }
104 if (lastLevelPixmapName != levelPixmapName.at(level)) { 107 if (lastLevelPixmapName != levelPixmapName.at(level)) {
105 levelPix = loadPixmap(this, levelPixmapName.at(level), levelPix); 108 levelPix = loadPixmap(this, levelPixmapName.at(level), levelPix);
106 lastLevelPixmapName = levelPixmapName.at(level); 109 lastLevelPixmapName = levelPixmapName.at(level);
107 } 110 }
108} 111}
109 112
110QString Status::decodeHexOctString(QString s) 113QString Status::decodeHexOctString(QString s)
111{ 114{
112 QString value; 115 QString value;
113 QString valids; 116 QString valids;
114 int pos, xpos = 0, opos = 0; 117 int pos, xpos = 0, opos = 0;
115 int v, len, leadin; 118 int v, len, leadin;
116 const char *ptr; 119 const char *ptr;
117 uchar c; 120 uchar c;
118 121
119 while (((xpos = s.find(QRegExp("\\\\x[0-9a-fA-F]+"), xpos)) != -1) || 122 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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include "mindbreaker.h" 21#include "mindbreaker.h"
22 22
23#include <qtopia/resource.h> 23#include <qtopia/resource.h>
24#include <qtopia/config.h> 24#include <qtopia/config.h>
25#include <qtopia/qpeapplication.h> 25#include <qtopia/qpeapplication.h>
26#include <qtoolbar.h> 26#include <qtoolbar.h>
27 27
28#include <qtoolbutton.h> 28#include <qtoolbutton.h>
29#include <qmessagebox.h> 29#include <qmessagebox.h>
30#include <qlayout.h> 30#include <qlayout.h>
31#include <qtimer.h> 31#include <qtimer.h>
32 32
33#include <stdlib.h> 33#include <stdlib.h>
34#include <sys/time.h> 34#include <sys/time.h>
35#include <unistd.h> 35#include <unistd.h>
36 36
37static int pegRTTI = 3393393; 37static int pegRTTI = 3393393;
38 38
39static int adjusted_panel_height; 39static int adjusted_panel_height;
40static int adjusted_panel_width; 40static int adjusted_panel_width;
41 41
42static int adjusted_bin_margin; 42static int adjusted_bin_margin;
43static int adjusted_peg_size; 43static int adjusted_peg_size;
44static int adjusted_answerpeg_size; 44static int adjusted_answerpeg_size;
45 45
46static int adjusted_title_height; 46static int adjusted_title_height;
47static int adjusted_title_width; 47static int adjusted_title_width;
48 48
49static int adjusted_first_peg_x_diff; 49static int adjusted_first_peg_x_diff;
50static int adjusted_first_peg_y_diff; 50static int adjusted_first_peg_y_diff;
51static int adjusted_peg_spacing; 51static int adjusted_peg_spacing;
52 52
53static int adjusted_answerpegx; 53static int adjusted_answerpegx;
54static int adjusted_answerpegy; 54static int adjusted_answerpegy;
55static int adjusted_answerpeg_xdiff; 55static int adjusted_answerpeg_xdiff;
56static int adjusted_answerpeg_ydiff; 56static int adjusted_answerpeg_ydiff;
57 57
58static int adjusted_board_height; 58static int adjusted_board_height;
59static int adjusted_board_width; 59static int adjusted_board_width;
60 60
61static void setupBoardSize(int w, int h) 61static void setupBoardSize(int w, int h)
62{ 62{
63 adjusted_panel_width = w * 3/4; 63 adjusted_panel_width = w * 3/4;
64 adjusted_title_width = w * 3/4; 64 adjusted_title_width = w * 3/4;
65 65
66 adjusted_title_height = h/10; 66 adjusted_title_height = h/10;
67 adjusted_panel_height = (h-adjusted_title_height)/9; 67 adjusted_panel_height = (h-adjusted_title_height)/9;
68 68
69 adjusted_bin_margin = w * 10/240; 69 adjusted_bin_margin = w * 10/240;
70 adjusted_peg_size = adjusted_panel_height*3/4; 70 adjusted_peg_size = adjusted_panel_height*3/4;
71 adjusted_answerpeg_size = QMIN(adjusted_panel_width*15/180,adjusted_panel_height*15/25); 71 adjusted_answerpeg_size = QMIN(adjusted_panel_width*15/180,adjusted_panel_height*15/25);
72 72
73 // looks a bit dodgy on larger sizes 73 // looks a bit dodgy on larger sizes
74 if ( adjusted_peg_size > 40 ) 74 if ( adjusted_peg_size > 40 )
75 adjusted_peg_size = 40; 75 adjusted_peg_size = 40;
76 76
77 adjusted_first_peg_x_diff = w * 31/240-adjusted_peg_size/2; 77 adjusted_first_peg_x_diff = w * 31/240-adjusted_peg_size/2;
78 adjusted_first_peg_y_diff = (adjusted_panel_height - adjusted_peg_size)/2; 78 adjusted_first_peg_y_diff = (adjusted_panel_height - adjusted_peg_size)/2;
79 adjusted_peg_spacing = w * 30/240; 79 adjusted_peg_spacing = w * 30/240;
80 80
81 // looks a bit dodgy on larger sizes (still does though, but not as much...) 81 // looks a bit dodgy on larger sizes (still does though, but not as much...)
82 if ( adjusted_answerpeg_size > 22 ) 82 if ( adjusted_answerpeg_size > 22 )
83 adjusted_answerpeg_size = 22; 83 adjusted_answerpeg_size = 22;
84 84
85 adjusted_answerpegx = adjusted_panel_width * 159/180 - adjusted_answerpeg_size/2; 85 adjusted_answerpegx = adjusted_panel_width * 159/180 - adjusted_answerpeg_size/2;
86 adjusted_answerpegy = adjusted_panel_height/3 - adjusted_answerpeg_size/2; 86 adjusted_answerpegy = adjusted_panel_height/3 - adjusted_answerpeg_size/2;
87 adjusted_answerpeg_xdiff = adjusted_panel_width * 10/180; 87 adjusted_answerpeg_xdiff = adjusted_panel_width * 10/180;
88 adjusted_answerpeg_ydiff = adjusted_panel_height * 9/25; 88 adjusted_answerpeg_ydiff = adjusted_panel_height * 9/25;
89 89
90 adjusted_board_height = adjusted_title_height + (adjusted_panel_height * 9); 90 adjusted_board_height = adjusted_title_height + (adjusted_panel_height * 9);
91 adjusted_board_width = adjusted_panel_width + (adjusted_bin_margin * 2) + adjusted_peg_size; 91 adjusted_board_width = adjusted_panel_width + (adjusted_bin_margin * 2) + adjusted_peg_size;
92 92
93// qDebug("Adjusted width %d height %d", adjusted_board_width, adjusted_board_height); 93// odebug << "Adjusted width " << adjusted_board_width << " height " << adjusted_board_height << "" << oendl;
94} 94}
95 95
96 96
97/* helper class, */ 97/* helper class, */
98class Peg : public QCanvasRectangle 98class Peg : public QCanvasRectangle
99{ 99{
100public: 100public:
101 Peg(QCanvas *canvas, int type, int go = -1, int pos = -1); 101 Peg(QCanvas *canvas, int type, int go = -1, int pos = -1);
102 int rtti() const {return pegRTTI; } 102 int rtti() const {return pegRTTI; }
103 void advance(int phase); 103 void advance(int phase);
104 104
105 bool hit( const QPoint &) const; 105 bool hit( const QPoint &) const;
106 106
107/* a placed peg is one that has been set down on the board correctly and 107/* a placed peg is one that has been set down on the board correctly and
108 should not be moved, only copied */ 108 should not be moved, only copied */
109 bool placed() const; 109 bool placed() const;
110 void setPlaced(bool); 110 void setPlaced(bool);
111 111
112 int pegGo() const; 112 int pegGo() const;
113 int pegPos() const; 113 int pegPos() const;
114 void setPegPos(int); 114 void setPegPos(int);
115 115
116 int type() const; 116 int type() const;
117 117
118 static void buildImages(); 118 static void buildImages();
119 static QImage imageForType(int t); 119 static QImage imageForType(int t);
120 120
121 static int eggLevel; 121 static int eggLevel;
122 122
123protected: 123protected:
124 void drawShape(QPainter &); 124 void drawShape(QPainter &);
125private: 125private:
126 static QVector<QImage> normalPegs; 126 static QVector<QImage> normalPegs;
127 static QVector<QImage> specialPegs; 127 static QVector<QImage> specialPegs;
128 128
129 bool isplaced; 129 bool isplaced;
130 int pegtype; 130 int pegtype;
131 int peg_go; 131 int peg_go;
132 int peg_pos; 132 int peg_pos;
133 133
134 int aniStep; 134 int aniStep;
135}; 135};
136int Peg::eggLevel = 0; 136int Peg::eggLevel = 0;
137QVector<QImage> Peg::normalPegs; 137QVector<QImage> Peg::normalPegs;
138QVector<QImage> Peg::specialPegs; 138QVector<QImage> Peg::specialPegs;
139 139
140void Peg::buildImages() 140void Peg::buildImages()
141{ 141{
142 QImage pegs = Resource::loadImage("mindbreaker/pegs"); 142 QImage pegs = Resource::loadImage("mindbreaker/pegs");
143 int x = 0; 143 int x = 0;
144 int y = 0; 144 int y = 0;
145 int i; 145 int i;
146 eggLevel = 0; 146 eggLevel = 0;
147 normalPegs.resize(10); 147 normalPegs.resize(10);
148 for (i = 0; i < 6; i++) { 148 for (i = 0; i < 6; i++) {
149 normalPegs.insert(i, new QImage(pegs.copy(x, y, peg_size, peg_size). 149 normalPegs.insert(i, new QImage(pegs.copy(x, y, peg_size, peg_size).
150 smoothScale(adjusted_peg_size, adjusted_peg_size) )); 150 smoothScale(adjusted_peg_size, adjusted_peg_size) ));
151 x += peg_size; 151 x += peg_size;
152 } 152 }
153 specialPegs.resize(5); 153 specialPegs.resize(5);
154 for (i = 0; i < 5; i++) { 154 for (i = 0; i < 5; i++) {
155 specialPegs.insert(i, new QImage(pegs.copy(x,y,peg_size, peg_size). 155 specialPegs.insert(i, new QImage(pegs.copy(x,y,peg_size, peg_size).
156 smoothScale(adjusted_peg_size, adjusted_peg_size) )); 156 smoothScale(adjusted_peg_size, adjusted_peg_size) ));
157 x += peg_size; 157 x += peg_size;
158 } 158 }
159 159
160 QImage image = Resource::loadImage("mindbreaker/mindbreaker"); 160 QImage image = Resource::loadImage("mindbreaker/mindbreaker");
161 /* copy from master image to functional images */ 161 /* copy from master image to functional images */
162 x = 0; 162 x = 0;
163 y = panel_height; 163 y = panel_height;
164 normalPegs.insert(8, 164 normalPegs.insert(8,
165 new QImage( image.copy(x, y, panel_width, panel_height). 165 new QImage( image.copy(x, y, panel_width, panel_height).
166 smoothScale( adjusted_panel_width, adjusted_panel_height) 166 smoothScale( adjusted_panel_width, adjusted_panel_height)
167 )); 167 ));
168 y += panel_height; 168 y += panel_height;
169 y += title_height; 169 y += title_height;
170 normalPegs.insert(9, 170 normalPegs.insert(9,
171 new QImage(image.copy(x, y, title_width, title_height). 171 new QImage(image.copy(x, y, title_width, title_height).
172 smoothScale( adjusted_title_width, adjusted_title_height) 172 smoothScale( adjusted_title_width, adjusted_title_height)
173 )); 173 ));
174 y += title_height; 174 y += title_height;
175 175
176 x = 6 * peg_size; 176 x = 6 * peg_size;
177 normalPegs.insert(6, 177 normalPegs.insert(6,
178 new QImage(image.copy(x, y, answerpeg_size, answerpeg_size). 178 new QImage(image.copy(x, y, answerpeg_size, answerpeg_size).
179 smoothScale( adjusted_answerpeg_size, adjusted_answerpeg_size) )); 179 smoothScale( adjusted_answerpeg_size, adjusted_answerpeg_size) ));
180 x += answerpeg_size; 180 x += answerpeg_size;
181 normalPegs.insert(7, 181 normalPegs.insert(7,
182 new QImage(image.copy(x, y, answerpeg_size, answerpeg_size). 182 new QImage(image.copy(x, y, answerpeg_size, answerpeg_size).
183 smoothScale( adjusted_answerpeg_size, adjusted_answerpeg_size) )); 183 smoothScale( adjusted_answerpeg_size, adjusted_answerpeg_size) ));
184} 184}
185 185
186QImage Peg::imageForType(int t) 186QImage Peg::imageForType(int t)
187{ 187{
188 if (eggLevel > t ) { 188 if (eggLevel > t ) {
189 if( t < 5) { 189 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 @@
1#include "oyatzee.h" 1#include "oyatzee.h"
2 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
7/* QT */
3#include <qmessagebox.h> 8#include <qmessagebox.h>
4#include <qpushbutton.h> 9#include <qpushbutton.h>
5#include <qpainter.h> 10#include <qpainter.h>
6#include <qlayout.h> 11#include <qlayout.h>
7 12
13/* STD */
8#include <stdlib.h> 14#include <stdlib.h>
9 15
10OYatzee::OYatzee( QWidget *parent , const char *name, WFlags fl ) : QMainWindow( parent , name , fl ) 16OYatzee::OYatzee( QWidget *parent , const char *name, WFlags fl ) : QMainWindow( parent , name , fl )
11{ 17{
12 QWidget *thing = new QWidget( this ); 18 QWidget *thing = new QWidget( this );
13 setCentralWidget( thing ); 19 setCentralWidget( thing );
14 20
15 setCaption( tr( "OYatzee" ) ); 21 setCaption( tr( "OYatzee" ) );
16 22
17 setPlayerNumber( 4 ); 23 setPlayerNumber( 4 );
18 setRoundsNumber( 1 ); 24 setRoundsNumber( 1 );
19 25
20 lastPlayerFinished = false; 26 lastPlayerFinished = false;
21 currentPlayer = 1; 27 currentPlayer = 1;
22 28
23 ps.append( new Player( "Carsten" ) ); 29 ps.append( new Player( "Carsten" ) );
24 ps.append( new Player( "Julia" ) ); 30 ps.append( new Player( "Julia" ) );
25 ps.append( new Player( "Christine" ) ); 31 ps.append( new Player( "Christine" ) );
26 ps.append( new Player( "Stephan" ) ); 32 ps.append( new Player( "Stephan" ) );
27 33
28 34
29 QVBoxLayout *vbox = new QVBoxLayout( thing ); 35 QVBoxLayout *vbox = new QVBoxLayout( thing );
30 36
31 sb = new Scoreboard( ps, thing , "sb" ); 37 sb = new Scoreboard( ps, thing , "sb" );
32 connect( sb->pb , SIGNAL( item(int) ), this , SLOT( slotEndRound(int) ) ); 38 connect( sb->pb , SIGNAL( item(int) ), this , SLOT( slotEndRound(int) ) );
33 39
34 dw = new DiceWidget( thing , "dw" ); 40 dw = new DiceWidget( thing , "dw" );
35 dw->setMaximumHeight( this->height()/4 ); 41 dw->setMaximumHeight( this->height()/4 );
36 connect( dw->rollButton, SIGNAL( clicked() ), this , SLOT( slotRollDices() ) ); 42 connect( dw->rollButton, SIGNAL( clicked() ), this , SLOT( slotRollDices() ) );
37 43
38 vbox->addWidget( sb ); 44 vbox->addWidget( sb );
39 vbox->addWidget( dw ); 45 vbox->addWidget( dw );
40} 46}
41 47
42void OYatzee::slotEndRound( int item ) 48void OYatzee::slotEndRound( int item )
43{ 49{
44 qDebug( "Der User hat Nummer %d ausgewählt" , item ); 50 odebug << "Der User hat Nummer " << item << " ausgewählt" << oendl;
45 51
46 /* 52 /*
47 * if the user clicked on Total, Bonus or Score and thus not on a 53 * if the user clicked on Total, Bonus or Score and thus not on a
48 * selectable item return and do nothing 54 * selectable item return and do nothing
49 */ 55 */
50 if ( item == 7 || item == 8 || item == 16 ) return; 56 if ( item == 7 || item == 8 || item == 16 ) return;
51 57
52 /* 58 /*
53 * check if the user can really click on that item 59 * check if the user can really click on that item
54 */ 60 */
55 if ( posibilities.find( item ) == posibilities.end() ) return; 61 if ( posibilities.find( item ) == posibilities.end() ) return;
56 62
57 QValueListInt numbers; 63 QValueListInt numbers;
58 64
59 Dice *d = dw->diceList.first(); 65 Dice *d = dw->diceList.first();
60 for ( ; d != 0 ; d = dw->diceList.next() ) 66 for ( ; d != 0 ; d = dw->diceList.next() )
61 { 67 {
62 numbers.append( d->hasValue() ); 68 numbers.append( d->hasValue() );
63 } 69 }
64 70
65 int points = 0; 71 int points = 0;
66 72
67 switch ( item ) 73 switch ( item )
68 { 74 {
69 case Ones: 75 case Ones:
70 points = getPoints( 1 , numbers ); 76 points = getPoints( 1 , numbers );
71 break; 77 break;
72 case Twos: 78 case Twos:
73 points = getPoints( 2 , numbers ); 79 points = getPoints( 2 , numbers );
74 break; 80 break;
75 case Threes: 81 case Threes:
76 points = getPoints( 3 , numbers ); 82 points = getPoints( 3 , numbers );
77 break; 83 break;
78 case Fours: 84 case Fours:
79 points = getPoints( 4 , numbers ); 85 points = getPoints( 4 , numbers );
80 break; 86 break;
81 case Fives: 87 case Fives:
82 points = getPoints( 5 , numbers ); 88 points = getPoints( 5 , numbers );
83 break; 89 break;
84 case Sixes: 90 case Sixes:
85 points = getPoints( 6 , numbers ); 91 points = getPoints( 6 , numbers );
86 break; 92 break;
87 case ThreeOfAKind: 93 case ThreeOfAKind:
88 points = oakPoints; 94 points = oakPoints;
89 break; 95 break;
90 case FourOfAKind: 96 case FourOfAKind:
91 points = oakPoints; 97 points = oakPoints;
92 break; 98 break;
93 case FullHouse: 99 case FullHouse:
94 points = 25; 100 points = 25;
95 break; 101 break;
96 case SStraight: 102 case SStraight:
97 points = 30; 103 points = 30;
98 break; 104 break;
99 case LStraight: 105 case LStraight:
100 points = 40; 106 points = 40;
101 break; 107 break;
102 case Yatzee: 108 case Yatzee:
103 points = 50; 109 points = 50;
104 break; 110 break;
105 case Chance: 111 case Chance:
106 points = getPoints ( Chance , numbers ); 112 points = getPoints ( Chance , numbers );
107 } 113 }
108 114
109 sb->nextRB(currentPlayer-1)->updateMap( item , points ); 115 sb->nextRB(currentPlayer-1)->updateMap( item , points );
110 nextPlayer(); 116 nextPlayer();
111 117
112 qDebug( "Punkte: %d" , points ); 118 odebug << "Punkte: " << points << "" << oendl;
113} 119}
114 120
115void OYatzee::nextPlayer() 121void OYatzee::nextPlayer()
116{ 122{
117 currentPlayer++; 123 currentPlayer++;
118 124
119 if ( currentPlayer > numOfPlayers ) 125 if ( currentPlayer > numOfPlayers )
120 { 126 {
121 currentPlayer = 1; 127 currentPlayer = 1;
122 } 128 }
123 129
124 ps.at(currentPlayer-1)->turn = 0; 130 ps.at(currentPlayer-1)->turn = 0;
125} 131}
126 132
127int OYatzee::getPoints( const int num , QValueListInt l) 133int OYatzee::getPoints( const int num , QValueListInt l)
128{ 134{
129 QValueListInt::Iterator it = l.begin(); 135 QValueListInt::Iterator it = l.begin();
130 int c = 0; 136 int c = 0;
131 137
132 if ( num != Chance ) 138 if ( num != Chance )
133 { 139 {
134 for ( ; it != l.end() ; ++it ) 140 for ( ; it != l.end() ; ++it )
135 { 141 {
136 if ( *it == num ) 142 if ( *it == num )
137 c++; 143 c++;
138 } 144 }
139 145
140 return c * num; 146 return c * num;
141 } 147 }
142 else 148 else
143 { 149 {
144 for ( ; it != l.end() ; ++it ) 150 for ( ; it != l.end() ; ++it )
145 { 151 {
146 c += *it; 152 c += *it;
147 } 153 }
148 return c; 154 return c;
149 } 155 }
150 } 156 }
151 157
152OYatzee::~OYatzee() 158OYatzee::~OYatzee()
153{ 159{
154} 160}
155 161
156void OYatzee::detectPosibilities() 162void OYatzee::detectPosibilities()
157{ 163{
158 posibilities.clear(); 164 posibilities.clear();
159 qDebug( "running detectPosibilities()" ); 165 odebug << "running detectPosibilities()" << oendl;
160 166
161 Dice *d = dw->diceList.first(); 167 Dice *d = dw->diceList.first();
162 168
163 QValueListInt numbers; 169 QValueListInt numbers;
164 170
165 for ( ; d != 0 ; d = dw->diceList.next() ) 171 for ( ; d != 0 ; d = dw->diceList.next() )
166 { 172 {
167 numbers.append( d->hasValue() ); 173 numbers.append( d->hasValue() );
168 } 174 }
169 175
170 //the 6 numbers 176 //the 6 numbers
171 QValueListInt::Iterator it; 177 QValueListInt::Iterator it;
172 178
173 for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6 179 for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6
174 { 180 {
175 bool cont = false; 181 bool cont = false;
176 it = numbers.begin(); 182 it = numbers.begin();
177 for ( ; it != numbers.end() ; ++it ) 183 for ( ; it != numbers.end() ; ++it )
178 { 184 {
179 if ( cont ) 185 if ( cont )
180 continue; 186 continue;
181 187
182 if ( numbers.find( i ) != numbers.end() ) 188 if ( numbers.find( i ) != numbers.end() )
183 { 189 {
184 posibilities.append( i ); 190 posibilities.append( i );
185 cont = true; 191 cont = true;
186 } 192 }
187 } 193 }
188 } 194 }
189 195
190 //3er, 4er, Yatzee 196 //3er, 4er, Yatzee
191 it = numbers.begin(); 197 it = numbers.begin();
192 int count; 198 int count;
193 int temp; 199 int temp;
194 int countFH = 0; //for the full-house-check 200 int countFH = 0; //for the full-house-check
195 201
196 for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6 at least 3 times 202 for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6 at least 3 times
197 { 203 {
198 count = 0; 204 count = 0;
199 temp = 0; 205 temp = 0;
200 it = numbers.begin(); 206 it = numbers.begin();
201 for ( ; it != numbers.end() ; ++it ) 207 for ( ; it != numbers.end() ; ++it )
202 { 208 {
203 if ( *it == i ) 209 if ( *it == i )
204 { 210 {
205 count++; 211 count++;
206 temp++; 212 temp++;
207 } 213 }
208 if ( temp == 2 ) 214 if ( temp == 2 )
209 countFH = temp; 215 countFH = temp;
210 } 216 }
211 217
212 if ( count >= 3 ) 218 if ( count >= 3 )
213 { 219 {
214 posibilities.append( 9 ); 220 posibilities.append( 9 );
215 221
216 //now we check if it is a full house 222 //now we check if it is a full house
217 if ( count == 3 && countFH == 2 ) //aka Full House 223 if ( count == 3 && countFH == 2 ) //aka Full House
218 posibilities.append( 11 ); 224 posibilities.append( 11 );
219 if ( count >= 4 ) 225 if ( count >= 4 )
220 posibilities.append( 10 ); 226 posibilities.append( 10 );
221 if ( count == 5 ) //Yatzee 227 if ( count == 5 ) //Yatzee
222 posibilities.append( 14 ); 228 posibilities.append( 14 );
223 229
224 oakPoints = count * i; 230 oakPoints = count * i;
225 } 231 }
226 } 232 }
227 233
228 //S-Straight 234 //S-Straight
229 if ( numbers.find( 3 ) != numbers.end() && numbers.find( 4 ) != numbers.end() ) 235 if ( numbers.find( 3 ) != numbers.end() && numbers.find( 4 ) != numbers.end() )
230 { 236 {
231 bool isLong = false; 237 bool isLong = false;
232 bool isShort = true; 238 bool isShort = true;
233 //L-Straight 239 //L-Straight
234 if ( numbers.find( 2 ) != numbers.end() && numbers.find( 5 ) != numbers.end() ) 240 if ( numbers.find( 2 ) != numbers.end() && numbers.find( 5 ) != numbers.end() )
235 { 241 {
236 isShort = true; 242 isShort = true;
237 243
238 //12345 or 23456 244 //12345 or 23456
239 if ( numbers.find( 1 ) != numbers.end() || numbers.find( 6) != numbers.end() ) 245 if ( numbers.find( 1 ) != numbers.end() || numbers.find( 6) != numbers.end() )
240 isLong = true; 246 isLong = true;
241 } 247 }
242 //1234 248 //1234
243 if ( numbers.find( 1 ) != numbers.end() && numbers.find( 2 ) != numbers.end() ) 249 if ( numbers.find( 1 ) != numbers.end() && numbers.find( 2 ) != numbers.end() )
244 isShort = true; 250 isShort = true;
245 //3456 251 //3456
246 if ( numbers.find( 5 ) != numbers.end() && numbers.find( 6 ) != numbers.end() ) 252 if ( numbers.find( 5 ) != numbers.end() && numbers.find( 6 ) != numbers.end() )
247 isShort = true; 253 isShort = true;
248 254
249 if ( isShort ) 255 if ( isShort )
250 posibilities.append( 12 ); 256 posibilities.append( 12 );
251 if ( isLong ) 257 if ( isLong )
252 posibilities.append( 13 ); 258 posibilities.append( 13 );
253 } 259 }
254 260
255 posibilities.append( 13 ); //Chance, well, this is allways possible 261 posibilities.append( 13 ); //Chance, well, this is allways possible
256 262
257 displayPossibilites(); 263 displayPossibilites();
258} 264}
259 265
260void OYatzee::displayPossibilites() 266void OYatzee::displayPossibilites()
261{ 267{
262 //X for ( QValueListInt::Iterator it = posibilities.begin() ; it != posibilities.end(); ++it ) 268 //X for ( QValueListInt::Iterator it = posibilities.begin() ; it != posibilities.end(); ++it )
263 //X { 269 //X {
264 //X qDebug( QString::number( *it ) ); 270 //X odebug << QString::number( *it ) << oendl;
265 //X switch ( *it ) 271 //X switch ( *it )
266 //X { 272 //X {
267 //X case Ones: 273 //X case Ones:
268 //X qDebug( "1er" ); 274 //X odebug << "1er" << oendl;
269 //X break; 275 //X break;
270 //X case Twos: 276 //X case Twos:
271 //X qDebug( "2er" ); 277 //X odebug << "2er" << oendl;
272 //X break; 278 //X break;
273 //X case Threes: 279 //X case Threes:
274 //X qDebug( "3er" ); 280 //X odebug << "3er" << oendl;
275 //X break; 281 //X break;
276 //X case Fours: 282 //X case Fours:
277 //X qDebug( "4er" ); 283 //X odebug << "4er" << oendl;
278 //X break; 284 //X break;
279 //X case Fives: 285 //X case Fives:
280 //X qDebug( "5er" ); 286 //X odebug << "5er" << oendl;
281 //X break; 287 //X break;
282 //X case Sixes: 288 //X case Sixes:
283 //X qDebug( "6er" ); 289 //X odebug << "6er" << oendl;
284 //X break; 290 //X break;
285 //X case ThreeOfAKind: 291 //X case ThreeOfAKind:
286 //X qDebug( "3oaK" ); 292 //X odebug << "3oaK" << oendl;
287 //X break; 293 //X break;
288 //X case FourOfAKind: 294 //X case FourOfAKind:
289 //X qDebug( "4oaK" ); 295 //X odebug << "4oaK" << oendl;
290 //X break; 296 //X break;
291 //X case FullHouse: 297 //X case FullHouse:
292 //X qDebug( "Full House" ); 298 //X odebug << "Full House" << oendl;
293 //X break; 299 //X break;
294 //X case SStraight: 300 //X case SStraight:
295 //X qDebug( "Short S" ); 301 //X odebug << "Short S" << oendl;
296 //X break; 302 //X break;
297 //X case LStraight: 303 //X case LStraight:
298 //X qDebug( "Long S" ); 304 //X odebug << "Long S" << oendl;
299 //X break; 305 //X break;
300 //X case Yatzee: 306 //X case Yatzee:
301 //X qDebug( "Yatzee!" ); 307 //X odebug << "Yatzee!" << oendl;
302 //X break; 308 //X break;
303 //X case Chance: 309 //X case Chance:
304 //X qDebug( "Chance" ); 310 //X odebug << "Chance" << oendl;
305 //X break; 311 //X break;
306 //X } 312 //X }
307 //X } 313 //X }
308 314
309 sb->pb->setIntlist( posibilities ); 315 sb->pb->setIntlist( posibilities );
310 sb->pb->update(); 316 sb->pb->update();
311} 317}
312 318
313void OYatzee::startGame() 319void OYatzee::startGame()
314{ 320{
315 /* 321 /*
316 * TODO 322 * TODO
317 */ 323 */
318} 324}
319 325
320void OYatzee::stopGame(){} 326void OYatzee::stopGame(){}
321 327
322void OYatzee::setPlayerNumber( const int num ) 328void OYatzee::setPlayerNumber( const int num )
323{ 329{
324 numOfPlayers = num; 330 numOfPlayers = num;
325} 331}
326 332
327void OYatzee::setRoundsNumber( const int num ) 333void OYatzee::setRoundsNumber( const int num )
328{ 334{
329 numOfRounds = num; 335 numOfRounds = num;
330} 336}
331 337
332void OYatzee::slotStartGame() 338void OYatzee::slotStartGame()
333{ 339{
334} 340}
335 341
336void OYatzee::slotRollDices() 342void OYatzee::slotRollDices()
337{ 343{
338 qDebug( "Roll nummer: %d" , ps.at( currentPlayer-1 )->turn ); 344 odebug << "Roll nummer: " << ps.at( currentPlayer-1 )->turn << "" << oendl;
339 345
340 if ( ps.at( currentPlayer-1 )->turn == 3 ) 346 if ( ps.at( currentPlayer-1 )->turn == 3 )
341 { 347 {
342 QMessageBox::information( this, 348 QMessageBox::information( this,
343 "OYatzee", 349 "OYatzee",
344 tr( "Only three rolls per turn allowed." ) ); 350 tr( "Only three rolls per turn allowed." ) );
345 return; 351 return;
346 } 352 }
347 353
348 Dice *d = dw->diceList.first(); 354 Dice *d = dw->diceList.first();
349 355
350 for ( ; d != 0 ; d = dw->diceList.next() ) 356 for ( ; d != 0 ; d = dw->diceList.next() )
351 { 357 {
352 if ( !d->isSelected ) 358 if ( !d->isSelected )
353 d->roll(); 359 d->roll();
354 } 360 }
355 361
356 //qDebug( "Roll nummer (vorher): %d" , ps.at( currentPlayer-1 )->turn ); 362 //odebug << "Roll nummer (vorher): " << ps.at( currentPlayer-1 )->turn << "" << oendl;
357 ps.at(currentPlayer-1)->turn++; 363 ps.at(currentPlayer-1)->turn++;
358 //qDebug( "Roll nummer (nachher): %d" , ps.at( currentPlayer-1 )->turn ); 364 //odebug << "Roll nummer (nachher): " << ps.at( currentPlayer-1 )->turn << "" << oendl;
359 365
360 detectPosibilities(); 366 detectPosibilities();
361} 367}
362 368
363/* 369/*
364 * Scoreboard 370 * Scoreboard
365 */ 371 */
366Scoreboard::Scoreboard( playerList ps, QWidget *parent, const char *name ) : QWidget( parent , name ) 372Scoreboard::Scoreboard( playerList ps, QWidget *parent, const char *name ) : QWidget( parent , name )
367{ 373{
368 ps_ = ps; 374 ps_ = ps;
369 375
370 pb = new Possibilityboard( this , "pb" ); 376 pb = new Possibilityboard( this , "pb" );
371 377
372 createResultboards( 4 ); 378 createResultboards( 4 );
373 379
374 QHBoxLayout *hbox = new QHBoxLayout( this ); 380 QHBoxLayout *hbox = new QHBoxLayout( this );
375 381
376 hbox->addWidget( pb ); 382 hbox->addWidget( pb );
377 383
378 hbox->addSpacing( 25 ); 384 hbox->addSpacing( 25 );
379 385
380 Resultboard *r = rbList.first(); 386 Resultboard *r = rbList.first();
381 387
382 for ( ; r != 0 ; r = rbList.next() ) 388 for ( ; r != 0 ; r = rbList.next() )
383 { 389 {
384 hbox->addWidget( r ); 390 hbox->addWidget( r );
385 } 391 }
386} 392}
387 393
388Resultboard* Scoreboard::nextRB( int currentPlayer ) 394Resultboard* Scoreboard::nextRB( int currentPlayer )
389{ 395{
390 Resultboard *b; 396 Resultboard *b;
391 397
392 b = rbList.at( currentPlayer ); 398 b = rbList.at( currentPlayer );
393 399
394 qDebug( "Anzahl: %d" ,rbList.count() ); 400 odebug << "Anzahl: " << rbList.count() << "" << oendl;
395 401
396 return b; 402 return b;
397 } 403 }
398 404
399void Scoreboard::createResultboards(const int num) 405void Scoreboard::createResultboards(const int num)
400{ 406{
401 Player *p = ps_.first(); 407 Player *p = ps_.first();
402 for ( int i = 0 ; i < num ; ++i , p = ps_.next() ) 408 for ( int i = 0 ; i < num ; ++i , p = ps_.next() )
403 { 409 {
404 QString n = p->playerName; 410 QString n = p->playerName;
405 rbList.append( new Resultboard( n , this ) ); 411 rbList.append( new Resultboard( n , this ) );
406 } 412 }
407} 413}
408 414
409void Scoreboard::paintEvent( QPaintEvent * ) 415void Scoreboard::paintEvent( QPaintEvent * )
410{ 416{
411 //X QPainter p; 417 //X QPainter p;
412 //X p.begin( this ); 418 //X p.begin( this );
413//X 419//X
414 //X p.drawRect( 0,0, this->width() , this->height() ); 420 //X p.drawRect( 0,0, this->width() , this->height() );
415} 421}
416 422
417/* 423/*
418 * Dice 424 * Dice
419 */ 425 */
420Dice::Dice( QWidget *parent , const char *name ) : QFrame( parent , name ) 426Dice::Dice( QWidget *parent , const char *name ) : QFrame( parent , name )
421{ 427{
422 QTime t = QTime::currentTime(); // set random seed 428 QTime t = QTime::currentTime(); // set random seed
423 srand(t.hour()*12+t.minute()*60+t.second()*60); 429 srand(t.hour()*12+t.minute()*60+t.second()*60);
424 430
425 connect( this , SIGNAL( selected() ), this , SLOT( slotSelected() ) ); 431 connect( this , SIGNAL( selected() ), this , SLOT( slotSelected() ) );
426} 432}
427 433
428void Dice::slotSelected() 434void Dice::slotSelected()
429{ 435{
430 if ( isSelected ) 436 if ( isSelected )
431 isSelected = false; 437 isSelected = false;
432 else isSelected = true; 438 else isSelected = true;
433 439
434 update(); 440 update();
435} 441}
436 442
437const int Dice::hasValue() const 443const int Dice::hasValue() const
438{ 444{
439 return Value; 445 return Value;
440} 446}
441 447
442void Dice::roll() 448void Dice::roll()
443{ 449{
444 Value = rand()%6; 450 Value = rand()%6;
445 Value += 1; 451 Value += 1;
446 452
447 update(); 453 update();
448} 454}
449 455
450void Dice::mousePressEvent( QMouseEvent* /*e*/ ) 456void Dice::mousePressEvent( QMouseEvent* /*e*/ )
451{ 457{
452 emit selected(); 458 emit selected();
453} 459}
454 460
455void Dice::paintEvent( QPaintEvent * ) 461void Dice::paintEvent( QPaintEvent * )
456{ 462{
457 QPainter p; 463 QPainter p;
458 p.begin( this ); 464 p.begin( this );
459 465
460 p.drawRect( 0,0, this->width() , this->height() ); 466 p.drawRect( 0,0, this->width() , this->height() );
461 467
462 if ( isSelected ) 468 if ( isSelected )
463 p.drawRect( 20,20, 10,10 ); 469 p.drawRect( 20,20, 10,10 );
464 470
465 paintNumber( &p ); 471 paintNumber( &p );
466} 472}
467 473
468void Dice::paintNumber( QPainter *p ) 474void Dice::paintNumber( QPainter *p )
469{ 475{
470 p->setBrush( Qt::black ); 476 p->setBrush( Qt::black );
471 477
472 int w = this->width(); 478 int w = this->width();
473 int h = this->height(); 479 int h = this->height();
474 int r = this->width(); 480 int r = this->width();
475 r /= 10; 481 r /= 10;
476 482
477 switch ( Value ) 483 switch ( Value )
478 { 484 {
479 case 1: 485 case 1:
480 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 486 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
481 break; 487 break;
482 case 2: 488 case 2:
483 p->drawEllipse( (int)( 0.3*w - r ) , (int)( 0.3*h - r ) , r , r ) ; 489 p->drawEllipse( (int)( 0.3*w - r ) , (int)( 0.3*h - r ) , r , r ) ;
484 p->drawEllipse( (int)( 0.7*w - r ) , (int)( 0.7*h - r ) , r , r ) ; 490 p->drawEllipse( (int)( 0.7*w - r ) , (int)( 0.7*h - r ) , r , r ) ;
485 break; 491 break;
486 case 3: 492 case 3:
487 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 493 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
488 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 494 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
489 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 495 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
490 break; 496 break;
@@ -515,173 +521,173 @@ void Dice::paintNumber( QPainter *p )
515/* 521/*
516 * DiceWidget 522 * DiceWidget
517 */ 523 */
518DiceWidget::DiceWidget( QWidget *parent , const char *name ) : QWidget( parent , name ) 524DiceWidget::DiceWidget( QWidget *parent , const char *name ) : QWidget( parent , name )
519{ 525{
520 rollButton = new QPushButton( tr( "Roll" ) , this ) ; 526 rollButton = new QPushButton( tr( "Roll" ) , this ) ;
521 527
522 for ( int i = 0 ; i < 5 ; i++ ) 528 for ( int i = 0 ; i < 5 ; i++ )
523 { 529 {
524 //appending the 5 dices of the game 530 //appending the 5 dices of the game
525 diceList.append( new Dice( this, "wuerfel" ) ); 531 diceList.append( new Dice( this, "wuerfel" ) );
526 } 532 }
527 533
528 QHBoxLayout *hbox = new QHBoxLayout( this ); 534 QHBoxLayout *hbox = new QHBoxLayout( this );
529 535
530 Dice *d = diceList.first(); 536 Dice *d = diceList.first();
531 537
532 for ( ; d != 0 ; d = diceList.next() ) 538 for ( ; d != 0 ; d = diceList.next() )
533 { 539 {
534 hbox->addWidget( d ); 540 hbox->addWidget( d );
535 } 541 }
536 542
537 hbox->addWidget( rollButton ); 543 hbox->addWidget( rollButton );
538} 544}
539 545
540/* 546/*
541 * Player 547 * Player
542 */ 548 */
543Player::Player( QString name ) 549Player::Player( QString name )
544{ 550{
545 playerName = name; 551 playerName = name;
546 setupResultList(); 552 setupResultList();
547 turn = 0; 553 turn = 0;
548} 554}
549 555
550void Player::setupResultList() 556void Player::setupResultList()
551{ 557{
552 for ( int i = 1 ; i < 14 ; ++i ) 558 for ( int i = 1 ; i < 14 ; ++i )
553 { 559 {
554 pResults.append( 0 ); 560 pResults.append( 0 );
555 } 561 }
556} 562}
557 563
558/* 564/*
559 * TODO: muss noch genutzt werden 565 * TODO: muss noch genutzt werden
560 */ 566 */
561void Player::updateTotalPoints( pointMap m ) 567void Player::updateTotalPoints( pointMap m )
562{ 568{
563 pointMap::Iterator it = m.begin(); 569 pointMap::Iterator it = m.begin();
564 for ( ; it != m.end() ; ++it ) 570 for ( ; it != m.end() ; ++it )
565 { 571 {
566 totalPoints += it.data(); 572 totalPoints += it.data();
567 } 573 }
568 574
569} 575}
570 576
571 577
572void Player::setResults( const int cat , const int points ) 578void Player::setResults( const int cat , const int points )
573{ 579{
574 QValueListInt::Iterator it = pResults.at( cat ); 580 QValueListInt::Iterator it = pResults.at( cat );
575 *it = points; 581 *it = points;
576} 582}
577 583
578/* 584/*
579 * Board 585 * Board
580 */ 586 */
581Board::Board( QWidget *parent , const char* name ) : QWidget ( parent , name ) 587Board::Board( QWidget *parent , const char* name ) : QWidget ( parent , name )
582{ 588{
583} 589}
584 590
585void Board::mousePressEvent( QMouseEvent *e ) 591void Board::mousePressEvent( QMouseEvent *e )
586{ 592{
587 emit clicked( e->pos() ); 593 emit clicked( e->pos() );
588} 594}
589 595
590/* 596/*
591 * Resultboard 597 * Resultboard
592 */ 598 */
593 599
594Resultboard::Resultboard( QString playerName , QWidget *parent , const char* name ) : Board ( parent , name ) 600Resultboard::Resultboard( QString playerName , QWidget *parent , const char* name ) : Board ( parent , name )
595{ 601{
596 pName = playerName; 602 pName = playerName;
597} 603}
598 604
599void Resultboard::paintEvent( QPaintEvent* ) 605void Resultboard::paintEvent( QPaintEvent* )
600{ 606{
601 QPainter p; 607 QPainter p;
602 p.begin( this ); 608 p.begin( this );
603 609
604 const int cell_width = this->width(); 610 const int cell_width = this->width();
605 const int cell_height = this->height()/17; 611 const int cell_height = this->height()/17;
606 612
607 pointMap::Iterator it = pMap.begin(); 613 pointMap::Iterator it = pMap.begin();
608 for ( ; it != pMap.end() ; ++it ) 614 for ( ; it != pMap.end() ; ++it )
609 { 615 {
610 int i = it.key(); 616 int i = it.key();
611 qDebug( "ok: %d , %d" , i , it.data() ); 617 odebug << "ok: " << i << " , " << it.data() << "" << oendl;
612 p.drawText( 0, i*cell_height , cell_width , cell_height , Qt::AlignCenter , QString::number( it.data() ) ); 618 p.drawText( 0, i*cell_height , cell_width , cell_height , Qt::AlignCenter , QString::number( it.data() ) );
613 } 619 }
614 620
615 p.drawText( 0,0,cell_width,cell_height, Qt::AlignCenter , pName ); //Playername 621 p.drawText( 0,0,cell_width,cell_height, Qt::AlignCenter , pName ); //Playername
616} 622}
617 623
618 624
619void Resultboard::updateMap( int item , int points ) 625void Resultboard::updateMap( int item , int points )
620{ 626{
621 pMap.insert( item , points ); 627 pMap.insert( item , points );
622 628
623 update(); 629 update();
624} 630}
625 631
626/* 632/*
627 * Possibilityboard 633 * Possibilityboard
628 */ 634 */
629 635
630Possibilityboard::Possibilityboard( QWidget *parent , const char* name ) : Board ( parent , name ) 636Possibilityboard::Possibilityboard( QWidget *parent , const char* name ) : Board ( parent , name )
631{ 637{
632 begriffe.append( "1er" ); 638 begriffe.append( "1er" );
633 begriffe.append( "2er" ); 639 begriffe.append( "2er" );
634 begriffe.append( "3er" ); 640 begriffe.append( "3er" );
635 begriffe.append( "4er" ); 641 begriffe.append( "4er" );
636 begriffe.append( "5er" ); 642 begriffe.append( "5er" );
637 begriffe.append( "6er" ); 643 begriffe.append( "6er" );
638 begriffe.append( "Total" ); 644 begriffe.append( "Total" );
639 begriffe.append( "Bonus" ); 645 begriffe.append( "Bonus" );
640 begriffe.append( "3oaK" ); 646 begriffe.append( "3oaK" );
641 begriffe.append( "4oaK" ); 647 begriffe.append( "4oaK" );
642 begriffe.append( "Full House" ); 648 begriffe.append( "Full House" );
643 begriffe.append( "Short S" ); 649 begriffe.append( "Short S" );
644 begriffe.append( "Long S" ); 650 begriffe.append( "Long S" );
645 begriffe.append( "Yatzee!" ); 651 begriffe.append( "Yatzee!" );
646 begriffe.append( "Chance" ); 652 begriffe.append( "Chance" );
647 begriffe.append( "Score" ); 653 begriffe.append( "Score" );
648 654
649 connect( this , SIGNAL( clicked(QPoint) ), this , SLOT( slotClicked(QPoint) ) ); 655 connect( this , SIGNAL( clicked(QPoint) ), this , SLOT( slotClicked(QPoint) ) );
650} 656}
651 657
652void Possibilityboard::slotClicked( QPoint p) 658void Possibilityboard::slotClicked( QPoint p)
653{ 659{
654 emit item( p.y()/(this->height()/17) ); 660 emit item( p.y()/(this->height()/17) );
655} 661}
656 662
657void Possibilityboard::paintEvent( QPaintEvent* ) 663void Possibilityboard::paintEvent( QPaintEvent* )
658{ 664{
659 QPainter p; 665 QPainter p;
660 p.begin( this ); 666 p.begin( this );
661 667
662 const int cell_width = this->width(); 668 const int cell_width = this->width();
663 const int cell_height = this->height()/17; 669 const int cell_height = this->height()/17;
664 670
665 p.setBrush( Qt::blue ); 671 p.setBrush( Qt::blue );
666 672
667 QValueListInt::Iterator listIt = list.begin(); 673 QValueListInt::Iterator listIt = list.begin();
668 for ( ; listIt != list.end() ; ++listIt ) 674 for ( ; listIt != list.end() ; ++listIt )
669 { 675 {
670 p.drawRect( 0 , (*listIt) * cell_height , cell_width , cell_height ); 676 p.drawRect( 0 , (*listIt) * cell_height , cell_width , cell_height );
671 } 677 }
672 678
673 p.setBrush( Qt::black ); 679 p.setBrush( Qt::black );
674 p.setBrush( Qt::NoBrush ); 680 p.setBrush( Qt::NoBrush );
675 QStringList::Iterator begriffeIt = begriffe.begin(); 681 QStringList::Iterator begriffeIt = begriffe.begin();
676 for ( int i = 1 ; i < 18 ; ++i ) 682 for ( int i = 1 ; i < 18 ; ++i )
677 { 683 {
678 p.drawText( 0 , i*cell_height , cell_width , cell_height , Qt::AlignCenter , *begriffeIt ); 684 p.drawText( 0 , i*cell_height , cell_width , cell_height , Qt::AlignCenter , *begriffeIt );
679 ++begriffeIt; 685 ++begriffeIt;
680 } 686 }
681} 687}
682 688
683void Possibilityboard::setIntlist( QValueListInt &l ) 689void Possibilityboard::setIntlist( QValueListInt &l )
684{ 690{
685 list = l; 691 list = l;
686} 692}
687 693
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 @@
1 TEMPLATE= app 1 TEMPLATE= app
2 CONFIG = qt warn_on 2 CONFIG = qt warn_on
3 DESTDIR = $(OPIEDIR)/bin 3 DESTDIR = $(OPIEDIR)/bin
4 HEADERS = oyatzee.h 4 HEADERS = oyatzee.h
5 SOURCES = main.cpp oyatzee.cpp 5 SOURCES = main.cpp oyatzee.cpp
6 TARGET = oyatzee 6 TARGET = oyatzee
7INCLUDEPATH += $(OPIEDIR)/include 7INCLUDEPATH += $(OPIEDIR)/include
8 DEPENDPATH+= $(OPIEDIR)/include 8 DEPENDPATH+= $(OPIEDIR)/include
9LIBS += -lqpe 9LIBS += -lqpe -lopiecore2
10 10
11include ( $(OPIEDIR)/include.pro ) 11include ( $(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()
582 uchar nletter[4095]; // QDawg only handles 0..4095 582 uchar nletter[4095]; // QDawg only handles 0..4095
583 memset(nletter,0,4096); 583 memset(nletter,0,4096);
584 for (int i=0; i<rack->count(); i++) { 584 for (int i=0; i<rack->count(); i++) {
585 const Tile* r = rack->tileRef(i); 585 const Tile* r = rack->tileRef(i);
586 if ( r->isBlank() ) 586 if ( r->isBlank() )
587 nletter[0]++; 587 nletter[0]++;
588 else 588 else
589 nletter[r->text()[0].unicode()]++; 589 nletter[r->text()[0].unicode()]++;
590 } 590 }
591 Tile blankvalues[99]; // ### max blanks 591 Tile blankvalues[99]; // ### max blanks
592 findBest(current, d, root, 0, nletter, tiles, 0, blankvalues, 0); 592 findBest(current, d, root, 0, nletter, tiles, 0, blankvalues, 0);
593 if ( ++current.rx() == board->xTiles() ) { 593 if ( ++current.rx() == board->xTiles() ) {
594 current.rx() = 0; 594 current.rx() = 0;
595 if ( ++current.ry() == board->yTiles() ) { 595 if ( ++current.ry() == board->yTiles() ) {
596 if ( across ) { 596 if ( across ) {
597 if ( dict == 1 ) { 597 if ( dict == 1 ) {
598 if ( best_score >= 0 ) { 598 if ( best_score >= 0 ) {
599 rack->arrangeTiles(best,best_n); 599 rack->arrangeTiles(best,best_n);
600 rack->setBlanks(best_blankvalues); 600 rack->setBlanks(best_blankvalues);
601 board->scoreTurn(best_start, best_n, best_dir); 601 board->scoreTurn(best_start, best_n, best_dir);
602 board->showTurn(); 602 board->showTurn();
603 } 603 }
604 return FALSE; 604 return FALSE;
605 } 605 }
606 dict++; 606 dict++;
607 across = FALSE; 607 across = FALSE;
608 current = QPoint(0,0); 608 current = QPoint(0,0);
609 } else { 609 } else {
610 across = TRUE; 610 across = TRUE;
611 current = QPoint(0,0); 611 current = QPoint(0,0);
612 } 612 }
613 } 613 }
614 } 614 }
615 return TRUE; 615 return TRUE;
616} 616}
617 617
618void ComputerPlayer::findBest(QPoint at, const QPoint& d, const QDawg::Node* node, ulong used, uchar* nletter, const Tile** tiles, int n, Tile* blankvalues, int blused) 618void ComputerPlayer::findBest(QPoint at, const QPoint& d, const QDawg::Node* node, ulong used, uchar* nletter, const Tile** tiles, int n, Tile* blankvalues, int blused)
619{ 619{
620 if ( !node ) 620 if ( !node )
621 return; 621 return;
622 QChar l = node->letter(); 622 QChar l = node->letter();
623 const Tile* cur = board->tile(at); 623 const Tile* cur = board->tile(at);
624 if ( cur ) { 624 if ( cur ) {
625 if ( cur->text()[0] == l ) { 625 if ( cur->text()[0] == l ) {
626 bool nextok = board->contains(at+d); 626 bool nextok = board->contains(at+d);
627 if ( node->isWord() && n && (!nextok || !board->tile(at+d)) ) 627 if ( node->isWord() && n && (!nextok || !board->tile(at+d)) )
628 noteChoice(tiles,n,d,blankvalues,blused); 628 noteChoice(tiles,n,d,blankvalues,blused);
629 if ( nextok ) 629 if ( nextok )
630 findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused); 630 findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused);
631 // #### text()[1]... 631 // #### text()[1]...
632 } 632 }
633 } else { 633 } else {
634 if ( nletter[l.unicode()] || nletter[0] ) { 634 if ( nletter[l.unicode()] || nletter[0] ) {
635 int rc = rack->count(); 635 int rc = rack->count();
636 ulong msk = 1; 636 ulong msk = 1;
637 for ( int x=0; x<rc; x++ ) { 637 for ( int x=0; x<rc; x++ ) {
638 if ( !(used&msk) ) { 638 if ( !(used&msk) ) {
639 const Tile* t = rack->tileRef(x); 639 const Tile* t = rack->tileRef(x);
640 if ( t->isBlank() || t->text() == l ) { // #### multi-char value()s 640 if ( t->isBlank() || t->text() == l ) { // #### multi-char value()s
641 bool nextok = board->contains(at+d); 641 bool nextok = board->contains(at+d);
642 tiles[n++] = t; 642 tiles[n++] = t;
643 if ( t->isBlank() ) 643 if ( t->isBlank() )
644 blankvalues[blused++] = Tile(l,0); 644 blankvalues[blused++] = Tile(l,0);
645 if ( node->isWord() && (!nextok || !board->tile(at+d)) ) 645 if ( node->isWord() && (!nextok || !board->tile(at+d)) )
646 noteChoice(tiles,n,d,blankvalues,blused); 646 noteChoice(tiles,n,d,blankvalues,blused);
647 used |= msk; // mark 647 used |= msk; // mark
648 nletter[t->text()[0].unicode()]--; 648 nletter[t->text()[0].unicode()]--;
649 if ( nextok ) 649 if ( nextok )
650 findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused); 650 findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused);
651 n--; 651 n--;
652 nletter[t->text()[0].unicode()]++; 652 nletter[t->text()[0].unicode()]++;
653 if ( t->isBlank() ) { 653 if ( t->isBlank() ) {
654 // keep looking 654 // keep looking
655 blused--; 655 blused--;
656 used &= ~msk; // unmark 656 used &= ~msk; // unmark
657 } else { 657 } else {
658 break; 658 break;
659 } 659 }
660 } 660 }
661 } 661 }
662 msk <<= 1; 662 msk <<= 1;
663 } 663 }
664 } 664 }
665 // #### text()[1]... 665 // #### text()[1]...
666 } 666 }
667 findBest(at, d, node->next(), used, nletter, tiles, n, blankvalues, blused); 667 findBest(at, d, node->next(), used, nletter, tiles, n, blankvalues, blused);
668} 668}
669 669
670void ComputerPlayer::noteChoice(const Tile** tiles, int n, const QPoint& d, const Tile* blankvalues, int blused) 670void ComputerPlayer::noteChoice(const Tile** tiles, int n, const QPoint& d, const Tile* blankvalues, int blused)
671{ 671{
672 int s = board->score(current, tiles, n, blankvalues, d, TRUE, 0); 672 int s = board->score(current, tiles, n, blankvalues, d, TRUE, 0);
673/* 673/*
674if (s>0 || current==QPoint(5,1)){ 674if (s>0 || current==QPoint(5,1)){
675QString st; 675QString st;
676for ( int i=0; i<n; i++ ) 676for ( int i=0; i<n; i++ )
677 st += tiles[i]->text(); 677 st += tiles[i]->text();
678qDebug("%d,%d: %s (%d) for %d",current.x(),current.y(),st.latin1(),n,s); 678odebug << "" << current.x() << "," << current.y() << ": " << st.latin1() << " (" << n << ") for " << s << "" << oendl;
679} 679}
680*/ 680*/
681 if ( s > best_score ) { 681 if ( s > best_score ) {
682 int i; 682 int i;
683 for ( i=0; i<n; i++ ) 683 for ( i=0; i<n; i++ )
684 best[i] = tiles[i]; 684 best[i] = tiles[i];
685 for ( i=0; i<blused; i++ ) 685 for ( i=0; i<blused; i++ )
686 best_blankvalues[i] = blankvalues[i]; 686 best_blankvalues[i] = blankvalues[i];
687 best_n = n; 687 best_n = n;
688 best_blused = blused; 688 best_blused = blused;
689 best_score = s; 689 best_score = s;
690 best_dir = d; 690 best_dir = d;
691 best_start = current; 691 best_start = current;
692 } 692 }
693} 693}
694 694
695int TileItem::smallWidth() 695int TileItem::smallWidth()
696{ 696{
697 return tile_smallw; 697 return tile_smallw;
698} 698}
699 699
700int TileItem::smallHeight() 700int TileItem::smallHeight()
701{ 701{
702 return tile_smallh; 702 return tile_smallh;
703} 703}
704 704
705int TileItem::bigWidth() 705int TileItem::bigWidth()
706{ 706{
707 return tile_bigw; 707 return tile_bigw;
708} 708}
709 709
710int TileItem::bigHeight() 710int TileItem::bigHeight()
711{ 711{
712 return tile_bigh; 712 return tile_bigh;
713} 713}
714 714
715void TileItem::setState( State state ) 715void TileItem::setState( State state )
716{ 716{
717 hide(); 717 hide();
718 s = state; 718 s = state;
719 show(); // ### use update() in Qt 3.0 719 show(); // ### use update() in Qt 3.0
720} 720}
721 721
722void TileItem::setTile(const Tile& tile) 722void TileItem::setTile(const Tile& tile)
723{ 723{
724 hide(); 724 hide();
725 t = tile; 725 t = tile;
726 show(); // ### use update() in Qt 3.0 726 show(); // ### use update() in Qt 3.0
727} 727}
728 728
729void TileItem::setBig(bool b) 729void TileItem::setBig(bool b)
730{ 730{
731 big = b; 731 big = b;
732} 732}
733 733
734void TileItem::drawShape(QPainter& p) 734void TileItem::drawShape(QPainter& p)
735{ 735{
736 static QFont *value_font=0; 736 static QFont *value_font=0;
737 static QFont *big_font=0; 737 static QFont *big_font=0;
738 static QFont *small_font=0; 738 static QFont *small_font=0;
739 if ( !value_font ) { 739 if ( !value_font ) {
740 value_font = new QFont("helvetica",8); 740 value_font = new QFont("helvetica",8);
741 if ( TileItem::bigWidth() < 20 ) { 741 if ( TileItem::bigWidth() < 20 ) {
742 big_font = new QFont("helvetica",12); 742 big_font = new QFont("helvetica",12);
743 small_font = new QFont("helvetica",8); 743 small_font = new QFont("helvetica",8);
744 } else { 744 } else {
745 big_font = new QFont("smoothtimes",17); 745 big_font = new QFont("smoothtimes",17);
746 small_font = new QFont("smoothtimes",10); 746 small_font = new QFont("smoothtimes",10);
747 } 747 }
748 } 748 }
749 749
750 QRect area(x(),y(),width(),height()); 750 QRect area(x(),y(),width(),height());
751 p.setBrush(s == Floating ? yellow/*lightGray*/ : white); 751 p.setBrush(s == Floating ? yellow/*lightGray*/ : white);
752 p.drawRect(area); 752 p.drawRect(area);
753 if ( big ) { 753 if ( big ) {
754 p.setFont(*value_font); 754 p.setFont(*value_font);
755 QString n = QString::number(t.value()); 755 QString n = QString::number(t.value());
756 int w = p.fontMetrics().width('1'); 756 int w = p.fontMetrics().width('1');
757 int h = p.fontMetrics().height(); 757 int h = p.fontMetrics().height();
758 w *= n.length(); 758 w *= n.length();
759 QRect valuearea(x()+width()-w-1,y()+height()-h,w,h); 759 QRect valuearea(x()+width()-w-1,y()+height()-h,w,h);
760 p.drawText(valuearea,AlignCenter,n); 760 p.drawText(valuearea,AlignCenter,n);
761 p.setFont(*big_font); 761 p.setFont(*big_font);
762 area = QRect(x(),y()+tile_btweak,width()-4,height()-1); 762 area = QRect(x(),y()+tile_btweak,width()-4,height()-1);
763 } else { 763 } else {
764 p.setFont(*small_font); 764 p.setFont(*small_font);
765 area = QRect(x()+1+tile_stweak,y()+1,width(),height()-3); 765 area = QRect(x()+1+tile_stweak,y()+1,width(),height()-3);
766 } 766 }
767 if ( t.value() == 0 ) 767 if ( t.value() == 0 )
768 p.setPen(darkGray); 768 p.setPen(darkGray);
769 p.drawText(area,AlignCenter,t.text().upper()); 769 p.drawText(area,AlignCenter,t.text().upper());
770} 770}
771 771
772Board::Board(QPixmap bgshapes, int w, int h, QWidget* parent) : 772Board::Board(QPixmap bgshapes, int w, int h, QWidget* parent) :
773 QCanvasView(new QCanvas(bgshapes,w,h, TileItem::smallWidth(), TileItem::smallHeight()), 773 QCanvasView(new QCanvas(bgshapes,w,h, TileItem::smallWidth(), TileItem::smallHeight()),
774 parent) 774 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 @@
1 config OPIE_EYE 1 config OPIE_EYE
2 boolean "opie-eye The Image Viewer and Browser" 2 boolean "opie-eye The Image Viewer and Browser"
3 default "y" 3 default "y"
4 depends on ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI 4 depends on ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && LIBOPIE2UI
5 5
6 config OPIE_EYE_SLAVE 6 config OPIE_EYE_SLAVE
7 boolean 7 boolean
8 default "y" if OPIE_EYE 8 default "y" if OPIE_EYE
9 depends on ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI 9 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 @@
1/* 1/*
2 * GPLv2 2 * GPLv2
3 * zecke@handhelds.org 3 * zecke@handhelds.org
4 */ 4 */
5 5
6#include "dir_ifaceinfo.h"
7
8/* OPIE */
9#include <opie2/odebug.h>
10#include <qpe/config.h>
11using namespace Opie::Core;
12
13/* QT */
6#include <qwidget.h> 14#include <qwidget.h>
7#include <qcheckbox.h> 15#include <qcheckbox.h>
8#include <qhbox.h> 16#include <qhbox.h>
9#include <qlabel.h> 17#include <qlabel.h>
10 18
11#include <qpe/config.h>
12
13#include "dir_ifaceinfo.h"
14
15namespace { 19namespace {
16 class DirImageWidget : public QHBox { 20 class DirImageWidget : public QHBox {
17 public: 21 public:
18 DirImageWidget() { 22 DirImageWidget() {
19 chkbox = new QCheckBox( QObject::tr("Show all files"), this ); 23 chkbox = new QCheckBox( QObject::tr("Show all files"), this );
20 } 24 }
21 ~DirImageWidget() {} 25 ~DirImageWidget() {}
22 QCheckBox* chkbox; 26 QCheckBox* chkbox;
23 }; 27 };
24} 28}
25 29
26 30
27DirInterfaceInfo::DirInterfaceInfo() { 31DirInterfaceInfo::DirInterfaceInfo() {
28} 32}
29DirInterfaceInfo::~DirInterfaceInfo() { 33DirInterfaceInfo::~DirInterfaceInfo() {
30} 34}
31 35
32QString DirInterfaceInfo::name()const { 36QString DirInterfaceInfo::name()const {
33 return QString::fromLatin1(QObject::tr("DirView" )); 37 return QString::fromLatin1(QObject::tr("DirView" ));
34} 38}
35 39
36QWidget* DirInterfaceInfo::configWidget(const Config& cfg) { 40QWidget* DirInterfaceInfo::configWidget(const Config& cfg) {
37 DirImageWidget* wid = new DirImageWidget(); 41 DirImageWidget* wid = new DirImageWidget();
38 wid->chkbox->setChecked( cfg.readBoolEntry("Dir_Check_All_Files", true) ); 42 wid->chkbox->setChecked( cfg.readBoolEntry("Dir_Check_All_Files", true) );
39 43
40 return wid; 44 return wid;
41} 45}
42 46
43void DirInterfaceInfo::writeConfig( QWidget* _wid, Config& cfg) { 47void DirInterfaceInfo::writeConfig( QWidget* _wid, Config& cfg) {
44 qWarning( "Write Config" ); 48 owarn << "Write Config" << oendl;
45 DirImageWidget* wid = static_cast<DirImageWidget*>(_wid); 49 DirImageWidget* wid = static_cast<DirImageWidget*>(_wid);
46 cfg.writeEntry("Dir_Check_All_Files", wid->chkbox->isChecked() ); 50 cfg.writeEntry("Dir_Check_All_Files", wid->chkbox->isChecked() );
47} 51}
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 @@
1/* 1/*
2 * GPLv2 zecke@handhelds.org 2 * GPLv2 zecke@handhelds.org
3 */ 3 */
4 4
5#include "dir_lister.h" 5#include "dir_lister.h"
6 6
7#include <lib/slavemaster.h> 7#include <lib/slavemaster.h>
8 8
9 9/* OPIE */
10#include <opie2/odebug.h>
10#include <qpe/config.h> 11#include <qpe/config.h>
11#include <qpe/qpeapplication.h> 12#include <qpe/qpeapplication.h>
13using namespace Opie::Core;
12 14
15/* QT */
13#include <qdir.h> 16#include <qdir.h>
14#include <qfileinfo.h> 17#include <qfileinfo.h>
15 18
16
17Dir_DirLister::Dir_DirLister( bool list ) 19Dir_DirLister::Dir_DirLister( bool list )
18 : PDirLister( "dir_dir_lister" ) 20 : PDirLister( "dir_dir_lister" )
19{ 21{
20 m_allFiles = list; 22 m_allFiles = list;
21 qWarning("All Files %d", m_allFiles ); 23 owarn << "All Files " << m_allFiles << "" << oendl;
22 24
23 SlaveMaster* master = SlaveMaster::self(); 25 SlaveMaster* master = SlaveMaster::self();
24 connect( master, SIGNAL(sig_start()), this, SIGNAL(sig_start()) ); 26 connect( master, SIGNAL(sig_start()), this, SIGNAL(sig_start()) );
25 connect( master, SIGNAL(sig_end()), this, SIGNAL(sig_end()) ); 27 connect( master, SIGNAL(sig_end()), this, SIGNAL(sig_end()) );
26 connect( master, SIGNAL(sig_thumbInfo(const QString&, const QString&)), 28 connect( master, SIGNAL(sig_thumbInfo(const QString&, const QString&)),
27 this, SIGNAL(sig_thumbInfo(const QString&, const QString&)) ); 29 this, SIGNAL(sig_thumbInfo(const QString&, const QString&)) );
28 connect( master, SIGNAL(sig_fullInfo(const QString&, const QString&)), 30 connect( master, SIGNAL(sig_fullInfo(const QString&, const QString&)),
29 this, SIGNAL(sig_fullInfo(const QString&, const QString&)) ); 31 this, SIGNAL(sig_fullInfo(const QString&, const QString&)) );
30 connect( master, SIGNAL(sig_thumbNail(const QString&, const QPixmap&)), 32 connect( master, SIGNAL(sig_thumbNail(const QString&, const QPixmap&)),
31 this, SIGNAL(sig_thumbNail(const QString&, const QPixmap&)) ); 33 this, SIGNAL(sig_thumbNail(const QString&, const QPixmap&)) );
32 34
33} 35}
34 36
35QString Dir_DirLister::defaultPath()const { 37QString Dir_DirLister::defaultPath()const {
36 return QPEApplication::documentDir(); 38 return QPEApplication::documentDir();
37} 39}
38 40
39QString Dir_DirLister::setStartPath( const QString& path ) { 41QString Dir_DirLister::setStartPath( const QString& path ) {
40 m_currentDir.cd( path ); 42 m_currentDir.cd( path );
41 if (!m_currentDir.exists() ) 43 if (!m_currentDir.exists() )
42 m_currentDir.cd(defaultPath()); 44 m_currentDir.cd(defaultPath());
43 45
44 46
45 return m_currentDir.absPath(); 47 return m_currentDir.absPath();
46} 48}
47 49
48QString Dir_DirLister::currentPath()const { 50QString Dir_DirLister::currentPath()const {
49 return m_currentDir.absPath(); 51 return m_currentDir.absPath();
50} 52}
51 53
52 54
53QStringList Dir_DirLister::folders()const { 55QStringList Dir_DirLister::folders()const {
54 return m_currentDir.entryList( QDir::Dirs ); 56 return m_currentDir.entryList( QDir::Dirs );
55} 57}
56 58
57QStringList Dir_DirLister::files()const { 59QStringList Dir_DirLister::files()const {
58 if ( m_allFiles ) 60 if ( m_allFiles )
59 return m_currentDir.entryList( QDir::Files ); 61 return m_currentDir.entryList( QDir::Files );
60 else { 62 else {
61 QStringList out; 63 QStringList out;
62 QStringList list = m_currentDir.entryList( QDir::Files | QDir::Readable ); 64 QStringList list = m_currentDir.entryList( QDir::Files | QDir::Readable );
63 for (QStringList::Iterator it = list.begin(); it != list.end();++it ) { 65 for (QStringList::Iterator it = list.begin(); it != list.end();++it ) {
64 QFileInfo inf( *it ); 66 QFileInfo inf( *it );
65 QString ext = inf.extension(false).lower(); 67 QString ext = inf.extension(false).lower();
66 if( ext == QString::fromLatin1("jpg") || 68 if( ext == QString::fromLatin1("jpg") ||
67 ext == QString::fromLatin1("jpeg" ) || 69 ext == QString::fromLatin1("jpeg" ) ||
68 ext == QString::fromLatin1("png" ) || 70 ext == QString::fromLatin1("png" ) ||
69 ext == QString::fromLatin1("gif" ) ) 71 ext == QString::fromLatin1("gif" ) )
70 out.append( *it ); 72 out.append( *it );
71 } 73 }
72 return out; 74 return out;
73 } 75 }
74} 76}
75 77
76void Dir_DirLister::deleteImage( const QString& fl) { 78void Dir_DirLister::deleteImage( const QString& fl) {
77 QFile::remove( fl ); 79 QFile::remove( fl );
78} 80}
79 81
80void Dir_DirLister::thumbNail( const QString& str, int w, int h) { 82void Dir_DirLister::thumbNail( const QString& str, int w, int h) {
81 SlaveMaster::self()->thumbNail( str, w, h ); 83 SlaveMaster::self()->thumbNail( str, w, h );
82} 84}
83 85
84QImage Dir_DirLister::image( const QString& str, Factor f, int m) { 86QImage Dir_DirLister::image( const QString& str, Factor f, int m) {
85 return SlaveMaster::self()->image( str, f, m ); 87 return SlaveMaster::self()->image( str, f, m );
86} 88}
87 89
88void Dir_DirLister::imageInfo( const QString& str) { 90void Dir_DirLister::imageInfo( const QString& str) {
89 SlaveMaster::self()->thumbInfo( str ); 91 SlaveMaster::self()->thumbInfo( str );
90} 92}
91 93
92void Dir_DirLister::fullImageInfo( const QString& str) { 94void Dir_DirLister::fullImageInfo( const QString& str) {
93 SlaveMaster::self()->imageInfo( str ); 95 SlaveMaster::self()->imageInfo( str );
94} 96}
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 @@
1#include "slavemaster.h" 1#include "slavemaster.h"
2 2
3/* OPIE */
4#include <opie2/odebug.h>
3#include <qpe/qpeapplication.h> 5#include <qpe/qpeapplication.h>
4#include <qpe/qcopenvelope_qws.h> 6#include <qpe/qcopenvelope_qws.h>
7using namespace Opie::Core;
5 8
9/* QT */
6#include <qcopchannel_qws.h> 10#include <qcopchannel_qws.h>
7#include <qtimer.h> 11#include <qtimer.h>
8 12
9QDataStream & operator << (QDataStream & str, bool b) 13QDataStream & operator << (QDataStream & str, bool b)
10{ 14{
11 str << Q_INT8(b); 15 str << Q_INT8(b);
12 return str; 16 return str;
13} 17}
14QDataStream & operator >> (QDataStream & str, bool & b) 18QDataStream & operator >> (QDataStream & str, bool & b)
15{ 19{
16 Q_INT8 l; 20 Q_INT8 l;
17 str >> l; 21 str >> l;
18 b = bool(l); 22 b = bool(l);
19 return str; 23 return str;
20} 24}
21 25
22/* 26/*
23 * ! We don't put a Pixmap in!!!! 27 * ! We don't put a Pixmap in!!!!
24 */ 28 */
25QDataStream &operator<<( QDataStream& s, const PixmapInfo& inf) { 29QDataStream &operator<<( QDataStream& s, const PixmapInfo& inf) {
26 qWarning( "Image request is %s %d %d", inf.file.latin1(), inf.width, inf.height ); 30 owarn << "Image request is " << inf.file.latin1() << " " << inf.width << " " << inf.height << "" << oendl;
27 return s << inf.file << inf.width << inf.height; 31 return s << inf.file << inf.width << inf.height;
28} 32}
29QDataStream &operator>>( QDataStream& s, PixmapInfo& inf ) { 33QDataStream &operator>>( QDataStream& s, PixmapInfo& inf ) {
30 s >> inf.file >> inf.pixmap >> inf.width >> inf.height; 34 s >> inf.file >> inf.pixmap >> inf.width >> inf.height;
31 return s; 35 return s;
32} 36}
33QDataStream &operator<<( QDataStream& s, const ImageInfo& i) { 37QDataStream &operator<<( QDataStream& s, const ImageInfo& i) {
34 return s << i.kind << i.file << i.info; 38 return s << i.kind << i.file << i.info;
35} 39}
36QDataStream &operator>>( QDataStream& s, ImageInfo& i ) { 40QDataStream &operator>>( QDataStream& s, ImageInfo& i ) {
37 s >> i.kind >> i.file >> i.info; 41 s >> i.kind >> i.file >> i.info;
38 return s; 42 return s;
39} 43}
40 44
41 45
42 46
43SlaveMaster* SlaveMaster::m_master = 0; 47SlaveMaster* SlaveMaster::m_master = 0;
44 48
45SlaveMaster::SlaveMaster() 49SlaveMaster::SlaveMaster()
46 : m_started( false ) 50 : m_started( false )
47{ 51{
48 QCopChannel *chan= new QCopChannel( "QPE/opie-eye",this ); 52 QCopChannel *chan= new QCopChannel( "QPE/opie-eye",this );
49 connect(chan, SIGNAL(received(const QCString&,const QByteArray&)), 53 connect(chan, SIGNAL(received(const QCString&,const QByteArray&)),
50 this, SLOT(recieve(const QCString&,const QByteArray&)) ); 54 this, SLOT(recieve(const QCString&,const QByteArray&)) );
51} 55}
52 56
53SlaveMaster::~SlaveMaster() { 57SlaveMaster::~SlaveMaster() {
54} 58}
55 59
56SlaveMaster* SlaveMaster::self() { 60SlaveMaster* SlaveMaster::self() {
57 if ( !m_master ) 61 if ( !m_master )
58 m_master = new SlaveMaster; 62 m_master = new SlaveMaster;
59 return m_master; 63 return m_master;
60} 64}
61 65
62void SlaveMaster::thumbInfo( const QString& str) { 66void SlaveMaster::thumbInfo( const QString& str) {
63 m_inThumbInfo.append( str ); 67 m_inThumbInfo.append( str );
64 68
65 if ( !m_started ) { 69 if ( !m_started ) {
66 QTimer::singleShot( 0, this, SLOT(slotTimerStart())); 70 QTimer::singleShot( 0, this, SLOT(slotTimerStart()));
67 m_started = true; 71 m_started = true;
68 } 72 }
69} 73}
70 74
71void SlaveMaster::imageInfo( const QString& str ) { 75void SlaveMaster::imageInfo( const QString& str ) {
72 m_inImageInfo.append( str ); 76 m_inImageInfo.append( str );
73 if ( !m_started ) { 77 if ( !m_started ) {
74 QTimer::singleShot( 0, this, SLOT(slotTimerStart())); 78 QTimer::singleShot( 0, this, SLOT(slotTimerStart()));
75 m_started = true; 79 m_started = true;
76 } 80 }
77} 81}
78 82
79void SlaveMaster::thumbNail( const QString& str, int w, int h ) { 83void SlaveMaster::thumbNail( const QString& str, int w, int h ) {
80 if ( str.isEmpty() ) { 84 if ( str.isEmpty() ) {
81 qWarning( "Asking for empty nail" ); 85 owarn << "Asking for empty nail" << oendl;
82 return; 86 return;
83 } 87 }
84 qWarning( "Asking for thumbNail in size %d %d" + str, w,h ); 88 owarn << "Asking for thumbNail in size " << w << " " << h << "" + str << oendl;
85 PixmapInfo item; 89 PixmapInfo item;
86 item.file = str; item.width = w; item.height = h; 90 item.file = str; item.width = w; item.height = h;
87 item.pixmap = QPixmap(); 91 item.pixmap = QPixmap();
88 m_inThumbNail.append( item ); 92 m_inThumbNail.append( item );
89 93
90 if ( !m_started ) { 94 if ( !m_started ) {
91 QTimer::singleShot( 0, this, SLOT(slotTimerStart())); 95 QTimer::singleShot( 0, this, SLOT(slotTimerStart()));
92 m_started = true; 96 m_started = true;
93 } 97 }
94} 98}
95 99
96 100
97void SlaveMaster::recieve( const QCString& str, const QByteArray& at) { 101void SlaveMaster::recieve( const QCString& str, const QByteArray& at) {
98 102
99 ImageInfos infos; 103 ImageInfos infos;
100 PixmapInfos pixinfos; 104 PixmapInfos pixinfos;
101 105
102 QDataStream stream( at, IO_ReadOnly ); 106 QDataStream stream( at, IO_ReadOnly );
103 if ( str == "pixmapsHandled(PixmapList)" ) 107 if ( str == "pixmapsHandled(PixmapList)" )
104 stream >> pixinfos; 108 stream >> pixinfos;
105 else if ( str == "pixmapsHandled(StringList)" ) 109 else if ( str == "pixmapsHandled(StringList)" )
106 stream >> infos; 110 stream >> infos;
107 111
108 qWarning( "PixInfos %d", pixinfos.count() ); 112 owarn << "PixInfos " << pixinfos.count() << "" << oendl;
109 113
110 bool got_data = ( !infos.isEmpty() || !pixinfos.isEmpty() ); 114 bool got_data = ( !infos.isEmpty() || !pixinfos.isEmpty() );
111 if ( got_data ) { 115 if ( got_data ) {
112 emit sig_start(); 116 emit sig_start();
113 for ( ImageInfos::Iterator _it = infos.begin(); _it != infos.end(); ++_it ) { 117 for ( ImageInfos::Iterator _it = infos.begin(); _it != infos.end(); ++_it ) {
114 if ( (*_it).kind ) 118 if ( (*_it).kind )
115 emit sig_fullInfo( (*_it).file, (*_it).info ); 119 emit sig_fullInfo( (*_it).file, (*_it).info );
116 else 120 else
117 emit sig_thumbInfo( (*_it).file, (*_it).info ); 121 emit sig_thumbInfo( (*_it).file, (*_it).info );
118 } 122 }
119 123
120 for ( PixmapInfos::Iterator it = pixinfos.begin(); it != pixinfos.end(); ++it ) 124 for ( PixmapInfos::Iterator it = pixinfos.begin(); it != pixinfos.end(); ++it )
121 emit sig_thumbNail( (*it).file, (*it).pixmap ); 125 emit sig_thumbNail( (*it).file, (*it).pixmap );
122 emit sig_end(); 126 emit sig_end();
123 } 127 }
124} 128}
125 129
126void SlaveMaster::slotTimerStart() { 130void SlaveMaster::slotTimerStart() {
127 m_started = false; 131 m_started = false;
128 132
129 if ( !m_inThumbInfo.isEmpty() ) { 133 if ( !m_inThumbInfo.isEmpty() ) {
130 QCopEnvelope env("QPE/opie-eye_slave", "thumbInfos(QStringList)" ); 134 QCopEnvelope env("QPE/opie-eye_slave", "thumbInfos(QStringList)" );
131 env << m_inThumbInfo; 135 env << m_inThumbInfo;
132 } 136 }
133 if ( !m_inImageInfo.isEmpty() ) { 137 if ( !m_inImageInfo.isEmpty() ) {
134 QCopEnvelope env("QPE/opie-eye_slave", "fullInfos(QStringList)" ); 138 QCopEnvelope env("QPE/opie-eye_slave", "fullInfos(QStringList)" );
135 env << m_inImageInfo; 139 env << m_inImageInfo;
136 } 140 }
137 if ( !m_inThumbNail.isEmpty() ) { 141 if ( !m_inThumbNail.isEmpty() ) {
138 QCopEnvelope env("QPE/opie-eye_slave", "pixmapInfos(PixmapInfos)" ); 142 QCopEnvelope env("QPE/opie-eye_slave", "pixmapInfos(PixmapInfos)" );
139 env << m_inThumbNail; 143 env << m_inThumbNail;
140 } 144 }
141 145
142 146
143 m_inThumbInfo.clear(); 147 m_inThumbInfo.clear();
144 m_inImageInfo.clear(); 148 m_inImageInfo.clear();
145 m_inThumbNail.clear(); 149 m_inThumbNail.clear();
146} 150}
147 151
148QImage SlaveMaster::image( const QString& str, PDirLister::Factor, int ) { 152QImage SlaveMaster::image( const QString& str, PDirLister::Factor, int ) {
149 return QImage(); 153 return QImage();
150} 154}
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 @@
1CONFIG += qt warn_on quick-app 1CONFIG += qt warn_on quick-app
2DESTDIR = $(OPIEDIR)/bin 2DESTDIR = $(OPIEDIR)/bin
3TEMPLATE = app 3TEMPLATE = app
4TARGET = opie-eye 4TARGET = opie-eye
5# the name of the resulting object 5# the name of the resulting object
6 6
7HEADERS = gui/iconview.h gui/filesystem.h gui/mainwindow.h \ 7HEADERS = gui/iconview.h gui/filesystem.h gui/mainwindow.h \
8 lib/imagecache.h impl/dir/dir_dirview.h \ 8 lib/imagecache.h impl/dir/dir_dirview.h \
9 iface/dirview.h iface/dirlister.h iface/ifaceinfo.h \ 9 iface/dirview.h iface/dirlister.h iface/ifaceinfo.h \
10 impl/dir/dir_lister.h impl/dir/dir_ifaceinfo.h \ 10 impl/dir/dir_lister.h impl/dir/dir_ifaceinfo.h \
11 lib/slavemaster.h \ 11 lib/slavemaster.h \
12 iface/slaveiface.h \ 12 iface/slaveiface.h \
13 gui/imageinfoui.h 13 gui/imageinfoui.h
14 14
15# A list header files 15# A list header files
16 16
17 17
18SOURCES = gui/iconview.cpp gui/filesystem.cpp gui/mainwindow.cpp \ 18SOURCES = gui/iconview.cpp gui/filesystem.cpp gui/mainwindow.cpp \
19 lib/imagecache.cpp lib/viewmap.cpp \ 19 lib/imagecache.cpp lib/viewmap.cpp \
20 impl/dir/dir_dirview.cpp iface/dirlister.cpp \ 20 impl/dir/dir_dirview.cpp iface/dirlister.cpp \
21 iface/dirview.cpp impl/dir/dir_lister.cpp \ 21 iface/dirview.cpp impl/dir/dir_lister.cpp \
22 impl/dir/dir_ifaceinfo.cpp lib/slavemaster.cpp \ 22 impl/dir/dir_ifaceinfo.cpp lib/slavemaster.cpp \
23 gui/imageinfoui.cpp 23 gui/imageinfoui.cpp
24# A list of source files 24# A list of source files
25 25
26INTERFACES = 26INTERFACES =
27# list of ui files 27# list of ui files
28 28
29INCLUDEPATH += . $(OPIEDIR)/include 29INCLUDEPATH += . $(OPIEDIR)/include
30DEPENDPATH += $(OPIEDIR)/include 30DEPENDPATH += $(OPIEDIR)/include
31 31
32 32
33 33
34LIBS += -lqpe -lopieui2 34LIBS += -lqpe -lopiecore2 -lopieui2
35 35
36include ( $(OPIEDIR)/include.pro ) 36include ( $(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 @@
1#include "jpeg_slave.h" 1#include "jpeg_slave.h"
2
3#include "thumbnailtool.h" 2#include "thumbnailtool.h"
4 3
5PHUNK_VIEW_INTERFACE( "JPEG", JpegSlave ) 4PHUNK_VIEW_INTERFACE( "JPEG", JpegSlave )
6 5
7#include <qtopia/timestring.h> 6/* OPIE */
7#include <opie2/odebug.h>
8#include <qpe/timestring.h>
9using namespace Opie::Core;
10
11/* QT */
8#include <qobject.h> 12#include <qobject.h>
9#include <qimage.h> 13#include <qimage.h>
10 14
11/** 15/**
12 exif.h 16 exif.h
13*/ 17*/
14 18
15#include <stdio.h> 19#include <stdio.h>
16#include <stdlib.h> 20#include <stdlib.h>
17#include <math.h> 21#include <math.h>
18#include <time.h> 22#include <time.h>
19 23
20#include <qstring.h> 24#include <qstring.h>
21#include <qfile.h> 25#include <qfile.h>
22#include <qimage.h> 26#include <qimage.h>
23 27
24typedef enum { 28typedef enum {
25 READ_EXIF = 1, 29 READ_EXIF = 1,
26 READ_IMAGE = 2, 30 READ_IMAGE = 2,
27 READ_ALL = 3 31 READ_ALL = 3
28}ReadMode_t; 32}ReadMode_t;
29 33
30//-------------------------------------------------------------------------- 34//--------------------------------------------------------------------------
31// This structure is used to store jpeg file sections in memory. 35// This structure is used to store jpeg file sections in memory.
32typedef struct { 36typedef struct {
33 uchar * Data; 37 uchar * Data;
34 int Type; 38 int Type;
35 unsigned Size; 39 unsigned Size;
36}Section_t; 40}Section_t;
37 41
38typedef unsigned char uchar; 42typedef unsigned char uchar;
39 43
40typedef struct { 44typedef struct {
41 unsigned short Tag; 45 unsigned short Tag;
42 const char*const Desc; 46 const char*const Desc;
43}TagTable_t; 47}TagTable_t;
44 48
45#define MAX_SECTIONS 20 49#define MAX_SECTIONS 20
46#define PSEUDO_IMAGE_MARKER 0x123; // Extra value. 50#define PSEUDO_IMAGE_MARKER 0x123; // Extra value.
47 51
48class ExifData { 52class ExifData {
49 Section_t Sections[MAX_SECTIONS]; 53 Section_t Sections[MAX_SECTIONS];
50 54
51 QString CameraMake; 55 QString CameraMake;
52 QString CameraModel; 56 QString CameraModel;
53 QString DateTime; 57 QString DateTime;
54 int Orientation; 58 int Orientation;
55 int Height, Width; 59 int Height, Width;
56 int ExifImageLength, ExifImageWidth; 60 int ExifImageLength, ExifImageWidth;
57 int IsColor; 61 int IsColor;
58 int Process; 62 int Process;
59 int FlashUsed; 63 int FlashUsed;
60 float FocalLength; 64 float FocalLength;
61 float ExposureTime; 65 float ExposureTime;
62 float ApertureFNumber; 66 float ApertureFNumber;
63 float Distance; 67 float Distance;
64 int Whitebalance; 68 int Whitebalance;
65 int MeteringMode; 69 int MeteringMode;
66 float CCDWidth; 70 float CCDWidth;
67 float ExposureBias; 71 float ExposureBias;
68 int ExposureProgram; 72 int ExposureProgram;
69 int ISOequivalent; 73 int ISOequivalent;
70 int CompressionLevel; 74 int CompressionLevel;
71 QString UserComment; 75 QString UserComment;
72 QString Comment; 76 QString Comment;
73 QImage Thumbnail; 77 QImage Thumbnail;
74 78
75 int ReadJpegSections (QFile & infile, ReadMode_t ReadMode); 79 int ReadJpegSections (QFile & infile, ReadMode_t ReadMode);
76 void DiscardData(void); 80 void DiscardData(void);
77 int Get16u(void * Short); 81 int Get16u(void * Short);
78 int Get32s(void * Long); 82 int Get32s(void * Long);
79 unsigned Get32u(void * Long); 83 unsigned Get32u(void * Long);
80 double ConvertAnyFormat(void * ValuePtr, int Format); 84 double ConvertAnyFormat(void * ValuePtr, int Format);
81 void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength); 85 void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength);
82 void process_COM (const uchar * Data, int length); 86 void process_COM (const uchar * Data, int length);
83 void process_SOFn (const uchar * Data, int marker); 87 void process_SOFn (const uchar * Data, int marker);
84 int Get16m(const void * Short); 88 int Get16m(const void * Short);
85 void process_EXIF(unsigned char * CharBuf, unsigned int length); 89 void process_EXIF(unsigned char * CharBuf, unsigned int length);
86 int Exif2tm(struct tm * timeptr, char * ExifTime); 90 int Exif2tm(struct tm * timeptr, char * ExifTime);
87 91
88public: 92public:
89 ExifData(); 93 ExifData();
90 bool scan(const QString &); 94 bool scan(const QString &);
91 QString getCameraMake() { return CameraMake; } 95 QString getCameraMake() { return CameraMake; }
92 QString getCameraModel() { return CameraModel; } 96 QString getCameraModel() { return CameraModel; }
93 QString getDateTime() { return DateTime; } 97 QString getDateTime() { return DateTime; }
94 int getOrientation() { return Orientation; } 98 int getOrientation() { return Orientation; }
95 int getHeight() { return Height; } 99 int getHeight() { return Height; }
96 int getWidth() { return Width; } 100 int getWidth() { return Width; }
97 int getIsColor() { return IsColor; } 101 int getIsColor() { return IsColor; }
98 int getProcess() { return Process; } 102 int getProcess() { return Process; }
99 int getFlashUsed() { return FlashUsed; } 103 int getFlashUsed() { return FlashUsed; }
100 float getFocalLength() { return FocalLength; } 104 float getFocalLength() { return FocalLength; }
101 float getExposureTime() { return ExposureTime; } 105 float getExposureTime() { return ExposureTime; }
102 float getApertureFNumber() { return ApertureFNumber; } 106 float getApertureFNumber() { return ApertureFNumber; }
103 float getDistance() { return Distance; } 107 float getDistance() { return Distance; }
104 int getWhitebalance() { return Whitebalance; } 108 int getWhitebalance() { return Whitebalance; }
105 int getMeteringMode() { return MeteringMode; } 109 int getMeteringMode() { return MeteringMode; }
106 float getCCDWidth() { return CCDWidth; } 110 float getCCDWidth() { return CCDWidth; }
107 float getExposureBias() { return ExposureBias; } 111 float getExposureBias() { return ExposureBias; }
108 int getExposureProgram() { return ExposureProgram; } 112 int getExposureProgram() { return ExposureProgram; }
109 int getISOequivalent() { return ISOequivalent; } 113 int getISOequivalent() { return ISOequivalent; }
110 int getCompressionLevel() { return CompressionLevel; } 114 int getCompressionLevel() { return CompressionLevel; }
111 QString getUserComment() { return UserComment; } 115 QString getUserComment() { return UserComment; }
112 QString getComment() { return Comment; } 116 QString getComment() { return Comment; }
113 QImage getThumbnail(); 117 QImage getThumbnail();
114 bool isThumbnailSane(); 118 bool isThumbnailSane();
115 bool isNullThumbnail() { return !isThumbnailSane(); } 119 bool isNullThumbnail() { return !isThumbnailSane(); }
116}; 120};
117 121
118class FatalError { 122class FatalError {
119 const char* ex; 123 const char* ex;
120public: 124public:
121 FatalError(const char* s) { ex = s; } 125 FatalError(const char* s) { ex = s; }
122 void debug_print() const { qWarning("exception: %s", ex ); } 126 void debug_print() const { owarn << "exception: " << ex << "" << oendl; }
123}; 127};
124 128
125 129
126 130
127static unsigned char * LastExifRefd; 131static unsigned char * LastExifRefd;
128static int ExifSettingsLength; 132static int ExifSettingsLength;
129static double FocalplaneXRes; 133static double FocalplaneXRes;
130static double FocalplaneUnits; 134static double FocalplaneUnits;
131static int MotorolaOrder = 0; 135static int MotorolaOrder = 0;
132static int SectionsRead; 136static int SectionsRead;
133//static int HaveAll; 137//static int HaveAll;
134 138
135//-------------------------------------------------------------------------- 139//--------------------------------------------------------------------------
136// Table of Jpeg encoding process names 140// Table of Jpeg encoding process names
137 141
138#define M_SOF0 0xC0 // Start Of Frame N 142#define M_SOF0 0xC0 // Start Of Frame N
139#define M_SOF1 0xC1 // N indicates which compression process 143#define M_SOF1 0xC1 // N indicates which compression process
140#define M_SOF2 0xC2 // Only SOF0-SOF2 are now in common use 144#define M_SOF2 0xC2 // Only SOF0-SOF2 are now in common use
141#define M_SOF3 0xC3 145#define M_SOF3 0xC3
142#define M_SOF5 0xC5 // NB: codes C4 and CC are NOT SOF markers 146#define M_SOF5 0xC5 // NB: codes C4 and CC are NOT SOF markers
143#define M_SOF6 0xC6 147#define M_SOF6 0xC6
144#define M_SOF7 0xC7 148#define M_SOF7 0xC7
145#define M_SOF9 0xC9 149#define M_SOF9 0xC9
146#define M_SOF10 0xCA 150#define M_SOF10 0xCA
147#define M_SOF11 0xCB 151#define M_SOF11 0xCB
148#define M_SOF13 0xCD 152#define M_SOF13 0xCD
149#define M_SOF14 0xCE 153#define M_SOF14 0xCE
150#define M_SOF15 0xCF 154#define M_SOF15 0xCF
151#define M_SOI 0xD8 // Start Of Image (beginning of datastream) 155#define M_SOI 0xD8 // Start Of Image (beginning of datastream)
152#define M_EOI 0xD9 // End Of Image (end of datastream) 156#define M_EOI 0xD9 // End Of Image (end of datastream)
153#define M_SOS 0xDA // Start Of Scan (begins compressed data) 157#define M_SOS 0xDA // Start Of Scan (begins compressed data)
154#define M_JFIF 0xE0 // Jfif marker 158#define M_JFIF 0xE0 // Jfif marker
155#define M_EXIF 0xE1 // Exif marker 159#define M_EXIF 0xE1 // Exif marker
156#define M_COM 0xFE // COMment 160#define M_COM 0xFE // COMment
157 161
158 162
159TagTable_t ProcessTable[] = { 163TagTable_t ProcessTable[] = {
160 { M_SOF0, "Baseline"}, 164 { M_SOF0, "Baseline"},
161 { M_SOF1, "Extended sequential"}, 165 { M_SOF1, "Extended sequential"},
162 { M_SOF2, "Progressive"}, 166 { M_SOF2, "Progressive"},
163 { M_SOF3, "Lossless"}, 167 { M_SOF3, "Lossless"},
164 { M_SOF5, "Differential sequential"}, 168 { M_SOF5, "Differential sequential"},
165 { M_SOF6, "Differential progressive"}, 169 { M_SOF6, "Differential progressive"},
166 { M_SOF7, "Differential lossless"}, 170 { M_SOF7, "Differential lossless"},
167 { M_SOF9, "Extended sequential, arithmetic coding"}, 171 { M_SOF9, "Extended sequential, arithmetic coding"},
168 { M_SOF10, "Progressive, arithmetic coding"}, 172 { M_SOF10, "Progressive, arithmetic coding"},
169 { M_SOF11, "Lossless, arithmetic coding"}, 173 { M_SOF11, "Lossless, arithmetic coding"},
170 { M_SOF13, "Differential sequential, arithmetic coding"}, 174 { M_SOF13, "Differential sequential, arithmetic coding"},
171 { M_SOF14, "Differential progressive, arithmetic coding"}, 175 { M_SOF14, "Differential progressive, arithmetic coding"},
172 { M_SOF15, "Differential lossless, arithmetic coding"}, 176 { M_SOF15, "Differential lossless, arithmetic coding"},
173 { 0, "Unknown"} 177 { 0, "Unknown"}
174}; 178};
175 179
176 180
177 181
178//-------------------------------------------------------------------------- 182//--------------------------------------------------------------------------
179// Describes format descriptor 183// Describes format descriptor
180static int BytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8}; 184static int BytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8};
181#define NUM_FORMATS 12 185#define NUM_FORMATS 12
182 186
183#define FMT_BYTE 1 187#define FMT_BYTE 1
184#define FMT_STRING 2 188#define FMT_STRING 2
185#define FMT_USHORT 3 189#define FMT_USHORT 3
186#define FMT_ULONG 4 190#define FMT_ULONG 4
187#define FMT_URATIONAL 5 191#define FMT_URATIONAL 5
188#define FMT_SBYTE 6 192#define FMT_SBYTE 6
189#define FMT_UNDEFINED 7 193#define FMT_UNDEFINED 7
190#define FMT_SSHORT 8 194#define FMT_SSHORT 8
191#define FMT_SLONG 9 195#define FMT_SLONG 9
192#define FMT_SRATIONAL 10 196#define FMT_SRATIONAL 10
193#define FMT_SINGLE 11 197#define FMT_SINGLE 11
194#define FMT_DOUBLE 12 198#define FMT_DOUBLE 12
195 199
196//-------------------------------------------------------------------------- 200//--------------------------------------------------------------------------
197// Describes tag values 201// Describes tag values
198 202
199#define TAG_EXIF_OFFSET 0x8769 203#define TAG_EXIF_OFFSET 0x8769
200#define TAG_INTEROP_OFFSET 0xa005 204#define TAG_INTEROP_OFFSET 0xa005
201 205
202#define TAG_MAKE 0x010F 206#define TAG_MAKE 0x010F
203#define TAG_MODEL 0x0110 207#define TAG_MODEL 0x0110
204#define TAG_ORIENTATION 0x0112 208#define TAG_ORIENTATION 0x0112
205 209
206#define TAG_EXPOSURETIME 0x829A 210#define TAG_EXPOSURETIME 0x829A
207#define TAG_FNUMBER 0x829D 211#define TAG_FNUMBER 0x829D
208 212
209#define TAG_SHUTTERSPEED 0x9201 213#define TAG_SHUTTERSPEED 0x9201
210#define TAG_APERTURE 0x9202 214#define TAG_APERTURE 0x9202
211#define TAG_MAXAPERTURE 0x9205 215#define TAG_MAXAPERTURE 0x9205
212#define TAG_FOCALLENGTH 0x920A 216#define TAG_FOCALLENGTH 0x920A
213 217
214#define TAG_DATETIME_ORIGINAL 0x9003 218#define TAG_DATETIME_ORIGINAL 0x9003
215#define TAG_USERCOMMENT 0x9286 219#define TAG_USERCOMMENT 0x9286
216 220
217#define TAG_SUBJECT_DISTANCE 0x9206 221#define TAG_SUBJECT_DISTANCE 0x9206
218#define TAG_FLASH 0x9209 222#define TAG_FLASH 0x9209
219 223
220#define TAG_FOCALPLANEXRES 0xa20E 224#define TAG_FOCALPLANEXRES 0xa20E
221#define TAG_FOCALPLANEUNITS 0xa210 225#define TAG_FOCALPLANEUNITS 0xa210
222#define TAG_EXIF_IMAGEWIDTH 0xA002 226#define TAG_EXIF_IMAGEWIDTH 0xA002
223#define TAG_EXIF_IMAGELENGTH 0xA003 227#define TAG_EXIF_IMAGELENGTH 0xA003
224 228
225// the following is added 05-jan-2001 vcs 229// the following is added 05-jan-2001 vcs
226#define TAG_EXPOSURE_BIAS 0x9204 230#define TAG_EXPOSURE_BIAS 0x9204
227#define TAG_WHITEBALANCE 0x9208 231#define TAG_WHITEBALANCE 0x9208
228#define TAG_METERING_MODE 0x9207 232#define TAG_METERING_MODE 0x9207
229#define TAG_EXPOSURE_PROGRAM 0x8822 233#define TAG_EXPOSURE_PROGRAM 0x8822
230#define TAG_ISO_EQUIVALENT 0x8827 234#define TAG_ISO_EQUIVALENT 0x8827
231#define TAG_COMPRESSION_LEVEL 0x9102 235#define TAG_COMPRESSION_LEVEL 0x9102
232 236
233#define TAG_THUMBNAIL_OFFSET 0x0201 237#define TAG_THUMBNAIL_OFFSET 0x0201
234#define TAG_THUMBNAIL_LENGTH 0x0202 238#define TAG_THUMBNAIL_LENGTH 0x0202
235 239
236 240
237 241
238 242
239//-------------------------------------------------------------------------- 243//--------------------------------------------------------------------------
240// Parse the marker stream until SOS or EOI is seen; 244// Parse the marker stream until SOS or EOI is seen;
241//-------------------------------------------------------------------------- 245//--------------------------------------------------------------------------
242int ExifData::ReadJpegSections (QFile & infile, ReadMode_t ReadMode) 246int ExifData::ReadJpegSections (QFile & infile, ReadMode_t ReadMode)
243{ 247{
244 int a; 248 int a;
245 249
246 a = infile.getch(); 250 a = infile.getch();
247 251
248 if (a != 0xff || infile.getch() != M_SOI) { 252 if (a != 0xff || infile.getch() != M_SOI) {
249 SectionsRead = 0; 253 SectionsRead = 0;
250 return false; 254 return false;
251 } 255 }
252 for(SectionsRead = 0; SectionsRead < MAX_SECTIONS-1; ){ 256 for(SectionsRead = 0; SectionsRead < MAX_SECTIONS-1; ){
253 int marker = 0; 257 int marker = 0;
254 int got; 258 int got;
255 unsigned int ll,lh; 259 unsigned int ll,lh;
256 unsigned int itemlen; 260 unsigned int itemlen;
257 uchar * Data; 261 uchar * Data;
258 262
259 for (a=0;a<7;a++){ 263 for (a=0;a<7;a++){
260 marker = infile.getch(); 264 marker = infile.getch();
261 if (marker != 0xff) break; 265 if (marker != 0xff) break;
262 266
263 if (a >= 6){ 267 if (a >= 6){
264 268
265 qWarning( "too many padding bytes" ); 269 owarn << "too many padding bytes" << oendl;
266 return false; 270 return false;
267 271
268 } 272 }
269 } 273 }
270 274
271 if (marker == 0xff){ 275 if (marker == 0xff){
272 // 0xff is legal padding, but if we get that many, something's wrong. 276 // 0xff is legal padding, but if we get that many, something's wrong.
273 return false; 277 return false;
274 } 278 }
275 279
276 Sections[SectionsRead].Type = marker; 280 Sections[SectionsRead].Type = marker;
277 281
278 // Read the length of the section. 282 // Read the length of the section.
279 lh = (uchar) infile.getch(); 283 lh = (uchar) infile.getch();
280 ll = (uchar) infile.getch(); 284 ll = (uchar) infile.getch();
281 285
282 itemlen = (lh << 8) | ll; 286 itemlen = (lh << 8) | ll;
283 287
284 if (itemlen < 2) { 288 if (itemlen < 2) {
285 return false;; 289 return false;;
286 } 290 }
287 291
288 Sections[SectionsRead].Size = itemlen; 292 Sections[SectionsRead].Size = itemlen;
289 293
290 Data = (uchar *)malloc(itemlen+1); // Add 1 to allow sticking a 0 at the end. 294 Data = (uchar *)malloc(itemlen+1); // Add 1 to allow sticking a 0 at the end.
291 Sections[SectionsRead].Data = Data; 295 Sections[SectionsRead].Data = Data;
292 296
293 // Store first two pre-read bytes. 297 // Store first two pre-read bytes.
294 Data[0] = (uchar)lh; 298 Data[0] = (uchar)lh;
295 Data[1] = (uchar)ll; 299 Data[1] = (uchar)ll;
296 300
297 got = infile.readBlock((char*)Data+2, itemlen-2); // Read the whole section. 301 got = infile.readBlock((char*)Data+2, itemlen-2); // Read the whole section.
298 if (( unsigned ) got != itemlen-2){ 302 if (( unsigned ) got != itemlen-2){
299 return false; 303 return false;
300 } 304 }
301 SectionsRead++; 305 SectionsRead++;
302 306
303 switch(marker){ 307 switch(marker){
304 308
305 case M_SOS: // stop before hitting compressed data 309 case M_SOS: // stop before hitting compressed data
306 // If reading entire image is requested, read the rest of the data. 310 // If reading entire image is requested, read the rest of the data.
307 if (ReadMode & READ_IMAGE){ 311 if (ReadMode & READ_IMAGE){
308 unsigned long size; 312 unsigned long size;
309 313
310 size = QMAX( 0ul, infile.size()-infile.at() ); 314 size = QMAX( 0ul, infile.size()-infile.at() );
311 Data = (uchar *)malloc(size); 315 Data = (uchar *)malloc(size);
312 if (Data == NULL){ 316 if (Data == NULL){
313 return false; 317 return false;
314 } 318 }
315 319
316 got = infile.readBlock((char*)Data, size); 320 got = infile.readBlock((char*)Data, size);
317 if (( unsigned ) got != size){ 321 if (( unsigned ) got != size){
318 return false; 322 return false;
319 } 323 }
320 324
321 Sections[SectionsRead].Data = Data; 325 Sections[SectionsRead].Data = Data;
322 Sections[SectionsRead].Size = size; 326 Sections[SectionsRead].Size = size;
323 Sections[SectionsRead].Type = PSEUDO_IMAGE_MARKER; 327 Sections[SectionsRead].Type = PSEUDO_IMAGE_MARKER;
324 SectionsRead ++; 328 SectionsRead ++;
325 //HaveAll = 1; 329 //HaveAll = 1;
326 } 330 }
327 return true; 331 return true;
328 332
329 case M_EOI: // in case it's a tables-only JPEG stream 333 case M_EOI: // in case it's a tables-only JPEG stream
330 qWarning( "No image in jpeg!" ); 334 owarn << "No image in jpeg!" << oendl;
331 return false; 335 return false;
332 336
333 case M_COM: // Comment section 337 case M_COM: // Comment section
334 // pieczy 2002-02-12 338 // pieczy 2002-02-12
335 // now the User comment goes to UserComment 339 // now the User comment goes to UserComment
336 // so we can store a Comment section also in READ_EXIF mode 340 // so we can store a Comment section also in READ_EXIF mode
337 process_COM(Data, itemlen); 341 process_COM(Data, itemlen);
338 break; 342 break;
339 343
340 case M_JFIF: 344 case M_JFIF:
341 // Regular jpegs always have this tag, exif images have the exif 345 // Regular jpegs always have this tag, exif images have the exif
342 // marker instead, althogh ACDsee will write images with both markers. 346 // marker instead, althogh ACDsee will write images with both markers.
343 // this program will re-create this marker on absence of exif marker. 347 // this program will re-create this marker on absence of exif marker.
344 // hence no need to keep the copy from the file. 348 // hence no need to keep the copy from the file.
345 free(Sections[--SectionsRead].Data); 349 free(Sections[--SectionsRead].Data);
346 break; 350 break;
347 351
348 case M_EXIF: 352 case M_EXIF:
349 // Seen files from some 'U-lead' software with Vivitar scanner 353 // Seen files from some 'U-lead' software with Vivitar scanner
350 // that uses marker 31 for non exif stuff. Thus make sure 354 // that uses marker 31 for non exif stuff. Thus make sure
351 // it says 'Exif' in the section before treating it as exif. 355 // it says 'Exif' in the section before treating it as exif.
352 if ((ReadMode & READ_EXIF) && memcmp(Data+2, "Exif", 4) == 0){ 356 if ((ReadMode & READ_EXIF) && memcmp(Data+2, "Exif", 4) == 0){
353 process_EXIF((uchar *)Data, itemlen); 357 process_EXIF((uchar *)Data, itemlen);
354 }else{ 358 }else{
355 // Discard this section. 359 // Discard this section.
356 free(Sections[--SectionsRead].Data); 360 free(Sections[--SectionsRead].Data);
357 } 361 }
358 break; 362 break;
359 363
360 case M_SOF0: 364 case M_SOF0:
361 case M_SOF1: 365 case M_SOF1:
362 case M_SOF2: 366 case M_SOF2:
363 case M_SOF3: 367 case M_SOF3:
364 case M_SOF5: 368 case M_SOF5:
365 case M_SOF6: 369 case M_SOF6:
366 case M_SOF7: 370 case M_SOF7:
367 case M_SOF9: 371 case M_SOF9:
368 case M_SOF10: 372 case M_SOF10:
369 case M_SOF11: 373 case M_SOF11:
370 case M_SOF13: 374 case M_SOF13:
371 case M_SOF14: 375 case M_SOF14:
372 case M_SOF15: 376 case M_SOF15:
373 process_SOFn(Data, marker); 377 process_SOFn(Data, marker);
374 default: 378 default:
375 break; 379 break;
376 break; 380 break;
377 } 381 }
378 } 382 }
379 return true; 383 return true;
380} 384}
381 385
382 386
383//-------------------------------------------------------------------------- 387//--------------------------------------------------------------------------
384// Discard read data. 388// Discard read data.
385//-------------------------------------------------------------------------- 389//--------------------------------------------------------------------------
386void ExifData::DiscardData(void) 390void ExifData::DiscardData(void)
387{ 391{
388 for (int a=0; a < SectionsRead; a++) 392 for (int a=0; a < SectionsRead; a++)
389 free(Sections[a].Data); 393 free(Sections[a].Data);
390 SectionsRead = 0; 394 SectionsRead = 0;
391} 395}
392 396
393//-------------------------------------------------------------------------- 397//--------------------------------------------------------------------------
394// Convert a 16 bit unsigned value from file's native byte order 398// Convert a 16 bit unsigned value from file's native byte order
395//-------------------------------------------------------------------------- 399//--------------------------------------------------------------------------
396int ExifData::Get16u(void * Short) 400int ExifData::Get16u(void * Short)
397{ 401{
398 if (MotorolaOrder){ 402 if (MotorolaOrder){
399 return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1]; 403 return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1];
400 }else{ 404 }else{
401 return (((uchar *)Short)[1] << 8) | ((uchar *)Short)[0]; 405 return (((uchar *)Short)[1] << 8) | ((uchar *)Short)[0];
402 } 406 }
403} 407}
404 408
405//-------------------------------------------------------------------------- 409//--------------------------------------------------------------------------
406// Convert a 32 bit signed value from file's native byte order 410// Convert a 32 bit signed value from file's native byte order
407//-------------------------------------------------------------------------- 411//--------------------------------------------------------------------------
408int ExifData::Get32s(void * Long) 412int ExifData::Get32s(void * Long)
409{ 413{
410 if (MotorolaOrder){ 414 if (MotorolaOrder){
411 return ((( char *)Long)[0] << 24) | (((uchar *)Long)[1] << 16) 415 return ((( char *)Long)[0] << 24) | (((uchar *)Long)[1] << 16)
412 | (((uchar *)Long)[2] << 8 ) | (((uchar *)Long)[3] << 0 ); 416 | (((uchar *)Long)[2] << 8 ) | (((uchar *)Long)[3] << 0 );
413 }else{ 417 }else{
414 return ((( char *)Long)[3] << 24) | (((uchar *)Long)[2] << 16) 418 return ((( char *)Long)[3] << 24) | (((uchar *)Long)[2] << 16)
415 | (((uchar *)Long)[1] << 8 ) | (((uchar *)Long)[0] << 0 ); 419 | (((uchar *)Long)[1] << 8 ) | (((uchar *)Long)[0] << 0 );
416 } 420 }
417} 421}
418 422
419//-------------------------------------------------------------------------- 423//--------------------------------------------------------------------------
420// Convert a 32 bit unsigned value from file's native byte order 424// Convert a 32 bit unsigned value from file's native byte order
421//-------------------------------------------------------------------------- 425//--------------------------------------------------------------------------
422unsigned ExifData::Get32u(void * Long) 426unsigned ExifData::Get32u(void * Long)
423{ 427{
424 return (unsigned)Get32s(Long) & 0xffffffff; 428 return (unsigned)Get32s(Long) & 0xffffffff;
425} 429}
426 430
@@ -633,380 +637,380 @@ void ExifData::ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBa
633 637
634 case TAG_EXIF_IMAGELENGTH: 638 case TAG_EXIF_IMAGELENGTH:
635 ExifImageLength = (int)ConvertAnyFormat(ValuePtr, Format); 639 ExifImageLength = (int)ConvertAnyFormat(ValuePtr, Format);
636 break; 640 break;
637 641
638 case TAG_EXIF_IMAGEWIDTH: 642 case TAG_EXIF_IMAGEWIDTH:
639 ExifImageWidth = (int)ConvertAnyFormat(ValuePtr, Format); 643 ExifImageWidth = (int)ConvertAnyFormat(ValuePtr, Format);
640 break; 644 break;
641 645
642 case TAG_FOCALPLANEXRES: 646 case TAG_FOCALPLANEXRES:
643 FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format); 647 FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format);
644 break; 648 break;
645 649
646 case TAG_FOCALPLANEUNITS: 650 case TAG_FOCALPLANEUNITS:
647 switch((int)ConvertAnyFormat(ValuePtr, Format)){ 651 switch((int)ConvertAnyFormat(ValuePtr, Format)){
648 case 1: FocalplaneUnits = 25.4; break; // inch 652 case 1: FocalplaneUnits = 25.4; break; // inch
649 case 2: 653 case 2:
650 // According to the information I was using, 2 means meters. 654 // According to the information I was using, 2 means meters.
651 // But looking at the Cannon powershot's files, inches is the only 655 // But looking at the Cannon powershot's files, inches is the only
652 // sensible value. 656 // sensible value.
653 FocalplaneUnits = 25.4; 657 FocalplaneUnits = 25.4;
654 break; 658 break;
655 659
656 case 3: FocalplaneUnits = 10; break; // centimeter 660 case 3: FocalplaneUnits = 10; break; // centimeter
657 case 4: FocalplaneUnits = 1; break; // milimeter 661 case 4: FocalplaneUnits = 1; break; // milimeter
658 case 5: FocalplaneUnits = .001; break; // micrometer 662 case 5: FocalplaneUnits = .001; break; // micrometer
659 } 663 }
660 break; 664 break;
661 665
662 // Remaining cases contributed by: Volker C. Schoech (schoech@gmx.de) 666 // Remaining cases contributed by: Volker C. Schoech (schoech@gmx.de)
663 667
664 case TAG_EXPOSURE_BIAS: 668 case TAG_EXPOSURE_BIAS:
665 ExifData::ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format); 669 ExifData::ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format);
666 break; 670 break;
667 671
668 case TAG_WHITEBALANCE: 672 case TAG_WHITEBALANCE:
669 ExifData::Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format); 673 ExifData::Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format);
670 break; 674 break;
671 675
672 case TAG_METERING_MODE: 676 case TAG_METERING_MODE:
673 ExifData::MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format); 677 ExifData::MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format);
674 break; 678 break;
675 679
676 case TAG_EXPOSURE_PROGRAM: 680 case TAG_EXPOSURE_PROGRAM:
677 ExifData::ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format); 681 ExifData::ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format);
678 break; 682 break;
679 683
680 case TAG_ISO_EQUIVALENT: 684 case TAG_ISO_EQUIVALENT:
681 ExifData::ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format); 685 ExifData::ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
682 if ( ExifData::ISOequivalent < 50 ) ExifData::ISOequivalent *= 200; 686 if ( ExifData::ISOequivalent < 50 ) ExifData::ISOequivalent *= 200;
683 break; 687 break;
684 688
685 case TAG_COMPRESSION_LEVEL: 689 case TAG_COMPRESSION_LEVEL:
686 ExifData::CompressionLevel = (int)ConvertAnyFormat(ValuePtr, Format); 690 ExifData::CompressionLevel = (int)ConvertAnyFormat(ValuePtr, Format);
687 break; 691 break;
688 692
689 case TAG_THUMBNAIL_OFFSET: 693 case TAG_THUMBNAIL_OFFSET:
690 ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format); 694 ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format);
691 break; 695 break;
692 696
693 case TAG_THUMBNAIL_LENGTH: 697 case TAG_THUMBNAIL_LENGTH:
694 ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format); 698 ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format);
695 break; 699 break;
696 700
697 } 701 }
698 702
699 if (Tag == TAG_EXIF_OFFSET || Tag == TAG_INTEROP_OFFSET){ 703 if (Tag == TAG_EXIF_OFFSET || Tag == TAG_INTEROP_OFFSET){
700 unsigned char * SubdirStart; 704 unsigned char * SubdirStart;
701 SubdirStart = OffsetBase + Get32u(ValuePtr); 705 SubdirStart = OffsetBase + Get32u(ValuePtr);
702 if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){ 706 if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
703 return; 707 return;
704 } 708 }
705 ProcessExifDir(SubdirStart, OffsetBase, ExifLength); 709 ProcessExifDir(SubdirStart, OffsetBase, ExifLength);
706 continue; 710 continue;
707 } 711 }
708 } 712 }
709 713
710 { 714 {
711 // In addition to linking to subdirectories via exif tags, 715 // In addition to linking to subdirectories via exif tags,
712 // there's also a potential link to another directory at the end of each 716 // there's also a potential link to another directory at the end of each
713 // directory. this has got to be the result of a comitee! 717 // directory. this has got to be the result of a comitee!
714 unsigned char * SubdirStart; 718 unsigned char * SubdirStart;
715 unsigned Offset; 719 unsigned Offset;
716 720
717 if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){ 721 if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){
718 Offset = Get32u(DIR_ENTRY_ADDR(DirStart, NumDirEntries)); 722 Offset = Get32u(DIR_ENTRY_ADDR(DirStart, NumDirEntries));
719 // There is at least one jpeg from an HP camera having an Offset of almost MAXUINT. 723 // There is at least one jpeg from an HP camera having an Offset of almost MAXUINT.
720 // Adding OffsetBase to it produces an overflow, so compare with ExifLength here. 724 // Adding OffsetBase to it produces an overflow, so compare with ExifLength here.
721 // See http://bugs.kde.org/show_bug.cgi?id=54542 725 // See http://bugs.kde.org/show_bug.cgi?id=54542
722 if (Offset && Offset < ExifLength){ 726 if (Offset && Offset < ExifLength){
723 SubdirStart = OffsetBase + Offset; 727 SubdirStart = OffsetBase + Offset;
724 if (SubdirStart > OffsetBase+ExifLength){ 728 if (SubdirStart > OffsetBase+ExifLength){
725 if (SubdirStart < OffsetBase+ExifLength+20){ 729 if (SubdirStart < OffsetBase+ExifLength+20){
726 // Jhead 1.3 or earlier would crop the whole directory! 730 // Jhead 1.3 or earlier would crop the whole directory!
727 // As Jhead produces this form of format incorrectness, 731 // As Jhead produces this form of format incorrectness,
728 // I'll just let it pass silently 732 // I'll just let it pass silently
729 qWarning( "Thumbnail removed with Jhead 1.3 or earlier" ); 733 owarn << "Thumbnail removed with Jhead 1.3 or earlier" << oendl;
730 }else{ 734 }else{
731 return; 735 return;
732 } 736 }
733 }else{ 737 }else{
734 if (SubdirStart <= OffsetBase+ExifLength){ 738 if (SubdirStart <= OffsetBase+ExifLength){
735 ProcessExifDir(SubdirStart, OffsetBase, ExifLength); 739 ProcessExifDir(SubdirStart, OffsetBase, ExifLength);
736 } 740 }
737 } 741 }
738 } 742 }
739 }else{ 743 }else{
740 // The exif header ends before the last next directory pointer. 744 // The exif header ends before the last next directory pointer.
741 } 745 }
742 } 746 }
743 747
744 if (ThumbnailSize && ThumbnailOffset){ 748 if (ThumbnailSize && ThumbnailOffset){
745 if (ThumbnailSize + ThumbnailOffset <= ExifLength){ 749 if (ThumbnailSize + ThumbnailOffset <= ExifLength){
746 // The thumbnail pointer appears to be valid. Store it. 750 // The thumbnail pointer appears to be valid. Store it.
747 Thumbnail.loadFromData(OffsetBase + ThumbnailOffset, ThumbnailSize, "JPEG"); 751 Thumbnail.loadFromData(OffsetBase + ThumbnailOffset, ThumbnailSize, "JPEG");
748 } 752 }
749 } 753 }
750} 754}
751 755
752//-------------------------------------------------------------------------- 756//--------------------------------------------------------------------------
753// Process a COM marker. We want to leave the bytes unchanged. The 757// Process a COM marker. We want to leave the bytes unchanged. The
754// progam that displays this text may decide to remove blanks, convert 758// progam that displays this text may decide to remove blanks, convert
755// newlines, or otherwise modify the text. In particular we want to be 759// newlines, or otherwise modify the text. In particular we want to be
756// safe for passing utf-8 text. 760// safe for passing utf-8 text.
757//-------------------------------------------------------------------------- 761//--------------------------------------------------------------------------
758void ExifData::process_COM (const uchar * Data, int length) 762void ExifData::process_COM (const uchar * Data, int length)
759{ 763{
760 QChar ch; 764 QChar ch;
761 int a; 765 int a;
762 766
763 for (a=2;a<length;a++){ 767 for (a=2;a<length;a++){
764 ch = Data[a]; 768 ch = Data[a];
765 if (ch == '\000') continue; // Remove nulls 769 if (ch == '\000') continue; // Remove nulls
766 Comment.append(ch); 770 Comment.append(ch);
767 } 771 }
768} 772}
769 773
770 774
771//-------------------------------------------------------------------------- 775//--------------------------------------------------------------------------
772// Process a SOFn marker. This is useful for the image dimensions 776// Process a SOFn marker. This is useful for the image dimensions
773//-------------------------------------------------------------------------- 777//--------------------------------------------------------------------------
774void ExifData::process_SOFn (const uchar * Data, int marker) 778void ExifData::process_SOFn (const uchar * Data, int marker)
775{ 779{
776 int data_precision, num_components; 780 int data_precision, num_components;
777 781
778 data_precision = Data[2]; 782 data_precision = Data[2];
779 ExifData::Height = Get16m(Data+3); 783 ExifData::Height = Get16m(Data+3);
780 ExifData::Width = Get16m(Data+5); 784 ExifData::Width = Get16m(Data+5);
781 num_components = Data[7]; 785 num_components = Data[7];
782 786
783 if (num_components == 3){ 787 if (num_components == 3){
784 ExifData::IsColor = 1; 788 ExifData::IsColor = 1;
785 }else{ 789 }else{
786 ExifData::IsColor = 0; 790 ExifData::IsColor = 0;
787 } 791 }
788 792
789 ExifData::Process = marker; 793 ExifData::Process = marker;
790 794
791} 795}
792 796
793//-------------------------------------------------------------------------- 797//--------------------------------------------------------------------------
794// Get 16 bits motorola order (always) for jpeg header stuff. 798// Get 16 bits motorola order (always) for jpeg header stuff.
795//-------------------------------------------------------------------------- 799//--------------------------------------------------------------------------
796int ExifData::Get16m(const void * Short) 800int ExifData::Get16m(const void * Short)
797{ 801{
798 return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1]; 802 return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1];
799} 803}
800 804
801 805
802//-------------------------------------------------------------------------- 806//--------------------------------------------------------------------------
803// Process a EXIF marker 807// Process a EXIF marker
804// Describes all the drivel that most digital cameras include... 808// Describes all the drivel that most digital cameras include...
805//-------------------------------------------------------------------------- 809//--------------------------------------------------------------------------
806void ExifData::process_EXIF(unsigned char * CharBuf, unsigned int length) 810void ExifData::process_EXIF(unsigned char * CharBuf, unsigned int length)
807{ 811{
808 ExifData::FlashUsed = 0; // If it s from a digicam, and it used flash, it says so. 812 ExifData::FlashUsed = 0; // If it s from a digicam, and it used flash, it says so.
809 813
810 FocalplaneXRes = 0; 814 FocalplaneXRes = 0;
811 FocalplaneUnits = 0; 815 FocalplaneUnits = 0;
812 ExifImageWidth = 0; 816 ExifImageWidth = 0;
813 ExifImageLength = 0; 817 ExifImageLength = 0;
814 818
815 { // Check the EXIF header component 819 { // Check the EXIF header component
816 static const uchar ExifHeader[] = "Exif\0\0"; 820 static const uchar ExifHeader[] = "Exif\0\0";
817 if (memcmp(CharBuf+2, ExifHeader,6)){ 821 if (memcmp(CharBuf+2, ExifHeader,6)){
818 return; 822 return;
819 } 823 }
820 } 824 }
821 825
822 if (memcmp(CharBuf+8,"II",2) == 0){ 826 if (memcmp(CharBuf+8,"II",2) == 0){
823 // printf("Exif section in Intel order\n"); 827 // printf("Exif section in Intel order\n");
824 MotorolaOrder = 0; 828 MotorolaOrder = 0;
825 }else{ 829 }else{
826 if (memcmp(CharBuf+8,"MM",2) == 0){ 830 if (memcmp(CharBuf+8,"MM",2) == 0){
827 // printf("Exif section in Motorola order\n"); 831 // printf("Exif section in Motorola order\n");
828 MotorolaOrder = 1; 832 MotorolaOrder = 1;
829 }else{ 833 }else{
830 return; 834 return;
831 } 835 }
832 } 836 }
833 837
834 // Check the next two values for correctness. 838 // Check the next two values for correctness.
835 if (Get16u(CharBuf+10) != 0x2a 839 if (Get16u(CharBuf+10) != 0x2a
836 || Get32u(CharBuf+12) != 0x08){ 840 || Get32u(CharBuf+12) != 0x08){
837 return; 841 return;
838 } 842 }
839 843
840 LastExifRefd = CharBuf; 844 LastExifRefd = CharBuf;
841 845
842 // First directory starts 16 bytes in. Offsets start at 8 bytes in. 846 // First directory starts 16 bytes in. Offsets start at 8 bytes in.
843 ProcessExifDir(CharBuf+16, CharBuf+8, length-6); 847 ProcessExifDir(CharBuf+16, CharBuf+8, length-6);
844 848
845 // This is how far the interesting (non thumbnail) part of the exif went. 849 // This is how far the interesting (non thumbnail) part of the exif went.
846 ExifSettingsLength = LastExifRefd - CharBuf; 850 ExifSettingsLength = LastExifRefd - CharBuf;
847 851
848 // Compute the CCD width, in milimeters. 852 // Compute the CCD width, in milimeters.
849 if (FocalplaneXRes != 0){ 853 if (FocalplaneXRes != 0){
850 ExifData::CCDWidth = (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes); 854 ExifData::CCDWidth = (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes);
851 } 855 }
852} 856}
853 857
854//-------------------------------------------------------------------------- 858//--------------------------------------------------------------------------
855// Convert exif time to Unix time structure 859// Convert exif time to Unix time structure
856//-------------------------------------------------------------------------- 860//--------------------------------------------------------------------------
857int ExifData::Exif2tm(struct tm * timeptr, char * ExifTime) 861int ExifData::Exif2tm(struct tm * timeptr, char * ExifTime)
858{ 862{
859 int a; 863 int a;
860 864
861 timeptr->tm_wday = -1; 865 timeptr->tm_wday = -1;
862 866
863 // Check for format: YYYY:MM:DD HH:MM:SS format. 867 // Check for format: YYYY:MM:DD HH:MM:SS format.
864 a = sscanf(ExifTime, "%d:%d:%d %d:%d:%d", 868 a = sscanf(ExifTime, "%d:%d:%d %d:%d:%d",
865 &timeptr->tm_year, &timeptr->tm_mon, &timeptr->tm_mday, 869 &timeptr->tm_year, &timeptr->tm_mon, &timeptr->tm_mday,
866 &timeptr->tm_hour, &timeptr->tm_min, &timeptr->tm_sec); 870 &timeptr->tm_hour, &timeptr->tm_min, &timeptr->tm_sec);
867 871
868 if (a == 6){ 872 if (a == 6){
869 timeptr->tm_isdst = -1; 873 timeptr->tm_isdst = -1;
870 timeptr->tm_mon -= 1; // Adjust for unix zero-based months 874 timeptr->tm_mon -= 1; // Adjust for unix zero-based months
871 timeptr->tm_year -= 1900; // Adjust for year starting at 1900 875 timeptr->tm_year -= 1900; // Adjust for year starting at 1900
872 return true; // worked. 876 return true; // worked.
873 } 877 }
874 878
875 return false; // Wasn't in Exif date format. 879 return false; // Wasn't in Exif date format.
876} 880}
877 881
878//-------------------------------------------------------------------------- 882//--------------------------------------------------------------------------
879// Contructor for initialising 883// Contructor for initialising
880//-------------------------------------------------------------------------- 884//--------------------------------------------------------------------------
881ExifData::ExifData() 885ExifData::ExifData()
882{ 886{
883 ExifData::Whitebalance = -1; 887 ExifData::Whitebalance = -1;
884 ExifData::MeteringMode = -1; 888 ExifData::MeteringMode = -1;
885 ExifData::FlashUsed = -1; 889 ExifData::FlashUsed = -1;
886 Orientation = 0; 890 Orientation = 0;
887 Height = 0; 891 Height = 0;
888 Width = 0; 892 Width = 0;
889 IsColor = 0; 893 IsColor = 0;
890 Process = 0; 894 Process = 0;
891 FocalLength = 0; 895 FocalLength = 0;
892 ExposureTime = 0; 896 ExposureTime = 0;
893 ApertureFNumber = 0; 897 ApertureFNumber = 0;
894 Distance = 0; 898 Distance = 0;
895 CCDWidth = 0; 899 CCDWidth = 0;
896 ExposureBias = 0; 900 ExposureBias = 0;
897 ExposureProgram = 0; 901 ExposureProgram = 0;
898 ISOequivalent = 0; 902 ISOequivalent = 0;
899 CompressionLevel = 0; 903 CompressionLevel = 0;
900} 904}
901 905
902//-------------------------------------------------------------------------- 906//--------------------------------------------------------------------------
903// process a EXIF jpeg file 907// process a EXIF jpeg file
904//-------------------------------------------------------------------------- 908//--------------------------------------------------------------------------
905bool ExifData::scan(const QString & path) 909bool ExifData::scan(const QString & path)
906{ 910{
907 int ret; 911 int ret;
908 912
909 QFile f(path); 913 QFile f(path);
910 f.open(IO_ReadOnly); 914 f.open(IO_ReadOnly);
911 915
912 // Scan the JPEG headers. 916 // Scan the JPEG headers.
913 ret = ReadJpegSections(f, READ_EXIF); 917 ret = ReadJpegSections(f, READ_EXIF);
914 918
915 if (ret == false){ 919 if (ret == false){
916 qWarning( "Not JPEG file!" ); 920 owarn << "Not JPEG file!" << oendl;
917 DiscardData(); 921 DiscardData();
918 f.close(); 922 f.close();
919 return false; 923 return false;
920 } 924 }
921 f.close(); 925 f.close();
922 DiscardData(); 926 DiscardData();
923 927
924 //now make the strings clean, 928 //now make the strings clean,
925 // for exmaple my Casio is a "QV-4000 " 929 // for exmaple my Casio is a "QV-4000 "
926 CameraMake = CameraMake.stripWhiteSpace(); 930 CameraMake = CameraMake.stripWhiteSpace();
927 CameraModel = CameraModel.stripWhiteSpace(); 931 CameraModel = CameraModel.stripWhiteSpace();
928 UserComment = UserComment.stripWhiteSpace(); 932 UserComment = UserComment.stripWhiteSpace();
929 Comment = Comment.stripWhiteSpace(); 933 Comment = Comment.stripWhiteSpace();
930 return true; 934 return true;
931} 935}
932 936
933//-------------------------------------------------------------------------- 937//--------------------------------------------------------------------------
934// Does the embedded thumbnail match the jpeg image? 938// Does the embedded thumbnail match the jpeg image?
935//-------------------------------------------------------------------------- 939//--------------------------------------------------------------------------
936#ifndef JPEG_TOL 940#ifndef JPEG_TOL
937#define JPEG_TOL 0.02 941#define JPEG_TOL 0.02
938#endif 942#endif
939bool ExifData::isThumbnailSane() { 943bool ExifData::isThumbnailSane() {
940 if (Thumbnail.isNull()) return false; 944 if (Thumbnail.isNull()) return false;
941 945
942 // check whether thumbnail dimensions match the image 946 // check whether thumbnail dimensions match the image
943 // not foolproof, but catches some altered images (jpegtran -rotate) 947 // not foolproof, but catches some altered images (jpegtran -rotate)
944 if (ExifImageLength != 0 && ExifImageLength != Height) return false; 948 if (ExifImageLength != 0 && ExifImageLength != Height) return false;
945 if (ExifImageWidth != 0 && ExifImageWidth != Width) return false; 949 if (ExifImageWidth != 0 && ExifImageWidth != Width) return false;
946 if (Thumbnail.width() == 0 || Thumbnail.height() == 0) return false; 950 if (Thumbnail.width() == 0 || Thumbnail.height() == 0) return false;
947 if (Height == 0 || Width == 0) return false; 951 if (Height == 0 || Width == 0) return false;
948 double d = (double)Height/Width*Thumbnail.width()/Thumbnail.height(); 952 double d = (double)Height/Width*Thumbnail.width()/Thumbnail.height();
949 return (1-JPEG_TOL < d) && (d < 1+JPEG_TOL); 953 return (1-JPEG_TOL < d) && (d < 1+JPEG_TOL);
950} 954}
951 955
952 956
953 957
954static QImage flip_image( const QImage& img ); 958static QImage flip_image( const QImage& img );
955static QImage rotate_90( const QImage& img ); 959static QImage rotate_90( const QImage& img );
956static QImage rotate_180( const QImage& ); 960static QImage rotate_180( const QImage& );
957static QImage rotate_270( const QImage& ); 961static QImage rotate_270( const QImage& );
958 962
959//-------------------------------------------------------------------------- 963//--------------------------------------------------------------------------
960// return a thumbnail that respects the orientation flag 964// return a thumbnail that respects the orientation flag
961// only if it seems sane 965// only if it seems sane
962//-------------------------------------------------------------------------- 966//--------------------------------------------------------------------------
963QImage ExifData::getThumbnail() { 967QImage ExifData::getThumbnail() {
964 if (!isThumbnailSane()) return NULL; 968 if (!isThumbnailSane()) return NULL;
965 if (!Orientation || Orientation == 1) return Thumbnail; 969 if (!Orientation || Orientation == 1) return Thumbnail;
966 970
967 // now fix orientation 971 // now fix orientation
968 972
969 QImage dest = Thumbnail; 973 QImage dest = Thumbnail;
970 switch (Orientation) { // notice intentional fallthroughs 974 switch (Orientation) { // notice intentional fallthroughs
971 case 2: dest = flip_image( dest ); break; 975 case 2: dest = flip_image( dest ); break;
972 case 4: dest = flip_image( dest ); 976 case 4: dest = flip_image( dest );
973 case 3: dest =rotate_180( dest ); break; 977 case 3: dest =rotate_180( dest ); break;
974 case 5: dest = flip_image( dest ); 978 case 5: dest = flip_image( dest );
975 case 6: dest = rotate_90( dest ); break; 979 case 6: dest = rotate_90( dest ); break;
976 case 7: dest = flip_image( dest ); 980 case 7: dest = flip_image( dest );
977 case 8: dest = rotate_270( dest ); break; 981 case 8: dest = rotate_270( dest ); break;
978 default: break; // should never happen 982 default: break; // should never happen
979 } 983 }
980 return dest; 984 return dest;
981} 985}
982 986
983 987
984/* 988/*
985 * 989 *
986 */ 990 */
987static QImage flip_image( const QImage& img ) { 991static QImage flip_image( const QImage& img ) {
988 return img.mirror( TRUE, FALSE ); 992 return img.mirror( TRUE, FALSE );
989} 993}
990 994
991 995
992static QImage dest; 996static QImage dest;
993static int x, y; 997static int x, y;
994static unsigned int *srcData, *destData; // we're not threaded anyway 998static unsigned int *srcData, *destData; // we're not threaded anyway
995static unsigned char *srcData8, *destData8; // 8 bit is char 999static unsigned char *srcData8, *destData8; // 8 bit is char
996static unsigned int *srcTable, *destTable; // destination table 1000static unsigned int *srcTable, *destTable; // destination table
997 1001
998 1002
999static QImage rotate_90_8( const QImage &img ) { 1003static QImage rotate_90_8( const QImage &img ) {
1000 dest.create(img.height(), img.width(), img.depth()); 1004 dest.create(img.height(), img.width(), img.depth());
1001 dest.setNumColors(img.numColors()); 1005 dest.setNumColors(img.numColors());
1002 srcTable = (unsigned int *)img.colorTable(); 1006 srcTable = (unsigned int *)img.colorTable();
1003 destTable = (unsigned int *)dest.colorTable(); 1007 destTable = (unsigned int *)dest.colorTable();
1004 for ( x=0; x < img.numColors(); ++x ) 1008 for ( x=0; x < img.numColors(); ++x )
1005 destTable[x] = srcTable[x]; 1009 destTable[x] = srcTable[x];
1006 for ( y=0; y < img.height(); ++y ){ 1010 for ( y=0; y < img.height(); ++y ){
1007 srcData8 = (unsigned char *)img.scanLine(y); 1011 srcData8 = (unsigned char *)img.scanLine(y);
1008 for ( x=0; x < img.width(); ++x ){ 1012 for ( x=0; x < img.width(); ++x ){
1009 destData8 = (unsigned char *)dest.scanLine(x); 1013 destData8 = (unsigned char *)dest.scanLine(x);
1010 destData8[img.height()-y-1] = srcData8[x]; 1014 destData8[img.height()-y-1] = srcData8[x];
1011 } 1015 }
1012 } 1016 }
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 @@
1/* 1/*
2 * GPLv2 Slave Main 2 * GPLv2 Slave Main
3 */ 3 */
4 4
5#include "gif_slave.h" 5#include "gif_slave.h"
6#include "png_slave.h" 6#include "png_slave.h"
7#include "jpeg_slave.h" 7#include "jpeg_slave.h"
8#include "thumbnailtool.h" 8#include "thumbnailtool.h"
9#include "slavereciever.h" 9#include "slavereciever.h"
10 10
11#include <qpixmap.h> 11#include <qpixmap.h>
12#include <qcopchannel_qws.h> 12#include <qcopchannel_qws.h>
13 13
14#include <qtopia/qpeapplication.h> 14#include <qtopia/qpeapplication.h>
15 15
16int main( int argc, char* argv[] ) { 16int main( int argc, char* argv[] ) {
17 QPEApplication app( argc, argv ); 17 QPEApplication app( argc, argv );
18 SlaveReciever rec( 0 ); 18 SlaveReciever rec( 0 );
19 19
20 QCopChannel chan( "QPE/opie-eye_slave" ); 20 QCopChannel chan( "QPE/opie-eye_slave" );
21 QObject::connect(&chan,SIGNAL(received(const QCString&, const QByteArray&)), 21 QObject::connect(&chan,SIGNAL(received(const QCString&, const QByteArray&)),
22 &rec, SLOT(recieveAnswer(const QCString&,const QByteArray&))); 22 &rec, SLOT(recieveAnswer(const QCString&,const QByteArray&)));
23 QObject::connect(qApp,SIGNAL(appMessage(const QCString&, const QByteArray&)), 23 QObject::connect(qApp,SIGNAL(appMessage(const QCString&, const QByteArray&)),
24 &rec, SLOT(recieveAnswer(const QCString&,const QByteArray&))); 24 &rec, SLOT(recieveAnswer(const QCString&,const QByteArray&)));
25 25
26 return app.exec(); 26 return app.exec();
27} 27}
28 28
29#ifdef DEBUG_IT 29#ifdef DEBUG_IT
30int main( int argc, char* argv[] ) { 30int main( int argc, char* argv[] ) {
31 QString str = QString::fromLatin1(argv[2] ); 31 QString str = QString::fromLatin1(argv[2] );
32 QApplication app( argc, argv ); 32 QApplication app( argc, argv );
33 GifSlave slave; 33 GifSlave slave;
34 qWarning( str +" "+slave.iconViewName(str ) ); 34 owarn << str +" "+slave.iconViewName(str ) << oendl;
35 qWarning( str+" "+slave.fullImageInfo( str ) ); 35 owarn << str+" "+slave.fullImageInfo( str ) << oendl;
36 36
37 PNGSlave pngslave; 37 PNGSlave pngslave;
38 qWarning( str + " " + pngslave.iconViewName(str) ); 38 owarn << str + " " + pngslave.iconViewName(str) << oendl;
39 qWarning( str + " " + pngslave.fullImageInfo(str)); 39 owarn << str + " " + pngslave.fullImageInfo(str) << oendl;
40 40
41 41
42 JpegSlave jpgslave; 42 JpegSlave jpgslave;
43 qWarning( str + " " + jpgslave.iconViewName(str ) ); 43 owarn << str + " " + jpgslave.iconViewName(str ) << oendl;
44 qWarning( str + " " + jpgslave.fullImageInfo( str ) ); 44 owarn << str + " " + jpgslave.fullImageInfo( str ) << oendl;
45//return app.exec(); 45//return app.exec();
46 QPixmap pix = ThumbNailTool::getThumb( str, 24, 24 ); 46 QPixmap pix = ThumbNailTool::getThumb( str, 24, 24 );
47 if ( pix.isNull() ) { 47 if ( pix.isNull() ) {
48 qWarning( "No Thumbnail" ); 48 owarn << "No Thumbnail" << oendl;
49 pix = slave.pixmap(str, 24, 24); 49 pix = slave.pixmap(str, 24, 24);
50 } 50 }
51 51
52 if (!pix.isNull() ) { 52 if (!pix.isNull() ) {
53 qWarning( "Saving Thumbnail" ); 53 owarn << "Saving Thumbnail" << oendl;
54 ThumbNailTool::putThumb( str, pix, 24, 24 ); 54 ThumbNailTool::putThumb( str, pix, 24, 24 );
55 } 55 }
56 56
57} 57}
58 58
59#endif 59#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 @@
1CONFIG += qte 1CONFIG = qt
2TEMPLATE = app 2TEMPLATE = app
3TARGET = opie-eye_slave 3TARGET = opie-eye_slave
4DESTDIR = $(OPIEDIR)/bin 4DESTDIR = $(OPIEDIR)/bin
5 5
6HEADERS = gif_slave.h slaveiface.h slavereciever.h \ 6HEADERS = gif_slave.h slaveiface.h slavereciever.h \
7 thumbnailtool.h png_slave.h jpeg_slave.h \ 7 thumbnailtool.h png_slave.h jpeg_slave.h \
8 ../iface/slaveiface.h 8 ../iface/slaveiface.h
9SOURCES = main.cpp gif_slave.cpp slavereciever.cpp \ 9SOURCES = main.cpp gif_slave.cpp slavereciever.cpp \
10 slaveiface.cpp thumbnailtool.cpp png_slave.cpp \ 10 slaveiface.cpp thumbnailtool.cpp png_slave.cpp \
11 jpeg_slave.cpp 11 jpeg_slave.cpp
12 12
13INCLUDEPATH += $(OPIEDIR)/include ../ 13INCLUDEPATH += $(OPIEDIR)/include ../
14DEPENDSPATH += $(OPIEDIR)/include 14DEPENDSPATH += $(OPIEDIR)/include
15 15
16LIBS += -lqpe 16LIBS += -lqpe -lopiecore2
17 17
18include ( $(OPIEDIR)/include.pro ) \ No newline at end of file 18include ( $(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 @@
1/* 1/*
2 * GPLv2 zecke@handhelds.org 2 * GPLv2 zecke@handhelds.org
3 */ 3 */
4 4
5#include "slavereciever.h" 5#include "slavereciever.h"
6#include "slaveiface.h" 6#include "slaveiface.h"
7 7
8/* OPIE */
9#include <opie2/odebug.h>
8#include <qpe/qcopenvelope_qws.h> 10#include <qpe/qcopenvelope_qws.h>
9#include <qpe/qpeapplication.h> 11#include <qpe/qpeapplication.h>
12using namespace Opie::Core;
10 13
14/* QT */
11#include <qtimer.h> 15#include <qtimer.h>
12 16
13static SlaveObjects* _slaveObj = 0; 17static SlaveObjects* _slaveObj = 0;
14 18
15QDataStream & operator << (QDataStream & str, bool b) 19QDataStream & operator << (QDataStream & str, bool b)
16{ 20{
17 str << Q_INT8(b); 21 str << Q_INT8(b);
18 return str; 22 return str;
19} 23}
20 24
21QDataStream & operator >> (QDataStream & str, bool & b) 25QDataStream & operator >> (QDataStream & str, bool & b)
22{ 26{
23 Q_INT8 l; 27 Q_INT8 l;
24 str >> l; 28 str >> l;
25 b = bool(l); 29 b = bool(l);
26 return str; 30 return str;
27} 31}
28 32
29 33
30 34
31QDataStream &operator<<( QDataStream& s, const PixmapInfo& inf) { 35QDataStream &operator<<( QDataStream& s, const PixmapInfo& inf) {
32 return s << inf.file << inf.pixmap << inf.width << inf.height; 36 return s << inf.file << inf.pixmap << inf.width << inf.height;
33} 37}
34 38
35/* 39/*
36 * GUI sends no QPIxmap!!! 40 * GUI sends no QPIxmap!!!
37 */ 41 */
38QDataStream &operator>>( QDataStream& s, PixmapInfo& inf ) { 42QDataStream &operator>>( QDataStream& s, PixmapInfo& inf ) {
39 s >> inf.file >> inf.width >> inf.height; 43 s >> inf.file >> inf.width >> inf.height;
40 qWarning( "Recieved %s %d %d", inf.file.latin1(), inf.width, inf.height ); 44 owarn << "Recieved " << inf.file.latin1() << " " << inf.width << " " << inf.height << "" << oendl;
41 return s; 45 return s;
42} 46}
43QDataStream &operator<<( QDataStream& s, const ImageInfo& i) { 47QDataStream &operator<<( QDataStream& s, const ImageInfo& i) {
44 return s << i.kind << i.file << i.info; 48 return s << i.kind << i.file << i.info;
45} 49}
46QDataStream &operator>>( QDataStream& s, ImageInfo& i ) { 50QDataStream &operator>>( QDataStream& s, ImageInfo& i ) {
47 s >> i.kind >> i.file >> i.info; 51 s >> i.kind >> i.file >> i.info;
48 return s; 52 return s;
49} 53}
50 54
51 55
52 56
53SlaveObjects* slaveObjects() { 57SlaveObjects* slaveObjects() {
54 if ( !_slaveObj ) 58 if ( !_slaveObj )
55 _slaveObj = new SlaveObjects; 59 _slaveObj = new SlaveObjects;
56 return _slaveObj; 60 return _slaveObj;
57} 61}
58 62
59SlaveReciever::SlaveReciever( QObject* par) 63SlaveReciever::SlaveReciever( QObject* par)
60 : QObject( par ), m_refs( 0 ) 64 : QObject( par ), m_refs( 0 )
61{ 65{
62 m_inf = new QTimer(this); 66 m_inf = new QTimer(this);
63 connect(m_inf,SIGNAL(timeout()), 67 connect(m_inf,SIGNAL(timeout()),
64 this, SLOT(slotImageInfo())); 68 this, SLOT(slotImageInfo()));
65 m_pix = new QTimer(this); 69 m_pix = new QTimer(this);
66 connect(m_pix,SIGNAL(timeout()), 70 connect(m_pix,SIGNAL(timeout()),
67 this, SLOT(slotThumbNail())); 71 this, SLOT(slotThumbNail()));
68 72
69 m_out = new QTimer(this); 73 m_out = new QTimer(this);
70 connect(m_out,SIGNAL(timeout()), 74 connect(m_out,SIGNAL(timeout()),
71 this, SLOT(slotSend())); 75 this, SLOT(slotSend()));
72 76
73 SlaveObjects *obj = slaveObjects(); // won't be changed 77 SlaveObjects *obj = slaveObjects(); // won't be changed
74 SlaveMap::Iterator it; 78 SlaveMap::Iterator it;
75 SlaveMap* map = slaveMap(); // SlaveMap won't be changed during execution!!! 79 SlaveMap* map = slaveMap(); // SlaveMap won't be changed during execution!!!
76 for(it = map->begin(); it != map->end(); ++it ) { 80 for(it = map->begin(); it != map->end(); ++it ) {
77 obj->insert( it.key(), (*it.data())() ); 81 obj->insert( it.key(), (*it.data())() );
78 } 82 }
79} 83}
80 84
81SlaveReciever::~SlaveReciever() { 85SlaveReciever::~SlaveReciever() {
82} 86}
83 87
84void SlaveReciever::recieveAnswer( const QCString& string, const QByteArray& ar) { 88void SlaveReciever::recieveAnswer( const QCString& string, const QByteArray& ar) {
85 qWarning( "String is %s", string.data() ); 89 owarn << "String is " << string.data() << "" << oendl;
86 QDataStream stream(ar, IO_ReadOnly ); 90 QDataStream stream(ar, IO_ReadOnly );
87 QStringList lst; 91 QStringList lst;
88 static ImageInfo inf; 92 static ImageInfo inf;
89 static PixmapInfo pix; 93 static PixmapInfo pix;
90 94
91 if ( string == "thumbInfo(QString)" ) { 95 if ( string == "thumbInfo(QString)" ) {
92 stream >> inf.file; 96 stream >> inf.file;
93 m_inList.append(inf); 97 m_inList.append(inf);
94 }else if ( string == "thumbInfos(QStringList)" ) { 98 }else if ( string == "thumbInfos(QStringList)" ) {
95 stream >> lst; 99 stream >> lst;
96 for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) { 100 for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) {
97 qWarning( "Adding thumbinfo for file "+ *it ); 101 owarn << "Adding thumbinfo for file "+ *it << oendl;
98 inf.file = (*it); 102 inf.file = (*it);
99 m_inList.append(inf); 103 m_inList.append(inf);
100 } 104 }
101 }else if ( string == "fullInfo(QString)" ) { 105 }else if ( string == "fullInfo(QString)" ) {
102 inf.kind = true; 106 inf.kind = true;
103 stream >> inf.file; 107 stream >> inf.file;
104 m_inList.append(inf); 108 m_inList.append(inf);
105 }else if ( string == "fullInfos(QStringList)" ) { 109 }else if ( string == "fullInfos(QStringList)" ) {
106 stream >> lst; 110 stream >> lst;
107 for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) { 111 for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) {
108 qWarning( "Adding fullInfo for"+ *it ); 112 owarn << "Adding fullInfo for"+ *it << oendl;
109 inf.file = (*it); 113 inf.file = (*it);
110 inf.kind = true; 114 inf.kind = true;
111 m_inList.append(inf); 115 m_inList.append(inf);
112 } 116 }
113 }else if ( string == "pixmapInfo(QString,int,int)" ) { 117 }else if ( string == "pixmapInfo(QString,int,int)" ) {
114 stream >> pix.file >> pix.width >> pix.height; 118 stream >> pix.file >> pix.width >> pix.height;
115 m_inPix.append(pix); 119 m_inPix.append(pix);
116 }else if ( string == "pixmapInfos(PixmapInfos)" ) { 120 }else if ( string == "pixmapInfos(PixmapInfos)" ) {
117 PixmapList list; 121 PixmapList list;
118 stream >> list; 122 stream >> list;
119 for(PixmapList::Iterator it = list.begin(); it != list.end(); ++it ) { 123 for(PixmapList::Iterator it = list.begin(); it != list.end(); ++it ) {
120 qWarning( "Got %d %d " + (*it).file, (*it).width , (*it).height ); 124 owarn << "Got " << (*it).width << " " << (*it).height << " " + (*it).file << oendl;
121 m_inPix.append(*it); 125 m_inPix.append(*it);
122 } 126 }
123 }else if ( string == "refUp()" ) { 127 }else if ( string == "refUp()" ) {
124 m_refs++; 128 m_refs++;
125 }else if ( string == "refDown()" ) { 129 }else if ( string == "refDown()" ) {
126 m_refs--; 130 m_refs--;
127 } 131 }
128 132
129 if (!m_inf->isActive() && !m_inList.isEmpty() ) 133 if (!m_inf->isActive() && !m_inList.isEmpty() )
130 m_inf->start(5); 134 m_inf->start(5);
131 135
132 if (!m_pix->isActive() && !m_inPix.isEmpty() ) 136 if (!m_pix->isActive() && !m_inPix.isEmpty() )
133 m_pix->start(5); 137 m_pix->start(5);
134 138
135 if ( m_refs ) 139 if ( m_refs )
136 QPEApplication::setKeepRunning(); 140 QPEApplication::setKeepRunning();
137 else 141 else
138 qApp->quit(); 142 qApp->quit();
139 143
140} 144}
141 145
142PixmapList SlaveReciever::outPix()const { 146PixmapList SlaveReciever::outPix()const {
143 return m_outPix; 147 return m_outPix;
144} 148}
145 149
146StringList SlaveReciever::outInf()const{ 150StringList SlaveReciever::outInf()const{
147 return m_outList; 151 return m_outList;
148} 152}
149 153
150void SlaveReciever::slotImageInfo() { 154void SlaveReciever::slotImageInfo() {
151 ImageInfo inf = m_inList.first(); 155 ImageInfo inf = m_inList.first();
152 m_inList.remove( inf ); 156 m_inList.remove( inf );
153 157
154 static SlaveObjects::Iterator it; 158 static SlaveObjects::Iterator it;
155 static SlaveObjects* map = slaveObjects(); // SlaveMap won't be changed during execution!!! 159 static SlaveObjects* map = slaveObjects(); // SlaveMap won't be changed during execution!!!
156 for(it = map->begin(); it != map->end(); ++it ) { 160 for(it = map->begin(); it != map->end(); ++it ) {
157 if( (*it)->supports(inf.file ) ) { 161 if( (*it)->supports(inf.file ) ) {
158 /* full image info */ 162 /* full image info */
159 if (inf.kind ) 163 if (inf.kind )
160 inf.info = (*it)->fullImageInfo( inf.file ); 164 inf.info = (*it)->fullImageInfo( inf.file );
161 else 165 else
162 inf.info = (*it)->iconViewName( inf.file ); 166 inf.info = (*it)->iconViewName( inf.file );
163 m_outList.append( inf ); 167 m_outList.append( inf );
164 break; 168 break;
165 } 169 }
166 } 170 }
167 171
168 if (m_inList.isEmpty() ) 172 if (m_inList.isEmpty() )
169 m_inf->stop(); 173 m_inf->stop();
170 if (!m_out->isActive() && !m_outList.isEmpty() ) 174 if (!m_out->isActive() && !m_outList.isEmpty() )
171 m_out->start( 100 ); 175 m_out->start( 100 );
172} 176}
173 177
174void SlaveReciever::slotThumbNail() { 178void SlaveReciever::slotThumbNail() {
175 PixmapInfo inf = m_inPix.first(); 179 PixmapInfo inf = m_inPix.first();
176 m_inPix.remove( inf ); 180 m_inPix.remove( inf );
177 181
178 static SlaveObjects::Iterator it; 182 static SlaveObjects::Iterator it;
179 static SlaveObjects* map = slaveObjects(); // SlaveMap won't be changed during execution!!! 183 static SlaveObjects* map = slaveObjects(); // SlaveMap won't be changed during execution!!!
180 for(it = map->begin(); it != map->end(); ++it ) { 184 for(it = map->begin(); it != map->end(); ++it ) {
181 SlaveInterface* iface = it.data(); 185 SlaveInterface* iface = it.data();
182 if( iface->supports(inf.file ) ) { 186 if( iface->supports(inf.file ) ) {
183 /* pixmap */ 187 /* pixmap */
184 qWarning( "Asking for thumbNail in size %d %d for "+inf.file, inf.width, inf.height ); 188 owarn << "Asking for thumbNail in size " << inf.width << " " << inf.height << " for "+inf.file << oendl;
185 inf.pixmap = iface->pixmap(inf.file, 64, 64); 189 inf.pixmap = iface->pixmap(inf.file, 64, 64);
186 m_outPix.append( inf ); 190 m_outPix.append( inf );
187 break; 191 break;
188 } 192 }
189 } 193 }
190 194
191 195
192 196
193 if(m_inPix.isEmpty() ) 197 if(m_inPix.isEmpty() )
194 m_pix->stop(); 198 m_pix->stop();
195 if(!m_out->isActive() && !m_outPix.isEmpty() ) 199 if(!m_out->isActive() && !m_outPix.isEmpty() )
196 m_out->start(100); 200 m_out->start(100);
197} 201}
198 202
199void SlaveReciever::slotSend() { 203void SlaveReciever::slotSend() {
200 204
201 m_out->stop(); 205 m_out->stop();
202 206
203 qWarning( "Sending %d %d", outPix().count(), outInf().count() ); 207 owarn << "Sending " << outPix().count() << " " << outInf().count() << "" << oendl;
204 /* queue it and send */ 208 /* queue it and send */
205 /* if this ever gets a service introduce request queues 209 /* if this ever gets a service introduce request queues
206 * so we can differinatate between different clients 210 * so we can differinatate between different clients
207 */ 211 */
208 if (! m_outPix.isEmpty() ) { 212 if (! m_outPix.isEmpty() ) {
209 QCopEnvelope answer("QPE/opie-eye", "pixmapsHandled(PixmapList)" ); 213 QCopEnvelope answer("QPE/opie-eye", "pixmapsHandled(PixmapList)" );
210 answer << outPix(); 214 answer << outPix();
211 for ( PixmapList::Iterator it = m_outPix.begin();it!=m_outPix.end();++it ) { 215 for ( PixmapList::Iterator it = m_outPix.begin();it!=m_outPix.end();++it ) {
212 qWarning( "Sending out %s %d %d", (*it).file.latin1(), (*it).width, (*it).height ); 216 owarn << "Sending out " << (*it).file.latin1() << " " << (*it).width << " " << (*it).height << "" << oendl;
213 } 217 }
214 } 218 }
215 if ( !m_outList.isEmpty() ) { 219 if ( !m_outList.isEmpty() ) {
216 QCopEnvelope answer("QPE/opie-eye", "pixmapsHandled(StringList)" ); 220 QCopEnvelope answer("QPE/opie-eye", "pixmapsHandled(StringList)" );
217 answer << outInf(); 221 answer << outInf();
218 for ( StringList::Iterator it = m_outList.begin();it!=m_outList.end();++it ) { 222 for ( StringList::Iterator it = m_outList.begin();it!=m_outList.end();++it ) {
219 qWarning( "Sending out2 " + (*it).file ); 223 owarn << "Sending out2 " + (*it).file << oendl;
220 } 224 }
221 } 225 }
222 226
223 m_outList.clear(); 227 m_outList.clear();
224 m_outPix.clear(); 228 m_outPix.clear();
225} 229}
226 230
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 @@
1#include "thumbnailtool.h" 1#include "thumbnailtool.h"
2 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
7/* QT */
3#include <qfileinfo.h> 8#include <qfileinfo.h>
4#include <qdir.h> 9#include <qdir.h>
5#include <qimage.h> 10#include <qimage.h>
6#include <qpixmap.h> 11#include <qpixmap.h>
7#include <qstring.h> 12#include <qstring.h>
8 13
9static bool makeThumbDir( const QFileInfo& inf, bool make = false) { 14static bool makeThumbDir( const QFileInfo& inf, bool make = false) {
10 QDir dir( inf.dirPath()+ "/.opie-eye" ); 15 QDir dir( inf.dirPath()+ "/.opie-eye" );
11 if ( !dir.exists() ) 16 if ( !dir.exists() )
12 if ( make ) 17 if ( make )
13 return dir.mkdir(QString::null); 18 return dir.mkdir(QString::null);
14 else 19 else
15 return false; 20 return false;
16 return true; 21 return true;
17} 22}
18 23
19 24
20/* 25/*
21 * check if the Opie opie-eye dir exists 26 * check if the Opie opie-eye dir exists
22 * check if a thumbnail exists 27 * check if a thumbnail exists
23 * load the thumbnail 28 * load the thumbnail
24 * /foo/bar/imagefoo.gif 29 * /foo/bar/imagefoo.gif
25 * check for a png in /foo/bar/.opie-eye/%dx%d-imagefoo.gif 30 * check for a png in /foo/bar/.opie-eye/%dx%d-imagefoo.gif
26 */ 31 */
27QPixmap ThumbNailTool::getThumb( const QString& path, int width, int height ) { 32QPixmap ThumbNailTool::getThumb( const QString& path, int width, int height ) {
28 QFileInfo inf( path ); 33 QFileInfo inf( path );
29 qWarning( "Get Thumb" ); 34 owarn << "Get Thumb" << oendl;
30 if ( !makeThumbDir( inf ) ) { 35 if ( !makeThumbDir( inf ) ) {
31 QPixmap pix; 36 QPixmap pix;
32 return pix; 37 return pix;
33 } 38 }
34 QString str = QString( "/.opie-eye/%1x%2-%3" ).arg( width ).arg( height ).arg( inf.fileName() ); 39 QString str = QString( "/.opie-eye/%1x%2-%3" ).arg( width ).arg( height ).arg( inf.fileName() );
35 qWarning( inf.dirPath()+str ); 40 owarn << inf.dirPath()+str << oendl;
36 return QPixmap( inf.dirPath()+str,"PNG" ); 41 return QPixmap( inf.dirPath()+str,"PNG" );
37 42
38} 43}
39 44
40void ThumbNailTool::putThumb( const QString& path, const QPixmap& pix, int width, int height ) { 45void ThumbNailTool::putThumb( const QString& path, const QPixmap& pix, int width, int height ) {
41 QFileInfo inf( path ); 46 QFileInfo inf( path );
42 makeThumbDir( inf, true ); 47 makeThumbDir( inf, true );
43 QString str = QString( "/.opie-eye/%1x%2-%3" ).arg( width ).arg( height ).arg( inf.fileName() ); 48 QString str = QString( "/.opie-eye/%1x%2-%3" ).arg( width ).arg( height ).arg( inf.fileName() );
44 qWarning( inf.dirPath()+str ); 49 owarn << inf.dirPath()+str << oendl;
45 pix.save( inf.dirPath()+str, "PNG" ); 50 pix.save( inf.dirPath()+str, "PNG" );
46} 51}
47 52
48 53
49QPixmap ThumbNailTool::scaleImage( QImage& img, int w, int h ) { 54QPixmap ThumbNailTool::scaleImage( QImage& img, int w, int h ) {
50 double hs = (double)h / (double)img.height() ; 55 double hs = (double)h / (double)img.height() ;
51 double ws = (double)w / (double)img.width() ; 56 double ws = (double)w / (double)img.width() ;
52 double scaleFactor = (hs > ws) ? ws : hs; 57 double scaleFactor = (hs > ws) ? ws : hs;
53 int smoothW = (int)(scaleFactor * img.width()); 58 int smoothW = (int)(scaleFactor * img.width());
54 int smoothH = (int)(scaleFactor * img.height()); 59 int smoothH = (int)(scaleFactor * img.height());
55 QPixmap pixmap; 60 QPixmap pixmap;
56 if ( img.width() <= w && img.height() <= h ) 61 if ( img.width() <= w && img.height() <= h )
57 pixmap.convertFromImage( img ); 62 pixmap.convertFromImage( img );
58 else 63 else
59 pixmap.convertFromImage( img.smoothScale( smoothW, smoothH) ); 64 pixmap.convertFromImage( img.smoothScale( smoothW, smoothH) );
60 return pixmap; 65 return pixmap;
61} 66}
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;
40namespace 40namespace
41{ 41{
42 42
43const int xo = -2; // movable x offset 43const int xo = -2; // movable x offset
44const int yo = 22; // movable y offset 44const int yo = 22; // movable y offset
45 45
46const MediaWidget::SkinButtonInfo skinInfo[] = 46const MediaWidget::SkinButtonInfo skinInfo[] =
47{ 47{
48 { MediaWidget::Play, "play", MediaWidget::ToggleButton }, 48 { MediaWidget::Play, "play", MediaWidget::ToggleButton },
49 { MediaWidget::Stop, "stop", MediaWidget::NormalButton }, 49 { MediaWidget::Stop, "stop", MediaWidget::NormalButton },
50 { MediaWidget::Next, "next", MediaWidget::NormalButton }, 50 { MediaWidget::Next, "next", MediaWidget::NormalButton },
51 { MediaWidget::Previous, "prev", MediaWidget::NormalButton }, 51 { MediaWidget::Previous, "prev", MediaWidget::NormalButton },
52 { MediaWidget::VolumeUp, "up", MediaWidget::NormalButton }, 52 { MediaWidget::VolumeUp, "up", MediaWidget::NormalButton },
53 { MediaWidget::VolumeDown, "down", MediaWidget::NormalButton }, 53 { MediaWidget::VolumeDown, "down", MediaWidget::NormalButton },
54 { MediaWidget::Loop, "loop", MediaWidget::ToggleButton }, 54 { MediaWidget::Loop, "loop", MediaWidget::ToggleButton },
55 { MediaWidget::PlayList, "playlist", MediaWidget::NormalButton }, 55 { MediaWidget::PlayList, "playlist", MediaWidget::NormalButton },
56 { MediaWidget::Forward, "forward", MediaWidget::NormalButton }, 56 { MediaWidget::Forward, "forward", MediaWidget::NormalButton },
57 { MediaWidget::Back, "back", MediaWidget::NormalButton } 57 { MediaWidget::Back, "back", MediaWidget::NormalButton }
58}; 58};
59 59
60const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] ); 60const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] );
61 61
62void changeTextColor( QWidget * w) { 62void changeTextColor( QWidget * w) {
63 QPalette p = w->palette(); 63 QPalette p = w->palette();
64 p.setBrush( QColorGroup::Background, QColor( 167, 212, 167 ) ); 64 p.setBrush( QColorGroup::Background, QColor( 167, 212, 167 ) );
65 p.setBrush( QColorGroup::Base, QColor( 167, 212, 167 ) ); 65 p.setBrush( QColorGroup::Base, QColor( 167, 212, 167 ) );
66 w->setPalette( p ); 66 w->setPalette( p );
67} 67}
68 68
69} 69}
70 70
71AudioWidget::AudioWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name) : 71AudioWidget::AudioWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name) :
72 72
73 MediaWidget( playList, mediaPlayerState, parent, name ), songInfo( this ), slider( Qt::Horizontal, this ), time( this ), 73 MediaWidget( playList, mediaPlayerState, parent, name ), songInfo( this ), slider( Qt::Horizontal, this ), time( this ),
74 audioSliderBeingMoved( false ) 74 audioSliderBeingMoved( false )
75{ 75{
76 setCaption( tr("OpiePlayer") ); 76 setCaption( tr("OpiePlayer") );
77 77
78 loadSkin(); 78 loadSkin();
79 79
80 connect( &mediaPlayerState, SIGNAL( loopingToggled(bool) ), this, SLOT( setLooping(bool) ) ); 80 connect( &mediaPlayerState, SIGNAL( loopingToggled(bool) ), this, SLOT( setLooping(bool) ) );
81 connect( &mediaPlayerState, SIGNAL( isSeekableToggled(bool) ), this, SLOT( setSeekable(bool) ) ); 81 connect( &mediaPlayerState, SIGNAL( isSeekableToggled(bool) ), this, SLOT( setSeekable(bool) ) );
82 82
83 connect( this, SIGNAL( forwardClicked() ), this, SLOT( skipFor() ) ); 83 connect( this, SIGNAL( forwardClicked() ), this, SLOT( skipFor() ) );
84 connect( this, SIGNAL( backClicked() ), this, SLOT( skipBack() ) ); 84 connect( this, SIGNAL( backClicked() ), this, SLOT( skipBack() ) );
85 connect( this, SIGNAL( forwardReleased() ), this, SLOT( stopSkip() ) ); 85 connect( this, SIGNAL( forwardReleased() ), this, SLOT( stopSkip() ) );
86 connect( this, SIGNAL( backReleased() ), this, SLOT( stopSkip() ) ); 86 connect( this, SIGNAL( backReleased() ), this, SLOT( stopSkip() ) );
87 87
88 // Intialise state 88 // Intialise state
89 setLength( mediaPlayerState.length() ); 89 setLength( mediaPlayerState.length() );
90 setPosition( mediaPlayerState.position() ); 90 setPosition( mediaPlayerState.position() );
91 setLooping( mediaPlayerState.isFullscreen() ); 91 setLooping( mediaPlayerState.isFullscreen() );
92 // setPaused( mediaPlayerState->paused() ); 92 // setPaused( mediaPlayerState->paused() );
93 setPlaying( mediaPlayerState.isPlaying() ); 93 setPlaying( mediaPlayerState.isPlaying() );
94} 94}
95 95
96AudioWidget::~AudioWidget() { 96AudioWidget::~AudioWidget() {
97 97
98// mediaPlayerState->setPlaying(false); 98// mediaPlayerState->setPlaying(false);
99} 99}
100 100
101MediaWidget::GUIInfo AudioWidget::guiInfo() 101MediaWidget::GUIInfo AudioWidget::guiInfo()
102{ 102{
103 return GUIInfo( QString::null /* infix */, ::skinInfo, ::buttonCount ); 103 return GUIInfo( QString::null /* infix */, ::skinInfo, ::buttonCount );
104} 104}
105 105
106void AudioWidget::resizeEvent( QResizeEvent *e ) { 106void AudioWidget::resizeEvent( QResizeEvent *e ) {
107 int h = height(); 107 int h = height();
108 int w = width(); 108 int w = width();
109 109
110 songInfo.setGeometry( QRect( 2, 2, w - 4, 20 ) ); 110 songInfo.setGeometry( QRect( 2, 2, w - 4, 20 ) );
111 slider.setFixedWidth( w - 110 ); 111 slider.setFixedWidth( w - 110 );
112 slider.setGeometry( QRect( 15, h - 22, w - 90, 20 ) ); 112 slider.setGeometry( QRect( 15, h - 22, w - 90, 20 ) );
113 slider.setBackgroundOrigin( QWidget::ParentOrigin ); 113 slider.setBackgroundOrigin( QWidget::ParentOrigin );
114 time.setGeometry( QRect( w - 85, h - 30, 70, 20 ) ); 114 time.setGeometry( QRect( w - 85, h - 30, 70, 20 ) );
115 115
116 upperLeftOfButtonMask.rx() = ( w - buttonUpImage.width() ) / 2; 116 upperLeftOfButtonMask.rx() = ( w - buttonUpImage.width() ) / 2;
117 upperLeftOfButtonMask.ry() = (( h - buttonUpImage.height() ) / 2) - 10; 117 upperLeftOfButtonMask.ry() = (( h - buttonUpImage.height() ) / 2) - 10;
118 118
119 MediaWidget::resizeEvent( e ); 119 MediaWidget::resizeEvent( e );
120} 120}
121 121
122void AudioWidget::sliderPressed() { 122void AudioWidget::sliderPressed() {
123 audioSliderBeingMoved = TRUE; 123 audioSliderBeingMoved = TRUE;
124} 124}
125 125
126 126
127void AudioWidget::sliderReleased() { 127void AudioWidget::sliderReleased() {
128 audioSliderBeingMoved = FALSE; 128 audioSliderBeingMoved = FALSE;
129 if ( slider.width() == 0 ) 129 if ( slider.width() == 0 )
130 return; 130 return;
131 long val = long((double)slider.value() * mediaPlayerState.length() / slider.width()); 131 long val = long((double)slider.value() * mediaPlayerState.length() / slider.width());
132 mediaPlayerState.setPosition( val ); 132 mediaPlayerState.setPosition( val );
133} 133}
134 134
135void AudioWidget::setPosition( long i ) { 135void AudioWidget::setPosition( long i ) {
136 // qDebug("<<<<<<<<<<<<<<<<<<<<<<<<set position %d",i); 136 // odebug << "<<<<<<<<<<<<<<<<<<<<<<<<set position " << i << "" << oendl;
137 updateSlider( i, mediaPlayerState.length() ); 137 updateSlider( i, mediaPlayerState.length() );
138} 138}
139 139
140 140
141void AudioWidget::setLength( long max ) { 141void AudioWidget::setLength( long max ) {
142 updateSlider( mediaPlayerState.position(), max ); 142 updateSlider( mediaPlayerState.position(), max );
143} 143}
144 144
145 145
146void AudioWidget::setDisplayType( MediaPlayerState::DisplayType mediaType ) { 146void AudioWidget::setDisplayType( MediaPlayerState::DisplayType mediaType ) {
147 if ( mediaType == MediaPlayerState::Audio ) { 147 if ( mediaType == MediaPlayerState::Audio ) {
148 // startTimer( 150 ); 148 // startTimer( 150 );
149 QPEApplication::showWidget( this ); 149 QPEApplication::showWidget( this );
150 return; 150 return;
151 } 151 }
152 152
153 killTimers(); 153 killTimers();
154 hide(); 154 hide();
155} 155}
156 156
157void AudioWidget::loadSkin() 157void AudioWidget::loadSkin()
158{ 158{
159 loadDefaultSkin( guiInfo() ); 159 loadDefaultSkin( guiInfo() );
160 160
161 songInfo.setFocusPolicy( QWidget::NoFocus ); 161 songInfo.setFocusPolicy( QWidget::NoFocus );
162// changeTextColor( &songInfo ); 162// changeTextColor( &songInfo );
163// songInfo.setBackgroundColor( QColor( 167, 212, 167 )); 163// songInfo.setBackgroundColor( QColor( 167, 212, 167 ));
164// songInfo.setFrameStyle( QFrame::NoFrame); 164// songInfo.setFrameStyle( QFrame::NoFrame);
165 songInfo.setFrameStyle( QFrame::WinPanel | QFrame::Sunken ); 165 songInfo.setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
166// songInfo.setForegroundColor(Qt::white); 166// songInfo.setForegroundColor(Qt::white);
167 167
168 slider.setFixedHeight( 20 ); 168 slider.setFixedHeight( 20 );
169 slider.setMinValue( 0 ); 169 slider.setMinValue( 0 );
170 slider.setMaxValue( 1 ); 170 slider.setMaxValue( 1 );
171 slider.setFocusPolicy( QWidget::NoFocus ); 171 slider.setFocusPolicy( QWidget::NoFocus );
172 slider.setBackgroundPixmap( backgroundPixmap ); 172 slider.setBackgroundPixmap( backgroundPixmap );
173 173
174// Config cofg("qpe"); 174// Config cofg("qpe");
175// cofg.setGroup("Appearance"); 175// cofg.setGroup("Appearance");
176// QColor backgroundcolor = QColor( cofg.readEntry( "Background", "#E5E1D5" ) ); 176// QColor backgroundcolor = QColor( cofg.readEntry( "Background", "#E5E1D5" ) );
177 177
178 time.setFocusPolicy( QWidget::NoFocus ); 178 time.setFocusPolicy( QWidget::NoFocus );
179 time.setAlignment( Qt::AlignCenter ); 179 time.setAlignment( Qt::AlignCenter );
180 180
181// time.setFrame(FALSE); 181// time.setFrame(FALSE);
182// changeTextColor( &time ); 182// changeTextColor( &time );
183 183
184 resizeEvent( 0 ); 184 resizeEvent( 0 );
185} 185}
186 186
187void AudioWidget::setSeekable( bool isSeekable ) { 187void AudioWidget::setSeekable( bool isSeekable ) {
188 188
189 if ( !isSeekable ) { 189 if ( !isSeekable ) {
190 qDebug("<<<<<<<<<<<<<<file is STREAMING>>>>>>>>>>>>>>>>>>>"); 190 odebug << "<<<<<<<<<<<<<<file is STREAMING>>>>>>>>>>>>>>>>>>>" << oendl;
191 if( !slider.isHidden()) { 191 if( !slider.isHidden()) {
192 slider.hide(); 192 slider.hide();
193 } 193 }
194 disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); 194 disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
195 disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); 195 disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
196 disconnect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); 196 disconnect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
197 disconnect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); 197 disconnect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
198 } else { 198 } else {
199 // this stops the slider from being moved, thus 199 // this stops the slider from being moved, thus
200 // does not stop stream when it reaches the end 200 // does not stop stream when it reaches the end
201 slider.show(); 201 slider.show();
202 qDebug( " CONNECT SET POSTION " ); 202 odebug << " CONNECT SET POSTION " << oendl;
203 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); 203 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
204 connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); 204 connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
205 connect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); 205 connect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
206 connect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); 206 connect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
207 } 207 }
208} 208}
209 209
210 210
211static QString timeAsString( long length ) { 211static QString timeAsString( long length ) {
212 int minutes = length / 60; 212 int minutes = length / 60;
213 int seconds = length % 60; 213 int seconds = length % 60;
214 return QString("%1:%2%3").arg( minutes ).arg( seconds / 10 ).arg( seconds % 10 ); 214 return QString("%1:%2%3").arg( minutes ).arg( seconds / 10 ).arg( seconds % 10 );
215} 215}
216 216
217void AudioWidget::updateSlider( long i, long max ) { 217void AudioWidget::updateSlider( long i, long max ) {
218 218
219 time.setText( timeAsString( i ) + " / " + timeAsString( max ) ); 219 time.setText( timeAsString( i ) + " / " + timeAsString( max ) );
220// qDebug( timeAsString( i ) + " / " + timeAsString( max ) ) ; 220// qDebug( timeAsString( i ) + " / " + timeAsString( max ) ) ;
221 221
222 if ( max == 0 ) { 222 if ( max == 0 ) {
223 return; 223 return;
224 } 224 }
225 // Will flicker too much if we don't do this 225 // Will flicker too much if we don't do this
226 // Scale to something reasonable 226 // Scale to something reasonable
227 int width = slider.width(); 227 int width = slider.width();
228 int val = int((double)i * width / max); 228 int val = int((double)i * width / max);
229 if ( !audioSliderBeingMoved ) { 229 if ( !audioSliderBeingMoved ) {
230 if ( slider.value() != val ) { 230 if ( slider.value() != val ) {
231 slider.setValue( val ); 231 slider.setValue( val );
232 } 232 }
233 233
234 if ( slider.maxValue() != width ) { 234 if ( slider.maxValue() != width ) {
235 slider.setMaxValue( width ); 235 slider.setMaxValue( width );
236 } 236 }
237 } 237 }
238} 238}
239 239
240void AudioWidget::skipFor() { 240void AudioWidget::skipFor() {
241 skipDirection = +1; 241 skipDirection = +1;
242 startTimer( 50 ); 242 startTimer( 50 );
243 mediaPlayerState.setPosition( mediaPlayerState.position() + 2 ); 243 mediaPlayerState.setPosition( mediaPlayerState.position() + 2 );
244} 244}
245 245
246void AudioWidget::skipBack() { 246void AudioWidget::skipBack() {
247 skipDirection = -1; 247 skipDirection = -1;
248 startTimer( 50 ); 248 startTimer( 50 );
249 mediaPlayerState.setPosition( mediaPlayerState.position() - 2 ); 249 mediaPlayerState.setPosition( mediaPlayerState.position() - 2 );
250} 250}
251 251
252 252
253 253
254void AudioWidget::stopSkip() { 254void AudioWidget::stopSkip() {
255 killTimers(); 255 killTimers();
256} 256}
257 257
258 258
259void AudioWidget::timerEvent( QTimerEvent * ) { 259void AudioWidget::timerEvent( QTimerEvent * ) {
260 if ( skipDirection == +1 ) { 260 if ( skipDirection == +1 ) {
261 mediaPlayerState.setPosition( mediaPlayerState.position() + 2 ); 261 mediaPlayerState.setPosition( mediaPlayerState.position() + 2 );
262 } else if ( skipDirection == -1 ) { 262 } else if ( skipDirection == -1 ) {
263 mediaPlayerState.setPosition( mediaPlayerState.position() - 2 ); 263 mediaPlayerState.setPosition( mediaPlayerState.position() - 2 );
264 } 264 }
265} 265}
266 266
267void AudioWidget::keyReleaseEvent( QKeyEvent *e) { 267void AudioWidget::keyReleaseEvent( QKeyEvent *e) {
268 switch ( e->key() ) { 268 switch ( e->key() ) {
269 ////////////////////////////// Zaurus keys 269 ////////////////////////////// Zaurus keys
270 case Key_Home: 270 case Key_Home:
271 break; 271 break;
272 case Key_F9: //activity 272 case Key_F9: //activity
273 hide(); 273 hide();
274 // qDebug("Audio F9"); 274 // odebug << "Audio F9" << oendl;
275 e->accept(); 275 e->accept();
276 break; 276 break;
277 case Key_F10: //contacts 277 case Key_F10: //contacts
278 break; 278 break;
279 case Key_F11: //menu 279 case Key_F11: //menu
280 mediaPlayerState.toggleBlank(); 280 mediaPlayerState.toggleBlank();
281 e->accept(); 281 e->accept();
282 break; 282 break;
283 case Key_F12: //home 283 case Key_F12: //home
284 break; 284 break;
285 case Key_F13: //mail 285 case Key_F13: //mail
286 mediaPlayerState.toggleBlank(); 286 mediaPlayerState.toggleBlank();
287 e->accept(); 287 e->accept();
288 break; 288 break;
289 case Key_Space: { 289 case Key_Space: {
290 e->accept(); 290 e->accept();
291 mediaPlayerState.togglePaused(); 291 mediaPlayerState.togglePaused();
292 } 292 }
293 break; 293 break;
294 case Key_Down: 294 case Key_Down:
295 // toggleButton(6); 295 // toggleButton(6);
296 emit lessClicked(); 296 emit lessClicked();
297 emit lessReleased(); 297 emit lessReleased();
298 // toggleButton(6); 298 // toggleButton(6);
299 e->accept(); 299 e->accept();
300 break; 300 break;
301 case Key_Up: 301 case Key_Up:
302 // toggleButton(5); 302 // toggleButton(5);
303 emit moreClicked(); 303 emit moreClicked();
304 emit moreReleased(); 304 emit moreReleased();
305 // toggleButton(5); 305 // toggleButton(5);
306 e->accept(); 306 e->accept();
307 break; 307 break;
308 case Key_Right: 308 case Key_Right:
309 // toggleButton(3); 309 // toggleButton(3);
310 mediaPlayerState.setNext(); 310 mediaPlayerState.setNext();
311 // toggleButton(3); 311 // toggleButton(3);
312 e->accept(); 312 e->accept();
313 break; 313 break;
314 case Key_Left: 314 case Key_Left:
315 // toggleButton(4); 315 // toggleButton(4);
316 mediaPlayerState.setPrev(); 316 mediaPlayerState.setPrev();
317 // toggleButton(4); 317 // toggleButton(4);
318 e->accept(); 318 e->accept();
319 break; 319 break;
320 case Key_Escape: { 320 case Key_Escape: {
321 } 321 }
322 break; 322 break;
323 323
324 }; 324 };
325} 325}
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 @@
13.="- .-=="i,     .._ License as published by the Free Software 13.="- .-=="i,     .._ License as published by the Free Software
14 - .   .-<_>     .<> Foundation; either version 2 of the License, 14 - .   .-<_>     .<> Foundation; either version 2 of the License,
15     ._= =}       : or (at your option) any later version. 15     ._= =}       : or (at your option) any later version.
16    .%`+i>       _;_. 16    .%`+i>       _;_.
17    .i_,=:_.      -<s. This program is distributed in the hope that 17    .i_,=:_.      -<s. This program is distributed in the hope that
18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
19    : ..    .:,     . . . without even the implied warranty of 19    : ..    .:,     . . . without even the implied warranty of
20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
22..}^=.=       =       ; Library General Public License for more 22..}^=.=       =       ; Library General Public License for more
23++=   -.     .`     .: details. 23++=   -.     .`     .: details.
24 :     =  ...= . :.=- 24 :     =  ...= . :.=-
25 -.   .:....=;==+<; You should have received a copy of the GNU 25 -.   .:....=;==+<; You should have received a copy of the GNU
26  -_. . .   )=.  = Library General Public License along with 26  -_. . .   )=.  = Library General Public License along with
27    --        :-=` this library; see the file COPYING.LIB. 27    --        :-=` this library; see the file COPYING.LIB.
28 If not, write to the Free Software Foundation, 28 If not, write to the Free Software Foundation,
29 Inc., 59 Temple Place - Suite 330, 29 Inc., 59 Temple Place - Suite 330,
30 Boston, MA 02111-1307, USA. 30 Boston, MA 02111-1307, USA.
31 31
32*/ 32*/
33 33
34 34
35#include <qtextstream.h> 35#include <qtextstream.h>
36 36
37#include <qdir.h> 37#include <qdir.h>
38 38
39#include <qgfx_qws.h> 39#include <qgfx_qws.h>
40 40
41#include <assert.h> 41#include <assert.h>
42 42
43#include "xinevideowidget.h" 43#include "xinevideowidget.h"
44#include "frame.h" 44#include "frame.h"
45#include "lib.h" 45#include "lib.h"
46 46
47 47
48typedef void (*display_xine_frame_t) (void *user_data, uint8_t* frame, 48typedef void (*display_xine_frame_t) (void *user_data, uint8_t* frame,
49 int width, int height,int bytes ); 49 int width, int height,int bytes );
50 50
51extern "C" { 51extern "C" {
52 xine_vo_driver_t* init_video_out_plugin( xine_t *xine, void* video, display_xine_frame_t, void * ); 52 xine_vo_driver_t* init_video_out_plugin( xine_t *xine, void* video, display_xine_frame_t, void * );
53 int null_is_showing_video( const xine_vo_driver_t* self ); 53 int null_is_showing_video( const xine_vo_driver_t* self );
54 void null_set_show_video( const xine_vo_driver_t* self, int show ); 54 void null_set_show_video( const xine_vo_driver_t* self, int show );
55 int null_is_fullscreen( const xine_vo_driver_t* self ); 55 int null_is_fullscreen( const xine_vo_driver_t* self );
56 void null_set_fullscreen( const xine_vo_driver_t* self, int screen ); 56 void null_set_fullscreen( const xine_vo_driver_t* self, int screen );
57 int null_is_scaling( const xine_vo_driver_t* self ); 57 int null_is_scaling( const xine_vo_driver_t* self );
58 void null_set_scaling( const xine_vo_driver_t* self, int scale ); 58 void null_set_scaling( const xine_vo_driver_t* self, int scale );
59 void null_set_gui_width( const xine_vo_driver_t* self, int width ); 59 void null_set_gui_width( const xine_vo_driver_t* self, int width );
60 void null_set_gui_height( const xine_vo_driver_t* self, int height ); 60 void null_set_gui_height( const xine_vo_driver_t* self, int height );
61 void null_set_mode( const xine_vo_driver_t* self, int depth, int rgb ); 61 void null_set_mode( const xine_vo_driver_t* self, int depth, int rgb );
62 void null_set_videoGamma( const xine_vo_driver_t* self , int value ); 62 void null_set_videoGamma( const xine_vo_driver_t* self , int value );
63 void null_display_handler( const xine_vo_driver_t* self, display_xine_frame_t t, void* user_data ); 63 void null_display_handler( const xine_vo_driver_t* self, display_xine_frame_t t, void* user_data );
64 64
65 void null_preload_decoders( xine_stream_t *stream ); 65 void null_preload_decoders( xine_stream_t *stream );
66} 66}
67 67
68using namespace XINE; 68using namespace XINE;
69 69
70Lib::Lib( InitializationMode initMode, XineVideoWidget* widget ) 70Lib::Lib( InitializationMode initMode, XineVideoWidget* widget )
71{ 71{
72 m_initialized = false; 72 m_initialized = false;
73 m_duringInitialization = false; 73 m_duringInitialization = false;
74 m_video = false; 74 m_video = false;
75 m_wid = widget; 75 m_wid = widget;
76 printf("Lib"); 76 printf("Lib");
77 QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf"; 77 QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf";
78 // get the configuration 78 // get the configuration
79 79
80 // not really OO, should be an extra class, later 80 // not really OO, should be an extra class, later
81 if ( !QFile::exists(configPath) ) { 81 if ( !QFile::exists(configPath) ) {
82 QFile f(configPath); 82 QFile f(configPath);
83 f.open(IO_WriteOnly); 83 f.open(IO_WriteOnly);
84 QTextStream ts( &f ); 84 QTextStream ts( &f );
85 ts << "misc.memcpy_method:glibc\n"; 85 ts << "misc.memcpy_method:glibc\n";
86 ts << "# uncomment if you experience double speed audio \n #audio.oss_sync_method:softsync\n"; 86 ts << "# uncomment if you experience double speed audio \n #audio.oss_sync_method:softsync\n";
87 ts << "codec.ffmpeg_pp_quality:3\n"; 87 ts << "codec.ffmpeg_pp_quality:3\n";
88 ts << "audio.num_buffers:50\n"; 88 ts << "audio.num_buffers:50\n";
89 ts << "audio.size_buffers:4096\n"; 89 ts << "audio.size_buffers:4096\n";
90 ts << "video.num_buffers:20\n"; 90 ts << "video.num_buffers:20\n";
91 ts << "video.size_buffers:4096\n"; 91 ts << "video.size_buffers:4096\n";
92 ts << "audio.out_num_audio_buf:16\n"; 92 ts << "audio.out_num_audio_buf:16\n";
93 ts << "audio.out_size_audio_buf:8096\n"; 93 ts << "audio.out_size_audio_buf:8096\n";
94 ts << "audio.out_size_zero_buf:1024\n"; 94 ts << "audio.out_size_zero_buf:1024\n";
95 ts << "audio.passthrough_offset:0\n"; 95 ts << "audio.passthrough_offset:0\n";
96 f.close(); 96 f.close();
97 } 97 }
98 98
99 if ( initMode == InitializeImmediately ) { 99 if ( initMode == InitializeImmediately ) {
100 initialize(); 100 initialize();
101 m_initialized = true; 101 m_initialized = true;
102 } 102 }
103 else 103 else
104 start(); 104 start();
105} 105}
106 106
107void Lib::run() 107void Lib::run()
108{ 108{
109 qDebug( "Lib::run() started" ); 109 odebug << "Lib::run() started" << oendl;
110 initialize(); 110 initialize();
111 m_initialized = true; 111 m_initialized = true;
112 qDebug( "Lib::run() finished" ); 112 odebug << "Lib::run() finished" << oendl;
113} 113}
114 114
115void Lib::initialize() 115void Lib::initialize()
116{ 116{
117 m_duringInitialization = true; 117 m_duringInitialization = true;
118 m_xine = xine_new( ); 118 m_xine = xine_new( );
119 119
120 QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf"; 120 QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf";
121 xine_config_load( m_xine, QFile::encodeName( configPath ) ); 121 xine_config_load( m_xine, QFile::encodeName( configPath ) );
122 122
123 xine_init( m_xine ); 123 xine_init( m_xine );
124 124
125 // allocate oss for sound 125 // allocate oss for sound
126 // and fb for framebuffer 126 // and fb for framebuffer
127 m_audioOutput = xine_open_audio_driver( m_xine, "oss", NULL ); 127 m_audioOutput = xine_open_audio_driver( m_xine, "oss", NULL );
128 m_videoOutput = ::init_video_out_plugin( m_xine, NULL, xine_display_frame, this ); 128 m_videoOutput = ::init_video_out_plugin( m_xine, NULL, xine_display_frame, this );
129 129
130 130
131//xine_open_video_driver( m_xine, NULL, XINE_VISUAL_TYPE_FB, NULL); 131//xine_open_video_driver( m_xine, NULL, XINE_VISUAL_TYPE_FB, NULL);
132 132
133 133
134// null_display_handler( m_videoOutput, xine_display_frame, this ); 134// null_display_handler( m_videoOutput, xine_display_frame, this );
135 135
136 m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput ); 136 m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput );
137 137
138 if (m_wid != 0 ) { 138 if (m_wid != 0 ) {
139 printf( "!0\n" ); 139 printf( "!0\n" );
140 setWidget( m_wid ); 140 setWidget( m_wid );
141 } 141 }
142 142
143 m_queue = xine_event_new_queue (m_stream); 143 m_queue = xine_event_new_queue (m_stream);
144 144
145 xine_event_create_listener_thread (m_queue, xine_event_handler, this); 145 xine_event_create_listener_thread (m_queue, xine_event_handler, this);
146 146
147 ::null_preload_decoders( m_stream ); 147 ::null_preload_decoders( m_stream );
148 148
149 m_duringInitialization = false; 149 m_duringInitialization = false;
150} 150}
151 151
152Lib::~Lib() { 152Lib::~Lib() {
153 assert( isRunning() == false ); 153 assert( isRunning() == false );
154 assert( m_initialized ); 154 assert( m_initialized );
155 155
156// free( m_config ); 156// free( m_config );
157 157
158 xine_close( m_stream ); 158 xine_close( m_stream );
159 159
160 xine_event_dispose_queue( m_queue ); 160 xine_event_dispose_queue( m_queue );
161 161
162 xine_dispose( m_stream ); 162 xine_dispose( m_stream );
163 163
164 xine_exit( m_xine ); 164 xine_exit( m_xine );
165 /* FIXME either free or delete but valgrind bitches against both */ 165 /* FIXME either free or delete but valgrind bitches against both */
166 //free( m_videoOutput ); 166 //free( m_videoOutput );
167 //delete m_audioOutput; 167 //delete m_audioOutput;
168} 168}
169 169
170void Lib::resize ( const QSize &s ) { 170void Lib::resize ( const QSize &s ) {
171 assert( m_initialized || m_duringInitialization ); 171 assert( m_initialized || m_duringInitialization );
172 172
173 if ( s. width ( ) && s. height ( ) ) { 173 if ( s. width ( ) && s. height ( ) ) {
174 ::null_set_gui_width( m_videoOutput, s. width() ); 174 ::null_set_gui_width( m_videoOutput, s. width() );
175 ::null_set_gui_height( m_videoOutput, s. height() ); 175 ::null_set_gui_height( m_videoOutput, s. height() );
176 } 176 }
177} 177}
178 178
179int Lib::majorVersion() { 179int Lib::majorVersion() {
180 int major, minor, sub; 180 int major, minor, sub;
181 xine_get_version ( &major, &minor, &sub ); 181 xine_get_version ( &major, &minor, &sub );
182 return major; 182 return major;
183} 183}
184 184
185int Lib::minorVersion() { 185int Lib::minorVersion() {
186 int major, minor, sub; 186 int major, minor, sub;
187 xine_get_version ( &major, &minor, &sub ); 187 xine_get_version ( &major, &minor, &sub );
188 return minor; 188 return minor;
189} 189}
190 190
191int Lib::subVersion() { 191int Lib::subVersion() {
192 int major, minor, sub; 192 int major, minor, sub;
193 xine_get_version ( &major, &minor, &sub ); 193 xine_get_version ( &major, &minor, &sub );
194 return sub; 194 return sub;
195} 195}
196 196
197int Lib::play( const QString& fileName, int startPos, int start_time ) { 197int Lib::play( const QString& fileName, int startPos, int start_time ) {
198 assert( m_initialized ); 198 assert( m_initialized );
199 // FIXME actually a hack imho. Should not be needed to dispose the whole stream 199 // FIXME actually a hack imho. Should not be needed to dispose the whole stream
200 // but without we get wrong media length reads from libxine for the second media 200 // but without we get wrong media length reads from libxine for the second media
201 //xine_dispose ( m_stream ); 201 //xine_dispose ( m_stream );
202 202
203 QString str = fileName.stripWhiteSpace(); 203 QString str = fileName.stripWhiteSpace();
204 204
205 //m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput ); 205 //m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput );
206 //m_queue = xine_event_new_queue (m_stream); 206 //m_queue = xine_event_new_queue (m_stream);
207 //xine_event_create_listener_thread (m_queue, xine_event_handler, this); 207 //xine_event_create_listener_thread (m_queue, xine_event_handler, this);
208 208
209 if ( !xine_open( m_stream, str.utf8().data() ) ) { 209 if ( !xine_open( m_stream, str.utf8().data() ) ) {
210 return 0; 210 return 0;
211 } 211 }
212 return xine_play( m_stream, startPos, start_time); 212 return xine_play( m_stream, startPos, start_time);
213} 213}
214 214
215void Lib::stop() { 215void Lib::stop() {
216 assert( m_initialized ); 216 assert( m_initialized );
217 217
218 qDebug("<<<<<<<< STOP IN LIB TRIGGERED >>>>>>>"); 218 odebug << "<<<<<<<< STOP IN LIB TRIGGERED >>>>>>>" << oendl;
219 xine_stop( m_stream ); 219 xine_stop( m_stream );
220} 220}
221 221
222void Lib::pause( bool toggle ) { 222void Lib::pause( bool toggle ) {
223 assert( m_initialized ); 223 assert( m_initialized );
224 224
225 xine_set_param( m_stream, XINE_PARAM_SPEED, toggle ? XINE_SPEED_PAUSE : XINE_SPEED_NORMAL ); 225 xine_set_param( m_stream, XINE_PARAM_SPEED, toggle ? XINE_SPEED_PAUSE : XINE_SPEED_NORMAL );
226} 226}
227 227
228int Lib::speed() const { 228int Lib::speed() const {
229 assert( m_initialized ); 229 assert( m_initialized );
230 230
231 return xine_get_param ( m_stream, XINE_PARAM_SPEED ); 231 return xine_get_param ( m_stream, XINE_PARAM_SPEED );
232} 232}
233 233
234void Lib::setSpeed( int speed ) { 234void Lib::setSpeed( int speed ) {
235 assert( m_initialized ); 235 assert( m_initialized );
236 236
237 xine_set_param ( m_stream, XINE_PARAM_SPEED, speed ); 237 xine_set_param ( m_stream, XINE_PARAM_SPEED, speed );
238} 238}
239 239
240int Lib::status() const { 240int Lib::status() const {
241 assert( m_initialized ); 241 assert( m_initialized );
242 242
243 return xine_get_status( m_stream ); 243 return xine_get_status( m_stream );
244} 244}
245 245
246int Lib::currentPosition() const { 246int Lib::currentPosition() const {
247 assert( m_initialized ); 247 assert( m_initialized );
248 248
249 int pos, time, length; 249 int pos, time, length;
250 xine_get_pos_length( m_stream, &pos, &time, &length ); 250 xine_get_pos_length( m_stream, &pos, &time, &length );
251 return pos; 251 return pos;
252} 252}
253 253
254int Lib::currentTime() const { 254int Lib::currentTime() const {
255 assert( m_initialized ); 255 assert( m_initialized );
256 256
257 int pos, time, length; 257 int pos, time, length;
258 xine_get_pos_length( m_stream, &pos, &time, &length ); 258 xine_get_pos_length( m_stream, &pos, &time, &length );
259 if ( time > 0 ) { 259 if ( time > 0 ) {
260 return time/1000; 260 return time/1000;
261 } else { 261 } else {
262 return 0; 262 return 0;
263 } 263 }
264} 264}
265 265
266int Lib::length() const { 266int Lib::length() const {
267 assert( m_initialized ); 267 assert( m_initialized );
268 268
269 int pos, time, length; 269 int pos, time, length;
270/* dilb: patch to solve the wrong stream length reported to the GUI*/ 270/* dilb: patch to solve the wrong stream length reported to the GUI*/
271 int iRetVal=0, iTestLoop=0; 271 int iRetVal=0, iTestLoop=0;
272 272
273 do 273 do
274 { 274 {
275 iRetVal = xine_get_pos_length( m_stream, &pos, &time, &length ); 275 iRetVal = xine_get_pos_length( m_stream, &pos, &time, &length );
276 if (iRetVal) 276 if (iRetVal)
277 {/* if the function didn't return 0, then pos, time and length are valid.*/ 277 {/* if the function didn't return 0, then pos, time and length are valid.*/
278 return length/1000; 278 return length/1000;
279 } 279 }
280 /*don't poll too much*/ 280 /*don't poll too much*/
281 usleep(100000); 281 usleep(100000);
282 iTestLoop++; 282 iTestLoop++;
283 } 283 }
284 while ( iTestLoop < 10 ); /* if after 1s, we still don't have any 284 while ( iTestLoop < 10 ); /* if after 1s, we still don't have any
285valid stream, then return -1 (this value could be used to make the stream 285valid stream, then return -1 (this value could be used to make the stream
286unseekable, but it should never occur!! Mr. Murphy ? :) ) */ 286unseekable, but it should never occur!! Mr. Murphy ? :) ) */
287 287
288 return -1; 288 return -1;
289} 289}
290 290
291bool Lib::isSeekable() const { 291bool Lib::isSeekable() const {
292 assert( m_initialized ); 292 assert( m_initialized );
293 293
294 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_SEEKABLE ); 294 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_SEEKABLE );
295} 295}
296 296
297void Lib::seekTo( int time ) { 297void Lib::seekTo( int time ) {
298 assert( m_initialized ); 298 assert( m_initialized );
299 299
300 //xine_trick_mode ( m_stream, XINE_TRICK_MODE_SEEK_TO_TIME, time ); NOT IMPLEMENTED YET IN XINE :_( 300 //xine_trick_mode ( m_stream, XINE_TRICK_MODE_SEEK_TO_TIME, time ); NOT IMPLEMENTED YET IN XINE :_(
301 // since its now milliseconds we need *1000 301 // since its now milliseconds we need *1000
302 xine_play( m_stream, 0, time*1000 ); 302 xine_play( m_stream, 0, time*1000 );
303} 303}
304 304
305 305
306Frame Lib::currentFrame() const { 306Frame Lib::currentFrame() const {
307 assert( m_initialized ); 307 assert( m_initialized );
308 308
309 Frame frame; 309 Frame frame;
310 return frame; 310 return frame;
311}; 311};
312 312
313QString Lib::metaInfo( int number) const { 313QString Lib::metaInfo( int number) const {
314 assert( m_initialized ); 314 assert( m_initialized );
315 315
316 return xine_get_meta_info( m_stream, number ); 316 return xine_get_meta_info( m_stream, number );
317} 317}
318 318
319int Lib::error() const { 319int Lib::error() const {
320 assert( m_initialized ); 320 assert( m_initialized );
321 321
322 return xine_get_error( m_stream ); 322 return xine_get_error( m_stream );
323}; 323};
324 324
325void Lib::ensureInitialized() 325void Lib::ensureInitialized()
326{ 326{
327 if ( m_initialized ) 327 if ( m_initialized )
328 return; 328 return;
329 329
330 qDebug( "waiting for initialization thread to finish" ); 330 odebug << "waiting for initialization thread to finish" << oendl;
331 wait(); 331 wait();
332 qDebug( "initialization thread finished!" ); 332 odebug << "initialization thread finished!" << oendl;
333} 333}
334 334
335void Lib::setWidget( XineVideoWidget *widget ) 335void Lib::setWidget( XineVideoWidget *widget )
336{ 336{
337 m_wid = widget; 337 m_wid = widget;
338 resize ( m_wid-> size ( ) ); 338 resize ( m_wid-> size ( ) );
339 ::null_set_mode( m_videoOutput, qt_screen->depth(), qt_screen->pixelType() ); 339 ::null_set_mode( m_videoOutput, qt_screen->depth(), qt_screen->pixelType() );
340 m_wid->repaint(); 340 m_wid->repaint();
341} 341}
342 342
343void Lib::receiveMessage( ThreadUtil::ChannelMessage *msg, SendType sendType ) 343void Lib::receiveMessage( ThreadUtil::ChannelMessage *msg, SendType sendType )
344{ 344{
345 assert( sendType == ThreadUtil::Channel::OneWay ); 345 assert( sendType == ThreadUtil::Channel::OneWay );
346 handleXineEvent( msg->type() ); 346 handleXineEvent( msg->type() );
347 delete msg; 347 delete msg;
348} 348}
349 349
350void Lib::handleXineEvent( const xine_event_t* t ) { 350void Lib::handleXineEvent( const xine_event_t* t ) {
351 send( new ThreadUtil::ChannelMessage( t->type ), OneWay ); 351 send( new ThreadUtil::ChannelMessage( t->type ), OneWay );
352} 352}
353 353
354void Lib::handleXineEvent( int type ) { 354void Lib::handleXineEvent( int type ) {
355 assert( m_initialized ); 355 assert( m_initialized );
356 356
357 if ( type == XINE_EVENT_UI_PLAYBACK_FINISHED ) { 357 if ( type == XINE_EVENT_UI_PLAYBACK_FINISHED ) {
358 emit stopped(); 358 emit stopped();
359 } 359 }
360} 360}
361 361
362 362
363void Lib::setShowVideo( bool video ) { 363void Lib::setShowVideo( bool video ) {
364 assert( m_initialized ); 364 assert( m_initialized );
365 365
366 m_video = video; 366 m_video = video;
367 ::null_set_show_video( m_videoOutput, video ); 367 ::null_set_show_video( m_videoOutput, video );
368} 368}
369 369
370bool Lib::isShowingVideo() const { 370bool Lib::isShowingVideo() const {
371 assert( m_initialized ); 371 assert( m_initialized );
372 372
373 return ::null_is_showing_video( m_videoOutput ); 373 return ::null_is_showing_video( m_videoOutput );
374} 374}
375 375
376bool Lib::hasVideo() const { 376bool Lib::hasVideo() const {
377 assert( m_initialized ); 377 assert( m_initialized );
378 378
379 return xine_get_stream_info( m_stream, 18 ); 379 return xine_get_stream_info( m_stream, 18 );
380} 380}
381 381
382void Lib::showVideoFullScreen( bool fullScreen ) { 382void Lib::showVideoFullScreen( bool fullScreen ) {
383 assert( m_initialized ); 383 assert( m_initialized );
384 384
385 ::null_set_fullscreen( m_videoOutput, fullScreen ); 385 ::null_set_fullscreen( m_videoOutput, fullScreen );
386} 386}
387 387
388bool Lib::isVideoFullScreen() const { 388bool Lib::isVideoFullScreen() const {
389 assert( m_initialized ); 389 assert( m_initialized );
390 390
391 return ::null_is_fullscreen( m_videoOutput ); 391 return ::null_is_fullscreen( m_videoOutput );
392} 392}
393 393
394void Lib::setScaling( bool scale ) { 394void Lib::setScaling( bool scale ) {
395 assert( m_initialized ); 395 assert( m_initialized );
396 396
397 ::null_set_scaling( m_videoOutput, scale ); 397 ::null_set_scaling( m_videoOutput, scale );
398} 398}
399 399
400void Lib::setGamma( int value ) { 400void Lib::setGamma( int value ) {
401 assert( m_initialized ); 401 assert( m_initialized );
402 402
403 ::null_set_videoGamma( m_videoOutput, value ); 403 ::null_set_videoGamma( m_videoOutput, value );
404} 404}
405 405
406bool Lib::isScaling() const { 406bool Lib::isScaling() const {
407 assert( m_initialized ); 407 assert( m_initialized );
408 408
409 return ::null_is_scaling( m_videoOutput ); 409 return ::null_is_scaling( m_videoOutput );
410} 410}
411 411
412void Lib::xine_event_handler( void* user_data, const xine_event_t* t ) { 412void Lib::xine_event_handler( void* user_data, const xine_event_t* t ) {
413 ( (Lib*)user_data)->handleXineEvent( t ); 413 ( (Lib*)user_data)->handleXineEvent( t );
414} 414}
415 415
416void Lib::xine_display_frame( void* user_data, uint8_t *frame, 416void Lib::xine_display_frame( void* user_data, uint8_t *frame,
417 int width, int height, int bytes ) { 417 int width, int height, int bytes ) {
418 ( (Lib*)user_data)->drawFrame( frame, width, height, bytes ); 418 ( (Lib*)user_data)->drawFrame( frame, width, height, bytes );
419} 419}
420 420
421void Lib::drawFrame( uint8_t* frame, int width, int height, int bytes ) { 421void Lib::drawFrame( uint8_t* frame, int width, int height, int bytes ) {
422 assert( m_initialized ); 422 assert( m_initialized );
423 423
424 if ( !m_video ) { 424 if ( !m_video ) {
425 qWarning("not showing video now"); 425 owarn << "not showing video now" << oendl;
426 return; 426 return;
427 } 427 }
428 428
429 assert( m_wid ); 429 assert( m_wid );
430 430
431 m_wid-> setVideoFrame ( frame, width, height, bytes ); 431 m_wid-> setVideoFrame ( frame, width, height, bytes );
432} 432}
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() {
59 delete xine; 59 delete xine;
60 } 60 }
61 delete m_xineControl; 61 delete m_xineControl;
62 delete m_audioUI; 62 delete m_audioUI;
63 delete m_videoUI; 63 delete m_videoUI;
64 delete volControl; 64 delete volControl;
65} 65}
66 66
67void MediaPlayer::pauseCheck( bool b ) { 67void MediaPlayer::pauseCheck( bool b ) {
68 if ( b && !mediaPlayerState.isPlaying() ) { 68 if ( b && !mediaPlayerState.isPlaying() ) {
69 mediaPlayerState.setPaused( FALSE ); 69 mediaPlayerState.setPaused( FALSE );
70 } 70 }
71} 71}
72 72
73void MediaPlayer::play() { 73void MediaPlayer::play() {
74 mediaPlayerState.setPlaying( FALSE ); 74 mediaPlayerState.setPlaying( FALSE );
75 mediaPlayerState.setPlaying( TRUE ); 75 mediaPlayerState.setPlaying( TRUE );
76} 76}
77 77
78void MediaPlayer::setPlaying( bool play ) { 78void MediaPlayer::setPlaying( bool play ) {
79 if ( !play ) { 79 if ( !play ) {
80 return; 80 return;
81 } 81 }
82 82
83 if ( mediaPlayerState.isPaused() ) { 83 if ( mediaPlayerState.isPaused() ) {
84 mediaPlayerState.setPaused( FALSE ); 84 mediaPlayerState.setPaused( FALSE );
85 return; 85 return;
86 } 86 }
87 87
88 QString tickerText, time, fileName; 88 QString tickerText, time, fileName;
89 if ( playList.currentTab() != PlayListWidget::CurrentPlayList ) { 89 if ( playList.currentTab() != PlayListWidget::CurrentPlayList ) {
90 //if playing in file list.. play in a different way 90 //if playing in file list.. play in a different way
91 // random and looping settings enabled causes problems here, 91 // random and looping settings enabled causes problems here,
92 // since there is no selected file in the playlist, but a selected file in the file list, 92 // since there is no selected file in the playlist, but a selected file in the file list,
93 // so we remember and shutoff 93 // so we remember and shutoff
94 l = mediaPlayerState.isLooping(); 94 l = mediaPlayerState.isLooping();
95 if(l) { 95 if(l) {
96 mediaPlayerState.setLooping( false ); 96 mediaPlayerState.setLooping( false );
97 } 97 }
98 r = mediaPlayerState.isShuffled(); 98 r = mediaPlayerState.isShuffled();
99 mediaPlayerState.setShuffled( false ); 99 mediaPlayerState.setShuffled( false );
100 } 100 }
101 101
102 PlayListWidget::Entry playListEntry = playList.currentEntry(); 102 PlayListWidget::Entry playListEntry = playList.currentEntry();
103 fileName = playListEntry.name; 103 fileName = playListEntry.name;
104 xineControl()->play( playListEntry.file ); 104 xineControl()->play( playListEntry.file );
105 105
106 long seconds = mediaPlayerState.length(); 106 long seconds = mediaPlayerState.length();
107 time.sprintf("%li:%02i", seconds/60, (int)seconds%60 ); 107 time.sprintf("%li:%02i", seconds/60, (int)seconds%60 );
108 108
109 if( fileName.left(4) == "http" ) { 109 if( fileName.left(4) == "http" ) {
110 fileName = QFileInfo( fileName ).baseName(); 110 fileName = QFileInfo( fileName ).baseName();
111 if ( xineControl()->getMetaInfo().isEmpty() ) { 111 if ( xineControl()->getMetaInfo().isEmpty() ) {
112 tickerText = tr( " File: " ) + fileName; 112 tickerText = tr( " File: " ) + fileName;
113 } else { 113 } else {
114 tickerText = xineControl()->getMetaInfo(); 114 tickerText = xineControl()->getMetaInfo();
115 } 115 }
116 } else { 116 } else {
117 if ( xineControl()->getMetaInfo().isEmpty() ) { 117 if ( xineControl()->getMetaInfo().isEmpty() ) {
118 tickerText = tr( " File: " ) + fileName + tr( ", Length: " ) + time + " "; 118 tickerText = tr( " File: " ) + fileName + tr( ", Length: " ) + time + " ";
119 } else { 119 } else {
120 tickerText = xineControl()->getMetaInfo() + " Length: " + time + " "; 120 tickerText = xineControl()->getMetaInfo() + " Length: " + time + " ";
121 } 121 }
122 } 122 }
123 audioUI()->setTickerText( tickerText ); 123 audioUI()->setTickerText( tickerText );
124} 124}
125 125
126 126
127void MediaPlayer::prev() { 127void MediaPlayer::prev() {
128 if( playList.currentTab() == PlayListWidget::CurrentPlayList ) { //if using the playlist 128 if( playList.currentTab() == PlayListWidget::CurrentPlayList ) { //if using the playlist
129 if ( playList.prev() ) { 129 if ( playList.prev() ) {
130 play(); 130 play();
131 } else if ( mediaPlayerState.isLooping() ) { 131 } else if ( mediaPlayerState.isLooping() ) {
132 if ( playList.last() ) { 132 if ( playList.last() ) {
133 play(); 133 play();
134 } 134 }
135 } else { 135 } else {
136 mediaPlayerState.setList(); 136 mediaPlayerState.setList();
137 } 137 }
138 } 138 }
139} 139}
140 140
141 141
142void MediaPlayer::next() { 142void MediaPlayer::next() {
143 143
144 if(playList.currentTab() == PlayListWidget::CurrentPlayList) { //if using the playlist 144 if(playList.currentTab() == PlayListWidget::CurrentPlayList) { //if using the playlist
145 if ( playList.next() ) { 145 if ( playList.next() ) {
146 play(); 146 play();
147 } else if ( mediaPlayerState.isLooping() ) { 147 } else if ( mediaPlayerState.isLooping() ) {
148 if ( playList.first() ) { 148 if ( playList.first() ) {
149 play(); 149 play();
150 } 150 }
151 } else { 151 } else {
152 mediaPlayerState.setList(); 152 mediaPlayerState.setList();
153 } 153 }
154 } else { //if playing from file list, let's just stop 154 } else { //if playing from file list, let's just stop
155 qDebug("<<<<<<<<<<<<<<<<<stop for filelists"); 155 odebug << "<<<<<<<<<<<<<<<<<stop for filelists" << oendl;
156 mediaPlayerState.setPlaying(false); 156 mediaPlayerState.setPlaying(false);
157 mediaPlayerState.setDisplayType( MediaPlayerState::MediaSelection ); 157 mediaPlayerState.setDisplayType( MediaPlayerState::MediaSelection );
158 if(l) mediaPlayerState.setLooping(l); 158 if(l) mediaPlayerState.setLooping(l);
159 if(r) mediaPlayerState.setShuffled(r); 159 if(r) mediaPlayerState.setShuffled(r);
160 } 160 }
161 qApp->processEvents(); 161 qApp->processEvents();
162} 162}
163 163
164 164
165void MediaPlayer::startDecreasingVolume() { 165void MediaPlayer::startDecreasingVolume() {
166 volumeDirection = -1; 166 volumeDirection = -1;
167 startTimer( 100 ); 167 startTimer( 100 );
168 volControl->decVol(2); 168 volControl->decVol(2);
169} 169}
170 170
171 171
172void MediaPlayer::startIncreasingVolume() { 172void MediaPlayer::startIncreasingVolume() {
173 volumeDirection = +1; 173 volumeDirection = +1;
174 startTimer( 100 ); 174 startTimer( 100 );
175 volControl->incVol(2); 175 volControl->incVol(2);
176} 176}
177 177
178 178
179bool drawnOnScreenDisplay = FALSE; 179bool drawnOnScreenDisplay = FALSE;
180unsigned int onScreenDisplayVolume = 0; 180unsigned int onScreenDisplayVolume = 0;
181const int yoff = 110; 181const int yoff = 110;
182 182
183void MediaPlayer::stopChangingVolume() { 183void MediaPlayer::stopChangingVolume() {
184 killTimers(); 184 killTimers();
185 // Get rid of the on-screen display stuff 185 // Get rid of the on-screen display stuff
186 drawnOnScreenDisplay = FALSE; 186 drawnOnScreenDisplay = FALSE;
187 onScreenDisplayVolume = 0; 187 onScreenDisplayVolume = 0;
188 int w=0; 188 int w=0;
189 int h=0; 189 int h=0;
190 if( !xineControl()->hasVideo() ) { 190 if( !xineControl()->hasVideo() ) {
191 w = audioUI()->width(); 191 w = audioUI()->width();
192 h = audioUI()->height(); 192 h = audioUI()->height();
193 audioUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE ); 193 audioUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE );
194 } else { 194 } else {
195 w = videoUI()->width(); 195 w = videoUI()->width();
196 h = videoUI()->height(); 196 h = videoUI()->height();
197 videoUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE ); 197 videoUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE );
198 } 198 }
199} 199}
200 200
201 201
202void MediaPlayer::timerEvent( QTimerEvent * ) { 202void MediaPlayer::timerEvent( QTimerEvent * ) {
203 if ( volumeDirection == +1 ) { 203 if ( volumeDirection == +1 ) {
204 volControl->incVol( 2 ); 204 volControl->incVol( 2 );
205 } else if ( volumeDirection == -1 ) { 205 } else if ( volumeDirection == -1 ) {
206 volControl->decVol( 2 ); 206 volControl->decVol( 2 );
207 } 207 }
208 208
209 209
210 // TODO FIXME 210 // TODO FIXME
211 // huh?? 211 // huh??
212 unsigned int v= 0; 212 unsigned int v= 0;
213 v = volControl->volume(); 213 v = volControl->volume();
214 v = v / 10; 214 v = v / 10;
215 215
216 if ( drawnOnScreenDisplay && onScreenDisplayVolume == v ) { 216 if ( drawnOnScreenDisplay && onScreenDisplayVolume == v ) {
217 return; 217 return;
218 } 218 }
219 219
220 int w=0; int h=0; 220 int w=0; int h=0;
221 if( !xineControl()->hasVideo() ) { 221 if( !xineControl()->hasVideo() ) {
222 w = audioUI()->width(); 222 w = audioUI()->width();
223 h = audioUI()->height(); 223 h = audioUI()->height();
224 224
225 if ( drawnOnScreenDisplay ) { 225 if ( drawnOnScreenDisplay ) {
226 if ( onScreenDisplayVolume > v ) { 226 if ( onScreenDisplayVolume > v ) {
227 audioUI()->repaint( ( w - 200 ) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE ); 227 audioUI()->repaint( ( w - 200 ) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE );
228 } 228 }
229 } 229 }
230 drawnOnScreenDisplay = TRUE; 230 drawnOnScreenDisplay = TRUE;
231 onScreenDisplayVolume = v; 231 onScreenDisplayVolume = v;
232 QPainter p( audioUI() ); 232 QPainter p( audioUI() );
233 p.setPen( QColor( 0x10, 0xD0, 0x10 ) ); 233 p.setPen( QColor( 0x10, 0xD0, 0x10 ) );
234 p.setBrush( QColor( 0x10, 0xD0, 0x10 ) ); 234 p.setBrush( QColor( 0x10, 0xD0, 0x10 ) );
235 235
236 QFont f; 236 QFont f;
237 f.setPixelSize( 20 ); 237 f.setPixelSize( 20 );
238 f.setBold( TRUE ); 238 f.setBold( TRUE );
239 p.setFont( f ); 239 p.setFont( f );
240 p.drawText( (w - 200) / 2, h - yoff + 20, tr("Volume") ); 240 p.drawText( (w - 200) / 2, h - yoff + 20, tr("Volume") );
241 241
242 for ( unsigned int i = 0; i < 10; i++ ) { 242 for ( unsigned int i = 0; i < 10; i++ ) {
243 if ( v > i ) { 243 if ( v > i ) {
244 p.drawRect( ( w - 200 ) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 ); 244 p.drawRect( ( w - 200 ) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 );
245 } else { 245 } else {
246 p.drawRect( ( w - 200 ) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 ); 246 p.drawRect( ( w - 200 ) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 );
247 } 247 }
248 } 248 }
249 } else { 249 } else {
250 w = videoUI()->width(); 250 w = videoUI()->width();
251 h = videoUI()->height(); 251 h = videoUI()->height();
252 252
253 if ( drawnOnScreenDisplay ) { 253 if ( drawnOnScreenDisplay ) {
254 if ( onScreenDisplayVolume > v ) { 254 if ( onScreenDisplayVolume > v ) {
255 videoUI()->repaint( (w - 200) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE ); 255 videoUI()->repaint( (w - 200) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE );
256 } 256 }
257 } 257 }
258 drawnOnScreenDisplay = TRUE; 258 drawnOnScreenDisplay = TRUE;
259 onScreenDisplayVolume = v; 259 onScreenDisplayVolume = v;
260 QPainter p( videoUI() ); 260 QPainter p( videoUI() );
261 p.setPen( QColor( 0x10, 0xD0, 0x10 ) ); 261 p.setPen( QColor( 0x10, 0xD0, 0x10 ) );
262 p.setBrush( QColor( 0x10, 0xD0, 0x10 ) ); 262 p.setBrush( QColor( 0x10, 0xD0, 0x10 ) );
263 263
264 QFont f; 264 QFont f;
265 f.setPixelSize( 20 ); 265 f.setPixelSize( 20 );
266 f.setBold( TRUE ); 266 f.setBold( TRUE );
267 p.setFont( f ); 267 p.setFont( f );
268 p.drawText( (w - 200) / 2, h - yoff + 20, tr( "Volume" ) ); 268 p.drawText( (w - 200) / 2, h - yoff + 20, tr( "Volume" ) );
269 269
270 for ( unsigned int i = 0; i < 10; i++ ) { 270 for ( unsigned int i = 0; i < 10; i++ ) {
271 if ( v > i ) { 271 if ( v > i ) {
272 p.drawRect( (w - 200) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 ); 272 p.drawRect( (w - 200) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 );
273 } else { 273 } else {
274 p.drawRect( (w - 200) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 ); 274 p.drawRect( (w - 200) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 );
275 } 275 }
276 } 276 }
277 } 277 }
278} 278}
279 279
280 280
281void MediaPlayer::blank( bool b ) { 281void MediaPlayer::blank( bool b ) {
282 fd=open("/dev/fb0",O_RDWR); 282 fd=open("/dev/fb0",O_RDWR);
283#ifdef QT_QWS_SL5XXX 283#ifdef QT_QWS_SL5XXX
284 fl= open( "/dev/fl", O_RDWR ); 284 fl= open( "/dev/fl", O_RDWR );
285#endif 285#endif
286 if (fd != -1) { 286 if (fd != -1) {
287 if ( b ) { 287 if ( b ) {
288 qDebug("do blanking"); 288 odebug << "do blanking" << oendl;
289#ifdef QT_QWS_SL5XXX 289#ifdef QT_QWS_SL5XXX
290 ioctl( fd, FBIOBLANK, 1 ); 290 ioctl( fd, FBIOBLANK, 1 );
291 if(fl !=-1) { 291 if(fl !=-1) {
292 ioctl( fl, 2 ); 292 ioctl( fl, 2 );
293 ::close(fl); 293 ::close(fl);
294 } 294 }
295#else 295#else
296 ioctl( fd, FBIOBLANK, 3 ); 296 ioctl( fd, FBIOBLANK, 3 );
297#endif 297#endif
298 isBlanked = TRUE; 298 isBlanked = TRUE;
299 } else { 299 } else {
300 qDebug("do unblanking"); 300 odebug << "do unblanking" << oendl;
301 ioctl( fd, FBIOBLANK, 0); 301 ioctl( fd, FBIOBLANK, 0);
302#ifdef QT_QWS_SL5XXX 302#ifdef QT_QWS_SL5XXX
303 if(fl != -1) { 303 if(fl != -1) {
304 ioctl( fl, 1); 304 ioctl( fl, 1);
305 ::close(fl); 305 ::close(fl);
306 } 306 }
307#endif 307#endif
308 isBlanked = FALSE; 308 isBlanked = FALSE;
309 } 309 }
310 close( fd ); 310 close( fd );
311 } else { 311 } else {
312 qDebug("<< /dev/fb0 could not be opened >>"); 312 odebug << "<< /dev/fb0 could not be opened >>" << oendl;
313 } 313 }
314} 314}
315 315
316void MediaPlayer::keyReleaseEvent( QKeyEvent *e) { 316void MediaPlayer::keyReleaseEvent( QKeyEvent *e) {
317 switch ( e->key() ) { 317 switch ( e->key() ) {
318////////////////////////////// Zaurus keys 318////////////////////////////// Zaurus keys
319 case Key_Home: 319 case Key_Home:
320 break; 320 break;
321 case Key_F9: //activity 321 case Key_F9: //activity
322 break; 322 break;
323 case Key_F10: //contacts 323 case Key_F10: //contacts
324 break; 324 break;
325 case Key_F11: //menu 325 case Key_F11: //menu
326 break; 326 break;
327 case Key_F12: //home 327 case Key_F12: //home
328 qDebug("Blank here"); 328 odebug << "Blank here" << oendl;
329// mediaPlayerState->toggleBlank(); 329// mediaPlayerState->toggleBlank();
330 break; 330 break;
331 case Key_F13: //mail 331 case Key_F13: //mail
332 qDebug("Blank here"); 332 odebug << "Blank here" << oendl;
333 // mediaPlayerState->toggleBlank(); 333 // mediaPlayerState->toggleBlank();
334 break; 334 break;
335 } 335 }
336} 336}
337 337
338void MediaPlayer::cleanUp() {// this happens on closing 338void MediaPlayer::cleanUp() {// this happens on closing
339 Config cfg( "OpiePlayer" ); 339 Config cfg( "OpiePlayer" );
340 mediaPlayerState.writeConfig( cfg ); 340 mediaPlayerState.writeConfig( cfg );
341 playList.writeDefaultPlaylist( ); 341 playList.writeDefaultPlaylist( );
342 342
343// QPEApplication::grabKeyboard(); 343// QPEApplication::grabKeyboard();
344// QPEApplication::ungrabKeyboard(); 344// QPEApplication::ungrabKeyboard();
345} 345}
346 346
347void MediaPlayer::recreateAudioAndVideoWidgets() const 347void MediaPlayer::recreateAudioAndVideoWidgets() const
348{ 348{
349 delete m_skinLoader; 349 delete m_skinLoader;
350 350
351 delete m_xineControl; 351 delete m_xineControl;
352 delete m_audioUI; 352 delete m_audioUI;
353 delete m_videoUI; 353 delete m_videoUI;
354 m_audioUI = new AudioWidget( playList, mediaPlayerState, 0, "audioUI" ); 354 m_audioUI = new AudioWidget( playList, mediaPlayerState, 0, "audioUI" );
355 m_videoUI = new VideoWidget( playList, mediaPlayerState, 0, "videoUI" ); 355 m_videoUI = new VideoWidget( playList, mediaPlayerState, 0, "videoUI" );
356 356
357 connect( m_audioUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) ); 357 connect( m_audioUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) );
358 connect( m_audioUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) ); 358 connect( m_audioUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) );
359 connect( m_audioUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) ); 359 connect( m_audioUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) );
360 connect( m_audioUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) ); 360 connect( m_audioUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) );
361 361
362 connect( m_videoUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) ); 362 connect( m_videoUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) );
363 connect( m_videoUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) ); 363 connect( m_videoUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) );
364 connect( m_videoUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) ); 364 connect( m_videoUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) );
365 connect( m_videoUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) ); 365 connect( m_videoUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) );
366 366
367 if ( !xine ) 367 if ( !xine )
368 xine = new XINE::Lib( XINE::Lib::InitializeImmediately ); 368 xine = new XINE::Lib( XINE::Lib::InitializeImmediately );
369 369
370 m_xineControl = new XineControl( xine, m_videoUI->vidWidget(), mediaPlayerState ); 370 m_xineControl = new XineControl( xine, m_videoUI->vidWidget(), mediaPlayerState );
371 371
372 xine = 0; 372 xine = 0;
373} 373}
374 374
375AudioWidget *MediaPlayer::audioUI() const 375AudioWidget *MediaPlayer::audioUI() const
376{ 376{
377 if ( !m_audioUI ) 377 if ( !m_audioUI )
378 recreateAudioAndVideoWidgets(); 378 recreateAudioAndVideoWidgets();
379 return m_audioUI; 379 return m_audioUI;
380} 380}
381 381
382VideoWidget *MediaPlayer::videoUI() const 382VideoWidget *MediaPlayer::videoUI() const
383{ 383{
384 if ( !m_videoUI ) 384 if ( !m_videoUI )
385 recreateAudioAndVideoWidgets(); 385 recreateAudioAndVideoWidgets();
386 return m_videoUI; 386 return m_videoUI;
387} 387}
388 388
389XineControl *MediaPlayer::xineControl() const 389XineControl *MediaPlayer::xineControl() const
390{ 390{
391 if ( !m_xineControl ) 391 if ( !m_xineControl )
392 recreateAudioAndVideoWidgets(); 392 recreateAudioAndVideoWidgets();
393 return m_xineControl; 393 return m_xineControl;
394} 394}
395 395
396void MediaPlayer::reloadSkins() 396void MediaPlayer::reloadSkins()
397{ 397{
398 audioUI()->loadSkin(); 398 audioUI()->loadSkin();
399 videoUI()->loadSkin(); 399 videoUI()->loadSkin();
400} 400}
401 401
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 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4 Copyright (c) 2002 L. Potter <ljp@llornkcor.com> 4 Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
5 =. 5 =.
6 .=l. 6 .=l.
7           .>+-= 7           .>+-=
8 _;:,     .>    :=|. This program is free software; you can 8 _;:,     .>    :=|. This program is free software; you can
9.> <`_,   >  .   <= redistribute it and/or modify it under 9.> <`_,   >  .   <= redistribute it and/or modify it under
10:`=1 )Y*s>-.--   : the terms of the GNU General Public 10:`=1 )Y*s>-.--   : the terms of the GNU General Public
11.="- .-=="i,     .._ License as published by the Free Software 11.="- .-=="i,     .._ License as published by the Free Software
12 - .   .-<_>     .<> Foundation; either version 2 of the License, 12 - .   .-<_>     .<> Foundation; either version 2 of the License,
13     ._= =}       : or (at your option) any later version. 13     ._= =}       : or (at your option) any later version.
14    .%`+i>       _;_. 14    .%`+i>       _;_.
15    .i_,=:_.      -<s. This program is distributed in the hope that 15    .i_,=:_.      -<s. This program is distributed in the hope that
16     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 16     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
17    : ..    .:,     . . . without even the implied warranty of 17    : ..    .:,     . . . without even the implied warranty of
18    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 18    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
19  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 19  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
20..}^=.=       =       ; General Public License for more 20..}^=.=       =       ; General Public License for more
21++=   -.     .`     .: details. 21++=   -.     .`     .: details.
22 :     =  ...= . :.=- 22 :     =  ...= . :.=-
23 -.   .:....=;==+<; You should have received a copy of the GNU 23 -.   .:....=;==+<; You should have received a copy of the GNU
24  -_. . .   )=.  = General Public License along with 24  -_. . .   )=.  = General Public License along with
25    --        :-=` this library; see the file COPYING.LIB. 25    --        :-=` this library; see the file COPYING.LIB.
26 If not, write to the Free Software Foundation, 26 If not, write to the Free Software Foundation,
27 Inc., 59 Temple Place - Suite 330, 27 Inc., 59 Temple Place - Suite 330,
28 Boston, MA 02111-1307, USA. 28 Boston, MA 02111-1307, USA.
29 29
30*/ 30*/
31 31
32#include "om3u.h" 32#include "om3u.h"
33 33
34 34
35 35
36//extern PlayListWidget *playList; 36//extern PlayListWidget *playList;
37 37
38Om3u::Om3u( const QString &filePath, int mode) 38Om3u::Om3u( const QString &filePath, int mode)
39 : QStringList (){ 39 : QStringList (){
40qDebug("<<<<<<<new m3u "+filePath); 40odebug << "<<<<<<<new m3u "+filePath << oendl;
41 f.setName(filePath); 41 f.setName(filePath);
42 f.open(mode); 42 f.open(mode);
43} 43}
44 44
45Om3u::~Om3u(){} 45Om3u::~Om3u(){}
46 46
47void Om3u::readM3u() { 47void Om3u::readM3u() {
48// qDebug("<<<<<<reading m3u "+f.name()); 48// odebug << "<<<<<<reading m3u "+f.name() << oendl;
49 QTextStream t(&f); 49 QTextStream t(&f);
50 t.setEncoding(QTextStream::UnicodeUTF8); 50 t.setEncoding(QTextStream::UnicodeUTF8);
51 QString s; 51 QString s;
52 while ( !t.atEnd() ) { 52 while ( !t.atEnd() ) {
53 s=t.readLine(); 53 s=t.readLine();
54// qDebug(s); 54// odebug << s << oendl;
55 if( s.find( "#", 0, TRUE) == -1 ) { 55 if( s.find( "#", 0, TRUE) == -1 ) {
56 if( s.left(2) == "E:" || s.left(2) == "P:" ) { 56 if( s.left(2) == "E:" || s.left(2) == "P:" ) {
57 s = s.right( s.length() -2 ); 57 s = s.right( s.length() -2 );
58 QFileInfo f( s ); 58 QFileInfo f( s );
59 QString name = f.baseName(); 59 QString name = f.baseName();
60 name = name.right( name.length() - name.findRev( "\\", -1, TRUE ) -1 ); 60 name = name.right( name.length() - name.findRev( "\\", -1, TRUE ) -1 );
61 s=s.replace( QRegExp( "\\" ), "/" ); 61 s=s.replace( QRegExp( "\\" ), "/" );
62 append(s); 62 append(s);
63// qDebug(s); 63// odebug << s << oendl;
64 } else { // is url 64 } else { // is url
65 QString name; 65 QString name;
66 name = s; 66 name = s;
67 append(name); 67 append(name);
68 } 68 }
69 } 69 }
70 } 70 }
71} 71}
72 72
73void Om3u::readPls() { //it's a pls file 73void Om3u::readPls() { //it's a pls file
74 QTextStream t( &f ); 74 QTextStream t( &f );
75 t.setEncoding(QTextStream::UnicodeUTF8); 75 t.setEncoding(QTextStream::UnicodeUTF8);
76 QString s; 76 QString s;
77 while ( !t.atEnd() ) { 77 while ( !t.atEnd() ) {
78 s = t.readLine(); 78 s = t.readLine();
79 if( s.left(4) == "File" ) { 79 if( s.left(4) == "File" ) {
80 s = s.right( s.length() - s.find("=",0,true)-1 ); 80 s = s.right( s.length() - s.find("=",0,true)-1 );
81 s = s.stripWhiteSpace(); 81 s = s.stripWhiteSpace();
82 s.replace( QRegExp( "%20" )," "); 82 s.replace( QRegExp( "%20" )," ");
83// qDebug( "adding " + s + " to playlist" ); 83// odebug << "adding " + s + " to playlist" << oendl;
84 // numberofentries=2 84 // numberofentries=2
85 // File1=http 85 // File1=http
86 // Title 86 // Title
87 // Length 87 // Length
88 // Version 88 // Version
89 // File2=http 89 // File2=http
90 s = s.replace( QRegExp( "\\" ), "/" ); 90 s = s.replace( QRegExp( "\\" ), "/" );
91 QFileInfo f( s ); 91 QFileInfo f( s );
92 QString name = f.baseName(); 92 QString name = f.baseName();
93 if( name.left( 4 ) == "http" ) { 93 if( name.left( 4 ) == "http" ) {
94 name = s.right( s.length() - 7); 94 name = s.right( s.length() - 7);
95 } else { 95 } else {
96 name = s; 96 name = s;
97 } 97 }
98 name = name.right( name.length() - name.findRev( "\\", -1, TRUE) - 1 ); 98 name = name.right( name.length() - name.findRev( "\\", -1, TRUE) - 1 );
99 if( s.at( s.length() - 4) == '.') // if this is probably a file 99 if( s.at( s.length() - 4) == '.') // if this is probably a file
100 append(s); 100 append(s);
101 else { //if its a url 101 else { //if its a url
102// if( name.right( 1 ).find( '/' ) == -1) { 102// if( name.right( 1 ).find( '/' ) == -1) {
103// s += "/"; 103// s += "/";
104// } 104// }
105 append(s); 105 append(s);
106 } 106 }
107 } 107 }
108 } 108 }
109} 109}
110 110
111void Om3u::write() { //writes list to m3u file 111void Om3u::write() { //writes list to m3u file
112 QString list; 112 QString list;
113 QTextStream t(&f); 113 QTextStream t(&f);
114 t.setEncoding(QTextStream::UnicodeUTF8); 114 t.setEncoding(QTextStream::UnicodeUTF8);
115 if(count()>0) { 115 if(count()>0) {
116 for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) { 116 for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) {
117// qDebug(*it); 117// odebug << *it << oendl;
118 t << *it << "\n"; 118 t << *it << "\n";
119 } 119 }
120 } 120 }
121// f.close(); 121// f.close();
122} 122}
123 123
124void Om3u::add(const QString &filePath) { //adds to m3u file 124void Om3u::add(const QString &filePath) { //adds to m3u file
125 append(filePath); 125 append(filePath);
126} 126}
127 127
128void Om3u::remove(const QString &filePath) { //removes from m3u list 128void Om3u::remove(const QString &filePath) { //removes from m3u list
129 QString list, currentFile; 129 QString list, currentFile;
130 if(count()>0) { 130 if(count()>0) {
131 for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) { 131 for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) {
132 currentFile=*it; 132 currentFile=*it;
133 // qDebug(*it); 133 // odebug << *it << oendl;
134 134
135 if( filePath != currentFile) 135 if( filePath != currentFile)
136 list += currentFile+"\n"; 136 list += currentFile+"\n";
137 } 137 }
138 f.writeBlock( list, list.length() ); 138 f.writeBlock( list, list.length() );
139 } 139 }
140} 140}
141 141
142void Om3u::deleteFile(const QString &/*filePath*/) {//deletes m3u file 142void Om3u::deleteFile(const QString &/*filePath*/) {//deletes m3u file
143 f.close(); 143 f.close();
144 f.remove(); 144 f.remove();
145 145
146} 146}
147 147
148void Om3u::close() { //closes m3u file 148void Om3u::close() { //closes m3u file
149 f.close(); 149 f.close();
150} 150}
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include <qheader.h> 21#include <qheader.h>
22 22
23#include "playlistselection.h" 23#include "playlistselection.h"
24 24
25#include <stdlib.h> 25#include <stdlib.h>
26 26
27class PlayListSelectionItem : public QListViewItem { 27class PlayListSelectionItem : public QListViewItem {
28public: 28public:
29 PlayListSelectionItem( QListView *parent, const DocLnk *f ) : QListViewItem( parent ), fl( f ) { 29 PlayListSelectionItem( QListView *parent, const DocLnk *f ) : QListViewItem( parent ), fl( f ) {
30 setText( 0, f->name() ); 30 setText( 0, f->name() );
31 setPixmap( 0, f->pixmap() ); 31 setPixmap( 0, f->pixmap() );
32 } 32 }
33 33
34 ~PlayListSelectionItem() { 34 ~PlayListSelectionItem() {
35 }; 35 };
36 36
37 const DocLnk *file() const { return fl; } 37 const DocLnk *file() const { return fl; }
38 38
39private: 39private:
40 const DocLnk *fl; 40 const DocLnk *fl;
41}; 41};
42 42
43 43
44PlayListSelection::PlayListSelection( QWidget *parent, const char *name ) 44PlayListSelection::PlayListSelection( QWidget *parent, const char *name )
45 : QListView( parent, name ) 45 : QListView( parent, name )
46{ 46{
47// qDebug("starting playlistselector"); 47// odebug << "starting playlistselector" << oendl;
48// #ifdef USE_PLAYLIST_BACKGROUND 48// #ifdef USE_PLAYLIST_BACKGROUND
49// setStaticBackground( TRUE ); 49// setStaticBackground( TRUE );
50// setBackgroundPixmap( Resource::loadPixmap( "opieplayer/background" ) ); 50// setBackgroundPixmap( Resource::loadPixmap( "opieplayer/background" ) );
51 51
52// setBackgroundPixmap( Resource::loadPixmap( "launcher/opielogo" ) ); 52// setBackgroundPixmap( Resource::loadPixmap( "launcher/opielogo" ) );
53// #endif 53// #endif
54// addColumn("Title",236); 54// addColumn("Title",236);
55// setAllColumnsShowFocus( TRUE ); 55// setAllColumnsShowFocus( TRUE );
56 addColumn( tr( "Playlist Selection" ) ); 56 addColumn( tr( "Playlist Selection" ) );
57 header()->hide(); 57 header()->hide();
58 setSorting( -1, FALSE ); 58 setSorting( -1, FALSE );
59} 59}
60 60
61 61
62PlayListSelection::~PlayListSelection() { 62PlayListSelection::~PlayListSelection() {
63} 63}
64 64
65 65
66// #ifdef USE_PLAYLIST_BACKGROUND 66// #ifdef USE_PLAYLIST_BACKGROUND
67void PlayListSelection::drawBackground( QPainter *p, const QRect &r ) { 67void PlayListSelection::drawBackground( QPainter *p, const QRect &r ) {
68// qDebug("drawBackground"); 68// odebug << "drawBackground" << oendl;
69 p->fillRect( r, QBrush( white ) ); 69 p->fillRect( r, QBrush( white ) );
70// QImage logo = Resource::loadImage( "launcher/opielogo" ); 70// QImage logo = Resource::loadImage( "launcher/opielogo" );
71// if ( !logo.isNull() ) 71// if ( !logo.isNull() )
72// p->drawImage( (width() - logo.width()) / 2, (height() - logo.height()) / 2, logo ); 72// p->drawImage( (width() - logo.width()) / 2, (height() - logo.height()) / 2, logo );
73} 73}
74// #endif 74// #endif
75 75
76 76
77void PlayListSelection::contentsMouseMoveEvent( QMouseEvent *event ) { 77void PlayListSelection::contentsMouseMoveEvent( QMouseEvent *event ) {
78 if ( event->state() == QMouseEvent::LeftButton ) { 78 if ( event->state() == QMouseEvent::LeftButton ) {
79 QListViewItem *currentItem = selectedItem(); 79 QListViewItem *currentItem = selectedItem();
80 QListViewItem *itemUnder = itemAt( QPoint( event->pos().x(), event->pos().y() - contentsY() ) ); 80 QListViewItem *itemUnder = itemAt( QPoint( event->pos().x(), event->pos().y() - contentsY() ) );
81 if ( currentItem && currentItem->itemAbove() == itemUnder ) 81 if ( currentItem && currentItem->itemAbove() == itemUnder )
82 moveSelectedUp(); 82 moveSelectedUp();
83 else if ( currentItem && currentItem->itemBelow() == itemUnder ) 83 else if ( currentItem && currentItem->itemBelow() == itemUnder )
84 moveSelectedDown(); 84 moveSelectedDown();
85 } 85 }
86} 86}
87 87
88 88
89const DocLnk *PlayListSelection::current() { 89const DocLnk *PlayListSelection::current() {
90 PlayListSelectionItem *item = (PlayListSelectionItem *)selectedItem(); 90 PlayListSelectionItem *item = (PlayListSelectionItem *)selectedItem();
91 if ( item ) 91 if ( item )
92 return item->file(); 92 return item->file();
93 return NULL; 93 return NULL;
94} 94}
95 95
96 96
97void PlayListSelection::addToSelection( const DocLnk &lnk ) { 97void PlayListSelection::addToSelection( const DocLnk &lnk ) {
98 PlayListSelectionItem *item = new PlayListSelectionItem( this, new DocLnk( lnk ) ); 98 PlayListSelectionItem *item = new PlayListSelectionItem( this, new DocLnk( lnk ) );
99 QListViewItem *current = selectedItem(); 99 QListViewItem *current = selectedItem();
100 if ( current ) 100 if ( current )
101 item->moveItem( current ); 101 item->moveItem( current );
102 setSelected( item, TRUE ); 102 setSelected( item, TRUE );
103 ensureItemVisible( selectedItem() ); 103 ensureItemVisible( selectedItem() );
104} 104}
105 105
106 106
107void PlayListSelection::removeSelected() { 107void PlayListSelection::removeSelected() {
108 QListViewItem *item = selectedItem(); 108 QListViewItem *item = selectedItem();
109 delete item; 109 delete item;
110 setSelected( currentItem(), TRUE ); 110 setSelected( currentItem(), TRUE );
111 ensureItemVisible( selectedItem() ); 111 ensureItemVisible( selectedItem() );
112} 112}
113 113
114 114
115void PlayListSelection::moveSelectedUp() { 115void PlayListSelection::moveSelectedUp() {
116 QListViewItem *item = selectedItem(); 116 QListViewItem *item = selectedItem();
117 if ( item && item->itemAbove() ) 117 if ( item && item->itemAbove() )
118 item->itemAbove()->moveItem( item ); 118 item->itemAbove()->moveItem( item );
119 ensureItemVisible( selectedItem() ); 119 ensureItemVisible( selectedItem() );
120} 120}
121 121
122 122
123void PlayListSelection::moveSelectedDown() { 123void PlayListSelection::moveSelectedDown() {
124 QListViewItem *item = selectedItem(); 124 QListViewItem *item = selectedItem();
125 if ( item && item->itemBelow() ) 125 if ( item && item->itemBelow() )
126 item->moveItem( item->itemBelow() ); 126 item->moveItem( item->itemBelow() );
127 ensureItemVisible( selectedItem() ); 127 ensureItemVisible( selectedItem() );
128} 128}
129 129
130 130
131bool PlayListSelection::prev() { 131bool PlayListSelection::prev() {
132 QListViewItem *item = selectedItem(); 132 QListViewItem *item = selectedItem();
133 if ( item && item->itemAbove() ) 133 if ( item && item->itemAbove() )
134 setSelected( item->itemAbove(), TRUE ); 134 setSelected( item->itemAbove(), TRUE );
135 else 135 else
136 return FALSE; 136 return FALSE;
137 ensureItemVisible( selectedItem() ); 137 ensureItemVisible( selectedItem() );
138 return TRUE; 138 return TRUE;
139} 139}
140 140
141bool PlayListSelection::next() { 141bool PlayListSelection::next() {
142 QListViewItem *item = selectedItem(); 142 QListViewItem *item = selectedItem();
143 if ( item && item->itemBelow() ) 143 if ( item && item->itemBelow() )
144 setSelected( item->itemBelow(), TRUE ); 144 setSelected( item->itemBelow(), TRUE );
145 else 145 else
146 return FALSE; 146 return FALSE;
147 ensureItemVisible( selectedItem() ); 147 ensureItemVisible( selectedItem() );
148 return TRUE; 148 return TRUE;
149} 149}
150 150
151 151
152bool PlayListSelection::first() { 152bool PlayListSelection::first() {
153 QListViewItem *item = firstChild(); 153 QListViewItem *item = firstChild();
154 if ( item ) 154 if ( item )
155 setSelected( item, TRUE ); 155 setSelected( item, TRUE );
156 else 156 else
157 return FALSE; 157 return FALSE;
158 ensureItemVisible( selectedItem() ); 158 ensureItemVisible( selectedItem() );
159 return TRUE; 159 return TRUE;
160} 160}
161 161
162 162
163bool PlayListSelection::last() { 163bool PlayListSelection::last() {
164 QListViewItem *prevItem = NULL; 164 QListViewItem *prevItem = NULL;
165 QListViewItem *item = firstChild(); 165 QListViewItem *item = firstChild();
166 while ( ( item = item->nextSibling() ) ) 166 while ( ( item = item->nextSibling() ) )
167 prevItem = item; 167 prevItem = item;
168 if ( prevItem ) 168 if ( prevItem )
169 setSelected( prevItem, TRUE ); 169 setSelected( prevItem, TRUE );
170 else 170 else
171 return FALSE; 171 return FALSE;
172 ensureItemVisible( selectedItem() ); 172 ensureItemVisible( selectedItem() );
173 return TRUE; 173 return TRUE;
174} 174}
175 175
176void PlayListSelection::unSelect() 176void PlayListSelection::unSelect()
177{ 177{
178 //QListViewItem *item = selectedItem(); 178 //QListViewItem *item = selectedItem();
179 setSelected( currentItem(), FALSE); 179 setSelected( currentItem(), FALSE);
180} 180}
181 181
182void PlayListSelection::writeCurrent( Config& cfg ) { 182void PlayListSelection::writeCurrent( Config& cfg ) {
183 cfg.setGroup("PlayList"); 183 cfg.setGroup("PlayList");
184 QListViewItem *item = selectedItem(); 184 QListViewItem *item = selectedItem();
185 if ( item ) 185 if ( item )
186 cfg.writeEntry("current", item->text(0) ); 186 cfg.writeEntry("current", item->text(0) );
187 qDebug(item->text(0)); 187 odebug << item->text(0) << oendl;
188 188
189} 189}
190 190
191void PlayListSelection::setSelectedItem(const QString &strk ) { 191void PlayListSelection::setSelectedItem(const QString &strk ) {
192 192
193 unSelect(); 193 unSelect();
194 QListViewItemIterator it( this ); 194 QListViewItemIterator it( this );
195 for ( ; it.current(); ++it ) { 195 for ( ; it.current(); ++it ) {
196// qDebug( it.current()->text(0)); 196// odebug << it.current()->text(0) << oendl;
197 if( strk == it.current()->text(0)) { 197 if( strk == it.current()->text(0)) {
198// qDebug( "We have a match "+strk); 198// odebug << "We have a match "+strk << oendl;
199 setSelected( it.current(), TRUE); 199 setSelected( it.current(), TRUE);
200 ensureItemVisible( it.current() ); 200 ensureItemVisible( it.current() );
201 return; 201 return;
202 } 202 }
203 } 203 }
204// setSelected( item, TRUE ); 204// setSelected( item, TRUE );
205// ensureItemVisible( selectedItem() ); 205// ensureItemVisible( selectedItem() );
206} 206}
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 )
89 audioView, SLOT( scanFiles() ) ); 89 audioView, SLOT( scanFiles() ) );
90 (void)new MenuItem( pmPlayList, tr( "Rescan for Video Files" ), 90 (void)new MenuItem( pmPlayList, tr( "Rescan for Video Files" ),
91 videoView, SLOT( scanFiles() ) ); 91 videoView, SLOT( scanFiles() ) );
92 92
93 pmView->insertItem( Resource::loadPixmap("fullscreen") , tr( "Full Screen"), 93 pmView->insertItem( Resource::loadPixmap("fullscreen") , tr( "Full Screen"),
94 mediaPlayerState, SLOT( toggleFullscreen() ) ); 94 mediaPlayerState, SLOT( toggleFullscreen() ) );
95 95
96 Config cfg( "OpiePlayer" ); 96 Config cfg( "OpiePlayer" );
97 bool b= cfg.readBoolEntry("FullScreen", 0); 97 bool b= cfg.readBoolEntry("FullScreen", 0);
98 mediaPlayerState->setFullscreen( b ); 98 mediaPlayerState->setFullscreen( b );
99 pmView->setItemChecked( -16, b ); 99 pmView->setItemChecked( -16, b );
100 100
101 (void)new ToolButton( vbox1, tr( "Move Up" ), "opieplayer2/up", 101 (void)new ToolButton( vbox1, tr( "Move Up" ), "opieplayer2/up",
102 d->selectedFiles, SLOT(moveSelectedUp() ) ); 102 d->selectedFiles, SLOT(moveSelectedUp() ) );
103 (void)new ToolButton( vbox1, tr( "Remove" ), "opieplayer2/cut", 103 (void)new ToolButton( vbox1, tr( "Remove" ), "opieplayer2/cut",
104 d->selectedFiles, SLOT(removeSelected() ) ); 104 d->selectedFiles, SLOT(removeSelected() ) );
105 (void)new ToolButton( vbox1, tr( "Move Down" ), "opieplayer2/down", 105 (void)new ToolButton( vbox1, tr( "Move Down" ), "opieplayer2/down",
106 d->selectedFiles, SLOT(moveSelectedDown() ) ); 106 d->selectedFiles, SLOT(moveSelectedDown() ) );
107 QVBox *stretch2 = new QVBox( vbox1 ); 107 QVBox *stretch2 = new QVBox( vbox1 );
108 108
109 connect( tbDeletePlaylist, ( SIGNAL( released() ) ), 109 connect( tbDeletePlaylist, ( SIGNAL( released() ) ),
110 SLOT( deletePlaylist() ) ); 110 SLOT( deletePlaylist() ) );
111 connect( pmView, SIGNAL( activated(int) ), 111 connect( pmView, SIGNAL( activated(int) ),
112 this, SLOT( pmViewActivated(int) ) ); 112 this, SLOT( pmViewActivated(int) ) );
113 connect( skinsMenu, SIGNAL( activated(int) ) , 113 connect( skinsMenu, SIGNAL( activated(int) ) ,
114 this, SLOT( skinsMenuActivated(int) ) ); 114 this, SLOT( skinsMenuActivated(int) ) );
115 connect( d->selectedFiles, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ), 115 connect( d->selectedFiles, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
116 this,SLOT( playlistViewPressed(int,QListViewItem*,const QPoint&,int) ) ); 116 this,SLOT( playlistViewPressed(int,QListViewItem*,const QPoint&,int) ) );
117 connect( audioView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ), 117 connect( audioView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
118 this,SLOT( viewPressed(int,QListViewItem*,const QPoint&,int) ) ); 118 this,SLOT( viewPressed(int,QListViewItem*,const QPoint&,int) ) );
119 connect( audioView, SIGNAL( returnPressed(QListViewItem*) ), 119 connect( audioView, SIGNAL( returnPressed(QListViewItem*) ),
120 this,SLOT( playIt(QListViewItem*) ) ); 120 this,SLOT( playIt(QListViewItem*) ) );
121 connect( audioView, SIGNAL( doubleClicked(QListViewItem*) ), 121 connect( audioView, SIGNAL( doubleClicked(QListViewItem*) ),
122 this, SLOT( addToSelection(QListViewItem*) ) ); 122 this, SLOT( addToSelection(QListViewItem*) ) );
123 connect( videoView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ), 123 connect( videoView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
124 this,SLOT( viewPressed(int,QListViewItem*,const QPoint&,int) ) ); 124 this,SLOT( viewPressed(int,QListViewItem*,const QPoint&,int) ) );
125 connect( videoView, SIGNAL( returnPressed(QListViewItem*) ), 125 connect( videoView, SIGNAL( returnPressed(QListViewItem*) ),
126 this,SLOT( playIt(QListViewItem*) ) ); 126 this,SLOT( playIt(QListViewItem*) ) );
127 connect( videoView, SIGNAL( doubleClicked(QListViewItem*) ), 127 connect( videoView, SIGNAL( doubleClicked(QListViewItem*) ),
128 this, SLOT( addToSelection(QListViewItem*) ) ); 128 this, SLOT( addToSelection(QListViewItem*) ) );
129 connect( playLists, SIGNAL( fileSelected(const DocLnk&) ), 129 connect( playLists, SIGNAL( fileSelected(const DocLnk&) ),
130 this, SLOT( loadList(const DocLnk&) ) ); 130 this, SLOT( loadList(const DocLnk&) ) );
131 connect( tabWidget, SIGNAL ( currentChanged(QWidget*) ), 131 connect( tabWidget, SIGNAL ( currentChanged(QWidget*) ),
132 this, SLOT( tabChanged(QWidget*) ) ); 132 this, SLOT( tabChanged(QWidget*) ) );
133 connect( mediaPlayerState, SIGNAL( playingToggled(bool) ), 133 connect( mediaPlayerState, SIGNAL( playingToggled(bool) ),
134 d->tbPlay, SLOT( setOn(bool) ) ); 134 d->tbPlay, SLOT( setOn(bool) ) );
135 connect( mediaPlayerState, SIGNAL( loopingToggled(bool) ), 135 connect( mediaPlayerState, SIGNAL( loopingToggled(bool) ),
136 d->tbLoop, SLOT( setOn(bool) ) ); 136 d->tbLoop, SLOT( setOn(bool) ) );
137 connect( mediaPlayerState, SIGNAL( shuffledToggled(bool) ), 137 connect( mediaPlayerState, SIGNAL( shuffledToggled(bool) ),
138 d->tbShuffle, SLOT( setOn(bool) ) ); 138 d->tbShuffle, SLOT( setOn(bool) ) );
139 connect( d->selectedFiles, SIGNAL( doubleClicked(QListViewItem*) ), 139 connect( d->selectedFiles, SIGNAL( doubleClicked(QListViewItem*) ),
140 this, SLOT( playIt(QListViewItem*) ) ); 140 this, SLOT( playIt(QListViewItem*) ) );
141 connect ( gammaSlider, SIGNAL( valueChanged(int) ), 141 connect ( gammaSlider, SIGNAL( valueChanged(int) ),
142 mediaPlayerState, SLOT( setVideoGamma(int) ) ); 142 mediaPlayerState, SLOT( setVideoGamma(int) ) );
143 143
144 connect( this, SIGNAL(skinSelected() ), 144 connect( this, SIGNAL(skinSelected() ),
145 m_mp, SLOT( reloadSkins() ) ); 145 m_mp, SLOT( reloadSkins() ) );
146 146
147 // see which skins are installed 147 // see which skins are installed
148 populateSkinsMenu(); 148 populateSkinsMenu();
149 initializeStates(); 149 initializeStates();
150 150
151 channel = new QCopChannel( "QPE/Application/opieplayer2", this ); 151 channel = new QCopChannel( "QPE/Application/opieplayer2", this );
152 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), 152 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
153 this, SLOT( qcopReceive(const QCString&,const QByteArray&)) ); 153 this, SLOT( qcopReceive(const QCString&,const QByteArray&)) );
154 154
155 155
156 cfg.setGroup("PlayList"); 156 cfg.setGroup("PlayList");
157 QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default"); 157 QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default");
158 loadList(DocLnk( currentPlaylist ) ); 158 loadList(DocLnk( currentPlaylist ) );
159 159
160 tabWidget->showPage( playListTab ); 160 tabWidget->showPage( playListTab );
161} 161}
162 162
163 163
164PlayListWidget::~PlayListWidget() { 164PlayListWidget::~PlayListWidget() {
165 delete d; 165 delete d;
166 delete m_mp; 166 delete m_mp;
167} 167}
168 168
169 169
170void PlayListWidget::initializeStates() { 170void PlayListWidget::initializeStates() {
171 d->tbPlay->setOn( mediaPlayerState->isPlaying() ); 171 d->tbPlay->setOn( mediaPlayerState->isPlaying() );
172 d->tbLoop->setOn( mediaPlayerState->isLooping() ); 172 d->tbLoop->setOn( mediaPlayerState->isLooping() );
173 d->tbShuffle->setOn( mediaPlayerState->isShuffled() ); 173 d->tbShuffle->setOn( mediaPlayerState->isShuffled() );
174 d->playListFrame->show(); 174 d->playListFrame->show();
175} 175}
176 176
177void PlayListWidget::writeDefaultPlaylist() { 177void PlayListWidget::writeDefaultPlaylist() {
178 178
179 Config config( "OpiePlayer" ); 179 Config config( "OpiePlayer" );
180 config.setGroup( "PlayList" ); 180 config.setGroup( "PlayList" );
181 QString filename=QPEApplication::documentDir() + "/default.m3u"; 181 QString filename=QPEApplication::documentDir() + "/default.m3u";
182 QString currentString = config.readEntry( "CurrentPlaylist", filename); 182 QString currentString = config.readEntry( "CurrentPlaylist", filename);
183 if( currentString == filename) { 183 if( currentString == filename) {
184 Om3u *m3uList; 184 Om3u *m3uList;
185 // qDebug("<<<<<<<<<<<<<default>>>>>>>>>>>>>>>>>>>"); 185 // odebug << "<<<<<<<<<<<<<default>>>>>>>>>>>>>>>>>>>" << oendl;
186 if( d->selectedFiles->first() ) { 186 if( d->selectedFiles->first() ) {
187 m3uList = new Om3u(filename, IO_ReadWrite | IO_Truncate); 187 m3uList = new Om3u(filename, IO_ReadWrite | IO_Truncate);
188 do { 188 do {
189 // qDebug(d->selectedFiles->current()->file()); 189 // odebug << d->selectedFiles->current()->file() << oendl;
190 m3uList->add( d->selectedFiles->current()->file() ); 190 m3uList->add( d->selectedFiles->current()->file() );
191 } 191 }
192 while ( d->selectedFiles->next() ); 192 while ( d->selectedFiles->next() );
193 193
194 m3uList->write(); 194 m3uList->write();
195 m3uList->close(); 195 m3uList->close();
196 delete m3uList; 196 delete m3uList;
197 197
198 } 198 }
199 } 199 }
200} 200}
201 201
202void PlayListWidget::addToSelection( const DocLnk& lnk ) { 202void PlayListWidget::addToSelection( const DocLnk& lnk ) {
203 d->setDocumentUsed = FALSE; 203 d->setDocumentUsed = FALSE;
204 if( QFileInfo( lnk.file() ).exists() || 204 if( QFileInfo( lnk.file() ).exists() ||
205 lnk.file().left(4) == "http" ) { 205 lnk.file().left(4) == "http" ) {
206 d->selectedFiles->addToSelection( lnk ); 206 d->selectedFiles->addToSelection( lnk );
207 } 207 }
208// writeCurrentM3u(); 208// writeCurrentM3u();
209} 209}
210 210
211 211
212void PlayListWidget::clearList() { 212void PlayListWidget::clearList() {
213 while ( first() ) { 213 while ( first() ) {
214 d->selectedFiles->removeSelected(); 214 d->selectedFiles->removeSelected();
215 } 215 }
216 Config cfg( "OpiePlayer" ); 216 Config cfg( "OpiePlayer" );
217 cfg.setGroup("PlayList"); 217 cfg.setGroup("PlayList");
218 cfg.writeEntry("CurrentPlaylist","default"); 218 cfg.writeEntry("CurrentPlaylist","default");
219 setCaption("OpiePlayer"); 219 setCaption("OpiePlayer");
220} 220}
221 221
222void PlayListWidget::viewPressed( int mouse, QListViewItem *, const QPoint& , int) { 222void PlayListWidget::viewPressed( int mouse, QListViewItem *, const QPoint& , int) {
223 switch (mouse) { 223 switch (mouse) {
224 case LeftButton: 224 case LeftButton:
225 break; 225 break;
226 case RightButton: 226 case RightButton:
227 { 227 {
228 QPopupMenu m; 228 QPopupMenu m;
229 m.insertItem( tr( "Play Selected" ), this, SLOT( playSelected() )); 229 m.insertItem( tr( "Play Selected" ), this, SLOT( playSelected() ));
230 m.insertItem( tr( "Add to Playlist" ), this, SLOT( addSelected() )); 230 m.insertItem( tr( "Add to Playlist" ), this, SLOT( addSelected() ));
231 m.exec( QCursor::pos() ); 231 m.exec( QCursor::pos() );
232 } 232 }
233 break; 233 break;
234 } 234 }
235} 235}
236 236
237 237
238void PlayListWidget::playlistViewPressed( int mouse, QListViewItem *, const QPoint& , int ) { 238void PlayListWidget::playlistViewPressed( int mouse, QListViewItem *, const QPoint& , int ) {
239 switch (mouse) { 239 switch (mouse) {
240 case LeftButton: 240 case LeftButton:
241 break; 241 break;
242 case RightButton: 242 case RightButton:
243 { 243 {
244 QPopupMenu m; 244 QPopupMenu m;
245 m.insertItem( tr( "Play" ), this, SLOT( playSelected() )); 245 m.insertItem( tr( "Play" ), this, SLOT( playSelected() ));
246 m.insertItem( tr( "Remove" ), this, SLOT( removeSelected() )); 246 m.insertItem( tr( "Remove" ), this, SLOT( removeSelected() ));
247 m.exec( QCursor::pos() ); 247 m.exec( QCursor::pos() );
248 } 248 }
249 break; 249 break;
250 } 250 }
251} 251}
252 252
253 253
254void PlayListWidget::addAllToList() { 254void PlayListWidget::addAllToList() {
255 255
256 256
257 audioView->populateView(); 257 audioView->populateView();
258 258
259 QListViewItemIterator audioIt( audioView ); 259 QListViewItemIterator audioIt( audioView );
260 DocLnk lnk; 260 DocLnk lnk;
261 QString filename; 261 QString filename;
262 // iterate through all items of the listview 262 // iterate through all items of the listview
263 for ( ; audioIt.current(); ++audioIt ) { 263 for ( ; audioIt.current(); ++audioIt ) {
264 filename = audioIt.current()->text(3); 264 filename = audioIt.current()->text(3);
265 lnk.setName( QFileInfo(filename).baseName() ); //sets name 265 lnk.setName( QFileInfo(filename).baseName() ); //sets name
266 lnk.setFile( filename ); //sets file name 266 lnk.setFile( filename ); //sets file name
267 d->selectedFiles->addToSelection( lnk); 267 d->selectedFiles->addToSelection( lnk);
268 } 268 }
269 269
270 videoView->populateView(); 270 videoView->populateView();
271 271
272 QListViewItemIterator videoIt( videoView ); 272 QListViewItemIterator videoIt( videoView );
273 for ( ; videoIt.current(); ++videoIt ) { 273 for ( ; videoIt.current(); ++videoIt ) {
274 filename = videoIt.current()->text(3); 274 filename = videoIt.current()->text(3);
275 lnk.setName( QFileInfo(filename).baseName() ); //sets name 275 lnk.setName( QFileInfo(filename).baseName() ); //sets name
276 lnk.setFile( filename ); //sets file name 276 lnk.setFile( filename ); //sets file name
277 d->selectedFiles->addToSelection( lnk); 277 d->selectedFiles->addToSelection( lnk);
278 } 278 }
279 279
280 tabWidget->setCurrentPage(0); 280 tabWidget->setCurrentPage(0);
281 281
282 writeCurrentM3u(); 282 writeCurrentM3u();
283 d->selectedFiles->first(); 283 d->selectedFiles->first();
284} 284}
285 285
286 286
287void PlayListWidget::addAllMusicToList() { 287void PlayListWidget::addAllMusicToList() {
288 288
289 audioView->populateView(); 289 audioView->populateView();
290 290
291 QListViewItemIterator audioIt( audioView ); 291 QListViewItemIterator audioIt( audioView );
292 DocLnk lnk; 292 DocLnk lnk;
293 QString filename; 293 QString filename;
294 // iterate through all items of the listview 294 // iterate through all items of the listview
295 for ( ; audioIt.current(); ++audioIt ) { 295 for ( ; audioIt.current(); ++audioIt ) {
296 filename = audioIt.current()->text(3); 296 filename = audioIt.current()->text(3);
297 lnk.setName( QFileInfo(filename).baseName() ); //sets name 297 lnk.setName( QFileInfo(filename).baseName() ); //sets name
298 lnk.setFile( filename ); //sets file name 298 lnk.setFile( filename ); //sets file name
299 d->selectedFiles->addToSelection( lnk); 299 d->selectedFiles->addToSelection( lnk);
300 } 300 }
301 301
302 tabWidget->setCurrentPage(0); 302 tabWidget->setCurrentPage(0);
303 writeCurrentM3u(); 303 writeCurrentM3u();
304 d->selectedFiles->first(); 304 d->selectedFiles->first();
305} 305}
306 306
307 307
308void PlayListWidget::addAllVideoToList() { 308void PlayListWidget::addAllVideoToList() {
309 309
310 videoView->populateView(); 310 videoView->populateView();
311 311
312 QListViewItemIterator videoIt( videoView ); 312 QListViewItemIterator videoIt( videoView );
313 DocLnk lnk; 313 DocLnk lnk;
314 QString filename; 314 QString filename;
315 for ( ; videoIt.current(); ++videoIt ) { 315 for ( ; videoIt.current(); ++videoIt ) {
316 filename = videoIt.current()->text(3); 316 filename = videoIt.current()->text(3);
317 lnk.setName( QFileInfo(filename).baseName() ); //sets name 317 lnk.setName( QFileInfo(filename).baseName() ); //sets name
318 lnk.setFile( filename ); //sets file name 318 lnk.setFile( filename ); //sets file name
319 d->selectedFiles->addToSelection( lnk); 319 d->selectedFiles->addToSelection( lnk);
320 } 320 }
321 tabWidget->setCurrentPage(0); 321 tabWidget->setCurrentPage(0);
322 writeCurrentM3u(); 322 writeCurrentM3u();
323 d->selectedFiles->first(); 323 d->selectedFiles->first();
324} 324}
325 325
326 326
327void PlayListWidget::setDocument( const QString& fileref ) { 327void PlayListWidget::setDocument( const QString& fileref ) {
328 // qDebug( "<<<<<<<<set document>>>>>>>>>> "+fileref ); 328 // odebug << "<<<<<<<<set document>>>>>>>>>> "+fileref << oendl;
329 fromSetDocument = TRUE; 329 fromSetDocument = TRUE;
330 QFileInfo fileInfo(fileref); 330 QFileInfo fileInfo(fileref);
331 331
332 if ( !fileInfo.exists() ) { 332 if ( !fileInfo.exists() ) {
333 QMessageBox::warning( this, tr( "Invalid File" ), 333 QMessageBox::warning( this, tr( "Invalid File" ),
334 tr( "There was a problem in getting the file." ) ); 334 tr( "There was a problem in getting the file." ) );
335 return; 335 return;
336 } 336 }
337 337
338 clearList(); 338 clearList();
339 QString extension = fileInfo.extension(false); 339 QString extension = fileInfo.extension(false);
340 340
341 if( extension.find( "m3u", 0, false) != -1 341 if( extension.find( "m3u", 0, false) != -1
342 || extension.find( "pls", 0, false) != -1 ) { 342 || extension.find( "pls", 0, false) != -1 ) {
343 readListFromFile( fileref ); 343 readListFromFile( fileref );
344 } else { 344 } else {
345 clearList(); 345 clearList();
346 DocLnk lnk; 346 DocLnk lnk;
347 lnk.setName( fileInfo.baseName() ); //sets name 347 lnk.setName( fileInfo.baseName() ); //sets name
348 lnk.setFile( fileref ); //sets file name 348 lnk.setFile( fileref ); //sets file name
349 addToSelection( lnk ); 349 addToSelection( lnk );
350 writeCurrentM3u(); 350 writeCurrentM3u();
351 351
352 d->setDocumentUsed = TRUE; 352 d->setDocumentUsed = TRUE;
353 mediaPlayerState->setPlaying( FALSE ); 353 mediaPlayerState->setPlaying( FALSE );
354 mediaPlayerState->setPlaying( TRUE ); 354 mediaPlayerState->setPlaying( TRUE );
355 } 355 }
356} 356}
357 357
358 358
359void PlayListWidget::useSelectedDocument() { 359void PlayListWidget::useSelectedDocument() {
360 d->setDocumentUsed = FALSE; 360 d->setDocumentUsed = FALSE;
361} 361}
362 362
363 363
364const DocLnk *PlayListWidget::current() const { // this is fugly 364const DocLnk *PlayListWidget::current() const { // this is fugly
365 assert( currentTab() == CurrentPlayList ); 365 assert( currentTab() == CurrentPlayList );
366 366
367 const DocLnk *lnk = d->selectedFiles->current(); 367 const DocLnk *lnk = d->selectedFiles->current();
368 if ( !lnk ) { 368 if ( !lnk ) {
369 d->selectedFiles->first(); 369 d->selectedFiles->first();
370 lnk = d->selectedFiles->current(); 370 lnk = d->selectedFiles->current();
371 } 371 }
372 assert( lnk ); 372 assert( lnk );
373 return lnk; 373 return lnk;
374} 374}
375 375
376 376
377bool PlayListWidget::prev() { 377bool PlayListWidget::prev() {
378 if ( mediaPlayerState->isShuffled() ) { 378 if ( mediaPlayerState->isShuffled() ) {
379 const DocLnk *cur = current(); 379 const DocLnk *cur = current();
380 int j = 1 + (int)(97.0 * rand() / (RAND_MAX + 1.0)); 380 int j = 1 + (int)(97.0 * rand() / (RAND_MAX + 1.0));
381 for ( int i = 0; i < j; i++ ) { 381 for ( int i = 0; i < j; i++ ) {
382 if ( !d->selectedFiles->next() ) 382 if ( !d->selectedFiles->next() )
383 d->selectedFiles->first(); 383 d->selectedFiles->first();
384 } 384 }
385 if ( cur == current() ) 385 if ( cur == current() )
386 if ( !d->selectedFiles->next() ) { 386 if ( !d->selectedFiles->next() ) {
387 d->selectedFiles->first(); 387 d->selectedFiles->first();
388 } 388 }
389 return TRUE; 389 return TRUE;
390 } else { 390 } else {
391 if ( !d->selectedFiles->prev() ) { 391 if ( !d->selectedFiles->prev() ) {
392 if ( mediaPlayerState->isLooping() ) { 392 if ( mediaPlayerState->isLooping() ) {
393 return d->selectedFiles->last(); 393 return d->selectedFiles->last();
394 } else { 394 } else {
395 return FALSE; 395 return FALSE;
396 } 396 }
397 } 397 }
398 return TRUE; 398 return TRUE;
399 } 399 }
400} 400}
401 401
402 402
403bool PlayListWidget::next() { 403bool PlayListWidget::next() {
404//qDebug("<<<<<<<<<<<<next()"); 404//odebug << "<<<<<<<<<<<<next()" << oendl;
405 if ( mediaPlayerState->isShuffled() ) { 405 if ( mediaPlayerState->isShuffled() ) {
406 return prev(); 406 return prev();
407 } else { 407 } else {
408 if ( !d->selectedFiles->next() ) { 408 if ( !d->selectedFiles->next() ) {
409 if ( mediaPlayerState->isLooping() ) { 409 if ( mediaPlayerState->isLooping() ) {
410 return d->selectedFiles->first(); 410 return d->selectedFiles->first();
411 } else { 411 } else {
412 return FALSE; 412 return FALSE;
413 } 413 }
414 } 414 }
415 return TRUE; 415 return TRUE;
416 } 416 }
417} 417}
418 418
419 419
420bool PlayListWidget::first() { 420bool PlayListWidget::first() {
421 return d->selectedFiles->first(); 421 return d->selectedFiles->first();
422} 422}
423 423
424 424
425bool PlayListWidget::last() { 425bool PlayListWidget::last() {
426 return d->selectedFiles->last(); 426 return d->selectedFiles->last();
427} 427}
428 428
429 429
430 void PlayListWidget::saveList() { 430 void PlayListWidget::saveList() {
431 writem3u(); 431 writem3u();
432 } 432 }
433 433
434 434
435void PlayListWidget::loadList( const DocLnk & lnk) { 435void PlayListWidget::loadList( const DocLnk & lnk) {
436 QString name = lnk.name(); 436 QString name = lnk.name();
437 437
438 if( name.length()>0) { 438 if( name.length()>0) {
439 setCaption("OpiePlayer: "+name); 439 setCaption("OpiePlayer: "+name);
440 clearList(); 440 clearList();
441 readListFromFile(lnk.file()); 441 readListFromFile(lnk.file());
442 tabWidget->setCurrentPage(0); 442 tabWidget->setCurrentPage(0);
443 } 443 }
444} 444}
445 445
446void PlayListWidget::addSelected() { 446void PlayListWidget::addSelected() {
447 assert( inFileListMode() ); 447 assert( inFileListMode() );
448 448
449 QListViewItemIterator it( currentFileListView ); 449 QListViewItemIterator it( currentFileListView );
450 for ( ; it.current(); ++it ) 450 for ( ; it.current(); ++it )
451 if ( it.current()->isSelected() ) { 451 if ( it.current()->isSelected() ) {
452 QString filename = it.current()->text(3); 452 QString filename = it.current()->text(3);
453 453
454 DocLnk lnk; 454 DocLnk lnk;
455 lnk.setName( QFileInfo( filename ).baseName() ); //sets name 455 lnk.setName( QFileInfo( filename ).baseName() ); //sets name
456 lnk.setFile( filename ); //sets file name 456 lnk.setFile( filename ); //sets file name
457 457
458 d->selectedFiles->addToSelection( lnk ); 458 d->selectedFiles->addToSelection( lnk );
459 } 459 }
460 460
461 currentFileListView->clearSelection(); 461 currentFileListView->clearSelection();
462 462
463 writeCurrentM3u(); 463 writeCurrentM3u();
464} 464}
465 465
466 466
467void PlayListWidget::removeSelected() { 467void PlayListWidget::removeSelected() {
468 d->selectedFiles->removeSelected( ); 468 d->selectedFiles->removeSelected( );
469 writeCurrentM3u(); 469 writeCurrentM3u();
470} 470}
471 471
472 472
473void PlayListWidget::playIt( QListViewItem *it) { 473void PlayListWidget::playIt( QListViewItem *it) {
474 if(!it) return; 474 if(!it) return;
475 mediaPlayerState->setPlaying(FALSE); 475 mediaPlayerState->setPlaying(FALSE);
476 mediaPlayerState->setPlaying(TRUE); 476 mediaPlayerState->setPlaying(TRUE);
477 d->selectedFiles->unSelect(); 477 d->selectedFiles->unSelect();
478} 478}
479 479
480 480
481void PlayListWidget::addToSelection( QListViewItem *it) { 481void PlayListWidget::addToSelection( QListViewItem *it) {
482 d->setDocumentUsed = FALSE; 482 d->setDocumentUsed = FALSE;
483 483
484 if(it) { 484 if(it) {
485 if ( currentTab() == CurrentPlayList ) 485 if ( currentTab() == CurrentPlayList )
486 return; 486 return;
487 DocLnk lnk; 487 DocLnk lnk;
488 QString filename; 488 QString filename;
489 489
490 filename=it->text(3); 490 filename=it->text(3);
491 lnk.setName( QFileInfo(filename).baseName() ); //sets name 491 lnk.setName( QFileInfo(filename).baseName() ); //sets name
492 lnk.setFile( filename ); //sets file name 492 lnk.setFile( filename ); //sets file name
493 d->selectedFiles->addToSelection( lnk); 493 d->selectedFiles->addToSelection( lnk);
494 494
495 writeCurrentM3u(); 495 writeCurrentM3u();
496// tabWidget->setCurrentPage(0); 496// tabWidget->setCurrentPage(0);
497 497
498 } 498 }
499} 499}
500 500
@@ -519,525 +519,525 @@ void PlayListWidget::tabChanged(QWidget *) {
519 d->tbRemoveFromList->setEnabled(TRUE); 519 d->tbRemoveFromList->setEnabled(TRUE);
520 d->tbAddToList->setEnabled(FALSE); 520 d->tbAddToList->setEnabled(FALSE);
521 521
522 d->tbPlay->setEnabled( !d->selectedFiles->isEmpty() ); 522 d->tbPlay->setEnabled( !d->selectedFiles->isEmpty() );
523 } 523 }
524 break; 524 break;
525 case AudioFiles: 525 case AudioFiles:
526 { 526 {
527 audioView->populateView(); 527 audioView->populateView();
528 528
529 if( !tbDeletePlaylist->isHidden() ) { 529 if( !tbDeletePlaylist->isHidden() ) {
530 tbDeletePlaylist->hide(); 530 tbDeletePlaylist->hide();
531 } 531 }
532 d->tbRemoveFromList->setEnabled(FALSE); 532 d->tbRemoveFromList->setEnabled(FALSE);
533 d->tbAddToList->setEnabled(TRUE); 533 d->tbAddToList->setEnabled(TRUE);
534 534
535 connect( audioView, SIGNAL( itemsSelected(bool) ), 535 connect( audioView, SIGNAL( itemsSelected(bool) ),
536 d->tbPlay, SLOT( setEnabled(bool) ) ); 536 d->tbPlay, SLOT( setEnabled(bool) ) );
537 537
538 d->tbPlay->setEnabled( audioView->hasSelection() ); 538 d->tbPlay->setEnabled( audioView->hasSelection() );
539 539
540 currentFileListView = audioView; 540 currentFileListView = audioView;
541 } 541 }
542 break; 542 break;
543 case VideoFiles: 543 case VideoFiles:
544 { 544 {
545 videoView->populateView(); 545 videoView->populateView();
546 if( !tbDeletePlaylist->isHidden() ) { 546 if( !tbDeletePlaylist->isHidden() ) {
547 tbDeletePlaylist->hide(); 547 tbDeletePlaylist->hide();
548 } 548 }
549 d->tbRemoveFromList->setEnabled(FALSE); 549 d->tbRemoveFromList->setEnabled(FALSE);
550 d->tbAddToList->setEnabled(TRUE); 550 d->tbAddToList->setEnabled(TRUE);
551 551
552 connect( videoView, SIGNAL( itemsSelected(bool) ), 552 connect( videoView, SIGNAL( itemsSelected(bool) ),
553 d->tbPlay, SLOT( setEnabled(bool) ) ); 553 d->tbPlay, SLOT( setEnabled(bool) ) );
554 554
555 d->tbPlay->setEnabled( videoView->hasSelection() ); 555 d->tbPlay->setEnabled( videoView->hasSelection() );
556 556
557 currentFileListView = videoView; 557 currentFileListView = videoView;
558 } 558 }
559 break; 559 break;
560 case PlayLists: 560 case PlayLists:
561 { 561 {
562 if( tbDeletePlaylist->isHidden() ) { 562 if( tbDeletePlaylist->isHidden() ) {
563 tbDeletePlaylist->show(); 563 tbDeletePlaylist->show();
564 } 564 }
565 playLists->reread(); 565 playLists->reread();
566 d->tbAddToList->setEnabled(FALSE); 566 d->tbAddToList->setEnabled(FALSE);
567 567
568 d->tbPlay->setEnabled( false ); 568 d->tbPlay->setEnabled( false );
569 } 569 }
570 break; 570 break;
571 }; 571 };
572} 572}
573 573
574 574
575void PlayListWidget::btnPlay(bool b) { 575void PlayListWidget::btnPlay(bool b) {
576// mediaPlayerState->setPlaying(false); 576// mediaPlayerState->setPlaying(false);
577 mediaPlayerState->setPlaying(b); 577 mediaPlayerState->setPlaying(b);
578 insanityBool=FALSE; 578 insanityBool=FALSE;
579} 579}
580 580
581void PlayListWidget::deletePlaylist() { 581void PlayListWidget::deletePlaylist() {
582 switch( QMessageBox::information( this, (tr("Remove Playlist?")), 582 switch( QMessageBox::information( this, (tr("Remove Playlist?")),
583 (tr("You really want to delete\nthis playlist?")), 583 (tr("You really want to delete\nthis playlist?")),
584 (tr("Yes")), (tr("No")), 0 )){ 584 (tr("Yes")), (tr("No")), 0 )){
585 case 0: // Yes clicked, 585 case 0: // Yes clicked,
586 QFile().remove(playLists->selectedDocument().file()); 586 QFile().remove(playLists->selectedDocument().file());
587 QFile().remove(playLists->selectedDocument().linkFile()); 587 QFile().remove(playLists->selectedDocument().linkFile());
588 playLists->reread(); 588 playLists->reread();
589 break; 589 break;
590 case 1: // Cancel 590 case 1: // Cancel
591 break; 591 break;
592 }; 592 };
593} 593}
594 594
595 595
596void PlayListWidget::playSelected() { 596void PlayListWidget::playSelected() {
597 btnPlay( TRUE); 597 btnPlay( TRUE);
598} 598}
599 599
600bool PlayListWidget::inFileListMode() const 600bool PlayListWidget::inFileListMode() const
601{ 601{
602 TabType tab = currentTab(); 602 TabType tab = currentTab();
603 return tab == AudioFiles || tab == VideoFiles; 603 return tab == AudioFiles || tab == VideoFiles;
604} 604}
605 605
606void PlayListWidget::openURL() { 606void PlayListWidget::openURL() {
607 // http://66.28.164.33:2080 607 // http://66.28.164.33:2080
608 // http://somafm.com/star0242.m3u 608 // http://somafm.com/star0242.m3u
609 QString filename, name; 609 QString filename, name;
610 InputDialog *fileDlg; 610 InputDialog *fileDlg;
611 fileDlg = new InputDialog(this,tr("Add URL"),TRUE, 0); 611 fileDlg = new InputDialog(this,tr("Add URL"),TRUE, 0);
612 fileDlg->exec(); 612 fileDlg->exec();
613 if( fileDlg->result() == 1 ) { 613 if( fileDlg->result() == 1 ) {
614 filename = fileDlg->text(); 614 filename = fileDlg->text();
615 qDebug( "Selected filename is " + filename ); 615 odebug << "Selected filename is " + filename << oendl;
616 // Om3u *m3uList; 616 // Om3u *m3uList;
617 DocLnk lnk; 617 DocLnk lnk;
618 Config cfg( "OpiePlayer" ); 618 Config cfg( "OpiePlayer" );
619 cfg.setGroup("PlayList"); 619 cfg.setGroup("PlayList");
620 620
621 if(filename.left(4) == "http") { 621 if(filename.left(4) == "http") {
622 QString m3uFile, m3uFilePath; 622 QString m3uFile, m3uFilePath;
623 if(filename.find(":",8,TRUE) != -1) { //found a port 623 if(filename.find(":",8,TRUE) != -1) { //found a port
624 m3uFile = filename.left( filename.find( ":",8,TRUE)); 624 m3uFile = filename.left( filename.find( ":",8,TRUE));
625 m3uFile = m3uFile.right( 7); 625 m3uFile = m3uFile.right( 7);
626 } else if(filename.left(4) == "http"){ 626 } else if(filename.left(4) == "http"){
627 m3uFile=filename; 627 m3uFile=filename;
628 m3uFile = m3uFile.right( m3uFile.length() - 7); 628 m3uFile = m3uFile.right( m3uFile.length() - 7);
629 } else{ 629 } else{
630 m3uFile=filename; 630 m3uFile=filename;
631 } 631 }
632 632
633 lnk.setName( filename ); //sets name 633 lnk.setName( filename ); //sets name
634 lnk.setFile( filename ); //sets file name 634 lnk.setFile( filename ); //sets file name
635 635
636// lnk.setIcon("opieplayer2/musicfile"); 636// lnk.setIcon("opieplayer2/musicfile");
637 637
638 d->selectedFiles->addToSelection( lnk ); 638 d->selectedFiles->addToSelection( lnk );
639 writeCurrentM3u(); 639 writeCurrentM3u();
640 d->selectedFiles->setSelectedItem( lnk.name()); 640 d->selectedFiles->setSelectedItem( lnk.name());
641 } 641 }
642 else if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) { 642 else if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) {
643 readListFromFile( filename ); 643 readListFromFile( filename );
644 } else { 644 } else {
645 lnk.setName( QFileInfo(filename).baseName() ); //sets name 645 lnk.setName( QFileInfo(filename).baseName() ); //sets name
646 lnk.setFile( filename ); //sets file name 646 lnk.setFile( filename ); //sets file name
647 d->selectedFiles->addToSelection( lnk); 647 d->selectedFiles->addToSelection( lnk);
648 writeCurrentM3u(); 648 writeCurrentM3u();
649 d->selectedFiles->setSelectedItem( lnk.name()); 649 d->selectedFiles->setSelectedItem( lnk.name());
650 } 650 }
651 } 651 }
652 652
653 653
654 delete fileDlg; 654 delete fileDlg;
655} 655}
656 656
657 657
658void PlayListWidget::openFile() { 658void PlayListWidget::openFile() {
659 659
660 QString filename, name; 660 QString filename, name;
661 661
662 Config cfg( "OpiePlayer" ); 662 Config cfg( "OpiePlayer" );
663 cfg.setGroup("Dialog"); 663 cfg.setGroup("Dialog");
664 MimeTypes types; 664 MimeTypes types;
665 QStringList audio, video, all; 665 QStringList audio, video, all;
666 audio << "audio/*"; 666 audio << "audio/*";
667 audio << "playlist/plain"; 667 audio << "playlist/plain";
668 audio << "audio/x-ogg"; 668 audio << "audio/x-ogg";
669 audio << "audio/x-mpegurl"; 669 audio << "audio/x-mpegurl";
670 670
671 video << "video/*"; 671 video << "video/*";
672 video << "playlist/plain"; 672 video << "playlist/plain";
673 673
674 all += audio; 674 all += audio;
675 all += video; 675 all += video;
676 types.insert("All Media Files", all ); 676 types.insert("All Media Files", all );
677 types.insert("Audio", audio ); 677 types.insert("Audio", audio );
678 types.insert("Video", video ); 678 types.insert("Video", video );
679 679
680 QString str = OFileDialog::getOpenFileName( 1, 680 QString str = OFileDialog::getOpenFileName( 1,
681 cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"", 681 cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"",
682 types, 0 ); 682 types, 0 );
683 683
684 if(str.left(2) == "//") { 684 if(str.left(2) == "//") {
685 str=str.right(str.length()-1); 685 str=str.right(str.length()-1);
686 } 686 }
687 cfg.writeEntry( "LastDirectory" ,QFileInfo( str ).dirPath() ); 687 cfg.writeEntry( "LastDirectory" ,QFileInfo( str ).dirPath() );
688 688
689 if( !str.isEmpty() ) { 689 if( !str.isEmpty() ) {
690 690
691 qDebug( "Selected filename is " + str ); 691 odebug << "Selected filename is " + str << oendl;
692 filename = str; 692 filename = str;
693 DocLnk lnk; 693 DocLnk lnk;
694 694
695 if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) { 695 if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) {
696 readListFromFile( filename ); 696 readListFromFile( filename );
697 } else { 697 } else {
698 lnk.setName( QFileInfo(filename).baseName() ); //sets name 698 lnk.setName( QFileInfo(filename).baseName() ); //sets name
699 lnk.setFile( filename ); //sets file name 699 lnk.setFile( filename ); //sets file name
700 d->selectedFiles->addToSelection( lnk ); 700 d->selectedFiles->addToSelection( lnk );
701 writeCurrentM3u(); 701 writeCurrentM3u();
702 d->selectedFiles->setSelectedItem( lnk.name() ); 702 d->selectedFiles->setSelectedItem( lnk.name() );
703 } 703 }
704 } 704 }
705} 705}
706 706
707 707
708void PlayListWidget::readListFromFile( const QString &filename ) { 708void PlayListWidget::readListFromFile( const QString &filename ) {
709 qDebug( "read list filename " + filename ); 709 odebug << "read list filename " + filename << oendl;
710 QFileInfo fi(filename); 710 QFileInfo fi(filename);
711 Om3u *m3uList; 711 Om3u *m3uList;
712 QString s, name; 712 QString s, name;
713 m3uList = new Om3u( filename, IO_ReadOnly ); 713 m3uList = new Om3u( filename, IO_ReadOnly );
714 if(fi.extension(false).find("m3u",0,false) != -1 ) 714 if(fi.extension(false).find("m3u",0,false) != -1 )
715 m3uList->readM3u(); 715 m3uList->readM3u();
716 else if(fi.extension(false).find("pls",0,false) != -1 ) 716 else if(fi.extension(false).find("pls",0,false) != -1 )
717 m3uList->readPls(); 717 m3uList->readPls();
718 718
719 DocLnk lnk; 719 DocLnk lnk;
720 for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) { 720 for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) {
721 s = *it; 721 s = *it;
722 // qDebug(s); 722 // odebug << s << oendl;
723 if(s.left(4)=="http") { 723 if(s.left(4)=="http") {
724 lnk.setName( s ); //sets file name 724 lnk.setName( s ); //sets file name
725 lnk.setIcon("opieplayer2/musicfile"); 725 lnk.setIcon("opieplayer2/musicfile");
726 lnk.setFile( s ); //sets file name 726 lnk.setFile( s ); //sets file name
727 727
728 } else { //is file 728 } else { //is file
729 lnk.setName( QFileInfo(s).baseName()); 729 lnk.setName( QFileInfo(s).baseName());
730 if(s.left(1) != "/") { 730 if(s.left(1) != "/") {
731 731
732 lnk.setFile( QFileInfo(filename).dirPath()+"/"+s); 732 lnk.setFile( QFileInfo(filename).dirPath()+"/"+s);
733 } else { 733 } else {
734 lnk.setFile( s); 734 lnk.setFile( s);
735 } 735 }
736 } 736 }
737 d->selectedFiles->addToSelection( lnk ); 737 d->selectedFiles->addToSelection( lnk );
738 } 738 }
739 Config config( "OpiePlayer" ); 739 Config config( "OpiePlayer" );
740 config.setGroup( "PlayList" ); 740 config.setGroup( "PlayList" );
741 741
742 config.writeEntry("CurrentPlaylist",filename); 742 config.writeEntry("CurrentPlaylist",filename);
743 config.write(); 743 config.write();
744 currentPlayList=filename; 744 currentPlayList=filename;
745 745
746 m3uList->close(); 746 m3uList->close();
747 delete m3uList; 747 delete m3uList;
748 748
749 d->selectedFiles->setSelectedItem( s); 749 d->selectedFiles->setSelectedItem( s);
750 setCaption(tr("OpiePlayer: ")+ QFileInfo(filename).baseName()); 750 setCaption(tr("OpiePlayer: ")+ QFileInfo(filename).baseName());
751 751
752} 752}
753 753
754// writes current playlist to current m3u file */ 754// writes current playlist to current m3u file */
755 void PlayListWidget::writeCurrentM3u() { 755 void PlayListWidget::writeCurrentM3u() {
756 qDebug("writing to current m3u"); 756 odebug << "writing to current m3u" << oendl;
757 Config cfg( "OpiePlayer" ); 757 Config cfg( "OpiePlayer" );
758 cfg.setGroup("PlayList"); 758 cfg.setGroup("PlayList");
759 QString currentPlaylist = cfg.readEntry("CurrentPlaylist","default"); 759 QString currentPlaylist = cfg.readEntry("CurrentPlaylist","default");
760 760
761 Om3u *m3uList; 761 Om3u *m3uList;
762 m3uList = new Om3u( currentPlaylist, IO_ReadWrite | IO_Truncate ); 762 m3uList = new Om3u( currentPlaylist, IO_ReadWrite | IO_Truncate );
763 if( d->selectedFiles->first()) { 763 if( d->selectedFiles->first()) {
764 764
765 do { 765 do {
766 // qDebug( "add writeCurrentM3u " +d->selectedFiles->current()->file()); 766 // odebug << "add writeCurrentM3u " +d->selectedFiles->current()->file() << oendl;
767 m3uList->add( d->selectedFiles->current()->file() ); 767 m3uList->add( d->selectedFiles->current()->file() );
768 } 768 }
769 while ( d->selectedFiles->next() ); 769 while ( d->selectedFiles->next() );
770 // qDebug( "<<<<<<<<<<<<>>>>>>>>>>>>>>>>>" ); 770 // odebug << "<<<<<<<<<<<<>>>>>>>>>>>>>>>>>" << oendl;
771 m3uList->write(); 771 m3uList->write();
772 m3uList->close(); 772 m3uList->close();
773 } 773 }
774 delete m3uList; 774 delete m3uList;
775 775
776 } 776 }
777 777
778 /* 778 /*
779 writes current playlist to m3u file */ 779 writes current playlist to m3u file */
780void PlayListWidget::writem3u() { 780void PlayListWidget::writem3u() {
781 //InputDilog *fileDlg; 781 //InputDilog *fileDlg;
782 //fileDlg = new InputDialog( this, tr( "Save m3u Playlist " ), TRUE, 0); 782 //fileDlg = new InputDialog( this, tr( "Save m3u Playlist " ), TRUE, 0);
783 //fileDlg->exec(); 783 //fileDlg->exec();
784 784
785 Config cfg( "OpiePlayer" ); 785 Config cfg( "OpiePlayer" );
786 cfg.setGroup("Dialog"); 786 cfg.setGroup("Dialog");
787 MimeTypes types; 787 MimeTypes types;
788 QStringList audio, video, all; 788 QStringList audio, video, all;
789 audio << "audio/*"; 789 audio << "audio/*";
790 audio << "playlist/plain"; 790 audio << "playlist/plain";
791 audio << "audio/x-mpegurl"; 791 audio << "audio/x-mpegurl";
792 792
793 video << "video/*"; 793 video << "video/*";
794 video << "playlist/plain"; 794 video << "playlist/plain";
795 795
796 all += audio; 796 all += audio;
797 all += video; 797 all += video;
798 types.insert("All Media Files", all ); 798 types.insert("All Media Files", all );
799 types.insert("Audio", audio ); 799 types.insert("Audio", audio );
800 types.insert("Video", video ); 800 types.insert("Video", video );
801 801
802 QString str = OFileDialog::getOpenFileName( 1, 802 QString str = OFileDialog::getOpenFileName( 1,
803 cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"", 803 cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"",
804 types, 0 ); 804 types, 0 );
805 if(str.left(2) == "//") str=str.right(str.length()-1); 805 if(str.left(2) == "//") str=str.right(str.length()-1);
806 cfg.writeEntry("LastDirectory" ,QFileInfo(str).dirPath()); 806 cfg.writeEntry("LastDirectory" ,QFileInfo(str).dirPath());
807 807
808 808
809 QString name, filename, list; 809 QString name, filename, list;
810 Om3u *m3uList; 810 Om3u *m3uList;
811 811
812 if( !str.isEmpty() ) { 812 if( !str.isEmpty() ) {
813 name = str; 813 name = str;
814 // name = fileDlg->text(); 814 // name = fileDlg->text();
815// qDebug( filename ); 815// odebug << filename << oendl;
816 if( name.find("/",0,true) != -1) {// assume they specify a file path 816 if( name.find("/",0,true) != -1) {// assume they specify a file path
817 filename = name; 817 filename = name;
818 name = name.right(name.length()- name.findRev("/",-1,true) - 1 ); 818 name = name.right(name.length()- name.findRev("/",-1,true) - 1 );
819 } 819 }
820 else //otherwise dump it somewhere noticable 820 else //otherwise dump it somewhere noticable
821 filename = QPEApplication::documentDir() + "/" + name; 821 filename = QPEApplication::documentDir() + "/" + name;
822 822
823 if( filename.right( 3 ) != "m3u" ) //needs filename extension 823 if( filename.right( 3 ) != "m3u" ) //needs filename extension
824 filename += ".m3u"; 824 filename += ".m3u";
825 825
826 if( d->selectedFiles->first()) { //ramble through playlist view 826 if( d->selectedFiles->first()) { //ramble through playlist view
827 m3uList = new Om3u( filename, IO_ReadWrite | IO_Truncate); 827 m3uList = new Om3u( filename, IO_ReadWrite | IO_Truncate);
828 828
829 do { 829 do {
830 m3uList->add( d->selectedFiles->current()->file()); 830 m3uList->add( d->selectedFiles->current()->file());
831 } 831 }
832 while ( d->selectedFiles->next() ); 832 while ( d->selectedFiles->next() );
833 // qDebug( list ); 833 // odebug << list << oendl;
834 m3uList->write(); 834 m3uList->write();
835 m3uList->close(); 835 m3uList->close();
836 delete m3uList; 836 delete m3uList;
837 837
838 //delete fileDlg; 838 //delete fileDlg;
839 839
840 DocLnk lnk; 840 DocLnk lnk;
841 lnk.setFile( filename); 841 lnk.setFile( filename);
842 lnk.setIcon("opieplayer2/playlist2"); 842 lnk.setIcon("opieplayer2/playlist2");
843 lnk.setName( name); //sets file name 843 lnk.setName( name); //sets file name
844 844
845 // qDebug(filename); 845 // odebug << filename << oendl;
846 Config config( "OpiePlayer" ); 846 Config config( "OpiePlayer" );
847 config.setGroup( "PlayList" ); 847 config.setGroup( "PlayList" );
848 848
849 config.writeEntry("CurrentPlaylist",filename); 849 config.writeEntry("CurrentPlaylist",filename);
850 currentPlayList=filename; 850 currentPlayList=filename;
851 851
852 if(!lnk.writeLink()) { 852 if(!lnk.writeLink()) {
853 qDebug("Writing doclink did not work"); 853 odebug << "Writing doclink did not work" << oendl;
854 } 854 }
855 855
856 setCaption(tr("OpiePlayer: ") + name); 856 setCaption(tr("OpiePlayer: ") + name);
857 } 857 }
858 } 858 }
859} 859}
860 860
861void PlayListWidget::keyReleaseEvent( QKeyEvent *e ) { 861void PlayListWidget::keyReleaseEvent( QKeyEvent *e ) {
862 switch ( e->key() ) { 862 switch ( e->key() ) {
863 ////////////////////////////// Zaurus keys 863 ////////////////////////////// Zaurus keys
864 case Key_F9: //activity 864 case Key_F9: //activity
865 // if(audioUI->isHidden()) 865 // if(audioUI->isHidden())
866 // audioUI->showMaximized(); 866 // audioUI->showMaximized();
867 break; 867 break;
868 case Key_F10: //contacts 868 case Key_F10: //contacts
869 // if( videoUI->isHidden()) 869 // if( videoUI->isHidden())
870 // videoUI->showMaximized(); 870 // videoUI->showMaximized();
871 break; 871 break;
872 case Key_F11: //menu 872 case Key_F11: //menu
873 break; 873 break;
874 case Key_F12: //home 874 case Key_F12: //home
875 // doBlank(); 875 // doBlank();
876 break; 876 break;
877 case Key_F13: //mail 877 case Key_F13: //mail
878 // doUnblank(); 878 // doUnblank();
879 break; 879 break;
880 case Key_Q: //add to playlist 880 case Key_Q: //add to playlist
881 addSelected(); 881 addSelected();
882 break; 882 break;
883 case Key_R: //remove from playlist 883 case Key_R: //remove from playlist
884 removeSelected(); 884 removeSelected();
885 break; 885 break;
886 // case Key_P: //play 886 // case Key_P: //play
887 // qDebug("Play"); 887 // odebug << "Play" << oendl;
888 // playSelected(); 888 // playSelected();
889 // break; 889 // break;
890 case Key_Space: 890 case Key_Space:
891 // playSelected(); puh 891 // playSelected(); puh
892 break; 892 break;
893 case Key_1: 893 case Key_1:
894 tabWidget->setCurrentPage( 0 ); 894 tabWidget->setCurrentPage( 0 );
895 break; 895 break;
896 case Key_2: 896 case Key_2:
897 tabWidget->setCurrentPage( 1 ); 897 tabWidget->setCurrentPage( 1 );
898 break; 898 break;
899 case Key_3: 899 case Key_3:
900 tabWidget->setCurrentPage( 2 ); 900 tabWidget->setCurrentPage( 2 );
901 break; 901 break;
902 case Key_4: 902 case Key_4:
903 tabWidget->setCurrentPage( 3 ); 903 tabWidget->setCurrentPage( 3 );
904 break; 904 break;
905 case Key_Down: 905 case Key_Down:
906 if ( !d->selectedFiles->next() ) 906 if ( !d->selectedFiles->next() )
907 d->selectedFiles->first(); 907 d->selectedFiles->first();
908 break; 908 break;
909 case Key_Up: 909 case Key_Up:
910 if ( !d->selectedFiles->prev() ) 910 if ( !d->selectedFiles->prev() )
911 // d->selectedFiles->last(); 911 // d->selectedFiles->last();
912 break; 912 break;
913 } 913 }
914} 914}
915 915
916void PlayListWidget::pmViewActivated(int index) { 916void PlayListWidget::pmViewActivated(int index) {
917// qDebug("%d", index); 917// odebug << "" << index << "" << oendl;
918 switch(index) { 918 switch(index) {
919 case -16: 919 case -16:
920 { 920 {
921 mediaPlayerState->toggleFullscreen(); 921 mediaPlayerState->toggleFullscreen();
922 bool b=mediaPlayerState->isFullscreen(); 922 bool b=mediaPlayerState->isFullscreen();
923 pmView->setItemChecked( index, b); 923 pmView->setItemChecked( index, b);
924 Config cfg( "OpiePlayer" ); 924 Config cfg( "OpiePlayer" );
925 cfg.writeEntry( "FullScreen", b ); 925 cfg.writeEntry( "FullScreen", b );
926 } 926 }
927 break; 927 break;
928 }; 928 };
929} 929}
930 930
931void PlayListWidget::populateSkinsMenu() { 931void PlayListWidget::populateSkinsMenu() {
932 int item = 0; 932 int item = 0;
933 defaultSkinIndex = 0; 933 defaultSkinIndex = 0;
934 QString skinName; 934 QString skinName;
935 Config cfg( "OpiePlayer" ); 935 Config cfg( "OpiePlayer" );
936 cfg.setGroup("Options" ); 936 cfg.setGroup("Options" );
937 QString skin = cfg.readEntry( "Skin", "default" ); 937 QString skin = cfg.readEntry( "Skin", "default" );
938 938
939 QDir skinsDir( QPEApplication::qpeDir() + "/pics/opieplayer2/skins" ); 939 QDir skinsDir( QPEApplication::qpeDir() + "/pics/opieplayer2/skins" );
940 skinsDir.setFilter( QDir::Dirs ); 940 skinsDir.setFilter( QDir::Dirs );
941 skinsDir.setSorting(QDir::Name ); 941 skinsDir.setSorting(QDir::Name );
942 const QFileInfoList *skinslist = skinsDir.entryInfoList(); 942 const QFileInfoList *skinslist = skinsDir.entryInfoList();
943 QFileInfoListIterator it( *skinslist ); 943 QFileInfoListIterator it( *skinslist );
944 QFileInfo *fi; 944 QFileInfo *fi;
945 while ( ( fi = it.current() ) ) { 945 while ( ( fi = it.current() ) ) {
946 skinName = fi->fileName(); 946 skinName = fi->fileName();
947// qDebug( fi->fileName() ); 947// odebug << fi->fileName() << oendl;
948 if( skinName != "." && skinName != ".." && skinName !="CVS" ) { 948 if( skinName != "." && skinName != ".." && skinName !="CVS" ) {
949 item = skinsMenu->insertItem( fi->fileName() ) ; 949 item = skinsMenu->insertItem( fi->fileName() ) ;
950 } 950 }
951 if( skinName == "default" ) { 951 if( skinName == "default" ) {
952 defaultSkinIndex = item; 952 defaultSkinIndex = item;
953 } 953 }
954 if( skinName == skin ) { 954 if( skinName == skin ) {
955 skinsMenu->setItemChecked( item, TRUE ); 955 skinsMenu->setItemChecked( item, TRUE );
956 } 956 }
957 ++it; 957 ++it;
958 } 958 }
959} 959}
960 960
961void PlayListWidget::skinsMenuActivated( int item ) { 961void PlayListWidget::skinsMenuActivated( int item ) {
962 for(unsigned int i = defaultSkinIndex; i > defaultSkinIndex - skinsMenu->count(); i-- ) { 962 for(unsigned int i = defaultSkinIndex; i > defaultSkinIndex - skinsMenu->count(); i-- ) {
963 skinsMenu->setItemChecked( i, FALSE ); 963 skinsMenu->setItemChecked( i, FALSE );
964 } 964 }
965 skinsMenu->setItemChecked( item, TRUE ); 965 skinsMenu->setItemChecked( item, TRUE );
966 966
967 { 967 {
968 Config cfg( "OpiePlayer" ); 968 Config cfg( "OpiePlayer" );
969 cfg.setGroup("Options"); 969 cfg.setGroup("Options");
970 cfg.writeEntry("Skin", skinsMenu->text( item ) ); 970 cfg.writeEntry("Skin", skinsMenu->text( item ) );
971 } 971 }
972 972
973 emit skinSelected(); 973 emit skinSelected();
974} 974}
975 975
976PlayListWidget::TabType PlayListWidget::currentTab() const 976PlayListWidget::TabType PlayListWidget::currentTab() const
977{ 977{
978 static const TabType indexToTabType[ TabTypeCount ] = 978 static const TabType indexToTabType[ TabTypeCount ] =
979 { CurrentPlayList, AudioFiles, VideoFiles, PlayLists }; 979 { CurrentPlayList, AudioFiles, VideoFiles, PlayLists };
980 980
981 int index = tabWidget->currentPageIndex(); 981 int index = tabWidget->currentPageIndex();
982 assert( index < TabTypeCount && index >= 0 ); 982 assert( index < TabTypeCount && index >= 0 );
983 983
984 return indexToTabType[ index ]; 984 return indexToTabType[ index ];
985} 985}
986 986
987PlayListWidget::Entry PlayListWidget::currentEntry() const 987PlayListWidget::Entry PlayListWidget::currentEntry() const
988{ 988{
989 if ( currentTab() == CurrentPlayList ) { 989 if ( currentTab() == CurrentPlayList ) {
990 const DocLnk *lnk = current(); 990 const DocLnk *lnk = current();
991 return Entry( lnk->name(), lnk->file() ); 991 return Entry( lnk->name(), lnk->file() );
992 } 992 }
993 993
994 return Entry( currentFileListPathName() ); 994 return Entry( currentFileListPathName() );
995} 995}
996 996
997QString PlayListWidget::currentFileListPathName() const { 997QString PlayListWidget::currentFileListPathName() const {
998 return currentFileListView->currentItem()->text( 3 ); 998 return currentFileListView->currentItem()->text( 3 );
999} 999}
1000 1000
1001 1001
1002void PlayListWidget::qcopReceive(const QCString &msg, const QByteArray &data) { 1002void PlayListWidget::qcopReceive(const QCString &msg, const QByteArray &data) {
1003 qDebug("qcop message "+msg ); 1003 odebug << "qcop message "+msg << oendl;
1004 QDataStream stream ( data, IO_ReadOnly ); 1004 QDataStream stream ( data, IO_ReadOnly );
1005 if ( msg == "play()" ) { //plays current selection 1005 if ( msg == "play()" ) { //plays current selection
1006 btnPlay( true); 1006 btnPlay( true);
1007 } else if ( msg == "stop()" ) { 1007 } else if ( msg == "stop()" ) {
1008 mediaPlayerState->setPlaying( false); 1008 mediaPlayerState->setPlaying( false);
1009 } else if ( msg == "togglePause()" ) { 1009 } else if ( msg == "togglePause()" ) {
1010 mediaPlayerState->togglePaused(); 1010 mediaPlayerState->togglePaused();
1011 } else if ( msg == "next()" ) { //select next in list 1011 } else if ( msg == "next()" ) { //select next in list
1012 mediaPlayerState->setNext(); 1012 mediaPlayerState->setNext();
1013 } else if ( msg == "prev()" ) { //select previous in list 1013 } else if ( msg == "prev()" ) { //select previous in list
1014 mediaPlayerState->setPrev(); 1014 mediaPlayerState->setPrev();
1015 } else if ( msg == "toggleLooping()" ) { //loop or not loop 1015 } else if ( msg == "toggleLooping()" ) { //loop or not loop
1016 mediaPlayerState->toggleLooping(); 1016 mediaPlayerState->toggleLooping();
1017 } else if ( msg == "toggleShuffled()" ) { //shuffled or not shuffled 1017 } else if ( msg == "toggleShuffled()" ) { //shuffled or not shuffled
1018 mediaPlayerState->toggleShuffled(); 1018 mediaPlayerState->toggleShuffled();
1019 } else if ( msg == "volUp()" ) { //volume more 1019 } else if ( msg == "volUp()" ) { //volume more
1020// emit moreClicked(); 1020// emit moreClicked();
1021// emit moreReleased(); 1021// emit moreReleased();
1022 } else if ( msg == "volDown()" ) { //volume less 1022 } else if ( msg == "volDown()" ) { //volume less
1023// emit lessClicked(); 1023// emit lessClicked();
1024// emit lessReleased(); 1024// emit lessReleased();
1025 } else if ( msg == "play(QString)" ) { //play this now 1025 } else if ( msg == "play(QString)" ) { //play this now
1026 QString file; 1026 QString file;
1027 stream >> file; 1027 stream >> file;
1028 setDocument( (const QString &) file); 1028 setDocument( (const QString &) file);
1029 } else if ( msg == "add(QString)" ) { //add to playlist 1029 } else if ( msg == "add(QString)" ) { //add to playlist
1030 QString file; 1030 QString file;
1031 stream >> file; 1031 stream >> file;
1032 QFileInfo fileInfo(file); 1032 QFileInfo fileInfo(file);
1033 DocLnk lnk; 1033 DocLnk lnk;
1034 lnk.setName( fileInfo.baseName() ); //sets name 1034 lnk.setName( fileInfo.baseName() ); //sets name
1035 lnk.setFile( file ); //sets file name 1035 lnk.setFile( file ); //sets file name
1036 addToSelection( lnk ); 1036 addToSelection( lnk );
1037 } else if ( msg == "rem(QString)" ) { //remove from playlist 1037 } else if ( msg == "rem(QString)" ) { //remove from playlist
1038 QString file; 1038 QString file;
1039 stream >> file; 1039 stream >> file;
1040 1040
1041 } 1041 }
1042 1042
1043} 1043}
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 )
90 gammaSlider->setTickmarks( QSlider::Left ); 90 gammaSlider->setTickmarks( QSlider::Left );
91 gammaSlider->setTickInterval( 20 ); 91 gammaSlider->setTickInterval( 20 );
92 gammaSlider->setFocusPolicy( QWidget::StrongFocus ); 92 gammaSlider->setFocusPolicy( QWidget::StrongFocus );
93 gammaSlider->setValue( 0 ); 93 gammaSlider->setValue( 0 );
94 gammaSlider->setMinimumHeight( 50 ); 94 gammaSlider->setMinimumHeight( 50 );
95 95
96 gammaLCD = new QLCDNumber( 3, gammaMenu ); 96 gammaLCD = new QLCDNumber( 3, gammaMenu );
97 gammaLCD-> setFrameShape ( QFrame::NoFrame ); 97 gammaLCD-> setFrameShape ( QFrame::NoFrame );
98 gammaLCD-> setSegmentStyle ( QLCDNumber::Flat ); 98 gammaLCD-> setSegmentStyle ( QLCDNumber::Flat );
99 99
100 gammaMenu->insertItem( gammaSlider ); 100 gammaMenu->insertItem( gammaSlider );
101 gammaMenu->insertItem( gammaLCD ); 101 gammaMenu->insertItem( gammaLCD );
102 102
103 connect( gammaSlider, SIGNAL( valueChanged(int) ), gammaLCD, SLOT( display(int) ) ); 103 connect( gammaSlider, SIGNAL( valueChanged(int) ), gammaLCD, SLOT( display(int) ) );
104 104
105 vbox5 = new QVBox( this ); 105 vbox5 = new QVBox( this );
106 QVBox *vbox4 = new QVBox( vbox5 ); 106 QVBox *vbox4 = new QVBox( vbox5 );
107 QHBox *hbox6 = new QHBox( vbox4 ); 107 QHBox *hbox6 = new QHBox( vbox4 );
108 108
109 tabWidget = new QTabWidget( hbox6, "tabWidget" ); 109 tabWidget = new QTabWidget( hbox6, "tabWidget" );
110 110
111 playListTab = new QWidget( tabWidget, "PlayListTab" ); 111 playListTab = new QWidget( tabWidget, "PlayListTab" );
112 tabWidget->insertTab( playListTab, "Playlist"); 112 tabWidget->insertTab( playListTab, "Playlist");
113 113
114 QGridLayout *Playout = new QGridLayout( playListTab ); 114 QGridLayout *Playout = new QGridLayout( playListTab );
115 Playout->setSpacing( 2); 115 Playout->setSpacing( 2);
116 Playout->setMargin( 2); 116 Playout->setMargin( 2);
117 117
118 // Add the playlist area 118 // Add the playlist area
119 QVBox *vbox3 = new QVBox( playListTab ); 119 QVBox *vbox3 = new QVBox( playListTab );
120 d->playListFrame = vbox3; 120 d->playListFrame = vbox3;
121 121
122 QHBox *hbox2 = new QHBox( vbox3 ); 122 QHBox *hbox2 = new QHBox( vbox3 );
123 d->selectedFiles = new PlayListSelection( hbox2 ); 123 d->selectedFiles = new PlayListSelection( hbox2 );
124 124
125 vbox1 = new QVBox( hbox2 ); 125 vbox1 = new QVBox( hbox2 );
126 QPEApplication::setStylusOperation( d->selectedFiles->viewport(), QPEApplication::RightOnHold ); 126 QPEApplication::setStylusOperation( d->selectedFiles->viewport(), QPEApplication::RightOnHold );
127 QVBox *stretch1 = new QVBox( vbox1 ); // add stretch 127 QVBox *stretch1 = new QVBox( vbox1 ); // add stretch
128 128
129 Playout->addMultiCellWidget( vbox3, 0, 0, 0, 1 ); 129 Playout->addMultiCellWidget( vbox3, 0, 0, 0, 1 );
130 130
131 QWidget *aTab; 131 QWidget *aTab;
132 aTab = new QWidget( tabWidget, "aTab" ); 132 aTab = new QWidget( tabWidget, "aTab" );
133 133
134 QGridLayout *Alayout = new QGridLayout( aTab ); 134 QGridLayout *Alayout = new QGridLayout( aTab );
135 Alayout->setSpacing( 2 ); 135 Alayout->setSpacing( 2 );
136 Alayout->setMargin( 2 ); 136 Alayout->setMargin( 2 );
137 // no m3u's here please 137 // no m3u's here please
138 audioView = new PlayListFileView( "audio/mpeg;audio/x-wav;application/ogg", "opieplayer2/musicfile", aTab, "Audioview" ); 138 audioView = new PlayListFileView( "audio/mpeg;audio/x-wav;application/ogg", "opieplayer2/musicfile", aTab, "Audioview" );
139 Alayout->addMultiCellWidget( audioView, 0, 0, 0, 1 ); 139 Alayout->addMultiCellWidget( audioView, 0, 0, 0, 1 );
140 tabWidget->insertTab( aTab, tr( "Audio" ) ); 140 tabWidget->insertTab( aTab, tr( "Audio" ) );
141 141
142 QPEApplication::setStylusOperation( audioView->viewport(), QPEApplication::RightOnHold ); 142 QPEApplication::setStylusOperation( audioView->viewport(), QPEApplication::RightOnHold );
143 143
144 QWidget *vTab; 144 QWidget *vTab;
145 vTab = new QWidget( tabWidget, "vTab" ); 145 vTab = new QWidget( tabWidget, "vTab" );
146 146
147 QGridLayout *Vlayout = new QGridLayout( vTab ); 147 QGridLayout *Vlayout = new QGridLayout( vTab );
148 Vlayout->setSpacing( 2 ); 148 Vlayout->setSpacing( 2 );
149 Vlayout->setMargin( 2 ); 149 Vlayout->setMargin( 2 );
150 videoView = new PlayListFileView( "video/*", "opieplayer2/videofile", vTab, "Videoview" ); 150 videoView = new PlayListFileView( "video/*", "opieplayer2/videofile", vTab, "Videoview" );
151 Vlayout->addMultiCellWidget( videoView, 0, 0, 0, 1 ); 151 Vlayout->addMultiCellWidget( videoView, 0, 0, 0, 1 );
152 152
153 QPEApplication::setStylusOperation( videoView->viewport(), QPEApplication::RightOnHold ); 153 QPEApplication::setStylusOperation( videoView->viewport(), QPEApplication::RightOnHold );
154 154
155 tabWidget->insertTab( vTab, tr( "Video" ) ); 155 tabWidget->insertTab( vTab, tr( "Video" ) );
156 156
157 //playlists list 157 //playlists list
158 QWidget *LTab; 158 QWidget *LTab;
159 LTab = new QWidget( tabWidget, "LTab" ); 159 LTab = new QWidget( tabWidget, "LTab" );
160 QGridLayout *Llayout = new QGridLayout( LTab ); 160 QGridLayout *Llayout = new QGridLayout( LTab );
161 Llayout->setSpacing( 2 ); 161 Llayout->setSpacing( 2 );
162 Llayout->setMargin( 2 ); 162 Llayout->setMargin( 2 );
163 163
164 playLists = new FileSelector( "playlist/plain;audio/x-mpegurl", LTab, "fileselector" , FALSE, FALSE ); 164 playLists = new FileSelector( "playlist/plain;audio/x-mpegurl", LTab, "fileselector" , FALSE, FALSE );
165 Llayout->addMultiCellWidget( playLists, 0, 0, 0, 1 ); 165 Llayout->addMultiCellWidget( playLists, 0, 0, 0, 1 );
166 166
167 tabWidget->insertTab( LTab, tr( "Lists" ) ); 167 tabWidget->insertTab( LTab, tr( "Lists" ) );
168 168
169 setCentralWidget( vbox5 ); 169 setCentralWidget( vbox5 );
170} 170}
171 171
172 172
173 173
174PlayListWidgetGui::~PlayListWidgetGui() { 174PlayListWidgetGui::~PlayListWidgetGui() {
175} 175}
176 176
177void PlayListWidgetGui::setView( char view ) { 177void PlayListWidgetGui::setView( char view ) {
178 if ( view == 'l' ) 178 if ( view == 'l' )
179 showMaximized(); 179 showMaximized();
180 else 180 else
181 hide(); 181 hide();
182} 182}
183 183
184 184
185void PlayListWidgetGui::setActiveWindow() { 185void PlayListWidgetGui::setActiveWindow() {
186 // qDebug("SETTING active window"); 186 // odebug << "SETTING active window" << oendl;
187 // When we get raised we need to ensure that it switches views 187 // When we get raised we need to ensure that it switches views
188 MediaPlayerState::DisplayType origDisplayType = mediaPlayerState->displayType(); 188 MediaPlayerState::DisplayType origDisplayType = mediaPlayerState->displayType();
189 mediaPlayerState->setDisplayType( MediaPlayerState::MediaSelection ); // invalidate 189 mediaPlayerState->setDisplayType( MediaPlayerState::MediaSelection ); // invalidate
190 mediaPlayerState->setDisplayType( origDisplayType ); // now switch back 190 mediaPlayerState->setDisplayType( origDisplayType ); // now switch back
191} 191}
192 192
193 193
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 )
85{ 85{
86 m_isCachable = true; 86 m_isCachable = true;
87 m_skinPath = "opieplayer2/skins/" + name; 87 m_skinPath = "opieplayer2/skins/" + name;
88 d = SkinCache::self().lookupAndTake( m_skinPath, m_fileNameInfix ); 88 d = SkinCache::self().lookupAndTake( m_skinPath, m_fileNameInfix );
89} 89}
90 90
91QPixmap Skin::backgroundPixmap() const 91QPixmap Skin::backgroundPixmap() const
92{ 92{
93 if ( d->backgroundPixmap.isNull() ) 93 if ( d->backgroundPixmap.isNull() )
94 d->backgroundPixmap = loadImage( QString( "%1/background" ).arg( m_skinPath ) ); 94 d->backgroundPixmap = loadImage( QString( "%1/background" ).arg( m_skinPath ) );
95 return d->backgroundPixmap; 95 return d->backgroundPixmap;
96} 96}
97 97
98QImage Skin::buttonUpImage() const 98QImage Skin::buttonUpImage() const
99{ 99{
100 if ( d->buttonUpImage.isNull() ) 100 if ( d->buttonUpImage.isNull() )
101 d->buttonUpImage = loadImage( QString( "%1/skin%2_up" ).arg( m_skinPath ).arg( m_fileNameInfix ) ); 101 d->buttonUpImage = loadImage( QString( "%1/skin%2_up" ).arg( m_skinPath ).arg( m_fileNameInfix ) );
102 return d->buttonUpImage; 102 return d->buttonUpImage;
103} 103}
104 104
105QImage Skin::buttonDownImage() const 105QImage Skin::buttonDownImage() const
106{ 106{
107 if ( d->buttonDownImage.isNull() ) 107 if ( d->buttonDownImage.isNull() )
108 d->buttonDownImage = loadImage( QString( "%1/skin%2_down" ).arg( m_skinPath ).arg( m_fileNameInfix ) ); 108 d->buttonDownImage = loadImage( QString( "%1/skin%2_down" ).arg( m_skinPath ).arg( m_fileNameInfix ) );
109 return d->buttonDownImage; 109 return d->buttonDownImage;
110} 110}
111 111
112QImage Skin::buttonMask( const MediaWidget::SkinButtonInfo *skinButtonInfo, uint buttonCount ) const 112QImage Skin::buttonMask( const MediaWidget::SkinButtonInfo *skinButtonInfo, uint buttonCount ) const
113{ 113{
114 if ( !d->buttonMask.isNull() ) 114 if ( !d->buttonMask.isNull() )
115 return d->buttonMask; 115 return d->buttonMask;
116 116
117 QSize buttonAreaSize = buttonUpImage().size(); 117 QSize buttonAreaSize = buttonUpImage().size();
118 118
119 d->buttonMask = QImage( buttonAreaSize, 8, 255 ); 119 d->buttonMask = QImage( buttonAreaSize, 8, 255 );
120 d->buttonMask.fill( 0 ); 120 d->buttonMask.fill( 0 );
121 121
122 for ( uint i = 0; i < buttonCount; ++i ) 122 for ( uint i = 0; i < buttonCount; ++i )
123 addButtonToMask( skinButtonInfo[ i ].command + 1, buttonMaskImage( skinButtonInfo[ i ].fileName ) ); 123 addButtonToMask( skinButtonInfo[ i ].command + 1, buttonMaskImage( skinButtonInfo[ i ].fileName ) );
124 124
125 return d->buttonMask; 125 return d->buttonMask;
126} 126}
127 127
128void Skin::addButtonToMask( int tag, const QImage &maskImage ) const 128void Skin::addButtonToMask( int tag, const QImage &maskImage ) const
129{ 129{
130 if ( maskImage.isNull() ) 130 if ( maskImage.isNull() )
131 return; 131 return;
132 132
133 uchar **dest = d->buttonMask.jumpTable(); 133 uchar **dest = d->buttonMask.jumpTable();
134 for ( int y = 0; y < d->buttonMask.height(); y++ ) { 134 for ( int y = 0; y < d->buttonMask.height(); y++ ) {
135 uchar *line = dest[y]; 135 uchar *line = dest[y];
136 for ( int x = 0; x < d->buttonMask.width(); x++ ) 136 for ( int x = 0; x < d->buttonMask.width(); x++ )
137 if ( !qRed( maskImage.pixel( x, y ) ) ) 137 if ( !qRed( maskImage.pixel( x, y ) ) )
138 line[x] = tag; 138 line[x] = tag;
139 } 139 }
140} 140}
141 141
142QImage Skin::buttonMaskImage( const QString &fileName ) const 142QImage Skin::buttonMaskImage( const QString &fileName ) const
143{ 143{
144 SkinData::ButtonMaskImageMap::Iterator it = d->buttonMasks.find( fileName ); 144 SkinData::ButtonMaskImageMap::Iterator it = d->buttonMasks.find( fileName );
145 if ( it == d->buttonMasks.end() ) { 145 if ( it == d->buttonMasks.end() ) {
146 QString prefix = m_skinPath + QString::fromLatin1( "/skin%1_mask_" ).arg( m_fileNameInfix ); 146 QString prefix = m_skinPath + QString::fromLatin1( "/skin%1_mask_" ).arg( m_fileNameInfix );
147 QString path = prefix + fileName; 147 QString path = prefix + fileName;
148 it = d->buttonMasks.insert( fileName, loadImage( path ) ); 148 it = d->buttonMasks.insert( fileName, loadImage( path ) );
149 } 149 }
150 return *it; 150 return *it;
151} 151}
152 152
153QString Skin::defaultSkinName() 153QString Skin::defaultSkinName()
154{ 154{
155 Config cfg( "OpiePlayer" ); 155 Config cfg( "OpiePlayer" );
156 cfg.setGroup( "Options" ); 156 cfg.setGroup( "Options" );
157 return cfg.readEntry( "Skin", "default" ); 157 return cfg.readEntry( "Skin", "default" );
158} 158}
159 159
160QImage Skin::loadImage( const QString &fileName ) 160QImage Skin::loadImage( const QString &fileName )
161{ 161{
162 return QImage( Resource::findPixmap( fileName ) ); 162 return QImage( Resource::findPixmap( fileName ) );
163} 163}
164 164
165SkinCache::SkinCache() 165SkinCache::SkinCache()
166{ 166{
167 // let's say we cache two skins (audio+video) at maximum 167 // let's say we cache two skins (audio+video) at maximum
168 m_cache.setMaxCost( 2 ); 168 m_cache.setMaxCost( 2 );
169 // ... and one background pixmap 169 // ... and one background pixmap
170 m_backgroundPixmapCache.setMaxCost( 1 ); 170 m_backgroundPixmapCache.setMaxCost( 1 );
171} 171}
172 172
173SkinData *SkinCache::lookupAndTake( const QString &skinPath, const QString &fileNameInfix ) 173SkinData *SkinCache::lookupAndTake( const QString &skinPath, const QString &fileNameInfix )
174{ 174{
175 QString key = skinPath + fileNameInfix; 175 QString key = skinPath + fileNameInfix;
176 176
177 SkinData *data = m_cache.take( key ); 177 SkinData *data = m_cache.take( key );
178 if ( !data ) 178 if ( !data )
179 data = new SkinData; 179 data = new SkinData;
180 else 180 else
181 qDebug( "SkinCache: hit" ); 181 odebug << "SkinCache: hit" << oendl;
182 182
183 QPixmap *bgPixmap = m_backgroundPixmapCache.find( skinPath ); 183 QPixmap *bgPixmap = m_backgroundPixmapCache.find( skinPath );
184 if ( bgPixmap ) { 184 if ( bgPixmap ) {
185 qDebug( "SkinCache: hit on bgpixmap" ); 185 odebug << "SkinCache: hit on bgpixmap" << oendl;
186 data->backgroundPixmap = *bgPixmap; 186 data->backgroundPixmap = *bgPixmap;
187 } 187 }
188 else 188 else
189 data->backgroundPixmap = QPixmap(); 189 data->backgroundPixmap = QPixmap();
190 190
191 return data; 191 return data;
192} 192}
193 193
194void SkinCache::store( const QString &skinPath, const QString &fileNameInfix, SkinData *data ) 194void SkinCache::store( const QString &skinPath, const QString &fileNameInfix, SkinData *data )
195{ 195{
196 QPixmap *backgroundPixmap = new QPixmap( data->backgroundPixmap ); 196 QPixmap *backgroundPixmap = new QPixmap( data->backgroundPixmap );
197 197
198 data->backgroundPixmap = QPixmap(); 198 data->backgroundPixmap = QPixmap();
199 199
200 QString key = skinPath + fileNameInfix; 200 QString key = skinPath + fileNameInfix;
201 201
202 if ( m_cache.find( key, false /*ref*/ ) != 0 || 202 if ( m_cache.find( key, false /*ref*/ ) != 0 ||
203 !m_cache.insert( key, data ) ) 203 !m_cache.insert( key, data ) )
204 delete data; 204 delete data;
205 205
206 if ( m_backgroundPixmapCache.find( skinPath, false /*ref*/ ) != 0 || 206 if ( m_backgroundPixmapCache.find( skinPath, false /*ref*/ ) != 0 ||
207 !m_backgroundPixmapCache.insert( skinPath, backgroundPixmap ) ) 207 !m_backgroundPixmapCache.insert( skinPath, backgroundPixmap ) )
208 delete backgroundPixmap; 208 delete backgroundPixmap;
209} 209}
210 210
211SkinLoader::IncrementalLoader::IncrementalLoader( const Info &info ) 211SkinLoader::IncrementalLoader::IncrementalLoader( const Info &info )
212 : m_skin( info.skinName, info.fileNameInfix ), m_info( info ) 212 : m_skin( info.skinName, info.fileNameInfix ), m_info( info )
213{ 213{
214 m_currentState = LoadBackgroundPixmap; 214 m_currentState = LoadBackgroundPixmap;
215} 215}
216 216
217SkinLoader::IncrementalLoader::LoaderResult SkinLoader::IncrementalLoader::loadStep() 217SkinLoader::IncrementalLoader::LoaderResult SkinLoader::IncrementalLoader::loadStep()
218{ 218{
219 switch ( m_currentState ) { 219 switch ( m_currentState ) {
220 case LoadBackgroundPixmap: 220 case LoadBackgroundPixmap:
221 qDebug( "load bgpixmap" ); 221 odebug << "load bgpixmap" << oendl;
222 m_skin.backgroundPixmap(); 222 m_skin.backgroundPixmap();
223 m_currentState = LoadButtonUpImage; 223 m_currentState = LoadButtonUpImage;
224 break; 224 break;
225 case LoadButtonUpImage: 225 case LoadButtonUpImage:
226 qDebug( "load upimage" ); 226 odebug << "load upimage" << oendl;
227 m_skin.buttonUpImage(); 227 m_skin.buttonUpImage();
228 m_currentState = LoadButtonDownImage; 228 m_currentState = LoadButtonDownImage;
229 break; 229 break;
230 case LoadButtonDownImage: 230 case LoadButtonDownImage:
231 qDebug( "load downimage" ); 231 odebug << "load downimage" << oendl;
232 m_skin.buttonDownImage(); 232 m_skin.buttonDownImage();
233 m_currentState = LoadButtonMasks; 233 m_currentState = LoadButtonMasks;
234 m_currentButton = 0; 234 m_currentButton = 0;
235 break; 235 break;
236 case LoadButtonMasks: 236 case LoadButtonMasks:
237 qDebug( "load button masks %i", m_currentButton ); 237 odebug << "load button masks " << m_currentButton << "" << oendl;
238 m_skin.buttonMaskImage( m_info.buttonInfo[ m_currentButton ].fileName ); 238 m_skin.buttonMaskImage( m_info.buttonInfo[ m_currentButton ].fileName );
239 239
240 m_currentButton++; 240 m_currentButton++;
241 if ( m_currentButton >= m_info.buttonCount ) 241 if ( m_currentButton >= m_info.buttonCount )
242 m_currentState = LoadButtonMask; 242 m_currentState = LoadButtonMask;
243 243
244 break; 244 break;
245 case LoadButtonMask: 245 case LoadButtonMask:
246 qDebug( "load whole mask" ); 246 odebug << "load whole mask" << oendl;
247 m_skin.buttonMask( m_info.buttonInfo, m_info.buttonCount ); 247 m_skin.buttonMask( m_info.buttonInfo, m_info.buttonCount );
248 return LoadingCompleted; 248 return LoadingCompleted;
249 } 249 }
250 250
251 return MoreToCome; 251 return MoreToCome;
252} 252}
253 253
254SkinLoader::SkinLoader() 254SkinLoader::SkinLoader()
255 : m_currentLoader( 0 ), m_timerId( -1 ) 255 : m_currentLoader( 0 ), m_timerId( -1 )
256{ 256{
257} 257}
258 258
259SkinLoader::~SkinLoader() 259SkinLoader::~SkinLoader()
260{ 260{
261 qDebug( "SkinLoader::~SkinLoader()" ); 261 odebug << "SkinLoader::~SkinLoader()" << oendl;
262 killTimers(); 262 killTimers();
263 delete m_currentLoader; 263 delete m_currentLoader;
264} 264}
265 265
266void SkinLoader::schedule( const MediaWidget::GUIInfo &guiInfo ) 266void SkinLoader::schedule( const MediaWidget::GUIInfo &guiInfo )
267{ 267{
268 schedule( Skin::defaultSkinName(), guiInfo ); 268 schedule( Skin::defaultSkinName(), guiInfo );
269} 269}
270 270
271void SkinLoader::schedule( const QString &skinName, const MediaWidget::GUIInfo &guiInfo ) 271void SkinLoader::schedule( const QString &skinName, const MediaWidget::GUIInfo &guiInfo )
272{ 272{
273 pendingSkins << Info( skinName, guiInfo ); 273 pendingSkins << Info( skinName, guiInfo );
274} 274}
275 275
276void SkinLoader::start() 276void SkinLoader::start()
277{ 277{
278 assert( m_timerId == -1 ); 278 assert( m_timerId == -1 );
279 m_timerId = startTimer( 100 /* ms */ ); 279 m_timerId = startTimer( 100 /* ms */ );
280 qDebug( "SkinLoader::start() %d jobs", pendingSkins.count() ); 280 odebug << "SkinLoader::start() " << pendingSkins.count() << " jobs" << oendl;
281} 281}
282 282
283void SkinLoader::timerEvent( QTimerEvent *ev ) 283void SkinLoader::timerEvent( QTimerEvent *ev )
284{ 284{
285 if ( ev->timerId() != m_timerId ) { 285 if ( ev->timerId() != m_timerId ) {
286 QObject::timerEvent( ev ); 286 QObject::timerEvent( ev );
287 return; 287 return;
288 } 288 }
289 289
290 if ( !m_currentLoader ) { 290 if ( !m_currentLoader ) {
291 291
292 if ( pendingSkins.isEmpty() ) { 292 if ( pendingSkins.isEmpty() ) {
293 qDebug( "all jobs done" ); 293 odebug << "all jobs done" << oendl;
294 killTimer( m_timerId ); 294 killTimer( m_timerId );
295 m_timerId = -1; 295 m_timerId = -1;
296 // ### qt3: use deleteLater(); 296 // ### qt3: use deleteLater();
297 QTimer::singleShot( 0, this, SLOT( deleteMe() ) ); 297 QTimer::singleShot( 0, this, SLOT( deleteMe() ) );
298 return; 298 return;
299 } 299 }
300 300
301 Info nfo = *pendingSkins.begin(); 301 Info nfo = *pendingSkins.begin();
302 pendingSkins.remove( pendingSkins.begin() ); 302 pendingSkins.remove( pendingSkins.begin() );
303 303
304 m_currentLoader = new IncrementalLoader( nfo ); 304 m_currentLoader = new IncrementalLoader( nfo );
305 qDebug( "new loader %i jobs left", pendingSkins.count() ); 305 odebug << "new loader " << pendingSkins.count() << " jobs left" << oendl;
306 } 306 }
307 307
308 if ( m_currentLoader->loadStep() == IncrementalLoader::LoadingCompleted ) { 308 if ( m_currentLoader->loadStep() == IncrementalLoader::LoadingCompleted ) {
309 delete m_currentLoader; 309 delete m_currentLoader;
310 m_currentLoader = 0; 310 m_currentLoader = 0;
311 } 311 }
312 312
313 qDebug( "finished step" ); 313 odebug << "finished step" << oendl;
314} 314}
315 315
316void SkinLoader::deleteMe() 316void SkinLoader::deleteMe()
317{ 317{
318 delete this; 318 delete this;
319} 319}
320 320
321/* vim: et sw=4 ts=4 321/* vim: et sw=4 ts=4
322 */ 322 */
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
94WaitCondition::WaitCondition() 94WaitCondition::WaitCondition()
95 : d( new Data ) 95 : d( new Data )
96{ 96{
97} 97}
98 98
99WaitCondition::~WaitCondition() 99WaitCondition::~WaitCondition()
100{ 100{
101 delete d; 101 delete d;
102} 102}
103 103
104bool WaitCondition::wait() 104bool WaitCondition::wait()
105{ 105{
106 Mutex m; 106 Mutex m;
107 m.lock(); 107 m.lock();
108 return wait( m ); 108 return wait( m );
109} 109}
110 110
111bool WaitCondition::wait( Mutex &mutex ) 111bool WaitCondition::wait( Mutex &mutex )
112{ 112{
113 return pthread_cond_wait( &d->waitCondition, &mutex.d->mutex ); 113 return pthread_cond_wait( &d->waitCondition, &mutex.d->mutex );
114} 114}
115 115
116void WaitCondition::wakeOne() 116void WaitCondition::wakeOne()
117{ 117{
118 pthread_cond_signal( &d->waitCondition ); 118 pthread_cond_signal( &d->waitCondition );
119} 119}
120 120
121void WaitCondition::wakeAll() 121void WaitCondition::wakeAll()
122{ 122{
123 pthread_cond_broadcast( &d->waitCondition ); 123 pthread_cond_broadcast( &d->waitCondition );
124} 124}
125 125
126struct Thread::Data 126struct Thread::Data
127{ 127{
128 Data() : isRunning( false ) 128 Data() : isRunning( false )
129 {} 129 {}
130 130
131 pthread_t self; 131 pthread_t self;
132 Mutex guard; 132 Mutex guard;
133 bool isRunning; 133 bool isRunning;
134 134
135 WaitCondition finishCondition; 135 WaitCondition finishCondition;
136 136
137 Thread *thr; 137 Thread *thr;
138 138
139 void run() { thr->run(); } 139 void run() { thr->run(); }
140}; 140};
141 141
142extern "C" 142extern "C"
143{ 143{
144 144
145static void terminate_thread( void *arg ) 145static void terminate_thread( void *arg )
146{ 146{
147 Thread::Data *data = ( Thread::Data* )arg; 147 Thread::Data *data = ( Thread::Data* )arg;
148 148
149 assert( data ); 149 assert( data );
150 150
151 AutoLock locker( data->guard ); 151 AutoLock locker( data->guard );
152 data->isRunning = false; 152 data->isRunning = false;
153 data->finishCondition.wakeAll(); 153 data->finishCondition.wakeAll();
154} 154}
155 155
156static void *start_thread( void *arg ) 156static void *start_thread( void *arg )
157{ 157{
158 Thread::Data *data = ( Thread::Data* )arg; 158 Thread::Data *data = ( Thread::Data* )arg;
159 159
160 pthread_cleanup_push( terminate_thread, data ); 160 pthread_cleanup_push( terminate_thread, data );
161 161
162 data->isRunning = true; 162 data->isRunning = true;
163 data->run(); 163 data->run();
164 164
165 pthread_cleanup_pop( true ); 165 pthread_cleanup_pop( true );
166 166
167 Thread::exit(); 167 Thread::exit();
168 return 0; // never reached 168 return 0; // never reached
169} 169}
170 170
171} 171}
172 172
173Thread::Thread() 173Thread::Thread()
174 : d( new Data ) 174 : d( new Data )
175{ 175{
176 d->thr = this; 176 d->thr = this;
177} 177}
178 178
179Thread::~Thread() 179Thread::~Thread()
180{ 180{
181 assert( d->isRunning == false ); 181 assert( d->isRunning == false );
182 delete d; 182 delete d;
183} 183}
184 184
185void Thread::start() 185void Thread::start()
186{ 186{
187 AutoLock lock( d->guard ); 187 AutoLock lock( d->guard );
188 188
189 if ( d->isRunning ) { 189 if ( d->isRunning ) {
190 qDebug( "ThreadUtil::Thread::start() called for running thread." ); 190 odebug << "ThreadUtil::Thread::start() called for running thread." << oendl;
191 return; 191 return;
192 } 192 }
193 193
194 pthread_attr_t attributes; 194 pthread_attr_t attributes;
195 pthread_attr_init( &attributes ); 195 pthread_attr_init( &attributes );
196 pthread_attr_setscope( &attributes, PTHREAD_SCOPE_SYSTEM ); 196 pthread_attr_setscope( &attributes, PTHREAD_SCOPE_SYSTEM );
197 int err = pthread_create( &d->self, &attributes, start_thread, ( void* )d ); 197 int err = pthread_create( &d->self, &attributes, start_thread, ( void* )d );
198 if ( err != 0 ) { 198 if ( err != 0 ) {
199 qDebug( "ThreadUtil::Thread::start() : can't create thread: %s", strerror( err ) ); 199 odebug << "ThreadUtil::Thread::start() : can't create thread: " << strerror( err ) << "" << oendl;
200 pthread_attr_destroy( &attributes ); 200 pthread_attr_destroy( &attributes );
201 return; 201 return;
202 } 202 }
203 pthread_attr_destroy( &attributes ); 203 pthread_attr_destroy( &attributes );
204} 204}
205 205
206void Thread::terminate() 206void Thread::terminate()
207{ 207{
208 AutoLock lock( d->guard ); 208 AutoLock lock( d->guard );
209 if ( !d->isRunning ) 209 if ( !d->isRunning )
210 return; 210 return;
211 211
212 pthread_cancel( d->self ); 212 pthread_cancel( d->self );
213} 213}
214 214
215bool Thread::wait() 215bool Thread::wait()
216{ 216{
217 AutoLock lock( d->guard ); 217 AutoLock lock( d->guard );
218 if ( !d->isRunning ) 218 if ( !d->isRunning )
219 return true; 219 return true;
220 220
221 return d->finishCondition.wait( d->guard ); 221 return d->finishCondition.wait( d->guard );
222} 222}
223 223
224bool Thread::isRunning() const 224bool Thread::isRunning() const
225{ 225{
226 AutoLock lock( d->guard ); 226 AutoLock lock( d->guard );
227 return d->isRunning; 227 return d->isRunning;
228} 228}
229 229
230void Thread::exit() 230void Thread::exit()
231{ 231{
232 pthread_exit( 0 ); 232 pthread_exit( 0 );
233} 233}
234 234
235OnewayNotifier::OnewayNotifier() 235OnewayNotifier::OnewayNotifier()
236{ 236{
237 int fds[ 2 ]; 237 int fds[ 2 ];
238 pipe( fds ); 238 pipe( fds );
239 m_readFd = fds[ 0 ]; 239 m_readFd = fds[ 0 ];
240 m_writeFd = fds[ 1 ]; 240 m_writeFd = fds[ 1 ];
241 241
242 m_notifier = new QSocketNotifier( m_readFd, QSocketNotifier::Read ); 242 m_notifier = new QSocketNotifier( m_readFd, QSocketNotifier::Read );
243 connect( m_notifier, SIGNAL( activated(int) ), 243 connect( m_notifier, SIGNAL( activated(int) ),
244 this, SLOT( wakeUp() ) ); 244 this, SLOT( wakeUp() ) );
245} 245}
246 246
247OnewayNotifier::~OnewayNotifier() 247OnewayNotifier::~OnewayNotifier()
248{ 248{
249 delete m_notifier; 249 delete m_notifier;
250 250
251 ::close( m_readFd ); 251 ::close( m_readFd );
252 ::close( m_writeFd ); 252 ::close( m_writeFd );
253} 253}
254 254
255void OnewayNotifier::notify() 255void OnewayNotifier::notify()
256{ 256{
257 const char c = 42; 257 const char c = 42;
258 ::write( m_writeFd, &c, 1 ); 258 ::write( m_writeFd, &c, 1 );
259} 259}
260 260
261void OnewayNotifier::wakeUp() 261void OnewayNotifier::wakeUp()
262{ 262{
263 char c = 0; 263 char c = 0;
264 264
265 if ( ::read( m_readFd, &c, 1 ) != 1 ) 265 if ( ::read( m_readFd, &c, 1 ) != 1 )
266 return; 266 return;
267 267
268 emit awake(); 268 emit awake();
269} 269}
270 270
271ChannelMessage::ChannelMessage( int type ) 271ChannelMessage::ChannelMessage( int type )
272 : m_type( type ), m_isCall( false ), m_replied( false ), 272 : m_type( type ), m_isCall( false ), m_replied( false ),
273 m_inEventHandler( false ) 273 m_inEventHandler( false )
274{ 274{
275} 275}
276 276
277ChannelMessage::~ChannelMessage() 277ChannelMessage::~ChannelMessage()
278{ 278{
279 if ( m_guard.isLocked() ) 279 if ( m_guard.isLocked() )
280 m_guard.unlock(); 280 m_guard.unlock();
281} 281}
282 282
283void ChannelMessage::reply() 283void ChannelMessage::reply()
284{ 284{
285 if ( !m_isCall ) 285 if ( !m_isCall )
286 { 286 {
287 qDebug( "ChannelMessage::reply() - can't reply oneway message!" ); 287 odebug << "ChannelMessage::reply() - can't reply oneway message!" << oendl;
288 return; 288 return;
289 } 289 }
290 290
291 if ( m_inEventHandler ) 291 if ( m_inEventHandler )
292 { 292 {
293 m_replied = true; 293 m_replied = true;
294 return; 294 return;
295 } 295 }
296 296
297 m_condition.wakeOne(); 297 m_condition.wakeOne();
298 m_guard.unlock(); 298 m_guard.unlock();
299} 299}
300 300
301struct Channel::Private 301struct Channel::Private
302{ 302{
303 Private() 303 Private()
304 { 304 {
305 ownerThread = pthread_self(); 305 ownerThread = pthread_self();
306 } 306 }
307 307
308 pthread_t ownerThread; 308 pthread_t ownerThread;
309}; 309};
310 310
311Channel::Channel( QObject *parent, const char *name ) 311Channel::Channel( QObject *parent, const char *name )
312 : QObject( parent, name ), d( new Private ) 312 : QObject( parent, name ), d( new Private )
313{ 313{
314 connect( &m_notifier, SIGNAL( awake() ), 314 connect( &m_notifier, SIGNAL( awake() ),
315 this, SLOT( deliver() ) ); 315 this, SLOT( deliver() ) );
316} 316}
317 317
318Channel::~Channel() 318Channel::~Channel()
319{ 319{
320 delete d; 320 delete d;
321} 321}
322 322
323void Channel::send( ChannelMessage *message, SendType type ) 323void Channel::send( ChannelMessage *message, SendType type )
324{ 324{
325 if ( type == WaitForReply ) 325 if ( type == WaitForReply )
326 { 326 {
327 message->m_guard.lock(); 327 message->m_guard.lock();
328 message->m_isCall = true; 328 message->m_isCall = true;
329 } 329 }
330 330
331 m_pendingMessagesGuard.lock(); 331 m_pendingMessagesGuard.lock();
332 m_pendingMessages << MsgEnvelope( type, message ); 332 m_pendingMessages << MsgEnvelope( type, message );
333 m_pendingMessagesGuard.unlock(); 333 m_pendingMessagesGuard.unlock();
334 334
335 if ( d->ownerThread == pthread_self() ) { 335 if ( d->ownerThread == pthread_self() ) {
336 assert( type != WaitForReply ); 336 assert( type != WaitForReply );
337 337
338 deliver(); 338 deliver();
339 } 339 }
340 else 340 else
341 m_notifier.notify(); 341 m_notifier.notify();
342 //QThread::postEvent( this, new QCustomEvent( QEvent::User, envelope ) ); 342 //QThread::postEvent( this, new QCustomEvent( QEvent::User, envelope ) );
343 343
344 if ( type == WaitForReply ) 344 if ( type == WaitForReply )
345 { 345 {
346 message->m_condition.wait( message->m_guard ); 346 message->m_condition.wait( message->m_guard );
347 message->m_guard.unlock(); 347 message->m_guard.unlock();
348 } 348 }
349} 349}
350 350
351void Channel::deliver() 351void Channel::deliver()
352{ 352{
353 AutoLock lock( m_pendingMessagesGuard ); 353 AutoLock lock( m_pendingMessagesGuard );
354 354
355 while ( !m_pendingMessages.isEmpty() ) { 355 while ( !m_pendingMessages.isEmpty() ) {
356 MsgEnvelope envelope = m_pendingMessages.first(); 356 MsgEnvelope envelope = m_pendingMessages.first();
357 357
358 m_pendingMessages.remove( m_pendingMessages.begin() ); 358 m_pendingMessages.remove( m_pendingMessages.begin() );
359 359
360 m_pendingMessagesGuard.unlock(); 360 m_pendingMessagesGuard.unlock();
361 deliverOne( envelope ); 361 deliverOne( envelope );
362 m_pendingMessagesGuard.lock(); 362 m_pendingMessagesGuard.lock();
363 } 363 }
364} 364}
365 365
366void Channel::deliverOne( const MsgEnvelope &envelope ) 366void Channel::deliverOne( const MsgEnvelope &envelope )
367{ 367{
368 ChannelMessage *msg = envelope.msg; 368 ChannelMessage *msg = envelope.msg;
369 369
370 assert( msg ); 370 assert( msg );
371 371
372 if ( envelope.type == WaitForReply ) 372 if ( envelope.type == WaitForReply )
373 { 373 {
374 msg->m_guard.lock(); 374 msg->m_guard.lock();
375 msg->m_inEventHandler = true; 375 msg->m_inEventHandler = true;
376 } 376 }
377 377
378 receiveMessage( msg, envelope.type ); 378 receiveMessage( msg, envelope.type );
379 379
380 if ( envelope.type == WaitForReply ) 380 if ( envelope.type == WaitForReply )
381 { 381 {
382 msg->m_inEventHandler = false; 382 msg->m_inEventHandler = false;
383 if ( msg->m_replied ) 383 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 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> 4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org>
5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com> 5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> 6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org>
7 =. 7 =.
8 .=l. 8 .=l.
9           .>+-= 9           .>+-=
10 _;:,     .>    :=|. This program is free software; you can 10 _;:,     .>    :=|. This program is free software; you can
11.> <`_,   >  .   <= redistribute it and/or modify it under 11.> <`_,   >  .   <= redistribute it and/or modify it under
12:`=1 )Y*s>-.--   : the terms of the GNU General Public 12:`=1 )Y*s>-.--   : the terms of the GNU General Public
13.="- .-=="i,     .._ License as published by the Free Software 13.="- .-=="i,     .._ License as published by the Free Software
14 - .   .-<_>     .<> Foundation; either version 2 of the License, 14 - .   .-<_>     .<> Foundation; either version 2 of the License,
15     ._= =}       : or (at your option) any later version. 15     ._= =}       : or (at your option) any later version.
16    .%`+i>       _;_. 16    .%`+i>       _;_.
17    .i_,=:_.      -<s. This program is distributed in the hope that 17    .i_,=:_.      -<s. This program is distributed in the hope that
18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
19    : ..    .:,     . . . without even the implied warranty of 19    : ..    .:,     . . . without even the implied warranty of
20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
22..}^=.=       =       ; General Public License for more 22..}^=.=       =       ; General Public License for more
23++=   -.     .`     .: details. 23++=   -.     .`     .: details.
24 :     =  ...= . :.=- 24 :     =  ...= . :.=-
25 -.   .:....=;==+<; You should have received a copy of the GNU 25 -.   .:....=;==+<; You should have received a copy of the GNU
26  -_. . .   )=.  = General Public License along with 26  -_. . .   )=.  = General Public License along with
27    --        :-=` this library; see the file COPYING.LIB. 27    --        :-=` this library; see the file COPYING.LIB.
28 If not, write to the Free Software Foundation, 28 If not, write to the Free Software Foundation,
29 Inc., 59 Temple Place - Suite 330, 29 Inc., 59 Temple Place - Suite 330,
30 Boston, MA 02111-1307, USA. 30 Boston, MA 02111-1307, USA.
31 31
32*/ 32*/
33 33
34 34
35#include <qtimer.h> 35#include <qtimer.h>
36#include <qmessagebox.h> 36#include <qmessagebox.h>
37#include <qpe/qcopenvelope_qws.h> 37#include <qpe/qcopenvelope_qws.h>
38#include <qpe/qpeapplication.h> 38#include <qpe/qpeapplication.h>
39 39
40#include "xinecontrol.h" 40#include "xinecontrol.h"
41#include "xinevideowidget.h" 41#include "xinevideowidget.h"
42 42
43XineControl::XineControl( XineVideoWidget *xineWidget, 43XineControl::XineControl( XineVideoWidget *xineWidget,
44 MediaPlayerState &_mediaPlayerState, 44 MediaPlayerState &_mediaPlayerState,
45 QObject *parent, const char *name ) 45 QObject *parent, const char *name )
46 : QObject( parent, name ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget ) 46 : QObject( parent, name ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget )
47{ 47{
48 libXine = new XINE::Lib( XINE::Lib::InitializeImmediately, xineWidget ); 48 libXine = new XINE::Lib( XINE::Lib::InitializeImmediately, xineWidget );
49 49
50 init(); 50 init();
51} 51}
52 52
53XineControl::XineControl( XINE::Lib *xine, XineVideoWidget *xineWidget, 53XineControl::XineControl( XINE::Lib *xine, XineVideoWidget *xineWidget,
54 MediaPlayerState &_mediaPlayerState, 54 MediaPlayerState &_mediaPlayerState,
55 QObject *parent, const char *name ) 55 QObject *parent, const char *name )
56 : QObject( parent, name ), libXine( xine ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget ) 56 : QObject( parent, name ), libXine( xine ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget )
57{ 57{
58 xine->ensureInitialized(); 58 xine->ensureInitialized();
59 59
60 xine->setWidget( xineWidget ); 60 xine->setWidget( xineWidget );
61 61
62 init(); 62 init();
63} 63}
64 64
65void XineControl::init() 65void XineControl::init()
66{ 66{
67 connect( &mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( pause(bool) ) ); 67 connect( &mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( pause(bool) ) );
68 connect( this, SIGNAL( positionChanged(long) ), &mediaPlayerState, SLOT( updatePosition(long) ) ); 68 connect( this, SIGNAL( positionChanged(long) ), &mediaPlayerState, SLOT( updatePosition(long) ) );
69 connect( &mediaPlayerState, SIGNAL( playingToggled(bool) ), this, SLOT( stop(bool) ) ); 69 connect( &mediaPlayerState, SIGNAL( playingToggled(bool) ), this, SLOT( stop(bool) ) );
70 connect( &mediaPlayerState, SIGNAL( fullscreenToggled(bool) ), this, SLOT( setFullscreen(bool) ) ); 70 connect( &mediaPlayerState, SIGNAL( fullscreenToggled(bool) ), this, SLOT( setFullscreen(bool) ) );
71 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ), this, SLOT( seekTo(long) ) ); 71 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ), this, SLOT( seekTo(long) ) );
72 connect( &mediaPlayerState, SIGNAL( videoGammaChanged(int) ), this, SLOT( setGamma(int) ) ); 72 connect( &mediaPlayerState, SIGNAL( videoGammaChanged(int) ), this, SLOT( setGamma(int) ) );
73 connect( libXine, SIGNAL( stopped() ), this, SLOT( nextMedia() ) ); 73 connect( libXine, SIGNAL( stopped() ), this, SLOT( nextMedia() ) );
74 connect( xineVideoWidget, SIGNAL( videoResized(const QSize&) ), this, SLOT( videoResized(const QSize&) ) ); 74 connect( xineVideoWidget, SIGNAL( videoResized(const QSize&) ), this, SLOT( videoResized(const QSize&) ) );
75 75
76 disabledSuspendScreenSaver = FALSE; 76 disabledSuspendScreenSaver = FALSE;
77} 77}
78 78
79XineControl::~XineControl() { 79XineControl::~XineControl() {
80#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 80#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
81 if ( disabledSuspendScreenSaver ) { 81 if ( disabledSuspendScreenSaver ) {
82 disabledSuspendScreenSaver = FALSE; 82 disabledSuspendScreenSaver = FALSE;
83 // Re-enable the suspend mode 83 // Re-enable the suspend mode
84 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; 84 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
85 } 85 }
86#endif 86#endif
87 delete libXine; 87 delete libXine;
88} 88}
89 89
90void XineControl::play( const QString& fileName ) { 90void XineControl::play( const QString& fileName ) {
91 91
92 hasVideoChannel = FALSE; 92 hasVideoChannel = FALSE;
93 hasAudioChannel = FALSE; 93 hasAudioChannel = FALSE;
94 m_fileName = fileName; 94 m_fileName = fileName;
95 95
96 qDebug("<<FILENAME: " + fileName + ">>>>"); 96 odebug << "<<FILENAME: " + fileName + ">>>>" << oendl;
97 97
98 if ( !libXine->play( fileName, 0, 0 ) ) { 98 if ( !libXine->play( fileName, 0, 0 ) ) {
99 QMessageBox::warning( 0l , tr( "Failure" ), getErrorCode() ); 99 QMessageBox::warning( 0l , tr( "Failure" ), getErrorCode() );
100 // toggle stop so the the play button is reset 100 // toggle stop so the the play button is reset
101 mediaPlayerState.setPlaying( false ); 101 mediaPlayerState.setPlaying( false );
102 return; 102 return;
103 } 103 }
104 mediaPlayerState.setPlaying( true ); 104 mediaPlayerState.setPlaying( true );
105 105
106 MediaPlayerState::DisplayType displayType; 106 MediaPlayerState::DisplayType displayType;
107 if ( !libXine->hasVideo() ) { 107 if ( !libXine->hasVideo() ) {
108 displayType = MediaPlayerState::Audio; 108 displayType = MediaPlayerState::Audio;
109 qDebug("HAS AUDIO"); 109 odebug << "HAS AUDIO" << oendl;
110 libXine->setShowVideo( false ); 110 libXine->setShowVideo( false );
111 hasAudioChannel = TRUE; 111 hasAudioChannel = TRUE;
112 } else { 112 } else {
113 displayType = MediaPlayerState::Video; 113 displayType = MediaPlayerState::Video;
114 qDebug("HAS VIDEO"); 114 odebug << "HAS VIDEO" << oendl;
115 libXine->setShowVideo( true ); 115 libXine->setShowVideo( true );
116 hasVideoChannel = TRUE; 116 hasVideoChannel = TRUE;
117 } 117 }
118 // determine if slider is shown 118 // determine if slider is shown
119 mediaPlayerState.setIsSeekable( libXine->isSeekable() ); 119 mediaPlayerState.setIsSeekable( libXine->isSeekable() );
120 120
121 // which gui (video / audio) 121 // which gui (video / audio)
122 mediaPlayerState.setDisplayType( displayType ); 122 mediaPlayerState.setDisplayType( displayType );
123 123
124#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 124#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
125 if ( !disabledSuspendScreenSaver ) { 125 if ( !disabledSuspendScreenSaver ) {
126 disabledSuspendScreenSaver = TRUE; 126 disabledSuspendScreenSaver = TRUE;
127 // Stop the screen from blanking and power saving state 127 // Stop the screen from blanking and power saving state
128 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) 128 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" )
129 << ( displayType == MediaPlayerState::Video ? QPEApplication::Disable : QPEApplication::DisableSuspend ); 129 << ( displayType == MediaPlayerState::Video ? QPEApplication::Disable : QPEApplication::DisableSuspend );
130 } 130 }
131#endif 131#endif
132 132
133 length(); 133 length();
134 position(); 134 position();
135} 135}
136 136
137void XineControl::nextMedia() { 137void XineControl::nextMedia() {
138 mediaPlayerState.setNext(); 138 mediaPlayerState.setNext();
139} 139}
140 140
141void XineControl::setGamma( int value ) { 141void XineControl::setGamma( int value ) {
142 libXine->setGamma( value ); 142 libXine->setGamma( value );
143} 143}
144 144
145void XineControl::stop( bool isSet ) { 145void XineControl::stop( bool isSet ) {
146 if ( !isSet ) { 146 if ( !isSet ) {
147 libXine->stop(); 147 libXine->stop();
148 148
149#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 149#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
150 if ( disabledSuspendScreenSaver ) { 150 if ( disabledSuspendScreenSaver ) {
151 disabledSuspendScreenSaver = FALSE; 151 disabledSuspendScreenSaver = FALSE;
152 // Re-enable the suspend mode 152 // Re-enable the suspend mode
153 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; 153 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
154 } 154 }
155#endif 155#endif
156 } 156 }
157} 157}
158 158
159/** 159/**
160 * Pause playback 160 * Pause playback
161 * @isSet 161 * @isSet
162 */ 162 */
163void XineControl::pause( bool isSet) { 163void XineControl::pause( bool isSet) {
164 libXine->pause( isSet ); 164 libXine->pause( isSet );
165} 165}
166 166
167 167
168/** 168/**
169 * get current time in playback 169 * get current time in playback
170 */ 170 */
171long XineControl::currentTime() { 171long XineControl::currentTime() {
172 // todo: jede sekunde überprüfen 172 // todo: jede sekunde überprüfen
173 m_currentTime = libXine->currentTime(); 173 m_currentTime = libXine->currentTime();
174 return m_currentTime; 174 return m_currentTime;
175 QTimer::singleShot( 1000, this, SLOT( currentTime() ) ); 175 QTimer::singleShot( 1000, this, SLOT( currentTime() ) );
176} 176}
177 177
178/** 178/**
179 * Set the length of the media file 179 * Set the length of the media file
180 */ 180 */
181void XineControl::length() { 181void XineControl::length() {
182 m_length = libXine->length(); 182 m_length = libXine->length();
183 mediaPlayerState.setLength( m_length ); 183 mediaPlayerState.setLength( m_length );
184} 184}
185 185
186 186
187/** 187/**
188 * Reports the position the xine backend is at right now 188 * Reports the position the xine backend is at right now
189 * @return long the postion in seconds 189 * @return long the postion in seconds
190 */ 190 */
191long XineControl::position() { 191long XineControl::position() {
192 m_position = ( currentTime() ); 192 m_position = ( currentTime() );
193 mediaPlayerState.updatePosition( m_position ); 193 mediaPlayerState.updatePosition( m_position );
194 long emitPos = (long)m_position; 194 long emitPos = (long)m_position;
195 emit positionChanged( emitPos ); 195 emit positionChanged( emitPos );
196 if( mediaPlayerState.isPlaying() ) { 196 if( mediaPlayerState.isPlaying() ) {
197 // needs to be stopped the media is stopped 197 // needs to be stopped the media is stopped
198 QTimer::singleShot( 1000, this, SLOT( position() ) ); 198 QTimer::singleShot( 1000, this, SLOT( position() ) );
199 } 199 }
200 return m_position; 200 return m_position;
201} 201}
202 202
203/** 203/**
204 * Set videoplayback to fullscreen 204 * Set videoplayback to fullscreen
205 * @param isSet 205 * @param isSet
206 */ 206 */
207void XineControl::setFullscreen( bool isSet ) { 207void XineControl::setFullscreen( bool isSet ) {
208 libXine->showVideoFullScreen( isSet ); 208 libXine->showVideoFullScreen( isSet );
209} 209}
210 210
211 211
212QString XineControl::getMetaInfo() { 212QString XineControl::getMetaInfo() {
213 213
214 QString returnString; 214 QString returnString;
215 215
216 if ( !libXine->metaInfo( 0 ).isEmpty() ) { 216 if ( !libXine->metaInfo( 0 ).isEmpty() ) {
217 returnString += tr( " Title: " + libXine->metaInfo( 0 ) ); 217 returnString += tr( " Title: " + libXine->metaInfo( 0 ) );
218 } 218 }
219 219
220 if ( !libXine->metaInfo( 1 ).isEmpty() ) { 220 if ( !libXine->metaInfo( 1 ).isEmpty() ) {
221 returnString += tr( " Comment: " + libXine->metaInfo( 1 ) ); 221 returnString += tr( " Comment: " + libXine->metaInfo( 1 ) );
222 } 222 }
223 223
224 if ( !libXine->metaInfo( 2 ).isEmpty() ) { 224 if ( !libXine->metaInfo( 2 ).isEmpty() ) {
225 returnString += tr( " Artist: " + libXine->metaInfo( 2 ) ); 225 returnString += tr( " Artist: " + libXine->metaInfo( 2 ) );
226 } 226 }
227 227
228 if ( !libXine->metaInfo( 3 ).isEmpty() ) { 228 if ( !libXine->metaInfo( 3 ).isEmpty() ) {
229 returnString += tr( " Genre: " + libXine->metaInfo( 3 ) ); 229 returnString += tr( " Genre: " + libXine->metaInfo( 3 ) );
230 } 230 }
231 231
232 if ( !libXine->metaInfo( 4 ).isEmpty() ) { 232 if ( !libXine->metaInfo( 4 ).isEmpty() ) {
233 returnString += tr( " Album: " + libXine->metaInfo( 4 ) ); 233 returnString += tr( " Album: " + libXine->metaInfo( 4 ) );
234 } 234 }
235 235
236 if ( !libXine->metaInfo( 5 ).isEmpty() ) { 236 if ( !libXine->metaInfo( 5 ).isEmpty() ) {
237 returnString += tr( " Year: " + libXine->metaInfo( 5 ) ); 237 returnString += tr( " Year: " + libXine->metaInfo( 5 ) );
238 } 238 }
239 return returnString; 239 return returnString;
240} 240}
241 241
242QString XineControl::getErrorCode() { 242QString XineControl::getErrorCode() {
243 243
244 int errorCode = libXine->error(); 244 int errorCode = libXine->error();
245 245
246 qDebug( QString("ERRORCODE: %1 ").arg(errorCode) ); 246 odebug << QString("ERRORCODE: %1 ").arg(errorCode) << oendl;
247 247
248 if ( errorCode == 1 ) { 248 if ( errorCode == 1 ) {
249 return tr( "No input plugin found for this media type" ); 249 return tr( "No input plugin found for this media type" );
250 } else if ( errorCode == 2 ) { 250 } else if ( errorCode == 2 ) {
251 return tr( "No demux plugin found for this media type" ); 251 return tr( "No demux plugin found for this media type" );
252 } else if ( errorCode == 3 ) { 252 } else if ( errorCode == 3 ) {
253 return tr( "Demuxing failed for this media type" ); 253 return tr( "Demuxing failed for this media type" );
254 } else if ( errorCode == 4 ) { 254 } else if ( errorCode == 4 ) {
255 return tr( "Malformed MRL" ); 255 return tr( "Malformed MRL" );
256 } else { 256 } else {
257 return tr( "Some other error" ); 257 return tr( "Some other error" );
258 } 258 }
259} 259}
260 260
261/** 261/**
262 * Seek to a position in the track 262 * Seek to a position in the track
263 * @param second the second to jump to 263 * @param second the second to jump to
264 */ 264 */
265void XineControl::seekTo( long second ) { 265void XineControl::seekTo( long second ) {
266 libXine->seekTo( (int)second ); 266 libXine->seekTo( (int)second );
267} 267}
268 268
269void XineControl::videoResized ( const QSize &s ) { 269void XineControl::videoResized ( const QSize &s ) {
270 libXine->resize( s ); 270 libXine->resize( s );
271} 271}
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 @@
1// device.cpp 1// device.cpp
2 2
3#include "device.h" 3#include "device.h"
4 4
5/* OPIE */
6#include <opie2/odebug.h>
5#include <qpe/config.h> 7#include <qpe/config.h>
6#include <qpe/qcopenvelope_qws.h> 8#include <qpe/qcopenvelope_qws.h>
9using namespace Opie::Core;
7 10
8 11/* STD */
9#include <fcntl.h> 12#include <fcntl.h>
10#include <stdio.h> 13#include <stdio.h>
11#include <stdlib.h> 14#include <stdlib.h>
12#include <sys/ioctl.h> 15#include <sys/ioctl.h>
13#include <sys/soundcard.h> 16#include <sys/soundcard.h>
14#include <unistd.h> 17#include <unistd.h>
15#include<sys/wait.h> 18#include <sys/wait.h>
16// #include <sys/stat.h>
17// #include <sys/time.h>
18// #include <sys/types.h>
19#include <unistd.h> 19#include <unistd.h>
20#include <errno.h> 20#include <errno.h>
21 21
22//extern QtRec *qperec; 22//extern QtRec *qperec;
23 23
24Device::Device( QObject * parent, const char * dsp, const char * mixr, bool record ) 24Device::Device( QObject * parent, const char * dsp, const char * mixr, bool record )
25 : QObject( parent) 25 : QObject( parent)
26{ 26{
27 dspstr = (char *)dsp; 27 dspstr = (char *)dsp;
28 mixstr = (char *)mixr; 28 mixstr = (char *)mixr;
29 29
30 devForm=-1; 30 devForm=-1;
31 devCh=-1; 31 devCh=-1;
32 devRate=-1; 32 devRate=-1;
33 33
34 if( !record){ //playing 34 if( !record){ //playing
35 qDebug("setting up DSP for playing"); 35 odebug << "setting up DSP for playing" << oendl;
36 flags = O_WRONLY; 36 flags = O_WRONLY;
37 } else { //recording 37 } else { //recording
38 qDebug("setting up DSP for recording"); 38 odebug << "setting up DSP for recording" << oendl;
39 flags = O_RDWR; 39 flags = O_RDWR;
40// flags = O_RDONLY; 40// flags = O_RDONLY;
41 41
42// selectMicInput(); 42// selectMicInput();
43 43
44 } 44 }
45} 45}
46 46
47bool Device::openDsp() { 47bool Device::openDsp() {
48 if( openDevice( flags) == -1) { 48 if( openDevice( flags) == -1) {
49 perror("<<<<<<<<<<<<<<ioctl(\"Open device\")"); 49 perror("<<<<<<<<<<<<<<ioctl(\"Open device\")");
50 return false; 50 return false;
51 } 51 }
52 return true; 52 return true;
53} 53}
54 54
55int Device::getOutVolume( ) { 55int Device::getOutVolume( ) {
56 unsigned int volume; 56 unsigned int volume;
57 int mixerHandle = open( mixstr, O_RDWR ); 57 int mixerHandle = open( mixstr, O_RDWR );
58 if ( mixerHandle >= 0 ) { 58 if ( mixerHandle >= 0 ) {
59 if(ioctl( mixerHandle, MIXER_READ(SOUND_MIXER_VOLUME), &volume )==-1) 59 if(ioctl( mixerHandle, MIXER_READ(SOUND_MIXER_VOLUME), &volume )==-1)
60 perror("<<<<<<<<<<<<<<ioctl(\"MIXER_READ\")"); 60 perror("<<<<<<<<<<<<<<ioctl(\"MIXER_READ\")");
61 ::close( mixerHandle ); 61 ::close( mixerHandle );
62 } else 62 } else
63 perror("open(\"/dev/mixer\")"); 63 perror("open(\"/dev/mixer\")");
64 printf("<<<<<<<<<<<<<<<<<<<<output volume %d\n",volume); 64 printf("<<<<<<<<<<<<<<<<<<<<output volume %d\n",volume);
65 65
66 Config cfg("qpe"); 66 Config cfg("qpe");
67 cfg.setGroup("Volume"); 67 cfg.setGroup("Volume");
68 68
69 return cfg.readNumEntry("VolumePercent"); 69 return cfg.readNumEntry("VolumePercent");
70} 70}
71 71
72int Device::getInVolume() { 72int Device::getInVolume() {
73 unsigned int volume=0; 73 unsigned int volume=0;
74 int mixerHandle = ::open( mixstr, O_RDWR ); 74 int mixerHandle = ::open( mixstr, O_RDWR );
75 if ( mixerHandle >= 0 ) { 75 if ( mixerHandle >= 0 ) {
76 if(ioctl( mixerHandle, MIXER_READ(SOUND_MIXER_MIC), &volume )==-1) 76 if(ioctl( mixerHandle, MIXER_READ(SOUND_MIXER_MIC), &volume )==-1)
77 perror("<<<<<<<<<<<<<<<ioctl(\"MIXER_READ\")"); 77 perror("<<<<<<<<<<<<<<<ioctl(\"MIXER_READ\")");
78 ::close( mixerHandle ); 78 ::close( mixerHandle );
79 } else 79 } else
80 perror("open(\"/dev/mixer\")"); 80 perror("open(\"/dev/mixer\")");
81 printf("<<<<<<<<<<<<<<input volume %d\n", volume ); 81 printf("<<<<<<<<<<<<<<input volume %d\n", volume );
82 Config cfg("qpe"); 82 Config cfg("qpe");
83 cfg.setGroup("Volume"); 83 cfg.setGroup("Volume");
84 84
85 return cfg.readNumEntry("Mic"); 85 return cfg.readNumEntry("Mic");
86} 86}
87 87
88void Device::changedOutVolume(int vol) { 88void Device::changedOutVolume(int vol) {
89 int level = (vol << 8) + vol; 89 int level = (vol << 8) + vol;
90 int fd = 0; 90 int fd = 0;
91 if ((fd = open("/dev/mixer", O_RDWR))>=0) { 91 if ((fd = open("/dev/mixer", O_RDWR))>=0) {
92 if(ioctl(fd, MIXER_WRITE(SOUND_MIXER_VOLUME), &level) == -1) 92 if(ioctl(fd, MIXER_WRITE(SOUND_MIXER_VOLUME), &level) == -1)
93 perror("ioctl(\"MIXER_IN_WRITE\")"); 93 perror("ioctl(\"MIXER_IN_WRITE\")");
94 94
95 Config cfg("qpe"); 95 Config cfg("qpe");
96 cfg.setGroup("Volume"); 96 cfg.setGroup("Volume");
97 cfg.writeEntry("VolumePercent", QString::number( vol )); 97 cfg.writeEntry("VolumePercent", QString::number( vol ));
98 QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << false; 98 QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << false;
99 qWarning("changing output vol %d", vol); 99 owarn << "changing output vol " << vol << "" << oendl;
100 } 100 }
101 ::close(fd); 101 ::close(fd);
102} 102}
103 103
104void Device::changedInVolume(int vol ) { 104void Device::changedInVolume(int vol ) {
105 int level = (vol << 8) + vol; 105 int level = (vol << 8) + vol;
106 int fd = 0; 106 int fd = 0;
107 if ((fd = open("/dev/mixer", O_RDWR))>=0) { 107 if ((fd = open("/dev/mixer", O_RDWR))>=0) {
108 if(ioctl(fd, MIXER_WRITE(SOUND_MIXER_MIC), &level) == -1) 108 if(ioctl(fd, MIXER_WRITE(SOUND_MIXER_MIC), &level) == -1)
109 perror("ioctl(\"MIXER_IN_WRITE\")"); 109 perror("ioctl(\"MIXER_IN_WRITE\")");
110 Config cfg("qpe"); 110 Config cfg("qpe");
111 cfg.setGroup("Volume"); 111 cfg.setGroup("Volume");
112 cfg.writeEntry("Mic", QString::number(vol )); 112 cfg.writeEntry("Mic", QString::number(vol ));
113 QCopEnvelope( "QPE/System", "micChange(bool)" ) << false; 113 QCopEnvelope( "QPE/System", "micChange(bool)" ) << false;
114 qWarning("changing input volume %d", vol); 114 owarn << "changing input volume " << vol << "" << oendl;
115 } 115 }
116 ::close(fd); 116 ::close(fd);
117} 117}
118 118
119bool Device::selectMicInput() { 119bool Device::selectMicInput() {
120 120
121 int md=0; 121 int md=0;
122 int info=MIXER_WRITE(SOUND_MIXER_MIC); 122 int info=MIXER_WRITE(SOUND_MIXER_MIC);
123 md = ::open( "/dev/mixer", O_RDWR ); 123 md = ::open( "/dev/mixer", O_RDWR );
124 if ( md == -1) 124 if ( md == -1)
125 perror("open(\"/dev/mixer\")"); 125 perror("open(\"/dev/mixer\")");
126 else { 126 else {
127 if( ioctl( md, SOUND_MIXER_WRITE_RECSRC, &info) == -1) 127 if( ioctl( md, SOUND_MIXER_WRITE_RECSRC, &info) == -1)
128 perror("ioctl(\"SOUND_MIXER_WRITE_RECSRC\")"); 128 perror("ioctl(\"SOUND_MIXER_WRITE_RECSRC\")");
129 ::close(md); 129 ::close(md);
130 return false; 130 return false;
131 } 131 }
132 ::close(md); 132 ::close(md);
133 133
134 return true; 134 return true;
135} 135}
136 136
137int Device::openDevice( int flags) { 137int Device::openDevice( int flags) {
138/* pid_t pid; 138/* pid_t pid;
139 int status; 139 int status;
140 int pipefd[2]; 140 int pipefd[2];
141 char message[20]; 141 char message[20];
142 if (pipe(pipefd) == -1){ 142 if (pipe(pipefd) == -1){
143 perror ("Error creating pipe"); 143 perror ("Error creating pipe");
144exit(1); 144exit(1);
145 } 145 }
146 switch (pid = fork()) { 146 switch (pid = fork()) {
147 case -1: 147 case -1:
148 perror("The fork failed!"); 148 perror("The fork failed!");
149 break; 149 break;
150 case 0: { 150 case 0: {
151 */ 151 */
152qDebug("Opening %s",dspstr); 152odebug << "Opening " << dspstr << "" << oendl;
153 if (( sd = ::open( dspstr, flags)) == -1) { 153 if (( sd = ::open( dspstr, flags)) == -1) {
154 perror("open(\"/dev/dsp\")"); 154 perror("open(\"/dev/dsp\")");
155 QString errorMsg="Could not open audio device\n /dev/dsp\n" 155 QString errorMsg="Could not open audio device\n /dev/dsp\n"
156 +(QString)strerror(errno); 156 +(QString)strerror(errno);
157 qDebug("XXXXXXXXXXXXXXXXXXXXXXX "+errorMsg); 157 odebug << "XXXXXXXXXXXXXXXXXXXXXXX "+errorMsg << oendl;
158 return -1; 158 return -1;
159 } 159 }
160 160
161qDebug("Opening mixer"); 161odebug << "Opening mixer" << oendl;
162 int mixerHandle=0; 162 int mixerHandle=0;
163 if (( mixerHandle = open("/dev/mixer",O_RDWR))<0) { 163 if (( mixerHandle = open("/dev/mixer",O_RDWR))<0) {
164 perror("open(\"/dev/mixer\")"); 164 perror("open(\"/dev/mixer\")");
165 QString errorMsg="Could not open audio device\n /dev/dsp\n" 165 QString errorMsg="Could not open audio device\n /dev/dsp\n"
166 +(QString)strerror(errno); 166 +(QString)strerror(errno);
167 qDebug("XXXXXXXXXXXXXXXXXXXXXX "+errorMsg); 167 odebug << "XXXXXXXXXXXXXXXXXXXXXX "+errorMsg << oendl;
168 } 168 }
169 169
170 if(ioctl(sd,SNDCTL_DSP_RESET,0)<0){ 170 if(ioctl(sd,SNDCTL_DSP_RESET,0)<0){
171 perror("ioctl RESET"); 171 perror("ioctl RESET");
172 } 172 }
173// sprintf(message, "%d", sd); 173// sprintf(message, "%d", sd);
174 174
175/* QFile f1("/pid"); 175/* QFile f1("/pid");
176 f1.open(IO_WriteOnly ); 176 f1.open(IO_WriteOnly );
177 f1.writeBlock(message, strlen(message)); 177 f1.writeBlock(message, strlen(message));
178 f1.close(); 178 f1.close();
179 */ 179 */
180 /* close(pipefd[0]); 180 /* close(pipefd[0]);
181 write(pipefd[1], message, sizeof(message)); 181 write(pipefd[1], message, sizeof(message));
182 close(pipefd[1]); 182 close(pipefd[1]);
183 // qDebug("%d",soundDevice->sd ); 183 // odebug << "" << soundDevice->sd << "" << oendl;
184 _exit(0); 184 _exit(0);
185 } 185 }
186 default: 186 default:
187 // pid greater than zero is parent getting the child's pid 187 // pid greater than zero is parent getting the child's pid
188 printf("Child's pid is %d\n",pid); 188 printf("Child's pid is %d\n",pid);
189 QString s; 189 QString s;
190 close(pipefd[1]); 190 close(pipefd[1]);
191 read(pipefd[0], message, sizeof(message)); 191 read(pipefd[0], message, sizeof(message));
192 s = message; 192 s = message;
193 close(pipefd[0]); 193 close(pipefd[0]);
194 194
195// while(wait(NULL)!=pid) 195// while(wait(NULL)!=pid)
196 // ; 196 // ;
197 printf("child %ld terminated normally, return status is zero\n", (long) pid); 197 printf("child %ld terminated normally, return status is zero\n", (long) pid);
198 */ 198 */
199 // filePara.sd=(long) pid; 199 // filePara.sd=(long) pid;
200 /* QFile f2("/pid"); 200 /* QFile f2("/pid");
201 f2.open(IO_ReadOnly); 201 f2.open(IO_ReadOnly);
202 QTextStream t(&f2); 202 QTextStream t(&f2);
203 // for(int f=0; f < t.atEnd() ;f++) { 203 // for(int f=0; f < t.atEnd() ;f++) {
204 s = t.readLine(); 204 s = t.readLine();
205 // } 205 // }
206 */ 206 */
207// bool ok; 207// bool ok;
208// sd = s.toInt(&ok, 10); 208// sd = s.toInt(&ok, 10);
209// qDebug("<<<<<<<<<<<<<>>>>>>>>>>>>"+s); 209// odebug << "<<<<<<<<<<<<<>>>>>>>>>>>>"+s << oendl;
210 210
211// f2.close(); 211// f2.close();
212// } 212// }
213::close(mixerHandle ); 213::close(mixerHandle );
214// qDebug("open device %s", dspstr); 214// odebug << "open device " << dspstr << "" << oendl;
215// qDebug("success! %d",sd); 215// odebug << "success! " << sd << "" << oendl;
216 return sd; 216 return sd;
217} 217}
218 218
219bool Device::closeDevice( bool) { 219bool Device::closeDevice( bool) {
220// if(b) {//close now 220// if(b) {//close now
221// if (ioctl( sd, SNDCTL_DSP_RESET, 0) == -1) { 221// if (ioctl( sd, SNDCTL_DSP_RESET, 0) == -1) {
222// perror("ioctl(\"SNDCTL_DSP_RESET\")"); 222// perror("ioctl(\"SNDCTL_DSP_RESET\")");
223// } 223// }
224// } else { //let play 224// } else { //let play
225// if (ioctl( sd, SNDCTL_DSP_SYNC, 0) == -1) { 225// if (ioctl( sd, SNDCTL_DSP_SYNC, 0) == -1) {
226// perror("ioctl(\"SNDCTL_DSP_SYNC\")"); 226// perror("ioctl(\"SNDCTL_DSP_SYNC\")");
227// } 227// }
228// } 228// }
229 229
230 ::close( sd); //close sound device 230 ::close( sd); //close sound device
231// sdfd=0; 231// sdfd=0;
232 // sd=0; 232 // sd=0;
233// qDebug("closed dsp"); 233// odebug << "closed dsp" << oendl;
234 return true; 234 return true;
235} 235}
236 236
237bool Device::setDeviceFormat( int form) { 237bool Device::setDeviceFormat( int form) {
238 qDebug("set device res %d %d", form, sd); 238 odebug << "set device res " << form << " " << sd << "" << oendl;
239 if (ioctl( sd, SNDCTL_DSP_SETFMT, &form)==-1) { //set format 239 if (ioctl( sd, SNDCTL_DSP_SETFMT, &form)==-1) { //set format
240 perror("ioctl(\"SNDCTL_DSP_SETFMT\")"); 240 perror("ioctl(\"SNDCTL_DSP_SETFMT\")");
241 return false; 241 return false;
242 } 242 }
243 devRes=form; 243 devRes=form;
244 return true; 244 return true;
245} 245}
246 246
247bool Device::setDeviceChannels( int ch) { 247bool Device::setDeviceChannels( int ch) {
248 qDebug("set channels %d %d", ch, sd); 248 odebug << "set channels " << ch << " " << sd << "" << oendl;
249 if (ioctl( sd, SNDCTL_DSP_CHANNELS, &ch)==-1) { 249 if (ioctl( sd, SNDCTL_DSP_CHANNELS, &ch)==-1) {
250 perror("ioctl(\"SNDCTL_DSP_CHANNELS\")"); 250 perror("ioctl(\"SNDCTL_DSP_CHANNELS\")");
251 return false; 251 return false;
252 } 252 }
253 devCh=ch; 253 devCh=ch;
254 return true; 254 return true;
255} 255}
256 256
257bool Device::setDeviceRate( int rate) { 257bool Device::setDeviceRate( int rate) {
258 qDebug("set rate %d %d", rate, sd); 258 odebug << "set rate " << rate << " " << sd << "" << oendl;
259 if (ioctl( sd, SNDCTL_DSP_SPEED, &rate) == -1) { 259 if (ioctl( sd, SNDCTL_DSP_SPEED, &rate) == -1) {
260 perror("ioctl(\"SNDCTL_DSP_SPEED\")"); 260 perror("ioctl(\"SNDCTL_DSP_SPEED\")");
261 return false; 261 return false;
262 } 262 }
263 263
264 devRate=rate; 264 devRate=rate;
265 265
266 return true; 266 return true;
267} 267}
268 268
269int Device::getRes() { 269int Device::getRes() {
270 return devRes; 270 return devRes;
271} 271}
272 272
273int Device::getFormat() { 273int Device::getFormat() {
274 return devForm; 274 return devForm;
275} 275}
276 276
277int Device::getRate() { 277int Device::getRate() {
278 return devRate; 278 return devRate;
279} 279}
280 280
281int Device::getChannels() { 281int Device::getChannels() {
282 return devCh; 282 return devCh;
283} 283}
284 284
285int Device::getDeviceFormat() { 285int Device::getDeviceFormat() {
286 return 0; 286 return 0;
287} 287}
288 288
289 289
290int Device::getDeviceRate() { 290int Device::getDeviceRate() {
291 int dRate=0; 291 int dRate=0;
292 if (ioctl( sd, SOUND_PCM_READ_RATE, &dRate) == -1) { 292 if (ioctl( sd, SOUND_PCM_READ_RATE, &dRate) == -1) {
293 perror("ioctl(\"SNDCTL_PCM_READ_RATE\")"); 293 perror("ioctl(\"SNDCTL_PCM_READ_RATE\")");
294 } 294 }
295 return dRate; 295 return dRate;
296 296
297} 297}
298 298
299int Device::getDeviceBits() { 299int Device::getDeviceBits() {
300 int dBits=0; 300 int dBits=0;
301#ifndef QT_QWS_EBX // zaurus doesnt have this 301#ifndef QT_QWS_EBX // zaurus doesnt have this
302 if (ioctl( sd, SOUND_PCM_READ_BITS, &dBits) == -1) { 302 if (ioctl( sd, SOUND_PCM_READ_BITS, &dBits) == -1) {
303 perror("ioctl(\"SNDCTL_PCM_READ_BITS\")"); 303 perror("ioctl(\"SNDCTL_PCM_READ_BITS\")");
304 } 304 }
305#endif 305#endif
306 return dBits; 306 return dBits;
307} 307}
308 308
309int Device::getDeviceChannels() { 309int Device::getDeviceChannels() {
310 int dCh=0; 310 int dCh=0;
311 if (ioctl( sd, SOUND_PCM_READ_CHANNELS, &dCh) == -1) { 311 if (ioctl( sd, SOUND_PCM_READ_CHANNELS, &dCh) == -1) {
312 perror("ioctl(\"SNDCTL_PCM_READ_CHANNELS\")"); 312 perror("ioctl(\"SNDCTL_PCM_READ_CHANNELS\")");
313 } 313 }
314 return dCh; 314 return dCh;
315} 315}
316 316
317int Device::getDeviceFragSize() { 317int Device::getDeviceFragSize() {
318 int frag_size; 318 int frag_size;
319 319
320 if (ioctl( sd, SNDCTL_DSP_GETBLKSIZE, &frag_size) == -1) { 320 if (ioctl( sd, SNDCTL_DSP_GETBLKSIZE, &frag_size) == -1) {
321 qDebug("no fragsize"); 321 odebug << "no fragsize" << oendl;
322 } else { 322 } else {
323 qDebug("driver says frag size is %d", frag_size); 323 odebug << "driver says frag size is " << frag_size << "" << oendl;
324 } 324 }
325 return frag_size; 325 return frag_size;
326} 326}
327 327
328bool Device::setFragSize(int frag) { 328bool Device::setFragSize(int frag) {
329 if (ioctl(sd, SNDCTL_DSP_SETFRAGMENT, &frag)) { 329 if (ioctl(sd, SNDCTL_DSP_SETFRAGMENT, &frag)) {
330 perror("ioctl(\"SNDCTL_DSP_SETFRAGMENT\")"); 330 perror("ioctl(\"SNDCTL_DSP_SETFRAGMENT\")");
331 return false; 331 return false;
332 } 332 }
333 return true; 333 return true;
334} 334}
335 335
336bool Device::reset() { 336bool Device::reset() {
337 closeDevice(true); 337 closeDevice(true);
338 openDsp(); 338 openDsp();
339 if (ioctl( sd, SNDCTL_DSP_RESET, 0) == -1) { 339 if (ioctl( sd, SNDCTL_DSP_RESET, 0) == -1) {
340 perror("ioctl(\"SNDCTL_DSP_RESET\")"); 340 perror("ioctl(\"SNDCTL_DSP_RESET\")");
341 return false; 341 return false;
342 } 342 }
343 return true; 343 return true;
344} 344}
345 345
346int Device::devRead(int soundDescriptor, short *buf, int size) { 346int Device::devRead(int soundDescriptor, short *buf, int size) {
347 int number = 0; 347 int number = 0;
348 number = ::read( soundDescriptor, (char *)buf, size); 348 number = ::read( soundDescriptor, (char *)buf, size);
349 return number; 349 return number;
350} 350}
351 351
352int Device::devWrite(int soundDescriptor, short * buf, int size) { 352int Device::devWrite(int soundDescriptor, short * buf, int size) {
353 int bytesWritten = 0; 353 int bytesWritten = 0;
354 bytesWritten = ::write( soundDescriptor, buf, size); 354 bytesWritten = ::write( soundDescriptor, buf, size);
355 return bytesWritten; 355 return bytesWritten;
356} 356}
357 357
358 358
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 @@
1/**************************************************************************** 1/****************************************************************************
2** $Id$ 2** $Id$
3** 3**
4** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. 4** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
5** 5**
6** This file is part of an example program for Qt. This example 6** This file is part of an example program for Qt. This example
7** program may be used, distributed and modified without limitation. 7** program may be used, distributed and modified without limitation.
8** 8**
9*****************************************************************************/ 9*****************************************************************************/
10 10
11#include "helpwindow.h" 11#include "helpwindow.h"
12#include <qlayout.h>
13 12
14#include <qtoolbar.h> 13/* OPIE */
14#include <opie2/odebug.h>
15#include <qpe/resource.h> 15#include <qpe/resource.h>
16using namespace Opie::Core;
16 17
18/* QT */
19#include <qlayout.h>
20#include <qtoolbar.h>
17#include <qaction.h> 21#include <qaction.h>
18#include <qmenubar.h> 22#include <qmenubar.h>
19 23
24/* STD */
20#include <ctype.h> 25#include <ctype.h>
21 26
22HelpWindow::HelpWindow( const QString& home_, const QString& _path, QWidget* parent, const char *name ) 27HelpWindow::HelpWindow( const QString& home_, const QString& _path, QWidget* parent, const char *name )
23 : QMainWindow( parent, name, WDestructiveClose ), pathCombo( 0 ), selectedURL() 28 : QMainWindow( parent, name, WDestructiveClose ), pathCombo( 0 ), selectedURL()
24{ 29{
25 QGridLayout *layout = new QGridLayout( this ); 30 QGridLayout *layout = new QGridLayout( this );
26 layout->setSpacing( 2); 31 layout->setSpacing( 2);
27 layout->setMargin( 2); 32 layout->setMargin( 2);
28 qDebug(_path); 33 odebug << _path << oendl;
29 browser = new QTextBrowser( this ); 34 browser = new QTextBrowser( this );
30 QStringList Strlist; 35 QStringList Strlist;
31 Strlist.append( home_); 36 Strlist.append( home_);
32 browser->mimeSourceFactory()->setFilePath( Strlist ); 37 browser->mimeSourceFactory()->setFilePath( Strlist );
33 browser->setFrameStyle( QFrame::Panel | QFrame::Sunken ); 38 browser->setFrameStyle( QFrame::Panel | QFrame::Sunken );
34 39
35 connect( browser, SIGNAL( textChanged() ), this, SLOT( textChanged() ) ); 40 connect( browser, SIGNAL( textChanged() ), this, SLOT( textChanged() ) );
36 41
37 if ( !home_.isEmpty() ) 42 if ( !home_.isEmpty() )
38 browser->setSource( home_ ); 43 browser->setSource( home_ );
39 QToolBar *toolbar = new QToolBar( this ); 44 QToolBar *toolbar = new QToolBar( this );
40 45
41 QAction *a = new QAction( tr( "Backward" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 ); 46 QAction *a = new QAction( tr( "Backward" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 );
42 connect( a, SIGNAL( activated() ), browser, SLOT( backward() ) ); 47 connect( a, SIGNAL( activated() ), browser, SLOT( backward() ) );
43 a->addTo( toolbar ); 48 a->addTo( toolbar );
44 49
45 a = new QAction( tr( "Forward" ), Resource::loadPixmap( "forward" ), QString::null, 0, this, 0 ); 50 a = new QAction( tr( "Forward" ), Resource::loadPixmap( "forward" ), QString::null, 0, this, 0 );
46 connect( a, SIGNAL( activated() ), browser, SLOT( forward() ) ); 51 connect( a, SIGNAL( activated() ), browser, SLOT( forward() ) );
47 a->addTo( toolbar ); 52 a->addTo( toolbar );
48 53
49 54
50 layout->addMultiCellWidget( toolbar, 0, 0, 0, 0); 55 layout->addMultiCellWidget( toolbar, 0, 0, 0, 0);
51 56
52 layout->addMultiCellWidget( browser, 1, 2, 0, 2); 57 layout->addMultiCellWidget( browser, 1, 2, 0, 2);
53 58
54 browser->setFocus(); 59 browser->setFocus();
55} 60}
56 61
57 62
58void HelpWindow::setBackwardAvailable( bool b) 63void HelpWindow::setBackwardAvailable( bool b)
59{ 64{
60 menuBar()->setItemEnabled( backwardId, b); 65 menuBar()->setItemEnabled( backwardId, b);
61} 66}
62 67
63void HelpWindow::setForwardAvailable( bool b) 68void HelpWindow::setForwardAvailable( bool b)
64{ 69{
65 menuBar()->setItemEnabled( forwardId, b); 70 menuBar()->setItemEnabled( forwardId, b);
66} 71}
67 72
68 73
69void HelpWindow::textChanged() 74void HelpWindow::textChanged()
70{ 75{
71 if ( browser->documentTitle().isNull() ) { 76 if ( browser->documentTitle().isNull() ) {
72 setCaption( "QpeRec - Helpviewer - " + browser->context() ); 77 setCaption( "QpeRec - Helpviewer - " + browser->context() );
73 selectedURL = browser->context(); 78 selectedURL = browser->context();
74 } 79 }
75 else { 80 else {
76 setCaption( "QpeRec - Helpviewer - " + browser->documentTitle() ) ; 81 setCaption( "QpeRec - Helpviewer - " + browser->documentTitle() ) ;
77 selectedURL = browser->documentTitle(); 82 selectedURL = browser->documentTitle();
78 } 83 }
79 84
80// if ( !selectedURL.isEmpty() && pathCombo ) { 85// if ( !selectedURL.isEmpty() && pathCombo ) {
81// bool exists = FALSE; 86// bool exists = FALSE;
82// int i; 87// int i;
83// for ( i = 0; i < pathCombo->count(); ++i ) { 88// for ( i = 0; i < pathCombo->count(); ++i ) {
84// if ( pathCombo->text( i ) == selectedURL ) { 89// if ( pathCombo->text( i ) == selectedURL ) {
85// exists = TRUE; 90// exists = TRUE;
86// break; 91// break;
87// } 92// }
88// } 93// }
89// if ( !exists ) { 94// if ( !exists ) {
90// pathCombo->insertItem( selectedURL, 0 ); 95// pathCombo->insertItem( selectedURL, 0 );
91// pathCombo->setCurrentItem( 0 ); 96// pathCombo->setCurrentItem( 0 );
92// mHistory[ hist->insertItem( selectedURL ) ] = selectedURL; 97// mHistory[ hist->insertItem( selectedURL ) ] = selectedURL;
93// } else 98// } else
94// pathCombo->setCurrentItem( i ); 99// pathCombo->setCurrentItem( i );
95// selectedURL = QString::null; 100// selectedURL = QString::null;
96// } 101// }
97} 102}
98 103
99HelpWindow::~HelpWindow() 104HelpWindow::~HelpWindow()
100{ 105{
101 history.clear(); 106 history.clear();
102 QMap<int, QString>::Iterator it = mHistory.begin(); 107 QMap<int, QString>::Iterator it = mHistory.begin();
103 for ( ; it != mHistory.end(); ++it ) 108 for ( ; it != mHistory.end(); ++it )
104 history.append( *it ); 109 history.append( *it );
105 110
106 QFile f( QDir::currentDirPath() + "/.history" ); 111 QFile f( QDir::currentDirPath() + "/.history" );
107 f.open( IO_WriteOnly ); 112 f.open( IO_WriteOnly );
108 QDataStream s( &f ); 113 QDataStream s( &f );
109 s << history; 114 s << history;
110 f.close(); 115 f.close();
111 116
112 bookmarks.clear(); 117 bookmarks.clear();
113 QMap<int, QString>::Iterator it2 = mBookmarks.begin(); 118 QMap<int, QString>::Iterator it2 = mBookmarks.begin();
114 for ( ; it2 != mBookmarks.end(); ++it2 ) 119 for ( ; it2 != mBookmarks.end(); ++it2 )
115 bookmarks.append( *it2 ); 120 bookmarks.append( *it2 );
116 121
117 QFile f2( QDir::currentDirPath() + "/.bookmarks" ); 122 QFile f2( QDir::currentDirPath() + "/.bookmarks" );
118 f2.open( IO_WriteOnly ); 123 f2.open( IO_WriteOnly );
119 QDataStream s2( &f2 ); 124 QDataStream s2( &f2 );
120 s2 << bookmarks; 125 s2 << bookmarks;
121 f2.close(); 126 f2.close();
122} 127}
123 128
124void HelpWindow::openFile() 129void 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 @@
1#CONFIG = qt warn_on pdaudio 1CONFIG = qt warn_on
2CONFIG = qt warn_on opie
3#CONFIG = qt warn_on quick-app
4HEADERS = adpcm.h \ 2HEADERS = adpcm.h \
5 pixmaps.h \ 3 pixmaps.h \
6 helpwindow.h \ 4 helpwindow.h \
7 qtrec.h \ 5 qtrec.h \
8 device.h \ 6 device.h \
9 wavFile.h \ 7 wavFile.h \
10 waveform.h 8 waveform.h
11SOURCES = adpcm.c \ 9SOURCES = adpcm.c \
12 helpwindow.cpp \ 10 helpwindow.cpp \
13 main.cpp \ 11 main.cpp \
14 qtrec.cpp \ 12 qtrec.cpp \
15 device.cpp \ 13 device.cpp \
16 wavFile.cpp \ 14 wavFile.cpp \
17 waveform.cpp 15 waveform.cpp
18INTERFACES = 16INTERFACES =
19 17
20contains(CONFIG, pdaudio) { 18contains(CONFIG, pdaudio) {
21# LIBS += -L/opt/buildroot-opie/output/staging/target/lib -lqpe -lpthread -ljpeg -lpng -lz 19# LIBS += -L/opt/buildroot-opie/output/staging/target/lib -lqpe -lpthread -ljpeg -lpng -lz
22 LIBS += -L$(QPEDIR)/lib -lqpe -lpthread -ljpeg -lpng -lz -lopiecore2 20 LIBS += -L$(QPEDIR)/lib -lqpe -lpthread -ljpeg -lpng -lz -lopiecore2
23 INCLUDEPATH += $(QPEDIR)/include 21 INCLUDEPATH += $(QPEDIR)/include
24 DEPENDPATH += $(QPEDIR)/include 22 DEPENDPATH += $(QPEDIR)/include
25 DEFINES += PDAUDIO 23 DEFINES += PDAUDIO
26 DEFINES += THREADED 24 DEFINES += THREADED
27 TARGET = qperec 25 TARGET = qperec
28 26
29# DESTDIR=$(QPEDIR)/bin 27# DESTDIR=$(QPEDIR)/bin
30} 28}
31 29
32contains(CONFIG, opie) { 30!contains(CONFIG, pdaudio) {
33 INCLUDEPATH += $(OPIEDIR)/include 31 INCLUDEPATH += $(OPIEDIR)/include
34 DEPENDPATH += $(OPIEDIR)/include 32 DEPENDPATH += $(OPIEDIR)/include
35 DESTDIR=$(OPIEDIR)/bin 33 DESTDIR=$(OPIEDIR)/bin
36 LIBS += -lqpe -lopiecore2 -lpthread 34 LIBS += -lqpe -lopiecore2 -lpthread
37 TARGET = opierec 35 TARGET = opierec
38 include ( $(OPIEDIR)/include.pro ) 36 include ( $(OPIEDIR)/include.pro )
39} 37}
40 38
41 39
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 @@
1/**************************************************************************** 1/****************************************************************************
2 // qtrec.cpp 2 // qtrec.cpp
3 Created: Thu Jan 17 11:19:58 2002 3 Created: Thu Jan 17 11:19:58 2002
4 copyright 2002 by L.J. Potter <ljp@llornkcor.com> 4 copyright 2002 by L.J. Potter <ljp@llornkcor.com>
5****************************************************************************/ 5****************************************************************************/
6#define DEV_VERSION 6#define DEV_VERSION
7 7
8#include "pixmaps.h" 8#include "pixmaps.h"
9#include "qtrec.h" 9#include "qtrec.h"
10#include "waveform.h" 10#include "waveform.h"
11
12#include <pthread.h>
13
14extern "C" { 11extern "C" {
15#include "adpcm.h" 12#include "adpcm.h"
16} 13}
17 14
18#include <sys/soundcard.h> 15/* OPIE */
19 16#include <opie2/odebug.h>
20#include <qpe/config.h> 17#include <qpe/config.h>
21#include <qpe/qcopenvelope_qws.h> 18#include <qpe/qcopenvelope_qws.h>
22#include <qpe/qpeapplication.h> 19#include <qpe/qpeapplication.h>
23#include <qpe/resource.h> 20#include <qpe/resource.h>
24#include <qpe/storage.h> 21#include <qpe/storage.h>
22using namespace Opie::Core;
25 23
24/* QT */
26#include <qcheckbox.h> 25#include <qcheckbox.h>
27#include <qcombobox.h> 26#include <qcombobox.h>
28//#include <qdatetime.h>
29#include <qdir.h> 27#include <qdir.h>
30#include <qgroupbox.h> 28#include <qgroupbox.h>
31#include <qlabel.h> 29#include <qlabel.h>
32#include <qlayout.h> 30#include <qlayout.h>
33#include <qlistview.h> 31#include <qlistview.h>
34#include <qmessagebox.h> 32#include <qmessagebox.h>
35#include <qpopupmenu.h> 33#include <qpopupmenu.h>
36#include <qpushbutton.h> 34#include <qpushbutton.h>
37#include <qslider.h> 35#include <qslider.h>
38#include <qtabwidget.h> 36#include <qtabwidget.h>
39#include <qtimer.h> 37#include <qtimer.h>
40 38
39/* STD */
41#include <errno.h> 40#include <errno.h>
42#include <fcntl.h> 41#include <fcntl.h>
43#include <math.h> 42#include <math.h>
44#include <mntent.h> 43#include <mntent.h>
45#include <stdio.h> 44#include <stdio.h>
46#include <stdlib.h> 45#include <stdlib.h>
47#include <sys/ioctl.h> 46#include <sys/ioctl.h>
48#include <sys/soundcard.h> 47#include <sys/soundcard.h>
49#include <sys/stat.h> 48#include <sys/stat.h>
50#include <sys/time.h> 49#include <sys/time.h>
51#include <sys/types.h> 50#include <sys/types.h>
52#include <sys/vfs.h> 51#include <sys/vfs.h>
53#include <unistd.h> 52#include <unistd.h>
54#include <sys/wait.h> 53#include <sys/wait.h>
55#include <sys/signal.h> 54#include <sys/signal.h>
56 55#include <pthread.h>
57 56
58#ifdef PDAUDIO //ALSA 57#ifdef PDAUDIO //ALSA
59#include <alsa/asoundlib.h> 58#include <alsa/asoundlib.h>
60static int deviceSampleRates[8] = { 32000, 44100, 48000, 88200, 96000, 176400, 192000, -1 }; 59static int deviceSampleRates[8] = { 32000, 44100, 48000, 88200, 96000, 176400, 192000, -1 };
61static int deviceBitRates[] = { 8, 16, 24, 32, -1 }; 60static int deviceBitRates[] = { 8, 16, 24, 32, -1 };
62#else //OSS 61#else //OSS
63static int deviceSampleRates[6] = { 11025, 16000, 22050, 32000, 44100, -1 }; 62static int deviceSampleRates[6] = { 11025, 16000, 22050, 32000, 44100, -1 };
64static int deviceBitRates[] = { 8, 16, -1 }; 63static int deviceBitRates[] = { 8, 16, -1 };
65#endif 64#endif
66 65
67#if defined(QT_QWS_SL5XXX) 66#if defined(QT_QWS_SL5XXX)
68///#if defined(QT_QWS_EBX) 67///#if defined(QT_QWS_EBX)
69 68
70#define DSPSTROUT "/dev/dsp" 69#define DSPSTROUT "/dev/dsp"
71#define DSPSTRIN "/dev/dsp1" 70#define DSPSTRIN "/dev/dsp1"
72#define DSPSTRMIXEROUT "/dev/mixer" 71#define DSPSTRMIXEROUT "/dev/mixer"
73#define DSPSTRMIXERIN "/dev/mixer1" 72#define DSPSTRMIXERIN "/dev/mixer1"
74 73
75#else 74#else
76 75
77#define DSPSTROUT "/dev/dsp" 76#define DSPSTROUT "/dev/dsp"
78#define DSPSTRIN "/dev/dsp" 77#define DSPSTRIN "/dev/dsp"
79#define DSPSTRMIXERIN "/dev/mixer" 78#define DSPSTRMIXERIN "/dev/mixer"
80#define DSPSTRMIXEROUT "/dev/mixer" 79#define DSPSTRMIXEROUT "/dev/mixer"
81 80
82#endif 81#endif
83 82
84//#define ZAURUS 0 83//#define ZAURUS 0
85struct adpcm_state encoder_state; 84struct adpcm_state encoder_state;
86struct adpcm_state decoder_state; 85struct adpcm_state decoder_state;
87 86
88typedef struct { 87typedef struct {
89 int sampleRate; 88 int sampleRate;
90 /* int fragSize; */ 89 /* int fragSize; */
91 /* int blockSize; */ 90 /* int blockSize; */
92 int resolution; //bitrate 91 int resolution; //bitrate
93 int channels; //number of channels 92 int channels; //number of channels
94 int fd; //file descriptor 93 int fd; //file descriptor
95 int sd; //sound device descriptor 94 int sd; //sound device descriptor
96 int numberSamples; //total number of samples 95 int numberSamples; //total number of samples
97 int SecondsToRecord; // number of seconds that should be recorded 96 int SecondsToRecord; // number of seconds that should be recorded
98 float numberOfRecordedSeconds; //total number of samples recorded 97 float numberOfRecordedSeconds; //total number of samples recorded
99 int samplesToRecord; //number of samples to be recorded 98 int samplesToRecord; //number of samples to be recorded
100 int inVol; //input volume 99 int inVol; //input volume
101 int outVol; //output volume 100 int outVol; //output volume
102 int format; //wavfile format PCM.. ADPCM 101 int format; //wavfile format PCM.. ADPCM
103 const char *fileName; //name of fiel to be played/recorded 102 const char *fileName; //name of fiel to be played/recorded
104} fileParameters; 103} fileParameters;
105 104
106fileParameters filePara; 105fileParameters filePara;
107 106
108bool monitoring, recording, playing; 107bool monitoring, recording, playing;
109bool stopped; 108bool stopped;
110QLabel *timeLabel; 109QLabel *timeLabel;
111QSlider *timeSlider; 110QSlider *timeSlider;
112int sd; 111int sd;
113 112
114Waveform* waveform; 113Waveform* waveform;
115Device *soundDevice; 114Device *soundDevice;
116 115
117 116
118#ifdef THREADED 117#ifdef THREADED
119void quickRec() 118void quickRec()
120#else 119#else
121 void QtRec::quickRec() 120 void QtRec::quickRec()
122#endif 121#endif
123{ 122{
124 123
125 qDebug("%d", 124 qDebug("%d",
126 filePara.numberSamples/filePara.sampleRate * filePara.channels); 125 filePara.numberSamples/filePara.sampleRate * filePara.channels);
127 qDebug("samples %d, rate %d, channels %d", 126 qDebug("samples %d, rate %d, channels %d",
128 filePara.numberSamples, filePara.sampleRate, filePara.channels); 127 filePara.numberSamples, filePara.sampleRate, filePara.channels);
129 128
130 int total = 0; // Total number of bytes read in so far. 129 int total = 0; // Total number of bytes read in so far.
131 int bytesWritten, number; 130 int bytesWritten, number;
132 131
133 bytesWritten = 0; 132 bytesWritten = 0;
134 number = 0; 133 number = 0;
135 QString num; 134 QString num;
136 int level = 0; 135 int level = 0;
137 int threshold = 0; 136 int threshold = 0;
138// int bits = filePara.resolution; 137// int bits = filePara.resolution;
139// qDebug("bits %d", bits); 138// odebug << "bits " << bits << "" << oendl;
140 139
141 if( filePara.resolution == 16 ) { //AFMT_S16_LE) 140 if( filePara.resolution == 16 ) { //AFMT_S16_LE)
142// qDebug("AFMT_S16_LE size %d", filePara.SecondsToRecord); 141// odebug << "AFMT_S16_LE size " << filePara.SecondsToRecord << "" << oendl;
143// qDebug("samples to record %d", filePara.samplesToRecord); 142// odebug << "samples to record " << filePara.samplesToRecord << "" << oendl;
144// qDebug("%d", filePara.sd); 143// odebug << "" << filePara.sd << "" << oendl;
145 level = 7; 144 level = 7;
146 threshold = 0; 145 threshold = 0;
147 146
148 if( filePara.format == WAVE_FORMAT_DVI_ADPCM) { 147 if( filePara.format == WAVE_FORMAT_DVI_ADPCM) {
149// qDebug("start recording WAVE_FORMAT_DVI_ADPCM"); 148// odebug << "start recording WAVE_FORMAT_DVI_ADPCM" << oendl;
150 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>> 149 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>>
151 char abuf[ BUFSIZE/2 ]; 150 char abuf[ BUFSIZE/2 ];
152 short sbuf[ BUFSIZE ]; 151 short sbuf[ BUFSIZE ];
153 short sbuf2[ BUFSIZE ]; 152 short sbuf2[ BUFSIZE ];
154 memset( abuf, 0, BUFSIZE/2); 153 memset( abuf, 0, BUFSIZE/2);
155 memset( sbuf, 0, BUFSIZE); 154 memset( sbuf, 0, BUFSIZE);
156 memset( sbuf2, 0, BUFSIZE); 155 memset( sbuf2, 0, BUFSIZE);
157 156
158 for(;;) { 157 for(;;) {
159 if ( stopped) { 158 if ( stopped) {
160 // qDebug("quickRec:: stopped"); 159 // odebug << "quickRec:: stopped" << oendl;
161 break; 160 break;
162 } 161 }
163 162
164// number=::read( filePara.sd, sbuf, BUFSIZE); 163// number=::read( filePara.sd, sbuf, BUFSIZE);
165 number = soundDevice ->devRead( filePara.sd, sbuf, BUFSIZE); 164 number = soundDevice ->devRead( filePara.sd, sbuf, BUFSIZE);
166 165
167 if(number <= 0) { 166 if(number <= 0) {
168 perror("recording error "); 167 perror("recording error ");
169 qDebug( "%s %d", filePara.fileName, number); 168 odebug << "" << filePara.fileName << " " << number << "" << oendl;
170 stopped = true; 169 stopped = true;
171 return; 170 return;
172 } 171 }
173 //if(stereo == 2) { 172 //if(stereo == 2) {
174// adpcm_coder( sbuf2, abuf, number/2, &encoder_state); 173// adpcm_coder( sbuf2, abuf, number/2, &encoder_state);
175 adpcm_coder( sbuf, abuf, number/2, &encoder_state); 174 adpcm_coder( sbuf, abuf, number/2, &encoder_state);
176 175
177 bytesWritten = ::write( filePara.fd , (short *)abuf, number/4); 176 bytesWritten = ::write( filePara.fd , (short *)abuf, number/4);
178 177
179 waveform->newSamples( (const short *)abuf, bytesWritten ); 178 waveform->newSamples( (const short *)abuf, bytesWritten );
180 179
181 total += bytesWritten; 180 total += bytesWritten;
182 filePara.numberSamples = total; 181 filePara.numberSamples = total;
183 timeSlider->setValue( total); 182 timeSlider->setValue( total);
184 183
185 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate * (float)2 / filePara.channels; 184 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate * (float)2 / filePara.channels;
186 185
187 qApp->processEvents(); 186 qApp->processEvents();
188 if( total >= filePara.samplesToRecord) { 187 if( total >= filePara.samplesToRecord) {
189 stopped = true; 188 stopped = true;
190 break; 189 break;
191 } 190 }
192 } 191 }
193 } else { 192 } else {
194 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>> 193 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>>
195 qDebug("start recording WAVE_FORMAT_PCM"); 194 odebug << "start recording WAVE_FORMAT_PCM" << oendl;
196 short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ]; 195 short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ];
197 memset( inbuffer, 0, BUFSIZE); 196 memset( inbuffer, 0, BUFSIZE);
198 memset( outbuffer, 0, BUFSIZE); 197 memset( outbuffer, 0, BUFSIZE);
199 198
200 for(;;) { 199 for(;;) {
201 if ( stopped) { 200 if ( stopped) {
202 qDebug("quickRec:: stopped"); 201 odebug << "quickRec:: stopped" << oendl;
203 stopped = true; 202 stopped = true;
204 break; // stop if playing was set to false 203 break; // stop if playing was set to false
205 return; 204 return;
206 } 205 }
207 206
208 number = soundDevice->devRead( filePara.sd, (short *)inbuffer, BUFSIZE); 207 number = soundDevice->devRead( filePara.sd, (short *)inbuffer, BUFSIZE);
209 waveform->newSamples( inbuffer, number ); 208 waveform->newSamples( inbuffer, number );
210 209
211 if( number <= 0) { 210 if( number <= 0) {
212 perror( "recording error "); 211 perror( "recording error ");
213 qDebug( filePara.fileName); 212 odebug << filePara.fileName << oendl;
214 stopped = true; 213 stopped = true;
215 return; 214 return;
216 } 215 }
217 216
218 bytesWritten = ::write( filePara.fd , inbuffer, number); 217 bytesWritten = ::write( filePara.fd , inbuffer, number);
219 218
220 if( bytesWritten < 0) { 219 if( bytesWritten < 0) {
221 perror("File writing error "); 220 perror("File writing error ");
222 stopped = true; 221 stopped = true;
223 return; 222 return;
224 } 223 }
225 224
226 total += bytesWritten; 225 total += bytesWritten;
227 226
228 filePara.numberSamples = total; 227 filePara.numberSamples = total;
229 228
230 if( filePara.SecondsToRecord != 0) 229 if( filePara.SecondsToRecord != 0)
231 timeSlider->setValue( total); 230 timeSlider->setValue( total);
232// printf("Writing number %d, bytes %d,total %d\r",number, bytesWritten , total); 231// printf("Writing number %d, bytes %d,total %d\r",number, bytesWritten , total);
233// fflush(stdout); 232// fflush(stdout);
234 233
235 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2/filePara.channels; 234 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2/filePara.channels;
236 qApp->processEvents(); 235 qApp->processEvents();
237 236
238 if( total >= filePara.samplesToRecord) { 237 if( total >= filePara.samplesToRecord) {
239 stopped = true; 238 stopped = true;
240 break; 239 break;
241 } 240 }
242 } 241 }
243 } //end main loop 242 } //end main loop
244 243
245 } else { 244 } else {
246// <<<<<<<<<<<<<<<<<<<<<<< format = AFMT_U8; 245// <<<<<<<<<<<<<<<<<<<<<<< format = AFMT_U8;
247 unsigned char unsigned_inbuffer[ BUFSIZE ], unsigned_outbuffer[ BUFSIZE ]; 246 unsigned char unsigned_inbuffer[ BUFSIZE ], unsigned_outbuffer[ BUFSIZE ];
248 memset( unsigned_inbuffer, 0, BUFSIZE); 247 memset( unsigned_inbuffer, 0, BUFSIZE);
249 memset( unsigned_outbuffer, 0, BUFSIZE); 248 memset( unsigned_outbuffer, 0, BUFSIZE);
250 249
251 for(;;) { 250 for(;;) {
252 if ( stopped) { 251 if ( stopped) {
253 qDebug("quickRec:: stopped"); 252 odebug << "quickRec:: stopped" << oendl;
254 break; // stop if playing was set to false 253 break; // stop if playing was set to false
255 } 254 }
256 255
257 number = ::read( filePara.sd, unsigned_inbuffer, BUFSIZE); 256 number = ::read( filePara.sd, unsigned_inbuffer, BUFSIZE);
258 bytesWritten = ::write( filePara.fd , unsigned_inbuffer, number); 257 bytesWritten = ::write( filePara.fd , unsigned_inbuffer, number);
259 258
260 if(bytesWritten < 0) { 259 if(bytesWritten < 0) {
261 stopped = true; 260 stopped = true;
262 QMessageBox::message("Note","There was a problem\nwriting to the file"); 261 QMessageBox::message("Note","There was a problem\nwriting to the file");
263 perror("File writing error "); 262 perror("File writing error ");
264 return; 263 return;
265 } 264 }
266 265
267 total += bytesWritten; 266 total += bytesWritten;
268 filePara.numberSamples = total; 267 filePara.numberSamples = total;
269 // printf("\nWriting number %d, bytes %d,total %d \r",number, bytesWritten , total); 268 // printf("\nWriting number %d, bytes %d,total %d \r",number, bytesWritten , total);
270 // fflush(stdout); 269 // fflush(stdout);
271 if( filePara.SecondsToRecord !=0) 270 if( filePara.SecondsToRecord !=0)
272 timeSlider->setValue( total); 271 timeSlider->setValue( total);
273 272
274 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate; 273 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate;
275 274
276 qApp->processEvents(); 275 qApp->processEvents();
277 if( total >= filePara.samplesToRecord) { 276 if( total >= filePara.samplesToRecord) {
278 stopped = true; 277 stopped = true;
279 break; 278 break;
280 } 279 }
281 } //end main loop 280 } //end main loop
282 } 281 }
283} /// END quickRec() 282} /// END quickRec()
284 283
285 284
286#ifdef THREADED 285#ifdef THREADED
287void playIt() 286void playIt()
288#else 287#else
289 void QtRec::playIt() 288 void QtRec::playIt()
290#endif 289#endif
291{ 290{
292 int bytesWritten = 0; 291 int bytesWritten = 0;
293 int number = 0; 292 int number = 0;
294 int total = 0; // Total number of bytes read in so far. 293 int total = 0; // Total number of bytes read in so far.
295 if( filePara.resolution == 16 ) { //AFMT_S16_LE) { 294 if( filePara.resolution == 16 ) { //AFMT_S16_LE) {
296 if( filePara.format == WAVE_FORMAT_DVI_ADPCM) { 295 if( filePara.format == WAVE_FORMAT_DVI_ADPCM) {
297 char abuf[ BUFSIZE / 2 ]; 296 char abuf[ BUFSIZE / 2 ];
298 short sbuf[ BUFSIZE ]; 297 short sbuf[ BUFSIZE ];
299 short sbuf2[ BUFSIZE * 2 ]; 298 short sbuf2[ BUFSIZE * 2 ];
300 memset( abuf, 0, BUFSIZE / 2); 299 memset( abuf, 0, BUFSIZE / 2);
301 memset( sbuf, 0, BUFSIZE); 300 memset( sbuf, 0, BUFSIZE);
302 memset( sbuf2, 0, BUFSIZE * 2); 301 memset( sbuf2, 0, BUFSIZE * 2);
303// <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>> 302// <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>>
304 for(;;) { // play loop 303 for(;;) { // play loop
305 if ( stopped) { 304 if ( stopped) {
306 break; 305 break;
307 return; 306 return;
308 }// stop if playing was set to false 307 }// stop if playing was set to false
309 308
310 number = ::read( filePara.fd, abuf, BUFSIZE / 2); 309 number = ::read( filePara.fd, abuf, BUFSIZE / 2);
311 adpcm_decoder( abuf, sbuf, number * 2, &decoder_state); 310 adpcm_decoder( abuf, sbuf, number * 2, &decoder_state);
312 311
313// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel 312// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel
314// sbuf2[i+1]=sbuf2[i]=sbuf[i]; 313// sbuf2[i+1]=sbuf2[i]=sbuf[i];
315// } 314// }
316 bytesWritten = write ( filePara.sd, sbuf, number * 4); 315 bytesWritten = write ( filePara.sd, sbuf, number * 4);
317 waveform->newSamples( (const short *)sbuf, number ); 316 waveform->newSamples( (const short *)sbuf, number );
318 // if(filePara.channels==1) 317 // if(filePara.channels==1)
319 // total += bytesWritten/2; //mono 318 // total += bytesWritten/2; //mono
320 // else 319 // else
321 total += bytesWritten; 320 total += bytesWritten;
322 filePara.numberSamples = total/4; 321 filePara.numberSamples = total/4;
323 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / 2; 322 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / 2;
324 323
325 timeSlider->setValue( total/4); 324 timeSlider->setValue( total/4);
326// timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds); 325// timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds);
327// if(filePara.numberOfRecordedSeconds>1) 326// if(filePara.numberOfRecordedSeconds>1)
328// timeLabel->setText( timeString+ tr(" seconds")); 327// timeLabel->setText( timeString+ tr(" seconds"));
329 // printf("playing number %d, bytes %d, total %d\n",number, bytesWritten, total/4); 328 // printf("playing number %d, bytes %d, total %d\n",number, bytesWritten, total/4);
330 // fflush(stdout); 329 // fflush(stdout);
331 330
332 qApp->processEvents(); 331 qApp->processEvents();
333 332
334 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) { 333 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
335// if( total >= filePara.numberSamples ){//|| secCount > filePara.numberOfRecordedSeconds ) { 334// if( total >= filePara.numberSamples ){//|| secCount > filePara.numberOfRecordedSeconds ) {
336 stopped = true; 335 stopped = true;
337 break; 336 break;
338 } 337 }
339 } 338 }
340 } else { 339 } else {
341 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>> 340 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>>
342 short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ]; 341 short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ];
343 memset( inbuffer, 0, BUFSIZE); 342 memset( inbuffer, 0, BUFSIZE);
344 memset( outbuffer, 0, BUFSIZE); 343 memset( outbuffer, 0, BUFSIZE);
345 344
346 for(;;) { // play loop 345 for(;;) { // play loop
347 if ( stopped) { 346 if ( stopped) {
348 break; 347 break;
349 return; 348 return;
350 } 349 }
351// stop if playing was set to false 350// stop if playing was set to false
352 number = ::read( filePara.fd, inbuffer, BUFSIZE); 351 number = ::read( filePara.fd, inbuffer, BUFSIZE);
353// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel 352// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel
354// // for (int i=0;i< number ; i++) { //2*i is left channel 353// // for (int i=0;i< number ; i++) { //2*i is left channel
355// outbuffer[i+1]= outbuffer[i]=inbuffer[i]; 354// outbuffer[i+1]= outbuffer[i]=inbuffer[i];
356// } 355// }
357 bytesWritten = ::write( filePara.sd, inbuffer, number); 356 bytesWritten = ::write( filePara.sd, inbuffer, number);
358 waveform->newSamples( inbuffer, bytesWritten ); 357 waveform->newSamples( inbuffer, bytesWritten );
359 //-------------->>>> out to device 358 //-------------->>>> out to device
360 // total+=bytesWritten; 359 // total+=bytesWritten;
361 // if(filePara.channels==1) 360 // if(filePara.channels==1)
362 // total += bytesWritten/2; //mono 361 // total += bytesWritten/2; //mono
363 // else 362 // else
364 total += bytesWritten; 363 total += bytesWritten;
365 timeSlider->setValue( total); 364 timeSlider->setValue( total);
366 365
367 filePara.numberSamples = total; 366 filePara.numberSamples = total;
368 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2; 367 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2;
369 368
370// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds); 369// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds);
371// timeLabel->setText( timeString + tr(" seconds")); 370// timeLabel->setText( timeString + tr(" seconds"));
372 371
373 qApp->processEvents(); 372 qApp->processEvents();
374 373
375 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) { 374 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
376 qWarning("Jane! Stop this crazy thing!"); 375 owarn << "Jane! Stop this crazy thing!" << oendl;
377 stopped = true; 376 stopped = true;
378// playing = false; 377// playing = false;
379 break; 378 break;
380 } 379 }
381 } 380 }
382 printf("\nplaying number %d, bytes %d, total %d\r",number, bytesWritten, total); 381 printf("\nplaying number %d, bytes %d, total %d\r",number, bytesWritten, total);
383 fflush(stdout); 382 fflush(stdout);
384 } //end loop 383 } //end loop
385 } else { 384 } else {
386/////////////////////////////// format = AFMT_U8; 385/////////////////////////////// format = AFMT_U8;
387 unsigned char unsigned_inbuffer[ BUFSIZE ]; //, unsigned_outbuffer[BUFSIZE]; 386 unsigned char unsigned_inbuffer[ BUFSIZE ]; //, unsigned_outbuffer[BUFSIZE];
388 memset( unsigned_inbuffer, 0, BUFSIZE); 387 memset( unsigned_inbuffer, 0, BUFSIZE);
389 for(;;) { 388 for(;;) {
390// main loop 389// main loop
391 if (stopped) { 390 if (stopped) {
392 break; // stop if playing was set to false 391 break; // stop if playing was set to false
393 return; 392 return;
394 } 393 }
395 number = ::read( filePara.fd, unsigned_inbuffer, BUFSIZE); 394 number = ::read( filePara.fd, unsigned_inbuffer, BUFSIZE);
396//data = (val >> 8) ^ 0x80; 395//data = (val >> 8) ^ 0x80;
397 // unsigned_outbuffer = (unsigned_inbuffer >> 8) ^ 0x80; 396 // unsigned_outbuffer = (unsigned_inbuffer >> 8) ^ 0x80;
398 bytesWritten = write ( filePara.sd, unsigned_inbuffer, number); 397 bytesWritten = write ( filePara.sd, unsigned_inbuffer, number);
399 waveform->newSamples( (const short *)unsigned_inbuffer, bytesWritten ); 398 waveform->newSamples( (const short *)unsigned_inbuffer, bytesWritten );
400 total += bytesWritten; 399 total += bytesWritten;
401 400
402 timeSlider->setValue( total); 401 timeSlider->setValue( total);
403 filePara.numberSamples = total; 402 filePara.numberSamples = total;
404 403
405 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate; 404 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate;
406// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds); 405// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds);
407// timeLabel->setText( timeString + tr(" seconds")); 406// timeLabel->setText( timeString + tr(" seconds"));
408 qApp->processEvents(); 407 qApp->processEvents();
409 408
410 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) { 409 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
411// if( total >= filePara.numberSamples ) { 410// if( total >= filePara.numberSamples ) {
412 stopped = true; 411 stopped = true;
413 break; 412 break;
414 } 413 }
415 // printf("Writing number %d, bytes %d, total %d, numberSamples %d\r",number, bytesWritten , total, filePara.numberSamples); 414 // printf("Writing number %d, bytes %d, total %d, numberSamples %d\r",number, bytesWritten , total, filePara.numberSamples);
416 // fflush(stdout); 415 // fflush(stdout);
417 } 416 }
418 } 417 }
419} 418}
420 419
421 420
422QtRec::QtRec( QWidget* parent, const char* name, WFlags fl ) 421QtRec::QtRec( QWidget* parent, const char* name, WFlags fl )
423 : QWidget( parent, name, fl ) 422 : QWidget( parent, name, fl )
424{ 423{
425 if ( !name ) 424 if ( !name )
426 setName( "OpieRec" ); 425 setName( "OpieRec" );
427 init(); 426 init();
428 initConfig(); 427 initConfig();
429 initConnections(); 428 initConnections();
430 renameBox = 0; 429 renameBox = 0;
431 430
432// open sound device to get volumes 431// open sound device to get volumes
433 Config hwcfg("OpieRec"); 432 Config hwcfg("OpieRec");
434 hwcfg.setGroup("Hardware"); 433 hwcfg.setGroup("Hardware");
435 434
436 435
437 soundDevice = new Device( this, 436 soundDevice = new Device( this,
438 hwcfg.readEntry( "Audio",DSPSTROUT), 437 hwcfg.readEntry( "Audio",DSPSTROUT),
439 hwcfg.readEntry( "Mixer",DSPSTRMIXEROUT), false); 438 hwcfg.readEntry( "Mixer",DSPSTRMIXEROUT), false);
440 // soundDevice = new Device( this, hwcfg.readEntry( "Audio","hw:0"), hwcfg.readEntry( "Mixer","hw:0"), false); 439 // soundDevice = new Device( this, hwcfg.readEntry( "Audio","hw:0"), hwcfg.readEntry( "Mixer","hw:0"), false);
441 440
442// soundDevice->setDeviceFormat(AFMT_S16_LE); 441// soundDevice->setDeviceFormat(AFMT_S16_LE);
443// soundDevice->setDeviceChannels(1); 442// soundDevice->setDeviceChannels(1);
444// soundDevice->setDeviceRate( 22050); 443// soundDevice->setDeviceRate( 22050);
445 444
446 getInVol(); 445 getInVol();
447 getOutVol(); 446 getOutVol();
448 447
449 soundDevice->closeDevice( true); 448 soundDevice->closeDevice( true);
450 soundDevice->sd = -1; 449 soundDevice->sd = -1;
451 soundDevice = 0; 450 soundDevice = 0;
452 wavFile = 0; 451 wavFile = 0;
453 452
454 if( soundDevice) delete soundDevice; 453 if( soundDevice) delete soundDevice;
455 454
456 initIconView(); 455 initIconView();
457 456
458 if( autoMute) 457 if( autoMute)
459 doMute( true); 458 doMute( true);
460 ListView1->setFocus(); 459 ListView1->setFocus();
461 playing = false; 460 playing = false;
462} 461}
463 462
464QtRec::~QtRec() { 463QtRec::~QtRec() {
465 464
466} 465}
467 466
468void QtRec::cleanUp() { 467void QtRec::cleanUp() {
469 468
470 if( !stopped) { 469 if( !stopped) {
471 stopped = true; 470 stopped = true;
472 endRecording(); 471 endRecording();
@@ -625,1477 +624,1477 @@ void QtRec::init() {
625 624
626 glayout3->addMultiCellWidget( dirGroup, 1, 1, 0, 0); 625 glayout3->addMultiCellWidget( dirGroup, 1, 1, 0, 0);
627 626
628 bitGroup = new QGroupBox( tab_3, "bitGroup" ); 627 bitGroup = new QGroupBox( tab_3, "bitGroup" );
629 bitGroup->setTitle( tr( "Bit Depth" ) ); 628 bitGroup->setTitle( tr( "Bit Depth" ) );
630 bitGroup->setFixedSize( 65, 50); 629 bitGroup->setFixedSize( 65, 50);
631 630
632 bitRateComboBox = new QComboBox( false, bitGroup, "BitRateComboBox" ); 631 bitRateComboBox = new QComboBox( false, bitGroup, "BitRateComboBox" );
633 632
634 z = 0; 633 z = 0;
635 while( deviceBitRates[z] != -1) { 634 while( deviceBitRates[z] != -1) {
636 bitRateComboBox->insertItem( s.setNum( deviceBitRates[z], 10) ); 635 bitRateComboBox->insertItem( s.setNum( deviceBitRates[z], 10) );
637 z++; 636 z++;
638 } 637 }
639 638
640 bitRateComboBox->setGeometry( QRect( 5, 20, 50, 25 ) ); 639 bitRateComboBox->setGeometry( QRect( 5, 20, 50, 25 ) );
641 640
642 glayout3->addMultiCellWidget( bitGroup, 1, 1, 1, 1); 641 glayout3->addMultiCellWidget( bitGroup, 1, 1, 1, 1);
643 642
644 compressionCheckBox = new QCheckBox ( tr("Wave Compression (smaller files)"), tab_3 ); 643 compressionCheckBox = new QCheckBox ( tr("Wave Compression (smaller files)"), tab_3 );
645 644
646 autoMuteCheckBox = new QCheckBox ( tr("Auto Mute"), tab_3 ); 645 autoMuteCheckBox = new QCheckBox ( tr("Auto Mute"), tab_3 );
647 stereoCheckBox = new QCheckBox ( tr("Stereo Channels"), tab_3 ); 646 stereoCheckBox = new QCheckBox ( tr("Stereo Channels"), tab_3 );
648 647
649 glayout3->addMultiCellWidget( compressionCheckBox, 2, 2, 0, 3); 648 glayout3->addMultiCellWidget( compressionCheckBox, 2, 2, 0, 3);
650 glayout3->addMultiCellWidget( autoMuteCheckBox, 3, 3, 0, 0); 649 glayout3->addMultiCellWidget( autoMuteCheckBox, 3, 3, 0, 0);
651 glayout3->addMultiCellWidget( stereoCheckBox, 3, 3, 1, 1); 650 glayout3->addMultiCellWidget( stereoCheckBox, 3, 3, 1, 1);
652 651
653 tab_5 = new QWidget( TabWidget, "tab_5" ); 652 tab_5 = new QWidget( TabWidget, "tab_5" );
654 653
655 QHBoxLayout *Layout19a; 654 QHBoxLayout *Layout19a;
656 Layout19a = new QHBoxLayout( tab_5); 655 Layout19a = new QHBoxLayout( tab_5);
657 Layout19a->setSpacing( 2 ); 656 Layout19a->setSpacing( 2 );
658 Layout19a->setMargin( 0 ); 657 Layout19a->setMargin( 0 );
659 658
660 Layout15 = new QVBoxLayout( this); 659 Layout15 = new QVBoxLayout( this);
661 Layout15->setSpacing( 2 ); 660 Layout15->setSpacing( 2 );
662 Layout15->setMargin( 0 ); 661 Layout15->setMargin( 0 );
663 662
664 Layout15b = new QVBoxLayout( this); 663 Layout15b = new QVBoxLayout( this);
665 Layout15b->setSpacing( 2 ); 664 Layout15b->setSpacing( 2 );
666 Layout15b->setMargin( 0 ); 665 Layout15b->setMargin( 0 );
667 666
668 TextLabel2 = new QLabel( tab_5, "InputLabel" ); 667 TextLabel2 = new QLabel( tab_5, "InputLabel" );
669 TextLabel2->setText( tr( "In")); 668 TextLabel2->setText( tr( "In"));
670 TextLabel2->setFixedWidth( 35); 669 TextLabel2->setFixedWidth( 35);
671 Layout15->addWidget( TextLabel2 ); 670 Layout15->addWidget( TextLabel2 );
672 671
673 TextLabel3 = new QLabel( tab_5, "OutputLabel" ); 672 TextLabel3 = new QLabel( tab_5, "OutputLabel" );
674 TextLabel3->setText( tr( "Out" ) ); 673 TextLabel3->setText( tr( "Out" ) );
675 Layout15b->addWidget( TextLabel3 ); 674 Layout15b->addWidget( TextLabel3 );
676 675
677 InputSlider = new QSlider( -100, 0, 10, 0, QSlider::Vertical, tab_5, (const char *) "InputSlider" ); 676 InputSlider = new QSlider( -100, 0, 10, 0, QSlider::Vertical, tab_5, (const char *) "InputSlider" );
678 InputSlider->setTickmarks( QSlider::Both); 677 InputSlider->setTickmarks( QSlider::Both);
679 Layout15->addWidget( InputSlider); 678 Layout15->addWidget( InputSlider);
680 679
681 OutputSlider = new QSlider( -100,0,10,0, QSlider::Vertical,tab_5,(const char *) "OutputSlider" ); 680 OutputSlider = new QSlider( -100,0,10,0, QSlider::Vertical,tab_5,(const char *) "OutputSlider" );
682 OutputSlider->setTickmarks( QSlider::Both); 681 OutputSlider->setTickmarks( QSlider::Both);
683 682
684 Layout15b->addWidget( OutputSlider ); 683 Layout15b->addWidget( OutputSlider );
685 684
686 outMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 ); 685 outMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 );
687 Layout15->addWidget( outMuteCheckBox ); 686 Layout15->addWidget( outMuteCheckBox );
688 687
689 inMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 ); 688 inMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 );
690 inMuteCheckBox-> setFocusPolicy ( QWidget::NoFocus ); 689 inMuteCheckBox-> setFocusPolicy ( QWidget::NoFocus );
691 Layout15b->addWidget( inMuteCheckBox ); 690 Layout15b->addWidget( inMuteCheckBox );
692 691
693 692
694 Layout19a->addLayout( Layout15 ); 693 Layout19a->addLayout( Layout15 );
695 Layout19a->addLayout( Layout15b ); 694 Layout19a->addLayout( Layout15b );
696 695
697 fillDirectoryCombo(); 696 fillDirectoryCombo();
698 697
699 TabWidget->insertTab( tab_3, tr( "Options" ) ); 698 TabWidget->insertTab( tab_3, tr( "Options" ) );
700 699
701 TabWidget->insertTab( tab_5, tr( "Volume" ) ); 700 TabWidget->insertTab( tab_5, tr( "Volume" ) );
702 701
703 702
704 waveform = new Waveform( this, "waveform" ); 703 waveform = new Waveform( this, "waveform" );
705// waveform->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)3, waveform->sizePolicy().hasHeightForWidth() ) ); 704// waveform->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)3, waveform->sizePolicy().hasHeightForWidth() ) );
706 waveform->setMinimumSize( QSize( 0, 50 ) ); 705 waveform->setMinimumSize( QSize( 0, 50 ) );
707 706
708 layout->addMultiCellWidget( waveform, 8, 8, 0, 7 ); 707 layout->addMultiCellWidget( waveform, 8, 8, 0, 7 );
709 waveform->setBackgroundColor ( black ); 708 waveform->setBackgroundColor ( black );
710} 709}
711 710
712void QtRec::initIconView() { 711void QtRec::initIconView() {
713 712
714 ListView1->clear(); 713 ListView1->clear();
715 Config cfg("OpieRec"); 714 Config cfg("OpieRec");
716 cfg.setGroup("Sounds"); 715 cfg.setGroup("Sounds");
717 QString temp; 716 QString temp;
718 QPixmap image0( ( const char** ) image0_data ); 717 QPixmap image0( ( const char** ) image0_data );
719 718
720 int nFiles = cfg.readNumEntry("NumberofFiles",0); 719 int nFiles = cfg.readNumEntry("NumberofFiles",0);
721 // qDebug("init number of files %d", nFiles); 720 // odebug << "init number of files " << nFiles << "" << oendl;
722 721
723 for(int i=1;i<= nFiles;i++) { 722 for(int i=1;i<= nFiles;i++) {
724 723
725 QListViewItem * item; 724 QListViewItem * item;
726 QString fileS, mediaLocation, fileDate, filePath; 725 QString fileS, mediaLocation, fileDate, filePath;
727 726
728 temp.sprintf( "%d",i); 727 temp.sprintf( "%d",i);
729 temp = cfg.readEntry( temp,""); //reads currentFile 728 temp = cfg.readEntry( temp,""); //reads currentFile
730 filePath = cfg.readEntry( temp,""); //currentFileName 729 filePath = cfg.readEntry( temp,""); //currentFileName
731 730
732 QFileInfo info(filePath); 731 QFileInfo info(filePath);
733 fileDate = info.lastModified().toString(); 732 fileDate = info.lastModified().toString();
734 733
735 fileS = cfg.readEntry( filePath, "0" );// file length in seconds 734 fileS = cfg.readEntry( filePath, "0" );// file length in seconds
736 mediaLocation = getStorage( filePath); 735 mediaLocation = getStorage( filePath);
737 if( info.exists()) { 736 if( info.exists()) {
738 item = new QListViewItem( ListView1, temp, fileS, mediaLocation, fileDate); 737 item = new QListViewItem( ListView1, temp, fileS, mediaLocation, fileDate);
739 item->setPixmap( 0, image0); 738 item->setPixmap( 0, image0);
740 if( currentFileName == filePath) 739 if( currentFileName == filePath)
741 ListView1->setSelected( item, true); 740 ListView1->setSelected( item, true);
742 } 741 }
743 } 742 }
744} 743}
745 744
746void QtRec::initConnections() { 745void QtRec::initConnections() {
747 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 746 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
748 747
749 connect( toBeginningButton, SIGNAL( pressed()), 748 connect( toBeginningButton, SIGNAL( pressed()),
750 this, SLOT( rewindPressed() )); 749 this, SLOT( rewindPressed() ));
751 connect( toBeginningButton, SIGNAL( released()), 750 connect( toBeginningButton, SIGNAL( released()),
752 this, SLOT( rewindReleased() )); 751 this, SLOT( rewindReleased() ));
753 connect( toEndButton, SIGNAL( pressed()), 752 connect( toEndButton, SIGNAL( pressed()),
754 this, SLOT( FastforwardPressed() )); 753 this, SLOT( FastforwardPressed() ));
755 connect( toEndButton, SIGNAL( released()), 754 connect( toEndButton, SIGNAL( released()),
756 this, SLOT( FastforwardReleased() )); 755 this, SLOT( FastforwardReleased() ));
757 connect( deleteSoundButton, SIGNAL(released()), 756 connect( deleteSoundButton, SIGNAL(released()),
758 this, SLOT( deleteSound() )); 757 this, SLOT( deleteSound() ));
759 connect( Stop_PushButton, SIGNAL(released()), 758 connect( Stop_PushButton, SIGNAL(released()),
760 this, SLOT( doPlayBtn() )); 759 this, SLOT( doPlayBtn() ));
761 connect( Rec_PushButton, SIGNAL(released()), 760 connect( Rec_PushButton, SIGNAL(released()),
762 this, SLOT( newSound() ) ); 761 this, SLOT( newSound() ) );
763 connect( TabWidget, SIGNAL( currentChanged(QWidget*)), 762 connect( TabWidget, SIGNAL( currentChanged(QWidget*)),
764 this, SLOT(thisTab(QWidget*) )); 763 this, SLOT(thisTab(QWidget*) ));
765 connect( OutputSlider, SIGNAL(sliderReleased()), 764 connect( OutputSlider, SIGNAL(sliderReleased()),
766 this, SLOT( changedOutVolume()) ); 765 this, SLOT( changedOutVolume()) );
767 connect( InputSlider, SIGNAL(sliderReleased()), 766 connect( InputSlider, SIGNAL(sliderReleased()),
768 this, SLOT( changedInVolume()) ); 767 this, SLOT( changedInVolume()) );
769 768
770 connect( sampleRateComboBox, SIGNAL(activated(int)), 769 connect( sampleRateComboBox, SIGNAL(activated(int)),
771 this, SLOT( changesamplerateCombo(int)) ); 770 this, SLOT( changesamplerateCombo(int)) );
772 connect( bitRateComboBox, SIGNAL(activated(int)), 771 connect( bitRateComboBox, SIGNAL(activated(int)),
773 this, SLOT( changebitrateCombo(int)) ); 772 this, SLOT( changebitrateCombo(int)) );
774 773
775 connect( directoryComboBox, SIGNAL(activated(int)), 774 connect( directoryComboBox, SIGNAL(activated(int)),
776 this, SLOT( changeDirCombo(int)) ); 775 this, SLOT( changeDirCombo(int)) );
777 connect( sizeLimitCombo, SIGNAL(activated(int)), 776 connect( sizeLimitCombo, SIGNAL(activated(int)),
778 this, SLOT( changeSizeLimitCombo(int)) ); 777 this, SLOT( changeSizeLimitCombo(int)) );
779 778
780 connect( stereoCheckBox, SIGNAL(toggled(bool)), 779 connect( stereoCheckBox, SIGNAL(toggled(bool)),
781 this, SLOT( changeStereoCheck(bool)) ); 780 this, SLOT( changeStereoCheck(bool)) );
782 781
783 connect( outMuteCheckBox, SIGNAL(toggled(bool)), 782 connect( outMuteCheckBox, SIGNAL(toggled(bool)),
784 this, SLOT( doVolMuting(bool)) ); 783 this, SLOT( doVolMuting(bool)) );
785 connect( inMuteCheckBox , SIGNAL(toggled(bool)), 784 connect( inMuteCheckBox , SIGNAL(toggled(bool)),
786 this, SLOT( doMicMuting(bool)) ); 785 this, SLOT( doMicMuting(bool)) );
787 786
788 connect( ListView1,SIGNAL(doubleClicked(QListViewItem*)), 787 connect( ListView1,SIGNAL(doubleClicked(QListViewItem*)),
789 this,SLOT( itClick(QListViewItem*))); 788 this,SLOT( itClick(QListViewItem*)));
790 connect( ListView1, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), 789 connect( ListView1, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
791 this,SLOT( listPressed(int,QListViewItem*,const QPoint&,int)) ); 790 this,SLOT( listPressed(int,QListViewItem*,const QPoint&,int)) );
792 connect( timeSlider, SIGNAL( sliderMoved(int)), 791 connect( timeSlider, SIGNAL( sliderMoved(int)),
793 this, SLOT( changeTimeSlider(int) )); 792 this, SLOT( changeTimeSlider(int) ));
794 connect( timeSlider, SIGNAL( sliderPressed()), 793 connect( timeSlider, SIGNAL( sliderPressed()),
795 this, SLOT( timeSliderPressed() )); 794 this, SLOT( timeSliderPressed() ));
796 connect( timeSlider, SIGNAL( sliderReleased()), 795 connect( timeSlider, SIGNAL( sliderReleased()),
797 this, SLOT( timeSliderReleased() )); 796 this, SLOT( timeSliderReleased() ));
798 connect( compressionCheckBox, SIGNAL( toggled(bool)), 797 connect( compressionCheckBox, SIGNAL( toggled(bool)),
799 this, SLOT( compressionSelected(bool))); 798 this, SLOT( compressionSelected(bool)));
800 connect( autoMuteCheckBox, SIGNAL( toggled(bool)), 799 connect( autoMuteCheckBox, SIGNAL( toggled(bool)),
801 this, SLOT( slotAutoMute(bool))); 800 this, SLOT( slotAutoMute(bool)));
802} 801}
803 802
804void QtRec::initConfig() { 803void QtRec::initConfig() {
805 int index, fred, i; 804 int index, fred, i;
806 Config cfg("OpieRec"); 805 Config cfg("OpieRec");
807 cfg.setGroup("Settings"); 806 cfg.setGroup("Settings");
808 807
809 index = cfg.readNumEntry("samplerate",22050); 808 index = cfg.readNumEntry("samplerate",22050);
810 bool ok; 809 bool ok;
811 810
812 for(int ws=0;ws<sampleRateComboBox->count();ws++) { 811 for(int ws=0;ws<sampleRateComboBox->count();ws++) {
813 fred = sampleRateComboBox->text(ws).toInt(&ok, 10); 812 fred = sampleRateComboBox->text(ws).toInt(&ok, 10);
814 if( index == fred) { 813 if( index == fred) {
815 filePara.sampleRate = fred; 814 filePara.sampleRate = fred;
816 sampleRateComboBox->setCurrentItem(ws); 815 sampleRateComboBox->setCurrentItem(ws);
817 } 816 }
818 } 817 }
819 818
820 i = cfg.readNumEntry("bitrate",16); 819 i = cfg.readNumEntry("bitrate",16);
821 if(i == 16) 820 if(i == 16)
822 bitRateComboBox->setCurrentItem( 1); 821 bitRateComboBox->setCurrentItem( 1);
823 elseif(i == 24) 822 elseif(i == 24)
824 bitRateComboBox->setCurrentItem( 2); 823 bitRateComboBox->setCurrentItem( 2);
825 elseif(i == 32) 824 elseif(i == 32)
826 bitRateComboBox->setCurrentItem( 3); 825 bitRateComboBox->setCurrentItem( 3);
827 else 826 else
828 bitRateComboBox->setCurrentItem( 0); 827 bitRateComboBox->setCurrentItem( 0);
829 828
830 filePara.resolution = i; 829 filePara.resolution = i;
831 830
832 i = cfg.readNumEntry("sizeLimit", 5 ); 831 i = cfg.readNumEntry("sizeLimit", 5 );
833 QString temp; 832 QString temp;
834 sizeLimitCombo->setCurrentItem((i/5)); 833 sizeLimitCombo->setCurrentItem((i/5));
835 834
836 stereoCheckBox->setChecked( cfg.readBoolEntry("stereo", 1)); 835 stereoCheckBox->setChecked( cfg.readBoolEntry("stereo", 1));
837 if( stereoCheckBox->isChecked()) { 836 if( stereoCheckBox->isChecked()) {
838 filePara.channels = 2; 837 filePara.channels = 2;
839 } else { 838 } else {
840 filePara.channels = 1; 839 filePara.channels = 1;
841 } 840 }
842 841
843 compressionCheckBox->setChecked( cfg.readBoolEntry("wavCompression",1)); 842 compressionCheckBox->setChecked( cfg.readBoolEntry("wavCompression",1));
844 if( compressionCheckBox->isChecked()) { 843 if( compressionCheckBox->isChecked()) {
845 bitRateComboBox->setEnabled(false); 844 bitRateComboBox->setEnabled(false);
846 bitRateComboBox->setCurrentItem(0); 845 bitRateComboBox->setCurrentItem(0);
847 filePara.resolution=16; 846 filePara.resolution=16;
848 } 847 }
849 848
850 autoMuteCheckBox->setChecked( cfg.readBoolEntry("useAutoMute",0)); 849 autoMuteCheckBox->setChecked( cfg.readBoolEntry("useAutoMute",0));
851 if( autoMuteCheckBox->isChecked()) 850 if( autoMuteCheckBox->isChecked())
852 slotAutoMute(true); 851 slotAutoMute(true);
853 else 852 else
854 slotAutoMute(false); 853 slotAutoMute(false);
855 854
856 Config cofg( "qpe"); 855 Config cofg( "qpe");
857 cofg.setGroup( "Volume"); 856 cofg.setGroup( "Volume");
858 outMuteCheckBox->setChecked( cofg.readBoolEntry( "Mute",0)); 857 outMuteCheckBox->setChecked( cofg.readBoolEntry( "Mute",0));
859 inMuteCheckBox->setChecked( cofg.readBoolEntry( "MicMute",0)); 858 inMuteCheckBox->setChecked( cofg.readBoolEntry( "MicMute",0));
860} 859}
861 860
862void QtRec::stop() { 861void QtRec::stop() {
863 qWarning("STOP"); 862 owarn << "STOP" << oendl;
864 setRecordButton(false); 863 setRecordButton(false);
865 864
866 if( !recording) 865 if( !recording)
867 endPlaying(); 866 endPlaying();
868 else 867 else
869 endRecording(); 868 endRecording();
870 timeSlider->setValue(0); 869 timeSlider->setValue(0);
871} 870}
872 871
873void QtRec::doPlayBtn() { 872void QtRec::doPlayBtn() {
874 873
875 if(!stopped) { 874 if(!stopped) {
876 playLabel2->setText(tr("Play")); 875 playLabel2->setText(tr("Play"));
877 stop(); 876 stop();
878 } else { 877 } else {
879 if(ListView1->currentItem() == 0) return; 878 if(ListView1->currentItem() == 0) return;
880 playLabel2->setText(tr("Stop")); 879 playLabel2->setText(tr("Stop"));
881 currentFile = ListView1->currentItem()->text(0); 880 currentFile = ListView1->currentItem()->text(0);
882 start(); 881 start();
883 } 882 }
884} 883}
885 884
886void QtRec::start() { //play 885void QtRec::start() { //play
887 if( stopped) { 886 if( stopped) {
888 QPixmap image3( ( const char** ) image3_data ); 887 QPixmap image3( ( const char** ) image3_data );
889 Stop_PushButton->setPixmap( image3 ); 888 Stop_PushButton->setPixmap( image3 );
890 Stop_PushButton->setDown( true); 889 Stop_PushButton->setDown( true);
891 stopped = false; 890 stopped = false;
892 paused = false; 891 paused = false;
893 secCount = 1; 892 secCount = 1;
894 893
895 if( openPlayFile()) 894 if( openPlayFile())
896 if( setupAudio( false)) //recording is false 895 if( setupAudio( false)) //recording is false
897 doPlay(); 896 doPlay();
898 } 897 }
899} 898}
900 899
901bool QtRec::rec() { //record 900bool QtRec::rec() { //record
902 QString timeString; 901 QString timeString;
903 timeString.sprintf("%.0f", 0.0); 902 timeString.sprintf("%.0f", 0.0);
904 timeLabel->setText( timeString+ " seconds"); 903 timeLabel->setText( timeString+ " seconds");
905 if(!stopped) { 904 if(!stopped) {
906 monitoring = true; 905 monitoring = true;
907 return false; 906 return false;
908 } else { 907 } else {
909 secCount = 1; 908 secCount = 1;
910 playLabel2->setText(tr("Stop")); 909 playLabel2->setText(tr("Stop"));
911 monitoring = false; 910 monitoring = false;
912 setRecordButton( true); 911 setRecordButton( true);
913 912
914 if( setupAudio( true)) 913 if( setupAudio( true))
915 if(setUpFile()) { 914 if(setUpFile()) {
916 int fileSize = 0; 915 int fileSize = 0;
917 Config cfg("OpieRec"); 916 Config cfg("OpieRec");
918 cfg.setGroup("Settings"); 917 cfg.setGroup("Settings");
919// qDebug( "<<<<<<<Device bits %d, device rate %d, device channels %d", 918// qDebug( "<<<<<<<Device bits %d, device rate %d, device channels %d",
920// soundDevice->getDeviceBits(), 919// soundDevice->getDeviceBits(),
921// soundDevice->getDeviceRate(), 920// soundDevice->getDeviceRate(),
922// soundDevice->getDeviceChannels()); 921// soundDevice->getDeviceChannels());
923 922
924 //filePara.sampleRate = cfg.readNumEntry("samplerate", 22050); 923 //filePara.sampleRate = cfg.readNumEntry("samplerate", 22050);
925// qDebug("sample rate is %d", filePara.sampleRate); 924// odebug << "sample rate is " << filePara.sampleRate << "" << oendl;
926 filePara.SecondsToRecord = getCurrentSizeLimit(); 925 filePara.SecondsToRecord = getCurrentSizeLimit();
927 926
928// qDebug("size limit %d sec", filePara.SecondsToRecord); 927// odebug << "size limit " << filePara.SecondsToRecord << " sec" << oendl;
929 int diskSize = checkDiskSpace( (const QString &) wavFile->trackName()); 928 int diskSize = checkDiskSpace( (const QString &) wavFile->trackName());
930 929
931 if( filePara.SecondsToRecord == 0) { 930 if( filePara.SecondsToRecord == 0) {
932 fileSize = diskSize; 931 fileSize = diskSize;
933 } else if( filePara.format == WAVE_FORMAT_PCM) { 932 } else if( filePara.format == WAVE_FORMAT_PCM) {
934// qDebug("WAVE_FORMAT_PCM"); 933// odebug << "WAVE_FORMAT_PCM" << oendl;
935 fileSize = (filePara.SecondsToRecord ) * filePara.channels 934 fileSize = (filePara.SecondsToRecord ) * filePara.channels
936 * filePara.sampleRate * ( filePara.resolution / 8) + 1000; 935 * filePara.sampleRate * ( filePara.resolution / 8) + 1000;
937 } else { 936 } else {
938// qDebug("WAVE_FORMAT_DVI_ADPCM"); 937// odebug << "WAVE_FORMAT_DVI_ADPCM" << oendl;
939 fileSize = ((filePara.SecondsToRecord) * filePara.channels 938 fileSize = ((filePara.SecondsToRecord) * filePara.channels
940 * filePara.sampleRate * ( filePara.resolution / 8) ) / 4 + 250; 939 * filePara.sampleRate * ( filePara.resolution / 8) ) / 4 + 250;
941 } 940 }
942 941
943 filePara.samplesToRecord = fileSize; 942 filePara.samplesToRecord = fileSize;
944 qDebug("filesize should be %d, bits %d, rate %d", 943 qDebug("filesize should be %d, bits %d, rate %d",
945 filePara.samplesToRecord, filePara.resolution, filePara.sampleRate); 944 filePara.samplesToRecord, filePara.resolution, filePara.sampleRate);
946 if( paused) { 945 if( paused) {
947 paused = false; 946 paused = false;
948 } 947 }
949 // else { 948 // else {
950 qDebug("Setting timeslider %d", filePara.samplesToRecord); 949 odebug << "Setting timeslider " << filePara.samplesToRecord << "" << oendl;
951 // if(fileSize != 0) 950 // if(fileSize != 0)
952 timeSlider->setRange(0, filePara.samplesToRecord); 951 timeSlider->setRange(0, filePara.samplesToRecord);
953 // } 952 // }
954 953
955 if( diskSize < fileSize/1024) { 954 if( diskSize < fileSize/1024) {
956 QMessageBox::warning(this, 955 QMessageBox::warning(this,
957 tr("Low Disk Space"), 956 tr("Low Disk Space"),
958 tr("You are running low of\nrecording space\n" 957 tr("You are running low of\nrecording space\n"
959 "or a card isn't being recognized")); 958 "or a card isn't being recognized"));
960 stopped = true; //we need to be stopped 959 stopped = true; //we need to be stopped
961 stop(); 960 stop();
962 } else { 961 } else {
963 QString msg; 962 QString msg;
964 msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution); 963 msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution);
965#ifdef DEV_VERSION 964#ifdef DEV_VERSION
966 setCaption( msg); 965 setCaption( msg);
967#endif 966#endif
968 filePara.fileName=currentFile.latin1(); 967 filePara.fileName=currentFile.latin1();
969 qDebug("Start recording thread"); 968 odebug << "Start recording thread" << oendl;
970 stopped = false; 969 stopped = false;
971 970
972#ifdef THREADED 971#ifdef THREADED
973 pthread_t thread1; 972 pthread_t thread1;
974 pthread_create( &thread1, NULL, (void * (*)(void *))quickRec, NULL/* &*/); 973 pthread_create( &thread1, NULL, (void * (*)(void *))quickRec, NULL/* &*/);
975#endif 974#endif
976 toBeginningButton->setEnabled( false); 975 toBeginningButton->setEnabled( false);
977 toEndButton->setEnabled( false); 976 toEndButton->setEnabled( false);
978 977
979 startTimer(1000); 978 startTimer(1000);
980#ifndef THREADED 979#ifndef THREADED
981 quickRec(); 980 quickRec();
982#endif 981#endif
983 } 982 }
984 } //end setUpFile 983 } //end setUpFile
985 } //end setupAudio 984 } //end setupAudio
986 return true; 985 return true;
987} 986}
988/* 987/*
989 This happens when a tab is selected*/ 988 This happens when a tab is selected*/
990void QtRec::thisTab(QWidget* widg) { 989void QtRec::thisTab(QWidget* widg) {
991 if(widg != NULL) { 990 if(widg != NULL) {
992 int index = TabWidget->currentPageIndex(); 991 int index = TabWidget->currentPageIndex();
993 992
994 if(index == 0) { //file page 993 if(index == 0) { //file page
995 } 994 }
996 995
997 if(index == 1) { //control page 996 if(index == 1) { //control page
998 fillDirectoryCombo(); 997 fillDirectoryCombo();
999// soundDevice->getOutVol(); 998// soundDevice->getOutVol();
1000// soundDevice->getInVol(); 999// soundDevice->getInVol();
1001 } 1000 }
1002 1001
1003 if( index==2) { //help page 1002 if( index==2) { //help page
1004 } 1003 }
1005 1004
1006 qApp->processEvents(); 1005 qApp->processEvents();
1007 update(); 1006 update();
1008 } 1007 }
1009} 1008}
1010 1009
1011void QtRec::getOutVol( ) { 1010void QtRec::getOutVol( ) {
1012 filePara.outVol = soundDevice->getOutVolume(); 1011 filePara.outVol = soundDevice->getOutVolume();
1013// qDebug("out vol %d", filePara.outVol); 1012// odebug << "out vol " << filePara.outVol << "" << oendl;
1014 OutputSlider->setValue( -filePara.outVol); 1013 OutputSlider->setValue( -filePara.outVol);
1015} 1014}
1016 1015
1017void QtRec::getInVol() { 1016void QtRec::getInVol() {
1018 filePara.inVol = soundDevice->getInVolume(); 1017 filePara.inVol = soundDevice->getInVolume();
1019// qDebug("in vol %d", filePara.inVol); 1018// odebug << "in vol " << filePara.inVol << "" << oendl;
1020 InputSlider->setValue( -filePara.inVol); 1019 InputSlider->setValue( -filePara.inVol);
1021} 1020}
1022 1021
1023void QtRec::changedOutVolume() { 1022void QtRec::changedOutVolume() {
1024 soundDevice->changedOutVolume( -OutputSlider->value()); 1023 soundDevice->changedOutVolume( -OutputSlider->value());
1025} 1024}
1026 1025
1027void QtRec::changedInVolume( ) { 1026void QtRec::changedInVolume( ) {
1028 soundDevice->changedInVolume( -InputSlider->value()); 1027 soundDevice->changedInVolume( -InputSlider->value());
1029} 1028}
1030 1029
1031 1030
1032bool QtRec::setupAudio( bool b) { 1031bool QtRec::setupAudio( bool b) {
1033 bool ok; 1032 bool ok;
1034 int sampleformat, stereo, flags; 1033 int sampleformat, stereo, flags;
1035 QString dspString, mixerString; 1034 QString dspString, mixerString;
1036 1035
1037 filePara.resolution = bitRateComboBox->currentText().toInt( &ok,10); //16 1036 filePara.resolution = bitRateComboBox->currentText().toInt( &ok,10); //16
1038 1037
1039 if( !b) { 1038 if( !b) {
1040// we want to play 1039// we want to play
1041#ifdef PDAUDIO //ALSA 1040#ifdef PDAUDIO //ALSA
1042 if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) { 1041 if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) {
1043 sampleformat = SND_PCM_FORMAT_S16; 1042 sampleformat = SND_PCM_FORMAT_S16;
1044 filePara.resolution = 16; 1043 filePara.resolution = 16;
1045 } else if( filePara.resolution == 24 || compressionCheckBox->isChecked() ) { 1044 } else if( filePara.resolution == 24 || compressionCheckBox->isChecked() ) {
1046 sampleformat = SND_PCM_FORMAT_S24; 1045 sampleformat = SND_PCM_FORMAT_S24;
1047 filePara.resolution = 24; 1046 filePara.resolution = 24;
1048 } else if( filePara.resolution == 32 || compressionCheckBox->isChecked() ) { 1047 } else if( filePara.resolution == 32 || compressionCheckBox->isChecked() ) {
1049 sampleformat = SND_PCM_FORMAT_S32; 1048 sampleformat = SND_PCM_FORMAT_S32;
1050 filePara.resolution = 32; 1049 filePara.resolution = 32;
1051 } else { 1050 } else {
1052 sampleformat = SND_PCM_FORMAT_U8; 1051 sampleformat = SND_PCM_FORMAT_U8;
1053 filePara.resolution = 8; 1052 filePara.resolution = 8;
1054 } 1053 }
1055#else 1054#else
1056// we want to play 1055// we want to play
1057 if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) { 1056 if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) {
1058 sampleformat = AFMT_S16_LE; 1057 sampleformat = AFMT_S16_LE;
1059 filePara.resolution = 16; 1058 filePara.resolution = 16;
1060 } else { 1059 } else {
1061 sampleformat = AFMT_U8; 1060 sampleformat = AFMT_U8;
1062 filePara.resolution = 8; 1061 filePara.resolution = 8;
1063 } 1062 }
1064#endif 1063#endif
1065 1064
1066 stereo = filePara.channels; 1065 stereo = filePara.channels;
1067 flags = O_WRONLY; 1066 flags = O_WRONLY;
1068 Config hwcfg("OpieRec"); 1067 Config hwcfg("OpieRec");
1069 hwcfg.setGroup("Hardware"); 1068 hwcfg.setGroup("Hardware");
1070 dspString = hwcfg.readEntry( "Audio", DSPSTROUT); 1069 dspString = hwcfg.readEntry( "Audio", DSPSTROUT);
1071 mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXEROUT); 1070 mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXEROUT);
1072 recording = false; 1071 recording = false;
1073 } else { // we want to record 1072 } else { // we want to record
1074 1073
1075#ifdef PDAUDIO //ALSA 1074#ifdef PDAUDIO //ALSA
1076 if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16") 1075 if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16")
1077 sampleformat = SND_PCM_FORMAT_S16; 1076 sampleformat = SND_PCM_FORMAT_S16;
1078 else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "24") 1077 else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "24")
1079 sampleformat = SND_PCM_FORMAT_S24; 1078 sampleformat = SND_PCM_FORMAT_S24;
1080 else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "32") 1079 else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "32")
1081 sampleformat = SND_PCM_FORMAT_S32; 1080 sampleformat = SND_PCM_FORMAT_S32;
1082 else 1081 else
1083 sampleformat = SND_PCM_FORMAT_U8; 1082 sampleformat = SND_PCM_FORMAT_U8;
1084 1083
1085#else 1084#else
1086 if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16") 1085 if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16")
1087 sampleformat = AFMT_S16_LE; 1086 sampleformat = AFMT_S16_LE;
1088 else 1087 else
1089 sampleformat = AFMT_U8; 1088 sampleformat = AFMT_U8;
1090 1089
1091 if( !compressionCheckBox->isChecked()) { 1090 if( !compressionCheckBox->isChecked()) {
1092 filePara.format = WAVE_FORMAT_PCM; 1091 filePara.format = WAVE_FORMAT_PCM;
1093// qDebug("WAVE_FORMAT_PCM"); 1092// odebug << "WAVE_FORMAT_PCM" << oendl;
1094 } else { 1093 } else {
1095 filePara.format = WAVE_FORMAT_DVI_ADPCM; 1094 filePara.format = WAVE_FORMAT_DVI_ADPCM;
1096 sampleformat = AFMT_S16_LE; 1095 sampleformat = AFMT_S16_LE;
1097// qDebug("WAVE_FORMAT_DVI_ADPCM"); 1096// odebug << "WAVE_FORMAT_DVI_ADPCM" << oendl;
1098 } 1097 }
1099#endif 1098#endif
1100 1099
1101 stereo = filePara.channels; 1100 stereo = filePara.channels;
1102// filePara.sampleRate = sampleRateComboBox->currentText().toInt( &ok,10);//44100; 1101// filePara.sampleRate = sampleRateComboBox->currentText().toInt( &ok,10);//44100;
1103 flags= O_RDWR; 1102 flags= O_RDWR;
1104// flags= O_RDONLY; 1103// flags= O_RDONLY;
1105 Config hwcfg("OpieRec"); 1104 Config hwcfg("OpieRec");
1106 hwcfg.setGroup("Hardware"); 1105 hwcfg.setGroup("Hardware");
1107 dspString = hwcfg.readEntry( "Audio", DSPSTRIN); 1106 dspString = hwcfg.readEntry( "Audio", DSPSTRIN);
1108 mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXERIN); 1107 mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXERIN);
1109 recording = true; 1108 recording = true;
1110 } 1109 }
1111 1110
1112 // if(soundDevice) delete soundDevice; 1111 // if(soundDevice) delete soundDevice;
1113 qDebug("<<<<<<<<<<<<<<<<<<<open dsp %d %d %d", filePara.sampleRate, filePara.channels, sampleformat); 1112 odebug << "<<<<<<<<<<<<<<<<<<<open dsp " << filePara.sampleRate << " " << filePara.channels << " " << sampleformat << "" << oendl;
1114 qWarning("change waveform settings"); 1113 owarn << "change waveform settings" << oendl;
1115 waveform->changeSettings( filePara.sampleRate, filePara.channels ); 1114 waveform->changeSettings( filePara.sampleRate, filePara.channels );
1116 1115
1117 soundDevice = new Device( this, dspString, mixerString, b); 1116 soundDevice = new Device( this, dspString, mixerString, b);
1118// soundDevice->openDsp(); 1117// soundDevice->openDsp();
1119 soundDevice->reset(); 1118 soundDevice->reset();
1120 1119
1121 qDebug("device has been made %d", soundDevice->sd); 1120 odebug << "device has been made " << soundDevice->sd << "" << oendl;
1122 1121
1123 ////////////////// <<<<<<<<<<<<>>>>>>>>>>>> 1122 ////////////////// <<<<<<<<<<<<>>>>>>>>>>>>
1124 soundDevice->setDeviceFormat( sampleformat); 1123 soundDevice->setDeviceFormat( sampleformat);
1125 soundDevice->setDeviceChannels( filePara.channels); 1124 soundDevice->setDeviceChannels( filePara.channels);
1126 soundDevice->setDeviceRate( filePara.sampleRate); 1125 soundDevice->setDeviceRate( filePara.sampleRate);
1127 soundDevice->getDeviceFragSize(); 1126 soundDevice->getDeviceFragSize();
1128#ifdef QT_QWS_EBX 1127#ifdef QT_QWS_EBX
1129 int frag = FRAGSIZE; 1128 int frag = FRAGSIZE;
1130 soundDevice->setFragSize( frag); 1129 soundDevice->setFragSize( frag);
1131 soundDevice->getDeviceFragSize(); 1130 soundDevice->getDeviceFragSize();
1132#endif 1131#endif
1133 ///////////////// 1132 /////////////////
1134 filePara.sd = soundDevice->sd; 1133 filePara.sd = soundDevice->sd;
1135 1134
1136 if ( filePara.sd == -1) { 1135 if ( filePara.sd == -1) {
1137 1136
1138 monitoring = false; 1137 monitoring = false;
1139 stopped = true; 1138 stopped = true;
1140 update(); 1139 update();
1141 setCaption( tr( "OpieRecord " )+ QString::number(VERSION) ); 1140 setCaption( tr( "OpieRecord " )+ QString::number(VERSION) );
1142 return false; 1141 return false;
1143 } 1142 }
1144 if(autoMute) 1143 if(autoMute)
1145 doMute(false); 1144 doMute(false);
1146 1145
1147 return true; 1146 return true;
1148} 1147}
1149 1148
1150 1149
1151bool QtRec::setUpFile() { //setup file for recording 1150bool QtRec::setUpFile() { //setup file for recording
1152// qDebug("Setting up wavfile"); 1151// odebug << "Setting up wavfile" << oendl;
1153// if(wavFile) delete wavFile; 1152// if(wavFile) delete wavFile;
1154 wavFile = new WavFile( this, (const QString &)"", 1153 wavFile = new WavFile( this, (const QString &)"",
1155 true, 1154 true,
1156 filePara.sampleRate, 1155 filePara.sampleRate,
1157 filePara.channels, 1156 filePara.channels,
1158 filePara.resolution, 1157 filePara.resolution,
1159 filePara.format); 1158 filePara.format);
1160 1159
1161 filePara.fd = wavFile->wavHandle(); 1160 filePara.fd = wavFile->wavHandle();
1162 if(filePara.fd == -1) { 1161 if(filePara.fd == -1) {
1163 return false; 1162 return false;
1164 } else { 1163 } else {
1165// filePara.channels=1; 1164// filePara.channels=1;
1166 } 1165 }
1167 return true; 1166 return true;
1168} 1167}
1169 1168
1170/// <<<<<<<<<<<<<<<< PLAY >>>>>>>>>>>>>>>>>>> 1169/// <<<<<<<<<<<<<<<< PLAY >>>>>>>>>>>>>>>>>>>
1171bool QtRec::doPlay() { 1170bool QtRec::doPlay() {
1172 1171
1173 if( !paused) { 1172 if( !paused) {
1174 total = 0; 1173 total = 0;
1175 filePara.numberOfRecordedSeconds = 0; 1174 filePara.numberOfRecordedSeconds = 0;
1176 } else { 1175 } else {
1177 paused = false; 1176 paused = false;
1178 secCount = (int)filePara.numberOfRecordedSeconds; 1177 secCount = (int)filePara.numberOfRecordedSeconds;
1179 } 1178 }
1180 playing = true; 1179 playing = true;
1181 stopped = false; 1180 stopped = false;
1182 recording = false; 1181 recording = false;
1183 1182
1184 QString num; 1183 QString num;
1185 qDebug( "Play number of samples %d", filePara.numberSamples); 1184 odebug << "Play number of samples " << filePara.numberSamples << "" << oendl;
1186 1185
1187// timeSlider->setRange( 0, filePara.numberSamples); 1186// timeSlider->setRange( 0, filePara.numberSamples);
1188 1187
1189 timeString.sprintf("%f", filePara.numberOfRecordedSeconds); 1188 timeString.sprintf("%f", filePara.numberOfRecordedSeconds);
1190 timeLabel->setText( timeString+ tr(" seconds")); 1189 timeLabel->setText( timeString+ tr(" seconds"));
1191 1190
1192 QString msg; 1191 QString msg;
1193 msg.sprintf("%d, %d, %d", 1192 msg.sprintf("%d, %d, %d",
1194 filePara.sampleRate, 1193 filePara.sampleRate,
1195 filePara.channels, 1194 filePara.channels,
1196 filePara.resolution); 1195 filePara.resolution);
1197#ifdef DEV_VERSION 1196#ifdef DEV_VERSION
1198 setCaption( msg); 1197 setCaption( msg);
1199#endif 1198#endif
1200 1199
1201 startTimer( 1000); 1200 startTimer( 1000);
1202#ifdef THREADED 1201#ifdef THREADED
1203 pthread_t thread2; 1202 pthread_t thread2;
1204 pthread_create( &thread2, NULL, (void * (*)(void *))playIt, NULL/* &*/); 1203 pthread_create( &thread2, NULL, (void * (*)(void *))playIt, NULL/* &*/);
1205#endif 1204#endif
1206 1205
1207 toBeginningButton->setEnabled( false); 1206 toBeginningButton->setEnabled( false);
1208 toEndButton->setEnabled( false); 1207 toEndButton->setEnabled( false);
1209#ifndef THREADED 1208#ifndef THREADED
1210 playIt(); 1209 playIt();
1211#endif 1210#endif
1212 return true; 1211 return true;
1213} 1212}
1214 1213
1215 1214
1216void QtRec::changebitrateCombo(int i) { 1215void QtRec::changebitrateCombo(int i) {
1217 Config cfg("OpieRec"); 1216 Config cfg("OpieRec");
1218 cfg.setGroup("Settings"); 1217 cfg.setGroup("Settings");
1219 int bits = 0; 1218 int bits = 0;
1220 if( i == 1) { bits = 16; } 1219 if( i == 1) { bits = 16; }
1221 else if( i == 2) { bits = 24; } 1220 else if( i == 2) { bits = 24; }
1222 else if( i == 3) { bits = 32; } 1221 else if( i == 3) { bits = 32; }
1223 else { bits=8; } 1222 else { bits=8; }
1224 cfg.writeEntry("bitrate", bits); 1223 cfg.writeEntry("bitrate", bits);
1225 filePara.resolution = bits; 1224 filePara.resolution = bits;
1226 cfg.write(); 1225 cfg.write();
1227} 1226}
1228 1227
1229void QtRec::changesamplerateCombo(int i) { 1228void QtRec::changesamplerateCombo(int i) {
1230 Config cfg("OpieRec"); 1229 Config cfg("OpieRec");
1231 cfg.setGroup("Settings"); 1230 cfg.setGroup("Settings");
1232 int rate=0; 1231 int rate=0;
1233 bool ok; 1232 bool ok;
1234 rate = sampleRateComboBox->text(i).toInt(&ok, 10); 1233 rate = sampleRateComboBox->text(i).toInt(&ok, 10);
1235 cfg.writeEntry( "samplerate",rate); 1234 cfg.writeEntry( "samplerate",rate);
1236 filePara.sampleRate=rate; 1235 filePara.sampleRate=rate;
1237 qDebug( "Change sample rate %d", rate); 1236 odebug << "Change sample rate " << rate << "" << oendl;
1238 cfg.write(); 1237 cfg.write();
1239} 1238}
1240 1239
1241 1240
1242void QtRec::changeDirCombo(int index) { 1241void QtRec::changeDirCombo(int index) {
1243 Config cfg("OpieRec"); 1242 Config cfg("OpieRec");
1244 cfg.setGroup("Settings"); 1243 cfg.setGroup("Settings");
1245 QString sName = directoryComboBox->text(index); 1244 QString sName = directoryComboBox->text(index);
1246 1245
1247 StorageInfo storageInfo; 1246 StorageInfo storageInfo;
1248 const QList<FileSystem> &fs = storageInfo.fileSystems(); 1247 const QList<FileSystem> &fs = storageInfo.fileSystems();
1249 QListIterator<FileSystem> it ( fs ); 1248 QListIterator<FileSystem> it ( fs );
1250 QString storage; 1249 QString storage;
1251 for( ; it.current(); ++it ){ 1250 for( ; it.current(); ++it ){
1252 if( sName == (*it)->name()+" "+ (*it)->path() || 1251 if( sName == (*it)->name()+" "+ (*it)->path() ||
1253 (*it)->name() == sName ) { 1252 (*it)->name() == sName ) {
1254 const QString path = (*it)->path(); 1253 const QString path = (*it)->path();
1255 recDir = path; 1254 recDir = path;
1256 cfg.writeEntry("directory", recDir); 1255 cfg.writeEntry("directory", recDir);
1257 qDebug("new rec dir "+recDir); 1256 odebug << "new rec dir "+recDir << oendl;
1258 } 1257 }
1259 } 1258 }
1260 cfg.write(); 1259 cfg.write();
1261} 1260}
1262 1261
1263 1262
1264void QtRec::changeSizeLimitCombo(int) { 1263void QtRec::changeSizeLimitCombo(int) {
1265 Config cfg("OpieRec"); 1264 Config cfg("OpieRec");
1266 cfg.setGroup("Settings"); 1265 cfg.setGroup("Settings");
1267 cfg.writeEntry("sizeLimit", getCurrentSizeLimit() ); 1266 cfg.writeEntry("sizeLimit", getCurrentSizeLimit() );
1268 cfg.write(); 1267 cfg.write();
1269} 1268}
1270 1269
1271void QtRec::newSound() { 1270void QtRec::newSound() {
1272 if( !rec()) { 1271 if( !rec()) {
1273 endRecording(); 1272 endRecording();
1274 deleteSound(); 1273 deleteSound();
1275 } 1274 }
1276} 1275}
1277 1276
1278void QtRec::itClick(QListViewItem *item) { 1277void QtRec::itClick(QListViewItem *item) {
1279 currentFile = item->text(0); 1278 currentFile = item->text(0);
1280 setCaption("OpieRecord "+currentFile); 1279 setCaption("OpieRecord "+currentFile);
1281} 1280}
1282 1281
1283void QtRec::deleteSound() { 1282void QtRec::deleteSound() {
1284 Config cfg("OpieRec"); 1283 Config cfg("OpieRec");
1285 cfg.setGroup("Sounds"); 1284 cfg.setGroup("Sounds");
1286 if( ListView1->currentItem() == NULL) 1285 if( ListView1->currentItem() == NULL)
1287 return; 1286 return;
1288#ifndef DEV_VERSION 1287#ifndef DEV_VERSION
1289 switch ( QMessageBox::warning(this,tr("Delete"), 1288 switch ( QMessageBox::warning(this,tr("Delete"),
1290 tr("Do you really want to <font size=+2><B>DELETE</B></font>\nthe selected file?"), 1289 tr("Do you really want to <font size=+2><B>DELETE</B></font>\nthe selected file?"),
1291 tr("Yes"),tr("No"),0,1,1) ) { 1290 tr("Yes"),tr("No"),0,1,1) ) {
1292 case 0: 1291 case 0:
1293#endif 1292#endif
1294 { 1293 {
1295 QString file = ListView1->currentItem()->text(0); 1294 QString file = ListView1->currentItem()->text(0);
1296 QString fileName; 1295 QString fileName;
1297 fileName = cfg.readEntry( file, ""); 1296 fileName = cfg.readEntry( file, "");
1298 QFile f( fileName); 1297 QFile f( fileName);
1299 if( f.exists()) 1298 if( f.exists())
1300 if( !f.remove()) 1299 if( !f.remove())
1301 QMessageBox::message( tr("Error"), tr("Could not remove file.")); 1300 QMessageBox::message( tr("Error"), tr("Could not remove file."));
1302 1301
1303 int nFiles = cfg.readNumEntry( "NumberofFiles",0); 1302 int nFiles = cfg.readNumEntry( "NumberofFiles",0);
1304 bool found = false; 1303 bool found = false;
1305 for(int i=0;i<nFiles+1;i++) { 1304 for(int i=0;i<nFiles+1;i++) {
1306 1305
1307 if( cfg.readEntry( QString::number(i),"").find( file,0,true) != -1) { 1306 if( cfg.readEntry( QString::number(i),"").find( file,0,true) != -1) {
1308 found = true; 1307 found = true;
1309 cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),"")); 1308 cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),""));
1310 } 1309 }
1311 if(found) 1310 if(found)
1312 cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),"")); 1311 cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),""));
1313 } 1312 }
1314 1313
1315 cfg.removeEntry( cfg.readEntry( file)); 1314 cfg.removeEntry( cfg.readEntry( file));
1316 cfg.removeEntry( file); 1315 cfg.removeEntry( file);
1317 cfg.writeEntry( "NumberofFiles", nFiles-1); 1316 cfg.writeEntry( "NumberofFiles", nFiles-1);
1318 cfg.write(); 1317 cfg.write();
1319 1318
1320 ListView1->takeItem( ListView1->currentItem() ); 1319 ListView1->takeItem( ListView1->currentItem() );
1321 delete ListView1->currentItem(); 1320 delete ListView1->currentItem();
1322 1321
1323 ListView1->clear(); 1322 ListView1->clear();
1324 ListView1->setSelected( ListView1->firstChild(), true); 1323 ListView1->setSelected( ListView1->firstChild(), true);
1325 initIconView(); 1324 initIconView();
1326 update(); 1325 update();
1327 } 1326 }
1328#ifndef DEV_VERSION 1327#ifndef DEV_VERSION
1329 }; 1328 };
1330#endif 1329#endif
1331 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); 1330 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) );
1332 1331
1333} 1332}
1334 1333
1335void QtRec::keyPressEvent( QKeyEvent *e) { 1334void QtRec::keyPressEvent( QKeyEvent *e) {
1336 1335
1337 switch ( e->key() ) { 1336 switch ( e->key() ) {
1338 // case Key_F1: 1337 // case Key_F1:
1339 // if(stopped && !recording) 1338 // if(stopped && !recording)
1340 // newSound(); 1339 // newSound();
1341 // else 1340 // else
1342 // stop(); 1341 // stop();
1343 // break; 1342 // break;
1344 // case Key_F2: { 1343 // case Key_F2: {
1345 // if( !e->isAutoRepeat()) 1344 // if( !e->isAutoRepeat())
1346 // rewindPressed(); 1345 // rewindPressed();
1347 // } 1346 // }
1348 // break; 1347 // break;
1349 // case Key_F3: { 1348 // case Key_F3: {
1350 // if( !e->isAutoRepeat()) 1349 // if( !e->isAutoRepeat())
1351 // FastforwardPressed(); 1350 // FastforwardPressed();
1352 // } 1351 // }
1353 // break; 1352 // break;
1354 1353
1355 ////////////////////////////// Zaurus keys 1354 ////////////////////////////// Zaurus keys
1356 case Key_F9: //activity 1355 case Key_F9: //activity
1357 break; 1356 break;
1358 case Key_F10: //contacts 1357 case Key_F10: //contacts
1359 break; 1358 break;
1360 case Key_F11: //menu 1359 case Key_F11: //menu
1361 break; 1360 break;
1362 case Key_F12: //home 1361 case Key_F12: //home
1363 break; 1362 break;
1364 case Key_F13: //mail 1363 case Key_F13: //mail
1365 break; 1364 break;
1366 case Key_Space: 1365 case Key_Space:
1367 break; 1366 break;
1368 case Key_Delete: 1367 case Key_Delete:
1369 break; 1368 break;
1370 case Key_Up: 1369 case Key_Up:
1371 // stop(); 1370 // stop();
1372 break; 1371 break;
1373 case Key_Down: 1372 case Key_Down:
1374 // newSound(); 1373 // newSound();
1375 break; 1374 break;
1376 case Key_Left: { 1375 case Key_Left: {
1377 qDebug("rewinding"); 1376 odebug << "rewinding" << oendl;
1378 if( !e->isAutoRepeat()) 1377 if( !e->isAutoRepeat())
1379 rewindPressed(); 1378 rewindPressed();
1380 } 1379 }
1381 break; 1380 break;
1382 case Key_Right: { 1381 case Key_Right: {
1383 if( !e->isAutoRepeat()) 1382 if( !e->isAutoRepeat())
1384 FastforwardPressed(); 1383 FastforwardPressed();
1385 } 1384 }
1386 break; 1385 break;
1387 } 1386 }
1388} 1387}
1389 1388
1390void QtRec::keyReleaseEvent( QKeyEvent *e) { 1389void QtRec::keyReleaseEvent( QKeyEvent *e) {
1391 switch ( e->key() ) { 1390 switch ( e->key() ) {
1392 // case Key_F1: 1391 // case Key_F1:
1393 // if(stopped && !recording) 1392 // if(stopped && !recording)
1394 // newSound(); 1393 // newSound();
1395 // else 1394 // else
1396 // stop(); 1395 // stop();
1397 // break; 1396 // break;
1398 // case Key_F2: 1397 // case Key_F2:
1399 // rewindReleased(); 1398 // rewindReleased();
1400 // break; 1399 // break;
1401 // case Key_F3: 1400 // case Key_F3:
1402 // FastforwardReleased(); 1401 // FastforwardReleased();
1403 // break; 1402 // break;
1404 1403
1405 ////////////////////////////// Zaurus keys 1404 ////////////////////////////// Zaurus keys
1406 case Key_F9: //activity 1405 case Key_F9: //activity
1407 break; 1406 break;
1408 case Key_F10: //contacts 1407 case Key_F10: //contacts
1409 break; 1408 break;
1410 case Key_F11: //menu 1409 case Key_F11: //menu
1411 break; 1410 break;
1412 case Key_F12: //home 1411 case Key_F12: //home
1413 if(stopped) 1412 if(stopped)
1414 doPlayBtn(); 1413 doPlayBtn();
1415 else 1414 else
1416 stop(); 1415 stop();
1417 break; 1416 break;
1418 case Key_F13: //mail 1417 case Key_F13: //mail
1419 break; 1418 break;
1420 case Key_Space: 1419 case Key_Space:
1421 if(stopped && !recording) 1420 if(stopped && !recording)
1422 newSound(); 1421 newSound();
1423 else 1422 else
1424 stop(); 1423 stop();
1425 break; 1424 break;
1426 case Key_Delete: 1425 case Key_Delete:
1427 deleteSound(); 1426 deleteSound();
1428 break; 1427 break;
1429 case Key_Up: 1428 case Key_Up:
1430 // stop(); 1429 // stop();
1431 qDebug("Up"); 1430 odebug << "Up" << oendl;
1432 break; 1431 break;
1433 case Key_Down: 1432 case Key_Down:
1434 // start(); 1433 // start();
1435 // qDebug("Down"); 1434 // odebug << "Down" << oendl;
1436 // newSound(); 1435 // newSound();
1437 break; 1436 break;
1438 case Key_Left: 1437 case Key_Left:
1439 qDebug("Left"); 1438 odebug << "Left" << oendl;
1440 rewindReleased(); 1439 rewindReleased();
1441 break; 1440 break;
1442 case Key_Right: 1441 case Key_Right:
1443 qDebug("Right"); 1442 odebug << "Right" << oendl;
1444 FastforwardReleased(); 1443 FastforwardReleased();
1445 break; 1444 break;
1446 } 1445 }
1447} 1446}
1448 1447
1449void QtRec::endRecording() { 1448void QtRec::endRecording() {
1450 monitoring = false; 1449 monitoring = false;
1451 recording = false; 1450 recording = false;
1452 stopped = true; 1451 stopped = true;
1453 waveform->reset(); 1452 waveform->reset();
1454 setRecordButton( false); 1453 setRecordButton( false);
1455 1454
1456 toBeginningButton->setEnabled( true); 1455 toBeginningButton->setEnabled( true);
1457 toEndButton->setEnabled( true); 1456 toEndButton->setEnabled( true);
1458 1457
1459 killTimers(); 1458 killTimers();
1460 1459
1461 if(autoMute) 1460 if(autoMute)
1462 doMute( true); 1461 doMute( true);
1463 1462
1464 soundDevice->closeDevice( true); 1463 soundDevice->closeDevice( true);
1465 1464
1466 if( wavFile->track.isOpen()) { 1465 if( wavFile->track.isOpen()) {
1467 wavFile->adjustHeaders( filePara.fd, filePara.numberSamples); 1466 wavFile->adjustHeaders( filePara.fd, filePara.numberSamples);
1468 // soundDevice->sd=-1; 1467 // soundDevice->sd=-1;
1469 filePara.numberSamples = 0; 1468 filePara.numberSamples = 0;
1470 // filePara.sd=-1; 1469 // filePara.sd=-1;
1471 wavFile->closeFile(); 1470 wavFile->closeFile();
1472 filePara.fd=0; 1471 filePara.fd=0;
1473 1472
1474 if( wavFile->isTempFile()) { 1473 if( wavFile->isTempFile()) {
1475// move tmp file to regular file 1474// move tmp file to regular file
1476 QString cmd; 1475 QString cmd;
1477 cmd.sprintf("mv "+ wavFile->trackName() + " " + wavFile->currentFileName); 1476 cmd.sprintf("mv "+ wavFile->trackName() + " " + wavFile->currentFileName);
1478// qDebug("moving tmp file to "+currentFileName); 1477// odebug << "moving tmp file to "+currentFileName << oendl;
1479 system( cmd.latin1()); 1478 system( cmd.latin1());
1480 } 1479 }
1481 1480
1482 qDebug("Just moved " + wavFile->currentFileName); 1481 odebug << "Just moved " + wavFile->currentFileName << oendl;
1483 Config cfg("OpieRec"); 1482 Config cfg("OpieRec");
1484 cfg.setGroup("Sounds"); 1483 cfg.setGroup("Sounds");
1485 1484
1486 int nFiles = cfg.readNumEntry( "NumberofFiles",0); 1485 int nFiles = cfg.readNumEntry( "NumberofFiles",0);
1487 1486
1488 currentFile = QFileInfo( wavFile->currentFileName).fileName(); 1487 currentFile = QFileInfo( wavFile->currentFileName).fileName();
1489 currentFile = currentFile.left( currentFile.length() - 4); 1488 currentFile = currentFile.left( currentFile.length() - 4);
1490 1489
1491 cfg.writeEntry( "NumberofFiles", nFiles + 1); 1490 cfg.writeEntry( "NumberofFiles", nFiles + 1);
1492 cfg.writeEntry( QString::number( nFiles + 1), currentFile); 1491 cfg.writeEntry( QString::number( nFiles + 1), currentFile);
1493 cfg.writeEntry( currentFile, wavFile->currentFileName); 1492 cfg.writeEntry( currentFile, wavFile->currentFileName);
1494 1493
1495 QString time; 1494 QString time;
1496 time.sprintf("%.2f", filePara.numberOfRecordedSeconds); 1495 time.sprintf("%.2f", filePara.numberOfRecordedSeconds);
1497 cfg.writeEntry( wavFile->currentFileName, time ); 1496 cfg.writeEntry( wavFile->currentFileName, time );
1498// qDebug("writing config numberOfRecordedSeconds "+time); 1497// odebug << "writing config numberOfRecordedSeconds "+time << oendl;
1499 1498
1500 cfg.write(); 1499 cfg.write();
1501 qDebug("finished recording"); 1500 odebug << "finished recording" << oendl;
1502 timeLabel->setText(""); 1501 timeLabel->setText("");
1503 } 1502 }
1504 1503
1505 if(soundDevice) delete soundDevice; 1504 if(soundDevice) delete soundDevice;
1506 1505
1507 timeSlider->setValue(0); 1506 timeSlider->setValue(0);
1508 initIconView(); 1507 initIconView();
1509 selectItemByName( currentFile); 1508 selectItemByName( currentFile);
1510} 1509}
1511 1510
1512void QtRec::endPlaying() { 1511void QtRec::endPlaying() {
1513 monitoring = false; 1512 monitoring = false;
1514 recording = false; 1513 recording = false;
1515 playing = false; 1514 playing = false;
1516 stopped = true; 1515 stopped = true;
1517 waveform->reset(); 1516 waveform->reset();
1518// errorStop(); 1517// errorStop();
1519// qDebug("end playing"); 1518// odebug << "end playing" << oendl;
1520 setRecordButton( false); 1519 setRecordButton( false);
1521 1520
1522 toBeginningButton->setEnabled( true); 1521 toBeginningButton->setEnabled( true);
1523 toEndButton->setEnabled( true); 1522 toEndButton->setEnabled( true);
1524 1523
1525 if(autoMute) 1524 if(autoMute)
1526 doMute( true); 1525 doMute( true);
1527 1526
1528 soundDevice->closeDevice( false); 1527 soundDevice->closeDevice( false);
1529 soundDevice->sd = -1; 1528 soundDevice->sd = -1;
1530 // if(soundDevice) delete soundDevice; 1529 // if(soundDevice) delete soundDevice;
1531// qDebug("file and sound device closed"); 1530// odebug << "file and sound device closed" << oendl;
1532 timeLabel->setText(""); 1531 timeLabel->setText("");
1533 total = 0; 1532 total = 0;
1534 filePara.numberSamples = 0; 1533 filePara.numberSamples = 0;
1535 filePara.sd = -1; 1534 filePara.sd = -1;
1536// wavFile->closeFile(); 1535// wavFile->closeFile();
1537 filePara.fd = 0; 1536 filePara.fd = 0;
1538// if(wavFile) delete wavFile; //this crashes 1537// if(wavFile) delete wavFile; //this crashes
1539 1538
1540// qDebug("track closed"); 1539// odebug << "track closed" << oendl;
1541 killTimers(); 1540 killTimers();
1542 qWarning("reset slider"); 1541 owarn << "reset slider" << oendl;
1543 timeSlider->setValue(0); 1542 timeSlider->setValue(0);
1544 1543
1545 if(soundDevice) delete soundDevice; 1544 if(soundDevice) delete soundDevice;
1546 1545
1547} 1546}
1548 1547
1549bool QtRec::openPlayFile() { 1548bool QtRec::openPlayFile() {
1550 1549
1551 qApp->processEvents(); 1550 qApp->processEvents();
1552 if( currentFile.isEmpty()) { 1551 if( currentFile.isEmpty()) {
1553 QMessageBox::message(tr("Opierec"),tr("Please select file to play")); 1552 QMessageBox::message(tr("Opierec"),tr("Please select file to play"));
1554 endPlaying(); 1553 endPlaying();
1555 return false; 1554 return false;
1556 } 1555 }
1557 QString currentFileName; 1556 QString currentFileName;
1558 Config cfg("OpieRec"); 1557 Config cfg("OpieRec");
1559 cfg.setGroup("Sounds"); 1558 cfg.setGroup("Sounds");
1560 int nFiles = cfg.readNumEntry( "NumberofFiles", 0); 1559 int nFiles = cfg.readNumEntry( "NumberofFiles", 0);
1561 for(int i=0;i<nFiles+1;i++) { //look for file 1560 for(int i=0;i<nFiles+1;i++) { //look for file
1562 if( cfg.readEntry( QString::number(i),"").find( currentFile,0,true) != -1) { 1561 if( cfg.readEntry( QString::number(i),"").find( currentFile,0,true) != -1) {
1563 currentFileName = cfg.readEntry( currentFile, "" ); 1562 currentFileName = cfg.readEntry( currentFile, "" );
1564 qDebug("opening for play: " + currentFileName); 1563 odebug << "opening for play: " + currentFileName << oendl;
1565 } 1564 }
1566 } 1565 }
1567 wavFile = new WavFile(this, 1566 wavFile = new WavFile(this,
1568 currentFileName, 1567 currentFileName,
1569 false); 1568 false);
1570 filePara.fd = wavFile->wavHandle(); 1569 filePara.fd = wavFile->wavHandle();
1571 if(filePara.fd == -1) { 1570 if(filePara.fd == -1) {
1572 // if(!track.open(IO_ReadOnly)) { 1571 // if(!track.open(IO_ReadOnly)) {
1573 QString errorMsg = (QString)strerror(errno); 1572 QString errorMsg = (QString)strerror(errno);
1574 monitoring = false; 1573 monitoring = false;
1575 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); 1574 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) );
1576 QMessageBox::message(tr("Note"), tr("Could not open audio file.\n") 1575 QMessageBox::message(tr("Note"), tr("Could not open audio file.\n")
1577 + errorMsg + "\n" + currentFile); 1576 + errorMsg + "\n" + currentFile);
1578 return false; 1577 return false;
1579 } else { 1578 } else {
1580 1579
1581 filePara.numberSamples = wavFile->getNumberSamples(); 1580 filePara.numberSamples = wavFile->getNumberSamples();
1582 filePara.format = wavFile->getFormat(); 1581 filePara.format = wavFile->getFormat();
1583 filePara.sampleRate = wavFile->getSampleRate(); 1582 filePara.sampleRate = wavFile->getSampleRate();
1584 filePara.resolution = wavFile->getResolution(); 1583 filePara.resolution = wavFile->getResolution();
1585 filePara.channels = wavFile->getChannels(); 1584 filePara.channels = wavFile->getChannels();
1586 timeSlider->setPageStep(1); 1585 timeSlider->setPageStep(1);
1587 monitoring = true; 1586 monitoring = true;
1588 1587
1589 qDebug("file %d, samples %d %d", filePara.fd, filePara.numberSamples, filePara.sampleRate); 1588 odebug << "file " << filePara.fd << ", samples " << filePara.numberSamples << " " << filePara.sampleRate << "" << oendl;
1590 int sec = (int) (( filePara.numberSamples / filePara.sampleRate) / filePara.channels) / ( filePara.channels*( filePara.resolution/8)); 1589 int sec = (int) (( filePara.numberSamples / filePara.sampleRate) / filePara.channels) / ( filePara.channels*( filePara.resolution/8));
1591 1590
1592 qWarning("seconds %d", sec); 1591 owarn << "seconds " << sec << "" << oendl;
1593 1592
1594 timeSlider->setRange(0, filePara.numberSamples ); 1593 timeSlider->setRange(0, filePara.numberSamples );
1595 } 1594 }
1596 1595
1597 return true; 1596 return true;
1598} 1597}
1599 1598
1600void QtRec::listPressed( int mouse, QListViewItem *item, const QPoint &, int ) { 1599void QtRec::listPressed( int mouse, QListViewItem *item, const QPoint &, int ) {
1601 if(item == NULL ) 1600 if(item == NULL )
1602 return; 1601 return;
1603 switch (mouse) { 1602 switch (mouse) {
1604 case 1: { 1603 case 1: {
1605 if( renameBox != 0 ) //tricky 1604 if( renameBox != 0 ) //tricky
1606 cancelRename(); 1605 cancelRename();
1607 1606
1608 currentFile = item->text(0); 1607 currentFile = item->text(0);
1609 setCaption( "OpieRecord " + currentFile); 1608 setCaption( "OpieRecord " + currentFile);
1610 } 1609 }
1611 break; 1610 break;
1612 case 2: 1611 case 2:
1613 showListMenu(item); 1612 showListMenu(item);
1614 ListView1->clearSelection(); 1613 ListView1->clearSelection();
1615 break; 1614 break;
1616 }; 1615 };
1617} 1616}
1618 1617
1619void QtRec::showListMenu(QListViewItem * item) { 1618void QtRec::showListMenu(QListViewItem * item) {
1620 if(item == NULL) 1619 if(item == NULL)
1621 return; 1620 return;
1622 QPopupMenu *m = new QPopupMenu(this); 1621 QPopupMenu *m = new QPopupMenu(this);
1623 m->insertItem( tr("Play"), this, SLOT( doMenuPlay() )); 1622 m->insertItem( tr("Play"), this, SLOT( doMenuPlay() ));
1624 if(Ir::supported()) m->insertItem( tr( "Send with Ir" ), this, SLOT( doBeam() )); 1623 if(Ir::supported()) m->insertItem( tr( "Send with Ir" ), this, SLOT( doBeam() ));
1625 m->insertItem( tr( "Rename" ), this, SLOT( doRename() )); 1624 m->insertItem( tr( "Rename" ), this, SLOT( doRename() ));
1626 // #if defined (QTOPIA_INTERNAL_FSLP) 1625 // #if defined (QTOPIA_INTERNAL_FSLP)
1627 // m->insertItem( tr( "Properties" ), this, SLOT( doProperties() )); 1626 // m->insertItem( tr( "Properties" ), this, SLOT( doProperties() ));
1628 // #endif 1627 // #endif
1629 m->insertSeparator(); 1628 m->insertSeparator();
1630 m->insertItem( tr("Delete"), this, SLOT( deleteSound() ) ); 1629 m->insertItem( tr("Delete"), this, SLOT( deleteSound() ) );
1631 m->exec( QCursor::pos() ); 1630 m->exec( QCursor::pos() );
1632 qApp->processEvents(); 1631 qApp->processEvents();
1633} 1632}
1634 1633
1635void QtRec::fileBeamFinished( Ir *ir) { 1634void QtRec::fileBeamFinished( Ir *ir) {
1636 if(ir) 1635 if(ir)
1637 QMessageBox::message( tr("Ir Beam out"), tr("Ir sent.") ,tr("Ok") ); 1636 QMessageBox::message( tr("Ir Beam out"), tr("Ir sent.") ,tr("Ok") );
1638 1637
1639} 1638}
1640 1639
1641void QtRec::doBeam() { 1640void QtRec::doBeam() {
1642 qApp->processEvents(); 1641 qApp->processEvents();
1643 if( ListView1->currentItem() == NULL) 1642 if( ListView1->currentItem() == NULL)
1644 return; 1643 return;
1645 Ir ir; 1644 Ir ir;
1646 if( ir.supported()) { 1645 if( ir.supported()) {
1647 QString file = ListView1->currentItem()->text(0); 1646 QString file = ListView1->currentItem()->text(0);
1648 Config cfg("OpieRec"); 1647 Config cfg("OpieRec");
1649 cfg.setGroup("Sounds"); 1648 cfg.setGroup("Sounds");
1650 1649
1651 int nFiles = cfg.readNumEntry("NumberofFiles",0); 1650 int nFiles = cfg.readNumEntry("NumberofFiles",0);
1652 1651
1653 for(int i=0;i<nFiles+1;i++) { 1652 for(int i=0;i<nFiles+1;i++) {
1654 if( cfg.readEntry( QString::number( i),"").find( file, 0, true) != -1) { 1653 if( cfg.readEntry( QString::number( i),"").find( file, 0, true) != -1) {
1655 QString filePath = cfg.readEntry(file,""); 1654 QString filePath = cfg.readEntry(file,"");
1656 Ir *file = new Ir(this, "IR"); 1655 Ir *file = new Ir(this, "IR");
1657 connect( file, SIGNAL( done(Ir*)), 1656 connect( file, SIGNAL( done(Ir*)),
1658 this, SLOT( fileBeamFinished(Ir*))); 1657 this, SLOT( fileBeamFinished(Ir*)));
1659 file->send( filePath, "OPieRec audio file\n" + filePath ); 1658 file->send( filePath, "OPieRec audio file\n" + filePath );
1660 } 1659 }
1661 } 1660 }
1662 } 1661 }
1663} 1662}
1664 1663
1665void QtRec::doMenuPlay() { 1664void QtRec::doMenuPlay() {
1666 qApp->processEvents(); 1665 qApp->processEvents();
1667 currentFile = ListView1->currentItem()->text(0); 1666 currentFile = ListView1->currentItem()->text(0);
1668} 1667}
1669 1668
1670void QtRec::doRename() { 1669void QtRec::doRename() {
1671 QRect r = ListView1->itemRect( ListView1->currentItem( )); 1670 QRect r = ListView1->itemRect( ListView1->currentItem( ));
1672 r = QRect( ListView1->viewportToContents( r.topLeft() ), r.size() ); 1671 r = QRect( ListView1->viewportToContents( r.topLeft() ), r.size() );
1673 r.setX( ListView1->contentsX() ); 1672 r.setX( ListView1->contentsX() );
1674 if ( r.width() > ListView1->visibleWidth() ) 1673 if ( r.width() > ListView1->visibleWidth() )
1675 r.setWidth( ListView1->visibleWidth() ); 1674 r.setWidth( ListView1->visibleWidth() );
1676 1675
1677 renameBox = new QLineEdit( ListView1->viewport(), "qt_renamebox" ); 1676 renameBox = new QLineEdit( ListView1->viewport(), "qt_renamebox" );
1678 renameBox->setFrame(true); 1677 renameBox->setFrame(true);
1679 1678
1680 renameBox->setText( ListView1->currentItem()->text(0) ); 1679 renameBox->setText( ListView1->currentItem()->text(0) );
1681 1680
1682 renameBox->selectAll(); 1681 renameBox->selectAll();
1683 renameBox->installEventFilter( this ); 1682 renameBox->installEventFilter( this );
1684 ListView1->addChild( renameBox, r.x(), r.y() ); 1683 ListView1->addChild( renameBox, r.x(), r.y() );
1685 renameBox->resize( r.size() ); 1684 renameBox->resize( r.size() );
1686 ListView1->viewport()->setFocusProxy( renameBox ); 1685 ListView1->viewport()->setFocusProxy( renameBox );
1687 renameBox->setFocus(); 1686 renameBox->setFocus();
1688 renameBox->show(); 1687 renameBox->show();
1689 1688
1690} 1689}
1691 1690
1692void QtRec::okRename() { 1691void QtRec::okRename() {
1693 qDebug(renameBox->text()); 1692 odebug << renameBox->text() << oendl;
1694 QString filename = renameBox->text(); 1693 QString filename = renameBox->text();
1695 cancelRename(); 1694 cancelRename();
1696 1695
1697 if( ListView1->currentItem() == NULL) 1696 if( ListView1->currentItem() == NULL)
1698 return; 1697 return;
1699 1698
1700 Config cfg("OpieRec"); 1699 Config cfg("OpieRec");
1701 cfg.setGroup("Sounds"); 1700 cfg.setGroup("Sounds");
1702 1701
1703 QString file = ListView1->currentItem()->text(0); 1702 QString file = ListView1->currentItem()->text(0);
1704 1703
1705 qDebug("filename is " + filename); 1704 odebug << "filename is " + filename << oendl;
1706 1705
1707 int nFiles = cfg.readNumEntry("NumberofFiles",0); 1706 int nFiles = cfg.readNumEntry("NumberofFiles",0);
1708 1707
1709 for(int i=0;i<nFiles+1;i++) { //look for file 1708 for(int i=0;i<nFiles+1;i++) { //look for file
1710 if( cfg.readEntry( QString::number(i),"").find(file,0,true) != -1) { 1709 if( cfg.readEntry( QString::number(i),"").find(file,0,true) != -1) {
1711 1710
1712 QString filePath = cfg.readEntry(file,""); 1711 QString filePath = cfg.readEntry(file,"");
1713 1712
1714 cfg.writeEntry( QString::number(i), filename ); 1713 cfg.writeEntry( QString::number(i), filename );
1715 cfg.writeEntry( filename, filePath ); 1714 cfg.writeEntry( filename, filePath );
1716 cfg.removeEntry( file); 1715 cfg.removeEntry( file);
1717 cfg.write(); 1716 cfg.write();
1718 } 1717 }
1719 } 1718 }
1720 1719
1721 ListView1->takeItem( ListView1->currentItem() ); 1720 ListView1->takeItem( ListView1->currentItem() );
1722 delete ListView1->currentItem(); 1721 delete ListView1->currentItem();
1723 ListView1->clear(); 1722 ListView1->clear();
1724 initIconView(); 1723 initIconView();
1725 update(); 1724 update();
1726} 1725}
1727 1726
1728void QtRec::cancelRename() { 1727void QtRec::cancelRename() {
1729 bool resetFocus = ListView1->viewport()->focusProxy() == renameBox; 1728 bool resetFocus = ListView1->viewport()->focusProxy() == renameBox;
1730 delete renameBox; 1729 delete renameBox;
1731 renameBox = 0; 1730 renameBox = 0;
1732 if ( resetFocus ) { 1731 if ( resetFocus ) {
1733 ListView1->viewport()->setFocusProxy( ListView1 ); 1732 ListView1->viewport()->setFocusProxy( ListView1 );
1734 ListView1->setFocus(); 1733 ListView1->setFocus();
1735 } 1734 }
1736} 1735}
1737 1736
1738bool QtRec::eventFilter( QObject * o, QEvent * e ) { 1737bool QtRec::eventFilter( QObject * o, QEvent * e ) {
1739 if ( o->inherits( "QLineEdit" ) ) { 1738 if ( o->inherits( "QLineEdit" ) ) {
1740 if ( e->type() == QEvent::KeyPress ) { 1739 if ( e->type() == QEvent::KeyPress ) {
1741 QKeyEvent *ke = (QKeyEvent*)e; 1740 QKeyEvent *ke = (QKeyEvent*)e;
1742 if ( ke->key() == Key_Return || 1741 if ( ke->key() == Key_Return ||
1743 ke->key() == Key_Enter ) { 1742 ke->key() == Key_Enter ) {
1744 okRename(); 1743 okRename();
1745 return true; 1744 return true;
1746 } else if ( ke->key() == Key_Escape ) { 1745 } else if ( ke->key() == Key_Escape ) {
1747 cancelRename(); 1746 cancelRename();
1748 return true; 1747 return true;
1749 } 1748 }
1750 } else if ( e->type() == QEvent::FocusOut ) { 1749 } else if ( e->type() == QEvent::FocusOut ) {
1751 cancelRename(); 1750 cancelRename();
1752 return true; 1751 return true;
1753 } 1752 }
1754 } 1753 }
1755 return QWidget::eventFilter( o, e ); 1754 return QWidget::eventFilter( o, e );
1756} 1755}
1757 1756
1758 1757
1759int QtRec::getCurrentSizeLimit() { 1758int QtRec::getCurrentSizeLimit() {
1760 return sizeLimitCombo->currentItem() * 5; 1759 return sizeLimitCombo->currentItem() * 5;
1761} 1760}
1762 1761
1763void QtRec::timerBreak() { 1762void QtRec::timerBreak() {
1764 endPlaying(); 1763 endPlaying();
1765} 1764}
1766 1765
1767void QtRec::doVolMuting(bool b) { 1766void QtRec::doVolMuting(bool b) {
1768 Config cfg( "qpe" ); 1767 Config cfg( "qpe" );
1769 cfg. setGroup( "Volume" ); 1768 cfg. setGroup( "Volume" );
1770 cfg.writeEntry( "Mute",b); 1769 cfg.writeEntry( "Mute",b);
1771 cfg.write(); 1770 cfg.write();
1772 QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << b; 1771 QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << b;
1773} 1772}
1774 1773
1775void QtRec::doMicMuting(bool b) { 1774void QtRec::doMicMuting(bool b) {
1776 // qDebug("mic mute"); 1775 // odebug << "mic mute" << oendl;
1777 Config cfg( "qpe" ); 1776 Config cfg( "qpe" );
1778 cfg. setGroup( "Volume" ); 1777 cfg. setGroup( "Volume" );
1779 cfg.writeEntry( "MicMute",b); 1778 cfg.writeEntry( "MicMute",b);
1780 cfg.write(); 1779 cfg.write();
1781 QCopEnvelope( "QPE/System", "micChange(bool)" ) << b; 1780 QCopEnvelope( "QPE/System", "micChange(bool)" ) << b;
1782} 1781}
1783 1782
1784void QtRec::compressionSelected(bool b) { 1783void QtRec::compressionSelected(bool b) {
1785 Config cfg("OpieRec"); 1784 Config cfg("OpieRec");
1786 cfg.setGroup("Settings"); 1785 cfg.setGroup("Settings");
1787 cfg.writeEntry("wavCompression", b); 1786 cfg.writeEntry("wavCompression", b);
1788 cfg.writeEntry("bitrate", 16); 1787 cfg.writeEntry("bitrate", 16);
1789 filePara.resolution = 16; 1788 filePara.resolution = 16;
1790 cfg.write(); 1789 cfg.write();
1791 1790
1792 if(b) { 1791 if(b) {
1793 bitRateComboBox->setEnabled( false); 1792 bitRateComboBox->setEnabled( false);
1794 bitRateComboBox->setCurrentItem( 0); 1793 bitRateComboBox->setCurrentItem( 0);
1795 filePara.resolution = 16; 1794 filePara.resolution = 16;
1796 } else{ 1795 } else{
1797 bitRateComboBox->setEnabled( true); 1796 bitRateComboBox->setEnabled( true);
1798 } 1797 }
1799} 1798}
1800 1799
1801long QtRec::checkDiskSpace(const QString &path) { 1800long QtRec::checkDiskSpace(const QString &path) {
1802 1801
1803 struct statfs fs; 1802 struct statfs fs;
1804 1803
1805 if ( !statfs( path.latin1(), &fs ) ) { 1804 if ( !statfs( path.latin1(), &fs ) ) {
1806 1805
1807 int blkSize = fs.f_bsize; 1806 int blkSize = fs.f_bsize;
1808 int availBlks = fs.f_bavail; 1807 int availBlks = fs.f_bavail;
1809 1808
1810 long mult = blkSize / 1024; 1809 long mult = blkSize / 1024;
1811 long div = 1024 / blkSize; 1810 long div = 1024 / blkSize;
1812 1811
1813 if ( !mult ) mult = 1; 1812 if ( !mult ) mult = 1;
1814 if ( !div ) div = 1; 1813 if ( !div ) div = 1;
1815 1814
1816 return availBlks * mult / div; 1815 return availBlks * mult / div;
1817 } 1816 }
1818 return -1; 1817 return -1;
1819} 1818}
1820 1819
1821// short f_fstyp; /* File system type */ 1820// short f_fstyp; /* File system type */
1822// long f_bsize; /* Block size */ 1821// long f_bsize; /* Block size */
1823// long f_frsize; /* Fragment size */ 1822// long f_frsize; /* Fragment size */
1824// long f_blocks; /* Total number of blocks*/ 1823// long f_blocks; /* Total number of blocks*/
1825// long f_bfree; /* Count of free blocks */ 1824// long f_bfree; /* Count of free blocks */
1826// long f_files; /* Total number of file nodes */ 1825// long f_files; /* Total number of file nodes */
1827// long f_ffree; /* Count of free file nodes */ 1826// long f_ffree; /* Count of free file nodes */
1828// char f_fname[6]; /* Volumename */ 1827// char f_fname[6]; /* Volumename */
1829// char f_fpack[6]; /* Pack name */ 1828// char f_fpack[6]; /* Pack name */
1830 1829
1831void QtRec::receive( const QCString &msg, const QByteArray & ) { 1830void QtRec::receive( const QCString &msg, const QByteArray & ) {
1832 qDebug("Voicerecord received message "+msg); 1831 odebug << "Voicerecord received message "+msg << oendl;
1833 1832
1834} 1833}
1835 1834
1836 1835
1837///////////////////////////// timerEvent 1836///////////////////////////// timerEvent
1838void QtRec::timerEvent( QTimerEvent * ) { 1837void QtRec::timerEvent( QTimerEvent * ) {
1839 1838
1840// if(!recording) 1839// if(!recording)
1841// timeSlider->setValue( secCount); 1840// timeSlider->setValue( secCount);
1842// else 1841// else
1843// timeSlider->setValue( filePara.numberOfRecordedSeconds); 1842// timeSlider->setValue( filePara.numberOfRecordedSeconds);
1844 1843
1845 if( stopped && playing) { 1844 if( stopped && playing) {
1846 stop(); 1845 stop();
1847 } 1846 }
1848 1847
1849 if( stopped && recording ){ 1848 if( stopped && recording ){
1850 stop(); 1849 stop();
1851 } 1850 }
1852 1851
1853 if( recording && filePara.SecondsToRecord < secCount && filePara.SecondsToRecord != 0) { 1852 if( recording && filePara.SecondsToRecord < secCount && filePara.SecondsToRecord != 0) {
1854 stop(); 1853 stop();
1855 } 1854 }
1856 1855
1857 qDebug( "%d", secCount ); 1856 odebug << "" << secCount << "" << oendl;
1858 QString timeString; 1857 QString timeString;
1859#ifdef DEV_VERSION 1858#ifdef DEV_VERSION
1860 QString msg; 1859 QString msg;
1861 msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution); 1860 msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution);
1862 setCaption( msg +" :: "+QString::number(secCount)); 1861 setCaption( msg +" :: "+QString::number(secCount));
1863#endif 1862#endif
1864 1863
1865 timeString.sprintf("%d", secCount); 1864 timeString.sprintf("%d", secCount);
1866 timeLabel->setText( timeString + " seconds"); 1865 timeLabel->setText( timeString + " seconds");
1867 1866
1868 secCount++; 1867 secCount++;
1869} 1868}
1870 1869
1871void QtRec::changeTimeSlider(int index) { 1870void QtRec::changeTimeSlider(int index) {
1872 if( ListView1->currentItem() == 0 || !wavFile->track.isOpen()) return; 1871 if( ListView1->currentItem() == 0 || !wavFile->track.isOpen()) return;
1873 // qDebug("Slider moved to %d",index); 1872 // odebug << "Slider moved to " << index << "" << oendl;
1874 paused = true; 1873 paused = true;
1875 stopped = true; 1874 stopped = true;
1876 1875
1877 sliderPos=index; 1876 sliderPos=index;
1878 1877
1879 QString timeString; 1878 QString timeString;
1880 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2; 1879 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
1881 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); 1880 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
1882 secCount = (int)filePara.numberOfRecordedSeconds; 1881 secCount = (int)filePara.numberOfRecordedSeconds;
1883 timeLabel->setText( timeString + tr(" seconds")); 1882 timeLabel->setText( timeString + tr(" seconds"));
1884} 1883}
1885 1884
1886void QtRec::timeSliderPressed() { 1885void QtRec::timeSliderPressed() {
1887 if( ListView1->currentItem() == 0) return; 1886 if( ListView1->currentItem() == 0) return;
1888 // qDebug("slider pressed"); 1887 // odebug << "slider pressed" << oendl;
1889 paused = true; 1888 paused = true;
1890 stopped = true; 1889 stopped = true;
1891} 1890}
1892 1891
1893void QtRec::timeSliderReleased() { 1892void QtRec::timeSliderReleased() {
1894 if( ListView1->currentItem() == 0) return; 1893 if( ListView1->currentItem() == 0) return;
1895 sliderPos = timeSlider->value(); 1894 sliderPos = timeSlider->value();
1896 1895
1897 // qDebug("slider released %d", sliderPos); 1896 // odebug << "slider released " << sliderPos << "" << oendl;
1898 stopped = false; 1897 stopped = false;
1899 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); 1898 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
1900 total = newPos*4; 1899 total = newPos*4;
1901 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2; 1900 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
1902 1901
1903 doPlay(); 1902 doPlay();
1904} 1903}
1905 1904
1906void QtRec::rewindPressed() { 1905void QtRec::rewindPressed() {
1907 if( ListView1->currentItem() == 0) return; 1906 if( ListView1->currentItem() == 0) return;
1908 if( !wavFile->track.isOpen()) { 1907 if( !wavFile->track.isOpen()) {
1909 if( !openPlayFile() ) 1908 if( !openPlayFile() )
1910 return; 1909 return;
1911 else 1910 else
1912 if( !setupAudio( false)) 1911 if( !setupAudio( false))
1913 return; 1912 return;
1914 } else { 1913 } else {
1915 killTimers(); 1914 killTimers();
1916 paused = true; 1915 paused = true;
1917 stopped = true; 1916 stopped = true;
1918 rewindTimer->start( 50, false); 1917 rewindTimer->start( 50, false);
1919 } 1918 }
1920} 1919}
1921 1920
1922void QtRec::rewindTimerTimeout() { 1921void QtRec::rewindTimerTimeout() {
1923 int sliderValue = timeSlider->value(); 1922 int sliderValue = timeSlider->value();
1924 sliderValue = sliderValue - ( filePara.numberSamples / 100); 1923 sliderValue = sliderValue - ( filePara.numberSamples / 100);
1925 // if(toBeginningButton->isDown()) 1924 // if(toBeginningButton->isDown())
1926 timeSlider->setValue( sliderValue ) ; 1925 timeSlider->setValue( sliderValue ) ;
1927 // qDebug("%d", sliderValue); 1926 // odebug << "" << sliderValue << "" << oendl;
1928 QString timeString; 1927 QString timeString;
1929 filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2; 1928 filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2;
1930 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); 1929 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
1931 timeLabel->setText( timeString+ tr(" seconds")); 1930 timeLabel->setText( timeString+ tr(" seconds"));
1932} 1931}
1933 1932
1934void QtRec::rewindReleased() { 1933void QtRec::rewindReleased() {
1935 rewindTimer->stop(); 1934 rewindTimer->stop();
1936 if( wavFile->track.isOpen()) { 1935 if( wavFile->track.isOpen()) {
1937 sliderPos=timeSlider->value(); 1936 sliderPos=timeSlider->value();
1938 stopped = false; 1937 stopped = false;
1939 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); 1938 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
1940 total = newPos * 4; 1939 total = newPos * 4;
1941 // qDebug("rewind released %d", total); 1940 // odebug << "rewind released " << total << "" << oendl;
1942 startTimer( 1000); 1941 startTimer( 1000);
1943 doPlay(); 1942 doPlay();
1944 } 1943 }
1945} 1944}
1946 1945
1947void QtRec::FastforwardPressed() { 1946void QtRec::FastforwardPressed() {
1948 if( ListView1->currentItem() == 0) return; 1947 if( ListView1->currentItem() == 0) return;
1949 if( !wavFile->track.isOpen()) 1948 if( !wavFile->track.isOpen())
1950 if( !openPlayFile() ) 1949 if( !openPlayFile() )
1951 return; 1950 return;
1952 else 1951 else
1953 if( !setupAudio( false)) 1952 if( !setupAudio( false))
1954 return; 1953 return;
1955 killTimers(); 1954 killTimers();
1956 1955
1957 paused = true; 1956 paused = true;
1958 stopped = true; 1957 stopped = true;
1959 forwardTimer->start(50, false); 1958 forwardTimer->start(50, false);
1960} 1959}
1961 1960
1962 1961
1963void QtRec::forwardTimerTimeout() { 1962void QtRec::forwardTimerTimeout() {
1964 int sliderValue = timeSlider->value(); 1963 int sliderValue = timeSlider->value();
1965 sliderValue = sliderValue + ( filePara.numberSamples / 100); 1964 sliderValue = sliderValue + ( filePara.numberSamples / 100);
1966 1965
1967 // if(toEndButton->isDown()) 1966 // if(toEndButton->isDown())
1968 timeSlider->setValue( sliderValue); 1967 timeSlider->setValue( sliderValue);
1969 1968
1970 QString timeString; 1969 QString timeString;
1971 filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2; 1970 filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2;
1972 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); 1971 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
1973 timeLabel->setText( timeString+ tr(" seconds")); 1972 timeLabel->setText( timeString+ tr(" seconds"));
1974} 1973}
1975 1974
1976void QtRec::FastforwardReleased() { 1975void QtRec::FastforwardReleased() {
1977 forwardTimer->stop(); 1976 forwardTimer->stop();
1978 if( wavFile->track.isOpen()) { 1977 if( wavFile->track.isOpen()) {
1979 sliderPos=timeSlider->value(); 1978 sliderPos=timeSlider->value();
1980 stopped = false; 1979 stopped = false;
1981 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); 1980 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
1982 total = newPos * 4; 1981 total = newPos * 4;
1983 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2; 1982 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
1984 startTimer( 1000); 1983 startTimer( 1000);
1985 doPlay(); 1984 doPlay();
1986 } 1985 }
1987} 1986}
1988 1987
1989 1988
1990QString QtRec::getStorage(const QString &fileName) { 1989QString QtRec::getStorage(const QString &fileName) {
1991 1990
1992 StorageInfo storageInfo; 1991 StorageInfo storageInfo;
1993 const QList<FileSystem> &fs = storageInfo.fileSystems(); 1992 const QList<FileSystem> &fs = storageInfo.fileSystems();
1994 QListIterator<FileSystem> it ( fs ); 1993 QListIterator<FileSystem> it ( fs );
1995 QString storage; 1994 QString storage;
1996 for( ; it.current(); ++it ){ 1995 for( ; it.current(); ++it ){
1997 const QString name = ( *it)->name(); 1996 const QString name = ( *it)->name();
1998 const QString path = ( *it)->path(); 1997 const QString path = ( *it)->path();
1999 const QString disk = ( *it)->disk(); 1998 const QString disk = ( *it)->disk();
2000 if( fileName.find( path,0,true) != -1) 1999 if( fileName.find( path,0,true) != -1)
2001 storage = name; 2000 storage = name;
2002 // const QString options = (*it)->options(); 2001 // const QString options = (*it)->options();
2003 // if( name.find( tr("Internal"),0,true) == -1) { 2002 // if( name.find( tr("Internal"),0,true) == -1) {
2004 // storageComboBox->insertItem( name +" -> "+disk); 2003 // storageComboBox->insertItem( name +" -> "+disk);
2005 // qDebug(name); 2004 // odebug << name << oendl;
2006 } 2005 }
2007 return storage; 2006 return storage;
2008 // struct mntent *me; 2007 // struct mntent *me;
2009 // // if(fileName == "/etc/mtab") { 2008 // // if(fileName == "/etc/mtab") {
2010 // FILE *mntfp = setmntent( fileName.latin1(), "r" ); 2009 // FILE *mntfp = setmntent( fileName.latin1(), "r" );
2011 // if ( mntfp ) { 2010 // if ( mntfp ) {
2012 // while ( (me = getmntent( mntfp )) != 0 ) { 2011 // while ( (me = getmntent( mntfp )) != 0 ) {
2013 // QString filesystemType = me->mnt_type; 2012 // QString filesystemType = me->mnt_type;
2014 2013
2015 // } 2014 // }
2016 // } 2015 // }
2017 // endmntent( mntfp ); 2016 // endmntent( mntfp );
2018} 2017}
2019 2018
2020void QtRec::setRecordButton(bool b) { 2019void QtRec::setRecordButton(bool b) {
2021 2020
2022 if(b) { //about to record or play 2021 if(b) { //about to record or play
2023 2022
2024 Rec_PushButton->setDown( true); 2023 Rec_PushButton->setDown( true);
2025 QPixmap image3( ( const char** ) image3_data ); 2024 QPixmap image3( ( const char** ) image3_data );
2026 Stop_PushButton->setPixmap( image3 ); 2025 Stop_PushButton->setPixmap( image3 );
2027 if(Stop_PushButton->isDown()) 2026 if(Stop_PushButton->isDown())
2028 Stop_PushButton->setDown( true); 2027 Stop_PushButton->setDown( true);
2029 playLabel2->setText( tr("Stop") ); 2028 playLabel2->setText( tr("Stop") );
2030 2029
2031 } else { //about to stop 2030 } else { //about to stop
2032 2031
2033 QPixmap image4( ( const char** ) image4_data ); 2032 QPixmap image4( ( const char** ) image4_data );
2034 Stop_PushButton->setPixmap( image4); 2033 Stop_PushButton->setPixmap( image4);
2035 if(Stop_PushButton->isDown()) 2034 if(Stop_PushButton->isDown())
2036 Stop_PushButton->setDown( false); 2035 Stop_PushButton->setDown( false);
2037 playLabel2->setText( tr("Play") ); 2036 playLabel2->setText( tr("Play") );
2038 if(Rec_PushButton->isDown()) 2037 if(Rec_PushButton->isDown())
2039 Rec_PushButton->setDown( false); 2038 Rec_PushButton->setDown( false);
2040 } 2039 }
2041} 2040}
2042 2041
2043void QtRec::fillDirectoryCombo() { 2042void QtRec::fillDirectoryCombo() {
2044 if( directoryComboBox->count() > 0) 2043 if( directoryComboBox->count() > 0)
2045 directoryComboBox->clear(); 2044 directoryComboBox->clear();
2046 int index = 0; 2045 int index = 0;
2047 Config cfg("OpieRec"); 2046 Config cfg("OpieRec");
2048 cfg.setGroup("Settings"); 2047 cfg.setGroup("Settings");
2049 QString dir = cfg.readEntry("directory", "/"); 2048 QString dir = cfg.readEntry("directory", "/");
2050 StorageInfo storageInfo; 2049 StorageInfo storageInfo;
2051 const QList<FileSystem> &fs = storageInfo.fileSystems(); 2050 const QList<FileSystem> &fs = storageInfo.fileSystems();
2052 QListIterator<FileSystem> it ( fs ); 2051 QListIterator<FileSystem> it ( fs );
2053 QString storage; 2052 QString storage;
2054 for( ; it.current(); ++it ){ 2053 for( ; it.current(); ++it ){
2055 const QString name = ( *it)->name(); 2054 const QString name = ( *it)->name();
2056 const QString path = ( *it)->path(); 2055 const QString path = ( *it)->path();
2057 // directoryComboBox->insertItem(name+" "+path); 2056 // directoryComboBox->insertItem(name+" "+path);
2058 directoryComboBox->insertItem(name); 2057 directoryComboBox->insertItem(name);
2059 if( path == dir) 2058 if( path == dir)
2060 directoryComboBox->setCurrentItem( index); 2059 directoryComboBox->setCurrentItem( index);
2061 index++; 2060 index++;
2062 } 2061 }
2063} 2062}
2064 2063
2065void QtRec::errorStop() { 2064void QtRec::errorStop() {
2066 stopped = true; 2065 stopped = true;
2067 wavFile->closeFile(); 2066 wavFile->closeFile();
2068 killTimers(); 2067 killTimers();
2069} 2068}
2070 2069
2071void QtRec::doMute(bool b) { 2070void QtRec::doMute(bool b) {
2072 doVolMuting( b); 2071 doVolMuting( b);
2073 doMicMuting( b); 2072 doMicMuting( b);
2074} 2073}
2075 2074
2076void QtRec::slotAutoMute(bool b) { 2075void QtRec::slotAutoMute(bool b) {
2077 autoMute = b; 2076 autoMute = b;
2078 Config cfg("OpieRec"); 2077 Config cfg("OpieRec");
2079 cfg.setGroup("Settings"); 2078 cfg.setGroup("Settings");
2080 cfg.writeEntry("useAutoMute",b); 2079 cfg.writeEntry("useAutoMute",b);
2081 doMute( b); 2080 doMute( b);
2082 outMuteCheckBox->setChecked( b); 2081 outMuteCheckBox->setChecked( b);
2083 inMuteCheckBox->setChecked( b); 2082 inMuteCheckBox->setChecked( b);
2084} 2083}
2085 2084
2086void QtRec::selectItemByName(const QString & name) { 2085void QtRec::selectItemByName(const QString & name) {
2087 QListViewItemIterator it( ListView1 ); 2086 QListViewItemIterator it( ListView1 );
2088 for ( ; it.current(); ++it ) 2087 for ( ; it.current(); ++it )
2089 if( name == it.current()->text(0)) 2088 if( name == it.current()->text(0))
2090 ListView1->setCurrentItem(it.current()); 2089 ListView1->setCurrentItem(it.current());
2091} 2090}
2092 2091
2093 2092
2094// long findPeak(long input ) { 2093// long findPeak(long input ) {
2095 2094
2096// // halfLife = time in seconds for output to decay to half value after an impulse 2095// // halfLife = time in seconds for output to decay to half value after an impulse
2097// static float output = 0.0; 2096// static float output = 0.0;
2098// float halfLife = .0025; 2097// float halfLife = .0025;
2099// float vsf = .0025; 2098// float vsf = .0025;
2100// float scalar = pow( 0.5, 1.0/(halfLife * filePara.sampleRate )); 2099// float scalar = pow( 0.5, 1.0/(halfLife * filePara.sampleRate ));
2101// if( input < 0.0 ) 2100// 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 @@
1//wavFile.cpp 1//wavFile.cpp
2#include "wavFile.h" 2#include "wavFile.h"
3#include "qtrec.h" 3#include "qtrec.h"
4 4
5/* OPIE */
6#include <opie2/odebug.h>
7#include <qpe/config.h>
8using namespace Opie::Core;
9
10/* QT */
5#include <qmessagebox.h> 11#include <qmessagebox.h>
6#include <qdir.h> 12#include <qdir.h>
7 13
8#include <qpe/config.h> 14/* STD */
9
10#include <errno.h> 15#include <errno.h>
11
12#include <sys/time.h> 16#include <sys/time.h>
13#include <sys/types.h> 17#include <sys/types.h>
14#include <sys/vfs.h> 18#include <sys/vfs.h>
15
16#include <fcntl.h> 19#include <fcntl.h>
17#include <math.h> 20#include <math.h>
18#include <mntent.h> 21#include <mntent.h>
19#include <stdio.h> 22#include <stdio.h>
20#include <stdlib.h> 23#include <stdlib.h>
21#include <unistd.h> 24#include <unistd.h>
22 25
23WavFile::WavFile( QObject * parent,const QString &fileName, bool makeNwFile, int sampleRate, 26WavFile::WavFile( QObject * parent,const QString &fileName, bool makeNwFile, int sampleRate,
24 int channels, int resolution, int format ) 27 int channels, int resolution, int format )
25 : QObject( parent) 28 : QObject( parent)
26{ 29{
27//qDebug("new wave file"); 30//odebug << "new wave file" << oendl;
28 bool b = makeNwFile; 31 bool b = makeNwFile;
29 wavSampleRate=sampleRate; 32 wavSampleRate=sampleRate;
30 wavFormat=format; 33 wavFormat=format;
31 wavChannels=channels; 34 wavChannels=channels;
32 wavResolution=resolution; 35 wavResolution=resolution;
33 useTmpFile=false; 36 useTmpFile=false;
34 if( b) { 37 if( b) {
35 newFile(); 38 newFile();
36 } else { 39 } else {
37 openFile(fileName); 40 openFile(fileName);
38 } 41 }
39} 42}
40 43
41bool WavFile::newFile() { 44bool WavFile::newFile() {
42 45
43// qDebug("Set up new file"); 46// odebug << "Set up new file" << oendl;
44 Config cfg("OpieRec"); 47 Config cfg("OpieRec");
45 cfg.setGroup("Settings"); 48 cfg.setGroup("Settings");
46 49
47 currentFileName=cfg.readEntry("directory",QDir::homeDirPath()); 50 currentFileName=cfg.readEntry("directory",QDir::homeDirPath());
48 QString date; 51 QString date;
49 QDateTime dt = QDateTime::currentDateTime(); 52 QDateTime dt = QDateTime::currentDateTime();
50 date = dt.toString();//TimeString::dateString( QDateTime::currentDateTime(),false,true); 53 date = dt.toString();//TimeString::dateString( QDateTime::currentDateTime(),false,true);
51 date.replace(QRegExp("'"),""); 54 date.replace(QRegExp("'"),"");
52 date.replace(QRegExp(" "),"_"); 55 date.replace(QRegExp(" "),"_");
53 date.replace(QRegExp(":"),"."); 56 date.replace(QRegExp(":"),".");
54 date.replace(QRegExp(","),""); 57 date.replace(QRegExp(","),"");
55 58
56 QString currentFile=date; 59 QString currentFile=date;
57 if(currentFileName.right(1).find("/",0,true) == -1) 60 if(currentFileName.right(1).find("/",0,true) == -1)
58 currentFileName += "/" + date; 61 currentFileName += "/" + date;
59 else 62 else
60 currentFileName += date; 63 currentFileName += date;
61 currentFileName+=".wav"; 64 currentFileName+=".wav";
62 65
63// qDebug("set up file for recording: "+currentFileName); 66// odebug << "set up file for recording: "+currentFileName << oendl;
64 char pointer[] = "/tmp/opierec-XXXXXX"; 67 char pointer[] = "/tmp/opierec-XXXXXX";
65 int fd = 0; 68 int fd = 0;
66 69
67 if( currentFileName.find("/mnt",0,true) == -1 70 if( currentFileName.find("/mnt",0,true) == -1
68 && currentFileName.find("/tmp",0,true) == -1 ) { 71 && currentFileName.find("/tmp",0,true) == -1 ) {
69 // if destination file is most likely in flash (assuming jffs2) 72 // if destination file is most likely in flash (assuming jffs2)
70 // we have to write to a different filesystem first 73 // we have to write to a different filesystem first
71 74
72 useTmpFile = true; 75 useTmpFile = true;
73 if(( fd = mkstemp( pointer)) < 0 ) { 76 if(( fd = mkstemp( pointer)) < 0 ) {
74 perror("mkstemp failed"); 77 perror("mkstemp failed");
75 return false; 78 return false;
76 } 79 }
77 80
78// qDebug("Opening tmp file %s",pointer); 81// odebug << "Opening tmp file " << pointer << "" << oendl;
79 track.setName( pointer); 82 track.setName( pointer);
80 83
81 } else { //just use regular file.. no moving 84 } else { //just use regular file.. no moving
82 85
83 useTmpFile = false; 86 useTmpFile = false;
84 track.setName( currentFileName); 87 track.setName( currentFileName);
85 } 88 }
86 if(!track.open( IO_ReadWrite | IO_Truncate)) { 89 if(!track.open( IO_ReadWrite | IO_Truncate)) {
87 QString errorMsg=(QString)strerror(errno); 90 QString errorMsg=(QString)strerror(errno);
88 qDebug(errorMsg); 91 odebug << errorMsg << oendl;
89 QMessageBox::message("Note", "Error opening file.\n" +errorMsg); 92 QMessageBox::message("Note", "Error opening file.\n" +errorMsg);
90 93
91 return false; 94 return false;
92 } else { 95 } else {
93 setWavHeader( track.handle() , &hdr); 96 setWavHeader( track.handle() , &hdr);
94 } 97 }
95return true; 98return true;
96} 99}
97 100
98WavFile::~WavFile() { 101WavFile::~WavFile() {
99 102
100 closeFile(); 103 closeFile();
101} 104}
102 105
103void WavFile::closeFile() { 106void WavFile::closeFile() {
104 if(track.isOpen()) 107 if(track.isOpen())
105 track.close(); 108 track.close();
106} 109}
107 110
108int WavFile::openFile(const QString &currentFileName) { 111int WavFile::openFile(const QString &currentFileName) {
109// qDebug("open play file "+currentFileName); 112// odebug << "open play file "+currentFileName << oendl;
110 closeFile(); 113 closeFile();
111 114
112 track.setName(currentFileName); 115 track.setName(currentFileName);
113 116
114 if(!track.open(IO_ReadOnly)) { 117 if(!track.open(IO_ReadOnly)) {
115 QString errorMsg=(QString)strerror(errno); 118 QString errorMsg=(QString)strerror(errno);
116 qDebug("<<<<<<<<<<< "+errorMsg+currentFileName); 119 odebug << "<<<<<<<<<<< "+errorMsg+currentFileName << oendl;
117 QMessageBox::message("Note", "Error opening file.\n" +errorMsg); 120 QMessageBox::message("Note", "Error opening file.\n" +errorMsg);
118 return -1; 121 return -1;
119 } else { 122 } else {
120 parseWavHeader( track.handle()); 123 parseWavHeader( track.handle());
121 } 124 }
122 return track.handle(); 125 return track.handle();
123} 126}
124 127
125bool WavFile::setWavHeader(int fd, wavhdr *hdr) { 128bool WavFile::setWavHeader(int fd, wavhdr *hdr) {
126 129
127 strncpy((*hdr).riffID, "RIFF", 4); // RIFF 130 strncpy((*hdr).riffID, "RIFF", 4); // RIFF
128 strncpy((*hdr).wavID, "WAVE", 4); //WAVE 131 strncpy((*hdr).wavID, "WAVE", 4); //WAVE
129 strncpy((*hdr).fmtID, "fmt ", 4); // fmt 132 strncpy((*hdr).fmtID, "fmt ", 4); // fmt
130 (*hdr).fmtLen = 16; // format length = 16 133 (*hdr).fmtLen = 16; // format length = 16
131 134
132 if( wavFormat == WAVE_FORMAT_PCM) { 135 if( wavFormat == WAVE_FORMAT_PCM) {
133 (*hdr).fmtTag = 1; // PCM 136 (*hdr).fmtTag = 1; // PCM
134// qDebug("set header WAVE_FORMAT_PCM"); 137// odebug << "set header WAVE_FORMAT_PCM" << oendl;
135 } 138 }
136 else { 139 else {
137 (*hdr).fmtTag = WAVE_FORMAT_DVI_ADPCM; //intel ADPCM 140 (*hdr).fmtTag = WAVE_FORMAT_DVI_ADPCM; //intel ADPCM
138 // qDebug("set header WAVE_FORMAT_DVI_ADPCM"); 141 // odebug << "set header WAVE_FORMAT_DVI_ADPCM" << oendl;
139 } 142 }
140 143
141 // (*hdr).nChannels = 1;//filePara.channels;// ? 2 : 1*/; // channels 144 // (*hdr).nChannels = 1;//filePara.channels;// ? 2 : 1*/; // channels
142 (*hdr).nChannels = wavChannels;// ? 2 : 1*/; // channels 145 (*hdr).nChannels = wavChannels;// ? 2 : 1*/; // channels
143 146
144 (*hdr).sampleRate = wavSampleRate; //samples per second 147 (*hdr).sampleRate = wavSampleRate; //samples per second
145 (*hdr).avgBytesPerSec = (wavSampleRate)*( wavChannels*(wavResolution/8)); // bytes per second 148 (*hdr).avgBytesPerSec = (wavSampleRate)*( wavChannels*(wavResolution/8)); // bytes per second
146 (*hdr).nBlockAlign = wavChannels*( wavResolution/8); //block align 149 (*hdr).nBlockAlign = wavChannels*( wavResolution/8); //block align
147 (*hdr).bitsPerSample = wavResolution; //bits per sample 8, or 16 150 (*hdr).bitsPerSample = wavResolution; //bits per sample 8, or 16
148 151
149 strncpy((*hdr).dataID, "data", 4); 152 strncpy((*hdr).dataID, "data", 4);
150 153
151 write( fd,hdr, sizeof(*hdr)); 154 write( fd,hdr, sizeof(*hdr));
152 qDebug("writing header: bitrate%d, samplerate %d, channels %d", 155 qDebug("writing header: bitrate%d, samplerate %d, channels %d",
153 wavResolution, wavSampleRate, wavChannels); 156 wavResolution, wavSampleRate, wavChannels);
154 return true; 157 return true;
155} 158}
156 159
157bool WavFile::adjustHeaders(int fd, int total) { 160bool WavFile::adjustHeaders(int fd, int total) {
158 lseek(fd, 4, SEEK_SET); 161 lseek(fd, 4, SEEK_SET);
159 int i = total + 36; 162 int i = total + 36;
160 write( fd, &i, sizeof(i)); 163 write( fd, &i, sizeof(i));
161 lseek( fd, 40, SEEK_SET); 164 lseek( fd, 40, SEEK_SET);
162 write( fd, &total, sizeof(total)); 165 write( fd, &total, sizeof(total));
163 qDebug("adjusting header %d", total); 166 odebug << "adjusting header " << total << "" << oendl;
164 return true; 167 return true;
165} 168}
166 169
167int WavFile::parseWavHeader(int fd) { 170int WavFile::parseWavHeader(int fd) {
168 qDebug("Parsing wav header"); 171 odebug << "Parsing wav header" << oendl;
169 char string[4]; 172 char string[4];
170 int found; 173 int found;
171 short fmt; 174 short fmt;
172 unsigned short ch, bitrate; 175 unsigned short ch, bitrate;
173 unsigned long samplerrate, longdata; 176 unsigned long samplerrate, longdata;
174 177
175 if (read(fd, string, 4) < 4) { 178 if (read(fd, string, 4) < 4) {
176 qDebug(" Could not read from sound file.\n"); 179 odebug << " Could not read from sound file.\n" << oendl;
177 return -1; 180 return -1;
178 } 181 }
179 if (strncmp(string, "RIFF", 4)) { 182 if (strncmp(string, "RIFF", 4)) {
180 qDebug(" not a valid WAV file.\n"); 183 odebug << " not a valid WAV file.\n" << oendl;
181 return -1; 184 return -1;
182 } 185 }
183 lseek(fd, 4, SEEK_CUR); 186 lseek(fd, 4, SEEK_CUR);
184 if (read(fd, string, 4) < 4) { 187 if (read(fd, string, 4) < 4) {
185 qDebug("Could not read from sound file.\n"); 188 odebug << "Could not read from sound file.\n" << oendl;
186 return -1; 189 return -1;
187 } 190 }
188 if (strncmp(string, "WAVE", 4)) { 191 if (strncmp(string, "WAVE", 4)) {
189 qDebug("not a valid WAV file.\n"); 192 odebug << "not a valid WAV file.\n" << oendl;
190 return -1; 193 return -1;
191 } 194 }
192 found = 0; 195 found = 0;
193 196
194 while (!found) { 197 while (!found) {
195 if (read(fd, string, 4) < 4) { 198 if (read(fd, string, 4) < 4) {
196 qDebug("Could not read from sound file.\n"); 199 odebug << "Could not read from sound file.\n" << oendl;
197 return -1; 200 return -1;
198 } 201 }
199 if (strncmp(string, "fmt ", 4)) { 202 if (strncmp(string, "fmt ", 4)) {
200 if (read(fd, &longdata, 4) < 4) { 203 if (read(fd, &longdata, 4) < 4) {
201 qDebug("Could not read from sound file.\n"); 204 odebug << "Could not read from sound file.\n" << oendl;
202 return -1; 205 return -1;
203 } 206 }
204 lseek(fd, longdata, SEEK_CUR); 207 lseek(fd, longdata, SEEK_CUR);
205 } else { 208 } else {
206 lseek(fd, 4, SEEK_CUR); 209 lseek(fd, 4, SEEK_CUR);
207 if (read(fd, &fmt, 2) < 2) { 210 if (read(fd, &fmt, 2) < 2) {
208 qDebug("Could not read format chunk.\n"); 211 odebug << "Could not read format chunk.\n" << oendl;
209 return -1; 212 return -1;
210 } 213 }
211 if (fmt != WAVE_FORMAT_PCM && fmt != WAVE_FORMAT_DVI_ADPCM) { 214 if (fmt != WAVE_FORMAT_PCM && fmt != WAVE_FORMAT_DVI_ADPCM) {
212 qDebug("Wave file contains unknown format." 215 qDebug("Wave file contains unknown format."
213 " Unable to continue.\n"); 216 " Unable to continue.\n");
214 return -1; 217 return -1;
215 } 218 }
216 wavFormat = fmt; 219 wavFormat = fmt;
217 // compressionFormat=fmt; 220 // compressionFormat=fmt;
218 qDebug("compressionFormat is %d", fmt); 221 odebug << "compressionFormat is " << fmt << "" << oendl;
219 if (read(fd, &ch, 2) < 2) { 222 if (read(fd, &ch, 2) < 2) {
220 qDebug("Could not read format chunk.\n"); 223 odebug << "Could not read format chunk.\n" << oendl;
221 return -1; 224 return -1;
222 } else { 225 } else {
223 wavChannels = ch; 226 wavChannels = ch;
224 qDebug("File has %d channels", ch); 227 odebug << "File has " << ch << " channels" << oendl;
225 } 228 }
226 if (read(fd, &samplerrate, 4) < 4) { 229 if (read(fd, &samplerrate, 4) < 4) {
227 qDebug("Could not read from format chunk.\n"); 230 odebug << "Could not read from format chunk.\n" << oendl;
228 return -1; 231 return -1;
229 } else { 232 } else {
230 wavSampleRate = samplerrate; 233 wavSampleRate = samplerrate;
231 // sampleRate = samplerrate; 234 // sampleRate = samplerrate;
232 qDebug("File has samplerate of %d",(int) samplerrate); 235 odebug << "File has samplerate of " << (int) samplerrate << "" << oendl;
233 } 236 }
234 lseek(fd, 6, SEEK_CUR); 237 lseek(fd, 6, SEEK_CUR);
235 if (read(fd, &bitrate, 2) < 2) { 238 if (read(fd, &bitrate, 2) < 2) {
236 qDebug("Could not read format chunk.\n"); 239 odebug << "Could not read format chunk.\n" << oendl;
237 return -1; 240 return -1;
238 } else { 241 } else {
239 wavResolution=bitrate; 242 wavResolution=bitrate;
240 // resolution = bitrate; 243 // resolution = bitrate;
241 qDebug("File has bitrate of %d", bitrate); 244 odebug << "File has bitrate of " << bitrate << "" << oendl;
242 } 245 }
243 found++; 246 found++;
244 } 247 }
245 } 248 }
246 found = 0; 249 found = 0;
247 while (!found) { 250 while (!found) {
248 if (read(fd, string, 4) < 4) { 251 if (read(fd, string, 4) < 4) {
249 qDebug("Could not read from sound file.\n"); 252 odebug << "Could not read from sound file.\n" << oendl;
250 return -1; 253 return -1;
251 } 254 }
252 255
253 if (strncmp(string, "data", 4)) { 256 if (strncmp(string, "data", 4)) {
254 if (read(fd, &longdata, 4)<4) { 257 if (read(fd, &longdata, 4)<4) {
255 qDebug("Could not read from sound file.\n"); 258 odebug << "Could not read from sound file.\n" << oendl;
256 return -1; 259 return -1;
257 } 260 }
258 261
259 lseek(fd, longdata, SEEK_CUR); 262 lseek(fd, longdata, SEEK_CUR);
260 } else { 263 } else {
261 if (read(fd, &longdata, 4) < 4) { 264 if (read(fd, &longdata, 4) < 4) {
262 qDebug("Could not read from sound file.\n"); 265 odebug << "Could not read from sound file.\n" << oendl;
263 return -1; 266 return -1;
264 } else { 267 } else {
265 wavNumberSamples = longdata; 268 wavNumberSamples = longdata;
266 qDebug("file has length of %d \nlasting %d seconds", (int)longdata, 269 qDebug("file has length of %d \nlasting %d seconds", (int)longdata,
267 (int)(( longdata / wavSampleRate) / wavChannels) / ( wavChannels*( wavResolution/8)) ); 270 (int)(( longdata / wavSampleRate) / wavChannels) / ( wavChannels*( wavResolution/8)) );
268// wavSeconds = (( longdata / wavSampleRate) / wavChannels) / ( wavChannels*( wavResolution/8)); 271// wavSeconds = (( longdata / wavSampleRate) / wavChannels) / ( wavChannels*( wavResolution/8));
269 272
270 return longdata; 273 return longdata;
271 } 274 }
272 } 275 }
273 } 276 }
274 277
275 lseek(fd, 0, SEEK_SET); 278 lseek(fd, 0, SEEK_SET);
276 279
277 return 0; 280 return 0;
278} 281}
279 282
280QString WavFile::trackName() { 283QString WavFile::trackName() {
281 return track.name(); 284 return track.name();
282} 285}
283 286
284int WavFile::wavHandle(){ 287int WavFile::wavHandle(){
285 return track.handle(); 288 return track.handle();
286} 289}
287 290
288int WavFile::getFormat() { 291int WavFile::getFormat() {
289return wavFormat; 292return wavFormat;
290} 293}
291 294
292int WavFile::getResolution() { 295int WavFile::getResolution() {
293return wavResolution; 296return wavResolution;
294} 297}
295 298
296int WavFile::getSampleRate() { 299int WavFile::getSampleRate() {
297 return wavSampleRate; 300 return wavSampleRate;
298} 301}
299 302
300int WavFile::getNumberSamples() { 303int WavFile::getNumberSamples() {
301 return wavNumberSamples; 304 return wavNumberSamples;
302} 305}
303 306
304bool WavFile::isTempFile() { 307bool WavFile::isTempFile() {
305return useTmpFile; 308return useTmpFile;
306} 309}
307 310
308int WavFile::getChannels() { 311int WavFile::getChannels() {
309 312
310 return wavChannels; 313 return wavChannels;
311} 314}
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 @@
1/********************************************************************** 1/**********************************************************************
2 ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2 ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3 ** 3 **
4 ** This file is part of the Qtopia Environment. 4 ** This file is part of the Qtopia Environment.
5 ** 5 **
6 ** This file may be distributed and/or modified under the terms of the 6 ** This file may be distributed and/or modified under the terms of the
7 ** GNU General Public License version 2 as published by the Free Software 7 ** GNU General Public License version 2 as published by the Free Software
8 ** Foundation and appearing in the file LICENSE.GPL included in the 8 ** Foundation and appearing in the file LICENSE.GPL included in the
9 ** packaging of this file. 9 ** packaging of this file.
10 ** 10 **
11 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13 ** 13 **
14 ** See http://www.trolltech.com/gpl/ for GPL licensing information. 14 ** See http://www.trolltech.com/gpl/ for GPL licensing information.
15 ** 15 **
16 ** Contact info@trolltech.com if any conditions of this licensing are 16 ** Contact info@trolltech.com if any conditions of this licensing are
17 ** not clear to you. 17 ** not clear to you.
18 ** 18 **
19 **********************************************************************/ 19 **********************************************************************/
20#include "waveform.h" 20#include "waveform.h"
21 21
22#include <qpainter.h> 22/* OPIE */
23#include <opie2/odebug.h>
24using namespace Opie::Core;
23 25
26/* QT */
27#include <qpainter.h>
24 28
25Waveform::Waveform( QWidget *parent, const char *name, WFlags fl ) 29Waveform::Waveform( QWidget *parent, const char *name, WFlags fl )
26 : QWidget( parent, name, fl ) 30 : QWidget( parent, name, fl )
27{ 31{
28 pixmap = 0; 32 pixmap = 0;
29 windowSize = 100; 33 windowSize = 100;
30 samplesPerPixel = 8000 / (5 * windowSize); 34 samplesPerPixel = 8000 / (5 * windowSize);
31 currentValue = 0; 35 currentValue = 0;
32 numSamples = 0; 36 numSamples = 0;
33 windowPosn = 0; 37 windowPosn = 0;
34 window = 0; 38 window = 0;
35} 39}
36 40
37 41
38void Waveform::changeSettings( int frequency, int channels ) 42void Waveform::changeSettings( int frequency, int channels )
39{ 43{
40 makePixmap(); 44 makePixmap();
41// qWarning("change waveform %d, %d", frequency, channels); 45// owarn << "change waveform " << frequency << ", " << channels << "" << oendl;
42 samplesPerPixel = frequency * channels / (5 * windowSize); 46 samplesPerPixel = frequency * channels / (5 * windowSize);
43 qWarning("Waveform::changeSettings %d", samplesPerPixel); 47 owarn << "Waveform::changeSettings " << samplesPerPixel << "" << oendl;
44 if ( !samplesPerPixel ) 48 if ( !samplesPerPixel )
45 samplesPerPixel = 1; 49 samplesPerPixel = 1;
46 currentValue = 0; 50 currentValue = 0;
47 numSamples = 0; 51 numSamples = 0;
48 windowPosn = 0; 52 windowPosn = 0;
49 draw(); 53 draw();
50} 54}
51 55
52 56
53Waveform::~Waveform() 57Waveform::~Waveform()
54{ 58{
55 if ( window ) 59 if ( window )
56 delete[] window; 60 delete[] window;
57 if ( pixmap ) 61 if ( pixmap )
58 delete pixmap; 62 delete pixmap;
59} 63}
60 64
61 65
62void Waveform::reset() 66void Waveform::reset()
63{ 67{
64 makePixmap(); 68 makePixmap();
65 currentValue = 0; 69 currentValue = 0;
66 numSamples = 0; 70 numSamples = 0;
67 windowPosn = 0; 71 windowPosn = 0;
68 draw(); 72 draw();
69} 73}
70 74
71 75
72void Waveform::newSamples( const short *buf, int len ) 76void Waveform::newSamples( const short *buf, int len )
73{ 77{
74 // Cache the object values in local variables. 78 // Cache the object values in local variables.
75 int samplesPerPixel = this->samplesPerPixel; 79 int samplesPerPixel = this->samplesPerPixel;
76 int currentValue = this->currentValue; 80 int currentValue = this->currentValue;
77 int numSamples = this->numSamples; 81 int numSamples = this->numSamples;
78 short *window = this->window; 82 short *window = this->window;
79 int windowPosn = this->windowPosn; 83 int windowPosn = this->windowPosn;
80 int windowSize = this->windowSize; 84 int windowSize = this->windowSize;
81 85
82 // Average the incoming samples to scale them to the window. 86 // Average the incoming samples to scale them to the window.
83 while ( len > 0 ) { 87 while ( len > 0 ) {
84 currentValue += *buf++; 88 currentValue += *buf++;
85 --len; 89 --len;
86 if ( ++numSamples >= samplesPerPixel ) { 90 if ( ++numSamples >= samplesPerPixel ) {
87 window[windowPosn++] = (short)(currentValue / numSamples); 91 window[windowPosn++] = (short)(currentValue / numSamples);
88 if ( windowPosn >= windowSize ) { 92 if ( windowPosn >= windowSize ) {
89 this->windowPosn = windowPosn; 93 this->windowPosn = windowPosn;
90 draw(); 94 draw();
91 windowPosn = 0; 95 windowPosn = 0;
92 } 96 }
93 numSamples = 0; 97 numSamples = 0;
94 currentValue = 0; 98 currentValue = 0;
95 } 99 }
96 } 100 }
97 101
98 // Copy the final state back to the object. 102 // Copy the final state back to the object.
99//qWarning("%d, %d, %d", currentValue, numSamples, windowPosn); 103//owarn << "" << currentValue << ", " << numSamples << ", " << windowPosn << "" << oendl;
100 this->currentValue = currentValue; 104 this->currentValue = currentValue;
101 this->numSamples = numSamples; 105 this->numSamples = numSamples;
102 this->windowPosn = windowPosn; 106 this->windowPosn = windowPosn;
103} 107}
104 108
105 109
106void Waveform::makePixmap() 110void Waveform::makePixmap()
107{ 111{
108 if ( !pixmap ) { 112 if ( !pixmap ) {
109 pixmap = new QPixmap( size() ); 113 pixmap = new QPixmap( size() );
110 windowSize = pixmap->width(); 114 windowSize = pixmap->width();
111 window = new short [windowSize]; 115 window = new short [windowSize];
112 } 116 }
113} 117}
114 118
115 119
116void Waveform::draw() 120void Waveform::draw()
117{ 121{
118 pixmap->fill( Qt::black ); 122 pixmap->fill( Qt::black );
119 QPainter painter; 123 QPainter painter;
120 painter.begin( pixmap ); 124 painter.begin( pixmap );
121 painter.setPen( Qt::green ); 125 painter.setPen( Qt::green );
122 126
123 int middle = pixmap->height() / 2; 127 int middle = pixmap->height() / 2;
124 int mag; 128 int mag;
125 short *window = this->window; 129 short *window = this->window;
126 int posn; 130 int posn;
127 int size = windowPosn; 131 int size = windowPosn;
128 for( posn = 0; posn < size; ++posn ) 132 for( posn = 0; posn < size; ++posn )
129 { 133 {
130 mag = (window[posn] * middle / 32768); 134 mag = (window[posn] * middle / 32768);
131 painter.drawLine(posn, middle - mag, posn, middle + mag); 135 painter.drawLine(posn, middle - mag, posn, middle + mag);
132 } 136 }
133 if ( windowPosn < windowSize ) 137 if ( windowPosn < windowSize )
134 { 138 {
135 painter.drawLine(windowPosn, middle, windowSize, middle); 139 painter.drawLine(windowPosn, middle, windowSize, middle);
136 } 140 }
137 141
138 painter.end(); 142 painter.end();
139 143
140 paintEvent( 0 ); 144 paintEvent( 0 );
141} 145}
142 146
143 147
144void Waveform::paintEvent( QPaintEvent * ) 148void Waveform::paintEvent( QPaintEvent * )
145{ 149{
146 QPainter painter; 150 QPainter painter;
147 painter.begin( this ); 151 painter.begin( this );
148 152
149 if ( pixmap ) { 153 if ( pixmap ) {
150 painter.drawPixmap( 0, 0, *pixmap ); 154 painter.drawPixmap( 0, 0, *pixmap );
151 } else { 155 } else {
152 painter.setPen( Qt::green ); 156 painter.setPen( Qt::green );
153 QSize sz = size(); 157 QSize sz = size();
154 painter.drawLine(0, sz.height() / 2, sz.width(), sz.height() / 2); 158 painter.drawLine(0, sz.height() / 2, sz.width(), sz.height() / 2);
155 } 159 }
156 160
157 painter.end(); 161 painter.end();
158} 162}
159 163
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 @@
1 config POWERCHORD 1 config POWERCHORD
2 boolean "opie-powerchord (guitar chord generator and tuning)" 2 boolean "opie-powerchord (guitar chord generator and tuning)"
3 default "n" 3 default "n"
4 depends ( LIBQPE || LIBQPE-X11 ) 4 depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
5 comment "opie-powerchord needs a libqpe" 5 comment "opie-powerchord needs a libqpe and libopiecore2"
6 depends !(( LIBQPE || LIBQPE-X11 ) ) 6 depends !(( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE )
7 7
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 @@
1 TEMPLATE= app 1 TEMPLATE= app
2 CONFIG = qt warn_on 2 CONFIG = qt warn_on
3 3
4 HEADERS = powerchord.h \ 4 HEADERS = powerchord.h \
5 fretboard.h \ 5 fretboard.h \
6 chordengine.h \ 6 chordengine.h \
7 vumeter.h \ 7 vumeter.h \
8 gs.h gt.h \ 8 gs.h gt.h \
9 powerchordbase.h 9 powerchordbase.h
10 10
11 SOURCES = main.cpp \ 11 SOURCES = main.cpp \
12 powerchord.cpp \ 12 powerchord.cpp \
13 fretboard.cpp \ 13 fretboard.cpp \
14 chordengine.cpp \ 14 chordengine.cpp \
15 vumeter.cpp \ 15 vumeter.cpp \
16 gs.cpp gt.cpp \ 16 gs.cpp gt.cpp \
17 powerchordbase.cpp 17 powerchordbase.cpp
18 18
19 INCLUDEPATH+= $(OPIEDIR)/include 19 INCLUDEPATH+= $(OPIEDIR)/include
20 DEPENDPATH+= $(OPIEDIR)/include 20 DEPENDPATH+= $(OPIEDIR)/include
21LIBS += -lqpe 21LIBS += -lqpe -lopiecore2
22 #INTERFACES= powerchordbase.ui
23DESTDIR = $(OPIEDIR)/bin 22DESTDIR = $(OPIEDIR)/bin
24 TARGET = powerchord 23 TARGET = powerchord
25 24
26include ( $(OPIEDIR)/include.pro ) 25include ( $(OPIEDIR)/include.pro )
27 26
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 @@
1/**************************************************************************** 1/****************************************************************************
2** Form implementation generated from reading ui file 'powerchordbase.ui' 2** Form implementation generated from reading ui file 'powerchordbase.ui'
3** 3**
4** Created: Sun Jan 13 23:05:11 2002 4** Created: Sun Jan 13 23:05:11 2002
5** by: The User Interface Compiler (uic) 5** by: The User Interface Compiler (uic)
6** 6**
7** WARNING! All changes made in this file will be lost! 7** WARNING! All changes made in this file will be lost!
8****************************************************************************/ 8****************************************************************************/
9#include "powerchordbase.h" 9#include "powerchordbase.h"
10
11#include "fretboard.h" 10#include "fretboard.h"
12#include "vumeter.h" 11#include "vumeter.h"
12
13/* OPIE */
14#include <opie2/odebug.h>
15#include <qpe/resource.h>
16using namespace Opie::Core;
17
18/* QT */
13#include <qcombobox.h> 19#include <qcombobox.h>
14#include <qlabel.h> 20#include <qlabel.h>
15#include <qlistbox.h> 21#include <qlistbox.h>
16#include <qpushbutton.h> 22#include <qpushbutton.h>
17#include <qspinbox.h> 23#include <qspinbox.h>
18#include <qtabwidget.h> 24#include <qtabwidget.h>
19#include <qlayout.h> 25#include <qlayout.h>
20#include <qtooltip.h> 26#include <qtooltip.h>
21#include <qpe/resource.h>
22
23 27
24/* 28/*
25 * Constructs a PowerchordBase which is a child of 'parent', with the 29 * Constructs a PowerchordBase which is a child of 'parent', with the
26 * name 'name' and widget flags set to 'f' 30 * name 'name' and widget flags set to 'f'
27 */ 31 */
28PowerchordBase::PowerchordBase( QWidget* parent, const char* name, WFlags fl ) 32PowerchordBase::PowerchordBase( QWidget* parent, const char* name, WFlags fl )
29 : QWidget( parent, name, fl ) 33 : QWidget( parent, name, fl )
30{ 34{
31 simulation_timer = 0; 35 simulation_timer = 0;
32 audio_timer = 0; 36 audio_timer = 0;
33 37
34 // setPalette( QPalette( QColor( 232, 227, 215) ) ); 38 // setPalette( QPalette( QColor( 232, 227, 215) ) );
35 39
36 // QPixmap image0(QString("/opt/Qtopia/pics/powerchord/image0")); 40 // QPixmap image0(QString("/opt/Qtopia/pics/powerchord/image0"));
37 QPixmap image1 = Resource::loadPixmap( "powerchord/image1"); 41 QPixmap image1 = Resource::loadPixmap( "powerchord/image1");
38 QPixmap image2 = Resource::loadPixmap( "powerchord/image2"); 42 QPixmap image2 = Resource::loadPixmap( "powerchord/image2");
39 QPixmap image3 = Resource::loadPixmap( "powerchord/image3"); 43 QPixmap image3 = Resource::loadPixmap( "powerchord/image3");
40 QPixmap image4 = Resource::loadPixmap( "powerchord/image4"); 44 QPixmap image4 = Resource::loadPixmap( "powerchord/image4");
41 QPixmap image5 = Resource::loadPixmap( "powerchord/image5"); 45 QPixmap image5 = Resource::loadPixmap( "powerchord/image5");
42 image6 = Resource::loadPixmap( "powerchord/image6"); 46 image6 = Resource::loadPixmap( "powerchord/image6");
43 image_open = Resource::loadPixmap( "powerchord/image_open"); 47 image_open = Resource::loadPixmap( "powerchord/image_open");
44 48
45 // image0.setMask(image0.createHeuristicMask()); 49 // image0.setMask(image0.createHeuristicMask());
46 image1.setMask(image1.createHeuristicMask()); 50 image1.setMask(image1.createHeuristicMask());
47 // image2.setMask(image2.createHeuristicMask()); 51 // image2.setMask(image2.createHeuristicMask());
48 // image3.setMask(image3.createHeuristicMask()); 52 // image3.setMask(image3.createHeuristicMask());
49 // image4.setMask(image4.createHeuristicMask()); 53 // image4.setMask(image4.createHeuristicMask());
50 // image5.setMask(image5.createHeuristicMask()); 54 // image5.setMask(image5.createHeuristicMask());
51 // image6->setMask(image6->createHeuristicMask()); 55 // image6->setMask(image6->createHeuristicMask());
52 // image_open->setMask(image_open->createHeuristicMask()); 56 // image_open->setMask(image_open->createHeuristicMask());
53 57
54 if ( !name ) 58 if ( !name )
55 setName( "PowerchordBase" ); 59 setName( "PowerchordBase" );
56 resize( 240, 284 ); 60 resize( 240, 284 );
57 setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)5, sizePolicy().hasHeightForWidth() ) ); 61 setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)5, sizePolicy().hasHeightForWidth() ) );
58 setMinimumSize( QSize( 240, 284 ) ); 62 setMinimumSize( QSize( 240, 284 ) );
59 setMaximumSize( QSize( 240, 284 ) ); 63 setMaximumSize( QSize( 240, 284 ) );
60 setCaption( tr( "Powerchord" ) ); 64 setCaption( tr( "Powerchord" ) );
61 65
62 tabs = new QTabWidget( this, "tabs" ); 66 tabs = new QTabWidget( this, "tabs" );
63 tabs->setEnabled( TRUE ); 67 tabs->setEnabled( TRUE );
64 tabs->setGeometry( QRect( 0, 0, 240, 286 ) ); 68 tabs->setGeometry( QRect( 0, 0, 240, 286 ) );
65 tabs->setTabPosition( QTabWidget::Bottom ); 69 tabs->setTabPosition( QTabWidget::Bottom );
66 70
67 tab = new QWidget( tabs, "tab" ); 71 tab = new QWidget( tabs, "tab" );
68 72
69 chordkey = new QComboBox( FALSE, tab, "chordkey" ); 73 chordkey = new QComboBox( FALSE, tab, "chordkey" );
70 chordkey->insertItem( tr( "maj" ) ); 74 chordkey->insertItem( tr( "maj" ) );
71 chordkey->insertItem( tr( "min" ) ); 75 chordkey->insertItem( tr( "min" ) );
72 chordkey->insertItem( tr( "7th" ) ); 76 chordkey->insertItem( tr( "7th" ) );
73 chordkey->insertItem( tr( "m7" ) ); 77 chordkey->insertItem( tr( "m7" ) );
74 chordkey->insertItem( tr( "maj7" ) ); 78 chordkey->insertItem( tr( "maj7" ) );
75 chordkey->insertItem( tr( "6th" ) ); 79 chordkey->insertItem( tr( "6th" ) );
76 chordkey->insertItem( tr( "m6th" ) ); 80 chordkey->insertItem( tr( "m6th" ) );
77 chordkey->insertItem( tr( "aug" ) ); 81 chordkey->insertItem( tr( "aug" ) );
78 chordkey->insertItem( tr( "dim" ) ); 82 chordkey->insertItem( tr( "dim" ) );
79 chordkey->insertItem( tr( "sus4" ) ); 83 chordkey->insertItem( tr( "sus4" ) );
80 chordkey->insertItem( tr( "7sus4" ) ); 84 chordkey->insertItem( tr( "7sus4" ) );
81 chordkey->insertItem( tr( "9th" ) ); 85 chordkey->insertItem( tr( "9th" ) );
82 chordkey->insertItem( tr( "add9" ) ); 86 chordkey->insertItem( tr( "add9" ) );
83 chordkey->insertItem( tr( "m9th" ) ); 87 chordkey->insertItem( tr( "m9th" ) );
84 chordkey->insertItem( tr( "maj9" ) ); 88 chordkey->insertItem( tr( "maj9" ) );
85 chordkey->insertItem( tr( "sus2" ) ); 89 chordkey->insertItem( tr( "sus2" ) );
86 chordkey->insertItem( tr( "7sus2" ) ); 90 chordkey->insertItem( tr( "7sus2" ) );
87 chordkey->insertItem( tr( "11th" ) ); 91 chordkey->insertItem( tr( "11th" ) );
88 chordkey->insertItem( tr( "m11th" ) ); 92 chordkey->insertItem( tr( "m11th" ) );
89 chordkey->insertItem( tr( "13th" ) ); 93 chordkey->insertItem( tr( "13th" ) );
90 chordkey->insertItem( tr( "m13th" ) ); 94 chordkey->insertItem( tr( "m13th" ) );
91 chordkey->insertItem( tr( "maj13" ) ); 95 chordkey->insertItem( tr( "maj13" ) );
92 chordkey->insertItem( tr( "6/9" ) ); 96 chordkey->insertItem( tr( "6/9" ) );
93 chordkey->insertItem( tr( "flat5" ) ); 97 chordkey->insertItem( tr( "flat5" ) );
94 chordkey->insertItem( tr( "7#9" ) ); 98 chordkey->insertItem( tr( "7#9" ) );
95 chordkey->insertItem( tr( QString::fromUtf8( "ø7" ) ) ); 99 chordkey->insertItem( tr( QString::fromUtf8( "ø7" ) ) );
96 chordkey->insertItem( tr( "5" ) ); 100 chordkey->insertItem( tr( "5" ) );
97 chordkey->setGeometry( QRect( 40, 0, 51, 21 ) ); 101 chordkey->setGeometry( QRect( 40, 0, 51, 21 ) );
98 102
99 chordfret = new QComboBox( FALSE, tab, "chordfret" ); 103 chordfret = new QComboBox( FALSE, tab, "chordfret" );
100 chordfret->insertItem( tr( "open" ) ); 104 chordfret->insertItem( tr( "open" ) );
101 chordfret->insertItem( tr( "1st" ) ); 105 chordfret->insertItem( tr( "1st" ) );
102 chordfret->insertItem( tr( "2nd" ) ); 106 chordfret->insertItem( tr( "2nd" ) );
103 chordfret->insertItem( tr( "3rd" ) ); 107 chordfret->insertItem( tr( "3rd" ) );
104 chordfret->insertItem( tr( "4th" ) ); 108 chordfret->insertItem( tr( "4th" ) );
105 chordfret->insertItem( tr( "5th" ) ); 109 chordfret->insertItem( tr( "5th" ) );
106 chordfret->insertItem( tr( "6th" ) ); 110 chordfret->insertItem( tr( "6th" ) );
107 chordfret->insertItem( tr( "7th" ) ); 111 chordfret->insertItem( tr( "7th" ) );
108 chordfret->insertItem( tr( "8th" ) ); 112 chordfret->insertItem( tr( "8th" ) );
109 chordfret->insertItem( tr( "9th" ) ); 113 chordfret->insertItem( tr( "9th" ) );
110 chordfret->insertItem( tr( "10th" ) ); 114 chordfret->insertItem( tr( "10th" ) );
111 chordfret->insertItem( tr( "11th" ) ); 115 chordfret->insertItem( tr( "11th" ) );
112 chordfret->insertItem( tr( "12th" ) ); 116 chordfret->insertItem( tr( "12th" ) );
113 chordfret->insertItem( tr( "13th" ) ); 117 chordfret->insertItem( tr( "13th" ) );
114 chordfret->insertItem( tr( "14th" ) ); 118 chordfret->insertItem( tr( "14th" ) );
115 chordfret->insertItem( tr( "15th" ) ); 119 chordfret->insertItem( tr( "15th" ) );
116 chordfret->insertItem( tr( "16th" ) ); 120 chordfret->insertItem( tr( "16th" ) );
117 chordfret->setGeometry( QRect( 90, 0, 55, 21 ) ); //cxm less 5 width 121 chordfret->setGeometry( QRect( 90, 0, 55, 21 ) ); //cxm less 5 width
118 122
@@ -487,99 +491,99 @@ void PowerchordBase::audio_cb(){
487// the real tuner 491// the real tuner
488// void PowerchordBase::tuner_start_cb(){ 492// void PowerchordBase::tuner_start_cb(){
489 493
490// if (tuner->Listening()){ 494// if (tuner->Listening()){
491// simulation_timer->stop(); 495// simulation_timer->stop();
492// tuner->Stop(); 496// tuner->Stop();
493// tuner_pic1->setPixmap( *image6 ); 497// tuner_pic1->setPixmap( *image6 );
494 498
495// }else{ 499// }else{
496// tuner_pic1->setPixmap( *image_open ); 500// tuner_pic1->setPixmap( *image_open );
497 501
498// if (!simulation_timer){ 502// if (!simulation_timer){
499// simulation_timer = new QTimer(); 503// simulation_timer = new QTimer();
500 504
501 505
502// connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_cb() )); 506// connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_cb() ));
503// } 507// }
504 508
505// simulation_timer->start(50); 509// simulation_timer->start(50);
506// tuner->Listen(); 510// tuner->Listen();
507 511
508// } 512// }
509// } 513// }
510 514
511void PowerchordBase::tuner_cb(){ 515void PowerchordBase::tuner_cb(){
512 if (tuner->Listening()){ 516 if (tuner->Listening()){
513 tuner->read_buffer(); 517 tuner->read_buffer();
514 tuner->process_buffer(); 518 tuner->process_buffer();
515 519
516 // update gui 520 // update gui
517 // do something with the note: tuner->Note() 521 // do something with the note: tuner->Note()
518 emit frequency_change(tuner->Tuning()); 522 emit frequency_change(tuner->Tuning());
519 523
520 }else{ 524 }else{
521 simulation_timer->stop(); 525 simulation_timer->stop();
522 tuner->Stop(); 526 tuner->Stop();
523 tuner_pic1->setPixmap( image6 ); 527 tuner_pic1->setPixmap( image6 );
524 } 528 }
525} 529}
526 530
527 531
528void PowerchordBase::tuner_start_cb(){ 532void PowerchordBase::tuner_start_cb(){
529 if (0 == QMessageBox::information(this, "Powerchord", "Using the microphone,\nthe note's frequency\nis analysed. This\nis a simulation.", "OK", "Cancel", 0, 1)){ 533 if (0 == QMessageBox::information(this, "Powerchord", "Using the microphone,\nthe note's frequency\nis analysed. This\nis a simulation.", "OK", "Cancel", 0, 1)){
530 if (simulation_timer){ 534 if (simulation_timer){
531 simulation_timer->stop(); 535 simulation_timer->stop();
532 }else{ 536 }else{
533 simulation_timer = new QTimer(); 537 simulation_timer = new QTimer();
534 connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_simulation_cb() )); 538 connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_simulation_cb() ));
535 539
536 } 540 }
537 simulation_x = -45; 541 simulation_x = -45;
538 simulation_v = 0; 542 simulation_v = 0;
539 simulation_iter = 0; 543 simulation_iter = 0;
540 544
541 tuner_pic1->setPixmap( image_open ); 545 tuner_pic1->setPixmap( image_open );
542 simulation_timer->start(100); 546 simulation_timer->start(100);
543 } 547 }
544} 548}
545 549
546#include <stdio.h> 550#include <stdio.h>
547 551
548void PowerchordBase::tuner_simulation_cb(){ 552void PowerchordBase::tuner_simulation_cb(){
549 if (simulation_x < -10 || simulation_x > 10){ 553 if (simulation_x < -10 || simulation_x > 10){
550 simulation_v = (simulation_v/2)-(simulation_x/5); 554 simulation_v = (simulation_v/2)-(simulation_x/5);
551 } 555 }
552 556
553 simulation_x += simulation_v; 557 simulation_x += simulation_v;
554 simulation_iter++; 558 simulation_iter++;
555 559
556 if (simulation_x > 50){ 560 if (simulation_x > 50){
557 simulation_x = 50; 561 simulation_x = 50;
558 } 562 }
559 563
560 if (simulation_x < -50){ 564 if (simulation_x < -50){
561 simulation_x = -50; 565 simulation_x = -50;
562 } 566 }
563 567
564 if (simulation_iter > 50){ 568 if (simulation_iter > 50){
565 simulation_timer->stop(); 569 simulation_timer->stop();
566 emit frequency_change(0); 570 emit frequency_change(0);
567 tuner_pic1->setPixmap( image6 ); 571 tuner_pic1->setPixmap( image6 );
568 }else{ 572 }else{
569 emit frequency_change(simulation_x); 573 emit frequency_change(simulation_x);
570 } 574 }
571} 575}
572 576
573/* 577/*
574 * Destroys the object and frees any allocated resources 578 * Destroys the object and frees any allocated resources
575 */ 579 */
576PowerchordBase::~PowerchordBase() 580PowerchordBase::~PowerchordBase()
577{ 581{
578 // no need to delete child widgets, Qt does it all for us 582 // no need to delete child widgets, Qt does it all for us
579} 583}
580 584
581void PowerchordBase::change_handler() 585void PowerchordBase::change_handler()
582{ 586{
583 qWarning( "PowerchordBase::change_handler(): Not implemented yet!" ); 587 owarn << "PowerchordBase::change_handler(): Not implemented yet!" << oendl;
584} 588}
585 589
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 @@
1#include "ImageFileSelector.h"
1 2
3/* OPIE */
4#include <opie2/odebug.h>
5#include <qpe/qpeapplication.h>
6using namespace Opie::Core;
2 7
3#include "qpe/qpeapplication.h" 8/* QT */
4 9#include <qlabel.h>
5#include <stdlib.h>
6
7#include <qlabel.h>
8#include <qfileinfo.h> 10#include <qfileinfo.h>
9 11
10#include "ImageFileSelector.h" 12/* STD */
11 13#include <stdlib.h>
12 14
13ThumbWidget::ThumbWidget(QPixmap p,QString text,const DocLnk& f,QWidget *parent,int w) 15ThumbWidget::ThumbWidget(QPixmap p,QString text,const DocLnk& f,QWidget *parent,int w)
14 : QWidget( parent ),fl(f) 16 : QWidget( parent ),fl(f)
15{ 17{
16 setBackgroundMode(NoBackground); 18 setBackgroundMode(NoBackground);
17 if ( w!=-1 ) 19 if ( w!=-1 )
18 setMinimumSize(w,p.height()+24); 20 setMinimumSize(w,p.height()+24);
19 else 21 else
20 setMinimumSize(p.width(),p.height()+24); 22 setMinimumSize(p.width(),p.height()+24);
21 description=new QLabel(text,this); 23 description=new QLabel(text,this);
22 description->setBackgroundColor(colorGroup().base()); 24 description->setBackgroundColor(colorGroup().base());
23 description->setAlignment(AlignCenter); 25 description->setAlignment(AlignCenter);
24 description->setGeometry(0,height()-24,width(),24); 26 description->setGeometry(0,height()-24,width(),24);
25 pixmap=p; 27 pixmap=p;
26} 28}
27 29
28void ThumbWidget::resizeEvent(QResizeEvent *) 30void ThumbWidget::resizeEvent(QResizeEvent *)
29{ 31{
30 description->setGeometry(0,height()-24,width(),24); 32 description->setGeometry(0,height()-24,width(),24);
31} 33}
32 34
33void ThumbWidget::paintEvent( QPaintEvent *e ) 35void ThumbWidget::paintEvent( QPaintEvent *e )
34{ 36{
35 QPainter painter(this); 37 QPainter painter(this);
36 38
37 painter.setClipRect(e->rect()); 39 painter.setClipRect(e->rect());
38 painter.fillRect(0,0,width(),height(),QColor(255,255,255)); 40 painter.fillRect(0,0,width(),height(),QColor(255,255,255));
39 painter.drawPixmap((width() - pixmap.width()) / 2,0, pixmap); 41 painter.drawPixmap((width() - pixmap.width()) / 2,0, pixmap);
40 42
41} 43}
42 44
43void ThumbWidget::mouseReleaseEvent(QMouseEvent* ) 45void ThumbWidget::mouseReleaseEvent(QMouseEvent* )
44{ 46{
45 emit clicked(fl); 47 emit clicked(fl);
46} 48}
47 49
48 50
49 51
50ImageFileSelectorItem::ImageFileSelectorItem( QListView *parent, const DocLnk &f) 52ImageFileSelectorItem::ImageFileSelectorItem( QListView *parent, const DocLnk &f)
51 : QListViewItem( parent ), fl( f ) 53 : QListViewItem( parent ), fl( f )
52{ 54{
53 setText( 0, f.name() ); 55 setText( 0, f.name() );
54 QFileInfo fi(f.file()); 56 QFileInfo fi(f.file());
55 setText( 1, (fi.extension()).upper() ); 57 setText( 1, (fi.extension()).upper() );
56 setPixmap( 0, f.pixmap() ); 58 setPixmap( 0, f.pixmap() );
57 59
58 60
59} 61}
60 62
61 63
62ImageFileSelectorItem::~ImageFileSelectorItem() 64ImageFileSelectorItem::~ImageFileSelectorItem()
63{ 65{
64 66
65} 67}
66 68
67 69
68ImageFileSelector::ImageFileSelector( CURRENT_VIEW scv,QWidget *parent,const char * ) 70ImageFileSelector::ImageFileSelector( CURRENT_VIEW scv,QWidget *parent,const char * )
69 : QWidgetStack(parent) 71 : QWidgetStack(parent)
70{ 72{
71 73
72 detailed=new QListView(this); 74 detailed=new QListView(this);
73 75
74 detailed->addColumn (tr("Title")); 76 detailed->addColumn (tr("Title"));
75 detailed->addColumn (tr("Type")); 77 detailed->addColumn (tr("Type"));
76 detailed->setAllColumnsShowFocus( true ); 78 detailed->setAllColumnsShowFocus( true );
77 79
78 tList.setAutoDelete(true); 80 tList.setAutoDelete(true);
79 81
80 thumb =new QScrollView(this); 82 thumb =new QScrollView(this);
81 thumb->setVScrollBarMode (QScrollView::Auto ); 83 thumb->setVScrollBarMode (QScrollView::Auto );
82 thumb->viewport()->setBackgroundColor(colorGroup().base()); 84 thumb->viewport()->setBackgroundColor(colorGroup().base());
83 85
84 background=new QWidget(0); 86 background=new QWidget(0);
85 background->setBackgroundColor(colorGroup().base()); 87 background->setBackgroundColor(colorGroup().base());
86 thumb->addChild(background); 88 thumb->addChild(background);
87 gl = new QGridLayout(background,1,2,4,4); 89 gl = new QGridLayout(background,1,2,4,4);
88 90
89 91
90 92
91 connect( detailed, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ), 93 connect( detailed, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),
92 this, SLOT( fileClicked(int,QListViewItem*,const QPoint&,int) ) ); 94 this, SLOT( fileClicked(int,QListViewItem*,const QPoint&,int) ) );
93 connect( detailed, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ), 95 connect( detailed, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
94 this, SLOT( filePressed(int,QListViewItem*,const QPoint&,int) ) ); 96 this, SLOT( filePressed(int,QListViewItem*,const QPoint&,int) ) );
95 connect( detailed, SIGNAL( returnPressed(QListViewItem*) ), 97 connect( detailed, SIGNAL( returnPressed(QListViewItem*) ),
96 this, SLOT( fileClicked(QListViewItem*) ) ); 98 this, SLOT( fileClicked(QListViewItem*) ) );
97 99
98 cView=UNKNOWN; 100 cView=UNKNOWN;
99 setView(scv); 101 setView(scv);
100 reread(); 102 reread();
101 103
102} 104}
103ImageFileSelector::~ImageFileSelector() 105ImageFileSelector::~ImageFileSelector()
104{ 106{
105 107
106} 108}
107 109
108 110
109void ImageFileSelector::switchView() 111void ImageFileSelector::switchView()
110{ 112{
111 CURRENT_VIEW v=cView; 113 CURRENT_VIEW v=cView;
112 114
113 if ( v==DETAILED ) 115 if ( v==DETAILED )
114 v=THUMBNAIL; 116 v=THUMBNAIL;
115 else 117 else
116 v=DETAILED; 118 v=DETAILED;
117 setView(v); 119 setView(v);
118} 120}
119 121
120void ImageFileSelector::setView(CURRENT_VIEW v) 122void ImageFileSelector::setView(CURRENT_VIEW v)
121{ 123{
122 124
123 if ( v==cView ) 125 if ( v==cView )
124 return; 126 return;
125 cView=v; 127 cView=v;
126 128
127 if ( cView!=DETAILED ) 129 if ( cView!=DETAILED )
128 { 130 {
129 raiseWidget(thumb); 131 raiseWidget(thumb);
130 updateSizes(); 132 updateSizes();
131 } 133 }
132 else 134 else
133 { 135 {
134 raiseWidget(detailed); 136 raiseWidget(detailed);
135 updateSizes(); 137 updateSizes();
136 } 138 }
137 139
138 140
139} 141}
140 142
141void ImageFileSelector::resizeEvent(QResizeEvent *) 143void ImageFileSelector::resizeEvent(QResizeEvent *)
142{ 144{
143 updateSizes(); 145 updateSizes();
144} 146}
145 147
146void ImageFileSelector::updateSizes() 148void ImageFileSelector::updateSizes()
147{ 149{
148 int ww=(detailed->width()-detailed->frameWidth()*2); 150 int ww=(detailed->width()-detailed->frameWidth()*2);
149 double w=(double)ww*0.70; 151 double w=(double)ww*0.70;
150 detailed->setColumnWidth(0,(int)w); 152 detailed->setColumnWidth(0,(int)w);
151 detailed->setColumnWidth(1,ww-(int)w); 153 detailed->setColumnWidth(1,ww-(int)w);
152 background->setMinimumWidth(thumb->visibleWidth()); 154 background->setMinimumWidth(thumb->visibleWidth());
153 thumb->updateScrollBars(); 155 thumb->updateScrollBars();
154} 156}
155 157
156void ImageFileSelector::reread(bool) 158void ImageFileSelector::reread(bool)
157{ 159{
158// qDebug("reread"); 160// odebug << "reread" << oendl;
159 ImageFileSelectorItem *item = (ImageFileSelectorItem *)detailed->selectedItem(); 161 ImageFileSelectorItem *item = (ImageFileSelectorItem *)detailed->selectedItem();
160 QString oldFile; 162 QString oldFile;
161 if ( item ) 163 if ( item )
162 oldFile = item->file().file(); 164 oldFile = item->file().file();
163 detailed->clear(); 165 detailed->clear();
164 tList.clear(); 166 tList.clear();
165 DocLnkSet files; 167 DocLnkSet files;
166 Global::findDocuments(&files, "image/*"); 168 Global::findDocuments(&files, "image/*");
167 count = files.children().count(); 169 count = files.children().count();
168 QListIterator<DocLnk> dit( files.children() ); 170 QListIterator<DocLnk> dit( files.children() );
169// int y=0; 171// int y=0;
170// int x=4; 172// int x=4;
171// int totalHeight=4; 173// int totalHeight=4;
172 ThumbWidget *l=0; 174 ThumbWidget *l=0;
173 int width=80; 175 int width=80;
174 gl->expand(dit.count()/2,2); 176 gl->expand(dit.count()/2,2);
175 int i,j; 177 int i,j;
176 i=j=0; 178 i=j=0;
177 detailed->setUpdatesEnabled(false); 179 detailed->setUpdatesEnabled(false);
178 thumb->setUpdatesEnabled(false); 180 thumb->setUpdatesEnabled(false);
179 181
180 for ( ; dit.current(); ++dit ) { 182 for ( ; dit.current(); ++dit ) {
181 item = new ImageFileSelectorItem( detailed, **dit ); 183 item = new ImageFileSelectorItem( detailed, **dit );
182 if ( item->file().file() == oldFile ) 184 if ( item->file().file() == oldFile )
183 detailed->setCurrentItem( item ); 185 detailed->setCurrentItem( item );
184 } 186 }
185 187
186 QListViewItemIterator it( detailed ); 188 QListViewItemIterator it( detailed );
187 ImageFileSelectorItem *ii; 189 ImageFileSelectorItem *ii;
188 // iterate through all items of the listview 190 // iterate through all items of the listview
189 for ( ; it.current(); ++it ) { 191 for ( ; it.current(); ++it ) {
190 ii=(ImageFileSelectorItem *)it.current(); 192 ii=(ImageFileSelectorItem *)it.current();
191 QImage img( ii->file().file() ); 193 QImage img( ii->file().file() );
192 if( !img.isNull()) { 194 if( !img.isNull()) {
193 img=img.smoothScale(64,64); 195 img=img.smoothScale(64,64);
194 QPixmap pix; 196 QPixmap pix;
195 pix.convertFromImage(img); 197 pix.convertFromImage(img);
196 l=new ThumbWidget(pix,ii->file().name(),ii->file(),background,width); 198 l=new ThumbWidget(pix,ii->file().name(),ii->file(),background,width);
197 l->setBackgroundColor(colorGroup().base()); 199 l->setBackgroundColor(colorGroup().base());
198 gl->addWidget(l,j,i); 200 gl->addWidget(l,j,i);
199 i++; 201 i++;
200 if ( i==2 ) { 202 if ( i==2 ) {
201 i=0; 203 i=0;
202 j++; 204 j++;
203 } 205 }
204 tList.append(l); 206 tList.append(l);
205 connect(l,SIGNAL(clicked(const DocLnk&)),this,SLOT(thumbClicked(const DocLnk&))); 207 connect(l,SIGNAL(clicked(const DocLnk&)),this,SLOT(thumbClicked(const DocLnk&)));
206 } 208 }
207 } 209 }
208 210
209 if ( !detailed->selectedItem() ) 211 if ( !detailed->selectedItem() )
210 detailed->setCurrentItem( detailed->firstChild() ); 212 detailed->setCurrentItem( detailed->firstChild() );
211 213
212 detailed->setUpdatesEnabled(true); 214 detailed->setUpdatesEnabled(true);
213 thumb->setUpdatesEnabled(true); 215 thumb->setUpdatesEnabled(true);
214 detailed->update(); 216 detailed->update();
215 thumb->update(); 217 thumb->update();
216} 218}
217 219
218int ImageFileSelector::fileCount() 220int ImageFileSelector::fileCount()
219{ 221{
220 return count; 222 return count;
221} 223}
222const DocLnk * ImageFileSelector::selected() 224const DocLnk * ImageFileSelector::selected()
223{ 225{
224 qDebug("image selected"); 226 odebug << "image selected" << oendl;
225 ImageFileSelectorItem *item = (ImageFileSelectorItem *) detailed->selectedItem(); 227 ImageFileSelectorItem *item = (ImageFileSelectorItem *) detailed->selectedItem();
226 if ( item ) 228 if ( item )
227 return new DocLnk( item->file() ); 229 return new DocLnk( item->file() );
228 return 0; 230 return 0;
229} 231}
230 232
231 233
232 234
233void ImageFileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int ) 235void ImageFileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int )
234{ 236{
235 if ( !i ) 237 if ( !i )
236 return; 238 return;
237 if ( button == Qt::LeftButton ) 239 if ( button == Qt::LeftButton )
238 { 240 {
239 fileClicked( i ); 241 fileClicked( i );
240 } 242 }
241} 243}
242 // pressed to get 'right down' 244 // pressed to get 'right down'
243void ImageFileSelector::filePressed( int, QListViewItem *, const QPoint &, int ) 245void ImageFileSelector::filePressed( int, QListViewItem *, const QPoint &, int )
244{ 246{
245 247
246} 248}
247void ImageFileSelector::fileClicked( QListViewItem *i) 249void ImageFileSelector::fileClicked( QListViewItem *i)
248{ 250{
249 if ( !i ) 251 if ( !i )
250 return; 252 return;
251 emit fileSelected( ( (ImageFileSelectorItem*)i )->file() ); 253 emit fileSelected( ( (ImageFileSelectorItem*)i )->file() );
252 emit closeMe(); 254 emit closeMe();
253} 255}
254 256
255void ImageFileSelector::thumbClicked(const DocLnk &f) 257void ImageFileSelector::thumbClicked(const DocLnk &f)
256{ 258{
257 emit fileSelected( f ); 259 emit fileSelected( f );
258 emit closeMe(); 260 emit closeMe();
259} 261}
260 262
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21// 21//
22// Full-screen and rotation options contributed by Robert Wittams <robert@wittams.com> 22// Full-screen and rotation options contributed by Robert Wittams <robert@wittams.com>
23// 23//
24 24
25#include "showimg.h" 25#include "showimg.h"
26#include "ImageFileSelector.h" 26#include "ImageFileSelector.h"
27#include "settingsdialog.h" 27#include "settingsdialog.h"
28 28
29 29/* OPIE */
30#include <opie2/odebug.h>
30#include <opie2/ofiledialog.h> 31#include <opie2/ofiledialog.h>
31
32#include <qpe/qpeapplication.h> 32#include <qpe/qpeapplication.h>
33#include <qpe/config.h> 33#include <qpe/config.h>
34#include <qpe/resource.h> 34#include <qpe/resource.h>
35#include <qtoolbar.h> 35using namespace Opie::Core;
36using namespace Opie::Ui;
36 37
38/* QT */
39#include <qtoolbar.h>
37#include <qaction.h> 40#include <qaction.h>
38#include <qfiledialog.h> 41#include <qfiledialog.h>
39#include <qmenubar.h> 42#include <qmenubar.h>
40#include <qspinbox.h> 43#include <qspinbox.h>
41 44
45/* STD */
42#include <math.h> 46#include <math.h>
43 47
44
45using namespace Opie::Ui;
46ControlsDialog::ControlsDialog(const QString &caption,QImage image,int *brightness,QWidget *parent) 48ControlsDialog::ControlsDialog(const QString &caption,QImage image,int *brightness,QWidget *parent)
47 : QDialog(parent,0,true) 49 : QDialog(parent,0,true)
48{ 50{
49 setCaption(caption); 51 setCaption(caption);
50 52
51 if ( parent ) { 53 if ( parent ) {
52 setPalette(parent->palette()); 54 setPalette(parent->palette());
53 } 55 }
54 56
55 b=brightness; 57 b=brightness;
56 img=image; 58 img=image;
57 59
58 setMinimumSize(140,80); 60 setMinimumSize(140,80);
59 61
60 QGridLayout *gl= new QGridLayout(this,2,2,4,4); 62 QGridLayout *gl= new QGridLayout(this,2,2,4,4);
61 63
62 pixmap =new ImageWidget(this);; 64 pixmap =new ImageWidget(this);;
63 QPixmap pm; 65 QPixmap pm;
64 pm.convertFromImage(img); 66 pm.convertFromImage(img);
65 pixmap->setPixmap(pm); 67 pixmap->setPixmap(pm);
66 pixmap->setMinimumSize(pm.width(),pm.height()); 68 pixmap->setMinimumSize(pm.width(),pm.height());
67 gl->addMultiCellWidget(pixmap,0,0,0,2,AlignCenter); 69 gl->addMultiCellWidget(pixmap,0,0,0,2,AlignCenter);
68 QLabel *l=new QLabel(tr("Brightness")+":",this); 70 QLabel *l=new QLabel(tr("Brightness")+":",this);
69 gl->addWidget(l,1,0,AlignLeft); 71 gl->addWidget(l,1,0,AlignLeft);
70 spb=new QSpinBox(-100,100,2,this); 72 spb=new QSpinBox(-100,100,2,this);
71 gl->addWidget(spb,1,1,AlignRight); 73 gl->addWidget(spb,1,1,AlignRight);
72 74
73 spb->setValue(0); 75 spb->setValue(0);
74 76
75 connect(spb,SIGNAL(valueChanged(int)),this, SLOT(bValueChanged(int))); 77 connect(spb,SIGNAL(valueChanged(int)),this, SLOT(bValueChanged(int)));
76 78
77} 79}
78 80
79void ControlsDialog::bValueChanged(int value) 81void ControlsDialog::bValueChanged(int value)
80{ 82{
81 QImage nImage=img; 83 QImage nImage=img;
82 nImage.detach(); 84 nImage.detach();
83 ImageViewer::intensity(nImage, (float)value/100); 85 ImageViewer::intensity(nImage, (float)value/100);
84 QPixmap pm; 86 QPixmap pm;
85 pm.convertFromImage(nImage); 87 pm.convertFromImage(nImage);
86 pixmap->setPixmap(pm); 88 pixmap->setPixmap(pm);
87 pixmap->repaint(false); 89 pixmap->repaint(false);
88 90
89 91
90} 92}
91 93
92void ControlsDialog::accept() 94void ControlsDialog::accept()
93{ 95{
94 *b=spb->value(); 96 *b=spb->value();
95 done(1); 97 done(1);
96} 98}
97 99
98//=========================================================================== 100//===========================================================================
99 101
100InfoDialog::InfoDialog(const QString &caption, const QStringList text,QWidget *parent) 102InfoDialog::InfoDialog(const QString &caption, const QStringList text,QWidget *parent)
101 : QDialog(parent,0,true) 103 : QDialog(parent,0,true)
102{ 104{
103 setCaption(caption); 105 setCaption(caption);
104 106
105 if ( parent ) 107 if ( parent )
106 { 108 {
107 setPalette(parent->palette()); 109 setPalette(parent->palette());
108 } 110 }
109 111
110 112
111 113
112 QString labels[]={ tr("File Name"),tr("Format"),tr("File Size"),tr("Size"),tr("Colors"),tr("Alpha") }; 114 QString labels[]={ tr("File Name"),tr("Format"),tr("File Size"),tr("Size"),tr("Colors"),tr("Alpha") };
113 115
114 setMinimumSize(180,80); 116 setMinimumSize(180,80);
115 int num=ImageViewer::LAST+1; 117 int num=ImageViewer::LAST+1;
116 if ( text[ImageViewer::ALPHA].isEmpty() ) 118 if ( text[ImageViewer::ALPHA].isEmpty() )
117 num--; 119 num--;
118 QGridLayout *gl= new QGridLayout(this,num,2,4,2); 120 QGridLayout *gl= new QGridLayout(this,num,2,4,2);
119 QLabel *l; 121 QLabel *l;
120 int count=0; 122 int count=0;
121 for ( int i=0;i<num;i++ ) 123 for ( int i=0;i<num;i++ )
122 { 124 {
123 if ( i==1 ) 125 if ( i==1 )
124 { 126 {
125 QFrame *frm=new QFrame(this); 127 QFrame *frm=new QFrame(this);
126 frm->setFrameStyle(QFrame::HLine|QFrame::Sunken); 128 frm->setFrameStyle(QFrame::HLine|QFrame::Sunken);
127 gl->addMultiCellWidget(frm,i,i,0,1); 129 gl->addMultiCellWidget(frm,i,i,0,1);
128 } 130 }
129 else 131 else
130 { 132 {
131 l=new QLabel( tr( labels[count] )+":",this); 133 l=new QLabel( tr( labels[count] )+":",this);
132 gl->addWidget(l,i,0,AlignLeft); 134 gl->addWidget(l,i,0,AlignLeft);
133 l=new QLabel(text[count],this); 135 l=new QLabel(text[count],this);
134 gl->addWidget(l,i,1,AlignRight); 136 gl->addWidget(l,i,1,AlignRight);
135 count++; 137 count++;
136 } 138 }
137 139
138 } 140 }
139 141
140} 142}
141 143
@@ -193,442 +195,442 @@ void ImageWidget::paintEvent( QPaintEvent *e )
193 } 195 }
194} 196}
195 197
196void ImageWidget::mouseReleaseEvent(QMouseEvent *) 198void ImageWidget::mouseReleaseEvent(QMouseEvent *)
197{ 199{
198 emit clicked(); 200 emit clicked();
199} 201}
200 202
201//=========================================================================== 203//===========================================================================
202 204
203ImageViewer::ImageViewer( QWidget *parent, const char *name, int /*wFlags*/ ) 205ImageViewer::ImageViewer( QWidget *parent, const char *name, int /*wFlags*/ )
204: QMainWindow( parent, name, WResizeNoErase ), filename( 0 ), bFromDocView( FALSE ) 206: QMainWindow( parent, name, WResizeNoErase ), filename( 0 ), bFromDocView( FALSE )
205{ 207{
206 setCaption( tr("Image Viewer") ); 208 setCaption( tr("Image Viewer") );
207 setIcon( Resource::loadPixmap( "ImageViewer" ) ); 209 setIcon( Resource::loadPixmap( "ImageViewer" ) );
208 210
209 211
210 Config cfg("Image Viewer"); 212 Config cfg("Image Viewer");
211 cfg.setGroup("Image Viewer"); 213 cfg.setGroup("Image Viewer");
212 214
213 showThumbView=cfg.readBoolEntry("ShowThumbnails",false); 215 showThumbView=cfg.readBoolEntry("ShowThumbnails",false);
214 isSized=cfg.readBoolEntry("SizeToScreen",true); 216 isSized=cfg.readBoolEntry("SizeToScreen",true);
215 217
216 isFullScreen = FALSE; 218 isFullScreen = FALSE;
217 219
218 setToolBarsMovable( FALSE ); 220 setToolBarsMovable( FALSE );
219 221
220 toolBar = new QToolBar( this ); 222 toolBar = new QToolBar( this );
221 toolBar->setHorizontalStretchable( TRUE ); 223 toolBar->setHorizontalStretchable( TRUE );
222 224
223 menuBar = new QMenuBar( toolBar ); 225 menuBar = new QMenuBar( toolBar );
224 226
225 current=menuBar; 227 current=menuBar;
226 228
227 229
228 230
229 fileMenuFile = new QPopupMenu(this); 231 fileMenuFile = new QPopupMenu(this);
230 //menuBarmenubarFile->insertItem( tr("File"), fileMenu ); 232 //menuBarmenubarFile->insertItem( tr("File"), fileMenu );
231 fileMenuFile->insertItem(tr("Open"), 233 fileMenuFile->insertItem(tr("Open"),
232 this, SLOT(openFile()), 0); 234 this, SLOT(openFile()), 0);
233 235
234 viewMenuFile = new QPopupMenu( this ); 236 viewMenuFile = new QPopupMenu( this );
235 //menubarFile->insertItem( tr("View"), viewMenu ); 237 //menubarFile->insertItem( tr("View"), viewMenu );
236 viewMenuFile->insertItem( tr("Thumbnail View"), 238 viewMenuFile->insertItem( tr("Thumbnail View"),
237 this, SLOT(switchThumbView()), 0, SHOW_THUMBNAILS ); 239 this, SLOT(switchThumbView()), 0, SHOW_THUMBNAILS );
238 240
239 viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView ); 241 viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView );
240 242
241 243
242 244
243 245
244 optionsMenuFile = new QPopupMenu( this); 246 optionsMenuFile = new QPopupMenu( this);
245 //menubarFile->insertItem( tr("Options"),optionsMenu ); 247 //menubarFile->insertItem( tr("Options"),optionsMenu );
246 slideAction = new QAction( tr( "Slide show" ), Resource::loadIconSet( "slideshow" ), 248 slideAction = new QAction( tr( "Slide show" ), Resource::loadIconSet( "slideshow" ),
247 QString::null, 0, this, 0 ); 249 QString::null, 0, this, 0 );
248 slideAction->setToggleAction( TRUE ); 250 slideAction->setToggleAction( TRUE );
249 connect( slideAction, SIGNAL( toggled(bool) ), this, SLOT( slideShow(bool) ) ); 251 connect( slideAction, SIGNAL( toggled(bool) ), this, SLOT( slideShow(bool) ) );
250 slideAction->addTo( optionsMenuFile); 252 slideAction->addTo( optionsMenuFile);
251// slideAction->addTo( toolBar ); 253// slideAction->addTo( toolBar );
252 254
253 255
254// optionsMenuFile->insertItem( tr("Slideshow") ); 256// optionsMenuFile->insertItem( tr("Slideshow") );
255 optionsMenuFile->insertSeparator(); 257 optionsMenuFile->insertSeparator();
256 optionsMenuFile->insertItem( tr("Preferences.."), this, SLOT(settings()), 0); 258 optionsMenuFile->insertItem( tr("Preferences.."), this, SLOT(settings()), 0);
257// optionsMenuFile->insertItem( tr("Help"), this, SLOT(help()), 0); 259// optionsMenuFile->insertItem( tr("Help"), this, SLOT(help()), 0);
258 260
259 QStrList fmt = QImage::outputFormats(); 261 QStrList fmt = QImage::outputFormats();
260 262
261 263
262 fileMenuView = new QPopupMenu( this ); 264 fileMenuView = new QPopupMenu( this );
263 //menubarView->insertItem( tr("File"),fileMenu ); 265 //menubarView->insertItem( tr("File"),fileMenu );
264 fileMenuView->insertItem( tr("Image Info ..."),this, SLOT(displayInfoDialog()),0 ); 266 fileMenuView->insertItem( tr("Image Info ..."),this, SLOT(displayInfoDialog()),0 );
265 fileMenuView->insertSeparator(); 267 fileMenuView->insertSeparator();
266 268
267 viewMenuView = new QPopupMenu(this ); 269 viewMenuView = new QPopupMenu(this );
268 viewMenuView->setCheckable ( true ); 270 viewMenuView->setCheckable ( true );
269 271
270 //menubarView->insertItem( tr("View"),viewMenu ); 272 //menubarView->insertItem( tr("View"),viewMenu );
271 viewMenuView->insertItem(tr("Horizontal flip"), this, SLOT(hFlip()), 0); 273 viewMenuView->insertItem(tr("Horizontal flip"), this, SLOT(hFlip()), 0);
272 viewMenuView->insertItem(tr("Vertical flip"), this, SLOT(vFlip()), 0); 274 viewMenuView->insertItem(tr("Vertical flip"), this, SLOT(vFlip()), 0);
273 275
274 stack = new QWidgetStack( this ); 276 stack = new QWidgetStack( this );
275 stack->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); 277 stack->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );
276 setCentralWidget( stack ); 278 setCentralWidget( stack );
277 279
278 280
279 imagePanel = new ImagePane( stack ); 281 imagePanel = new ImagePane( stack );
280 connect(imagePanel, SIGNAL(clicked()), this, SLOT(normalView())); 282 connect(imagePanel, SIGNAL(clicked()), this, SLOT(normalView()));
281 283
282 284
283 ImageFileSelector::CURRENT_VIEW cv; 285 ImageFileSelector::CURRENT_VIEW cv;
284 if(showThumbView) 286 if(showThumbView)
285 cv=ImageFileSelector::THUMBNAIL; 287 cv=ImageFileSelector::THUMBNAIL;
286 else 288 else
287 cv=ImageFileSelector::DETAILED; 289 cv=ImageFileSelector::DETAILED;
288 290
289 qDebug("cv = %d",cv); 291 odebug << "cv = " << cv << "" << oendl;
290 292
291 fileSelector = new ImageFileSelector( cv,stack, "fs"); 293 fileSelector = new ImageFileSelector( cv,stack, "fs");
292 294
293 //switchThumbView(); 295 //switchThumbView();
294 296
295 297
296 //fileSelector = new ImageFileSelector("image/*", stack, "fs"); 298 //fileSelector = new ImageFileSelector("image/*", stack, "fs");
297 //fileSelector->setNewVisible(FALSE); 299 //fileSelector->setNewVisible(FALSE);
298 //fileSelector->setCloseVisible(FALSE); 300 //fileSelector->setCloseVisible(FALSE);
299 connect( fileSelector, SIGNAL( closeMe() ), this, SLOT( closeFileSelector() ) ); 301 connect( fileSelector, SIGNAL( closeMe() ), this, SLOT( closeFileSelector() ) );
300 connect( fileSelector, SIGNAL( fileSelected(const DocLnk&) ), 302 connect( fileSelector, SIGNAL( fileSelected(const DocLnk&) ),
301 this, SLOT( openFile(const DocLnk&) ) ); 303 this, SLOT( openFile(const DocLnk&) ) );
302 304
303 imageList = fileSelector->fileList(); 305 imageList = fileSelector->fileList();
304 slideAction->setEnabled( imageList.count() != 0); 306 slideAction->setEnabled( imageList.count() != 0);
305 307
306 iconToolBar = new QToolBar(this); 308 iconToolBar = new QToolBar(this);
307 309
308 QAction *a; 310 QAction *a;
309 311
310 a = new QAction( tr( "Open ..." ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 ); 312 a = new QAction( tr( "Open ..." ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 );
311 connect( a, SIGNAL( activated() ), this, SLOT( open() ) ); 313 connect( a, SIGNAL( activated() ), this, SLOT( open() ) );
312 a->addTo( fileMenuView); 314 a->addTo( fileMenuView);
313 a->addTo( iconToolBar ); 315 a->addTo( iconToolBar );
314 316
315 317
316 a = new QAction( tr( "Rotate 90"), Resource::loadPixmap( "rotate90" ), QString::null, 0, this, 0); 318 a = new QAction( tr( "Rotate 90"), Resource::loadPixmap( "rotate90" ), QString::null, 0, this, 0);
317 connect( a, SIGNAL( activated() ), this, SLOT( rot90() ) ); 319 connect( a, SIGNAL( activated() ), this, SLOT( rot90() ) );
318 a->addTo( iconToolBar ); 320 a->addTo( iconToolBar );
319 a->addTo( viewMenuView ); 321 a->addTo( viewMenuView );
320 322
321 a = new QAction( tr( "Rotate 180" ), Resource::loadPixmap( "repeat" ), QString::null, 0, this, 0 ); 323 a = new QAction( tr( "Rotate 180" ), Resource::loadPixmap( "repeat" ), QString::null, 0, this, 0 );
322 connect( a, SIGNAL( activated() ), this, SLOT( rot180() ) ); 324 connect( a, SIGNAL( activated() ), this, SLOT( rot180() ) );
323 a->addTo( iconToolBar ); 325 a->addTo( iconToolBar );
324 a->addTo( viewMenuView ); 326 a->addTo( viewMenuView );
325 327
326 328
327 a = new QAction( tr( "Rotate 270"), Resource::loadPixmap( "rotate270" ), QString::null, 0, this, 0); 329 a = new QAction( tr( "Rotate 270"), Resource::loadPixmap( "rotate270" ), QString::null, 0, this, 0);
328 connect( a, SIGNAL( activated() ), this, SLOT( rot270() ) ); 330 connect( a, SIGNAL( activated() ), this, SLOT( rot270() ) );
329 //a->addTo( iconToolBar ); 331 //a->addTo( iconToolBar );
330 a->addTo( viewMenuView ); 332 a->addTo( viewMenuView );
331 333
332 334
333 335
334 viewMenuView->insertSeparator(); 336 viewMenuView->insertSeparator();
335 viewMenuView->insertItem(tr("Brightness ..."), this, SLOT(displayControlsDialog()), 0); 337 viewMenuView->insertItem(tr("Brightness ..."), this, SLOT(displayControlsDialog()), 0);
336 viewMenuView->insertItem(tr("Black And White"), this, SLOT(blackAndWhite()), 0,BLACKANDWHITE); 338 viewMenuView->insertItem(tr("Black And White"), this, SLOT(blackAndWhite()), 0,BLACKANDWHITE);
337 viewMenuView->insertSeparator(); 339 viewMenuView->insertSeparator();
338 340
339 341
340 sss = new QAction( tr( "Scale to Screen"), Resource::loadPixmap( "scale" ), QString::null, 0, this, 0,true); 342 sss = new QAction( tr( "Scale to Screen"), Resource::loadPixmap( "scale" ), QString::null, 0, this, 0,true);
341 connect( sss, SIGNAL( activated() ), this, SLOT( switchSizeToScreen() ) ); 343 connect( sss, SIGNAL( activated() ), this, SLOT( switchSizeToScreen() ) );
342 sss->addTo( iconToolBar ); 344 sss->addTo( iconToolBar );
343 sss->addTo( viewMenuView ); 345 sss->addTo( viewMenuView );
344 346
345 sss->setOn(isSized); 347 sss->setOn(isSized);
346 viewMenuView->insertSeparator(); 348 viewMenuView->insertSeparator();
347 349
348 350
349 a = new QAction( tr( "Fullscreen" ), Resource::loadPixmap( "fullscreen" ), 351 a = new QAction( tr( "Fullscreen" ), Resource::loadPixmap( "fullscreen" ),
350 QString::null, 0, this, 0 ); 352 QString::null, 0, this, 0 );
351 connect( a, SIGNAL( activated() ), this, SLOT( fullScreen() ) ); 353 connect( a, SIGNAL( activated() ), this, SLOT( fullScreen() ) );
352 a->addTo( iconToolBar ); 354 a->addTo( iconToolBar );
353 a->addTo( viewMenuView); 355 a->addTo( viewMenuView);
354 356
355 a = new QAction( tr( "Stop Slideshow" ), Resource::loadPixmap( "quit_icon" ), 357 a = new QAction( tr( "Stop Slideshow" ), Resource::loadPixmap( "quit_icon" ),
356 QString::null, 0, this, 0 ); 358 QString::null, 0, this, 0 );
357 connect( a, SIGNAL( activated() ), this, SLOT( stopSlideShow() ) ); 359 connect( a, SIGNAL( activated() ), this, SLOT( stopSlideShow() ) );
358 a->addTo( iconToolBar ); 360 a->addTo( iconToolBar );
359 a->addTo( viewMenuView); 361 a->addTo( viewMenuView);
360 362
361 363
362 Config config( "ImageViewer" ); 364 Config config( "ImageViewer" );
363 config.setGroup( "SlideShow" ); 365 config.setGroup( "SlideShow" );
364 slideDelay = config.readNumEntry( "Delay", 2); 366 slideDelay = config.readNumEntry( "Delay", 2);
365 slideRepeat = config.readBoolEntry( "Repeat", FALSE ); 367 slideRepeat = config.readBoolEntry( "Repeat", FALSE );
366 slideReverse = config.readBoolEntry("Reverse", FALSE); 368 slideReverse = config.readBoolEntry("Reverse", FALSE);
367 369
368 config.setGroup("Default"); 370 config.setGroup("Default");
369 rotateOnLoad = config.readBoolEntry("Rotate", FALSE); 371 rotateOnLoad = config.readBoolEntry("Rotate", FALSE);
370 fastLoad = config.readBoolEntry("FastLoad", TRUE); 372 fastLoad = config.readBoolEntry("FastLoad", TRUE);
371 slideTimer = new QTimer( this ); 373 slideTimer = new QTimer( this );
372 connect( slideTimer, SIGNAL(timeout()), this, SLOT(slideUpdate()) ); 374 connect( slideTimer, SIGNAL(timeout()), this, SLOT(slideUpdate()) );
373 375
374 switchToFileSelector(); 376 switchToFileSelector();
375 377
376 setMouseTracking( TRUE ); 378 setMouseTracking( TRUE );
377 379
378 380
379} 381}
380 382
381ImageViewer::~ImageViewer() 383ImageViewer::~ImageViewer()
382{ 384{
383 Config cfg("Image Viewer"); 385 Config cfg("Image Viewer");
384 cfg.setGroup("Image Viewer"); 386 cfg.setGroup("Image Viewer");
385 387
386 cfg.writeEntry("ShowThumbnails",(int)showThumbView); 388 cfg.writeEntry("ShowThumbnails",(int)showThumbView);
387 cfg.writeEntry("SizeToScreen",(int)isSized); 389 cfg.writeEntry("SizeToScreen",(int)isSized);
388 390
389 cfg.setGroup( "SlideShow" ); 391 cfg.setGroup( "SlideShow" );
390 cfg.writeEntry( "Delay", slideDelay); 392 cfg.writeEntry( "Delay", slideDelay);
391 cfg.writeEntry( "Repeat", slideRepeat ); 393 cfg.writeEntry( "Repeat", slideRepeat );
392 cfg.writeEntry("Reverse", slideReverse); 394 cfg.writeEntry("Reverse", slideReverse);
393 395
394 cfg.setGroup("Default"); 396 cfg.setGroup("Default");
395 cfg.writeEntry("Rotate", rotateOnLoad); 397 cfg.writeEntry("Rotate", rotateOnLoad);
396 cfg.writeEntry("FastLoad", fastLoad); 398 cfg.writeEntry("FastLoad", fastLoad);
397 399
398 delete imagePanel; // in case it is fullscreen 400 delete imagePanel; // in case it is fullscreen
399} 401}
400 402
401void ImageViewer::help() { 403void ImageViewer::help() {
402 404
403} 405}
404 406
405 407
406void ImageViewer::settings() 408void ImageViewer::settings()
407{ 409{
408 SettingsDialog dlg( this, 0, TRUE ); 410 SettingsDialog dlg( this, 0, TRUE );
409 dlg.setDelay( slideDelay ); 411 dlg.setDelay( slideDelay );
410 dlg.setRepeat( slideRepeat ); 412 dlg.setRepeat( slideRepeat );
411 dlg.setReverse( slideReverse ); 413 dlg.setReverse( slideReverse );
412 dlg.setRotate(rotateOnLoad); 414 dlg.setRotate(rotateOnLoad);
413 dlg.setFastLoad(fastLoad); 415 dlg.setFastLoad(fastLoad);
414 416
415 if ( QPEApplication::execDialog(&dlg) == QDialog::Accepted ) { 417 if ( QPEApplication::execDialog(&dlg) == QDialog::Accepted ) {
416 qDebug("<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>"); 418 odebug << "<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>" << oendl;
417 slideDelay = dlg.delay(); 419 slideDelay = dlg.delay();
418 slideRepeat = dlg.repeat(); 420 slideRepeat = dlg.repeat();
419 slideReverse = dlg.reverse(); 421 slideReverse = dlg.reverse();
420 rotateOnLoad = dlg.rotate(); 422 rotateOnLoad = dlg.rotate();
421 fastLoad = dlg.fastLoad(); 423 fastLoad = dlg.fastLoad();
422 424
423 Config config( "ImageViewer" ); 425 Config config( "ImageViewer" );
424 config.setGroup( "SlideShow" ); 426 config.setGroup( "SlideShow" );
425 config.writeEntry( "Delay", slideDelay ); 427 config.writeEntry( "Delay", slideDelay );
426 config.writeEntry( "Repeat", slideRepeat ); 428 config.writeEntry( "Repeat", slideRepeat );
427 config.writeEntry("Reverse", slideReverse); 429 config.writeEntry("Reverse", slideReverse);
428 430
429 config.setGroup("Default"); 431 config.setGroup("Default");
430 config.writeEntry("Rotate", rotateOnLoad); 432 config.writeEntry("Rotate", rotateOnLoad);
431 config.writeEntry("FastLoad", fastLoad); 433 config.writeEntry("FastLoad", fastLoad);
432 } 434 }
433} 435}
434 436
435void ImageViewer::switchSizeToScreen() 437void ImageViewer::switchSizeToScreen()
436{ 438{
437 isSized=!isSized; 439 isSized=!isSized;
438 sss->setOn(isSized); 440 sss->setOn(isSized);
439 updateImage(); 441 updateImage();
440} 442}
441 443
442void ImageViewer::updateImage() 444void ImageViewer::updateImage()
443{ 445{
444 if ( isSized ) { 446 if ( isSized ) {
445 imagePanel->setPixmap(pmScaled); 447 imagePanel->setPixmap(pmScaled);
446 } else { 448 } else {
447 imagePanel->setPixmap(pm); 449 imagePanel->setPixmap(pm);
448 } 450 }
449} 451}
450 452
451void ImageViewer::switchThumbView() 453void ImageViewer::switchThumbView()
452{ 454{
453 455
454 showThumbView=!showThumbView; 456 showThumbView=!showThumbView;
455 viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView ); 457 viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView );
456 fileSelector->switchView(); 458 fileSelector->switchView();
457 459
458} 460}
459 461
460void ImageViewer::switchToFileSelector() 462void ImageViewer::switchToFileSelector()
461{ 463{
462 stack->raiseWidget(fileSelector); 464 stack->raiseWidget(fileSelector);
463 menuBar->clear(); 465 menuBar->clear();
464 menuBar->insertItem( tr("File"), fileMenuFile ); 466 menuBar->insertItem( tr("File"), fileMenuFile );
465 menuBar->insertItem( tr("View"), viewMenuFile ); 467 menuBar->insertItem( tr("View"), viewMenuFile );
466 menuBar->insertItem( tr("Options"), optionsMenuFile ); 468 menuBar->insertItem( tr("Options"), optionsMenuFile );
467 iconToolBar->hide(); 469 iconToolBar->hide();
468 imagePanel->disable(); 470 imagePanel->disable();
469 slideShow(false); 471 slideShow(false);
470 472
471} 473}
472 474
473void ImageViewer::switchToImageView() 475void ImageViewer::switchToImageView()
474{ 476{
475 stack->raiseWidget(imagePanel); 477 stack->raiseWidget(imagePanel);
476 478
477 menuBar->clear(); 479 menuBar->clear();
478 menuBar->insertItem( tr("File"), fileMenuView ); 480 menuBar->insertItem( tr("File"), fileMenuView );
479 menuBar->insertItem( tr("View"), viewMenuView ); 481 menuBar->insertItem( tr("View"), viewMenuView );
480 viewMenuView->setItemEnabled(BLACKANDWHITE,true); 482 viewMenuView->setItemEnabled(BLACKANDWHITE,true);
481 iconToolBar->show(); 483 iconToolBar->show();
482 484
483 imagePanel->setPosition(0,0); 485 imagePanel->setPosition(0,0);
484 486
485} 487}
486 488
487 489
488void ImageViewer::setDocument(const QString& fileref) 490void ImageViewer::setDocument(const QString& fileref)
489{ 491{
490 delayLoad = fileref; 492 delayLoad = fileref;
491 switchToImageView(); 493 switchToImageView();
492 QTimer::singleShot( 0, this, SLOT(doDelayedLoad()) ); 494 QTimer::singleShot( 0, this, SLOT(doDelayedLoad()) );
493} 495}
494 496
495void ImageViewer::doDelayedLoad() 497void ImageViewer::doDelayedLoad()
496{ 498{
497 show(delayLoad); 499 show(delayLoad);
498} 500}
499 501
500void ImageViewer::show() 502void ImageViewer::show()
501{ 503{
502 normalView(); 504 normalView();
503 QMainWindow::show(); 505 QMainWindow::show();
504} 506}
505 507
506void ImageViewer::show(const QString& fileref) 508void ImageViewer::show(const QString& fileref)
507{ 509{
508// qDebug("Show "+fileref); 510// odebug << "Show "+fileref << oendl;
509 bFromDocView = TRUE; 511 bFromDocView = TRUE;
510 closeFileSelector(); 512 closeFileSelector();
511 DocLnk link(fileref); 513 DocLnk link(fileref);
512 if ( link.isValid() ) { 514 if ( link.isValid() ) {
513 openFile(link); 515 openFile(link);
514 } else { 516 } else {
515 filename = fileref; 517 filename = fileref;
516 updateCaption( fileref ); 518 updateCaption( fileref );
517 loadImage( fileref ); 519 loadImage( fileref );
518 } 520 }
519} 521}
520 522
521void ImageViewer::openFile() { 523void ImageViewer::openFile() {
522 MimeTypes types; 524 MimeTypes types;
523 QStringList image; 525 QStringList image;
524 image << "image/*"; 526 image << "image/*";
525 types.insert("Images", image); 527 types.insert("Images", image);
526 528
527 QString str = OFileDialog::getOpenFileName( 1,QPEApplication::documentDir(),"", types, 0 ); 529 QString str = OFileDialog::getOpenFileName( 1,QPEApplication::documentDir(),"", types, 0 );
528 DocLnk link(str); 530 DocLnk link(str);
529// if ( link.isValid() ) 531// if ( link.isValid() )
530 openFile(link); 532 openFile(link);
531 533
532} 534}
533 535
534void ImageViewer::openFile( const DocLnk &link ) 536void ImageViewer::openFile( const DocLnk &link )
535{ 537{
536 closeFileSelector(); 538 closeFileSelector();
537// DocLnk link(file); 539// DocLnk link(file);
538 qDebug("open "+link.name()); 540 odebug << "open "+link.name() << oendl;
539 updateCaption( link.name() ); 541 updateCaption( link.name() );
540 loadImage( link.file() ); 542 loadImage( link.file() );
541 if (slideTimer->isActive()) { 543 if (slideTimer->isActive()) {
542 slideTimer->start(slideDelay * 1000, FALSE); 544 slideTimer->start(slideDelay * 1000, FALSE);
543 } 545 }
544 546
545} 547}
546 548
547void ImageViewer::open() 549void ImageViewer::open()
548{ 550{
549 switchToFileSelector(); 551 switchToFileSelector();
550} 552}
551 553
552void ImageViewer::closeFileSelector() 554void ImageViewer::closeFileSelector()
553{ 555{
554 switchToImageView(); 556 switchToImageView();
555} 557}
556 558
557void ImageViewer::updateCaption( QString name ) 559void ImageViewer::updateCaption( QString name )
558{ 560{
559 int sep = name.findRev( '/' ); 561 int sep = name.findRev( '/' );
560 if ( sep >= 0 ) 562 if ( sep >= 0 )
561 name = name.mid( sep+1 ); 563 name = name.mid( sep+1 );
562 setCaption( name + tr(" - Image Viewer") ); 564 setCaption( name + tr(" - Image Viewer") );
563} 565}
564 566
565/* 567/*
566 This function loads an image from a file. 568 This function loads an image from a file.
567*/ 569*/
568 570
569void ImageViewer::loadImage( const char *fileName ) 571void ImageViewer::loadImage( const char *fileName )
570{ 572{
571 filename = fileName; 573 filename = fileName;
572 if ( filename ) { 574 if ( filename ) {
573 QApplication::setOverrideCursor( waitCursor ); // this might take time 575 QApplication::setOverrideCursor( waitCursor ); // this might take time
574 //imagePanel->statusLabel()->setText( tr("Loading image...") ); 576 //imagePanel->statusLabel()->setText( tr("Loading image...") );
575 qApp->processEvents(); 577 qApp->processEvents();
576 bool ok = image.load(filename, 0); 578 bool ok = image.load(filename, 0);
577 if ( ok ) { 579 if ( ok ) {
578 ok = reconvertImage(); 580 ok = reconvertImage();
579 updateImageInfo(filename); 581 updateImageInfo(filename);
580 } 582 }
581 if ( !ok ) { 583 if ( !ok ) {
582 pm.resize(0,0); // couldn't load image 584 pm.resize(0,0); // couldn't load image
583 update(); 585 update();
584 } 586 }
585 QApplication::restoreOverrideCursor(); // restore original cursor 587 QApplication::restoreOverrideCursor(); // restore original cursor
586 } 588 }
587 589
588// fastLoad ? ", Fast" : "", 590// fastLoad ? ", Fast" : "",
589// fastLoad ? QMAX(imagewidth/maxsize, imageheight/maxsize) : 1); 591// fastLoad ? QMAX(imagewidth/maxsize, imageheight/maxsize) : 1);
590 592
591 593
592// matrix.reset(); 594// matrix.reset();
593 rotated90 = FALSE; 595 rotated90 = FALSE;
594 596
595 if (rotateOnLoad) { 597 if (rotateOnLoad) {
596 rotated90 = TRUE; 598 rotated90 = TRUE;
597 rot90(); 599 rot90();
598// matrix.rotate( -90.0 ); 600// matrix.rotate( -90.0 );
599 } 601 }
600 602
601 switchToImageView(); 603 switchToImageView();
602 updateImage(); 604 updateImage();
603 605
604} 606}
605 607
606bool ImageViewer::loadSelected() 608bool ImageViewer::loadSelected()
607{ 609{
608 bool ok = false; 610 bool ok = false;
609 if ( stack->visibleWidget() == fileSelector ) 611 if ( stack->visibleWidget() == fileSelector )
610 { 612 {
611 const DocLnk *link = fileSelector->selected(); 613 const DocLnk *link = fileSelector->selected();
612 if ( link ) 614 if ( link )
613 { 615 {
614 if ( link->file() != filename ) 616 if ( link->file() != filename )
615 { 617 {
616 updateCaption( link->name() ); 618 updateCaption( link->name() );
617 filename = link->file(); 619 filename = link->file();
618 qApp->processEvents(); 620 qApp->processEvents();
619 ok = image.load(filename, 0); 621 ok = image.load(filename, 0);
620 if ( ok ) 622 if ( ok )
621 { 623 {
622 updateImageInfo(filename); 624 updateImageInfo(filename);
623 ok = reconvertImage(); 625 ok = reconvertImage();
624 } 626 }
625 if ( !ok ) 627 if ( !ok )
626 pm.resize(0,0); 628 pm.resize(0,0);
627 } 629 }
628 } 630 }
629 } 631 }
630 if ( !image.isNull() ) 632 if ( !image.isNull() )
631 { 633 {
632 ok = true; 634 ok = true;
633 closeFileSelector(); 635 closeFileSelector();
634 } 636 }
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 @@
1CONFIG += qt warn_on quick-app 1CONFIG += qt warn_on quick-app
2HEADERS = showimg.h ImageFileSelector.h settingsdialog.h settingsdialogbase.h 2HEADERS = showimg.h ImageFileSelector.h settingsdialog.h settingsdialogbase.h
3SOURCES = main.cpp showimg.cpp ImageFileSelector.cpp settingsdialog.cpp settingsdialogbase.cpp 3SOURCES = main.cpp showimg.cpp ImageFileSelector.cpp settingsdialog.cpp settingsdialogbase.cpp
4TARGET = showimg 4TARGET = showimg
5INCLUDEPATH += $(OPIEDIR)/include 5INCLUDEPATH += $(OPIEDIR)/include
6DEPENDPATH += $(OPIEDIR)/include 6DEPENDPATH += $(OPIEDIR)/include
7LIBS += -lqpe -lopiecore2 -lopieui2 7LIBS += -lqpe -lopiecore2 -lopieui2
8 8
9include ( $(OPIEDIR)/include.pro ) 9include ( $(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 @@
1 config TONLEITER 1 config TONLEITER
2 boolean "tonleiter (shows scales on sting instruments)" 2 boolean "tonleiter (shows scales on sting instruments)"
3 default "n" 3 default "n"
4 depends ( LIBQPE || LIBQPE-X11 ) 4 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 @@
1#include "editinst.h" 1#include "editinst.h"
2 2
3#include <qpushbutton.h> 3/* OPIE */
4 4#include <opie2/odebug.h>
5#include <qpe/config.h>
5#include <qpe/qpeapplication.h> 6#include <qpe/qpeapplication.h>
7using namespace Opie::Core;
8
9/* QT */
10#include <qpushbutton.h>
6 11
7Menu::InstEditDialog::InstEditDialog(TonleiterData* data,QWidget* parent,const char* name) 12Menu::InstEditDialog::InstEditDialog(TonleiterData* data,QWidget* parent,const char* name)
8:QDialog(parent,name,true,0),data(data) 13:QDialog(parent,name,true,0),data(data)
9{ 14{
10 setCaption("Tonleiter::"+tr("Instrument")); 15 setCaption("Tonleiter::"+tr("Instrument"));
11 QBoxLayout* masterlayout=new QBoxLayout(this,QBoxLayout::TopToBottom); 16 QBoxLayout* masterlayout=new QBoxLayout(this,QBoxLayout::TopToBottom);
12 instid=data->getCurrentInstrumentID(); 17 instid=data->getCurrentInstrumentID();
13 stringlist.setAutoDelete(true); 18 stringlist.setAutoDelete(true);
14 19
15 QBoxLayout* toplayout=new QBoxLayout(masterlayout,QBoxLayout::LeftToRight); 20 QBoxLayout* toplayout=new QBoxLayout(masterlayout,QBoxLayout::LeftToRight);
16 21
17 //Name combo + Add + Delete 22 //Name combo + Add + Delete
18 boxInst=new QComboBox(this,"boxInst"); 23 boxInst=new QComboBox(this,"boxInst");
19 boxInst->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Maximum)); 24 boxInst->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Maximum));
20 connect(boxInst,SIGNAL(activated(int)),this,SLOT(setCurrentInstrumetID(int))); 25 connect(boxInst,SIGNAL(activated(int)),this,SLOT(setCurrentInstrumetID(int)));
21 for(int i=0;i<data->noOfInstruments();i++) 26 for(int i=0;i<data->noOfInstruments();i++)
22 { 27 {
23 Instrument inst=data->getInstrument(i); 28 Instrument inst=data->getInstrument(i);
24 QString name=inst.instName(); 29 QString name=inst.instName();
25 if(name.isNull()) continue; 30 if(name.isNull()) continue;
26 boxInst->insertItem(name,i); 31 boxInst->insertItem(name,i);
27 } 32 }
28 boxInst->setCurrentItem(instid); 33 boxInst->setCurrentItem(instid);
29 toplayout->addWidget(boxInst); 34 toplayout->addWidget(boxInst);
30 35
31 QPushButton* addButton=new QPushButton(tr("Add"),this,"addButton"); 36 QPushButton* addButton=new QPushButton(tr("Add"),this,"addButton");
32 connect(addButton,SIGNAL(pressed()),this,SLOT(addInstrument())); 37 connect(addButton,SIGNAL(pressed()),this,SLOT(addInstrument()));
33 toplayout->addWidget(addButton); 38 toplayout->addWidget(addButton);
34 39
35 QPushButton* delButton=new QPushButton(tr("Delete"),this,"delButton"); 40 QPushButton* delButton=new QPushButton(tr("Delete"),this,"delButton");
36 connect(delButton,SIGNAL(pressed()),this,SLOT(deleteInstrument())); 41 connect(delButton,SIGNAL(pressed()),this,SLOT(deleteInstrument()));
37 toplayout->addWidget(delButton); 42 toplayout->addWidget(delButton);
38 43
39 QPushButton* addhighButton=new QPushButton(tr("Add High String"),this,"addhighButton"); 44 QPushButton* addhighButton=new QPushButton(tr("Add High String"),this,"addhighButton");
40 masterlayout->addWidget(addhighButton); 45 masterlayout->addWidget(addhighButton);
41 46
42 scrollview=new QScrollView(this); 47 scrollview=new QScrollView(this);
43 scrollview->setVScrollBarMode(QScrollView::AlwaysOn); 48 scrollview->setVScrollBarMode(QScrollView::AlwaysOn);
44 scrollview->setHScrollBarMode(QScrollView::AlwaysOff); 49 scrollview->setHScrollBarMode(QScrollView::AlwaysOff);
45 stringwidget=new QVBox(scrollview->viewport()); 50 stringwidget=new QVBox(scrollview->viewport());
46 stringwidget->setSizePolicy(QSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum)); 51 stringwidget->setSizePolicy(QSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum));
47 stringwidget->setSpacing(10); 52 stringwidget->setSpacing(10);
48 scrollview->addChild(stringwidget); 53 scrollview->addChild(stringwidget);
49 scrollview->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Maximum)); 54 scrollview->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Maximum));
50 masterlayout->addWidget(scrollview); 55 masterlayout->addWidget(scrollview);
51 56
52 loadInstrument(); 57 loadInstrument();
53 58
54 QPushButton* addlowButton=new QPushButton(tr("Add Low String"),this,"addlowButton"); 59 QPushButton* addlowButton=new QPushButton(tr("Add Low String"),this,"addlowButton");
55 masterlayout->addWidget(addlowButton); 60 masterlayout->addWidget(addlowButton);
56 61
57 //make dialog fit the screen 62 //make dialog fit the screen
58 QPEApplication::showDialog( this ); 63 QPEApplication::showDialog( this );
59} 64}
60//**************************************************************************** 65//****************************************************************************
61Menu::InstEditDialog::~InstEditDialog() 66Menu::InstEditDialog::~InstEditDialog()
62{ 67{
63} 68}
64//**************************************************************************** 69//****************************************************************************
65void Menu::InstEditDialog::setCurrentInstrumetID(int id) 70void Menu::InstEditDialog::setCurrentInstrumetID(int id)
66{ 71{
67 saveInstrument(); 72 saveInstrument();
68 instid=id; 73 instid=id;
69 data->setCurrentInstrumetID(id); 74 data->setCurrentInstrumetID(id);
70 loadInstrument(); 75 loadInstrument();
71} 76}
72//**************************************************************************** 77//****************************************************************************
73void Menu::InstEditDialog::addInstrument() 78void Menu::InstEditDialog::addInstrument()
74{ 79{
75} 80}
76//**************************************************************************** 81//****************************************************************************
77void Menu::InstEditDialog::deleteInstrument() 82void Menu::InstEditDialog::deleteInstrument()
78{ 83{
79} 84}
80//**************************************************************************** 85//****************************************************************************
81void Menu::InstEditDialog::addLowString() 86void Menu::InstEditDialog::addLowString()
82{ 87{
83} 88}
84//**************************************************************************** 89//****************************************************************************
85void Menu::InstEditDialog::addHighString() 90void Menu::InstEditDialog::addHighString()
86{ 91{
87} 92}
88//**************************************************************************** 93//****************************************************************************
89void Menu::InstEditDialog::deleteString(int id) 94void Menu::InstEditDialog::deleteString(int id)
90{ 95{
91} 96}
92//**************************************************************************** 97//****************************************************************************
93void Menu::InstEditDialog::saveInstrument() 98void Menu::InstEditDialog::saveInstrument()
94{ 99{
95 //auto delete is set to true so widgets _should_ be deleted 100 //auto delete is set to true so widgets _should_ be deleted
96 stringlist.clear(); 101 stringlist.clear();
97} 102}
98//**************************************************************************** 103//****************************************************************************
99void Menu::InstEditDialog::loadInstrument() 104void Menu::InstEditDialog::loadInstrument()
100{ 105{
101 stringlist.clear(); 106 stringlist.clear();
102 Instrument inst=data->getInstrument(instid); 107 Instrument inst=data->getInstrument(instid);
103 qDebug("load Instrument : %d strings",inst.noOfStrings()); 108 odebug << "load Instrument : " << inst.noOfStrings() << " strings" << oendl;
104 for(uint s=0;s<inst.noOfStrings();s++) 109 for(uint s=0;s<inst.noOfStrings();s++)
105 { 110 {
106 stringlist.append(new EditStringWidget(inst.string(s),stringwidget)); 111 stringlist.append(new EditStringWidget(inst.string(s),stringwidget));
107 } 112 }
108} 113}
109//**************************************************************************** 114//****************************************************************************
110//**************************************************************************** 115//****************************************************************************
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 @@
1#include "fretboard.h" 1#include "fretboard.h"
2 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
7/* QT */
3#include <qpainter.h> 8#include <qpainter.h>
4 9
5Graph::FretBoard::FretBoard(TonleiterData* data,QWidget* parent,const char* name,WFlags f) 10Graph::FretBoard::FretBoard(TonleiterData* data,QWidget* parent,const char* name,WFlags f)
6:QWidget(parent,name,f),data(data) 11:QWidget(parent,name,f),data(data)
7{ 12{
8 setBackgroundColor(QColor(0,0,0)); 13 setBackgroundColor(QColor(0,0,0));
9 fretpen=QPen(QColor(155,155,155),0); 14 fretpen=QPen(QColor(155,155,155),0);
10 markerbrush=QBrush(QColor(155,155,155)); 15 markerbrush=QBrush(QColor(155,155,155));
11 stringpen=QPen(QColor(255,255,255),3); 16 stringpen=QPen(QColor(255,255,255),3);
12 connect(data,SIGNAL(dataChange()),this,SLOT(dataChange())); 17 connect(data,SIGNAL(dataChange()),this,SLOT(dataChange()));
13} 18}
14//**************************************************************************** 19//****************************************************************************
15Graph::FretBoard::~FretBoard() 20Graph::FretBoard::~FretBoard()
16{ 21{
17} 22}
18//**************************************************************************** 23//****************************************************************************
19void Graph::FretBoard::dataChange() 24void Graph::FretBoard::dataChange()
20{ 25{
21 repaint(true); 26 repaint(true);
22} 27}
23//**************************************************************************** 28//****************************************************************************
24void Graph::FretBoard::paintEvent(QPaintEvent* pe) 29void Graph::FretBoard::paintEvent(QPaintEvent* pe)
25{ 30{
26 Q_UNUSED(pe); 31 Q_UNUSED(pe);
27 32
28 int instid=data->getCurrentInstrumentID(); 33 int instid=data->getCurrentInstrumentID();
29 inst=data->getInstrument(instid); 34 inst=data->getInstrument(instid);
30 //qDebug("inst %d is %s",instid,inst.instName().data()); 35 //odebug << "inst " << instid << " is " << inst.instName().data() << "" << oendl;
31 36
32 QRect mysize=rect(); 37 QRect mysize=rect();
33 38
34 xmargin=(int)(mysize.width()*0.05); 39 xmargin=(int)(mysize.width()*0.05);
35 xmin=2*xmargin; 40 xmin=2*xmargin;
36 xmax=mysize.width()-xmargin; 41 xmax=mysize.width()-xmargin;
37 xwidth=xmax-xmin; 42 xwidth=xmax-xmin;
38 43
39 ymargin=(int)(mysize.height()*0.1); 44 ymargin=(int)(mysize.height()*0.1);
40 ymin=ymargin; 45 ymin=ymargin;
41 ymax=mysize.height()-2*ymargin; 46 ymax=mysize.height()-2*ymargin;
42 yheight=ymax-ymin; 47 yheight=ymax-ymin;
43 48
44 QPainter p(this); 49 QPainter p(this);
45 paintBoard(&p); 50 paintBoard(&p);
46 paintFrets(&p); 51 paintFrets(&p);
47 paintStrings(&p); 52 paintStrings(&p);
48 paintScale(&p); 53 paintScale(&p);
49} 54}
50//**************************************************************************** 55//****************************************************************************
51void Graph::FretBoard::resizeEvent(QResizeEvent* re) 56void Graph::FretBoard::resizeEvent(QResizeEvent* re)
52{ 57{
53 Q_UNUSED(re); 58 Q_UNUSED(re);
54} 59}
55//**************************************************************************** 60//****************************************************************************
56void Graph::FretBoard::mouseReleaseEvent(QMouseEvent* me) 61void Graph::FretBoard::mouseReleaseEvent(QMouseEvent* me)
57{ 62{
58 Q_UNUSED(me); 63 Q_UNUSED(me);
59 emit pressed(); 64 emit pressed();
60} 65}
61//**************************************************************************** 66//****************************************************************************
62void Graph::FretBoard::paintBoard(QPainter* p) 67void Graph::FretBoard::paintBoard(QPainter* p)
63{ 68{
64 //debug 69 //debug
65 QColor bgc=QColor(142,138,120); 70 QColor bgc=QColor(142,138,120);
66 p->setPen(QPen(bgc,5)); 71 p->setPen(QPen(bgc,5));
67 p->setBrush(QBrush(bgc)); 72 p->setBrush(QBrush(bgc));
68 p->drawRect(xmin,ymin,xwidth,yheight); 73 p->drawRect(xmin,ymin,xwidth,yheight);
69 74
70} 75}
71//**************************************************************************** 76//****************************************************************************
72void Graph::FretBoard::paintFrets(QPainter* p) 77void Graph::FretBoard::paintFrets(QPainter* p)
73{ 78{
74 //draw frets 79 //draw frets
75 p->setPen(fretpen); 80 p->setPen(fretpen);
76 p->setBrush(markerbrush); 81 p->setBrush(markerbrush);
77 fretdist=(double)(xwidth)/(double)(inst.noOfFrets()); 82 fretdist=(double)(xwidth)/(double)(inst.noOfFrets());
78 83
79 int markerwidth = (int)(fretdist/4.0); 84 int markerwidth = (int)(fretdist/4.0);
80 if(markerwidth>5) 85 if(markerwidth>5)
81 markerwidth=5; 86 markerwidth=5;
82 else if(markerwidth<2) 87 else if(markerwidth<2)
83 markerwidth=2; 88 markerwidth=2;
84 89
85 for(int f=0;f<=inst.noOfFrets();f++) 90 for(int f=0;f<=inst.noOfFrets();f++)
86 { 91 {
87 int fretpos=(int)(fretdist*f); 92 int fretpos=(int)(fretdist*f);
88 p->drawLine(fretpos+xmin,ymin,fretpos+xmin,ymax); 93 p->drawLine(fretpos+xmin,ymin,fretpos+xmin,ymax);
89 94
90 int above_octave=f%12; 95 int above_octave=f%12;
91 int octave=(f-above_octave)/12; 96 int octave=(f-above_octave)/12;
92 int marker=f-12*octave; 97 int marker=f-12*octave;
93 98
94 99
95 if(marker==5 || marker==7 || marker==9) 100 if(marker==5 || marker==7 || marker==9)
96 { 101 {
97 p->drawEllipse(fretpos+xmin,ymax+ymargin,markerwidth,markerwidth); 102 p->drawEllipse(fretpos+xmin,ymax+ymargin,markerwidth,markerwidth);
98 } 103 }
99 else if(marker==0 && f!=0) 104 else if(marker==0 && f!=0)
100 { 105 {
101 p->drawEllipse(fretpos+xmin,ymax+ymargin+2*markerwidth,markerwidth,markerwidth); 106 p->drawEllipse(fretpos+xmin,ymax+ymargin+2*markerwidth,markerwidth,markerwidth);
102 p->drawEllipse(fretpos+xmin,ymax+ymargin-2*markerwidth,markerwidth,markerwidth); 107 p->drawEllipse(fretpos+xmin,ymax+ymargin-2*markerwidth,markerwidth,markerwidth);
103 } 108 }
104 109
105 } 110 }
106} 111}
107//**************************************************************************** 112//****************************************************************************
108void Graph::FretBoard::paintStrings(QPainter* p) 113void Graph::FretBoard::paintStrings(QPainter* p)
109{ 114{
110 //draw strings 115 //draw strings
111 p->setPen(stringpen); 116 p->setPen(stringpen);
112 117
113 stringdist=(double)(yheight)/(double)(inst.noOfStrings()-1); 118 stringdist=(double)(yheight)/(double)(inst.noOfStrings()-1);
114 for(int s=0;s<inst.noOfStrings();s++) 119 for(int s=0;s<inst.noOfStrings();s++)
115 { 120 {
116 int stringpos=(int)(stringdist*s); 121 int stringpos=(int)(stringdist*s);
117 p->drawLine(xmin,stringpos+ymin,xmax,stringpos+ymin); 122 p->drawLine(xmin,stringpos+ymin,xmax,stringpos+ymin);
118 123
119 int stinglabelid=inst.noOfStrings()-(s+1); 124 int stinglabelid=inst.noOfStrings()-(s+1);
120 QString label=Note::getNameOfNote(inst.string(stinglabelid)); 125 QString label=Note::getNameOfNote(inst.string(stinglabelid));
121 p->drawText(xmargin/2,stringpos+ymin,label); 126 p->drawText(xmargin/2,stringpos+ymin,label);
122 } 127 }
123} 128}
124//**************************************************************************** 129//****************************************************************************
125void Graph::FretBoard::paintScale(QPainter* p) 130void Graph::FretBoard::paintScale(QPainter* p)
126{ 131{
127 int dotsize=10; 132 int dotsize=10;
128 int scaleid=data->getCurrentScaleID(); 133 int scaleid=data->getCurrentScaleID();
129 Scale scale=data->getScale(scaleid); 134 Scale scale=data->getScale(scaleid);
130 int baseoctave=Note::octaveOfBaseNote(data->getCurrentBaseNote(),inst.lowestNote()); 135 int baseoctave=Note::octaveOfBaseNote(data->getCurrentBaseNote(),inst.lowestNote());
131 136
132 for(int s=0;s<inst.noOfStrings();s++) 137 for(int s=0;s<inst.noOfStrings();s++)
133 { 138 {
134 int y=(int)(stringdist*s)+ymin; 139 int y=(int)(stringdist*s)+ymin;
135 int stingid=inst.noOfStrings()-(s+1); 140 int stingid=inst.noOfStrings()-(s+1);
136 for(int f=0;f<=inst.noOfFrets();f++) 141 for(int f=0;f<=inst.noOfFrets();f++)
137 { 142 {
138 int note=inst.string(stingid)+f; 143 int note=inst.string(stingid)+f;
139 if(scale.noteInScale(data->getCurrentBaseNote(),note)) 144 if(scale.noteInScale(data->getCurrentBaseNote(),note))
140 { 145 {
141 int x=(int)(fretdist*f)+xmin; 146 int x=(int)(fretdist*f)+xmin;
142 147
143 //no more than six octaves can be visualised (there is a zero octave) 148 //no more than six octaves can be visualised (there is a zero octave)
144 int octave=Note::octaveOfBaseNote(data->getCurrentBaseNote(),note)-baseoctave; 149 int octave=Note::octaveOfBaseNote(data->getCurrentBaseNote(),note)-baseoctave;
145 if(octave<0) 150 if(octave<0)
146 qDebug("%d,%d",octave,baseoctave); 151 odebug << "" << octave << "," << baseoctave << "" << oendl;
147 if(octave>5) 152 if(octave>5)
148 { 153 {
149 qDebug("octave out of range"); 154 odebug << "octave out of range" << oendl;
150 octave=5; 155 octave=5;
151 } 156 }
152 157
153 p->setPen(QColor(255,0,0)); 158 p->setPen(QColor(255,0,0));
154 int c= ( (note-12*baseoctave) - (12*octave+data->getCurrentBaseNote()) )*15; 159 int c= ( (note-12*baseoctave) - (12*octave+data->getCurrentBaseNote()) )*15;
155 if(c<0 || c>255) 160 if(c<0 || c>255)
156 qDebug("%d = %d - ( %d + %d)",c,note,12*octave,data->getCurrentBaseNote()); 161 odebug << "" << c << " = " << note << " - ( " << 12*octave << " + " << data->getCurrentBaseNote() << ")" << oendl;
157 QColor dotcolor(255,255,255); 162 QColor dotcolor(255,255,255);
158 163
159 if(octave==0) 164 if(octave==0)
160 dotcolor=QColor(c,c,255); 165 dotcolor=QColor(c,c,255);
161 else if(octave==1) 166 else if(octave==1)
162 dotcolor=QColor(c,255,c); 167 dotcolor=QColor(c,255,c);
163 else if(octave==2) 168 else if(octave==2)
164 dotcolor=QColor(255,c,c); 169 dotcolor=QColor(255,c,c);
165 else if(octave==3) 170 else if(octave==3)
166 dotcolor=QColor(255,255,c); 171 dotcolor=QColor(255,255,c);
167 else if(octave==4) 172 else if(octave==4)
168 dotcolor=QColor(255,c,255); 173 dotcolor=QColor(255,c,255);
169 else 174 else
170 dotcolor=QColor(c,255,255); 175 dotcolor=QColor(c,255,255);
171 176
172 p->setBrush(dotcolor); 177 p->setBrush(dotcolor);
173 p->drawEllipse(x-dotsize/2,y-dotsize/2,dotsize,dotsize); 178 p->drawEllipse(x-dotsize/2,y-dotsize/2,dotsize,dotsize);
174 179
175 if(data->isDrawNames()) 180 if(data->isDrawNames())
176 { 181 {
177 p->setPen(QColor(255,155,0)); 182 p->setPen(QColor(255,155,0));
178 p->drawText(x-dotsize/2,y-dotsize/2,Note::getNameOfNote(note)); 183 p->drawText(x-dotsize/2,y-dotsize/2,Note::getNameOfNote(note));
179 } 184 }
180 185
181 } 186 }
182 } 187 }
183 } 188 }
184} 189}
185//**************************************************************************** 190//****************************************************************************
186//**************************************************************************** 191//****************************************************************************
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 @@
1TEMPLATE = app 1TEMPLATE = app
2#CONFIG = qt warn_on
3CONFIG = qt warn_on 2CONFIG = qt warn_on
4HEADERS = mainwidget.h tonleiterdata.h tonleiterdatahelper.h fretboard.h menuwidget.h editinst.h editstringwidget.h editscale.h pianoscale.h 3HEADERS = mainwidget.h tonleiterdata.h tonleiterdatahelper.h fretboard.h menuwidget.h editinst.h editstringwidget.h editscale.h pianoscale.h
5SOURCES = mainwidget.cpp tonleiterdata.cpp tonleiterdatahelper.cpp fretboard.cpp menuwidget.cpp main.cpp editinst.cpp editstringwidget.cpp editscale.cpp pianoscale.cpp 4SOURCES = mainwidget.cpp tonleiterdata.cpp tonleiterdatahelper.cpp fretboard.cpp menuwidget.cpp main.cpp editinst.cpp editstringwidget.cpp editscale.cpp pianoscale.cpp
6INCLUDEPATH += $(OPIEDIR)/include 5INCLUDEPATH += $(OPIEDIR)/include
7DEPENDPATH += $(OPIEDIR)/include 6DEPENDPATH += $(OPIEDIR)/include
8LIBS += -lqpe 7LIBS += -lqpe -lopiecore2
9INTERFACES =
10TARGET = tonleiter 8TARGET = tonleiter
11DESTDIR = $(OPIEDIR)/bin 9DESTDIR = $(OPIEDIR)/bin
12#TMAKE_CXXFLAGS += -DQT_QWS_VERCEL_IDR -DQWS -fno-exceptions -fno-rtti 10
13include ( $(OPIEDIR)/include.pro ) 11include ( $(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 @@
1#include "tonleiterdata.h" 1#include "tonleiterdata.h"
2
3#include <qpe/config.h>
4
5using namespace Data; 2using namespace Data;
6 3
4/* OPIE */
5#include <opie2/odebug.h>
6#include <qpe/config.h>
7using namespace Opie::Core;
7 8
8TonleiterData::TonleiterData(QObject* parent) 9TonleiterData::TonleiterData(QObject* parent)
9:QObject(parent) 10:QObject(parent)
10{ 11{
11 drawnames=true; 12 drawnames=true;
12 loadData(); 13 loadData();
13} 14}
14//**************************************************************************** 15//****************************************************************************
15TonleiterData::~TonleiterData() 16TonleiterData::~TonleiterData()
16{ 17{
17 saveData(); 18 saveData();
18} 19}
19//**************************************************************************** 20//****************************************************************************
20void TonleiterData::setCurrentInstrumetID(int id) 21void TonleiterData::setCurrentInstrumetID(int id)
21{ 22{
22 if(id>=0 && id<noOfInstruments()) 23 if(id>=0 && id<noOfInstruments())
23 { 24 {
24 currentInstrumentID=id; 25 currentInstrumentID=id;
25 emit dataChange(); 26 emit dataChange();
26 } 27 }
27} 28}
28//**************************************************************************** 29//****************************************************************************
29void TonleiterData::setCurrentScaleID(int id) 30void TonleiterData::setCurrentScaleID(int id)
30{ 31{
31 if(id>=0 && id<noOfScales()) 32 if(id>=0 && id<noOfScales())
32 { 33 {
33 currentScaleID=id; 34 currentScaleID=id;
34 emit dataChange(); 35 emit dataChange();
35 } 36 }
36} 37}
37//**************************************************************************** 38//****************************************************************************
38void TonleiterData::setCurrentNote(int id) 39void TonleiterData::setCurrentNote(int id)
39{ 40{
40 if(id>=0 && id<12) 41 if(id>=0 && id<12)
41 { 42 {
42 currentNote=id; 43 currentNote=id;
43 emit dataChange(); 44 emit dataChange();
44 } 45 }
45} 46}
46//**************************************************************************** 47//****************************************************************************
47void TonleiterData::setDrawNames(bool dn) 48void TonleiterData::setDrawNames(bool dn)
48{ 49{
49 drawnames=dn; 50 drawnames=dn;
50 emit dataChange(); 51 emit dataChange();
51} 52}
52//**************************************************************************** 53//****************************************************************************
53void TonleiterData::loadData() 54void TonleiterData::loadData()
54{ 55{
55 Config load("Tonleiter"); 56 Config load("Tonleiter");
56 if(!load.isValid()) 57 if(!load.isValid())
57 { 58 {
58 //write some default values 59 //write some default values
59 load.setGroup("General"); 60 load.setGroup("General");
60 load.writeEntry("currentInstrumentID",1); 61 load.writeEntry("currentInstrumentID",1);
61 load.writeEntry("currentNote",3); 62 load.writeEntry("currentNote",3);
62 load.writeEntry("currentScaleID",0); 63 load.writeEntry("currentScaleID",0);
63 load.writeEntry("drawnames",1); 64 load.writeEntry("drawnames",1);
64 load.setGroup("Instrument"); 65 load.setGroup("Instrument");
65 load.writeEntry("Inst0","Thumb6;26;14;19;24;29;34;39;"); 66 load.writeEntry("Inst0","Thumb6;26;14;19;24;29;34;39;");
66 load.writeEntry("Inst1","Bass 4;12;19;24;29;34;"); 67 load.writeEntry("Inst1","Bass 4;12;19;24;29;34;");
67 load.writeEntry("noOfInstruments",2); 68 load.writeEntry("noOfInstruments",2);
68 load.setGroup("Scale"); 69 load.setGroup("Scale");
69 load.writeEntry("Scale0","ionian;0;2;4;5;7;9;11;"); 70 load.writeEntry("Scale0","ionian;0;2;4;5;7;9;11;");
70 load.writeEntry("Scale1","aeolian;0;2;3;5;7;8;10;"); 71 load.writeEntry("Scale1","aeolian;0;2;3;5;7;8;10;");
71 load.writeEntry("Scale2","dorian;0;2;3;5;7;9;10;"); 72 load.writeEntry("Scale2","dorian;0;2;3;5;7;9;10;");
72 load.writeEntry("Scale3","phrygian;0;1;3;5;7;8;10;"); 73 load.writeEntry("Scale3","phrygian;0;1;3;5;7;8;10;");
73 load.writeEntry("Scale4","lydian;0;2;4;6;7;9;11;"); 74 load.writeEntry("Scale4","lydian;0;2;4;6;7;9;11;");
74 load.writeEntry("Scale5","mixolydian;0;2;4;5;7;9;10;"); 75 load.writeEntry("Scale5","mixolydian;0;2;4;5;7;9;10;");
75 load.writeEntry("noOfScales",6); 76 load.writeEntry("noOfScales",6);
76 77
77 } 78 }
78 79
79 load.setGroup("General"); 80 load.setGroup("General");
80 currentNote=load.readNumEntry("currentNote"); 81 currentNote=load.readNumEntry("currentNote");
81 drawnames=load.readBoolEntry("drawnames"); 82 drawnames=load.readBoolEntry("drawnames");
82 currentInstrumentID=load.readNumEntry("currentInstrumentID"); 83 currentInstrumentID=load.readNumEntry("currentInstrumentID");
83 currentScaleID=load.readNumEntry("currentScaleID"); 84 currentScaleID=load.readNumEntry("currentScaleID");
84 85
85 load.setGroup("Instrument"); 86 load.setGroup("Instrument");
86 int noOfInstr=load.readNumEntry("noOfInstruments",0); 87 int noOfInstr=load.readNumEntry("noOfInstruments",0);
87 for(int i=0;i<noOfInstr;i++) 88 for(int i=0;i<noOfInstr;i++)
88 { 89 {
89 QStringList instlist=load.readListEntry("Inst"+QString::number(i),';'); 90 QStringList instlist=load.readListEntry("Inst"+QString::number(i),';');
90 QValueList<int> strings; 91 QValueList<int> strings;
91 for(int st=2;st<(int)instlist.count();st++) 92 for(int st=2;st<(int)instlist.count();st++)
92 strings.append(instlist[st].toInt()); 93 strings.append(instlist[st].toInt());
93 instruments.append(Instrument(instlist[0],instlist[1].toInt(),strings)); 94 instruments.append(Instrument(instlist[0],instlist[1].toInt(),strings));
94 } 95 }
95 96
96 load.setGroup("Scale"); 97 load.setGroup("Scale");
97 int scaleno=load.readNumEntry("noOfScales",0); 98 int scaleno=load.readNumEntry("noOfScales",0);
98 for(int s=0;s<scaleno;s++) 99 for(int s=0;s<scaleno;s++)
99 { 100 {
100 QStringList scalelist=load.readListEntry("Scale"+QString::number(s),';'); 101 QStringList scalelist=load.readListEntry("Scale"+QString::number(s),';');
101 QValueList<int> halftones; 102 QValueList<int> halftones;
102 for(int ht=1;ht<(int)scalelist.count();ht++) 103 for(int ht=1;ht<(int)scalelist.count();ht++)
103 halftones.append(scalelist[ht].toInt()); 104 halftones.append(scalelist[ht].toInt());
104 scales.append(Scale(scalelist[0],halftones)); 105 scales.append(Scale(scalelist[0],halftones));
105 } 106 }
106 107
107} 108}
108//**************************************************************************** 109//****************************************************************************
109void TonleiterData::saveData() 110void TonleiterData::saveData()
110{ 111{
111 Config save("Tonleiter"); 112 Config save("Tonleiter");
112 save.setGroup("General"); 113 save.setGroup("General");
113 save.writeEntry("currentNote",currentNote); 114 save.writeEntry("currentNote",currentNote);
114 save.writeEntry("drawnames",drawnames); 115 save.writeEntry("drawnames",drawnames);
115 save.writeEntry("currentInstrumentID",currentInstrumentID); 116 save.writeEntry("currentInstrumentID",currentInstrumentID);
116 save.writeEntry("currentScaleID",currentScaleID); 117 save.writeEntry("currentScaleID",currentScaleID);
117 118
118 save.setGroup("Instrument"); 119 save.setGroup("Instrument");
119 save.writeEntry("noOfInstruments",noOfInstruments()); 120 save.writeEntry("noOfInstruments",noOfInstruments());
120 for(int i=0;i<noOfInstruments();i++) 121 for(int i=0;i<noOfInstruments();i++)
121 { 122 {
122 QStringList instlist; 123 QStringList instlist;
123 Instrument inst=getInstrument(i); 124 Instrument inst=getInstrument(i);
124 instlist.append(inst.instName()); 125 instlist.append(inst.instName());
125 instlist.append(QString::number(inst.noOfFrets())); 126 instlist.append(QString::number(inst.noOfFrets()));
126 for(int st=0;st<inst.noOfStrings();st++) 127 for(int st=0;st<inst.noOfStrings();st++)
127 instlist.append(QString::number(inst.string(st))); 128 instlist.append(QString::number(inst.string(st)));
128 save.writeEntry("Inst"+QString::number(i),instlist,';'); 129 save.writeEntry("Inst"+QString::number(i),instlist,';');
129 } 130 }
130 131
131 save.setGroup("Scale"); 132 save.setGroup("Scale");
132 save.writeEntry("noOfScales",noOfScales()); 133 save.writeEntry("noOfScales",noOfScales());
133 for(int s=0;s<noOfScales();s++) 134 for(int s=0;s<noOfScales();s++)
134 { 135 {
135 QStringList scalelist; 136 QStringList scalelist;
136 Scale scale=getScale(s); 137 Scale scale=getScale(s);
137 scalelist.append(scale.scaleName()); 138 scalelist.append(scale.scaleName());
138 for(int ht=0;ht<scale.noOfHaltones();ht++) 139 for(int ht=0;ht<scale.noOfHaltones();ht++)
139 scalelist.append(QString::number(scale.getHalfTone(ht))); 140 scalelist.append(QString::number(scale.getHalfTone(ht)));
140 save.writeEntry("Scale"+QString::number(s),scalelist,';'); 141 save.writeEntry("Scale"+QString::number(s),scalelist,';');
141 } 142 }
142} 143}
143//**************************************************************************** 144//****************************************************************************
144int TonleiterData::noOfInstruments() 145int TonleiterData::noOfInstruments()
145{ 146{
146 return (int)instruments.count(); 147 return (int)instruments.count();
147} 148}
148//**************************************************************************** 149//****************************************************************************
149Instrument TonleiterData::getInstrument(int id) 150Instrument TonleiterData::getInstrument(int id)
150{ 151{
151 if(id>=0 && id<noOfInstruments()) 152 if(id>=0 && id<noOfInstruments())
152 return instruments[id]; 153 return instruments[id];
153 else 154 else
154 { 155 {
155 qDebug("undefined insrtument %d of %d",id,instruments.count()); 156 odebug << "undefined insrtument " << id << " of " << instruments.count() << "" << oendl;
156 return Instrument(); 157 return Instrument();
157 } 158 }
158 159
159} 160}
160//**************************************************************************** 161//****************************************************************************
161int TonleiterData::getCurrentInstrumentID() 162int TonleiterData::getCurrentInstrumentID()
162{ 163{
163 return currentInstrumentID; 164 return currentInstrumentID;
164} 165}
165//**************************************************************************** 166//****************************************************************************
166int TonleiterData::noOfScales() 167int TonleiterData::noOfScales()
167{ 168{
168 return (int)scales.count(); 169 return (int)scales.count();
169} 170}
170//**************************************************************************** 171//****************************************************************************
171Scale TonleiterData::getScale(int id) 172Scale TonleiterData::getScale(int id)
172{ 173{
173 if(id>=0 && id<noOfScales()) 174 if(id>=0 && id<noOfScales())
174 return scales[id]; 175 return scales[id];
175 else 176 else
176 { 177 {
177 qDebug("Undefined scale"); 178 odebug << "Undefined scale" << oendl;
178 return Scale(); 179 return Scale();
179 } 180 }
180} 181}
181//**************************************************************************** 182//****************************************************************************
182int TonleiterData::getCurrentScaleID() 183int TonleiterData::getCurrentScaleID()
183{ 184{
184 return currentScaleID; 185 return currentScaleID;
185} 186}
186//**************************************************************************** 187//****************************************************************************
187int TonleiterData::getCurrentBaseNote() 188int TonleiterData::getCurrentBaseNote()
188{ 189{
189 return currentNote; 190 return currentNote;
190} 191}
191//**************************************************************************** 192//****************************************************************************
192bool TonleiterData::isDrawNames() 193bool TonleiterData::isDrawNames()
193{ 194{
194 return drawnames; 195 return drawnames;
195} 196}
196//**************************************************************************** 197//****************************************************************************
197//**************************************************************************** 198//****************************************************************************
198 199
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 @@
1#include "tonleiterdatahelper.h" 1#include "tonleiterdatahelper.h"
2 2
3#include <math.h> 3#include <math.h>
4 4
5using namespace Data; 5using namespace Data;
6 6
7int Note::getOctaveOfNote(int note) 7int Note::getOctaveOfNote(int note)
8{ 8{
9 int remain=note%12; 9 int remain=note%12;
10 return (note-remain)/12; 10 return (note-remain)/12;
11} 11}
12//**************************************************************************** 12//****************************************************************************
13QString Note::getNameOfNote(int note) 13QString Note::getNameOfNote(int note)
14{ 14{
15 int octave=getOctaveOfNote(note); 15 int octave=getOctaveOfNote(note);
16 return notenames[note-12*octave]; 16 return notenames[note-12*octave];
17} 17}
18//**************************************************************************** 18//****************************************************************************
19int Note::getNoteFromName(QString name,int octave) 19int Note::getNoteFromName(QString name,int octave)
20{ 20{
21 int notevalue=0; 21 int notevalue=0;
22 for(int a=0;a<12;a++) 22 for(int a=0;a<12;a++)
23 { 23 {
24 if(name==notenames[a]) 24 if(name==notenames[a])
25 { 25 {
26 notevalue=a; 26 notevalue=a;
27 break; 27 break;
28 } 28 }
29 } 29 }
30 return notevalue+12*octave; 30 return notevalue+12*octave;
31} 31}
32//**************************************************************************** 32//****************************************************************************
33int Note::octaveOfBaseNote(int base,int note) 33int Note::octaveOfBaseNote(int base,int note)
34{ 34{
35 int normnote = (note>=base) ? note-base : (12-base)+note; 35 int normnote = (note>=base) ? note-base : (12-base)+note;
36 int octave=getOctaveOfNote(normnote); 36 int octave=getOctaveOfNote(normnote);
37 //qDebug("note %d of %d base is norm %d -> ocatve %d",note,base,normnote,octave); 37 //odebug << "note " << note << " of " << base << " base is norm " << normnote << " -> ocatve " << octave << "" << oendl;
38 return octave; 38 return octave;
39} 39}
40//**************************************************************************** 40//****************************************************************************
41//**************************************************************************** 41//****************************************************************************
42Instrument::Instrument() 42Instrument::Instrument()
43{ 43{
44 name="UNDEFINED"; 44 name="UNDEFINED";
45 frets=0; 45 frets=0;
46} 46}
47//**************************************************************************** 47//****************************************************************************
48Instrument::Instrument(QString name,int frets,QValueList<int> strings) 48Instrument::Instrument(QString name,int frets,QValueList<int> strings)
49:name(name),frets(frets),strings(strings) 49:name(name),frets(frets),strings(strings)
50{ 50{
51} 51}
52//**************************************************************************** 52//****************************************************************************
53Instrument::~Instrument() 53Instrument::~Instrument()
54{ 54{
55} 55}
56//**************************************************************************** 56//****************************************************************************
57int Instrument::noOfStrings() 57int Instrument::noOfStrings()
58{ 58{
59 return (int)strings.count(); 59 return (int)strings.count();
60} 60}
61//**************************************************************************** 61//****************************************************************************
62int Instrument::noOfFrets() 62int Instrument::noOfFrets()
63{ 63{
64 return frets; 64 return frets;
65} 65}
66//**************************************************************************** 66//****************************************************************************
67QString Instrument::instName() 67QString Instrument::instName()
68{ 68{
69 return name; 69 return name;
70} 70}
71//**************************************************************************** 71//****************************************************************************
72int Instrument::string(int id) 72int Instrument::string(int id)
73{ 73{
74 return strings[id]; 74 return strings[id];
75} 75}
76//**************************************************************************** 76//****************************************************************************
77int Instrument::noOfOctaves() 77int Instrument::noOfOctaves()
78{ 78{
79 return (int) ceil((highestNote()-lowestNote())/12.0); 79 return (int) ceil((highestNote()-lowestNote())/12.0);
80} 80}
81//**************************************************************************** 81//****************************************************************************
82int Instrument::lowestNote() 82int Instrument::lowestNote()
83{ 83{
84 return strings[0]; 84 return strings[0];
85 85
86} 86}
87//**************************************************************************** 87//****************************************************************************
88int Instrument::highestNote() 88int Instrument::highestNote()
89{ 89{
90 return strings[strings.count()-1]+frets; 90 return strings[strings.count()-1]+frets;
91} 91}
92//**************************************************************************** 92//****************************************************************************
93//**************************************************************************** 93//****************************************************************************
94Scale::Scale() 94Scale::Scale()
95{ 95{
96 name="UNDEFINED"; 96 name="UNDEFINED";
97} 97}
98//**************************************************************************** 98//****************************************************************************
99Scale::Scale(QString name,QValueList<int> halftones) 99Scale::Scale(QString name,QValueList<int> halftones)
100:name(name),halftones(halftones) 100:name(name),halftones(halftones)
101{ 101{
102} 102}
103//**************************************************************************** 103//****************************************************************************
104Scale::~Scale() 104Scale::~Scale()
105{ 105{
106} 106}
107//**************************************************************************** 107//****************************************************************************
108int Scale::noOfHaltones() 108int Scale::noOfHaltones()
109{ 109{
110 return (int)halftones.count(); 110 return (int)halftones.count();
111} 111}
112//**************************************************************************** 112//****************************************************************************
113int Scale::getHalfTone(int id) 113int Scale::getHalfTone(int id)
114{ 114{
115 if(id>=0 && id<noOfHaltones()) 115 if(id>=0 && id<noOfHaltones())
116 return halftones[id]; 116 return halftones[id];
117 else 117 else
118 return 0; 118 return 0;
119} 119}
120//**************************************************************************** 120//****************************************************************************
121QString Scale::scaleName() 121QString Scale::scaleName()
122{ 122{
123 return name; 123 return name;
124} 124}
125//**************************************************************************** 125//****************************************************************************
126bool Scale::noteInScale(int base,int note) 126bool Scale::noteInScale(int base,int note)
127{ 127{
128 int octave=Note::getOctaveOfNote(note); 128 int octave=Note::getOctaveOfNote(note);
129 note-=12*octave; 129 note-=12*octave;
130 int normnote = (note>=base) ? note-base : (12-base)+note; 130 int normnote = (note>=base) ? note-base : (12-base)+note;
131 131
132 if(halftones.contains(normnote)>0) 132 if(halftones.contains(normnote)>0)
133 { 133 {
134 //qDebug("OK : base : %d, note %d -> norm %d",base,note,normnote); 134 //odebug << "OK : base : " << base << ", note " << note << " -> norm " << normnote << "" << oendl;
135 return true; 135 return true;
136 } 136 }
137 else 137 else
138 { 138 {
139 //qDebug("BAD : base : %d, note %d -> norm %d",base,note,normnote); 139 //odebug << "BAD : base : " << base << ", note " << note << " -> norm " << normnote << "" << oendl;
140 return false; 140 return false;
141 } 141 }
142} 142}
143//**************************************************************************** 143//****************************************************************************
144//**************************************************************************** 144//****************************************************************************
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 @@
1 1
2#include "accountitem.h" 2#include "accountitem.h"
3#include "accountview.h" 3#include "accountview.h"
4#include "newmaildir.h" 4#include "newmaildir.h"
5#include "nntpgroupsdlg.h" 5#include "nntpgroupsdlg.h"
6#include "defines.h" 6#include "defines.h"
7 7
8/* OPIE */ 8/* OPIE */
9#include <libmailwrapper/mailtypes.h> 9#include <libmailwrapper/mailtypes.h>
10#include <libmailwrapper/abstractmail.h> 10#include <libmailwrapper/abstractmail.h>
11#include <libmailwrapper/mailwrapper.h> 11#include <libmailwrapper/mailwrapper.h>
12#include <qpe/qpeapplication.h> 12#include <qpe/qpeapplication.h>
13 13
14/* QT */ 14/* QT */
15#include <qpopupmenu.h> 15#include <qpopupmenu.h>
16#include <qmessagebox.h> 16#include <qmessagebox.h>
17 17
18using namespace Opie::Core; 18using namespace Opie::Core;
19#define SETPIX(x) if (!account->getOffline()) {setPixmap( 0,x);} else {setPixmap( 0, PIXMAP_OFFLINE );} 19#define SETPIX(x) if (!account->getOffline()) {setPixmap( 0,x);} else {setPixmap( 0, PIXMAP_OFFLINE );}
20/** 20/**
21 * POP3 Account stuff 21 * POP3 Account stuff
22 */ 22 */
23POP3viewItem::POP3viewItem( POP3account *a, AccountView *parent ) 23POP3viewItem::POP3viewItem( POP3account *a, AccountView *parent )
24 : AccountViewItem( parent ) 24 : AccountViewItem( parent )
25{ 25{
26 account = a; 26 account = a;
27 wrapper = AbstractMail::getWrapper( account ); 27 wrapper = AbstractMail::getWrapper( account );
28 SETPIX(PIXMAP_POP3FOLDER); 28 SETPIX(PIXMAP_POP3FOLDER);
29#if 0 29#if 0
30 if (!account->getOffline()) 30 if (!account->getOffline())
31 { 31 {
32 setPixmap( 0, ); 32 setPixmap( 0, );
33 } 33 }
34 else 34 else
35 { 35 {
36 setPixmap( 0, PIXMAP_OFFLINE ); 36 setPixmap( 0, PIXMAP_OFFLINE );
37 } 37 }
38#endif 38#endif
39 setText( 0, account->getAccountName() ); 39 setText( 0, account->getAccountName() );
40 setOpen( true ); 40 setOpen( true );
41} 41}
42 42
43POP3viewItem::~POP3viewItem() 43POP3viewItem::~POP3viewItem()
44{ 44{
45 delete wrapper; 45 delete wrapper;
46} 46}
47 47
48AbstractMail *POP3viewItem::getWrapper() 48AbstractMail *POP3viewItem::getWrapper()
49{ 49{
50 return wrapper; 50 return wrapper;
51} 51}
52 52
53void POP3viewItem::refresh(QValueList<Opie::Core::OSmartPointer<RecMail> > & ) 53void POP3viewItem::refresh(QValueList<Opie::Core::OSmartPointer<RecMail> > & )
54{ 54{
55 refresh(); 55 refresh();
56} 56}
57 57
58void POP3viewItem::refresh() 58void POP3viewItem::refresh()
59{ 59{
60 if (account->getOffline()) return; 60 if (account->getOffline()) return;
61 QValueList<FolderP> *folders = wrapper->listFolders(); 61 QValueList<FolderP> *folders = wrapper->listFolders();
62 QListViewItem *child = firstChild(); 62 QListViewItem *child = firstChild();
63 while ( child ) 63 while ( child )
64 { 64 {
65 QListViewItem *tmp = child; 65 QListViewItem *tmp = child;
66 child = child->nextSibling(); 66 child = child->nextSibling();
67 delete tmp; 67 delete tmp;
68 } 68 }
69 QValueList<FolderP>::ConstIterator it; 69 QValueList<FolderP>::ConstIterator it;
70 QListViewItem*item = 0; 70 QListViewItem*item = 0;
71 for ( it = folders->begin(); it!=folders->end(); ++it) 71 for ( it = folders->begin(); it!=folders->end(); ++it)
72 { 72 {
73 item = new POP3folderItem( (*it), this , item ); 73 item = new POP3folderItem( (*it), this , item );
74 item->setSelectable( (*it)->may_select()); 74 item->setSelectable( (*it)->may_select());
75 } 75 }
76 delete folders; 76 delete folders;
77} 77}
78 78
79RECBODYP POP3viewItem::fetchBody( const RecMailP &mail ) 79RECBODYP POP3viewItem::fetchBody( const RecMailP &mail )
80{ 80{
81 qDebug( "POP3 fetchBody" ); 81 odebug << "POP3 fetchBody" << oendl;
82 return wrapper->fetchBody( mail ); 82 return wrapper->fetchBody( mail );
83} 83}
84 84
85QPopupMenu * POP3viewItem::getContextMenu() 85QPopupMenu * POP3viewItem::getContextMenu()
86{ 86{
87 QPopupMenu *m = new QPopupMenu(0); 87 QPopupMenu *m = new QPopupMenu(0);
88 if (m) 88 if (m)
89 { 89 {
90 if (!account->getOffline()) 90 if (!account->getOffline())
91 { 91 {
92 m->insertItem(QObject::tr("Disconnect",contextName),0); 92 m->insertItem(QObject::tr("Disconnect",contextName),0);
93 m->insertItem(QObject::tr("Set offline",contextName),1); 93 m->insertItem(QObject::tr("Set offline",contextName),1);
94 } 94 }
95 else 95 else
96 { 96 {
97 m->insertItem(QObject::tr("Set online",contextName),1); 97 m->insertItem(QObject::tr("Set online",contextName),1);
98 } 98 }
99 } 99 }
100 return m; 100 return m;
101} 101}
102 102
103void POP3viewItem::disconnect() 103void POP3viewItem::disconnect()
104{ 104{
105 QListViewItem *child = firstChild(); 105 QListViewItem *child = firstChild();
106 while ( child ) 106 while ( child )
107 { 107 {
108 QListViewItem *tmp = child; 108 QListViewItem *tmp = child;
109 child = child->nextSibling(); 109 child = child->nextSibling();
110 delete tmp; 110 delete tmp;
111 } 111 }
112 wrapper->logout(); 112 wrapper->logout();
113} 113}
114 114
115void POP3viewItem::setOnOffline() 115void POP3viewItem::setOnOffline()
116{ 116{
117 if (!account->getOffline()) 117 if (!account->getOffline())
118 { 118 {
119 disconnect(); 119 disconnect();
120 } 120 }
121 account->setOffline(!account->getOffline()); 121 account->setOffline(!account->getOffline());
122 account->save(); 122 account->save();
123 SETPIX(PIXMAP_POP3FOLDER); 123 SETPIX(PIXMAP_POP3FOLDER);
124 refresh(); 124 refresh();
125} 125}
126 126
127void POP3viewItem::contextMenuSelected(int which) 127void POP3viewItem::contextMenuSelected(int which)
128{ 128{
129 switch (which) 129 switch (which)
130 { 130 {
131 case 0: 131 case 0:
132 disconnect(); 132 disconnect();
133 break; 133 break;
134 case 1: 134 case 1:
135 setOnOffline(); 135 setOnOffline();
136 break; 136 break;
137 } 137 }
138} 138}
139 139
140POP3folderItem::~POP3folderItem() 140POP3folderItem::~POP3folderItem()
141{} 141{}
142 142
143POP3folderItem::POP3folderItem( const FolderP&folderInit, POP3viewItem *parent , QListViewItem*after ) 143POP3folderItem::POP3folderItem( const FolderP&folderInit, POP3viewItem *parent , QListViewItem*after )
144 : AccountViewItem(folderInit,parent,after ) 144 : AccountViewItem(folderInit,parent,after )
145{ 145{
146 pop3 = parent; 146 pop3 = parent;
147 if (folder->getDisplayName().lower()!="inbox") 147 if (folder->getDisplayName().lower()!="inbox")
148 { 148 {
149 setPixmap( 0, PIXMAP_POP3FOLDER ); 149 setPixmap( 0, PIXMAP_POP3FOLDER );
150 } 150 }
151 else 151 else
152 { 152 {
153 setPixmap( 0, PIXMAP_INBOXFOLDER); 153 setPixmap( 0, PIXMAP_INBOXFOLDER);
154 } 154 }
155 setText( 0, folder->getDisplayName() ); 155 setText( 0, folder->getDisplayName() );
156} 156}
157 157
158void POP3folderItem::refresh(QValueList<RecMailP>&target) 158void POP3folderItem::refresh(QValueList<RecMailP>&target)
159{ 159{
160 if (folder->may_select()) 160 if (folder->may_select())
161 pop3->getWrapper()->listMessages( folder->getName(),target ); 161 pop3->getWrapper()->listMessages( folder->getName(),target );
162} 162}
163 163
164RECBODYP POP3folderItem::fetchBody(const RecMailP&aMail) 164RECBODYP POP3folderItem::fetchBody(const RecMailP&aMail)
165{ 165{
166 return pop3->getWrapper()->fetchBody(aMail); 166 return pop3->getWrapper()->fetchBody(aMail);
167} 167}
168 168
169QPopupMenu * POP3folderItem::getContextMenu() 169QPopupMenu * POP3folderItem::getContextMenu()
170{ 170{
171 QPopupMenu *m = new QPopupMenu(0); 171 QPopupMenu *m = new QPopupMenu(0);
172 if (m) 172 if (m)
173 { 173 {
174 m->insertItem(QObject::tr("Refresh header list",contextName),0); 174 m->insertItem(QObject::tr("Refresh header list",contextName),0);
175 m->insertItem(QObject::tr("Delete all mails",contextName),1); 175 m->insertItem(QObject::tr("Delete all mails",contextName),1);
176 m->insertItem(QObject::tr("Move/Copie all mails",contextName),2); 176 m->insertItem(QObject::tr("Move/Copie all mails",contextName),2);
177 } 177 }
178 return m; 178 return m;
179} 179}
180 180
181void POP3folderItem::downloadMails() 181void POP3folderItem::downloadMails()
182{ 182{
183 AccountView*bl = pop3->accountView(); 183 AccountView*bl = pop3->accountView();
184 if (!bl) return; 184 if (!bl) return;
185 bl->downloadMails(folder,pop3->getWrapper()); 185 bl->downloadMails(folder,pop3->getWrapper());
186} 186}
187 187
188void POP3folderItem::contextMenuSelected(int which) 188void POP3folderItem::contextMenuSelected(int which)
189{ 189{
190 AccountView * view = (AccountView*)listView(); 190 AccountView * view = (AccountView*)listView();
191 switch (which) 191 switch (which)
192 { 192 {
193 case 0: 193 case 0:
194 /* must be 'cause pop3 lists are cached */ 194 /* must be 'cause pop3 lists are cached */
195 pop3->getWrapper()->logout(); 195 pop3->getWrapper()->logout();
196 view->refreshCurrent(); 196 view->refreshCurrent();
197 break; 197 break;
198 case 1: 198 case 1:
199 deleteAllMail(pop3->getWrapper(),folder); 199 deleteAllMail(pop3->getWrapper(),folder);
200 break; 200 break;
201 case 2: 201 case 2:
202 downloadMails(); 202 downloadMails();
203 break; 203 break;
204 default: 204 default:
205 break; 205 break;
206 } 206 }
207} 207}
208 208
209/** 209/**
210 * NNTP Account stuff 210 * NNTP Account stuff
211 */ 211 */
212NNTPviewItem::NNTPviewItem( NNTPaccount *a, AccountView *parent ) 212NNTPviewItem::NNTPviewItem( NNTPaccount *a, AccountView *parent )
213 : AccountViewItem( parent ) 213 : AccountViewItem( parent )
214{ 214{
215 account = a; 215 account = a;
216 wrapper = AbstractMail::getWrapper( account ); 216 wrapper = AbstractMail::getWrapper( account );
217 //FIXME 217 //FIXME
218 SETPIX(PIXMAP_POP3FOLDER); 218 SETPIX(PIXMAP_POP3FOLDER);
219#if 0 219#if 0
220 if (!account->getOffline()) 220 if (!account->getOffline())
221 { 221 {
222 setPixmap( 0, ); 222 setPixmap( 0, );
223 } 223 }
224 else 224 else
225 { 225 {
226 setPixmap( 0, PIXMAP_OFFLINE ); 226 setPixmap( 0, PIXMAP_OFFLINE );
227 } 227 }
228#endif 228#endif
229 setText( 0, account->getAccountName() ); 229 setText( 0, account->getAccountName() );
230 setOpen( true ); 230 setOpen( true );
231} 231}
232 232
233NNTPviewItem::~NNTPviewItem() 233NNTPviewItem::~NNTPviewItem()
234{ 234{
235 delete wrapper; 235 delete wrapper;
236} 236}
237 237
238AbstractMail *NNTPviewItem::getWrapper() 238AbstractMail *NNTPviewItem::getWrapper()
239{ 239{
240 return wrapper; 240 return wrapper;
241} 241}
242 242
243void NNTPviewItem::refresh( QValueList<RecMailP> & ) 243void NNTPviewItem::refresh( QValueList<RecMailP> & )
244{ 244{
245 refresh(); 245 refresh();
246} 246}
247 247
248void NNTPviewItem::refresh() 248void NNTPviewItem::refresh()
249{ 249{
250 if (account->getOffline()) return; 250 if (account->getOffline()) return;
251 QValueList<FolderP> *folders = wrapper->listFolders(); 251 QValueList<FolderP> *folders = wrapper->listFolders();
252 252
253 QListViewItem *child = firstChild(); 253 QListViewItem *child = firstChild();
254 while ( child ) 254 while ( child )
255 { 255 {
256 QListViewItem *tmp = child; 256 QListViewItem *tmp = child;
257 child = child->nextSibling(); 257 child = child->nextSibling();
258 delete tmp; 258 delete tmp;
259 } 259 }
260 QValueList<FolderP>::ConstIterator it; 260 QValueList<FolderP>::ConstIterator it;
261 QListViewItem*item = 0; 261 QListViewItem*item = 0;
262 for ( it = folders->begin(); it!=folders->end(); ++it) 262 for ( it = folders->begin(); it!=folders->end(); ++it)
263 { 263 {
264 item = new NNTPfolderItem( (*it), this , item ); 264 item = new NNTPfolderItem( (*it), this , item );
265 item->setSelectable( (*it)->may_select()); 265 item->setSelectable( (*it)->may_select());
266 } 266 }
267 delete folders; 267 delete folders;
268} 268}
269 269
270RECBODYP NNTPviewItem::fetchBody( const RecMailP &mail ) 270RECBODYP NNTPviewItem::fetchBody( const RecMailP &mail )
271{ 271{
272 qDebug( "NNTP fetchBody" ); 272 odebug << "NNTP fetchBody" << oendl;
273 return wrapper->fetchBody( mail ); 273 return wrapper->fetchBody( mail );
274} 274}
275 275
276QPopupMenu * NNTPviewItem::getContextMenu() 276QPopupMenu * NNTPviewItem::getContextMenu()
277{ 277{
278 QPopupMenu *m = new QPopupMenu(0); 278 QPopupMenu *m = new QPopupMenu(0);
279 if (m) 279 if (m)
280 { 280 {
281 if (!account->getOffline()) 281 if (!account->getOffline())
282 { 282 {
283 m->insertItem(QObject::tr("Disconnect",contextName),0); 283 m->insertItem(QObject::tr("Disconnect",contextName),0);
284 m->insertItem(QObject::tr("Set offline",contextName),1); 284 m->insertItem(QObject::tr("Set offline",contextName),1);
285 m->insertItem(QObject::tr("(Un-)Subscribe groups",contextName),2); 285 m->insertItem(QObject::tr("(Un-)Subscribe groups",contextName),2);
286 } 286 }
287 else 287 else
288 { 288 {
289 m->insertItem(QObject::tr("Set online",contextName),1); 289 m->insertItem(QObject::tr("Set online",contextName),1);
290 } 290 }
291 } 291 }
292 return m; 292 return m;
293} 293}
294 294
295void NNTPviewItem::subscribeGroups() 295void NNTPviewItem::subscribeGroups()
296{ 296{
297 NNTPGroupsDlg dlg(account); 297 NNTPGroupsDlg dlg(account);
298 if (QPEApplication::execDialog(&dlg)== QDialog::Accepted ){ 298 if (QPEApplication::execDialog(&dlg)== QDialog::Accepted ){
299 refresh(); 299 refresh();
300 } 300 }
301} 301}
302 302
303void NNTPviewItem::disconnect() 303void NNTPviewItem::disconnect()
304{ 304{
305 QListViewItem *child = firstChild(); 305 QListViewItem *child = firstChild();
306 while ( child ) 306 while ( child )
307 { 307 {
308 QListViewItem *tmp = child; 308 QListViewItem *tmp = child;
309 child = child->nextSibling(); 309 child = child->nextSibling();
310 delete tmp; 310 delete tmp;
311 } 311 }
312 wrapper->logout(); 312 wrapper->logout();
313} 313}
314 314
315void NNTPviewItem::setOnOffline() 315void NNTPviewItem::setOnOffline()
316{ 316{
317 if (!account->getOffline()) 317 if (!account->getOffline())
318 { 318 {
319 disconnect(); 319 disconnect();
320 } 320 }
321 account->setOffline(!account->getOffline()); 321 account->setOffline(!account->getOffline());
322 account->save(); 322 account->save();
323 //FIXME 323 //FIXME
324 SETPIX(PIXMAP_POP3FOLDER); 324 SETPIX(PIXMAP_POP3FOLDER);
325 refresh(); 325 refresh();
326} 326}
327 327
328void NNTPviewItem::contextMenuSelected(int which) 328void NNTPviewItem::contextMenuSelected(int which)
329{ 329{
330 switch (which) 330 switch (which)
331 { 331 {
332 case 0: 332 case 0:
333 disconnect(); 333 disconnect();
334 break; 334 break;
335 case 1: 335 case 1:
336 setOnOffline(); 336 setOnOffline();
337 break; 337 break;
338 case 2: 338 case 2:
339 subscribeGroups(); 339 subscribeGroups();
340 break; 340 break;
341 } 341 }
342} 342}
343 343
344NNTPfolderItem::~NNTPfolderItem() 344NNTPfolderItem::~NNTPfolderItem()
345{} 345{}
346 346
347NNTPfolderItem::NNTPfolderItem( const FolderP &folderInit, NNTPviewItem *parent , QListViewItem*after ) 347NNTPfolderItem::NNTPfolderItem( const FolderP &folderInit, NNTPviewItem *parent , QListViewItem*after )
348 : AccountViewItem( folderInit, parent,after ) 348 : AccountViewItem( folderInit, parent,after )
349{ 349{
350 nntp = parent; 350 nntp = parent;
351 if (folder->getDisplayName().lower()!="inbox") 351 if (folder->getDisplayName().lower()!="inbox")
352 { 352 {
353 setPixmap( 0, PIXMAP_POP3FOLDER ); 353 setPixmap( 0, PIXMAP_POP3FOLDER );
354 } 354 }
355 else 355 else
356 { 356 {
357 setPixmap( 0, PIXMAP_INBOXFOLDER); 357 setPixmap( 0, PIXMAP_INBOXFOLDER);
358 } 358 }
359 setText( 0, folder->getDisplayName() ); 359 setText( 0, folder->getDisplayName() );
360} 360}
361 361
362void NNTPfolderItem::refresh(QValueList<RecMailP>&target) 362void NNTPfolderItem::refresh(QValueList<RecMailP>&target)
363{ 363{
364 if (folder->may_select()) 364 if (folder->may_select())
365 nntp->getWrapper()->listMessages( folder->getName(),target ); 365 nntp->getWrapper()->listMessages( folder->getName(),target );
366} 366}
367 367
368RECBODYP NNTPfolderItem::fetchBody(const RecMailP&aMail) 368RECBODYP NNTPfolderItem::fetchBody(const RecMailP&aMail)
369{ 369{
370 return nntp->getWrapper()->fetchBody(aMail); 370 return nntp->getWrapper()->fetchBody(aMail);
371} 371}
372 372
373QPopupMenu * NNTPfolderItem::getContextMenu() 373QPopupMenu * NNTPfolderItem::getContextMenu()
374{ 374{
375 QPopupMenu *m = new QPopupMenu(0); 375 QPopupMenu *m = new QPopupMenu(0);
376 if (m) 376 if (m)
377 { 377 {
378 m->insertItem(QObject::tr("Refresh header list",contextName),0); 378 m->insertItem(QObject::tr("Refresh header list",contextName),0);
379 m->insertItem(QObject::tr("Copy all postings",contextName),1); 379 m->insertItem(QObject::tr("Copy all postings",contextName),1);
380 } 380 }
381 return m; 381 return m;
382} 382}
383 383
384void NNTPfolderItem::downloadMails() 384void NNTPfolderItem::downloadMails()
385{ 385{
386 AccountView*bl = nntp->accountView(); 386 AccountView*bl = nntp->accountView();
387 if (!bl) return; 387 if (!bl) return;
388 bl->downloadMails(folder,nntp->getWrapper()); 388 bl->downloadMails(folder,nntp->getWrapper());
389} 389}
390 390
391void NNTPfolderItem::contextMenuSelected(int which) 391void NNTPfolderItem::contextMenuSelected(int which)
392{ 392{
393 AccountView * view = (AccountView*)listView(); 393 AccountView * view = (AccountView*)listView();
394 switch (which) 394 switch (which)
395 { 395 {
396 case 0: 396 case 0:
397 /* must be 'cause pop3 lists are cached */ 397 /* must be 'cause pop3 lists are cached */
398 nntp->getWrapper()->logout(); 398 nntp->getWrapper()->logout();
399 view->refreshCurrent(); 399 view->refreshCurrent();
400 break; 400 break;
401 case 1: 401 case 1:
402 downloadMails(); 402 downloadMails();
403 break; 403 break;
404 default: 404 default:
405 break; 405 break;
406 } 406 }
407} 407}
408 408
409/** 409/**
410 * IMAP Account stuff 410 * IMAP Account stuff
411 */ 411 */
412IMAPviewItem::IMAPviewItem( IMAPaccount *a, AccountView *parent ) 412IMAPviewItem::IMAPviewItem( IMAPaccount *a, AccountView *parent )
413 : AccountViewItem( parent ) 413 : AccountViewItem( parent )
414{ 414{
415 account = a; 415 account = a;
416 wrapper = AbstractMail::getWrapper( account ); 416 wrapper = AbstractMail::getWrapper( account );
417 SETPIX(PIXMAP_IMAPFOLDER); 417 SETPIX(PIXMAP_IMAPFOLDER);
418 setText( 0, account->getAccountName() ); 418 setText( 0, account->getAccountName() );
419 setOpen( true ); 419 setOpen( true );
420} 420}
421 421
422IMAPviewItem::~IMAPviewItem() 422IMAPviewItem::~IMAPviewItem()
423{ 423{
424 delete wrapper; 424 delete wrapper;
425} 425}
426 426
427AbstractMail *IMAPviewItem::getWrapper() 427AbstractMail *IMAPviewItem::getWrapper()
428{ 428{
429 return wrapper; 429 return wrapper;
430} 430}
431 431
432void IMAPviewItem::refresh(QValueList<RecMailP>&) 432void IMAPviewItem::refresh(QValueList<RecMailP>&)
433{ 433{
434 refreshFolders(false); 434 refreshFolders(false);
435} 435}
436 436
437const QStringList&IMAPviewItem::subFolders() 437const QStringList&IMAPviewItem::subFolders()
438{ 438{
439 return currentFolders; 439 return currentFolders;
440} 440}
441 441
442void IMAPviewItem::refreshFolders(bool force) 442void IMAPviewItem::refreshFolders(bool force)
443{ 443{
444 if (childCount()>0 && force==false) return; 444 if (childCount()>0 && force==false) return;
445 if (account->getOffline()) return; 445 if (account->getOffline()) return;
446 446
447 removeChilds(); 447 removeChilds();
448 currentFolders.clear(); 448 currentFolders.clear();
449 QValueList<FolderP> * folders = wrapper->listFolders(); 449 QValueList<FolderP> * folders = wrapper->listFolders();
450 450
451 QValueList<FolderP>::Iterator it; 451 QValueList<FolderP>::Iterator it;
452 QListViewItem*item = 0; 452 QListViewItem*item = 0;
453 QListViewItem*titem = 0; 453 QListViewItem*titem = 0;
454 QString fname,del,search; 454 QString fname,del,search;
455 int pos; 455 int pos;
456 456
457 for ( it = folders->begin(); it!=folders->end(); ++it) 457 for ( it = folders->begin(); it!=folders->end(); ++it)
458 { 458 {
459 if ((*it)->getDisplayName().lower()=="inbox") 459 if ((*it)->getDisplayName().lower()=="inbox")
460 { 460 {
461 item = new IMAPfolderItem( (*it), this , item ); 461 item = new IMAPfolderItem( (*it), this , item );
462 folders->remove(it); 462 folders->remove(it);
463 qDebug("inbox found"); 463 odebug << "inbox found" << oendl;
464 break; 464 break;
465 } 465 }
466 } 466 }
467 for ( it = folders->begin(); it!=folders->end(); ++it) 467 for ( it = folders->begin(); it!=folders->end(); ++it)
468 { 468 {
469 fname = (*it)->getDisplayName(); 469 fname = (*it)->getDisplayName();
470 currentFolders.append((*it)->getName()); 470 currentFolders.append((*it)->getName());
471 pos = fname.findRev((*it)->Separator()); 471 pos = fname.findRev((*it)->Separator());
472 if (pos != -1) 472 if (pos != -1)
473 { 473 {
474 fname = fname.left(pos); 474 fname = fname.left(pos);
475 } 475 }
476 IMAPfolderItem*pitem = (IMAPfolderItem*)findSubItem(fname); 476 IMAPfolderItem*pitem = (IMAPfolderItem*)findSubItem(fname);
477 if (pitem) 477 if (pitem)
478 { 478 {
479 titem = item; 479 titem = item;
480 item = new IMAPfolderItem( (*it),pitem,pitem->firstChild(),this); 480 item = new IMAPfolderItem( (*it),pitem,pitem->firstChild(),this);
481 /* setup the short name */ 481 /* setup the short name */
482 item->setText(0,(*it)->getDisplayName().right((*it)->getDisplayName().length()-pos-1)); 482 item->setText(0,(*it)->getDisplayName().right((*it)->getDisplayName().length()-pos-1));
483 item = titem; 483 item = titem;
484 } 484 }
485 else 485 else
486 { 486 {
487 item = new IMAPfolderItem( (*it), this , item ); 487 item = new IMAPfolderItem( (*it), this , item );
488 } 488 }
489 } 489 }
490 delete folders; 490 delete folders;
491} 491}
492 492
493QPopupMenu * IMAPviewItem::getContextMenu() 493QPopupMenu * IMAPviewItem::getContextMenu()
494{ 494{
495 QPopupMenu *m = new QPopupMenu(0); 495 QPopupMenu *m = new QPopupMenu(0);
496 if (m) 496 if (m)
497 { 497 {
498 if (!account->getOffline()) 498 if (!account->getOffline())
499 { 499 {
500 m->insertItem(QObject::tr("Refresh folder list",contextName),0); 500 m->insertItem(QObject::tr("Refresh folder list",contextName),0);
501 m->insertItem(QObject::tr("Create new folder",contextName),1); 501 m->insertItem(QObject::tr("Create new folder",contextName),1);
502 m->insertSeparator(); 502 m->insertSeparator();
503 m->insertItem(QObject::tr("Disconnect",contextName),2); 503 m->insertItem(QObject::tr("Disconnect",contextName),2);
504 m->insertItem(QObject::tr("Set offline",contextName),3); 504 m->insertItem(QObject::tr("Set offline",contextName),3);
505 } 505 }
506 else 506 else
507 { 507 {
508 m->insertItem(QObject::tr("Set online",contextName),3); 508 m->insertItem(QObject::tr("Set online",contextName),3);
509 } 509 }
510 } 510 }
511 return m; 511 return m;
512} 512}
513 513
514void IMAPviewItem::createNewFolder() 514void IMAPviewItem::createNewFolder()
515{ 515{
516 Newmdirdlg ndirdlg; 516 Newmdirdlg ndirdlg;
517 if ( QPEApplication::execDialog( &ndirdlg )) 517 if ( QPEApplication::execDialog( &ndirdlg ))
518 { 518 {
519 QString ndir = ndirdlg.Newdir(); 519 QString ndir = ndirdlg.Newdir();
520 bool makesubs = ndirdlg.subpossible(); 520 bool makesubs = ndirdlg.subpossible();
521 QString delemiter = "/"; 521 QString delemiter = "/";
522 IMAPfolderItem*item = (IMAPfolderItem*)firstChild(); 522 IMAPfolderItem*item = (IMAPfolderItem*)firstChild();
523 if (item) 523 if (item)
524 { 524 {
525 delemiter = item->Delemiter(); 525 delemiter = item->Delemiter();
526 } 526 }
527 if (wrapper->createMbox(ndir,0,delemiter,makesubs)) 527 if (wrapper->createMbox(ndir,0,delemiter,makesubs))
528 { 528 {
529 refreshFolders(true); 529 refreshFolders(true);
530 } 530 }
531 } 531 }
532} 532}
533 533
534void IMAPviewItem::contextMenuSelected(int id) 534void IMAPviewItem::contextMenuSelected(int id)
535{ 535{
536 qDebug("Id selected: %i",id); 536 odebug << "Id selected: " << id << "" << oendl;
537 switch (id) 537 switch (id)
538 { 538 {
539 case 0: 539 case 0:
540 refreshFolders(true); 540 refreshFolders(true);
541 break; 541 break;
542 case 1: 542 case 1:
543 createNewFolder(); 543 createNewFolder();
544 break; 544 break;
545 case 2: 545 case 2:
546 removeChilds(); 546 removeChilds();
547 wrapper->logout(); 547 wrapper->logout();
548 break; 548 break;
549 case 3: 549 case 3:
550 if (account->getOffline()==false) 550 if (account->getOffline()==false)
551 { 551 {
552 removeChilds(); 552 removeChilds();
553 wrapper->logout(); 553 wrapper->logout();
554 } 554 }
555 account->setOffline(!account->getOffline()); 555 account->setOffline(!account->getOffline());
556 account->save(); 556 account->save();
557 SETPIX(PIXMAP_IMAPFOLDER); 557 SETPIX(PIXMAP_IMAPFOLDER);
558 refreshFolders(false); 558 refreshFolders(false);
559 break; 559 break;
560 default: 560 default:
561 break; 561 break;
562 } 562 }
563} 563}
564 564
565RECBODYP IMAPviewItem::fetchBody(const RecMailP&) 565RECBODYP IMAPviewItem::fetchBody(const RecMailP&)
566{ 566{
567 return new RecBody(); 567 return new RecBody();
568} 568}
569 569
570bool IMAPviewItem::offline() 570bool IMAPviewItem::offline()
571{ 571{
572 return account->getOffline(); 572 return account->getOffline();
573} 573}
574 574
575IMAPfolderItem::IMAPfolderItem( const FolderP& folderInit, IMAPviewItem *parent , QListViewItem*after ) 575IMAPfolderItem::IMAPfolderItem( const FolderP& folderInit, IMAPviewItem *parent , QListViewItem*after )
576 : AccountViewItem( folderInit, parent , after ) 576 : AccountViewItem( folderInit, parent , after )
577{ 577{
578 imap = parent; 578 imap = parent;
579 if (folder->getDisplayName().lower()!="inbox") 579 if (folder->getDisplayName().lower()!="inbox")
580 { 580 {
581 setPixmap( 0, PIXMAP_IMAPFOLDER ); 581 setPixmap( 0, PIXMAP_IMAPFOLDER );
582 } 582 }
583 else 583 else
584 { 584 {
585 setPixmap( 0, PIXMAP_INBOXFOLDER); 585 setPixmap( 0, PIXMAP_INBOXFOLDER);
586 } 586 }
587 setText( 0, folder->getDisplayName() ); 587 setText( 0, folder->getDisplayName() );
588} 588}
589 589
590IMAPfolderItem::IMAPfolderItem(const FolderP &folderInit, IMAPfolderItem *parent , QListViewItem*after, IMAPviewItem *master ) 590IMAPfolderItem::IMAPfolderItem(const FolderP &folderInit, IMAPfolderItem *parent , QListViewItem*after, IMAPviewItem *master )
591 : AccountViewItem(folderInit, parent,after ) 591 : AccountViewItem(folderInit, parent,after )
592{ 592{
593 imap = master; 593 imap = master;
594 if (folder->getDisplayName().lower()!="inbox") 594 if (folder->getDisplayName().lower()!="inbox")
595 { 595 {
596 setPixmap( 0, PIXMAP_IMAPFOLDER ); 596 setPixmap( 0, PIXMAP_IMAPFOLDER );
597 } 597 }
598 else 598 else
599 { 599 {
600 setPixmap( 0, PIXMAP_INBOXFOLDER); 600 setPixmap( 0, PIXMAP_INBOXFOLDER);
601 } 601 }
602 setText( 0, folder->getDisplayName() ); 602 setText( 0, folder->getDisplayName() );
603} 603}
604 604
605IMAPfolderItem::~IMAPfolderItem() 605IMAPfolderItem::~IMAPfolderItem()
606{} 606{}
607 607
608const QString& IMAPfolderItem::Delemiter()const 608const QString& IMAPfolderItem::Delemiter()const
609{ 609{
610 return folder->Separator(); 610 return folder->Separator();
611} 611}
612 612
613void IMAPfolderItem::refresh(QValueList<RecMailP>&target) 613void IMAPfolderItem::refresh(QValueList<RecMailP>&target)
614{ 614{
615 if (folder->may_select()) 615 if (folder->may_select())
616 { 616 {
617 imap->getWrapper()->listMessages( folder->getName(),target ); 617 imap->getWrapper()->listMessages( folder->getName(),target );
618 } 618 }
619 else 619 else
620 { 620 {
621 target.clear(); 621 target.clear();
622 } 622 }
623} 623}
624 624
625RECBODYP IMAPfolderItem::fetchBody(const RecMailP&aMail) 625RECBODYP IMAPfolderItem::fetchBody(const RecMailP&aMail)
626{ 626{
627 return imap->getWrapper()->fetchBody(aMail); 627 return imap->getWrapper()->fetchBody(aMail);
628} 628}
629 629
630QPopupMenu * IMAPfolderItem::getContextMenu() 630QPopupMenu * IMAPfolderItem::getContextMenu()
631{ 631{
632 QPopupMenu *m = new QPopupMenu(0); 632 QPopupMenu *m = new QPopupMenu(0);
633 if (m) 633 if (m)
634 { 634 {
635 if (folder->may_select()) 635 if (folder->may_select())
636 { 636 {
637 m->insertItem(QObject::tr("Refresh header list",contextName),0); 637 m->insertItem(QObject::tr("Refresh header list",contextName),0);
638 m->insertItem(QObject::tr("Move/Copie all mails",contextName),4); 638 m->insertItem(QObject::tr("Move/Copie all mails",contextName),4);
639 m->insertItem(QObject::tr("Delete all mails",contextName),1); 639 m->insertItem(QObject::tr("Delete all mails",contextName),1);
640 } 640 }
641 if (folder->no_inferior()==false) 641 if (folder->no_inferior()==false)
642 { 642 {
643 m->insertItem(QObject::tr("Create new subfolder",contextName),2); 643 m->insertItem(QObject::tr("Create new subfolder",contextName),2);
644 } 644 }
645 if (folder->getDisplayName().lower()!="inbox") 645 if (folder->getDisplayName().lower()!="inbox")
646 { 646 {
647 m->insertItem(QObject::tr("Delete folder",contextName),3); 647 m->insertItem(QObject::tr("Delete folder",contextName),3);
648 } 648 }
649 } 649 }
650 return m; 650 return m;
651} 651}
652 652
653void IMAPfolderItem::createNewFolder() 653void IMAPfolderItem::createNewFolder()
654{ 654{
655 Newmdirdlg ndirdlg; 655 Newmdirdlg ndirdlg;
656 if ( QPEApplication::execDialog( &ndirdlg ) ) 656 if ( QPEApplication::execDialog( &ndirdlg ) )
657 { 657 {
658 QString ndir = ndirdlg.Newdir(); 658 QString ndir = ndirdlg.Newdir();
659 bool makesubs = ndirdlg.subpossible(); 659 bool makesubs = ndirdlg.subpossible();
660 QString delemiter = Delemiter(); 660 QString delemiter = Delemiter();
661 if (imap->wrapper->createMbox(ndir,folder,delemiter,makesubs)) 661 if (imap->wrapper->createMbox(ndir,folder,delemiter,makesubs))
662 { 662 {
663 imap->refreshFolders(true); 663 imap->refreshFolders(true);
664 } 664 }
665 } 665 }
666} 666}
667 667
668void IMAPfolderItem::deleteFolder() 668void IMAPfolderItem::deleteFolder()
669{ 669{
670 int yesno = QMessageBox::warning(0,QObject::tr("Delete folder",contextName), 670 int yesno = QMessageBox::warning(0,QObject::tr("Delete folder",contextName),
671 QObject::tr("<center>Realy delete folder <br><b>%1</b><br>and all if it content?</center>",contextName).arg(folder->getDisplayName()), 671 QObject::tr("<center>Realy delete folder <br><b>%1</b><br>and all if it content?</center>",contextName).arg(folder->getDisplayName()),
672 QObject::tr("Yes",contextName), 672 QObject::tr("Yes",contextName),
673 QObject::tr("No",contextName),QString::null,1,1); 673 QObject::tr("No",contextName),QString::null,1,1);
674 qDebug("Auswahl: %i",yesno); 674 odebug << "Auswahl: " << yesno << "" << oendl;
675 if (yesno == 0) 675 if (yesno == 0)
676 { 676 {
677 if (imap->getWrapper()->deleteMbox(folder)) 677 if (imap->getWrapper()->deleteMbox(folder))
678 { 678 {
679 QListView*v=listView(); 679 QListView*v=listView();
680 IMAPviewItem * box = imap; 680 IMAPviewItem * box = imap;
681 /* be carefull - after that this object is destroyd so don't use 681 /* be carefull - after that this object is destroyd so don't use
682 * any member of it after that call!!*/ 682 * any member of it after that call!!*/
683 imap->refreshFolders(true); 683 imap->refreshFolders(true);
684 if (v) 684 if (v)
685 { 685 {
686 v->setSelected(box,true); 686 v->setSelected(box,true);
687 } 687 }
688 } 688 }
689 } 689 }
690} 690}
691 691
692void IMAPfolderItem::downloadMails() 692void IMAPfolderItem::downloadMails()
693{ 693{
694 AccountView*bl = imap->accountView(); 694 AccountView*bl = imap->accountView();
695 if (!bl) return; 695 if (!bl) return;
696 bl->downloadMails(folder,imap->getWrapper()); 696 bl->downloadMails(folder,imap->getWrapper());
697} 697}
698 698
699void IMAPfolderItem::contextMenuSelected(int id) 699void IMAPfolderItem::contextMenuSelected(int id)
700{ 700{
701 qDebug("Selected id: %i",id); 701 odebug << "Selected id: " << id << "" << oendl;
702 AccountView * view = (AccountView*)listView(); 702 AccountView * view = (AccountView*)listView();
703 switch(id) 703 switch(id)
704 { 704 {
705 case 0: 705 case 0:
706 view->refreshCurrent(); 706 view->refreshCurrent();
707 break; 707 break;
708 case 1: 708 case 1:
709 deleteAllMail(imap->getWrapper(),folder); 709 deleteAllMail(imap->getWrapper(),folder);
710 break; 710 break;
711 case 2: 711 case 2:
712 createNewFolder(); 712 createNewFolder();
713 break; 713 break;
714 case 3: 714 case 3:
715 deleteFolder(); 715 deleteFolder();
716 break; 716 break;
717 case 4: 717 case 4:
718 downloadMails(); 718 downloadMails();
719 break; 719 break;
720 default: 720 default:
721 break; 721 break;
722 } 722 }
723} 723}
724 724
725/** 725/**
726 * MH Account stuff 726 * MH Account stuff
727 */ 727 */
728/* MH is a little bit different - the top folder can contains messages other than in IMAP and 728/* MH is a little bit different - the top folder can contains messages other than in IMAP and
729 POP3 and MBOX */ 729 POP3 and MBOX */
730MHviewItem::MHviewItem( const QString&aPath, AccountView *parent ) 730MHviewItem::MHviewItem( const QString&aPath, AccountView *parent )
731 : AccountViewItem( parent ) 731 : AccountViewItem( parent )
732{ 732{
733 m_Path = aPath; 733 m_Path = aPath;
734 /* be carefull - the space within settext is wanted - thats why the string twice */ 734 /* be carefull - the space within settext is wanted - thats why the string twice */
735 wrapper = AbstractMail::getWrapper( m_Path,"Local Folders"); 735 wrapper = AbstractMail::getWrapper( m_Path,"Local Folders");
736 setPixmap( 0, PIXMAP_LOCALFOLDER ); 736 setPixmap( 0, PIXMAP_LOCALFOLDER );
737 setText( 0, " Local Folders" ); 737 setText( 0, " Local Folders" );
738 setOpen( true ); 738 setOpen( true );
739 folder = 0; 739 folder = 0;
740} 740}
741 741
742MHviewItem::~MHviewItem() 742MHviewItem::~MHviewItem()
743{ 743{
744 delete wrapper; 744 delete wrapper;
745} 745}
746 746
747AbstractMail *MHviewItem::getWrapper() 747AbstractMail *MHviewItem::getWrapper()
748{ 748{
749 return wrapper; 749 return wrapper;
750} 750}
751 751
752void MHviewItem::refresh( QValueList<RecMailP> & target) 752void MHviewItem::refresh( QValueList<RecMailP> & target)
753{ 753{
754 refresh(false); 754 refresh(false);
755 getWrapper()->listMessages( "",target ); 755 getWrapper()->listMessages( "",target );
756} 756}
757 757
758void MHviewItem::refresh(bool force) 758void MHviewItem::refresh(bool force)
759{ 759{
760 if (childCount()>0 && force==false) return; 760 if (childCount()>0 && force==false) return;
761 removeChilds(); 761 removeChilds();
762 currentFolders.clear(); 762 currentFolders.clear();
763 QValueList<FolderP> *folders = wrapper->listFolders(); 763 QValueList<FolderP> *folders = wrapper->listFolders();
764 QValueList<FolderP>::ConstIterator it; 764 QValueList<FolderP>::ConstIterator it;
765 MHfolderItem*item = 0; 765 MHfolderItem*item = 0;
766 MHfolderItem*pmaster = 0; 766 MHfolderItem*pmaster = 0;
767 QString fname = ""; 767 QString fname = "";
768 int pos; 768 int pos;
769 for ( it = folders->begin(); it!=folders->end(); ++it) 769 for ( it = folders->begin(); it!=folders->end(); ++it)
770 { 770 {
771 fname = (*it)->getDisplayName(); 771 fname = (*it)->getDisplayName();
772 /* this folder itself */ 772 /* this folder itself */
773 if (fname=="/") 773 if (fname=="/")
774 { 774 {
775 currentFolders.append(fname); 775 currentFolders.append(fname);
776 folder = (*it); 776 folder = (*it);
777 continue; 777 continue;
778 } 778 }
779 currentFolders.append(fname); 779 currentFolders.append(fname);
780 pos = fname.findRev("/"); 780 pos = fname.findRev("/");
781 if (pos > 0) 781 if (pos > 0)
782 { 782 {
783 fname = fname.left(pos); 783 fname = fname.left(pos);
784 pmaster = (MHfolderItem*)findSubItem(fname); 784 pmaster = (MHfolderItem*)findSubItem(fname);
785 } 785 }
786 else 786 else
787 { 787 {
788 pmaster = 0; 788 pmaster = 0;
789 } 789 }
790 if (pmaster) 790 if (pmaster)
791 { 791 {
792 item = new MHfolderItem( (*it), pmaster, item, this ); 792 item = new MHfolderItem( (*it), pmaster, item, this );
793 } 793 }
794 else 794 else
795 { 795 {
796 item = new MHfolderItem( (*it), this , item ); 796 item = new MHfolderItem( (*it), this , item );
797 } 797 }
798 item->setSelectable((*it)->may_select()); 798 item->setSelectable((*it)->may_select());
799 } 799 }
800 delete folders; 800 delete folders;
801} 801}
802 802
803RECBODYP MHviewItem::fetchBody( const RecMailP &mail ) 803RECBODYP MHviewItem::fetchBody( const RecMailP &mail )
804{ 804{
805 qDebug( "MH fetchBody" ); 805 odebug << "MH fetchBody" << oendl;
806 return wrapper->fetchBody( mail ); 806 return wrapper->fetchBody( mail );
807} 807}
808 808
809QPopupMenu * MHviewItem::getContextMenu() 809QPopupMenu * MHviewItem::getContextMenu()
810{ 810{
811 QPopupMenu *m = new QPopupMenu(0); 811 QPopupMenu *m = new QPopupMenu(0);
812 if (m) 812 if (m)
813 { 813 {
814 m->insertItem(QObject::tr("Refresh folder list",contextName),0); 814 m->insertItem(QObject::tr("Refresh folder list",contextName),0);
815 m->insertItem(QObject::tr("Create new folder",contextName),1); 815 m->insertItem(QObject::tr("Create new folder",contextName),1);
816 m->insertItem(QObject::tr("Delete all mails",contextName),2); 816 m->insertItem(QObject::tr("Delete all mails",contextName),2);
817 m->insertItem(QObject::tr("Move/Copie all mails",contextName),3); 817 m->insertItem(QObject::tr("Move/Copie all mails",contextName),3);
818 } 818 }
819 return m; 819 return m;
820} 820}
821 821
822void MHviewItem::createFolder() 822void MHviewItem::createFolder()
823{ 823{
824 Newmdirdlg ndirdlg(0,0,true); 824 Newmdirdlg ndirdlg(0,0,true);
825 if ( QPEApplication::execDialog( &ndirdlg ) ) 825 if ( QPEApplication::execDialog( &ndirdlg ) )
826 { 826 {
827 QString ndir = ndirdlg.Newdir(); 827 QString ndir = ndirdlg.Newdir();
828 if (wrapper->createMbox(ndir)) 828 if (wrapper->createMbox(ndir))
829 { 829 {
830 refresh(true); 830 refresh(true);
831 } 831 }
832 } 832 }
833} 833}
834 834
835void MHviewItem::downloadMails() 835void MHviewItem::downloadMails()
836{ 836{
837 AccountView*bl = accountView(); 837 AccountView*bl = accountView();
838 if (!bl) return; 838 if (!bl) return;
839 bl->downloadMails(folder,getWrapper()); 839 bl->downloadMails(folder,getWrapper());
840} 840}
841 841
842QStringList MHviewItem::subFolders() 842QStringList MHviewItem::subFolders()
843{ 843{
844 return currentFolders; 844 return currentFolders;
845} 845}
846 846
847void MHviewItem::contextMenuSelected(int which) 847void MHviewItem::contextMenuSelected(int which)
848{ 848{
849 switch (which) 849 switch (which)
850 { 850 {
851 case 0: 851 case 0:
852 refresh(true); 852 refresh(true);
853 break; 853 break;
854 case 1: 854 case 1:
855 createFolder(); 855 createFolder();
856 break; 856 break;
857 case 2: 857 case 2:
858 deleteAllMail(getWrapper(),folder); 858 deleteAllMail(getWrapper(),folder);
859 break; 859 break;
860 case 3: 860 case 3:
861 downloadMails(); 861 downloadMails();
862 break; 862 break;
863 default: 863 default:
864 break; 864 break;
865 } 865 }
866} 866}
867 867
868MHfolderItem::~MHfolderItem() 868MHfolderItem::~MHfolderItem()
869{} 869{}
870 870
871MHfolderItem::MHfolderItem( const FolderP &folderInit, MHviewItem *parent , QListViewItem*after ) 871MHfolderItem::MHfolderItem( const FolderP &folderInit, MHviewItem *parent , QListViewItem*after )
872 : AccountViewItem(folderInit, parent,after ) 872 : AccountViewItem(folderInit, parent,after )
873{ 873{
874 mbox = parent; 874 mbox = parent;
875 initName(); 875 initName();
876} 876}
877 877
878MHfolderItem::MHfolderItem(const FolderP& folderInit, MHfolderItem *parent, QListViewItem*after, MHviewItem*master) 878MHfolderItem::MHfolderItem(const FolderP& folderInit, MHfolderItem *parent, QListViewItem*after, MHviewItem*master)
879 : AccountViewItem(folderInit, parent,after ) 879 : AccountViewItem(folderInit, parent,after )
880{ 880{
881 folder = folderInit; 881 folder = folderInit;
882 mbox = master; 882 mbox = master;
883 initName(); 883 initName();
884} 884}
885 885
886void MHfolderItem::initName() 886void MHfolderItem::initName()
887{ 887{
888 QString bName = folder->getDisplayName(); 888 QString bName = folder->getDisplayName();
889 if (bName.startsWith("/")&&bName.length()>1) 889 if (bName.startsWith("/")&&bName.length()>1)
890 { 890 {
891 bName.replace(0,1,""); 891 bName.replace(0,1,"");
892 } 892 }
893 int pos = bName.findRev("/"); 893 int pos = bName.findRev("/");
894 if (pos > 0) 894 if (pos > 0)
895 { 895 {
896 bName.replace(0,pos+1,""); 896 bName.replace(0,pos+1,"");
897 } 897 }
898 if (bName.lower() == "outgoing") 898 if (bName.lower() == "outgoing")
899 { 899 {
900 setPixmap( 0, PIXMAP_OUTBOXFOLDER ); 900 setPixmap( 0, PIXMAP_OUTBOXFOLDER );
901 } 901 }
902 else if (bName.lower() == "inbox") 902 else if (bName.lower() == "inbox")
903 { 903 {
904 setPixmap( 0, PIXMAP_INBOXFOLDER); 904 setPixmap( 0, PIXMAP_INBOXFOLDER);
905 } else if (bName.lower() == "drafts") { 905 } else if (bName.lower() == "drafts") {
906 setPixmap(0, Resource::loadPixmap("inline/edit")); 906 setPixmap(0, Resource::loadPixmap("inline/edit"));
907 } else { 907 } else {
908 setPixmap( 0, PIXMAP_MBOXFOLDER ); 908 setPixmap( 0, PIXMAP_MBOXFOLDER );
909 } 909 }
910 setText( 0, bName ); 910 setText( 0, bName );
911} 911}
912 912
913const FolderP&MHfolderItem::getFolder()const 913const FolderP&MHfolderItem::getFolder()const
914{ 914{
915 return folder; 915 return folder;
916} 916}
917 917
918void MHfolderItem::refresh(QValueList<RecMailP>&target) 918void MHfolderItem::refresh(QValueList<RecMailP>&target)
919{ 919{
920 if (folder->may_select()) 920 if (folder->may_select())
921 mbox->getWrapper()->listMessages( folder->getName(),target ); 921 mbox->getWrapper()->listMessages( folder->getName(),target );
922} 922}
923 923
924RECBODYP MHfolderItem::fetchBody(const RecMailP&aMail) 924RECBODYP MHfolderItem::fetchBody(const RecMailP&aMail)
925{ 925{
926 return mbox->getWrapper()->fetchBody(aMail); 926 return mbox->getWrapper()->fetchBody(aMail);
927} 927}
928 928
929void MHfolderItem::deleteFolder() 929void MHfolderItem::deleteFolder()
930{ 930{
931 int yesno = QMessageBox::warning(0,QObject::tr("Delete folder",contextName), 931 int yesno = QMessageBox::warning(0,QObject::tr("Delete folder",contextName),
932 QObject::tr("<center>Realy delete folder <br><b>%1</b><br>and all if it content?</center>",contextName).arg(folder->getDisplayName()), 932 QObject::tr("<center>Realy delete folder <br><b>%1</b><br>and all if it content?</center>",contextName).arg(folder->getDisplayName()),
933 QObject::tr("Yes",contextName), 933 QObject::tr("Yes",contextName),
934 QObject::tr("No",contextName),QString::null,1,1); 934 QObject::tr("No",contextName),QString::null,1,1);
935 qDebug("Auswahl: %i",yesno); 935 odebug << "Auswahl: " << yesno << "" << oendl;
936 if (yesno == 0) 936 if (yesno == 0)
937 { 937 {
938 if (mbox->getWrapper()->deleteMbox(folder)) 938 if (mbox->getWrapper()->deleteMbox(folder))
939 { 939 {
940 QListView*v=listView(); 940 QListView*v=listView();
941 MHviewItem * box = mbox; 941 MHviewItem * box = mbox;
942 /* be carefull - after that this object is destroyd so don't use 942 /* be carefull - after that this object is destroyd so don't use
943 * any member of it after that call!!*/ 943 * any member of it after that call!!*/
944 mbox->refresh(true); 944 mbox->refresh(true);
945 if (v) 945 if (v)
946 { 946 {
947 v->setSelected(box,true); 947 v->setSelected(box,true);
948 } 948 }
949 } 949 }
950 } 950 }
951} 951}
952 952
953QPopupMenu * MHfolderItem::getContextMenu() 953QPopupMenu * MHfolderItem::getContextMenu()
954{ 954{
955 QPopupMenu *m = new QPopupMenu(0); 955 QPopupMenu *m = new QPopupMenu(0);
956 if (m) 956 if (m)
957 { 957 {
958 m->insertItem(QObject::tr("Move/Copie all mails",contextName),2); 958 m->insertItem(QObject::tr("Move/Copie all mails",contextName),2);
959 m->insertItem(QObject::tr("Delete all mails",contextName),0); 959 m->insertItem(QObject::tr("Delete all mails",contextName),0);
960 m->insertItem(QObject::tr("Create new subfolder",contextName),3); 960 m->insertItem(QObject::tr("Create new subfolder",contextName),3);
961 m->insertItem(QObject::tr("Delete folder",contextName),1); 961 m->insertItem(QObject::tr("Delete folder",contextName),1);
962 } 962 }
963 return m; 963 return m;
964} 964}
965 965
966void MHfolderItem::downloadMails() 966void MHfolderItem::downloadMails()
967{ 967{
968 AccountView*bl = mbox->accountView(); 968 AccountView*bl = mbox->accountView();
969 if (!bl) return; 969 if (!bl) return;
970 bl->downloadMails(folder,mbox->getWrapper()); 970 bl->downloadMails(folder,mbox->getWrapper());
971} 971}
972 972
973void MHfolderItem::createFolder() 973void MHfolderItem::createFolder()
974{ 974{
975 Newmdirdlg ndirdlg(0,0,true); 975 Newmdirdlg ndirdlg(0,0,true);
976 if ( QPEApplication::execDialog( &ndirdlg ) ) 976 if ( QPEApplication::execDialog( &ndirdlg ) )
977 { 977 {
978 QString ndir = ndirdlg.Newdir(); 978 QString ndir = ndirdlg.Newdir();
979 if (mbox->getWrapper()->createMbox(ndir,folder)) 979 if (mbox->getWrapper()->createMbox(ndir,folder))
980 { 980 {
981 QListView*v=listView(); 981 QListView*v=listView();
982 MHviewItem * box = mbox; 982 MHviewItem * box = mbox;
983 /* be carefull - after that this object is destroyd so don't use 983 /* be carefull - after that this object is destroyd so don't use
984 * any member of it after that call!!*/ 984 * any member of it after that call!!*/
985 mbox->refresh(true); 985 mbox->refresh(true);
986 if (v) 986 if (v)
987 { 987 {
988 v->setSelected(box,true); 988 v->setSelected(box,true);
989 } 989 }
990 } 990 }
991 } 991 }
992} 992}
993 993
994void MHfolderItem::contextMenuSelected(int which) 994void MHfolderItem::contextMenuSelected(int which)
995{ 995{
996 switch(which) 996 switch(which)
997 { 997 {
998 case 0: 998 case 0:
999 deleteAllMail(mbox->getWrapper(),folder); 999 deleteAllMail(mbox->getWrapper(),folder);
1000 break; 1000 break;
1001 case 1: 1001 case 1:
1002 deleteFolder(); 1002 deleteFolder();
1003 break; 1003 break;
1004 case 2: 1004 case 2:
1005 downloadMails(); 1005 downloadMails();
1006 break; 1006 break;
1007 case 3: 1007 case 3:
1008 createFolder(); 1008 createFolder();
1009 break; 1009 break;
1010 default: 1010 default:
1011 break; 1011 break;
1012 } 1012 }
1013} 1013}
1014 1014
1015bool MHfolderItem::isDraftfolder() 1015bool MHfolderItem::isDraftfolder()
1016{ 1016{
1017 if (folder && folder->getName()==AbstractMail::defaultLocalfolder()+"/"+AbstractMail::draftFolder()) return true; 1017 if (folder && folder->getName()==AbstractMail::defaultLocalfolder()+"/"+AbstractMail::draftFolder()) return true;
1018 return false; 1018 return false;
1019} 1019}
1020 1020
1021/** 1021/**
1022 * Generic stuff 1022 * Generic stuff
1023 */ 1023 */
1024 1024
1025const QString AccountViewItem::contextName="AccountViewItem"; 1025const QString AccountViewItem::contextName="AccountViewItem";
1026 1026
1027AccountViewItem::AccountViewItem( AccountView *parent ) 1027AccountViewItem::AccountViewItem( AccountView *parent )
1028 : QListViewItem( parent ) 1028 : QListViewItem( parent )
1029{ 1029{
1030 init(); 1030 init();
1031 m_Backlink = parent; 1031 m_Backlink = parent;
1032} 1032}
1033 1033
1034AccountViewItem::AccountViewItem( QListViewItem *parent) 1034AccountViewItem::AccountViewItem( QListViewItem *parent)
1035 : QListViewItem( parent),folder(0) 1035 : QListViewItem( parent),folder(0)
1036{ 1036{
1037 init(); 1037 init();
1038} 1038}
1039 1039
1040AccountViewItem::AccountViewItem( QListViewItem *parent , QListViewItem*after ) 1040AccountViewItem::AccountViewItem( QListViewItem *parent , QListViewItem*after )
1041 :QListViewItem( parent,after ),folder(0) 1041 :QListViewItem( parent,after ),folder(0)
1042{ 1042{
1043 init(); 1043 init();
1044} 1044}
1045 1045
1046AccountViewItem::AccountViewItem( const Opie::Core::OSmartPointer<Folder>&folderInit,QListViewItem *parent , QListViewItem*after ) 1046AccountViewItem::AccountViewItem( const Opie::Core::OSmartPointer<Folder>&folderInit,QListViewItem *parent , QListViewItem*after )
1047 :QListViewItem( parent,after ),folder(folderInit) 1047 :QListViewItem( parent,after ),folder(folderInit)
1048{ 1048{
1049 init(); 1049 init();
1050} 1050}
1051 1051
1052void AccountViewItem::init() 1052void AccountViewItem::init()
1053{ 1053{
1054 m_Backlink = 0; 1054 m_Backlink = 0;
1055} 1055}
1056 1056
1057AccountViewItem::~AccountViewItem() 1057AccountViewItem::~AccountViewItem()
1058{ 1058{
1059 folder = 0; 1059 folder = 0;
1060} 1060}
1061 1061
1062AccountView*AccountViewItem::accountView() 1062AccountView*AccountViewItem::accountView()
1063{ 1063{
1064 return m_Backlink; 1064 return m_Backlink;
1065} 1065}
1066 1066
1067void AccountViewItem::deleteAllMail(AbstractMail*wrapper,const FolderP&folder) 1067void AccountViewItem::deleteAllMail(AbstractMail*wrapper,const FolderP&folder)
1068{ 1068{
1069 if (!wrapper) return; 1069 if (!wrapper) return;
1070 QString fname=""; 1070 QString fname="";
1071 if (folder) fname = folder->getDisplayName(); 1071 if (folder) fname = folder->getDisplayName();
1072 int yesno = QMessageBox::warning(0,QObject::tr("Delete all mails",contextName), 1072 int yesno = QMessageBox::warning(0,QObject::tr("Delete all mails",contextName),
1073 QObject::tr("<center>Realy delete all mails in box <br>%1</center>",contextName). 1073 QObject::tr("<center>Realy delete all mails in box <br>%1</center>",contextName).
1074 arg(fname), 1074 arg(fname),
1075 QObject::tr("Yes",contextName), 1075 QObject::tr("Yes",contextName),
1076 QObject::tr("No",contextName),QString::null,1,1); 1076 QObject::tr("No",contextName),QString::null,1,1);
1077 qDebug("Auswahl: %i",yesno); 1077 odebug << "Auswahl: " << yesno << "" << oendl;
1078 if (yesno == 0) 1078 if (yesno == 0)
1079 { 1079 {
1080 if (wrapper->deleteAllMail(folder)) 1080 if (wrapper->deleteAllMail(folder))
1081 { 1081 {
1082 AccountView * view = (AccountView*)listView(); 1082 AccountView * view = (AccountView*)listView();
1083 if (view) view->refreshCurrent(); 1083 if (view) view->refreshCurrent();
1084 } 1084 }
1085 } 1085 }
1086} 1086}
1087 1087
1088void AccountViewItem::removeChilds() 1088void AccountViewItem::removeChilds()
1089{ 1089{
1090 QListViewItem *child = firstChild(); 1090 QListViewItem *child = firstChild();
1091 while ( child ) 1091 while ( child )
1092 { 1092 {
1093 QListViewItem *tmp = child; 1093 QListViewItem *tmp = child;
1094 child = child->nextSibling(); 1094 child = child->nextSibling();
1095 delete tmp; 1095 delete tmp;
1096 } 1096 }
1097} 1097}
1098 1098
1099bool AccountViewItem::matchName(const QString&name)const 1099bool AccountViewItem::matchName(const QString&name)const
1100{ 1100{
1101 if (!folder) return false; 1101 if (!folder) return false;
1102 return folder->getDisplayName()==name; 1102 return folder->getDisplayName()==name;
1103} 1103}
1104 1104
1105 1105
1106AccountViewItem*AccountViewItem::findSubItem(const QString&path,AccountViewItem*start) 1106AccountViewItem*AccountViewItem::findSubItem(const QString&path,AccountViewItem*start)
1107{ 1107{
1108 AccountViewItem*pitem,*sitem; 1108 AccountViewItem*pitem,*sitem;
1109 if (!start) pitem = (AccountViewItem*)firstChild(); 1109 if (!start) pitem = (AccountViewItem*)firstChild();
1110 else pitem = (AccountViewItem*)start->firstChild(); 1110 else pitem = (AccountViewItem*)start->firstChild();
1111 while (pitem) 1111 while (pitem)
1112 { 1112 {
1113 if (pitem->matchName(path)) 1113 if (pitem->matchName(path))
1114 { 1114 {
1115 break; 1115 break;
1116 } 1116 }
1117 if (pitem->childCount()>0) 1117 if (pitem->childCount()>0)
1118 { 1118 {
1119 sitem = findSubItem(path,pitem); 1119 sitem = findSubItem(path,pitem);
1120 if (sitem) 1120 if (sitem)
1121 { 1121 {
1122 pitem = sitem; 1122 pitem = sitem;
1123 break; 1123 break;
1124 } 1124 }
1125 } 1125 }
1126 pitem=(AccountViewItem*)pitem->nextSibling(); 1126 pitem=(AccountViewItem*)pitem->nextSibling();
1127 } 1127 }
1128 return pitem; 1128 return pitem;
1129} 1129}
1130 1130
1131bool AccountViewItem::isDraftfolder() 1131bool AccountViewItem::isDraftfolder()
1132{ 1132{
1133 return false; 1133 return false;
1134} 1134}
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 @@
1 1
2#include "accountview.h" 2#include "accountview.h"
3#include "accountitem.h" 3#include "accountitem.h"
4#include "selectstore.h" 4#include "selectstore.h"
5 5
6/* OPIE */ 6/* OPIE */
7#include <libmailwrapper/settings.h> 7#include <libmailwrapper/settings.h>
8#include <libmailwrapper/mailwrapper.h> 8#include <libmailwrapper/mailwrapper.h>
9#include <libmailwrapper/mailtypes.h> 9#include <libmailwrapper/mailtypes.h>
10#include <libmailwrapper/abstractmail.h> 10#include <libmailwrapper/abstractmail.h>
11#include <qpe/qpeapplication.h> 11#include <qpe/qpeapplication.h>
12 12
13/* QT */ 13/* QT */
14#include <qmessagebox.h> 14#include <qmessagebox.h>
15#include <qpopupmenu.h> 15#include <qpopupmenu.h>
16 16
17using namespace Opie::Core; 17using namespace Opie::Core;
18AccountView::AccountView( QWidget *parent, const char *name, WFlags flags ) 18AccountView::AccountView( QWidget *parent, const char *name, WFlags flags )
19 : QListView( parent, name, flags ) 19 : QListView( parent, name, flags )
20{ 20{
21 connect( this, SIGNAL( selectionChanged(QListViewItem*) ), 21 connect( this, SIGNAL( selectionChanged(QListViewItem*) ),
22 SLOT( refresh(QListViewItem*) ) ); 22 SLOT( refresh(QListViewItem*) ) );
23 connect( this, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),this, 23 connect( this, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),this,
24 SLOT( slotHold(int,QListViewItem*,const QPoint&,int) ) ); 24 SLOT( slotHold(int,QListViewItem*,const QPoint&,int) ) );
25 setSorting(0); 25 setSorting(0);
26} 26}
27 27
28AccountView::~AccountView() 28AccountView::~AccountView()
29{ 29{
30 imapAccounts.clear(); 30 imapAccounts.clear();
31 mhAccounts.clear(); 31 mhAccounts.clear();
32} 32}
33 33
34void AccountView::slotContextMenu(int id) 34void AccountView::slotContextMenu(int id)
35{ 35{
36 AccountViewItem *view = static_cast<AccountViewItem *>(currentItem()); 36 AccountViewItem *view = static_cast<AccountViewItem *>(currentItem());
37 if (!view) return; 37 if (!view) return;
38 view->contextMenuSelected(id); 38 view->contextMenuSelected(id);
39} 39}
40 40
41void AccountView::slotHold(int button, QListViewItem * item,const QPoint&,int) 41void AccountView::slotHold(int button, QListViewItem * item,const QPoint&,int)
42{ 42{
43 if (button==1) {return;} 43 if (button==1) {return;}
44 if (!item) return; 44 if (!item) return;
45 AccountViewItem *view = static_cast<AccountViewItem *>(item); 45 AccountViewItem *view = static_cast<AccountViewItem *>(item);
46 QPopupMenu*m = view->getContextMenu(); 46 QPopupMenu*m = view->getContextMenu();
47 if (!m) return; 47 if (!m) return;
48 connect(m,SIGNAL(activated(int)),this,SLOT(slotContextMenu(int))); 48 connect(m,SIGNAL(activated(int)),this,SLOT(slotContextMenu(int)));
49 m->setFocus(); 49 m->setFocus();
50 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) ); 50 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) );
51 delete m; 51 delete m;
52} 52}
53 53
54void AccountView::populate( QList<Account> list ) 54void AccountView::populate( QList<Account> list )
55{ 55{
56 clear(); 56 clear();
57 57
58 imapAccounts.clear(); 58 imapAccounts.clear();
59 mhAccounts.clear(); 59 mhAccounts.clear();
60 60
61 mhAccounts.append(new MHviewItem(AbstractMail::defaultLocalfolder(),this)); 61 mhAccounts.append(new MHviewItem(AbstractMail::defaultLocalfolder(),this));
62 62
63 Account *it; 63 Account *it;
64 for ( it = list.first(); it; it = list.next() ) 64 for ( it = list.first(); it; it = list.next() )
65 { 65 {
66 if ( it->getType() == MAILLIB::A_IMAP ) 66 if ( it->getType() == MAILLIB::A_IMAP )
67 { 67 {
68 IMAPaccount *imap = static_cast<IMAPaccount *>(it); 68 IMAPaccount *imap = static_cast<IMAPaccount *>(it);
69 qDebug( "added IMAP " + imap->getAccountName() ); 69 odebug << "added IMAP " + imap->getAccountName() << oendl;
70 imapAccounts.append(new IMAPviewItem( imap, this )); 70 imapAccounts.append(new IMAPviewItem( imap, this ));
71 } 71 }
72 else if ( it->getType() == MAILLIB::A_POP3 ) 72 else if ( it->getType() == MAILLIB::A_POP3 )
73 { 73 {
74 POP3account *pop3 = static_cast<POP3account *>(it); 74 POP3account *pop3 = static_cast<POP3account *>(it);
75 qDebug( "added POP3 " + pop3->getAccountName() ); 75 odebug << "added POP3 " + pop3->getAccountName() << oendl;
76 /* must not be hold 'cause it isn't required */ 76 /* must not be hold 'cause it isn't required */
77 (void) new POP3viewItem( pop3, this ); 77 (void) new POP3viewItem( pop3, this );
78 } 78 }
79 else if ( it->getType() == MAILLIB::A_NNTP ) 79 else if ( it->getType() == MAILLIB::A_NNTP )
80 { 80 {
81 NNTPaccount *nntp = static_cast<NNTPaccount *>(it); 81 NNTPaccount *nntp = static_cast<NNTPaccount *>(it);
82 qDebug( "added NNTP " + nntp->getAccountName() ); 82 odebug << "added NNTP " + nntp->getAccountName() << oendl;
83 /* must not be hold 'cause it isn't required */ 83 /* must not be hold 'cause it isn't required */
84 (void) new NNTPviewItem( nntp, this ); 84 (void) new NNTPviewItem( nntp, this );
85 } 85 }
86 } 86 }
87} 87}
88 88
89void AccountView::refresh(QListViewItem *item) 89void AccountView::refresh(QListViewItem *item)
90{ 90{
91 91
92 qDebug("AccountView refresh..."); 92 odebug << "AccountView refresh..." << oendl;
93 if ( item ) 93 if ( item )
94 { 94 {
95 m_currentItem = item; 95 m_currentItem = item;
96 QValueList<RecMailP> headerlist; 96 QValueList<RecMailP> headerlist;
97 AccountViewItem *view = static_cast<AccountViewItem *>(item); 97 AccountViewItem *view = static_cast<AccountViewItem *>(item);
98 view->refresh(headerlist); 98 view->refresh(headerlist);
99 emit refreshMailview(headerlist); 99 emit refreshMailview(headerlist);
100 } 100 }
101} 101}
102 102
103void AccountView::refreshCurrent() 103void AccountView::refreshCurrent()
104{ 104{
105 m_currentItem = currentItem(); 105 m_currentItem = currentItem();
106 if ( !m_currentItem ) return; 106 if ( !m_currentItem ) return;
107 QValueList<RecMailP> headerlist; 107 QValueList<RecMailP> headerlist;
108 AccountViewItem *view = static_cast<AccountViewItem *>(m_currentItem); 108 AccountViewItem *view = static_cast<AccountViewItem *>(m_currentItem);
109 view->refresh(headerlist); 109 view->refresh(headerlist);
110 emit refreshMailview(headerlist); 110 emit refreshMailview(headerlist);
111} 111}
112 112
113void AccountView::refreshAll() 113void AccountView::refreshAll()
114{ 114{
115} 115}
116 116
117RecBodyP AccountView::fetchBody(const RecMailP&aMail) 117RecBodyP AccountView::fetchBody(const RecMailP&aMail)
118{ 118{
119 QListViewItem*item = selectedItem (); 119 QListViewItem*item = selectedItem ();
120 if (!item) return new RecBody(); 120 if (!item) return new RecBody();
121 AccountViewItem *view = static_cast<AccountViewItem *>(item); 121 AccountViewItem *view = static_cast<AccountViewItem *>(item);
122 return view->fetchBody(aMail); 122 return view->fetchBody(aMail);
123} 123}
124 124
125void AccountView::setupFolderselect(Selectstore*sels) 125void AccountView::setupFolderselect(Selectstore*sels)
126{ 126{
127 QPEApplication::showDialog( sels ); 127 QPEApplication::showDialog( sels );
128 QStringList sFolders; 128 QStringList sFolders;
129 unsigned int i = 0; 129 unsigned int i = 0;
130 for (i=0; i < mhAccounts.count();++i) 130 for (i=0; i < mhAccounts.count();++i)
131 { 131 {
132 mhAccounts[i]->refresh(false); 132 mhAccounts[i]->refresh(false);
133 sFolders = mhAccounts[i]->subFolders(); 133 sFolders = mhAccounts[i]->subFolders();
134 sels->addAccounts(mhAccounts[i]->getWrapper(),sFolders); 134 sels->addAccounts(mhAccounts[i]->getWrapper(),sFolders);
135 } 135 }
136 for (i=0; i < imapAccounts.count();++i) 136 for (i=0; i < imapAccounts.count();++i)
137 { 137 {
138 if (imapAccounts[i]->offline()) 138 if (imapAccounts[i]->offline())
139 continue; 139 continue;
140 imapAccounts[i]->refreshFolders(false); 140 imapAccounts[i]->refreshFolders(false);
141 sels->addAccounts(imapAccounts[i]->getWrapper(),imapAccounts[i]->subFolders()); 141 sels->addAccounts(imapAccounts[i]->getWrapper(),imapAccounts[i]->subFolders());
142 } 142 }
143} 143}
144 144
145void AccountView::downloadMails(const FolderP&fromFolder,AbstractMail*fromWrapper) 145void AccountView::downloadMails(const FolderP&fromFolder,AbstractMail*fromWrapper)
146{ 146{
147 AbstractMail*targetMail = 0; 147 AbstractMail*targetMail = 0;
148 QString targetFolder = ""; 148 QString targetFolder = "";
149 Selectstore sels; 149 Selectstore sels;
150 setupFolderselect(&sels); 150 setupFolderselect(&sels);
151 if (!sels.exec()) return; 151 if (!sels.exec()) return;
152 targetMail = sels.currentMail(); 152 targetMail = sels.currentMail();
153 targetFolder = sels.currentFolder(); 153 targetFolder = sels.currentFolder();
154 if ( (fromWrapper==targetMail && fromFolder->getName()==targetFolder) || 154 if ( (fromWrapper==targetMail && fromFolder->getName()==targetFolder) ||
155 targetFolder.isEmpty()) 155 targetFolder.isEmpty())
156 { 156 {
157 return; 157 return;
158 } 158 }
159 if (sels.newFolder() && !targetMail->createMbox(targetFolder)) 159 if (sels.newFolder() && !targetMail->createMbox(targetFolder))
160 { 160 {
161 QMessageBox::critical(0,tr("Error creating new Folder"), 161 QMessageBox::critical(0,tr("Error creating new Folder"),
162 tr("<center>Error while creating<br>new folder - breaking.</center>")); 162 tr("<center>Error while creating<br>new folder - breaking.</center>"));
163 return; 163 return;
164 } 164 }
165 qDebug("Targetfolder: %s",targetFolder.latin1()); 165 odebug << "Targetfolder: " << targetFolder.latin1() << "" << oendl;
166 qDebug("Fromfolder: %s",fromFolder->getName().latin1()); 166 odebug << "Fromfolder: " << fromFolder->getName().latin1() << "" << oendl;
167 fromWrapper->mvcpAllMails(fromFolder,targetFolder,targetMail,sels.moveMails()); 167 fromWrapper->mvcpAllMails(fromFolder,targetFolder,targetMail,sels.moveMails());
168 refreshCurrent(); 168 refreshCurrent();
169} 169}
170 170
171bool AccountView::currentisDraft() 171bool AccountView::currentisDraft()
172{ 172{
173 AccountViewItem *view = static_cast<AccountViewItem *>(currentItem()); 173 AccountViewItem *view = static_cast<AccountViewItem *>(currentItem());
174 if (!view) return false; 174 if (!view) return false;
175 return view->isDraftfolder(); 175 return view->isDraftfolder();
176} 176}
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 )
90 90
91void ComposeMail::setTo( const QString & to ) 91void ComposeMail::setTo( const QString & to )
92{ 92{
93 toLine->setText( to ); 93 toLine->setText( to );
94} 94}
95 95
96void ComposeMail::setSubject( const QString & subject ) 96void ComposeMail::setSubject( const QString & subject )
97{ 97{
98 subjectLine->setText( subject ); 98 subjectLine->setText( subject );
99} 99}
100 100
101void ComposeMail::setInReplyTo( const QString & messageId ) 101void ComposeMail::setInReplyTo( const QString & messageId )
102{ 102{
103 m_replyid = messageId; 103 m_replyid = messageId;
104} 104}
105 105
106void ComposeMail::setMessage( const QString & text ) 106void ComposeMail::setMessage( const QString & text )
107{ 107{
108 message->setText( text ); 108 message->setText( text );
109} 109}
110 110
111 111
112void ComposeMail::pickAddressTo() 112void ComposeMail::pickAddressTo()
113{ 113{
114 pickAddress( toLine ); 114 pickAddress( toLine );
115} 115}
116 116
117void ComposeMail::pickAddressCC() 117void ComposeMail::pickAddressCC()
118{ 118{
119 pickAddress( ccLine ); 119 pickAddress( ccLine );
120} 120}
121 121
122void ComposeMail::pickAddressBCC() 122void ComposeMail::pickAddressBCC()
123{ 123{
124 pickAddress( bccLine ); 124 pickAddress( bccLine );
125} 125}
126 126
127void ComposeMail::pickAddressReply() 127void ComposeMail::pickAddressReply()
128{ 128{
129 pickAddress( replyLine ); 129 pickAddress( replyLine );
130} 130}
131 131
132void ComposeMail::fillValues( int ) 132void ComposeMail::fillValues( int )
133{ 133{
134#if 0 134#if 0
135 SMTPaccount *smtp = smtpAccounts.at( current ); 135 SMTPaccount *smtp = smtpAccounts.at( current );
136 ccLine->clear(); 136 ccLine->clear();
137 if ( smtp->getUseCC() ) { 137 if ( smtp->getUseCC() ) {
138 ccLine->setText( smtp->getCC() ); 138 ccLine->setText( smtp->getCC() );
139 } 139 }
140 bccLine->clear(); 140 bccLine->clear();
141 if ( smtp->getUseBCC() ) { 141 if ( smtp->getUseBCC() ) {
142 bccLine->setText( smtp->getBCC() ); 142 bccLine->setText( smtp->getBCC() );
143 } 143 }
144 replyLine->clear(); 144 replyLine->clear();
145 if ( smtp->getUseReply() ) { 145 if ( smtp->getUseReply() ) {
146 replyLine->setText( smtp->getReply() ); 146 replyLine->setText( smtp->getReply() );
147 } 147 }
148 sigMultiLine->setText( smtp->getSignature() ); 148 sigMultiLine->setText( smtp->getSignature() );
149#endif 149#endif
150} 150}
151 151
152void ComposeMail::slotAdjustColumns() 152void ComposeMail::slotAdjustColumns()
153{ 153{
154 int currPage = tabWidget->currentPageIndex(); 154 int currPage = tabWidget->currentPageIndex();
155 155
156 tabWidget->showPage( attachTab ); 156 tabWidget->showPage( attachTab );
157 attList->setColumnWidth( 0, attList->visibleWidth() - 80 ); 157 attList->setColumnWidth( 0, attList->visibleWidth() - 80 );
158 attList->setColumnWidth( 1, 80 ); 158 attList->setColumnWidth( 1, 80 );
159 159
160 tabWidget->setCurrentPage( currPage ); 160 tabWidget->setCurrentPage( currPage );
161} 161}
162 162
163void ComposeMail::addAttachment() 163void ComposeMail::addAttachment()
164{ 164{
165 DocLnk lnk = OFileDialog::getOpenFileName( 1, "/" ); 165 DocLnk lnk = OFileDialog::getOpenFileName( 1, "/" );
166 if ( !lnk.name().isEmpty() ) { 166 if ( !lnk.name().isEmpty() ) {
167 Attachment *att = new Attachment( lnk ); 167 Attachment *att = new Attachment( lnk );
168 (void) new AttachViewItem( attList, att ); 168 (void) new AttachViewItem( attList, att );
169 } 169 }
170} 170}
171 171
172void ComposeMail::removeAttachment() 172void ComposeMail::removeAttachment()
173{ 173{
174 if ( !attList->currentItem() ) { 174 if ( !attList->currentItem() ) {
175 QMessageBox::information( this, tr( "Error" ), 175 QMessageBox::information( this, tr( "Error" ),
176 tr( "<p>Please select a File.</p>" ), 176 tr( "<p>Please select a File.</p>" ),
177 tr( "Ok" ) ); 177 tr( "Ok" ) );
178 } else { 178 } else {
179 attList->takeItem( attList->currentItem() ); 179 attList->takeItem( attList->currentItem() );
180 } 180 }
181} 181}
182 182
183void ComposeMail::accept() 183void ComposeMail::accept()
184{ 184{
185 if ( checkBoxLater->isChecked() ) { 185 if ( checkBoxLater->isChecked() ) {
186 qDebug( "Send later" ); 186 odebug << "Send later" << oendl;
187 } 187 }
188 188
189#if 0 189#if 0
190 qDebug( "Sending Mail with " + 190 qDebug( "Sending Mail with " +
191 smtpAccounts.at( smtpAccountBox->currentItem() )->getAccountName() ); 191 smtpAccounts.at( smtpAccountBox->currentItem() )->getAccountName() );
192#endif 192#endif
193 Opie::Core::OSmartPointer<Mail> mail=new Mail; 193 Opie::Core::OSmartPointer<Mail> mail=new Mail;
194 194
195 SMTPaccount *smtp = smtpAccounts.at( smtpAccountBox->currentItem() ); 195 SMTPaccount *smtp = smtpAccounts.at( smtpAccountBox->currentItem() );
196 mail->setMail(fromBox->currentText()); 196 mail->setMail(fromBox->currentText());
197 197
198 if ( !toLine->text().isEmpty() ) { 198 if ( !toLine->text().isEmpty() ) {
199 mail->setTo( toLine->text() ); 199 mail->setTo( toLine->text() );
200 } else { 200 } else {
201 QMessageBox::warning(0,tr("Sending mail"), 201 QMessageBox::warning(0,tr("Sending mail"),
202 tr("No Receiver spezified" ) ); 202 tr("No Receiver spezified" ) );
203 return; 203 return;
204 } 204 }
205 mail->setName(senderNameEdit->text()); 205 mail->setName(senderNameEdit->text());
206 mail->setCC( ccLine->text() ); 206 mail->setCC( ccLine->text() );
207 mail->setBCC( bccLine->text() ); 207 mail->setBCC( bccLine->text() );
208 mail->setReply( replyLine->text() ); 208 mail->setReply( replyLine->text() );
209 mail->setSubject( subjectLine->text() ); 209 mail->setSubject( subjectLine->text() );
210 if (!m_replyid.isEmpty()) { 210 if (!m_replyid.isEmpty()) {
211 QStringList ids; 211 QStringList ids;
212 ids.append(m_replyid); 212 ids.append(m_replyid);
213 mail->setInreply(ids); 213 mail->setInreply(ids);
214 } 214 }
215 QString txt = message->text(); 215 QString txt = message->text();
216 if ( !sigMultiLine->text().isEmpty() ) { 216 if ( !sigMultiLine->text().isEmpty() ) {
217 txt.append( "\n--\n" ); 217 txt.append( "\n--\n" );
218 txt.append( sigMultiLine->text() ); 218 txt.append( sigMultiLine->text() );
219 } 219 }
220 mail->setMessage( txt ); 220 mail->setMessage( txt );
221 AttachViewItem *it = (AttachViewItem *) attList->firstChild(); 221 AttachViewItem *it = (AttachViewItem *) attList->firstChild();
222 while ( it != NULL ) { 222 while ( it != NULL ) {
223 mail->addAttachment( it->getAttachment() ); 223 mail->addAttachment( it->getAttachment() );
224 it = (AttachViewItem *) it->nextSibling(); 224 it = (AttachViewItem *) it->nextSibling();
225 } 225 }
226 226
227 SMTPwrapper wrapper( smtp ); 227 SMTPwrapper wrapper( smtp );
228 wrapper.sendMail( mail,checkBoxLater->isChecked() ); 228 wrapper.sendMail( mail,checkBoxLater->isChecked() );
229 229
230 QDialog::accept(); 230 QDialog::accept();
231} 231}
232 232
233void ComposeMail::reject() 233void ComposeMail::reject()
234{ 234{
235 int yesno = QMessageBox::warning(0,tr("Store message"), 235 int yesno = QMessageBox::warning(0,tr("Store message"),
236 tr("Store message into drafts?"), 236 tr("Store message into drafts?"),
237 tr("Yes"), 237 tr("Yes"),
238 tr("No"),QString::null,0,1); 238 tr("No"),QString::null,0,1);
239 239
240 if (yesno == 0) { 240 if (yesno == 0) {
241 Opie::Core::OSmartPointer<Mail> mail=new Mail(); 241 Opie::Core::OSmartPointer<Mail> mail=new Mail();
242 mail->setMail(fromBox->currentText()); 242 mail->setMail(fromBox->currentText());
243 mail->setTo( toLine->text() ); 243 mail->setTo( toLine->text() );
244 mail->setName(senderNameEdit->text()); 244 mail->setName(senderNameEdit->text());
245 mail->setCC( ccLine->text() ); 245 mail->setCC( ccLine->text() );
246 mail->setBCC( bccLine->text() ); 246 mail->setBCC( bccLine->text() );
247 mail->setReply( replyLine->text() ); 247 mail->setReply( replyLine->text() );
248 mail->setSubject( subjectLine->text() ); 248 mail->setSubject( subjectLine->text() );
249 if (!m_replyid.isEmpty()) { 249 if (!m_replyid.isEmpty()) {
250 QStringList ids; 250 QStringList ids;
251 ids.append(m_replyid); 251 ids.append(m_replyid);
252 mail->setInreply(ids); 252 mail->setInreply(ids);
253 } 253 }
254 QString txt = message->text(); 254 QString txt = message->text();
255 if ( !sigMultiLine->text().isEmpty() ) { 255 if ( !sigMultiLine->text().isEmpty() ) {
256 txt.append( "\n--\n" ); 256 txt.append( "\n--\n" );
257 txt.append( sigMultiLine->text() ); 257 txt.append( sigMultiLine->text() );
258 } 258 }
259 qDebug(txt); 259 odebug << txt << oendl;
260 mail->setMessage( txt ); 260 mail->setMessage( txt );
261 261
262 /* only use the default drafts folder name! */ 262 /* only use the default drafts folder name! */
263 Storemail wrapper(AbstractMail::draftFolder()); 263 Storemail wrapper(AbstractMail::draftFolder());
264 wrapper.storeMail(mail); 264 wrapper.storeMail(mail);
265 265
266 AttachViewItem *it = (AttachViewItem *) attList->firstChild(); 266 AttachViewItem *it = (AttachViewItem *) attList->firstChild();
267 /* attachments we will ignore! */ 267 /* attachments we will ignore! */
268 if ( it != NULL ) { 268 if ( it != NULL ) {
269 QMessageBox::warning(0,tr("Store message"), 269 QMessageBox::warning(0,tr("Store message"),
270 tr("<center>Attachments will not be stored in \"Draft\" folder</center>")); 270 tr("<center>Attachments will not be stored in \"Draft\" folder</center>"));
271 } 271 }
272 } 272 }
273 QDialog::reject(); 273 QDialog::reject();
274} 274}
275 275
276ComposeMail::~ComposeMail() 276ComposeMail::~ComposeMail()
277{ 277{
278} 278}
279 279
280void ComposeMail::reEditMail(const RecMailP&current) 280void ComposeMail::reEditMail(const RecMailP&current)
281{ 281{
282 RecMailP data = current; 282 RecMailP data = current;
283 message->setText(data->Wrapper()->fetchBody(current)->Bodytext()); 283 message->setText(data->Wrapper()->fetchBody(current)->Bodytext());
284 subjectLine->setText( data->getSubject()); 284 subjectLine->setText( data->getSubject());
285 toLine->setText(data->To().join(",")); 285 toLine->setText(data->To().join(","));
286 ccLine->setText(data->CC().join(",")); 286 ccLine->setText(data->CC().join(","));
287 bccLine->setText(data->Bcc().join(",")); 287 bccLine->setText(data->Bcc().join(","));
288 replyLine->setText(data->Replyto()); 288 replyLine->setText(data->Replyto());
289} 289}
290 290
291AttachViewItem::AttachViewItem( QListView *parent, Attachment *att ) 291AttachViewItem::AttachViewItem( QListView *parent, Attachment *att )
292 : QListViewItem( parent ) 292 : QListViewItem( parent )
293{ 293{
294 attachment = att; 294 attachment = att;
295 qDebug( att->getMimeType() ); 295 odebug << att->getMimeType() << oendl;
296 setPixmap( 0, attachment->getDocLnk().pixmap().isNull() ? 296 setPixmap( 0, attachment->getDocLnk().pixmap().isNull() ?
297 Resource::loadPixmap( "UnknownDocument-14" ) : 297 Resource::loadPixmap( "UnknownDocument-14" ) :
298 attachment->getDocLnk().pixmap() ); 298 attachment->getDocLnk().pixmap() );
299 setText( 0, att->getName().isEmpty() ? att->getFileName() : att->getName() ); 299 setText( 0, att->getName().isEmpty() ? att->getFileName() : att->getName() );
300 setText( 1, QString::number( att->getSize() ) ); 300 setText( 1, QString::number( att->getSize() ) );
301} 301}
302 302
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 @@
1 1
2#include "defines.h" 2#include "defines.h"
3#include "editaccounts.h" 3#include "editaccounts.h"
4 4
5/* OPIE */ 5/* OPIE */
6#include <qpe/qpeapplication.h> 6#include <qpe/qpeapplication.h>
7 7
8/* QT */ 8/* QT */
9#include <qt.h> 9#include <qt.h>
10#include <qstringlist.h> 10#include <qstringlist.h>
11 11
12#include <libmailwrapper/nntpwrapper.h> 12#include <libmailwrapper/nntpwrapper.h>
13 13
14AccountListItem::AccountListItem( QListView *parent, Account *a) 14AccountListItem::AccountListItem( QListView *parent, Account *a)
15 : QListViewItem( parent ) 15 : QListViewItem( parent )
16{ 16{
17 account = a; 17 account = a;
18 setText( 0, account->getAccountName() ); 18 setText( 0, account->getAccountName() );
19 QString ttext = ""; 19 QString ttext = "";
20 switch (account->getType()) { 20 switch (account->getType()) {
21 case MAILLIB::A_NNTP: 21 case MAILLIB::A_NNTP:
22 ttext="NNTP"; 22 ttext="NNTP";
23 break; 23 break;
24 case MAILLIB::A_POP3: 24 case MAILLIB::A_POP3:
25 ttext = "POP3"; 25 ttext = "POP3";
26 break; 26 break;
27 case MAILLIB::A_IMAP: 27 case MAILLIB::A_IMAP:
28 ttext = "IMAP"; 28 ttext = "IMAP";
29 break; 29 break;
30 case MAILLIB::A_SMTP: 30 case MAILLIB::A_SMTP:
31 ttext = "SMTP"; 31 ttext = "SMTP";
32 break; 32 break;
33 default: 33 default:
34 ttext = "UNKNOWN"; 34 ttext = "UNKNOWN";
35 break; 35 break;
36 } 36 }
37 setText( 1, ttext); 37 setText( 1, ttext);
38} 38}
39 39
40EditAccounts::EditAccounts( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags ) 40EditAccounts::EditAccounts( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags )
41 : EditAccountsUI( parent, name, modal, flags ) 41 : EditAccountsUI( parent, name, modal, flags )
42{ 42{
43 qDebug( "New Account Configuration Widget" ); 43 odebug << "New Account Configuration Widget" << oendl;
44 settings = s; 44 settings = s;
45 45
46 mailList->addColumn( tr( "Account" ) ); 46 mailList->addColumn( tr( "Account" ) );
47 mailList->addColumn( tr( "Type" ) ); 47 mailList->addColumn( tr( "Type" ) );
48 48
49 newsList->addColumn( tr( "Account" ) ); 49 newsList->addColumn( tr( "Account" ) );
50 50
51 connect( newMail, SIGNAL( clicked() ), SLOT( slotNewMail() ) ); 51 connect( newMail, SIGNAL( clicked() ), SLOT( slotNewMail() ) );
52 connect( editMail, SIGNAL( clicked() ), SLOT( slotEditMail() ) ); 52 connect( editMail, SIGNAL( clicked() ), SLOT( slotEditMail() ) );
53 connect( deleteMail, SIGNAL( clicked() ), SLOT( slotDeleteMail() ) ); 53 connect( deleteMail, SIGNAL( clicked() ), SLOT( slotDeleteMail() ) );
54 connect( newNews, SIGNAL( clicked() ), SLOT( slotNewNews() ) ); 54 connect( newNews, SIGNAL( clicked() ), SLOT( slotNewNews() ) );
55 connect( editNews, SIGNAL( clicked() ), SLOT( slotEditNews() ) ); 55 connect( editNews, SIGNAL( clicked() ), SLOT( slotEditNews() ) );
56 connect( deleteNews, SIGNAL( clicked() ), SLOT( slotDeleteNews() ) ); 56 connect( deleteNews, SIGNAL( clicked() ), SLOT( slotDeleteNews() ) );
57 57
58 slotFillLists(); 58 slotFillLists();
59} 59}
60 60
61void EditAccounts::slotFillLists() 61void EditAccounts::slotFillLists()
62{ 62{
63 mailList->clear(); 63 mailList->clear();
64 newsList->clear(); 64 newsList->clear();
65 65
66 QList<Account> accounts = settings->getAccounts(); 66 QList<Account> accounts = settings->getAccounts();
67 Account *it; 67 Account *it;
68 for ( it = accounts.first(); it; it = accounts.next() ) 68 for ( it = accounts.first(); it; it = accounts.next() )
69 { 69 {
70 if ( it->getType()==MAILLIB::A_NNTP ) 70 if ( it->getType()==MAILLIB::A_NNTP )
71 { 71 {
72 (void) new AccountListItem( newsList, it ); 72 (void) new AccountListItem( newsList, it );
73 } 73 }
74 else 74 else
75 { 75 {
76 (void) new AccountListItem( mailList, it ); 76 (void) new AccountListItem( mailList, it );
77 } 77 }
78 } 78 }
79} 79}
80 80
81void EditAccounts::slotNewMail() 81void EditAccounts::slotNewMail()
82{ 82{
83 qDebug( "New Mail Account" ); 83 odebug << "New Mail Account" << oendl;
84 QString *selection = new QString(); 84 QString *selection = new QString();
85 SelectMailType selType( selection, this, 0, true ); 85 SelectMailType selType( selection, this, 0, true );
86 selType.show(); 86 selType.show();
87 if ( QDialog::Accepted == selType.exec() ) 87 if ( QDialog::Accepted == selType.exec() )
88 { 88 {
89 slotNewAccount( *selection ); 89 slotNewAccount( *selection );
90 } 90 }
91} 91}
92 92
93void EditAccounts::slotNewAccount( const QString &type ) 93void EditAccounts::slotNewAccount( const QString &type )
94{ 94{
95 if ( type.compare( "IMAP" ) == 0 ) 95 if ( type.compare( "IMAP" ) == 0 )
96 { 96 {
97 qDebug( "-> config IMAP" ); 97 odebug << "-> config IMAP" << oendl;
98 IMAPaccount *account = new IMAPaccount(); 98 IMAPaccount *account = new IMAPaccount();
99 IMAPconfig imap( account, this, 0, true ); 99 IMAPconfig imap( account, this, 0, true );
100 if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) ) 100 if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) )
101 { 101 {
102 settings->addAccount( account ); 102 settings->addAccount( account );
103 account->save(); 103 account->save();
104 slotFillLists(); 104 slotFillLists();
105 } 105 }
106 else 106 else
107 { 107 {
108 account->remove(); 108 account->remove();
109 } 109 }
110 } 110 }
111 else if ( type.compare( "POP3" ) == 0 ) 111 else if ( type.compare( "POP3" ) == 0 )
112 { 112 {
113 qDebug( "-> config POP3" ); 113 odebug << "-> config POP3" << oendl;
114 POP3account *account = new POP3account(); 114 POP3account *account = new POP3account();
115 POP3config pop3( account, this, 0, true, WStyle_ContextHelp ); 115 POP3config pop3( account, this, 0, true, WStyle_ContextHelp );
116 if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) ) 116 if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) )
117 { 117 {
118 settings->addAccount( account ); 118 settings->addAccount( account );
119 account->save(); 119 account->save();
120 slotFillLists(); 120 slotFillLists();
121 } 121 }
122 else 122 else
123 { 123 {
124 account->remove(); 124 account->remove();
125 } 125 }
126 } 126 }
127 else if ( type.compare( "SMTP" ) == 0 ) 127 else if ( type.compare( "SMTP" ) == 0 )
128 { 128 {
129 qDebug( "-> config SMTP" ); 129 odebug << "-> config SMTP" << oendl;
130 SMTPaccount *account = new SMTPaccount(); 130 SMTPaccount *account = new SMTPaccount();
131 SMTPconfig smtp( account, this, 0, true, WStyle_ContextHelp ); 131 SMTPconfig smtp( account, this, 0, true, WStyle_ContextHelp );
132 if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) ) 132 if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) )
133 { 133 {
134 settings->addAccount( account ); 134 settings->addAccount( account );
135 account->save(); 135 account->save();
136 slotFillLists(); 136 slotFillLists();
137 137
138 } 138 }
139 else 139 else
140 { 140 {
141 account->remove(); 141 account->remove();
142 } 142 }
143 } 143 }
144 else if ( type.compare( "NNTP" ) == 0 ) 144 else if ( type.compare( "NNTP" ) == 0 )
145 { 145 {
146 qDebug( "-> config NNTP" ); 146 odebug << "-> config NNTP" << oendl;
147 NNTPaccount *account = new NNTPaccount(); 147 NNTPaccount *account = new NNTPaccount();
148 NNTPconfig nntp( account, this, 0, true, WStyle_ContextHelp ); 148 NNTPconfig nntp( account, this, 0, true, WStyle_ContextHelp );
149 if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) ) 149 if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) )
150 { 150 {
151 settings->addAccount( account ); 151 settings->addAccount( account );
152 account->save(); 152 account->save();
153 slotFillLists(); 153 slotFillLists();
154 } 154 }
155 else 155 else
156 { 156 {
157 account->remove(); 157 account->remove();
158 } 158 }
159 } 159 }
160} 160}
161 161
162void EditAccounts::slotEditAccount( Account *account ) 162void EditAccounts::slotEditAccount( Account *account )
163{ 163{
164 if ( account->getType() == MAILLIB::A_IMAP ) 164 if ( account->getType() == MAILLIB::A_IMAP )
165 { 165 {
166 IMAPaccount *imapAcc = static_cast<IMAPaccount *>(account); 166 IMAPaccount *imapAcc = static_cast<IMAPaccount *>(account);
167 IMAPconfig imap( imapAcc, this, 0, true, WStyle_ContextHelp ); 167 IMAPconfig imap( imapAcc, this, 0, true, WStyle_ContextHelp );
168 if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) ) 168 if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) )
169 { 169 {
170 slotFillLists(); 170 slotFillLists();
171 } 171 }
172 } 172 }
173 else if ( account->getType()==MAILLIB::A_POP3 ) 173 else if ( account->getType()==MAILLIB::A_POP3 )
174 { 174 {
175 POP3account *pop3Acc = static_cast<POP3account *>(account); 175 POP3account *pop3Acc = static_cast<POP3account *>(account);
176 POP3config pop3( pop3Acc, this, 0, true, WStyle_ContextHelp ); 176 POP3config pop3( pop3Acc, this, 0, true, WStyle_ContextHelp );
177 if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) ) 177 if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) )
178 { 178 {
179 slotFillLists(); 179 slotFillLists();
180 } 180 }
181 } 181 }
182 else if ( account->getType()==MAILLIB::A_SMTP ) 182 else if ( account->getType()==MAILLIB::A_SMTP )
183 { 183 {
184 SMTPaccount *smtpAcc = static_cast<SMTPaccount *>(account); 184 SMTPaccount *smtpAcc = static_cast<SMTPaccount *>(account);
185 SMTPconfig smtp( smtpAcc, this, 0, true, WStyle_ContextHelp ); 185 SMTPconfig smtp( smtpAcc, this, 0, true, WStyle_ContextHelp );
186 if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) ) 186 if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) )
187 { 187 {
188 slotFillLists(); 188 slotFillLists();
189 } 189 }
190 } 190 }
191 else if ( account->getType()==MAILLIB::A_NNTP) 191 else if ( account->getType()==MAILLIB::A_NNTP)
192 { 192 {
193 NNTPaccount *nntpAcc = static_cast<NNTPaccount *>(account); 193 NNTPaccount *nntpAcc = static_cast<NNTPaccount *>(account);
194 NNTPconfig nntp( nntpAcc, this, 0, true, WStyle_ContextHelp ); 194 NNTPconfig nntp( nntpAcc, this, 0, true, WStyle_ContextHelp );
195 if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) ) 195 if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) )
196 { 196 {
197 slotFillLists(); 197 slotFillLists();
198 } 198 }
199 } 199 }
200} 200}
201 201
202void EditAccounts::slotDeleteAccount( Account *account ) 202void EditAccounts::slotDeleteAccount( Account *account )
203{ 203{
204 if ( QMessageBox::information( this, tr( "Question" ), 204 if ( QMessageBox::information( this, tr( "Question" ),
205 tr( "<p>Do you really want to delete the selected Account?</p>" ), 205 tr( "<p>Do you really want to delete the selected Account?</p>" ),
206 tr( "Yes" ), tr( "No" ) ) == 0 ) 206 tr( "Yes" ), tr( "No" ) ) == 0 )
207 { 207 {
208 settings->delAccount( account ); 208 settings->delAccount( account );
209 slotFillLists(); 209 slotFillLists();
210 } 210 }
211} 211}
212 212
213void EditAccounts::slotEditMail() 213void EditAccounts::slotEditMail()
214{ 214{
215 qDebug( "Edit Mail Account" ); 215 odebug << "Edit Mail Account" << oendl;
216 if ( !mailList->currentItem() ) 216 if ( !mailList->currentItem() )
217 { 217 {
218 QMessageBox::information( this, tr( "Error" ), 218 QMessageBox::information( this, tr( "Error" ),
219 tr( "<p>Please select an account.</p>" ), 219 tr( "<p>Please select an account.</p>" ),
220 tr( "Ok" ) ); 220 tr( "Ok" ) );
221 return; 221 return;
222 } 222 }
223 223
224 Account *a = ((AccountListItem *) mailList->currentItem())->getAccount(); 224 Account *a = ((AccountListItem *) mailList->currentItem())->getAccount();
225 slotEditAccount( a ); 225 slotEditAccount( a );
226} 226}
227 227
228void EditAccounts::slotDeleteMail() 228void EditAccounts::slotDeleteMail()
229{ 229{
230 if ( !mailList->currentItem() ) 230 if ( !mailList->currentItem() )
231 { 231 {
232 QMessageBox::information( this, tr( "Error" ), 232 QMessageBox::information( this, tr( "Error" ),
233 tr( "<p>Please select an account.</p>" ), 233 tr( "<p>Please select an account.</p>" ),
234 tr( "Ok" ) ); 234 tr( "Ok" ) );
235 return; 235 return;
236 } 236 }
237 237
238 Account *a = ((AccountListItem *) mailList->currentItem())->getAccount(); 238 Account *a = ((AccountListItem *) mailList->currentItem())->getAccount();
239 slotDeleteAccount( a ); 239 slotDeleteAccount( a );
240} 240}
241 241
242void EditAccounts::slotNewNews() 242void EditAccounts::slotNewNews()
243{ 243{
244 qDebug( "New News Account" ); 244 odebug << "New News Account" << oendl;
245 slotNewAccount( "NNTP" ); 245 slotNewAccount( "NNTP" );
246} 246}
247 247
248void EditAccounts::slotEditNews() 248void EditAccounts::slotEditNews()
249{ 249{
250 qDebug( "Edit News Account" ); 250 odebug << "Edit News Account" << oendl;
251 if ( !newsList->currentItem() ) 251 if ( !newsList->currentItem() )
252 { 252 {
253 QMessageBox::information( this, tr( "Error" ), 253 QMessageBox::information( this, tr( "Error" ),
254 tr( "<p>Please select an account.</p>" ), 254 tr( "<p>Please select an account.</p>" ),
255 tr( "Ok" ) ); 255 tr( "Ok" ) );
256 return; 256 return;
257 } 257 }
258 258
259 Account *a = ((AccountListItem *) newsList->currentItem())->getAccount(); 259 Account *a = ((AccountListItem *) newsList->currentItem())->getAccount();
260 slotEditAccount( a ); 260 slotEditAccount( a );
261} 261}
262 262
263void EditAccounts::slotDeleteNews() 263void EditAccounts::slotDeleteNews()
264{ 264{
265 qDebug( "Delete News Account" ); 265 odebug << "Delete News Account" << oendl;
266 if ( !newsList->currentItem() ) 266 if ( !newsList->currentItem() )
267 { 267 {
268 QMessageBox::information( this, tr( "Error" ), 268 QMessageBox::information( this, tr( "Error" ),
269 tr( "<p>Please select an account.</p>" ), 269 tr( "<p>Please select an account.</p>" ),
270 tr( "Ok" ) ); 270 tr( "Ok" ) );
271 return; 271 return;
272 } 272 }
273 273
274 Account *a = ((AccountListItem *) newsList->currentItem())->getAccount(); 274 Account *a = ((AccountListItem *) newsList->currentItem())->getAccount();
275 slotDeleteAccount( a ); 275 slotDeleteAccount( a );
276} 276}
277 277
278void EditAccounts::slotAdjustColumns() 278void EditAccounts::slotAdjustColumns()
279{ 279{
280 int currPage = configTab->currentPageIndex(); 280 int currPage = configTab->currentPageIndex();
281 281
282 configTab->showPage( mailTab ); 282 configTab->showPage( mailTab );
283 mailList->setColumnWidth( 0, mailList->visibleWidth() - 50 ); 283 mailList->setColumnWidth( 0, mailList->visibleWidth() - 50 );
284 mailList->setColumnWidth( 1, 50 ); 284 mailList->setColumnWidth( 1, 50 );
285 285
286 configTab->showPage( newsTab ); 286 configTab->showPage( newsTab );
287 newsList->setColumnWidth( 0, newsList->visibleWidth() ); 287 newsList->setColumnWidth( 0, newsList->visibleWidth() );
288 288
289 configTab->setCurrentPage( currPage ); 289 configTab->setCurrentPage( currPage );
290} 290}
291 291
292void EditAccounts::accept() 292void EditAccounts::accept()
293{ 293{
294 settings->saveAccounts(); 294 settings->saveAccounts();
295 295
296 QDialog::accept(); 296 QDialog::accept();
297} 297}
298 298
299/** 299/**
300 * SelectMailType 300 * SelectMailType
301 */ 301 */
302 302
303SelectMailType::SelectMailType( QString *selection, QWidget *parent, const char *name, bool modal, WFlags flags ) 303SelectMailType::SelectMailType( QString *selection, QWidget *parent, const char *name, bool modal, WFlags flags )
304 : SelectMailTypeUI( parent, name, modal, flags ) 304 : SelectMailTypeUI( parent, name, modal, flags )
305{ 305{
306 selected = selection; 306 selected = selection;
307 selected->replace( 0, selected->length(), typeBox->currentText() ); 307 selected->replace( 0, selected->length(), typeBox->currentText() );
308 connect( typeBox, SIGNAL( activated(const QString&) ), SLOT( slotSelection(const QString&) ) ); 308 connect( typeBox, SIGNAL( activated(const QString&) ), SLOT( slotSelection(const QString&) ) );
309} 309}
310 310
311void SelectMailType::slotSelection( const QString &sel ) 311void SelectMailType::slotSelection( const QString &sel )
312{ 312{
313 selected->replace( 0, selected->length(), sel ); 313 selected->replace( 0, selected->length(), sel );
314} 314}
315 315
316/** 316/**
317 * IMAPconfig 317 * IMAPconfig
318 */ 318 */
319 319
320IMAPconfig::IMAPconfig( IMAPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags ) 320IMAPconfig::IMAPconfig( IMAPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags )
321 : IMAPconfigUI( parent, name, modal, flags ) 321 : IMAPconfigUI( parent, name, modal, flags )
322{ 322{
323 data = account; 323 data = account;
324 324
325 fillValues(); 325 fillValues();
326 326
327 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) ); 327 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) );
328 ComboBox1->insertItem( "Only if available", 0 ); 328 ComboBox1->insertItem( "Only if available", 0 );
329 ComboBox1->insertItem( "Always, Negotiated", 1 ); 329 ComboBox1->insertItem( "Always, Negotiated", 1 );
330 ComboBox1->insertItem( "Connect on secure port", 2 ); 330 ComboBox1->insertItem( "Connect on secure port", 2 );
331 ComboBox1->insertItem( "Run command instead", 3 ); 331 ComboBox1->insertItem( "Run command instead", 3 );
332 CommandEdit->hide(); 332 CommandEdit->hide();
333 ComboBox1->setCurrentItem( data->ConnectionType() ); 333 ComboBox1->setCurrentItem( data->ConnectionType() );
334} 334}
335 335
336void IMAPconfig::slotConnectionToggle( int index ) 336void IMAPconfig::slotConnectionToggle( int index )
337{ 337{
338 if ( index == 2 ) 338 if ( index == 2 )
339 { 339 {
340 portLine->setText( IMAP_SSL_PORT ); 340 portLine->setText( IMAP_SSL_PORT );
341 } 341 }
342 else if ( index == 3 ) 342 else if ( index == 3 )
343 { 343 {
344 portLine->setText( IMAP_PORT ); 344 portLine->setText( IMAP_PORT );
345 CommandEdit->show(); 345 CommandEdit->show();
346 } 346 }
347 else 347 else
348 { 348 {
349 portLine->setText( IMAP_PORT ); 349 portLine->setText( IMAP_PORT );
350 } 350 }
351} 351}
352 352
353void IMAPconfig::fillValues() 353void IMAPconfig::fillValues()
354{ 354{
355 accountLine->setText( data->getAccountName() ); 355 accountLine->setText( data->getAccountName() );
356 serverLine->setText( data->getServer() ); 356 serverLine->setText( data->getServer() );
357 portLine->setText( data->getPort() ); 357 portLine->setText( data->getPort() );
358 ComboBox1->setCurrentItem( data->ConnectionType() ); 358 ComboBox1->setCurrentItem( data->ConnectionType() );
359 userLine->setText( data->getUser() ); 359 userLine->setText( data->getUser() );
360 passLine->setText( data->getPassword() ); 360 passLine->setText( data->getPassword() );
361 prefixLine->setText(data->getPrefix()); 361 prefixLine->setText(data->getPrefix());
@@ -485,110 +485,110 @@ void SMTPconfig::fillValues()
485 passLine->setText( data->getPassword() ); 485 passLine->setText( data->getPassword() );
486} 486}
487 487
488void SMTPconfig::accept() 488void SMTPconfig::accept()
489{ 489{
490 data->setAccountName( accountLine->text() ); 490 data->setAccountName( accountLine->text() );
491 data->setServer( serverLine->text() ); 491 data->setServer( serverLine->text() );
492 data->setPort( portLine->text() ); 492 data->setPort( portLine->text() );
493 data->setConnectionType( ComboBox1->currentItem() ); 493 data->setConnectionType( ComboBox1->currentItem() );
494 data->setLogin( loginBox->isChecked() ); 494 data->setLogin( loginBox->isChecked() );
495 data->setUser( userLine->text() ); 495 data->setUser( userLine->text() );
496 data->setPassword( passLine->text() ); 496 data->setPassword( passLine->text() );
497 497
498 QDialog::accept(); 498 QDialog::accept();
499} 499}
500 500
501/** 501/**
502 * NNTPconfig 502 * NNTPconfig
503 */ 503 */
504 504
505NNTPconfig::NNTPconfig( NNTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags ) 505NNTPconfig::NNTPconfig( NNTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags )
506 : NNTPconfigUI( parent, name, modal, flags ) 506 : NNTPconfigUI( parent, name, modal, flags )
507{ 507{
508 data = account; 508 data = account;
509 509
510 connect( loginBox, SIGNAL( toggled(bool) ), userLine, SLOT( setEnabled(bool) ) ); 510 connect( loginBox, SIGNAL( toggled(bool) ), userLine, SLOT( setEnabled(bool) ) );
511 connect( loginBox, SIGNAL( toggled(bool) ), passLine, SLOT( setEnabled(bool) ) ); 511 connect( loginBox, SIGNAL( toggled(bool) ), passLine, SLOT( setEnabled(bool) ) );
512 connect( GetNGButton, SIGNAL( clicked() ), this, SLOT( slotGetNG() ) ); 512 connect( GetNGButton, SIGNAL( clicked() ), this, SLOT( slotGetNG() ) );
513 fillValues(); 513 fillValues();
514 514
515 connect( sslBox, SIGNAL( toggled(bool) ), SLOT( slotSSL(bool) ) ); 515 connect( sslBox, SIGNAL( toggled(bool) ), SLOT( slotSSL(bool) ) );
516} 516}
517 517
518void NNTPconfig::slotGetNG() { 518void NNTPconfig::slotGetNG() {
519 save(); 519 save();
520 data->save(); 520 data->save();
521 NNTPwrapper* tmp = new NNTPwrapper( data ); 521 NNTPwrapper* tmp = new NNTPwrapper( data );
522 QStringList list = tmp->listAllNewsgroups(); 522 QStringList list = tmp->listAllNewsgroups();
523 523
524 ListViewGroups->clear(); 524 ListViewGroups->clear();
525 525
526 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { 526 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
527 QCheckListItem *item; 527 QCheckListItem *item;
528 item = new QCheckListItem( ListViewGroups, (*it), QCheckListItem::CheckBox ); 528 item = new QCheckListItem( ListViewGroups, (*it), QCheckListItem::CheckBox );
529 if ( subscribedGroups.contains( (*it) ) >= 1 ) { 529 if ( subscribedGroups.contains( (*it) ) >= 1 ) {
530 item->setOn( true ); 530 item->setOn( true );
531 } 531 }
532 } 532 }
533} 533}
534 534
535void NNTPconfig::slotSSL( bool enabled ) 535void NNTPconfig::slotSSL( bool enabled )
536{ 536{
537 if ( enabled ) 537 if ( enabled )
538 { 538 {
539 portLine->setText( NNTP_SSL_PORT ); 539 portLine->setText( NNTP_SSL_PORT );
540 } 540 }
541 else 541 else
542 { 542 {
543 portLine->setText( NNTP_PORT ); 543 portLine->setText( NNTP_PORT );
544 } 544 }
545} 545}
546 546
547void NNTPconfig::fillValues() 547void NNTPconfig::fillValues()
548{ 548{
549 accountLine->setText( data->getAccountName() ); 549 accountLine->setText( data->getAccountName() );
550 serverLine->setText( data->getServer() ); 550 serverLine->setText( data->getServer() );
551 portLine->setText( data->getPort() ); 551 portLine->setText( data->getPort() );
552 sslBox->setChecked( data->getSSL() ); 552 sslBox->setChecked( data->getSSL() );
553 loginBox->setChecked( data->getLogin() ); 553 loginBox->setChecked( data->getLogin() );
554 userLine->setText( data->getUser() ); 554 userLine->setText( data->getUser() );
555 passLine->setText( data->getPassword() ); 555 passLine->setText( data->getPassword() );
556 subscribedGroups = data->getGroups(); 556 subscribedGroups = data->getGroups();
557 /* don't forget that - you will overwrite values if user clicks cancel! */ 557 /* don't forget that - you will overwrite values if user clicks cancel! */
558 for ( QStringList::Iterator it = subscribedGroups.begin(); it != subscribedGroups.end(); ++it ) { 558 for ( QStringList::Iterator it = subscribedGroups.begin(); it != subscribedGroups.end(); ++it ) {
559 QCheckListItem *item; 559 QCheckListItem *item;
560 item = new QCheckListItem( ListViewGroups, (*it), QCheckListItem::CheckBox ); 560 item = new QCheckListItem( ListViewGroups, (*it), QCheckListItem::CheckBox );
561 item->setOn( true ); 561 item->setOn( true );
562 } 562 }
563} 563}
564 564
565void NNTPconfig::save() 565void NNTPconfig::save()
566{ 566{
567 data->setAccountName( accountLine->text() ); 567 data->setAccountName( accountLine->text() );
568 data->setServer( serverLine->text() ); 568 data->setServer( serverLine->text() );
569 data->setPort( portLine->text() ); 569 data->setPort( portLine->text() );
570 data->setSSL( sslBox->isChecked() ); 570 data->setSSL( sslBox->isChecked() );
571 data->setLogin( loginBox->isChecked() ); 571 data->setLogin( loginBox->isChecked() );
572 data->setUser( userLine->text() ); 572 data->setUser( userLine->text() );
573 data->setPassword( passLine->text() ); 573 data->setPassword( passLine->text() );
574 574
575 QListViewItemIterator list_it( ListViewGroups ); 575 QListViewItemIterator list_it( ListViewGroups );
576 576
577 QStringList groupList; 577 QStringList groupList;
578 for ( ; list_it.current(); ++list_it ) { 578 for ( ; list_it.current(); ++list_it ) {
579 579
580 if ( ( (QCheckListItem*)list_it.current() )->isOn() ) { 580 if ( ( (QCheckListItem*)list_it.current() )->isOn() ) {
581 qDebug(list_it.current()->text(0) ); 581 odebug << list_it.current()->text(0) << oendl;
582 groupList.append( list_it.current()->text(0) ); 582 groupList.append( list_it.current()->text(0) );
583 } 583 }
584 584
585 } 585 }
586 data->setGroups( groupList ); 586 data->setGroups( groupList );
587} 587}
588 588
589void NNTPconfig::accept() 589void NNTPconfig::accept()
590{ 590{
591 save(); 591 save();
592 QDialog::accept(); 592 QDialog::accept();
593} 593}
594 594
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 @@
1#include "abstractmail.h" 1#include "abstractmail.h"
2#include "imapwrapper.h" 2#include "imapwrapper.h"
3#include "pop3wrapper.h" 3#include "pop3wrapper.h"
4#include "nntpwrapper.h" 4#include "nntpwrapper.h"
5#include "mhwrapper.h" 5#include "mhwrapper.h"
6#include "mailtypes.h" 6#include "mailtypes.h"
7 7
8#include <qfile.h> 8#include <qfile.h>
9#include <qtextstream.h> 9#include <qtextstream.h>
10#include <stdlib.h> 10#include <stdlib.h>
11#include <libetpan/mailmime_content.h> 11#include <libetpan/mailmime_content.h>
12#include <libetpan/mailmime.h> 12#include <libetpan/mailmime.h>
13 13
14using namespace Opie::Core; 14using namespace Opie::Core;
15AbstractMail* AbstractMail::getWrapper(IMAPaccount *a) 15AbstractMail* AbstractMail::getWrapper(IMAPaccount *a)
16{ 16{
17 return new IMAPwrapper(a); 17 return new IMAPwrapper(a);
18} 18}
19 19
20AbstractMail* AbstractMail::getWrapper(POP3account *a) 20AbstractMail* AbstractMail::getWrapper(POP3account *a)
21{ 21{
22 return new POP3wrapper(a); 22 return new POP3wrapper(a);
23} 23}
24 24
25AbstractMail* AbstractMail::getWrapper(NNTPaccount *a) 25AbstractMail* AbstractMail::getWrapper(NNTPaccount *a)
26{ 26{
27 return new NNTPwrapper(a); 27 return new NNTPwrapper(a);
28} 28}
29 29
30AbstractMail* AbstractMail::getWrapper(const QString&a,const QString&name) 30AbstractMail* AbstractMail::getWrapper(const QString&a,const QString&name)
31{ 31{
32 return new MHwrapper(a,name); 32 return new MHwrapper(a,name);
33} 33}
34 34
35AbstractMail* AbstractMail::getWrapper(Account*a) 35AbstractMail* AbstractMail::getWrapper(Account*a)
36{ 36{
37 if (!a) return 0; 37 if (!a) return 0;
38 switch (a->getType()) { 38 switch (a->getType()) {
39 case MAILLIB::A_IMAP: 39 case MAILLIB::A_IMAP:
40 return new IMAPwrapper((IMAPaccount*)a); 40 return new IMAPwrapper((IMAPaccount*)a);
41 break; 41 break;
42 case MAILLIB::A_POP3: 42 case MAILLIB::A_POP3:
43 return new POP3wrapper((POP3account*)a); 43 return new POP3wrapper((POP3account*)a);
44 break; 44 break;
45 case MAILLIB::A_NNTP: 45 case MAILLIB::A_NNTP:
46 return new NNTPwrapper((NNTPaccount*)a); 46 return new NNTPwrapper((NNTPaccount*)a);
47 break; 47 break;
48 default: 48 default:
49 return 0; 49 return 0;
50 } 50 }
51} 51}
52 52
53encodedString* AbstractMail::decode_String(const encodedString*text,const QString&enc) 53encodedString* AbstractMail::decode_String(const encodedString*text,const QString&enc)
54{ 54{
55 qDebug("Decode string start"); 55 odebug << "Decode string start" << oendl;
56 char*result_text; 56 char*result_text;
57 size_t index = 0; 57 size_t index = 0;
58 /* reset for recursive use! */ 58 /* reset for recursive use! */
59 size_t target_length = 0; 59 size_t target_length = 0;
60 result_text = 0; 60 result_text = 0;
61 int mimetype = MAILMIME_MECHANISM_7BIT; 61 int mimetype = MAILMIME_MECHANISM_7BIT;
62 if (enc.lower()=="quoted-printable") { 62 if (enc.lower()=="quoted-printable") {
63 mimetype = MAILMIME_MECHANISM_QUOTED_PRINTABLE; 63 mimetype = MAILMIME_MECHANISM_QUOTED_PRINTABLE;
64 } else if (enc.lower()=="base64") { 64 } else if (enc.lower()=="base64") {
65 mimetype = MAILMIME_MECHANISM_BASE64; 65 mimetype = MAILMIME_MECHANISM_BASE64;
66 } else if (enc.lower()=="8bit") { 66 } else if (enc.lower()=="8bit") {
67 mimetype = MAILMIME_MECHANISM_8BIT; 67 mimetype = MAILMIME_MECHANISM_8BIT;
68 } else if (enc.lower()=="binary") { 68 } else if (enc.lower()=="binary") {
69 mimetype = MAILMIME_MECHANISM_BINARY; 69 mimetype = MAILMIME_MECHANISM_BINARY;
70 } 70 }
71 71
72 int err = mailmime_part_parse(text->Content(),text->Length(),&index,mimetype, 72 int err = mailmime_part_parse(text->Content(),text->Length(),&index,mimetype,
73 &result_text,&target_length); 73 &result_text,&target_length);
74 74
75 encodedString* result = new encodedString(); 75 encodedString* result = new encodedString();
76 if (err == MAILIMF_NO_ERROR) { 76 if (err == MAILIMF_NO_ERROR) {
77 result->setContent(result_text,target_length); 77 result->setContent(result_text,target_length);
78 } 78 }
79 qDebug("Decode string finished"); 79 odebug << "Decode string finished" << oendl;
80 return result; 80 return result;
81} 81}
82 82
83QString AbstractMail::convert_String(const char*text) 83QString AbstractMail::convert_String(const char*text)
84{ 84{
85 //size_t index = 0; 85 //size_t index = 0;
86 char*res = 0; 86 char*res = 0;
87 int err = MAILIMF_NO_ERROR; 87 int err = MAILIMF_NO_ERROR;
88 88
89 QString result(text); 89 QString result(text);
90 90
91 /* due a bug in libetpan it isn't usable this moment */ 91 /* due a bug in libetpan it isn't usable this moment */
92/* int err = mailmime_encoded_phrase_parse("iso-8859-1", 92/* int err = mailmime_encoded_phrase_parse("iso-8859-1",
93 text, strlen(text),&index, "iso-8859-1",&res);*/ 93 text, strlen(text),&index, "iso-8859-1",&res);*/
94 //qDebug("Input: %s",text); 94 //odebug << "Input: " << text << "" << oendl;
95 if (err == MAILIMF_NO_ERROR && res && strlen(res)) { 95 if (err == MAILIMF_NO_ERROR && res && strlen(res)) {
96// result = QString(res); 96// result = QString(res);
97// qDebug("Res: %s, length: %i",res,strlen(res)); 97// odebug << "Res: " << res << ", length: " << strlen(res) << "" << oendl;
98 } 98 }
99 if (res) free(res); 99 if (res) free(res);
100 return result; 100 return result;
101} 101}
102 102
103/* cp & paste from launcher */ 103/* cp & paste from launcher */
104QString AbstractMail::gen_attachment_id() 104QString AbstractMail::gen_attachment_id()
105{ 105{
106 QFile file( "/proc/sys/kernel/random/uuid" ); 106 QFile file( "/proc/sys/kernel/random/uuid" );
107 if (!file.open(IO_ReadOnly ) ) 107 if (!file.open(IO_ReadOnly ) )
108 return QString::null; 108 return QString::null;
109 109
110 QTextStream stream(&file); 110 QTextStream stream(&file);
111 111
112 return "{" + stream.read().stripWhiteSpace() + "}"; 112 return "{" + stream.read().stripWhiteSpace() + "}";
113} 113}
114 114
115int AbstractMail::createMbox(const QString&,const FolderP&,const QString& ,bool) 115int AbstractMail::createMbox(const QString&,const FolderP&,const QString& ,bool)
116{ 116{
117 return 0; 117 return 0;
118} 118}
119 119
120QString AbstractMail::defaultLocalfolder() 120QString AbstractMail::defaultLocalfolder()
121{ 121{
122 QString f = getenv( "HOME" ); 122 QString f = getenv( "HOME" );
123 f += "/Applications/opiemail/localmail"; 123 f += "/Applications/opiemail/localmail";
124 return f; 124 return f;
125} 125}
126 126
127QString AbstractMail::draftFolder() 127QString AbstractMail::draftFolder()
128{ 128{
129 return QString("Drafts"); 129 return QString("Drafts");
130} 130}
131 131
132/* temporary - will be removed when implemented in all classes */ 132/* temporary - will be removed when implemented in all classes */
133void AbstractMail::deleteMails(const QString &,const QValueList<Opie::Core::OSmartPointer<RecMail> > &) 133void AbstractMail::deleteMails(const QString &,const QValueList<Opie::Core::OSmartPointer<RecMail> > &)
134{ 134{
135} 135}
136 136
137void AbstractMail::mvcpAllMails(const FolderP&fromFolder, 137void AbstractMail::mvcpAllMails(const FolderP&fromFolder,
138 const QString&targetFolder,AbstractMail*targetWrapper,bool moveit) 138 const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
139{ 139{
140 QValueList<RecMailP> t; 140 QValueList<RecMailP> t;
141 listMessages(fromFolder->getName(),t); 141 listMessages(fromFolder->getName(),t);
142 encodedString*st = 0; 142 encodedString*st = 0;
143 while (t.count()>0) { 143 while (t.count()>0) {
144 RecMailP r = (*t.begin()); 144 RecMailP r = (*t.begin());
145 st = fetchRawBody(r); 145 st = fetchRawBody(r);
146 if (st) { 146 if (st) {
147 targetWrapper->storeMessage(st->Content(),st->Length(),targetFolder); 147 targetWrapper->storeMessage(st->Content(),st->Length(),targetFolder);
148 delete st; 148 delete st;
149 } 149 }
150 t.remove(t.begin()); 150 t.remove(t.begin());
151 } 151 }
152 if (moveit) { 152 if (moveit) {
153 deleteAllMail(fromFolder); 153 deleteAllMail(fromFolder);
154 } 154 }
155} 155}
156 156
157void AbstractMail::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit) 157void AbstractMail::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
158{ 158{
159 encodedString*st = 0; 159 encodedString*st = 0;
160 st = fetchRawBody(mail); 160 st = fetchRawBody(mail);
161 if (st) { 161 if (st) {
162 targetWrapper->storeMessage(st->Content(),st->Length(),targetFolder); 162 targetWrapper->storeMessage(st->Content(),st->Length(),targetFolder);
163 delete st; 163 delete st;
164 } 164 }
165 if (moveit) { 165 if (moveit) {
166 deleteMail(mail); 166 deleteMail(mail);
167 } 167 }
168} 168}
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 @@
4#include <libetpan/libetpan.h> 4#include <libetpan/libetpan.h>
5 5
6#include <qt.h> 6#include <qt.h>
7 7
8using namespace Opie::Core; 8using namespace Opie::Core;
9const char* Generatemail::USER_AGENT="OpieMail v0.6"; 9const char* Generatemail::USER_AGENT="OpieMail v0.6";
10 10
11Generatemail::Generatemail() 11Generatemail::Generatemail()
12{ 12{
13} 13}
14 14
15Generatemail::~Generatemail() 15Generatemail::~Generatemail()
16{ 16{
17} 17}
18 18
19void Generatemail::addRcpts( clist *list, mailimf_address_list *addr_list ) { 19void Generatemail::addRcpts( clist *list, mailimf_address_list *addr_list ) {
20 clistiter *it, *it2; 20 clistiter *it, *it2;
21 21
22 for ( it = clist_begin( addr_list->ad_list ); it; it = it->next ) { 22 for ( it = clist_begin( addr_list->ad_list ); it; it = it->next ) {
23 mailimf_address *addr; 23 mailimf_address *addr;
24 addr = (mailimf_address *) it->data; 24 addr = (mailimf_address *) it->data;
25 25
26 if ( addr->ad_type == MAILIMF_ADDRESS_MAILBOX ) { 26 if ( addr->ad_type == MAILIMF_ADDRESS_MAILBOX ) {
27 esmtp_address_list_add( list, addr->ad_data.ad_mailbox->mb_addr_spec, 0, NULL ); 27 esmtp_address_list_add( list, addr->ad_data.ad_mailbox->mb_addr_spec, 0, NULL );
28 } else if ( addr->ad_type == MAILIMF_ADDRESS_GROUP ) { 28 } else if ( addr->ad_type == MAILIMF_ADDRESS_GROUP ) {
29 clist *l = addr->ad_data.ad_group->grp_mb_list->mb_list; 29 clist *l = addr->ad_data.ad_group->grp_mb_list->mb_list;
30 for ( it2 = clist_begin( l ); it2; it2 = it2->next ) { 30 for ( it2 = clist_begin( l ); it2; it2 = it2->next ) {
31 mailimf_mailbox *mbox; 31 mailimf_mailbox *mbox;
32 mbox = (mailimf_mailbox *) it2->data; 32 mbox = (mailimf_mailbox *) it2->data;
33 esmtp_address_list_add( list, mbox->mb_addr_spec, 0, NULL ); 33 esmtp_address_list_add( list, mbox->mb_addr_spec, 0, NULL );
34 } 34 }
35 } 35 }
36 } 36 }
37} 37}
38 38
39char *Generatemail::getFrom( mailimf_field *ffrom) { 39char *Generatemail::getFrom( mailimf_field *ffrom) {
40 char *from = NULL; 40 char *from = NULL;
41 if ( ffrom && (ffrom->fld_type == MAILIMF_FIELD_FROM) 41 if ( ffrom && (ffrom->fld_type == MAILIMF_FIELD_FROM)
42 && ffrom->fld_data.fld_from->frm_mb_list && ffrom->fld_data.fld_from->frm_mb_list->mb_list ) { 42 && ffrom->fld_data.fld_from->frm_mb_list && ffrom->fld_data.fld_from->frm_mb_list->mb_list ) {
43 clist *cl = ffrom->fld_data.fld_from->frm_mb_list->mb_list; 43 clist *cl = ffrom->fld_data.fld_from->frm_mb_list->mb_list;
44 clistiter *it; 44 clistiter *it;
45 for ( it = clist_begin( cl ); it; it = it->next ) { 45 for ( it = clist_begin( cl ); it; it = it->next ) {
46 mailimf_mailbox *mb = (mailimf_mailbox *) it->data; 46 mailimf_mailbox *mb = (mailimf_mailbox *) it->data;
47 from = strdup( mb->mb_addr_spec ); 47 from = strdup( mb->mb_addr_spec );
48 } 48 }
49 } 49 }
50 50
51 return from; 51 return from;
52} 52}
53 53
54char *Generatemail::getFrom( mailmime *mail ) { 54char *Generatemail::getFrom( mailmime *mail ) {
55 /* no need to delete - its just a pointer to structure content */ 55 /* no need to delete - its just a pointer to structure content */
56 mailimf_field *ffrom = 0; 56 mailimf_field *ffrom = 0;
57 ffrom = getField( mail->mm_data.mm_message.mm_fields, MAILIMF_FIELD_FROM ); 57 ffrom = getField( mail->mm_data.mm_message.mm_fields, MAILIMF_FIELD_FROM );
58 return getFrom(ffrom); 58 return getFrom(ffrom);
59} 59}
60 60
61mailimf_field *Generatemail::getField( mailimf_fields *fields, int type ) { 61mailimf_field *Generatemail::getField( mailimf_fields *fields, int type ) {
62 mailimf_field *field; 62 mailimf_field *field;
63 clistiter *it; 63 clistiter *it;
64 64
65 it = clist_begin( fields->fld_list ); 65 it = clist_begin( fields->fld_list );
66 while ( it ) { 66 while ( it ) {
67 field = (mailimf_field *) it->data; 67 field = (mailimf_field *) it->data;
68 if ( field->fld_type == type ) { 68 if ( field->fld_type == type ) {
69 return field; 69 return field;
70 } 70 }
71 it = it->next; 71 it = it->next;
72 } 72 }
73 73
74 return NULL; 74 return NULL;
75} 75}
76 76
77mailimf_address_list *Generatemail::parseAddresses(const QString&addr ) { 77mailimf_address_list *Generatemail::parseAddresses(const QString&addr ) {
78 mailimf_address_list *addresses; 78 mailimf_address_list *addresses;
79 79
80 if ( addr.isEmpty() ) 80 if ( addr.isEmpty() )
81 return NULL; 81 return NULL;
82 82
83 addresses = mailimf_address_list_new_empty(); 83 addresses = mailimf_address_list_new_empty();
84 84
85 bool literal_open = false; 85 bool literal_open = false;
86 unsigned int startpos = 0; 86 unsigned int startpos = 0;
87 QStringList list; 87 QStringList list;
88 QString s; 88 QString s;
89 unsigned int i = 0; 89 unsigned int i = 0;
90 for (; i < addr.length();++i) { 90 for (; i < addr.length();++i) {
91 switch (addr[i]) { 91 switch (addr[i]) {
92 case '\"': 92 case '\"':
93 literal_open = !literal_open; 93 literal_open = !literal_open;
94 break; 94 break;
95 case ',': 95 case ',':
96 if (!literal_open) { 96 if (!literal_open) {
97 s = addr.mid(startpos,i-startpos); 97 s = addr.mid(startpos,i-startpos);
98 if (!s.isEmpty()) { 98 if (!s.isEmpty()) {
99 list.append(s); 99 list.append(s);
100 qDebug("Appended %s",s.latin1()); 100 odebug << "Appended " << s.latin1() << "" << oendl;
101 } 101 }
102 // !!!! this is a MUST BE! 102 // !!!! this is a MUST BE!
103 startpos = ++i; 103 startpos = ++i;
104 } 104 }
105 break; 105 break;
106 default: 106 default:
107 break; 107 break;
108 } 108 }
109 } 109 }
110 s = addr.mid(startpos,i-startpos); 110 s = addr.mid(startpos,i-startpos);
111 if (!s.isEmpty()) { 111 if (!s.isEmpty()) {
112 list.append(s); 112 list.append(s);
113 qDebug("Appended %s",s.latin1()); 113 odebug << "Appended " << s.latin1() << "" << oendl;
114 } 114 }
115 QStringList::Iterator it; 115 QStringList::Iterator it;
116 for ( it = list.begin(); it != list.end(); it++ ) { 116 for ( it = list.begin(); it != list.end(); it++ ) {
117 int err = mailimf_address_list_add_parse( addresses, (char*)(*it).latin1() ); 117 int err = mailimf_address_list_add_parse( addresses, (char*)(*it).latin1() );
118 if ( err != MAILIMF_NO_ERROR ) { 118 if ( err != MAILIMF_NO_ERROR ) {
119 qDebug( "Error parsing" ); 119 odebug << "Error parsing" << oendl;
120 qDebug( *it ); 120 odebug << *it << oendl;
121 } else { 121 } else {
122 qDebug( "Parse success! %s",(*it).latin1()); 122 odebug << "Parse success! " << (*it).latin1() << "" << oendl;
123 } 123 }
124 } 124 }
125 return addresses; 125 return addresses;
126} 126}
127 127
128mailmime *Generatemail::buildFilePart(const QString&filename,const QString&mimetype,const QString&TextContent ) { 128mailmime *Generatemail::buildFilePart(const QString&filename,const QString&mimetype,const QString&TextContent ) {
129 mailmime * filePart = 0; 129 mailmime * filePart = 0;
130 mailmime_fields * fields = 0; 130 mailmime_fields * fields = 0;
131 mailmime_content * content = 0; 131 mailmime_content * content = 0;
132 mailmime_parameter * param = 0; 132 mailmime_parameter * param = 0;
133 char*name = 0; 133 char*name = 0;
134 char*file = 0; 134 char*file = 0;
135 int err; 135 int err;
136 136
137 int pos = filename.findRev( '/' ); 137 int pos = filename.findRev( '/' );
138 138
139 if (filename.length()>0) { 139 if (filename.length()>0) {
140 QString tmp = filename.right( filename.length() - ( pos + 1 ) ); 140 QString tmp = filename.right( filename.length() - ( pos + 1 ) );
141 name = strdup( tmp.latin1() ); // just filename 141 name = strdup( tmp.latin1() ); // just filename
142 file = strdup( filename.latin1() ); // full name with path 142 file = strdup( filename.latin1() ); // full name with path
143 } 143 }
144 144
145 int disptype = MAILMIME_DISPOSITION_TYPE_ATTACHMENT; 145 int disptype = MAILMIME_DISPOSITION_TYPE_ATTACHMENT;
146 int mechanism = MAILMIME_MECHANISM_BASE64; 146 int mechanism = MAILMIME_MECHANISM_BASE64;
147 147
148 if ( mimetype.startsWith( "text/" ) ) { 148 if ( mimetype.startsWith( "text/" ) ) {
149 param = mailmime_parameter_new( strdup( "charset" ), 149 param = mailmime_parameter_new( strdup( "charset" ),
150 strdup( "iso-8859-1" ) ); 150 strdup( "iso-8859-1" ) );
151 mechanism = MAILMIME_MECHANISM_QUOTED_PRINTABLE; 151 mechanism = MAILMIME_MECHANISM_QUOTED_PRINTABLE;
152 } 152 }
153 153
154 fields = mailmime_fields_new_filename( 154 fields = mailmime_fields_new_filename(
155 disptype, name, 155 disptype, name,
156 mechanism ); 156 mechanism );
157 content = mailmime_content_new_with_str( (char*)mimetype.latin1() ); 157 content = mailmime_content_new_with_str( (char*)mimetype.latin1() );
158 if (content!=0 && fields != 0) { 158 if (content!=0 && fields != 0) {
159 if (param) { 159 if (param) {
160 clist_append(content->ct_parameters,param); 160 clist_append(content->ct_parameters,param);
161 param = 0; 161 param = 0;
162 } 162 }
163 if (filename.length()>0) { 163 if (filename.length()>0) {
164 QFileInfo f(filename); 164 QFileInfo f(filename);
165 param = mailmime_parameter_new(strdup("name"),strdup(f.fileName().latin1())); 165 param = mailmime_parameter_new(strdup("name"),strdup(f.fileName().latin1()));
166 clist_append(content->ct_parameters,param); 166 clist_append(content->ct_parameters,param);
167 param = 0; 167 param = 0;
168 } 168 }
169 filePart = mailmime_new_empty( content, fields ); 169 filePart = mailmime_new_empty( content, fields );
170 } 170 }
171 if (filePart) { 171 if (filePart) {
172 if (filename.length()>0) { 172 if (filename.length()>0) {
173 err = mailmime_set_body_file( filePart, file ); 173 err = mailmime_set_body_file( filePart, file );
174 } else { 174 } else {
175 err = mailmime_set_body_text(filePart,strdup(TextContent.data()),TextContent.length()); 175 err = mailmime_set_body_text(filePart,strdup(TextContent.data()),TextContent.length());
176 } 176 }
177 if (err != MAILIMF_NO_ERROR) { 177 if (err != MAILIMF_NO_ERROR) {
178 qDebug("Error setting body with file %s",file); 178 odebug << "Error setting body with file " << file << "" << oendl;
179 mailmime_free( filePart ); 179 mailmime_free( filePart );
180 filePart = 0; 180 filePart = 0;
181 } 181 }
182 } 182 }
183 183
184 if (!filePart) { 184 if (!filePart) {
185 if ( param != NULL ) { 185 if ( param != NULL ) {
186 mailmime_parameter_free( param ); 186 mailmime_parameter_free( param );
187 } 187 }
188 if (content) { 188 if (content) {
189 mailmime_content_free( content ); 189 mailmime_content_free( content );
190 } 190 }
191 if (fields) { 191 if (fields) {
192 mailmime_fields_free( fields ); 192 mailmime_fields_free( fields );
193 } else { 193 } else {
194 if (name) { 194 if (name) {
195 free( name ); 195 free( name );
196 } 196 }
197 if (file) { 197 if (file) {
198 free( file ); 198 free( file );
199 } 199 }
200 } 200 }
201 } 201 }
202 return filePart; // Success :) 202 return filePart; // Success :)
203 203
204} 204}
205 205
206void Generatemail::addFileParts( mailmime *message,const QList<Attachment>&files ) { 206void Generatemail::addFileParts( mailmime *message,const QList<Attachment>&files ) {
207 const Attachment *it; 207 const Attachment *it;
208 unsigned int count = files.count(); 208 unsigned int count = files.count();
209 qDebug("List contains %i values",count); 209 odebug << "List contains " << count << " values" << oendl;
210 for ( unsigned int i = 0; i < count; ++i ) { 210 for ( unsigned int i = 0; i < count; ++i ) {
211 qDebug( "Adding file" ); 211 odebug << "Adding file" << oendl;
212 mailmime *filePart; 212 mailmime *filePart;
213 int err; 213 int err;
214 it = ((QList<Attachment>)files).at(i); 214 it = ((QList<Attachment>)files).at(i);
215 215
216 filePart = buildFilePart( it->getFileName(), it->getMimeType(),"" ); 216 filePart = buildFilePart( it->getFileName(), it->getMimeType(),"" );
217 if ( filePart == NULL ) { 217 if ( filePart == NULL ) {
218 qDebug( "addFileParts: error adding file:" ); 218 odebug << "addFileParts: error adding file:" << oendl;
219 qDebug( it->getFileName() ); 219 odebug << it->getFileName() << oendl;
220 continue; 220 continue;
221 } 221 }
222 err = mailmime_smart_add_part( message, filePart ); 222 err = mailmime_smart_add_part( message, filePart );
223 if ( err != MAILIMF_NO_ERROR ) { 223 if ( err != MAILIMF_NO_ERROR ) {
224 mailmime_free( filePart ); 224 mailmime_free( filePart );
225 qDebug("error smart add"); 225 odebug << "error smart add" << oendl;
226 } 226 }
227 } 227 }
228} 228}
229 229
230mailmime *Generatemail::buildTxtPart(const QString&str ) { 230mailmime *Generatemail::buildTxtPart(const QString&str ) {
231 mailmime *txtPart; 231 mailmime *txtPart;
232 mailmime_fields *fields; 232 mailmime_fields *fields;
233 mailmime_content *content; 233 mailmime_content *content;
234 mailmime_parameter *param; 234 mailmime_parameter *param;
235 int err; 235 int err;
236 236
237 param = mailmime_parameter_new( strdup( "charset" ), 237 param = mailmime_parameter_new( strdup( "charset" ),
238 strdup( "iso-8859-1" ) ); 238 strdup( "iso-8859-1" ) );
239 if ( param == NULL ) 239 if ( param == NULL )
240 goto err_free; 240 goto err_free;
241 241
242 content = mailmime_content_new_with_str( "text/plain" ); 242 content = mailmime_content_new_with_str( "text/plain" );
243 if ( content == NULL ) 243 if ( content == NULL )
244 goto err_free_param; 244 goto err_free_param;
245 245
246 err = clist_append( content->ct_parameters, param ); 246 err = clist_append( content->ct_parameters, param );
247 if ( err != MAILIMF_NO_ERROR ) 247 if ( err != MAILIMF_NO_ERROR )
248 goto err_free_content; 248 goto err_free_content;
249 249
250 fields = mailmime_fields_new_encoding(MAILMIME_MECHANISM_8BIT); 250 fields = mailmime_fields_new_encoding(MAILMIME_MECHANISM_8BIT);
251 if ( fields == NULL ) 251 if ( fields == NULL )
252 goto err_free_content; 252 goto err_free_content;
253 253
254 txtPart = mailmime_new_empty( content, fields ); 254 txtPart = mailmime_new_empty( content, fields );
255 if ( txtPart == NULL ) 255 if ( txtPart == NULL )
256 goto err_free_fields; 256 goto err_free_fields;
257 257
258 err = mailmime_set_body_text( txtPart, (char*)str.data(), str.length() ); 258 err = mailmime_set_body_text( txtPart, (char*)str.data(), str.length() );
259 if ( err != MAILIMF_NO_ERROR ) 259 if ( err != MAILIMF_NO_ERROR )
260 goto err_free_txtPart; 260 goto err_free_txtPart;
261 261
262 return txtPart; // Success :) 262 return txtPart; // Success :)
263 263
264err_free_txtPart: 264err_free_txtPart:
265 mailmime_free( txtPart ); 265 mailmime_free( txtPart );
266err_free_fields: 266err_free_fields:
267 mailmime_fields_free( fields ); 267 mailmime_fields_free( fields );
268err_free_content: 268err_free_content:
269 mailmime_content_free( content ); 269 mailmime_content_free( content );
270err_free_param: 270err_free_param:
271 mailmime_parameter_free( param ); 271 mailmime_parameter_free( param );
272err_free: 272err_free:
273 qDebug( "buildTxtPart - error" ); 273 odebug << "buildTxtPart - error" << oendl;
274 274
275 return NULL; // Error :( 275 return NULL; // Error :(
276} 276}
277 277
278mailimf_mailbox *Generatemail::newMailbox(const QString&name, const QString&mail ) { 278mailimf_mailbox *Generatemail::newMailbox(const QString&name, const QString&mail ) {
279 return mailimf_mailbox_new( strdup( name.latin1() ), 279 return mailimf_mailbox_new( strdup( name.latin1() ),
280 strdup( mail.latin1() ) ); 280 strdup( mail.latin1() ) );
281} 281}
282 282
283mailimf_fields *Generatemail::createImfFields(const Opie::Core::OSmartPointer<Mail>&mail ) 283mailimf_fields *Generatemail::createImfFields(const Opie::Core::OSmartPointer<Mail>&mail )
284{ 284{
285 mailimf_fields *fields = NULL; 285 mailimf_fields *fields = NULL;
286 mailimf_field *xmailer = NULL; 286 mailimf_field *xmailer = NULL;
287 mailimf_mailbox *sender=0,*fromBox=0; 287 mailimf_mailbox *sender=0,*fromBox=0;
288 mailimf_mailbox_list *from=0; 288 mailimf_mailbox_list *from=0;
289 mailimf_address_list *to=0, *cc=0, *bcc=0, *reply=0; 289 mailimf_address_list *to=0, *cc=0, *bcc=0, *reply=0;
290 clist*in_reply_to = 0; 290 clist*in_reply_to = 0;
291 char *subject = strdup( mail->getSubject().latin1() ); 291 char *subject = strdup( mail->getSubject().latin1() );
292 int err; 292 int err;
293 int res = 1; 293 int res = 1;
294 294
295 sender = newMailbox( mail->getName(), mail->getMail() ); 295 sender = newMailbox( mail->getName(), mail->getMail() );
296 if ( sender == NULL ) { 296 if ( sender == NULL ) {
297 res = 0; 297 res = 0;
298 } 298 }
299 299
300 if (res) { 300 if (res) {
301 fromBox = newMailbox( mail->getName(), mail->getMail() ); 301 fromBox = newMailbox( mail->getName(), mail->getMail() );
302 } 302 }
303 if ( fromBox == NULL ) { 303 if ( fromBox == NULL ) {
304 res = 0; 304 res = 0;
305 } 305 }
306 306
307 if (res) { 307 if (res) {
308 from = mailimf_mailbox_list_new_empty(); 308 from = mailimf_mailbox_list_new_empty();
309 } 309 }
310 if ( from == NULL ) { 310 if ( from == NULL ) {
311 res = 0; 311 res = 0;
312 } 312 }
313 313
314 if (res && from) { 314 if (res && from) {
315 err = mailimf_mailbox_list_add( from, fromBox ); 315 err = mailimf_mailbox_list_add( from, fromBox );
316 if ( err != MAILIMF_NO_ERROR ) { 316 if ( err != MAILIMF_NO_ERROR ) {
317 res = 0; 317 res = 0;
318 } 318 }
319 } 319 }
320 320
321 if (res) to = parseAddresses( mail->getTo() ); 321 if (res) to = parseAddresses( mail->getTo() );
322 if (res) cc = parseAddresses( mail->getCC() ); 322 if (res) cc = parseAddresses( mail->getCC() );
323 if (res) bcc = parseAddresses( mail->getBCC() ); 323 if (res) bcc = parseAddresses( mail->getBCC() );
324 if (res) reply = parseAddresses( mail->getReply() ); 324 if (res) reply = parseAddresses( mail->getReply() );
325 325
326 if (res && mail->Inreply().count()>0) { 326 if (res && mail->Inreply().count()>0) {
327 in_reply_to = clist_new(); 327 in_reply_to = clist_new();
328 char*c_reply; 328 char*c_reply;
329 unsigned int nsize = 0; 329 unsigned int nsize = 0;
330 for (QStringList::ConstIterator it=mail->Inreply().begin(); 330 for (QStringList::ConstIterator it=mail->Inreply().begin();
331 it != mail->Inreply().end();++it) { 331 it != mail->Inreply().end();++it) {
332 if ((*it).isEmpty()) 332 if ((*it).isEmpty())
333 continue; 333 continue;
334 QString h((*it)); 334 QString h((*it));
335 while (h.length()>0 && h[0]=='<') { 335 while (h.length()>0 && h[0]=='<') {
336 h.remove(0,1); 336 h.remove(0,1);
337 } 337 }
338 while (h.length()>0 && h[h.length()-1]=='>') { 338 while (h.length()>0 && h[h.length()-1]=='>') {
339 h.remove(h.length()-1,1); 339 h.remove(h.length()-1,1);
340 } 340 }
341 if (h.isEmpty()) continue; 341 if (h.isEmpty()) continue;
342 nsize = strlen(h.latin1()); 342 nsize = strlen(h.latin1());
343 /* yes! must be malloc! */ 343 /* yes! must be malloc! */
344 c_reply = (char*)malloc( (nsize+1)*sizeof(char)); 344 c_reply = (char*)malloc( (nsize+1)*sizeof(char));
345 memset(c_reply,0,nsize+1); 345 memset(c_reply,0,nsize+1);
346 memcpy(c_reply,h.latin1(),nsize); 346 memcpy(c_reply,h.latin1(),nsize);
347 clist_append(in_reply_to,c_reply); 347 clist_append(in_reply_to,c_reply);
348 qDebug("In reply to: %s",c_reply); 348 odebug << "In reply to: " << c_reply << "" << oendl;
349 } 349 }
350 } 350 }
351 351
352 if (res) { 352 if (res) {
353 fields = mailimf_fields_new_with_data( from, sender, reply, to, cc, bcc, 353 fields = mailimf_fields_new_with_data( from, sender, reply, to, cc, bcc,
354 in_reply_to, NULL, subject ); 354 in_reply_to, NULL, subject );
355 if ( fields == NULL ) { 355 if ( fields == NULL ) {
356 qDebug("Error creating mailimf fields"); 356 odebug << "Error creating mailimf fields" << oendl;
357 res = 0; 357 res = 0;
358 } 358 }
359 } 359 }
360 if (res) xmailer = mailimf_field_new_custom( strdup( "User-Agent" ), 360 if (res) xmailer = mailimf_field_new_custom( strdup( "User-Agent" ),
361 strdup( USER_AGENT ) ); 361 strdup( USER_AGENT ) );
362 if ( xmailer == NULL ) { 362 if ( xmailer == NULL ) {
363 res = 0; 363 res = 0;
364 } else { 364 } else {
365 err = mailimf_fields_add( fields, xmailer ); 365 err = mailimf_fields_add( fields, xmailer );
366 if ( err != MAILIMF_NO_ERROR ) { 366 if ( err != MAILIMF_NO_ERROR ) {
367 res = 0; 367 res = 0;
368 } 368 }
369 } 369 }
370 if (!res ) { 370 if (!res ) {
371 if (xmailer) { 371 if (xmailer) {
372 mailimf_field_free( xmailer ); 372 mailimf_field_free( xmailer );
373 xmailer = NULL; 373 xmailer = NULL;
374 } 374 }
375 if (fields) { 375 if (fields) {
376 mailimf_fields_free( fields ); 376 mailimf_fields_free( fields );
377 fields = NULL; 377 fields = NULL;
378 } else { 378 } else {
379 if (reply) 379 if (reply)
380 mailimf_address_list_free( reply ); 380 mailimf_address_list_free( reply );
381 if (bcc) 381 if (bcc)
382 mailimf_address_list_free( bcc ); 382 mailimf_address_list_free( bcc );
383 if (cc) 383 if (cc)
384 mailimf_address_list_free( cc ); 384 mailimf_address_list_free( cc );
385 if (to) 385 if (to)
386 mailimf_address_list_free( to ); 386 mailimf_address_list_free( to );
387 if (fromBox) { 387 if (fromBox) {
388 mailimf_mailbox_free( fromBox ); 388 mailimf_mailbox_free( fromBox );
389 } else if (from) { 389 } else if (from) {
390 mailimf_mailbox_list_free( from ); 390 mailimf_mailbox_list_free( from );
391 } 391 }
392 if (sender) { 392 if (sender) {
393 mailimf_mailbox_free( sender ); 393 mailimf_mailbox_free( sender );
394 } 394 }
395 if (subject) { 395 if (subject) {
396 free( subject ); 396 free( subject );
397 } 397 }
398 } 398 }
399 } 399 }
400 return fields; 400 return fields;
401} 401}
402 402
403mailmime *Generatemail::createMimeMail(const Opie::Core::OSmartPointer<Mail> &mail ) { 403mailmime *Generatemail::createMimeMail(const Opie::Core::OSmartPointer<Mail> &mail ) {
404 mailmime *message, *txtPart; 404 mailmime *message, *txtPart;
405 mailimf_fields *fields; 405 mailimf_fields *fields;
406 int err; 406 int err;
407 407
408 fields = createImfFields( mail ); 408 fields = createImfFields( mail );
409 if ( fields == NULL ) 409 if ( fields == NULL )
410 goto err_free; 410 goto err_free;
411 411
412 message = mailmime_new_message_data( NULL ); 412 message = mailmime_new_message_data( NULL );
413 if ( message == NULL ) 413 if ( message == NULL )
414 goto err_free_fields; 414 goto err_free_fields;
415 415
416 mailmime_set_imf_fields( message, fields ); 416 mailmime_set_imf_fields( message, fields );
417 417
418 txtPart = buildTxtPart( mail->getMessage() ); 418 txtPart = buildTxtPart( mail->getMessage() );
419 419
420 if ( txtPart == NULL ) 420 if ( txtPart == NULL )
421 goto err_free_message; 421 goto err_free_message;
422 422
423 err = mailmime_smart_add_part( message, txtPart ); 423 err = mailmime_smart_add_part( message, txtPart );
424 if ( err != MAILIMF_NO_ERROR ) 424 if ( err != MAILIMF_NO_ERROR )
425 goto err_free_txtPart; 425 goto err_free_txtPart;
426 426
427 addFileParts( message, mail->getAttachments() ); 427 addFileParts( message, mail->getAttachments() );
428 428
429 return message; // Success :) 429 return message; // Success :)
430 430
431err_free_txtPart: 431err_free_txtPart:
432 mailmime_free( txtPart ); 432 mailmime_free( txtPart );
433err_free_message: 433err_free_message:
434 mailmime_free( message ); 434 mailmime_free( message );
435err_free_fields: 435err_free_fields:
436 mailimf_fields_free( fields ); 436 mailimf_fields_free( fields );
437err_free: 437err_free:
438 qDebug( "createMimeMail: error" ); 438 odebug << "createMimeMail: error" << oendl;
439 439
440 return NULL; // Error :( 440 return NULL; // Error :(
441} 441}
442 442
443clist *Generatemail::createRcptList( mailimf_fields *fields ) { 443clist *Generatemail::createRcptList( mailimf_fields *fields ) {
444 clist *rcptList; 444 clist *rcptList;
445 mailimf_field *field; 445 mailimf_field *field;
446 446
447 rcptList = esmtp_address_list_new(); 447 rcptList = esmtp_address_list_new();
448 448
449 field = getField( fields, MAILIMF_FIELD_TO ); 449 field = getField( fields, MAILIMF_FIELD_TO );
450 if ( field && (field->fld_type == MAILIMF_FIELD_TO) 450 if ( field && (field->fld_type == MAILIMF_FIELD_TO)
451 && field->fld_data.fld_to->to_addr_list ) { 451 && field->fld_data.fld_to->to_addr_list ) {
452 addRcpts( rcptList, field->fld_data.fld_to->to_addr_list ); 452 addRcpts( rcptList, field->fld_data.fld_to->to_addr_list );
453 } 453 }
454 454
455 field = getField( fields, MAILIMF_FIELD_CC ); 455 field = getField( fields, MAILIMF_FIELD_CC );
456 if ( field && (field->fld_type == MAILIMF_FIELD_CC) 456 if ( field && (field->fld_type == MAILIMF_FIELD_CC)
457 && field->fld_data.fld_cc->cc_addr_list ) { 457 && field->fld_data.fld_cc->cc_addr_list ) {
458 addRcpts( rcptList, field->fld_data.fld_cc->cc_addr_list ); 458 addRcpts( rcptList, field->fld_data.fld_cc->cc_addr_list );
459 } 459 }
460 460
461 field = getField( fields, MAILIMF_FIELD_BCC ); 461 field = getField( fields, MAILIMF_FIELD_BCC );
462 if ( field && (field->fld_type == MAILIMF_FIELD_BCC) 462 if ( field && (field->fld_type == MAILIMF_FIELD_BCC)
463 && field->fld_data.fld_bcc->bcc_addr_list ) { 463 && field->fld_data.fld_bcc->bcc_addr_list ) {
464 addRcpts( rcptList, field->fld_data.fld_bcc->bcc_addr_list ); 464 addRcpts( rcptList, field->fld_data.fld_bcc->bcc_addr_list );
465 } 465 }
466 466
467 return rcptList; 467 return rcptList;
468} 468}
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)
42 target->setSubtype("plain"); 42 target->setSubtype("plain");
43 } else { 43 } else {
44 target->setSubtype(type->ct_subtype); 44 target->setSubtype(type->ct_subtype);
45 switch(type->ct_type->tp_data.tp_discrete_type->dt_type) { 45 switch(type->ct_type->tp_data.tp_discrete_type->dt_type) {
46 case MAILMIME_DISCRETE_TYPE_TEXT: 46 case MAILMIME_DISCRETE_TYPE_TEXT:
47 target->setType("text"); 47 target->setType("text");
48 break; 48 break;
49 case MAILMIME_DISCRETE_TYPE_IMAGE: 49 case MAILMIME_DISCRETE_TYPE_IMAGE:
50 target->setType("image"); 50 target->setType("image");
51 break; 51 break;
52 case MAILMIME_DISCRETE_TYPE_AUDIO: 52 case MAILMIME_DISCRETE_TYPE_AUDIO:
53 target->setType("audio"); 53 target->setType("audio");
54 break; 54 break;
55 case MAILMIME_DISCRETE_TYPE_VIDEO: 55 case MAILMIME_DISCRETE_TYPE_VIDEO:
56 target->setType("video"); 56 target->setType("video");
57 break; 57 break;
58 case MAILMIME_DISCRETE_TYPE_APPLICATION: 58 case MAILMIME_DISCRETE_TYPE_APPLICATION:
59 target->setType("application"); 59 target->setType("application");
60 break; 60 break;
61 case MAILMIME_DISCRETE_TYPE_EXTENSION: 61 case MAILMIME_DISCRETE_TYPE_EXTENSION:
62 default: 62 default:
63 if (type->ct_type->tp_data.tp_discrete_type->dt_extension) { 63 if (type->ct_type->tp_data.tp_discrete_type->dt_extension) {
64 target->setType(type->ct_type->tp_data.tp_discrete_type->dt_extension); 64 target->setType(type->ct_type->tp_data.tp_discrete_type->dt_extension);
65 } 65 }
66 break; 66 break;
67 } 67 }
68 if (type->ct_parameters) { 68 if (type->ct_parameters) {
69 fillParameters(target,type->ct_parameters); 69 fillParameters(target,type->ct_parameters);
70 } 70 }
71 } 71 }
72 if (mime->mm_mime_fields && mime->mm_mime_fields->fld_list) { 72 if (mime->mm_mime_fields && mime->mm_mime_fields->fld_list) {
73 for (current=clist_begin(mime->mm_mime_fields->fld_list);current!=0;current=clist_next(current)) { 73 for (current=clist_begin(mime->mm_mime_fields->fld_list);current!=0;current=clist_next(current)) {
74 field = (mailmime_field*)current->data; 74 field = (mailmime_field*)current->data;
75 switch(field->fld_type) { 75 switch(field->fld_type) {
76 case MAILMIME_FIELD_TRANSFER_ENCODING: 76 case MAILMIME_FIELD_TRANSFER_ENCODING:
77 target->setEncoding(getencoding(field->fld_data.fld_encoding)); 77 target->setEncoding(getencoding(field->fld_data.fld_encoding));
78 break; 78 break;
79 case MAILMIME_FIELD_ID: 79 case MAILMIME_FIELD_ID:
80 target->setIdentifier(field->fld_data.fld_id); 80 target->setIdentifier(field->fld_data.fld_id);
81 break; 81 break;
82 case MAILMIME_FIELD_DESCRIPTION: 82 case MAILMIME_FIELD_DESCRIPTION:
83 target->setDescription(field->fld_data.fld_description); 83 target->setDescription(field->fld_data.fld_description);
84 break; 84 break;
85 default: 85 default:
86 break; 86 break;
87 } 87 }
88 } 88 }
89 } 89 }
90} 90}
91 91
92void Genericwrapper::fillParameters(RecPartP&target,clist*parameters) 92void Genericwrapper::fillParameters(RecPartP&target,clist*parameters)
93{ 93{
94 if (!parameters) {return;} 94 if (!parameters) {return;}
95 clistcell*current=0; 95 clistcell*current=0;
96 mailmime_parameter*param; 96 mailmime_parameter*param;
97 for (current=clist_begin(parameters);current!=0;current=clist_next(current)) { 97 for (current=clist_begin(parameters);current!=0;current=clist_next(current)) {
98 param = (mailmime_parameter*)current->data; 98 param = (mailmime_parameter*)current->data;
99 if (param) { 99 if (param) {
100 target->addParameter(QString(param->pa_name).lower(),QString(param->pa_value)); 100 target->addParameter(QString(param->pa_name).lower(),QString(param->pa_value));
101 } 101 }
102 } 102 }
103} 103}
104 104
105QString Genericwrapper::getencoding(mailmime_mechanism*aEnc) 105QString Genericwrapper::getencoding(mailmime_mechanism*aEnc)
106{ 106{
107 QString enc="7bit"; 107 QString enc="7bit";
108 if (!aEnc) return enc; 108 if (!aEnc) return enc;
109 switch(aEnc->enc_type) { 109 switch(aEnc->enc_type) {
110 case MAILMIME_MECHANISM_7BIT: 110 case MAILMIME_MECHANISM_7BIT:
111 enc = "7bit"; 111 enc = "7bit";
112 break; 112 break;
113 case MAILMIME_MECHANISM_8BIT: 113 case MAILMIME_MECHANISM_8BIT:
114 enc = "8bit"; 114 enc = "8bit";
115 break; 115 break;
116 case MAILMIME_MECHANISM_BINARY: 116 case MAILMIME_MECHANISM_BINARY:
117 enc = "binary"; 117 enc = "binary";
118 break; 118 break;
119 case MAILMIME_MECHANISM_QUOTED_PRINTABLE: 119 case MAILMIME_MECHANISM_QUOTED_PRINTABLE:
120 enc = "quoted-printable"; 120 enc = "quoted-printable";
121 break; 121 break;
122 case MAILMIME_MECHANISM_BASE64: 122 case MAILMIME_MECHANISM_BASE64:
123 enc = "base64"; 123 enc = "base64";
124 break; 124 break;
125 case MAILMIME_MECHANISM_TOKEN: 125 case MAILMIME_MECHANISM_TOKEN:
126 default: 126 default:
127 if (aEnc->enc_token) { 127 if (aEnc->enc_token) {
128 enc = QString(aEnc->enc_token); 128 enc = QString(aEnc->enc_token);
129 } 129 }
130 break; 130 break;
131 } 131 }
132 return enc; 132 return enc;
133} 133}
134 134
135void Genericwrapper::traverseBody(RecBodyP&target,mailmessage*message,mailmime*mime,QValueList<int>recList,unsigned int current_rec,int current_count) 135void Genericwrapper::traverseBody(RecBodyP&target,mailmessage*message,mailmime*mime,QValueList<int>recList,unsigned int current_rec,int current_count)
136{ 136{
137 if (current_rec >= 10) { 137 if (current_rec >= 10) {
138 qDebug("too deep recursion!"); 138 odebug << "too deep recursion!" << oendl;
139 } 139 }
140 if (!message || !mime) { 140 if (!message || !mime) {
141 return; 141 return;
142 } 142 }
143 int r; 143 int r;
144 char*data = 0; 144 char*data = 0;
145 size_t len; 145 size_t len;
146 clistiter * cur = 0; 146 clistiter * cur = 0;
147 QString b; 147 QString b;
148 RecPartP part = new RecPart(); 148 RecPartP part = new RecPart();
149 149
150 switch (mime->mm_type) { 150 switch (mime->mm_type) {
151 case MAILMIME_SINGLE: 151 case MAILMIME_SINGLE:
152 { 152 {
153 QValueList<int>countlist = recList; 153 QValueList<int>countlist = recList;
154 countlist.append(current_count); 154 countlist.append(current_count);
155 r = mailmessage_fetch_section(message,mime,&data,&len); 155 r = mailmessage_fetch_section(message,mime,&data,&len);
156 part->setSize(len); 156 part->setSize(len);
157 part->setPositionlist(countlist); 157 part->setPositionlist(countlist);
158 b = gen_attachment_id(); 158 b = gen_attachment_id();
159 part->setIdentifier(b); 159 part->setIdentifier(b);
160 fillSingleBody(part,message,mime); 160 fillSingleBody(part,message,mime);
161 if (part->Type()=="text" && target->Bodytext().isNull()) { 161 if (part->Type()=="text" && target->Bodytext().isNull()) {
162 encodedString*rs = new encodedString(); 162 encodedString*rs = new encodedString();
163 rs->setContent(data,len); 163 rs->setContent(data,len);
164 encodedString*res = decode_String(rs,part->Encoding()); 164 encodedString*res = decode_String(rs,part->Encoding());
165 if (countlist.count()>2) { 165 if (countlist.count()>2) {
166 bodyCache[b]=rs; 166 bodyCache[b]=rs;
167 target->addPart(part); 167 target->addPart(part);
168 } else { 168 } else {
169 delete rs; 169 delete rs;
170 } 170 }
171 b = QString(res->Content()); 171 b = QString(res->Content());
172 delete res; 172 delete res;
173 target->setBodytext(b); 173 target->setBodytext(b);
174 target->setDescription(part); 174 target->setDescription(part);
175 } else { 175 } else {
176 bodyCache[b]=new encodedString(data,len); 176 bodyCache[b]=new encodedString(data,len);
177 target->addPart(part); 177 target->addPart(part);
178 } 178 }
179 } 179 }
180 break; 180 break;
181 case MAILMIME_MULTIPLE: 181 case MAILMIME_MULTIPLE:
182 { 182 {
183 unsigned int ccount = 1; 183 unsigned int ccount = 1;
184 mailmime*cbody=0; 184 mailmime*cbody=0;
185 QValueList<int>countlist = recList; 185 QValueList<int>countlist = recList;
186 for (cur = clist_begin(mime->mm_data.mm_multipart.mm_mp_list) ; cur != NULL ; cur = clist_next(cur)) { 186 for (cur = clist_begin(mime->mm_data.mm_multipart.mm_mp_list) ; cur != NULL ; cur = clist_next(cur)) {
187 cbody = (mailmime*)clist_content(cur); 187 cbody = (mailmime*)clist_content(cur);
188 if (cbody->mm_type==MAILMIME_MULTIPLE) { 188 if (cbody->mm_type==MAILMIME_MULTIPLE) {
189 RecPartP targetPart = new RecPart(); 189 RecPartP targetPart = new RecPart();
190 targetPart->setType("multipart"); 190 targetPart->setType("multipart");
191 countlist.append(current_count); 191 countlist.append(current_count);
192 targetPart->setPositionlist(countlist); 192 targetPart->setPositionlist(countlist);
193 target->addPart(targetPart); 193 target->addPart(targetPart);
194 } 194 }
195 traverseBody(target,message, cbody,countlist,current_rec+1,ccount); 195 traverseBody(target,message, cbody,countlist,current_rec+1,ccount);
196 if (cbody->mm_type==MAILMIME_MULTIPLE) { 196 if (cbody->mm_type==MAILMIME_MULTIPLE) {
197 countlist = recList; 197 countlist = recList;
198 } 198 }
199 ++ccount; 199 ++ccount;
200 } 200 }
201 } 201 }
202 break; 202 break;
203 case MAILMIME_MESSAGE: 203 case MAILMIME_MESSAGE:
204 { 204 {
205 QValueList<int>countlist = recList; 205 QValueList<int>countlist = recList;
206 countlist.append(current_count); 206 countlist.append(current_count);
207 /* the own header is always at recursion 0 - we don't need that */ 207 /* the own header is always at recursion 0 - we don't need that */
208 if (current_rec > 0) { 208 if (current_rec > 0) {
209 part->setPositionlist(countlist); 209 part->setPositionlist(countlist);
210 r = mailmessage_fetch_section(message,mime,&data,&len); 210 r = mailmessage_fetch_section(message,mime,&data,&len);
211 part->setSize(len); 211 part->setSize(len);
212 part->setPositionlist(countlist); 212 part->setPositionlist(countlist);
213 b = gen_attachment_id(); 213 b = gen_attachment_id();
214 part->setIdentifier(b); 214 part->setIdentifier(b);
215 part->setType("message"); 215 part->setType("message");
216 part->setSubtype("rfc822"); 216 part->setSubtype("rfc822");
217 bodyCache[b]=new encodedString(data,len); 217 bodyCache[b]=new encodedString(data,len);
218 target->addPart(part); 218 target->addPart(part);
219 } 219 }
220 if (mime->mm_data.mm_message.mm_msg_mime != NULL) { 220 if (mime->mm_data.mm_message.mm_msg_mime != NULL) {
221 traverseBody(target,message,mime->mm_data.mm_message.mm_msg_mime,countlist,current_rec+1); 221 traverseBody(target,message,mime->mm_data.mm_message.mm_msg_mime,countlist,current_rec+1);
222 } 222 }
223 } 223 }
224 break; 224 break;
225 } 225 }
226} 226}
227 227
228RecBodyP Genericwrapper::parseMail( mailmessage * msg ) 228RecBodyP Genericwrapper::parseMail( mailmessage * msg )
229{ 229{
230 int err = MAILIMF_NO_ERROR; 230 int err = MAILIMF_NO_ERROR;
231 mailmime_single_fields fields; 231 mailmime_single_fields fields;
232 /* is bound to msg and will be freed there */ 232 /* is bound to msg and will be freed there */
233 mailmime * mime=0; 233 mailmime * mime=0;
234 RecBodyP body = new RecBody(); 234 RecBodyP body = new RecBody();
235 memset(&fields, 0, sizeof(struct mailmime_single_fields)); 235 memset(&fields, 0, sizeof(struct mailmime_single_fields));
236 err = mailmessage_get_bodystructure(msg,&mime); 236 err = mailmessage_get_bodystructure(msg,&mime);
237 QValueList<int>recList; 237 QValueList<int>recList;
238 traverseBody(body,msg,mime,recList); 238 traverseBody(body,msg,mime,recList);
239 return body; 239 return body;
240} 240}
241 241
242QString Genericwrapper::parseDateTime( mailimf_date_time *date ) 242QString Genericwrapper::parseDateTime( mailimf_date_time *date )
243{ 243{
244 char tmp[23]; 244 char tmp[23];
245 245
246 snprintf( tmp, 23, "%02i.%02i.%04i %02i:%02i:%02i %+05i", 246 snprintf( tmp, 23, "%02i.%02i.%04i %02i:%02i:%02i %+05i",
247 date->dt_day, date->dt_month, date->dt_year, date->dt_hour, date->dt_min, date->dt_sec, date->dt_zone ); 247 date->dt_day, date->dt_month, date->dt_year, date->dt_hour, date->dt_min, date->dt_sec, date->dt_zone );
248 248
249 return QString( tmp ); 249 return QString( tmp );
250} 250}
251 251
252QString Genericwrapper::parseAddressList( mailimf_address_list *list ) 252QString Genericwrapper::parseAddressList( mailimf_address_list *list )
253{ 253{
254 QString result( "" ); 254 QString result( "" );
255 255
256 bool first = true; 256 bool first = true;
257 if (list == 0) return result; 257 if (list == 0) return result;
258 for ( clistiter *current = clist_begin( list->ad_list ); current != NULL; current = current->next ) { 258 for ( clistiter *current = clist_begin( list->ad_list ); current != NULL; current = current->next ) {
259 mailimf_address *addr = (mailimf_address *) current->data; 259 mailimf_address *addr = (mailimf_address *) current->data;
260 260
261 if ( !first ) { 261 if ( !first ) {
262 result.append( "," ); 262 result.append( "," );
263 } else { 263 } else {
264 first = false; 264 first = false;
265 } 265 }
266 266
267 switch ( addr->ad_type ) { 267 switch ( addr->ad_type ) {
268 case MAILIMF_ADDRESS_MAILBOX: 268 case MAILIMF_ADDRESS_MAILBOX:
269 result.append( parseMailbox( addr->ad_data.ad_mailbox ) ); 269 result.append( parseMailbox( addr->ad_data.ad_mailbox ) );
270 break; 270 break;
271 case MAILIMF_ADDRESS_GROUP: 271 case MAILIMF_ADDRESS_GROUP:
272 result.append( parseGroup( addr->ad_data.ad_group ) ); 272 result.append( parseGroup( addr->ad_data.ad_group ) );
273 break; 273 break;
274 default: 274 default:
275 qDebug( "Generic: unkown mailimf address type" ); 275 odebug << "Generic: unkown mailimf address type" << oendl;
276 break; 276 break;
277 } 277 }
278 } 278 }
279 279
280 return result; 280 return result;
281} 281}
282 282
283QString Genericwrapper::parseGroup( mailimf_group *group ) 283QString Genericwrapper::parseGroup( mailimf_group *group )
284{ 284{
285 QString result( "" ); 285 QString result( "" );
286 286
287 result.append( group->grp_display_name ); 287 result.append( group->grp_display_name );
288 result.append( ": " ); 288 result.append( ": " );
289 289
290 if ( group->grp_mb_list != NULL ) { 290 if ( group->grp_mb_list != NULL ) {
291 result.append( parseMailboxList( group->grp_mb_list ) ); 291 result.append( parseMailboxList( group->grp_mb_list ) );
292 } 292 }
293 293
294 result.append( ";" ); 294 result.append( ";" );
295 295
296 return result; 296 return result;
297} 297}
298 298
299QString Genericwrapper::parseMailbox( mailimf_mailbox *box ) 299QString Genericwrapper::parseMailbox( mailimf_mailbox *box )
300{ 300{
301 QString result( "" ); 301 QString result( "" );
302 302
303 if ( box->mb_display_name == NULL ) { 303 if ( box->mb_display_name == NULL ) {
304 result.append( box->mb_addr_spec ); 304 result.append( box->mb_addr_spec );
305 } else { 305 } else {
306 result.append( convert_String(box->mb_display_name).latin1() ); 306 result.append( convert_String(box->mb_display_name).latin1() );
307 result.append( " <" ); 307 result.append( " <" );
308 result.append( box->mb_addr_spec ); 308 result.append( box->mb_addr_spec );
309 result.append( ">" ); 309 result.append( ">" );
310 } 310 }
311 311
312 return result; 312 return result;
313} 313}
314 314
315QString Genericwrapper::parseMailboxList( mailimf_mailbox_list *list ) 315QString Genericwrapper::parseMailboxList( mailimf_mailbox_list *list )
316{ 316{
317 QString result( "" ); 317 QString result( "" );
318 318
319 bool first = true; 319 bool first = true;
320 for ( clistiter *current = clist_begin( list->mb_list ); current != NULL; current = current->next ) { 320 for ( clistiter *current = clist_begin( list->mb_list ); current != NULL; current = current->next ) {
321 mailimf_mailbox *box = (mailimf_mailbox *) current->data; 321 mailimf_mailbox *box = (mailimf_mailbox *) current->data;
322 322
323 if ( !first ) { 323 if ( !first ) {
324 result.append( "," ); 324 result.append( "," );
325 } else { 325 } else {
326 first = false; 326 first = false;
327 } 327 }
328 328
329 result.append( parseMailbox( box ) ); 329 result.append( parseMailbox( box ) );
330 } 330 }
331 331
332 return result; 332 return result;
333} 333}
334 334
335encodedString* Genericwrapper::fetchDecodedPart(const RecMailP&,const RecPartP&part) 335encodedString* Genericwrapper::fetchDecodedPart(const RecMailP&,const RecPartP&part)
336{ 336{
337 QMap<QString,encodedString*>::ConstIterator it = bodyCache.find(part->Identifier()); 337 QMap<QString,encodedString*>::ConstIterator it = bodyCache.find(part->Identifier());
338 if (it==bodyCache.end()) return new encodedString(); 338 if (it==bodyCache.end()) return new encodedString();
339 encodedString*t = decode_String(it.data(),part->Encoding()); 339 encodedString*t = decode_String(it.data(),part->Encoding());
340 return t; 340 return t;
341} 341}
342 342
343encodedString* Genericwrapper::fetchRawPart(const RecMailP&,const RecPartP&part) 343encodedString* Genericwrapper::fetchRawPart(const RecMailP&,const RecPartP&part)
344{ 344{
345 QMap<QString,encodedString*>::ConstIterator it = bodyCache.find(part->Identifier()); 345 QMap<QString,encodedString*>::ConstIterator it = bodyCache.find(part->Identifier());
346 if (it==bodyCache.end()) return new encodedString(); 346 if (it==bodyCache.end()) return new encodedString();
347 encodedString*t = it.data(); 347 encodedString*t = it.data();
348 return t; 348 return t;
349} 349}
350 350
351QString Genericwrapper::fetchTextPart(const RecMailP&mail,const RecPartP&part) 351QString Genericwrapper::fetchTextPart(const RecMailP&mail,const RecPartP&part)
352{ 352{
353 encodedString*t = fetchDecodedPart(mail,part); 353 encodedString*t = fetchDecodedPart(mail,part);
354 QString text=t->Content(); 354 QString text=t->Content();
355 delete t; 355 delete t;
356 return text; 356 return text;
357} 357}
358 358
359void Genericwrapper::cleanMimeCache() 359void Genericwrapper::cleanMimeCache()
360{ 360{
361 QMap<QString,encodedString*>::Iterator it = bodyCache.begin(); 361 QMap<QString,encodedString*>::Iterator it = bodyCache.begin();
362 for (;it!=bodyCache.end();++it) { 362 for (;it!=bodyCache.end();++it) {
363 encodedString*t = it.data(); 363 encodedString*t = it.data();
364 //it.setValue(0); 364 //it.setValue(0);
365 if (t) delete t; 365 if (t) delete t;
366 } 366 }
367 bodyCache.clear(); 367 bodyCache.clear();
368 qDebug("Genericwrapper: cache cleaned"); 368 odebug << "Genericwrapper: cache cleaned" << oendl;
369} 369}
370 370
371QStringList Genericwrapper::parseInreplies(mailimf_in_reply_to * in_replies) 371QStringList Genericwrapper::parseInreplies(mailimf_in_reply_to * in_replies)
372{ 372{
373 QStringList res; 373 QStringList res;
374 if (!in_replies || !in_replies->mid_list) return res; 374 if (!in_replies || !in_replies->mid_list) return res;
375 clistiter * current = 0; 375 clistiter * current = 0;
376 for ( current = clist_begin( in_replies->mid_list ); current != NULL; current = current->next ) { 376 for ( current = clist_begin( in_replies->mid_list ); current != NULL; current = current->next ) {
377 QString h((char*)current->data); 377 QString h((char*)current->data);
378 while (h.length()>0 && h[0]=='<') { 378 while (h.length()>0 && h[0]=='<') {
379 h.remove(0,1); 379 h.remove(0,1);
380 } 380 }
381 while (h.length()>0 && h[h.length()-1]=='>') { 381 while (h.length()>0 && h[h.length()-1]=='>') {
382 h.remove(h.length()-1,1); 382 h.remove(h.length()-1,1);
383 } 383 }
384 if (h.length()>0) { 384 if (h.length()>0) {
385 res.append(h); 385 res.append(h);
386 } 386 }
387 } 387 }
388 return res; 388 return res;
389} 389}
390 390
391void Genericwrapper::parseList(QValueList<Opie::Core::OSmartPointer<RecMail> > &target,mailsession*session,const QString&mailbox,bool mbox_as_to) 391void Genericwrapper::parseList(QValueList<Opie::Core::OSmartPointer<RecMail> > &target,mailsession*session,const QString&mailbox,bool mbox_as_to)
392{ 392{
393 int r; 393 int r;
394 mailmessage_list * env_list = 0; 394 mailmessage_list * env_list = 0;
395 r = mailsession_get_messages_list(session,&env_list); 395 r = mailsession_get_messages_list(session,&env_list);
396 if (r != MAIL_NO_ERROR) { 396 if (r != MAIL_NO_ERROR) {
397 qDebug("Error message list"); 397 odebug << "Error message list" << oendl;
398 return; 398 return;
399 } 399 }
400 r = mailsession_get_envelopes_list(session, env_list); 400 r = mailsession_get_envelopes_list(session, env_list);
401 if (r != MAIL_NO_ERROR) { 401 if (r != MAIL_NO_ERROR) {
402 qDebug("Error filling message list"); 402 odebug << "Error filling message list" << oendl;
403 if (env_list) { 403 if (env_list) {
404 mailmessage_list_free(env_list); 404 mailmessage_list_free(env_list);
405 } 405 }
406 return; 406 return;
407 } 407 }
408 mailimf_references * refs = 0; 408 mailimf_references * refs = 0;
409 mailimf_in_reply_to * in_replies = 0; 409 mailimf_in_reply_to * in_replies = 0;
410 uint32_t i = 0; 410 uint32_t i = 0;
411 for(; i < carray_count(env_list->msg_tab) ; ++i) { 411 for(; i < carray_count(env_list->msg_tab) ; ++i) {
412 mailmessage * msg; 412 mailmessage * msg;
413 QBitArray mFlags(7); 413 QBitArray mFlags(7);
414 msg = (mailmessage*)carray_get(env_list->msg_tab, i); 414 msg = (mailmessage*)carray_get(env_list->msg_tab, i);
415 if (msg->msg_fields == NULL) { 415 if (msg->msg_fields == NULL) {
416 //qDebug("could not fetch envelope of message %i", i); 416 //odebug << "could not fetch envelope of message " << i << "" << oendl;
417 continue; 417 continue;
418 } 418 }
419 RecMailP mail = new RecMail(); 419 RecMailP mail = new RecMail();
420 mail->setWrapper(this); 420 mail->setWrapper(this);
421 mail_flags * flag_result = 0; 421 mail_flags * flag_result = 0;
422 r = mailmessage_get_flags(msg,&flag_result); 422 r = mailmessage_get_flags(msg,&flag_result);
423 if (r == MAIL_ERROR_NOT_IMPLEMENTED) { 423 if (r == MAIL_ERROR_NOT_IMPLEMENTED) {
424 mFlags.setBit(FLAG_SEEN); 424 mFlags.setBit(FLAG_SEEN);
425 } 425 }
426 mailimf_single_fields single_fields; 426 mailimf_single_fields single_fields;
427 mailimf_single_fields_init(&single_fields, msg->msg_fields); 427 mailimf_single_fields_init(&single_fields, msg->msg_fields);
428 mail->setMsgsize(msg->msg_size); 428 mail->setMsgsize(msg->msg_size);
429 mail->setFlags(mFlags); 429 mail->setFlags(mFlags);
430 mail->setMbox(mailbox); 430 mail->setMbox(mailbox);
431 mail->setNumber(msg->msg_index); 431 mail->setNumber(msg->msg_index);
432 if (single_fields.fld_subject) 432 if (single_fields.fld_subject)
433 mail->setSubject( convert_String(single_fields.fld_subject->sbj_value)); 433 mail->setSubject( convert_String(single_fields.fld_subject->sbj_value));
434 if (single_fields.fld_from) 434 if (single_fields.fld_from)
435 mail->setFrom(parseMailboxList(single_fields.fld_from->frm_mb_list)); 435 mail->setFrom(parseMailboxList(single_fields.fld_from->frm_mb_list));
436 if (!mbox_as_to) { 436 if (!mbox_as_to) {
437 if (single_fields.fld_to) 437 if (single_fields.fld_to)
438 mail->setTo( parseAddressList( single_fields.fld_to->to_addr_list ) ); 438 mail->setTo( parseAddressList( single_fields.fld_to->to_addr_list ) );
439 } else { 439 } else {
440 mail->setTo(mailbox); 440 mail->setTo(mailbox);
441 } 441 }
442 if (single_fields.fld_cc) 442 if (single_fields.fld_cc)
443 mail->setCC( parseAddressList( single_fields.fld_cc->cc_addr_list ) ); 443 mail->setCC( parseAddressList( single_fields.fld_cc->cc_addr_list ) );
444 if (single_fields.fld_bcc) 444 if (single_fields.fld_bcc)
445 mail->setBcc( parseAddressList( single_fields.fld_bcc->bcc_addr_list ) ); 445 mail->setBcc( parseAddressList( single_fields.fld_bcc->bcc_addr_list ) );
446 if (single_fields.fld_orig_date) 446 if (single_fields.fld_orig_date)
447 mail->setDate( parseDateTime( single_fields.fld_orig_date->dt_date_time ) ); 447 mail->setDate( parseDateTime( single_fields.fld_orig_date->dt_date_time ) );
448 // crashes when accessing pop3 account? 448 // crashes when accessing pop3 account?
449 if (single_fields.fld_message_id->mid_value) { 449 if (single_fields.fld_message_id->mid_value) {
450 mail->setMsgid(QString(single_fields.fld_message_id->mid_value)); 450 mail->setMsgid(QString(single_fields.fld_message_id->mid_value));
451 qDebug("Msgid == %s",mail->Msgid().latin1()); 451 odebug << "Msgid == " << mail->Msgid().latin1() << "" << oendl;
452 } 452 }
453 453
454 if (single_fields.fld_reply_to) { 454 if (single_fields.fld_reply_to) {
455 QStringList t = parseAddressList(single_fields.fld_reply_to->rt_addr_list); 455 QStringList t = parseAddressList(single_fields.fld_reply_to->rt_addr_list);
456 if (t.count()>0) { 456 if (t.count()>0) {
457 mail->setReplyto(t[0]); 457 mail->setReplyto(t[0]);
458 } 458 }
459 } 459 }
460#if 0 460#if 0
461 refs = single_fields.fld_references; 461 refs = single_fields.fld_references;
462 if (refs && refs->mid_list && clist_count(refs->mid_list)) { 462 if (refs && refs->mid_list && clist_count(refs->mid_list)) {
463 char * text = (char*)refs->mid_list->first->data; 463 char * text = (char*)refs->mid_list->first->data;
464 mail->setReplyto(QString(text)); 464 mail->setReplyto(QString(text));
465 } 465 }
466#endif 466#endif
467 if (single_fields.fld_in_reply_to && single_fields.fld_in_reply_to->mid_list && 467 if (single_fields.fld_in_reply_to && single_fields.fld_in_reply_to->mid_list &&
468 clist_count(single_fields.fld_in_reply_to->mid_list)) { 468 clist_count(single_fields.fld_in_reply_to->mid_list)) {
469 mail->setInreply(parseInreplies(single_fields.fld_in_reply_to)); 469 mail->setInreply(parseInreplies(single_fields.fld_in_reply_to));
470 } 470 }
471 target.append(mail); 471 target.append(mail);
472 } 472 }
473 if (env_list) { 473 if (env_list) {
474 mailmessage_list_free(env_list); 474 mailmessage_list_free(env_list);
475 } 475 }
476} 476}
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 @@
1#include <stdlib.h> 1#include <stdlib.h>
2#include <libetpan/libetpan.h> 2#include <libetpan/libetpan.h>
3#include <qpe/global.h> 3#include <qpe/global.h>
4#include <opie2/oapplication.h> 4#include <opie2/oapplication.h>
5 5
6#include "imapwrapper.h" 6#include "imapwrapper.h"
7#include "mailtypes.h" 7#include "mailtypes.h"
8#include "logindialog.h" 8#include "logindialog.h"
9 9
10using namespace Opie::Core; 10using namespace Opie::Core;
11IMAPwrapper::IMAPwrapper( IMAPaccount *a ) 11IMAPwrapper::IMAPwrapper( IMAPaccount *a )
12 : AbstractMail() 12 : AbstractMail()
13{ 13{
14 account = a; 14 account = a;
15 m_imap = 0; 15 m_imap = 0;
16 m_Lastmbox = ""; 16 m_Lastmbox = "";
17} 17}
18 18
19IMAPwrapper::~IMAPwrapper() 19IMAPwrapper::~IMAPwrapper()
20{ 20{
21 logout(); 21 logout();
22} 22}
23 23
24/* to avoid to often select statements in loops etc. 24/* to avoid to often select statements in loops etc.
25 we trust that we are logged in and connection is established!*/ 25 we trust that we are logged in and connection is established!*/
26int IMAPwrapper::selectMbox(const QString&mbox) 26int IMAPwrapper::selectMbox(const QString&mbox)
27{ 27{
28 if (mbox == m_Lastmbox) { 28 if (mbox == m_Lastmbox) {
29 return MAILIMAP_NO_ERROR; 29 return MAILIMAP_NO_ERROR;
30 } 30 }
31 int err = mailimap_select( m_imap, (char*)mbox.latin1()); 31 int err = mailimap_select( m_imap, (char*)mbox.latin1());
32 if ( err != MAILIMAP_NO_ERROR ) { 32 if ( err != MAILIMAP_NO_ERROR ) {
33 qDebug("error selecting mailbox: %s",m_imap->imap_response); 33 odebug << "error selecting mailbox: " << m_imap->imap_response << "" << oendl;
34 m_Lastmbox = ""; 34 m_Lastmbox = "";
35 return err; 35 return err;
36 } 36 }
37 m_Lastmbox = mbox; 37 m_Lastmbox = mbox;
38 return err; 38 return err;
39} 39}
40 40
41void IMAPwrapper::imap_progress( size_t current, size_t maximum ) 41void IMAPwrapper::imap_progress( size_t current, size_t maximum )
42{ 42{
43 qApp->processEvents(); 43 qApp->processEvents();
44 qDebug( "IMAP: %i of %i", current, maximum ); 44 odebug << "IMAP: " << current << " of " << maximum << "" << oendl;
45} 45}
46 46
47bool IMAPwrapper::start_tls(bool force_tls) 47bool IMAPwrapper::start_tls(bool force_tls)
48{ 48{
49 int err; 49 int err;
50 bool try_tls; 50 bool try_tls;
51 mailimap_capability_data * cap_data = 0; 51 mailimap_capability_data * cap_data = 0;
52 52
53 err = mailimap_capability(m_imap,&cap_data); 53 err = mailimap_capability(m_imap,&cap_data);
54 if (err != MAILIMAP_NO_ERROR) { 54 if (err != MAILIMAP_NO_ERROR) {
55 Global::statusMessage("error getting capabilities!"); 55 Global::statusMessage("error getting capabilities!");
56 qDebug("error getting capabilities!"); 56 odebug << "error getting capabilities!" << oendl;
57 return false; 57 return false;
58 } 58 }
59 clistiter * cur; 59 clistiter * cur;
60 for(cur = clist_begin(cap_data->cap_list) ; cur != NULL;cur = clist_next(cur)) { 60 for(cur = clist_begin(cap_data->cap_list) ; cur != NULL;cur = clist_next(cur)) {
61 struct mailimap_capability * cap; 61 struct mailimap_capability * cap;
62 cap = (struct mailimap_capability *)clist_content(cur); 62 cap = (struct mailimap_capability *)clist_content(cur);
63 if (cap->cap_type == MAILIMAP_CAPABILITY_NAME) { 63 if (cap->cap_type == MAILIMAP_CAPABILITY_NAME) {
64 if (strcasecmp(cap->cap_data.cap_name, "STARTTLS") == 0) { 64 if (strcasecmp(cap->cap_data.cap_name, "STARTTLS") == 0) {
65 try_tls = true; 65 try_tls = true;
66 break; 66 break;
67 } 67 }
68 } 68 }
69 } 69 }
70 if (cap_data) { 70 if (cap_data) {
71 mailimap_capability_data_free(cap_data); 71 mailimap_capability_data_free(cap_data);
72 } 72 }
73 if (try_tls) { 73 if (try_tls) {
74 err = mailimap_starttls(m_imap); 74 err = mailimap_starttls(m_imap);
75 if (err != MAILIMAP_NO_ERROR && force_tls) { 75 if (err != MAILIMAP_NO_ERROR && force_tls) {
76 Global::statusMessage(tr("Server has no TLS support!")); 76 Global::statusMessage(tr("Server has no TLS support!"));
77 qDebug("Server has no TLS support!"); 77 odebug << "Server has no TLS support!" << oendl;
78 try_tls = false; 78 try_tls = false;
79 } else { 79 } else {
80 mailstream_low * low; 80 mailstream_low * low;
81 mailstream_low * new_low; 81 mailstream_low * new_low;
82 low = mailstream_get_low(m_imap->imap_stream); 82 low = mailstream_get_low(m_imap->imap_stream);
83 if (!low) { 83 if (!low) {
84 try_tls = false; 84 try_tls = false;
85 } else { 85 } else {
86 int fd = mailstream_low_get_fd(low); 86 int fd = mailstream_low_get_fd(low);
87 if (fd > -1 && (new_low = mailstream_low_ssl_open(fd))!=0) { 87 if (fd > -1 && (new_low = mailstream_low_ssl_open(fd))!=0) {
88 mailstream_low_free(low); 88 mailstream_low_free(low);
89 mailstream_set_low(m_imap->imap_stream, new_low); 89 mailstream_set_low(m_imap->imap_stream, new_low);
90 } else { 90 } else {
91 try_tls = false; 91 try_tls = false;
92 } 92 }
93 } 93 }
94 } 94 }
95 } 95 }
96 return try_tls; 96 return try_tls;
97} 97}
98 98
99void IMAPwrapper::login() 99void IMAPwrapper::login()
100{ 100{
101 const char *server, *user, *pass; 101 const char *server, *user, *pass;
102 uint16_t port; 102 uint16_t port;
103 int err = MAILIMAP_NO_ERROR; 103 int err = MAILIMAP_NO_ERROR;
104 104
105 if (account->getOffline()) return; 105 if (account->getOffline()) return;
106 /* we are connected this moment */ 106 /* we are connected this moment */
107 /* TODO: setup a timer holding the line or if connection closed - delete the value */ 107 /* TODO: setup a timer holding the line or if connection closed - delete the value */
108 if (m_imap) { 108 if (m_imap) {
109 err = mailimap_noop(m_imap); 109 err = mailimap_noop(m_imap);
110 if (err!=MAILIMAP_NO_ERROR) { 110 if (err!=MAILIMAP_NO_ERROR) {
111 logout(); 111 logout();
112 } else { 112 } else {
113 mailstream_flush(m_imap->imap_stream); 113 mailstream_flush(m_imap->imap_stream);
114 return; 114 return;
115 } 115 }
116 } 116 }
117 server = account->getServer().latin1(); 117 server = account->getServer().latin1();
118 port = account->getPort().toUInt(); 118 port = account->getPort().toUInt();
119 if ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) { 119 if ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) {
120 LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true ); 120 LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true );
121 login.show(); 121 login.show();
122 if ( QDialog::Accepted == login.exec() ) { 122 if ( QDialog::Accepted == login.exec() ) {
123 // ok 123 // ok
124 user = login.getUser().latin1(); 124 user = login.getUser().latin1();
125 pass = login.getPassword().latin1(); 125 pass = login.getPassword().latin1();
126 } else { 126 } else {
127 // cancel 127 // cancel
128 qDebug( "IMAP: Login canceled" ); 128 odebug << "IMAP: Login canceled" << oendl;
129 return; 129 return;
130 } 130 }
131 } else { 131 } else {
132 user = account->getUser().latin1(); 132 user = account->getUser().latin1();
133 pass = account->getPassword().latin1(); 133 pass = account->getPassword().latin1();
134 } 134 }
135 135
136 m_imap = mailimap_new( 20, &imap_progress ); 136 m_imap = mailimap_new( 20, &imap_progress );
137 137
138 /* connect */ 138 /* connect */
139 bool ssl = false; 139 bool ssl = false;
140 bool try_tls = false; 140 bool try_tls = false;
141 bool force_tls = false; 141 bool force_tls = false;
142 142
143 if ( account->ConnectionType() == 2 ) { 143 if ( account->ConnectionType() == 2 ) {
144 ssl = true; 144 ssl = true;
145 } 145 }
146 if (account->ConnectionType()==1) { 146 if (account->ConnectionType()==1) {
147 force_tls = true; 147 force_tls = true;
148 } 148 }
149 149
150 if ( ssl ) { 150 if ( ssl ) {
151 qDebug( "using ssl" ); 151 odebug << "using ssl" << oendl;
152 err = mailimap_ssl_connect( m_imap, (char*)server, port ); 152 err = mailimap_ssl_connect( m_imap, (char*)server, port );
153 } else { 153 } else {
154 err = mailimap_socket_connect( m_imap, (char*)server, port ); 154 err = mailimap_socket_connect( m_imap, (char*)server, port );
155 } 155 }
156 156
157 if ( err != MAILIMAP_NO_ERROR && 157 if ( err != MAILIMAP_NO_ERROR &&
158 err != MAILIMAP_NO_ERROR_AUTHENTICATED && 158 err != MAILIMAP_NO_ERROR_AUTHENTICATED &&
159 err != MAILIMAP_NO_ERROR_NON_AUTHENTICATED ) { 159 err != MAILIMAP_NO_ERROR_NON_AUTHENTICATED ) {
160 QString failure = ""; 160 QString failure = "";
161 if (err == MAILIMAP_ERROR_CONNECTION_REFUSED) { 161 if (err == MAILIMAP_ERROR_CONNECTION_REFUSED) {
162 failure="Connection refused"; 162 failure="Connection refused";
163 } else { 163 } else {
164 failure="Unknown failure"; 164 failure="Unknown failure";
165 } 165 }
166 Global::statusMessage(tr("error connecting imap server: %1").arg(failure)); 166 Global::statusMessage(tr("error connecting imap server: %1").arg(failure));
167 mailimap_free( m_imap ); 167 mailimap_free( m_imap );
168 m_imap = 0; 168 m_imap = 0;
169 return; 169 return;
170 } 170 }
171 171
172 if (!ssl) { 172 if (!ssl) {
173 try_tls = start_tls(force_tls); 173 try_tls = start_tls(force_tls);
174 } 174 }
175 175
176 bool ok = true; 176 bool ok = true;
177 if (force_tls && !try_tls) { 177 if (force_tls && !try_tls) {
178 Global::statusMessage(tr("Server has no TLS support!")); 178 Global::statusMessage(tr("Server has no TLS support!"));
179 qDebug("Server has no TLS support!"); 179 odebug << "Server has no TLS support!" << oendl;
180 ok = false; 180 ok = false;
181 } 181 }
182 182
183 183
184 /* login */ 184 /* login */
185 185
186 if (ok) { 186 if (ok) {
187 err = mailimap_login_simple( m_imap, (char*)user, (char*)pass ); 187 err = mailimap_login_simple( m_imap, (char*)user, (char*)pass );
188 if ( err != MAILIMAP_NO_ERROR ) { 188 if ( err != MAILIMAP_NO_ERROR ) {
189 Global::statusMessage(tr("error logging in imap server: %1").arg(m_imap->imap_response)); 189 Global::statusMessage(tr("error logging in imap server: %1").arg(m_imap->imap_response));
190 ok = false; 190 ok = false;
191 } 191 }
192 } 192 }
193 if (!ok) { 193 if (!ok) {
194 err = mailimap_close( m_imap ); 194 err = mailimap_close( m_imap );
195 mailimap_free( m_imap ); 195 mailimap_free( m_imap );
196 m_imap = 0; 196 m_imap = 0;
197 } 197 }
198} 198}
199 199
200void IMAPwrapper::logout() 200void IMAPwrapper::logout()
201{ 201{
202 int err = MAILIMAP_NO_ERROR; 202 int err = MAILIMAP_NO_ERROR;
203 if (!m_imap) return; 203 if (!m_imap) return;
204 err = mailimap_logout( m_imap ); 204 err = mailimap_logout( m_imap );
205 err = mailimap_close( m_imap ); 205 err = mailimap_close( m_imap );
206 mailimap_free( m_imap ); 206 mailimap_free( m_imap );
207 m_imap = 0; 207 m_imap = 0;
208 m_Lastmbox = ""; 208 m_Lastmbox = "";
209} 209}
210 210
211void IMAPwrapper::listMessages(const QString&mailbox,QValueList<Opie::Core::OSmartPointer<RecMail> > &target ) 211void IMAPwrapper::listMessages(const QString&mailbox,QValueList<Opie::Core::OSmartPointer<RecMail> > &target )
212{ 212{
213 int err = MAILIMAP_NO_ERROR; 213 int err = MAILIMAP_NO_ERROR;
214 clist *result = 0; 214 clist *result = 0;
215 clistcell *current; 215 clistcell *current;
216 mailimap_fetch_type *fetchType = 0; 216 mailimap_fetch_type *fetchType = 0;
217 mailimap_set *set = 0; 217 mailimap_set *set = 0;
218 218
219 login(); 219 login();
220 if (!m_imap) { 220 if (!m_imap) {
221 return; 221 return;
222 } 222 }
223 /* select mailbox READONLY for operations */ 223 /* select mailbox READONLY for operations */
224 err = selectMbox(mailbox); 224 err = selectMbox(mailbox);
225 if ( err != MAILIMAP_NO_ERROR ) { 225 if ( err != MAILIMAP_NO_ERROR ) {
226 return; 226 return;
227 } 227 }
228 228
229 int last = m_imap->imap_selection_info->sel_exists; 229 int last = m_imap->imap_selection_info->sel_exists;
230 230
231 if (last == 0) { 231 if (last == 0) {
232 Global::statusMessage(tr("Mailbox has no mails")); 232 Global::statusMessage(tr("Mailbox has no mails"));
233 return; 233 return;
234 } else { 234 } else {
235 } 235 }
236 236
237 /* the range has to start at 1!!! not with 0!!!! */ 237 /* the range has to start at 1!!! not with 0!!!! */
238 set = mailimap_set_new_interval( 1, last ); 238 set = mailimap_set_new_interval( 1, last );
239 fetchType = mailimap_fetch_type_new_fetch_att_list_empty(); 239 fetchType = mailimap_fetch_type_new_fetch_att_list_empty();
240 mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_envelope()); 240 mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_envelope());
241 mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_flags()); 241 mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_flags());
242 mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_internaldate()); 242 mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_internaldate());
243 mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_rfc822_size()); 243 mailimap_fetch_type_new_fetch_att_list_add(fetchType,mailimap_fetch_att_new_rfc822_size());
244 244
245 err = mailimap_fetch( m_imap, set, fetchType, &result ); 245 err = mailimap_fetch( m_imap, set, fetchType, &result );
246 mailimap_set_free( set ); 246 mailimap_set_free( set );
247 mailimap_fetch_type_free( fetchType ); 247 mailimap_fetch_type_free( fetchType );
248 248
249 QString date,subject,from; 249 QString date,subject,from;
250 250
251 if ( err == MAILIMAP_NO_ERROR ) { 251 if ( err == MAILIMAP_NO_ERROR ) {
252 mailimap_msg_att * msg_att; 252 mailimap_msg_att * msg_att;
253 int i = 0; 253 int i = 0;
254 for (current = clist_begin(result); current != 0; current=clist_next(current)) { 254 for (current = clist_begin(result); current != 0; current=clist_next(current)) {
255 ++i; 255 ++i;
256 msg_att = (mailimap_msg_att*)current->data; 256 msg_att = (mailimap_msg_att*)current->data;
257 RecMail*m = parse_list_result(msg_att); 257 RecMail*m = parse_list_result(msg_att);
258 if (m) { 258 if (m) {
259 m->setNumber(i); 259 m->setNumber(i);
260 m->setMbox(mailbox); 260 m->setMbox(mailbox);
261 m->setWrapper(this); 261 m->setWrapper(this);
262 target.append(m); 262 target.append(m);
263 } 263 }
264 } 264 }
265 Global::statusMessage(tr("Mailbox has %1 mails").arg(target.count())); 265 Global::statusMessage(tr("Mailbox has %1 mails").arg(target.count()));
266 } else { 266 } else {
267 Global::statusMessage(tr("Error fetching headers: %1").arg(m_imap->imap_response)); 267 Global::statusMessage(tr("Error fetching headers: %1").arg(m_imap->imap_response));
268 } 268 }
269 if (result) mailimap_fetch_list_free(result); 269 if (result) mailimap_fetch_list_free(result);
270} 270}
271 271
272QValueList<Opie::Core::OSmartPointer<Folder> >* IMAPwrapper::listFolders() 272QValueList<Opie::Core::OSmartPointer<Folder> >* IMAPwrapper::listFolders()
273{ 273{
274 const char *path, *mask; 274 const char *path, *mask;
275 int err = MAILIMAP_NO_ERROR; 275 int err = MAILIMAP_NO_ERROR;
276 clist *result = 0; 276 clist *result = 0;
277 clistcell *current = 0; 277 clistcell *current = 0;
278 clistcell*cur_flag = 0; 278 clistcell*cur_flag = 0;
279 mailimap_mbx_list_flags*bflags = 0; 279 mailimap_mbx_list_flags*bflags = 0;
280 280
281 QValueList<FolderP>* folders = new QValueList<FolderP>(); 281 QValueList<FolderP>* folders = new QValueList<FolderP>();
282 login(); 282 login();
283 if (!m_imap) { 283 if (!m_imap) {
284 return folders; 284 return folders;
285 } 285 }
286 286
287/* 287/*
288 * First we have to check for INBOX 'cause it sometimes it's not inside the path. 288 * First we have to check for INBOX 'cause it sometimes it's not inside the path.
289 * We must not forget to filter them out in next loop! 289 * We must not forget to filter them out in next loop!
290 * it seems like ugly code. and yes - it is ugly code. but the best way. 290 * it seems like ugly code. and yes - it is ugly code. but the best way.
291 */ 291 */
292 QString temp; 292 QString temp;
293 mask = "INBOX" ; 293 mask = "INBOX" ;
294 mailimap_mailbox_list *list; 294 mailimap_mailbox_list *list;
295 err = mailimap_list( m_imap, (char*)"", (char*)mask, &result ); 295 err = mailimap_list( m_imap, (char*)"", (char*)mask, &result );
296 QString del; 296 QString del;
297 bool selectable = true; 297 bool selectable = true;
298 bool no_inferiors = false; 298 bool no_inferiors = false;
299 if ( err == MAILIMAP_NO_ERROR ) { 299 if ( err == MAILIMAP_NO_ERROR ) {
300 current = result->first; 300 current = result->first;
301 for ( int i = result->count; i > 0; i-- ) { 301 for ( int i = result->count; i > 0; i-- ) {
302 list = (mailimap_mailbox_list *) current->data; 302 list = (mailimap_mailbox_list *) current->data;
303 // it is better use the deep copy mechanism of qt itself 303 // it is better use the deep copy mechanism of qt itself
304 // instead of using strdup! 304 // instead of using strdup!
305 temp = list->mb_name; 305 temp = list->mb_name;
306 del = list->mb_delimiter; 306 del = list->mb_delimiter;
307 current = current->next; 307 current = current->next;
308 if ( (bflags = list->mb_flag) ) { 308 if ( (bflags = list->mb_flag) ) {
309 selectable = !(bflags->mbf_type==MAILIMAP_MBX_LIST_FLAGS_SFLAG&& 309 selectable = !(bflags->mbf_type==MAILIMAP_MBX_LIST_FLAGS_SFLAG&&
310 bflags->mbf_sflag==MAILIMAP_MBX_LIST_SFLAG_NOSELECT); 310 bflags->mbf_sflag==MAILIMAP_MBX_LIST_SFLAG_NOSELECT);
311 for(cur_flag=clist_begin(bflags->mbf_oflags);cur_flag;cur_flag=clist_next(cur_flag)) { 311 for(cur_flag=clist_begin(bflags->mbf_oflags);cur_flag;cur_flag=clist_next(cur_flag)) {
312 if ( ((mailimap_mbx_list_oflag*)cur_flag->data)->of_type==MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS) { 312 if ( ((mailimap_mbx_list_oflag*)cur_flag->data)->of_type==MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS) {
313 no_inferiors = true; 313 no_inferiors = true;
314 } 314 }
315 } 315 }
316 } 316 }
317 folders->append( new IMAPFolder(temp,del,selectable,no_inferiors,account->getPrefix())); 317 folders->append( new IMAPFolder(temp,del,selectable,no_inferiors,account->getPrefix()));
318 } 318 }
319 } else { 319 } else {
320 qDebug("error fetching folders: %s",m_imap->imap_response); 320 odebug << "error fetching folders: " << m_imap->imap_response << "" << oendl;
321 } 321 }
322 mailimap_list_result_free( result ); 322 mailimap_list_result_free( result );
323 323
324/* 324/*
325 * second stage - get the other then inbox folders 325 * second stage - get the other then inbox folders
326 */ 326 */
327 mask = "*" ; 327 mask = "*" ;
328 path = account->getPrefix().latin1(); 328 path = account->getPrefix().latin1();
329 if (!path) path = ""; 329 if (!path) path = "";
330 qDebug(path); 330 odebug << path << oendl;
331 err = mailimap_list( m_imap, (char*)path, (char*)mask, &result ); 331 err = mailimap_list( m_imap, (char*)path, (char*)mask, &result );
332 if ( err == MAILIMAP_NO_ERROR ) { 332 if ( err == MAILIMAP_NO_ERROR ) {
333 current = result->first; 333 current = result->first;
334 for ( current=clist_begin(result);current!=NULL;current=clist_next(current)) { 334 for ( current=clist_begin(result);current!=NULL;current=clist_next(current)) {
335 no_inferiors = false; 335 no_inferiors = false;
336 list = (mailimap_mailbox_list *) current->data; 336 list = (mailimap_mailbox_list *) current->data;
337 // it is better use the deep copy mechanism of qt itself 337 // it is better use the deep copy mechanism of qt itself
338 // instead of using strdup! 338 // instead of using strdup!
339 temp = list->mb_name; 339 temp = list->mb_name;
340 if (temp.lower()=="inbox") 340 if (temp.lower()=="inbox")
341 continue; 341 continue;
342 if (temp.lower()==account->getPrefix().lower()) 342 if (temp.lower()==account->getPrefix().lower())
343 continue; 343 continue;
344 if ( (bflags = list->mb_flag) ) { 344 if ( (bflags = list->mb_flag) ) {
345 selectable = !(bflags->mbf_type==MAILIMAP_MBX_LIST_FLAGS_SFLAG&& 345 selectable = !(bflags->mbf_type==MAILIMAP_MBX_LIST_FLAGS_SFLAG&&
346 bflags->mbf_sflag==MAILIMAP_MBX_LIST_SFLAG_NOSELECT); 346 bflags->mbf_sflag==MAILIMAP_MBX_LIST_SFLAG_NOSELECT);
347 for(cur_flag=clist_begin(bflags->mbf_oflags);cur_flag;cur_flag=clist_next(cur_flag)) { 347 for(cur_flag=clist_begin(bflags->mbf_oflags);cur_flag;cur_flag=clist_next(cur_flag)) {
348 if ( ((mailimap_mbx_list_oflag*)cur_flag->data)->of_type==MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS) { 348 if ( ((mailimap_mbx_list_oflag*)cur_flag->data)->of_type==MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS) {
349 no_inferiors = true; 349 no_inferiors = true;
350 } 350 }
351 } 351 }
352 } 352 }
353 del = list->mb_delimiter; 353 del = list->mb_delimiter;
354 folders->append(new IMAPFolder(temp,del,selectable,no_inferiors,account->getPrefix())); 354 folders->append(new IMAPFolder(temp,del,selectable,no_inferiors,account->getPrefix()));
355 } 355 }
356 } else { 356 } else {
357 qDebug("error fetching folders %s",m_imap->imap_response); 357 odebug << "error fetching folders " << m_imap->imap_response << "" << oendl;
358 } 358 }
359 if (result) mailimap_list_result_free( result ); 359 if (result) mailimap_list_result_free( result );
360 return folders; 360 return folders;
361} 361}
362 362
363RecMail*IMAPwrapper::parse_list_result(mailimap_msg_att* m_att) 363RecMail*IMAPwrapper::parse_list_result(mailimap_msg_att* m_att)
364{ 364{
365 RecMail * m = 0; 365 RecMail * m = 0;
366 mailimap_msg_att_item *item=0; 366 mailimap_msg_att_item *item=0;
367 clistcell *current,*c,*cf; 367 clistcell *current,*c,*cf;
368 mailimap_msg_att_dynamic*flist; 368 mailimap_msg_att_dynamic*flist;
369 mailimap_flag_fetch*cflag; 369 mailimap_flag_fetch*cflag;
370 int size; 370 int size;
371 QBitArray mFlags(7); 371 QBitArray mFlags(7);
372 QStringList addresslist; 372 QStringList addresslist;
373 373
374 if (!m_att) { 374 if (!m_att) {
375 return m; 375 return m;
376 } 376 }
377 m = new RecMail(); 377 m = new RecMail();
378 for (c = clist_begin(m_att->att_list); c!=NULL;c=clist_next(c) ) { 378 for (c = clist_begin(m_att->att_list); c!=NULL;c=clist_next(c) ) {
379 current = c; 379 current = c;
380 size = 0; 380 size = 0;
381 item = (mailimap_msg_att_item*)current->data; 381 item = (mailimap_msg_att_item*)current->data;
382 if (item->att_type!=MAILIMAP_MSG_ATT_ITEM_STATIC) { 382 if (item->att_type!=MAILIMAP_MSG_ATT_ITEM_STATIC) {
383 flist = (mailimap_msg_att_dynamic*)item->att_data.att_dyn; 383 flist = (mailimap_msg_att_dynamic*)item->att_data.att_dyn;
384 if (!flist->att_list) { 384 if (!flist->att_list) {
385 continue; 385 continue;
386 } 386 }
387 cf = flist->att_list->first; 387 cf = flist->att_list->first;
388 for (cf = clist_begin(flist->att_list); cf!=NULL; cf = clist_next(cf)) { 388 for (cf = clist_begin(flist->att_list); cf!=NULL; cf = clist_next(cf)) {
389 cflag = (mailimap_flag_fetch*)cf->data; 389 cflag = (mailimap_flag_fetch*)cf->data;
390 if (cflag->fl_type==MAILIMAP_FLAG_FETCH_OTHER && cflag->fl_flag!=0) { 390 if (cflag->fl_type==MAILIMAP_FLAG_FETCH_OTHER && cflag->fl_flag!=0) {
391 switch (cflag->fl_flag->fl_type) { 391 switch (cflag->fl_flag->fl_type) {
392 case MAILIMAP_FLAG_ANSWERED: /* \Answered flag */ 392 case MAILIMAP_FLAG_ANSWERED: /* \Answered flag */
393 mFlags.setBit(FLAG_ANSWERED); 393 mFlags.setBit(FLAG_ANSWERED);
394 break; 394 break;
395 case MAILIMAP_FLAG_FLAGGED: /* \Flagged flag */ 395 case MAILIMAP_FLAG_FLAGGED: /* \Flagged flag */
396 mFlags.setBit(FLAG_FLAGGED); 396 mFlags.setBit(FLAG_FLAGGED);
397 break; 397 break;
398 case MAILIMAP_FLAG_DELETED: /* \Deleted flag */ 398 case MAILIMAP_FLAG_DELETED: /* \Deleted flag */
399 mFlags.setBit(FLAG_DELETED); 399 mFlags.setBit(FLAG_DELETED);
400 break; 400 break;
401 case MAILIMAP_FLAG_SEEN: /* \Seen flag */ 401 case MAILIMAP_FLAG_SEEN: /* \Seen flag */
402 mFlags.setBit(FLAG_SEEN); 402 mFlags.setBit(FLAG_SEEN);
403 break; 403 break;
404 case MAILIMAP_FLAG_DRAFT: /* \Draft flag */ 404 case MAILIMAP_FLAG_DRAFT: /* \Draft flag */
405 mFlags.setBit(FLAG_DRAFT); 405 mFlags.setBit(FLAG_DRAFT);
406 break; 406 break;
407 case MAILIMAP_FLAG_KEYWORD: /* keyword flag */ 407 case MAILIMAP_FLAG_KEYWORD: /* keyword flag */
408 break; 408 break;
409 case MAILIMAP_FLAG_EXTENSION: /* \extension flag */ 409 case MAILIMAP_FLAG_EXTENSION: /* \extension flag */
410 break; 410 break;
411 default: 411 default:
412 break; 412 break;
413 } 413 }
414 } else if (cflag->fl_type==MAILIMAP_FLAG_FETCH_RECENT) { 414 } else if (cflag->fl_type==MAILIMAP_FLAG_FETCH_RECENT) {
415 mFlags.setBit(FLAG_RECENT); 415 mFlags.setBit(FLAG_RECENT);
416 } 416 }
417 } 417 }
418 continue; 418 continue;
419 } 419 }
420 if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_ENVELOPE) { 420 if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_ENVELOPE) {
421 mailimap_envelope * head = item->att_data.att_static->att_data.att_env; 421 mailimap_envelope * head = item->att_data.att_static->att_data.att_env;
422 m->setDate(head->env_date); 422 m->setDate(head->env_date);
423 m->setSubject(convert_String((const char*)head->env_subject)); 423 m->setSubject(convert_String((const char*)head->env_subject));
424 //m->setSubject(head->env_subject); 424 //m->setSubject(head->env_subject);
425 if (head->env_from!=NULL) { 425 if (head->env_from!=NULL) {
426 addresslist = address_list_to_stringlist(head->env_from->frm_list); 426 addresslist = address_list_to_stringlist(head->env_from->frm_list);
427 if (addresslist.count()) { 427 if (addresslist.count()) {
428 m->setFrom(addresslist.first()); 428 m->setFrom(addresslist.first());
429 } 429 }
430 } 430 }
431 if (head->env_to!=NULL) { 431 if (head->env_to!=NULL) {
432 addresslist = address_list_to_stringlist(head->env_to->to_list); 432 addresslist = address_list_to_stringlist(head->env_to->to_list);
433 m->setTo(addresslist); 433 m->setTo(addresslist);
434 } 434 }
435 if (head->env_cc!=NULL) { 435 if (head->env_cc!=NULL) {
436 addresslist = address_list_to_stringlist(head->env_cc->cc_list); 436 addresslist = address_list_to_stringlist(head->env_cc->cc_list);
437 m->setCC(addresslist); 437 m->setCC(addresslist);
438 } 438 }
439 if (head->env_bcc!=NULL) { 439 if (head->env_bcc!=NULL) {
440 addresslist = address_list_to_stringlist(head->env_bcc->bcc_list); 440 addresslist = address_list_to_stringlist(head->env_bcc->bcc_list);
441 m->setBcc(addresslist); 441 m->setBcc(addresslist);
442 } 442 }
443 /* reply to address, eg. email. */ 443 /* reply to address, eg. email. */
444 if (head->env_reply_to!=NULL) { 444 if (head->env_reply_to!=NULL) {
445 addresslist = address_list_to_stringlist(head->env_reply_to->rt_list); 445 addresslist = address_list_to_stringlist(head->env_reply_to->rt_list);
446 if (addresslist.count()) { 446 if (addresslist.count()) {
447 m->setReplyto(addresslist.first()); 447 m->setReplyto(addresslist.first());
448 } 448 }
449 } 449 }
450 if (head->env_in_reply_to!=NULL) { 450 if (head->env_in_reply_to!=NULL) {
451 QString h(head->env_in_reply_to); 451 QString h(head->env_in_reply_to);
452 while (h.length()>0 && h[0]=='<') { 452 while (h.length()>0 && h[0]=='<') {
453 h.remove(0,1); 453 h.remove(0,1);
454 } 454 }
455 while (h.length()>0 && h[h.length()-1]=='>') { 455 while (h.length()>0 && h[h.length()-1]=='>') {
456 h.remove(h.length()-1,1); 456 h.remove(h.length()-1,1);
457 } 457 }
458 if (h.length()>0) { 458 if (h.length()>0) {
459 m->setInreply(QStringList(h)); 459 m->setInreply(QStringList(h));
460 } 460 }
461 } 461 }
462 if (head->env_message_id) { 462 if (head->env_message_id) {
463 m->setMsgid(QString(head->env_message_id)); 463 m->setMsgid(QString(head->env_message_id));
464 } 464 }
465 } else if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_INTERNALDATE) { 465 } else if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_INTERNALDATE) {
466#if 0 466#if 0
467 mailimap_date_time*d = item->att_data.att_static->att_data.att_internal_date; 467 mailimap_date_time*d = item->att_data.att_static->att_data.att_internal_date;
468 QDateTime da(QDate(d->dt_year,d->dt_month,d->dt_day),QTime(d->dt_hour,d->dt_min,d->dt_sec)); 468 QDateTime da(QDate(d->dt_year,d->dt_month,d->dt_day),QTime(d->dt_hour,d->dt_min,d->dt_sec));
469 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); 469 odebug << "" << d->dt_year << " " << d->dt_month << " " << d->dt_day << " - " << d->dt_hour << " " << d->dt_min << " " << d->dt_sec << "" << oendl;
470 qDebug(da.toString()); 470 odebug << da.toString() << oendl;
471#endif 471#endif
472 } else if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_RFC822_SIZE) { 472 } else if (item->att_data.att_static->att_type==MAILIMAP_MSG_ATT_RFC822_SIZE) {
473 size = item->att_data.att_static->att_data.att_rfc822_size; 473 size = item->att_data.att_static->att_data.att_rfc822_size;
474 } 474 }
475 } 475 }
476 /* msg is already deleted */ 476 /* msg is already deleted */
477 if (mFlags.testBit(FLAG_DELETED) && m) { 477 if (mFlags.testBit(FLAG_DELETED) && m) {
478 delete m; 478 delete m;
479 m = 0; 479 m = 0;
480 } 480 }
481 if (m) { 481 if (m) {
482 m->setFlags(mFlags); 482 m->setFlags(mFlags);
483 m->setMsgsize(size); 483 m->setMsgsize(size);
484 } 484 }
485 return m; 485 return m;
486} 486}
487 487
488RecBodyP IMAPwrapper::fetchBody(const RecMailP&mail) 488RecBodyP IMAPwrapper::fetchBody(const RecMailP&mail)
489{ 489{
490 RecBodyP body = new RecBody(); 490 RecBodyP body = new RecBody();
491 const char *mb; 491 const char *mb;
492 int err = MAILIMAP_NO_ERROR; 492 int err = MAILIMAP_NO_ERROR;
493 clist *result = 0; 493 clist *result = 0;
494 clistcell *current; 494 clistcell *current;
495 mailimap_fetch_att *fetchAtt = 0; 495 mailimap_fetch_att *fetchAtt = 0;
496 mailimap_fetch_type *fetchType = 0; 496 mailimap_fetch_type *fetchType = 0;
497 mailimap_set *set = 0; 497 mailimap_set *set = 0;
498 mailimap_body*body_desc = 0; 498 mailimap_body*body_desc = 0;
499 499
500 mb = mail->getMbox().latin1(); 500 mb = mail->getMbox().latin1();
501 501
502 login(); 502 login();
503 if (!m_imap) { 503 if (!m_imap) {
504 return body; 504 return body;
505 } 505 }
506 err = selectMbox(mail->getMbox()); 506 err = selectMbox(mail->getMbox());
507 if ( err != MAILIMAP_NO_ERROR ) { 507 if ( err != MAILIMAP_NO_ERROR ) {
508 return body; 508 return body;
509 } 509 }
510 510
511 /* the range has to start at 1!!! not with 0!!!! */ 511 /* the range has to start at 1!!! not with 0!!!! */
512 set = mailimap_set_new_interval( mail->getNumber(),mail->getNumber() ); 512 set = mailimap_set_new_interval( mail->getNumber(),mail->getNumber() );
513 fetchAtt = mailimap_fetch_att_new_bodystructure(); 513 fetchAtt = mailimap_fetch_att_new_bodystructure();
514 fetchType = mailimap_fetch_type_new_fetch_att(fetchAtt); 514 fetchType = mailimap_fetch_type_new_fetch_att(fetchAtt);
515 err = mailimap_fetch( m_imap, set, fetchType, &result ); 515 err = mailimap_fetch( m_imap, set, fetchType, &result );
516 mailimap_set_free( set ); 516 mailimap_set_free( set );
517 mailimap_fetch_type_free( fetchType ); 517 mailimap_fetch_type_free( fetchType );
518 518
519 if (err == MAILIMAP_NO_ERROR && (current=clist_begin(result)) ) { 519 if (err == MAILIMAP_NO_ERROR && (current=clist_begin(result)) ) {
520 mailimap_msg_att * msg_att; 520 mailimap_msg_att * msg_att;
521 msg_att = (mailimap_msg_att*)current->data; 521 msg_att = (mailimap_msg_att*)current->data;
522 mailimap_msg_att_item*item = (mailimap_msg_att_item*)msg_att->att_list->first->data; 522 mailimap_msg_att_item*item = (mailimap_msg_att_item*)msg_att->att_list->first->data;
523 QValueList<int> path; 523 QValueList<int> path;
524 body_desc = item->att_data.att_static->att_data.att_body; 524 body_desc = item->att_data.att_static->att_data.att_body;
525 traverseBody(mail,body_desc,body,0,path); 525 traverseBody(mail,body_desc,body,0,path);
526 } else { 526 } else {
527 qDebug("error fetching body: %s",m_imap->imap_response); 527 odebug << "error fetching body: " << m_imap->imap_response << "" << oendl;
528 } 528 }
529 if (result) mailimap_fetch_list_free(result); 529 if (result) mailimap_fetch_list_free(result);
530 return body; 530 return body;
531} 531}
532 532
533QStringList IMAPwrapper::address_list_to_stringlist(clist*list) 533QStringList IMAPwrapper::address_list_to_stringlist(clist*list)
534{ 534{
535 QStringList l; 535 QStringList l;
536 QString from; 536 QString from;
537 bool named_from; 537 bool named_from;
538 clistcell *current = NULL; 538 clistcell *current = NULL;
539 mailimap_address * current_address=NULL; 539 mailimap_address * current_address=NULL;
540 if (!list) { 540 if (!list) {
541 return l; 541 return l;
542 } 542 }
543 unsigned int count = 0; 543 unsigned int count = 0;
544 for (current=clist_begin(list);current!= NULL;current=clist_next(current)) { 544 for (current=clist_begin(list);current!= NULL;current=clist_next(current)) {
545 from = ""; 545 from = "";
546 named_from = false; 546 named_from = false;
547 current_address=(mailimap_address*)current->data; 547 current_address=(mailimap_address*)current->data;
548 if (current_address->ad_personal_name){ 548 if (current_address->ad_personal_name){
549 from+=convert_String((const char*)current_address->ad_personal_name); 549 from+=convert_String((const char*)current_address->ad_personal_name);
550 from+=" "; 550 from+=" ";
551 named_from = true; 551 named_from = true;
552 } 552 }
553 if (named_from && (current_address->ad_mailbox_name || current_address->ad_host_name)) { 553 if (named_from && (current_address->ad_mailbox_name || current_address->ad_host_name)) {
554 from+="<"; 554 from+="<";
555 } 555 }
556 if (current_address->ad_mailbox_name) { 556 if (current_address->ad_mailbox_name) {
557 from+=QString(current_address->ad_mailbox_name); 557 from+=QString(current_address->ad_mailbox_name);
558 from+="@"; 558 from+="@";
559 } 559 }
560 if (current_address->ad_host_name) { 560 if (current_address->ad_host_name) {
561 from+=QString(current_address->ad_host_name); 561 from+=QString(current_address->ad_host_name);
562 } 562 }
563 if (named_from && (current_address->ad_mailbox_name || current_address->ad_host_name)) { 563 if (named_from && (current_address->ad_mailbox_name || current_address->ad_host_name)) {
564 from+=">"; 564 from+=">";
565 } 565 }
566 l.append(QString(from)); 566 l.append(QString(from));
567 if (++count > 99) { 567 if (++count > 99) {
568 break; 568 break;
569 } 569 }
570 } 570 }
571 return l; 571 return l;
572} 572}
573 573
574encodedString*IMAPwrapper::fetchRawPart(const RecMailP&mail,const QValueList<int>&path,bool internal_call) 574encodedString*IMAPwrapper::fetchRawPart(const RecMailP&mail,const QValueList<int>&path,bool internal_call)
575{ 575{
576 encodedString*res=new encodedString; 576 encodedString*res=new encodedString;
577 int err; 577 int err;
578 mailimap_fetch_type *fetchType; 578 mailimap_fetch_type *fetchType;
579 mailimap_set *set; 579 mailimap_set *set;
580 clistcell*current,*cur; 580 clistcell*current,*cur;
581 mailimap_section_part * section_part = 0; 581 mailimap_section_part * section_part = 0;
582 mailimap_section_spec * section_spec = 0; 582 mailimap_section_spec * section_spec = 0;
583 mailimap_section * section = 0; 583 mailimap_section * section = 0;
584 mailimap_fetch_att * fetch_att = 0; 584 mailimap_fetch_att * fetch_att = 0;
585 585
586 login(); 586 login();
587 if (!m_imap) { 587 if (!m_imap) {
588 return res; 588 return res;
589 } 589 }
590 if (!internal_call) { 590 if (!internal_call) {
591 err = selectMbox(mail->getMbox()); 591 err = selectMbox(mail->getMbox());
592 if ( err != MAILIMAP_NO_ERROR ) { 592 if ( err != MAILIMAP_NO_ERROR ) {
593 return res; 593 return res;
594 } 594 }
595 } 595 }
596 set = mailimap_set_new_single(mail->getNumber()); 596 set = mailimap_set_new_single(mail->getNumber());
597 597
598 clist*id_list = 0; 598 clist*id_list = 0;
599 599
600 /* if path == empty then its a request for the whole rfc822 mail and generates 600 /* if path == empty then its a request for the whole rfc822 mail and generates
601 a "fetch <id> (body[])" statement on imap server */ 601 a "fetch <id> (body[])" statement on imap server */
602 if (path.count()>0 ) { 602 if (path.count()>0 ) {
603 id_list = clist_new(); 603 id_list = clist_new();
604 for (unsigned j=0; j < path.count();++j) { 604 for (unsigned j=0; j < path.count();++j) {
605 uint32_t * p_id = (uint32_t *)malloc(sizeof(*p_id)); 605 uint32_t * p_id = (uint32_t *)malloc(sizeof(*p_id));
606 *p_id = path[j]; 606 *p_id = path[j];
607 clist_append(id_list,p_id); 607 clist_append(id_list,p_id);
608 } 608 }
609 section_part = mailimap_section_part_new(id_list); 609 section_part = mailimap_section_part_new(id_list);
610 section_spec = mailimap_section_spec_new(MAILIMAP_SECTION_SPEC_SECTION_PART, NULL, section_part, NULL); 610 section_spec = mailimap_section_spec_new(MAILIMAP_SECTION_SPEC_SECTION_PART, NULL, section_part, NULL);
611 } 611 }
612 612
613 section = mailimap_section_new(section_spec); 613 section = mailimap_section_new(section_spec);
614 fetch_att = mailimap_fetch_att_new_body_section(section); 614 fetch_att = mailimap_fetch_att_new_body_section(section);
615 fetchType = mailimap_fetch_type_new_fetch_att(fetch_att); 615 fetchType = mailimap_fetch_type_new_fetch_att(fetch_att);
616 616
617 clist*result = 0; 617 clist*result = 0;
618 618
619 err = mailimap_fetch( m_imap, set, fetchType, &result ); 619 err = mailimap_fetch( m_imap, set, fetchType, &result );
620 mailimap_set_free( set ); 620 mailimap_set_free( set );
621 mailimap_fetch_type_free( fetchType ); 621 mailimap_fetch_type_free( fetchType );
622 622
623 if (err == MAILIMAP_NO_ERROR && (current=clist_begin(result)) ) { 623 if (err == MAILIMAP_NO_ERROR && (current=clist_begin(result)) ) {
624 mailimap_msg_att * msg_att; 624 mailimap_msg_att * msg_att;
625 msg_att = (mailimap_msg_att*)current->data; 625 msg_att = (mailimap_msg_att*)current->data;
626 mailimap_msg_att_item*msg_att_item; 626 mailimap_msg_att_item*msg_att_item;
627 for(cur = clist_begin(msg_att->att_list) ; cur != NULL ; cur = clist_next(cur)) { 627 for(cur = clist_begin(msg_att->att_list) ; cur != NULL ; cur = clist_next(cur)) {
628 msg_att_item = (mailimap_msg_att_item*)clist_content(cur); 628 msg_att_item = (mailimap_msg_att_item*)clist_content(cur);
629 if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) { 629 if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
630 if (msg_att_item->att_data.att_static->att_type == MAILIMAP_MSG_ATT_BODY_SECTION) { 630 if (msg_att_item->att_data.att_static->att_type == MAILIMAP_MSG_ATT_BODY_SECTION) {
631 char*text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part; 631 char*text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
632 /* detach - we take over the content */ 632 /* detach - we take over the content */
633 msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = 0L; 633 msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = 0L;
634 res->setContent(text,msg_att_item->att_data.att_static->att_data.att_body_section->sec_length); 634 res->setContent(text,msg_att_item->att_data.att_static->att_data.att_body_section->sec_length);
635 } 635 }
636 } 636 }
637 } 637 }
638 } else { 638 } else {
639 qDebug("error fetching text: %s",m_imap->imap_response); 639 odebug << "error fetching text: " << m_imap->imap_response << "" << oendl;
640 } 640 }
641 if (result) mailimap_fetch_list_free(result); 641 if (result) mailimap_fetch_list_free(result);
642 return res; 642 return res;
643} 643}
644 644
645/* current_recursion is for recursive calls. 645/* current_recursion is for recursive calls.
646 current_count means the position inside the internal loop! */ 646 current_count means the position inside the internal loop! */
647void IMAPwrapper::traverseBody(const RecMailP&mail,mailimap_body*body,RecBodyP&target_body, 647void IMAPwrapper::traverseBody(const RecMailP&mail,mailimap_body*body,RecBodyP&target_body,
648 int current_recursion,QValueList<int>recList,int current_count) 648 int current_recursion,QValueList<int>recList,int current_count)
649{ 649{
650 if (!body || current_recursion>=10) { 650 if (!body || current_recursion>=10) {
651 return; 651 return;
652 } 652 }
653 switch (body->bd_type) { 653 switch (body->bd_type) {
654 case MAILIMAP_BODY_1PART: 654 case MAILIMAP_BODY_1PART:
655 { 655 {
656 QValueList<int>countlist = recList; 656 QValueList<int>countlist = recList;
657 countlist.append(current_count); 657 countlist.append(current_count);
658 RecPartP currentPart = new RecPart(); 658 RecPartP currentPart = new RecPart();
659 mailimap_body_type_1part*part1 = body->bd_data.bd_body_1part; 659 mailimap_body_type_1part*part1 = body->bd_data.bd_body_1part;
660 QString id(""); 660 QString id("");
661 currentPart->setPositionlist(countlist); 661 currentPart->setPositionlist(countlist);
662 for (unsigned int j = 0; j < countlist.count();++j) { 662 for (unsigned int j = 0; j < countlist.count();++j) {
663 id+=(j>0?" ":""); 663 id+=(j>0?" ":"");
664 id+=QString("%1").arg(countlist[j]); 664 id+=QString("%1").arg(countlist[j]);
665 } 665 }
666 qDebug("ID = %s",id.latin1()); 666 odebug << "ID = " << id.latin1() << "" << oendl;
667 currentPart->setIdentifier(id); 667 currentPart->setIdentifier(id);
668 fillSinglePart(currentPart,part1); 668 fillSinglePart(currentPart,part1);
669 /* important: Check for is NULL 'cause a body can be empty! 669 /* important: Check for is NULL 'cause a body can be empty!
670 And we put it only into the mail if it is the FIRST part */ 670 And we put it only into the mail if it is the FIRST part */
671 if (part1->bd_type==MAILIMAP_BODY_TYPE_1PART_TEXT && target_body->Bodytext().isNull() && countlist[0]==1) { 671 if (part1->bd_type==MAILIMAP_BODY_TYPE_1PART_TEXT && target_body->Bodytext().isNull() && countlist[0]==1) {
672 QString body_text = fetchTextPart(mail,countlist,true,currentPart->Encoding()); 672 QString body_text = fetchTextPart(mail,countlist,true,currentPart->Encoding());
673 target_body->setDescription(currentPart); 673 target_body->setDescription(currentPart);
674 target_body->setBodytext(body_text); 674 target_body->setBodytext(body_text);
675 if (countlist.count()>1) { 675 if (countlist.count()>1) {
676 target_body->addPart(currentPart); 676 target_body->addPart(currentPart);
677 } 677 }
678 } else { 678 } else {
679 target_body->addPart(currentPart); 679 target_body->addPart(currentPart);
680 } 680 }
681 if (part1->bd_type==MAILIMAP_BODY_TYPE_1PART_MSG) { 681 if (part1->bd_type==MAILIMAP_BODY_TYPE_1PART_MSG) {
682 traverseBody(mail,part1->bd_data.bd_type_msg->bd_body,target_body,current_recursion+1,countlist); 682 traverseBody(mail,part1->bd_data.bd_type_msg->bd_body,target_body,current_recursion+1,countlist);
683 } 683 }
684 } 684 }
685 break; 685 break;
686 case MAILIMAP_BODY_MPART: 686 case MAILIMAP_BODY_MPART:
687 { 687 {
688 QValueList<int>countlist = recList; 688 QValueList<int>countlist = recList;
689 clistcell*current=0; 689 clistcell*current=0;
690 mailimap_body*current_body=0; 690 mailimap_body*current_body=0;
691 unsigned int ccount = 1; 691 unsigned int ccount = 1;
692 mailimap_body_type_mpart*mailDescription = body->bd_data.bd_body_mpart; 692 mailimap_body_type_mpart*mailDescription = body->bd_data.bd_body_mpart;
693 for (current=clist_begin(mailDescription->bd_list);current!=0;current=clist_next(current)) { 693 for (current=clist_begin(mailDescription->bd_list);current!=0;current=clist_next(current)) {
694 current_body = (mailimap_body*)current->data; 694 current_body = (mailimap_body*)current->data;
695 if (current_body->bd_type==MAILIMAP_BODY_MPART) { 695 if (current_body->bd_type==MAILIMAP_BODY_MPART) {
696 RecPartP targetPart = new RecPart(); 696 RecPartP targetPart = new RecPart();
697 targetPart->setType("multipart"); 697 targetPart->setType("multipart");
698 fillMultiPart(targetPart,mailDescription); 698 fillMultiPart(targetPart,mailDescription);
699 countlist.append(current_count); 699 countlist.append(current_count);
700 targetPart->setPositionlist(countlist); 700 targetPart->setPositionlist(countlist);
701 target_body->addPart(targetPart); 701 target_body->addPart(targetPart);
702 QString id(""); 702 QString id("");
703 for (unsigned int j = 0; j < countlist.count();++j) { 703 for (unsigned int j = 0; j < countlist.count();++j) {
704 id+=(j>0?" ":""); 704 id+=(j>0?" ":"");
705 id+=QString("%1").arg(countlist[j]); 705 id+=QString("%1").arg(countlist[j]);
706 } 706 }
707 qDebug("ID(mpart) = %s",id.latin1()); 707 odebug << "ID(mpart) = " << id.latin1() << "" << oendl;
708 } 708 }
709 traverseBody(mail,current_body,target_body,current_recursion+1,countlist,ccount); 709 traverseBody(mail,current_body,target_body,current_recursion+1,countlist,ccount);
710 if (current_body->bd_type==MAILIMAP_BODY_MPART) { 710 if (current_body->bd_type==MAILIMAP_BODY_MPART) {
711 countlist = recList; 711 countlist = recList;
712 } 712 }
713 ++ccount; 713 ++ccount;
714 } 714 }
715 } 715 }
716 break; 716 break;
717 default: 717 default:
718 break; 718 break;
719 } 719 }
720} 720}
721 721
722void IMAPwrapper::fillSinglePart(RecPartP&target_part,mailimap_body_type_1part*Description) 722void IMAPwrapper::fillSinglePart(RecPartP&target_part,mailimap_body_type_1part*Description)
723{ 723{
724 if (!Description) { 724 if (!Description) {
725 return; 725 return;
726 } 726 }
727 switch (Description->bd_type) { 727 switch (Description->bd_type) {
728 case MAILIMAP_BODY_TYPE_1PART_TEXT: 728 case MAILIMAP_BODY_TYPE_1PART_TEXT:
729 target_part->setType("text"); 729 target_part->setType("text");
730 fillSingleTextPart(target_part,Description->bd_data.bd_type_text); 730 fillSingleTextPart(target_part,Description->bd_data.bd_type_text);
731 break; 731 break;
732 case MAILIMAP_BODY_TYPE_1PART_BASIC: 732 case MAILIMAP_BODY_TYPE_1PART_BASIC:
733 fillSingleBasicPart(target_part,Description->bd_data.bd_type_basic); 733 fillSingleBasicPart(target_part,Description->bd_data.bd_type_basic);
734 break; 734 break;
735 case MAILIMAP_BODY_TYPE_1PART_MSG: 735 case MAILIMAP_BODY_TYPE_1PART_MSG:
736 target_part->setType("message"); 736 target_part->setType("message");
737 fillSingleMsgPart(target_part,Description->bd_data.bd_type_msg); 737 fillSingleMsgPart(target_part,Description->bd_data.bd_type_msg);
738 break; 738 break;
739 default: 739 default:
740 break; 740 break;
741 } 741 }
742} 742}
743 743
744void IMAPwrapper::fillSingleTextPart(RecPartP&target_part,mailimap_body_type_text*which) 744void IMAPwrapper::fillSingleTextPart(RecPartP&target_part,mailimap_body_type_text*which)
745{ 745{
746 if (!which) { 746 if (!which) {
747 return; 747 return;
748 } 748 }
749 QString sub; 749 QString sub;
750 sub = which->bd_media_text; 750 sub = which->bd_media_text;
751 qDebug("Type= text/%s",which->bd_media_text); 751 odebug << "Type= text/" << which->bd_media_text << "" << oendl;
752 target_part->setSubtype(sub.lower()); 752 target_part->setSubtype(sub.lower());
753 target_part->setLines(which->bd_lines); 753 target_part->setLines(which->bd_lines);
754 fillBodyFields(target_part,which->bd_fields); 754 fillBodyFields(target_part,which->bd_fields);
755} 755}
756 756
757void IMAPwrapper::fillSingleMsgPart(RecPartP&target_part,mailimap_body_type_msg*which) 757void IMAPwrapper::fillSingleMsgPart(RecPartP&target_part,mailimap_body_type_msg*which)
758{ 758{
759 if (!which) { 759 if (!which) {
760 return; 760 return;
761 } 761 }
762 target_part->setSubtype("rfc822"); 762 target_part->setSubtype("rfc822");
763 qDebug("Message part"); 763 odebug << "Message part" << oendl;
764 /* we set this type to text/plain */ 764 /* we set this type to text/plain */
765 target_part->setLines(which->bd_lines); 765 target_part->setLines(which->bd_lines);
766 fillBodyFields(target_part,which->bd_fields); 766 fillBodyFields(target_part,which->bd_fields);
767} 767}
768 768
769void IMAPwrapper::fillMultiPart(RecPartP&target_part,mailimap_body_type_mpart*which) 769void IMAPwrapper::fillMultiPart(RecPartP&target_part,mailimap_body_type_mpart*which)
770{ 770{
771 if (!which) return; 771 if (!which) return;
772 QString sub = which->bd_media_subtype; 772 QString sub = which->bd_media_subtype;
773 target_part->setSubtype(sub.lower()); 773 target_part->setSubtype(sub.lower());
774 if (which->bd_ext_mpart && which->bd_ext_mpart->bd_parameter && which->bd_ext_mpart->bd_parameter->pa_list) { 774 if (which->bd_ext_mpart && which->bd_ext_mpart->bd_parameter && which->bd_ext_mpart->bd_parameter->pa_list) {
775 clistcell*cur = 0; 775 clistcell*cur = 0;
776 mailimap_single_body_fld_param*param=0; 776 mailimap_single_body_fld_param*param=0;
777 for (cur = clist_begin(which->bd_ext_mpart->bd_parameter->pa_list);cur!=NULL;cur=clist_next(cur)) { 777 for (cur = clist_begin(which->bd_ext_mpart->bd_parameter->pa_list);cur!=NULL;cur=clist_next(cur)) {
778 param = (mailimap_single_body_fld_param*)cur->data; 778 param = (mailimap_single_body_fld_param*)cur->data;
779 if (param) { 779 if (param) {
780 target_part->addParameter(QString(param->pa_name).lower(),QString(param->pa_value)); 780 target_part->addParameter(QString(param->pa_name).lower(),QString(param->pa_value));
781 } 781 }
782 } 782 }
783 } 783 }
784} 784}
785 785
786void IMAPwrapper::fillSingleBasicPart(RecPartP&target_part,mailimap_body_type_basic*which) 786void IMAPwrapper::fillSingleBasicPart(RecPartP&target_part,mailimap_body_type_basic*which)
787{ 787{
788 if (!which) { 788 if (!which) {
789 return; 789 return;
790 } 790 }
791 QString type,sub; 791 QString type,sub;
792 switch (which->bd_media_basic->med_type) { 792 switch (which->bd_media_basic->med_type) {
793 case MAILIMAP_MEDIA_BASIC_APPLICATION: 793 case MAILIMAP_MEDIA_BASIC_APPLICATION:
794 type = "application"; 794 type = "application";
795 break; 795 break;
796 case MAILIMAP_MEDIA_BASIC_AUDIO: 796 case MAILIMAP_MEDIA_BASIC_AUDIO:
797 type = "audio"; 797 type = "audio";
798 break; 798 break;
799 case MAILIMAP_MEDIA_BASIC_IMAGE: 799 case MAILIMAP_MEDIA_BASIC_IMAGE:
800 type = "image"; 800 type = "image";
801 break; 801 break;
802 case MAILIMAP_MEDIA_BASIC_MESSAGE: 802 case MAILIMAP_MEDIA_BASIC_MESSAGE:
803 type = "message"; 803 type = "message";
804 break; 804 break;
805 case MAILIMAP_MEDIA_BASIC_VIDEO: 805 case MAILIMAP_MEDIA_BASIC_VIDEO:
806 type = "video"; 806 type = "video";
807 break; 807 break;
808 case MAILIMAP_MEDIA_BASIC_OTHER: 808 case MAILIMAP_MEDIA_BASIC_OTHER:
809 default: 809 default:
810 if (which->bd_media_basic->med_basic_type) { 810 if (which->bd_media_basic->med_basic_type) {
811 type = which->bd_media_basic->med_basic_type; 811 type = which->bd_media_basic->med_basic_type;
812 } else { 812 } else {
813 type = ""; 813 type = "";
814 } 814 }
815 break; 815 break;
816 } 816 }
817 if (which->bd_media_basic->med_subtype) { 817 if (which->bd_media_basic->med_subtype) {
818 sub = which->bd_media_basic->med_subtype; 818 sub = which->bd_media_basic->med_subtype;
819 } else { 819 } else {
820 sub = ""; 820 sub = "";
821 } 821 }
822 qDebug("Type = %s/%s",type.latin1(),sub.latin1()); 822 odebug << "Type = " << type.latin1() << "/" << sub.latin1() << "" << oendl;
823 target_part->setType(type.lower()); 823 target_part->setType(type.lower());
824 target_part->setSubtype(sub.lower()); 824 target_part->setSubtype(sub.lower());
825 fillBodyFields(target_part,which->bd_fields); 825 fillBodyFields(target_part,which->bd_fields);
826} 826}
827 827
828void IMAPwrapper::fillBodyFields(RecPartP&target_part,mailimap_body_fields*which) 828void IMAPwrapper::fillBodyFields(RecPartP&target_part,mailimap_body_fields*which)
829{ 829{
830 if (!which) return; 830 if (!which) return;
831 if (which->bd_parameter && which->bd_parameter->pa_list && which->bd_parameter->pa_list->count>0) { 831 if (which->bd_parameter && which->bd_parameter->pa_list && which->bd_parameter->pa_list->count>0) {
832 clistcell*cur; 832 clistcell*cur;
833 mailimap_single_body_fld_param*param=0; 833 mailimap_single_body_fld_param*param=0;
834 for (cur = clist_begin(which->bd_parameter->pa_list);cur!=NULL;cur=clist_next(cur)) { 834 for (cur = clist_begin(which->bd_parameter->pa_list);cur!=NULL;cur=clist_next(cur)) {
835 param = (mailimap_single_body_fld_param*)cur->data; 835 param = (mailimap_single_body_fld_param*)cur->data;
836 if (param) { 836 if (param) {
837 target_part->addParameter(QString(param->pa_name).lower(),QString(param->pa_value)); 837 target_part->addParameter(QString(param->pa_name).lower(),QString(param->pa_value));
838 } 838 }
839 } 839 }
840 } 840 }
841 mailimap_body_fld_enc*enc = which->bd_encoding; 841 mailimap_body_fld_enc*enc = which->bd_encoding;
842 QString encoding(""); 842 QString encoding("");
843 switch (enc->enc_type) { 843 switch (enc->enc_type) {
844 case MAILIMAP_BODY_FLD_ENC_7BIT: 844 case MAILIMAP_BODY_FLD_ENC_7BIT:
845 encoding = "7bit"; 845 encoding = "7bit";
846 break; 846 break;
847 case MAILIMAP_BODY_FLD_ENC_8BIT: 847 case MAILIMAP_BODY_FLD_ENC_8BIT:
848 encoding = "8bit"; 848 encoding = "8bit";
849 break; 849 break;
850 case MAILIMAP_BODY_FLD_ENC_BINARY: 850 case MAILIMAP_BODY_FLD_ENC_BINARY:
851 encoding="binary"; 851 encoding="binary";
852 break; 852 break;
853 case MAILIMAP_BODY_FLD_ENC_BASE64: 853 case MAILIMAP_BODY_FLD_ENC_BASE64:
854 encoding="base64"; 854 encoding="base64";
855 break; 855 break;
856 case MAILIMAP_BODY_FLD_ENC_QUOTED_PRINTABLE: 856 case MAILIMAP_BODY_FLD_ENC_QUOTED_PRINTABLE:
857 encoding="quoted-printable"; 857 encoding="quoted-printable";
858 break; 858 break;
859 case MAILIMAP_BODY_FLD_ENC_OTHER: 859 case MAILIMAP_BODY_FLD_ENC_OTHER:
860 default: 860 default:
861 if (enc->enc_value) { 861 if (enc->enc_value) {
862 char*t=enc->enc_value; 862 char*t=enc->enc_value;
863 encoding=QString(enc->enc_value); 863 encoding=QString(enc->enc_value);
864 enc->enc_value=0L; 864 enc->enc_value=0L;
865 free(t); 865 free(t);
866 } 866 }
867 } 867 }
868 if (which->bd_description) { 868 if (which->bd_description) {
869 target_part->setDescription(QString(which->bd_description)); 869 target_part->setDescription(QString(which->bd_description));
870 } 870 }
871 target_part->setEncoding(encoding); 871 target_part->setEncoding(encoding);
872 target_part->setSize(which->bd_size); 872 target_part->setSize(which->bd_size);
873} 873}
874 874
875void IMAPwrapper::deleteMail(const RecMailP&mail) 875void IMAPwrapper::deleteMail(const RecMailP&mail)
876{ 876{
877 mailimap_flag_list*flist; 877 mailimap_flag_list*flist;
878 mailimap_set *set; 878 mailimap_set *set;
879 mailimap_store_att_flags * store_flags; 879 mailimap_store_att_flags * store_flags;
880 int err; 880 int err;
881 login(); 881 login();
882 if (!m_imap) { 882 if (!m_imap) {
883 return; 883 return;
884 } 884 }
885 err = selectMbox(mail->getMbox()); 885 err = selectMbox(mail->getMbox());
886 if ( err != MAILIMAP_NO_ERROR ) { 886 if ( err != MAILIMAP_NO_ERROR ) {
887 return; 887 return;
888 } 888 }
889 flist = mailimap_flag_list_new_empty(); 889 flist = mailimap_flag_list_new_empty();
890 mailimap_flag_list_add(flist,mailimap_flag_new_deleted()); 890 mailimap_flag_list_add(flist,mailimap_flag_new_deleted());
891 store_flags = mailimap_store_att_flags_new_set_flags(flist); 891 store_flags = mailimap_store_att_flags_new_set_flags(flist);
892 set = mailimap_set_new_single(mail->getNumber()); 892 set = mailimap_set_new_single(mail->getNumber());
893 err = mailimap_store(m_imap,set,store_flags); 893 err = mailimap_store(m_imap,set,store_flags);
894 mailimap_set_free( set ); 894 mailimap_set_free( set );
895 mailimap_store_att_flags_free(store_flags); 895 mailimap_store_att_flags_free(store_flags);
896 896
897 if (err != MAILIMAP_NO_ERROR) { 897 if (err != MAILIMAP_NO_ERROR) {
898 qDebug("error deleting mail: %s",m_imap->imap_response); 898 odebug << "error deleting mail: " << m_imap->imap_response << "" << oendl;
899 return; 899 return;
900 } 900 }
901 qDebug("deleting mail: %s",m_imap->imap_response); 901 odebug << "deleting mail: " << m_imap->imap_response << "" << oendl;
902 /* should we realy do that at this moment? */ 902 /* should we realy do that at this moment? */
903 err = mailimap_expunge(m_imap); 903 err = mailimap_expunge(m_imap);
904 if (err != MAILIMAP_NO_ERROR) { 904 if (err != MAILIMAP_NO_ERROR) {
905 qDebug("error deleting mail: %s",m_imap->imap_response); 905 odebug << "error deleting mail: " << m_imap->imap_response << "" << oendl;
906 } 906 }
907 qDebug("Delete successfull %s",m_imap->imap_response); 907 odebug << "Delete successfull " << m_imap->imap_response << "" << oendl;
908} 908}
909 909
910void IMAPwrapper::answeredMail(const RecMailP&mail) 910void IMAPwrapper::answeredMail(const RecMailP&mail)
911{ 911{
912 mailimap_flag_list*flist; 912 mailimap_flag_list*flist;
913 mailimap_set *set; 913 mailimap_set *set;
914 mailimap_store_att_flags * store_flags; 914 mailimap_store_att_flags * store_flags;
915 int err; 915 int err;
916 login(); 916 login();
917 if (!m_imap) { 917 if (!m_imap) {
918 return; 918 return;
919 } 919 }
920 err = selectMbox(mail->getMbox()); 920 err = selectMbox(mail->getMbox());
921 if ( err != MAILIMAP_NO_ERROR ) { 921 if ( err != MAILIMAP_NO_ERROR ) {
922 return; 922 return;
923 } 923 }
924 flist = mailimap_flag_list_new_empty(); 924 flist = mailimap_flag_list_new_empty();
925 mailimap_flag_list_add(flist,mailimap_flag_new_answered()); 925 mailimap_flag_list_add(flist,mailimap_flag_new_answered());
926 store_flags = mailimap_store_att_flags_new_add_flags(flist); 926 store_flags = mailimap_store_att_flags_new_add_flags(flist);
927 set = mailimap_set_new_single(mail->getNumber()); 927 set = mailimap_set_new_single(mail->getNumber());
928 err = mailimap_store(m_imap,set,store_flags); 928 err = mailimap_store(m_imap,set,store_flags);
929 mailimap_set_free( set ); 929 mailimap_set_free( set );
930 mailimap_store_att_flags_free(store_flags); 930 mailimap_store_att_flags_free(store_flags);
931 931
932 if (err != MAILIMAP_NO_ERROR) { 932 if (err != MAILIMAP_NO_ERROR) {
933 qDebug("error marking mail: %s",m_imap->imap_response); 933 odebug << "error marking mail: " << m_imap->imap_response << "" << oendl;
934 return; 934 return;
935 } 935 }
936} 936}
937 937
938QString IMAPwrapper::fetchTextPart(const RecMailP&mail,const QValueList<int>&path,bool internal_call,const QString&enc) 938QString IMAPwrapper::fetchTextPart(const RecMailP&mail,const QValueList<int>&path,bool internal_call,const QString&enc)
939{ 939{
940 QString body(""); 940 QString body("");
941 encodedString*res = fetchRawPart(mail,path,internal_call); 941 encodedString*res = fetchRawPart(mail,path,internal_call);
942 encodedString*r = decode_String(res,enc); 942 encodedString*r = decode_String(res,enc);
943 delete res; 943 delete res;
944 if (r) { 944 if (r) {
945 if (r->Length()>0) { 945 if (r->Length()>0) {
946 body = r->Content(); 946 body = r->Content();
947 } 947 }
948 delete r; 948 delete r;
949 } 949 }
950 return body; 950 return body;
951} 951}
952 952
953QString IMAPwrapper::fetchTextPart(const RecMailP&mail,const RecPartP&part) 953QString IMAPwrapper::fetchTextPart(const RecMailP&mail,const RecPartP&part)
954{ 954{
955 return fetchTextPart(mail,part->Positionlist(),false,part->Encoding()); 955 return fetchTextPart(mail,part->Positionlist(),false,part->Encoding());
956} 956}
957 957
958encodedString* IMAPwrapper::fetchDecodedPart(const RecMailP&mail,const RecPartP&part) 958encodedString* IMAPwrapper::fetchDecodedPart(const RecMailP&mail,const RecPartP&part)
959{ 959{
960 encodedString*res = fetchRawPart(mail,part->Positionlist(),false); 960 encodedString*res = fetchRawPart(mail,part->Positionlist(),false);
961 encodedString*r = decode_String(res,part->Encoding()); 961 encodedString*r = decode_String(res,part->Encoding());
962 delete res; 962 delete res;
963 return r; 963 return r;
964} 964}
965 965
966encodedString* IMAPwrapper::fetchRawPart(const RecMailP&mail,const RecPartP&part) 966encodedString* IMAPwrapper::fetchRawPart(const RecMailP&mail,const RecPartP&part)
967{ 967{
968 return fetchRawPart(mail,part->Positionlist(),false); 968 return fetchRawPart(mail,part->Positionlist(),false);
969} 969}
970 970
971int IMAPwrapper::deleteAllMail(const FolderP&folder) 971int IMAPwrapper::deleteAllMail(const FolderP&folder)
972{ 972{
973 login(); 973 login();
974 if (!m_imap) { 974 if (!m_imap) {
975 return 0; 975 return 0;
976 } 976 }
977 mailimap_flag_list*flist; 977 mailimap_flag_list*flist;
978 mailimap_set *set; 978 mailimap_set *set;
979 mailimap_store_att_flags * store_flags; 979 mailimap_store_att_flags * store_flags;
980 int err = selectMbox(folder->getName()); 980 int err = selectMbox(folder->getName());
981 if ( err != MAILIMAP_NO_ERROR ) { 981 if ( err != MAILIMAP_NO_ERROR ) {
982 return 0; 982 return 0;
983 } 983 }
984 984
985 int last = m_imap->imap_selection_info->sel_exists; 985 int last = m_imap->imap_selection_info->sel_exists;
986 if (last == 0) { 986 if (last == 0) {
987 Global::statusMessage(tr("Mailbox has no mails!")); 987 Global::statusMessage(tr("Mailbox has no mails!"));
988 return 0; 988 return 0;
989 } 989 }
990 flist = mailimap_flag_list_new_empty(); 990 flist = mailimap_flag_list_new_empty();
991 mailimap_flag_list_add(flist,mailimap_flag_new_deleted()); 991 mailimap_flag_list_add(flist,mailimap_flag_new_deleted());
992 store_flags = mailimap_store_att_flags_new_set_flags(flist); 992 store_flags = mailimap_store_att_flags_new_set_flags(flist);
993 set = mailimap_set_new_interval( 1, last ); 993 set = mailimap_set_new_interval( 1, last );
994 err = mailimap_store(m_imap,set,store_flags); 994 err = mailimap_store(m_imap,set,store_flags);
995 mailimap_set_free( set ); 995 mailimap_set_free( set );
996 mailimap_store_att_flags_free(store_flags); 996 mailimap_store_att_flags_free(store_flags);
997 if (err != MAILIMAP_NO_ERROR) { 997 if (err != MAILIMAP_NO_ERROR) {
998 Global::statusMessage(tr("error deleting mail: %s").arg(m_imap->imap_response)); 998 Global::statusMessage(tr("error deleting mail: %s").arg(m_imap->imap_response));
999 return 0; 999 return 0;
1000 } 1000 }
1001 qDebug("deleting mail: %s",m_imap->imap_response); 1001 odebug << "deleting mail: " << m_imap->imap_response << "" << oendl;
1002 /* should we realy do that at this moment? */ 1002 /* should we realy do that at this moment? */
1003 err = mailimap_expunge(m_imap); 1003 err = mailimap_expunge(m_imap);
1004 if (err != MAILIMAP_NO_ERROR) { 1004 if (err != MAILIMAP_NO_ERROR) {
1005 Global::statusMessage(tr("error deleting mail: %s").arg(m_imap->imap_response)); 1005 Global::statusMessage(tr("error deleting mail: %s").arg(m_imap->imap_response));
1006 return 0; 1006 return 0;
1007 } 1007 }
1008 qDebug("Delete successfull %s",m_imap->imap_response); 1008 odebug << "Delete successfull " << m_imap->imap_response << "" << oendl;
1009 return 1; 1009 return 1;
1010} 1010}
1011 1011
1012int IMAPwrapper::createMbox(const QString&folder,const FolderP&parentfolder,const QString& delemiter,bool getsubfolder) 1012int IMAPwrapper::createMbox(const QString&folder,const FolderP&parentfolder,const QString& delemiter,bool getsubfolder)
1013{ 1013{
1014 if (folder.length()==0) return 0; 1014 if (folder.length()==0) return 0;
1015 login(); 1015 login();
1016 if (!m_imap) {return 0;} 1016 if (!m_imap) {return 0;}
1017 QString pre = account->getPrefix(); 1017 QString pre = account->getPrefix();
1018 if (delemiter.length()>0 && pre.findRev(delemiter)!=pre.length()-1) { 1018 if (delemiter.length()>0 && pre.findRev(delemiter)!=pre.length()-1) {
1019 pre+=delemiter; 1019 pre+=delemiter;
1020 } 1020 }
1021 if (parentfolder) { 1021 if (parentfolder) {
1022 pre += parentfolder->getDisplayName()+delemiter; 1022 pre += parentfolder->getDisplayName()+delemiter;
1023 } 1023 }
1024 pre+=folder; 1024 pre+=folder;
1025 if (getsubfolder) { 1025 if (getsubfolder) {
1026 if (delemiter.length()>0) { 1026 if (delemiter.length()>0) {
1027 pre+=delemiter; 1027 pre+=delemiter;
1028 } else { 1028 } else {
1029 Global::statusMessage(tr("Cannot create folder %1 for holding subfolders").arg(pre)); 1029 Global::statusMessage(tr("Cannot create folder %1 for holding subfolders").arg(pre));
1030 return 0; 1030 return 0;
1031 } 1031 }
1032 } 1032 }
1033 qDebug("Creating %s",pre.latin1()); 1033 odebug << "Creating " << pre.latin1() << "" << oendl;
1034 int res = mailimap_create(m_imap,pre.latin1()); 1034 int res = mailimap_create(m_imap,pre.latin1());
1035 if (res != MAILIMAP_NO_ERROR) { 1035 if (res != MAILIMAP_NO_ERROR) {
1036 Global::statusMessage(tr("%1").arg(m_imap->imap_response)); 1036 Global::statusMessage(tr("%1").arg(m_imap->imap_response));
1037 return 0; 1037 return 0;
1038 } 1038 }
1039 return 1; 1039 return 1;
1040} 1040}
1041 1041
1042int IMAPwrapper::deleteMbox(const FolderP&folder) 1042int IMAPwrapper::deleteMbox(const FolderP&folder)
1043{ 1043{
1044 if (!folder) return 0; 1044 if (!folder) return 0;
1045 login(); 1045 login();
1046 if (!m_imap) {return 0;} 1046 if (!m_imap) {return 0;}
1047 int res = mailimap_delete(m_imap,folder->getName()); 1047 int res = mailimap_delete(m_imap,folder->getName());
1048 if (res != MAILIMAP_NO_ERROR) { 1048 if (res != MAILIMAP_NO_ERROR) {
1049 Global::statusMessage(tr("%1").arg(m_imap->imap_response)); 1049 Global::statusMessage(tr("%1").arg(m_imap->imap_response));
1050 return 0; 1050 return 0;
1051 } 1051 }
1052 return 1; 1052 return 1;
1053} 1053}
1054 1054
1055void IMAPwrapper::statusFolder(folderStat&target_stat,const QString & mailbox) 1055void IMAPwrapper::statusFolder(folderStat&target_stat,const QString & mailbox)
1056{ 1056{
1057 mailimap_status_att_list * att_list =0; 1057 mailimap_status_att_list * att_list =0;
1058 mailimap_mailbox_data_status * status=0; 1058 mailimap_mailbox_data_status * status=0;
1059 clistiter * cur = 0; 1059 clistiter * cur = 0;
1060 int r = 0; 1060 int r = 0;
1061 target_stat.message_count = 0; 1061 target_stat.message_count = 0;
1062 target_stat.message_unseen = 0; 1062 target_stat.message_unseen = 0;
1063 target_stat.message_recent = 0; 1063 target_stat.message_recent = 0;
1064 login(); 1064 login();
1065 if (!m_imap) { 1065 if (!m_imap) {
1066 return; 1066 return;
1067 } 1067 }
1068 att_list = mailimap_status_att_list_new_empty(); 1068 att_list = mailimap_status_att_list_new_empty();
1069 if (!att_list) return; 1069 if (!att_list) return;
1070 r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_MESSAGES); 1070 r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_MESSAGES);
1071 r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_RECENT); 1071 r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_RECENT);
1072 r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_UNSEEN); 1072 r = mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_UNSEEN);
1073 r = mailimap_status(m_imap, mailbox.latin1(), att_list, &status); 1073 r = mailimap_status(m_imap, mailbox.latin1(), att_list, &status);
1074 if (r==MAILIMAP_NO_ERROR&&status->st_info_list!=0) { 1074 if (r==MAILIMAP_NO_ERROR&&status->st_info_list!=0) {
1075 for (cur = clist_begin(status->st_info_list); 1075 for (cur = clist_begin(status->st_info_list);
1076 cur != NULL ; cur = clist_next(cur)) { 1076 cur != NULL ; cur = clist_next(cur)) {
1077 mailimap_status_info * status_info; 1077 mailimap_status_info * status_info;
1078 status_info = (mailimap_status_info *)clist_content(cur); 1078 status_info = (mailimap_status_info *)clist_content(cur);
1079 switch (status_info->st_att) { 1079 switch (status_info->st_att) {
1080 case MAILIMAP_STATUS_ATT_MESSAGES: 1080 case MAILIMAP_STATUS_ATT_MESSAGES:
1081 target_stat.message_count = status_info->st_value; 1081 target_stat.message_count = status_info->st_value;
1082 break; 1082 break;
1083 case MAILIMAP_STATUS_ATT_RECENT: 1083 case MAILIMAP_STATUS_ATT_RECENT:
1084 target_stat.message_recent = status_info->st_value; 1084 target_stat.message_recent = status_info->st_value;
1085 break; 1085 break;
1086 case MAILIMAP_STATUS_ATT_UNSEEN: 1086 case MAILIMAP_STATUS_ATT_UNSEEN:
1087 target_stat.message_unseen = status_info->st_value; 1087 target_stat.message_unseen = status_info->st_value;
1088 break; 1088 break;
1089 } 1089 }
1090 } 1090 }
1091 } else { 1091 } else {
1092 qDebug("Error retrieving status"); 1092 odebug << "Error retrieving status" << oendl;
1093 } 1093 }
1094 if (status) mailimap_mailbox_data_status_free(status); 1094 if (status) mailimap_mailbox_data_status_free(status);
1095 if (att_list) mailimap_status_att_list_free(att_list); 1095 if (att_list) mailimap_status_att_list_free(att_list);
1096} 1096}
1097 1097
1098void IMAPwrapper::storeMessage(const char*msg,size_t length, const QString&folder) 1098void IMAPwrapper::storeMessage(const char*msg,size_t length, const QString&folder)
1099{ 1099{
1100 login(); 1100 login();
1101 if (!m_imap) return; 1101 if (!m_imap) return;
1102 if (!msg) return; 1102 if (!msg) return;
1103 int r = mailimap_append(m_imap,(char*)folder.latin1(),0,0,msg,length); 1103 int r = mailimap_append(m_imap,(char*)folder.latin1(),0,0,msg,length);
1104 if (r != MAILIMAP_NO_ERROR) { 1104 if (r != MAILIMAP_NO_ERROR) {
1105 Global::statusMessage("Error storing mail!"); 1105 Global::statusMessage("Error storing mail!");
1106 } 1106 }
1107} 1107}
1108 1108
1109MAILLIB::ATYPE IMAPwrapper::getType()const 1109MAILLIB::ATYPE IMAPwrapper::getType()const
1110{ 1110{
1111 return account->getType(); 1111 return account->getType();
1112} 1112}
1113 1113
1114const QString&IMAPwrapper::getName()const 1114const QString&IMAPwrapper::getName()const
1115{ 1115{
1116 qDebug("Get name: %s",account->getAccountName().latin1()); 1116 odebug << "Get name: " << account->getAccountName().latin1() << "" << oendl;
1117 return account->getAccountName(); 1117 return account->getAccountName();
1118} 1118}
1119 1119
1120encodedString* IMAPwrapper::fetchRawBody(const RecMailP&mail) 1120encodedString* IMAPwrapper::fetchRawBody(const RecMailP&mail)
1121{ 1121{
1122 // dummy 1122 // dummy
1123 QValueList<int> path; 1123 QValueList<int> path;
1124 return fetchRawPart(mail,path,false); 1124 return fetchRawPart(mail,path,false);
1125} 1125}
1126 1126
1127void IMAPwrapper::mvcpAllMails(const FolderP&fromFolder, 1127void IMAPwrapper::mvcpAllMails(const FolderP&fromFolder,
1128 const QString&targetFolder,AbstractMail*targetWrapper,bool moveit) 1128 const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
1129{ 1129{
1130 if (targetWrapper != this) { 1130 if (targetWrapper != this) {
1131 AbstractMail::mvcpAllMails(fromFolder,targetFolder,targetWrapper,moveit); 1131 AbstractMail::mvcpAllMails(fromFolder,targetFolder,targetWrapper,moveit);
1132 qDebug("Using generic"); 1132 odebug << "Using generic" << oendl;
1133 return; 1133 return;
1134 } 1134 }
1135 mailimap_set *set = 0; 1135 mailimap_set *set = 0;
1136 login(); 1136 login();
1137 if (!m_imap) { 1137 if (!m_imap) {
1138 return; 1138 return;
1139 } 1139 }
1140 int err = selectMbox(fromFolder->getName()); 1140 int err = selectMbox(fromFolder->getName());
1141 if ( err != MAILIMAP_NO_ERROR ) { 1141 if ( err != MAILIMAP_NO_ERROR ) {
1142 return; 1142 return;
1143 } 1143 }
1144 int last = m_imap->imap_selection_info->sel_exists; 1144 int last = m_imap->imap_selection_info->sel_exists;
1145 set = mailimap_set_new_interval( 1, last ); 1145 set = mailimap_set_new_interval( 1, last );
1146 err = mailimap_copy(m_imap,set,targetFolder.latin1()); 1146 err = mailimap_copy(m_imap,set,targetFolder.latin1());
1147 mailimap_set_free( set ); 1147 mailimap_set_free( set );
1148 if ( err != MAILIMAP_NO_ERROR ) { 1148 if ( err != MAILIMAP_NO_ERROR ) {
1149 QString error_msg = tr("error copy mails: %1").arg(m_imap->imap_response); 1149 QString error_msg = tr("error copy mails: %1").arg(m_imap->imap_response);
1150 Global::statusMessage(error_msg); 1150 Global::statusMessage(error_msg);
1151 qDebug(error_msg); 1151 odebug << error_msg << oendl;
1152 return; 1152 return;
1153 } 1153 }
1154 if (moveit) { 1154 if (moveit) {
1155 deleteAllMail(fromFolder); 1155 deleteAllMail(fromFolder);
1156 } 1156 }
1157} 1157}
1158 1158
1159void IMAPwrapper::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit) 1159void IMAPwrapper::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
1160{ 1160{
1161 if (targetWrapper != this) { 1161 if (targetWrapper != this) {
1162 qDebug("Using generic"); 1162 odebug << "Using generic" << oendl;
1163 AbstractMail::mvcpMail(mail,targetFolder,targetWrapper,moveit); 1163 AbstractMail::mvcpMail(mail,targetFolder,targetWrapper,moveit);
1164 return; 1164 return;
1165 } 1165 }
1166 mailimap_set *set = 0; 1166 mailimap_set *set = 0;
1167 login(); 1167 login();
1168 if (!m_imap) { 1168 if (!m_imap) {
1169 return; 1169 return;
1170 } 1170 }
1171 int err = selectMbox(mail->getMbox()); 1171 int err = selectMbox(mail->getMbox());
1172 if ( err != MAILIMAP_NO_ERROR ) { 1172 if ( err != MAILIMAP_NO_ERROR ) {
1173 return; 1173 return;
1174 } 1174 }
1175 set = mailimap_set_new_single(mail->getNumber()); 1175 set = mailimap_set_new_single(mail->getNumber());
1176 err = mailimap_copy(m_imap,set,targetFolder.latin1()); 1176 err = mailimap_copy(m_imap,set,targetFolder.latin1());
1177 mailimap_set_free( set ); 1177 mailimap_set_free( set );
1178 if ( err != MAILIMAP_NO_ERROR ) { 1178 if ( err != MAILIMAP_NO_ERROR ) {
1179 QString error_msg = tr("error copy mail: %1").arg(m_imap->imap_response); 1179 QString error_msg = tr("error copy mail: %1").arg(m_imap->imap_response);
1180 Global::statusMessage(error_msg); 1180 Global::statusMessage(error_msg);
1181 qDebug(error_msg); 1181 odebug << error_msg << oendl;
1182 return; 1182 return;
1183 } 1183 }
1184 if (moveit) { 1184 if (moveit) {
1185 deleteMail(mail); 1185 deleteMail(mail);
1186 } 1186 }
1187} 1187}
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 @@
1#include <qlineedit.h> 1#include <qlineedit.h>
2 2
3#include "logindialog.h" 3#include "logindialog.h"
4 4
5LoginDialog::LoginDialog(const QString&user,const QString&pass, QWidget *parent, const char *name, bool modal, WFlags flags ) 5LoginDialog::LoginDialog(const QString&user,const QString&pass, QWidget *parent, const char *name, bool modal, WFlags flags )
6 : LoginDialogUI( parent, name, modal, flags ) 6 : LoginDialogUI( parent, name, modal, flags )
7{ 7{
8 userLine->setText( (user.isEmpty()?QString(""):user) ); 8 userLine->setText( (user.isEmpty()?QString(""):user) );
9 passLine->setText( (pass.isEmpty()?QString(""):pass) ); 9 passLine->setText( (pass.isEmpty()?QString(""):pass) );
10 _user = user; 10 _user = user;
11 _pass = pass; 11 _pass = pass;
12 12
13 if ( user.isEmpty() ) { 13 if ( user.isEmpty() ) {
14 userLine->setFocus(); 14 userLine->setFocus();
15 } else { 15 } else {
16 passLine->setFocus(); 16 passLine->setFocus();
17 } 17 }
18} 18}
19 19
20void LoginDialog::accept() 20void LoginDialog::accept()
21{ 21{
22 //_user.replace( 0, _user.length(), userLine->text() ); 22 //_user.replace( 0, _user.length(), userLine->text() );
23 //_pass.replace( 0, _pass.length(), passLine->text() ); 23 //_pass.replace( 0, _pass.length(), passLine->text() );
24 _user = userLine->text(); 24 _user = userLine->text();
25 _pass = passLine->text(); 25 _pass = passLine->text();
26 26
27 qDebug("User im accept: |%s|",_user.latin1()); 27 odebug << "User im accept: |" << _user.latin1() << "|" << oendl;
28 QDialog::accept(); 28 QDialog::accept();
29} 29}
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 @@
1#include "mailtypes.h" 1#include "mailtypes.h"
2#include <stdlib.h> 2#include <stdlib.h>
3 3
4using namespace Opie::Core; 4using namespace Opie::Core;
5RecMail::RecMail() 5RecMail::RecMail()
6 :Opie::Core::ORefCount(),subject(""),date(""),from(""),mbox(""),msg_id(""),msg_number(0),msg_size(0),msg_flags(7) 6 :Opie::Core::ORefCount(),subject(""),date(""),from(""),mbox(""),msg_id(""),msg_number(0),msg_size(0),msg_flags(7)
7{ 7{
8 init(); 8 init();
9} 9}
10 10
11RecMail::RecMail(const RecMail&old) 11RecMail::RecMail(const RecMail&old)
12 :Opie::Core::ORefCount(),subject(""),date(""),from(""),mbox(""),msg_id(""),msg_number(0),msg_flags(7) 12 :Opie::Core::ORefCount(),subject(""),date(""),from(""),mbox(""),msg_id(""),msg_number(0),msg_flags(7)
13{ 13{
14 init(); 14 init();
15 copy_old(old); 15 copy_old(old);
16 qDebug("Copy constructor RecMail"); 16 odebug << "Copy constructor RecMail" << oendl;
17} 17}
18 18
19RecMail::~RecMail() 19RecMail::~RecMail()
20{ 20{
21 wrapper = 0; 21 wrapper = 0;
22} 22}
23 23
24void RecMail::copy_old(const RecMail&old) 24void RecMail::copy_old(const RecMail&old)
25{ 25{
26 subject = old.subject; 26 subject = old.subject;
27 date = old.date; 27 date = old.date;
28 mbox = old.mbox; 28 mbox = old.mbox;
29 msg_id = old.msg_id; 29 msg_id = old.msg_id;
30 msg_size = old.msg_size; 30 msg_size = old.msg_size;
31 msg_number = old.msg_number; 31 msg_number = old.msg_number;
32 from = old.from; 32 from = old.from;
33 msg_flags = old.msg_flags; 33 msg_flags = old.msg_flags;
34 to = old.to; 34 to = old.to;
35 cc = old.cc; 35 cc = old.cc;
36 bcc = old.bcc; 36 bcc = old.bcc;
37 wrapper = old.wrapper; 37 wrapper = old.wrapper;
38 in_reply_to = old.in_reply_to; 38 in_reply_to = old.in_reply_to;
39 references = old.references; 39 references = old.references;
40 replyto = old.replyto; 40 replyto = old.replyto;
41} 41}
42 42
43void RecMail::init() 43void RecMail::init()
44{ 44{
45 to.clear(); 45 to.clear();
46 cc.clear(); 46 cc.clear();
47 bcc.clear(); 47 bcc.clear();
48 in_reply_to.clear(); 48 in_reply_to.clear();
49 references.clear(); 49 references.clear();
50 wrapper = 0; 50 wrapper = 0;
51} 51}
52 52
53void RecMail::setWrapper(AbstractMail*awrapper) 53void RecMail::setWrapper(AbstractMail*awrapper)
54{ 54{
55 wrapper = awrapper; 55 wrapper = awrapper;
56} 56}
57 57
58AbstractMail* RecMail::Wrapper() 58AbstractMail* RecMail::Wrapper()
59{ 59{
60 return wrapper; 60 return wrapper;
61} 61}
62 62
63void RecMail::setTo(const QStringList&list) 63void RecMail::setTo(const QStringList&list)
64{ 64{
65 to = list; 65 to = list;
66} 66}
67 67
68const QStringList&RecMail::To()const 68const QStringList&RecMail::To()const
69{ 69{
70 return to; 70 return to;
71} 71}
72 72
73void RecMail::setCC(const QStringList&list) 73void RecMail::setCC(const QStringList&list)
74{ 74{
75 cc = list; 75 cc = list;
76} 76}
77 77
78const QStringList&RecMail::CC()const 78const QStringList&RecMail::CC()const
79{ 79{
80 return cc; 80 return cc;
81} 81}
82 82
83void RecMail::setBcc(const QStringList&list) 83void RecMail::setBcc(const QStringList&list)
84{ 84{
85 bcc = list; 85 bcc = list;
86} 86}
87 87
88const QStringList& RecMail::Bcc()const 88const QStringList& RecMail::Bcc()const
89{ 89{
90 return bcc; 90 return bcc;
91} 91}
92 92
93void RecMail::setInreply(const QStringList&list) 93void RecMail::setInreply(const QStringList&list)
94{ 94{
95 in_reply_to = list; 95 in_reply_to = list;
96} 96}
97 97
98const QStringList& RecMail::Inreply()const 98const QStringList& RecMail::Inreply()const
99{ 99{
100 return in_reply_to; 100 return in_reply_to;
101} 101}
102 102
103void RecMail::setReferences(const QStringList&list) 103void RecMail::setReferences(const QStringList&list)
104{ 104{
105 references = list; 105 references = list;
106} 106}
107 107
108const QStringList& RecMail::References()const 108const QStringList& RecMail::References()const
109{ 109{
110 return references; 110 return references;
111} 111}
112 112
113RecPart::RecPart() 113RecPart::RecPart()
114 : Opie::Core::ORefCount(), 114 : Opie::Core::ORefCount(),
115 m_type(""),m_subtype(""),m_identifier(""),m_encoding(""),m_description(""),m_lines(0),m_size(0) 115 m_type(""),m_subtype(""),m_identifier(""),m_encoding(""),m_description(""),m_lines(0),m_size(0)
116{ 116{
117 m_Parameters.clear(); 117 m_Parameters.clear();
118 m_poslist.clear(); 118 m_poslist.clear();
119} 119}
120 120
121RecPart::RecPart(const RecPart&old) 121RecPart::RecPart(const RecPart&old)
122 : Opie::Core::ORefCount(), 122 : Opie::Core::ORefCount(),
123 m_type(""),m_subtype(""),m_identifier(""),m_encoding(""),m_description(""),m_lines(0),m_size(0) 123 m_type(""),m_subtype(""),m_identifier(""),m_encoding(""),m_description(""),m_lines(0),m_size(0)
124{ 124{
125 m_type = old.m_type; 125 m_type = old.m_type;
126 m_subtype = old.m_subtype; 126 m_subtype = old.m_subtype;
127 m_identifier = old.m_identifier; 127 m_identifier = old.m_identifier;
128 m_encoding = old.m_encoding; 128 m_encoding = old.m_encoding;
129 m_description = old.m_description; 129 m_description = old.m_description;
130 m_lines = old.m_lines; 130 m_lines = old.m_lines;
131 m_size = old.m_size; 131 m_size = old.m_size;
132 m_Parameters = old.m_Parameters; 132 m_Parameters = old.m_Parameters;
133 m_poslist = old.m_poslist; 133 m_poslist = old.m_poslist;
134 qDebug("RecPart copy constructor"); 134 odebug << "RecPart copy constructor" << oendl;
135} 135}
136 136
137RecPart::~RecPart() 137RecPart::~RecPart()
138{ 138{
139} 139}
140 140
141void RecPart::setSize(unsigned int size) 141void RecPart::setSize(unsigned int size)
142{ 142{
143 m_size = size; 143 m_size = size;
144} 144}
145 145
146const unsigned int RecPart::Size()const 146const unsigned int RecPart::Size()const
147{ 147{
148 return m_size; 148 return m_size;
149} 149}
150 150
151void RecPart::setLines(unsigned int lines) 151void RecPart::setLines(unsigned int lines)
152{ 152{
153 m_lines = lines; 153 m_lines = lines;
154} 154}
155 155
156const unsigned int RecPart::Lines()const 156const unsigned int RecPart::Lines()const
157{ 157{
158 return m_lines; 158 return m_lines;
159} 159}
160 160
161const QString& RecPart::Type()const 161const QString& RecPart::Type()const
162{ 162{
163 return m_type; 163 return m_type;
164} 164}
165 165
166void RecPart::setType(const QString&type) 166void RecPart::setType(const QString&type)
167{ 167{
168 m_type = type; 168 m_type = type;
169} 169}
170 170
171const QString& RecPart::Subtype()const 171const QString& RecPart::Subtype()const
172{ 172{
173 return m_subtype; 173 return m_subtype;
174} 174}
175 175
176void RecPart::setSubtype(const QString&subtype) 176void RecPart::setSubtype(const QString&subtype)
177{ 177{
178 m_subtype = subtype; 178 m_subtype = subtype;
179} 179}
180 180
181const QString& RecPart::Identifier()const 181const QString& RecPart::Identifier()const
182{ 182{
183 return m_identifier; 183 return m_identifier;
184} 184}
185 185
186void RecPart::setIdentifier(const QString&identifier) 186void RecPart::setIdentifier(const QString&identifier)
187{ 187{
188 m_identifier = identifier; 188 m_identifier = identifier;
189} 189}
190 190
191const QString& RecPart::Encoding()const 191const QString& RecPart::Encoding()const
192{ 192{
193 return m_encoding; 193 return m_encoding;
194} 194}
195 195
196void RecPart::setEncoding(const QString&encoding) 196void RecPart::setEncoding(const QString&encoding)
197{ 197{
198 m_encoding = encoding; 198 m_encoding = encoding;
199} 199}
200 200
201const QString& RecPart::Description()const 201const QString& RecPart::Description()const
202{ 202{
203 return m_description; 203 return m_description;
204} 204}
205 205
206void RecPart::setDescription(const QString&desc) 206void RecPart::setDescription(const QString&desc)
207{ 207{
208 m_description = desc; 208 m_description = desc;
209} 209}
210 210
211void RecPart::setParameters(const part_plist_t&list) 211void RecPart::setParameters(const part_plist_t&list)
212{ 212{
213 m_Parameters = list; 213 m_Parameters = list;
214} 214}
215 215
216const part_plist_t& RecPart::Parameters()const 216const part_plist_t& RecPart::Parameters()const
217{ 217{
218 return m_Parameters; 218 return m_Parameters;
219} 219}
220 220
221void RecPart::addParameter(const QString&key,const QString&value) 221void RecPart::addParameter(const QString&key,const QString&value)
222{ 222{
223 m_Parameters[key]=value; 223 m_Parameters[key]=value;
224} 224}
225 225
226const QString RecPart::searchParamter(const QString&key)const 226const QString RecPart::searchParamter(const QString&key)const
227{ 227{
228 QString value(""); 228 QString value("");
229 part_plist_t::ConstIterator it = m_Parameters.find(key); 229 part_plist_t::ConstIterator it = m_Parameters.find(key);
230 if (it != m_Parameters.end()) { 230 if (it != m_Parameters.end()) {
231 value = it.data(); 231 value = it.data();
232 } 232 }
233 return value; 233 return value;
234} 234}
235 235
236void RecPart::setPositionlist(const QValueList<int>&poslist) 236void RecPart::setPositionlist(const QValueList<int>&poslist)
237{ 237{
238 m_poslist = poslist; 238 m_poslist = poslist;
239} 239}
240 240
241const QValueList<int>& RecPart::Positionlist()const 241const QValueList<int>& RecPart::Positionlist()const
242{ 242{
243 return m_poslist; 243 return m_poslist;
244} 244}
245 245
246RecBody::RecBody() 246RecBody::RecBody()
247 : Opie::Core::ORefCount(),m_BodyText(),m_description(new RecPart()) 247 : Opie::Core::ORefCount(),m_BodyText(),m_description(new RecPart())
248{ 248{
249 m_PartsList.clear(); 249 m_PartsList.clear();
250} 250}
251 251
252RecBody::RecBody(const RecBody&old) 252RecBody::RecBody(const RecBody&old)
253 :Opie::Core::ORefCount(),m_BodyText(),m_PartsList(),m_description(new RecPart()) 253 :Opie::Core::ORefCount(),m_BodyText(),m_PartsList(),m_description(new RecPart())
254{ 254{
255 m_BodyText = old.m_BodyText; 255 m_BodyText = old.m_BodyText;
256 m_PartsList = old.m_PartsList; 256 m_PartsList = old.m_PartsList;
257 m_description = old.m_description; 257 m_description = old.m_description;
258 qDebug("Recbody copy constructor"); 258 odebug << "Recbody copy constructor" << oendl;
259} 259}
260 260
261RecBody::~RecBody() 261RecBody::~RecBody()
262{ 262{
263} 263}
264 264
265void RecBody::setBodytext(const QString&bodyText) 265void RecBody::setBodytext(const QString&bodyText)
266{ 266{
267 m_BodyText = bodyText; 267 m_BodyText = bodyText;
268} 268}
269 269
270const QString& RecBody::Bodytext()const 270const QString& RecBody::Bodytext()const
271{ 271{
272 return m_BodyText; 272 return m_BodyText;
273} 273}
274 274
275void RecBody::setParts(const QValueList<RecPartP>&parts) 275void RecBody::setParts(const QValueList<RecPartP>&parts)
276{ 276{
277 m_PartsList.clear(); 277 m_PartsList.clear();
278 m_PartsList = parts; 278 m_PartsList = parts;
279} 279}
280 280
281const QValueList<RecPartP>& RecBody::Parts()const 281const QValueList<RecPartP>& RecBody::Parts()const
282{ 282{
283 return m_PartsList; 283 return m_PartsList;
284} 284}
285 285
286void RecBody::addPart(const RecPartP& part) 286void RecBody::addPart(const RecPartP& part)
287{ 287{
288 m_PartsList.append(part); 288 m_PartsList.append(part);
289} 289}
290 290
291void RecBody::setDescription(const RecPartP&des) 291void RecBody::setDescription(const RecPartP&des)
292{ 292{
293 m_description = des; 293 m_description = des;
294} 294}
295 295
296const RecPartP& RecBody::Description()const 296const RecPartP& RecBody::Description()const
297{ 297{
298 return m_description; 298 return m_description;
299} 299}
300 300
301/* handling encoded content */ 301/* handling encoded content */
302encodedString::encodedString() 302encodedString::encodedString()
303{ 303{
304 init(); 304 init();
305} 305}
306 306
307encodedString::encodedString(const char*nContent,unsigned int nSize) 307encodedString::encodedString(const char*nContent,unsigned int nSize)
308{ 308{
309 init(); 309 init();
310 setContent(nContent,nSize); 310 setContent(nContent,nSize);
311} 311}
312 312
313encodedString::encodedString(char*nContent,unsigned int nSize) 313encodedString::encodedString(char*nContent,unsigned int nSize)
314{ 314{
315 init(); 315 init();
316 setContent(nContent,nSize); 316 setContent(nContent,nSize);
317} 317}
318 318
319encodedString::encodedString(const encodedString&old) 319encodedString::encodedString(const encodedString&old)
320{ 320{
321 init(); 321 init();
322 copy_old(old); 322 copy_old(old);
323 qDebug("encodedeString: copy constructor!"); 323 odebug << "encodedeString: copy constructor!" << oendl;
324} 324}
325 325
326encodedString& encodedString::operator=(const encodedString&old) 326encodedString& encodedString::operator=(const encodedString&old)
327{ 327{
328 init(); 328 init();
329 copy_old(old); 329 copy_old(old);
330 qDebug("encodedString: assign operator!"); 330 odebug << "encodedString: assign operator!" << oendl;
331 return *this; 331 return *this;
332} 332}
333 333
334encodedString::~encodedString() 334encodedString::~encodedString()
335{ 335{
336 clean(); 336 clean();
337} 337}
338 338
339void encodedString::init() 339void encodedString::init()
340{ 340{
341 content = 0; 341 content = 0;
342 size = 0; 342 size = 0;
343} 343}
344 344
345void encodedString::clean() 345void encodedString::clean()
346{ 346{
347 if (content) { 347 if (content) {
348 free(content); 348 free(content);
349 } 349 }
350 content = 0; 350 content = 0;
351 size = 0; 351 size = 0;
352} 352}
353 353
354void encodedString::copy_old(const encodedString&old) 354void encodedString::copy_old(const encodedString&old)
355{ 355{
356 clean(); 356 clean();
357 if (old.size>0 && old.content) { 357 if (old.size>0 && old.content) {
358 content = (char*)malloc(old.size*sizeof(char)); 358 content = (char*)malloc(old.size*sizeof(char));
359 memcpy(content,old.content,size); 359 memcpy(content,old.content,size);
360 size = old.size; 360 size = old.size;
361 } 361 }
362} 362}
363 363
364const char*encodedString::Content()const 364const char*encodedString::Content()const
365{ 365{
366 return content; 366 return content;
367} 367}
368 368
369const int encodedString::Length()const 369const int encodedString::Length()const
370{ 370{
371 return size; 371 return size;
372} 372}
373 373
374void encodedString::setContent(const char*nContent,int nSize) 374void encodedString::setContent(const char*nContent,int nSize)
375{ 375{
376 if (nSize>0 && nContent) { 376 if (nSize>0 && nContent) {
377 content = (char*)malloc(nSize*sizeof(char)); 377 content = (char*)malloc(nSize*sizeof(char));
378 memcpy(content,nContent,nSize); 378 memcpy(content,nContent,nSize);
379 size = nSize; 379 size = nSize;
380 } 380 }
381} 381}
382 382
383void encodedString::setContent(char*nContent,int nSize) 383void encodedString::setContent(char*nContent,int nSize)
384{ 384{
385 content = nContent; 385 content = nContent;
386 size = nSize; 386 size = nSize;
387} 387}
388 388
389folderStat&folderStat::operator=(const folderStat&old) 389folderStat&folderStat::operator=(const folderStat&old)
390{ 390{
391 message_count = old.message_count; 391 message_count = old.message_count;
392 message_unseen = old.message_unseen; 392 message_unseen = old.message_unseen;
393 message_recent = old.message_recent; 393 message_recent = old.message_recent;
394 return *this; 394 return *this;
395} 395}
396 396
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 @@
1#include <stdlib.h> 1#include <stdlib.h>
2#include <sys/stat.h> 2#include <sys/stat.h>
3#include <sys/types.h> 3#include <sys/types.h>
4#include <unistd.h> 4#include <unistd.h>
5#include <fcntl.h> 5#include <fcntl.h>
6#include <string.h> 6#include <string.h>
7#include <qdir.h> 7#include <qdir.h>
8 8
9#include "mailwrapper.h" 9#include "mailwrapper.h"
10//#include "logindialog.h" 10//#include "logindialog.h"
11//#include "defines.h" 11//#include "defines.h"
12 12
13#define UNDEFINED 64 13#define UNDEFINED 64
14#define MAXLINE 76 14#define MAXLINE 76
15#define UTF16MASK 0x03FFUL 15#define UTF16MASK 0x03FFUL
16#define UTF16SHIFT 10 16#define UTF16SHIFT 10
17#define UTF16BASE 0x10000UL 17#define UTF16BASE 0x10000UL
18#define UTF16HIGHSTART 0xD800UL 18#define UTF16HIGHSTART 0xD800UL
19#define UTF16HIGHEND 0xDBFFUL 19#define UTF16HIGHEND 0xDBFFUL
20#define UTF16LOSTART 0xDC00UL 20#define UTF16LOSTART 0xDC00UL
21#define UTF16LOEND 0xDFFFUL 21#define UTF16LOEND 0xDFFFUL
22 22
23 23
24using namespace Opie::Core; 24using namespace Opie::Core;
25Attachment::Attachment( DocLnk lnk ) 25Attachment::Attachment( DocLnk lnk )
26{ 26{
27 doc = lnk; 27 doc = lnk;
28 size = QFileInfo( doc.file() ).size(); 28 size = QFileInfo( doc.file() ).size();
29} 29}
30 30
31Folder::Folder(const QString&tmp_name, const QString&sep ) 31Folder::Folder(const QString&tmp_name, const QString&sep )
32{ 32{
33 name = tmp_name; 33 name = tmp_name;
34 nameDisplay = name; 34 nameDisplay = name;
35 separator = sep; 35 separator = sep;
36 prefix = ""; 36 prefix = "";
37} 37}
38 38
39Folder::~Folder() 39Folder::~Folder()
40{ 40{
41} 41}
42 42
43const QString& Folder::Separator()const 43const QString& Folder::Separator()const
44{ 44{
45 return separator; 45 return separator;
46} 46}
47 47
48IMAPFolder::IMAPFolder(const QString&name,const QString&sep, bool select,bool no_inf, const QString&aprefix ) 48IMAPFolder::IMAPFolder(const QString&name,const QString&sep, bool select,bool no_inf, const QString&aprefix )
49 : Folder( name,sep ),m_MaySelect(select),m_NoInferior(no_inf) 49 : Folder( name,sep ),m_MaySelect(select),m_NoInferior(no_inf)
50{ 50{
51 // Decode IMAP foldername 51 // Decode IMAP foldername
52 nameDisplay = IMAPFolder::decodeFolderName( name ); 52 nameDisplay = IMAPFolder::decodeFolderName( name );
53 /* 53 /*
54 qDebug( "folder " + name + " - displayed as " + nameDisplay ); 54 odebug << "folder " + name + " - displayed as " + nameDisplay << oendl;
55 */ 55 */
56 prefix = aprefix; 56 prefix = aprefix;
57 57
58 if (prefix.length()>0) { 58 if (prefix.length()>0) {
59 if (nameDisplay.startsWith(prefix) && nameDisplay.length()>prefix.length()) { 59 if (nameDisplay.startsWith(prefix) && nameDisplay.length()>prefix.length()) {
60 nameDisplay=nameDisplay.right(nameDisplay.length()-prefix.length()); 60 nameDisplay=nameDisplay.right(nameDisplay.length()-prefix.length());
61 } 61 }
62 } 62 }
63} 63}
64 64
65IMAPFolder::~IMAPFolder() 65IMAPFolder::~IMAPFolder()
66{ 66{
67} 67}
68 68
69static unsigned char base64chars[] = 69static unsigned char base64chars[] =
70 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,"; 70 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
71 71
72/** 72/**
73 * Decodes base64 encoded parts of the imapfolder name 73 * Decodes base64 encoded parts of the imapfolder name
74 * Code taken from kde cvs: kdebase/kioslave/imap4/rfcdecoder.cc 74 * Code taken from kde cvs: kdebase/kioslave/imap4/rfcdecoder.cc
75 */ 75 */
76QString IMAPFolder::decodeFolderName( const QString &name ) 76QString IMAPFolder::decodeFolderName( const QString &name )
77{ 77{
78 unsigned char c, i, bitcount; 78 unsigned char c, i, bitcount;
79 unsigned long ucs4, utf16, bitbuf; 79 unsigned long ucs4, utf16, bitbuf;
80 unsigned char base64[256], utf8[6]; 80 unsigned char base64[256], utf8[6];
81 unsigned long srcPtr = 0; 81 unsigned long srcPtr = 0;
82 QCString dst = ""; 82 QCString dst = "";
83 QCString src = name.ascii(); 83 QCString src = name.ascii();
84 84
85 /* initialize modified base64 decoding table */ 85 /* initialize modified base64 decoding table */
86 memset(base64, UNDEFINED, sizeof(base64)); 86 memset(base64, UNDEFINED, sizeof(base64));
87 for (i = 0; i < sizeof(base64chars); ++i) { 87 for (i = 0; i < sizeof(base64chars); ++i) {
88 base64[(int)base64chars[i]] = i; 88 base64[(int)base64chars[i]] = i;
89 } 89 }
90 90
91 /* loop until end of string */ 91 /* loop until end of string */
92 while (srcPtr < src.length ()) { 92 while (srcPtr < src.length ()) {
93 c = src[srcPtr++]; 93 c = src[srcPtr++];
94 /* deal with literal characters and &- */ 94 /* deal with literal characters and &- */
95 if (c != '&' || src[srcPtr] == '-') { 95 if (c != '&' || src[srcPtr] == '-') {
96 /* encode literally */ 96 /* encode literally */
97 dst += c; 97 dst += c;
98 /* skip over the '-' if this is an &- sequence */ 98 /* skip over the '-' if this is an &- sequence */
99 if (c == '&') 99 if (c == '&')
100 srcPtr++; 100 srcPtr++;
101 } else { 101 } else {
102 /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */ 102 /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
103 bitbuf = 0; 103 bitbuf = 0;
104 bitcount = 0; 104 bitcount = 0;
105 ucs4 = 0; 105 ucs4 = 0;
106 while ((c = base64[(unsigned char) src[srcPtr]]) != UNDEFINED) { 106 while ((c = base64[(unsigned char) src[srcPtr]]) != UNDEFINED) {
107 ++srcPtr; 107 ++srcPtr;
108 bitbuf = (bitbuf << 6) | c; 108 bitbuf = (bitbuf << 6) | c;
109 bitcount += 6; 109 bitcount += 6;
110 /* enough bits for a UTF-16 character? */ 110 /* enough bits for a UTF-16 character? */
111 if (bitcount >= 16) { 111 if (bitcount >= 16) {
112 bitcount -= 16; 112 bitcount -= 16;
113 utf16 = (bitcount ? bitbuf >> bitcount : bitbuf) & 0xffff; 113 utf16 = (bitcount ? bitbuf >> bitcount : bitbuf) & 0xffff;
114 /* convert UTF16 to UCS4 */ 114 /* convert UTF16 to UCS4 */
115 if (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) { 115 if (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
116 ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT; 116 ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
117 continue; 117 continue;
118 } else if (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) { 118 } else if (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
119 ucs4 += utf16 - UTF16LOSTART + UTF16BASE; 119 ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
120 } else { 120 } else {
121 ucs4 = utf16; 121 ucs4 = utf16;
122 } 122 }
123 /* convert UTF-16 range of UCS4 to UTF-8 */ 123 /* convert UTF-16 range of UCS4 to UTF-8 */
124 if (ucs4 <= 0x7fUL) { 124 if (ucs4 <= 0x7fUL) {
125 utf8[0] = ucs4; 125 utf8[0] = ucs4;
126 i = 1; 126 i = 1;
127 } else if (ucs4 <= 0x7ffUL) { 127 } else if (ucs4 <= 0x7ffUL) {
128 utf8[0] = 0xc0 | (ucs4 >> 6); 128 utf8[0] = 0xc0 | (ucs4 >> 6);
129 utf8[1] = 0x80 | (ucs4 & 0x3f); 129 utf8[1] = 0x80 | (ucs4 & 0x3f);
130 i = 2; 130 i = 2;
131 } else if (ucs4 <= 0xffffUL) { 131 } else if (ucs4 <= 0xffffUL) {
132 utf8[0] = 0xe0 | (ucs4 >> 12); 132 utf8[0] = 0xe0 | (ucs4 >> 12);
133 utf8[1] = 0x80 | ((ucs4 >> 6) & 0x3f); 133 utf8[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
134 utf8[2] = 0x80 | (ucs4 & 0x3f); 134 utf8[2] = 0x80 | (ucs4 & 0x3f);
135 i = 3; 135 i = 3;
136 } else { 136 } else {
137 utf8[0] = 0xf0 | (ucs4 >> 18); 137 utf8[0] = 0xf0 | (ucs4 >> 18);
138 utf8[1] = 0x80 | ((ucs4 >> 12) & 0x3f); 138 utf8[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
139 utf8[2] = 0x80 | ((ucs4 >> 6) & 0x3f); 139 utf8[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
140 utf8[3] = 0x80 | (ucs4 & 0x3f); 140 utf8[3] = 0x80 | (ucs4 & 0x3f);
141 i = 4; 141 i = 4;
142 } 142 }
143 /* copy it */ 143 /* copy it */
144 for (c = 0; c < i; ++c) { 144 for (c = 0; c < i; ++c) {
145 dst += utf8[c]; 145 dst += utf8[c];
146 } 146 }
147 } 147 }
148 } 148 }
149 /* skip over trailing '-' in modified UTF-7 encoding */ 149 /* skip over trailing '-' in modified UTF-7 encoding */
150 if (src[srcPtr] == '-') 150 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 @@
1#include "mboxwrapper.h" 1#include "mboxwrapper.h"
2#include "mailtypes.h" 2#include "mailtypes.h"
3#include "mailwrapper.h" 3#include "mailwrapper.h"
4#include <libetpan/libetpan.h> 4#include <libetpan/libetpan.h>
5#include <qdir.h> 5#include <qdir.h>
6#include <stdlib.h> 6#include <stdlib.h>
7#include <qpe/global.h> 7#include <qpe/global.h>
8 8
9using namespace Opie::Core; 9using namespace Opie::Core;
10MBOXwrapper::MBOXwrapper(const QString & mbox_dir,const QString&mbox_name) 10MBOXwrapper::MBOXwrapper(const QString & mbox_dir,const QString&mbox_name)
11 : Genericwrapper(),MBOXPath(mbox_dir),MBOXName(mbox_name) 11 : Genericwrapper(),MBOXPath(mbox_dir),MBOXName(mbox_name)
12{ 12{
13 QDir dir(MBOXPath); 13 QDir dir(MBOXPath);
14 if (!dir.exists()) { 14 if (!dir.exists()) {
15 dir.mkdir(MBOXPath); 15 dir.mkdir(MBOXPath);
16 } 16 }
17} 17}
18 18
19MBOXwrapper::~MBOXwrapper() 19MBOXwrapper::~MBOXwrapper()
20{ 20{
21} 21}
22 22
23void MBOXwrapper::listMessages(const QString & mailbox, QValueList<RecMailP> &target ) 23void MBOXwrapper::listMessages(const QString & mailbox, QValueList<RecMailP> &target )
24{ 24{
25 mailstorage*storage = mailstorage_new(NULL); 25 mailstorage*storage = mailstorage_new(NULL);
26 QString p = MBOXPath+"/"; 26 QString p = MBOXPath+"/";
27 p+=mailbox; 27 p+=mailbox;
28 28
29 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0); 29 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
30 mailfolder*folder; 30 mailfolder*folder;
31 folder = mailfolder_new( storage,(char*)p.latin1(),NULL); 31 folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
32 r = mailfolder_connect(folder); 32 r = mailfolder_connect(folder);
33 if (r != MAIL_NO_ERROR) { 33 if (r != MAIL_NO_ERROR) {
34 qDebug("Error initializing mbox"); 34 odebug << "Error initializing mbox" << oendl;
35 mailfolder_free(folder); 35 mailfolder_free(folder);
36 mailstorage_free(storage); 36 mailstorage_free(storage);
37 return; 37 return;
38 } 38 }
39 39
40 parseList(target,folder->fld_session,mailbox); 40 parseList(target,folder->fld_session,mailbox);
41 41
42 mailfolder_disconnect(folder); 42 mailfolder_disconnect(folder);
43 mailfolder_free(folder); 43 mailfolder_free(folder);
44 mailstorage_free(storage); 44 mailstorage_free(storage);
45 Global::statusMessage(tr("Mailbox has %1 mail(s)").arg(target.count())); 45 Global::statusMessage(tr("Mailbox has %1 mail(s)").arg(target.count()));
46} 46}
47 47
48QValueList<Opie::Core::OSmartPointer<Folder> >* MBOXwrapper::listFolders() 48QValueList<Opie::Core::OSmartPointer<Folder> >* MBOXwrapper::listFolders()
49{ 49{
50 QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >(); 50 QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >();
51 QDir dir(MBOXPath); 51 QDir dir(MBOXPath);
52 if (!dir.exists()) return folders; 52 if (!dir.exists()) return folders;
53 dir.setFilter(QDir::Files|QDir::Writable|QDir::Readable); 53 dir.setFilter(QDir::Files|QDir::Writable|QDir::Readable);
54 QStringList entries = dir.entryList(); 54 QStringList entries = dir.entryList();
55 QStringList::ConstIterator it = entries.begin(); 55 QStringList::ConstIterator it = entries.begin();
56 for (;it!=entries.end();++it) { 56 for (;it!=entries.end();++it) {
57 FolderP inb=new Folder(*it,"/"); 57 FolderP inb=new Folder(*it,"/");
58 folders->append(inb); 58 folders->append(inb);
59 } 59 }
60 return folders; 60 return folders;
61} 61}
62 62
63void MBOXwrapper::deleteMail(const RecMailP & mail) 63void MBOXwrapper::deleteMail(const RecMailP & mail)
64{ 64{
65 mailstorage*storage = mailstorage_new(NULL); 65 mailstorage*storage = mailstorage_new(NULL);
66 QString p = MBOXPath+"/"; 66 QString p = MBOXPath+"/";
67 p+=mail->getMbox(); 67 p+=mail->getMbox();
68 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0); 68 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
69 mailfolder*folder; 69 mailfolder*folder;
70 folder = mailfolder_new( storage,(char*)p.latin1(),NULL); 70 folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
71 r = mailfolder_connect(folder); 71 r = mailfolder_connect(folder);
72 if (r != MAIL_NO_ERROR) { 72 if (r != MAIL_NO_ERROR) {
73 qDebug("Error initializing mbox"); 73 odebug << "Error initializing mbox" << oendl;
74 mailfolder_free(folder); 74 mailfolder_free(folder);
75 mailstorage_free(storage); 75 mailstorage_free(storage);
76 return; 76 return;
77 } 77 }
78 r = mailsession_remove_message(folder->fld_session,mail->getNumber()); 78 r = mailsession_remove_message(folder->fld_session,mail->getNumber());
79 if (r != MAIL_NO_ERROR) { 79 if (r != MAIL_NO_ERROR) {
80 qDebug("error deleting mail"); 80 odebug << "error deleting mail" << oendl;
81 } 81 }
82 mailfolder_free(folder); 82 mailfolder_free(folder);
83 mailstorage_free(storage); 83 mailstorage_free(storage);
84} 84}
85 85
86void MBOXwrapper::answeredMail(const RecMailP&) 86void MBOXwrapper::answeredMail(const RecMailP&)
87{ 87{
88} 88}
89 89
90RecBodyP MBOXwrapper::fetchBody( const RecMailP &mail ) 90RecBodyP MBOXwrapper::fetchBody( const RecMailP &mail )
91{ 91{
92 RecBodyP body = new RecBody(); 92 RecBodyP body = new RecBody();
93 mailstorage*storage = mailstorage_new(NULL); 93 mailstorage*storage = mailstorage_new(NULL);
94 QString p = MBOXPath+"/"; 94 QString p = MBOXPath+"/";
95 p+=mail->getMbox(); 95 p+=mail->getMbox();
96 mailmessage * msg; 96 mailmessage * msg;
97 char*data=0; 97 char*data=0;
98 size_t size; 98 size_t size;
99 99
100 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0); 100 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
101 mailfolder*folder; 101 mailfolder*folder;
102 folder = mailfolder_new( storage,(char*)p.latin1(),NULL); 102 folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
103 r = mailfolder_connect(folder); 103 r = mailfolder_connect(folder);
104 if (r != MAIL_NO_ERROR) { 104 if (r != MAIL_NO_ERROR) {
105 qDebug("Error initializing mbox"); 105 odebug << "Error initializing mbox" << oendl;
106 mailfolder_free(folder); 106 mailfolder_free(folder);
107 mailstorage_free(storage); 107 mailstorage_free(storage);
108 return body; 108 return body;
109 } 109 }
110 r = mailsession_get_message(folder->fld_session, mail->getNumber(), &msg); 110 r = mailsession_get_message(folder->fld_session, mail->getNumber(), &msg);
111 if (r != MAIL_NO_ERROR) { 111 if (r != MAIL_NO_ERROR) {
112 qDebug("Error fetching mail %i",mail->getNumber()); 112 odebug << "Error fetching mail " << mail->getNumber() << "" << oendl;
113 mailfolder_free(folder); 113 mailfolder_free(folder);
114 mailstorage_free(storage); 114 mailstorage_free(storage);
115 return body; 115 return body;
116 } 116 }
117 r = mailmessage_fetch(msg,&data,&size); 117 r = mailmessage_fetch(msg,&data,&size);
118 if (r != MAIL_NO_ERROR) { 118 if (r != MAIL_NO_ERROR) {
119 qDebug("Error fetching mail %i",mail->getNumber()); 119 odebug << "Error fetching mail " << mail->getNumber() << "" << oendl;
120 mailfolder_free(folder); 120 mailfolder_free(folder);
121 mailstorage_free(storage); 121 mailstorage_free(storage);
122 mailmessage_free(msg); 122 mailmessage_free(msg);
123 return body; 123 return body;
124 } 124 }
125 body = parseMail(msg); 125 body = parseMail(msg);
126 mailmessage_fetch_result_free(msg,data); 126 mailmessage_fetch_result_free(msg,data);
127 mailfolder_free(folder); 127 mailfolder_free(folder);
128 mailstorage_free(storage); 128 mailstorage_free(storage);
129 129
130 return body; 130 return body;
131} 131}
132 132
133void MBOXwrapper::mbox_progress( size_t current, size_t maximum ) 133void MBOXwrapper::mbox_progress( size_t current, size_t maximum )
134{ 134{
135 qDebug("MBOX %i von %i",current,maximum); 135 odebug << "MBOX " << current << " von " << maximum << "" << oendl;
136} 136}
137 137
138int MBOXwrapper::createMbox(const QString&folder,const FolderP&,const QString&,bool ) 138int MBOXwrapper::createMbox(const QString&folder,const FolderP&,const QString&,bool )
139{ 139{
140 QString p = MBOXPath+"/"; 140 QString p = MBOXPath+"/";
141 p+=folder; 141 p+=folder;
142 QFileInfo fi(p); 142 QFileInfo fi(p);
143 if (fi.exists()) { 143 if (fi.exists()) {
144 Global::statusMessage(tr("Mailbox exists.")); 144 Global::statusMessage(tr("Mailbox exists."));
145 return 0; 145 return 0;
146 } 146 }
147 mailmbox_folder*f = 0; 147 mailmbox_folder*f = 0;
148 if (mailmbox_init(p.latin1(),0,1,0,&f) != MAIL_NO_ERROR) { 148 if (mailmbox_init(p.latin1(),0,1,0,&f) != MAIL_NO_ERROR) {
149 Global::statusMessage(tr("Error init folder")); 149 Global::statusMessage(tr("Error init folder"));
150 return 0; 150 return 0;
151 } 151 }
152 if (f) mailmbox_done(f); 152 if (f) mailmbox_done(f);
153 return 1; 153 return 1;
154} 154}
155 155
156void MBOXwrapper::storeMessage(const char*msg,size_t length, const QString&folder) 156void MBOXwrapper::storeMessage(const char*msg,size_t length, const QString&folder)
157{ 157{
158 QString p = MBOXPath+"/"; 158 QString p = MBOXPath+"/";
159 p+=folder; 159 p+=folder;
160 mailmbox_folder*f = 0; 160 mailmbox_folder*f = 0;
161 int r = mailmbox_init(p.latin1(),0,1,0,&f); 161 int r = mailmbox_init(p.latin1(),0,1,0,&f);
162 if (r != MAIL_NO_ERROR) { 162 if (r != MAIL_NO_ERROR) {
163 Global::statusMessage(tr("Error init folder")); 163 Global::statusMessage(tr("Error init folder"));
164 return; 164 return;
165 } 165 }
166 r = mailmbox_append_message(f,msg,length); 166 r = mailmbox_append_message(f,msg,length);
167 if (r != MAIL_NO_ERROR) { 167 if (r != MAIL_NO_ERROR) {
168 Global::statusMessage(tr("Error writing to message folder")); 168 Global::statusMessage(tr("Error writing to message folder"));
169 } 169 }
170 mailmbox_done(f); 170 mailmbox_done(f);
171} 171}
172 172
173encodedString* MBOXwrapper::fetchRawBody(const RecMailP&mail) 173encodedString* MBOXwrapper::fetchRawBody(const RecMailP&mail)
174{ 174{
175 RecBody body; 175 RecBody body;
176 mailstorage*storage = mailstorage_new(NULL); 176 mailstorage*storage = mailstorage_new(NULL);
177 QString p = MBOXPath+"/"; 177 QString p = MBOXPath+"/";
178 p+=mail->getMbox(); 178 p+=mail->getMbox();
179 mailmessage * msg; 179 mailmessage * msg;
180 char*data=0; 180 char*data=0;
181 size_t size; 181 size_t size;
182 182
183 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0); 183 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
184 mailfolder*folder; 184 mailfolder*folder;
185 folder = mailfolder_new( storage,(char*)p.latin1(),NULL); 185 folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
186 r = mailfolder_connect(folder); 186 r = mailfolder_connect(folder);
187 if (r != MAIL_NO_ERROR) { 187 if (r != MAIL_NO_ERROR) {
188 Global::statusMessage(tr("Error initializing mbox")); 188 Global::statusMessage(tr("Error initializing mbox"));
189 mailfolder_free(folder); 189 mailfolder_free(folder);
190 mailstorage_free(storage); 190 mailstorage_free(storage);
191 return 0; 191 return 0;
192 } 192 }
193 r = mailsession_get_message(folder->fld_session, mail->getNumber(), &msg); 193 r = mailsession_get_message(folder->fld_session, mail->getNumber(), &msg);
194 if (r != MAIL_NO_ERROR) { 194 if (r != MAIL_NO_ERROR) {
195 Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber())); 195 Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber()));
196 mailfolder_free(folder); 196 mailfolder_free(folder);
197 mailstorage_free(storage); 197 mailstorage_free(storage);
198 return 0; 198 return 0;
199 } 199 }
200 r = mailmessage_fetch(msg,&data,&size); 200 r = mailmessage_fetch(msg,&data,&size);
201 if (r != MAIL_NO_ERROR) { 201 if (r != MAIL_NO_ERROR) {
202 Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber())); 202 Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber()));
203 mailfolder_free(folder); 203 mailfolder_free(folder);
204 mailstorage_free(storage); 204 mailstorage_free(storage);
205 mailmessage_free(msg); 205 mailmessage_free(msg);
206 return 0; 206 return 0;
207 } 207 }
208 encodedString*result = new encodedString(data,size); 208 encodedString*result = new encodedString(data,size);
209 209
210 mailfolder_free(folder); 210 mailfolder_free(folder);
211 mailstorage_free(storage); 211 mailstorage_free(storage);
212 mailmessage_free(msg); 212 mailmessage_free(msg);
213 return result; 213 return result;
214} 214}
215 215
216void MBOXwrapper::deleteMails(const QString & mailbox,const QValueList<RecMailP> &target) 216void MBOXwrapper::deleteMails(const QString & mailbox,const QValueList<RecMailP> &target)
217{ 217{
218 QString p = MBOXPath+"/"; 218 QString p = MBOXPath+"/";
219 p+=mailbox; 219 p+=mailbox;
220 mailmbox_folder*f = 0; 220 mailmbox_folder*f = 0;
221 int r = mailmbox_init(p.latin1(),0,1,0,&f); 221 int r = mailmbox_init(p.latin1(),0,1,0,&f);
222 if (r != MAIL_NO_ERROR) { 222 if (r != MAIL_NO_ERROR) {
223 qDebug("Error init folder"); 223 odebug << "Error init folder" << oendl;
224 return; 224 return;
225 } 225 }
226 deleteMails(f,target); 226 deleteMails(f,target);
227 mailmbox_done(f); 227 mailmbox_done(f);
228} 228}
229 229
230void MBOXwrapper::deleteMails(mailmbox_folder*f,const QValueList<RecMailP> &target) 230void MBOXwrapper::deleteMails(mailmbox_folder*f,const QValueList<RecMailP> &target)
231{ 231{
232 if (!f) return; 232 if (!f) return;
233 int r; 233 int r;
234 QValueList<RecMailP>::ConstIterator it; 234 QValueList<RecMailP>::ConstIterator it;
235 for (it=target.begin(); it != target.end();++it) { 235 for (it=target.begin(); it != target.end();++it) {
236 r = mailmbox_delete_msg(f,(*it)->getNumber()); 236 r = mailmbox_delete_msg(f,(*it)->getNumber());
237 if (r!=MAILMBOX_NO_ERROR) { 237 if (r!=MAILMBOX_NO_ERROR) {
238 qDebug("error delete mail"); 238 odebug << "error delete mail" << oendl;
239 } 239 }
240 } 240 }
241 r = mailmbox_expunge(f); 241 r = mailmbox_expunge(f);
242 if (r != MAILMBOX_NO_ERROR) { 242 if (r != MAILMBOX_NO_ERROR) {
243 qDebug("error expunge mailbox"); 243 odebug << "error expunge mailbox" << oendl;
244 } 244 }
245} 245}
246 246
247int MBOXwrapper::deleteAllMail(const FolderP&tfolder) 247int MBOXwrapper::deleteAllMail(const FolderP&tfolder)
248{ 248{
249 if (!tfolder) return 0; 249 if (!tfolder) return 0;
250 QString p = MBOXPath+"/"+tfolder->getDisplayName(); 250 QString p = MBOXPath+"/"+tfolder->getDisplayName();
251 int res = 1; 251 int res = 1;
252 252
253 mailfolder*folder = 0; 253 mailfolder*folder = 0;
254 mailmessage_list*l=0; 254 mailmessage_list*l=0;
255 mailstorage*storage = mailstorage_new(NULL); 255 mailstorage*storage = mailstorage_new(NULL);
256 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0); 256 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
257 if (r != MAIL_NO_ERROR) { 257 if (r != MAIL_NO_ERROR) {
258 Global::statusMessage(tr("Error initializing mbox")); 258 Global::statusMessage(tr("Error initializing mbox"));
259 res = 0; 259 res = 0;
260 } 260 }
261 if (res) { 261 if (res) {
262 folder = mailfolder_new( storage,(char*)p.latin1(),NULL); 262 folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
263 r = mailfolder_connect(folder); 263 r = mailfolder_connect(folder);
264 if (r != MAIL_NO_ERROR) { 264 if (r != MAIL_NO_ERROR) {
265 Global::statusMessage(tr("Error initializing mbox")); 265 Global::statusMessage(tr("Error initializing mbox"));
266 res = 0; 266 res = 0;
267 } 267 }
268 } 268 }
269 if (res) { 269 if (res) {
270 r = mailsession_get_messages_list(folder->fld_session,&l); 270 r = mailsession_get_messages_list(folder->fld_session,&l);
271 if (r != MAIL_NO_ERROR) { 271 if (r != MAIL_NO_ERROR) {
272 qDebug("Error message list"); 272 odebug << "Error message list" << oendl;
273 res=0; 273 res=0;
274 } 274 }
275 } 275 }
276 for(unsigned int i = 0 ; l!= 0 && res==1 && i < carray_count(l->msg_tab) ; ++i) { 276 for(unsigned int i = 0 ; l!= 0 && res==1 && i < carray_count(l->msg_tab) ; ++i) {
277 r = mailsession_remove_message(folder->fld_session,i+1); 277 r = mailsession_remove_message(folder->fld_session,i+1);
278 if (r != MAIL_NO_ERROR) { 278 if (r != MAIL_NO_ERROR) {
279 Global::statusMessage(tr("Error deleting mail %1").arg(i+1)); 279 Global::statusMessage(tr("Error deleting mail %1").arg(i+1));
280 res = 0; 280 res = 0;
281 break; 281 break;
282 } 282 }
283 } 283 }
284 if (l) mailmessage_list_free(l); 284 if (l) mailmessage_list_free(l);
285 if (folder) mailfolder_free(folder); 285 if (folder) mailfolder_free(folder);
286 if (storage) mailstorage_free(storage); 286 if (storage) mailstorage_free(storage);
287 return res; 287 return res;
288} 288}
289 289
290int MBOXwrapper::deleteMbox(const FolderP&tfolder) 290int MBOXwrapper::deleteMbox(const FolderP&tfolder)
291{ 291{
292 if (!tfolder) return 0; 292 if (!tfolder) return 0;
293 QString p = MBOXPath+"/"+tfolder->getDisplayName(); 293 QString p = MBOXPath+"/"+tfolder->getDisplayName();
294 QFile fi(p); 294 QFile fi(p);
295 if (!fi.exists()) { 295 if (!fi.exists()) {
296 Global::statusMessage(tr("Mailbox doesn't exist.")); 296 Global::statusMessage(tr("Mailbox doesn't exist."));
297 return 0; 297 return 0;
298 } 298 }
299 if (!fi.remove()) { 299 if (!fi.remove()) {
300 Global::statusMessage(tr("Error deleting Mailbox.")); 300 Global::statusMessage(tr("Error deleting Mailbox."));
301 return 0; 301 return 0;
302 } 302 }
303 return 1; 303 return 1;
304} 304}
305 305
306void MBOXwrapper::statusFolder(folderStat&target_stat,const QString & mailbox) 306void MBOXwrapper::statusFolder(folderStat&target_stat,const QString & mailbox)
307{ 307{
308 mailfolder*folder = 0; 308 mailfolder*folder = 0;
309 mailstorage*storage = mailstorage_new(NULL); 309 mailstorage*storage = mailstorage_new(NULL);
310 target_stat.message_count = 0; 310 target_stat.message_count = 0;
311 target_stat.message_unseen = 0; 311 target_stat.message_unseen = 0;
312 target_stat.message_recent = 0; 312 target_stat.message_recent = 0;
313 QString p = MBOXPath+"/"+mailbox; 313 QString p = MBOXPath+"/"+mailbox;
314 QFile fi(p); 314 QFile fi(p);
315 if (!fi.exists()) { 315 if (!fi.exists()) {
316 Global::statusMessage(tr("Mailbox doesn't exist.")); 316 Global::statusMessage(tr("Mailbox doesn't exist."));
317 return; 317 return;
318 } 318 }
319 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0); 319 int r = mbox_mailstorage_init(storage,(char*)p.latin1(),0,0,0);
320 folder = mailfolder_new( storage,(char*)p.latin1(),NULL); 320 folder = mailfolder_new( storage,(char*)p.latin1(),NULL);
321 r = mailfolder_connect(folder); 321 r = mailfolder_connect(folder);
322 r = mailsession_status_folder(folder->fld_session,(char*)mailbox.latin1(),&target_stat.message_count, 322 r = mailsession_status_folder(folder->fld_session,(char*)mailbox.latin1(),&target_stat.message_count,
323 &target_stat.message_recent,&target_stat.message_unseen); 323 &target_stat.message_recent,&target_stat.message_unseen);
324 if (folder) mailfolder_free(folder); 324 if (folder) mailfolder_free(folder);
325 if (storage) mailstorage_free(storage); 325 if (storage) mailstorage_free(storage);
326} 326}
327 327
328MAILLIB::ATYPE MBOXwrapper::getType()const 328MAILLIB::ATYPE MBOXwrapper::getType()const
329{ 329{
330 return MAILLIB::A_MBOX; 330 return MAILLIB::A_MBOX;
331} 331}
332 332
333const QString&MBOXwrapper::getName()const 333const QString&MBOXwrapper::getName()const
334{ 334{
335 return MBOXName; 335 return MBOXName;
336} 336}
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 @@
1#include "mhwrapper.h" 1#include "mhwrapper.h"
2#include "mailtypes.h" 2#include "mailtypes.h"
3#include "mailwrapper.h" 3#include "mailwrapper.h"
4#include <libetpan/libetpan.h> 4#include <libetpan/libetpan.h>
5#include <qdir.h> 5#include <qdir.h>
6#include <qmessagebox.h> 6#include <qmessagebox.h>
7#include <stdlib.h> 7#include <stdlib.h>
8#include <qpe/global.h> 8#include <qpe/global.h>
9#include <opie2/oprocess.h> 9#include <opie2/oprocess.h>
10 10
11using namespace Opie::Core; 11using namespace Opie::Core;
12MHwrapper::MHwrapper(const QString & mbox_dir,const QString&mbox_name) 12MHwrapper::MHwrapper(const QString & mbox_dir,const QString&mbox_name)
13 : Genericwrapper(),MHPath(mbox_dir),MHName(mbox_name) 13 : Genericwrapper(),MHPath(mbox_dir),MHName(mbox_name)
14{ 14{
15 if (MHPath.length()>0) { 15 if (MHPath.length()>0) {
16 if (MHPath[MHPath.length()-1]=='/') { 16 if (MHPath[MHPath.length()-1]=='/') {
17 MHPath=MHPath.left(MHPath.length()-1); 17 MHPath=MHPath.left(MHPath.length()-1);
18 } 18 }
19 qDebug(MHPath); 19 odebug << MHPath << oendl;
20 QDir dir(MHPath); 20 QDir dir(MHPath);
21 if (!dir.exists()) { 21 if (!dir.exists()) {
22 dir.mkdir(MHPath); 22 dir.mkdir(MHPath);
23 } 23 }
24 init_storage(); 24 init_storage();
25 } 25 }
26} 26}
27 27
28void MHwrapper::init_storage() 28void MHwrapper::init_storage()
29{ 29{
30 int r; 30 int r;
31 QString pre = MHPath; 31 QString pre = MHPath;
32 if (!m_storage) { 32 if (!m_storage) {
33 m_storage = mailstorage_new(NULL); 33 m_storage = mailstorage_new(NULL);
34 r = mh_mailstorage_init(m_storage,(char*)pre.latin1(),0,0,0); 34 r = mh_mailstorage_init(m_storage,(char*)pre.latin1(),0,0,0);
35 if (r != MAIL_NO_ERROR) { 35 if (r != MAIL_NO_ERROR) {
36 qDebug("error initializing storage"); 36 odebug << "error initializing storage" << oendl;
37 mailstorage_free(m_storage); 37 mailstorage_free(m_storage);
38 m_storage = 0; 38 m_storage = 0;
39 return; 39 return;
40 } 40 }
41 } 41 }
42 r = mailstorage_connect(m_storage); 42 r = mailstorage_connect(m_storage);
43 if (r!=MAIL_NO_ERROR) { 43 if (r!=MAIL_NO_ERROR) {
44 qDebug("error connecting storage"); 44 odebug << "error connecting storage" << oendl;
45 mailstorage_free(m_storage); 45 mailstorage_free(m_storage);
46 m_storage = 0; 46 m_storage = 0;
47 } 47 }
48} 48}
49 49
50void MHwrapper::clean_storage() 50void MHwrapper::clean_storage()
51{ 51{
52 if (m_storage) { 52 if (m_storage) {
53 mailstorage_disconnect(m_storage); 53 mailstorage_disconnect(m_storage);
54 mailstorage_free(m_storage); 54 mailstorage_free(m_storage);
55 m_storage = 0; 55 m_storage = 0;
56 } 56 }
57} 57}
58 58
59MHwrapper::~MHwrapper() 59MHwrapper::~MHwrapper()
60{ 60{
61 clean_storage(); 61 clean_storage();
62} 62}
63 63
64void MHwrapper::listMessages(const QString & mailbox, QValueList<Opie::Core::OSmartPointer<RecMail> > &target ) 64void MHwrapper::listMessages(const QString & mailbox, QValueList<Opie::Core::OSmartPointer<RecMail> > &target )
65{ 65{
66 init_storage(); 66 init_storage();
67 if (!m_storage) { 67 if (!m_storage) {
68 return; 68 return;
69 } 69 }
70 QString f = buildPath(mailbox); 70 QString f = buildPath(mailbox);
71 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1()); 71 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
72 if (r!=MAIL_NO_ERROR) { 72 if (r!=MAIL_NO_ERROR) {
73 qDebug("listMessages: error selecting folder!"); 73 odebug << "listMessages: error selecting folder!" << oendl;
74 return; 74 return;
75 } 75 }
76 parseList(target,m_storage->sto_session,f); 76 parseList(target,m_storage->sto_session,f);
77 Global::statusMessage(tr("Mailbox has %1 mail(s)").arg(target.count())); 77 Global::statusMessage(tr("Mailbox has %1 mail(s)").arg(target.count()));
78} 78}
79 79
80QValueList<Opie::Core::OSmartPointer<Folder> >* MHwrapper::listFolders() 80QValueList<Opie::Core::OSmartPointer<Folder> >* MHwrapper::listFolders()
81{ 81{
82 QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >(); 82 QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >();
83 /* this is needed! */ 83 /* this is needed! */
84 if (m_storage) mailstorage_disconnect(m_storage); 84 if (m_storage) mailstorage_disconnect(m_storage);
85 init_storage(); 85 init_storage();
86 if (!m_storage) { 86 if (!m_storage) {
87 return folders; 87 return folders;
88 } 88 }
89 mail_list*flist = 0; 89 mail_list*flist = 0;
90 clistcell*current=0; 90 clistcell*current=0;
91 int r = mailsession_list_folders(m_storage->sto_session,NULL,&flist); 91 int r = mailsession_list_folders(m_storage->sto_session,NULL,&flist);
92 if (r != MAIL_NO_ERROR || !flist) { 92 if (r != MAIL_NO_ERROR || !flist) {
93 qDebug("error getting folder list"); 93 odebug << "error getting folder list" << oendl;
94 return folders; 94 return folders;
95 } 95 }
96 for (current=clist_begin(flist->mb_list);current!=0;current=clist_next(current)) { 96 for (current=clist_begin(flist->mb_list);current!=0;current=clist_next(current)) {
97 QString t = (char*)current->data; 97 QString t = (char*)current->data;
98 t.replace(0,MHPath.length(),""); 98 t.replace(0,MHPath.length(),"");
99 folders->append(new MHFolder(t,MHPath)); 99 folders->append(new MHFolder(t,MHPath));
100 } 100 }
101 mail_list_free(flist); 101 mail_list_free(flist);
102 return folders; 102 return folders;
103} 103}
104 104
105void MHwrapper::deleteMail(const RecMailP&mail) 105void MHwrapper::deleteMail(const RecMailP&mail)
106{ 106{
107 init_storage(); 107 init_storage();
108 if (!m_storage) { 108 if (!m_storage) {
109 return; 109 return;
110 } 110 }
111 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1()); 111 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1());
112 if (r!=MAIL_NO_ERROR) { 112 if (r!=MAIL_NO_ERROR) {
113 qDebug("error selecting folder!"); 113 odebug << "error selecting folder!" << oendl;
114 return; 114 return;
115 } 115 }
116 r = mailsession_remove_message(m_storage->sto_session,mail->getNumber()); 116 r = mailsession_remove_message(m_storage->sto_session,mail->getNumber());
117 if (r != MAIL_NO_ERROR) { 117 if (r != MAIL_NO_ERROR) {
118 qDebug("error deleting mail"); 118 odebug << "error deleting mail" << oendl;
119 } 119 }
120} 120}
121 121
122void MHwrapper::answeredMail(const RecMailP&) 122void MHwrapper::answeredMail(const RecMailP&)
123{ 123{
124} 124}
125 125
126RecBodyP MHwrapper::fetchBody( const RecMailP &mail ) 126RecBodyP MHwrapper::fetchBody( const RecMailP &mail )
127{ 127{
128 RecBodyP body = new RecBody(); 128 RecBodyP body = new RecBody();
129 init_storage(); 129 init_storage();
130 if (!m_storage) { 130 if (!m_storage) {
131 return body; 131 return body;
132 } 132 }
133 mailmessage * msg; 133 mailmessage * msg;
134 char*data=0; 134 char*data=0;
135 135
136 /* mail should hold the complete path! */ 136 /* mail should hold the complete path! */
137 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1()); 137 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1());
138 if (r != MAIL_NO_ERROR) { 138 if (r != MAIL_NO_ERROR) {
139 return body; 139 return body;
140 } 140 }
141 r = mailsession_get_message(m_storage->sto_session, mail->getNumber(), &msg); 141 r = mailsession_get_message(m_storage->sto_session, mail->getNumber(), &msg);
142 if (r != MAIL_NO_ERROR) { 142 if (r != MAIL_NO_ERROR) {
143 qDebug("Error fetching mail %i",mail->getNumber()); 143 odebug << "Error fetching mail " << mail->getNumber() << "" << oendl;
144 return body; 144 return body;
145 } 145 }
146 body = parseMail(msg); 146 body = parseMail(msg);
147 mailmessage_fetch_result_free(msg,data); 147 mailmessage_fetch_result_free(msg,data);
148 return body; 148 return body;
149} 149}
150 150
151void MHwrapper::mbox_progress( size_t current, size_t maximum ) 151void MHwrapper::mbox_progress( size_t current, size_t maximum )
152{ 152{
153 qDebug("MH %i von %i",current,maximum); 153 odebug << "MH " << current << " von " << maximum << "" << oendl;
154} 154}
155 155
156QString MHwrapper::buildPath(const QString&p) 156QString MHwrapper::buildPath(const QString&p)
157{ 157{
158 QString f=""; 158 QString f="";
159 if (p.length()==0||p=="/") 159 if (p.length()==0||p=="/")
160 return MHPath; 160 return MHPath;
161 if (!p.startsWith(MHPath)) { 161 if (!p.startsWith(MHPath)) {
162 f+=MHPath; 162 f+=MHPath;
163 } 163 }
164 if (!p.startsWith("/")) { 164 if (!p.startsWith("/")) {
165 f+="/"; 165 f+="/";
166 } 166 }
167 f+=p; 167 f+=p;
168 return f; 168 return f;
169} 169}
170 170
171int MHwrapper::createMbox(const QString&folder,const FolderP&pfolder,const QString&,bool ) 171int MHwrapper::createMbox(const QString&folder,const FolderP&pfolder,const QString&,bool )
172{ 172{
173 init_storage(); 173 init_storage();
174 if (!m_storage) { 174 if (!m_storage) {
175 return 0; 175 return 0;
176 } 176 }
177 QString f; 177 QString f;
178 if (!pfolder) { 178 if (!pfolder) {
179 // toplevel folder 179 // toplevel folder
180 f = buildPath(folder); 180 f = buildPath(folder);
181 } else { 181 } else {
182 f = pfolder->getName(); 182 f = pfolder->getName();
183 f+="/"; 183 f+="/";
184 f+=folder; 184 f+=folder;
185 } 185 }
186 qDebug(f); 186 odebug << f << oendl;
187 int r = mailsession_create_folder(m_storage->sto_session,(char*)f.latin1()); 187 int r = mailsession_create_folder(m_storage->sto_session,(char*)f.latin1());
188 if (r != MAIL_NO_ERROR) { 188 if (r != MAIL_NO_ERROR) {
189 qDebug("error creating folder %i",r); 189 odebug << "error creating folder " << r << "" << oendl;
190 return 0; 190 return 0;
191 } 191 }
192 qDebug("Folder created"); 192 odebug << "Folder created" << oendl;
193 return 1; 193 return 1;
194} 194}
195 195
196void MHwrapper::storeMessage(const char*msg,size_t length, const QString&Folder) 196void MHwrapper::storeMessage(const char*msg,size_t length, const QString&Folder)
197{ 197{
198 init_storage(); 198 init_storage();
199 if (!m_storage) { 199 if (!m_storage) {
200 return; 200 return;
201 } 201 }
202 QString f = buildPath(Folder); 202 QString f = buildPath(Folder);
203 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1()); 203 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
204 if (r!=MAIL_NO_ERROR) { 204 if (r!=MAIL_NO_ERROR) {
205 qDebug("error selecting folder!"); 205 odebug << "error selecting folder!" << oendl;
206 return; 206 return;
207 } 207 }
208 r = mailsession_append_message(m_storage->sto_session,(char*)msg,length); 208 r = mailsession_append_message(m_storage->sto_session,(char*)msg,length);
209 if (r!=MAIL_NO_ERROR) { 209 if (r!=MAIL_NO_ERROR) {
210 qDebug("error storing mail"); 210 odebug << "error storing mail" << oendl;
211 } 211 }
212 return; 212 return;
213} 213}
214 214
215encodedString* MHwrapper::fetchRawBody(const RecMailP&mail) 215encodedString* MHwrapper::fetchRawBody(const RecMailP&mail)
216{ 216{
217 encodedString*result = 0; 217 encodedString*result = 0;
218 init_storage(); 218 init_storage();
219 if (!m_storage) { 219 if (!m_storage) {
220 return result; 220 return result;
221 } 221 }
222 mailmessage * msg = 0; 222 mailmessage * msg = 0;
223 char*data=0; 223 char*data=0;
224 size_t size; 224 size_t size;
225 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1()); 225 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1());
226 if (r!=MAIL_NO_ERROR) { 226 if (r!=MAIL_NO_ERROR) {
227 qDebug("error selecting folder!"); 227 odebug << "error selecting folder!" << oendl;
228 return result; 228 return result;
229 } 229 }
230 r = mailsession_get_message(m_storage->sto_session, mail->getNumber(), &msg); 230 r = mailsession_get_message(m_storage->sto_session, mail->getNumber(), &msg);
231 if (r != MAIL_NO_ERROR) { 231 if (r != MAIL_NO_ERROR) {
232 Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber())); 232 Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber()));
233 return 0; 233 return 0;
234 } 234 }
235 r = mailmessage_fetch(msg,&data,&size); 235 r = mailmessage_fetch(msg,&data,&size);
236 if (r != MAIL_NO_ERROR) { 236 if (r != MAIL_NO_ERROR) {
237 Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber())); 237 Global::statusMessage(tr("Error fetching mail %i").arg(mail->getNumber()));
238 if (msg) mailmessage_free(msg); 238 if (msg) mailmessage_free(msg);
239 return 0; 239 return 0;
240 } 240 }
241 result = new encodedString(data,size); 241 result = new encodedString(data,size);
242 if (msg) mailmessage_free(msg); 242 if (msg) mailmessage_free(msg);
243 return result; 243 return result;
244} 244}
245 245
246void MHwrapper::deleteMails(const QString & mailbox,const QValueList<RecMailP> &target) 246void MHwrapper::deleteMails(const QString & mailbox,const QValueList<RecMailP> &target)
247{ 247{
248 QString f = buildPath(mailbox); 248 QString f = buildPath(mailbox);
249 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1()); 249 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
250 if (r!=MAIL_NO_ERROR) { 250 if (r!=MAIL_NO_ERROR) {
251 qDebug("deleteMails: error selecting folder!"); 251 odebug << "deleteMails: error selecting folder!" << oendl;
252 return; 252 return;
253 } 253 }
254 QValueList<RecMailP>::ConstIterator it; 254 QValueList<RecMailP>::ConstIterator it;
255 for (it=target.begin(); it!=target.end();++it) { 255 for (it=target.begin(); it!=target.end();++it) {
256 r = mailsession_remove_message(m_storage->sto_session,(*it)->getNumber()); 256 r = mailsession_remove_message(m_storage->sto_session,(*it)->getNumber());
257 if (r != MAIL_NO_ERROR) { 257 if (r != MAIL_NO_ERROR) {
258 qDebug("error deleting mail"); 258 odebug << "error deleting mail" << oendl;
259 break; 259 break;
260 } 260 }
261 } 261 }
262} 262}
263 263
264int MHwrapper::deleteAllMail(const FolderP&tfolder) 264int MHwrapper::deleteAllMail(const FolderP&tfolder)
265{ 265{
266 init_storage(); 266 init_storage();
267 if (!m_storage) { 267 if (!m_storage) {
268 return 0; 268 return 0;
269 } 269 }
270 int res = 1; 270 int res = 1;
271 if (!tfolder) return 0; 271 if (!tfolder) return 0;
272 int r = mailsession_select_folder(m_storage->sto_session,(char*)tfolder->getName().latin1()); 272 int r = mailsession_select_folder(m_storage->sto_session,(char*)tfolder->getName().latin1());
273 if (r!=MAIL_NO_ERROR) { 273 if (r!=MAIL_NO_ERROR) {
274 qDebug("error selecting folder!"); 274 odebug << "error selecting folder!" << oendl;
275 return 0; 275 return 0;
276 } 276 }
277 mailmessage_list*l=0; 277 mailmessage_list*l=0;
278 r = mailsession_get_messages_list(m_storage->sto_session,&l); 278 r = mailsession_get_messages_list(m_storage->sto_session,&l);
279 if (r != MAIL_NO_ERROR) { 279 if (r != MAIL_NO_ERROR) {
280 qDebug("Error message list"); 280 odebug << "Error message list" << oendl;
281 res = 0; 281 res = 0;
282 } 282 }
283 unsigned j = 0; 283 unsigned j = 0;
284 for(unsigned int i = 0 ; l!= 0 && res==1 && i < carray_count(l->msg_tab) ; ++i) { 284 for(unsigned int i = 0 ; l!= 0 && res==1 && i < carray_count(l->msg_tab) ; ++i) {
285 mailmessage * msg; 285 mailmessage * msg;
286 msg = (mailmessage*)carray_get(l->msg_tab, i); 286 msg = (mailmessage*)carray_get(l->msg_tab, i);
287 j = msg->msg_index; 287 j = msg->msg_index;
288 r = mailsession_remove_message(m_storage->sto_session,j); 288 r = mailsession_remove_message(m_storage->sto_session,j);
289 if (r != MAIL_NO_ERROR) { 289 if (r != MAIL_NO_ERROR) {
290 Global::statusMessage(tr("Error deleting mail %1").arg(i+1)); 290 Global::statusMessage(tr("Error deleting mail %1").arg(i+1));
291 res = 0; 291 res = 0;
292 break; 292 break;
293 } 293 }
294 } 294 }
295 if (l) mailmessage_list_free(l); 295 if (l) mailmessage_list_free(l);
296 return res; 296 return res;
297} 297}
298 298
299int MHwrapper::deleteMbox(const FolderP&tfolder) 299int MHwrapper::deleteMbox(const FolderP&tfolder)
300{ 300{
301 init_storage(); 301 init_storage();
302 if (!m_storage) { 302 if (!m_storage) {
303 return 0; 303 return 0;
304 } 304 }
305 if (!tfolder) return 0; 305 if (!tfolder) return 0;
306 if (tfolder->getName()=="/" || tfolder->getName().isEmpty()) return 0; 306 if (tfolder->getName()=="/" || tfolder->getName().isEmpty()) return 0;
307 307
308 int r = mailsession_delete_folder(m_storage->sto_session,(char*)tfolder->getName().latin1()); 308 int r = mailsession_delete_folder(m_storage->sto_session,(char*)tfolder->getName().latin1());
309 309
310 if (r != MAIL_NO_ERROR) { 310 if (r != MAIL_NO_ERROR) {
311 qDebug("error deleting mail box"); 311 odebug << "error deleting mail box" << oendl;
312 return 0; 312 return 0;
313 } 313 }
314 QString cmd = "rm -rf "+tfolder->getName(); 314 QString cmd = "rm -rf "+tfolder->getName();
315 QStringList command; 315 QStringList command;
316 command << "/bin/sh"; 316 command << "/bin/sh";
317 command << "-c"; 317 command << "-c";
318 command << cmd.latin1(); 318 command << cmd.latin1();
319 OProcess *process = new OProcess(); 319 OProcess *process = new OProcess();
320 320
321 connect(process, SIGNAL(processExited(Opie::Core::OProcess*)), 321 connect(process, SIGNAL(processExited(Opie::Core::OProcess*)),
322 this, SLOT( processEnded(Opie::Core::OProcess*))); 322 this, SLOT( processEnded(Opie::Core::OProcess*)));
323 connect(process, SIGNAL( receivedStderr(Opie::Core::OProcess*,char*,int)), 323 connect(process, SIGNAL( receivedStderr(Opie::Core::OProcess*,char*,int)),
324 this, SLOT( oprocessStderr(Opie::Core::OProcess*,char*,int))); 324 this, SLOT( oprocessStderr(Opie::Core::OProcess*,char*,int)));
325 325
326 *process << command; 326 *process << command;
327 removeMboxfailed = false; 327 removeMboxfailed = false;
328 if(!process->start(OProcess::Block, OProcess::All) ) { 328 if(!process->start(OProcess::Block, OProcess::All) ) {
329 qDebug("could not start process"); 329 odebug << "could not start process" << oendl;
330 return 0; 330 return 0;
331 } 331 }
332 qDebug("mail box deleted"); 332 odebug << "mail box deleted" << oendl;
333 return 1; 333 return 1;
334} 334}
335 335
336void MHwrapper::processEnded(OProcess *p) 336void MHwrapper::processEnded(OProcess *p)
337{ 337{
338 if (p) delete p; 338 if (p) delete p;
339} 339}
340 340
341void MHwrapper::oprocessStderr(OProcess*, char *buffer, int ) 341void MHwrapper::oprocessStderr(OProcess*, char *buffer, int )
342{ 342{
343 QString lineStr = buffer; 343 QString lineStr = buffer;
344 QMessageBox::warning( 0, tr("Error"), lineStr ,tr("Ok") ); 344 QMessageBox::warning( 0, tr("Error"), lineStr ,tr("Ok") );
345 removeMboxfailed = true; 345 removeMboxfailed = true;
346} 346}
347 347
348void MHwrapper::statusFolder(folderStat&target_stat,const QString & mailbox) 348void MHwrapper::statusFolder(folderStat&target_stat,const QString & mailbox)
349{ 349{
350 init_storage(); 350 init_storage();
351 if (!m_storage) { 351 if (!m_storage) {
352 return; 352 return;
353 } 353 }
354 target_stat.message_count = 0; 354 target_stat.message_count = 0;
355 target_stat.message_unseen = 0; 355 target_stat.message_unseen = 0;
356 target_stat.message_recent = 0; 356 target_stat.message_recent = 0;
357 QString f = buildPath(mailbox); 357 QString f = buildPath(mailbox);
358 int r = mailsession_status_folder(m_storage->sto_session,(char*)f.latin1(),&target_stat.message_count, 358 int r = mailsession_status_folder(m_storage->sto_session,(char*)f.latin1(),&target_stat.message_count,
359 &target_stat.message_recent,&target_stat.message_unseen); 359 &target_stat.message_recent,&target_stat.message_unseen);
360 if (r != MAIL_NO_ERROR) { 360 if (r != MAIL_NO_ERROR) {
361 Global::statusMessage(tr("Error retrieving status")); 361 Global::statusMessage(tr("Error retrieving status"));
362 } 362 }
363} 363}
364 364
365MAILLIB::ATYPE MHwrapper::getType()const 365MAILLIB::ATYPE MHwrapper::getType()const
366{ 366{
367 return MAILLIB::A_MH; 367 return MAILLIB::A_MH;
368} 368}
369 369
370const QString&MHwrapper::getName()const 370const QString&MHwrapper::getName()const
371{ 371{
372 return MHName; 372 return MHName;
373} 373}
374void MHwrapper::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit) 374void MHwrapper::mvcpMail(const RecMailP&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
375{ 375{
376 init_storage(); 376 init_storage();
377 if (!m_storage) { 377 if (!m_storage) {
378 return; 378 return;
379 } 379 }
380 if (targetWrapper != this) { 380 if (targetWrapper != this) {
381 qDebug("Using generic"); 381 odebug << "Using generic" << oendl;
382 Genericwrapper::mvcpMail(mail,targetFolder,targetWrapper,moveit); 382 Genericwrapper::mvcpMail(mail,targetFolder,targetWrapper,moveit);
383 return; 383 return;
384 } 384 }
385 qDebug("Using internal routines for move/copy"); 385 odebug << "Using internal routines for move/copy" << oendl;
386 QString tf = buildPath(targetFolder); 386 QString tf = buildPath(targetFolder);
387 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1()); 387 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail->getMbox().latin1());
388 if (r != MAIL_NO_ERROR) { 388 if (r != MAIL_NO_ERROR) {
389 qDebug("Error selecting source mailbox"); 389 odebug << "Error selecting source mailbox" << oendl;
390 return; 390 return;
391 } 391 }
392 if (moveit) { 392 if (moveit) {
393 r = mailsession_move_message(m_storage->sto_session,mail->getNumber(),(char*)tf.latin1()); 393 r = mailsession_move_message(m_storage->sto_session,mail->getNumber(),(char*)tf.latin1());
394 } else { 394 } else {
395 r = mailsession_copy_message(m_storage->sto_session,mail->getNumber(),(char*)tf.latin1()); 395 r = mailsession_copy_message(m_storage->sto_session,mail->getNumber(),(char*)tf.latin1());
396 } 396 }
397 if (r != MAIL_NO_ERROR) { 397 if (r != MAIL_NO_ERROR) {
398 qDebug("Error copy/moving mail internal (%i)",r); 398 odebug << "Error copy/moving mail internal (" << r << ")" << oendl;
399 } 399 }
400} 400}
401 401
402void MHwrapper::mvcpAllMails(const FolderP&fromFolder, 402void MHwrapper::mvcpAllMails(const FolderP&fromFolder,
403 const QString&targetFolder,AbstractMail*targetWrapper,bool moveit) 403 const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
404{ 404{
405 init_storage(); 405 init_storage();
406 if (!m_storage) { 406 if (!m_storage) {
407 return; 407 return;
408 } 408 }
409 if (targetWrapper != this) { 409 if (targetWrapper != this) {
410 qDebug("Using generic"); 410 odebug << "Using generic" << oendl;
411 Genericwrapper::mvcpAllMails(fromFolder,targetFolder,targetWrapper,moveit); 411 Genericwrapper::mvcpAllMails(fromFolder,targetFolder,targetWrapper,moveit);
412 return; 412 return;
413 } 413 }
414 if (!fromFolder) return; 414 if (!fromFolder) return;
415 int r = mailsession_select_folder(m_storage->sto_session,(char*)fromFolder->getName().latin1()); 415 int r = mailsession_select_folder(m_storage->sto_session,(char*)fromFolder->getName().latin1());
416 if (r!=MAIL_NO_ERROR) { 416 if (r!=MAIL_NO_ERROR) {
417 qDebug("error selecting source folder!"); 417 odebug << "error selecting source folder!" << oendl;
418 return; 418 return;
419 } 419 }
420 QString tf = buildPath(targetFolder); 420 QString tf = buildPath(targetFolder);
421 mailmessage_list*l=0; 421 mailmessage_list*l=0;
422 r = mailsession_get_messages_list(m_storage->sto_session,&l); 422 r = mailsession_get_messages_list(m_storage->sto_session,&l);
423 if (r != MAIL_NO_ERROR) { 423 if (r != MAIL_NO_ERROR) {
424 qDebug("Error message list"); 424 odebug << "Error message list" << oendl;
425 } 425 }
426 unsigned j = 0; 426 unsigned j = 0;
427 for(unsigned int i = 0 ; l!= 0 && i < carray_count(l->msg_tab) ; ++i) { 427 for(unsigned int i = 0 ; l!= 0 && i < carray_count(l->msg_tab) ; ++i) {
428 mailmessage * msg; 428 mailmessage * msg;
429 msg = (mailmessage*)carray_get(l->msg_tab, i); 429 msg = (mailmessage*)carray_get(l->msg_tab, i);
430 j = msg->msg_index; 430 j = msg->msg_index;
431 if (moveit) { 431 if (moveit) {
432 r = mailsession_move_message(m_storage->sto_session,j,(char*)tf.latin1()); 432 r = mailsession_move_message(m_storage->sto_session,j,(char*)tf.latin1());
433 } else { 433 } else {
434 r = mailsession_copy_message(m_storage->sto_session,j,(char*)tf.latin1()); 434 r = mailsession_copy_message(m_storage->sto_session,j,(char*)tf.latin1());
435 } 435 }
436 if (r != MAIL_NO_ERROR) { 436 if (r != MAIL_NO_ERROR) {
437 qDebug("Error copy/moving mail internal (%i)",r); 437 odebug << "Error copy/moving mail internal (" << r << ")" << oendl;
438 break; 438 break;
439 } 439 }
440 } 440 }
441 if (l) mailmessage_list_free(l); 441 if (l) mailmessage_list_free(l);
442} 442}
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 @@
1#include "nntpwrapper.h" 1#include "nntpwrapper.h"
2#include "logindialog.h" 2#include "logindialog.h"
3#include "mailtypes.h" 3#include "mailtypes.h"
4 4
5#include <qfile.h> 5#include <qfile.h>
6 6
7#include <stdlib.h> 7#include <stdlib.h>
8 8
9#include <libetpan/libetpan.h> 9#include <libetpan/libetpan.h>
10 10
11 11
12#define HARD_MSG_SIZE_LIMIT 5242880 12#define HARD_MSG_SIZE_LIMIT 5242880
13 13
14using namespace Opie::Core; 14using namespace Opie::Core;
15NNTPwrapper::NNTPwrapper( NNTPaccount *a ) 15NNTPwrapper::NNTPwrapper( NNTPaccount *a )
16: Genericwrapper() { 16: Genericwrapper() {
17 account = a; 17 account = a;
18 m_nntp = NULL; 18 m_nntp = NULL;
19 msgTempName = a->getFileName()+"_msg_cache"; 19 msgTempName = a->getFileName()+"_msg_cache";
20 last_msg_id = 0; 20 last_msg_id = 0;
21} 21}
22 22
23NNTPwrapper::~NNTPwrapper() { 23NNTPwrapper::~NNTPwrapper() {
24 logout(); 24 logout();
25 QFile msg_cache(msgTempName); 25 QFile msg_cache(msgTempName);
26 if (msg_cache.exists()) { 26 if (msg_cache.exists()) {
27 msg_cache.remove(); 27 msg_cache.remove();
28 } 28 }
29} 29}
30 30
31void NNTPwrapper::nntp_progress( size_t current, size_t maximum ) { 31void NNTPwrapper::nntp_progress( size_t current, size_t maximum ) {
32 qDebug( "NNTP: %i of %i", current, maximum ); 32 odebug << "NNTP: " << current << " of " << maximum << "" << oendl;
33} 33}
34 34
35 35
36RecBodyP NNTPwrapper::fetchBody( const RecMailP &mail ) { 36RecBodyP NNTPwrapper::fetchBody( const RecMailP &mail ) {
37 int err = NEWSNNTP_NO_ERROR; 37 int err = NEWSNNTP_NO_ERROR;
38 char *message = 0; 38 char *message = 0;
39 size_t length = 0; 39 size_t length = 0;
40 40
41 RecBodyP body = new RecBody(); 41 RecBodyP body = new RecBody();
42 login(); 42 login();
43 if ( !m_nntp ) { 43 if ( !m_nntp ) {
44 return body; 44 return body;
45 } 45 }
46 46
47 mailmessage * mailmsg; 47 mailmessage * mailmsg;
48 if (mail->Msgsize()>HARD_MSG_SIZE_LIMIT) { 48 if (mail->Msgsize()>HARD_MSG_SIZE_LIMIT) {
49 qDebug("Message to large: %i",mail->Msgsize()); 49 odebug << "Message to large: " << mail->Msgsize() << "" << oendl;
50 return body; 50 return body;
51 } 51 }
52 52
53 QFile msg_cache(msgTempName); 53 QFile msg_cache(msgTempName);
54 54
55 cleanMimeCache(); 55 cleanMimeCache();
56 56
57 if (mail->getNumber()!=last_msg_id) { 57 if (mail->getNumber()!=last_msg_id) {
58 if (msg_cache.exists()) { 58 if (msg_cache.exists()) {
59 msg_cache.remove(); 59 msg_cache.remove();
60 } 60 }
61 msg_cache.open(IO_ReadWrite|IO_Truncate); 61 msg_cache.open(IO_ReadWrite|IO_Truncate);
62 last_msg_id = mail->getNumber(); 62 last_msg_id = mail->getNumber();
63 err = mailsession_get_message(m_nntp->sto_session, mail->getNumber(), &mailmsg); 63 err = mailsession_get_message(m_nntp->sto_session, mail->getNumber(), &mailmsg);
64 err = mailmessage_fetch(mailmsg,&message,&length); 64 err = mailmessage_fetch(mailmsg,&message,&length);
65 msg_cache.writeBlock(message,length); 65 msg_cache.writeBlock(message,length);
66 } else { 66 } else {
67 QString msg=""; 67 QString msg="";
68 msg_cache.open(IO_ReadOnly); 68 msg_cache.open(IO_ReadOnly);
69 message = new char[4096]; 69 message = new char[4096];
70 memset(message,0,4096); 70 memset(message,0,4096);
71 while (msg_cache.readBlock(message,4095)>0) { 71 while (msg_cache.readBlock(message,4095)>0) {
72 msg+=message; 72 msg+=message;
73 memset(message,0,4096); 73 memset(message,0,4096);
74 } 74 }
75 delete message; 75 delete message;
76 message = (char*)malloc(msg.length()+1*sizeof(char)); 76 message = (char*)malloc(msg.length()+1*sizeof(char));
77 memset(message,0,msg.length()+1); 77 memset(message,0,msg.length()+1);
78 memcpy(message,msg.latin1(),msg.length()); 78 memcpy(message,msg.latin1(),msg.length());
79 /* transform to libetpan stuff */ 79 /* transform to libetpan stuff */
80 mailmsg = mailmessage_new(); 80 mailmsg = mailmessage_new();
81 mailmessage_init(mailmsg, NULL, data_message_driver, 0, strlen(message)); 81 mailmessage_init(mailmsg, NULL, data_message_driver, 0, strlen(message));
82 generic_message_t * msg_data; 82 generic_message_t * msg_data;
83 msg_data = (generic_message_t *)mailmsg->msg_data; 83 msg_data = (generic_message_t *)mailmsg->msg_data;
84 msg_data->msg_fetched = 1; 84 msg_data->msg_fetched = 1;
85 msg_data->msg_message = message; 85 msg_data->msg_message = message;
86 msg_data->msg_length = strlen(message); 86 msg_data->msg_length = strlen(message);
87 } 87 }
88 body = parseMail(mailmsg); 88 body = parseMail(mailmsg);
89 89
90 /* clean up */ 90 /* clean up */
91 if (mailmsg) 91 if (mailmsg)
92 mailmessage_free(mailmsg); 92 mailmessage_free(mailmsg);
93 if (message) 93 if (message)
94 free(message); 94 free(message);
95 95
96 return body; 96 return body;
97} 97}
98 98
99 99
100void NNTPwrapper::listMessages(const QString & which, QValueList<Opie::Core::OSmartPointer<RecMail> > &target ) 100void NNTPwrapper::listMessages(const QString & which, QValueList<Opie::Core::OSmartPointer<RecMail> > &target )
101{ 101{
102 login(); 102 login();
103 if (!m_nntp) 103 if (!m_nntp)
104 return; 104 return;
105 uint32_t res_messages,res_recent,res_unseen; 105 uint32_t res_messages,res_recent,res_unseen;
106 mailsession_status_folder(m_nntp->sto_session,(char*)which.latin1(),&res_messages,&res_recent,&res_unseen); 106 mailsession_status_folder(m_nntp->sto_session,(char*)which.latin1(),&res_messages,&res_recent,&res_unseen);
107 parseList(target,m_nntp->sto_session,which,true); 107 parseList(target,m_nntp->sto_session,which,true);
108} 108}
109 109
110void NNTPwrapper::login() 110void NNTPwrapper::login()
111{ 111{
112 if (account->getOffline()) 112 if (account->getOffline())
113 return; 113 return;
114 /* we'll hold the line */ 114 /* we'll hold the line */
115 if ( m_nntp != NULL ) 115 if ( m_nntp != NULL )
116 return; 116 return;
117 117
118 const char *server, *user, *pass; 118 const char *server, *user, *pass;
119 QString User,Pass; 119 QString User,Pass;
120 uint16_t port; 120 uint16_t port;
121 int err = NEWSNNTP_NO_ERROR; 121 int err = NEWSNNTP_NO_ERROR;
122 122
123 server = account->getServer().latin1(); 123 server = account->getServer().latin1();
124 port = account->getPort().toUInt(); 124 port = account->getPort().toUInt();
125 125
126 user = pass = 0; 126 user = pass = 0;
127 127
128 if ( ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) && account->getLogin() ) { 128 if ( ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) && account->getLogin() ) {
129 LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true ); 129 LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true );
130 login.show(); 130 login.show();
131 if ( QDialog::Accepted == login.exec() ) { 131 if ( QDialog::Accepted == login.exec() ) {
132 // ok 132 // ok
133 User = login.getUser().latin1(); 133 User = login.getUser().latin1();
134 Pass = login.getPassword().latin1(); 134 Pass = login.getPassword().latin1();
135 } else { 135 } else {
136 // cancel 136 // cancel
137 qDebug( "NNTP: Login canceled" ); 137 odebug << "NNTP: Login canceled" << oendl;
138 return; 138 return;
139 } 139 }
140 } else { 140 } else {
141 User = account->getUser().latin1(); 141 User = account->getUser().latin1();
142 Pass = account->getPassword().latin1(); 142 Pass = account->getPassword().latin1();
143 } 143 }
144 144
145 if (User.isEmpty()) { 145 if (User.isEmpty()) {
146 user=0; 146 user=0;
147 pass = 0; 147 pass = 0;
148 } else { 148 } else {
149 user=User.latin1(); 149 user=User.latin1();
150 pass=Pass.latin1(); 150 pass=Pass.latin1();
151 } 151 }
152 // bool ssl = account->getSSL(); 152 // bool ssl = account->getSSL();
153 153
154 m_nntp=mailstorage_new(NULL); 154 m_nntp=mailstorage_new(NULL);
155 155
156 int conntypeset = account->ConnectionType(); 156 int conntypeset = account->ConnectionType();
157 int conntype = 0; 157 int conntype = 0;
158 if ( conntypeset == 3 ) { 158 if ( conntypeset == 3 ) {
159 conntype = CONNECTION_TYPE_COMMAND; 159 conntype = CONNECTION_TYPE_COMMAND;
160 } else if ( conntypeset == 2 ) { 160 } else if ( conntypeset == 2 ) {
161 conntype = CONNECTION_TYPE_TLS; 161 conntype = CONNECTION_TYPE_TLS;
162 } else if ( conntypeset == 1 ) { 162 } else if ( conntypeset == 1 ) {
163 conntype = CONNECTION_TYPE_STARTTLS; 163 conntype = CONNECTION_TYPE_STARTTLS;
164 } else if ( conntypeset == 0 ) { 164 } else if ( conntypeset == 0 ) {
165 conntype = CONNECTION_TYPE_TRY_STARTTLS; 165 conntype = CONNECTION_TYPE_TRY_STARTTLS;
166 } 166 }
167 167
168 nntp_mailstorage_init(m_nntp,(char*)server, port, NULL, CONNECTION_TYPE_PLAIN, NNTP_AUTH_TYPE_PLAIN, 168 nntp_mailstorage_init(m_nntp,(char*)server, port, NULL, CONNECTION_TYPE_PLAIN, NNTP_AUTH_TYPE_PLAIN,
169 (char*)user,(char*)pass,0,0,0); 169 (char*)user,(char*)pass,0,0,0);
170 170
171 err = mailstorage_connect( m_nntp ); 171 err = mailstorage_connect( m_nntp );
172 172
173 if (err != NEWSNNTP_NO_ERROR) { 173 if (err != NEWSNNTP_NO_ERROR) {
174 qDebug( QString( "FEHLERNUMMER %1" ).arg( err ) ); 174 odebug << QString( "FEHLERNUMMER %1" ).arg( err ) << oendl;
175 // Global::statusMessage(tr("Error initializing folder")); 175 // Global::statusMessage(tr("Error initializing folder"));
176 mailstorage_free(m_nntp); 176 mailstorage_free(m_nntp);
177 m_nntp = 0; 177 m_nntp = 0;
178 178
179 } else { 179 } else {
180 mailsession * session = m_nntp->sto_session; 180 mailsession * session = m_nntp->sto_session;
181 newsnntp * news = ( ( nntp_session_state_data * )session->sess_data )->nntp_session; 181 newsnntp * news = ( ( nntp_session_state_data * )session->sess_data )->nntp_session;
182 news->nntp_progr_fun = &nntp_progress; 182 news->nntp_progr_fun = &nntp_progress;
183 } 183 }
184 184
185} 185}
186 186
187void NNTPwrapper::logout() 187void NNTPwrapper::logout()
188{ 188{
189 int err = NEWSNNTP_NO_ERROR; 189 int err = NEWSNNTP_NO_ERROR;
190 if ( m_nntp == NULL ) 190 if ( m_nntp == NULL )
191 return; 191 return;
192 mailstorage_free(m_nntp); 192 mailstorage_free(m_nntp);
193 m_nntp = 0; 193 m_nntp = 0;
194} 194}
195 195
196QValueList<Opie::Core::OSmartPointer<Folder> >* NNTPwrapper::listFolders() { 196QValueList<Opie::Core::OSmartPointer<Folder> >* NNTPwrapper::listFolders() {
197 197
198 QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >(); 198 QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<Opie::Core::OSmartPointer<Folder> >();
199 QStringList groups; 199 QStringList groups;
200 if (account) { 200 if (account) {
201 groups = account->getGroups(); 201 groups = account->getGroups();
202 } 202 }
203 for ( QStringList::Iterator it = groups.begin(); it != groups.end(); ++it ) { 203 for ( QStringList::Iterator it = groups.begin(); it != groups.end(); ++it ) {
204 folders->append(new Folder((*it),".")); 204 folders->append(new Folder((*it),"."));
205 } 205 }
206 return folders; 206 return folders;
207} 207}
208 208
209/* we made this method in raw nntp access of etpan and not via generic interface 209/* we made this method in raw nntp access of etpan and not via generic interface
210 * 'cause in that case there will be doubled copy operations. eg. the etpan would 210 * 'cause in that case there will be doubled copy operations. eg. the etpan would
211 * copy that stuff into its own structures and we must copy it into useable c++ 211 * copy that stuff into its own structures and we must copy it into useable c++
212 * structures for our frontend. this would not make sense, so it is better to reimplement 212 * structures for our frontend. this would not make sense, so it is better to reimplement
213 * the stuff from generic interface of etpan but copy it direct to qt classes. 213 * the stuff from generic interface of etpan but copy it direct to qt classes.
214 */ 214 */
215QStringList NNTPwrapper::listAllNewsgroups(const QString&mask) { 215QStringList NNTPwrapper::listAllNewsgroups(const QString&mask) {
216 login(); 216 login();
217 QStringList res; 217 QStringList res;
218 clist *result = 0; 218 clist *result = 0;
219 clistcell *current = 0; 219 clistcell *current = 0;
220 newsnntp_group_description *group; 220 newsnntp_group_description *group;
221 221
222 if ( m_nntp ) { 222 if ( m_nntp ) {
223 mailsession * session = m_nntp->sto_session; 223 mailsession * session = m_nntp->sto_session;
224 newsnntp * news = ( ( nntp_session_state_data * )session->sess_data )->nntp_session; 224 newsnntp * news = ( ( nntp_session_state_data * )session->sess_data )->nntp_session;
225 int err = NEWSNNTP_NO_ERROR; 225 int err = NEWSNNTP_NO_ERROR;
226 if (mask.isEmpty()) { 226 if (mask.isEmpty()) {
227 err = newsnntp_list(news, &result); 227 err = newsnntp_list(news, &result);
228 } else { 228 } else {
229 /* taken from generic wrapper of etpan */ 229 /* taken from generic wrapper of etpan */
230 QString nmask = mask+".*"; 230 QString nmask = mask+".*";
231 err = newsnntp_list_active(news, nmask.latin1(), &result); 231 err = newsnntp_list_active(news, nmask.latin1(), &result);
232 } 232 }
233 if ( err == NEWSNNTP_NO_ERROR && result) { 233 if ( err == NEWSNNTP_NO_ERROR && result) {
234 for ( current=clist_begin(result);current!=NULL;current=clist_next(current) ) { 234 for ( current=clist_begin(result);current!=NULL;current=clist_next(current) ) {
235 group = ( newsnntp_group_description* ) current->data; 235 group = ( newsnntp_group_description* ) current->data;
236 if (!group||!group->grp_name||strlen(group->grp_name)==0) continue; 236 if (!group||!group->grp_name||strlen(group->grp_name)==0) continue;
237 res.append(group->grp_name); 237 res.append(group->grp_name);
238 } 238 }
239 } 239 }
240 } 240 }
241 if (result) { 241 if (result) {
242 newsnntp_list_free(result); 242 newsnntp_list_free(result);
243 } 243 }
244 return res; 244 return res;
245} 245}
246 246
247void NNTPwrapper::answeredMail(const RecMailP&) {} 247void NNTPwrapper::answeredMail(const RecMailP&) {}
248 248
249void NNTPwrapper::statusFolder(folderStat&target_stat,const QString&) { 249void NNTPwrapper::statusFolder(folderStat&target_stat,const QString&) {
250 login(); 250 login();
251 target_stat.message_count = 0; 251 target_stat.message_count = 0;
252 target_stat.message_unseen = 0; 252 target_stat.message_unseen = 0;
253 target_stat.message_recent = 0; 253 target_stat.message_recent = 0;
254 if (!m_nntp) 254 if (!m_nntp)
255 return; 255 return;
256 int r = mailsession_status_folder(m_nntp->sto_session,0,&target_stat.message_count, 256 int r = mailsession_status_folder(m_nntp->sto_session,0,&target_stat.message_count,
257 &target_stat.message_recent,&target_stat.message_unseen); 257 &target_stat.message_recent,&target_stat.message_unseen);
258} 258}
259 259
260 260
261encodedString* NNTPwrapper::fetchRawBody(const RecMailP&mail) { 261encodedString* NNTPwrapper::fetchRawBody(const RecMailP&mail) {
262 char*target=0; 262 char*target=0;
263 size_t length=0; 263 size_t length=0;
264 encodedString*res = 0; 264 encodedString*res = 0;
265 mailmessage * mailmsg = 0; 265 mailmessage * mailmsg = 0;
266 int err = mailsession_get_message(m_nntp->sto_session, mail->getNumber(), &mailmsg); 266 int err = mailsession_get_message(m_nntp->sto_session, mail->getNumber(), &mailmsg);
267 err = mailmessage_fetch(mailmsg,&target,&length); 267 err = mailmessage_fetch(mailmsg,&target,&length);
268 if (mailmsg) 268 if (mailmsg)
269 mailmessage_free(mailmsg); 269 mailmessage_free(mailmsg);
270 if (target) { 270 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 @@
1#include <stdlib.h> 1#include <stdlib.h>
2#include "pop3wrapper.h" 2#include "pop3wrapper.h"
3#include "mailtypes.h" 3#include "mailtypes.h"
4#include "logindialog.h" 4#include "logindialog.h"
5#include <libetpan/libetpan.h> 5#include <libetpan/libetpan.h>
6#include <qpe/global.h> 6#include <qpe/global.h>
7#include <qfile.h> 7#include <qfile.h>
8//#include <qstring.h> 8//#include <qstring.h>
9 9
10/* we don't fetch messages larger than 5 MB */ 10/* we don't fetch messages larger than 5 MB */
11#define HARD_MSG_SIZE_LIMIT 5242880 11#define HARD_MSG_SIZE_LIMIT 5242880
12 12
13using namespace Opie::Core; 13using namespace Opie::Core;
14POP3wrapper::POP3wrapper( POP3account *a ) 14POP3wrapper::POP3wrapper( POP3account *a )
15: Genericwrapper() { 15: Genericwrapper() {
16 account = a; 16 account = a;
17 m_pop3 = NULL; 17 m_pop3 = NULL;
18 msgTempName = a->getFileName()+"_msg_cache"; 18 msgTempName = a->getFileName()+"_msg_cache";
19 last_msg_id = 0; 19 last_msg_id = 0;
20} 20}
21 21
22POP3wrapper::~POP3wrapper() { 22POP3wrapper::~POP3wrapper() {
23 logout(); 23 logout();
24 QFile msg_cache(msgTempName); 24 QFile msg_cache(msgTempName);
25 if (msg_cache.exists()) { 25 if (msg_cache.exists()) {
26 msg_cache.remove(); 26 msg_cache.remove();
27 } 27 }
28} 28}
29 29
30void POP3wrapper::pop3_progress( size_t current, size_t maximum ) { 30void POP3wrapper::pop3_progress( size_t current, size_t maximum ) {
31 qDebug( "POP3: %i of %i", current, maximum ); 31 odebug << "POP3: " << current << " of " << maximum << "" << oendl;
32} 32}
33 33
34RecBodyP POP3wrapper::fetchBody( const RecMailP &mail ) { 34RecBodyP POP3wrapper::fetchBody( const RecMailP &mail ) {
35 int err = MAILPOP3_NO_ERROR; 35 int err = MAILPOP3_NO_ERROR;
36 char *message = 0; 36 char *message = 0;
37 size_t length = 0; 37 size_t length = 0;
38 38
39 RecBodyP body = new RecBody(); 39 RecBodyP body = new RecBody();
40 40
41 login(); 41 login();
42 if ( !m_pop3 ) { 42 if ( !m_pop3 ) {
43 return body; 43 return body;
44 } 44 }
45 45
46 mailmessage * mailmsg; 46 mailmessage * mailmsg;
47 if (mail->Msgsize()>HARD_MSG_SIZE_LIMIT) { 47 if (mail->Msgsize()>HARD_MSG_SIZE_LIMIT) {
48 qDebug("Message to large: %i",mail->Msgsize()); 48 odebug << "Message to large: " << mail->Msgsize() << "" << oendl;
49 return body; 49 return body;
50 } 50 }
51 51
52 QFile msg_cache(msgTempName); 52 QFile msg_cache(msgTempName);
53 53
54 cleanMimeCache(); 54 cleanMimeCache();
55 55
56 if (mail->getNumber()!=last_msg_id) { 56 if (mail->getNumber()!=last_msg_id) {
57 if (msg_cache.exists()) { 57 if (msg_cache.exists()) {
58 msg_cache.remove(); 58 msg_cache.remove();
59 } 59 }
60 msg_cache.open(IO_ReadWrite|IO_Truncate); 60 msg_cache.open(IO_ReadWrite|IO_Truncate);
61 last_msg_id = mail->getNumber(); 61 last_msg_id = mail->getNumber();
62 err = mailsession_get_message(m_pop3->sto_session, mail->getNumber(), &mailmsg); 62 err = mailsession_get_message(m_pop3->sto_session, mail->getNumber(), &mailmsg);
63 err = mailmessage_fetch(mailmsg,&message,&length); 63 err = mailmessage_fetch(mailmsg,&message,&length);
64 msg_cache.writeBlock(message,length); 64 msg_cache.writeBlock(message,length);
65 } else { 65 } else {
66 QString msg=""; 66 QString msg="";
67 msg_cache.open(IO_ReadOnly); 67 msg_cache.open(IO_ReadOnly);
68 message = new char[4096]; 68 message = new char[4096];
69 memset(message,0,4096); 69 memset(message,0,4096);
70 while (msg_cache.readBlock(message,4095)>0) { 70 while (msg_cache.readBlock(message,4095)>0) {
71 msg+=message; 71 msg+=message;
72 memset(message,0,4096); 72 memset(message,0,4096);
73 } 73 }
74 delete message; 74 delete message;
75 message = (char*)malloc(msg.length()+1*sizeof(char)); 75 message = (char*)malloc(msg.length()+1*sizeof(char));
76 memset(message,0,msg.length()+1); 76 memset(message,0,msg.length()+1);
77 memcpy(message,msg.latin1(),msg.length()); 77 memcpy(message,msg.latin1(),msg.length());
78 /* transform to libetpan stuff */ 78 /* transform to libetpan stuff */
79 mailmsg = mailmessage_new(); 79 mailmsg = mailmessage_new();
80 mailmessage_init(mailmsg, NULL, data_message_driver, 0, strlen(message)); 80 mailmessage_init(mailmsg, NULL, data_message_driver, 0, strlen(message));
81 generic_message_t * msg_data; 81 generic_message_t * msg_data;
82 msg_data = (generic_message_t *)mailmsg->msg_data; 82 msg_data = (generic_message_t *)mailmsg->msg_data;
83 msg_data->msg_fetched = 1; 83 msg_data->msg_fetched = 1;
84 msg_data->msg_message = message; 84 msg_data->msg_message = message;
85 msg_data->msg_length = strlen(message); 85 msg_data->msg_length = strlen(message);
86 } 86 }
87 body = parseMail(mailmsg); 87 body = parseMail(mailmsg);
88 88
89 /* clean up */ 89 /* clean up */
90 if (mailmsg) 90 if (mailmsg)
91 mailmessage_free(mailmsg); 91 mailmessage_free(mailmsg);
92 if (message) 92 if (message)
93 free(message); 93 free(message);
94 94
95 return body; 95 return body;
96} 96}
97 97
98void POP3wrapper::listMessages(const QString &, QValueList<Opie::Core::OSmartPointer<RecMail> > &target ) 98void POP3wrapper::listMessages(const QString &, QValueList<Opie::Core::OSmartPointer<RecMail> > &target )
99{ 99{
100 login(); 100 login();
101 if (!m_pop3) 101 if (!m_pop3)
102 return; 102 return;
103 uint32_t res_messages,res_recent,res_unseen; 103 uint32_t res_messages,res_recent,res_unseen;
104 mailsession_status_folder(m_pop3->sto_session,"INBOX",&res_messages,&res_recent,&res_unseen); 104 mailsession_status_folder(m_pop3->sto_session,"INBOX",&res_messages,&res_recent,&res_unseen);
105 parseList(target,m_pop3->sto_session,"INBOX"); 105 parseList(target,m_pop3->sto_session,"INBOX");
106 Global::statusMessage( tr("Mailbox contains %1 mail(s)").arg(res_messages)); 106 Global::statusMessage( tr("Mailbox contains %1 mail(s)").arg(res_messages));
107} 107}
108 108
109void POP3wrapper::login() 109void POP3wrapper::login()
110{ 110{
111 if (account->getOffline()) 111 if (account->getOffline())
112 return; 112 return;
113 /* we'll hold the line */ 113 /* we'll hold the line */
114 if ( m_pop3 != NULL ) 114 if ( m_pop3 != NULL )
115 return; 115 return;
116 116
117 const char *server, *user, *pass; 117 const char *server, *user, *pass;
118 uint16_t port; 118 uint16_t port;
119 int err = MAILPOP3_NO_ERROR; 119 int err = MAILPOP3_NO_ERROR;
120 120
121 server = account->getServer().latin1(); 121 server = account->getServer().latin1();
122 port = account->getPort().toUInt(); 122 port = account->getPort().toUInt();
123 123
124 if ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) { 124 if ( account->getUser().isEmpty() || account->getPassword().isEmpty() ) {
125 LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true ); 125 LoginDialog login( account->getUser(), account->getPassword(), NULL, 0, true );
126 login.show(); 126 login.show();
127 if ( QDialog::Accepted == login.exec() ) { 127 if ( QDialog::Accepted == login.exec() ) {
128 // ok 128 // ok
129 user = login.getUser().latin1(); 129 user = login.getUser().latin1();
130 pass = login.getPassword().latin1(); 130 pass = login.getPassword().latin1();
131 } else { 131 } else {
132 // cancel 132 // cancel
133 qDebug( "POP3: Login canceled" ); 133 odebug << "POP3: Login canceled" << oendl;
134 return; 134 return;
135 } 135 }
136 } else { 136 } else {
137 user = account->getUser().latin1(); 137 user = account->getUser().latin1();
138 pass = account->getPassword().latin1(); 138 pass = account->getPassword().latin1();
139 } 139 }
140 140
141 // bool ssl = account->getSSL(); 141 // bool ssl = account->getSSL();
142 142
143 m_pop3=mailstorage_new(NULL); 143 m_pop3=mailstorage_new(NULL);
144 144
145 int conntypeset = account->ConnectionType(); 145 int conntypeset = account->ConnectionType();
146 int conntype = 0; 146 int conntype = 0;
147 if ( conntypeset == 3 ) { 147 if ( conntypeset == 3 ) {
148 conntype = CONNECTION_TYPE_COMMAND; 148 conntype = CONNECTION_TYPE_COMMAND;
149 } else if ( conntypeset == 2 ) { 149 } else if ( conntypeset == 2 ) {
150 conntype = CONNECTION_TYPE_TLS; 150 conntype = CONNECTION_TYPE_TLS;
151 } else if ( conntypeset == 1 ) { 151 } else if ( conntypeset == 1 ) {
152 conntype = CONNECTION_TYPE_STARTTLS; 152 conntype = CONNECTION_TYPE_STARTTLS;
153 } else if ( conntypeset == 0 ) { 153 } else if ( conntypeset == 0 ) {
154 conntype = CONNECTION_TYPE_TRY_STARTTLS; 154 conntype = CONNECTION_TYPE_TRY_STARTTLS;
155 } 155 }
156 156
157 //(ssl?CONNECTION_TYPE_TLS:CONNECTION_TYPE_PLAIN); 157 //(ssl?CONNECTION_TYPE_TLS:CONNECTION_TYPE_PLAIN);
158 158
159 pop3_mailstorage_init(m_pop3,(char*)server, port, NULL, conntype, POP3_AUTH_TYPE_PLAIN, 159 pop3_mailstorage_init(m_pop3,(char*)server, port, NULL, conntype, POP3_AUTH_TYPE_PLAIN,
160 (char*)user,(char*)pass,0,0,0); 160 (char*)user,(char*)pass,0,0,0);
161 161
162 162
163 err = mailstorage_connect(m_pop3); 163 err = mailstorage_connect(m_pop3);
164 if (err != MAIL_NO_ERROR) { 164 if (err != MAIL_NO_ERROR) {
165 qDebug( QString( "FEHLERNUMMER %1" ).arg( err ) ); 165 odebug << QString( "FEHLERNUMMER %1" ).arg( err ) << oendl;
166 Global::statusMessage(tr("Error initializing folder")); 166 Global::statusMessage(tr("Error initializing folder"));
167 mailstorage_free(m_pop3); 167 mailstorage_free(m_pop3);
168 m_pop3 = 0; 168 m_pop3 = 0;
169 } else { 169 } else {
170 mailsession * session = m_pop3->sto_session; 170 mailsession * session = m_pop3->sto_session;
171 mailpop3 * mail = ( ( pop3_session_state_data * )session->sess_data )->pop3_session; 171 mailpop3 * mail = ( ( pop3_session_state_data * )session->sess_data )->pop3_session;
172 if (mail) { 172 if (mail) {
173 mail->pop3_progr_fun = &pop3_progress; 173 mail->pop3_progr_fun = &pop3_progress;
174 } 174 }
175 } 175 }
176} 176}
177 177
178void POP3wrapper::logout() 178void POP3wrapper::logout()
179{ 179{
180 if ( m_pop3 == NULL ) 180 if ( m_pop3 == NULL )
181 return; 181 return;
182 mailstorage_free(m_pop3); 182 mailstorage_free(m_pop3);
183 m_pop3 = 0; 183 m_pop3 = 0;
184} 184}
185 185
186 186
187QValueList<Opie::Core::OSmartPointer<Folder> >* POP3wrapper::listFolders() { 187QValueList<Opie::Core::OSmartPointer<Folder> >* POP3wrapper::listFolders() {
188 QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<FolderP>(); 188 QValueList<Opie::Core::OSmartPointer<Folder> >* folders = new QValueList<FolderP>();
189 FolderP inb=new Folder("INBOX","/"); 189 FolderP inb=new Folder("INBOX","/");
190 folders->append(inb); 190 folders->append(inb);
191 return folders; 191 return folders;
192} 192}
193 193
194void POP3wrapper::deleteMail(const RecMailP&mail) { 194void POP3wrapper::deleteMail(const RecMailP&mail) {
195 login(); 195 login();
196 if (!m_pop3) 196 if (!m_pop3)
197 return; 197 return;
198 int err = mailsession_remove_message(m_pop3->sto_session,mail->getNumber()); 198 int err = mailsession_remove_message(m_pop3->sto_session,mail->getNumber());
199 if (err != MAIL_NO_ERROR) { 199 if (err != MAIL_NO_ERROR) {
200 Global::statusMessage(tr("error deleting mail")); 200 Global::statusMessage(tr("error deleting mail"));
201 } 201 }
202} 202}
203 203
204void POP3wrapper::answeredMail(const RecMailP&) {} 204void POP3wrapper::answeredMail(const RecMailP&) {}
205 205
206int POP3wrapper::deleteAllMail(const FolderP&) { 206int POP3wrapper::deleteAllMail(const FolderP&) {
207 login(); 207 login();
208 if (!m_pop3) 208 if (!m_pop3)
209 return 0; 209 return 0;
210 int res = 1; 210 int res = 1;
211 211
212 uint32_t result = 0; 212 uint32_t result = 0;
213 int err = mailsession_messages_number(m_pop3->sto_session,NULL,&result); 213 int err = mailsession_messages_number(m_pop3->sto_session,NULL,&result);
214 if (err != MAIL_NO_ERROR) { 214 if (err != MAIL_NO_ERROR) {
215 Global::statusMessage(tr("Error getting folder info")); 215 Global::statusMessage(tr("Error getting folder info"));
216 return 0; 216 return 0;
217 } 217 }
218 for (unsigned int i = 0; i < result; ++i) { 218 for (unsigned int i = 0; i < result; ++i) {
219 err = mailsession_remove_message(m_pop3->sto_session,i+1); 219 err = mailsession_remove_message(m_pop3->sto_session,i+1);
220 if (err != MAIL_NO_ERROR) { 220 if (err != MAIL_NO_ERROR) {
221 Global::statusMessage(tr("Error deleting mail %1").arg(i+1)); 221 Global::statusMessage(tr("Error deleting mail %1").arg(i+1));
222 res=0; 222 res=0;
223 } 223 }
224 break; 224 break;
225 } 225 }
226 return res; 226 return res;
227} 227}
228 228
229void POP3wrapper::statusFolder(folderStat&target_stat,const QString&) { 229void POP3wrapper::statusFolder(folderStat&target_stat,const QString&) {
230 login(); 230 login();
231 target_stat.message_count = 0; 231 target_stat.message_count = 0;
232 target_stat.message_unseen = 0; 232 target_stat.message_unseen = 0;
233 target_stat.message_recent = 0; 233 target_stat.message_recent = 0;
234 if (!m_pop3) 234 if (!m_pop3)
235 return; 235 return;
236 int r = mailsession_status_folder(m_pop3->sto_session,0,&target_stat.message_count, 236 int r = mailsession_status_folder(m_pop3->sto_session,0,&target_stat.message_count,
237 &target_stat.message_recent,&target_stat.message_unseen); 237 &target_stat.message_recent,&target_stat.message_unseen);
238 if (r != MAIL_NO_ERROR) { 238 if (r != MAIL_NO_ERROR) {
239 qDebug("error getting folter status."); 239 odebug << "error getting folter status." << oendl;
240 } 240 }
241} 241}
242 242
243encodedString* POP3wrapper::fetchRawBody(const RecMailP&mail) { 243encodedString* POP3wrapper::fetchRawBody(const RecMailP&mail) {
244 char*target=0; 244 char*target=0;
245 size_t length=0; 245 size_t length=0;
246 encodedString*res = 0; 246 encodedString*res = 0;
247 mailmessage * mailmsg = 0; 247 mailmessage * mailmsg = 0;
248 int err = mailsession_get_message(m_pop3->sto_session, mail->getNumber(), &mailmsg); 248 int err = mailsession_get_message(m_pop3->sto_session, mail->getNumber(), &mailmsg);
249 err = mailmessage_fetch(mailmsg,&target,&length); 249 err = mailmessage_fetch(mailmsg,&target,&length);
250 if (mailmsg) 250 if (mailmsg)
251 mailmessage_free(mailmsg); 251 mailmessage_free(mailmsg);
252 if (target) { 252 if (target) {
253 res = new encodedString(target,length); 253 res = new encodedString(target,length);
254 } 254 }
255 return res; 255 return res;
256} 256}
257 257
258MAILLIB::ATYPE POP3wrapper::getType()const { 258MAILLIB::ATYPE POP3wrapper::getType()const {
259 return account->getType(); 259 return account->getType();
260} 260}
261 261
262const QString&POP3wrapper::getName()const{ 262const QString&POP3wrapper::getName()const{
263 return account->getAccountName(); 263 return account->getAccountName();
264} 264}
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 @@
1#include <stdlib.h> 1#include <stdlib.h>
2#include <qdir.h> 2#include <qdir.h>
3 3
4#include <qpe/config.h> 4#include <qpe/config.h>
5 5
6#include "settings.h" 6#include "settings.h"
7//#include "defines.h" 7//#include "defines.h"
8 8
9#define IMAP_PORT "143" 9#define IMAP_PORT "143"
10#define IMAP_SSL_PORT "993" 10#define IMAP_SSL_PORT "993"
11#define SMTP_PORT "25" 11#define SMTP_PORT "25"
12#define SMTP_SSL_PORT "465" 12#define SMTP_SSL_PORT "465"
13#define POP3_PORT "110" 13#define POP3_PORT "110"
14#define POP3_SSL_PORT "995" 14#define POP3_SSL_PORT "995"
15#define NNTP_PORT "119" 15#define NNTP_PORT "119"
16#define NNTP_SSL_PORT "563" 16#define NNTP_SSL_PORT "563"
17 17
18 18
19Settings::Settings() 19Settings::Settings()
20 : QObject() 20 : QObject()
21{ 21{
22 updateAccounts(); 22 updateAccounts();
23} 23}
24 24
25void Settings::checkDirectory() 25void Settings::checkDirectory()
26{ 26{
27 if ( !QDir( (QString) getenv( "HOME" ) + "/Applications/opiemail/" ).exists() ) { 27 if ( !QDir( (QString) getenv( "HOME" ) + "/Applications/opiemail/" ).exists() ) {
28 system( "mkdir -p $HOME/Applications/opiemail" ); 28 system( "mkdir -p $HOME/Applications/opiemail" );
29 qDebug( "$HOME/Applications/opiemail created" ); 29 odebug << "$HOME/Applications/opiemail created" << oendl;
30 } 30 }
31} 31}
32 32
33QList<Account> Settings::getAccounts() 33QList<Account> Settings::getAccounts()
34{ 34{
35 return accounts; 35 return accounts;
36} 36}
37 37
38void Settings::addAccount( Account *account ) 38void Settings::addAccount( Account *account )
39{ 39{
40 accounts.append( account ); 40 accounts.append( account );
41} 41}
42 42
43void Settings::delAccount( Account *account ) 43void Settings::delAccount( Account *account )
44{ 44{
45 accounts.remove( account ); 45 accounts.remove( account );
46 account->remove(); 46 account->remove();
47} 47}
48 48
49void Settings::updateAccounts() 49void Settings::updateAccounts()
50{ 50{
51 accounts.clear(); 51 accounts.clear();
52 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" ); 52 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
53 QStringList::Iterator it; 53 QStringList::Iterator it;
54 54
55 QStringList imap = dir.entryList( "imap-*" ); 55 QStringList imap = dir.entryList( "imap-*" );
56 for ( it = imap.begin(); it != imap.end(); it++ ) { 56 for ( it = imap.begin(); it != imap.end(); it++ ) {
57 qDebug( "Added IMAP account" ); 57 odebug << "Added IMAP account" << oendl;
58 IMAPaccount *account = new IMAPaccount( (*it).replace(0, 5, "") ); 58 IMAPaccount *account = new IMAPaccount( (*it).replace(0, 5, "") );
59 accounts.append( account ); 59 accounts.append( account );
60 } 60 }
61 61
62 QStringList pop3 = dir.entryList( "pop3-*" ); 62 QStringList pop3 = dir.entryList( "pop3-*" );
63 for ( it = pop3.begin(); it != pop3.end(); it++ ) { 63 for ( it = pop3.begin(); it != pop3.end(); it++ ) {
64 qDebug( "Added POP account" ); 64 odebug << "Added POP account" << oendl;
65 POP3account *account = new POP3account( (*it).replace(0, 5, "") ); 65 POP3account *account = new POP3account( (*it).replace(0, 5, "") );
66 accounts.append( account ); 66 accounts.append( account );
67 } 67 }
68 68
69 QStringList smtp = dir.entryList( "smtp-*" ); 69 QStringList smtp = dir.entryList( "smtp-*" );
70 for ( it = smtp.begin(); it != smtp.end(); it++ ) { 70 for ( it = smtp.begin(); it != smtp.end(); it++ ) {
71 qDebug( "Added SMTP account" ); 71 odebug << "Added SMTP account" << oendl;
72 SMTPaccount *account = new SMTPaccount( (*it).replace(0, 5, "") ); 72 SMTPaccount *account = new SMTPaccount( (*it).replace(0, 5, "") );
73 accounts.append( account ); 73 accounts.append( account );
74 } 74 }
75 75
76 QStringList nntp = dir.entryList( "nntp-*" ); 76 QStringList nntp = dir.entryList( "nntp-*" );
77 for ( it = nntp.begin(); it != nntp.end(); it++ ) { 77 for ( it = nntp.begin(); it != nntp.end(); it++ ) {
78 qDebug( "Added NNTP account" ); 78 odebug << "Added NNTP account" << oendl;
79 NNTPaccount *account = new NNTPaccount( (*it).replace(0, 5, "") ); 79 NNTPaccount *account = new NNTPaccount( (*it).replace(0, 5, "") );
80 accounts.append( account ); 80 accounts.append( account );
81 } 81 }
82 82
83 readAccounts(); 83 readAccounts();
84} 84}
85 85
86void Settings::saveAccounts() 86void Settings::saveAccounts()
87{ 87{
88 checkDirectory(); 88 checkDirectory();
89 Account *it; 89 Account *it;
90 90
91 for ( it = accounts.first(); it; it = accounts.next() ) { 91 for ( it = accounts.first(); it; it = accounts.next() ) {
92 it->save(); 92 it->save();
93 } 93 }
94} 94}
95 95
96void Settings::readAccounts() 96void Settings::readAccounts()
97{ 97{
98 checkDirectory(); 98 checkDirectory();
99 Account *it; 99 Account *it;
100 100
101 for ( it = accounts.first(); it; it = accounts.next() ) { 101 for ( it = accounts.first(); it; it = accounts.next() ) {
102 it->read(); 102 it->read();
103 } 103 }
104} 104}
105 105
106Account::Account() 106Account::Account()
107{ 107{
108 accountName = "changeMe"; 108 accountName = "changeMe";
109 type = MAILLIB::A_UNDEFINED; 109 type = MAILLIB::A_UNDEFINED;
110 ssl = false; 110 ssl = false;
111 connectionType = 1; 111 connectionType = 1;
112 offline = false; 112 offline = false;
113} 113}
114 114
115void Account::remove() 115void Account::remove()
116{ 116{
117 QFile file( getFileName() ); 117 QFile file( getFileName() );
118 file.remove(); 118 file.remove();
119} 119}
120 120
121IMAPaccount::IMAPaccount() 121IMAPaccount::IMAPaccount()
122 : Account() 122 : Account()
123{ 123{
124 file = IMAPaccount::getUniqueFileName(); 124 file = IMAPaccount::getUniqueFileName();
125 accountName = "New IMAP Account"; 125 accountName = "New IMAP Account";
126 ssl = false; 126 ssl = false;
127 connectionType = 1; 127 connectionType = 1;
128 type = MAILLIB::A_IMAP; 128 type = MAILLIB::A_IMAP;
129 port = IMAP_PORT; 129 port = IMAP_PORT;
130} 130}
131 131
132IMAPaccount::IMAPaccount( QString filename ) 132IMAPaccount::IMAPaccount( QString filename )
133 : Account() 133 : Account()
134{ 134{
135 file = filename; 135 file = filename;
136 accountName = "New IMAP Account"; 136 accountName = "New IMAP Account";
137 ssl = false; 137 ssl = false;
138 connectionType = 1; 138 connectionType = 1;
139 type = MAILLIB::A_IMAP; 139 type = MAILLIB::A_IMAP;
140 port = IMAP_PORT; 140 port = IMAP_PORT;
141} 141}
142 142
143QString IMAPaccount::getUniqueFileName() 143QString IMAPaccount::getUniqueFileName()
144{ 144{
145 int num = 0; 145 int num = 0;
146 QString unique; 146 QString unique;
147 147
148 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" ); 148 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
149 149
150 QStringList imap = dir.entryList( "imap-*" ); 150 QStringList imap = dir.entryList( "imap-*" );
151 do { 151 do {
152 unique.setNum( num++ ); 152 unique.setNum( num++ );
153 } while ( imap.contains( "imap-" + unique ) > 0 ); 153 } while ( imap.contains( "imap-" + unique ) > 0 );
154 154
155 return unique; 155 return unique;
156} 156}
157 157
158void IMAPaccount::read() 158void IMAPaccount::read()
159{ 159{
160 Config *conf = new Config( getFileName(), Config::File ); 160 Config *conf = new Config( getFileName(), Config::File );
161 conf->setGroup( "IMAP Account" ); 161 conf->setGroup( "IMAP Account" );
162 accountName = conf->readEntry( "Account","" ); 162 accountName = conf->readEntry( "Account","" );
163 if (accountName.isNull()) accountName = ""; 163 if (accountName.isNull()) accountName = "";
164 server = conf->readEntry( "Server","" ); 164 server = conf->readEntry( "Server","" );
165 if (server.isNull()) server=""; 165 if (server.isNull()) server="";
166 port = conf->readEntry( "Port","" ); 166 port = conf->readEntry( "Port","" );
167 if (port.isNull()) port="143"; 167 if (port.isNull()) port="143";
168 connectionType = conf->readNumEntry( "ConnectionType" ); 168 connectionType = conf->readNumEntry( "ConnectionType" );
169 ssl = conf->readBoolEntry( "SSL",false ); 169 ssl = conf->readBoolEntry( "SSL",false );
170 user = conf->readEntry( "User","" ); 170 user = conf->readEntry( "User","" );
171 if (user.isNull()) user = ""; 171 if (user.isNull()) user = "";
172 password = conf->readEntryCrypt( "Password","" ); 172 password = conf->readEntryCrypt( "Password","" );
173 if (password.isNull()) password = ""; 173 if (password.isNull()) password = "";
174 prefix = conf->readEntry("MailPrefix",""); 174 prefix = conf->readEntry("MailPrefix","");
175 if (prefix.isNull()) prefix = ""; 175 if (prefix.isNull()) prefix = "";
176 offline = conf->readBoolEntry("Offline",false); 176 offline = conf->readBoolEntry("Offline",false);
177 delete conf; 177 delete conf;
178} 178}
179 179
180void IMAPaccount::save() 180void IMAPaccount::save()
181{ 181{
182 qDebug( "saving " + getFileName() ); 182 odebug << "saving " + getFileName() << oendl;
183 Settings::checkDirectory(); 183 Settings::checkDirectory();
184 184
185 Config *conf = new Config( getFileName(), Config::File ); 185 Config *conf = new Config( getFileName(), Config::File );
186 conf->setGroup( "IMAP Account" ); 186 conf->setGroup( "IMAP Account" );
187 conf->writeEntry( "Account", accountName ); 187 conf->writeEntry( "Account", accountName );
188 conf->writeEntry( "Server", server ); 188 conf->writeEntry( "Server", server );
189 conf->writeEntry( "Port", port ); 189 conf->writeEntry( "Port", port );
190 conf->writeEntry( "SSL", ssl ); 190 conf->writeEntry( "SSL", ssl );
191 conf->writeEntry( "ConnectionType", connectionType ); 191 conf->writeEntry( "ConnectionType", connectionType );
192 conf->writeEntry( "User", user ); 192 conf->writeEntry( "User", user );
193 conf->writeEntryCrypt( "Password", password ); 193 conf->writeEntryCrypt( "Password", password );
194 conf->writeEntry( "MailPrefix",prefix); 194 conf->writeEntry( "MailPrefix",prefix);
195 conf->writeEntry( "Offline",offline); 195 conf->writeEntry( "Offline",offline);
196 conf->write(); 196 conf->write();
197 delete conf; 197 delete conf;
198} 198}
199 199
200 200
201QString IMAPaccount::getFileName() 201QString IMAPaccount::getFileName()
202{ 202{
203 return (QString) getenv( "HOME" ) + "/Applications/opiemail/imap-" + file; 203 return (QString) getenv( "HOME" ) + "/Applications/opiemail/imap-" + file;
204} 204}
205 205
206POP3account::POP3account() 206POP3account::POP3account()
207 : Account() 207 : Account()
208{ 208{
209 file = POP3account::getUniqueFileName(); 209 file = POP3account::getUniqueFileName();
210 accountName = "New POP3 Account"; 210 accountName = "New POP3 Account";
211 ssl = false; 211 ssl = false;
212 connectionType = 1; 212 connectionType = 1;
213 type = MAILLIB::A_POP3; 213 type = MAILLIB::A_POP3;
214 port = POP3_PORT; 214 port = POP3_PORT;
215} 215}
216 216
217POP3account::POP3account( QString filename ) 217POP3account::POP3account( QString filename )
218 : Account() 218 : Account()
219{ 219{
220 file = filename; 220 file = filename;
221 accountName = "New POP3 Account"; 221 accountName = "New POP3 Account";
222 ssl = false; 222 ssl = false;
223 connectionType = 1; 223 connectionType = 1;
224 type = MAILLIB::A_POP3; 224 type = MAILLIB::A_POP3;
225 port = POP3_PORT; 225 port = POP3_PORT;
226} 226}
227 227
228QString POP3account::getUniqueFileName() 228QString POP3account::getUniqueFileName()
229{ 229{
230 int num = 0; 230 int num = 0;
231 QString unique; 231 QString unique;
232 232
233 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" ); 233 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
234 234
235 QStringList imap = dir.entryList( "pop3-*" ); 235 QStringList imap = dir.entryList( "pop3-*" );
236 do { 236 do {
237 unique.setNum( num++ ); 237 unique.setNum( num++ );
238 } while ( imap.contains( "pop3-" + unique ) > 0 ); 238 } while ( imap.contains( "pop3-" + unique ) > 0 );
239 239
240 return unique; 240 return unique;
241} 241}
242 242
243void POP3account::read() 243void POP3account::read()
244{ 244{
245 Config *conf = new Config( getFileName(), Config::File ); 245 Config *conf = new Config( getFileName(), Config::File );
246 conf->setGroup( "POP3 Account" ); 246 conf->setGroup( "POP3 Account" );
247 accountName = conf->readEntry( "Account" ); 247 accountName = conf->readEntry( "Account" );
248 server = conf->readEntry( "Server" ); 248 server = conf->readEntry( "Server" );
249 port = conf->readEntry( "Port" ); 249 port = conf->readEntry( "Port" );
250 ssl = conf->readBoolEntry( "SSL" ); 250 ssl = conf->readBoolEntry( "SSL" );
251 connectionType = conf->readNumEntry( "ConnectionType" ); 251 connectionType = conf->readNumEntry( "ConnectionType" );
252 user = conf->readEntry( "User" ); 252 user = conf->readEntry( "User" );
253 password = conf->readEntryCrypt( "Password" ); 253 password = conf->readEntryCrypt( "Password" );
254 offline = conf->readBoolEntry("Offline",false); 254 offline = conf->readBoolEntry("Offline",false);
255 delete conf; 255 delete conf;
256} 256}
257 257
258void POP3account::save() 258void POP3account::save()
259{ 259{
260 qDebug( "saving " + getFileName() ); 260 odebug << "saving " + getFileName() << oendl;
261 Settings::checkDirectory(); 261 Settings::checkDirectory();
262 262
263 Config *conf = new Config( getFileName(), Config::File ); 263 Config *conf = new Config( getFileName(), Config::File );
264 conf->setGroup( "POP3 Account" ); 264 conf->setGroup( "POP3 Account" );
265 conf->writeEntry( "Account", accountName ); 265 conf->writeEntry( "Account", accountName );
266 conf->writeEntry( "Server", server ); 266 conf->writeEntry( "Server", server );
267 conf->writeEntry( "Port", port ); 267 conf->writeEntry( "Port", port );
268 conf->writeEntry( "SSL", ssl ); 268 conf->writeEntry( "SSL", ssl );
269 conf->writeEntry( "ConnectionType", connectionType ); 269 conf->writeEntry( "ConnectionType", connectionType );
270 conf->writeEntry( "User", user ); 270 conf->writeEntry( "User", user );
271 conf->writeEntryCrypt( "Password", password ); 271 conf->writeEntryCrypt( "Password", password );
272 conf->writeEntry( "Offline",offline); 272 conf->writeEntry( "Offline",offline);
273 conf->write(); 273 conf->write();
274 delete conf; 274 delete conf;
275} 275}
276 276
277 277
278QString POP3account::getFileName() 278QString POP3account::getFileName()
279{ 279{
280 return (QString) getenv( "HOME" ) + "/Applications/opiemail/pop3-" + file; 280 return (QString) getenv( "HOME" ) + "/Applications/opiemail/pop3-" + file;
281} 281}
282 282
283SMTPaccount::SMTPaccount() 283SMTPaccount::SMTPaccount()
284 : Account() 284 : Account()
285{ 285{
286 file = SMTPaccount::getUniqueFileName(); 286 file = SMTPaccount::getUniqueFileName();
287 accountName = "New SMTP Account"; 287 accountName = "New SMTP Account";
288 ssl = false; 288 ssl = false;
289 connectionType = 1; 289 connectionType = 1;
290 login = false; 290 login = false;
291 useCC = false; 291 useCC = false;
292 useBCC = false; 292 useBCC = false;
293 useReply = false; 293 useReply = false;
294 type = MAILLIB::A_SMTP; 294 type = MAILLIB::A_SMTP;
295 port = SMTP_PORT; 295 port = SMTP_PORT;
296} 296}
297 297
298SMTPaccount::SMTPaccount( QString filename ) 298SMTPaccount::SMTPaccount( QString filename )
299 : Account() 299 : Account()
300{ 300{
301 file = filename; 301 file = filename;
302 accountName = "New SMTP Account"; 302 accountName = "New SMTP Account";
303 ssl = false; 303 ssl = false;
304 connectionType = 1; 304 connectionType = 1;
305 login = false; 305 login = false;
306 type = MAILLIB::A_SMTP; 306 type = MAILLIB::A_SMTP;
307 port = SMTP_PORT; 307 port = SMTP_PORT;
308} 308}
309 309
310QString SMTPaccount::getUniqueFileName() 310QString SMTPaccount::getUniqueFileName()
311{ 311{
312 int num = 0; 312 int num = 0;
313 QString unique; 313 QString unique;
314 314
315 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" ); 315 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
316 316
317 QStringList imap = dir.entryList( "smtp-*" ); 317 QStringList imap = dir.entryList( "smtp-*" );
318 do { 318 do {
319 unique.setNum( num++ ); 319 unique.setNum( num++ );
320 } while ( imap.contains( "smtp-" + unique ) > 0 ); 320 } while ( imap.contains( "smtp-" + unique ) > 0 );
321 321
322 return unique; 322 return unique;
323} 323}
324 324
325void SMTPaccount::read() 325void SMTPaccount::read()
326{ 326{
327 Config *conf = new Config( getFileName(), Config::File ); 327 Config *conf = new Config( getFileName(), Config::File );
328 conf->setGroup( "SMTP Account" ); 328 conf->setGroup( "SMTP Account" );
329 accountName = conf->readEntry( "Account" ); 329 accountName = conf->readEntry( "Account" );
330 server = conf->readEntry( "Server" ); 330 server = conf->readEntry( "Server" );
331 port = conf->readEntry( "Port" ); 331 port = conf->readEntry( "Port" );
332 ssl = conf->readBoolEntry( "SSL" ); 332 ssl = conf->readBoolEntry( "SSL" );
333 connectionType = conf->readNumEntry( "ConnectionType" ); 333 connectionType = conf->readNumEntry( "ConnectionType" );
334 login = conf->readBoolEntry( "Login" ); 334 login = conf->readBoolEntry( "Login" );
335 user = conf->readEntry( "User" ); 335 user = conf->readEntry( "User" );
336 password = conf->readEntryCrypt( "Password" ); 336 password = conf->readEntryCrypt( "Password" );
337 delete conf; 337 delete conf;
338} 338}
339 339
340void SMTPaccount::save() 340void SMTPaccount::save()
341{ 341{
342 qDebug( "saving " + getFileName() ); 342 odebug << "saving " + getFileName() << oendl;
343 Settings::checkDirectory(); 343 Settings::checkDirectory();
344 344
345 Config *conf = new Config( getFileName(), Config::File ); 345 Config *conf = new Config( getFileName(), Config::File );
346 conf->setGroup( "SMTP Account" ); 346 conf->setGroup( "SMTP Account" );
347 conf->writeEntry( "Account", accountName ); 347 conf->writeEntry( "Account", accountName );
348 conf->writeEntry( "Server", server ); 348 conf->writeEntry( "Server", server );
349 conf->writeEntry( "Port", port ); 349 conf->writeEntry( "Port", port );
350 conf->writeEntry( "SSL", ssl ); 350 conf->writeEntry( "SSL", ssl );
351 conf->writeEntry( "ConnectionType", connectionType ); 351 conf->writeEntry( "ConnectionType", connectionType );
352 conf->writeEntry( "Login", login ); 352 conf->writeEntry( "Login", login );
353 conf->writeEntry( "User", user ); 353 conf->writeEntry( "User", user );
354 conf->writeEntryCrypt( "Password", password ); 354 conf->writeEntryCrypt( "Password", password );
355 conf->write(); 355 conf->write();
356 delete conf; 356 delete conf;
357} 357}
358 358
359 359
360QString SMTPaccount::getFileName() 360QString SMTPaccount::getFileName()
361{ 361{
362 return (QString) getenv( "HOME" ) + "/Applications/opiemail/smtp-" + file; 362 return (QString) getenv( "HOME" ) + "/Applications/opiemail/smtp-" + file;
363} 363}
364 364
365NNTPaccount::NNTPaccount() 365NNTPaccount::NNTPaccount()
366 : Account() 366 : Account()
367{ 367{
368 file = NNTPaccount::getUniqueFileName(); 368 file = NNTPaccount::getUniqueFileName();
369 accountName = "New NNTP Account"; 369 accountName = "New NNTP Account";
370 ssl = false; 370 ssl = false;
371 login = false; 371 login = false;
372 type = MAILLIB::A_NNTP; 372 type = MAILLIB::A_NNTP;
373 port = NNTP_PORT; 373 port = NNTP_PORT;
374} 374}
375 375
376NNTPaccount::NNTPaccount( QString filename ) 376NNTPaccount::NNTPaccount( QString filename )
377 : Account() 377 : Account()
378{ 378{
379 file = filename; 379 file = filename;
380 accountName = "New NNTP Account"; 380 accountName = "New NNTP Account";
381 ssl = false; 381 ssl = false;
382 login = false; 382 login = false;
383 type = MAILLIB::A_NNTP; 383 type = MAILLIB::A_NNTP;
384 port = NNTP_PORT; 384 port = NNTP_PORT;
385} 385}
386 386
387QString NNTPaccount::getUniqueFileName() 387QString NNTPaccount::getUniqueFileName()
388{ 388{
389 int num = 0; 389 int num = 0;
390 QString unique; 390 QString unique;
391 391
392 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" ); 392 QDir dir( (QString) getenv( "HOME" ) + "/Applications/opiemail" );
393 393
394 QStringList imap = dir.entryList( "nntp-*" ); 394 QStringList imap = dir.entryList( "nntp-*" );
395 do { 395 do {
396 unique.setNum( num++ ); 396 unique.setNum( num++ );
397 } while ( imap.contains( "nntp-" + unique ) > 0 ); 397 } while ( imap.contains( "nntp-" + unique ) > 0 );
398 398
399 return unique; 399 return unique;
400} 400}
401 401
402void NNTPaccount::read() 402void NNTPaccount::read()
403{ 403{
404 Config *conf = new Config( getFileName(), Config::File ); 404 Config *conf = new Config( getFileName(), Config::File );
405 conf->setGroup( "NNTP Account" ); 405 conf->setGroup( "NNTP Account" );
406 accountName = conf->readEntry( "Account" ); 406 accountName = conf->readEntry( "Account" );
407 server = conf->readEntry( "Server" ); 407 server = conf->readEntry( "Server" );
408 port = conf->readEntry( "Port" ); 408 port = conf->readEntry( "Port" );
409 ssl = conf->readBoolEntry( "SSL" ); 409 ssl = conf->readBoolEntry( "SSL" );
410 login = conf->readBoolEntry( "Login" ); 410 login = conf->readBoolEntry( "Login" );
411 user = conf->readEntry( "User" ); 411 user = conf->readEntry( "User" );
412 password = conf->readEntryCrypt( "Password" ); 412 password = conf->readEntryCrypt( "Password" );
413 subscribedGroups = conf->readListEntry( "Subscribed", ',' ); 413 subscribedGroups = conf->readListEntry( "Subscribed", ',' );
414 delete conf; 414 delete conf;
415} 415}
416 416
417void NNTPaccount::save() 417void NNTPaccount::save()
418{ 418{
419 qDebug( "saving " + getFileName() ); 419 odebug << "saving " + getFileName() << oendl;
420 Settings::checkDirectory(); 420 Settings::checkDirectory();
421 421
422 Config *conf = new Config( getFileName(), Config::File ); 422 Config *conf = new Config( getFileName(), Config::File );
423 conf->setGroup( "NNTP Account" ); 423 conf->setGroup( "NNTP Account" );
424 conf->writeEntry( "Account", accountName ); 424 conf->writeEntry( "Account", accountName );
425 conf->writeEntry( "Server", server ); 425 conf->writeEntry( "Server", server );
426 conf->writeEntry( "Port", port ); 426 conf->writeEntry( "Port", port );
427 conf->writeEntry( "SSL", ssl ); 427 conf->writeEntry( "SSL", ssl );
428 conf->writeEntry( "Login", login ); 428 conf->writeEntry( "Login", login );
429 conf->writeEntry( "User", user ); 429 conf->writeEntry( "User", user );
430 conf->writeEntryCrypt( "Password", password ); 430 conf->writeEntryCrypt( "Password", password );
431 conf->writeEntry( "Subscribed" , subscribedGroups, ',' ); 431 conf->writeEntry( "Subscribed" , subscribedGroups, ',' );
432 conf->write(); 432 conf->write();
433 delete conf; 433 delete conf;
434} 434}
435 435
436 436
437QString NNTPaccount::getFileName() 437QString NNTPaccount::getFileName()
438{ 438{
439 return (QString) getenv( "HOME" ) + "/Applications/opiemail/nntp-" + file; 439 return (QString) getenv( "HOME" ) + "/Applications/opiemail/nntp-" + file;
440} 440}
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 )
22 m_SmtpAccount = aSmtp; 22 m_SmtpAccount = aSmtp;
23 Config cfg( "mail" ); 23 Config cfg( "mail" );
24 cfg.setGroup( "Status" ); 24 cfg.setGroup( "Status" );
25 m_queuedMail = cfg.readNumEntry( "outgoing", 0 ); 25 m_queuedMail = cfg.readNumEntry( "outgoing", 0 );
26 emit queuedMails( m_queuedMail ); 26 emit queuedMails( m_queuedMail );
27 connect( this, SIGNAL( queuedMails(int) ), this, SLOT( emitQCop(int) ) ); 27 connect( this, SIGNAL( queuedMails(int) ), this, SLOT( emitQCop(int) ) );
28 m_smtp = 0; 28 m_smtp = 0;
29} 29}
30 30
31SMTPwrapper::~SMTPwrapper() 31SMTPwrapper::~SMTPwrapper()
32{ 32{
33 disc_server(); 33 disc_server();
34} 34}
35 35
36void SMTPwrapper::emitQCop( int queued ) { 36void SMTPwrapper::emitQCop( int queued ) {
37 QCopEnvelope env( "QPE/Pim", "outgoingMails(int)" ); 37 QCopEnvelope env( "QPE/Pim", "outgoingMails(int)" );
38 env << queued; 38 env << queued;
39} 39}
40 40
41QString SMTPwrapper::mailsmtpError( int errnum ) { 41QString SMTPwrapper::mailsmtpError( int errnum ) {
42 switch ( errnum ) { 42 switch ( errnum ) {
43 case MAILSMTP_NO_ERROR: 43 case MAILSMTP_NO_ERROR:
44 return tr( "No error" ); 44 return tr( "No error" );
45 case MAILSMTP_ERROR_UNEXPECTED_CODE: 45 case MAILSMTP_ERROR_UNEXPECTED_CODE:
46 return tr( "Unexpected error code" ); 46 return tr( "Unexpected error code" );
47 case MAILSMTP_ERROR_SERVICE_NOT_AVAILABLE: 47 case MAILSMTP_ERROR_SERVICE_NOT_AVAILABLE:
48 return tr( "Service not available" ); 48 return tr( "Service not available" );
49 case MAILSMTP_ERROR_STREAM: 49 case MAILSMTP_ERROR_STREAM:
50 return tr( "Stream error" ); 50 return tr( "Stream error" );
51 case MAILSMTP_ERROR_HOSTNAME: 51 case MAILSMTP_ERROR_HOSTNAME:
52 return tr( "gethostname() failed" ); 52 return tr( "gethostname() failed" );
53 case MAILSMTP_ERROR_NOT_IMPLEMENTED: 53 case MAILSMTP_ERROR_NOT_IMPLEMENTED:
54 return tr( "Not implemented" ); 54 return tr( "Not implemented" );
55 case MAILSMTP_ERROR_ACTION_NOT_TAKEN: 55 case MAILSMTP_ERROR_ACTION_NOT_TAKEN:
56 return tr( "Error, action not taken" ); 56 return tr( "Error, action not taken" );
57 case MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION: 57 case MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION:
58 return tr( "Data exceeds storage allocation" ); 58 return tr( "Data exceeds storage allocation" );
59 case MAILSMTP_ERROR_IN_PROCESSING: 59 case MAILSMTP_ERROR_IN_PROCESSING:
60 return tr( "Error in processing" ); 60 return tr( "Error in processing" );
61 case MAILSMTP_ERROR_STARTTLS_NOT_SUPPORTED: 61 case MAILSMTP_ERROR_STARTTLS_NOT_SUPPORTED:
62 return tr( "Starttls not supported" ); 62 return tr( "Starttls not supported" );
63 // case MAILSMTP_ERROR_INSUFFISANT_SYSTEM_STORAGE: 63 // case MAILSMTP_ERROR_INSUFFISANT_SYSTEM_STORAGE:
64 // return tr( "Insufficient system storage" ); 64 // return tr( "Insufficient system storage" );
65 case MAILSMTP_ERROR_MAILBOX_UNAVAILABLE: 65 case MAILSMTP_ERROR_MAILBOX_UNAVAILABLE:
66 return tr( "Mailbox unavailable" ); 66 return tr( "Mailbox unavailable" );
67 case MAILSMTP_ERROR_MAILBOX_NAME_NOT_ALLOWED: 67 case MAILSMTP_ERROR_MAILBOX_NAME_NOT_ALLOWED:
68 return tr( "Mailbox name not allowed" ); 68 return tr( "Mailbox name not allowed" );
69 case MAILSMTP_ERROR_BAD_SEQUENCE_OF_COMMAND: 69 case MAILSMTP_ERROR_BAD_SEQUENCE_OF_COMMAND:
70 return tr( "Bad command sequence" ); 70 return tr( "Bad command sequence" );
71 case MAILSMTP_ERROR_USER_NOT_LOCAL: 71 case MAILSMTP_ERROR_USER_NOT_LOCAL:
72 return tr( "User not local" ); 72 return tr( "User not local" );
73 case MAILSMTP_ERROR_TRANSACTION_FAILED: 73 case MAILSMTP_ERROR_TRANSACTION_FAILED:
74 return tr( "Transaction failed" ); 74 return tr( "Transaction failed" );
75 case MAILSMTP_ERROR_MEMORY: 75 case MAILSMTP_ERROR_MEMORY:
76 return tr( "Memory error" ); 76 return tr( "Memory error" );
77 case MAILSMTP_ERROR_CONNECTION_REFUSED: 77 case MAILSMTP_ERROR_CONNECTION_REFUSED:
78 return tr( "Connection refused" ); 78 return tr( "Connection refused" );
79 default: 79 default:
80 return tr( "Unknown error code" ); 80 return tr( "Unknown error code" );
81 } 81 }
82} 82}
83 83
84 84
85void SMTPwrapper::progress( size_t current, size_t maximum ) { 85void SMTPwrapper::progress( size_t current, size_t maximum ) {
86 if (SMTPwrapper::sendProgress) { 86 if (SMTPwrapper::sendProgress) {
87 SMTPwrapper::sendProgress->setSingleMail(current, maximum ); 87 SMTPwrapper::sendProgress->setSingleMail(current, maximum );
88 qApp->processEvents(); 88 qApp->processEvents();
89 } 89 }
90} 90}
91 91
92void SMTPwrapper::storeMail(const char*mail, size_t length, const QString&box) { 92void SMTPwrapper::storeMail(const char*mail, size_t length, const QString&box) {
93 if (!mail) 93 if (!mail)
94 return; 94 return;
95 QString localfolders = AbstractMail::defaultLocalfolder(); 95 QString localfolders = AbstractMail::defaultLocalfolder();
96 AbstractMail*wrap = AbstractMail::getWrapper(localfolders); 96 AbstractMail*wrap = AbstractMail::getWrapper(localfolders);
97 wrap->createMbox(box); 97 wrap->createMbox(box);
98 wrap->storeMessage(mail,length,box); 98 wrap->storeMessage(mail,length,box);
99 delete wrap; 99 delete wrap;
100} 100}
101 101
102void SMTPwrapper::smtpSend( mailmime *mail,bool later) { 102void SMTPwrapper::smtpSend( mailmime *mail,bool later) {
103 clist *rcpts = 0; 103 clist *rcpts = 0;
104 char *from, *data; 104 char *from, *data;
105 size_t size; 105 size_t size;
106 106
107 from = data = 0; 107 from = data = 0;
108 108
109 mailmessage * msg = 0; 109 mailmessage * msg = 0;
110 msg = mime_message_init(mail); 110 msg = mime_message_init(mail);
111 mime_message_set_tmpdir(msg,getenv( "HOME" )); 111 mime_message_set_tmpdir(msg,getenv( "HOME" ));
112 int r = mailmessage_fetch(msg,&data,&size); 112 int r = mailmessage_fetch(msg,&data,&size);
113 mime_message_detach_mime(msg); 113 mime_message_detach_mime(msg);
114 mailmessage_free(msg); 114 mailmessage_free(msg);
115 if (r != MAIL_NO_ERROR || !data) { 115 if (r != MAIL_NO_ERROR || !data) {
116 if (data) 116 if (data)
117 free(data); 117 free(data);
118 qDebug("Error fetching mime..."); 118 odebug << "Error fetching mime..." << oendl;
119 return; 119 return;
120 } 120 }
121 msg = 0; 121 msg = 0;
122 if (later) { 122 if (later) {
123 storeMail(data,size,"Outgoing"); 123 storeMail(data,size,"Outgoing");
124 if (data) 124 if (data)
125 free( data ); 125 free( data );
126 Config cfg( "mail" ); 126 Config cfg( "mail" );
127 cfg.setGroup( "Status" ); 127 cfg.setGroup( "Status" );
128 cfg.writeEntry( "outgoing", ++m_queuedMail ); 128 cfg.writeEntry( "outgoing", ++m_queuedMail );
129 emit queuedMails( m_queuedMail ); 129 emit queuedMails( m_queuedMail );
130 return; 130 return;
131 } 131 }
132 from = getFrom( mail ); 132 from = getFrom( mail );
133 rcpts = createRcptList( mail->mm_data.mm_message.mm_fields ); 133 rcpts = createRcptList( mail->mm_data.mm_message.mm_fields );
134 smtpSend(from,rcpts,data,size); 134 smtpSend(from,rcpts,data,size);
135 if (data) { 135 if (data) {
136 free(data); 136 free(data);
137 } 137 }
138 if (from) { 138 if (from) {
139 free(from); 139 free(from);
140 } 140 }
141 if (rcpts) 141 if (rcpts)
142 smtp_address_list_free( rcpts ); 142 smtp_address_list_free( rcpts );
143} 143}
144 144
145void SMTPwrapper::storeFailedMail(const char*data,unsigned int size, const char*failuremessage) 145void SMTPwrapper::storeFailedMail(const char*data,unsigned int size, const char*failuremessage)
146{ 146{
147 if (data) { 147 if (data) {
148 storeMail(data,size,"Sendfailed"); 148 storeMail(data,size,"Sendfailed");
149 } 149 }
150 if (failuremessage) { 150 if (failuremessage) {
151 QMessageBox::critical(0,tr("Error sending mail"), 151 QMessageBox::critical(0,tr("Error sending mail"),
152 tr("<center>%1</center>").arg(failuremessage)); 152 tr("<center>%1</center>").arg(failuremessage));
153 } 153 }
154} 154}
155 155
156int SMTPwrapper::start_smtp_tls() 156int SMTPwrapper::start_smtp_tls()
157{ 157{
158 if (!m_smtp) { 158 if (!m_smtp) {
159 return MAILSMTP_ERROR_IN_PROCESSING; 159 return MAILSMTP_ERROR_IN_PROCESSING;
160 } 160 }
161 int err = mailesmtp_starttls(m_smtp); 161 int err = mailesmtp_starttls(m_smtp);
162 if (err != MAILSMTP_NO_ERROR) return err; 162 if (err != MAILSMTP_NO_ERROR) return err;
163 mailstream_low * low; 163 mailstream_low * low;
164 mailstream_low * new_low; 164 mailstream_low * new_low;
165 low = mailstream_get_low(m_smtp->stream); 165 low = mailstream_get_low(m_smtp->stream);
166 if (!low) { 166 if (!low) {
167 return MAILSMTP_ERROR_IN_PROCESSING; 167 return MAILSMTP_ERROR_IN_PROCESSING;
168 } 168 }
169 int fd = mailstream_low_get_fd(low); 169 int fd = mailstream_low_get_fd(low);
170 if (fd > -1 && (new_low = mailstream_low_ssl_open(fd))!=0) { 170 if (fd > -1 && (new_low = mailstream_low_ssl_open(fd))!=0) {
171 mailstream_low_free(low); 171 mailstream_low_free(low);
172 mailstream_set_low(m_smtp->stream, new_low); 172 mailstream_set_low(m_smtp->stream, new_low);
173 } else { 173 } else {
174 return MAILSMTP_ERROR_IN_PROCESSING; 174 return MAILSMTP_ERROR_IN_PROCESSING;
175 } 175 }
176 return err; 176 return err;
177} 177}
178 178
179void SMTPwrapper::connect_server() 179void SMTPwrapper::connect_server()
180{ 180{
181 const char *server, *user, *pass; 181 const char *server, *user, *pass;
182 bool ssl; 182 bool ssl;
183 uint16_t port; 183 uint16_t port;
184 ssl = false; 184 ssl = false;
185 bool try_tls = true; 185 bool try_tls = true;
186 bool force_tls=false; 186 bool force_tls=false;
187 server = user = pass = 0; 187 server = user = pass = 0;
188 QString failuretext = ""; 188 QString failuretext = "";
189 189
190 if (m_smtp || !m_SmtpAccount) { 190 if (m_smtp || !m_SmtpAccount) {
191 return; 191 return;
192 } 192 }
193 server = m_SmtpAccount->getServer().latin1(); 193 server = m_SmtpAccount->getServer().latin1();
194 if ( m_SmtpAccount->ConnectionType() == 2 ) { 194 if ( m_SmtpAccount->ConnectionType() == 2 ) {
195 ssl = true; 195 ssl = true;
196 try_tls = false; 196 try_tls = false;
197 } else if (m_SmtpAccount->ConnectionType() == 1) { 197 } else if (m_SmtpAccount->ConnectionType() == 1) {
198 force_tls = true; 198 force_tls = true;
199 } 199 }
200 int result = 1; 200 int result = 1;
201 port = m_SmtpAccount->getPort().toUInt(); 201 port = m_SmtpAccount->getPort().toUInt();
202 202
203 m_smtp = mailsmtp_new( 20, &progress ); 203 m_smtp = mailsmtp_new( 20, &progress );
204 if ( m_smtp == NULL ) { 204 if ( m_smtp == NULL ) {
205 /* no failure message cause this happens when problems with memory - than we 205 /* no failure message cause this happens when problems with memory - than we
206 we can not display any messagebox */ 206 we can not display any messagebox */
207 return; 207 return;
208 } 208 }
209 209
210 int err = MAILSMTP_NO_ERROR; 210 int err = MAILSMTP_NO_ERROR;
211 qDebug( "Servername %s at port %i", server, port ); 211 odebug << "Servername " << server << " at port " << port << "" << oendl;
212 if ( ssl ) { 212 if ( ssl ) {
213 qDebug( "SSL session" ); 213 odebug << "SSL session" << oendl;
214 err = mailsmtp_ssl_connect( m_smtp, server, port ); 214 err = mailsmtp_ssl_connect( m_smtp, server, port );
215 } else { 215 } else {
216 qDebug( "No SSL session" ); 216 odebug << "No SSL session" << oendl;
217 err = mailsmtp_socket_connect( m_smtp, server, port ); 217 err = mailsmtp_socket_connect( m_smtp, server, port );
218 } 218 }
219 if ( err != MAILSMTP_NO_ERROR ) { 219 if ( err != MAILSMTP_NO_ERROR ) {
220 qDebug("Error init connection"); 220 odebug << "Error init connection" << oendl;
221 failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err)); 221 failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err));
222 result = 0; 222 result = 0;
223 } 223 }
224 224
225 /* switch to tls after init 'cause there it will send the ehlo */ 225 /* switch to tls after init 'cause there it will send the ehlo */
226 if (result) { 226 if (result) {
227 err = mailsmtp_init( m_smtp ); 227 err = mailsmtp_init( m_smtp );
228 if (err != MAILSMTP_NO_ERROR) { 228 if (err != MAILSMTP_NO_ERROR) {
229 result = 0; 229 result = 0;
230 failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err)); 230 failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err));
231 } 231 }
232 } 232 }
233 233
234 if (try_tls) { 234 if (try_tls) {
235 err = start_smtp_tls(); 235 err = start_smtp_tls();
236 if (err != MAILSMTP_NO_ERROR) { 236 if (err != MAILSMTP_NO_ERROR) {
237 try_tls = false; 237 try_tls = false;
238 } else { 238 } else {
239 err = mailesmtp_ehlo(m_smtp); 239 err = mailesmtp_ehlo(m_smtp);
240 } 240 }
241 } 241 }
242 242
243 if (!try_tls && force_tls) { 243 if (!try_tls && force_tls) {
244 result = 0; 244 result = 0;
245 failuretext = tr("Error init SMTP tls: %1").arg(mailsmtpError(err)); 245 failuretext = tr("Error init SMTP tls: %1").arg(mailsmtpError(err));
246 } 246 }
247 247
248 if (result==1 && m_SmtpAccount->getLogin() ) { 248 if (result==1 && m_SmtpAccount->getLogin() ) {
249 qDebug("smtp with auth"); 249 odebug << "smtp with auth" << oendl;
250 if ( m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty() ) { 250 if ( m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty() ) {
251 // get'em 251 // get'em
252 LoginDialog login( m_SmtpAccount->getUser(), 252 LoginDialog login( m_SmtpAccount->getUser(),
253 m_SmtpAccount->getPassword(), NULL, 0, true ); 253 m_SmtpAccount->getPassword(), NULL, 0, true );
254 login.show(); 254 login.show();
255 if ( QDialog::Accepted == login.exec() ) { 255 if ( QDialog::Accepted == login.exec() ) {
256 // ok 256 // ok
257 user = login.getUser().latin1(); 257 user = login.getUser().latin1();
258 pass = login.getPassword().latin1(); 258 pass = login.getPassword().latin1();
259 } else { 259 } else {
260 result = 0; 260 result = 0;
261 failuretext=tr("Login aborted - storing mail to localfolder"); 261 failuretext=tr("Login aborted - storing mail to localfolder");
262 } 262 }
263 } else { 263 } else {
264 user = m_SmtpAccount->getUser().latin1(); 264 user = m_SmtpAccount->getUser().latin1();
265 pass = m_SmtpAccount->getPassword().latin1(); 265 pass = m_SmtpAccount->getPassword().latin1();
266 } 266 }
267 qDebug( "session->auth: %i", m_smtp->auth); 267 odebug << "session->auth: " << m_smtp->auth << "" << oendl;
268 if (result) { 268 if (result) {
269 err = mailsmtp_auth( m_smtp, (char*)user, (char*)pass ); 269 err = mailsmtp_auth( m_smtp, (char*)user, (char*)pass );
270 if ( err == MAILSMTP_NO_ERROR ) { 270 if ( err == MAILSMTP_NO_ERROR ) {
271 qDebug("auth ok"); 271 odebug << "auth ok" << oendl;
272 } else { 272 } else {
273 failuretext = tr("Authentification failed"); 273 failuretext = tr("Authentification failed");
274 result = 0; 274 result = 0;
275 } 275 }
276 } 276 }
277 } 277 }
278} 278}
279 279
280void SMTPwrapper::disc_server() 280void SMTPwrapper::disc_server()
281{ 281{
282 if (m_smtp) { 282 if (m_smtp) {
283 mailsmtp_quit( m_smtp ); 283 mailsmtp_quit( m_smtp );
284 mailsmtp_free( m_smtp ); 284 mailsmtp_free( m_smtp );
285 m_smtp = 0; 285 m_smtp = 0;
286 } 286 }
287} 287}
288 288
289int SMTPwrapper::smtpSend(char*from,clist*rcpts,const char*data,size_t size ) 289int SMTPwrapper::smtpSend(char*from,clist*rcpts,const char*data,size_t size )
290{ 290{
291 int err,result; 291 int err,result;
292 QString failuretext = ""; 292 QString failuretext = "";
293 293
294 connect_server(); 294 connect_server();
295 295
296 result = 1; 296 result = 1;
297 if (m_smtp) { 297 if (m_smtp) {
298 err = mailsmtp_send( m_smtp, from, rcpts, data, size ); 298 err = mailsmtp_send( m_smtp, from, rcpts, data, size );
299 if ( err != MAILSMTP_NO_ERROR ) { 299 if ( err != MAILSMTP_NO_ERROR ) {
300 failuretext=tr("Error sending mail: %1").arg(mailsmtpError(err)); 300 failuretext=tr("Error sending mail: %1").arg(mailsmtpError(err));
301 result = 0; 301 result = 0;
302 } 302 }
303 } else { 303 } else {
304 result = 0; 304 result = 0;
305 } 305 }
306 306
307 if (!result) { 307 if (!result) {
308 storeFailedMail(data,size,failuretext); 308 storeFailedMail(data,size,failuretext);
309 } else { 309 } else {
310 qDebug( "Mail sent." ); 310 odebug << "Mail sent." << oendl;
311 storeMail(data,size,"Sent"); 311 storeMail(data,size,"Sent");
312 } 312 }
313 return result; 313 return result;
314} 314}
315 315
316void SMTPwrapper::sendMail(const Opie::Core::OSmartPointer<Mail>&mail,bool later ) 316void SMTPwrapper::sendMail(const Opie::Core::OSmartPointer<Mail>&mail,bool later )
317{ 317{
318 mailmime * mimeMail; 318 mailmime * mimeMail;
319 319
320 mimeMail = createMimeMail(mail ); 320 mimeMail = createMimeMail(mail );
321 if ( mimeMail == NULL ) { 321 if ( mimeMail == NULL ) {
322 qDebug( "sendMail: error creating mime mail" ); 322 odebug << "sendMail: error creating mime mail" << oendl;
323 } else { 323 } else {
324 sendProgress = new progressMailSend(); 324 sendProgress = new progressMailSend();
325 sendProgress->show(); 325 sendProgress->show();
326 sendProgress->setMaxMails(1); 326 sendProgress->setMaxMails(1);
327 smtpSend( mimeMail,later); 327 smtpSend( mimeMail,later);
328 qDebug("Clean up done"); 328 odebug << "Clean up done" << oendl;
329 sendProgress->hide(); 329 sendProgress->hide();
330 delete sendProgress; 330 delete sendProgress;
331 sendProgress = 0; 331 sendProgress = 0;
332 mailmime_free( mimeMail ); 332 mailmime_free( mimeMail );
333 } 333 }
334} 334}
335 335
336int SMTPwrapper::sendQueuedMail(AbstractMail*wrap,const RecMailP&which) { 336int SMTPwrapper::sendQueuedMail(AbstractMail*wrap,const RecMailP&which) {
337 size_t curTok = 0; 337 size_t curTok = 0;
338 mailimf_fields *fields = 0; 338 mailimf_fields *fields = 0;
339 mailimf_field*ffrom = 0; 339 mailimf_field*ffrom = 0;
340 clist *rcpts = 0; 340 clist *rcpts = 0;
341 char*from = 0; 341 char*from = 0;
342 int res = 0; 342 int res = 0;
343 343
344 encodedString * data = wrap->fetchRawBody(which); 344 encodedString * data = wrap->fetchRawBody(which);
345 if (!data) 345 if (!data)
346 return 0; 346 return 0;
347 int err = mailimf_fields_parse( data->Content(), data->Length(), &curTok, &fields ); 347 int err = mailimf_fields_parse( data->Content(), data->Length(), &curTok, &fields );
348 if (err != MAILIMF_NO_ERROR) { 348 if (err != MAILIMF_NO_ERROR) {
349 delete data; 349 delete data;
350 delete wrap; 350 delete wrap;
351 return 0; 351 return 0;
352 } 352 }
353 353
354 rcpts = createRcptList( fields ); 354 rcpts = createRcptList( fields );
355 ffrom = getField(fields, MAILIMF_FIELD_FROM ); 355 ffrom = getField(fields, MAILIMF_FIELD_FROM );
356 from = getFrom(ffrom); 356 from = getFrom(ffrom);
357 357
358 if (rcpts && from) { 358 if (rcpts && from) {
359 res = smtpSend(from,rcpts,data->Content(),data->Length()); 359 res = smtpSend(from,rcpts,data->Content(),data->Length());
360 } 360 }
361 if (fields) { 361 if (fields) {
362 mailimf_fields_free(fields); 362 mailimf_fields_free(fields);
363 fields = 0; 363 fields = 0;
364 } 364 }
365 if (data) { 365 if (data) {
366 delete data; 366 delete data;
367 } 367 }
368 if (from) { 368 if (from) {
369 free(from); 369 free(from);
370 } 370 }
371 if (rcpts) { 371 if (rcpts) {
372 smtp_address_list_free( rcpts ); 372 smtp_address_list_free( rcpts );
373 } 373 }
374 return res; 374 return res;
375} 375}
376 376
377/* this is a special fun */ 377/* this is a special fun */
378bool SMTPwrapper::flushOutbox() { 378bool SMTPwrapper::flushOutbox() {
379 bool returnValue = true; 379 bool returnValue = true;
380 380
381 qDebug("Sending the queue"); 381 odebug << "Sending the queue" << oendl;
382 if (!m_SmtpAccount) { 382 if (!m_SmtpAccount) {
383 qDebug("No smtp account given"); 383 odebug << "No smtp account given" << oendl;
384 return false; 384 return false;
385 } 385 }
386 386
387 bool reset_user_value = false; 387 bool reset_user_value = false;
388 QString localfolders = AbstractMail::defaultLocalfolder(); 388 QString localfolders = AbstractMail::defaultLocalfolder();
389 AbstractMail*wrap = AbstractMail::getWrapper(localfolders); 389 AbstractMail*wrap = AbstractMail::getWrapper(localfolders);
390 if (!wrap) { 390 if (!wrap) {
391 qDebug("memory error"); 391 odebug << "memory error" << oendl;
392 return false; 392 return false;
393 } 393 }
394 QString oldPw, oldUser; 394 QString oldPw, oldUser;
395 QValueList<RecMailP> mailsToSend; 395 QValueList<RecMailP> mailsToSend;
396 QValueList<RecMailP> mailsToRemove; 396 QValueList<RecMailP> mailsToRemove;
397 QString mbox("Outgoing"); 397 QString mbox("Outgoing");
398 wrap->listMessages(mbox,mailsToSend); 398 wrap->listMessages(mbox,mailsToSend);
399 if (mailsToSend.count()==0) { 399 if (mailsToSend.count()==0) {
400 delete wrap; 400 delete wrap;
401 qDebug("No mails to send"); 401 odebug << "No mails to send" << oendl;
402 return false; 402 return false;
403 } 403 }
404 404
405 oldPw = m_SmtpAccount->getPassword(); 405 oldPw = m_SmtpAccount->getPassword();
406 oldUser = m_SmtpAccount->getUser(); 406 oldUser = m_SmtpAccount->getUser();
407 if (m_SmtpAccount->getLogin() && (m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty()) ) { 407 if (m_SmtpAccount->getLogin() && (m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty()) ) {
408 // get'em 408 // get'em
409 QString user,pass; 409 QString user,pass;
410 LoginDialog login( m_SmtpAccount->getUser(), m_SmtpAccount->getPassword(), NULL, 0, true ); 410 LoginDialog login( m_SmtpAccount->getUser(), m_SmtpAccount->getPassword(), NULL, 0, true );
411 login.show(); 411 login.show();
412 if ( QDialog::Accepted == login.exec() ) { 412 if ( QDialog::Accepted == login.exec() ) {
413 // ok 413 // ok
414 user = login.getUser().latin1(); 414 user = login.getUser().latin1();
415 pass = login.getPassword().latin1(); 415 pass = login.getPassword().latin1();
416 reset_user_value = true; 416 reset_user_value = true;
417 m_SmtpAccount->setUser(user); 417 m_SmtpAccount->setUser(user);
418 m_SmtpAccount->setPassword(pass); 418 m_SmtpAccount->setPassword(pass);
419 } else { 419 } else {
420 return true; 420 return true;
421 } 421 }
422 } 422 }
423 423
424 424
425 sendProgress = new progressMailSend(); 425 sendProgress = new progressMailSend();
426 sendProgress->show(); 426 sendProgress->show();
427 sendProgress->setMaxMails(mailsToSend.count()); 427 sendProgress->setMaxMails(mailsToSend.count());
428 428
429 while (mailsToSend.count()>0) { 429 while (mailsToSend.count()>0) {
430 if (sendQueuedMail(wrap, (*mailsToSend.begin()))==0) { 430 if (sendQueuedMail(wrap, (*mailsToSend.begin()))==0) {
431 QMessageBox::critical(0,tr("Error sending mail"), 431 QMessageBox::critical(0,tr("Error sending mail"),
432 tr("Error sending queued mail - breaking")); 432 tr("Error sending queued mail - breaking"));
433 returnValue = false; 433 returnValue = false;
434 break; 434 break;
435 } 435 }
436 mailsToRemove.append((*mailsToSend.begin())); 436 mailsToRemove.append((*mailsToSend.begin()));
437 mailsToSend.remove(mailsToSend.begin()); 437 mailsToSend.remove(mailsToSend.begin());
438 sendProgress->setCurrentMails(mailsToRemove.count()); 438 sendProgress->setCurrentMails(mailsToRemove.count());
439 } 439 }
440 if (reset_user_value) { 440 if (reset_user_value) {
441 m_SmtpAccount->setUser(oldUser); 441 m_SmtpAccount->setUser(oldUser);
442 m_SmtpAccount->setPassword(oldPw); 442 m_SmtpAccount->setPassword(oldPw);
443 } 443 }
444 Config cfg( "mail" ); 444 Config cfg( "mail" );
445 cfg.setGroup( "Status" ); 445 cfg.setGroup( "Status" );
446 m_queuedMail = 0; 446 m_queuedMail = 0;
447 cfg.writeEntry( "outgoing", m_queuedMail ); 447 cfg.writeEntry( "outgoing", m_queuedMail );
448 emit queuedMails( m_queuedMail ); 448 emit queuedMails( m_queuedMail );
449 sendProgress->hide(); 449 sendProgress->hide();
450 delete sendProgress; 450 delete sendProgress;
451 sendProgress = 0; 451 sendProgress = 0;
452 wrap->deleteMails(mbox,mailsToRemove); 452 wrap->deleteMails(mbox,mailsToRemove);
453 delete wrap; 453 delete wrap;
454 return returnValue; 454 return returnValue;
455} 455}
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 @@
1#include "statusmail.h" 1#include "statusmail.h"
2 2
3StatusMail::StatusMail(QList<Account>&list) 3StatusMail::StatusMail(QList<Account>&list)
4{ 4{
5 currentImapStat.message_count=0; 5 currentImapStat.message_count=0;
6 currentImapStat.message_unseen=0; 6 currentImapStat.message_unseen=0;
7 currentImapStat.message_recent=0; 7 currentImapStat.message_recent=0;
8 lastPop3Stat = currentImapStat; 8 lastPop3Stat = currentImapStat;
9 currentPop3Stat = currentImapStat; 9 currentPop3Stat = currentImapStat;
10 connectionList.setAutoDelete(true); 10 connectionList.setAutoDelete(true);
11 connectionList.clear(); 11 connectionList.clear();
12 initAccounts(list); 12 initAccounts(list);
13} 13}
14 14
15StatusMail::~StatusMail() 15StatusMail::~StatusMail()
16{ 16{
17} 17}
18 18
19void StatusMail::initAccounts(QList<Account>&accounts) 19void StatusMail::initAccounts(QList<Account>&accounts)
20{ 20{
21 21
22 Account *it; 22 Account *it;
23 folderStat currentStat; 23 folderStat currentStat;
24 AbstractMail * current = 0; 24 AbstractMail * current = 0;
25 currentPop3Stat.message_count=0; 25 currentPop3Stat.message_count=0;
26 currentPop3Stat.message_recent=0; 26 currentPop3Stat.message_recent=0;
27 currentPop3Stat.message_unseen=0; 27 currentPop3Stat.message_unseen=0;
28 for ( it = accounts.first(); it; it = accounts.next() ) { 28 for ( it = accounts.first(); it; it = accounts.next() ) {
29 if ( it->getType()==MAILLIB::A_IMAP && !it->getOffline() ) { 29 if ( it->getType()==MAILLIB::A_IMAP && !it->getOffline() ) {
30 IMAPaccount*ima = static_cast<IMAPaccount *>(it); 30 IMAPaccount*ima = static_cast<IMAPaccount *>(it);
31 current = AbstractMail::getWrapper(ima); 31 current = AbstractMail::getWrapper(ima);
32 connectionList.append(current); 32 connectionList.append(current);
33 current->statusFolder(currentStat); 33 current->statusFolder(currentStat);
34 currentImapStat.message_count+=currentStat.message_unseen; 34 currentImapStat.message_count+=currentStat.message_unseen;
35 currentImapStat.message_count+=currentStat.message_recent; 35 currentImapStat.message_count+=currentStat.message_recent;
36 currentImapStat.message_count+=currentStat.message_count; 36 currentImapStat.message_count+=currentStat.message_count;
37 } else if ( it->getType() == MAILLIB::A_POP3 && !it->getOffline() ) { 37 } else if ( it->getType() == MAILLIB::A_POP3 && !it->getOffline() ) {
38 POP3account *pop3 = static_cast<POP3account *>(it); 38 POP3account *pop3 = static_cast<POP3account *>(it);
39 current = AbstractMail::getWrapper(pop3); 39 current = AbstractMail::getWrapper(pop3);
40 connectionList.append(current); 40 connectionList.append(current);
41 current->statusFolder(currentStat); 41 current->statusFolder(currentStat);
42 currentPop3Stat.message_count+=currentStat.message_count; 42 currentPop3Stat.message_count+=currentStat.message_count;
43 } 43 }
44 current->logout(); 44 current->logout();
45 } 45 }
46 qDebug("Pop3 init count: %i",currentPop3Stat.message_count); 46 odebug << "Pop3 init count: " << currentPop3Stat.message_count << "" << oendl;
47 currentPop3Stat.message_recent = currentPop3Stat.message_unseen = 0; 47 currentPop3Stat.message_recent = currentPop3Stat.message_unseen = 0;
48 lastPop3Stat.message_unseen = currentPop3Stat.message_unseen; 48 lastPop3Stat.message_unseen = currentPop3Stat.message_unseen;
49 lastPop3Stat.message_recent = currentPop3Stat.message_recent; 49 lastPop3Stat.message_recent = currentPop3Stat.message_recent;
50 lastPop3Stat.message_count = currentPop3Stat.message_count; 50 lastPop3Stat.message_count = currentPop3Stat.message_count;
51} 51}
52 52
53void StatusMail::reset_status() 53void StatusMail::reset_status()
54{ 54{
55 lastPop3Stat = currentPop3Stat; 55 lastPop3Stat = currentPop3Stat;
56} 56}
57 57
58void StatusMail::check_current_stat(folderStat&targetStat) 58void StatusMail::check_current_stat(folderStat&targetStat)
59{ 59{
60 AbstractMail*it = 0; 60 AbstractMail*it = 0;
61 folderStat currentStat; 61 folderStat currentStat;
62 currentPop3Stat.message_recent = 0; 62 currentPop3Stat.message_recent = 0;
63 currentPop3Stat.message_count = 0; 63 currentPop3Stat.message_count = 0;
64 currentPop3Stat.message_unseen = 0; 64 currentPop3Stat.message_unseen = 0;
65 currentImapStat = currentPop3Stat; 65 currentImapStat = currentPop3Stat;
66 for ( it = connectionList.first(); it; it = connectionList.next() ) { 66 for ( it = connectionList.first(); it; it = connectionList.next() ) {
67 it->statusFolder(currentStat); 67 it->statusFolder(currentStat);
68 it->logout(); 68 it->logout();
69 if (it->getType() == MAILLIB::A_IMAP) { 69 if (it->getType() == MAILLIB::A_IMAP) {
70 currentImapStat.message_unseen+=currentStat.message_unseen; 70 currentImapStat.message_unseen+=currentStat.message_unseen;
71 currentImapStat.message_recent+=currentStat.message_recent; 71 currentImapStat.message_recent+=currentStat.message_recent;
72 currentImapStat.message_count+=currentStat.message_count; 72 currentImapStat.message_count+=currentStat.message_count;
73 } else if (it->getType() == MAILLIB::A_POP3) { 73 } else if (it->getType() == MAILLIB::A_POP3) {
74 currentPop3Stat.message_count+=currentStat.message_count; 74 currentPop3Stat.message_count+=currentStat.message_count;
75 qDebug("Pop3 count: %i",currentPop3Stat.message_count); 75 odebug << "Pop3 count: " << currentPop3Stat.message_count << "" << oendl;
76 } 76 }
77 } 77 }
78 qDebug("Pop3 last: %i",lastPop3Stat.message_count); 78 odebug << "Pop3 last: " << lastPop3Stat.message_count << "" << oendl;
79 if (currentPop3Stat.message_count > lastPop3Stat.message_count) { 79 if (currentPop3Stat.message_count > lastPop3Stat.message_count) {
80 currentPop3Stat.message_recent = currentPop3Stat.message_count - lastPop3Stat.message_count; 80 currentPop3Stat.message_recent = currentPop3Stat.message_count - lastPop3Stat.message_count;
81 currentPop3Stat.message_unseen = currentPop3Stat.message_recent; 81 currentPop3Stat.message_unseen = currentPop3Stat.message_recent;
82 } else { 82 } else {
83 lastPop3Stat.message_count = currentPop3Stat.message_count; 83 lastPop3Stat.message_count = currentPop3Stat.message_count;
84 currentPop3Stat.message_recent = currentPop3Stat.message_unseen = 0; 84 currentPop3Stat.message_recent = currentPop3Stat.message_unseen = 0;
85 } 85 }
86 targetStat = currentImapStat; 86 targetStat = currentImapStat;
87 targetStat.message_unseen+=currentPop3Stat.message_unseen; 87 targetStat.message_unseen+=currentPop3Stat.message_unseen;
88 targetStat.message_recent+=currentPop3Stat.message_recent; 88 targetStat.message_recent+=currentPop3Stat.message_recent;
89 targetStat.message_count+=currentPop3Stat.message_count; 89 targetStat.message_count+=currentPop3Stat.message_count;
90} 90}
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 @@
1#include "storemail.h" 1#include "storemail.h"
2#include "mailwrapper.h" 2#include "mailwrapper.h"
3#include "settings.h" 3#include "settings.h"
4#include "abstractmail.h" 4#include "abstractmail.h"
5 5
6#include <libetpan/libetpan.h> 6#include <libetpan/libetpan.h>
7 7
8#include <qstring.h> 8#include <qstring.h>
9 9
10#include <stdlib.h> 10#include <stdlib.h>
11 11
12using namespace Opie::Core; 12using namespace Opie::Core;
13Storemail::Storemail(Account*aAccount,const QString&aFolder) 13Storemail::Storemail(Account*aAccount,const QString&aFolder)
14 : Generatemail() 14 : Generatemail()
15{ 15{
16 wrapper = 0; 16 wrapper = 0;
17 m_Account = aAccount; 17 m_Account = aAccount;
18 m_tfolder = aFolder; 18 m_tfolder = aFolder;
19 wrapper = AbstractMail::getWrapper(m_Account); 19 wrapper = AbstractMail::getWrapper(m_Account);
20 if (wrapper) { 20 if (wrapper) {
21 wrapper->createMbox(m_tfolder); 21 wrapper->createMbox(m_tfolder);
22 } 22 }
23} 23}
24 24
25Storemail::Storemail(const QString&dir,const QString&aFolder) 25Storemail::Storemail(const QString&dir,const QString&aFolder)
26 : Generatemail() 26 : Generatemail()
27{ 27{
28 wrapper = 0; 28 wrapper = 0;
29 m_Account = 0; 29 m_Account = 0;
30 m_tfolder = aFolder; 30 m_tfolder = aFolder;
31 wrapper = AbstractMail::getWrapper(dir); 31 wrapper = AbstractMail::getWrapper(dir);
32 if (wrapper) { 32 if (wrapper) {
33 wrapper->createMbox(m_tfolder); 33 wrapper->createMbox(m_tfolder);
34 } 34 }
35} 35}
36 36
37Storemail::Storemail(const QString&aFolder) 37Storemail::Storemail(const QString&aFolder)
38 : Generatemail() 38 : Generatemail()
39{ 39{
40 wrapper = 0; 40 wrapper = 0;
41 m_Account = 0; 41 m_Account = 0;
42 m_tfolder = aFolder; 42 m_tfolder = aFolder;
43 wrapper = AbstractMail::getWrapper(AbstractMail::defaultLocalfolder()); 43 wrapper = AbstractMail::getWrapper(AbstractMail::defaultLocalfolder());
44 if (wrapper) { 44 if (wrapper) {
45 wrapper->createMbox(m_tfolder); 45 wrapper->createMbox(m_tfolder);
46 } 46 }
47} 47}
48 48
49Storemail::~Storemail() 49Storemail::~Storemail()
50{ 50{
51} 51}
52 52
53int Storemail::storeMail(const Opie::Core::OSmartPointer<Mail>&mail) 53int Storemail::storeMail(const Opie::Core::OSmartPointer<Mail>&mail)
54{ 54{
55 if (!wrapper) return 0; 55 if (!wrapper) return 0;
56 int ret = 1; 56 int ret = 1;
57 57
58 mailmime * mimeMail = 0; 58 mailmime * mimeMail = 0;
59 mimeMail = createMimeMail(mail ); 59 mimeMail = createMimeMail(mail );
60 if ( mimeMail == NULL ) { 60 if ( mimeMail == NULL ) {
61 qDebug( "storeMail: error creating mime mail" ); 61 odebug << "storeMail: error creating mime mail" << oendl;
62 return 0; 62 return 0;
63 } 63 }
64 char *data; 64 char *data;
65 size_t size; 65 size_t size;
66 data = 0; 66 data = 0;
67 67
68 mailmessage * msg = 0; 68 mailmessage * msg = 0;
69 msg = mime_message_init(mimeMail); 69 msg = mime_message_init(mimeMail);
70 mime_message_set_tmpdir(msg,getenv( "HOME" )); 70 mime_message_set_tmpdir(msg,getenv( "HOME" ));
71 int r = mailmessage_fetch(msg,&data,&size); 71 int r = mailmessage_fetch(msg,&data,&size);
72 mime_message_detach_mime(msg); 72 mime_message_detach_mime(msg);
73 mailmessage_free(msg); 73 mailmessage_free(msg);
74 msg = 0; 74 msg = 0;
75 if (r != MAIL_NO_ERROR || !data) { 75 if (r != MAIL_NO_ERROR || !data) {
76 qDebug("Error fetching mime..."); 76 odebug << "Error fetching mime..." << oendl;
77 ret = 0; 77 ret = 0;
78 } 78 }
79 79
80 if (ret) { 80 if (ret) {
81 wrapper->storeMessage(data,size,m_tfolder); 81 wrapper->storeMessage(data,size,m_tfolder);
82 } 82 }
83 83
84 if (data) { 84 if (data) {
85 free(data); 85 free(data);
86 } 86 }
87 if (mimeMail) { 87 if (mimeMail) {
88 mailmime_free( mimeMail ); 88 mailmime_free( mimeMail );
89 } 89 }
90 return ret; 90 return ret;
91} 91}
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 )
48 syncFolders->addTo( mailMenu ); 48 syncFolders->addTo( mailMenu );
49 */ 49 */
50 50
51 showFolders = new QAction( tr( "Show/Hide folders" ), ICON_SHOWFOLDERS, 51 showFolders = new QAction( tr( "Show/Hide folders" ), ICON_SHOWFOLDERS,
52 0, 0, this, 0, true ); 52 0, 0, this, 0, true );
53 showFolders->addTo( toolBar ); 53 showFolders->addTo( toolBar );
54 showFolders->addTo( mailMenu ); 54 showFolders->addTo( mailMenu );
55 showFolders->setOn( true ); 55 showFolders->setOn( true );
56 connect(showFolders, SIGNAL( toggled(bool) ), 56 connect(showFolders, SIGNAL( toggled(bool) ),
57 SLOT( slotShowFolders(bool) ) ); 57 SLOT( slotShowFolders(bool) ) );
58 58
59 /* 59 /*
60 searchMails = new QAction( tr( "Search mails" ), QIconSet( Resource::loadPixmap("find") ), 60 searchMails = new QAction( tr( "Search mails" ), QIconSet( Resource::loadPixmap("find") ),
61 0, 0, this ); 61 0, 0, this );
62 searchMails->addTo( toolBar ); 62 searchMails->addTo( toolBar );
63 searchMails->addTo( mailMenu ); 63 searchMails->addTo( mailMenu );
64 */ 64 */
65 65
66 deleteMails = new QAction(tr("Delete Mail"), QIconSet( Resource::loadPixmap("trash")), 0, 0, this); 66 deleteMails = new QAction(tr("Delete Mail"), QIconSet( Resource::loadPixmap("trash")), 0, 0, this);
67 deleteMails->addTo( toolBar ); 67 deleteMails->addTo( toolBar );
68 deleteMails->addTo( mailMenu ); 68 deleteMails->addTo( mailMenu );
69 connect( deleteMails, SIGNAL( activated() ), 69 connect( deleteMails, SIGNAL( activated() ),
70 SLOT( slotDeleteMail() ) ); 70 SLOT( slotDeleteMail() ) );
71 71
72 editSettings = new QAction( tr( "Edit settings" ), QIconSet( Resource::loadPixmap("SettingsIcon") ) , 72 editSettings = new QAction( tr( "Edit settings" ), QIconSet( Resource::loadPixmap("SettingsIcon") ) ,
73 0, 0, this ); 73 0, 0, this );
74 editSettings->addTo( settingsMenu ); 74 editSettings->addTo( settingsMenu );
75 connect( editSettings, SIGNAL( activated() ), 75 connect( editSettings, SIGNAL( activated() ),
76 SLOT( slotEditSettings() ) ); 76 SLOT( slotEditSettings() ) );
77 editAccounts = new QAction( tr( "Configure accounts" ), QIconSet( Resource::loadPixmap("mail/editaccounts") ) , 77 editAccounts = new QAction( tr( "Configure accounts" ), QIconSet( Resource::loadPixmap("mail/editaccounts") ) ,
78 0, 0, this ); 78 0, 0, this );
79 editAccounts->addTo( settingsMenu ); 79 editAccounts->addTo( settingsMenu );
80 80
81 //setCentralWidget( view ); 81 //setCentralWidget( view );
82 82
83 QVBox* wrapperBox = new QVBox( this ); 83 QVBox* wrapperBox = new QVBox( this );
84 setCentralWidget( wrapperBox ); 84 setCentralWidget( wrapperBox );
85 85
86 QWidget *view = new QWidget( wrapperBox ); 86 QWidget *view = new QWidget( wrapperBox );
87 87
88 layout = new QBoxLayout ( view, QBoxLayout::LeftToRight ); 88 layout = new QBoxLayout ( view, QBoxLayout::LeftToRight );
89 89
90 folderView = new AccountView( view ); 90 folderView = new AccountView( view );
91 folderView->header()->hide(); 91 folderView->header()->hide();
92 folderView->setRootIsDecorated( true ); 92 folderView->setRootIsDecorated( true );
93 folderView->addColumn( tr( "Mailbox" ) ); 93 folderView->addColumn( tr( "Mailbox" ) );
94 94
95 layout->addWidget( folderView ); 95 layout->addWidget( folderView );
96 96
97 mailView = new QListView( view ); 97 mailView = new QListView( view );
98 mailView->addColumn( tr( "" ) ); 98 mailView->addColumn( tr( "" ) );
99 mailView->addColumn( tr( "Subject" ),QListView::Manual ); 99 mailView->addColumn( tr( "Subject" ),QListView::Manual );
100 mailView->addColumn( tr( "Sender" ),QListView::Manual ); 100 mailView->addColumn( tr( "Sender" ),QListView::Manual );
101 mailView->addColumn( tr( "Size" ),QListView::Manual); 101 mailView->addColumn( tr( "Size" ),QListView::Manual);
102 mailView->addColumn( tr( "Date" )); 102 mailView->addColumn( tr( "Date" ));
103 mailView->setAllColumnsShowFocus(true); 103 mailView->setAllColumnsShowFocus(true);
104 mailView->setSorting(-1); 104 mailView->setSorting(-1);
105 105
106 statusWidget = new StatusWidget( wrapperBox ); 106 statusWidget = new StatusWidget( wrapperBox );
107 statusWidget->hide(); 107 statusWidget->hide();
108 108
109 layout->addWidget( mailView ); 109 layout->addWidget( mailView );
110 layout->setStretchFactor( folderView, 1 ); 110 layout->setStretchFactor( folderView, 1 );
111 layout->setStretchFactor( mailView, 2 ); 111 layout->setStretchFactor( mailView, 2 );
112 112
113 slotAdjustLayout(); 113 slotAdjustLayout();
114 114
115 QPEApplication::setStylusOperation( mailView->viewport(),QPEApplication::RightOnHold); 115 QPEApplication::setStylusOperation( mailView->viewport(),QPEApplication::RightOnHold);
116 QPEApplication::setStylusOperation( folderView->viewport(),QPEApplication::RightOnHold); 116 QPEApplication::setStylusOperation( folderView->viewport(),QPEApplication::RightOnHold);
117 117
118 connect( mailView, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),this, 118 connect( mailView, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),this,
119 SLOT( mailLeftClicked(int,QListViewItem*,const QPoint&,int) ) ); 119 SLOT( mailLeftClicked(int,QListViewItem*,const QPoint&,int) ) );
120 connect( mailView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),this, 120 connect( mailView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),this,
121 SLOT( mailHold(int,QListViewItem*,const QPoint&,int) ) ); 121 SLOT( mailHold(int,QListViewItem*,const QPoint&,int) ) );
122 connect(folderView, SIGNAL(refreshMailview(const QValueList<RecMailP>&)), 122 connect(folderView, SIGNAL(refreshMailview(const QValueList<RecMailP>&)),
123 this,SLOT(refreshMailView(const QValueList<RecMailP>&))); 123 this,SLOT(refreshMailView(const QValueList<RecMailP>&)));
124 connect( composeMail, SIGNAL( activated() ), SLOT( slotComposeMail() ) ); 124 connect( composeMail, SIGNAL( activated() ), SLOT( slotComposeMail() ) );
125 connect( sendQueued, SIGNAL( activated() ), SLOT( slotSendQueued() ) ); 125 connect( sendQueued, SIGNAL( activated() ), SLOT( slotSendQueued() ) );
126// connect( searchMails, SIGNAL( activated() ), SLOT( slotSearchMails() ) ); 126// connect( searchMails, SIGNAL( activated() ), SLOT( slotSearchMails() ) );
127 connect( editAccounts, SIGNAL( activated() ), SLOT( slotEditAccounts() ) ); 127 connect( editAccounts, SIGNAL( activated() ), SLOT( slotEditAccounts() ) );
128 // Added by Stefan Eilers to allow starting by addressbook.. 128 // Added by Stefan Eilers to allow starting by addressbook..
129 // copied from old mail2 129 // copied from old mail2
130#if !defined(QT_NO_COP) 130#if !defined(QT_NO_COP)
131 connect( qApp, SIGNAL( appMessage(const QCString&,const QByteArray&) ), 131 connect( qApp, SIGNAL( appMessage(const QCString&,const QByteArray&) ),
132 this, SLOT( appMessage(const QCString&,const QByteArray&) ) ); 132 this, SLOT( appMessage(const QCString&,const QByteArray&) ) );
133#endif 133#endif
134 134
135 QTimer::singleShot( 1000, this, SLOT( slotAdjustColumns() ) ); 135 QTimer::singleShot( 1000, this, SLOT( slotAdjustColumns() ) );
136} 136}
137 137
138MainWindow::~MainWindow() 138MainWindow::~MainWindow()
139{ 139{
140} 140}
141 141
142void MainWindow::appMessage(const QCString &, const QByteArray &) 142void MainWindow::appMessage(const QCString &, const QByteArray &)
143{ 143{
144 qDebug("appMessage not reached"); 144 odebug << "appMessage not reached" << oendl;
145} 145}
146 146
147void MainWindow::slotAdjustLayout() { 147void MainWindow::slotAdjustLayout() {
148 148
149 QWidget *d = QApplication::desktop(); 149 QWidget *d = QApplication::desktop();
150 150
151 if ( d->width() < d->height() ) { 151 if ( d->width() < d->height() ) {
152 layout->setDirection( QBoxLayout::TopToBottom ); 152 layout->setDirection( QBoxLayout::TopToBottom );
153 } else { 153 } else {
154 layout->setDirection( QBoxLayout::LeftToRight ); 154 layout->setDirection( QBoxLayout::LeftToRight );
155 } 155 }
156} 156}
157 157
158void MainWindow::slotAdjustColumns() 158void MainWindow::slotAdjustColumns()
159{ 159{
160 bool hidden = folderView->isHidden(); 160 bool hidden = folderView->isHidden();
161 if ( hidden ) folderView->show(); 161 if ( hidden ) folderView->show();
162 folderView->setColumnWidth( 0, folderView->visibleWidth() ); 162 folderView->setColumnWidth( 0, folderView->visibleWidth() );
163 if ( hidden ) folderView->hide(); 163 if ( hidden ) folderView->hide();
164 164
165 mailView->setColumnWidth( 0, 10 ); 165 mailView->setColumnWidth( 0, 10 );
166 mailView->setColumnWidth( 1, mailView->visibleWidth() - 130 ); 166 mailView->setColumnWidth( 1, mailView->visibleWidth() - 130 );
167 mailView->setColumnWidth( 2, 80 ); 167 mailView->setColumnWidth( 2, 80 );
168 mailView->setColumnWidth( 3, 50 ); 168 mailView->setColumnWidth( 3, 50 );
169 mailView->setColumnWidth( 4, 50 ); 169 mailView->setColumnWidth( 4, 50 );
170} 170}
171 171
172void MainWindow::slotEditSettings() 172void MainWindow::slotEditSettings()
173{ 173{
174} 174}
175 175
176void MainWindow::slotShowFolders( bool ) 176void MainWindow::slotShowFolders( bool )
177{ 177{
178 qDebug( "slotShowFolders not reached" ); 178 odebug << "slotShowFolders not reached" << oendl;
179} 179}
180 180
181void MainWindow::refreshMailView(const QValueList<RecMailP>&) 181void MainWindow::refreshMailView(const QValueList<RecMailP>&)
182{ 182{
183 qDebug( "refreshMailView not reached" ); 183 odebug << "refreshMailView not reached" << oendl;
184} 184}
185 185
186void MainWindow::mailLeftClicked(int, QListViewItem *,const QPoint&,int ) 186void MainWindow::mailLeftClicked(int, QListViewItem *,const QPoint&,int )
187{ 187{
188 qDebug( "mailLeftClicked not reached" ); 188 odebug << "mailLeftClicked not reached" << oendl;
189} 189}
190 190
191void MainWindow::displayMail() 191void MainWindow::displayMail()
192{ 192{
193 qDebug("displayMail not reached"); 193 odebug << "displayMail not reached" << oendl;
194} 194}
195 195
196void MainWindow::slotDeleteMail() 196void MainWindow::slotDeleteMail()
197{ 197{
198 qDebug("deleteMail not reached"); 198 odebug << "deleteMail not reached" << oendl;
199} 199}
200 200
201void MainWindow::mailHold(int, QListViewItem *,const QPoint&,int ) 201void MainWindow::mailHold(int, QListViewItem *,const QPoint&,int )
202{ 202{
203 qDebug("mailHold not reached"); 203 odebug << "mailHold not reached" << oendl;
204} 204}
205 205
206void MainWindow::slotSendQueued() 206void MainWindow::slotSendQueued()
207{ 207{
208} 208}
209 209
210void MainWindow::slotEditAccounts() 210void MainWindow::slotEditAccounts()
211{ 211{
212} 212}
213 213
214void MainWindow::slotComposeMail() 214void MainWindow::slotComposeMail()
215{ 215{
216} 216}
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 @@
1#include "nntpgroups.h" 1#include "nntpgroups.h"
2 2
3#include <libmailwrapper/settings.h> 3#include <libmailwrapper/settings.h>
4 4
5#include <qlistview.h> 5#include <qlistview.h>
6#include <qlineedit.h> 6#include <qlineedit.h>
7 7
8NNTPGroups::NNTPGroups(NNTPaccount *account, QWidget* parent, const char* name, WFlags fl) 8NNTPGroups::NNTPGroups(NNTPaccount *account, QWidget* parent, const char* name, WFlags fl)
9 : NNTPGroupsUI(parent,name,fl),subscribedGroups() 9 : NNTPGroupsUI(parent,name,fl),subscribedGroups()
10{ 10{
11 m_Account = account; 11 m_Account = account;
12 fillGroups(); 12 fillGroups();
13} 13}
14 14
15NNTPGroups::~NNTPGroups() 15NNTPGroups::~NNTPGroups()
16{ 16{
17 17
18} 18}
19 19
20void NNTPGroups::slotGetNG() 20void NNTPGroups::slotGetNG()
21{ 21{
22 if (!m_Account) return; 22 if (!m_Account) return;
23 GroupListView->clear(); 23 GroupListView->clear();
24 NNTPwrapper tmp( m_Account ); 24 NNTPwrapper tmp( m_Account );
25 QString filter = Groupfilteredit->text(); 25 QString filter = Groupfilteredit->text();
26 QStringList list = tmp.listAllNewsgroups(filter); 26 QStringList list = tmp.listAllNewsgroups(filter);
27 subscribedGroupsNotListed = subscribedGroups; 27 subscribedGroupsNotListed = subscribedGroups;
28 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { 28 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
29 QCheckListItem *item; 29 QCheckListItem *item;
30 item = new QCheckListItem( GroupListView, (*it), QCheckListItem::CheckBox ); 30 item = new QCheckListItem( GroupListView, (*it), QCheckListItem::CheckBox );
31 if ( subscribedGroups.contains( (*it) ) >= 1 ) { 31 if ( subscribedGroups.contains( (*it) ) >= 1 ) {
32 item->setOn( true ); 32 item->setOn( true );
33 subscribedGroupsNotListed.remove((*it)); 33 subscribedGroupsNotListed.remove((*it));
34 } 34 }
35 } 35 }
36} 36}
37 37
38void NNTPGroups::fillGroups() 38void NNTPGroups::fillGroups()
39{ 39{
40 if (!m_Account) return; 40 if (!m_Account) return;
41 subscribedGroups = m_Account->getGroups(); 41 subscribedGroups = m_Account->getGroups();
42 for ( QStringList::Iterator it = subscribedGroups.begin(); it != subscribedGroups.end(); ++it ) { 42 for ( QStringList::Iterator it = subscribedGroups.begin(); it != subscribedGroups.end(); ++it ) {
43 QCheckListItem *item; 43 QCheckListItem *item;
44 item = new QCheckListItem( GroupListView, (*it), QCheckListItem::CheckBox ); 44 item = new QCheckListItem( GroupListView, (*it), QCheckListItem::CheckBox );
45 item->setOn( true ); 45 item->setOn( true );
46 } 46 }
47} 47}
48 48
49void NNTPGroups::storeValues() 49void NNTPGroups::storeValues()
50{ 50{
51 if (!m_Account) return; 51 if (!m_Account) return;
52 QListViewItemIterator list_it( GroupListView ); 52 QListViewItemIterator list_it( GroupListView );
53 subscribedGroups.clear(); 53 subscribedGroups.clear();
54 for ( ; list_it.current(); ++list_it ) { 54 for ( ; list_it.current(); ++list_it ) {
55 if ( ( (QCheckListItem*)list_it.current() )->isOn() ) { 55 if ( ( (QCheckListItem*)list_it.current() )->isOn() ) {
56 qDebug(list_it.current()->text(0) ); 56 odebug << list_it.current()->text(0) << oendl;
57 subscribedGroups.append( list_it.current()->text(0) ); 57 subscribedGroups.append( list_it.current()->text(0) );
58 } 58 }
59 } 59 }
60 subscribedGroups+=subscribedGroupsNotListed; 60 subscribedGroups+=subscribedGroupsNotListed;
61 m_Account->setGroups( subscribedGroups ); 61 m_Account->setGroups( subscribedGroups );
62} 62}
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 @@
1 1
2#include "settingsdialog.h" 2#include "settingsdialog.h"
3#include "opiemail.h" 3#include "opiemail.h"
4#include "editaccounts.h" 4#include "editaccounts.h"
5#include "composemail.h" 5#include "composemail.h"
6#include "mailistviewitem.h" 6#include "mailistviewitem.h"
7#include "viewmail.h" 7#include "viewmail.h"
8#include "selectstore.h" 8#include "selectstore.h"
9#include "selectsmtp.h" 9#include "selectsmtp.h"
10 10
11/* OPIE */ 11/* OPIE */
12#include <libmailwrapper/smtpwrapper.h> 12#include <libmailwrapper/smtpwrapper.h>
13#include <libmailwrapper/mailtypes.h> 13#include <libmailwrapper/mailtypes.h>
14#include <libmailwrapper/abstractmail.h> 14#include <libmailwrapper/abstractmail.h>
15#include <qpe/resource.h> 15#include <qpe/resource.h>
16#include <qpe/qpeapplication.h> 16#include <qpe/qpeapplication.h>
17 17
18/* QT */ 18/* QT */
19 19
20OpieMail::OpieMail( QWidget *parent, const char *name, WFlags flags ) 20OpieMail::OpieMail( QWidget *parent, const char *name, WFlags flags )
21 : MainWindow( parent, name, WStyle_ContextHelp ) 21 : MainWindow( parent, name, WStyle_ContextHelp )
22{ 22{
23 settings = new Settings(); 23 settings = new Settings();
24 24
25 folderView->populate( settings->getAccounts() ); 25 folderView->populate( settings->getAccounts() );
26} 26}
27 27
28OpieMail::~OpieMail() 28OpieMail::~OpieMail()
29{ 29{
30 if (settings) delete settings; 30 if (settings) delete settings;
31} 31}
32 32
33void OpieMail::appMessage(const QCString &msg, const QByteArray &data) 33void OpieMail::appMessage(const QCString &msg, const QByteArray &data)
34{ 34{
35 // copied from old mail2 35 // copied from old mail2
36 if (msg == "writeMail(QString,QString)") 36 if (msg == "writeMail(QString,QString)")
37 { 37 {
38 QDataStream stream(data,IO_ReadOnly); 38 QDataStream stream(data,IO_ReadOnly);
39 QString name, email; 39 QString name, email;
40 stream >> name >> email; 40 stream >> name >> email;
41 // removing the whitespaces at beginning and end is needed! 41 // removing the whitespaces at beginning and end is needed!
42 slotwriteMail(name.stripWhiteSpace(),email.stripWhiteSpace()); 42 slotwriteMail(name.stripWhiteSpace(),email.stripWhiteSpace());
43 } 43 }
44 else if (msg == "newMail()") 44 else if (msg == "newMail()")
45 { 45 {
46 slotComposeMail(); 46 slotComposeMail();
47 } 47 }
48} 48}
49 49
50void OpieMail::slotwriteMail(const QString&name,const QString&email) 50void OpieMail::slotwriteMail(const QString&name,const QString&email)
51{ 51{
52 ComposeMail compose( settings, this, 0, true , WStyle_ContextHelp ); 52 ComposeMail compose( settings, this, 0, true , WStyle_ContextHelp );
53 if (!email.isEmpty()) 53 if (!email.isEmpty())
54 { 54 {
55 if (!name.isEmpty()) 55 if (!name.isEmpty())
56 { 56 {
57 compose.setTo("\"" + name + "\"" + " " + "<"+ email + ">"); 57 compose.setTo("\"" + name + "\"" + " " + "<"+ email + ">");
58 } 58 }
59 else 59 else
60 { 60 {
61 compose.setTo(email); 61 compose.setTo(email);
62 } 62 }
63 } 63 }
64 compose.slotAdjustColumns(); 64 compose.slotAdjustColumns();
65 QPEApplication::execDialog( &compose ); 65 QPEApplication::execDialog( &compose );
66} 66}
67 67
68void OpieMail::slotComposeMail() 68void OpieMail::slotComposeMail()
69{ 69{
70 qDebug( "Compose Mail" ); 70 odebug << "Compose Mail" << oendl;
71 slotwriteMail(0l,0l); 71 slotwriteMail(0l,0l);
72} 72}
73 73
74void OpieMail::slotSendQueued() 74void OpieMail::slotSendQueued()
75{ 75{
76 qDebug( "Send Queued" ); 76 odebug << "Send Queued" << oendl;
77 SMTPaccount *smtp = 0; 77 SMTPaccount *smtp = 0;
78 78
79 QList<Account> list = settings->getAccounts(); 79 QList<Account> list = settings->getAccounts();
80 QList<SMTPaccount> smtpList; 80 QList<SMTPaccount> smtpList;
81 smtpList.setAutoDelete(false); 81 smtpList.setAutoDelete(false);
82 Account *it; 82 Account *it;
83 for ( it = list.first(); it; it = list.next() ) 83 for ( it = list.first(); it; it = list.next() )
84 { 84 {
85 if ( it->getType() == MAILLIB::A_SMTP ) 85 if ( it->getType() == MAILLIB::A_SMTP )
86 { 86 {
87 smtp = static_cast<SMTPaccount *>(it); 87 smtp = static_cast<SMTPaccount *>(it);
88 smtpList.append(smtp); 88 smtpList.append(smtp);
89 } 89 }
90 } 90 }
91 if (smtpList.count()==0) 91 if (smtpList.count()==0)
92 { 92 {
93 QMessageBox::information(0,tr("Info"),tr("Define a smtp account first")); 93 QMessageBox::information(0,tr("Info"),tr("Define a smtp account first"));
94 return; 94 return;
95 } 95 }
96 if (smtpList.count()==1) 96 if (smtpList.count()==1)
97 { 97 {
98 smtp = smtpList.at(0); 98 smtp = smtpList.at(0);
99 } 99 }
100 else 100 else
101 { 101 {
102 smtp = 0; 102 smtp = 0;
103 selectsmtp selsmtp; 103 selectsmtp selsmtp;
104 selsmtp.setSelectionlist(&smtpList); 104 selsmtp.setSelectionlist(&smtpList);
105 if ( QPEApplication::execDialog( &selsmtp ) == QDialog::Accepted ) 105 if ( QPEApplication::execDialog( &selsmtp ) == QDialog::Accepted )
106 { 106 {
107 smtp = selsmtp.selected_smtp(); 107 smtp = selsmtp.selected_smtp();
108 } 108 }
109 } 109 }
110 if (smtp) 110 if (smtp)
111 { 111 {
112 SMTPwrapper * wrap = new SMTPwrapper(smtp); 112 SMTPwrapper * wrap = new SMTPwrapper(smtp);
113 if ( wrap->flushOutbox() ) 113 if ( wrap->flushOutbox() )
114 { 114 {
115 QMessageBox::information(0,tr("Info"),tr("Mail queue flushed")); 115 QMessageBox::information(0,tr("Info"),tr("Mail queue flushed"));
116 } 116 }
117 delete wrap; 117 delete wrap;
118 } 118 }
119} 119}
120 120
121void OpieMail::slotSearchMails() 121void OpieMail::slotSearchMails()
122{ 122{
123 qDebug( "Search Mails" ); 123 odebug << "Search Mails" << oendl;
124} 124}
125 125
126void OpieMail::slotEditSettings() 126void OpieMail::slotEditSettings()
127{ 127{
128 SettingsDialog settingsDialog( this, 0, true, WStyle_ContextHelp ); 128 SettingsDialog settingsDialog( this, 0, true, WStyle_ContextHelp );
129 QPEApplication::execDialog( &settingsDialog ); 129 QPEApplication::execDialog( &settingsDialog );
130} 130}
131 131
132void OpieMail::slotEditAccounts() 132void OpieMail::slotEditAccounts()
133{ 133{
134 qDebug( "Edit Accounts" ); 134 odebug << "Edit Accounts" << oendl;
135 EditAccounts eaDialog( settings, this, 0, true, WStyle_ContextHelp ); 135 EditAccounts eaDialog( settings, this, 0, true, WStyle_ContextHelp );
136 eaDialog.slotAdjustColumns(); 136 eaDialog.slotAdjustColumns();
137 QPEApplication::execDialog( &eaDialog ); 137 QPEApplication::execDialog( &eaDialog );
138 if ( settings ) delete settings; 138 if ( settings ) delete settings;
139 settings = new Settings(); 139 settings = new Settings();
140 140
141 folderView->populate( settings->getAccounts() ); 141 folderView->populate( settings->getAccounts() );
142} 142}
143 143
144void OpieMail::displayMail() 144void OpieMail::displayMail()
145{ 145{
146 QListViewItem*item = mailView->currentItem(); 146 QListViewItem*item = mailView->currentItem();
147 if (!item) return; 147 if (!item) return;
148 RecMailP mail = ((MailListViewItem*)item)->data(); 148 RecMailP mail = ((MailListViewItem*)item)->data();
149 RecBodyP body = folderView->fetchBody(mail); 149 RecBodyP body = folderView->fetchBody(mail);
150 ViewMail readMail( this,"", Qt::WType_Modal | WStyle_ContextHelp ); 150 ViewMail readMail( this,"", Qt::WType_Modal | WStyle_ContextHelp );
151 readMail.setBody( body ); 151 readMail.setBody( body );
152 readMail.setMail( mail ); 152 readMail.setMail( mail );
153 readMail.showMaximized(); 153 readMail.showMaximized();
154 readMail.exec(); 154 readMail.exec();
155 155
156 if ( readMail.deleted ) 156 if ( readMail.deleted )
157 { 157 {
158 folderView->refreshCurrent(); 158 folderView->refreshCurrent();
159 } 159 }
160 else 160 else
161 { 161 {
162 ( (MailListViewItem*)item )->setPixmap( 0, Resource::loadPixmap( "" ) ); 162 ( (MailListViewItem*)item )->setPixmap( 0, Resource::loadPixmap( "" ) );
163 } 163 }
164} 164}
165 165
166void OpieMail::slotDeleteMail() 166void OpieMail::slotDeleteMail()
167{ 167{
168 if (!mailView->currentItem()) return; 168 if (!mailView->currentItem()) return;
169 RecMailP mail = ((MailListViewItem*)mailView->currentItem() )->data(); 169 RecMailP mail = ((MailListViewItem*)mailView->currentItem() )->data();
170 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 ) 170 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 )
171 { 171 {
172 mail->Wrapper()->deleteMail( mail ); 172 mail->Wrapper()->deleteMail( mail );
173 folderView->refreshCurrent(); 173 folderView->refreshCurrent();
174 } 174 }
175} 175}
176 176
177void OpieMail::mailHold(int button, QListViewItem *item,const QPoint&,int ) 177void OpieMail::mailHold(int button, QListViewItem *item,const QPoint&,int )
178{ 178{
179 if (!mailView->currentItem()) return; 179 if (!mailView->currentItem()) return;
180 MAILLIB::ATYPE mailtype = ((MailListViewItem*)mailView->currentItem() )->wrapperType(); 180 MAILLIB::ATYPE mailtype = ((MailListViewItem*)mailView->currentItem() )->wrapperType();
181 /* just the RIGHT button - or hold on pda */ 181 /* just the RIGHT button - or hold on pda */
182 if (button!=2) {return;} 182 if (button!=2) {return;}
183 qDebug("Event right/hold"); 183 odebug << "Event right/hold" << oendl;
184 if (!item) return; 184 if (!item) return;
185 QPopupMenu *m = new QPopupMenu(0); 185 QPopupMenu *m = new QPopupMenu(0);
186 if (m) 186 if (m)
187 { 187 {
188 if (mailtype==MAILLIB::A_NNTP) { 188 if (mailtype==MAILLIB::A_NNTP) {
189 m->insertItem(tr("Read this posting"),this,SLOT(displayMail())); 189 m->insertItem(tr("Read this posting"),this,SLOT(displayMail()));
190// m->insertItem(tr("Copy this posting"),this,SLOT(slotMoveCopyMail())); 190// m->insertItem(tr("Copy this posting"),this,SLOT(slotMoveCopyMail()));
191 } else { 191 } else {
192 if (folderView->currentisDraft()) { 192 if (folderView->currentisDraft()) {
193 m->insertItem(tr("Edit this mail"),this,SLOT(reEditMail())); 193 m->insertItem(tr("Edit this mail"),this,SLOT(reEditMail()));
194 } 194 }
195 m->insertItem(tr("Read this mail"),this,SLOT(displayMail())); 195 m->insertItem(tr("Read this mail"),this,SLOT(displayMail()));
196 m->insertItem(tr("Delete this mail"),this,SLOT(slotDeleteMail())); 196 m->insertItem(tr("Delete this mail"),this,SLOT(slotDeleteMail()));
197 m->insertItem(tr("Copy/Move this mail"),this,SLOT(slotMoveCopyMail())); 197 m->insertItem(tr("Copy/Move this mail"),this,SLOT(slotMoveCopyMail()));
198 } 198 }
199 m->setFocus(); 199 m->setFocus();
200 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) ); 200 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) );
201 delete m; 201 delete m;
202 } 202 }
203} 203}
204 204
205void OpieMail::slotShowFolders( bool show ) 205void OpieMail::slotShowFolders( bool show )
206{ 206{
207 qDebug( "Show Folders" ); 207 odebug << "Show Folders" << oendl;
208 if ( show && folderView->isHidden() ) 208 if ( show && folderView->isHidden() )
209 { 209 {
210 qDebug( "-> showing" ); 210 odebug << "-> showing" << oendl;
211 folderView->show(); 211 folderView->show();
212 } 212 }
213 else if ( !show && !folderView->isHidden() ) 213 else if ( !show && !folderView->isHidden() )
214 { 214 {
215 qDebug( "-> hiding" ); 215 odebug << "-> hiding" << oendl;
216 folderView->hide(); 216 folderView->hide();
217 } 217 }
218} 218}
219 219
220void OpieMail::refreshMailView(const QValueList<RecMailP>&list) 220void OpieMail::refreshMailView(const QValueList<RecMailP>&list)
221{ 221{
222 MailListViewItem*item = 0; 222 MailListViewItem*item = 0;
223 mailView->clear(); 223 mailView->clear();
224 224
225 QValueList<RecMailP>::ConstIterator it; 225 QValueList<RecMailP>::ConstIterator it;
226 for (it = list.begin(); it != list.end();++it) 226 for (it = list.begin(); it != list.end();++it)
227 { 227 {
228 item = new MailListViewItem(mailView,item); 228 item = new MailListViewItem(mailView,item);
229 item->storeData((*it)); 229 item->storeData((*it));
230 item->showEntry(); 230 item->showEntry();
231 } 231 }
232} 232}
233 233
234void OpieMail::mailLeftClicked(int button, QListViewItem *item,const QPoint&,int ) 234void OpieMail::mailLeftClicked(int button, QListViewItem *item,const QPoint&,int )
235{ 235{
236 /* just LEFT button - or tap with stylus on pda */ 236 /* just LEFT button - or tap with stylus on pda */
237 if (button!=1) return; 237 if (button!=1) return;
238 if (!item) return; 238 if (!item) return;
239 if (folderView->currentisDraft()) { 239 if (folderView->currentisDraft()) {
240 reEditMail(); 240 reEditMail();
241 } else { 241 } else {
242 displayMail(); 242 displayMail();
243 } 243 }
244} 244}
245 245
246void OpieMail::slotMoveCopyMail() 246void OpieMail::slotMoveCopyMail()
247{ 247{
248 if (!mailView->currentItem()) return; 248 if (!mailView->currentItem()) return;
249 RecMailP mail = ((MailListViewItem*)mailView->currentItem() )->data(); 249 RecMailP mail = ((MailListViewItem*)mailView->currentItem() )->data();
250 AbstractMail*targetMail = 0; 250 AbstractMail*targetMail = 0;
251 QString targetFolder = ""; 251 QString targetFolder = "";
252 Selectstore sels; 252 Selectstore sels;
253 folderView->setupFolderselect(&sels); 253 folderView->setupFolderselect(&sels);
254 if (!sels.exec()) return; 254 if (!sels.exec()) return;
255 targetMail = sels.currentMail(); 255 targetMail = sels.currentMail();
256 targetFolder = sels.currentFolder(); 256 targetFolder = sels.currentFolder();
257 if ( (mail->Wrapper()==targetMail && mail->getMbox()==targetFolder) || 257 if ( (mail->Wrapper()==targetMail && mail->getMbox()==targetFolder) ||
258 targetFolder.isEmpty()) 258 targetFolder.isEmpty())
259 { 259 {
260 return; 260 return;
261 } 261 }
262 if (sels.newFolder() && !targetMail->createMbox(targetFolder)) 262 if (sels.newFolder() && !targetMail->createMbox(targetFolder))
263 { 263 {
264 QMessageBox::critical(0,tr("Error creating new Folder"), 264 QMessageBox::critical(0,tr("Error creating new Folder"),
265 tr("<center>Error while creating<br>new folder - breaking.</center>")); 265 tr("<center>Error while creating<br>new folder - breaking.</center>"));
266 return; 266 return;
267 } 267 }
268 mail->Wrapper()->mvcpMail(mail,targetFolder,targetMail,sels.moveMails()); 268 mail->Wrapper()->mvcpMail(mail,targetFolder,targetMail,sels.moveMails());
269 folderView->refreshCurrent(); 269 folderView->refreshCurrent();
270} 270}
271 271
272void OpieMail::reEditMail() 272void OpieMail::reEditMail()
273{ 273{
274 if (!mailView->currentItem()) return; 274 if (!mailView->currentItem()) return;
275 275
276 ComposeMail compose( settings, this, 0, true , WStyle_ContextHelp ); 276 ComposeMail compose( settings, this, 0, true , WStyle_ContextHelp );
277 compose.reEditMail(((MailListViewItem*)mailView->currentItem() )->data()); 277 compose.reEditMail(((MailListViewItem*)mailView->currentItem() )->data());
278 compose.slotAdjustColumns(); 278 compose.slotAdjustColumns();
279 QPEApplication::execDialog( &compose ); 279 QPEApplication::execDialog( &compose );
280} 280}
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 @@
11#include <libmailwrapper/settings.h> 11#include <libmailwrapper/settings.h>
12 12
13#include "mailapplet.h" 13#include "mailapplet.h"
14 14
15using namespace Opie::Core; 15using namespace Opie::Core;
16 16
17MailApplet::MailApplet( QWidget *parent ) 17MailApplet::MailApplet( QWidget *parent )
18: QWidget( parent ) { 18: QWidget( parent ) {
19 19
20 m_config = new Config( "mail" ); 20 m_config = new Config( "mail" );
21 m_config->setGroup( "Applet" ); 21 m_config->setGroup( "Applet" );
22 22
23 setFixedWidth( AppLnk::smallIconSize() ); 23 setFixedWidth( AppLnk::smallIconSize() );
24 setFixedHeight( AppLnk::smallIconSize() ); 24 setFixedHeight( AppLnk::smallIconSize() );
25 25
26 hide(); 26 hide();
27 27
28 m_newMails = 0; 28 m_newMails = 0;
29 m_statusMail = 0l; 29 m_statusMail = 0l;
30 30
31 if ( !m_config->readBoolEntry( "Disabled", false ) ) { 31 if ( !m_config->readBoolEntry( "Disabled", false ) ) {
32 // delay 5 sec until the whole mail backend gets started .-) 32 // delay 5 sec until the whole mail backend gets started .-)
33 QTimer::singleShot( 5000, this, SLOT( startup() ) ); 33 QTimer::singleShot( 5000, this, SLOT( startup() ) );
34 } 34 }
35 repaint( true ); 35 repaint( true );
36} 36}
37 37
38 38
39MailApplet::~MailApplet() { 39MailApplet::~MailApplet() {
40 if ( m_statusMail ) 40 if ( m_statusMail )
41 delete m_statusMail; 41 delete m_statusMail;
42 if ( m_config ) 42 if ( m_config )
43 delete m_config; 43 delete m_config;
44} 44}
45 45
46void MailApplet::paintEvent( QPaintEvent* ) { 46void MailApplet::paintEvent( QPaintEvent* ) {
47 QPainter p( this ); 47 QPainter p( this );
48 p.drawPixmap( 0, 0, Resource::loadPixmap( "mail/inbox" ) ); 48 p.drawPixmap( 0, 0, Resource::loadPixmap( "mail/inbox" ) );
49 QFont f( "vera", AppLnk::smallIconSize() ); 49 QFont f( "vera", AppLnk::smallIconSize() );
50 QFontMetrics fm( f ); 50 QFontMetrics fm( f );
51 p.setFont( f ); 51 p.setFont( f );
52 p.setPen( Qt::blue ); 52 p.setPen( Qt::blue );
53 p.drawText( AppLnk::smallIconSize()/3, AppLnk::smallIconSize() - 2, QString::number( m_newMails ) ); 53 p.drawText( AppLnk::smallIconSize()/3, AppLnk::smallIconSize() - 2, QString::number( m_newMails ) );
54 return; 54 return;
55 55
56} 56}
57 57
58void MailApplet::mouseReleaseEvent( QMouseEvent* e ) { 58void MailApplet::mouseReleaseEvent( QMouseEvent* e ) {
59 slotClicked(); 59 slotClicked();
60} 60}
61 61
62void MailApplet::slotClicked() { 62void MailApplet::slotClicked() {
63 QCopEnvelope e( "QPE/System", "execute(QString)" ); 63 QCopEnvelope e( "QPE/System", "execute(QString)" );
64 e << QString( "opiemail" ); 64 e << QString( "opiemail" );
65 65
66 ODevice *device = ODevice::inst(); 66 ODevice *device = ODevice::inst();
67 if ( !device-> ledList().isEmpty() ) { 67 if ( !device-> ledList().isEmpty() ) {
68 OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0]; 68 OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0];
69 69
70 device->setLedState( led, Led_Off ); 70 device->setLedState( led, Led_Off );
71 } 71 }
72 72
73 if (m_statusMail) 73 if (m_statusMail)
74 m_statusMail->reset_status(); 74 m_statusMail->reset_status();
75 75
76 hide(); 76 hide();
77} 77}
78 78
79void MailApplet::startup() { 79void MailApplet::startup() {
80 Settings *settings = new Settings(); 80 Settings *settings = new Settings();
81 QList<Account> ma = settings->getAccounts(); 81 QList<Account> ma = settings->getAccounts();
82 m_statusMail = new StatusMail( ma ); 82 m_statusMail = new StatusMail( ma );
83 delete settings; 83 delete settings;
84 84
85 m_intervalMs = m_config->readNumEntry( "CheckEvery", 5 ) * 60000; 85 m_intervalMs = m_config->readNumEntry( "CheckEvery", 5 ) * 60000;
86 m_intervalTimer = new QTimer(); 86 m_intervalTimer = new QTimer();
87 m_intervalTimer->start( m_intervalMs ); 87 m_intervalTimer->start( m_intervalMs );
88 connect( m_intervalTimer, SIGNAL( timeout() ), this, SLOT( slotCheck() ) ); 88 connect( m_intervalTimer, SIGNAL( timeout() ), this, SLOT( slotCheck() ) );
89} 89}
90 90
91void MailApplet::slotCheck() { 91void MailApplet::slotCheck() {
92 // Check wether the check interval has been changed. 92 // Check wether the check interval has been changed.
93 int newIntervalMs = m_config->readNumEntry( "CheckEvery", 5 ) * 60000; 93 int newIntervalMs = m_config->readNumEntry( "CheckEvery", 5 ) * 60000;
94 if ( newIntervalMs != m_intervalMs ) { 94 if ( newIntervalMs != m_intervalMs ) {
95 m_intervalTimer->changeInterval( newIntervalMs ); 95 m_intervalTimer->changeInterval( newIntervalMs );
96 m_intervalMs = newIntervalMs; 96 m_intervalMs = newIntervalMs;
97 } 97 }
98 98
99 if (m_statusMail == 0) { 99 if (m_statusMail == 0) {
100 return; 100 return;
101 } 101 }
102 102
103 folderStat stat; 103 folderStat stat;
104 m_statusMail->check_current_stat( stat ); 104 m_statusMail->check_current_stat( stat );
105 int newMailsOld = m_newMails; 105 int newMailsOld = m_newMails;
106 m_newMails = stat.message_unseen; 106 m_newMails = stat.message_unseen;
107 qDebug( QString( "test %1" ).arg( m_newMails ) ); 107 odebug << QString( "test %1" ).arg( m_newMails ) << oendl;
108 if ( m_newMails > 0 && newMailsOld != m_newMails ) { 108 if ( m_newMails > 0 && newMailsOld != m_newMails ) {
109 ODevice *device = ODevice::inst(); 109 ODevice *device = ODevice::inst();
110 if ( isHidden() ) 110 if ( isHidden() )
111 show(); 111 show();
112 if ( m_config->readBoolEntry( "BlinkLed", true ) ) { 112 if ( m_config->readBoolEntry( "BlinkLed", true ) ) {
113 if ( !device->ledList().isEmpty() ) { 113 if ( !device->ledList().isEmpty() ) {
114 OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0]; 114 OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0];
115 device->setLedState( led, device->ledStateList( led ).contains( Led_BlinkSlow ) ? Led_BlinkSlow : Led_On ); 115 device->setLedState( led, device->ledStateList( led ).contains( Led_BlinkSlow ) ? Led_BlinkSlow : Led_On );
116 } 116 }
117 } 117 }
118 if ( m_config->readBoolEntry( "PlaySound", false ) ) 118 if ( m_config->readBoolEntry( "PlaySound", false ) )
119 device->playAlarmSound(); 119 device->playAlarmSound();
120 120
121 Config cfg( "mail" ); 121 Config cfg( "mail" );
122 cfg.setGroup( "Status" ); 122 cfg.setGroup( "Status" );
123 cfg.writeEntry( "newMails", m_newMails ); 123 cfg.writeEntry( "newMails", m_newMails );
124 QCopEnvelope env( "QPE/Pim", "newMails(int)" ); 124 QCopEnvelope env( "QPE/Pim", "newMails(int)" );
125 env << m_newMails; 125 env << m_newMails;
126 repaint( true ); 126 repaint( true );
127 127
128 } else { 128 } else {
129 ODevice *device = ODevice::inst(); 129 ODevice *device = ODevice::inst();
130 if ( !isHidden() ) 130 if ( !isHidden() )
131 hide(); 131 hide();
132 if ( !device->ledList().isEmpty() ) { 132 if ( !device->ledList().isEmpty() ) {
133 OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0]; 133 OLed led = ( device->ledList().contains( Led_Mail ) ) ? Led_Mail : device->ledList()[0];
134 device->setLedState( led, Led_Off ); 134 device->setLedState( led, Led_Off );
135 } 135 }
136 136
137 if ( newMailsOld != m_newMails ) { 137 if ( newMailsOld != m_newMails ) {
138 Config cfg( "mail" ); 138 Config cfg( "mail" );
139 cfg.setGroup( "Status" ); 139 cfg.setGroup( "Status" );
140 cfg.writeEntry( "newMails", m_newMails ); 140 cfg.writeEntry( "newMails", m_newMails );
141 QCopEnvelope env( "QPE/Pim", "newMails(int)" ); 141 QCopEnvelope env( "QPE/Pim", "newMails(int)" );
142 env << m_newMails; 142 env << m_newMails;
143 } 143 }
144 } 144 }
145} 145}
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)
46 /* if not set, then no parent */ 46 /* if not set, then no parent */
47 if (path.count()==0||_path.count()==0) return false; 47 if (path.count()==0||_path.count()==0) return false;
48 /* the parent must have one digit less then a child */ 48 /* the parent must have one digit less then a child */
49 if (path.count()!=_path.count()+1) return false; 49 if (path.count()!=_path.count()+1) return false;
50 for (unsigned int i=0; i < _path.count();++i) 50 for (unsigned int i=0; i < _path.count();++i)
51 { 51 {
52 if (_path[i]!=path[i]) return false; 52 if (_path[i]!=path[i]) return false;
53 } 53 }
54 return true; 54 return true;
55} 55}
56 56
57AttachItem* ViewMail::searchParent(const QValueList<int>&path) 57AttachItem* ViewMail::searchParent(const QValueList<int>&path)
58{ 58{
59 QListViewItemIterator it( attachments ); 59 QListViewItemIterator it( attachments );
60 for ( ; it.current(); ++it ) 60 for ( ; it.current(); ++it )
61 { 61 {
62 AttachItem*ati = (AttachItem*)it.current(); 62 AttachItem*ati = (AttachItem*)it.current();
63 if (ati->isParentof(path)) return ati; 63 if (ati->isParentof(path)) return ati;
64 } 64 }
65 return 0; 65 return 0;
66} 66}
67 67
68AttachItem* ViewMail::lastChild(AttachItem*parent) 68AttachItem* ViewMail::lastChild(AttachItem*parent)
69{ 69{
70 if (!parent) return 0; 70 if (!parent) return 0;
71 AttachItem* item = (AttachItem*)parent->firstChild(); 71 AttachItem* item = (AttachItem*)parent->firstChild();
72 if (!item) return item; 72 if (!item) return item;
73 AttachItem*temp=0; 73 AttachItem*temp=0;
74 while( (temp=(AttachItem*)item->nextSibling())) 74 while( (temp=(AttachItem*)item->nextSibling()))
75 { 75 {
76 item = temp; 76 item = temp;
77 } 77 }
78 return item; 78 return item;
79} 79}
80 80
81void ViewMail::setBody(const RecBodyP&body ) 81void ViewMail::setBody(const RecBodyP&body )
82{ 82{
83 83
84 m_body = body; 84 m_body = body;
85 m_mail[2] = body->Bodytext(); 85 m_mail[2] = body->Bodytext();
86 attachbutton->setEnabled(body->Parts().count()>0); 86 attachbutton->setEnabled(body->Parts().count()>0);
87 attachments->setEnabled(body->Parts().count()>0); 87 attachments->setEnabled(body->Parts().count()>0);
88 if (body->Parts().count()==0) 88 if (body->Parts().count()==0)
89 { 89 {
90 return; 90 return;
91 } 91 }
92 AttachItem * curItem=0; 92 AttachItem * curItem=0;
93 AttachItem * parentItem = 0; 93 AttachItem * parentItem = 0;
94 QString type=body->Description()->Type()+"/"+body->Description()->Subtype(); 94 QString type=body->Description()->Type()+"/"+body->Description()->Subtype();
95 QString desc,fsize; 95 QString desc,fsize;
96 double s = body->Description()->Size(); 96 double s = body->Description()->Size();
97 int w; 97 int w;
98 w=0; 98 w=0;
99 99
100 while (s>1024) 100 while (s>1024)
101 { 101 {
102 s/=1024; 102 s/=1024;
103 ++w; 103 ++w;
104 if (w>=2) break; 104 if (w>=2) break;
105 } 105 }
106 106
107 QString q=""; 107 QString q="";
108 switch(w) 108 switch(w)
109 { 109 {
110 case 1: 110 case 1:
111 q="k"; 111 q="k";
112 break; 112 break;
113 case 2: 113 case 2:
114 q="M"; 114 q="M";
115 break; 115 break;
116 default: 116 default:
117 break; 117 break;
118 } 118 }
119 119
120 { 120 {
121 /* I did not found a method to make a CONTENT reset on a QTextStream 121 /* I did not found a method to make a CONTENT reset on a QTextStream
122 so I use this construct that the stream will re-constructed in each 122 so I use this construct that the stream will re-constructed in each
123 loop. To let it work, the textstream is packed into a own area of 123 loop. To let it work, the textstream is packed into a own area of
124 code is it will be destructed after finishing its small job. 124 code is it will be destructed after finishing its small job.
125 */ 125 */
126 QTextOStream o(&fsize); 126 QTextOStream o(&fsize);
127 if (w>0) o.precision(2); else o.precision(0); 127 if (w>0) o.precision(2); else o.precision(0);
128 o.setf(QTextStream::fixed); 128 o.setf(QTextStream::fixed);
129 o << s << " " << q << "Byte"; 129 o << s << " " << q << "Byte";
130 } 130 }
131 131
132 curItem=new AttachItem(attachments,curItem,type,"Mailbody","",fsize,-1,body->Description()->Positionlist()); 132 curItem=new AttachItem(attachments,curItem,type,"Mailbody","",fsize,-1,body->Description()->Positionlist());
133 QString filename = ""; 133 QString filename = "";
134 134
135 for (unsigned int i = 0; i < body->Parts().count();++i) 135 for (unsigned int i = 0; i < body->Parts().count();++i)
136 { 136 {
137 filename = ""; 137 filename = "";
138 type = body->Parts()[i]->Type()+"/"+body->Parts()[i]->Subtype(); 138 type = body->Parts()[i]->Type()+"/"+body->Parts()[i]->Subtype();
139 part_plist_t::ConstIterator it = body->Parts()[i]->Parameters().begin(); 139 part_plist_t::ConstIterator it = body->Parts()[i]->Parameters().begin();
140 for (;it!=body->Parts()[i]->Parameters().end();++it) 140 for (;it!=body->Parts()[i]->Parameters().end();++it)
141 { 141 {
142 qDebug(it.key()); 142 odebug << it.key() << oendl;
143 if (it.key().lower()=="name") 143 if (it.key().lower()=="name")
144 { 144 {
145 filename=it.data(); 145 filename=it.data();
146 } 146 }
147 } 147 }
148 s = body->Parts()[i]->Size(); 148 s = body->Parts()[i]->Size();
149 w = 0; 149 w = 0;
150 while (s>1024) 150 while (s>1024)
151 { 151 {
152 s/=1024; 152 s/=1024;
153 ++w; 153 ++w;
154 if (w>=2) break; 154 if (w>=2) break;
155 } 155 }
156 switch(w) 156 switch(w)
157 { 157 {
158 case 1: 158 case 1:
159 q="k"; 159 q="k";
160 break; 160 break;
161 case 2: 161 case 2:
162 q="M"; 162 q="M";
163 break; 163 break;
164 default: 164 default:
165 q=""; 165 q="";
166 break; 166 break;
167 } 167 }
168 QTextOStream o(&fsize); 168 QTextOStream o(&fsize);
169 if (w>0) o.precision(2); else o.precision(0); 169 if (w>0) o.precision(2); else o.precision(0);
170 o.setf(QTextStream::fixed); 170 o.setf(QTextStream::fixed);
171 o << s << " " << q << "Byte"; 171 o << s << " " << q << "Byte";
172 desc = body->Parts()[i]->Description(); 172 desc = body->Parts()[i]->Description();
173 parentItem = searchParent(body->Parts()[i]->Positionlist()); 173 parentItem = searchParent(body->Parts()[i]->Positionlist());
174 if (parentItem) 174 if (parentItem)
175 { 175 {
176 AttachItem*temp = lastChild(parentItem); 176 AttachItem*temp = lastChild(parentItem);
177 if (temp) curItem = temp; 177 if (temp) curItem = temp;
178 curItem=new AttachItem(parentItem,curItem,type,desc,filename,fsize,i,body->Parts()[i]->Positionlist()); 178 curItem=new AttachItem(parentItem,curItem,type,desc,filename,fsize,i,body->Parts()[i]->Positionlist());
179 attachments->setRootIsDecorated(true); 179 attachments->setRootIsDecorated(true);
180 curItem = parentItem; 180 curItem = parentItem;
181 } 181 }
182 else 182 else
183 { 183 {
184 curItem=new AttachItem(attachments,curItem,type,desc,filename,fsize,i,body->Parts()[i]->Positionlist()); 184 curItem=new AttachItem(attachments,curItem,type,desc,filename,fsize,i,body->Parts()[i]->Positionlist());
185 } 185 }
186 } 186 }
187} 187}
188 188
189 189
190void ViewMail::slotShowHtml( bool state ) 190void ViewMail::slotShowHtml( bool state )
191{ 191{
192 m_showHtml = state; 192 m_showHtml = state;
193 setText(); 193 setText();
194} 194}
195 195
196void ViewMail::slotItemClicked( QListViewItem * item , const QPoint & point, int ) 196void ViewMail::slotItemClicked( QListViewItem * item , const QPoint & point, int )
197{ 197{
198 if (!item ) 198 if (!item )
199 return; 199 return;
200 200
201 if ( ( ( AttachItem* )item )->Partnumber() == -1 ) 201 if ( ( ( AttachItem* )item )->Partnumber() == -1 )
202 { 202 {
203 setText(); 203 setText();
204 return; 204 return;
205 } 205 }
206 QPopupMenu *menu = new QPopupMenu(); 206 QPopupMenu *menu = new QPopupMenu();
207 int ret=0; 207 int ret=0;
208 208
209 if ( item->text( 0 ).left( 5 ) == "text/" || item->text(0)=="message/rfc822" ) 209 if ( item->text( 0 ).left( 5 ) == "text/" || item->text(0)=="message/rfc822" )
210 { 210 {
211 menu->insertItem( tr( "Show Text" ), 1 ); 211 menu->insertItem( tr( "Show Text" ), 1 );
212 } 212 }
213 menu->insertItem( tr( "Save Attachment" ), 0 ); 213 menu->insertItem( tr( "Save Attachment" ), 0 );
214 menu->insertSeparator(1); 214 menu->insertSeparator(1);
215 215
216 ret = menu->exec( point, 0 ); 216 ret = menu->exec( point, 0 );
217 217
218 switch(ret) 218 switch(ret)
219 { 219 {
220 case 0: 220 case 0:
221 { 221 {
222 MimeTypes types; 222 MimeTypes types;
223 types.insert( "all", "*" ); 223 types.insert( "all", "*" );
224 QString str = OFileDialog::getSaveFileName( 1, 224 QString str = OFileDialog::getSaveFileName( 1,
225 "/", item->text( 2 ) , types, 0 ); 225 "/", item->text( 2 ) , types, 0 );
226 226
227 if( !str.isEmpty() ) 227 if( !str.isEmpty() )
228 { 228 {
229 encodedString*content = m_recMail->Wrapper()->fetchDecodedPart( m_recMail, m_body->Parts()[ ( ( AttachItem* )item )->Partnumber() ] ); 229 encodedString*content = m_recMail->Wrapper()->fetchDecodedPart( m_recMail, m_body->Parts()[ ( ( AttachItem* )item )->Partnumber() ] );
230 if (content) 230 if (content)
231 { 231 {
232 QFile output(str); 232 QFile output(str);
233 output.open(IO_WriteOnly); 233 output.open(IO_WriteOnly);
234 output.writeBlock(content->Content(),content->Length()); 234 output.writeBlock(content->Content(),content->Length());
235 output.close(); 235 output.close();
236 delete content; 236 delete content;
237 } 237 }
238 } 238 }
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 @@
1 config OPIEFTP 1 config OPIEFTP
2 boolean "opie-ftp (ftp client for Opie)" 2 boolean "opie-ftp (ftp client for Opie)"
3 default "y" 3 default "y"
4 depends ( LIBQPE || LIBQPE-X11 ) && FTPLIB 4 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 @@
1/**************************************************************************** 1/****************************************************************************
2** copyright 2002 ljp ljp@llornkcor.com 2** copyright 2002 ljp ljp@llornkcor.com
3** Created: Sat Feb 23 19:44:40 2002 L.J. Potter 3** Created: Sat Feb 23 19:44:40 2002 L.J. Potter
4** 4**
5** This file may be distributed and/or modified under the terms of the 5** This file may be distributed and/or modified under the terms of the
6** GNU General Public License version 2 as published by the Free Software 6** GNU General Public License version 2 as published by the Free Software
7** Foundation and appearing in the file LICENSE.GPL included in the 7** Foundation and appearing in the file LICENSE.GPL included in the
8** packaging of this file. 8** packaging of this file.
9** 9**
10** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 10** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
11** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 11** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
12** 12**
13****************************************************************************/ 13****************************************************************************/
14#include "filePermissions.h" 14#include "filePermissions.h"
15 15
16#include <qfileinfo.h> 16#include <qfileinfo.h>
17 17
18#include <qcheckbox.h> 18#include <qcheckbox.h>
19#include <qlabel.h> 19#include <qlabel.h>
20#include <qlineedit.h> 20#include <qlineedit.h>
21#include <qmessagebox.h> 21#include <qmessagebox.h>
22 22
23#include <unistd.h> 23#include <unistd.h>
24#include <sys/stat.h> 24#include <sys/stat.h>
25#include <stdlib.h> 25#include <stdlib.h>
26#include <sys/types.h> 26#include <sys/types.h>
27#include <pwd.h> 27#include <pwd.h>
28#include <grp.h> 28#include <grp.h>
29 29
30filePermissions::filePermissions( QWidget* parent, const char* name, bool modal, WFlags fl, const QString &fileName, bool useRemote ) 30filePermissions::filePermissions( QWidget* parent, const char* name, bool modal, WFlags fl, const QString &fileName, bool useRemote )
31 : QDialog( parent, name, modal, fl ) 31 : QDialog( parent, name, modal, fl )
32{ 32{
33 if ( !name ) 33 if ( !name )
34 setName( tr("filePermissions") ); 34 setName( tr("filePermissions") );
35// qDebug("FilePermissions "+fileName); 35// odebug << "FilePermissions "+fileName << oendl;
36 resize( 236, 210 ); 36 resize( 236, 210 );
37 isRemote=useRemote; 37 isRemote=useRemote;
38 setMaximumSize( QSize( 236, 210 ) ); 38 setMaximumSize( QSize( 236, 210 ) );
39 setCaption( tr( "Set File Permissions" ) ); 39 setCaption( tr( "Set File Permissions" ) );
40 40
41 TextLabel1 = new QLabel( this, "TextLabel1" ); 41 TextLabel1 = new QLabel( this, "TextLabel1" );
42 TextLabel1->setGeometry( QRect( 25, 5, 175, 20 ) ); 42 TextLabel1->setGeometry( QRect( 25, 5, 175, 20 ) );
43 TextLabel1->setText( tr( "Set file permissions for:" ) ); 43 TextLabel1->setText( tr( "Set file permissions for:" ) );
44 44
45 LineEdit1 = new QLineEdit( this, "LineEdit1" ); 45 LineEdit1 = new QLineEdit( this, "LineEdit1" );
46 LineEdit1->setGeometry( QRect( 10, 25, 218, 22 ) ); 46 LineEdit1->setGeometry( QRect( 10, 25, 218, 22 ) );
47 LineEdit1->setReadOnly(true); 47 LineEdit1->setReadOnly(true);
48 48
49 TextLabel4 = new QLabel( this, "TextLabel4" ); 49 TextLabel4 = new QLabel( this, "TextLabel4" );
50 TextLabel4->setGeometry( QRect( 5, 85, 50, 15 ) ); 50 TextLabel4->setGeometry( QRect( 5, 85, 50, 15 ) );
51 TextLabel4->setText( tr( "owner" ) ); 51 TextLabel4->setText( tr( "owner" ) );
52 52
53 TextLabel4_2 = new QLabel( this, "TextLabel4_2" ); 53 TextLabel4_2 = new QLabel( this, "TextLabel4_2" );
54 TextLabel4_2->setGeometry( QRect( 5, 105, 50, 15 ) ); 54 TextLabel4_2->setGeometry( QRect( 5, 105, 50, 15 ) );
55 TextLabel4_2->setText( tr( "group" ) ); 55 TextLabel4_2->setText( tr( "group" ) );
56 56
57 TextLabel4_3 = new QLabel( this, "TextLabel4_3" ); 57 TextLabel4_3 = new QLabel( this, "TextLabel4_3" );
58 TextLabel4_3->setGeometry( QRect( 5, 125, 50, 15 ) ); 58 TextLabel4_3->setGeometry( QRect( 5, 125, 50, 15 ) );
59 TextLabel4_3->setText( tr( "others" ) ); 59 TextLabel4_3->setText( tr( "others" ) );
60 60
61 CheckBox1 = new QCheckBox( this, "CheckBox1" ); 61 CheckBox1 = new QCheckBox( this, "CheckBox1" );
62 CheckBox1->setGeometry( QRect( 75, 85, 20, 16 ) ); 62 CheckBox1->setGeometry( QRect( 75, 85, 20, 16 ) );
63 connect(CheckBox1, SIGNAL(released()),this,SLOT(ownReadCheck())); 63 connect(CheckBox1, SIGNAL(released()),this,SLOT(ownReadCheck()));
64 64
65 CheckBox1_2 = new QCheckBox( this, "CheckBox1_2" ); 65 CheckBox1_2 = new QCheckBox( this, "CheckBox1_2" );
66 CheckBox1_2->setGeometry( QRect( 135, 85, 20, 16 ) ); 66 CheckBox1_2->setGeometry( QRect( 135, 85, 20, 16 ) );
67 connect(CheckBox1_2, SIGNAL(released()),this,SLOT(ownWriteCheck())); 67 connect(CheckBox1_2, SIGNAL(released()),this,SLOT(ownWriteCheck()));
68 68
69 CheckBox1_3 = new QCheckBox( this, "CheckBox1_3" ); 69 CheckBox1_3 = new QCheckBox( this, "CheckBox1_3" );
70 CheckBox1_3->setGeometry( QRect( 195, 85, 20, 16 ) ); 70 CheckBox1_3->setGeometry( QRect( 195, 85, 20, 16 ) );
71 connect(CheckBox1_3, SIGNAL(released()),this,SLOT(ownExeCheck())); 71 connect(CheckBox1_3, SIGNAL(released()),this,SLOT(ownExeCheck()));
72 72
73 CheckBox1_4 = new QCheckBox( this, "CheckBox1_4" ); 73 CheckBox1_4 = new QCheckBox( this, "CheckBox1_4" );
74 CheckBox1_4->setGeometry( QRect( 75, 105, 20, 16 ) ); 74 CheckBox1_4->setGeometry( QRect( 75, 105, 20, 16 ) );
75 connect(CheckBox1_4, SIGNAL(released()),this,SLOT(grpReadCheck())); 75 connect(CheckBox1_4, SIGNAL(released()),this,SLOT(grpReadCheck()));
76 76
77 CheckBox1_5 = new QCheckBox( this, "CheckBox1_5" ); 77 CheckBox1_5 = new QCheckBox( this, "CheckBox1_5" );
78 CheckBox1_5->setGeometry( QRect( 135, 105, 20, 16 ) ); 78 CheckBox1_5->setGeometry( QRect( 135, 105, 20, 16 ) );
79 connect(CheckBox1_5, SIGNAL(released()),this,SLOT(grpWriteCheck())); 79 connect(CheckBox1_5, SIGNAL(released()),this,SLOT(grpWriteCheck()));
80 80
81 CheckBox1_6 = new QCheckBox( this, "CheckBox1_6" ); 81 CheckBox1_6 = new QCheckBox( this, "CheckBox1_6" );
82 CheckBox1_6->setGeometry( QRect( 195, 105, 20, 16 ) ); 82 CheckBox1_6->setGeometry( QRect( 195, 105, 20, 16 ) );
83 connect(CheckBox1_6, SIGNAL(released()),this,SLOT(grpExeCheck())); 83 connect(CheckBox1_6, SIGNAL(released()),this,SLOT(grpExeCheck()));
84 84
85 CheckBox1_7 = new QCheckBox( this, "CheckBox1_7" ); 85 CheckBox1_7 = new QCheckBox( this, "CheckBox1_7" );
86 CheckBox1_7->setGeometry( QRect( 75, 125, 16, 16 ) ); 86 CheckBox1_7->setGeometry( QRect( 75, 125, 16, 16 ) );
87 connect(CheckBox1_7, SIGNAL(released()),this,SLOT(wrldReadCheck())); 87 connect(CheckBox1_7, SIGNAL(released()),this,SLOT(wrldReadCheck()));
88 88
89 CheckBox1_8 = new QCheckBox( this, "CheckBox1_8" ); 89 CheckBox1_8 = new QCheckBox( this, "CheckBox1_8" );
90 CheckBox1_8->setGeometry( QRect( 135, 125, 20, 16 ) ); 90 CheckBox1_8->setGeometry( QRect( 135, 125, 20, 16 ) );
91 connect(CheckBox1_8, SIGNAL(released()),this,SLOT(wrldWriteCheck())); 91 connect(CheckBox1_8, SIGNAL(released()),this,SLOT(wrldWriteCheck()));
92 92
93 CheckBox1_8_2 = new QCheckBox( this, "CheckBox1_8_2" ); 93 CheckBox1_8_2 = new QCheckBox( this, "CheckBox1_8_2" );
94 CheckBox1_8_2->setGeometry( QRect( 195, 125, 20, 16 ) ); 94 CheckBox1_8_2->setGeometry( QRect( 195, 125, 20, 16 ) );
95 connect(CheckBox1_8_2, SIGNAL(released()),this,SLOT(wrldExeCheck())); 95 connect(CheckBox1_8_2, SIGNAL(released()),this,SLOT(wrldExeCheck()));
96 96
97 GroupLineEdit = new QLineEdit( this, "GroupLineEdit" ); 97 GroupLineEdit = new QLineEdit( this, "GroupLineEdit" );
98 GroupLineEdit->setGeometry( QRect( 125, 155, 106, 22 ) ); 98 GroupLineEdit->setGeometry( QRect( 125, 155, 106, 22 ) );
99 99
100 OwnerLineEdit = new QLineEdit( this, "OwnerLineEdit" ); 100 OwnerLineEdit = new QLineEdit( this, "OwnerLineEdit" );
101 OwnerLineEdit->setGeometry( QRect( 10, 155, 106, 22 ) ); 101 OwnerLineEdit->setGeometry( QRect( 10, 155, 106, 22 ) );
102 102
103 TextLabel5 = new QLabel( this, "TextLabel5" ); 103 TextLabel5 = new QLabel( this, "TextLabel5" );
104 TextLabel5->setGeometry( QRect( 45, 180, 40, 16 ) ); 104 TextLabel5->setGeometry( QRect( 45, 180, 40, 16 ) );
105 TextLabel5->setText( tr( "Owner" ) ); 105 TextLabel5->setText( tr( "Owner" ) );
106 106
107 TextLabel5_2 = new QLabel( this, "TextLabel5_2" ); 107 TextLabel5_2 = new QLabel( this, "TextLabel5_2" );
108 TextLabel5_2->setGeometry( QRect( 155, 180, 40, 16 ) ); 108 TextLabel5_2->setGeometry( QRect( 155, 180, 40, 16 ) );
109 TextLabel5_2->setText( tr( "Group" ) ); 109 TextLabel5_2->setText( tr( "Group" ) );
110 110
111 ModeLine = new QLineEdit( this, "TextLabelMode" ); 111 ModeLine = new QLineEdit( this, "TextLabelMode" );
112 ModeLine->setGeometry( QRect( 10, 60, 40, 15 ) ); 112 ModeLine->setGeometry( QRect( 10, 60, 40, 15 ) );
113 113
114 TextLabel3_2 = new QLabel( this, "TextLabel3_2" ); 114 TextLabel3_2 = new QLabel( this, "TextLabel3_2" );
115 TextLabel3_2->setGeometry( QRect( 60, 55, 50, 20 ) ); 115 TextLabel3_2->setGeometry( QRect( 60, 55, 50, 20 ) );
116 TextLabel3_2->setText( tr( "read" ) ); 116 TextLabel3_2->setText( tr( "read" ) );
117 TextLabel3_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) ); 117 TextLabel3_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
118 118
119 TextLabel3_2_2 = new QLabel( this, "TextLabel3_2_2" ); 119 TextLabel3_2_2 = new QLabel( this, "TextLabel3_2_2" );
120 TextLabel3_2_2->setGeometry( QRect( 120, 55, 50, 20 ) ); 120 TextLabel3_2_2->setGeometry( QRect( 120, 55, 50, 20 ) );
121 TextLabel3_2_2->setText( tr( "write" ) ); 121 TextLabel3_2_2->setText( tr( "write" ) );
122 TextLabel3_2_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) ); 122 TextLabel3_2_2->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
123 123
124 TextLabel3 = new QLabel( this, "TextLabel3" ); 124 TextLabel3 = new QLabel( this, "TextLabel3" );
125 TextLabel3->setGeometry( QRect( 180, 55, 50, 20 ) ); 125 TextLabel3->setGeometry( QRect( 180, 55, 50, 20 ) );
126 TextLabel3->setText( tr( "execute" ) ); 126 TextLabel3->setText( tr( "execute" ) );
127 TextLabel3->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) ); 127 TextLabel3->setAlignment( int( QLabel::AlignBottom | QLabel::AlignHCenter ) );
128 128
129 struct stat buf; 129 struct stat buf;
130 mode_t mode; 130 mode_t mode;
131 file = fileName; 131 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 @@
1/*************************************************************************** 1/***************************************************************************
2 opieftp.cpp 2 opieftp.cpp
3 ------------------- 3 -------------------
4** Created: Sat Mar 9 23:33:09 2002 4** Created: Sat Mar 9 23:33:09 2002
5 copyright : (C) 2002 by ljp 5 copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12//#define DEVELOPERS_VERSION 12//#define DEVELOPERS_VERSION
13 13
14#include "opieftp.h" 14#include "opieftp.h"
15 15
16extern "C" { 16extern "C" {
17#include "../ftplib/ftplib.h" 17#include "../ftplib/ftplib.h"
18} 18}
19 19
20#include "inputDialog.h" 20#include "inputDialog.h"
21 21
22#include <qmenubar.h> 22/* OPIE */
23#include <opie2/odebug.h>
23#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
24#include <qpe/resource.h> 25#include <qpe/resource.h>
25#include <qpe/config.h> 26#include <qpe/config.h>
26#include <qpe/mimetype.h> 27#include <qpe/mimetype.h>
28using namespace Opie::Core;
27 29
28#include <qtextstream.h> 30#include <qtextstream.h>
29#include <qpushbutton.h> 31#include <qpushbutton.h>
30#include <qtoolbutton.h> 32#include <qtoolbutton.h>
31#include <qcombobox.h> 33#include <qcombobox.h>
32#include <qlistview.h> 34#include <qlistview.h>
33#include <qlabel.h> 35#include <qlabel.h>
34#include <qprogressbar.h> 36#include <qprogressbar.h>
35#include <qspinbox.h> 37#include <qspinbox.h>
36#include <qtabwidget.h> 38#include <qtabwidget.h>
37#include <qlayout.h> 39#include <qlayout.h>
38#include <qmessagebox.h> 40#include <qmessagebox.h>
41#include <qmenubar.h>
39#include <qlineedit.h> 42#include <qlineedit.h>
40#include <qlistbox.h> 43#include <qlistbox.h>
41#include <qvbox.h> 44#include <qvbox.h>
42 45
46/* STD */
43#include <unistd.h> 47#include <unistd.h>
44#include <stdlib.h> 48#include <stdlib.h>
45 49
46
47QProgressBar *ProgressBar; 50QProgressBar *ProgressBar;
48static netbuf *conn=NULL; 51static netbuf *conn=NULL;
49 52
50static int log_progress(netbuf *, int xfered, void *) 53static int log_progress(netbuf *, int xfered, void *)
51{ 54{
52// int fsz = *(int *)arg; 55// int fsz = *(int *)arg;
53// int pct = (xfered * 100) / fsz; 56// int pct = (xfered * 100) / fsz;
54// printf("%3d%%\r", pct); 57// printf("%3d%%\r", pct);
55// fflush(stdout); 58// fflush(stdout);
56 ProgressBar->setProgress(xfered); 59 ProgressBar->setProgress(xfered);
57 qApp->processEvents(); 60 qApp->processEvents();
58 return 1; 61 return 1;
59} 62}
60 63
61OpieFtp::OpieFtp( QWidget* parent, const char* name, WFlags fl) 64OpieFtp::OpieFtp( QWidget* parent, const char* name, WFlags fl)
62 : QMainWindow( parent, name, fl ) 65 : QMainWindow( parent, name, fl )
63{ 66{
64 qDebug("OpieFtp constructor"); 67 odebug << "OpieFtp constructor" << oendl;
65 setCaption( tr( "OpieFtp" ) ); 68 setCaption( tr( "OpieFtp" ) );
66 fuckeduphack=FALSE; 69 fuckeduphack=FALSE;
67 70
68 QVBox* wrapperBox = new QVBox( this ); 71 QVBox* wrapperBox = new QVBox( this );
69 setCentralWidget( wrapperBox ); 72 setCentralWidget( wrapperBox );
70 73
71 QWidget *view = new QWidget( wrapperBox ); 74 QWidget *view = new QWidget( wrapperBox );
72 75
73 QGridLayout *layout = new QGridLayout( view ); 76 QGridLayout *layout = new QGridLayout( view );
74 layout->setSpacing( 2); 77 layout->setSpacing( 2);
75 layout->setMargin( 2); 78 layout->setMargin( 2);
76 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 79 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
77 80
78 QMenuBar *menuBar = new QMenuBar(this); 81 QMenuBar *menuBar = new QMenuBar(this);
79// QToolBar *menuBar = new QToolBar(this); 82// QToolBar *menuBar = new QToolBar(this);
80// menuBar->setHorizontalStretchable( TRUE ); 83// menuBar->setHorizontalStretchable( TRUE );
81 84
82 QWMatrix matrix; 85 QWMatrix matrix;
83 QPixmap pix(Resource::loadPixmap( "UnknownDocument" )); 86 QPixmap pix(Resource::loadPixmap( "UnknownDocument" ));
84 matrix.scale( .4, .4); 87 matrix.scale( .4, .4);
85 unknownXpm = pix.xForm(matrix); 88 unknownXpm = pix.xForm(matrix);
86 89
87 connectionMenu = new QPopupMenu( this ); 90 connectionMenu = new QPopupMenu( this );
88 localMenu = new QPopupMenu( this ); 91 localMenu = new QPopupMenu( this );
89 remoteMenu = new QPopupMenu( this ); 92 remoteMenu = new QPopupMenu( this );
90 tabMenu = new QPopupMenu( this ); 93 tabMenu = new QPopupMenu( this );
91 94
92//#if 0 95//#if 0
93 layout->addMultiCellWidget( menuBar, 0, 0, 0, 2 ); 96 layout->addMultiCellWidget( menuBar, 0, 0, 0, 2 );
94//#endif 97//#endif
95 98
96 menuBar->insertItem( tr( "Connection" ), connectionMenu); 99 menuBar->insertItem( tr( "Connection" ), connectionMenu);
97// menuBar->insertItem( tr( "Local" ), localMenu); 100// menuBar->insertItem( tr( "Local" ), localMenu);
98// menuBar->insertItem( tr( "Remote" ), remoteMenu); 101// menuBar->insertItem( tr( "Remote" ), remoteMenu);
99 menuBar->insertItem( tr( "View" ), tabMenu); 102 menuBar->insertItem( tr( "View" ), tabMenu);
100 103
101 tabMenu->insertItem( tr( "Local" ), localMenu); 104 tabMenu->insertItem( tr( "Local" ), localMenu);
102 tabMenu->insertItem( tr( "Remote" ), remoteMenu); 105 tabMenu->insertItem( tr( "Remote" ), remoteMenu);
103 106
104 connectionMenu->insertItem( tr( "New" ), this, SLOT( newConnection() )); 107 connectionMenu->insertItem( tr( "New" ), this, SLOT( newConnection() ));
105 connectionMenu->insertItem( tr( "Connect" ), this, SLOT( connector() )); 108 connectionMenu->insertItem( tr( "Connect" ), this, SLOT( connector() ));
106 connectionMenu->insertItem( tr( "Disconnect" ), this, SLOT( disConnector() )); 109 connectionMenu->insertItem( tr( "Disconnect" ), this, SLOT( disConnector() ));
107 110
108 localMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() )); 111 localMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() ));
109 localMenu->insertSeparator(); 112 localMenu->insertSeparator();
110 localMenu->insertItem( tr( "Upload" ), this, SLOT( localUpload() )); 113 localMenu->insertItem( tr( "Upload" ), this, SLOT( localUpload() ));
111 localMenu->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() )); 114 localMenu->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() ));
112 localMenu->insertItem( tr( "Rename" ), this, SLOT( localRename() )); 115 localMenu->insertItem( tr( "Rename" ), this, SLOT( localRename() ));
113 localMenu->insertSeparator(); 116 localMenu->insertSeparator();
114 localMenu->insertItem( tr( "Delete" ), this, SLOT( localDelete() )); 117 localMenu->insertItem( tr( "Delete" ), this, SLOT( localDelete() ));
115 localMenu->setCheckable(TRUE); 118 localMenu->setCheckable(TRUE);
116 119
117 remoteMenu->insertItem( tr( "Download" ), this, SLOT( remoteDownload() )); 120 remoteMenu->insertItem( tr( "Download" ), this, SLOT( remoteDownload() ));
118 remoteMenu->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() )); 121 remoteMenu->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() ));
119 remoteMenu->insertItem( tr( "Rename" ), this, SLOT( remoteRename() )); 122 remoteMenu->insertItem( tr( "Rename" ), this, SLOT( remoteRename() ));
120 remoteMenu->insertSeparator(); 123 remoteMenu->insertSeparator();
121 remoteMenu->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() )); 124 remoteMenu->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() ));
122 125
123 tabMenu->insertSeparator(); 126 tabMenu->insertSeparator();
124 tabMenu->insertItem( tr( "Switch to Local" ), this, SLOT( switchToLocalTab() )); 127 tabMenu->insertItem( tr( "Switch to Local" ), this, SLOT( switchToLocalTab() ));
125 tabMenu->insertItem( tr( "Switch to Remote" ), this, SLOT( switchToRemoteTab() )); 128 tabMenu->insertItem( tr( "Switch to Remote" ), this, SLOT( switchToRemoteTab() ));
126 tabMenu->insertItem( tr( "Switch to Config" ), this, SLOT( switchToConfigTab() )); 129 tabMenu->insertItem( tr( "Switch to Config" ), this, SLOT( switchToConfigTab() ));
127 tabMenu->insertSeparator(); 130 tabMenu->insertSeparator();
128// tabMenu->insertItem( tr( "About" ), this, SLOT( doAbout() )); 131// tabMenu->insertItem( tr( "About" ), this, SLOT( doAbout() ));
129 tabMenu->setCheckable(TRUE); 132 tabMenu->setCheckable(TRUE);
130 133
131 134
132 cdUpButton = new QToolButton( view,"cdUpButton"); 135 cdUpButton = new QToolButton( view,"cdUpButton");
133 cdUpButton->setPixmap(Resource::loadPixmap("up")); 136 cdUpButton->setPixmap(Resource::loadPixmap("up"));
134 cdUpButton ->setFixedSize( QSize( 20, 20 ) ); 137 cdUpButton ->setFixedSize( QSize( 20, 20 ) );
135 connect( cdUpButton ,SIGNAL(released()),this,SLOT( upDir()) ); 138 connect( cdUpButton ,SIGNAL(released()),this,SLOT( upDir()) );
136 layout->addMultiCellWidget( cdUpButton, 0, 0, 3, 3 ); 139 layout->addMultiCellWidget( cdUpButton, 0, 0, 3, 3 );
137 cdUpButton->hide(); 140 cdUpButton->hide();
138 141
139// docButton = new QPushButton(Resource::loadIconSet("DocsIcon"),"",view,"docsButton"); 142// docButton = new QPushButton(Resource::loadIconSet("DocsIcon"),"",view,"docsButton");
140// docButton->setFixedSize( QSize( 20, 20 ) ); 143// docButton->setFixedSize( QSize( 20, 20 ) );
141// connect( docButton,SIGNAL(released()),this,SLOT( docButtonPushed()) ); 144// connect( docButton,SIGNAL(released()),this,SLOT( docButtonPushed()) );
142// docButton->setFlat(TRUE); 145// docButton->setFlat(TRUE);
143// layout->addMultiCellWidget( docButton, 0, 0, 6, 6 ); 146// layout->addMultiCellWidget( docButton, 0, 0, 6, 6 );
144 147
145 homeButton = new QToolButton(view,"homeButton"); 148 homeButton = new QToolButton(view,"homeButton");
146 homeButton->setPixmap( Resource::loadPixmap("home")); 149 homeButton->setPixmap( Resource::loadPixmap("home"));
147 homeButton->setFixedSize( QSize( 20, 20 ) ); 150 homeButton->setFixedSize( QSize( 20, 20 ) );
148 connect(homeButton,SIGNAL(released()),this,SLOT(homeButtonPushed()) ); 151 connect(homeButton,SIGNAL(released()),this,SLOT(homeButtonPushed()) );
149 layout->addMultiCellWidget( homeButton, 0, 0, 4, 4); 152 layout->addMultiCellWidget( homeButton, 0, 0, 4, 4);
150 homeButton->hide(); 153 homeButton->hide();
151 154
152 TabWidget = new QTabWidget( view, "TabWidget" ); 155 TabWidget = new QTabWidget( view, "TabWidget" );
153 layout->addMultiCellWidget( TabWidget, 1, 1, 0, 4 ); 156 layout->addMultiCellWidget( TabWidget, 1, 1, 0, 4 );
154 157
155// TabWidget->setTabShape(QTabWidget::Triangular); 158// TabWidget->setTabShape(QTabWidget::Triangular);
156 159
157 tab = new QWidget( TabWidget, "tab" ); 160 tab = new QWidget( TabWidget, "tab" );
158 tabLayout = new QGridLayout( tab ); 161 tabLayout = new QGridLayout( tab );
159 tabLayout->setSpacing( 2); 162 tabLayout->setSpacing( 2);
160 tabLayout->setMargin( 2); 163 tabLayout->setMargin( 2);
@@ -241,725 +244,725 @@ OpieFtp::OpieFtp( QWidget* parent, const char* name, WFlags fl)
241 tabLayout_3->addMultiCellWidget( PasswordEdit, 1, 1, 2, 3 ); 244 tabLayout_3->addMultiCellWidget( PasswordEdit, 1, 1, 2, 3 );
242 245
243 connect( PasswordEdit,SIGNAL(textChanged(const QString&)),this, 246 connect( PasswordEdit,SIGNAL(textChanged(const QString&)),this,
244 SLOT( PasswordEditEdited(const QString&) )); 247 SLOT( PasswordEditEdited(const QString&) ));
245 248
246//PasswordEdit->setFixedWidth(85); 249//PasswordEdit->setFixedWidth(85);
247 TextLabel3 = new QLabel( tab_3, "TextLabel3" ); 250 TextLabel3 = new QLabel( tab_3, "TextLabel3" );
248 TextLabel3->setText( tr( "Remote server" ) ); 251 TextLabel3->setText( tr( "Remote server" ) );
249 tabLayout_3->addMultiCellWidget( TextLabel3, 2, 2, 0, 1 ); 252 tabLayout_3->addMultiCellWidget( TextLabel3, 2, 2, 0, 1 );
250 253
251 ServerComboBox = new QComboBox( FALSE, tab_3, "ServerComboBox" ); 254 ServerComboBox = new QComboBox( FALSE, tab_3, "ServerComboBox" );
252 ServerComboBox->setEditable(TRUE); 255 ServerComboBox->setEditable(TRUE);
253 tabLayout_3->addMultiCellWidget( ServerComboBox, 3, 3, 0, 1 ); 256 tabLayout_3->addMultiCellWidget( ServerComboBox, 3, 3, 0, 1 );
254 257
255 connect(ServerComboBox,SIGNAL(activated(int)),this,SLOT(serverComboSelected(int) )); 258 connect(ServerComboBox,SIGNAL(activated(int)),this,SLOT(serverComboSelected(int) ));
256 connect(ServerComboBox,SIGNAL(textChanged(const QString&)),this, 259 connect(ServerComboBox,SIGNAL(textChanged(const QString&)),this,
257 SLOT(serverComboEdited(const QString&) )); 260 SLOT(serverComboEdited(const QString&) ));
258 261
259 QLabel *TextLabel5 = new QLabel( tab_3, "TextLabel5" ); 262 QLabel *TextLabel5 = new QLabel( tab_3, "TextLabel5" );
260 TextLabel5->setText( tr( "Remote path" ) ); 263 TextLabel5->setText( tr( "Remote path" ) );
261 tabLayout_3->addMultiCellWidget( TextLabel5, 2, 2, 2, 3 ); 264 tabLayout_3->addMultiCellWidget( TextLabel5, 2, 2, 2, 3 );
262 265
263 266
264 remotePath = new QLineEdit( "/", tab_3, "remotePath" ); 267 remotePath = new QLineEdit( "/", tab_3, "remotePath" );
265 tabLayout_3->addMultiCellWidget( remotePath, 3, 3, 2, 3 ); 268 tabLayout_3->addMultiCellWidget( remotePath, 3, 3, 2, 3 );
266 TextLabel4 = new QLabel( tab_3, "TextLabel4" ); 269 TextLabel4 = new QLabel( tab_3, "TextLabel4" );
267 TextLabel4->setText( tr( "Port" ) ); 270 TextLabel4->setText( tr( "Port" ) );
268 tabLayout_3->addMultiCellWidget( TextLabel4, 4, 4, 0, 1 ); 271 tabLayout_3->addMultiCellWidget( TextLabel4, 4, 4, 0, 1 );
269 272
270 PortSpinBox = new QSpinBox( tab_3, "PortSpinBox" ); 273 PortSpinBox = new QSpinBox( tab_3, "PortSpinBox" );
271 PortSpinBox->setButtonSymbols( QSpinBox::UpDownArrows ); 274 PortSpinBox->setButtonSymbols( QSpinBox::UpDownArrows );
272 PortSpinBox->setMaxValue(32786); 275 PortSpinBox->setMaxValue(32786);
273 tabLayout_3->addMultiCellWidget( PortSpinBox, 4, 4, 1, 1); 276 tabLayout_3->addMultiCellWidget( PortSpinBox, 4, 4, 1, 1);
274 277
275 serverListView = new QListBox( tab_3, "ServerListView" ); 278 serverListView = new QListBox( tab_3, "ServerListView" );
276 tabLayout_3->addMultiCellWidget( serverListView , 5, 5, 0, 5); 279 tabLayout_3->addMultiCellWidget( serverListView , 5, 5, 0, 5);
277 280
278 connect( serverListView, SIGNAL( highlighted(const QString&)), 281 connect( serverListView, SIGNAL( highlighted(const QString&)),
279 this,SLOT( serverListClicked(const QString&) ) ); 282 this,SLOT( serverListClicked(const QString&) ) );
280 283
281 connectServerBtn = new QPushButton( tr("Connect"), tab_3 , "ConnectButton" ); 284 connectServerBtn = new QPushButton( tr("Connect"), tab_3 , "ConnectButton" );
282 tabLayout_3->addMultiCellWidget( connectServerBtn, 6, 6, 0, 1); 285 tabLayout_3->addMultiCellWidget( connectServerBtn, 6, 6, 0, 1);
283 connectServerBtn->setToggleButton(TRUE); 286 connectServerBtn->setToggleButton(TRUE);
284 connect(connectServerBtn,SIGNAL( toggled(bool)),SLOT( connectorBtnToggled(bool) )); 287 connect(connectServerBtn,SIGNAL( toggled(bool)),SLOT( connectorBtnToggled(bool) ));
285 288
286 newServerButton= new QPushButton( tr("Add"), tab_3 , "NewServerButton" ); 289 newServerButton= new QPushButton( tr("Add"), tab_3 , "NewServerButton" );
287 tabLayout_3->addMultiCellWidget( newServerButton, 6, 6, 2, 2); 290 tabLayout_3->addMultiCellWidget( newServerButton, 6, 6, 2, 2);
288 connect( newServerButton,SIGNAL( clicked()),SLOT( NewServer() )); 291 connect( newServerButton,SIGNAL( clicked()),SLOT( NewServer() ));
289 292
290 QPushButton *deleteServerBtn; 293 QPushButton *deleteServerBtn;
291 deleteServerBtn = new QPushButton( tr("Delete"), tab_3 , "OpenButton" ); 294 deleteServerBtn = new QPushButton( tr("Delete"), tab_3 , "OpenButton" );
292 tabLayout_3->addMultiCellWidget( deleteServerBtn, 6, 6, 3, 3); 295 tabLayout_3->addMultiCellWidget( deleteServerBtn, 6, 6, 3, 3);
293 296
294 connect(deleteServerBtn,SIGNAL(clicked()),SLOT(deleteServer())); 297 connect(deleteServerBtn,SIGNAL(clicked()),SLOT(deleteServer()));
295 298
296 299
297 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); 300 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
298 tabLayout_3->addItem( spacer, 5, 0 ); 301 tabLayout_3->addItem( spacer, 5, 0 );
299 302
300 TabWidget->insertTab( tab_3, tr( "Config" ) ); 303 TabWidget->insertTab( tab_3, tr( "Config" ) );
301 304
302#if 0 305#if 0
303 connect(TabWidget,SIGNAL(currentChanged(QWidget*)), 306 connect(TabWidget,SIGNAL(currentChanged(QWidget*)),
304 this,SLOT(tabChanged(QWidget*))); 307 this,SLOT(tabChanged(QWidget*)));
305#endif 308#endif
306 309
307 currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 310 currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
308 currentDir.setPath( QDir::currentDirPath()); 311 currentDir.setPath( QDir::currentDirPath());
309// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 312// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
310 313
311 currentPathCombo = new QComboBox( FALSE, view, "currentPathCombo" ); 314 currentPathCombo = new QComboBox( FALSE, view, "currentPathCombo" );
312 layout->addMultiCellWidget( currentPathCombo, 3, 3, 0, 4); 315 layout->addMultiCellWidget( currentPathCombo, 3, 3, 0, 4);
313 currentPathCombo ->setFixedWidth(220); 316 currentPathCombo ->setFixedWidth(220);
314 currentPathCombo->setEditable(TRUE); 317 currentPathCombo->setEditable(TRUE);
315 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath()); 318 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath());
316 319
317#if 0 320#if 0
318 connect( currentPathCombo, SIGNAL( activated(const QString&) ), 321 connect( currentPathCombo, SIGNAL( activated(const QString&) ),
319 this, SLOT( currentPathComboActivated(const QString&) ) ); 322 this, SLOT( currentPathComboActivated(const QString&) ) );
320 323
321 connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()), 324 connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()),
322 this,SLOT(currentPathComboChanged())); 325 this,SLOT(currentPathComboChanged()));
323#endif 326#endif
324 ProgressBar = new QProgressBar( view, "ProgressBar" ); 327 ProgressBar = new QProgressBar( view, "ProgressBar" );
325 layout->addMultiCellWidget( ProgressBar, 4, 4, 0, 4); 328 layout->addMultiCellWidget( ProgressBar, 4, 4, 0, 4);
326 ProgressBar->setMaximumHeight(10); 329 ProgressBar->setMaximumHeight(10);
327 filterStr="*"; 330 filterStr="*";
328 b=FALSE; 331 b=FALSE;
329#if 0 332#if 0
330 populateLocalView(); 333 populateLocalView();
331#endif 334#endif
332 readConfig(); 335 readConfig();
333 336
334// ServerComboBox->setCurrentItem(currentServerConfig); 337// ServerComboBox->setCurrentItem(currentServerConfig);
335 338
336 TabWidget->setCurrentPage(2); 339 TabWidget->setCurrentPage(2);
337 qDebug("Constructor done"); 340 odebug << "Constructor done" << oendl;
338} 341}
339 342
340OpieFtp::~OpieFtp() 343OpieFtp::~OpieFtp()
341{ 344{
342} 345}
343 346
344void OpieFtp::cleanUp() 347void OpieFtp::cleanUp()
345{ 348{
346 if(conn) 349 if(conn)
347 FtpQuit(conn); 350 FtpQuit(conn);
348 QString sfile=QDir::homeDirPath(); 351 QString sfile=QDir::homeDirPath();
349 if(sfile.right(1) != "/") 352 if(sfile.right(1) != "/")
350 sfile+="/._temp"; 353 sfile+="/._temp";
351 else 354 else
352 sfile+="._temp"; 355 sfile+="._temp";
353 QFile file( sfile); 356 QFile file( sfile);
354 if(file.exists()) 357 if(file.exists())
355 file.remove(); 358 file.remove();
356 Config cfg("opieftp"); 359 Config cfg("opieftp");
357 cfg.setGroup("Server"); 360 cfg.setGroup("Server");
358 cfg.writeEntry("currentServer", currentServerConfig); 361 cfg.writeEntry("currentServer", currentServerConfig);
359 362
360 exit(0); 363 exit(0);
361} 364}
362 365
363void OpieFtp::tabChanged(QWidget *) 366void OpieFtp::tabChanged(QWidget *)
364{ 367{
365 if (TabWidget->currentPageIndex() == 0) { 368 if (TabWidget->currentPageIndex() == 0) {
366 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath()); 369 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath());
367 tabMenu->setItemChecked(tabMenu->idAt(0),TRUE); 370 tabMenu->setItemChecked(tabMenu->idAt(0),TRUE);
368 tabMenu->setItemChecked(tabMenu->idAt(1),FALSE); 371 tabMenu->setItemChecked(tabMenu->idAt(1),FALSE);
369 tabMenu->setItemChecked(tabMenu->idAt(2),FALSE); 372 tabMenu->setItemChecked(tabMenu->idAt(2),FALSE);
370 if(cdUpButton->isHidden()) 373 if(cdUpButton->isHidden())
371 cdUpButton->show(); 374 cdUpButton->show();
372 if(homeButton->isHidden()) 375 if(homeButton->isHidden())
373 homeButton->show(); 376 homeButton->show();
374 377
375 } 378 }
376 if (TabWidget->currentPageIndex() == 1) { 379 if (TabWidget->currentPageIndex() == 1) {
377 currentPathCombo->lineEdit()->setText( currentRemoteDir ); 380 currentPathCombo->lineEdit()->setText( currentRemoteDir );
378 tabMenu->setItemChecked(tabMenu->idAt(1),TRUE); 381 tabMenu->setItemChecked(tabMenu->idAt(1),TRUE);
379 tabMenu->setItemChecked(tabMenu->idAt(0),FALSE); 382 tabMenu->setItemChecked(tabMenu->idAt(0),FALSE);
380 tabMenu->setItemChecked(tabMenu->idAt(2),FALSE); 383 tabMenu->setItemChecked(tabMenu->idAt(2),FALSE);
381 if(cdUpButton->isHidden()) 384 if(cdUpButton->isHidden())
382 cdUpButton->show(); 385 cdUpButton->show();
383 homeButton->hide(); 386 homeButton->hide();
384 387
385 } 388 }
386 if (TabWidget->currentPageIndex() == 2) { 389 if (TabWidget->currentPageIndex() == 2) {
387 tabMenu->setItemChecked(tabMenu->idAt(2),TRUE); 390 tabMenu->setItemChecked(tabMenu->idAt(2),TRUE);
388 tabMenu->setItemChecked(tabMenu->idAt(0),FALSE); 391 tabMenu->setItemChecked(tabMenu->idAt(0),FALSE);
389 tabMenu->setItemChecked(tabMenu->idAt(1),FALSE); 392 tabMenu->setItemChecked(tabMenu->idAt(1),FALSE);
390 cdUpButton->hide(); 393 cdUpButton->hide();
391 homeButton->hide(); 394 homeButton->hide();
392 } 395 }
393} 396}
394 397
395void OpieFtp::newConnection() 398void OpieFtp::newConnection()
396{ 399{
397 UsernameComboBox->lineEdit()->setText(""); 400 UsernameComboBox->lineEdit()->setText("");
398 PasswordEdit->setText( "" ); 401 PasswordEdit->setText( "" );
399 ServerComboBox->lineEdit()->setText( ""); 402 ServerComboBox->lineEdit()->setText( "");
400 remotePath->setText( currentRemoteDir = "/"); 403 remotePath->setText( currentRemoteDir = "/");
401 PortSpinBox->setValue( 21); 404 PortSpinBox->setValue( 21);
402 TabWidget->setCurrentPage(2); 405 TabWidget->setCurrentPage(2);
403} 406}
404 407
405void OpieFtp::serverComboEdited(const QString & ) 408void OpieFtp::serverComboEdited(const QString & )
406{ 409{
407// if( ServerComboBox->text(currentServerConfig) != edit /*edit.isEmpty() */) { 410// if( ServerComboBox->text(currentServerConfig) != edit /*edit.isEmpty() */) {
408// qDebug("ServerComboEdited"); 411// odebug << "ServerComboEdited" << oendl;
409// // currentServerConfig = -1; 412// // currentServerConfig = -1;
410// } 413// }
411} 414}
412 415
413void OpieFtp::UsernameComboBoxEdited(const QString &) { 416void OpieFtp::UsernameComboBoxEdited(const QString &) {
414// currentServerConfig = -1; 417// currentServerConfig = -1;
415} 418}
416 419
417void OpieFtp::PasswordEditEdited(const QString & ) { 420void OpieFtp::PasswordEditEdited(const QString & ) {
418// currentServerConfig = -1; 421// currentServerConfig = -1;
419} 422}
420 423
421void OpieFtp::connectorBtnToggled(bool On) 424void OpieFtp::connectorBtnToggled(bool On)
422{ 425{
423 if(On) { 426 if(On) {
424 connector(); 427 connector();
425 } else { 428 } else {
426 disConnector(); 429 disConnector();
427 } 430 }
428 431
429} 432}
430 433
431void OpieFtp::connector() 434void OpieFtp::connector()
432{ 435{
433// QCopEnvelope ( "QPE/System", "busy()" ); 436// QCopEnvelope ( "QPE/System", "busy()" );
434// qApp->processEvents(); 437// qApp->processEvents();
435 currentRemoteDir=remotePath->text(); 438 currentRemoteDir=remotePath->text();
436 439
437 if( ServerComboBox->currentText().isEmpty()) { 440 if( ServerComboBox->currentText().isEmpty()) {
438 441
439 QMessageBox::warning(this,tr("Ftp"),tr("Please set the server info"),tr("Ok"),0,0); 442 QMessageBox::warning(this,tr("Ftp"),tr("Please set the server info"),tr("Ok"),0,0);
440 TabWidget->setCurrentPage(2); 443 TabWidget->setCurrentPage(2);
441 ServerComboBox->setFocus(); 444 ServerComboBox->setFocus();
442 connectServerBtn->setOn(FALSE); 445 connectServerBtn->setOn(FALSE);
443 connectServerBtn->setText( tr("Connect")); 446 connectServerBtn->setText( tr("Connect"));
444 return; 447 return;
445 } 448 }
446 449
447 FtpInit(); 450 FtpInit();
448 451
449 TabWidget->setCurrentPage(1); 452 TabWidget->setCurrentPage(1);
450 QString ftp_host = ServerComboBox->currentText(); 453 QString ftp_host = ServerComboBox->currentText();
451 QString ftp_user = UsernameComboBox->currentText(); 454 QString ftp_user = UsernameComboBox->currentText();
452 QString ftp_pass = PasswordEdit->text(); 455 QString ftp_pass = PasswordEdit->text();
453 QString port=PortSpinBox->cleanText(); 456 QString port=PortSpinBox->cleanText();
454 port.stripWhiteSpace(); 457 port.stripWhiteSpace();
455 458
456 Config cfg("opieftp"); 459 Config cfg("opieftp");
457 cfg.setGroup("Server"); 460 cfg.setGroup("Server");
458// int current=cfg.readNumEntry("currentServer", 1); 461// int current=cfg.readNumEntry("currentServer", 1);
459 462
460// if(ftp_host!= cfg.readEntry(QString::number( current))) 463// if(ftp_host!= cfg.readEntry(QString::number( current)))
461// currentServerConfig=-1; 464// currentServerConfig=-1;
462// cfg.setGroup(QString::number(current)); 465// cfg.setGroup(QString::number(current));
463// if( ftp_user != cfg.readEntry("Username")) 466// if( ftp_user != cfg.readEntry("Username"))
464// currentServerConfig=-1; 467// currentServerConfig=-1;
465// if(ftp_pass != cfg.readEntry(cfg.readEntry("Username"))) 468// if(ftp_pass != cfg.readEntry(cfg.readEntry("Username")))
466// currentServerConfig=-1; 469// currentServerConfig=-1;
467 470
468 471
469 if(ftp_host.find("ftp://",0, TRUE) != -1 ) 472 if(ftp_host.find("ftp://",0, TRUE) != -1 )
470 ftp_host=ftp_host.right(ftp_host.length()-6); 473 ftp_host=ftp_host.right(ftp_host.length()-6);
471 ftp_host+=":"+port; 474 ftp_host+=":"+port;
472 475
473 if (!FtpConnect( ftp_host.latin1(), &conn)) { 476 if (!FtpConnect( ftp_host.latin1(), &conn)) {
474 QMessageBox::message(tr("Note"),tr("Unable to connect to\n")+ftp_host); 477 QMessageBox::message(tr("Note"),tr("Unable to connect to\n")+ftp_host);
475 connectServerBtn->setOn(FALSE); 478 connectServerBtn->setOn(FALSE);
476 connectServerBtn->setText( tr("Connect")); 479 connectServerBtn->setText( tr("Connect"));
477 return ; 480 return ;
478 } 481 }
479 482
480 if (!FtpLogin( ftp_user.latin1(), ftp_pass.latin1(),conn )) { 483 if (!FtpLogin( ftp_user.latin1(), ftp_pass.latin1(),conn )) {
481 QString msg; 484 QString msg;
482 msg.sprintf(tr("Unable to log in\n")+"%s",FtpLastResponse(conn)); 485 msg.sprintf(tr("Unable to log in\n")+"%s",FtpLastResponse(conn));
483 msg.replace(QRegExp(":"),"\n"); 486 msg.replace(QRegExp(":"),"\n");
484 QMessageBox::message(tr("Note"),msg); 487 QMessageBox::message(tr("Note"),msg);
485 if(conn) 488 if(conn)
486 FtpQuit(conn); 489 FtpQuit(conn);
487 connectServerBtn->setOn(FALSE); 490 connectServerBtn->setOn(FALSE);
488 connectServerBtn->setText( tr("Connect")); 491 connectServerBtn->setText( tr("Connect"));
489 return ; 492 return ;
490 } 493 }
491 494
492 remoteDirList("/") ; 495 remoteDirList("/") ;
493 setCaption(ftp_host); 496 setCaption(ftp_host);
494 if( currentServerConfig == -1) 497 if( currentServerConfig == -1)
495 writeConfig(); 498 writeConfig();
496 connectServerBtn->setText( tr("Disconnect")); 499 connectServerBtn->setText( tr("Disconnect"));
497// QCopEnvelope ( "QPE/System", "notBusy()" ); 500// QCopEnvelope ( "QPE/System", "notBusy()" );
498} 501}
499 502
500void OpieFtp::disConnector() 503void OpieFtp::disConnector()
501{ 504{
502 if(conn) 505 if(conn)
503 FtpQuit(conn); 506 FtpQuit(conn);
504 setCaption("OpieFtp"); 507 setCaption("OpieFtp");
505 currentRemoteDir="/"; 508 currentRemoteDir="/";
506 Remote_View->clear(); 509 Remote_View->clear();
507 connectServerBtn->setText( tr("Connect")); 510 connectServerBtn->setText( tr("Connect"));
508 connectServerBtn->setOn(FALSE); 511 connectServerBtn->setOn(FALSE);
509 setCaption("OpieFtp"); 512 setCaption("OpieFtp");
510} 513}
511 514
512void OpieFtp::localUpload() 515void OpieFtp::localUpload()
513{ 516{
514 int fsz; 517 int fsz;
515// QCopEnvelope ( "QPE/System", "busy()" ); 518// QCopEnvelope ( "QPE/System", "busy()" );
516// qApp->processEvents(); 519// qApp->processEvents();
517 QList<QListViewItem> * getSelectedItems( QListView * Local_View ); 520 QList<QListViewItem> * getSelectedItems( QListView * Local_View );
518 QListViewItemIterator it( Local_View ); 521 QListViewItemIterator it( Local_View );
519 for ( ; it.current(); ++it ) { 522 for ( ; it.current(); ++it ) {
520 if ( it.current()->isSelected() ) { 523 if ( it.current()->isSelected() ) {
521 QString strItem = it.current()->text(0); 524 QString strItem = it.current()->text(0);
522 QString localFile = currentDir.canonicalPath()+"/"+strItem; 525 QString localFile = currentDir.canonicalPath()+"/"+strItem;
523 QString remoteFile= currentRemoteDir+strItem; 526 QString remoteFile= currentRemoteDir+strItem;
524 QFileInfo fi(localFile); 527 QFileInfo fi(localFile);
525 if( !fi.isDir()) { 528 if( !fi.isDir()) {
526 fsz=fi.size(); 529 fsz=fi.size();
527 ProgressBar->setTotalSteps(fsz); 530 ProgressBar->setTotalSteps(fsz);
528 531
529 FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn); 532 FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn);
530 FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn); 533 FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn);
531 FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn); 534 FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn);
532 FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn); 535 FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn);
533 qDebug("Put: %s, %s",localFile.latin1(),remoteFile.latin1()); 536 odebug << "Put: " << localFile.latin1() << ", " << remoteFile.latin1() << "" << oendl;
534 537
535 if( !FtpPut( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) { 538 if( !FtpPut( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) {
536 QString msg; 539 QString msg;
537 msg.sprintf(tr("Unable to upload\n")+"%s",FtpLastResponse(conn)); 540 msg.sprintf(tr("Unable to upload\n")+"%s",FtpLastResponse(conn));
538 msg.replace(QRegExp(":"),"\n"); 541 msg.replace(QRegExp(":"),"\n");
539 QMessageBox::message(tr("Note"),msg); 542 QMessageBox::message(tr("Note"),msg);
540 } 543 }
541 } else { 544 } else {
542 QMessageBox::message(tr("Note"),tr("Cannot upload directories")); 545 QMessageBox::message(tr("Note"),tr("Cannot upload directories"));
543 } 546 }
544 ProgressBar->reset(); 547 ProgressBar->reset();
545 nullifyCallBack(); 548 nullifyCallBack();
546 it.current()->setSelected(FALSE); 549 it.current()->setSelected(FALSE);
547 } //end currentSelected 550 } //end currentSelected
548 } 551 }
549 for ( ; it.current(); ++it ) { 552 for ( ; it.current(); ++it ) {
550 Local_View->clearSelection(); 553 Local_View->clearSelection();
551 } 554 }
552 Local_View->clearFocus(); 555 Local_View->clearFocus();
553 TabWidget->setCurrentPage(1); 556 TabWidget->setCurrentPage(1);
554 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 557 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
555// QCopEnvelope ( "QPE/System", "notBusy()" ); 558// QCopEnvelope ( "QPE/System", "notBusy()" );
556} 559}
557 560
558void OpieFtp::nullifyCallBack() 561void OpieFtp::nullifyCallBack()
559{ 562{
560 FtpOptions(FTPLIB_CALLBACK, 0, conn); 563 FtpOptions(FTPLIB_CALLBACK, 0, conn);
561 FtpOptions(FTPLIB_IDLETIME, 0, conn); 564 FtpOptions(FTPLIB_IDLETIME, 0, conn);
562 FtpOptions(FTPLIB_CALLBACKARG, 0, conn); 565 FtpOptions(FTPLIB_CALLBACKARG, 0, conn);
563 FtpOptions(FTPLIB_CALLBACKBYTES, 0, conn); 566 FtpOptions(FTPLIB_CALLBACKBYTES, 0, conn);
564} 567}
565 568
566void OpieFtp::remoteDownload() 569void OpieFtp::remoteDownload()
567{ 570{
568// qApp->processEvents(); 571// qApp->processEvents();
569 int fsz; 572 int fsz;
570// QCopEnvelope ( "QPE/System", "busy()" ); 573// QCopEnvelope ( "QPE/System", "busy()" );
571 574
572 QList<QListViewItem> * getSelectedItems( QListView * Remote_View ); 575 QList<QListViewItem> * getSelectedItems( QListView * Remote_View );
573 QListViewItemIterator it( Remote_View ); 576 QListViewItemIterator it( Remote_View );
574 for ( ; it.current(); ++it ) { 577 for ( ; it.current(); ++it ) {
575 if ( it.current()->isSelected() ) { 578 if ( it.current()->isSelected() ) {
576 QString strItem = it.current()->text(0); 579 QString strItem = it.current()->text(0);
577// strItem=strItem.right(strItem.length()-1); 580// strItem=strItem.right(strItem.length()-1);
578 QString localFile = currentDir.canonicalPath(); 581 QString localFile = currentDir.canonicalPath();
579 if(localFile.right(1).find("/",0,TRUE) == -1) 582 if(localFile.right(1).find("/",0,TRUE) == -1)
580 localFile += "/"; 583 localFile += "/";
581 localFile += strItem; 584 localFile += strItem;
582// QString localFile = currentDir.canonicalPath()+"/"+strItem; 585// QString localFile = currentDir.canonicalPath()+"/"+strItem;
583 QString remoteFile= currentRemoteDir+strItem; 586 QString remoteFile= currentRemoteDir+strItem;
584 if (!FtpSize( remoteFile.latin1(), &fsz, FTPLIB_ASCII, conn)) 587 if (!FtpSize( remoteFile.latin1(), &fsz, FTPLIB_ASCII, conn))
585 fsz = 0; 588 fsz = 0;
586 QString temp; 589 QString temp;
587 temp.sprintf( remoteFile+" "+" %dkb", fsz); 590 temp.sprintf( remoteFile+" "+" %dkb", fsz);
588 591
589 ProgressBar->setTotalSteps(fsz); 592 ProgressBar->setTotalSteps(fsz);
590 FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn); 593 FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn);
591 FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn); 594 FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn);
592 FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn); 595 FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn);
593 FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn); 596 FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn);
594 qDebug("Get: %s, %s",localFile.latin1(),remoteFile.latin1()); 597 odebug << "Get: " << localFile.latin1() << ", " << remoteFile.latin1() << "" << oendl;
595 598
596 if(!FtpGet( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) { 599 if(!FtpGet( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) {
597 QString msg; 600 QString msg;
598 msg.sprintf(tr("Unable to download \n")+"%s",FtpLastResponse(conn)); 601 msg.sprintf(tr("Unable to download \n")+"%s",FtpLastResponse(conn));
599 msg.replace(QRegExp(":"),"\n"); 602 msg.replace(QRegExp(":"),"\n");
600 QMessageBox::message(tr("Note"),msg); 603 QMessageBox::message(tr("Note"),msg);
601 } 604 }
602 ProgressBar->reset(); 605 ProgressBar->reset();
603 nullifyCallBack(); 606 nullifyCallBack();
604 it.current()->setSelected(FALSE); 607 it.current()->setSelected(FALSE);
605 } 608 }
606 } 609 }
607 for ( ; it.current(); ++it ) { 610 for ( ; it.current(); ++it ) {
608 Remote_View->clearSelection(); 611 Remote_View->clearSelection();
609 } 612 }
610 Remote_View->setFocus(); 613 Remote_View->setFocus();
611 TabWidget->setCurrentPage(0); 614 TabWidget->setCurrentPage(0);
612 populateLocalView(); 615 populateLocalView();
613// QCopEnvelope ( "QPE/System", "notBusy()" ); 616// QCopEnvelope ( "QPE/System", "notBusy()" );
614} 617}
615 618
616bool OpieFtp::remoteDirList(const QString &dir) 619bool OpieFtp::remoteDirList(const QString &dir)
617{ 620{
618 QString tmp = QDir::homeDirPath(); 621 QString tmp = QDir::homeDirPath();
619 if(tmp.right(1) != "/") 622 if(tmp.right(1) != "/")
620 tmp+="/._temp"; 623 tmp+="/._temp";
621 else 624 else
622 tmp+="._temp"; 625 tmp+="._temp";
623// qDebug("Listing remote dir "+tmp); 626// odebug << "Listing remote dir "+tmp << oendl;
624// QCopEnvelope ( "QPE/System", "busy()" ); 627// QCopEnvelope ( "QPE/System", "busy()" );
625 if (!FtpDir( tmp.latin1(), dir.latin1(), conn) ) { 628 if (!FtpDir( tmp.latin1(), dir.latin1(), conn) ) {
626 QString msg; 629 QString msg;
627 msg.sprintf(tr("Unable to list the directory\n")+dir+"\n%s",FtpLastResponse(conn) ); 630 msg.sprintf(tr("Unable to list the directory\n")+dir+"\n%s",FtpLastResponse(conn) );
628 msg.replace(QRegExp(":"),"\n"); 631 msg.replace(QRegExp(":"),"\n");
629 QMessageBox::message(tr("Note"),msg); 632 QMessageBox::message(tr("Note"),msg);
630 return false; 633 return false;
631 } 634 }
632 populateRemoteView() ; 635 populateRemoteView() ;
633// QCopEnvelope ( "QPE/System", "notBusy()" ); 636// QCopEnvelope ( "QPE/System", "notBusy()" );
634 return true; 637 return true;
635} 638}
636 639
637bool OpieFtp::remoteChDir(const QString &dir) 640bool OpieFtp::remoteChDir(const QString &dir)
638{ 641{
639// QCopEnvelope ( "QPE/System", "busy()" ); 642// QCopEnvelope ( "QPE/System", "busy()" );
640 if (!FtpChdir( dir.latin1(), conn )) { 643 if (!FtpChdir( dir.latin1(), conn )) {
641 QString msg; 644 QString msg;
642 msg.sprintf(tr("Unable to change directories\n")+dir+"\n%s",FtpLastResponse(conn)); 645 msg.sprintf(tr("Unable to change directories\n")+dir+"\n%s",FtpLastResponse(conn));
643 msg.replace(QRegExp(":"),"\n"); 646 msg.replace(QRegExp(":"),"\n");
644 QMessageBox::message(tr("Note"),msg); 647 QMessageBox::message(tr("Note"),msg);
645// qDebug(msg); 648// odebug << msg << oendl;
646// QCopEnvelope ( "QPE/System", "notBusy()" ); 649// QCopEnvelope ( "QPE/System", "notBusy()" );
647 return FALSE; 650 return FALSE;
648 } 651 }
649// QCopEnvelope ( "QPE/System", "notBusy()" ); 652// QCopEnvelope ( "QPE/System", "notBusy()" );
650 return TRUE; 653 return TRUE;
651} 654}
652 655
653void OpieFtp::populateLocalView() 656void OpieFtp::populateLocalView()
654{ 657{
655 Local_View->clear(); 658 Local_View->clear();
656 currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 659 currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
657 currentDir.setMatchAllDirs(TRUE); 660 currentDir.setMatchAllDirs(TRUE);
658 currentDir.setNameFilter(filterStr); 661 currentDir.setNameFilter(filterStr);
659 QString fileL, fileS, fileDate; 662 QString fileL, fileS, fileDate;
660 bool isDir=FALSE; 663 bool isDir=FALSE;
661 const QFileInfoList *list = currentDir.entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/); 664 const QFileInfoList *list = currentDir.entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/);
662 QFileInfoListIterator it(*list); 665 QFileInfoListIterator it(*list);
663 QFileInfo *fi; 666 QFileInfo *fi;
664 while ( (fi=it.current()) ) { 667 while ( (fi=it.current()) ) {
665 if (fi->isSymLink() ){ 668 if (fi->isSymLink() ){
666 QString symLink=fi->readLink(); 669 QString symLink=fi->readLink();
667 qDebug("Symlink detected "+symLink); 670 odebug << "Symlink detected "+symLink << oendl;
668 QFileInfo sym( symLink); 671 QFileInfo sym( symLink);
669 fileS.sprintf( "%10i", sym.size() ); 672 fileS.sprintf( "%10i", sym.size() );
670 fileL.sprintf( "%s -> %s", fi->fileName().data(),sym.absFilePath().data() ); 673 fileL.sprintf( "%s -> %s", fi->fileName().data(),sym.absFilePath().data() );
671 fileDate = sym.lastModified().toString(); 674 fileDate = sym.lastModified().toString();
672 } else { 675 } else {
673 qDebug("Not a dir: "+currentDir.canonicalPath()+fileL); 676 odebug << "Not a dir: "+currentDir.canonicalPath()+fileL << oendl;
674 fileS.sprintf( "%10i", fi->size() ); 677 fileS.sprintf( "%10i", fi->size() );
675 fileL.sprintf( "%s",fi->fileName().data() ); 678 fileL.sprintf( "%s",fi->fileName().data() );
676 fileDate= fi->lastModified().toString(); 679 fileDate= fi->lastModified().toString();
677 if( QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+fileL)).exists() ) { 680 if( QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+fileL)).exists() ) {
678 fileL+="/"; 681 fileL+="/";
679 isDir=TRUE; 682 isDir=TRUE;
680 qDebug( fileL); 683 odebug << fileL << oendl;
681 } 684 }
682 } 685 }
683 if(fileL !="./" && fi->exists()) { 686 if(fileL !="./" && fi->exists()) {
684 item = new QListViewItem( Local_View,fileL, fileDate, fileS ); 687 item = new QListViewItem( Local_View,fileL, fileDate, fileS );
685 QPixmap pm; 688 QPixmap pm;
686 689
687 if(isDir || fileL.find("/",0,TRUE) != -1) { 690 if(isDir || fileL.find("/",0,TRUE) != -1) {
688 if( !QDir( fi->filePath() ).isReadable()) 691 if( !QDir( fi->filePath() ).isReadable())
689 pm = Resource::loadPixmap( "lockedfolder" ); 692 pm = Resource::loadPixmap( "lockedfolder" );
690 else 693 else
691 pm= Resource::loadPixmap( "folder" ); 694 pm= Resource::loadPixmap( "folder" );
692 item->setPixmap( 0,pm ); 695 item->setPixmap( 0,pm );
693 } else { 696 } else {
694 if( !fi->isReadable() ) 697 if( !fi->isReadable() )
695 pm = Resource::loadPixmap( "locked" ); 698 pm = Resource::loadPixmap( "locked" );
696 else { 699 else {
697 MimeType mt(fi->filePath()); 700 MimeType mt(fi->filePath());
698 pm=mt.pixmap(); //sets the correct pixmap for mimetype 701 pm=mt.pixmap(); //sets the correct pixmap for mimetype
699 if(pm.isNull()) 702 if(pm.isNull())
700 pm = unknownXpm; 703 pm = unknownXpm;
701 } 704 }
702 } 705 }
703 if( fileL.find("->",0,TRUE) != -1) { 706 if( fileL.find("->",0,TRUE) != -1) {
704 // overlay link image 707 // overlay link image
705 pm= Resource::loadPixmap( "folder" ); 708 pm= Resource::loadPixmap( "folder" );
706 QPixmap lnk = Resource::loadPixmap( "opie/symlink" ); 709 QPixmap lnk = Resource::loadPixmap( "opie/symlink" );
707 QPainter painter( &pm ); 710 QPainter painter( &pm );
708 painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk ); 711 painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk );
709 pm.setMask( pm.createHeuristicMask( FALSE ) ); 712 pm.setMask( pm.createHeuristicMask( FALSE ) );
710 } 713 }
711 item->setPixmap( 0,pm); 714 item->setPixmap( 0,pm);
712 } 715 }
713 isDir=FALSE; 716 isDir=FALSE;
714 ++it; 717 ++it;
715 } 718 }
716 Local_View->setSorting( 3,FALSE); 719 Local_View->setSorting( 3,FALSE);
717 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath() ); 720 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath() );
718 fillCombo( (const QString &)currentDir); 721 fillCombo( (const QString &)currentDir);
719} 722}
720 723
721bool OpieFtp::populateRemoteView( ) 724bool OpieFtp::populateRemoteView( )
722{ 725{
723// qDebug("populate remoteview"); 726// odebug << "populate remoteview" << oendl;
724 QString sfile=QDir::homeDirPath(); 727 QString sfile=QDir::homeDirPath();
725 if(sfile.right(1) != "/") 728 if(sfile.right(1) != "/")
726 sfile+="/._temp"; 729 sfile+="/._temp";
727 else 730 else
728 sfile+="._temp"; 731 sfile+="._temp";
729 QFile file( sfile); 732 QFile file( sfile);
730 Remote_View->clear(); 733 Remote_View->clear();
731 QString s, File_Name; 734 QString s, File_Name;
732 QListViewItem *itemDir=NULL, *itemFile=NULL; 735 QListViewItem *itemDir=NULL, *itemFile=NULL;
733 QRegExp monthRe(" [JFMASOND][eapuecoe][brynlgptvc] [ 0-9][0-9] [ 0-9][0-9][:0-9][0-9][0-9] "); 736 QRegExp monthRe(" [JFMASOND][eapuecoe][brynlgptvc] [ 0-9][0-9] [ 0-9][0-9][:0-9][0-9][0-9] ");
734 QString fileL, fileS, fileDate; 737 QString fileL, fileS, fileDate;
735 if ( file.open(IO_ReadOnly)) { 738 if ( file.open(IO_ReadOnly)) {
736 QTextStream t( &file ); // use a text stream 739 QTextStream t( &file ); // use a text stream
737 while ( !t.eof()) { 740 while ( !t.eof()) {
738 s = t.readLine(); 741 s = t.readLine();
739 742
740 if(s.find("total",0,TRUE) == 0) 743 if(s.find("total",0,TRUE) == 0)
741 continue; 744 continue;
742 745
743 int len, month = monthRe.match(s, 0, &len); 746 int len, month = monthRe.match(s, 0, &len);
744 fileDate = s.mid(month + 1, len - 2); // minus spaces 747 fileDate = s.mid(month + 1, len - 2); // minus spaces
745 fileL = s.right(s.length() - month - len); 748 fileL = s.right(s.length() - month - len);
746 if(s.left(1) == "d") 749 if(s.left(1) == "d")
747 fileL = fileL+"/"; 750 fileL = fileL+"/";
748 fileS = s.mid(month - 8, 8); // FIXME 751 fileS = s.mid(month - 8, 8); // FIXME
749 fileS = fileS.stripWhiteSpace(); 752 fileS = fileS.stripWhiteSpace();
750 753
751 if(s.left(1) == "d" || fileL.find("/",0,TRUE) != -1) { 754 if(s.left(1) == "d" || fileL.find("/",0,TRUE) != -1) {
752 QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"d"); 755 QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"d");
753 item->setPixmap( 0, Resource::loadPixmap( "folder" )); 756 item->setPixmap( 0, Resource::loadPixmap( "folder" ));
754// if(itemDir) 757// if(itemDir)
755 item->moveItem(itemDir); 758 item->moveItem(itemDir);
756 itemDir=item; 759 itemDir=item;
757 } else { 760 } else {
758 QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"f"); 761 QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"f");
759 item->setPixmap( 0, Resource::loadPixmap( "fileopen" )); 762 item->setPixmap( 0, Resource::loadPixmap( "fileopen" ));
760// if(itemFile) 763// if(itemFile)
761 item->moveItem(itemDir); 764 item->moveItem(itemDir);
762 item->moveItem(itemFile); 765 item->moveItem(itemFile);
763 itemFile=item; 766 itemFile=item;
764 } 767 }
765 } 768 }
766 QListViewItem * item1 = new QListViewItem( Remote_View, "../"); 769 QListViewItem * item1 = new QListViewItem( Remote_View, "../");
767 item1->setPixmap( 0, Resource::loadPixmap( "folder" )); 770 item1->setPixmap( 0, Resource::loadPixmap( "folder" ));
768 file.close(); 771 file.close();
769 if( file.exists()) 772 if( file.exists())
770 file. remove(); 773 file. remove();
771 } else 774 } else
772 qDebug("temp file not opened successfully "+sfile); 775 odebug << "temp file not opened successfully "+sfile << oendl;
773 Remote_View->setSorting( 4,TRUE); 776 Remote_View->setSorting( 4,TRUE);
774 return true; 777 return true;
775} 778}
776 779
777void OpieFtp::remoteListClicked(QListViewItem *selectedItem) 780void OpieFtp::remoteListClicked(QListViewItem *selectedItem)
778{ 781{
779 if( selectedItem) { 782 if( selectedItem) {
780 // if(selectedItem!= NULL) { 783 // if(selectedItem!= NULL) {
781// QCopEnvelope ( "QPE/System", "busy()" ); 784// QCopEnvelope ( "QPE/System", "busy()" );
782 QString oldRemoteCurrentDir = currentRemoteDir; 785 QString oldRemoteCurrentDir = currentRemoteDir;
783 QString strItem=selectedItem->text(0); 786 QString strItem=selectedItem->text(0);
784 strItem=strItem.simplifyWhiteSpace(); 787 strItem=strItem.simplifyWhiteSpace();
785 if(strItem == "../") { // the user wants to go ^ 788 if(strItem == "../") { // the user wants to go ^
786 if( FtpCDUp( conn) == 0) { 789 if( FtpCDUp( conn) == 0) {
787 QString msg; 790 QString msg;
788 msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn)); 791 msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn));
789 msg.replace(QRegExp(":"),"\n"); 792 msg.replace(QRegExp(":"),"\n");
790 QMessageBox::message(tr("Note"),msg); 793 QMessageBox::message(tr("Note"),msg);
791// qDebug(msg); 794// odebug << msg << oendl;
792 } 795 }
793 char path[256]; 796 char path[256];
794 if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string 797 if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string
795 QString msg; 798 QString msg;
796 msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn)); 799 msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn));
797 msg.replace(QRegExp(":"),"\n"); 800 msg.replace(QRegExp(":"),"\n");
798 QMessageBox::message(tr("Note"),msg); 801 QMessageBox::message(tr("Note"),msg);
799// qDebug(msg); 802// odebug << msg << oendl;
800 } 803 }
801 currentRemoteDir=path; 804 currentRemoteDir=path;
802 } else { 805 } else {
803 if(strItem.find("->",0,TRUE) != -1) { //symlink on some servers 806 if(strItem.find("->",0,TRUE) != -1) { //symlink on some servers
804 strItem=strItem.right( strItem.length() - strItem.find("->",0,TRUE) - 2 ); 807 strItem=strItem.right( strItem.length() - strItem.find("->",0,TRUE) - 2 );
805 strItem = strItem.stripWhiteSpace(); 808 strItem = strItem.stripWhiteSpace();
806 currentRemoteDir = strItem; 809 currentRemoteDir = strItem;
807 if( !remoteChDir( (const QString &)strItem)) { 810 if( !remoteChDir( (const QString &)strItem)) {
808 currentRemoteDir = oldRemoteCurrentDir; 811 currentRemoteDir = oldRemoteCurrentDir;
809 strItem=""; 812 strItem="";
810// qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir); 813// odebug << "RemoteCurrentDir1 "+oldRemoteCurrentDir << oendl;
811 } 814 }
812 } else if(strItem.find("/",0,TRUE) != -1) { // this is a directory 815 } else if(strItem.find("/",0,TRUE) != -1) { // this is a directory
813 if( !remoteChDir( (const QString &)currentRemoteDir + strItem)) { 816 if( !remoteChDir( (const QString &)currentRemoteDir + strItem)) {
814 currentRemoteDir = oldRemoteCurrentDir; 817 currentRemoteDir = oldRemoteCurrentDir;
815 strItem=""; 818 strItem="";
816// qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir); 819// odebug << "RemoteCurrentDir1 "+oldRemoteCurrentDir << oendl;
817 820
818 } else { 821 } else {
819 currentRemoteDir = currentRemoteDir+strItem; 822 currentRemoteDir = currentRemoteDir+strItem;
820 } 823 }
821 } else { 824 } else {
822// QCopEnvelope ( "QPE/System", "notBusy()" ); 825// QCopEnvelope ( "QPE/System", "notBusy()" );
823 return; 826 return;
824 } 827 }
825 } 828 }
826 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 829 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
827 if(currentRemoteDir.right(1) !="/") 830 if(currentRemoteDir.right(1) !="/")
828 currentRemoteDir +="/"; 831 currentRemoteDir +="/";
829 currentPathCombo->lineEdit()->setText( currentRemoteDir); 832 currentPathCombo->lineEdit()->setText( currentRemoteDir);
830 fillRemoteCombo( (const QString &)currentRemoteDir); 833 fillRemoteCombo( (const QString &)currentRemoteDir);
831// QCopEnvelope ( "QPE/System", "notBusy()" ); 834// QCopEnvelope ( "QPE/System", "notBusy()" );
832 Remote_View->ensureItemVisible(Remote_View->firstChild()); 835 Remote_View->ensureItemVisible(Remote_View->firstChild());
833 836
834 } 837 }
835} 838}
836 839
837void OpieFtp::localListClicked(QListViewItem *selectedItem) 840void OpieFtp::localListClicked(QListViewItem *selectedItem)
838{ 841{
839 if(selectedItem!= NULL) { 842 if(selectedItem!= NULL) {
840 843
841 QString strItem=selectedItem->text(0); 844 QString strItem=selectedItem->text(0);
842 QString strSize=selectedItem->text(1); 845 QString strSize=selectedItem->text(1);
843 strSize=strSize.stripWhiteSpace(); 846 strSize=strSize.stripWhiteSpace();
844 if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) { //if symlink 847 if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) { //if symlink
845 // is symlink 848 // is symlink
846 QString strItem2 = strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4); 849 QString strItem2 = strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4);
847 if(QDir(strItem2).exists() ) { 850 if(QDir(strItem2).exists() ) {
848 currentDir.cd(strItem2, TRUE); 851 currentDir.cd(strItem2, TRUE);
849 populateLocalView(); 852 populateLocalView();
850 } 853 }
851 } else { // not a symlink 854 } else { // not a symlink
852 if(strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) { 855 if(strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) {
853 856
854 if(QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem)).exists() ) { 857 if(QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem)).exists() ) {
855 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); 858 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem);
856 currentDir.cd(strItem,FALSE); 859 currentDir.cd(strItem,FALSE);
857 populateLocalView(); 860 populateLocalView();
858 } else { 861 } else {
859 currentDir.cdUp(); 862 currentDir.cdUp();
860 populateLocalView(); 863 populateLocalView();
861 } 864 }
862 if(QDir(strItem).exists()){ 865 if(QDir(strItem).exists()){
863 currentDir.cd(strItem, TRUE); 866 currentDir.cd(strItem, TRUE);
864 populateLocalView(); 867 populateLocalView();
865 } 868 }
866 } else { 869 } else {
867 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); 870 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem);
868 if( QFile::exists(strItem ) ) { 871 if( QFile::exists(strItem ) ) {
869 // qDebug("upload "+strItem); 872 // odebug << "upload "+strItem << oendl;
870 return; 873 return;
871 } 874 }
872 } //end not symlink 875 } //end not symlink
873 chdir(strItem.latin1()); 876 chdir(strItem.latin1());
874 } 877 }
875 Local_View->ensureItemVisible(Local_View->firstChild()); 878 Local_View->ensureItemVisible(Local_View->firstChild());
876 } 879 }
877} 880}
878 881
879void OpieFtp::doLocalCd() 882void OpieFtp::doLocalCd()
880{ 883{
881 localListClicked( Local_View->currentItem()); 884 localListClicked( Local_View->currentItem());
882} 885}
883 886
884void OpieFtp:: doRemoteCd() 887void OpieFtp:: doRemoteCd()
885{ 888{
886 remoteListClicked( Remote_View->currentItem()); 889 remoteListClicked( Remote_View->currentItem());
887 890
888} 891}
889 892
890void OpieFtp::showHidden() 893void OpieFtp::showHidden()
891{ 894{
892 if (!b) { 895 if (!b) {
893 currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 896 currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
894 localMenu->setItemChecked(localMenu->idAt(0),TRUE); 897 localMenu->setItemChecked(localMenu->idAt(0),TRUE);
895// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 898// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
896 b=TRUE; 899 b=TRUE;
897 900
898 } else { 901 } else {
899 currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 902 currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
900 localMenu->setItemChecked(localMenu->idAt(0),FALSE); 903 localMenu->setItemChecked(localMenu->idAt(0),FALSE);
901// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 904// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
902 b=FALSE; 905 b=FALSE;
903 } 906 }
904 populateLocalView(); 907 populateLocalView();
905} 908}
906 909
907void OpieFtp::ListPressed( int mouse, QListViewItem *item, const QPoint &, int) 910void OpieFtp::ListPressed( int mouse, QListViewItem *item, const QPoint &, int)
908{ 911{
909// if(item) 912// if(item)
910 if (mouse == 2) { 913 if (mouse == 2) {
911 showLocalMenu(item); 914 showLocalMenu(item);
912 } 915 }
913} 916}
914 917
915void OpieFtp::RemoteListPressed( int mouse, QListViewItem *item, const QPoint &, int ) 918void OpieFtp::RemoteListPressed( int mouse, QListViewItem *item, const QPoint &, int )
916{ 919{
917 if(mouse == 2) { 920 if(mouse == 2) {
918 showRemoteMenu(item); 921 showRemoteMenu(item);
919 } 922 }
920} 923}
921 924
922void OpieFtp::showRemoteMenu(QListViewItem * item) 925void OpieFtp::showRemoteMenu(QListViewItem * item)
923{ 926{
924 QPopupMenu * m;// = new QPopupMenu( Local_View ); 927 QPopupMenu * m;// = new QPopupMenu( Local_View );
925 m = new QPopupMenu(this); 928 m = new QPopupMenu(this);
926 if(item != NULL ) { 929 if(item != NULL ) {
927 if( item->text(0).find("/",0,TRUE) != -1) 930 if( item->text(0).find("/",0,TRUE) != -1)
928 m->insertItem( tr( "Change Directory" ), this, SLOT( doRemoteCd() )); 931 m->insertItem( tr( "Change Directory" ), this, SLOT( doRemoteCd() ));
929 else 932 else
930 m->insertItem( tr( "Download" ), this, SLOT( remoteDownload() )); 933 m->insertItem( tr( "Download" ), this, SLOT( remoteDownload() ));
931 } 934 }
932 m->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() )); 935 m->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() ));
933 m->insertItem( tr("Rescan"), this, SLOT( populateLocalView() )); 936 m->insertItem( tr("Rescan"), this, SLOT( populateLocalView() ));
934 m->insertItem( tr( "Rename" ), this, SLOT( remoteRename() )); 937 m->insertItem( tr( "Rename" ), this, SLOT( remoteRename() ));
935 m->insertSeparator(); 938 m->insertSeparator();
936 m->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() )); 939 m->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() ));
937 m->exec( QCursor::pos() ); 940 m->exec( QCursor::pos() );
938 delete m; 941 delete m;
939} 942}
940 943
941void OpieFtp::showLocalMenu(QListViewItem * item) 944void OpieFtp::showLocalMenu(QListViewItem * item)
942{ 945{
943 946
944 QPopupMenu *m; 947 QPopupMenu *m;
945 m = new QPopupMenu( this); 948 m = new QPopupMenu( this);
946 m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() )); 949 m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() ));
947 m->insertSeparator(); 950 m->insertSeparator();
948 if(item != NULL ) { 951 if(item != NULL ) {
949 if( item->text(0).find("/",0,TRUE) !=-1) 952 if( item->text(0).find("/",0,TRUE) !=-1)
950 m->insertItem( tr( "Change Directory" ), this, SLOT( doLocalCd() )); 953 m->insertItem( tr( "Change Directory" ), this, SLOT( doLocalCd() ));
951 else 954 else
952 m->insertItem( tr( "Upload" ), this, SLOT( localUpload() )); 955 m->insertItem( tr( "Upload" ), this, SLOT( localUpload() ));
953 } 956 }
954 m->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() )); 957 m->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() ));
955 m->insertItem( tr("Rescan"), this, SLOT( populateRemoteView() )); 958 m->insertItem( tr("Rescan"), this, SLOT( populateRemoteView() ));
956 m->insertItem( tr( "Rename" ), this, SLOT( localRename() )); 959 m->insertItem( tr( "Rename" ), this, SLOT( localRename() ));
957 m->insertSeparator(); 960 m->insertSeparator();
958 m->insertItem( tr( "Delete" ), this, SLOT( localDelete() )); 961 m->insertItem( tr( "Delete" ), this, SLOT( localDelete() ));
959 m->setCheckable(TRUE); 962 m->setCheckable(TRUE);
960 if (b) 963 if (b)
961 m->setItemChecked(m->idAt(0),TRUE); 964 m->setItemChecked(m->idAt(0),TRUE);
962 else 965 else
963 m->setItemChecked(m->idAt(0),FALSE); 966 m->setItemChecked(m->idAt(0),FALSE);
964 967
965 m->exec( QCursor::pos() ); 968 m->exec( QCursor::pos() );
@@ -1077,453 +1080,453 @@ void OpieFtp::remoteDelete()
1077 msg.sprintf(tr("Unable to delete file\n")+"%s",FtpLastResponse(conn)); 1080 msg.sprintf(tr("Unable to delete file\n")+"%s",FtpLastResponse(conn));
1078 msg.replace(QRegExp(":"),"\n"); 1081 msg.replace(QRegExp(":"),"\n");
1079 QMessageBox::message(tr("Note"),msg); 1082 QMessageBox::message(tr("Note"),msg);
1080 } 1083 }
1081 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1084 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1082 } 1085 }
1083 break; 1086 break;
1084 }; 1087 };
1085 } 1088 }
1086 } 1089 }
1087 } 1090 }
1088// QCopEnvelope ( "QPE/System", "notBusy()" ); 1091// QCopEnvelope ( "QPE/System", "notBusy()" );
1089} 1092}
1090 1093
1091void OpieFtp::remoteRename() 1094void OpieFtp::remoteRename()
1092{ 1095{
1093 QString curFile = Remote_View->currentItem()->text(0); 1096 QString curFile = Remote_View->currentItem()->text(0);
1094 InputDialog *fileDlg; 1097 InputDialog *fileDlg;
1095 fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0); 1098 fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0);
1096 fileDlg->setTextEdit((const QString &)curFile); 1099 fileDlg->setTextEdit((const QString &)curFile);
1097 fileDlg->exec(); 1100 fileDlg->exec();
1098 if( fileDlg->result() == 1 ) { 1101 if( fileDlg->result() == 1 ) {
1099 QString oldName = currentRemoteDir +"/"+ curFile; 1102 QString oldName = currentRemoteDir +"/"+ curFile;
1100 QString newName = currentRemoteDir +"/"+ fileDlg->LineEdit1->text();//+".playlist"; 1103 QString newName = currentRemoteDir +"/"+ fileDlg->LineEdit1->text();//+".playlist";
1101// QCopEnvelope ( "QPE/System", "busy()" ); 1104// QCopEnvelope ( "QPE/System", "busy()" );
1102 if(FtpRename( oldName.latin1(), newName.latin1(),conn) == 0) { 1105 if(FtpRename( oldName.latin1(), newName.latin1(),conn) == 0) {
1103 QString msg; 1106 QString msg;
1104 msg.sprintf(tr("Unable to rename file\n")+"%s",FtpLastResponse(conn)); 1107 msg.sprintf(tr("Unable to rename file\n")+"%s",FtpLastResponse(conn));
1105 msg.replace(QRegExp(":"),"\n"); 1108 msg.replace(QRegExp(":"),"\n");
1106 QMessageBox::message(tr("Note"),msg); 1109 QMessageBox::message(tr("Note"),msg);
1107 } 1110 }
1108// QCopEnvelope ( "QPE/System", "notBusy()" ); 1111// QCopEnvelope ( "QPE/System", "notBusy()" );
1109 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1112 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1110 } 1113 }
1111} 1114}
1112 1115
1113void OpieFtp::localRename() 1116void OpieFtp::localRename()
1114{ 1117{
1115 QString curFile = Local_View->currentItem()->text(0); 1118 QString curFile = Local_View->currentItem()->text(0);
1116 InputDialog *fileDlg; 1119 InputDialog *fileDlg;
1117 fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0); 1120 fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0);
1118 fileDlg->setTextEdit((const QString &)curFile); 1121 fileDlg->setTextEdit((const QString &)curFile);
1119 fileDlg->exec(); 1122 fileDlg->exec();
1120 if( fileDlg->result() == 1 ) { 1123 if( fileDlg->result() == 1 ) {
1121 QString oldname = currentDir.canonicalPath() + "/" + curFile; 1124 QString oldname = currentDir.canonicalPath() + "/" + curFile;
1122 QString newName = currentDir.canonicalPath() + "/" + fileDlg->LineEdit1->text();//+".playlist"; 1125 QString newName = currentDir.canonicalPath() + "/" + fileDlg->LineEdit1->text();//+".playlist";
1123 if( rename(oldname.latin1(), newName.latin1())== -1) 1126 if( rename(oldname.latin1(), newName.latin1())== -1)
1124 QMessageBox::message(tr("Note"),tr("Could not rename")); 1127 QMessageBox::message(tr("Note"),tr("Could not rename"));
1125 } 1128 }
1126 populateLocalView(); 1129 populateLocalView();
1127} 1130}
1128 1131
1129void OpieFtp::currentPathComboActivated(const QString & currentPath) { 1132void OpieFtp::currentPathComboActivated(const QString & currentPath) {
1130 if (TabWidget->currentPageIndex() == 0) { 1133 if (TabWidget->currentPageIndex() == 0) {
1131 chdir( currentPath.latin1() ); 1134 chdir( currentPath.latin1() );
1132 currentDir.cd( currentPath, TRUE); 1135 currentDir.cd( currentPath, TRUE);
1133 populateLocalView(); 1136 populateLocalView();
1134 update(); 1137 update();
1135 } else { 1138 } else {
1136// chdir( currentPath.latin1() ); 1139// chdir( currentPath.latin1() );
1137// currentDir.cd( currentPath, TRUE); 1140// currentDir.cd( currentPath, TRUE);
1138// populateList(); 1141// populateList();
1139// update(); 1142// update();
1140 1143
1141 } 1144 }
1142} 1145}
1143 1146
1144void OpieFtp::fillCombo(const QString &currentPath) { 1147void OpieFtp::fillCombo(const QString &currentPath) {
1145 1148
1146 currentPathCombo->lineEdit()->setText(currentPath); 1149 currentPathCombo->lineEdit()->setText(currentPath);
1147 if( localDirPathStringList.grep(currentPath,TRUE).isEmpty() ) { 1150 if( localDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
1148 currentPathCombo->clear(); 1151 currentPathCombo->clear();
1149 localDirPathStringList.prepend(currentPath ); 1152 localDirPathStringList.prepend(currentPath );
1150 currentPathCombo->insertStringList( localDirPathStringList,-1); 1153 currentPathCombo->insertStringList( localDirPathStringList,-1);
1151 } 1154 }
1152 currentPathCombo->lineEdit()->setText(currentPath); 1155 currentPathCombo->lineEdit()->setText(currentPath);
1153 if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) { 1156 if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
1154 currentPathCombo->clear(); 1157 currentPathCombo->clear();
1155 remoteDirPathStringList.prepend(currentPath ); 1158 remoteDirPathStringList.prepend(currentPath );
1156 currentPathCombo->insertStringList( remoteDirPathStringList,-1); 1159 currentPathCombo->insertStringList( remoteDirPathStringList,-1);
1157 } 1160 }
1158} 1161}
1159 1162
1160void OpieFtp::fillRemoteCombo(const QString &currentPath) { 1163void OpieFtp::fillRemoteCombo(const QString &currentPath) {
1161 1164
1162 currentPathCombo->lineEdit()->setText(currentPath); 1165 currentPathCombo->lineEdit()->setText(currentPath);
1163 if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) { 1166 if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
1164 currentPathCombo->clear(); 1167 currentPathCombo->clear();
1165 remoteDirPathStringList.prepend(currentPath ); 1168 remoteDirPathStringList.prepend(currentPath );
1166 currentPathCombo->insertStringList( remoteDirPathStringList,-1); 1169 currentPathCombo->insertStringList( remoteDirPathStringList,-1);
1167 } 1170 }
1168} 1171}
1169 1172
1170void OpieFtp::currentPathComboChanged() 1173void OpieFtp::currentPathComboChanged()
1171{ 1174{
1172 QString oldRemoteCurrentDir = currentRemoteDir; 1175 QString oldRemoteCurrentDir = currentRemoteDir;
1173// qDebug("oldRemoteCurrentDir "+oldRemoteCurrentDir); 1176// odebug << "oldRemoteCurrentDir "+oldRemoteCurrentDir << oendl;
1174 if (TabWidget->currentPageIndex() == 0) { 1177 if (TabWidget->currentPageIndex() == 0) {
1175 if(QDir( currentPathCombo->lineEdit()->text()).exists()) { 1178 if(QDir( currentPathCombo->lineEdit()->text()).exists()) {
1176 currentDir.setPath( currentPathCombo->lineEdit()->text() ); 1179 currentDir.setPath( currentPathCombo->lineEdit()->text() );
1177 populateLocalView(); 1180 populateLocalView();
1178 } else { 1181 } else {
1179 QMessageBox::message(tr("Note"),tr("That directory does not exist")); 1182 QMessageBox::message(tr("Note"),tr("That directory does not exist"));
1180 } 1183 }
1181 } 1184 }
1182 if (TabWidget->currentPageIndex() == 1) { 1185 if (TabWidget->currentPageIndex() == 1) {
1183 currentRemoteDir = currentPathCombo->lineEdit()->text(); 1186 currentRemoteDir = currentPathCombo->lineEdit()->text();
1184 if(currentRemoteDir.right(1) !="/") { 1187 if(currentRemoteDir.right(1) !="/") {
1185 currentRemoteDir = currentRemoteDir +"/"; 1188 currentRemoteDir = currentRemoteDir +"/";
1186 currentPathCombo->lineEdit()->setText( currentRemoteDir ); 1189 currentPathCombo->lineEdit()->setText( currentRemoteDir );
1187 } 1190 }
1188 if( !remoteChDir( (const QString &)currentRemoteDir) ) { 1191 if( !remoteChDir( (const QString &)currentRemoteDir) ) {
1189 currentRemoteDir = oldRemoteCurrentDir; 1192 currentRemoteDir = oldRemoteCurrentDir;
1190 currentPathCombo->lineEdit()->setText( currentRemoteDir ); 1193 currentPathCombo->lineEdit()->setText( currentRemoteDir );
1191 } 1194 }
1192 1195
1193 remoteDirList( (const QString &)currentRemoteDir); 1196 remoteDirList( (const QString &)currentRemoteDir);
1194 } 1197 }
1195} 1198}
1196 1199
1197void OpieFtp::switchToLocalTab() 1200void OpieFtp::switchToLocalTab()
1198{ 1201{
1199 TabWidget->setCurrentPage(0); 1202 TabWidget->setCurrentPage(0);
1200} 1203}
1201 1204
1202void OpieFtp::switchToRemoteTab() 1205void OpieFtp::switchToRemoteTab()
1203{ 1206{
1204 TabWidget->setCurrentPage(1); 1207 TabWidget->setCurrentPage(1);
1205} 1208}
1206 1209
1207void OpieFtp::switchToConfigTab() 1210void OpieFtp::switchToConfigTab()
1208{ 1211{
1209 TabWidget->setCurrentPage(2); 1212 TabWidget->setCurrentPage(2);
1210} 1213}
1211 1214
1212void OpieFtp::readConfig() 1215void OpieFtp::readConfig()
1213{ 1216{
1214 fillCombos(); 1217 fillCombos();
1215 Config cfg("opieftp"); 1218 Config cfg("opieftp");
1216 cfg.setGroup("Server"); 1219 cfg.setGroup("Server");
1217 currentServerConfig = cfg.readNumEntry("currentServer", -1); 1220 currentServerConfig = cfg.readNumEntry("currentServer", -1);
1218 1221
1219// qDebug("Reading %d", currentServerConfig); 1222// odebug << "Reading " << currentServerConfig << "" << oendl;
1220 serverComboSelected( currentServerConfig-1); 1223 serverComboSelected( currentServerConfig-1);
1221 1224
1222} 1225}
1223 1226
1224void OpieFtp::writeConfig() 1227void OpieFtp::writeConfig()
1225{ 1228{
1226 qDebug("write config"); 1229 odebug << "write config" << oendl;
1227 Config cfg("opieftp"); 1230 Config cfg("opieftp");
1228 cfg.setGroup("Server"); 1231 cfg.setGroup("Server");
1229 1232
1230 QString username, remoteServerStr, remotePathStr, password, port, temp; 1233 QString username, remoteServerStr, remotePathStr, password, port, temp;
1231 1234
1232 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1235 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1233 1236
1234 if( currentServerConfig == -1) { 1237 if( currentServerConfig == -1) {
1235 1238
1236 for (int i = 1; i <= numberOfEntries; i++) { 1239 for (int i = 1; i <= numberOfEntries; i++) {
1237 temp.setNum(i); 1240 temp.setNum(i);
1238 cfg.setGroup("Server"); 1241 cfg.setGroup("Server");
1239 QString tempStr = cfg.readEntry( temp,""); 1242 QString tempStr = cfg.readEntry( temp,"");
1240 } 1243 }
1241 1244
1242 temp.setNum( numberOfEntries + 1); 1245 temp.setNum( numberOfEntries + 1);
1243 cfg.setGroup("Server"); 1246 cfg.setGroup("Server");
1244 1247
1245 remoteServerStr = cfg.readEntry( temp,""); 1248 remoteServerStr = cfg.readEntry( temp,"");
1246 1249
1247 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE); 1250 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
1248 remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider); 1251 remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider);
1249 1252
1250 temp.setNum(numberOfEntries+1); 1253 temp.setNum(numberOfEntries+1);
1251 cfg.setGroup("Server"); 1254 cfg.setGroup("Server");
1252 1255
1253 cfg.writeEntry( temp, ServerComboBox->currentText() +":"+PortSpinBox->cleanText() ); 1256 cfg.writeEntry( temp, ServerComboBox->currentText() +":"+PortSpinBox->cleanText() );
1254 cfg.writeEntry("currentServer", numberOfEntries+1); 1257 cfg.writeEntry("currentServer", numberOfEntries+1);
1255 1258
1256 currentServerConfig = numberOfEntries+1; 1259 currentServerConfig = numberOfEntries+1;
1257 qDebug("setting currentserverconfig to %d", currentServerConfig); 1260 odebug << "setting currentserverconfig to " << currentServerConfig << "" << oendl;
1258 1261
1259 cfg.setGroup(temp); 1262 cfg.setGroup(temp);
1260 if(!newServerName.isEmpty()) 1263 if(!newServerName.isEmpty())
1261 cfg.writeEntry("ServerName", newServerName); 1264 cfg.writeEntry("ServerName", newServerName);
1262 1265
1263 cfg.writeEntry("RemotePath", remotePath->text()); 1266 cfg.writeEntry("RemotePath", remotePath->text());
1264 1267
1265 cfg.writeEntry("Username", UsernameComboBox->currentText()); 1268 cfg.writeEntry("Username", UsernameComboBox->currentText());
1266 1269
1267 cfg.writeEntryCrypt( UsernameComboBox->currentText(), PasswordEdit->text()); 1270 cfg.writeEntryCrypt( UsernameComboBox->currentText(), PasswordEdit->text());
1268 cfg.setGroup("Server"); 1271 cfg.setGroup("Server");
1269 1272
1270 cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries + 1 )); 1273 cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries + 1 ));
1271 1274
1272 } 1275 }
1273} 1276}
1274 1277
1275void OpieFtp::clearCombos() { 1278void OpieFtp::clearCombos() {
1276 qDebug("clearing"); 1279 odebug << "clearing" << oendl;
1277 ServerComboBox->clear(); 1280 ServerComboBox->clear();
1278 UsernameComboBox->clear(); 1281 UsernameComboBox->clear();
1279 PasswordEdit->clear(); 1282 PasswordEdit->clear();
1280 serverListView->clear(); 1283 serverListView->clear();
1281} 1284}
1282 1285
1283 1286
1284void OpieFtp::fillCombos() 1287void OpieFtp::fillCombos()
1285{ 1288{
1286 clearCombos(); 1289 clearCombos();
1287 1290
1288 Config cfg("opieftp"); 1291 Config cfg("opieftp");
1289 cfg.setGroup("Server"); 1292 cfg.setGroup("Server");
1290 QString username, remoteServerStr, remotePathStr, password, port, temp; 1293 QString username, remoteServerStr, remotePathStr, password, port, temp;
1291 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1294 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1292 1295
1293 for (int i = 1; i <= numberOfEntries; i++) { 1296 for (int i = 1; i <= numberOfEntries; i++) {
1294 temp.setNum(i); 1297 temp.setNum(i);
1295 qDebug(temp); 1298 odebug << temp << oendl;
1296 cfg.setGroup("Server"); 1299 cfg.setGroup("Server");
1297 remoteServerStr = cfg.readEntry( temp,""); 1300 remoteServerStr = cfg.readEntry( temp,"");
1298 qDebug( remoteServerStr); 1301 odebug << remoteServerStr << oendl;
1299 1302
1300 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE); 1303 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
1301 port = remoteServerStr.right( divider - 1); 1304 port = remoteServerStr.right( divider - 1);
1302 bool ok; 1305 bool ok;
1303 PortSpinBox->setValue( port.toInt(&ok,10)); 1306 PortSpinBox->setValue( port.toInt(&ok,10));
1304 1307
1305 remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider); 1308 remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider);
1306 qDebug( "remote server string "+remoteServerStr); 1309 odebug << "remote server string "+remoteServerStr << oendl;
1307 ServerComboBox->insertItem( remoteServerStr ); 1310 ServerComboBox->insertItem( remoteServerStr );
1308 1311
1309 cfg.setGroup(temp); 1312 cfg.setGroup(temp);
1310 1313
1311 username = cfg.readEntry(temp); 1314 username = cfg.readEntry(temp);
1312 UsernameComboBox->insertItem(username); 1315 UsernameComboBox->insertItem(username);
1313 password = cfg.readEntryCrypt(username,""); 1316 password = cfg.readEntryCrypt(username,"");
1314 PasswordEdit->setText(password); 1317 PasswordEdit->setText(password);
1315 1318
1316 serverListView->insertItem( cfg.readEntry("ServerName")); 1319 serverListView->insertItem( cfg.readEntry("ServerName"));
1317 } 1320 }
1318} 1321}
1319 1322
1320 1323
1321void OpieFtp::serverComboSelected(int index) 1324void OpieFtp::serverComboSelected(int index)
1322{ 1325{
1323 currentServerConfig = index+1; 1326 currentServerConfig = index+1;
1324 qDebug("server combo selected %d", index+1); 1327 odebug << "server combo selected " << index+1 << "" << oendl;
1325 QString username, remoteServerStr, remotePathStr, password, port, temp; 1328 QString username, remoteServerStr, remotePathStr, password, port, temp;
1326// remoteServerStr = ServerComboBox->text(index); 1329// remoteServerStr = ServerComboBox->text(index);
1327 1330
1328 Config cfg("opieftp"); 1331 Config cfg("opieftp");
1329 cfg.setGroup("Server"); 1332 cfg.setGroup("Server");
1330// int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1333// int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1331 1334
1332 temp.setNum(index+1); 1335 temp.setNum(index+1);
1333 remoteServerStr = cfg.readEntry( temp,""); 1336 remoteServerStr = cfg.readEntry( temp,"");
1334 1337
1335 qDebug("Group" +temp); 1338 odebug << "Group" +temp << oendl;
1336 cfg.setGroup(temp); 1339 cfg.setGroup(temp);
1337// qDebug(temp); 1340// odebug << temp << oendl;
1338 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE); 1341 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
1339 port = remoteServerStr.right( divider - 1); 1342 port = remoteServerStr.right( divider - 1);
1340 bool ok; 1343 bool ok;
1341 int portInt = port.toInt(&ok,10); 1344 int portInt = port.toInt(&ok,10);
1342 if( portInt == 0) portInt = 21; 1345 if( portInt == 0) portInt = 21;
1343 1346
1344 ServerComboBox->lineEdit()->setText(remoteServerStr.left( remoteServerStr.find(":",0,TRUE))); 1347 ServerComboBox->lineEdit()->setText(remoteServerStr.left( remoteServerStr.find(":",0,TRUE)));
1345 1348
1346 PortSpinBox->setValue( portInt); 1349 PortSpinBox->setValue( portInt);
1347 1350
1348 remotePath->setText(cfg.readEntry("RemotePath", "/")); 1351 remotePath->setText(cfg.readEntry("RemotePath", "/"));
1349 1352
1350 username = cfg.readEntry("Username", "anonymous"); 1353 username = cfg.readEntry("Username", "anonymous");
1351 UsernameComboBox->lineEdit()->setText(username); 1354 UsernameComboBox->lineEdit()->setText(username);
1352 qDebug(username); 1355 odebug << username << oendl;
1353// qDebug("Password is "+cfg.readEntryCrypt(username, "me@opieftp.org")); 1356// odebug << "Password is "+cfg.readEntryCrypt(username << oendl;
1354 PasswordEdit->setText(cfg.readEntryCrypt(username, "me@opieftp.org")); 1357 PasswordEdit->setText(cfg.readEntryCrypt(username, "me@opieftp.org"));
1355// UsernameComboBox 1358// UsernameComboBox
1356// PasswordEdit 1359// PasswordEdit
1357 1360
1358 cfg.setGroup("Server"); 1361 cfg.setGroup("Server");
1359 temp.sprintf("%d",currentServerConfig); 1362 temp.sprintf("%d",currentServerConfig);
1360 cfg.writeEntry("currentServer", temp); 1363 cfg.writeEntry("currentServer", temp);
1361 1364
1362 fuckeduphack = TRUE; 1365 fuckeduphack = TRUE;
1363 serverListView->setCurrentItem( index); 1366 serverListView->setCurrentItem( index);
1364 fuckeduphack=FALSE; 1367 fuckeduphack=FALSE;
1365 qDebug("server list set selected %d",index); 1368 odebug << "server list set selected " << index << "" << oendl;
1366 update(); 1369 update();
1367} 1370}
1368 1371
1369void OpieFtp::deleteServer() 1372void OpieFtp::deleteServer()
1370{ 1373{
1371 QString username, remoteServerStr, remotePathStr, password, port, temp, servername; 1374 QString username, remoteServerStr, remotePathStr, password, port, temp, servername;
1372 remoteServerStr = ServerComboBox->currentText( ); 1375 remoteServerStr = ServerComboBox->currentText( );
1373 username = UsernameComboBox->currentText(); 1376 username = UsernameComboBox->currentText();
1374 servername=serverListView->currentText(); 1377 servername=serverListView->currentText();
1375 1378
1376 Config cfg("opieftp"); 1379 Config cfg("opieftp");
1377 cfg.setGroup("Server"); 1380 cfg.setGroup("Server");
1378 QString tempname; 1381 QString tempname;
1379 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1382 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1380 1383
1381 for (int i = 1; i <= numberOfEntries; i++) { 1384 for (int i = 1; i <= numberOfEntries; i++) {
1382 temp.setNum(i); 1385 temp.setNum(i);
1383// cfg.setGroup("Server"); 1386// cfg.setGroup("Server");
1384 cfg.setGroup(QString::number(i)); 1387 cfg.setGroup(QString::number(i));
1385 tempname=cfg.readEntry( "ServerName",""); 1388 tempname=cfg.readEntry( "ServerName","");
1386 1389
1387 if( tempname.find( servername,0,TRUE) != -1 ) { 1390 if( tempname.find( servername,0,TRUE) != -1 ) {
1388// servername.find( cfg.readEntry("ServerName")) != -1 && 1391// servername.find( cfg.readEntry("ServerName")) != -1 &&
1389// remoteServerStr.find( cfg.readEntry("RemotePath")) != -1 && 1392// remoteServerStr.find( cfg.readEntry("RemotePath")) != -1 &&
1390// username.find( cfg.readEntry("Username")) != -1) { 1393// username.find( cfg.readEntry("Username")) != -1) {
1391 1394
1392 serverListView->removeItem(i); 1395 serverListView->removeItem(i);
1393 1396
1394 qDebug("OK DELETE "+tempname); 1397 odebug << "OK DELETE "+tempname << oendl;
1395 cfg.removeEntry(QString::number(i)); 1398 cfg.removeEntry(QString::number(i));
1396 for ( ; i <= numberOfEntries; i++) { 1399 for ( ; i <= numberOfEntries; i++) {
1397 cfg.setGroup("Server"); 1400 cfg.setGroup("Server");
1398 cfg.writeEntry("Server", QString::number(numberOfEntries + 1 )); 1401 cfg.writeEntry("Server", QString::number(numberOfEntries + 1 ));
1399 1402
1400 cfg.setGroup(QString::number(i+1)); //get next server config 1403 cfg.setGroup(QString::number(i+1)); //get next server config
1401 servername=cfg.readEntry("ServerName"); 1404 servername=cfg.readEntry("ServerName");
1402 remoteServerStr=cfg.readEntry("RemotePath"); 1405 remoteServerStr=cfg.readEntry("RemotePath");
1403 username=cfg.readEntry("Username"); 1406 username=cfg.readEntry("Username");
1404 password=cfg.readEntryCrypt( username); 1407 password=cfg.readEntryCrypt( username);
1405 1408
1406 cfg.setGroup(QString::number(i)); 1409 cfg.setGroup(QString::number(i));
1407 1410
1408 cfg.writeEntry("RemotePath", remoteServerStr); 1411 cfg.writeEntry("RemotePath", remoteServerStr);
1409 cfg.writeEntry("ServerName", servername); 1412 cfg.writeEntry("ServerName", servername);
1410 cfg.writeEntry("Username", username); 1413 cfg.writeEntry("Username", username);
1411 cfg.writeEntryCrypt( username, password); 1414 cfg.writeEntryCrypt( username, password);
1412 1415
1413 } 1416 }
1414 cfg.setGroup("Server"); 1417 cfg.setGroup("Server");
1415 cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries - 1 )); 1418 cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries - 1 ));
1416 } 1419 }
1417 } 1420 }
1418 cfg.setGroup(QString::number(numberOfEntries)); 1421 cfg.setGroup(QString::number(numberOfEntries));
1419 cfg.removeEntry("Server"); 1422 cfg.removeEntry("Server");
1420 cfg.removeEntry("RemotePath"); 1423 cfg.removeEntry("RemotePath");
1421 cfg.removeEntry("ServerName"); 1424 cfg.removeEntry("ServerName");
1422 username=cfg.readEntry("Username"); 1425 username=cfg.readEntry("Username");
1423 cfg.removeEntry("Username"); 1426 cfg.removeEntry("Username");
1424 cfg.removeEntry(username); 1427 cfg.removeEntry(username);
1425 1428
1426 currentServerConfig=currentServerConfig-1; 1429 currentServerConfig=currentServerConfig-1;
1427 1430
1428 fillCombos(); 1431 fillCombos();
1429 update(); 1432 update();
1430} 1433}
1431 1434
1432void OpieFtp::upDir() 1435void OpieFtp::upDir()
1433{ 1436{
1434 if (TabWidget->currentPageIndex() == 0) { 1437 if (TabWidget->currentPageIndex() == 0) {
1435 QString current = currentDir.canonicalPath(); 1438 QString current = currentDir.canonicalPath();
1436 QDir dir(current); 1439 QDir dir(current);
1437 dir.cdUp(); 1440 dir.cdUp();
1438 current = dir.canonicalPath(); 1441 current = dir.canonicalPath();
1439 chdir( current.latin1() ); 1442 chdir( current.latin1() );
1440 currentDir.cd( current, TRUE); 1443 currentDir.cd( current, TRUE);
1441 populateLocalView(); 1444 populateLocalView();
1442 update(); 1445 update();
1443 } else { 1446 } else {
1444 if( FtpCDUp( conn) == 0) { 1447 if( FtpCDUp( conn) == 0) {
1445 QString msg; 1448 QString msg;
1446 msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn)); 1449 msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn));
1447 msg.replace(QRegExp(":"),"\n"); 1450 msg.replace(QRegExp(":"),"\n");
1448 QMessageBox::message(tr("Note"),msg); 1451 QMessageBox::message(tr("Note"),msg);
1449// qDebug(msg); 1452// odebug << msg << oendl;
1450 } 1453 }
1451 char path[256]; 1454 char path[256];
1452 if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string 1455 if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string
1453 QString msg; 1456 QString msg;
1454 msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn)); 1457 msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn));
1455 msg.replace(QRegExp(":"),"\n"); 1458 msg.replace(QRegExp(":"),"\n");
1456 QMessageBox::message(tr("Note"),msg); 1459 QMessageBox::message(tr("Note"),msg);
1457// qDebug(msg); 1460// odebug << msg << oendl;
1458 } 1461 }
1459 currentRemoteDir=path; 1462 currentRemoteDir=path;
1460 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1463 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1461 if(currentRemoteDir.right(1) !="/") 1464 if(currentRemoteDir.right(1) !="/")
1462 currentRemoteDir +="/"; 1465 currentRemoteDir +="/";
1463 currentPathCombo->lineEdit()->setText( currentRemoteDir); 1466 currentPathCombo->lineEdit()->setText( currentRemoteDir);
1464 fillRemoteCombo( (const QString &)currentRemoteDir); 1467 fillRemoteCombo( (const QString &)currentRemoteDir);
1465 1468
1466 } 1469 }
1467} 1470}
1468 1471
1469void OpieFtp::docButtonPushed() { 1472void OpieFtp::docButtonPushed() {
1470 QString current = QPEApplication::documentDir(); 1473 QString current = QPEApplication::documentDir();
1471 chdir( current.latin1() ); 1474 chdir( current.latin1() );
1472 currentDir.cd( current, TRUE); 1475 currentDir.cd( current, TRUE);
1473 populateLocalView(); 1476 populateLocalView();
1474 update(); 1477 update();
1475 1478
1476} 1479}
1477 1480
1478void OpieFtp::homeButtonPushed() { 1481void OpieFtp::homeButtonPushed() {
1479 QString current = QDir::homeDirPath(); 1482 QString current = QDir::homeDirPath();
1480 chdir( current.latin1() ); 1483 chdir( current.latin1() );
1481 currentDir.cd( current, TRUE); 1484 currentDir.cd( current, TRUE);
1482 populateLocalView(); 1485 populateLocalView();
1483 update(); 1486 update();
1484} 1487}
1485 1488
1486void OpieFtp::doAbout() { 1489void OpieFtp::doAbout() {
1487 QMessageBox::message("OpieFtp","Opie ftp client is copyright 2002 by\n" 1490 QMessageBox::message("OpieFtp","Opie ftp client is copyright 2002 by\n"
1488 "L.J.Potter<llornkcor@handhelds.org>\n" 1491 "L.J.Potter<llornkcor@handhelds.org>\n"
1489 "and uses ftplib copyright 1996-2000\n" 1492 "and uses ftplib copyright 1996-2000\n"
1490 "by Thomas Pfau, pfau@cnj.digex.net\n\n" 1493 "by Thomas Pfau, pfau@cnj.digex.net\n\n"
1491 "and is licensed by the GPL"); 1494 "and is licensed by the GPL");
1492} 1495}
1493 1496
1494void OpieFtp::NewServer() { 1497void OpieFtp::NewServer() {
1495 InputDialog *fileDlg; 1498 InputDialog *fileDlg;
1496 fileDlg = new InputDialog(this,tr("New Server name"),TRUE, 0); 1499 fileDlg = new InputDialog(this,tr("New Server name"),TRUE, 0);
1497 fileDlg->exec(); 1500 fileDlg->exec();
1498 Config cfg("opieftp"); 1501 Config cfg("opieftp");
1499 if( fileDlg->result() == 1 ) { 1502 if( fileDlg->result() == 1 ) {
1500 newServerName = fileDlg->LineEdit1->text(); 1503 newServerName = fileDlg->LineEdit1->text();
1501 for(int i=1;i<serverListView->count();i++) { 1504 for(int i=1;i<serverListView->count();i++) {
1502 cfg.setGroup( QString::number(i)); 1505 cfg.setGroup( QString::number(i));
1503 if(cfg.readEntry("ServerName").find(newServerName,0,TRUE) != -1) { 1506 if(cfg.readEntry("ServerName").find(newServerName,0,TRUE) != -1) {
1504 QMessageBox::message(tr("OpieFtp"),tr("Sorry name already taken")); 1507 QMessageBox::message(tr("OpieFtp"),tr("Sorry name already taken"));
1505 return; 1508 return;
1506 } 1509 }
1507 } 1510 }
1508 currentServerConfig =-1; 1511 currentServerConfig =-1;
1509 writeConfig(); 1512 writeConfig();
1510 serverListView->insertItem( newServerName ); 1513 serverListView->insertItem( newServerName );
1511 serverListView->setCurrentItem( serverListView->count()); 1514 serverListView->setCurrentItem( serverListView->count());
1512 } 1515 }
1513} 1516}
1514 1517
1515void OpieFtp::serverListClicked( const QString &item) { 1518void OpieFtp::serverListClicked( const QString &item) {
1516 if(item.isEmpty()) return; 1519 if(item.isEmpty()) return;
1517 Config cfg("opieftp"); 1520 Config cfg("opieftp");
1518 qDebug("highltined "+item); 1521 odebug << "highltined "+item << oendl;
1519 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1522 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1520 for (int i = 1; i <= numberOfEntries; i++) { 1523 for (int i = 1; i <= numberOfEntries; i++) {
1521 cfg.setGroup(QString::number(i)); 1524 cfg.setGroup(QString::number(i));
1522 if(cfg.readEntry( "ServerName").find(item) != -1 && !fuckeduphack) 1525 if(cfg.readEntry( "ServerName").find(item) != -1 && !fuckeduphack)
1523 serverComboSelected(i-1); 1526 serverComboSelected(i-1);
1524 } 1527 }
1525} 1528}
1526 1529
1527void OpieFtp::timerOut() { 1530void OpieFtp::timerOut() {
1528 1531
1529} 1532}
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 @@
1#CONFIG += qt warn_on quick-app 1CONFIG += qt warn_on
2CONFIG += qt warn_on 2HEADERS = opieftp.h inputDialog.h
3HEADERS = opieftp.h inputDialog.h 3SOURCES = opieftp.cpp inputDialog.cpp main.cpp
4SOURCES = opieftp.cpp inputDialog.cpp main.cpp 4TARGET = opieftp
5TARGET = opieftp
6INCLUDEPATH += $(OPIEDIR)/include 5INCLUDEPATH += $(OPIEDIR)/include
7DEPENDPATH += $(OPIEDIR)/include 6DEPENDPATH += $(OPIEDIR)/include
8LIBS += -lqpe -lftplib 7LIBS += -lqpe -lopiecore2 -lftplib
9DESTDIR = $(OPIEDIR)/bin 8DESTDIR = $(OPIEDIR)/bin
10 9
11include ( $(OPIEDIR)/include.pro ) 10include ( $(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 @@
1 config OPIEIRC 1 config OPIEIRC
2 boolean "opie-irc (chat via your favorite IRC server)" 2 boolean "opie-irc (chat via your favorite IRC server)"
3 default "y" 3 default "y"
4 depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI && LIBQTAUX 4 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 @@
1#include <stdio.h>
2#include "ircmisc.h" 1#include "ircmisc.h"
3 2
3/* OPIE */
4#include <opie2/odebug.h>
5using namespace Opie::Core;
6
4IRCTabBar::IRCTabBar(QWidget *parent, const char *name) : QTabBar(parent, name) { 7IRCTabBar::IRCTabBar(QWidget *parent, const char *name) : QTabBar(parent, name) {
5} 8}
6 9
7int IRCTabBar::insertTab(QTab *tab, int index) { 10int IRCTabBar::insertTab(QTab *tab, int index) {
8 /* FIXME: find some nicer way to do this */ 11 /* FIXME: find some nicer way to do this */
9 QExtTab *ext = new QExtTab(); 12 QExtTab *ext = new QExtTab();
10 ext->color = black; 13 ext->color = black;
11 ext->label = tab->text(); 14 ext->label = tab->text();
12 ext->r = tab->rect(); 15 ext->r = tab->rect();
13 ext->enabled = tab->isEnabled(); 16 ext->enabled = tab->isEnabled();
14 ext->iconset = tab->iconSet(); 17 ext->iconset = tab->iconSet();
15 delete tab; 18 delete tab;
16 return QTabBar::insertTab(ext, index); 19 return QTabBar::insertTab(ext, index);
17} 20}
18 21
19void IRCTabBar::setTabColor(int index, QColor color) { 22void IRCTabBar::setTabColor(int index, QColor color) {
20 ((QExtTab *)tab(index))->color = color; 23 ((QExtTab *)tab(index))->color = color;
21 update(); 24 update();
22} 25}
23 26
24void IRCTabBar::paintLabel(QPainter* p, const QRect& br, QTab* t, bool focus) const { 27void IRCTabBar::paintLabel(QPainter* p, const QRect& br, QTab* t, bool focus) const {
25 QRect r = br; 28 QRect r = br;
26 QTabBar::paintLabel(p, br, t, focus); 29 QTabBar::paintLabel(p, br, t, focus);
27 if (t->id == currentTab()) 30 if (t->id == currentTab())
28 r.setBottom(r.bottom() - style().defaultFrameWidth()); 31 r.setBottom(r.bottom() - style().defaultFrameWidth());
29 p->setPen(((QExtTab *)t)->color); 32 p->setPen(((QExtTab *)t)->color);
30 p->drawText(r, AlignCenter | ShowPrefix, t->label); 33 p->drawText(r, AlignCenter | ShowPrefix, t->label);
31} 34}
32 35
33IRCTabWidget::IRCTabWidget(QWidget *parent, const char *name) : QTabWidget(parent, name) { 36IRCTabWidget::IRCTabWidget(QWidget *parent, const char *name) : QTabWidget(parent, name) {
34 setTabBar(new IRCTabBar(this, "tab control")); 37 setTabBar(new IRCTabBar(this, "tab control"));
35} 38}
36 39
37void IRCTabWidget::setTabColor(int index, QColor color) { 40void IRCTabWidget::setTabColor(int index, QColor color) {
38 ((IRCTabBar *)tabBar())->setTabColor(index, color); 41 ((IRCTabBar *)tabBar())->setTabColor(index, color);
39} 42}
40 43
41 44
42IRCHistoryLineEdit::IRCHistoryLineEdit(QWidget *parent, const char *name) : QLineEdit(parent, name) { 45IRCHistoryLineEdit::IRCHistoryLineEdit(QWidget *parent, const char *name) : QLineEdit(parent, name) {
43 m_index = -1; 46 m_index = -1;
44 installEventFilter(this); 47 installEventFilter(this);
45} 48}
46 49
47void IRCHistoryLineEdit::keyPressEvent(QKeyEvent *event) { 50void IRCHistoryLineEdit::keyPressEvent(QKeyEvent *event) {
48 int key = event->key(); 51 int key = event->key();
49 if (key == Key_Up) { 52 if (key == Key_Up) {
50 if (m_history.count() > 0 && m_index < (signed int)m_history.count()-1) { 53 if (m_history.count() > 0 && m_index < (signed int)m_history.count()-1) {
51 m_index++; 54 m_index++;
52 setText(m_history[m_index]); 55 setText(m_history[m_index]);
53 } 56 }
54 } else if (key == Key_Down) { 57 } else if (key == Key_Down) {
55 if (m_history.count() > 0 && m_index > 0) { 58 if (m_history.count() > 0 && m_index > 0) {
56 m_index--; 59 m_index--;
57 setText(m_history[m_index]); 60 setText(m_history[m_index]);
58 } 61 }
59 if (m_index == 0) { 62 if (m_index == 0) {
60 m_index = -1; 63 m_index = -1;
61 setText(""); 64 setText("");
62 } 65 }
63 } else if (key == Key_Return) { 66 } else if (key == Key_Return) {
64 m_history.prepend(text()); 67 m_history.prepend(text());
65 m_index = -1; 68 m_index = -1;
66 } else if (key == Key_Tab) { 69 } else if (key == Key_Tab) {
67 printf("got tab\n"); 70 odebug << "got tab" << oendl;
68 return; 71 return;
69 } 72 }
70 QLineEdit::keyPressEvent(event); 73 QLineEdit::keyPressEvent(event);
71} 74}
72 75
73bool IRCHistoryLineEdit::eventFilter(QObject *object, QEvent *event) { 76bool IRCHistoryLineEdit::eventFilter(QObject *object, QEvent *event) {
74 if (event->type() == QEvent::KeyPress) { 77 if (event->type() == QEvent::KeyPress) {
75 QKeyEvent *k = (QKeyEvent *) event; 78 QKeyEvent *k = (QKeyEvent *) event;
76 /* Catch tab characters */ 79 /* Catch tab characters */
77 if (k->key() == Key_Tab) { 80 if (k->key() == Key_Tab) {
78 qDebug("tab!"); 81 odebug << "tab!" << oendl;
79 return TRUE; 82 return TRUE;
80 } 83 }
81 } 84 }
82 return QLineEdit::eventFilter(object, event); 85 return QLineEdit::eventFilter(object, event);
83} 86}
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 @@
1 CONFIG = qt warn_on quick-app 1 CONFIG = qt warn_on quick-app
2 HEADERS = ircchannel.h ircconnection.h \ 2HEADERS = ircchannel.h ircconnection.h \
3 ircmessage.h \ 3 ircmessage.h \
4 ircmessageparser.h ircoutput.h \ 4 ircmessageparser.h ircoutput.h \
5 ircperson.h ircserver.h ircsession.h \ 5 ircperson.h ircserver.h ircsession.h \
6 mainwindow.h irctab.h ircservertab.h \ 6 mainwindow.h irctab.h ircservertab.h \
7 ircchanneltab.h ircchannellist.h \ 7 ircchanneltab.h ircchannellist.h \
8 ircserverlist.h ircservereditor.h \ 8 ircserverlist.h ircservereditor.h \
9 ircquerytab.h ircsettings.h ircmisc.h 9 ircquerytab.h ircsettings.h ircmisc.h
10 SOURCES = ircchannel.cpp ircconnection.cpp \ 10 SOURCES = ircchannel.cpp ircconnection.cpp \
11 ircmessage.cpp \ 11 ircmessage.cpp \
12 ircmessageparser.cpp ircoutput.cpp \ 12 ircmessageparser.cpp ircoutput.cpp \
13 ircperson.cpp ircserver.cpp \ 13 ircperson.cpp ircserver.cpp \
14 ircsession.cpp main.cpp mainwindow.cpp \ 14 ircsession.cpp main.cpp mainwindow.cpp \
15 irctab.cpp ircservertab.cpp \ 15 irctab.cpp ircservertab.cpp \
16 ircchanneltab.cpp ircchannellist.cpp \ 16 ircchanneltab.cpp ircchannellist.cpp \
17 ircserverlist.cpp ircservereditor.cpp \ 17 ircserverlist.cpp ircservereditor.cpp \
18 ircquerytab.cpp ircsettings.cpp ircmisc.cpp 18 ircquerytab.cpp ircsettings.cpp ircmisc.cpp
19INCLUDEPATH += $(OPIEDIR)/include 19INCLUDEPATH += $(OPIEDIR)/include
20 DEPENDPATH+= $(OPIEDIR)/include 20DEPENDPATH += $(OPIEDIR)/include
21LIBS += -lqpe -lopieui2 -lqtaux2 21LIBS += -lqpe -lopiecore2 -lopieui2 -lqtaux2
22 22TARGET = opieirc
23 TARGET= opieirc
24 23
25include ( $(OPIEDIR)/include.pro ) 24include ( $(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 {
113 int BluezApplet::setBluezDiscoveryStatus(int d) { 113 int BluezApplet::setBluezDiscoveryStatus(int d) {
114 } 114 }
115 115
116 void BluezApplet::mousePressEvent( QMouseEvent *) { 116 void BluezApplet::mousePressEvent( QMouseEvent *) {
117 117
118 QPopupMenu *menu = new QPopupMenu(); 118 QPopupMenu *menu = new QPopupMenu();
119 QPopupMenu *signal = new QPopupMenu(); 119 QPopupMenu *signal = new QPopupMenu();
120 int ret=0; 120 int ret=0;
121 121
122 /* Refresh active state */ 122 /* Refresh active state */
123 timerEvent( 0 ); 123 timerEvent( 0 );
124 124
125 125
126 if (bluezactive) { 126 if (bluezactive) {
127 menu->insertItem( tr("Disable Bluetooth"), 0 ); 127 menu->insertItem( tr("Disable Bluetooth"), 0 );
128 } else { 128 } else {
129 menu->insertItem( tr("Enable Bluetooth"), 1 ); 129 menu->insertItem( tr("Enable Bluetooth"), 1 );
130 } 130 }
131 131
132 menu->insertItem( tr("Launch manager"), 2 ); 132 menu->insertItem( tr("Launch manager"), 2 );
133 133
134 menu->insertSeparator(6); 134 menu->insertSeparator(6);
135 //menu->insertItem( tr("Signal strength"), signal, 5); 135 //menu->insertItem( tr("Signal strength"), signal, 5);
136 //menu->insertSeparator(8); 136 //menu->insertSeparator(8);
137 137
138 if (bluezDiscoveryActive) { 138 if (bluezDiscoveryActive) {
139 menu->insertItem( tr("Disable discovery"), 3 ); 139 menu->insertItem( tr("Disable discovery"), 3 );
140 } else { 140 } else {
141 menu->insertItem( tr("Enable discovery"), 4 ); 141 menu->insertItem( tr("Enable discovery"), 4 );
142 } 142 }
143 143
144 144
145 QPoint p = mapToGlobal( QPoint(1, -menu->sizeHint().height()-1) ); 145 QPoint p = mapToGlobal( QPoint(1, -menu->sizeHint().height()-1) );
146 ret = menu->exec(p, 0); 146 ret = menu->exec(p, 0);
147 147
148 switch(ret) { 148 switch(ret) {
149 case 0: 149 case 0:
150 setBluezStatus(0); 150 setBluezStatus(0);
151 timerEvent( 0 ); 151 timerEvent( 0 );
152 break; 152 break;
153 case 1: 153 case 1:
154 setBluezStatus(1); 154 setBluezStatus(1);
155 timerEvent( 0 ); 155 timerEvent( 0 );
156 break; 156 break;
157 case 2: 157 case 2:
158 // start bluetoothmanager 158 // start bluetoothmanager
159 launchManager(); 159 launchManager();
160 timerEvent( 0 ); 160 timerEvent( 0 );
161 break; 161 break;
162 case 3: 162 case 3:
163 setBluezDiscoveryStatus(0); 163 setBluezDiscoveryStatus(0);
164 timerEvent( 0 ); 164 timerEvent( 0 );
165 break; 165 break;
166 case 4: 166 case 4:
167 setBluezDiscoveryStatus(1); 167 setBluezDiscoveryStatus(1);
168 timerEvent(0 ); 168 timerEvent(0 );
169 break; 169 break;
170 //case 7: 170 //case 7:
171 // With table of currently-detected devices. 171 // With table of currently-detected devices.
172 } 172 }
173 173
174 delete signal; 174 delete signal;
175 delete menu; 175 delete menu;
176 } 176 }
177 177
178 178
179/** 179/**
180 * Launches the bluetooth manager 180 * Launches the bluetooth manager
181 */ 181 */
182 void BluezApplet::launchManager() { 182 void BluezApplet::launchManager() {
183 QCopEnvelope e("QPE/System", "execute(QString)"); 183 QCopEnvelope e("QPE/System", "execute(QString)");
184 e << QString("bluetooth-manager"); 184 e << QString("bluetooth-manager");
185 } 185 }
186 186
187/** 187/**
188 * Refresh timer 188 * Refresh timer
189 * @param the timer event 189 * @param the timer event
190 */ 190 */
191 void BluezApplet::timerEvent( QTimerEvent * ) { 191 void BluezApplet::timerEvent( QTimerEvent * ) {
192 bool oldactive = bluezactive; 192 bool oldactive = bluezactive;
193 int olddiscovery = bluezDiscoveryActive; 193 int olddiscovery = bluezDiscoveryActive;
194 194
195 bluezactive = checkBluezStatus(); 195 bluezactive = checkBluezStatus();
196 bluezDiscoveryActive = checkBluezDiscoveryStatus(); 196 bluezDiscoveryActive = checkBluezDiscoveryStatus();
197 197
198 if ((bluezactive != oldactive) || (bluezDiscoveryActive != olddiscovery)) { 198 if ((bluezactive != oldactive) || (bluezDiscoveryActive != olddiscovery)) {
199 update(); 199 update();
200 } 200 }
201 } 201 }
202 202
203/** 203/**
204 * Implementation of the paint event 204 * Implementation of the paint event
205 * @param the QPaintEvent 205 * @param the QPaintEvent
206 */ 206 */
207 void BluezApplet::paintEvent( QPaintEvent* ) { 207 void BluezApplet::paintEvent( QPaintEvent* ) {
208 QPainter p(this); 208 QPainter p(this);
209 qDebug("paint bluetooth pixmap"); 209 odebug << "paint bluetooth pixmap" << oendl;
210 210
211 if (bluezactive > 0) { 211 if (bluezactive > 0) {
212 p.drawPixmap( 0, 1, bluezOnPixmap ); 212 p.drawPixmap( 0, 1, bluezOnPixmap );
213 } else { 213 } else {
214 p.drawPixmap( 0, 1, bluezOffPixmap ); 214 p.drawPixmap( 0, 1, bluezOffPixmap );
215 } 215 }
216 216
217 if (bluezDiscoveryActive > 0) { 217 if (bluezDiscoveryActive > 0) {
218 p.drawPixmap( 0, 1, bluezDiscoveryOnPixmap ); 218 p.drawPixmap( 0, 1, bluezDiscoveryOnPixmap );
219 } 219 }
220 } 220 }
221}; 221};
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 @@
1 1
2#include "startdunconnection.h" 2#include "startdunconnection.h"
3 3
4using namespace OpieTooth; 4using namespace OpieTooth;
5 5
6 6
7using namespace Opie::Core; 7using namespace Opie::Core;
8StartDunConnection::StartDunConnection() { 8StartDunConnection::StartDunConnection() {
9 m_dunConnect = 0l; 9 m_dunConnect = 0l;
10 setConnectionType(); 10 setConnectionType();
11} 11}
12 12
13StartDunConnection::~StartDunConnection() { 13StartDunConnection::~StartDunConnection() {
14 delete m_dunConnect; 14 delete m_dunConnect;
15} 15}
16 16
17StartDunConnection::StartDunConnection( QString mac ) { 17StartDunConnection::StartDunConnection( QString mac ) {
18 m_dunConnect = 0l; 18 m_dunConnect = 0l;
19 m_mac = mac; 19 m_mac = mac;
20 setConnectionType(); 20 setConnectionType();
21} 21}
22 22
23void StartDunConnection::setName( QString name ) { 23void StartDunConnection::setName( QString name ) {
24 m_name = name; 24 m_name = name;
25} 25}
26 26
27QString StartDunConnection::name() { 27QString StartDunConnection::name() {
28 return m_name; 28 return m_name;
29} 29}
30 30
31void StartDunConnection::setConnectionType() { 31void StartDunConnection::setConnectionType() {
32 m_connectionType = Pan; 32 m_connectionType = Pan;
33} 33}
34 34
35StartConnection::ConnectionType StartDunConnection::type() { 35StartConnection::ConnectionType StartDunConnection::type() {
36 return m_connectionType; 36 return m_connectionType;
37} 37}
38 38
39void StartDunConnection::start() { 39void StartDunConnection::start() {
40 m_dunConnect = new OProcess(); 40 m_dunConnect = new OProcess();
41 *m_dunConnect << "dund" << "--listen" << "--connect" << m_mac; 41 *m_dunConnect << "dund" << "--listen" << "--connect" << m_mac;
42 42
43 connect( m_dunConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) , 43 connect( m_dunConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) ,
44 this, SLOT( slotExited(Opie::Core::OProcess*) ) ); 44 this, SLOT( slotExited(Opie::Core::OProcess*) ) );
45 connect( m_dunConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ), 45 connect( m_dunConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ),
46 this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) ); 46 this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) );
47 if (!m_dunConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) { 47 if (!m_dunConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
48 qWarning( "could not start" ); 48 owarn << "could not start" << oendl;
49 delete m_dunConnect; 49 delete m_dunConnect;
50 } 50 }
51} 51}
52 52
53 53
54void StartDunConnection::slotExited( OProcess* proc ) { 54void StartDunConnection::slotExited( OProcess* proc ) {
55 delete m_dunConnect; 55 delete m_dunConnect;
56} 56}
57 57
58void StartDunConnection::slotStdOut(OProcess* proc, char* chars, int len) 58void StartDunConnection::slotStdOut(OProcess* proc, char* chars, int len)
59{} 59{}
60 60
61 61
62void StartDunConnection::stop() { 62void StartDunConnection::stop() {
63 if ( m_dunConnect ) { 63 if ( m_dunConnect ) {
64 delete m_dunConnect; 64 delete m_dunConnect;
65 m_dunConnect = 0l; 65 m_dunConnect = 0l;
66 } 66 }
67} 67}
68 68
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 @@
1 1
2#include "startpanconnection.h" 2#include "startpanconnection.h"
3 3
4using namespace OpieTooth; 4using namespace OpieTooth;
5 5
6 6
7using namespace Opie::Core; 7using namespace Opie::Core;
8using namespace Opie::Core; 8using namespace Opie::Core;
9StartPanConnection::StartPanConnection() { 9StartPanConnection::StartPanConnection() {
10 m_panConnect = 0l; 10 m_panConnect = 0l;
11 setConnectionType(); 11 setConnectionType();
12} 12}
13 13
14StartPanConnection::~StartPanConnection() { 14StartPanConnection::~StartPanConnection() {
15 delete m_panConnect; 15 delete m_panConnect;
16} 16}
17 17
18StartPanConnection::StartPanConnection( QString mac ) { 18StartPanConnection::StartPanConnection( QString mac ) {
19 m_panConnect = 0l; 19 m_panConnect = 0l;
20 m_mac = mac; 20 m_mac = mac;
21 setConnectionType(); 21 setConnectionType();
22} 22}
23 23
24void StartPanConnection::setName( QString name ) { 24void StartPanConnection::setName( QString name ) {
25 m_name = name; 25 m_name = name;
26} 26}
27 27
28QString StartPanConnection::name() { 28QString StartPanConnection::name() {
29 return m_name; 29 return m_name;
30} 30}
31 31
32void StartPanConnection::setConnectionType() { 32void StartPanConnection::setConnectionType() {
33 m_connectionType = Pan; 33 m_connectionType = Pan;
34} 34}
35 35
36StartConnection::ConnectionType StartPanConnection::type() { 36StartConnection::ConnectionType StartPanConnection::type() {
37 return m_connectionType; 37 return m_connectionType;
38} 38}
39 39
40void StartPanConnection::start() { 40void StartPanConnection::start() {
41 m_panConnect = new OProcess(); 41 m_panConnect = new OProcess();
42 qDebug( "IM START " + m_mac ); 42 odebug << "IM START " + m_mac << oendl;
43 *m_panConnect << "pand" << "--connect" << m_mac; 43 *m_panConnect << "pand" << "--connect" << m_mac;
44 44
45 connect( m_panConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) , 45 connect( m_panConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) ,
46 this, SLOT( slotExited(Opie::Core::OProcess*) ) ); 46 this, SLOT( slotExited(Opie::Core::OProcess*) ) );
47 connect( m_panConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ), 47 connect( m_panConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ),
48 this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) ); 48 this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) );
49 if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) { 49 if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
50 qWarning( "could not start" ); 50 owarn << "could not start" << oendl;
51 delete m_panConnect; 51 delete m_panConnect;
52 } 52 }
53} 53}
54 54
55 55
56void StartPanConnection::slotExited( OProcess* proc ) { 56void StartPanConnection::slotExited( OProcess* proc ) {
57 delete m_panConnect; 57 delete m_panConnect;
58 m_panConnect = 0l; 58 m_panConnect = 0l;
59} 59}
60 60
61void StartPanConnection::slotStdOut(OProcess* proc, char* chars, int len) 61void StartPanConnection::slotStdOut(OProcess* proc, char* chars, int len)
62{} 62{}
63 63
64 64
65void StartPanConnection::stop() { 65void StartPanConnection::stop() {
66 if ( m_panConnect ) { 66 if ( m_panConnect ) {
67 delete m_panConnect; 67 delete m_panConnect;
68 m_panConnect = 0l; 68 m_panConnect = 0l;
69 } 69 }
70 m_panConnect = new OProcess(); 70 m_panConnect = new OProcess();
71 qDebug("IM STOP " + m_mac); 71 odebug << "IM STOP " + m_mac << oendl;
72 72
73 *m_panConnect << "pand" << "--kill" << m_mac; 73 *m_panConnect << "pand" << "--kill" << m_mac;
74 74
75 connect( m_panConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) , 75 connect( m_panConnect, SIGNAL( processExited(Opie::Core::OProcess*) ) ,
76 this, SLOT( slotExited(Opie::Core::OProcess*) ) ); 76 this, SLOT( slotExited(Opie::Core::OProcess*) ) );
77 connect( m_panConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ), 77 connect( m_panConnect, SIGNAL( receivedStdout(Opie::Core::OProcess*,char*,int) ),
78 this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) ); 78 this, SLOT( slotStdOut(Opie::Core::OProcess*,char*,int) ) );
79 if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) { 79 if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
80 qWarning( "could not stop" ); 80 owarn << "could not stop" << oendl;
81 delete m_panConnect; 81 delete m_panConnect;
82 } 82 }
83} 83}
84 84
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 )
62 62
63 connect( PushButton2, SIGNAL( clicked() ), this, SLOT(startScan() ) ); 63 connect( PushButton2, SIGNAL( clicked() ), this, SLOT(startScan() ) );
64 connect( configApplyButton, SIGNAL(clicked() ), this, SLOT(applyConfigChanges() ) ); 64 connect( configApplyButton, SIGNAL(clicked() ), this, SLOT(applyConfigChanges() ) );
65 65
66 connect( rfcommBindButton, SIGNAL( clicked() ), this, SLOT( rfcommDialog() ) ); 66 connect( rfcommBindButton, SIGNAL( clicked() ), this, SLOT( rfcommDialog() ) );
67 // not good since lib is async 67 // not good since lib is async
68 // connect( ListView2, SIGNAL( expanded(QListViewItem*) ), 68 // connect( ListView2, SIGNAL( expanded(QListViewItem*) ),
69 // this, SLOT( addServicesToDevice(QListViewItem*) ) ); 69 // this, SLOT( addServicesToDevice(QListViewItem*) ) );
70 connect( ListView2, SIGNAL( clicked(QListViewItem*)), 70 connect( ListView2, SIGNAL( clicked(QListViewItem*)),
71 this, SLOT( startServiceActionClicked(QListViewItem*) ) ); 71 this, SLOT( startServiceActionClicked(QListViewItem*) ) );
72 connect( ListView2, SIGNAL( rightButtonClicked(QListViewItem*,const QPoint&,int) ), 72 connect( ListView2, SIGNAL( rightButtonClicked(QListViewItem*,const QPoint&,int) ),
73 this, SLOT(startServiceActionHold(QListViewItem*,const QPoint&,int) ) ); 73 this, SLOT(startServiceActionHold(QListViewItem*,const QPoint&,int) ) );
74 connect( m_localDevice , SIGNAL( foundServices(const QString&,Services::ValueList) ), 74 connect( m_localDevice , SIGNAL( foundServices(const QString&,Services::ValueList) ),
75 this, SLOT( addServicesToDevice(const QString&,Services::ValueList) ) ); 75 this, SLOT( addServicesToDevice(const QString&,Services::ValueList) ) );
76 connect( m_localDevice, SIGNAL( available(const QString&,bool) ), 76 connect( m_localDevice, SIGNAL( available(const QString&,bool) ),
77 this, SLOT( deviceActive(const QString&,bool) ) ); 77 this, SLOT( deviceActive(const QString&,bool) ) );
78 connect( m_localDevice, SIGNAL( connections(ConnectionState::ValueList) ), 78 connect( m_localDevice, SIGNAL( connections(ConnectionState::ValueList) ),
79 this, SLOT( addConnectedDevices(ConnectionState::ValueList) ) ); 79 this, SLOT( addConnectedDevices(ConnectionState::ValueList) ) );
80 connect( m_localDevice, SIGNAL( signalStrength(const QString&,const QString&) ), 80 connect( m_localDevice, SIGNAL( signalStrength(const QString&,const QString&) ),
81 this, SLOT( addSignalStrength(const QString&,const QString&) ) ); 81 this, SLOT( addSignalStrength(const QString&,const QString&) ) );
82 82
83 83
84 // let hold be rightButtonClicked() 84 // let hold be rightButtonClicked()
85 QPEApplication::setStylusOperation( ListView2->viewport(), QPEApplication::RightOnHold); 85 QPEApplication::setStylusOperation( ListView2->viewport(), QPEApplication::RightOnHold);
86 QPEApplication::setStylusOperation( ListView4->viewport(), QPEApplication::RightOnHold); 86 QPEApplication::setStylusOperation( ListView4->viewport(), QPEApplication::RightOnHold);
87 87
88 //Load all icons needed 88 //Load all icons needed
89 m_offPix = Resource::loadPixmap( "opietooth/notconnected" ); 89 m_offPix = Resource::loadPixmap( "opietooth/notconnected" );
90 m_onPix = Resource::loadPixmap( "opietooth/connected" ); 90 m_onPix = Resource::loadPixmap( "opietooth/connected" );
91 m_findPix = Resource::loadPixmap( "opietooth/find" ); 91 m_findPix = Resource::loadPixmap( "opietooth/find" );
92 92
93 QPalette pal = this->palette(); 93 QPalette pal = this->palette();
94 QColor col = pal.color( QPalette::Active, QColorGroup::Background ); 94 QColor col = pal.color( QPalette::Active, QColorGroup::Background );
95 pal.setColor( QPalette::Active, QColorGroup::Button, col ); 95 pal.setColor( QPalette::Active, QColorGroup::Button, col );
96 pal.setColor( QPalette::Inactive, QColorGroup::Button, col ); 96 pal.setColor( QPalette::Inactive, QColorGroup::Button, col );
97 pal.setColor( QPalette::Normal, QColorGroup::Button, col ); 97 pal.setColor( QPalette::Normal, QColorGroup::Button, col );
98 pal.setColor( QPalette::Disabled, QColorGroup::Button, col ); 98 pal.setColor( QPalette::Disabled, QColorGroup::Button, col );
99 this->setPalette( pal ); 99 this->setPalette( pal );
100 100
101 setCaption( tr( "Bluetooth Manager" ) ); 101 setCaption( tr( "Bluetooth Manager" ) );
102 102
103 readConfig(); 103 readConfig();
104 initGui(); 104 initGui();
105 105
106 ListView2->setRootIsDecorated(true); 106 ListView2->setRootIsDecorated(true);
107 107
108 108
109 writeToHciConfig(); 109 writeToHciConfig();
110 // search conncetions 110 // search conncetions
111 addConnectedDevices(); 111 addConnectedDevices();
112 addSignalStrength(); 112 addSignalStrength();
113 m_iconLoader = new BTIconLoader(); 113 m_iconLoader = new BTIconLoader();
114 readSavedDevices(); 114 readSavedDevices();
115} 115}
116 116
117/** 117/**
118 * Reads all options from the config file 118 * Reads all options from the config file
119 */ 119 */
120void BlueBase::readConfig() 120void BlueBase::readConfig()
121{ 121{
122 122
123 Config cfg( "bluetoothmanager" ); 123 Config cfg( "bluetoothmanager" );
124 cfg.setGroup( "bluezsettings" ); 124 cfg.setGroup( "bluezsettings" );
125 125
126 m_deviceName = cfg.readEntry( "name" , "No name" ); // name the device should identify with 126 m_deviceName = cfg.readEntry( "name" , "No name" ); // name the device should identify with
127 m_defaultPasskey = cfg.readEntryCrypt( "passkey" , "" ); // <- hmm, look up how good the trolls did that, maybe too weak 127 m_defaultPasskey = cfg.readEntryCrypt( "passkey" , "" ); // <- hmm, look up how good the trolls did that, maybe too weak
128 m_useEncryption = cfg.readBoolEntry( "useEncryption" , TRUE ); 128 m_useEncryption = cfg.readBoolEntry( "useEncryption" , TRUE );
129 m_enableAuthentification = cfg.readBoolEntry( "enableAuthentification" , TRUE ); 129 m_enableAuthentification = cfg.readBoolEntry( "enableAuthentification" , TRUE );
130 m_enablePagescan = cfg.readBoolEntry( "enablePagescan" , TRUE ); 130 m_enablePagescan = cfg.readBoolEntry( "enablePagescan" , TRUE );
131 m_enableInquiryscan = cfg.readBoolEntry( "enableInquiryscan" , TRUE ); 131 m_enableInquiryscan = cfg.readBoolEntry( "enableInquiryscan" , TRUE );
132} 132}
133 133
134/** 134/**
135 * Writes all options to the config file 135 * Writes all options to the config file
136 */ 136 */
137void BlueBase::writeConfig() 137void BlueBase::writeConfig()
138{ 138{
139 139
140 Config cfg( "bluetoothmanager" ); 140 Config cfg( "bluetoothmanager" );
141 cfg.setGroup( "bluezsettings" ); 141 cfg.setGroup( "bluezsettings" );
142 142
143 cfg.writeEntry( "name" , m_deviceName ); 143 cfg.writeEntry( "name" , m_deviceName );
144 cfg.writeEntryCrypt( "passkey" , m_defaultPasskey ); 144 cfg.writeEntryCrypt( "passkey" , m_defaultPasskey );
145 cfg.writeEntry( "useEncryption" , m_useEncryption ); 145 cfg.writeEntry( "useEncryption" , m_useEncryption );
146 cfg.writeEntry( "enableAuthentification" , m_enableAuthentification ); 146 cfg.writeEntry( "enableAuthentification" , m_enableAuthentification );
147 cfg.writeEntry( "enablePagescan" , m_enablePagescan ); 147 cfg.writeEntry( "enablePagescan" , m_enablePagescan );
148 cfg.writeEntry( "enableInquiryscan" , m_enableInquiryscan ); 148 cfg.writeEntry( "enableInquiryscan" , m_enableInquiryscan );
149 149
150 writeToHciConfig(); 150 writeToHciConfig();
151} 151}
152 152
153/** 153/**
154 * Modify the hcid.conf file to our needs 154 * Modify the hcid.conf file to our needs
155 */ 155 */
156void BlueBase::writeToHciConfig() 156void BlueBase::writeToHciConfig()
157{ 157{
158 qWarning("writeToHciConfig"); 158 owarn << "writeToHciConfig" << oendl;
159 HciConfWrapper hciconf ( "/etc/bluetooth/hcid.conf" ); 159 HciConfWrapper hciconf ( "/etc/bluetooth/hcid.conf" );
160 hciconf.load(); 160 hciconf.load();
161 hciconf.setPinHelper( "/opt/QtPalmtop/bin/bluepin" ); 161 hciconf.setPinHelper( "/opt/QtPalmtop/bin/bluepin" );
162 hciconf.setName( m_deviceName ); 162 hciconf.setName( m_deviceName );
163 hciconf.setEncrypt( m_useEncryption ); 163 hciconf.setEncrypt( m_useEncryption );
164 hciconf.setAuth( m_enableAuthentification ); 164 hciconf.setAuth( m_enableAuthentification );
165 hciconf.setPscan( m_enablePagescan ); 165 hciconf.setPscan( m_enablePagescan );
166 hciconf.setIscan( m_enableInquiryscan ); 166 hciconf.setIscan( m_enableInquiryscan );
167 hciconf.save(); 167 hciconf.save();
168} 168}
169 169
170 170
171/** 171/**
172 * Read the list of allready known devices 172 * Read the list of allready known devices
173 */ 173 */
174void BlueBase::readSavedDevices() 174void BlueBase::readSavedDevices()
175{ 175{
176 176
177 QValueList<RemoteDevice> loadedDevices; 177 QValueList<RemoteDevice> loadedDevices;
178 DeviceHandler handler; 178 DeviceHandler handler;
179 loadedDevices = handler.load(); 179 loadedDevices = handler.load();
180 180
181 addSearchedDevices( loadedDevices ); 181 addSearchedDevices( loadedDevices );
182} 182}
183 183
184 184
185/** 185/**
186 * Write the list of allready known devices 186 * Write the list of allready known devices
187 */ 187 */
188void BlueBase::writeSavedDevices() 188void BlueBase::writeSavedDevices()
189{ 189{
190 QListViewItemIterator it( ListView2 ); 190 QListViewItemIterator it( ListView2 );
191 BTListItem* item; 191 BTListItem* item;
192 BTDeviceItem* device; 192 BTDeviceItem* device;
193 RemoteDevice::ValueList list; 193 RemoteDevice::ValueList list;
194 for ( ; it.current(); ++it ) 194 for ( ; it.current(); ++it )
195 { 195 {
196 item = (BTListItem*)it.current(); 196 item = (BTListItem*)it.current();
197 if(item->typeId() != BTListItem::Device ) 197 if(item->typeId() != BTListItem::Device )
198 continue; 198 continue;
199 device = (BTDeviceItem*)item; 199 device = (BTDeviceItem*)item;
200 200
201 list.append( device->remoteDevice() ); 201 list.append( device->remoteDevice() );
202 } 202 }
203 /* 203 /*
204 * if not empty save the List through DeviceHandler 204 * if not empty save the List through DeviceHandler
205 */ 205 */
206 if ( list.isEmpty() ) 206 if ( list.isEmpty() )
207 return; 207 return;
208 DeviceHandler handler; 208 DeviceHandler handler;
209 handler.save( list ); 209 handler.save( list );
210} 210}
211 211
212 212
213/** 213/**
214 * Set up the gui 214 * Set up the gui
215 */ 215 */
216void BlueBase::initGui() 216void BlueBase::initGui()
217{ 217{
218 StatusLabel->setText( status() ); // maybe move it to getStatus() 218 StatusLabel->setText( status() ); // maybe move it to getStatus()
219 cryptCheckBox->setChecked( m_useEncryption ); 219 cryptCheckBox->setChecked( m_useEncryption );
220 authCheckBox->setChecked( m_enableAuthentification ); 220 authCheckBox->setChecked( m_enableAuthentification );
221 pagescanCheckBox->setChecked( m_enablePagescan ); 221 pagescanCheckBox->setChecked( m_enablePagescan );
222 inquiryscanCheckBox->setChecked( m_enableInquiryscan ); 222 inquiryscanCheckBox->setChecked( m_enableInquiryscan );
223 deviceNameLine->setText( m_deviceName ); 223 deviceNameLine->setText( m_deviceName );
224 passkeyLine->setText( m_defaultPasskey ); 224 passkeyLine->setText( m_defaultPasskey );
225 // set info tab 225 // set info tab
226 setInfo(); 226 setInfo();
227} 227}
228 228
229 229
230/** 230/**
231 * Get the status informations and returns it 231 * Get the status informations and returns it
232 * @return QString the status informations gathered 232 * @return QString the status informations gathered
233 */ 233 */
234QString BlueBase::status()const 234QString BlueBase::status()const
235{ 235{
236 QString infoString = tr( "<b>Device name : </b> Ipaq" ); 236 QString infoString = tr( "<b>Device name : </b> Ipaq" );
237 infoString += QString( "<br><b>" + tr( "MAC adress: " ) +"</b> No idea" ); 237 infoString += QString( "<br><b>" + tr( "MAC adress: " ) +"</b> No idea" );
238 infoString += QString( "<br><b>" + tr( "Class" ) + "</b> PDA" ); 238 infoString += QString( "<br><b>" + tr( "Class" ) + "</b> PDA" );
239 239
240 return (infoString); 240 return (infoString);
241} 241}
242 242
243 243
244/** 244/**
245 * Read the current values from the gui and invoke writeConfig() 245 * Read the current values from the gui and invoke writeConfig()
246 */ 246 */
247void BlueBase::applyConfigChanges() 247void BlueBase::applyConfigChanges()
248{ 248{
249 m_deviceName = deviceNameLine->text(); 249 m_deviceName = deviceNameLine->text();
250 m_defaultPasskey = passkeyLine->text(); 250 m_defaultPasskey = passkeyLine->text();
251 m_useEncryption = cryptCheckBox->isChecked(); 251 m_useEncryption = cryptCheckBox->isChecked();
252 m_enableAuthentification = authCheckBox->isChecked(); 252 m_enableAuthentification = authCheckBox->isChecked();
253 m_enablePagescan = pagescanCheckBox->isChecked(); 253 m_enablePagescan = pagescanCheckBox->isChecked();
254 m_enableInquiryscan = inquiryscanCheckBox->isChecked(); 254 m_enableInquiryscan = inquiryscanCheckBox->isChecked();
@@ -274,415 +274,415 @@ void BlueBase::rfcommDialog()
274 274
275/** 275/**
276 * Add fresh found devices from scan dialog to the listing 276 * Add fresh found devices from scan dialog to the listing
277 * 277 *
278 */ 278 */
279void BlueBase::addSearchedDevices( const QValueList<RemoteDevice> &newDevices ) 279void BlueBase::addSearchedDevices( const QValueList<RemoteDevice> &newDevices )
280{ 280{
281 BTDeviceItem * deviceItem; 281 BTDeviceItem * deviceItem;
282 QValueList<RemoteDevice>::ConstIterator it; 282 QValueList<RemoteDevice>::ConstIterator it;
283 283
284 for( it = newDevices.begin(); it != newDevices.end() ; ++it ) 284 for( it = newDevices.begin(); it != newDevices.end() ; ++it )
285 { 285 {
286 286
287 if (find( (*it) )) // is already inserted 287 if (find( (*it) )) // is already inserted
288 continue; 288 continue;
289 289
290 deviceItem = new BTDeviceItem( ListView2 , (*it) ); 290 deviceItem = new BTDeviceItem( ListView2 , (*it) );
291 deviceItem->setPixmap( 1, m_findPix ); 291 deviceItem->setPixmap( 1, m_findPix );
292 deviceItem->setExpandable ( true ); 292 deviceItem->setExpandable ( true );
293 293
294 // look if device is avail. atm, async 294 // look if device is avail. atm, async
295 deviceActive( (*it) ); 295 deviceActive( (*it) );
296 296
297 // ggf auch hier? 297 // ggf auch hier?
298 addServicesToDevice( deviceItem ); 298 addServicesToDevice( deviceItem );
299 } 299 }
300} 300}
301 301
302 302
303/** 303/**
304 * Action that is toggled on entrys on click 304 * Action that is toggled on entrys on click
305 */ 305 */
306void BlueBase::startServiceActionClicked( QListViewItem */*item*/ ) 306void BlueBase::startServiceActionClicked( QListViewItem */*item*/ )
307{} 307{}
308 308
309 309
310/** 310/**
311 * Action that are toggled on hold (mostly QPopups i guess) 311 * Action that are toggled on hold (mostly QPopups i guess)
312 */ 312 */
313void BlueBase::startServiceActionHold( QListViewItem * item, const QPoint & point, int /*column*/ ) 313void BlueBase::startServiceActionHold( QListViewItem * item, const QPoint & point, int /*column*/ )
314{ 314{
315 if (!item ) 315 if (!item )
316 return; 316 return;
317 317
318 QPopupMenu *menu = new QPopupMenu(); 318 QPopupMenu *menu = new QPopupMenu();
319 int ret=0; 319 int ret=0;
320 320
321 if ( ((BTListItem*)item)->type() == "device") 321 if ( ((BTListItem*)item)->type() == "device")
322 { 322 {
323 323
324 QPopupMenu *groups = new QPopupMenu(); 324 QPopupMenu *groups = new QPopupMenu();
325 325
326 menu->insertItem( ((BTDeviceItem*)item)->name(),0 ); 326 menu->insertItem( ((BTDeviceItem*)item)->name(),0 );
327 menu->insertSeparator(1); 327 menu->insertSeparator(1);
328 menu->insertItem( tr("rescan sevices"), 2); 328 menu->insertItem( tr("rescan sevices"), 2);
329 menu->insertItem( tr("to group"), groups , 3); 329 menu->insertItem( tr("to group"), groups , 3);
330 menu->insertItem( tr("delete"), 4); 330 menu->insertItem( tr("delete"), 4);
331 331
332 ret = menu->exec( point , 0); 332 ret = menu->exec( point , 0);
333 333
334 switch(ret) 334 switch(ret)
335 { 335 {
336 case -1: 336 case -1:
337 break; 337 break;
338 case 2: 338 case 2:
339 addServicesToDevice( (BTDeviceItem*)item ); 339 addServicesToDevice( (BTDeviceItem*)item );
340 break; 340 break;
341 341
342 case 4: 342 case 4:
343 // deletes childs too 343 // deletes childs too
344 delete item; 344 delete item;
345 break; 345 break;
346 } 346 }
347 delete groups; 347 delete groups;
348 348
349 } 349 }
350 350
351 /* 351 /*
352 * We got service sensitive PopupMenus in our factory 352 * We got service sensitive PopupMenus in our factory
353 * We will create one through the factory and will insert 353 * We will create one through the factory and will insert
354 * our Separator + ShowInfo into the menu or create a new 354 * our Separator + ShowInfo into the menu or create a new
355 * one if the factory returns 0 355 * one if the factory returns 0
356 * PopupMenu deletion is kind of weird. 356 * PopupMenu deletion is kind of weird.
357 * If escaped( -1 ) or any of our items were chosen we'll 357 * If escaped( -1 ) or any of our items were chosen we'll
358 * delete the PopupMenu otherwise it's the responsibility of 358 * delete the PopupMenu otherwise it's the responsibility of
359 * the PopupMenu to delete itself 359 * the PopupMenu to delete itself
360 * 360 *
361 */ 361 */
362 else if ( ((BTListItem*)item)->type() == "service") 362 else if ( ((BTListItem*)item)->type() == "service")
363 { 363 {
364 BTServiceItem* service = (BTServiceItem*)item; 364 BTServiceItem* service = (BTServiceItem*)item;
365 QMap<int, QString> list = service->services().classIdList(); 365 QMap<int, QString> list = service->services().classIdList();
366 QMap<int, QString>::Iterator it = list.begin(); 366 QMap<int, QString>::Iterator it = list.begin();
367 QPopupMenu *popup =0l; 367 QPopupMenu *popup =0l;
368 if ( it != list.end() ) 368 if ( it != list.end() )
369 { 369 {
370 qWarning("Searching id %d %s", it.key(), it.data().latin1() ); 370 owarn << "Searching id " << it.key() << " " << it.data().latin1() << "" << oendl;
371 popup = m_popHelper.find( it.key(), 371 popup = m_popHelper.find( it.key(),
372 service->services(), 372 service->services(),
373 (BTDeviceItem*)service->parent() ); 373 (BTDeviceItem*)service->parent() );
374 } 374 }
375 else 375 else
376 { 376 {
377 qWarning("Empty"); 377 owarn << "Empty" << oendl;
378 } 378 }
379 379
380 if ( popup == 0l ) 380 if ( popup == 0l )
381 { 381 {
382 qWarning("factory returned 0l"); 382 owarn << "factory returned 0l" << oendl;
383 popup = new QPopupMenu(); 383 popup = new QPopupMenu();
384 } 384 }
385 int test1 = popup->insertItem( tr("Test1:"), 2); 385 int test1 = popup->insertItem( tr("Test1:"), 2);
386 386
387 ret = popup->exec( point ); 387 ret = popup->exec( point );
388 qWarning("returned from exec() "); 388 owarn << "returned from exec() " << oendl;
389 if ( ret == -1 ) 389 if ( ret == -1 )
390 { 390 {
391 ; 391 ;
392 } 392 }
393 else if ( ret == test1 ) 393 else if ( ret == test1 )
394 { 394 {
395 ; 395 ;
396 } 396 }
397 delete popup; 397 delete popup;
398 } 398 }
399 delete menu; 399 delete menu;
400} 400}
401 401
402 402
403/** 403/**
404 * Search and display avail. services for a device (on expand from device listing) 404 * Search and display avail. services for a device (on expand from device listing)
405 * @param item the service item returned 405 * @param item the service item returned
406 */ 406 */
407void BlueBase::addServicesToDevice( BTDeviceItem * item ) 407void BlueBase::addServicesToDevice( BTDeviceItem * item )
408{ 408{
409 qDebug("addServicesToDevice"); 409 odebug << "addServicesToDevice" << oendl;
410 // row of mac adress text(3) 410 // row of mac adress text(3)
411 RemoteDevice device = item->remoteDevice(); 411 RemoteDevice device = item->remoteDevice();
412 m_deviceList.insert( item->mac() , item ); 412 m_deviceList.insert( item->mac() , item );
413 // and some time later I get a signal foundServices( const QString& device, Services::ValueList ); back 413 // and some time later I get a signal foundServices( const QString& device, Services::ValueList ); back
414 m_localDevice->searchServices( device ); 414 m_localDevice->searchServices( device );
415} 415}
416 416
417 417
418/** 418/**
419 * Overloaded. This one it the one that is 419 * Overloaded. This one it the one that is
420 ted to the foundServices signal 420 ted to the foundServices signal
421 * @param device the mac address of the remote device 421 * @param device the mac address of the remote device
422 * @param servicesList the list with the service the device has. 422 * @param servicesList the list with the service the device has.
423 */ 423 */
424void BlueBase::addServicesToDevice( const QString& device, Services::ValueList servicesList ) 424void BlueBase::addServicesToDevice( const QString& device, Services::ValueList servicesList )
425{ 425{
426 qDebug("fill services list"); 426 odebug << "fill services list" << oendl;
427 427
428 QMap<QString,BTDeviceItem*>::Iterator it; 428 QMap<QString,BTDeviceItem*>::Iterator it;
429 BTDeviceItem* deviceItem = 0; 429 BTDeviceItem* deviceItem = 0;
430 430
431 // get the right devices which requested the search 431 // get the right devices which requested the search
432 it = m_deviceList.find( device ); 432 it = m_deviceList.find( device );
433 if( it == m_deviceList.end() ) 433 if( it == m_deviceList.end() )
434 return; 434 return;
435 deviceItem = it.data(); 435 deviceItem = it.data();
436 436
437 // remove previous entries 437 // remove previous entries
438 QList<QListViewItem> tempList; 438 QList<QListViewItem> tempList;
439 tempList.setAutoDelete( true ); 439 tempList.setAutoDelete( true );
440 QListViewItem * child = deviceItem->firstChild(); 440 QListViewItem * child = deviceItem->firstChild();
441 while( child ) 441 while( child )
442 { 442 {
443 tempList.append( child ); 443 tempList.append( child );
444 child = child->nextSibling(); 444 child = child->nextSibling();
445 } 445 }
446 tempList.clear(); 446 tempList.clear();
447 447
448 QValueList<OpieTooth::Services>::Iterator it2; 448 QValueList<OpieTooth::Services>::Iterator it2;
449 BTServiceItem* serviceItem; 449 BTServiceItem* serviceItem;
450 450
451 451
452 if (!servicesList.isEmpty() ) 452 if (!servicesList.isEmpty() )
453 { 453 {
454 // add services 454 // add services
455 QMap<int, QString> list; 455 QMap<int, QString> list;
456 QMap<int, QString>::Iterator classIt; 456 QMap<int, QString>::Iterator classIt;
457 for( it2 = servicesList.begin(); it2 != servicesList.end(); ++it2 ) 457 for( it2 = servicesList.begin(); it2 != servicesList.end(); ++it2 )
458 { 458 {
459 serviceItem = new BTServiceItem( deviceItem, (*it2) ); 459 serviceItem = new BTServiceItem( deviceItem, (*it2) );
460 list = (*it2).classIdList(); 460 list = (*it2).classIdList();
461 classIt = list.begin(); 461 classIt = list.begin();
462 int classId=0; 462 int classId=0;
463 if ( classIt != list.end() ) 463 if ( classIt != list.end() )
464 { 464 {
465 classId = classIt.key(); 465 classId = classIt.key();
466 } 466 }
467 467
468 serviceItem->setPixmap( 0, m_iconLoader->serviceIcon( classId ) ); 468 serviceItem->setPixmap( 0, m_iconLoader->serviceIcon( classId ) );
469 } 469 }
470 } 470 }
471 else 471 else
472 { 472 {
473 Services s1; 473 Services s1;
474 s1.setServiceName( tr("no services found") ); 474 s1.setServiceName( tr("no services found") );
475 serviceItem = new BTServiceItem( deviceItem, s1 ); 475 serviceItem = new BTServiceItem( deviceItem, s1 );
476 } 476 }
477 // now remove them from the list 477 // now remove them from the list
478 m_deviceList.remove( it ); 478 m_deviceList.remove( it );
479} 479}
480 480
481 481
482 482
483 483
484 484
485void BlueBase::addSignalStrength() 485void BlueBase::addSignalStrength()
486{ 486{
487 487
488 QListViewItemIterator it( ListView4 ); 488 QListViewItemIterator it( ListView4 );
489 for ( ; it.current(); ++it ) 489 for ( ; it.current(); ++it )
490 { 490 {
491 m_localDevice->signalStrength( ((BTConnectionItem*)it.current() )->connection().mac() ); 491 m_localDevice->signalStrength( ((BTConnectionItem*)it.current() )->connection().mac() );
492 } 492 }
493 493
494 QTimer::singleShot( 5000, this, SLOT( addSignalStrength() ) ); 494 QTimer::singleShot( 5000, this, SLOT( addSignalStrength() ) );
495} 495}
496 496
497void BlueBase::addSignalStrength( const QString& mac, const QString& strength ) 497void BlueBase::addSignalStrength( const QString& mac, const QString& strength )
498{ 498{
499 499
500 QListViewItemIterator it( ListView4 ); 500 QListViewItemIterator it( ListView4 );
501 for ( ; it.current(); ++it ) 501 for ( ; it.current(); ++it )
502 { 502 {
503 if( ((BTConnectionItem*)it.current())->connection().mac() == mac ) 503 if( ((BTConnectionItem*)it.current())->connection().mac() == mac )
504 { 504 {
505 ((BTConnectionItem*)it.current() )->setSignalStrength( strength ); 505 ((BTConnectionItem*)it.current() )->setSignalStrength( strength );
506 } 506 }
507 } 507 }
508} 508}
509 509
510/** 510/**
511 * Add the existing connections (pairs) to the connections tab. 511 * Add the existing connections (pairs) to the connections tab.
512 * This one triggers the search 512 * This one triggers the search
513 */ 513 */
514void BlueBase::addConnectedDevices() 514void BlueBase::addConnectedDevices()
515{ 515{
516 m_localDevice->searchConnections(); 516 m_localDevice->searchConnections();
517} 517}
518 518
519/** 519/**
520 * This adds the found connections to the connection tab. 520 * This adds the found connections to the connection tab.
521 * @param connectionList the ValueList with all current connections 521 * @param connectionList the ValueList with all current connections
522 */ 522 */
523void BlueBase::addConnectedDevices( ConnectionState::ValueList connectionList ) 523void BlueBase::addConnectedDevices( ConnectionState::ValueList connectionList )
524{ 524{
525 525
526 QValueList<OpieTooth::ConnectionState>::Iterator it; 526 QValueList<OpieTooth::ConnectionState>::Iterator it;
527 BTConnectionItem * connectionItem; 527 BTConnectionItem * connectionItem;
528 528
529 if ( !connectionList.isEmpty() ) 529 if ( !connectionList.isEmpty() )
530 { 530 {
531 531
532 for (it = connectionList.begin(); it != connectionList.end(); ++it) 532 for (it = connectionList.begin(); it != connectionList.end(); ++it)
533 { 533 {
534 534
535 QListViewItemIterator it2( ListView4 ); 535 QListViewItemIterator it2( ListView4 );
536 bool found = false; 536 bool found = false;
537 for ( ; it2.current(); ++it2 ) 537 for ( ; it2.current(); ++it2 )
538 { 538 {
539 if( ( (BTConnectionItem*)it2.current())->connection().mac() == (*it).mac() ) 539 if( ( (BTConnectionItem*)it2.current())->connection().mac() == (*it).mac() )
540 { 540 {
541 found = true; 541 found = true;
542 } 542 }
543 } 543 }
544 544
545 if ( found == false ) 545 if ( found == false )
546 { 546 {
547 connectionItem = new BTConnectionItem( ListView4, (*it) ); 547 connectionItem = new BTConnectionItem( ListView4, (*it) );
548 548
549 if( m_deviceList.find((*it).mac()).data() ) 549 if( m_deviceList.find((*it).mac()).data() )
550 { 550 {
551 connectionItem->setName( m_deviceList.find( (*it).mac()).data()->name() ); 551 connectionItem->setName( m_deviceList.find( (*it).mac()).data()->name() );
552 } 552 }
553 } 553 }
554 554
555 } 555 }
556 556
557 QListViewItemIterator it2( ListView4 ); 557 QListViewItemIterator it2( ListView4 );
558 for ( ; it2.current(); ++it2 ) 558 for ( ; it2.current(); ++it2 )
559 { 559 {
560 bool found = false; 560 bool found = false;
561 for (it = connectionList.begin(); it != connectionList.end(); ++it) 561 for (it = connectionList.begin(); it != connectionList.end(); ++it)
562 { 562 {
563 if( ( ((BTConnectionItem*)it2.current())->connection().mac() ) == (*it).mac() ) 563 if( ( ((BTConnectionItem*)it2.current())->connection().mac() ) == (*it).mac() )
564 { 564 {
565 found = true; 565 found = true;
566 } 566 }
567 } 567 }
568 568
569 if ( !found ) 569 if ( !found )
570 { 570 {
571 delete it2.current(); 571 delete it2.current();
572 } 572 }
573 573
574 } 574 }
575 575
576 576
577 } 577 }
578 else 578 else
579 { 579 {
580 ListView4->clear(); 580 ListView4->clear();
581 ConnectionState con; 581 ConnectionState con;
582 con.setMac( tr("No connections found") ); 582 con.setMac( tr("No connections found") );
583 connectionItem = new BTConnectionItem( ListView4 , con ); 583 connectionItem = new BTConnectionItem( ListView4 , con );
584 } 584 }
585 585
586 // recall connection search after some time 586 // recall connection search after some time
587 QTimer::singleShot( 15000, this, SLOT( addConnectedDevices() ) ); 587 QTimer::singleShot( 15000, this, SLOT( addConnectedDevices() ) );
588} 588}
589 589
590 590
591/** 591/**
592 * Find out if a device can currently be reached 592 * Find out if a device can currently be reached
593 * @param device 593 * @param device
594 */ 594 */
595void BlueBase::deviceActive( const RemoteDevice &device ) 595void BlueBase::deviceActive( const RemoteDevice &device )
596{ 596{
597 // search by mac, async, gets a signal back 597 // search by mac, async, gets a signal back
598 // We should have a BTDeviceItem there or where does it get added to the map -zecke 598 // We should have a BTDeviceItem there or where does it get added to the map -zecke
599 m_localDevice->isAvailable( device.mac() ); 599 m_localDevice->isAvailable( device.mac() );
600} 600}
601 601
602 602
603/** 603/**
604 * The signal catcher. Set the avail. status on device. 604 * The signal catcher. Set the avail. status on device.
605 * @param device - the mac address 605 * @param device - the mac address
606 * @param connected - if it is avail. or not 606 * @param connected - if it is avail. or not
607 */ 607 */
608void BlueBase::deviceActive( const QString& device, bool connected ) 608void BlueBase::deviceActive( const QString& device, bool connected )
609{ 609{
610 qDebug("deviceActive slot"); 610 odebug << "deviceActive slot" << oendl;
611 611
612 QMap<QString,BTDeviceItem*>::Iterator it; 612 QMap<QString,BTDeviceItem*>::Iterator it;
613 613
614 it = m_deviceList.find( device ); 614 it = m_deviceList.find( device );
615 if( it == m_deviceList.end() ) 615 if( it == m_deviceList.end() )
616 return; 616 return;
617 617
618 BTDeviceItem* deviceItem = it.data(); 618 BTDeviceItem* deviceItem = it.data();
619 619
620 620
621 if ( connected ) 621 if ( connected )
622 { 622 {
623 deviceItem->setPixmap( 1, m_onPix ); 623 deviceItem->setPixmap( 1, m_onPix );
624 } 624 }
625 else 625 else
626 { 626 {
627 deviceItem->setPixmap( 1, m_offPix ); 627 deviceItem->setPixmap( 1, m_offPix );
628 } 628 }
629 m_deviceList.remove( it ); 629 m_deviceList.remove( it );
630} 630}
631 631
632 632
633/** 633/**
634 * Open the "scan for devices" dialog 634 * Open the "scan for devices" dialog
635 */ 635 */
636void BlueBase::startScan() 636void BlueBase::startScan()
637{ 637{
638 ScanDialog *scan = new ScanDialog( this, "ScanDialog", 638 ScanDialog *scan = new ScanDialog( this, "ScanDialog",
639 true, WDestructiveClose ); 639 true, WDestructiveClose );
640 QObject::connect( scan, SIGNAL( selectedDevices(const QValueList<RemoteDevice>&) ), 640 QObject::connect( scan, SIGNAL( selectedDevices(const QValueList<RemoteDevice>&) ),
641 this, SLOT( addSearchedDevices(const QValueList<RemoteDevice>&) ) ); 641 this, SLOT( addSearchedDevices(const QValueList<RemoteDevice>&) ) );
642 642
643 QPEApplication::showDialog( scan ); 643 QPEApplication::showDialog( scan );
644} 644}
645 645
646 646
647/** 647/**
648 * Set the informations about the local device in information Tab 648 * Set the informations about the local device in information Tab
649 */ 649 */
650void BlueBase::setInfo() 650void BlueBase::setInfo()
651{ 651{
652 StatusLabel->setText( status() ); 652 StatusLabel->setText( status() );
653} 653}
654 654
655 655
656/** 656/**
657 * Decontructor 657 * Decontructor
658 */ 658 */
659BlueBase::~BlueBase() 659BlueBase::~BlueBase()
660{ 660{
661 writeSavedDevices(); 661 writeSavedDevices();
662 delete m_iconLoader; 662 delete m_iconLoader;
663} 663}
664 664
665 665
666/** 666/**
667 * find searches the ListView for a BTDeviceItem containig 667 * find searches the ListView for a BTDeviceItem containig
668 * the same Device if found return true else false 668 * the same Device if found return true else false
669 * @param dev RemoteDevice to find 669 * @param dev RemoteDevice to find
670 * @return returns true if found 670 * @return returns true if found
671 */ 671 */
672bool BlueBase::find( const RemoteDevice& rem ) 672bool BlueBase::find( const RemoteDevice& rem )
673{ 673{
674 QListViewItemIterator it( ListView2 ); 674 QListViewItemIterator it( ListView2 );
675 BTListItem* item; 675 BTListItem* item;
676 BTDeviceItem* device; 676 BTDeviceItem* device;
677 for (; it.current(); ++it ) 677 for (; it.current(); ++it )
678 { 678 {
679 item = (BTListItem*) it.current(); 679 item = (BTListItem*) it.current();
680 if ( item->typeId() != BTListItem::Device ) 680 if ( item->typeId() != BTListItem::Device )
681 continue; 681 continue;
682 682
683 device = (BTDeviceItem*)item; 683 device = (BTDeviceItem*)item;
684 if ( rem.equals( device->remoteDevice() ) ) 684 if ( rem.equals( device->remoteDevice() ) )
685 return true; 685 return true;
686 } 686 }
687 return false; // not found 687 return false; // not found
688} 688}
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 @@
1 1
2#include <stdlib.h> 2#include <stdlib.h>
3 3
4#include <qdir.h> 4#include <qdir.h>
5#include <qpe/config.h> 5#include <qpe/config.h>
6 6
7#include "devicehandler.h" 7#include "devicehandler.h"
8 8
9using namespace OpieTooth; 9using namespace OpieTooth;
10 10
11DeviceHandler::DeviceHandler() { 11DeviceHandler::DeviceHandler() {
12 12
13}; 13};
14DeviceHandler::~DeviceHandler() { 14DeviceHandler::~DeviceHandler() {
15 15
16} 16}
17 17
18RemoteDevice::ValueList DeviceHandler::load() { 18RemoteDevice::ValueList DeviceHandler::load() {
19 RemoteDevice::ValueList list; 19 RemoteDevice::ValueList list;
20QString path = QDir::homeDirPath() + "/Settings/bluetooth"; 20QString path = QDir::homeDirPath() + "/Settings/bluetooth";
21 QDir deviceListSave( path); 21 QDir deviceListSave( path);
22 22
23 // list of .conf files 23 // list of .conf files
24 QStringList devicesFileList = deviceListSave.entryList(); 24 QStringList devicesFileList = deviceListSave.entryList();
25 25
26 26
27 // cut .conf of to get the mac and also read the name entry in it. 27 // cut .conf of to get the mac and also read the name entry in it.
28 if (!devicesFileList.isEmpty() ) { 28 if (!devicesFileList.isEmpty() ) {
29 QString name; 29 QString name;
30 QString mac; 30 QString mac;
31 QStringList::Iterator it; 31 QStringList::Iterator it;
32 for (it = devicesFileList.begin(); it != devicesFileList.end(); ++it ) { 32 for (it = devicesFileList.begin(); it != devicesFileList.end(); ++it ) {
33 if ( (*it) == "." || (*it) == ".." ) 33 if ( (*it) == "." || (*it) == ".." )
34 continue; 34 continue;
35 35
36 qDebug((*it).latin1() ); 36 odebug << (*it).latin1() << oendl;
37 Config conf(path + "/"+(*it), Config::File); 37 Config conf(path + "/"+(*it), Config::File);
38 conf.setGroup("Info"); 38 conf.setGroup("Info");
39 name = conf.readEntry("name", "Error"); 39 name = conf.readEntry("name", "Error");
40 mac = conf.readEntry("mac", QString::null); 40 mac = conf.readEntry("mac", QString::null);
41 qDebug("MAC: " + mac); 41 odebug << "MAC: " + mac << oendl;
42 qDebug("NAME: " + name); 42 odebug << "NAME: " + name << oendl;
43 if (mac.isEmpty() ) 43 if (mac.isEmpty() )
44 continue; 44 continue;
45 RemoteDevice currentDevice( mac , name ); 45 RemoteDevice currentDevice( mac , name );
46 list.append( currentDevice ); 46 list.append( currentDevice );
47 } 47 }
48 } 48 }
49 return list; 49 return list;
50}; 50};
51/* 51/*
52 * This is some how rude but make sure all old devices 52 * This is some how rude but make sure all old devices
53 * are getting deleted 53 * are getting deleted
54 */ 54 */
55void DeviceHandler::save( const RemoteDevice::ValueList& list) { 55void DeviceHandler::save( const RemoteDevice::ValueList& list) {
56 QCString rm; 56 QCString rm;
57 rm += "rm -rf "; 57 rm += "rm -rf ";
58 rm += QDir::homeDirPath() + "/Settings/bluetooth"; 58 rm += QDir::homeDirPath() + "/Settings/bluetooth";
59 system ( rm.data() ); 59 system ( rm.data() );
60 60
61 if (list.isEmpty() ) // no need to create the dir 61 if (list.isEmpty() ) // no need to create the dir
62 return; 62 return;
63 63
64 /** 64 /**
65 * Create a new dir 65 * Create a new dir
66 */ 66 */
67 rm = "mkdir "; 67 rm = "mkdir ";
68 rm += QDir::homeDirPath() + "/Settings/bluetooth"; 68 rm += QDir::homeDirPath() + "/Settings/bluetooth";
69 qWarning("out %s", rm.data() ); 69 owarn << "out " << rm.data() << "" << oendl;
70 system( rm.data() ); 70 system( rm.data() );
71 71
72 RemoteDevice::ValueList::ConstIterator it; 72 RemoteDevice::ValueList::ConstIterator it;
73 // write the config 73 // write the config
74 74
75 for ( it = list.begin(); it != list.end(); ++it ) { 75 for ( it = list.begin(); it != list.end(); ++it ) {
76 qDebug( "/Settings/bluetooth/" + (*it).mac() + ".conf"); 76 odebug << "/Settings/bluetooth/" + (*it).mac() + ".conf" << oendl;
77 77
78 Config conf( QDir::homeDirPath() + 78 Config conf( QDir::homeDirPath() +
79 "/Settings/bluetooth/" + 79 "/Settings/bluetooth/" +
80 (*it).mac() + ".conf", Config::File ); 80 (*it).mac() + ".conf", Config::File );
81 81
82 conf.setGroup( "Info" ); 82 conf.setGroup( "Info" );
83 conf.writeEntry( "name", (*it).name() ); 83 conf.writeEntry( "name", (*it).name() );
84 conf.writeEntry( "mac", (*it).mac() ); 84 conf.writeEntry( "mac", (*it).mac() );
85 } 85 }
86 86
87} 87}
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 @@
1#include <qpe/qcopenvelope_qws.h> 1#include <qpe/qcopenvelope_qws.h>
2 2
3#include <qtimer.h> 3#include <qtimer.h>
4 4
5#include "dunpopup.h" 5#include "dunpopup.h"
6 6
7using namespace OpieTooth; 7using namespace OpieTooth;
8 8
9/* 9/*
10 * c'tor init the QAction 10 * c'tor init the QAction
11 */ 11 */
12DunPopup::DunPopup( OpieTooth::BTDeviceItem* item ) : QPopupMenu() { 12DunPopup::DunPopup( OpieTooth::BTDeviceItem* item ) : QPopupMenu() {
13 13
14 qWarning("DunPopup c'tor"); 14 owarn << "DunPopup c'tor" << oendl;
15 15
16 m_item = item; 16 m_item = item;
17 QAction *a, *b, *c; 17 QAction *a, *b, *c;
18 18
19 m_dunconnection = 0l; 19 m_dunconnection = 0l;
20 /* connect action */ 20 /* connect action */
21 21
22 22
23 a = new QAction(); // so it's get deleted 23 a = new QAction(); // so it's get deleted
24 a->setText( tr("connect") ); 24 a->setText( tr("connect") );
25 a->addTo( this ); 25 a->addTo( this );
26 connect( a, SIGNAL( activated() ), this, SLOT( slotConnect() ) ); 26 connect( a, SIGNAL( activated() ), this, SLOT( slotConnect() ) );
27 27
28 28
29 b = new QAction(); 29 b = new QAction();
30 b->setText( tr( "connect+conf" ) ); 30 b->setText( tr( "connect+conf" ) );
31 b->addTo( this ); 31 b->addTo( this );
32 connect( b, SIGNAL( activated() ), this, SLOT( slotConnectAndConfig() ) ); 32 connect( b, SIGNAL( activated() ), this, SLOT( slotConnectAndConfig() ) );
33 33
34 c = new QAction(); 34 c = new QAction();
35 c->setText( tr( "disconnect" ) ); 35 c->setText( tr( "disconnect" ) );
36 c->addTo( this ); 36 c->addTo( this );
37 connect( c, SIGNAL( activated() ), this, SLOT( slotDisconnect() ) ); 37 connect( c, SIGNAL( activated() ), this, SLOT( slotDisconnect() ) );
38 38
39}; 39};
40 40
41DunPopup::~DunPopup() { 41DunPopup::~DunPopup() {
42 42
43} 43}
44 44
45void DunPopup::slotConnect() { 45void DunPopup::slotConnect() {
46 46
47 m_dunconnection = new StartDunConnection( m_item->mac() ); 47 m_dunconnection = new StartDunConnection( m_item->mac() );
48 m_dunconnection->start(); 48 m_dunconnection->start();
49} 49}
50 50
51void DunPopup::slotDisconnect() { 51void DunPopup::slotDisconnect() {
52 m_dunconnection->stop(); 52 m_dunconnection->stop();
53} 53}
54 54
55 55
56void DunPopup::slotConnectAndConfig() { 56void DunPopup::slotConnectAndConfig() {
57 slotConnect(); 57 slotConnect();
58 58
59 // more intelligence here later like passing the device ( bnepX ) 59 // more intelligence here later like passing the device ( bnepX )
60 QCopEnvelope e( "QPE/System", "execute(QString)" ); 60 QCopEnvelope e( "QPE/System", "execute(QString)" );
61 e << QString( "networksettings" ); 61 e << QString( "networksettings" );
62 62
63} 63}
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 @@
1#include "hciconfwrapper.h" 1#include "hciconfwrapper.h"
2 2
3#include <qfile.h> 3#include <qfile.h>
4#include <qtextstream.h> 4#include <qtextstream.h>
5#include <qregexp.h> 5#include <qregexp.h>
6 6
7namespace OpieTooth { 7namespace OpieTooth {
8 8
9 9
10 HciConfWrapper::HciConfWrapper( const QString &fileName) { 10 HciConfWrapper::HciConfWrapper( const QString &fileName) {
11 m_fileName = fileName; 11 m_fileName = fileName;
12 } 12 }
13 13
14 HciConfWrapper::~HciConfWrapper() { 14 HciConfWrapper::~HciConfWrapper() {
15 } 15 }
16 16
17 17
18 void HciConfWrapper::setPinHelper( const QString& app ) { 18 void HciConfWrapper::setPinHelper( const QString& app ) {
19 setValue( "pin_helper" , app ); 19 setValue( "pin_helper" , app );
20 } 20 }
21 21
22 void HciConfWrapper::setName( const QString &name ) { 22 void HciConfWrapper::setName( const QString &name ) {
23 qDebug ("NAME : " + name); 23 qDebug ("NAME : " + name);
24 setValue( "name" , "\"" + name + "\"" ); 24 setValue( "name" , "\"" + name + "\"" );
25 } 25 }
26 26
27 void HciConfWrapper::setIscan( bool enable) { 27 void HciConfWrapper::setIscan( bool enable) {
28 28
29 if ( enable ) { 29 if ( enable ) {
30 setValue( "iscan" , "enable" ); 30 setValue( "iscan" , "enable" );
31 } else { 31 } else {
32 setValue( "iscan" , "disable" ); 32 setValue( "iscan" , "disable" );
33 } 33 }
34 } 34 }
35 35
36 void HciConfWrapper::setPscan( bool enable) { 36 void HciConfWrapper::setPscan( bool enable) {
37 37
38 if ( enable ) { 38 if ( enable ) {
39 setValue( "pscan" , "enable" ); 39 setValue( "pscan" , "enable" );
40 } else { 40 } else {
41 setValue( "pscan" , "disable" ); 41 setValue( "pscan" , "disable" );
42 } 42 }
43 } 43 }
44 44
45 45
46 void HciConfWrapper::setAuth( bool enable) { 46 void HciConfWrapper::setAuth( bool enable) {
47 47
48 if ( enable ) { 48 if ( enable ) {
49 setValue( "auth" , "enable" ); 49 setValue( "auth" , "enable" );
50 } else { 50 } else {
51 setValue( "auth" , "disable" ); 51 setValue( "auth" , "disable" );
52 } 52 }
53 } 53 }
54 54
55 55
56 void HciConfWrapper::setEncrypt( bool enable) { 56 void HciConfWrapper::setEncrypt( bool enable) {
57 57
58 if ( enable ) { 58 if ( enable ) {
59 setValue( "encrypt" , "enable" ); 59 setValue( "encrypt" , "enable" );
60 } else { 60 } else {
61 setValue( "encrypt" , "disable" ); 61 setValue( "encrypt" , "disable" );
62 } 62 }
63 } 63 }
64 64
65 65
66 void HciConfWrapper::setValue(const QString &key, const QString &value ) { 66 void HciConfWrapper::setValue(const QString &key, const QString &value ) {
67 67
68 if (m_file.isEmpty() ) // load first 68 if (m_file.isEmpty() ) // load first
69 return; 69 return;
70 70
71 QStringList::Iterator it; 71 QStringList::Iterator it;
72 72
73 QString str; 73 QString str;
74 for (it = m_file.begin(); it != m_file.end(); ++it ) { 74 for (it = m_file.begin(); it != m_file.end(); ++it ) {
75 str = (*it); 75 str = (*it);
76 if( (str.contains(key)) > 0 ) { 76 if( (str.contains(key)) > 0 ) {
77 qDebug("Found"); 77 odebug << "Found" << oendl;
78 // still need to look if its commented out!!! 78 // still need to look if its commented out!!!
79 str.simplifyWhiteSpace(); 79 str.simplifyWhiteSpace();
80 qDebug( key ); 80 odebug << key << oendl;
81 if (str.startsWith("#")) { 81 if (str.startsWith("#")) {
82 str = (key + " " + value + ";"); 82 str = (key + " " + value + ";");
83 } else { 83 } else {
84 str = str.replace( QRegExp( "\\s*"+key+"\\s+[^\\s][^;]*;" ), key + " " + value + ";"); 84 str = str.replace( QRegExp( "\\s*"+key+"\\s+[^\\s][^;]*;" ), key + " " + value + ";");
85 } 85 }
86 qDebug( str ); 86 odebug << str << oendl;
87 it = m_file.remove( it ); 87 it = m_file.remove( it );
88 it = m_file.insert( it, str ); 88 it = m_file.insert( it, str );
89 //return; the regexp is too wide -zecke // all set 89 //return; the regexp is too wide -zecke // all set
90 } 90 }
91 } 91 }
92 92
93 93
94 } 94 }
95 95
96 /** 96 /**
97 * This loads the config file and stores it inside 97 * This loads the config file and stores it inside
98 * the m_file 98 * the m_file
99 */ 99 */
100 void HciConfWrapper::load() { 100 void HciConfWrapper::load() {
101 qWarning("loaded"); 101 owarn << "loaded" << oendl;
102 m_file.clear(); 102 m_file.clear();
103 QFile file( m_fileName ); 103 QFile file( m_fileName );
104 if (!file.open( IO_ReadOnly ) ) { 104 if (!file.open( IO_ReadOnly ) ) {
105 qDebug("Could not open"); 105 odebug << "Could not open" << oendl;
106 return; 106 return;
107 } 107 }
108 108
109 /** 109 /**
110 * readAll() into a QByteArray 110 * readAll() into a QByteArray
111 * QStringList::split('\n', array ) 111 * QStringList::split('\n', array )
112 * would this be faster? -zecke 112 * would this be faster? -zecke
113 */ 113 */
114 QTextStream stream(&file ); 114 QTextStream stream(&file );
115 QString tmp; 115 QString tmp;
116 while ( !stream.atEnd() ) { 116 while ( !stream.atEnd() ) {
117 tmp = stream.readLine(); 117 tmp = stream.readLine();
118 m_file.append( tmp ); 118 m_file.append( tmp );
119 } 119 }
120 } 120 }
121 void HciConfWrapper::save() { 121 void HciConfWrapper::save() {
122 qWarning("save"); 122 owarn << "save" << oendl;
123 if (m_file.isEmpty() ) // load first 123 if (m_file.isEmpty() ) // load first
124 return; 124 return;
125 125
126 QFile file( m_fileName ); 126 QFile file( m_fileName );
127 if ( !file.open(IO_WriteOnly ) ) { 127 if ( !file.open(IO_WriteOnly ) ) {
128 qWarning("could not open %s", m_fileName.latin1() ); 128 owarn << "could not open " << m_fileName.latin1() << "" << oendl;
129 return; 129 return;
130 } 130 }
131 131
132 QTextStream stream(&file ); 132 QTextStream stream(&file );
133 QStringList::Iterator it; 133 QStringList::Iterator it;
134 for ( it = m_file.begin(); it != m_file.end(); ++it ) { 134 for ( it = m_file.begin(); it != m_file.end(); ++it ) {
135 stream << (*it) << endl; 135 stream << (*it) << endl;
136 } 136 }
137 qWarning("saved"); 137 owarn << "saved" << oendl;
138 }; 138 };
139} 139}
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 @@
1 1
2#include "obexdialog.h" 2#include "obexdialog.h"
3#include <qpushbutton.h> 3#include <qpushbutton.h>
4#include <qmultilineedit.h> 4#include <qmultilineedit.h>
5#include <qlineedit.h> 5#include <qlineedit.h>
6#include <qlayout.h> 6#include <qlayout.h>
7#include <qlabel.h> 7#include <qlabel.h>
8#include <qfileinfo.h> 8#include <qfileinfo.h>
9 9
10#include <qpe/resource.h> 10#include <qpe/resource.h>
11 11
12#include <opie2/oprocess.h> 12#include <opie2/oprocess.h>
13#include <opie2/ofiledialog.h> 13#include <opie2/ofiledialog.h>
14 14
15using namespace OpieTooth; 15using namespace OpieTooth;
16 16
17using namespace Opie::Core; 17using namespace Opie::Core;
18using namespace Opie::Ui; 18using namespace Opie::Ui;
19using namespace Opie::Core; 19using namespace Opie::Core;
20ObexDialog::ObexDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device ) 20ObexDialog::ObexDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device )
21 : QDialog( parent, name, modal, fl ) { 21 : QDialog( parent, name, modal, fl ) {
22 22
23 if ( !name ) 23 if ( !name )
24 setName( "ObexDialog" ); 24 setName( "ObexDialog" );
25 setCaption( tr( "beam files " ) ) ; 25 setCaption( tr( "beam files " ) ) ;
26 26
27 m_device = device; 27 m_device = device;
28 28
29 layout = new QVBoxLayout( this ); 29 layout = new QVBoxLayout( this );
30 30
31 QLabel* info = new QLabel( this ); 31 QLabel* info = new QLabel( this );
32 info->setText( tr("Which file should be beamed?") ); 32 info->setText( tr("Which file should be beamed?") );
33 33
34 cmdLine = new QLineEdit( this ); 34 cmdLine = new QLineEdit( this );
35 35
36 QPushButton *browserButton; 36 QPushButton *browserButton;
37 browserButton = new QPushButton( Resource::loadIconSet("fileopen"),"",this,"BrowseButton"); 37 browserButton = new QPushButton( Resource::loadIconSet("fileopen"),"",this,"BrowseButton");
38 connect( browserButton, SIGNAL(released() ), this , SLOT(browse() ) ); 38 connect( browserButton, SIGNAL(released() ), this , SLOT(browse() ) );
39 39
40 chNameLine = new QLineEdit( this ); 40 chNameLine = new QLineEdit( this );
41 41
42 sendButton = new QPushButton( this ); 42 sendButton = new QPushButton( this );
43 sendButton->setText( tr( "Send" ) ); 43 sendButton->setText( tr( "Send" ) );
44 44
45 layout->addWidget(info); 45 layout->addWidget(info);
46 layout->addWidget(cmdLine); 46 layout->addWidget(cmdLine);
47 layout->addWidget(browserButton); 47 layout->addWidget(browserButton);
48 layout->addWidget(chNameLine); 48 layout->addWidget(chNameLine);
49 layout->addWidget(sendButton); 49 layout->addWidget(sendButton);
50 50
51 connect( sendButton, SIGNAL( clicked() ), this, SLOT( sendData() ) ); 51 connect( sendButton, SIGNAL( clicked() ), this, SLOT( sendData() ) );
52 52
53} 53}
54 54
55ObexDialog::~ObexDialog() { 55ObexDialog::~ObexDialog() {
56} 56}
57 57
58void ObexDialog::browse() { 58void ObexDialog::browse() {
59 59
60 MimeTypes types; 60 MimeTypes types;
61 QStringList all; 61 QStringList all;
62 all << "*/*"; 62 all << "*/*";
63 types.insert("All Files", all ); 63 types.insert("All Files", all );
64 64
65 QString str = OFileDialog::getOpenFileName( 1,"/","", types, 0 ); 65 QString str = OFileDialog::getOpenFileName( 1,"/","", types, 0 );
66 cmdLine->setText( str ); 66 cmdLine->setText( str );
67 67
68} 68}
69 69
70void ObexDialog::sendData() { 70void ObexDialog::sendData() {
71 QString fileURL = cmdLine->text(); 71 QString fileURL = cmdLine->text();
72 QString file = QFileInfo( fileURL ).fileName(); 72 QString file = QFileInfo( fileURL ).fileName();
73 QString modifiedName = chNameLine->text(); 73 QString modifiedName = chNameLine->text();
74 74
75 // vom popupmenu beziehen 75 // vom popupmenu beziehen
76 OProcess* obexSend = new OProcess(); 76 OProcess* obexSend = new OProcess();
77 if ( !modifiedName.isEmpty() ) { 77 if ( !modifiedName.isEmpty() ) {
78 *obexSend << "ussp-push" << m_device << fileURL << modifiedName; 78 *obexSend << "ussp-push" << m_device << fileURL << modifiedName;
79 } else { 79 } else {
80 *obexSend << "ussp-push" << m_device << fileURL << file; 80 *obexSend << "ussp-push" << m_device << fileURL << file;
81 } 81 }
82 if (!obexSend->start(OProcess::DontCare, OProcess::AllOutput) ) { 82 if (!obexSend->start(OProcess::DontCare, OProcess::AllOutput) ) {
83 qWarning("could not start"); 83 owarn << "could not start" << oendl;
84 delete obexSend; 84 delete obexSend;
85 } 85 }
86 86
87 87
88 88
89} 89}
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 @@
1 1
2#include "obexdialog.h" 2#include "obexdialog.h"
3#include "obexpopup.h" 3#include "obexpopup.h"
4 4
5/* OPIE */ 5/* OPIE */
6#include <qpe/qpeapplication.h> 6#include <qpe/qpeapplication.h>
7 7
8/* QT */ 8/* QT */
9#include <qtimer.h> 9#include <qtimer.h>
10 10
11using namespace OpieTooth; 11using namespace OpieTooth;
12 12
13/* 13/*
14 * c'tor init the QAction 14 * c'tor init the QAction
15 */ 15 */
16ObexPopup::ObexPopup() 16ObexPopup::ObexPopup()
17 : QPopupMenu() 17 : QPopupMenu()
18{ 18{
19 qWarning("RfcCommPopup c'tor"); 19 owarn << "RfcCommPopup c'tor" << oendl;
20 20
21 QAction* a; 21 QAction* a;
22 22
23 /* connect action */ 23 /* connect action */
24 a = new QAction( ); // so it's get deleted 24 a = new QAction( ); // so it's get deleted
25 a->setText("Push file"); 25 a->setText("Push file");
26 a->addTo( this ); 26 a->addTo( this );
27 connect( a, SIGNAL( activated() ), 27 connect( a, SIGNAL( activated() ),
28 this, SLOT( slotPush() ) ); 28 this, SLOT( slotPush() ) );
29}; 29};
30 30
31 31
32ObexPopup::~ObexPopup() 32ObexPopup::~ObexPopup()
33{} 33{}
34 34
35 35
36void ObexPopup::slotPush() 36void ObexPopup::slotPush()
37{ 37{
38 38
39 qWarning("push something"); 39 owarn << "push something" << oendl;
40 40
41 ObexDialog obexDialog; 41 ObexDialog obexDialog;
42 QPEApplication::execDialog( &obexDialog ); 42 QPEApplication::execDialog( &obexDialog );
43} 43}
44 44
45 45
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 @@
1#include <qpe/qcopenvelope_qws.h> 1#include <qpe/qcopenvelope_qws.h>
2 2
3#include <qtimer.h> 3#include <qtimer.h>
4 4
5#include "panpopup.h" 5#include "panpopup.h"
6 6
7using namespace OpieTooth; 7using namespace OpieTooth;
8 8
9/* 9/*
10 * c'tor init the QAction 10 * c'tor init the QAction
11 */ 11 */
12PanPopup::PanPopup( OpieTooth::BTDeviceItem* item ) : QPopupMenu() { 12PanPopup::PanPopup( OpieTooth::BTDeviceItem* item ) : QPopupMenu() {
13 13
14 qWarning("PanPopup c'tor"); 14 owarn << "PanPopup c'tor" << oendl;
15 15
16 m_item = item; 16 m_item = item;
17 QAction *a, *b, *c; 17 QAction *a, *b, *c;
18 18
19 m_panconnection = 0l; 19 m_panconnection = 0l;
20 /* connect action */ 20 /* connect action */
21 21
22 22
23 a = new QAction(); // so it's get deleted 23 a = new QAction(); // so it's get deleted
24 a->setText( tr("connect") ); 24 a->setText( tr("connect") );
25 a->addTo( this ); 25 a->addTo( this );
26 connect( a, SIGNAL( activated() ), this, SLOT( slotConnect() ) ); 26 connect( a, SIGNAL( activated() ), this, SLOT( slotConnect() ) );
27 27
28 28
29 b = new QAction(); 29 b = new QAction();
30 b->setText( tr( "connect+conf" ) ); 30 b->setText( tr( "connect+conf" ) );
31 b->addTo( this ); 31 b->addTo( this );
32 connect( b, SIGNAL( activated() ), this, SLOT( slotConnectAndConfig() ) ); 32 connect( b, SIGNAL( activated() ), this, SLOT( slotConnectAndConfig() ) );
33 33
34 c = new QAction(); 34 c = new QAction();
35 c->setText( tr( "disconnect" ) ); 35 c->setText( tr( "disconnect" ) );
36 c->addTo( this ); 36 c->addTo( this );
37 connect( c, SIGNAL( activated() ), this, SLOT( slotDisconnect() ) ); 37 connect( c, SIGNAL( activated() ), this, SLOT( slotDisconnect() ) );
38 38
39}; 39};
40 40
41PanPopup::~PanPopup() { 41PanPopup::~PanPopup() {
42 42
43} 43}
44 44
45void PanPopup::slotConnect() { 45void PanPopup::slotConnect() {
46 46
47 m_panconnection = new StartPanConnection( m_item->mac() ); 47 m_panconnection = new StartPanConnection( m_item->mac() );
48 m_panconnection->start(); 48 m_panconnection->start();
49} 49}
50 50
51void PanPopup::slotDisconnect() { 51void PanPopup::slotDisconnect() {
52 if (!m_panconnection) m_panconnection = new StartPanConnection( m_item->mac() ); 52 if (!m_panconnection) m_panconnection = new StartPanConnection( m_item->mac() );
53 m_panconnection->stop(); 53 m_panconnection->stop();
54} 54}
55 55
56 56
57void PanPopup::slotConnectAndConfig() { 57void PanPopup::slotConnectAndConfig() {
58 slotConnect(); 58 slotConnect();
59 59
60 // more intelligence here later like passing the device ( bnepX ) 60 // more intelligence here later like passing the device ( bnepX )
61 QCopEnvelope e( "QPE/System", "execute(QString)" ); 61 QCopEnvelope e( "QPE/System", "execute(QString)" );
62 e << QString( "networksettings" ); 62 e << QString( "networksettings" );
63 63
64} 64}
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 @@
1 1
2#include "stdpopups.h" 2#include "stdpopups.h"
3#include "popuphelper.h" 3#include "popuphelper.h"
4 4
5using namespace OpieTooth; 5using namespace OpieTooth;
6 6
7PopupHelper::PopupHelper() { 7PopupHelper::PopupHelper() {
8 init(); 8 init();
9} 9}
10 10
11PopupHelper::~PopupHelper() { 11PopupHelper::~PopupHelper() {
12} 12}
13 13
14void PopupHelper::insert( int id, popupFactory fact ) { 14void PopupHelper::insert( int id, popupFactory fact ) {
15 m_map.insert(id, fact ); 15 m_map.insert(id, fact );
16} 16}
17 17
18QPopupMenu* PopupHelper::find( int id, const Services& ser, BTDeviceItem* item ) { 18QPopupMenu* PopupHelper::find( int id, const Services& ser, BTDeviceItem* item ) {
19 //qWarning("find"); 19 //owarn << "find" << oendl;
20 FactoryMap::Iterator it = m_map.find(id ); 20 FactoryMap::Iterator it = m_map.find(id );
21 if ( it != m_map.end() ) { 21 if ( it != m_map.end() ) {
22 //qWarning("found"); 22 //owarn << "found" << oendl;
23 popupFactory fact = it.data(); 23 popupFactory fact = it.data();
24 return (*fact)(ser, item); 24 return (*fact)(ser, item);
25 } 25 }
26 return 0l; 26 return 0l;
27} 27}
28 28
29void PopupHelper::init() { 29void PopupHelper::init() {
30 insert( 4355, newRfcComPopup ); 30 insert( 4355, newRfcComPopup );
31 insert( 4354, newDunPopup ); 31 insert( 4354, newDunPopup );
32 insert( 4353, newRfcComPopup ); 32 insert( 4353, newRfcComPopup );
33 insert( 4357, newObexPushPopup ); 33 insert( 4357, newObexPushPopup );
34 insert( 4358, newObexPushPopup ); 34 insert( 4358, newObexPushPopup );
35 insert( 4374, newPanPopup ); 35 insert( 4374, newPanPopup );
36} 36}
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 @@
1 1
2#include "pppdialog.h" 2#include "pppdialog.h"
3#include <qpushbutton.h> 3#include <qpushbutton.h>
4#include <qmultilineedit.h> 4#include <qmultilineedit.h>
5#include <qlineedit.h> 5#include <qlineedit.h>
6#include <qlayout.h> 6#include <qlayout.h>
7#include <qlabel.h> 7#include <qlabel.h>
8#include <opie2/oprocess.h> 8#include <opie2/oprocess.h>
9 9
10using namespace OpieTooth; 10using namespace OpieTooth;
11 11
12using namespace Opie::Core; 12using namespace Opie::Core;
13PPPDialog::PPPDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device ) 13PPPDialog::PPPDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device )
14 : QDialog( parent, name, modal, fl ) { 14 : QDialog( parent, name, modal, fl ) {
15 15
16 if ( !name ) 16 if ( !name )
17 setName( "PPPDialog" ); 17 setName( "PPPDialog" );
18 setCaption( tr( "ppp connection " ) ) ; 18 setCaption( tr( "ppp connection " ) ) ;
19 19
20 m_device = device; 20 m_device = device;
21 21
22 layout = new QVBoxLayout( this ); 22 layout = new QVBoxLayout( this );
23 23
24 QLabel* info = new QLabel( this ); 24 QLabel* info = new QLabel( this );
25 info->setText( tr("Enter an ppp script name:") ); 25 info->setText( tr("Enter an ppp script name:") );
26 26
27 cmdLine = new QLineEdit( this ); 27 cmdLine = new QLineEdit( this );
28 28
29 outPut = new QMultiLineEdit( this ); 29 outPut = new QMultiLineEdit( this );
30 QFont outPut_font( outPut->font() ); 30 QFont outPut_font( outPut->font() );
31 outPut_font.setPointSize( 8 ); 31 outPut_font.setPointSize( 8 );
32 outPut->setFont( outPut_font ); 32 outPut->setFont( outPut_font );
33 outPut->setWordWrap( QMultiLineEdit::WidgetWidth ); 33 outPut->setWordWrap( QMultiLineEdit::WidgetWidth );
34 34
35 connectButton = new QPushButton( this ); 35 connectButton = new QPushButton( this );
36 connectButton->setText( tr( "Connect" ) ); 36 connectButton->setText( tr( "Connect" ) );
37 37
38 layout->addWidget(info); 38 layout->addWidget(info);
39 layout->addWidget(cmdLine); 39 layout->addWidget(cmdLine);
40 layout->addWidget(outPut); 40 layout->addWidget(outPut);
41 layout->addWidget(connectButton); 41 layout->addWidget(connectButton);
42 42
43 connect( connectButton, SIGNAL( clicked() ), this, SLOT( connectToDevice() ) ); 43 connect( connectButton, SIGNAL( clicked() ), this, SLOT( connectToDevice() ) );
44 44
45} 45}
46 46
47PPPDialog::~PPPDialog() { 47PPPDialog::~PPPDialog() {
48} 48}
49 49
50void PPPDialog::connectToDevice() { 50void PPPDialog::connectToDevice() {
51 outPut->clear(); 51 outPut->clear();
52 // vom popupmenu beziehen 52 // vom popupmenu beziehen
53 QString connectScript = "/etc/ppp/peers/" + cmdLine->text(); 53 QString connectScript = "/etc/ppp/peers/" + cmdLine->text();
54 OProcess* pppDial = new OProcess(); 54 OProcess* pppDial = new OProcess();
55 *pppDial << "pppd" << m_device << "call" << connectScript; 55 *pppDial << "pppd" << m_device << "call" << connectScript;
56 connect( pppDial, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int) ), 56 connect( pppDial, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int) ),
57 this, SLOT(fillOutPut(Opie::Core::OProcess*,char*,int) ) ); 57 this, SLOT(fillOutPut(Opie::Core::OProcess*,char*,int) ) );
58 if (!pppDial->start(OProcess::DontCare, OProcess::AllOutput) ) { 58 if (!pppDial->start(OProcess::DontCare, OProcess::AllOutput) ) {
59 qWarning("could not start"); 59 owarn << "could not start" << oendl;
60 delete pppDial; 60 delete pppDial;
61 } 61 }
62} 62}
63 63
64void PPPDialog::fillOutPut( OProcess* pppDial, char* cha, int len ) { 64void PPPDialog::fillOutPut( OProcess* pppDial, char* cha, int len ) {
65 QCString str(cha, len ); 65 QCString str(cha, len );
66 outPut->insertLine( str ); 66 outPut->insertLine( str );
67 delete pppDial; 67 delete pppDial;
68} 68}
69 69
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 @@
1 1
2#include "rfcommassigndialogimpl.h" 2#include "rfcommassigndialogimpl.h"
3#include "rfcommassigndialogitem.h" 3#include "rfcommassigndialogitem.h"
4#include "rfcommconfhandler.h" 4#include "rfcommconfhandler.h"
5 5
6/* OPIE */ 6/* OPIE */
7#include <qpe/config.h> 7#include <qpe/config.h>
8#include <qpe/qpeapplication.h> 8#include <qpe/qpeapplication.h>
9 9
10/* QT */ 10/* QT */
11#include <qlayout.h> 11#include <qlayout.h>
12 12
13using namespace OpieTooth; 13using namespace OpieTooth;
14 14
15// TODO: write only the file in bluebase? 15// TODO: write only the file in bluebase?
16// muss rfcommd dann neu gestartet werden 16// muss rfcommd dann neu gestartet werden
17// sollte rfcomm bind all nicht eh default config sein ( polled das? - d.h. sobald nen gerät in der nähe ist bindet es? 17// sollte rfcomm bind all nicht eh default config sein ( polled das? - d.h. sobald nen gerät in der nähe ist bindet es?
18 18
19 19
20RfcommAssignDialog::RfcommAssignDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) 20RfcommAssignDialog::RfcommAssignDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
21 : RfcommAssignDialogBase( parent, name, modal, fl ) 21 : RfcommAssignDialogBase( parent, name, modal, fl )
22{ 22{
23 23
24 m_range = 5; 24 m_range = 5;
25 25
26 m_scrollView = new QScrollView( this ); 26 m_scrollView = new QScrollView( this );
27 m_scrollView->setResizePolicy( QScrollView::AutoOneFit ); 27 m_scrollView->setResizePolicy( QScrollView::AutoOneFit );
28 m_scrollView->setHScrollBarMode( QScrollView::AlwaysOff ); 28 m_scrollView->setHScrollBarMode( QScrollView::AlwaysOff );
29 29
30 RfcommAssignDialogBaseLayout->addWidget( m_scrollView ); 30 RfcommAssignDialogBaseLayout->addWidget( m_scrollView );
31 31
32 m_box = new QVBox( m_scrollView->viewport() ); 32 m_box = new QVBox( m_scrollView->viewport() );
33 m_scrollView->addChild( m_box ); 33 m_scrollView->addChild( m_box );
34 34
35 confHandler = new RfCommConfHandler( "/etc/bluetooth/rfcomm.conf" ); 35 confHandler = new RfCommConfHandler( "/etc/bluetooth/rfcomm.conf" );
36 36
37 loadConfig(); 37 loadConfig();
38} 38}
39 39
40RfcommAssignDialog::~RfcommAssignDialog() 40RfcommAssignDialog::~RfcommAssignDialog()
41{ 41{
42 if ( confHandler ) 42 if ( confHandler )
43 { 43 {
44 delete confHandler; 44 delete confHandler;
45 } 45 }
46} 46}
47 47
48 48
49void RfcommAssignDialog::newDevice( const QString & mac ) 49void RfcommAssignDialog::newDevice( const QString & mac )
50{ 50{
51 51
52 for ( int i = 0 ; i < m_range; i++ ) 52 for ( int i = 0 ; i < m_range; i++ )
53 { 53 {
54 54
55 QMap<QString, RfCommConfObject*>::Iterator it; 55 QMap<QString, RfCommConfObject*>::Iterator it;
56 it = confHandler->foundEntries().find( QString("%1").arg( i ) ); 56 it = confHandler->foundEntries().find( QString("%1").arg( i ) );
57 // make sure that rfcommX is not assigned yet 57 // make sure that rfcommX is not assigned yet
58 if ( it == confHandler->foundEntries().end() ) 58 if ( it == confHandler->foundEntries().end() )
59 { 59 {
60 QDialog dialog( this, "newdevice", true, WStyle_ContextHelp ); 60 QDialog dialog( this, "newdevice", true, WStyle_ContextHelp );
61 61
62 RfcommDialogItem *newDev = new RfcommDialogItem( &dialog ); 62 RfcommDialogItem *newDev = new RfcommDialogItem( &dialog );
63 newDev->setIdent( i ); 63 newDev->setIdent( i );
64 newDev->setMac( mac ); 64 newDev->setMac( mac );
65 65
66 if ( QPEApplication::execDialog( &dialog ) == QDialog::Accepted ) 66 if ( QPEApplication::execDialog( &dialog ) == QDialog::Accepted )
67 { 67 {
68 RfcommDialogItem *rfcomm = new RfcommDialogItem( m_box ); 68 RfcommDialogItem *rfcomm = new RfcommDialogItem( m_box );
69 m_itemList.insert( i , rfcomm ); 69 m_itemList.insert( i , rfcomm );
70 rfcomm->setIdent( i ); 70 rfcomm->setIdent( i );
71 rfcomm->setMac( mac ); 71 rfcomm->setMac( mac );
72 rfcomm->setChannel( newDev->channel() ); 72 rfcomm->setChannel( newDev->channel() );
73 rfcomm->setComment( newDev->comment() ); 73 rfcomm->setComment( newDev->comment() );
74 qDebug( "New device set up" ); 74 odebug << "New device set up" << oendl;
75 } 75 }
76 } 76 }
77 } 77 }
78} 78}
79 79
80void RfcommAssignDialog::loadConfig() 80void RfcommAssignDialog::loadConfig()
81{ 81{
82 82
83 //Config cfg( "bluetoothmanager-rfcommbind" ); 83 //Config cfg( "bluetoothmanager-rfcommbind" );
84 84
85 for ( int i = 0 ; i < m_range; i++ ) 85 for ( int i = 0 ; i < m_range; i++ )
86 { 86 {
87 // cfg.setGroup( QString("%1").arg( i ) ); 87 // cfg.setGroup( QString("%1").arg( i ) );
88 RfcommDialogItem *rfcomm = new RfcommDialogItem( m_box ); 88 RfcommDialogItem *rfcomm = new RfcommDialogItem( m_box );
89 m_itemList.insert( i , rfcomm ); 89 m_itemList.insert( i , rfcomm );
90 rfcomm->setIdent( i ); 90 rfcomm->setIdent( i );
91 QMap<QString, RfCommConfObject*>::Iterator it; 91 QMap<QString, RfCommConfObject*>::Iterator it;
92 it = confHandler->foundEntries().find( QString("%1").arg( i ) ); 92 it = confHandler->foundEntries().find( QString("%1").arg( i ) );
93 if ( it != confHandler->foundEntries().end() ) 93 if ( it != confHandler->foundEntries().end() )
94 { 94 {
95 qDebug( "Found key in foundEntries() " ); 95 odebug << "Found key in foundEntries() " << oendl;
96 rfcomm->setMac( it.data()->mac() ); 96 rfcomm->setMac( it.data()->mac() );
97 rfcomm->setChannel( it.data()->channel() ); 97 rfcomm->setChannel( it.data()->channel() );
98 rfcomm->setComment( it.data()->comment() ); 98 rfcomm->setComment( it.data()->comment() );
99 } 99 }
100 /* Use rfcomm.conf directly for now 100 /* Use rfcomm.conf directly for now
101 * rfcomm->setMac( cfg.readEntry( "mac", "" ) ); 101 * rfcomm->setMac( cfg.readEntry( "mac", "" ) );
102 * rfcomm->setChannel( cfg.readNumEntry( "channel", 1 ) ); 102 * rfcomm->setChannel( cfg.readNumEntry( "channel", 1 ) );
103 * rfcomm->setComment( cfg.readEntry( "comment", "" ) ); 103 * rfcomm->setComment( cfg.readEntry( "comment", "" ) );
104 */ 104 */
105 } 105 }
106} 106}
107 107
108 108
109void RfcommAssignDialog::saveConfig() 109void RfcommAssignDialog::saveConfig()
110{ 110{
111 111
112 //Config cfg( "bluetoothmanager-rfcommbind" ); 112 //Config cfg( "bluetoothmanager-rfcommbind" );
113 113
114 QMap< int, RfcommDialogItem*>::Iterator it; 114 QMap< int, RfcommDialogItem*>::Iterator it;
115 115
116 QMap< QString, RfCommConfObject*> outMap; 116 QMap< QString, RfCommConfObject*> outMap;
117 117
118 for( it = m_itemList.begin(); it != m_itemList.end(); ++it ) 118 for( it = m_itemList.begin(); it != m_itemList.end(); ++it )
119 { 119 {
120 120
121 //cfg.setGroup( QString("%1").arg( it.key() ) ); 121 //cfg.setGroup( QString("%1").arg( it.key() ) );
122 RfcommDialogItem *rfcomm = it.data(); 122 RfcommDialogItem *rfcomm = it.data();
123 123
124 124
125 outMap.insert( QString( "%1").arg( it.key() ), new RfCommConfObject( it.key(), rfcomm->mac(), rfcomm->channel(), rfcomm->comment() ) ); 125 outMap.insert( QString( "%1").arg( it.key() ), new RfCommConfObject( it.key(), rfcomm->mac(), rfcomm->channel(), rfcomm->comment() ) );
126 126
127 127
128 //cfg.writeEntry( "mac", rfcomm->mac() ); 128 //cfg.writeEntry( "mac", rfcomm->mac() );
129 //cfg.writeEntry( "channel", rfcomm->channel() ); 129 //cfg.writeEntry( "channel", rfcomm->channel() );
130 //cfg.writeEntry( "comment", rfcomm->comment() ); 130 //cfg.writeEntry( "comment", rfcomm->comment() );
131 } 131 }
132 132
133 confHandler->save( outMap ); 133 confHandler->save( outMap );
134 134
135} 135}
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 @@
1 1
2#include <qtextstream.h> 2#include <qtextstream.h>
3 3
4#include "rfcommconfhandler.h" 4#include "rfcommconfhandler.h"
5 5
6 6
7using namespace OpieTooth; 7using namespace OpieTooth;
8 8
9// move to lib 9// move to lib
10 10
11 11
12RfCommConfObject::RfCommConfObject( int number, QString mac, int channel, QString comment ) { 12RfCommConfObject::RfCommConfObject( int number, QString mac, int channel, QString comment ) {
13 m_number = number; 13 m_number = number;
14 m_mac = mac; 14 m_mac = mac;
15 m_channel = channel; 15 m_channel = channel;
16 m_comment = comment; 16 m_comment = comment;
17 // m_foundEntries = 0; 17 // m_foundEntries = 0;
18} 18}
19 19
20void RfCommConfObject::setNumber( int number ) { 20void RfCommConfObject::setNumber( int number ) {
21 m_number = number; 21 m_number = number;
22} 22}
23 23
24void RfCommConfObject::setMac( QString mac ) { 24void RfCommConfObject::setMac( QString mac ) {
25 m_mac = mac; 25 m_mac = mac;
26} 26}
27 27
28void RfCommConfObject::setChannel( int channel ) { 28void RfCommConfObject::setChannel( int channel ) {
29 m_channel = channel; 29 m_channel = channel;
30} 30}
31 31
32void RfCommConfObject::setComment( QString comment ) { 32void RfCommConfObject::setComment( QString comment ) {
33 m_comment = comment; 33 m_comment = comment;
34} 34}
35 35
36 36
37RfCommConfObject::~RfCommConfObject() { 37RfCommConfObject::~RfCommConfObject() {
38} 38}
39 39
40 40
41RfCommConfHandler::RfCommConfHandler( const QString & filename ) { 41RfCommConfHandler::RfCommConfHandler( const QString & filename ) {
42 42
43 m_filename = filename; 43 m_filename = filename;
44 load(); 44 load();
45} 45}
46 46
47RfCommConfHandler::~RfCommConfHandler() { 47RfCommConfHandler::~RfCommConfHandler() {
48 48
49} 49}
50 50
51void RfCommConfHandler::save( QMap<QString, RfCommConfObject*> devices ) { 51void RfCommConfHandler::save( QMap<QString, RfCommConfObject*> devices ) {
52 52
53 QFile rfCommConf( "/tmp/test" ); 53 QFile rfCommConf( "/tmp/test" );
54 QTextStream outStream( &rfCommConf ); 54 QTextStream outStream( &rfCommConf );
55 if ( rfCommConf.open( IO_WriteOnly ) ) { 55 if ( rfCommConf.open( IO_WriteOnly ) ) {
56 56
57 QMap<QString, RfCommConfObject*>::Iterator it; 57 QMap<QString, RfCommConfObject*>::Iterator it;
58 for( it = devices.begin(); it != devices.end(); ++it ) { 58 for( it = devices.begin(); it != devices.end(); ++it ) {
59 outStream << "rfcomm" + QString("%1").arg( it.data()->number() ) + " {\n"; 59 outStream << "rfcomm" + QString("%1").arg( it.data()->number() ) + " {\n";
60 outStream << " device " + it.data()->mac() + ";\n"; 60 outStream << " device " + it.data()->mac() + ";\n";
61 outStream << " channel " + QString( "%1" ).arg( it.data()->channel() ) + ";\n"; 61 outStream << " channel " + QString( "%1" ).arg( it.data()->channel() ) + ";\n";
62 outStream << " comment \"" + it.data()->comment() + "\";\n"; 62 outStream << " comment \"" + it.data()->comment() + "\";\n";
63 outStream << "}\n\n"; 63 outStream << "}\n\n";
64 } 64 }
65 65
66 rfCommConf.close(); 66 rfCommConf.close();
67 } 67 }
68} 68}
69 69
70 70
71QMap<QString, RfCommConfObject*> RfCommConfHandler::foundEntries() { 71QMap<QString, RfCommConfObject*> RfCommConfHandler::foundEntries() {
72 return m_foundEntries; 72 return m_foundEntries;
73} 73}
74 74
75void RfCommConfHandler::load() { 75void RfCommConfHandler::load() {
76 76
77 QFile rfCommConf( m_filename ); 77 QFile rfCommConf( m_filename );
78 if ( rfCommConf.open( IO_ReadOnly ) ) { 78 if ( rfCommConf.open( IO_ReadOnly ) ) {
79 79
80 QStringList list; 80 QStringList list;
81 QTextStream inStream( &rfCommConf ); 81 QTextStream inStream( &rfCommConf );
82 list = QStringList::split( "\n", inStream.read() ); 82 list = QStringList::split( "\n", inStream.read() );
83 83
84 QString number; 84 QString number;
85 QString mac; 85 QString mac;
86 QString channel; 86 QString channel;
87 QString comment; 87 QString comment;
88 88
89 for ( QStringList::Iterator line=list.begin(); line != list.end(); line++ ) { 89 for ( QStringList::Iterator line=list.begin(); line != list.end(); line++ ) {
90 90
91 QString tmpLine = ( *line ).stripWhiteSpace(); 91 QString tmpLine = ( *line ).stripWhiteSpace();
92 92
93 if ( tmpLine.startsWith("rfcomm") ) { 93 if ( tmpLine.startsWith("rfcomm") ) {
94 QString number = tmpLine.mid( 6,1 ); 94 QString number = tmpLine.mid( 6,1 );
95 qDebug( tmpLine ); 95 odebug << tmpLine << oendl;
96 qDebug( "TEST " + number ); 96 odebug << "TEST " + number << oendl;
97 } else if ( tmpLine.startsWith( "}" ) ) { 97 } else if ( tmpLine.startsWith( "}" ) ) {
98 m_foundEntries.insert( number, new RfCommConfObject( number.toInt(), mac, channel.toInt(), comment ) ); 98 m_foundEntries.insert( number, new RfCommConfObject( number.toInt(), mac, channel.toInt(), comment ) );
99 } else if ( tmpLine.startsWith( "device" ) ) { 99 } else if ( tmpLine.startsWith( "device" ) ) {
100 mac = tmpLine.mid( 7, 17 ); 100 mac = tmpLine.mid( 7, 17 );
101 qDebug( "mac" + mac ); 101 odebug << "mac" + mac << oendl;
102 } else if ( tmpLine.startsWith( "channel" ) ) { 102 } else if ( tmpLine.startsWith( "channel" ) ) {
103 channel = tmpLine.mid( 8, 1 ); 103 channel = tmpLine.mid( 8, 1 );
104 qDebug ( "Channel :" + channel ); 104 qDebug ( "Channel :" + channel );
105 } else if ( tmpLine.startsWith( "comment" ) ) { 105 } else if ( tmpLine.startsWith( "comment" ) ) {
106 comment = tmpLine.mid( 9, tmpLine.find( ';' ) - 9 - 1 ); 106 comment = tmpLine.mid( 9, tmpLine.find( ';' ) - 9 - 1 );
107 qDebug( "Comment: " + comment ); 107 odebug << "Comment: " + comment << oendl;
108 } 108 }
109 } 109 }
110 rfCommConf.close(); 110 rfCommConf.close();
111 } 111 }
112 save( m_foundEntries ); 112 save( m_foundEntries );
113 qDebug( QString( "ENTries: %1").arg( m_foundEntries.count() ) ); 113 odebug << QString( "ENTries: %1").arg( m_foundEntries.count() ) << oendl;
114} 114}
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 @@
1 1
2#include "pppdialog.h" 2#include "pppdialog.h"
3#include "rfcpopup.h" 3#include "rfcpopup.h"
4#include "rfcommassigndialogimpl.h" 4#include "rfcommassigndialogimpl.h"
5 5
6/* OPIE */ 6/* OPIE */
7#include <qpe/qpeapplication.h> 7#include <qpe/qpeapplication.h>
8 8
9/* QT */ 9/* QT */
10#include <qtimer.h> 10#include <qtimer.h>
11 11
12using namespace OpieTooth; 12using namespace OpieTooth;
13 13
14/* 14/*
15 * c'tor init the QAction 15 * c'tor init the QAction
16 */ 16 */
17RfcCommPopup::RfcCommPopup( OpieTooth::BTDeviceItem* item ) 17RfcCommPopup::RfcCommPopup( OpieTooth::BTDeviceItem* item )
18 : QPopupMenu() 18 : QPopupMenu()
19{ 19{
20 qWarning("RfcCommPopup c'tor"); 20 owarn << "RfcCommPopup c'tor" << oendl;
21 21
22 QAction* a; 22 QAction* a;
23 23
24 24
25 m_item = item; 25 m_item = item;
26 26
27 /* connect action */ 27 /* connect action */
28 a = new QAction( ); // so it's get deleted 28 a = new QAction( ); // so it's get deleted
29 a->setText("Connect"); 29 a->setText("Connect");
30 a->addTo( this ); 30 a->addTo( this );
31 connect( a, SIGNAL( activated() ), 31 connect( a, SIGNAL( activated() ),
32 this, SLOT( slotConnect() ) ); 32 this, SLOT( slotConnect() ) );
33 33
34 34
35 /* disconnect action */ 35 /* disconnect action */
36 a = new QAction( ); 36 a = new QAction( );
37 a->setText("Disconnect"); 37 a->setText("Disconnect");
38 a->addTo( this ); 38 a->addTo( this );
39 connect( a, SIGNAL( activated() ) , 39 connect( a, SIGNAL( activated() ) ,
40 this, SLOT( slotDisconnect() ) ); 40 this, SLOT( slotDisconnect() ) );
41 41
42 42
43 /* foo action */ 43 /* foo action */
44 a = new QAction( ); 44 a = new QAction( );
45 a->setText("Bind table"); 45 a->setText("Bind table");
46 a->addTo( this ); 46 a->addTo( this );
47 connect( a, SIGNAL( activated() ), 47 connect( a, SIGNAL( activated() ),
48 this, SLOT( slotBind() ) ); 48 this, SLOT( slotBind() ) );
49 49
50 50
51 /* bar action */ 51 /* bar action */
52 a = new QAction( ); 52 a = new QAction( );
53 a->setText( "Bar" ); 53 a->setText( "Bar" );
54 a->addTo( this ); 54 a->addTo( this );
55 connect( a, SIGNAL( activated() ), 55 connect( a, SIGNAL( activated() ),
56 this, SLOT( slotBar() ) ); 56 this, SLOT( slotBar() ) );
57 57
58}; 58};
59 59
60 60
61RfcCommPopup::~RfcCommPopup() 61RfcCommPopup::~RfcCommPopup()
62{ 62{
63 /* delete m_con; 63 /* delete m_con;
64 delete m_dis; 64 delete m_dis;
65 delete m_foo; 65 delete m_foo;
66 delete m_bar; */ 66 delete m_bar; */
67} 67}
68 68
69 69
70void RfcCommPopup::slotConnect() 70void RfcCommPopup::slotConnect()
71{ 71{
72 72
73 qWarning("connect"); 73 owarn << "connect" << oendl;
74 74
75 PPPDialog pppDialog; 75 PPPDialog pppDialog;
76 QPEApplication::execDialog( &pppDialog ); 76 QPEApplication::execDialog( &pppDialog );
77} 77}
78 78
79 79
80void RfcCommPopup::slotDisconnect() 80void RfcCommPopup::slotDisconnect()
81{ 81{
82 qWarning("slot disconnected"); 82 owarn << "slot disconnected" << oendl;
83} 83}
84 84
85 85
86void RfcCommPopup::slotBind() 86void RfcCommPopup::slotBind()
87{ 87{
88 RfcommAssignDialog rfcommAssign ( this, "RfcommAssignDialog", true, WStyle_ContextHelp ); 88 RfcommAssignDialog rfcommAssign ( this, "RfcommAssignDialog", true, WStyle_ContextHelp );
89 89
90 rfcommAssign.newDevice( m_item->mac() ); 90 rfcommAssign.newDevice( m_item->mac() );
91 91
92 if ( QPEApplication::execDialog( &rfcommAssign ) == QDialog::Accepted ) 92 if ( QPEApplication::execDialog( &rfcommAssign ) == QDialog::Accepted )
93 { 93 {
94 rfcommAssign.saveConfig(); 94 rfcommAssign.saveConfig();
95 } 95 }
96} 96}
97 97
98 98
99void RfcCommPopup::slotBar() 99void RfcCommPopup::slotBar()
100{ 100{
101 qWarning("slotBar"); 101 owarn << "slotBar" << oendl;
102}; 102};
103 103
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 {
62 Layout11->addWidget( ListView1 ); 62 Layout11->addWidget( ListView1 );
63 Layout11->addWidget( progress ); 63 Layout11->addWidget( progress );
64 Layout11->addWidget( StartStopButton ); 64 Layout11->addWidget( StartStopButton );
65 65
66 localDevice = new Manager( "hci0" ); 66 localDevice = new Manager( "hci0" );
67 67
68 connect( StartStopButton, SIGNAL( clicked() ), this, SLOT( startSearch() ) ); 68 connect( StartStopButton, SIGNAL( clicked() ), this, SLOT( startSearch() ) );
69 connect( localDevice, SIGNAL( foundDevices(const QString&,RemoteDevice::ValueList) ), 69 connect( localDevice, SIGNAL( foundDevices(const QString&,RemoteDevice::ValueList) ),
70 this, SLOT( fillList(const QString&,RemoteDevice::ValueList) ) ) ; 70 this, SLOT( fillList(const QString&,RemoteDevice::ValueList) ) ) ;
71 71
72 progressStat = 0; 72 progressStat = 0;
73 m_search = false; 73 m_search = false;
74 } 74 }
75 75
76// hack, make cleaner later 76// hack, make cleaner later
77 void ScanDialog::progressTimer() { 77 void ScanDialog::progressTimer() {
78 78
79 progressStat++; 79 progressStat++;
80 if ( progressStat++ < 20 && m_search ) { 80 if ( progressStat++ < 20 && m_search ) {
81 QTimer::singleShot( 2000, this, SLOT( progressTimer() ) ); 81 QTimer::singleShot( 2000, this, SLOT( progressTimer() ) );
82 progress->setProgress( progressStat++ ); 82 progress->setProgress( progressStat++ );
83 } 83 }
84 } 84 }
85 85
86 void ScanDialog::accept() { 86 void ScanDialog::accept() {
87 emitToManager(); 87 emitToManager();
88 QDialog::accept(); 88 QDialog::accept();
89 } 89 }
90 90
91 91
92 void ScanDialog::startSearch() { 92 void ScanDialog::startSearch() {
93 if ( m_search ) { 93 if ( m_search ) {
94 stopSearch(); 94 stopSearch();
95 return; 95 return;
96 } 96 }
97 m_search = true; 97 m_search = true;
98 progress->setProgress(0); 98 progress->setProgress(0);
99 progressStat = 0; 99 progressStat = 0;
100 100
101 // empty list before a new scan 101 // empty list before a new scan
102 ListView1->clear(); 102 ListView1->clear();
103 103
104 progressTimer(); 104 progressTimer();
105 // when finished, it emmite foundDevices() 105 // when finished, it emmite foundDevices()
106 // checken ob initialisiert , qcop ans applet. 106 // checken ob initialisiert , qcop ans applet.
107 StartStopButton->setText( tr( "Stop scan" ) ); 107 StartStopButton->setText( tr( "Stop scan" ) );
108 108
109 localDevice->searchDevices(); 109 localDevice->searchDevices();
110 110
111 } 111 }
112 112
113 void ScanDialog::stopSearch() { 113 void ScanDialog::stopSearch() {
114 m_search = true; 114 m_search = true;
115 } 115 }
116 116
117 void ScanDialog::fillList(const QString&, RemoteDevice::ValueList deviceList) { 117 void ScanDialog::fillList(const QString&, RemoteDevice::ValueList deviceList) {
118 progress->setProgress(0); 118 progress->setProgress(0);
119 progressStat = 0; 119 progressStat = 0;
120 QCheckListItem * deviceItem; 120 QCheckListItem * deviceItem;
121 121
122 RemoteDevice::ValueList::Iterator it; 122 RemoteDevice::ValueList::Iterator it;
123 for( it = deviceList.begin(); it != deviceList.end(); ++it ) { 123 for( it = deviceList.begin(); it != deviceList.end(); ++it ) {
124 124
125 deviceItem = new QCheckListItem( ListView1, (*it).name(), QCheckListItem::CheckBox ); 125 deviceItem = new QCheckListItem( ListView1, (*it).name(), QCheckListItem::CheckBox );
126 deviceItem->setText( 1, (*it).mac() ); 126 deviceItem->setText( 1, (*it).mac() );
127 } 127 }
128 m_search = false; 128 m_search = false;
129 StartStopButton->setText( tr( "Start scan" ) ); 129 StartStopButton->setText( tr( "Start scan" ) );
130 } 130 }
131 131
132/** 132/**
133 * Iterates trough the items, and collects the checked items. 133 * Iterates trough the items, and collects the checked items.
134 * Then it emits it, so the manager can connect to the signal to fill the listing. 134 * Then it emits it, so the manager can connect to the signal to fill the listing.
135 */ 135 */
136 void ScanDialog::emitToManager() { 136 void ScanDialog::emitToManager() {
137 137
138 if (!ListView1) { 138 if (!ListView1) {
139 return; 139 return;
140 } 140 }
141 141
142 QValueList<RemoteDevice> deviceList; 142 QValueList<RemoteDevice> deviceList;
143 143
144 QListViewItemIterator it( ListView1 ); 144 QListViewItemIterator it( ListView1 );
145 for ( ; it.current(); ++it ) { 145 for ( ; it.current(); ++it ) {
146 if ( ( (QCheckListItem*)it.current() )->isOn() ) { 146 if ( ( (QCheckListItem*)it.current() )->isOn() ) {
147 RemoteDevice device( it.current()->text(1), it.current()->text(0) ); 147 RemoteDevice device( it.current()->text(1), it.current()->text(0) );
148 deviceList.append( device ); 148 deviceList.append( device );
149 } 149 }
150 } 150 }
151 emit selectedDevices( deviceList ); 151 emit selectedDevices( deviceList );
152 } 152 }
153 153
154/** 154/**
155 * Cleanup 155 * Cleanup
156 */ 156 */
157 ScanDialog::~ScanDialog() { 157 ScanDialog::~ScanDialog() {
158 qWarning("delete scan dialog"); 158 owarn << "delete scan dialog" << oendl;
159 delete localDevice; 159 delete localDevice;
160 } 160 }
161} 161}
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Wellenreiter II. 4** This file is part of Wellenreiter II.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16/* LOCAL */ 16/* LOCAL */
17#include "configwindow.h" 17#include "configwindow.h"
18#include "mainwindow.h" 18#include "mainwindow.h"
19 19
20/* OPIE */ 20/* OPIE */
21#include <opie2/onetwork.h> 21#include <opie2/onetwork.h>
22#ifdef QWS 22#ifdef QWS
23#include <opie2/oapplication.h> 23#include <opie2/oapplication.h>
24#include <opie2/oconfig.h> 24#include <opie2/oconfig.h>
25#include <opie2/odevice.h> 25#include <opie2/odevice.h>
26using namespace Opie; 26#include <opie2/odebug.h>
27using namespace Opie::Core;
28using namespace Opie::Net;
27#endif 29#endif
28 30
29/* QT */ 31/* QT */
30#include <qapplication.h> 32#include <qapplication.h>
31#include <qcheckbox.h> 33#include <qcheckbox.h>
32#include <qcombobox.h> 34#include <qcombobox.h>
33#include <qfile.h> 35#include <qfile.h>
34#include <qlineedit.h> 36#include <qlineedit.h>
35#include <qlayout.h> 37#include <qlayout.h>
36#include <qmap.h> 38#include <qmap.h>
37#include <qpushbutton.h> 39#include <qpushbutton.h>
38#include <qtabwidget.h> 40#include <qtabwidget.h>
39#include <qtoolbutton.h> 41#include <qtoolbutton.h>
40#include <qspinbox.h> 42#include <qspinbox.h>
41#include <qtextstream.h> 43#include <qtextstream.h>
42 44
43/* POSIX */ 45/* STD */
44#include <assert.h> 46#include <assert.h>
45 47
46using namespace Opie::Core;
47using namespace Opie::Net;
48using namespace Opie::Core;
49using namespace Opie::Net;
50using namespace Opie::Core;
51using namespace Opie::Net;
52WellenreiterConfigWindow* WellenreiterConfigWindow::_instance = 0; 48WellenreiterConfigWindow* WellenreiterConfigWindow::_instance = 0;
53 49
54WellenreiterConfigWindow::WellenreiterConfigWindow( QWidget * parent, const char * name, WFlags f ) 50WellenreiterConfigWindow::WellenreiterConfigWindow( QWidget * parent, const char * name, WFlags f )
55 :WellenreiterConfigBase( parent, name, true, f ) 51 :WellenreiterConfigBase( parent, name, true, f )
56{ 52{
57 _devicetype[ "cisco" ] = DEVTYPE_CISCO; 53 _devicetype[ "cisco" ] = DEVTYPE_CISCO;
58 _devicetype[ "wlan-ng" ] = DEVTYPE_WLAN_NG; 54 _devicetype[ "wlan-ng" ] = DEVTYPE_WLAN_NG;
59 _devicetype[ "hostap" ] = DEVTYPE_HOSTAP; 55 _devicetype[ "hostap" ] = DEVTYPE_HOSTAP;
60 _devicetype[ "orinoco" ] = DEVTYPE_ORINOCO; 56 _devicetype[ "orinoco" ] = DEVTYPE_ORINOCO;
61 _devicetype[ "<manual>" ] = DEVTYPE_MANUAL; 57 _devicetype[ "<manual>" ] = DEVTYPE_MANUAL;
62 _devicetype[ "<file>" ] = DEVTYPE_FILE; 58 _devicetype[ "<file>" ] = DEVTYPE_FILE;
63 59
64 // gather possible interface names from ONetwork 60 // gather possible interface names from ONetwork
65 ONetwork* net = ONetwork::instance(); 61 ONetwork* net = ONetwork::instance();
66 ONetwork::InterfaceIterator it = net->iterator(); 62 ONetwork::InterfaceIterator it = net->iterator();
67 while ( it.current() ) 63 while ( it.current() )
68 { 64 {
69 if ( it.current()->isWireless() ) 65 if ( it.current()->isWireless() )
70 interfaceName->insertItem( it.current()->name() ); 66 interfaceName->insertItem( it.current()->name() );
71 ++it; 67 ++it;
72 } 68 }
73 69
74 load(); 70 load();
75 71
76 #ifdef Q_WS_X11 // We're on X11: adding an Ok-Button for the Dialog here 72 #ifdef Q_WS_X11 // We're on X11: adding an Ok-Button for the Dialog here
77 QPushButton* okButton = new QPushButton( "ok", this ); 73 QPushButton* okButton = new QPushButton( "ok", this );
78 okButton->show(); 74 okButton->show();
79 WellenreiterConfigBaseLayout->addWidget( okButton, 0, 3 ); //FIXME: rename this in configbase.ui 75 WellenreiterConfigBaseLayout->addWidget( okButton, 0, 3 ); //FIXME: rename this in configbase.ui
80 connect( okButton, SIGNAL( clicked() ), this, SLOT( accept() ) ); 76 connect( okButton, SIGNAL( clicked() ), this, SLOT( accept() ) );
81 #endif 77 #endif
82 78
83 WellenreiterConfigWindow::_instance = this; 79 WellenreiterConfigWindow::_instance = this;
84 80
85 connect( deviceType, SIGNAL( activated(int) ), this, SLOT( changedDeviceType(int) ) ); 81 connect( deviceType, SIGNAL( activated(int) ), this, SLOT( changedDeviceType(int) ) );
86 connect( newNetworkAction, SIGNAL( activated(int) ), this, SLOT( changedNetworkAction(int) ) ); 82 connect( newNetworkAction, SIGNAL( activated(int) ), this, SLOT( changedNetworkAction(int) ) );
87 connect( newClientAction, SIGNAL( activated(int) ), this, SLOT( changedClientAction(int) ) ); 83 connect( newClientAction, SIGNAL( activated(int) ), this, SLOT( changedClientAction(int) ) );
88 connect( newStationAction, SIGNAL( activated(int) ), this, SLOT( changedStationAction(int) ) ); 84 connect( newStationAction, SIGNAL( activated(int) ), this, SLOT( changedStationAction(int) ) );
89 connect( getCaptureFileName, SIGNAL( clicked() ), this, SLOT( getCaptureFileNameClicked() ) ); 85 connect( getCaptureFileName, SIGNAL( clicked() ), this, SLOT( getCaptureFileNameClicked() ) );
90 86
91 // make the checkbox 'channelAll' control all other channels 87 // make the checkbox 'channelAll' control all other channels
92 connect( channelAll, SIGNAL( stateChanged(int) ), this, SLOT( channelAllClicked(int) ) ); 88 connect( channelAll, SIGNAL( stateChanged(int) ), this, SLOT( channelAllClicked(int) ) );
93 89
94 connect( autodetect, SIGNAL( clicked() ), this, SLOT( performAutodetection() ) ); 90 connect( autodetect, SIGNAL( clicked() ), this, SLOT( performAutodetection() ) );
95 91
96 // hide tab4 (parse) until Wellenreiter 1.2 92 // hide tab4 (parse) until Wellenreiter 1.2
97 tab->removePage( tab_4 ); 93 tab->removePage( tab_4 );
98}; 94};
99 95
100 96
101void WellenreiterConfigWindow::accept() 97void WellenreiterConfigWindow::accept()
102{ 98{
103 save(); 99 save();
104 QDialog::accept(); 100 QDialog::accept();
105} 101}
106 102
107 103
108WellenreiterConfigWindow::~WellenreiterConfigWindow() 104WellenreiterConfigWindow::~WellenreiterConfigWindow()
109{ 105{
110} 106}
111 107
112 108
113void WellenreiterConfigWindow::performAutodetection() 109void WellenreiterConfigWindow::performAutodetection()
114{ 110{
115 //TODO: insert modal splash screen here 111 //TODO: insert modal splash screen here
116 // and sleep a second, so that it looks 112 // and sleep a second, so that it looks
117 // like we're actually doing something fancy... ;-) 113 // like we're actually doing something fancy... ;-)
118 114
119 qDebug( "WellenreiterConfigWindow::performAutodetection()" ); 115 odebug << "WellenreiterConfigWindow::performAutodetection()" << oendl;
120 116
121 // try to guess device type 117 // try to guess device type
122 QFile m( "/proc/modules" ); 118 QFile m( "/proc/modules" );
123 if ( m.open( IO_ReadOnly ) ) 119 if ( m.open( IO_ReadOnly ) )
124 { 120 {
125 int devicetype(0); 121 int devicetype(0);
126 QString line; 122 QString line;
127 QTextStream modules( &m ); 123 QTextStream modules( &m );
128 while( !modules.atEnd() && !devicetype ) 124 while( !modules.atEnd() && !devicetype )
129 { 125 {
130 modules >> line; 126 modules >> line;
131 if ( line.contains( "cisco" ) ) devicetype = DEVTYPE_CISCO; 127 if ( line.contains( "cisco" ) ) devicetype = DEVTYPE_CISCO;
132 else if ( line.contains( "hostap" ) ) devicetype = DEVTYPE_HOSTAP; 128 else if ( line.contains( "hostap" ) ) devicetype = DEVTYPE_HOSTAP;
133 else if ( line.contains( "prism" ) ) devicetype = DEVTYPE_WLAN_NG; 129 else if ( line.contains( "prism" ) ) devicetype = DEVTYPE_WLAN_NG;
134 else if ( line.contains( "orinoco" ) ) devicetype = DEVTYPE_ORINOCO; 130 else if ( line.contains( "orinoco" ) ) devicetype = DEVTYPE_ORINOCO;
135 } 131 }
136 if ( devicetype ) 132 if ( devicetype )
137 { 133 {
138 deviceType->setCurrentItem( devicetype ); 134 deviceType->setCurrentItem( devicetype );
139 _guess = devicetype; 135 _guess = devicetype;
140 qDebug( "Wellenreiter: guessed device type to be #%d", devicetype ); 136 odebug << "Wellenreiter: guessed device type to be #" << devicetype << "" << oendl;
141 } 137 }
142 } 138 }
143} 139}
144 140
145 141
146int WellenreiterConfigWindow::driverType() const 142int WellenreiterConfigWindow::driverType() const
147{ 143{
148 QString name = deviceType->currentText(); 144 QString name = deviceType->currentText();
149 if ( _devicetype.contains( name ) ) 145 if ( _devicetype.contains( name ) )
150 { 146 {
151 return _devicetype[name]; 147 return _devicetype[name];
152 } 148 }
153 else 149 else
154 { 150 {
155 return 0; 151 return 0;
156 } 152 }
157}; 153};
158 154
159 155
160int WellenreiterConfigWindow::hoppingInterval() const 156int WellenreiterConfigWindow::hoppingInterval() const
161{ 157{
162 return hopInterval->cleanText().toInt(); 158 return hopInterval->cleanText().toInt();
163} 159}
164 160
165 161
166bool WellenreiterConfigWindow::usePrismHeader() const 162bool WellenreiterConfigWindow::usePrismHeader() const
167{ 163{
168 return prismHeader->isChecked(); 164 return prismHeader->isChecked();
169} 165}
170 166
171 167
172bool WellenreiterConfigWindow::isChannelChecked( int channel ) const 168bool WellenreiterConfigWindow::isChannelChecked( int channel ) const
173{ 169{
174 switch ( channel ) 170 switch ( channel )
175 { 171 {
176 case 1: return channel1->isOn(); 172 case 1: return channel1->isOn();
177 case 2: return channel2->isOn(); 173 case 2: return channel2->isOn();
178 case 3: return channel3->isOn(); 174 case 3: return channel3->isOn();
179 case 4: return channel4->isOn(); 175 case 4: return channel4->isOn();
180 case 5: return channel5->isOn(); 176 case 5: return channel5->isOn();
181 case 6: return channel6->isOn(); 177 case 6: return channel6->isOn();
182 case 7: return channel7->isOn(); 178 case 7: return channel7->isOn();
183 case 8: return channel8->isOn(); 179 case 8: return channel8->isOn();
184 case 9: return channel9->isOn(); 180 case 9: return channel9->isOn();
185 case 10: return channel10->isOn(); 181 case 10: return channel10->isOn();
186 case 11: return channel11->isOn(); 182 case 11: return channel11->isOn();
187 case 12: return channel12->isOn(); 183 case 12: return channel12->isOn();
188 case 13: return channel13->isOn(); 184 case 13: return channel13->isOn();
189 case 14: return channel14->isOn(); 185 case 14: return channel14->isOn();
190 } 186 }
191} 187}
192 188
193 189
194void WellenreiterConfigWindow::changedDeviceType(int t) 190void WellenreiterConfigWindow::changedDeviceType(int t)
195{ 191{
196 if ( t != DEVTYPE_FILE ) return; 192 if ( t != DEVTYPE_FILE ) return;
197 QString name = ( (WellenreiterMainWindow*) qApp->mainWidget() )->getFileName(false); 193 QString name = ( (WellenreiterMainWindow*) qApp->mainWidget() )->getFileName(false);
198 if ( !name.isEmpty() && QFile::exists( name ) ) 194 if ( !name.isEmpty() && QFile::exists( name ) )
199 { 195 {
200 interfaceName->insertItem( name ); 196 interfaceName->insertItem( name );
201 interfaceName->setCurrentItem( interfaceName->count()-1 ); 197 interfaceName->setCurrentItem( interfaceName->count()-1 );
202 } 198 }
203 else 199 else
204 { 200 {
205 deviceType->setCurrentItem( _guess ); 201 deviceType->setCurrentItem( _guess );
206 } 202 }
207 203
208} 204}
209 205
210 206
211void WellenreiterConfigWindow::synchronizeActionsAndScripts() 207void WellenreiterConfigWindow::synchronizeActionsAndScripts()
212{ 208{
213 if ( newNetworkAction->currentItem() == 4 ) newNetworkScript->show(); else newNetworkScript->hide(); 209 if ( newNetworkAction->currentItem() == 4 ) newNetworkScript->show(); else newNetworkScript->hide();
214 if ( newClientAction->currentItem() == 4 ) newClientScript->show(); else newClientScript->hide(); 210 if ( newClientAction->currentItem() == 4 ) newClientScript->show(); else newClientScript->hide();
215 if ( newStationAction->currentItem() == 4 ) newStationScript->show(); else newStationScript->hide(); 211 if ( newStationAction->currentItem() == 4 ) newStationScript->show(); else newStationScript->hide();
216 212
217 //newNetworkScript->setEnabled( newNetworkAction->currentItem() == 4 ); 213 //newNetworkScript->setEnabled( newNetworkAction->currentItem() == 4 );
218 //newClientScript->setEnabled( newClientAction->currentItem() == 4 ); 214 //newClientScript->setEnabled( newClientAction->currentItem() == 4 );
219 //newStationScript->setEnabled( newStationAction->currentItem() == 4 ); 215 //newStationScript->setEnabled( newStationAction->currentItem() == 4 );
220} 216}
221 217
222 218
223void WellenreiterConfigWindow::changedNetworkAction(int t) 219void WellenreiterConfigWindow::changedNetworkAction(int t)
224{ 220{
225 synchronizeActionsAndScripts(); 221 synchronizeActionsAndScripts();
226} 222}
227 223
228 224
229void WellenreiterConfigWindow::changedClientAction(int t) 225void WellenreiterConfigWindow::changedClientAction(int t)
230{ 226{
231 synchronizeActionsAndScripts(); 227 synchronizeActionsAndScripts();
232} 228}
233 229
234 230
235void WellenreiterConfigWindow::changedStationAction(int t) 231void WellenreiterConfigWindow::changedStationAction(int t)
236{ 232{
237 synchronizeActionsAndScripts(); 233 synchronizeActionsAndScripts();
238} 234}
239 235
240 236
241void WellenreiterConfigWindow::getCaptureFileNameClicked() 237void WellenreiterConfigWindow::getCaptureFileNameClicked()
242{ 238{
243 QString name = ( (WellenreiterMainWindow*) qApp->mainWidget() )->getFileName(true); 239 QString name = ( (WellenreiterMainWindow*) qApp->mainWidget() )->getFileName(true);
244 qDebug( "name = %s", (const char*) name ); 240 odebug << "name = " << (const char*) name << "" << oendl;
245 if ( !name.isEmpty() ) 241 if ( !name.isEmpty() )
246 { 242 {
247 captureFileName->setText( name ); 243 captureFileName->setText( name );
248 } 244 }
249} 245}
250 246
251 247
252void WellenreiterConfigWindow::channelAllClicked(int state) 248void WellenreiterConfigWindow::channelAllClicked(int state)
253{ 249{
254 bool b = state; 250 bool b = state;
255 channel1->setChecked( b ); 251 channel1->setChecked( b );
256 channel2->setChecked( b ); 252 channel2->setChecked( b );
257 channel3->setChecked( b ); 253 channel3->setChecked( b );
258 channel4->setChecked( b ); 254 channel4->setChecked( b );
259 channel5->setChecked( b ); 255 channel5->setChecked( b );
260 channel6->setChecked( b ); 256 channel6->setChecked( b );
261 channel7->setChecked( b ); 257 channel7->setChecked( b );
262 channel8->setChecked( b ); 258 channel8->setChecked( b );
263 channel9->setChecked( b ); 259 channel9->setChecked( b );
264 channel10->setChecked( b ); 260 channel10->setChecked( b );
265 channel11->setChecked( b ); 261 channel11->setChecked( b );
266 channel12->setChecked( b ); 262 channel12->setChecked( b );
267 channel13->setChecked( b ); 263 channel13->setChecked( b );
268 channel14->setChecked( b ); 264 channel14->setChecked( b );
269} 265}
270 266
271 267
272bool WellenreiterConfigWindow::useGPS() const 268bool WellenreiterConfigWindow::useGPS() const
273{ 269{
274 return enableGPS->isChecked(); 270 return enableGPS->isChecked();
275} 271}
276 272
277 273
278const QString WellenreiterConfigWindow::gpsHost() const 274const QString WellenreiterConfigWindow::gpsHost() const
279{ 275{
280 return useGPS() ? gpsdHost->currentText() : QString::null; 276 return useGPS() ? gpsdHost->currentText() : QString::null;
281} 277}
282 278
283 279
284int WellenreiterConfigWindow::gpsPort() const 280int WellenreiterConfigWindow::gpsPort() const
285{ 281{
286 bool ok; 282 bool ok;
287 return useGPS() ? gpsdPort->value() : -1; 283 return useGPS() ? gpsdPort->value() : -1;
288} 284}
289 285
290 286
291void WellenreiterConfigWindow::performAction( const QString& type, 287void WellenreiterConfigWindow::performAction( const QString& type,
292 const QString& essid, 288 const QString& essid,
293 const QString& mac, 289 const QString& mac,
294 bool wep, 290 bool wep,
295 int channel, 291 int channel,
296 int signal 292 int signal
297 /* , const GpsLocation& loc */ ) 293 /* , const GpsLocation& loc */ )
298{ 294{
299 int action; 295 int action;
300 QString script; 296 QString script;
301 297
302 if ( type == "network" ) 298 if ( type == "network" )
303 { 299 {
304 action = newNetworkAction->currentItem(); 300 action = newNetworkAction->currentItem();
305 script = newNetworkScript->text(); 301 script = newNetworkScript->text();
306 } 302 }
307 else if ( type == "managed" || type == "adhoc" ) 303 else if ( type == "managed" || type == "adhoc" )
308 { 304 {
309 action = newClientAction->currentItem(); 305 action = newClientAction->currentItem();
310 script = newClientScript->text(); 306 script = newClientScript->text();
311 } 307 }
312 else if ( type == "station" ) 308 else if ( type == "station" )
313 { 309 {
314 action = newStationAction->currentItem(); 310 action = newStationAction->currentItem();
315 script = newStationScript->text(); 311 script = newStationScript->text();
316 } 312 }
317 else 313 else
318 { 314 {
319 qWarning( "WellenreiterConfigWindow::performAction(): unknown type '%s'", (const char*) type ); 315 owarn << "WellenreiterConfigWindow::performAction(): unknown type '" << (const char*) type << "'" << oendl;
320 return; 316 return;
321 } 317 }
322 318
323 qDebug( "for event '%s' I'm going to perform action %d (script='%s')", (const char*) type, action, (const char*) script ); 319 odebug << "for event '" << (const char*) type << "' I'm going to perform action " << action << " (script='" << (const char*) script << "')" << oendl;
324 320
325 switch( action ) 321 switch( action )
326 { 322 {
327 case 0: /* Ignore */ return; 323 case 0: /* Ignore */ return;
328 case 1: /* Play Alarm */ ODevice::inst()->playAlarmSound(); return; 324 case 1: /* Play Alarm */ ODevice::inst()->playAlarmSound(); return;
329 case 2: /* Play Click */ ODevice::inst()->playTouchSound(); return; 325 case 2: /* Play Click */ ODevice::inst()->playTouchSound(); return;
330 case 3: /* Blink LED */ break; //FIXME: Implement this 326 case 3: /* Blink LED */ break; //FIXME: Implement this
331 case 4: /* Run Script */ 327 case 4: /* Run Script */
332 { 328 {
333 /** 329 /**
334 * 330 *
335 * Script Substitution Information: 331 * Script Substitution Information:
336 * 332 *
337 * $SSID = SSID 333 * $SSID = SSID
338 * $MAC = MAC 334 * $MAC = MAC
339 * $WEP = Wep 335 * $WEP = Wep
340 * $CHAN = Channel 336 * $CHAN = Channel
341 * 337 *
342 **/ 338 **/
343 script = script.replace( QRegExp( "$SSID" ), essid ); 339 script = script.replace( QRegExp( "$SSID" ), essid );
344 script = script.replace( QRegExp( "$MAC" ), mac ); 340 script = script.replace( QRegExp( "$MAC" ), mac );
345 script = script.replace( QRegExp( "$WEP" ), wep ? QString( "true" ) : QString( "false" ) ); 341 script = script.replace( QRegExp( "$WEP" ), wep ? QString( "true" ) : QString( "false" ) );
346 script = script.replace( QRegExp( "$CHAN" ), QString::number( channel ) ); 342 script = script.replace( QRegExp( "$CHAN" ), QString::number( channel ) );
347 343
348 qDebug( "going to call script '%s'", (const char*) script ); 344 odebug << "going to call script '" << (const char*) script << "'" << oendl;
349 ::system( script ); 345 ::system( script );
350 qDebug( "script returned." ); 346 odebug << "script returned." << oendl;
351 return; 347 return;
352 } 348 }
353 default: assert( false ); 349 default: assert( false );
354 } 350 }
355} 351}
356 352
357 353
358void WellenreiterConfigWindow::load() 354void WellenreiterConfigWindow::load()
359{ 355{
360#ifdef Q_WS_X11 356#ifdef Q_WS_X11
361 #warning Persistent Configuration not yet implemented for standalone X11 build 357 #warning Persistent Configuration not yet implemented for standalone X11 build
362 performAutodetection(); 358 performAutodetection();
363#else 359#else
364 qDebug( "loading configuration settings..." ); 360 odebug << "loading configuration settings..." << oendl;
365 361
366 /* This is dumb monkey typing stuff... We _need_ to do this automatically! */ 362 /* This is dumb monkey typing stuff... We _need_ to do this automatically! */
367 363
368 OConfig* c = oApp->config(); 364 OConfig* c = oApp->config();
369 365
370 c->setGroup( "Interface" ); 366 c->setGroup( "Interface" );
371 367
372 QString interface = c->readEntry( "name", "<none>" ); 368 QString interface = c->readEntry( "name", "<none>" );
373 if ( interface != "<none>" ) 369 if ( interface != "<none>" )
374 { 370 {
375#if QT_VERSION < 300 371#if QT_VERSION < 300
376 interfaceName->insertItem( interface, 0 ); 372 interfaceName->insertItem( interface, 0 );
377 interfaceName->setCurrentItem( 0 ); 373 interfaceName->setCurrentItem( 0 );
378#else 374#else
379 interfaceName->setCurrentText( interface ); 375 interfaceName->setCurrentText( interface );
380#endif 376#endif
381 377
382 QString device = c->readEntry( "type", "<select>" ); 378 QString device = c->readEntry( "type", "<select>" );
383#if QT_VERSION < 300 379#if QT_VERSION < 300
384 for ( int i = 0; i < deviceType->count(); ++i ) 380 for ( int i = 0; i < deviceType->count(); ++i )
385 { 381 {
386 if ( deviceType->text( i ) == device ) 382 if ( deviceType->text( i ) == device )
387 { 383 {
388 deviceType->setCurrentItem( i ); 384 deviceType->setCurrentItem( i );
389 break; 385 break;
390 } 386 }
391 } 387 }
392#else 388#else
393 deviceType->setCurrentText( device ); 389 deviceType->setCurrentText( device );
394#endif 390#endif
395 } 391 }
396 else 392 else
397 { 393 {
398 performAutodetection(); 394 performAutodetection();
399 } 395 }
400 396
401 prismHeader->setChecked( c->readBoolEntry( "prism", false ) ); 397 prismHeader->setChecked( c->readBoolEntry( "prism", false ) );
402 hopChannels->setChecked( c->readBoolEntry( "hop", true ) ); 398 hopChannels->setChecked( c->readBoolEntry( "hop", true ) );
403 hopInterval->setValue( c->readNumEntry( "interval", 250 ) ); 399 hopInterval->setValue( c->readNumEntry( "interval", 250 ) );
404 adaptiveHopping->setChecked( c->readBoolEntry( "adaptive", true ) ); 400 adaptiveHopping->setChecked( c->readBoolEntry( "adaptive", true ) );
405 401
406 c->setGroup( "Capture" ); 402 c->setGroup( "Capture" );
407 captureFileName->setText( c->readEntry( "filename", "/tmp/capture" ) ); 403 captureFileName->setText( c->readEntry( "filename", "/tmp/capture" ) );
408 404
409 c->setGroup( "UI" ); 405 c->setGroup( "UI" );
410 lookupVendor->setChecked( c->readBoolEntry( "lookupVendor", true ) ); 406 lookupVendor->setChecked( c->readBoolEntry( "lookupVendor", true ) );
411 openTree->setChecked( c->readBoolEntry( "openTree", true ) ); 407 openTree->setChecked( c->readBoolEntry( "openTree", true ) );
412 disablePM->setChecked( c->readBoolEntry( "disablePM", true ) ); 408 disablePM->setChecked( c->readBoolEntry( "disablePM", true ) );
413 newNetworkAction->setCurrentItem( c->readNumEntry( "newNetworkAction", 1 ) ); // Default: Play Alarm 409 newNetworkAction->setCurrentItem( c->readNumEntry( "newNetworkAction", 1 ) ); // Default: Play Alarm
414 newNetworkScript->setText( c->readEntry( "newNetworkScript", "" ) ); 410 newNetworkScript->setText( c->readEntry( "newNetworkScript", "" ) );
415 newClientAction->setCurrentItem( c->readNumEntry( "newClientAction", 2 ) ); // Default: Play Click 411 newClientAction->setCurrentItem( c->readNumEntry( "newClientAction", 2 ) ); // Default: Play Click
416 newClientScript->setText( c->readEntry( "newClientScript", "" ) ); 412 newClientScript->setText( c->readEntry( "newClientScript", "" ) );
417 newStationAction->setCurrentItem( c->readNumEntry( "newStationAction", 2 ) ); // Default: Play Click 413 newStationAction->setCurrentItem( c->readNumEntry( "newStationAction", 2 ) ); // Default: Play Click
418 newStationScript->setText( c->readEntry( "newStationScript", "" ) ); 414 newStationScript->setText( c->readEntry( "newStationScript", "" ) );
419 synchronizeActionsAndScripts(); // needed for showing/hiding the script QLineEdit on demand 415 synchronizeActionsAndScripts(); // needed for showing/hiding the script QLineEdit on demand
420 416
421 c->setGroup( "GPS" ); 417 c->setGroup( "GPS" );
422 enableGPS->setChecked( c->readBoolEntry( "use", false ) ); 418 enableGPS->setChecked( c->readBoolEntry( "use", false ) );
423#if QT_VERSION < 300 419#if QT_VERSION < 300
424 gpsdHost->insertItem( c->readEntry( "host", "localhost" ), 0 ); 420 gpsdHost->insertItem( c->readEntry( "host", "localhost" ), 0 );
425 gpsdHost->setCurrentItem( 0 ); 421 gpsdHost->setCurrentItem( 0 );
426#else 422#else
427 gpsdHost->setCurrentText( c->readEntry( "host", "localhost" ) ); 423 gpsdHost->setCurrentText( c->readEntry( "host", "localhost" ) );
428#endif 424#endif
429 gpsdPort->setValue( c->readNumEntry( "port", 2947 ) ); 425 gpsdPort->setValue( c->readNumEntry( "port", 2947 ) );
430 startGPS->setChecked( c->readBoolEntry( "start", false ) ); 426 startGPS->setChecked( c->readBoolEntry( "start", false ) );
431 commandGPS->setText( c->readEntry( "command", "gpsd -p /dev/ttyS3 -s 57600" ) ); 427 commandGPS->setText( c->readEntry( "command", "gpsd -p /dev/ttyS3 -s 57600" ) );
432 428
433#endif 429#endif
434} 430}
435 431
436 432
437void WellenreiterConfigWindow::save() 433void WellenreiterConfigWindow::save()
438{ 434{
439#ifdef Q_WS_X11 435#ifdef Q_WS_X11
440 #warning Persistent Configuration not yet implemented for standalone X11 build 436 #warning Persistent Configuration not yet implemented for standalone X11 build
441#else 437#else
442 qDebug( "saving configuration settings..." ); 438 odebug << "saving configuration settings..." << oendl;
443 439
444 /* This is dumb monkey typing stuff... We _need_ to do this automatically! */ 440 /* This is dumb monkey typing stuff... We _need_ to do this automatically! */
445 441
446 OConfig* c = oApp->config(); 442 OConfig* c = oApp->config();
447 443
448 c->setGroup( "Interface" ); 444 c->setGroup( "Interface" );
449 c->writeEntry( "name", interfaceName->currentText() ); 445 c->writeEntry( "name", interfaceName->currentText() );
450 c->writeEntry( "type", deviceType->currentText() ); 446 c->writeEntry( "type", deviceType->currentText() );
451 c->writeEntry( "prism", prismHeader->isChecked() ); 447 c->writeEntry( "prism", prismHeader->isChecked() );
452 c->writeEntry( "hop", hopChannels->isChecked() ); 448 c->writeEntry( "hop", hopChannels->isChecked() );
453 c->writeEntry( "interval", hopInterval->value() ); 449 c->writeEntry( "interval", hopInterval->value() );
454 c->writeEntry( "adaptive", adaptiveHopping->isChecked() ); 450 c->writeEntry( "adaptive", adaptiveHopping->isChecked() );
455 451
456 c->setGroup( "Capture" ); 452 c->setGroup( "Capture" );
457 c->writeEntry( "filename", captureFileName->text() ); 453 c->writeEntry( "filename", captureFileName->text() );
458 454
459 c->setGroup( "UI" ); 455 c->setGroup( "UI" );
460 c->writeEntry( "lookupVendor", lookupVendor->isChecked() ); 456 c->writeEntry( "lookupVendor", lookupVendor->isChecked() );
461 c->writeEntry( "openTree", openTree->isChecked() ); 457 c->writeEntry( "openTree", openTree->isChecked() );
462 c->writeEntry( "disablePM", disablePM->isChecked() ); 458 c->writeEntry( "disablePM", disablePM->isChecked() );
463 c->writeEntry( "newNetworkAction", newNetworkAction->currentItem() ); 459 c->writeEntry( "newNetworkAction", newNetworkAction->currentItem() );
464 c->writeEntry( "newNetworkScript", newNetworkScript->text() ); 460 c->writeEntry( "newNetworkScript", newNetworkScript->text() );
465 c->writeEntry( "newClientAction", newClientAction->currentItem() ); 461 c->writeEntry( "newClientAction", newClientAction->currentItem() );
466 c->writeEntry( "newClientScript", newClientScript->text() ); 462 c->writeEntry( "newClientScript", newClientScript->text() );
467 c->writeEntry( "newStationAction", newStationAction->currentItem() ); 463 c->writeEntry( "newStationAction", newStationAction->currentItem() );
468 c->writeEntry( "newStationScript", newStationScript->text() ); 464 c->writeEntry( "newStationScript", newStationScript->text() );
469 465
470 c->setGroup( "GPS" ); 466 c->setGroup( "GPS" );
471 c->writeEntry( "use", enableGPS->isChecked() ); 467 c->writeEntry( "use", enableGPS->isChecked() );
472 c->writeEntry( "host", gpsdHost->currentText() ); 468 c->writeEntry( "host", gpsdHost->currentText() );
473 c->writeEntry( "port", gpsdPort->value() ); 469 c->writeEntry( "port", gpsdPort->value() );
474 c->writeEntry( "start", startGPS->isChecked() ); 470 c->writeEntry( "start", startGPS->isChecked() );
475 c->writeEntry( "command", commandGPS->text() ); 471 c->writeEntry( "command", commandGPS->text() );
476 472
477 c->write(); 473 c->write();
478 474
479#endif 475#endif
480} 476}
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2003 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2003 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Wellenreiter II. 4** This file is part of Wellenreiter II.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "gps.h" 16#include "gps.h"
17 17
18/* OPIE */
19#include <opie2/odebug.h>
20using namespace Opie::Core;
21
18/* QT */ 22/* QT */
19#include <qtextstream.h> 23#include <qtextstream.h>
20 24
21/* STD */ 25/* STD */
22#include <stdlib.h> 26#include <stdlib.h>
23#include <unistd.h> 27#include <unistd.h>
24 28
25GPS::GPS( QObject* parent, const char * name ) 29GPS::GPS( QObject* parent, const char * name )
26 :QObject( parent, name ) 30 :QObject( parent, name )
27{ 31{
28 qDebug( "GPS::GPS()" ); 32 odebug << "GPS::GPS()" << oendl;
29 _socket = new QSocket( this, "gpsd commsock" ); 33 _socket = new QSocket( this, "gpsd commsock" );
30} 34}
31 35
32 36
33GPS::~GPS() 37GPS::~GPS()
34{ 38{
35 qDebug( "GPS::~GPS()" ); 39 odebug << "GPS::~GPS()" << oendl;
36} 40}
37 41
38 42
39bool GPS::open( const QString& host, int port ) 43bool GPS::open( const QString& host, int port )
40{ 44{
41 _socket->connectToHost( host, port ); 45 _socket->connectToHost( host, port );
42} 46}
43 47
44 48
45GpsLocation GPS::position() const 49GpsLocation GPS::position() const
46{ 50{
47 char buf[256]; 51 char buf[256];
48 double lat = -111.0; 52 double lat = -111.0;
49 double lon = -111.0; 53 double lon = -111.0;
50 54
51 int result = _socket->writeBlock( "p\r\n", 3 ); 55 int result = _socket->writeBlock( "p\r\n", 3 );
52 _socket->flush(); 56 _socket->flush();
53 if ( result ) 57 if ( result )
54 { 58 {
55 int numAvail = _socket->bytesAvailable(); 59 int numAvail = _socket->bytesAvailable();
56 qDebug( "GPS write succeeded, %d bytes available for reading...", numAvail ); 60 odebug << "GPS write succeeded, " << numAvail << " bytes available for reading..." << oendl;
57 if ( numAvail ) 61 if ( numAvail )
58 { 62 {
59 int numRead = _socket->readBlock( &buf[0], sizeof buf ); 63 int numRead = _socket->readBlock( &buf[0], sizeof buf );
60 int numScan = ::sscanf( &buf[0], "GPSD,P=%lg %lg", &lat, &lon); 64 int numScan = ::sscanf( &buf[0], "GPSD,P=%lg %lg", &lat, &lon);
61 65
62 if ( numRead < 7 || numScan != 2 ) 66 if ( numRead < 7 || numScan != 2 )
63 { 67 {
64 qDebug( "GPS read %d bytes succeeded, invalid response: '%s'", numRead, &buf[0] ); 68 odebug << "GPS read " << numRead << " bytes succeeded, invalid response: '" << &buf[0] << "'" << oendl;
65 return GpsLocation( -111, -111 ); 69 return GpsLocation( -111, -111 );
66 } 70 }
67 else 71 else
68 { 72 {
69 return GpsLocation( lat, lon ); 73 return GpsLocation( lat, lon );
70 } 74 }
71 } 75 }
72 } 76 }
73 return GpsLocation( -111, -111 ); 77 return GpsLocation( -111, -111 );
74} 78}
75 79
76 80
77QString GpsLocation::dmsPosition() const 81QString GpsLocation::dmsPosition() const
78{ 82{
79 if ( _latitude == -111 || _longitude == -111 ) 83 if ( _latitude == -111 || _longitude == -111 )
80 return "N/A"; 84 return "N/A";
81 if ( _latitude == 0.0 && _longitude == 0.0 ) 85 if ( _latitude == 0.0 && _longitude == 0.0 )
82 return "NULL"; 86 return "NULL";
83 87
84 /* compute latitude */ 88 /* compute latitude */
85 89
86 QString dms = "N"; 90 QString dms = "N";
87 if ( _latitude >= 0 ) dms.append( "+" ); 91 if ( _latitude >= 0 ) dms.append( "+" );
88 92
89 int trunc = int( _latitude ); 93 int trunc = int( _latitude );
90 float rest = _latitude - trunc; 94 float rest = _latitude - trunc;
91 95
92 float minf = rest * 60; 96 float minf = rest * 60;
93 int minutes = int( minf ); 97 int minutes = int( minf );
94 98
95 rest = minf - minutes; 99 rest = minf - minutes;
96 int seconds = int( rest * 60 ); 100 int seconds = int( rest * 60 );
97 101
98 dms.append( QString::number( trunc ) ); 102 dms.append( QString::number( trunc ) );
99 dms.append( "° " ); 103 dms.append( "° " );
100 dms.append( QString::number( ::abs( minutes ) ) ); 104 dms.append( QString::number( ::abs( minutes ) ) );
101 dms.append( "' " ); 105 dms.append( "' " );
102 dms.append( QString::number( ::abs( seconds ) ) ); 106 dms.append( QString::number( ::abs( seconds ) ) );
103 dms.append( "'' " ); 107 dms.append( "'' " );
104 108
105 /* compute longitude */ 109 /* compute longitude */
106 110
107 dms.append( " | W" ); 111 dms.append( " | W" );
108 if ( _longitude > 0 ) dms.append( "+" ); 112 if ( _longitude > 0 ) dms.append( "+" );
109 113
110 trunc = int( _longitude ); 114 trunc = int( _longitude );
111 rest = _longitude - trunc; 115 rest = _longitude - trunc;
112 116
113 minf = rest * 60; 117 minf = rest * 60;
114 minutes = int( minf ); 118 minutes = int( minf );
115 119
116 rest = minf - minutes; 120 rest = minf - minutes;
117 seconds = int( rest * 60 ); 121 seconds = int( rest * 60 );
118 122
119 dms.append( QString::number( trunc ) ); 123 dms.append( QString::number( trunc ) );
120 dms.append( "° " ); 124 dms.append( "° " );
121 dms.append( QString::number( ::abs( minutes ) ) ); 125 dms.append( QString::number( ::abs( minutes ) ) );
122 dms.append( "' " ); 126 dms.append( "' " );
123 dms.append( QString::number( ::abs( seconds ) ) ); 127 dms.append( QString::number( ::abs( seconds ) ) );
124 dms.append( "'' " ); 128 dms.append( "'' " );
125 129
126 return dms; 130 return dms;
127} 131}
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Wellenreiter II. 4** This file is part of Wellenreiter II.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "logwindow.h" 16#include "logwindow.h"
17
18/* OPIE */
19#include <opie2/odebug.h>
20using namespace Opie::Core;
21
22/* QT */
17#include <qmultilineedit.h> 23#include <qmultilineedit.h>
18#include <qdatetime.h> 24#include <qdatetime.h>
19 25
20MLogWindow* MLogWindow::_instance; 26MLogWindow* MLogWindow::_instance;
21 27
22MLogWindow::MLogWindow( QWidget * parent, const char * name, WFlags f ) 28MLogWindow::MLogWindow( QWidget * parent, const char * name, WFlags f )
23 :QVBox( parent, name, f ) 29 :QVBox( parent, name, f )
24{ 30{
25 ledit = new QMultiLineEdit( this ); 31 ledit = new QMultiLineEdit( this );
26 ledit->setReadOnly( true ); 32 ledit->setReadOnly( true );
27 33
28 MLogWindow::_instance = this; 34 MLogWindow::_instance = this;
29} 35}
30 36
31 37
32void MLogWindow::log( QString text ) 38void MLogWindow::log( QString text )
33{ 39{
34 QTime time = QTime::currentTime(); 40 QTime time = QTime::currentTime();
35 QString line; 41 QString line;
36 line.sprintf( "[%s] %s\n", (const char*) time.toString(), (const char*) text ); 42 line.sprintf( "[%s] %s\n", (const char*) time.toString(), (const char*) text );
37 int col; 43 int col;
38 int row; 44 int row;
39 ledit->getCursorPosition( &col, &row ); 45 ledit->getCursorPosition( &col, &row );
40 ledit->insertAt( line, col, row ); 46 ledit->insertAt( line, col, row );
41 qDebug( line ); 47 odebug << line << oendl;
42} 48}
43 49
44 50
45void MLogWindow::clear() 51void MLogWindow::clear()
46{ 52{
47 ledit->clear(); 53 ledit->clear();
48} 54}
49 55
50 56
51const QString MLogWindow::getLog() const 57const QString MLogWindow::getLog() const
52{ 58{
53 return ledit->text(); 59 return ledit->text();
54} 60}
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Wellenreiter II. 4** This file is part of Wellenreiter II.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "mainwindow.h" 16#include "mainwindow.h"
17
17#ifdef QWS 18#ifdef QWS
19#include <opie2/odebug.h>
18#include <opie2/oapplication.h> 20#include <opie2/oapplication.h>
19#include <opie2/oprocess.h> 21#include <opie2/oprocess.h>
20#else 22#else
21#include <qapplication.h> 23#include <qapplication.h>
22#endif 24#endif
23 25
26/* QT */
24#include <qmessagebox.h> 27#include <qmessagebox.h>
25#include <qstringlist.h> 28#include <qstringlist.h>
26 29
30/* STD */
27#include <errno.h> 31#include <errno.h>
28#include <signal.h> 32#include <signal.h>
29#include <string.h> 33#include <string.h>
30#include <unistd.h> 34#include <unistd.h>
31 35
32using namespace Opie::Core; 36using namespace Opie::Core;
33using namespace Opie::Core; 37
34using namespace Opie::Core;
35int main( int argc, char **argv ) 38int main( int argc, char **argv )
36{ 39{
37 #ifdef QWS 40 #ifdef QWS
38 OApplication a( argc, argv, "Wellenreiter II" ); 41 OApplication a( argc, argv, "Wellenreiter II" );
39 #else 42 #else
40 QApplication a( argc, argv ); 43 QApplication a( argc, argv );
41 #endif 44 #endif
42 WellenreiterMainWindow* w = new WellenreiterMainWindow(); 45 WellenreiterMainWindow* w = new WellenreiterMainWindow();
43 #ifdef QWS 46 #ifdef QWS
44 a.showMainWidget( w ); 47 a.showMainWidget( w );
45 #else 48 #else
46 a.setMainWidget( w ); 49 a.setMainWidget( w );
47 w->setCaption( "Wellenreiter II" ); 50 w->setCaption( "Wellenreiter II" );
48 w->show(); 51 w->show();
49 #endif 52 #endif
50 53
51 a.processEvents(); // show the window before doing the safety checks 54 a.processEvents(); // show the window before doing the safety checks
52 int result = -1; 55 int result = -1;
53 static int killed = false; 56 static int killed = false;
54 57
55 bool check = true; 58 bool check = true;
56 for ( int i = 1; i < argc; ++i ) 59 for ( int i = 1; i < argc; ++i )
57 { 60 {
58 qDebug( "Wellenreiter::main() parsing argument %d = '%s'", i, argv[i] ); 61 odebug << "Wellenreiter::main() parsing argument " << i << " = '" << argv[i] << "'" << oendl;
59 if ( !strcmp( "-nocheck", argv[i] ) ) 62 if ( !strcmp( "-nocheck", argv[i] ) )
60 { 63 {
61 qDebug( "-nocheck found" ); 64 odebug << "-nocheck found" << oendl;
62 check = false; 65 check = false;
63 break; 66 break;
64 } 67 }
65 } 68 }
66 69
67 if ( check ) 70 if ( check )
68 { 71 {
69 // root check 72 // root check
70 if ( getuid() ) 73 if ( getuid() )
71 { 74 {
72 qWarning( QObject::tr( "Wellenreiter: trying to run as non-root!" ) ); 75 owarn << QObject::tr( "Wellenreiter: trying to run as non-root!" ) << oendl;
73 result = QMessageBox::warning( w, " - Wellenreiter II - (non-root)", QObject::tr( "You have started Wellenreiter II\n" 76 result = QMessageBox::warning( w, " - Wellenreiter II - (non-root)", QObject::tr( "You have started Wellenreiter II\n"
74 "as non-root. You will have\nonly limited functionality.\nProceed anyway?" ), 77 "as non-root. You will have\nonly limited functionality.\nProceed anyway?" ),
75 QMessageBox::Yes, QMessageBox::No ); 78 QMessageBox::Yes, QMessageBox::No );
76 if ( result == QMessageBox::No ) return -1; 79 if ( result == QMessageBox::No ) return -1;
77 } 80 }
78 81
79 int dhcpid = OProcess::processPID( "dhcpc" ); 82 int dhcpid = OProcess::processPID( "dhcpc" );
80 83
81 if ( dhcpid ) 84 if ( dhcpid )
82 { 85 {
83 result = QMessageBox::warning( w, " - Wellenreiter II - (dhcp)", QObject::tr( "You have a dhcp client running.\n" 86 result = QMessageBox::warning( w, " - Wellenreiter II - (dhcp)", QObject::tr( "You have a dhcp client running.\n"
84 "(PID = %1)\nThis can severly limit scanning!\nShould I kill it for you?" ).arg( dhcpid ), 87 "(PID = %1)\nThis can severly limit scanning!\nShould I kill it for you?" ).arg( dhcpid ),
85 QMessageBox::Yes, QMessageBox::No ); 88 QMessageBox::Yes, QMessageBox::No );
86 if ( result == QMessageBox::Yes ) 89 if ( result == QMessageBox::Yes )
87 { 90 {
88 if ( -1 == ::kill( dhcpid, SIGTERM ) ) 91 if ( -1 == ::kill( dhcpid, SIGTERM ) )
89 qWarning( "Wellenreiter: can't kill process #%d (%s)", result, strerror( errno ) ); 92 owarn << "Wellenreiter: can't kill process #" << result << " (" << strerror( errno ) << ")" << oendl;
90 else 93 else
91 killed = true; 94 killed = true;
92 } 95 }
93 } 96 }
94 } 97 }
95 98
96 a.exec(); 99 a.exec();
97 100
98 if ( check ) 101 if ( check )
99 { 102 {
100 103
101 if ( killed ) 104 if ( killed )
102 { 105 {
103 result = QMessageBox::warning( w, " - Wellenreiter II - (dhcp)", QObject::tr( "Restart your dhcp client?" ), QMessageBox::Yes, QMessageBox::No ); 106 result = QMessageBox::warning( w, " - Wellenreiter II - (dhcp)", QObject::tr( "Restart your dhcp client?" ), QMessageBox::Yes, QMessageBox::No );
104 if ( result == QMessageBox::Yes ) 107 if ( result == QMessageBox::Yes )
105 { 108 {
106 ::system( QString().sprintf( "dhclient &; udhcpcd &; dhcpcd &" ) ); 109 ::system( QString().sprintf( "dhclient &; udhcpcd &; dhcpcd &" ) );
107 } 110 }
108 } 111 }
109 112
110 delete w; 113 delete w;
111 } 114 }
112 return 0; 115 return 0;
113} 116}
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Wellenreiter II. 4** This file is part of Wellenreiter II.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "configwindow.h" 16#include "configwindow.h"
17#include "gps.h" 17#include "gps.h"
18#include "logwindow.h" 18#include "logwindow.h"
19#include "packetview.h" 19#include "packetview.h"
20#include "mainwindow.h" 20#include "mainwindow.h"
21#include "wellenreiter.h" 21#include "wellenreiter.h"
22#include "scanlist.h" 22#include "scanlist.h"
23 23
24/* OPIE */
25#ifdef QWS
26#include <qpe/resource.h>
27#include <opie2/odebug.h>
28#include <opie2/ofiledialog.h>
29#else
30#include "resource.h"
31#include <qapplication.h>
32#include <qfiledialog.h>
33#endif
34using namespace Opie::Core;
35using namespace Opie::Net;
36using namespace Opie::Ui;
37
38/* QT */
24#include <qcombobox.h> 39#include <qcombobox.h>
25#include <qdatastream.h> 40#include <qdatastream.h>
26#include <qfile.h> 41#include <qfile.h>
27#include <qfileinfo.h> 42#include <qfileinfo.h>
28#include <qlabel.h> 43#include <qlabel.h>
29#include <qlayout.h> 44#include <qlayout.h>
30#include <qlineedit.h> 45#include <qlineedit.h>
31#include <qiconset.h> 46#include <qiconset.h>
32#include <qmenubar.h> 47#include <qmenubar.h>
33#include <qmessagebox.h> 48#include <qmessagebox.h>
34#include <qpopupmenu.h> 49#include <qpopupmenu.h>
35#include <qpushbutton.h> 50#include <qpushbutton.h>
36#include <qstatusbar.h> 51#include <qstatusbar.h>
37#include <qspinbox.h> 52#include <qspinbox.h>
38#include <qtextstream.h> 53#include <qtextstream.h>
39#include <qtoolbutton.h> 54#include <qtoolbutton.h>
40#include <qwhatsthis.h> 55#include <qwhatsthis.h>
41 56
42#ifdef QWS 57/* STD */
43#include <qpe/resource.h>
44#include <opie2/ofiledialog.h>
45using namespace Opie;
46#else
47#include "resource.h"
48#include <qapplication.h>
49#include <qfiledialog.h>
50#endif
51
52#include <unistd.h> 58#include <unistd.h>
53 59
54using namespace Opie::Ui;
55using namespace Opie::Net;
56using namespace Opie::Ui;
57using namespace Opie::Net;
58using namespace Opie::Net;
59WellenreiterMainWindow::WellenreiterMainWindow( QWidget * parent, const char * name, WFlags f ) 60WellenreiterMainWindow::WellenreiterMainWindow( QWidget * parent, const char * name, WFlags f )
60 :QMainWindow( parent, name, f ) 61 :QMainWindow( parent, name, f )
61{ 62{
62 cw = new WellenreiterConfigWindow( this ); 63 cw = new WellenreiterConfigWindow( this );
63 mw = new Wellenreiter( this ); 64 mw = new Wellenreiter( this );
64 mw->setConfigWindow( cw ); 65 mw->setConfigWindow( cw );
65 setCentralWidget( mw ); 66 setCentralWidget( mw );
66 67
67 // setup application icon 68 // setup application icon
68 69
69 setIcon( Resource::loadPixmap( "wellenreiter/appicon-trans" ) ); 70 setIcon( Resource::loadPixmap( "wellenreiter/appicon-trans" ) );
70 #ifndef QWS 71 #ifndef QWS
71 setIconText( "Wellenreiter/X11" ); 72 setIconText( "Wellenreiter/X11" );
72 #endif 73 #endif
73 74
74 // setup tool buttons 75 // setup tool buttons
75 76
76 startButton = new QToolButton( 0 ); 77 startButton = new QToolButton( 0 );
77 QWhatsThis::add( startButton, tr( "Click here to start scanning." ) ); 78 QWhatsThis::add( startButton, tr( "Click here to start scanning." ) );
78 #ifdef QWS 79 #ifdef QWS
79 startButton->setAutoRaise( true ); 80 startButton->setAutoRaise( true );
80 #endif 81 #endif
81 startButton->setIconSet( Resource::loadIconSet( "wellenreiter/SearchIcon" ) ); 82 startButton->setIconSet( Resource::loadIconSet( "wellenreiter/SearchIcon" ) );
82 startButton->setEnabled( false ); 83 startButton->setEnabled( false );
83 connect( startButton, SIGNAL( clicked() ), mw, SLOT( startClicked() ) ); 84 connect( startButton, SIGNAL( clicked() ), mw, SLOT( startClicked() ) );
84 85
85 stopButton = new QToolButton( 0 ); 86 stopButton = new QToolButton( 0 );
86 QWhatsThis::add( stopButton, tr( "Click here to stop scanning." ) ); 87 QWhatsThis::add( stopButton, tr( "Click here to stop scanning." ) );
87 #ifdef QWS 88 #ifdef QWS
88 stopButton->setAutoRaise( true ); 89 stopButton->setAutoRaise( true );
89 #endif 90 #endif
90 stopButton->setIconSet( Resource::loadIconSet( "wellenreiter/CancelIcon" ) ); 91 stopButton->setIconSet( Resource::loadIconSet( "wellenreiter/CancelIcon" ) );
91 stopButton->setEnabled( false ); 92 stopButton->setEnabled( false );
92 connect( stopButton, SIGNAL( clicked() ), mw, SLOT( stopClicked() ) ); 93 connect( stopButton, SIGNAL( clicked() ), mw, SLOT( stopClicked() ) );
93 94
94 QToolButton* d = new QToolButton( 0 ); 95 QToolButton* d = new QToolButton( 0 );
95 QWhatsThis::add( d, tr( "Click here to open the configure dialog." ) ), 96 QWhatsThis::add( d, tr( "Click here to open the configure dialog." ) ),
96 #ifdef QWS 97 #ifdef QWS
97 d->setAutoRaise( true ); 98 d->setAutoRaise( true );
98 #endif 99 #endif
99 d->setIconSet( Resource::loadIconSet( "wellenreiter/SettingsIcon" ) ); 100 d->setIconSet( Resource::loadIconSet( "wellenreiter/SettingsIcon" ) );
100 connect( d, SIGNAL( clicked() ), this, SLOT( showConfigure() ) ); 101 connect( d, SIGNAL( clicked() ), this, SLOT( showConfigure() ) );
101 102
102 uploadButton = new QToolButton( 0 ); 103 uploadButton = new QToolButton( 0 );
103 QWhatsThis::add( uploadButton, tr( "Click here to upload a capture session." ) ); 104 QWhatsThis::add( uploadButton, tr( "Click here to upload a capture session." ) );
104 #ifdef QWS 105 #ifdef QWS
105 uploadButton->setAutoRaise( true ); 106 uploadButton->setAutoRaise( true );
106 #endif 107 #endif
107 uploadButton->setIconSet( Resource::loadIconSet( "up" ) ); 108 uploadButton->setIconSet( Resource::loadIconSet( "up" ) );
108 uploadButton->setEnabled( false ); 109 uploadButton->setEnabled( false );
109 //uploadButton->setEnabled( true ); // DEBUGGING 110 //uploadButton->setEnabled( true ); // DEBUGGING
110 connect( uploadButton, SIGNAL( clicked() ), this, SLOT( uploadSession() ) ); 111 connect( uploadButton, SIGNAL( clicked() ), this, SLOT( uploadSession() ) );
111 112
112 // setup menu bar 113 // setup menu bar
113 114
114 int id; 115 int id;
115 116
116 QMenuBar* mb = menuBar(); 117 QMenuBar* mb = menuBar();
117 118
118 QPopupMenu* fileSave = new QPopupMenu( mb ); 119 QPopupMenu* fileSave = new QPopupMenu( mb );
119 fileSave->insertItem( tr( "&Session..." ), this, SLOT( fileSaveSession() ) ); 120 fileSave->insertItem( tr( "&Session..." ), this, SLOT( fileSaveSession() ) );
120 fileSave->insertItem( tr( "&Text Log..." ), this, SLOT( fileSaveLog() ) ); 121 fileSave->insertItem( tr( "&Text Log..." ), this, SLOT( fileSaveLog() ) );
121 fileSave->insertItem( tr( "&Hex Log..." ), this, SLOT( fileSaveHex() ) ); 122 fileSave->insertItem( tr( "&Hex Log..." ), this, SLOT( fileSaveHex() ) );
122 123
123 QPopupMenu* fileLoad = new QPopupMenu( mb ); 124 QPopupMenu* fileLoad = new QPopupMenu( mb );
124 fileLoad->insertItem( tr( "&Session..." ), this, SLOT( fileLoadSession() ) ); 125 fileLoad->insertItem( tr( "&Session..." ), this, SLOT( fileLoadSession() ) );
125 //fileLoad->insertItem( "&Log", this, SLOT( fileLoadLog() ) ); 126 //fileLoad->insertItem( "&Log", this, SLOT( fileLoadLog() ) );
126 127
127 QPopupMenu* file = new QPopupMenu( mb ); 128 QPopupMenu* file = new QPopupMenu( mb );
128 file->insertItem( tr( "&New" ), this, SLOT( fileNew() ) ); 129 file->insertItem( tr( "&New" ), this, SLOT( fileNew() ) );
129 id = file->insertItem( tr( "&Load" ), fileLoad ); 130 id = file->insertItem( tr( "&Load" ), fileLoad );
130 file->insertItem( tr( "&Save" ), fileSave ); 131 file->insertItem( tr( "&Save" ), fileSave );
131 file->insertSeparator(); 132 file->insertSeparator();
132 uploadID = file->insertItem( tr( "&Upload Session" ), this, SLOT( uploadSession() ) ); 133 uploadID = file->insertItem( tr( "&Upload Session" ), this, SLOT( uploadSession() ) );
133 file->insertSeparator(); 134 file->insertSeparator();
134 file->insertItem( tr( "&Exit" ), qApp, SLOT( quit() ) ); 135 file->insertItem( tr( "&Exit" ), qApp, SLOT( quit() ) );
135 136
136 QPopupMenu* sniffer = new QPopupMenu( mb ); 137 QPopupMenu* sniffer = new QPopupMenu( mb );
137 sniffer->insertItem( tr( "&Configure..." ), this, SLOT( showConfigure() ) ); 138 sniffer->insertItem( tr( "&Configure..." ), this, SLOT( showConfigure() ) );
138 sniffer->insertSeparator(); 139 sniffer->insertSeparator();
139 startID = sniffer->insertItem( tr( "&Start" ), mw, SLOT( startClicked() ) ); 140 startID = sniffer->insertItem( tr( "&Start" ), mw, SLOT( startClicked() ) );
140 sniffer->setItemEnabled( startID, false ); 141 sniffer->setItemEnabled( startID, false );
141 stopID = sniffer->insertItem( tr( "Sto&p" ), mw, SLOT( stopClicked() ) ); 142 stopID = sniffer->insertItem( tr( "Sto&p" ), mw, SLOT( stopClicked() ) );
142 sniffer->setItemEnabled( stopID, false ); 143 sniffer->setItemEnabled( stopID, false );
143 144
144 QPopupMenu* view = new QPopupMenu( mb ); 145 QPopupMenu* view = new QPopupMenu( mb );
145 view->insertItem( tr( "&Expand All" ), this, SLOT( viewExpandAll() ) ); 146 view->insertItem( tr( "&Expand All" ), this, SLOT( viewExpandAll() ) );
146 view->insertItem( tr( "&Collapse All" ), this, SLOT( viewCollapseAll() ) ); 147 view->insertItem( tr( "&Collapse All" ), this, SLOT( viewCollapseAll() ) );
147 148
148 QPopupMenu* demo = new QPopupMenu( mb ); 149 QPopupMenu* demo = new QPopupMenu( mb );
149 demo->insertItem( tr( "&Add something" ), this, SLOT( demoAddStations() ) ); 150 demo->insertItem( tr( "&Add something" ), this, SLOT( demoAddStations() ) );
150 //demo->insertItem( tr( "&Read from GPSd" ), this, SLOT( demoReadFromGps() ) ); 151 //demo->insertItem( tr( "&Read from GPSd" ), this, SLOT( demoReadFromGps() ) );
151 152
152 id = mb->insertItem( tr( "&File" ), file ); 153 id = mb->insertItem( tr( "&File" ), file );
153 154
154 id = mb->insertItem( tr( "&View" ), view ); 155 id = mb->insertItem( tr( "&View" ), view );
155 //mb->setItemEnabled( id, false ); 156 //mb->setItemEnabled( id, false );
156 157
157 id = mb->insertItem( tr( "&Sniffer" ), sniffer ); 158 id = mb->insertItem( tr( "&Sniffer" ), sniffer );
158 159
159 id = mb->insertItem( tr( "&Demo" ), demo ); 160 id = mb->insertItem( tr( "&Demo" ), demo );
160 mb->setItemEnabled( id, true ); 161 mb->setItemEnabled( id, true );
161 mb->setItemEnabled( uploadID, false ); 162 mb->setItemEnabled( uploadID, false );
162 163
163 #ifdef QWS 164 #ifdef QWS
164 mb->insertItem( startButton ); 165 mb->insertItem( startButton );
165 mb->insertItem( stopButton ); 166 mb->insertItem( stopButton );
166 mb->insertItem( uploadButton ); 167 mb->insertItem( uploadButton );
167 mb->insertItem( d ); 168 mb->insertItem( d );
168 #else // Qt3 changed the insertion order. It's now totally random :( 169 #else // Qt3 changed the insertion order. It's now totally random :(
169 mb->insertItem( d ); 170 mb->insertItem( d );
170 mb->insertItem( uploadButton ); 171 mb->insertItem( uploadButton );
171 mb->insertItem( stopButton ); 172 mb->insertItem( stopButton );
172 mb->insertItem( startButton ); 173 mb->insertItem( startButton );
173 #endif 174 #endif
174 175
175 updateToolButtonState(); 176 updateToolButtonState();
176 177
177 // setup status bar (for now only on X11) 178 // setup status bar (for now only on X11)
178 179
179 #ifndef QWS 180 #ifndef QWS
180 statusBar()->message( tr( "Ready." ) ); 181 statusBar()->message( tr( "Ready." ) );
181 #endif 182 #endif
182 183
183 connect( mw, SIGNAL( startedSniffing() ), this, SLOT( changedSniffingState() ) ); 184 connect( mw, SIGNAL( startedSniffing() ), this, SLOT( changedSniffingState() ) );
184 connect( mw, SIGNAL( stoppedSniffing() ), this, SLOT( changedSniffingState() ) ); 185 connect( mw, SIGNAL( stoppedSniffing() ), this, SLOT( changedSniffingState() ) );
185}; 186};
186 187
187 188
188 189
189void WellenreiterMainWindow::showConfigure() 190void WellenreiterMainWindow::showConfigure()
190{ 191{
191 qDebug( "show configure..." ); 192 odebug << "show configure..." << oendl;
192 cw->setCaption( tr( "Configure" ) ); 193 cw->setCaption( tr( "Configure" ) );
193 int result = QPEApplication::execDialog( cw ); 194 int result = QPEApplication::execDialog( cw );
194 195
195 if ( result ) updateToolButtonState(); 196 if ( result ) updateToolButtonState();
196} 197}
197 198
198 199
199void WellenreiterMainWindow::updateToolButtonState() 200void WellenreiterMainWindow::updateToolButtonState()
200{ 201{
201 const QString& interface = cw->interfaceName->currentText(); 202 const QString& interface = cw->interfaceName->currentText();
202 const int cardtype = cw->driverType(); 203 const int cardtype = cw->driverType();
203 204
204 if ( ( interface != "<select>" ) && ( cardtype != 0 ) ) 205 if ( ( interface != "<select>" ) && ( cardtype != 0 ) )
205 { 206 {
206 startButton->setEnabled( true ); 207 startButton->setEnabled( true );
207 menuBar()->setItemEnabled( startID, true ); 208 menuBar()->setItemEnabled( startID, true );
208 } 209 }
209 else 210 else
210 { 211 {
211 startButton->setEnabled( false ); 212 startButton->setEnabled( false );
212 menuBar()->setItemEnabled( startID, false ); 213 menuBar()->setItemEnabled( startID, false );
213 } 214 }
214} 215}
215 216
216 217
217void WellenreiterMainWindow::changedSniffingState() 218void WellenreiterMainWindow::changedSniffingState()
218{ 219{
219 startButton->setEnabled( !mw->sniffing ); 220 startButton->setEnabled( !mw->sniffing );
220 menuBar()->setItemEnabled( startID, !mw->sniffing ); 221 menuBar()->setItemEnabled( startID, !mw->sniffing );
221 stopButton->setEnabled( mw->sniffing ); 222 stopButton->setEnabled( mw->sniffing );
222 menuBar()->setItemEnabled( stopID, mw->sniffing ); 223 menuBar()->setItemEnabled( stopID, mw->sniffing );
223 224
224 if ( !mw->sniffing ) 225 if ( !mw->sniffing )
225 { 226 {
226 menuBar()->setItemEnabled( uploadID, true ); 227 menuBar()->setItemEnabled( uploadID, true );
227 uploadButton->setEnabled( true ); 228 uploadButton->setEnabled( true );
228 } 229 }
229} 230}
230 231
231 232
232WellenreiterMainWindow::~WellenreiterMainWindow() 233WellenreiterMainWindow::~WellenreiterMainWindow()
233{ 234{
234 qDebug( "Wellenreiter: bye." ); 235 odebug << "Wellenreiter: bye." << oendl;
235}; 236};
236 237
237 238
238void WellenreiterMainWindow::demoAddStations() 239void WellenreiterMainWindow::demoAddStations()
239{ 240{
240 //mw = 0; // test SIGSEGV handling 241 //mw = 0; // test SIGSEGV handling
241 242
242 mw->netView()->addNewItem( "managed", "Vanille", OMacAddress::fromString("00:00:20:EF:A6:43"), true, 6, 80, GpsLocation( 39.8794, -94.0936) ); 243 mw->netView()->addNewItem( "managed", "Vanille", OMacAddress::fromString("00:00:20:EF:A6:43"), true, 6, 80, GpsLocation( 39.8794, -94.0936) );
243 mw->netView()->addNewItem( "managed", "Vanille", OMacAddress::fromString("00:30:6D:EF:A6:23"), true, 11, 10, GpsLocation( 0.0, 0.0 ) ); 244 mw->netView()->addNewItem( "managed", "Vanille", OMacAddress::fromString("00:30:6D:EF:A6:23"), true, 11, 10, GpsLocation( 0.0, 0.0 ) );
244 mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:03:F8:E7:16:22"), false, 3, 10, GpsLocation( 5.5, 2.3 ) ); 245 mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:03:F8:E7:16:22"), false, 3, 10, GpsLocation( 5.5, 2.3 ) );
245 mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:04:01:E7:56:62"), false, 3, 15, GpsLocation( 2.3, 5.5 ) ); 246 mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:04:01:E7:56:62"), false, 3, 15, GpsLocation( 2.3, 5.5 ) );
246 mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:05:8E:E7:56:E2"), false, 3, 20, GpsLocation( -10.0, -20.5 ) ); 247 mw->netView()->addNewItem( "adhoc", "ELAN", OMacAddress::fromString("00:05:8E:E7:56:E2"), false, 3, 20, GpsLocation( -10.0, -20.5 ) );
247} 248}
248 249
249 250
250void WellenreiterMainWindow::demoReadFromGps() 251void WellenreiterMainWindow::demoReadFromGps()
251{ 252{
252 WellenreiterConfigWindow* configwindow = WellenreiterConfigWindow::instance(); 253 WellenreiterConfigWindow* configwindow = WellenreiterConfigWindow::instance();
253 GPS* gps = new GPS( this ); 254 GPS* gps = new GPS( this );
254 qDebug( "Wellenreiter::demoReadFromGps(): url=gps://%s:%d/", (const char*) configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() ); 255 odebug << "Wellenreiter::demoReadFromGps(): url=gps://" << (const char*) configwindow->gpsdHost->currentText() << ":" << configwindow->gpsdPort->value() << "/" << oendl;
255 gps->open( configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() ); 256 gps->open( configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() );
256 GpsLocation loc = gps->position(); 257 GpsLocation loc = gps->position();
257 QMessageBox::information( this, "Wellenreiter/Opie", tr( "GPS said:\n%1" ).arg( loc.dmsPosition() ) ); 258 QMessageBox::information( this, "Wellenreiter/Opie", tr( "GPS said:\n%1" ).arg( loc.dmsPosition() ) );
258 delete gps; 259 delete gps;
259} 260}
260 261
261 262
262QString WellenreiterMainWindow::getFileName( bool save ) 263QString WellenreiterMainWindow::getFileName( bool save )
263{ 264{
264 QMap<QString, QStringList> map; 265 QMap<QString, QStringList> map;
265 map.insert( tr("All"), QStringList() ); 266 map.insert( tr("All"), QStringList() );
266 QStringList text; 267 QStringList text;
267 text << "text/*"; 268 text << "text/*";
268 map.insert( tr("Text"), text ); 269 map.insert( tr("Text"), text );
269 text << "*"; 270 text << "*";
270 map.insert( tr("All"), text ); 271 map.insert( tr("All"), text );
271 272
272 QString str; 273 QString str;
273 if ( save ) 274 if ( save )
274 { 275 {
275 #ifdef QWS 276 #ifdef QWS
276 str = OFileDialog::getSaveFileName( 2, "/", QString::null, map ); 277 str = OFileDialog::getSaveFileName( 2, "/", QString::null, map );
277 #else 278 #else
278 str = QFileDialog::getSaveFileName(); 279 str = QFileDialog::getSaveFileName();
279 #endif 280 #endif
280 if ( str.isEmpty() /*|| QFileInfo(str).isDir()*/ ) 281 if ( str.isEmpty() /*|| QFileInfo(str).isDir()*/ )
281 return ""; 282 return "";
282 } 283 }
283 else 284 else
284 { 285 {
285 #ifdef QWS 286 #ifdef QWS
286 str = OFileDialog::getOpenFileName( 2, "/", QString::null, map ); 287 str = OFileDialog::getOpenFileName( 2, "/", QString::null, map );
287 #else 288 #else
288 str = QFileDialog::getOpenFileName(); 289 str = QFileDialog::getOpenFileName();
289 #endif 290 #endif
290 if ( str.isEmpty() || !QFile(str).exists() || QFileInfo(str).isDir() ) 291 if ( str.isEmpty() || !QFile(str).exists() || QFileInfo(str).isDir() )
291 return ""; 292 return "";
292 } 293 }
293 return str; 294 return str;
294} 295}
295 296
296 297
297void WellenreiterMainWindow::fileSaveLog() 298void WellenreiterMainWindow::fileSaveLog()
298{ 299{
299 QString fname = getFileName( true ); 300 QString fname = getFileName( true );
300 if ( !fname.isEmpty() ) 301 if ( !fname.isEmpty() )
301 { 302 {
302 QFile f( fname ); 303 QFile f( fname );
303 if ( f.open(IO_WriteOnly) ) 304 if ( f.open(IO_WriteOnly) )
304 { 305 {
305 QTextStream t( &f ); 306 QTextStream t( &f );
306 t << mw->logWindow()->getLog(); 307 t << mw->logWindow()->getLog();
307 f.close(); 308 f.close();
308 qDebug( "Saved log to file '%s'", (const char*) fname ); 309 odebug << "Saved log to file '" << (const char*) fname << "'" << oendl;
309 } 310 }
310 else 311 else
311 { 312 {
312 qDebug( "Problem saving log to file '%s'", (const char*) fname ); 313 odebug << "Problem saving log to file '" << (const char*) fname << "'" << oendl;
313 } 314 }
314 } 315 }
315} 316}
316 317
317void WellenreiterMainWindow::fileSaveSession() 318void WellenreiterMainWindow::fileSaveSession()
318{ 319{
319 QString fname = getFileName( true ); 320 QString fname = getFileName( true );
320 if ( !fname.isEmpty() ) 321 if ( !fname.isEmpty() )
321 { 322 {
322 323
323 QFile f( fname ); 324 QFile f( fname );
324 if ( f.open(IO_WriteOnly) ) 325 if ( f.open(IO_WriteOnly) )
325 { 326 {
326 QDataStream t( &f ); 327 QDataStream t( &f );
327 t << *mw->netView(); 328 t << *mw->netView();
328 f.close(); 329 f.close();
329 qDebug( "Saved session to file '%s'", (const char*) fname ); 330 odebug << "Saved session to file '" << (const char*) fname << "'" << oendl;
330 } 331 }
331 else 332 else
332 { 333 {
333 qDebug( "Problem saving session to file '%s'", (const char*) fname ); 334 odebug << "Problem saving session to file '" << (const char*) fname << "'" << oendl;
334 } 335 }
335 } 336 }
336} 337}
337 338
338void WellenreiterMainWindow::fileSaveHex() 339void WellenreiterMainWindow::fileSaveHex()
339{ 340{
340 #warning DOES NOT WORK AT THE MOMENT 341 #warning DOES NOT WORK AT THE MOMENT
341 /* 342 /*
342 QString fname = getFileName( true ); 343 QString fname = getFileName( true );
343 if ( !fname.isEmpty() ) 344 if ( !fname.isEmpty() )
344 { 345 {
345 QFile f( fname ); 346 QFile f( fname );
346 if ( f.open(IO_WriteOnly) ) 347 if ( f.open(IO_WriteOnly) )
347 { 348 {
348 QTextStream t( &f ); 349 QTextStream t( &f );
349 t << mw->hexWindow()->getLog(); 350 t << mw->hexWindow()->getLog();
350 f.close(); 351 f.close();
351 qDebug( "Saved hex log to file '%s'", (const char*) fname ); 352 odebug << "Saved hex log to file '" << (const char*) fname << "'" << oendl;
352 } 353 }
353 else 354 else
354 { 355 {
355 qDebug( "Problem saving hex log to file '%s'", (const char*) fname ); 356 odebug << "Problem saving hex log to file '" << (const char*) fname << "'" << oendl;
356 } 357 }
357 } 358 }
358 */ 359 */
359} 360}
360 361
361void WellenreiterMainWindow::fileLoadSession() 362void WellenreiterMainWindow::fileLoadSession()
362{ 363{
363 QString fname = getFileName( false ); 364 QString fname = getFileName( false );
364 if ( !fname.isEmpty() ) 365 if ( !fname.isEmpty() )
365 { 366 {
366 QFile f( fname ); 367 QFile f( fname );
367 if ( f.open(IO_ReadOnly) ) 368 if ( f.open(IO_ReadOnly) )
368 { 369 {
369 QDataStream t( &f ); 370 QDataStream t( &f );
370 t >> *mw->netView(); 371 t >> *mw->netView();
371 f.close(); 372 f.close();
372 qDebug( "Loaded session from file '%s'", (const char*) fname ); 373 odebug << "Loaded session from file '" << (const char*) fname << "'" << oendl;
373 } 374 }
374 else 375 else
375 { 376 {
376 qDebug( "Problem loading session from file '%s'", (const char*) fname ); 377 odebug << "Problem loading session from file '" << (const char*) fname << "'" << oendl;
377 } 378 }
378 } 379 }
379} 380}
380 381
381 382
382void WellenreiterMainWindow::fileNew() 383void WellenreiterMainWindow::fileNew()
383{ 384{
384 mw->netView()->clear(); 385 mw->netView()->clear();
385 mw->logWindow()->clear(); 386 mw->logWindow()->clear();
386 mw->hexWindow()->clear(); 387 mw->hexWindow()->clear();
387} 388}
388 389
389 390
390void WellenreiterMainWindow::closeEvent( QCloseEvent* e ) 391void WellenreiterMainWindow::closeEvent( QCloseEvent* e )
391{ 392{
392 if ( mw->isDaemonRunning() ) 393 if ( mw->isDaemonRunning() )
393 { 394 {
394 QMessageBox::warning( this, "Wellenreiter/Opie", 395 QMessageBox::warning( this, "Wellenreiter/Opie",
395 tr( "Sniffing in progress!\nPlease stop sniffing before closing." ) ); 396 tr( "Sniffing in progress!\nPlease stop sniffing before closing." ) );
396 e->ignore(); 397 e->ignore();
397 } 398 }
398 else 399 else
399 { 400 {
400 QMainWindow::closeEvent( e ); 401 QMainWindow::closeEvent( e );
401 } 402 }
402} 403}
403 404
404static const char* CAP_hostname = "www.vanille.de"; 405static const char* CAP_hostname = "www.vanille.de";
405 406
406#include <netdb.h> 407#include <netdb.h>
407#include <unistd.h> 408#include <unistd.h>
408#include <sys/types.h> 409#include <sys/types.h>
409#include <sys/socket.h> 410#include <sys/socket.h>
410 411
411void WellenreiterMainWindow::uploadSession() 412void WellenreiterMainWindow::uploadSession()
412{ 413{
413 QLineEdit* from; 414 QLineEdit* from;
414 QLineEdit* location; 415 QLineEdit* location;
415 QLineEdit* comments; 416 QLineEdit* comments;
416 QPushButton* accept; 417 QPushButton* accept;
417 QPushButton* reject; 418 QPushButton* reject;
418 419
419 QDialog* d = new QDialog( 0, "session upload", true ); 420 QDialog* d = new QDialog( 0, "session upload", true );
420 d->setCaption( tr( "Upload Session" ) ); 421 d->setCaption( tr( "Upload Session" ) );
421 QGridLayout* g = new QGridLayout( d, 4, 2, 3 ); 422 QGridLayout* g = new QGridLayout( d, 4, 2, 3 );
422 g->addWidget( new QLabel( tr( "From: " ), d ), 0, 0 ); 423 g->addWidget( new QLabel( tr( "From: " ), d ), 0, 0 );
423 g->addWidget( from = new QLineEdit( d ), 0, 1 ); 424 g->addWidget( from = new QLineEdit( d ), 0, 1 );
424 g->addWidget( new QLabel( tr( "Location: " ), d ), 1, 0 ); 425 g->addWidget( new QLabel( tr( "Location: " ), d ), 1, 0 );
425 g->addWidget( location = new QLineEdit( d ), 1, 1 ); 426 g->addWidget( location = new QLineEdit( d ), 1, 1 );
426 g->addWidget( new QLabel( tr( "Comments: " ), d ), 2, 0 ); 427 g->addWidget( new QLabel( tr( "Comments: " ), d ), 2, 0 );
427 g->addWidget( comments = new QLineEdit( d ), 2, 1 ); 428 g->addWidget( comments = new QLineEdit( d ), 2, 1 );
428 g->addWidget( accept = new QPushButton( tr( "&Ok" ), d ), 3, 0 ); 429 g->addWidget( accept = new QPushButton( tr( "&Ok" ), d ), 3, 0 );
429 g->addWidget( reject = new QPushButton( tr( "&Cancel" ), d ), 3, 1 ); 430 g->addWidget( reject = new QPushButton( tr( "&Cancel" ), d ), 3, 1 );
430 accept->setDefault( true ); 431 accept->setDefault( true );
431 accept->setAutoDefault( true ); 432 accept->setAutoDefault( true );
432 from->setText( "WL II User" ); 433 from->setText( "WL II User" );
433 location->setText( "WL II Location" ); 434 location->setText( "WL II Location" );
434 comments->setText( "No Comments." ); 435 comments->setText( "No Comments." );
435 connect( accept, SIGNAL( clicked() ), d, SLOT( accept() ) ); 436 connect( accept, SIGNAL( clicked() ), d, SLOT( accept() ) );
436 connect( reject, SIGNAL( clicked() ), d, SLOT( reject() ) ); 437 connect( reject, SIGNAL( clicked() ), d, SLOT( reject() ) );
437 int result = d->exec(); 438 int result = d->exec();
438 439
439 if ( !result ) 440 if ( !result )
440 { 441 {
441 qDebug( "Session upload cancelled :(" ); 442 odebug << "Session upload cancelled :(" << oendl;
442 return; 443 return;
443 } 444 }
444 445
445 qDebug( "Starting upload..." ); 446 odebug << "Starting upload..." << oendl;
446 447
447 struct sockaddr_in raddr; 448 struct sockaddr_in raddr;
448 struct hostent *rhost_info; 449 struct hostent *rhost_info;
449 int sock = -1; 450 int sock = -1;
450 bool ok = false; 451 bool ok = false;
451 452
452 rhost_info = (struct hostent *) ::gethostbyname( CAP_hostname ); 453 rhost_info = (struct hostent *) ::gethostbyname( CAP_hostname );
453 if ( rhost_info ) 454 if ( rhost_info )
454 { 455 {
455 456
456 457
457 if ( !QFile::exists( mw->captureFileName() ) ) 458 if ( !QFile::exists( mw->captureFileName() ) )
458 { 459 {
459 QMessageBox::warning( 0, tr( "Error" ), tr( "<p>Logfile '%1' doesn't exist</p>").arg( mw->captureFileName() ) ); 460 QMessageBox::warning( 0, tr( "Error" ), tr( "<p>Logfile '%1' doesn't exist</p>").arg( mw->captureFileName() ) );
460 return; 461 return;
461 } 462 }
462 463
463 QFile f( mw->captureFileName() ); 464 QFile f( mw->captureFileName() );
464 if ( !f.open( IO_ReadOnly ) ) 465 if ( !f.open( IO_ReadOnly ) )
465 { 466 {
466 QMessageBox::warning( 0, tr( "Error" ), tr( "<p>Can't open Logfile '%1'</p>").arg( mw->captureFileName() ) ); 467 QMessageBox::warning( 0, tr( "Error" ), tr( "<p>Can't open Logfile '%1'</p>").arg( mw->captureFileName() ) );
467 return; 468 return;
468 } 469 }
469 470
470 int content_length = f.size(); 471 int content_length = f.size();
471 472
472 ::memset( &raddr, 0, sizeof (struct sockaddr_in) ); 473 ::memset( &raddr, 0, sizeof (struct sockaddr_in) );
473 ::memcpy( &raddr. sin_addr, rhost_info-> h_addr, rhost_info-> h_length ); 474 ::memcpy( &raddr. sin_addr, rhost_info-> h_addr, rhost_info-> h_length );
474 raddr.sin_family = rhost_info-> h_addrtype; 475 raddr.sin_family = rhost_info-> h_addrtype;
475 raddr.sin_port = htons ( 80 ); 476 raddr.sin_port = htons ( 80 );
476 477
477 sock = ::socket( AF_INET, SOCK_STREAM, 0 ); 478 sock = ::socket( AF_INET, SOCK_STREAM, 0 );
478 479
479 if ( sock >= 0 ) 480 if ( sock >= 0 )
480 { 481 {
481 if ( ::connect ( sock, (struct sockaddr *) & raddr, sizeof (struct sockaddr)) >= 0 ) 482 if ( ::connect ( sock, (struct sockaddr *) & raddr, sizeof (struct sockaddr)) >= 0 )
482 { 483 {
483 QString header; 484 QString header;
484 QString content; 485 QString content;
485 QString preambel; 486 QString preambel;
486 487
487 header = "" 488 header = ""
488 "POST /projects/capturedump.spy HTTP/1.1\r\n" 489 "POST /projects/capturedump.spy HTTP/1.1\r\n"
489 "Host: www.vanille.de\r\n" 490 "Host: www.vanille.de\r\n"
490 "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.5) Gecko/20031010 Galeon/1.3.10\r\n" 491 "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.5) Gecko/20031010 Galeon/1.3.10\r\n"
491 "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" 492 "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"
492 "Accept-Language: en\r\n" 493 "Accept-Language: en\r\n"
493 "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n" 494 "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n"
494 "Accept-Charset: us-ascii,utf-8;q=0.7,*;q=0.7\r\n" 495 "Accept-Charset: us-ascii,utf-8;q=0.7,*;q=0.7\r\n"
495 "Keep-Alive: 300\r\n" 496 "Keep-Alive: 300\r\n"
496 "Connection: keep-alive\r\n" 497 "Connection: keep-alive\r\n"
497 "Referer: http://www.vanille.de/projects/capturedump.spy\r\n" 498 "Referer: http://www.vanille.de/projects/capturedump.spy\r\n"
498 "Content-Type: multipart/form-data; boundary=---------------------------97267758015830030481215568065\r\n" 499 "Content-Type: multipart/form-data; boundary=---------------------------97267758015830030481215568065\r\n"
499 "Content-Length: %1\r\n" 500 "Content-Length: %1\r\n"
500 "\r\n"; 501 "\r\n";
501 502
502 content = "" 503 content = ""
503 "-----------------------------97267758015830030481215568065\r\n" 504 "-----------------------------97267758015830030481215568065\r\n"
504 "Content-Disposition: form-data; name=\"Name\"\r\n" 505 "Content-Disposition: form-data; name=\"Name\"\r\n"
505 "\r\n" 506 "\r\n"
506 "%1\r\n" 507 "%1\r\n"
507 "-----------------------------97267758015830030481215568065\r\n" 508 "-----------------------------97267758015830030481215568065\r\n"
508 "Content-Disposition: form-data; name=\"Location\"\r\n" 509 "Content-Disposition: form-data; name=\"Location\"\r\n"
509 "\r\n" 510 "\r\n"
510 "%2\r\n" 511 "%2\r\n"
511 "-----------------------------97267758015830030481215568065\r\n" 512 "-----------------------------97267758015830030481215568065\r\n"
512 "Content-Disposition: form-data; name=\"Comments\"\r\n" 513 "Content-Disposition: form-data; name=\"Comments\"\r\n"
513 "\r\n" 514 "\r\n"
514 "%3\r\n" 515 "%3\r\n"
515 "-----------------------------97267758015830030481215568065\r\n" 516 "-----------------------------97267758015830030481215568065\r\n"
516 "Content-Disposition: form-data; name=\"upfile\"; filename=\"%4\"\r\n" 517 "Content-Disposition: form-data; name=\"upfile\"; filename=\"%4\"\r\n"
517 "Content-Type: application/octet-stream\r\n" 518 "Content-Type: application/octet-stream\r\n"
518 "\r\n"; 519 "\r\n";
519 520
520 preambel = "" 521 preambel = ""
521 "\r\n-----------------------------97267758015830030481215568065--\r\n"; 522 "\r\n-----------------------------97267758015830030481215568065--\r\n";
522 523
523 content = content.arg( from->text().isEmpty() ? QString( "Anonymous Wellenreiter II User" ) : from->text() ); 524 content = content.arg( from->text().isEmpty() ? QString( "Anonymous Wellenreiter II User" ) : from->text() );
524 content = content.arg( location->text().isEmpty() ? QString( "Anonymous Wellenreiter II Location" ) : location->text() ); 525 content = content.arg( location->text().isEmpty() ? QString( "Anonymous Wellenreiter II Location" ) : location->text() );
525 content = content.arg( comments->text().isEmpty() ? QString( "Anonymous Wellenreiter II Comments" ) : comments->text() ); 526 content = content.arg( comments->text().isEmpty() ? QString( "Anonymous Wellenreiter II Comments" ) : comments->text() );
526 content = content.arg( mw->captureFileName() ); 527 content = content.arg( mw->captureFileName() );
527 528
528 header = header.arg( QString::number( content.length() + f.size() + preambel.length() ) ); 529 header = header.arg( QString::number( content.length() + f.size() + preambel.length() ) );
529 530
530 // write header 531 // write header
531 532
532 const char* ascii = header.latin1(); 533 const char* ascii = header.latin1();
533 uint ascii_len = ::strlen( ascii ); 534 uint ascii_len = ::strlen( ascii );
534 ::write ( sock, ascii, ascii_len ); 535 ::write ( sock, ascii, ascii_len );
535 536
536 // write fixed content 537 // write fixed content
537 538
538 ascii = content.latin1(); 539 ascii = content.latin1();
539 ascii_len = ::strlen( ascii ); 540 ascii_len = ::strlen( ascii );
540 ::write ( sock, ascii, ascii_len ); 541 ::write ( sock, ascii, ascii_len );
541 542
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Wellenreiter II. 4** This file is part of Wellenreiter II.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "packetview.h" 16#include "packetview.h"
17 17
18/* OPIE */ 18/* OPIE */
19#include <opie2/opcap.h> 19#include <opie2/opcap.h>
20#include <opie2/odebug.h> 20#include <opie2/odebug.h>
21#include <opie2/olistview.h> 21#include <opie2/olistview.h>
22 22
23/* QT */ 23/* QT */
24#include <qfont.h> 24#include <qfont.h>
25#include <qlabel.h> 25#include <qlabel.h>
26#include <qlayout.h> 26#include <qlayout.h>
27#include <qlist.h> 27#include <qlist.h>
28#include <qlistview.h> 28#include <qlistview.h>
29#include <qobjectlist.h> 29#include <qobjectlist.h>
30#include <qspinbox.h> 30#include <qspinbox.h>
31#include <qtextview.h> 31#include <qtextview.h>
32 32
33using namespace Opie::Net; 33using namespace Opie::Net;
34using namespace Opie::Core; 34using namespace Opie::Core;
35using namespace Opie::Ui; 35using namespace Opie::Ui;
36 36
37PacketView::PacketView( QWidget * parent, const char * name, WFlags f ) 37PacketView::PacketView( QWidget * parent, const char * name, WFlags f )
38 :QFrame( parent, name, f ) 38 :QFrame( parent, name, f )
39{ 39{
40 _number = new QSpinBox( this ); 40 _number = new QSpinBox( this );
41 _number->setPrefix( "Packet # " ); 41 _number->setPrefix( "Packet # " );
42 _label = new QLabel( this ); 42 _label = new QLabel( this );
43 _label->setText( "eth0 2004/03/08 - 00:00:21" ); 43 _label->setText( "eth0 2004/03/08 - 00:00:21" );
44 44
45 _list = new OListView( this ); 45 _list = new OListView( this );
46 _list->addColumn( "#" ); 46 _list->addColumn( "#" );
47 _list->addColumn( "Packet Type" ); 47 _list->addColumn( "Packet Type" );
48 _list->setColumnAlignment( 0, Qt::AlignCenter ); 48 _list->setColumnAlignment( 0, Qt::AlignCenter );
49 _list->setColumnAlignment( 1, Qt::AlignLeft ); 49 _list->setColumnAlignment( 1, Qt::AlignLeft );
50 _list->setAllColumnsShowFocus( true ); 50 _list->setAllColumnsShowFocus( true );
51 _list->setFont( QFont( "Fixed", 8 ) ); 51 _list->setFont( QFont( "Fixed", 8 ) );
52 52
53 _hex = new QTextView( this ); 53 _hex = new QTextView( this );
54 _hex->setFont( QFont( "Fixed", 8 ) ); 54 _hex->setFont( QFont( "Fixed", 8 ) );
55 55
56 QVBoxLayout* vb = new QVBoxLayout( this, 2, 2 ); 56 QVBoxLayout* vb = new QVBoxLayout( this, 2, 2 );
57 QHBoxLayout* hb = new QHBoxLayout( vb, 2 ); 57 QHBoxLayout* hb = new QHBoxLayout( vb, 2 );
58 hb->addWidget( _label ); 58 hb->addWidget( _label );
59 hb->addWidget( _number ); 59 hb->addWidget( _number );
60 vb->addWidget( _list ); 60 vb->addWidget( _list );
61 vb->addWidget( _hex ); 61 vb->addWidget( _hex );
62 62
63 _packets.setAutoDelete( true ); 63 _packets.setAutoDelete( true );
64 64
65 connect( _number, SIGNAL( valueChanged( int ) ), this, SLOT( showPacket( int ) ) ); 65 connect( _number, SIGNAL( valueChanged( int ) ), this, SLOT( showPacket( int ) ) );
66} 66}
67 67
68void PacketView::add( const OPacket* p ) 68void PacketView::add( const OPacket* p )
69{ 69{
70 _packets.append( p ); 70 _packets.append( p );
71 // Add Circular Buffer and check for number of elements here 71 // Add Circular Buffer and check for number of elements here
72} 72}
73 73
74void PacketView::showPacket( int number ) 74void PacketView::showPacket( int number )
75{ 75{
76 _list->clear(); 76 _list->clear();
77 _hex->setText(""); 77 _hex->setText("");
78 const OPacket* p = _packets.at( number ); 78 const OPacket* p = _packets.at( number );
79 79
80 if ( p ) 80 if ( p )
81 { 81 {
82 _doSubPackets( const_cast<QObjectList*>( p->children() ), 0 ); 82 _doSubPackets( const_cast<QObjectList*>( p->children() ), 0 );
83 _doHexPacket( p ); 83 _doHexPacket( p );
84 } 84 }
85 else 85 else
86 { 86 {
87 qDebug( "D'oh! No packet!" ); 87 odebug << "D'oh! No packet!" << oendl;
88 } 88 }
89} 89}
90 90
91void PacketView::_doSubPackets( QObjectList* l, int counter ) 91void PacketView::_doSubPackets( QObjectList* l, int counter )
92{ 92{
93 if (!l) return; 93 if (!l) return;
94 QObject* o = l->first(); 94 QObject* o = l->first();
95 while ( o ) 95 while ( o )
96 { 96 {
97 new OListViewItem( _list, QString::number( counter++ ), o->name() ); 97 new OListViewItem( _list, QString::number( counter++ ), o->name() );
98 _doSubPackets( const_cast<QObjectList*>( o->children() ), counter ); 98 _doSubPackets( const_cast<QObjectList*>( o->children() ), counter );
99 o = l->next(); 99 o = l->next();
100 } 100 }
101} 101}
102 102
103void PacketView::_doHexPacket( const OPacket* p ) 103void PacketView::_doHexPacket( const OPacket* p )
104{ 104{
105 _hex->setText( p->dump( 16 ) ); 105 _hex->setText( p->dump( 16 ) );
106} 106}
107 107
108const QString PacketView::getLog() const 108const QString PacketView::getLog() const
109{ 109{
110} 110}
111 111
112void PacketView::clear() 112void PacketView::clear()
113{ 113{
114 _packets.clear(); 114 _packets.clear();
115 _number->setMinValue( 0 ); 115 _number->setMinValue( 0 );
116 _number->setMaxValue( 0 ); 116 _number->setMaxValue( 0 );
117 _label->setText( "---" ); 117 _label->setText( "---" );
118 _list->clear(); 118 _list->clear();
119 _hex->setText( " <i>-- no Packet available --</i> " ); 119 _hex->setText( " <i>-- no Packet available --</i> " );
120} 120}
121 121
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Wellenreiter II. 4** This file is part of Wellenreiter II.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "resource.h" 16#include "resource.h"
17 17
18#define PIXMAPPATH "/usr/local/share" 18#define PIXMAPPATH "/usr/local/share"
19 19
20#include <qiconset.h> 20#include <qiconset.h>
21 21
22namespace Resource 22namespace Resource
23{ 23{
24 24
25QPixmap loadPixmap( const QString& pix ) 25QPixmap loadPixmap( const QString& pix )
26{ 26{
27 QString filename; 27 QString filename;
28 filename.sprintf( "%s/%s.png", (const char*) PIXMAPPATH, (const char*) pix ); 28 filename.sprintf( "%s/%s.png", (const char*) PIXMAPPATH, (const char*) pix );
29 QPixmap pixmap( filename ); 29 QPixmap pixmap( filename );
30 if ( pixmap.isNull() ) 30 if ( pixmap.isNull() )
31 { 31 {
32 qDebug( "Wellenreiter::Resource: can't find pixmap " + filename ); 32 odebug << "Wellenreiter::Resource: can't find pixmap " + filename << oendl;
33 } 33 }
34 return pixmap; 34 return pixmap;
35}; 35};
36 36
37QIconSet loadIconSet( const QString& pix ) 37QIconSet loadIconSet( const QString& pix )
38{ 38{
39 QString filename; 39 QString filename;
40 filename.sprintf( "%s/%s.png", (const char*) PIXMAPPATH, (const char*) pix ); 40 filename.sprintf( "%s/%s.png", (const char*) PIXMAPPATH, (const char*) pix );
41 QPixmap pixmap( filename ); 41 QPixmap pixmap( filename );
42 if ( pixmap.isNull() ) 42 if ( pixmap.isNull() )
43 { 43 {
44 qDebug( "Wellenreiter::Resource: can't find pixmap " + filename ); 44 odebug << "Wellenreiter::Resource: can't find pixmap " + filename << oendl;
45 } 45 }
46 return QIconSet( pixmap ); 46 return QIconSet( pixmap );
47}; 47};
48 48
49}; 49};
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Wellenreiter II. 4** This file is part of Wellenreiter II.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "scanlist.h" 16#include "scanlist.h"
17#include "configwindow.h" 17#include "configwindow.h"
18#include "logwindow.h" 18#include "logwindow.h"
19 19
20#include <assert.h> 20/* OPIE */
21#include <qcursor.h>
22#include <qdatetime.h>
23#include <qpopupmenu.h>
24#include <qcheckbox.h>
25
26#ifdef QWS 21#ifdef QWS
22#include <opie2/odebug.h>
27#include <qpe/qpeapplication.h> 23#include <qpe/qpeapplication.h>
28#endif
29
30#ifdef QWS
31#include <qpe/resource.h> 24#include <qpe/resource.h>
32#else 25#else
33#include "resource.h" 26#include "resource.h"
34#endif 27#endif
28using namespace Opie::Core;
29using namespace Opie::Ui;
30using namespace Opie::Net;
31
32/* QT */
33#include <qcursor.h>
34#include <qdatetime.h>
35#include <qpopupmenu.h>
36#include <qcheckbox.h>
37
38/* STD */
39#include <assert.h>
35 40
36const int col_type = 0; 41const int col_type = 0;
37const int col_essid = 0; 42const int col_essid = 0;
38const int col_sig = 1; 43const int col_sig = 1;
39const int col_ap = 2; 44const int col_ap = 2;
40const int col_channel = 3; 45const int col_channel = 3;
41const int col_wep = 4; 46const int col_wep = 4;
42const int col_traffic = 5; 47const int col_traffic = 5;
43const int col_ip = 6; 48const int col_ip = 6;
44const int col_manuf = 7; 49const int col_manuf = 7;
45const int col_firstseen = 8; 50const int col_firstseen = 8;
46const int col_lastseen = 9; 51const int col_lastseen = 9;
47const int col_location = 10; 52const int col_location = 10;
48 53
49using namespace Opie::Net;
50using namespace Opie::Ui;
51using namespace Opie::Net;
52using namespace Opie::Ui;
53using namespace Opie::Ui;
54using namespace Opie::Net;
55MScanListView::MScanListView( QWidget* parent, const char* name ) 54MScanListView::MScanListView( QWidget* parent, const char* name )
56 :OListView( parent, name ) 55 :OListView( parent, name )
57{ 56{
58 setFrameShape( QListView::StyledPanel ); 57 setFrameShape( QListView::StyledPanel );
59 setFrameShadow( QListView::Sunken ); 58 setFrameShadow( QListView::Sunken );
60 59
61 addColumn( tr( "Net/Station" ) ); 60 addColumn( tr( "Net/Station" ) );
62 setColumnAlignment( col_essid, AlignLeft || AlignVCenter ); 61 setColumnAlignment( col_essid, AlignLeft || AlignVCenter );
63 addColumn( tr( "#" ) ); 62 addColumn( tr( "#" ) );
64 setColumnAlignment( col_sig, AlignCenter ); 63 setColumnAlignment( col_sig, AlignCenter );
65 addColumn( tr( "MAC" ) ); 64 addColumn( tr( "MAC" ) );
66 setColumnAlignment( col_ap, AlignCenter ); 65 setColumnAlignment( col_ap, AlignCenter );
67 addColumn( tr( "Chn" ) ); 66 addColumn( tr( "Chn" ) );
68 setColumnAlignment( col_channel, AlignCenter ); 67 setColumnAlignment( col_channel, AlignCenter );
69 addColumn( tr( "W" ) ); 68 addColumn( tr( "W" ) );
70 setColumnAlignment( col_wep, AlignCenter ); 69 setColumnAlignment( col_wep, AlignCenter );
71 addColumn( tr( "T" ) ); 70 addColumn( tr( "T" ) );
72 setColumnAlignment( col_traffic, AlignCenter ); 71 setColumnAlignment( col_traffic, AlignCenter );
73 addColumn( tr( "IP" ) ); 72 addColumn( tr( "IP" ) );
74 setColumnAlignment( col_ip, AlignCenter ); 73 setColumnAlignment( col_ip, AlignCenter );
75 addColumn( tr( "Manufacturer" ) ); 74 addColumn( tr( "Manufacturer" ) );
76 setColumnAlignment( col_manuf, AlignCenter ); 75 setColumnAlignment( col_manuf, AlignCenter );
77 addColumn( tr( "First Seen" ) ); 76 addColumn( tr( "First Seen" ) );
78 setColumnAlignment( col_firstseen, AlignCenter ); 77 setColumnAlignment( col_firstseen, AlignCenter );
79 addColumn( tr( "Last Seen" ) ); 78 addColumn( tr( "Last Seen" ) );
80 setColumnAlignment( col_lastseen, AlignCenter ); 79 setColumnAlignment( col_lastseen, AlignCenter );
81 addColumn( tr( "Location" ) ); 80 addColumn( tr( "Location" ) );
82 setColumnAlignment( col_location, AlignCenter ); 81 setColumnAlignment( col_location, AlignCenter );
83 setRootIsDecorated( true ); 82 setRootIsDecorated( true );
84 setAllColumnsShowFocus( true ); 83 setAllColumnsShowFocus( true );
85 84
86 connect( this, SIGNAL( rightButtonClicked(QListViewItem*,const QPoint&,int) ), 85 connect( this, SIGNAL( rightButtonClicked(QListViewItem*,const QPoint&,int) ),
87 this, SLOT( contextMenuRequested(QListViewItem*,const QPoint&,int) ) ); 86 this, SLOT( contextMenuRequested(QListViewItem*,const QPoint&,int) ) );
88 87
89 #ifdef QWS 88 #ifdef QWS
90 QPEApplication::setStylusOperation( viewport(), QPEApplication::RightOnHold ); 89 QPEApplication::setStylusOperation( viewport(), QPEApplication::RightOnHold );
91 #endif 90 #endif
92 91
93}; 92};
94 93
95 94
96MScanListView::~MScanListView() 95MScanListView::~MScanListView()
97{ 96{
98}; 97};
99 98
100 99
101OListViewItem* MScanListView::childFactory() 100OListViewItem* MScanListView::childFactory()
102{ 101{
103 return new MScanListItem( this ); 102 return new MScanListItem( this );
104} 103}
105 104
106 105
107void MScanListView::serializeTo( QDataStream& s) const 106void MScanListView::serializeTo( QDataStream& s) const
108{ 107{
109 qDebug( "serializing MScanListView" ); 108 odebug << "serializing MScanListView" << oendl;
110 OListView::serializeTo( s ); 109 OListView::serializeTo( s );
111} 110}
112 111
113 112
114void MScanListView::serializeFrom( QDataStream& s) 113void MScanListView::serializeFrom( QDataStream& s)
115{ 114{
116 qDebug( "serializing MScanListView" ); 115 odebug << "serializing MScanListView" << oendl;
117 OListView::serializeFrom( s ); 116 OListView::serializeFrom( s );
118} 117}
119 118
120 119
121void MScanListView::addNewItem( const QString& type, 120void MScanListView::addNewItem( const QString& type,
122 const QString& essid, 121 const QString& essid,
123 const OMacAddress& mac, 122 const OMacAddress& mac,
124 bool wep, 123 bool wep,
125 int channel, 124 int channel,
126 int signal, 125 int signal,
127 const GpsLocation& loc, 126 const GpsLocation& loc,
128 bool probe ) 127 bool probe )
129{ 128{
130 QString macaddr = mac.toString(true); 129 QString macaddr = mac.toString(true);
131 130
132 #ifdef DEBUG 131 #ifdef DEBUG
133 qDebug( "MScanList::addNewItem( %s / %s / %s [%d]", (const char*) type, 132 qDebug( "MScanList::addNewItem( %s / %s / %s [%d]", (const char*) type,
134 (const char*) essid, (const char*) macaddr, channel ); 133 (const char*) essid, (const char*) macaddr, channel );
135 #endif 134 #endif
136 135
137 // search, if we already have seen this net 136 // search, if we already have seen this net
138 137
139 QString s; 138 QString s;
140 MScanListItem* network; 139 MScanListItem* network;
141 MScanListItem* item = static_cast<MScanListItem*> ( firstChild() ); 140 MScanListItem* item = static_cast<MScanListItem*> ( firstChild() );
142 141
143 while ( item && ( item->text( col_essid ) != essid ) ) 142 while ( item && ( item->text( col_essid ) != essid ) )
144 { 143 {
145 #ifdef DEBUG 144 #ifdef DEBUG
146 qDebug( "itemtext: %s", (const char*) item->text( col_essid ) ); 145 odebug << "itemtext: " << (const char*) item->text( col_essid ) << "" << oendl;
147 #endif 146 #endif
148 item = static_cast<MScanListItem*> ( item->nextSibling() ); 147 item = static_cast<MScanListItem*> ( item->nextSibling() );
149 } 148 }
150 if ( item ) 149 if ( item )
151 { 150 {
152 // we have already seen this net, check all childs if MAC exists 151 // we have already seen this net, check all childs if MAC exists
153 152
154 network = item; 153 network = item;
155 154
156 item = static_cast<MScanListItem*> ( item->firstChild() ); 155 item = static_cast<MScanListItem*> ( item->firstChild() );
157 assert( item ); // this shouldn't fail 156 assert( item ); // this shouldn't fail
158 157
159 while ( item && ( item->text( col_ap ) != macaddr ) ) 158 while ( item && ( item->text( col_ap ) != macaddr ) )
160 { 159 {
161 #ifdef DEBUG 160 #ifdef DEBUG
162 qDebug( "subitemtext: %s", (const char*) item->text( col_ap ) ); 161 odebug << "subitemtext: " << (const char*) item->text( col_ap ) << "" << oendl;
163 #endif 162 #endif
164 item = static_cast<MScanListItem*> ( item->nextSibling() ); 163 item = static_cast<MScanListItem*> ( item->nextSibling() );
165 } 164 }
166 165
167 if ( item ) 166 if ( item )
168 { 167 {
169 // we have already seen this item, it's a dupe 168 // we have already seen this item, it's a dupe
170 #ifdef DEBUG 169 #ifdef DEBUG
171 qDebug( "%s is a dupe - ignoring...", (const char*) macaddr ); 170 odebug << "" << (const char*) macaddr << " is a dupe - ignoring..." << oendl;
172 #endif 171 #endif
173 item->receivedBeacon(); 172 item->receivedBeacon();
174 return; 173 return;
175 } 174 }
176 } 175 }
177 else 176 else
178 { 177 {
179 s.sprintf( "(i) New network: ESSID '%s'", (const char*) essid ); 178 s.sprintf( "(i) New network: ESSID '%s'", (const char*) essid );
180 MLogWindow::logwindow()->log( s ); 179 MLogWindow::logwindow()->log( s );
181 network = new MScanListItem( this, "network", essid, QString::null, 0, 0, 0, probe ); 180 network = new MScanListItem( this, "network", essid, QString::null, 0, 0, 0, probe );
182 } 181 }
183 182
184 183
185 // insert new station as child from network 184 // insert new station as child from network
186 // no essid to reduce clutter, maybe later we have a nick or stationname to display!? 185 // no essid to reduce clutter, maybe later we have a nick or stationname to display!?
187 186
188 #ifdef DEBUG 187 #ifdef DEBUG
189 qDebug( "inserting new station %s", (const char*) macaddr ); 188 odebug << "inserting new station " << (const char*) macaddr << "" << oendl;
190 #endif 189 #endif
191 190
192 MScanListItem* station = new MScanListItem( network, type, "", macaddr, wep, channel, signal ); 191 MScanListItem* station = new MScanListItem( network, type, "", macaddr, wep, channel, signal );
193 station->setManufacturer( mac.manufacturer() ); 192 station->setManufacturer( mac.manufacturer() );
194 station->setLocation( loc.dmsPosition() ); 193 station->setLocation( loc.dmsPosition() );
195 194
196 if ( type == "managed" ) 195 if ( type == "managed" )
197 { 196 {
198 s.sprintf( "(i) New Access Point in '%s' [%d]", (const char*) essid, channel ); 197 s.sprintf( "(i) New Access Point in '%s' [%d]", (const char*) essid, channel );
199 } 198 }
200 else 199 else
201 { 200 {
202 s.sprintf( "(i) New AdHoc station in '%s' [%d]", (const char*) essid, channel ); 201 s.sprintf( "(i) New AdHoc station in '%s' [%d]", (const char*) essid, channel );
203 } 202 }
204 MLogWindow::logwindow()->log( s ); 203 MLogWindow::logwindow()->log( s );
205} 204}
206 205
207 206
208void MScanListView::addIfNotExisting( MScanListItem* network, const OMacAddress& addr, const QString& type ) 207void MScanListView::addIfNotExisting( MScanListItem* network, const OMacAddress& addr, const QString& type )
209{ 208{
210 MScanListItem* subitem = static_cast<MScanListItem*>( network->firstChild() ); 209 MScanListItem* subitem = static_cast<MScanListItem*>( network->firstChild() );
211 210
212 while ( subitem && ( subitem->text( col_ap ) != addr.toString(true) ) ) 211 while ( subitem && ( subitem->text( col_ap ) != addr.toString(true) ) )
213 { 212 {
214 #ifdef DEBUG 213 #ifdef DEBUG
215 qDebug( "subitemtext: %s", (const char*) subitem->text( col_ap ) ); 214 odebug << "subitemtext: " << (const char*) subitem->text( col_ap ) << "" << oendl;
216 #endif 215 #endif
217 subitem = static_cast<MScanListItem*> ( subitem->nextSibling() ); 216 subitem = static_cast<MScanListItem*> ( subitem->nextSibling() );
218 } 217 }
219 218
220 if ( subitem ) 219 if ( subitem )
221 { 220 {
222 // we have already seen this item, it's a dupe 221 // we have already seen this item, it's a dupe
223 #ifdef DEBUG 222 #ifdef DEBUG
224 qDebug( "%s is a dupe - ignoring...", (const char*) addr.toString(true) ); 223 odebug << "" << (const char*) addr.toString(true) << " is a dupe - ignoring..." << oendl;
225 #endif 224 #endif
226 subitem->receivedBeacon(); //FIXME: sent data bit 225 subitem->receivedBeacon(); //FIXME: sent data bit
227 return; 226 return;
228 } 227 }
229 228
230 // Hey, it seems to be a new item :-D 229 // Hey, it seems to be a new item :-D
231 MScanListItem* station = new MScanListItem( network, type, /* network->text( col_essid ) */ "", addr.toString(true), false, -1, -1 ); 230 MScanListItem* station = new MScanListItem( network, type, /* network->text( col_essid ) */ "", addr.toString(true), false, -1, -1 );
232 station->setManufacturer( addr.manufacturer() ); 231 station->setManufacturer( addr.manufacturer() );
233 232
234 QString s; 233 QString s;
235 if ( type == "station" ) 234 if ( type == "station" )
236 { 235 {
237 s.sprintf( "(i) New Station in '%s' [xx]", (const char*) network->text( col_essid ) ); 236 s.sprintf( "(i) New Station in '%s' [xx]", (const char*) network->text( col_essid ) );
238 } 237 }
239 else 238 else
240 { 239 {
241 s.sprintf( "(i) New Wireless Station in '%s' [xx]", (const char*) network->text( col_essid ) ); 240 s.sprintf( "(i) New Wireless Station in '%s' [xx]", (const char*) network->text( col_essid ) );
242 } 241 }
243 MLogWindow::logwindow()->log( s ); 242 MLogWindow::logwindow()->log( s );
244} 243}
245 244
246 245
247void MScanListView::WDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& viaFrom, const OMacAddress& viaTo ) 246void MScanListView::WDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& viaFrom, const OMacAddress& viaTo )
248{ 247{
249 qDebug( "WDSTraffic: %s and %s seem to form a WDS", (const char*) viaFrom.toString(), (const char*) viaTo.toString() ); 248 odebug << "WDSTraffic: " << (const char*) viaFrom.toString() << " and " << (const char*) viaTo.toString() << " seem to form a WDS" << oendl;
250 QString s; 249 QString s;
251 MScanListItem* network; 250 MScanListItem* network;
252 251
253 QListViewItemIterator it( this ); 252 QListViewItemIterator it( this );
254 while ( it.current() && 253 while ( it.current() &&
255 it.current()->text( col_ap ) != viaFrom.toString(true) && 254 it.current()->text( col_ap ) != viaFrom.toString(true) &&
256 it.current()->text( col_ap ) != viaTo.toString(true) ) ++it; 255 it.current()->text( col_ap ) != viaTo.toString(true) ) ++it;
257 256
258 MScanListItem* item = static_cast<MScanListItem*>( it.current() ); 257 MScanListItem* item = static_cast<MScanListItem*>( it.current() );
259 258
260 if ( item ) // Either viaFrom or viaTo AP has shown up yet, so just add our two new stations 259 if ( item ) // Either viaFrom or viaTo AP has shown up yet, so just add our two new stations
261 { 260 {
262 addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from ); 261 addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from );
263 addIfNotExisting( static_cast<MScanListItem*>(item->parent()), to ); 262 addIfNotExisting( static_cast<MScanListItem*>(item->parent()), to );
264 } 263 }
265 else 264 else
266 { 265 {
267 qDebug( "D'Oh! Stations without AP... ignoring for now... will handle this in 1.1 version :-D" ); 266 odebug << "D'Oh! Stations without AP... ignoring for now... will handle this in 1.1 version :-D" << oendl;
268 MLogWindow::logwindow()->log( "WARNING: Unhandled WSD traffic!" ); 267 MLogWindow::logwindow()->log( "WARNING: Unhandled WSD traffic!" );
269 } 268 }
270} 269}
271 270
272 271
273void MScanListView::toDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via ) 272void MScanListView::toDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via )
274{ 273{
275 QString s; 274 QString s;
276 MScanListItem* network; 275 MScanListItem* network;
277 276
278 QListViewItemIterator it( this ); 277 QListViewItemIterator it( this );
279 while ( it.current() && it.current()->text( col_ap ) != via.toString(true) ) ++it; 278 while ( it.current() && it.current()->text( col_ap ) != via.toString(true) ) ++it;
280 279
281 MScanListItem* item = static_cast<MScanListItem*>( it.current() ); 280 MScanListItem* item = static_cast<MScanListItem*>( it.current() );
282 281
283 if ( item ) // AP has shown up yet, so just add our new "from" - station 282 if ( item ) // AP has shown up yet, so just add our new "from" - station
284 { 283 {
285 addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from, "adhoc" ); 284 addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from, "adhoc" );
286 } 285 }
287 else 286 else
288 { 287 {
289 qDebug( "D'Oh! Station without AP... ignoring for now... will handle this in 1.1 :-D" ); 288 odebug << "D'Oh! Station without AP... ignoring for now... will handle this in 1.1 :-D" << oendl;
290 MLogWindow::logwindow()->log( "WARNING: Unhandled toDS traffic!" ); 289 MLogWindow::logwindow()->log( "WARNING: Unhandled toDS traffic!" );
291 290
292 } 291 }
293} 292}
294 293
295 294
296void MScanListView::fromDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via ) 295void MScanListView::fromDStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via )
297{ 296{
298 QString s; 297 QString s;
299 MScanListItem* network; 298 MScanListItem* network;
300 299
301 QListViewItemIterator it( this ); 300 QListViewItemIterator it( this );
302 while ( it.current() && it.current()->text( col_ap ) != via.toString(true) ) ++it; 301 while ( it.current() && it.current()->text( col_ap ) != via.toString(true) ) ++it;
303 302
304 MScanListItem* item = static_cast<MScanListItem*>( it.current() ); 303 MScanListItem* item = static_cast<MScanListItem*>( it.current() );
305 304
306 if ( item ) // AP has shown up yet, so just add our new "from" - station 305 if ( item ) // AP has shown up yet, so just add our new "from" - station
307 { 306 {
308 addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from, "station" ); 307 addIfNotExisting( static_cast<MScanListItem*>(item->parent()), from, "station" );
309 } 308 }
310 else 309 else
311 { 310 {
312 qDebug( "D'Oh! Station without AP... ignoring for now... will handle this in 1.1 :-D" ); 311 odebug << "D'Oh! Station without AP... ignoring for now... will handle this in 1.1 :-D" << oendl;
313 MLogWindow::logwindow()->log( "WARNING: Unhandled fromDS traffic!" ); 312 MLogWindow::logwindow()->log( "WARNING: Unhandled fromDS traffic!" );
314 } 313 }
315} 314}
316 315
317 316
318void MScanListView::IBSStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via ) 317void MScanListView::IBSStraffic( const OMacAddress& from, const OMacAddress& to, const OMacAddress& via )
319{ 318{
320 qWarning( "D'oh! Not yet implemented..." ); 319 owarn << "D'oh! Not yet implemented..." << oendl;
321 MLogWindow::logwindow()->log( "WARNING: Unhandled IBSS traffic!" ); 320 MLogWindow::logwindow()->log( "WARNING: Unhandled IBSS traffic!" );
322} 321}
323 322
324 323
325void MScanListView::identify( const OMacAddress& macaddr, const QString& ip ) 324void MScanListView::identify( const OMacAddress& macaddr, const QString& ip )
326{ 325{
327 qDebug( "identify %s = %s", (const char*) macaddr.toString(), (const char*) ip ); 326 odebug << "identify " << (const char*) macaddr.toString() << " = " << (const char*) ip << "" << oendl;
328 327
329 QListViewItemIterator it( this ); 328 QListViewItemIterator it( this );
330 for ( ; it.current(); ++it ) 329 for ( ; it.current(); ++it )
331 { 330 {
332 if ( it.current()->text( col_ap ) == macaddr.toString(true) ) 331 if ( it.current()->text( col_ap ) == macaddr.toString(true) )
333 { 332 {
334 it.current()->setText( col_ip, ip ); 333 it.current()->setText( col_ip, ip );
335 return; 334 return;
336 } 335 }
337 } 336 }
338 qDebug( "D'oh! Received identification, but item not yet in list... ==> Handle this!" ); 337 odebug << "D'oh! Received identification, but item not yet in list... ==> Handle this!" << oendl;
339 MLogWindow::logwindow()->log( QString().sprintf( "WARNING: Unhandled identification %s = %s!", 338 MLogWindow::logwindow()->log( QString().sprintf( "WARNING: Unhandled identification %s = %s!",
340 (const char*) macaddr.toString(), (const char*) ip ) ); 339 (const char*) macaddr.toString(), (const char*) ip ) );
341} 340}
342 341
343 342
344void MScanListView::addService( const QString& name, const OMacAddress& macaddr, const QString& ip ) 343void MScanListView::addService( const QString& name, const OMacAddress& macaddr, const QString& ip )
345{ 344{
346 qDebug( "addService '%s', Server = %s = %s", (const char*) name, (const char*) macaddr.toString(), (const char*) ip ); 345 odebug << "addService '" << (const char*) name << "', Server = " << (const char*) macaddr.toString() << " = " << (const char*) ip << "" << oendl;
347 346
348 //TODO: Refactor that out, we need it all over the place. 347 //TODO: Refactor that out, we need it all over the place.
349 // Best to do it in a more comfortable abstraction in OListView 348 // Best to do it in a more comfortable abstraction in OListView
350 // (Hmm, didn't I already start something in this direction?) 349 // (Hmm, didn't I already start something in this direction?)
351 350
352 QListViewItemIterator it( this ); 351 QListViewItemIterator it( this );
353 for ( ; it.current(); ++it ) 352 for ( ; it.current(); ++it )
354 { 353 {
355 if ( it.current()->text( col_ap ) == macaddr.toString(true) ) 354 if ( it.current()->text( col_ap ) == macaddr.toString(true) )
356 { 355 {
357 356
358 MScanListItem* subitem = static_cast<MScanListItem*>( it.current()->firstChild() ); 357 MScanListItem* subitem = static_cast<MScanListItem*>( it.current()->firstChild() );
359 358
360 while ( subitem && ( subitem->text( col_essid ) != name ) ) 359 while ( subitem && ( subitem->text( col_essid ) != name ) )
361 { 360 {
362 #ifdef DEBUG 361 #ifdef DEBUG
363 qDebug( "subitemtext: %s", (const char*) subitem->text( col_essid ) ); 362 odebug << "subitemtext: " << (const char*) subitem->text( col_essid ) << "" << oendl;
364 #endif 363 #endif
365 subitem = static_cast<MScanListItem*> ( subitem->nextSibling() ); 364 subitem = static_cast<MScanListItem*> ( subitem->nextSibling() );
366 } 365 }
367 366
368 if ( subitem ) 367 if ( subitem )
369 { 368 {
370 // we have already seen this item, it's a dupe 369 // we have already seen this item, it's a dupe
371 #ifdef DEBUG 370 #ifdef DEBUG
372 qDebug( "%s is a dupe - ignoring...", (const char*) name ); 371 odebug << "" << (const char*) name << " is a dupe - ignoring..." << oendl;
373 #endif 372 #endif
374 subitem->receivedBeacon(); //FIXME: sent data bit 373 subitem->receivedBeacon(); //FIXME: sent data bit
375 return; 374 return;
376 } 375 }
377 376
378 // never seen that - add new item 377 // never seen that - add new item
379 378
380 MScanListItem* item = new MScanListItem( it.current(), "service", "N/A", " ", false, -1, -1 ); 379 MScanListItem* item = new MScanListItem( it.current(), "service", "N/A", " ", false, -1, -1 );
381 item->setText( col_essid, name ); 380 item->setText( col_essid, name );
382 381
383 return; 382 return;
384 } 383 }
385 } 384 }
386 qDebug( "D'oh! Received identification, but item not yet in list... ==> Handle this!" ); 385 odebug << "D'oh! Received identification, but item not yet in list... ==> Handle this!" << oendl;
387 MLogWindow::logwindow()->log( QString().sprintf( "WARNING: Unhandled service addition %s = %s!", 386 MLogWindow::logwindow()->log( QString().sprintf( "WARNING: Unhandled service addition %s = %s!",
388 (const char*) macaddr.toString(), (const char*) ip ) ); 387 (const char*) macaddr.toString(), (const char*) ip ) );
389} 388}
390 389
391 390
392void MScanListView::contextMenuRequested( QListViewItem* item, const QPoint&, int col ) 391void MScanListView::contextMenuRequested( QListViewItem* item, const QPoint&, int col )
393{ 392{
394 if ( !item ) return; 393 if ( !item ) return;
395 394
396 MScanListItem* itm = static_cast<MScanListItem*>( item ); 395 MScanListItem* itm = static_cast<MScanListItem*>( item );
397 396
398 qDebug( "contextMenuRequested on item '%s' (%s) in column: '%d'", 397 qDebug( "contextMenuRequested on item '%s' (%s) in column: '%d'",
399 (const char*) itm->text(0), (const char*) itm->type, col ); 398 (const char*) itm->text(0), (const char*) itm->type, col );
400 399
401 if ( itm->type == "adhoc" || itm->type == "managed" ) 400 if ( itm->type == "adhoc" || itm->type == "managed" )
402 { 401 {
403 QString entry = QString().sprintf( "&Join %s Net '%s'...", (const char*) itm->type, (const char*) itm->essid() ); 402 QString entry = QString().sprintf( "&Join %s Net '%s'...", (const char*) itm->type, (const char*) itm->essid() );
404 403
405 QPopupMenu m( this ); 404 QPopupMenu m( this );
406 m.insertItem( entry, 37773, 0 ); 405 m.insertItem( entry, 37773, 0 );
407 int result = m.exec( QCursor::pos() ); 406 int result = m.exec( QCursor::pos() );
408 if ( result == 37773 ) 407 if ( result == 37773 )
409 emit joinNetwork( itm->type, itm->essid(), itm->channel(), itm->macaddr() ); 408 emit joinNetwork( itm->type, itm->essid(), itm->channel(), itm->macaddr() );
410 } 409 }
411} 410}
412 411
413//============================================================ 412//============================================================
414// MScanListItem 413// MScanListItem
415//============================================================ 414//============================================================
416 415
417MScanListItem::MScanListItem( QListView* parent, const QString& type, const QString& essid, const QString& macaddr, 416MScanListItem::MScanListItem( QListView* parent, const QString& type, const QString& essid, const QString& macaddr,
418 bool wep, int channel, int signal, bool probed ) 417 bool wep, int channel, int signal, bool probed )
419 :OListViewItem( parent, essid, QString::null, macaddr, QString::null, QString::null ), 418 :OListViewItem( parent, essid, QString::null, macaddr, QString::null, QString::null ),
420 _type( type ), _essid( essid ), _macaddr( macaddr ), _wep( wep ), 419 _type( type ), _essid( essid ), _macaddr( macaddr ), _wep( wep ),
421 _channel( channel ), _signal( signal ), _beacons( 1 ) 420 _channel( channel ), _signal( signal ), _beacons( 1 )
422{ 421{
423 #ifdef DEBUG 422 #ifdef DEBUG
424 qDebug( "creating scanlist item" ); 423 odebug << "creating scanlist item" << oendl;
425 #endif 424 #endif
426 425
427 if ( WellenreiterConfigWindow::instance() ) 426 if ( WellenreiterConfigWindow::instance() )
428 WellenreiterConfigWindow::instance()->performAction( type, essid, macaddr, wep, channel, signal ); // better use signal/slot combination here 427 WellenreiterConfigWindow::instance()->performAction( type, essid, macaddr, wep, channel, signal ); // better use signal/slot combination here
429 428
430 decorateItem( type, essid, macaddr, wep, channel, signal, probed ); 429 decorateItem( type, essid, macaddr, wep, channel, signal, probed );
431} 430}
432 431
433MScanListItem::MScanListItem( QListViewItem* parent, const QString& type, const QString& essid, const QString& macaddr, 432MScanListItem::MScanListItem( QListViewItem* parent, const QString& type, const QString& essid, const QString& macaddr,
434 bool wep, int channel, int signal ) 433 bool wep, int channel, int signal )
435 :OListViewItem( parent, essid, QString::null, macaddr, QString::null, QString::null ) 434 :OListViewItem( parent, essid, QString::null, macaddr, QString::null, QString::null )
436{ 435{
437 #ifdef DEBUG 436 #ifdef DEBUG
438 qDebug( "creating scanlist item" ); 437 odebug << "creating scanlist item" << oendl;
439 #endif 438 #endif
440 if ( WellenreiterConfigWindow::instance() ) 439 if ( WellenreiterConfigWindow::instance() )
441 WellenreiterConfigWindow::instance()->performAction( type, essid, macaddr, wep, channel, signal ); // better use signal/slot combination here 440 WellenreiterConfigWindow::instance()->performAction( type, essid, macaddr, wep, channel, signal ); // better use signal/slot combination here
442 441
443 decorateItem( type, essid, macaddr, wep, channel, signal, false ); 442 decorateItem( type, essid, macaddr, wep, channel, signal, false );
444} 443}
445 444
446const QString& MScanListItem::essid() const 445const QString& MScanListItem::essid() const
447{ 446{
448 if ( type == "network" ) 447 if ( type == "network" )
449 return _essid; 448 return _essid;
450 else 449 else
451 return ( (MScanListItem*) parent() )->essid(); 450 return ( (MScanListItem*) parent() )->essid();
452} 451}
453 452
454OListViewItem* MScanListItem::childFactory() 453OListViewItem* MScanListItem::childFactory()
455{ 454{
456 return new MScanListItem( this ); 455 return new MScanListItem( this );
457} 456}
458 457
459void MScanListItem::serializeTo( QDataStream& s ) const 458void MScanListItem::serializeTo( QDataStream& s ) const
460{ 459{
461 #ifdef DEBUG 460 #ifdef DEBUG
462 qDebug( "serializing MScanListItem" ); 461 odebug << "serializing MScanListItem" << oendl;
463 #endif 462 #endif
464 OListViewItem::serializeTo( s ); 463 OListViewItem::serializeTo( s );
465 464
466 s << _type; 465 s << _type;
467 s << (Q_UINT8) ( _wep ? 'y' : 'n' ); 466 s << (Q_UINT8) ( _wep ? 'y' : 'n' );
468} 467}
469 468
470void MScanListItem::serializeFrom( QDataStream& s ) 469void MScanListItem::serializeFrom( QDataStream& s )
471{ 470{
472 #ifdef DEBUG 471 #ifdef DEBUG
473 qDebug( "serializing MScanListItem" ); 472 odebug << "serializing MScanListItem" << oendl;
474 #endif 473 #endif
475 OListViewItem::serializeFrom( s ); 474 OListViewItem::serializeFrom( s );
476 475
477 char wep; 476 char wep;
478 s >> _type; 477 s >> _type;
479 s >> (Q_UINT8) wep; 478 s >> (Q_UINT8) wep;
480 _wep = (wep == 'y'); 479 _wep = (wep == 'y');
481 480
482 QString name; 481 QString name;
483 name.sprintf( "wellenreiter/%s", (const char*) _type ); 482 name.sprintf( "wellenreiter/%s", (const char*) _type );
484 setPixmap( col_type, Resource::loadPixmap( name ) ); 483 setPixmap( col_type, Resource::loadPixmap( name ) );
485 if ( _wep ) 484 if ( _wep )
486 setPixmap( col_wep, Resource::loadPixmap( "wellenreiter/cracked" ) ); //FIXME: rename the pixmap! 485 setPixmap( col_wep, Resource::loadPixmap( "wellenreiter/cracked" ) ); //FIXME: rename the pixmap!
487 listView()->triggerUpdate(); 486 listView()->triggerUpdate();
488} 487}
489 488
490void MScanListItem::decorateItem( QString type, QString essid, QString macaddr, bool wep, int channel, int signal, bool probed ) 489void MScanListItem::decorateItem( QString type, QString essid, QString macaddr, bool wep, int channel, int signal, bool probed )
491{ 490{
492 #ifdef DEBUG 491 #ifdef DEBUG
493 qDebug( "decorating scanlist item %s / %s / %s [%d]", 492 qDebug( "decorating scanlist item %s / %s / %s [%d]",
494 (const char*) type, 493 (const char*) type,
495 (const char*) essid, 494 (const char*) essid,
496 (const char*) macaddr, 495 (const char*) macaddr,
497 channel ); 496 channel );
498 #endif 497 #endif
499 498
500 // set icon for managed or adhoc mode 499 // set icon for managed or adhoc mode
501 QString name; 500 QString name;
502 name.sprintf( "wellenreiter/%s", (const char*) type ); 501 name.sprintf( "wellenreiter/%s", (const char*) type );
503 setPixmap( col_type, Resource::loadPixmap( name ) ); 502 setPixmap( col_type, Resource::loadPixmap( name ) );
504 503
505 // special case for probed networks FIXME: This is ugly at present 504 // special case for probed networks FIXME: This is ugly at present
506 if ( type == "network" && probed ) 505 if ( type == "network" && probed )
507 { 506 {
508 setPixmap( col_type, Resource::loadPixmap( "wellenreiter/network-probed.png" ) ); 507 setPixmap( col_type, Resource::loadPixmap( "wellenreiter/network-probed.png" ) );
509 } 508 }
510 509
511 // set icon for wep (wireless encryption protocol) 510 // set icon for wep (wireless encryption protocol)
512 if ( wep ) 511 if ( wep )
513 setPixmap( col_wep, Resource::loadPixmap( "wellenreiter/cracked" ) ); //FIXME: rename the pixmap! 512 setPixmap( col_wep, Resource::loadPixmap( "wellenreiter/cracked" ) ); //FIXME: rename the pixmap!
514 513
515 // set channel and signal text 514 // set channel and signal text
516 515
517 if ( signal != -1 ) 516 if ( signal != -1 )
518 setText( col_sig, QString::number( signal ) ); 517 setText( col_sig, QString::number( signal ) );
519 if ( channel != -1 ) 518 if ( channel != -1 )
520 setText( col_channel, QString::number( channel ) ); 519 setText( col_channel, QString::number( channel ) );
521 520
522 setText( col_firstseen, QTime::currentTime().toString() ); 521 setText( col_firstseen, QTime::currentTime().toString() );
523 //setText( col_lastseen, QTime::currentTime().toString() ); 522 //setText( col_lastseen, QTime::currentTime().toString() );
524 523
525 listView()->triggerUpdate(); 524 listView()->triggerUpdate();
526 525
527 this->type = type; 526 this->type = type;
528 _type = type; 527 _type = type;
529 _essid = essid; 528 _essid = essid;
530 _macaddr = macaddr; 529 _macaddr = macaddr;
531 _channel = channel; 530 _channel = channel;
532 _beacons = 1; 531 _beacons = 1;
533 _signal = 0; 532 _signal = 0;
534 533
535 if ( WellenreiterConfigWindow::instance()->openTree->isChecked() ) 534 if ( WellenreiterConfigWindow::instance()->openTree->isChecked() )
536 { 535 {
537 listView()->ensureItemVisible( this ); 536 listView()->ensureItemVisible( this );
538 } 537 }
539 538
540} 539}
541 540
542 541
543void MScanListItem::setManufacturer( const QString& manufacturer ) 542void MScanListItem::setManufacturer( const QString& manufacturer )
544{ 543{
545 setText( col_manuf, manufacturer ); 544 setText( col_manuf, manufacturer );
546} 545}
547 546
548 547
549void MScanListItem::setLocation( const QString& location ) 548void MScanListItem::setLocation( const QString& location )
550{ 549{
551 setText( col_location, location ); 550 setText( col_location, location );
552} 551}
553 552
554 553
555void MScanListItem::receivedBeacon() 554void MScanListItem::receivedBeacon()
556{ 555{
557 _beacons++; 556 _beacons++;
558 #ifdef DEBUG 557 #ifdef DEBUG
559 qDebug( "MScanListItem %s: received beacon #%d", (const char*) _macaddr, _beacons ); 558 odebug << "MScanListItem " << (const char*) _macaddr << ": received beacon #" << _beacons << "" << oendl;
560 #endif 559 #endif
561 setText( col_sig, QString::number( _beacons ) ); 560 setText( col_sig, QString::number( _beacons ) );
562 setText( col_lastseen, QTime::currentTime().toString() ); 561 setText( col_lastseen, QTime::currentTime().toString() );
563 562
564 MScanListItem* p = (MScanListItem*) parent(); 563 MScanListItem* p = (MScanListItem*) parent();
565 if ( p ) p->receivedBeacon(); 564 if ( p ) p->receivedBeacon();
566 565
567} 566}
568 567
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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file may be distributed and/or modified under the terms of the 4** This file may be distributed and/or modified under the terms of the
5** GNU General Public License version 2 as published by the Free Software 5** GNU General Public License version 2 as published by the Free Software
6** Foundation and appearing in the file LICENSE.GPL included in the 6** Foundation and appearing in the file LICENSE.GPL included in the
7** packaging of this file. 7** packaging of this file.
8** 8**
9** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 9** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
10** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 10** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
11** 11**
12***********************************************************************/ 12***********************************************************************/
13 13
14// Local
15
16#include "gps.h" 14#include "gps.h"
17#include "wellenreiter.h" 15#include "wellenreiter.h"
18#include "scanlist.h" 16#include "scanlist.h"
19#include "logwindow.h" 17#include "logwindow.h"
20#include "packetview.h" 18#include "packetview.h"
21#include "configwindow.h" 19#include "configwindow.h"
22#include "statwindow.h" 20#include "statwindow.h"
23#include "graphwindow.h" 21#include "graphwindow.h"
24#include "protolistview.h" 22#include "protolistview.h"
25 23
26// Opie 24/* OPIE */
27
28#ifdef QWS 25#ifdef QWS
29#include <opie2/oapplication.h> 26#include <opie2/oapplication.h>
27#include <opie2/odebug.h>
30#include <opie2/odevice.h> 28#include <opie2/odevice.h>
31#else 29#else
32#include <qapplication.h> 30#include <qapplication.h>
33#endif 31#endif
34#include <opie2/omanufacturerdb.h> 32#include <opie2/omanufacturerdb.h>
35#include <opie2/onetwork.h> 33#include <opie2/onetwork.h>
36#include <opie2/opcap.h> 34#include <opie2/opcap.h>
37#include <qpe/qcopenvelope_qws.h> 35#include <qpe/qcopenvelope_qws.h>
38using namespace Opie; 36using namespace Opie::Core;
39 37using namespace Opie::Net;
40// Qt 38using namespace Opie::Ui;
41 39
40/* QT */
42#include <qcheckbox.h> 41#include <qcheckbox.h>
43#include <qcombobox.h> 42#include <qcombobox.h>
44#include <qdatetime.h> 43#include <qdatetime.h>
45#include <qpushbutton.h> 44#include <qpushbutton.h>
46#include <qlineedit.h> 45#include <qlineedit.h>
47#include <qmessagebox.h> 46#include <qmessagebox.h>
48#include <qobjectlist.h> 47#include <qobjectlist.h>
49#include <qregexp.h> 48#include <qregexp.h>
50#include <qspinbox.h> 49#include <qspinbox.h>
51#include <qtimer.h> 50#include <qtimer.h>
52#include <qtoolbutton.h> 51#include <qtoolbutton.h>
53#include <qmainwindow.h> 52#include <qmainwindow.h>
54 53
55// Standard 54/* STD */
56
57#include <assert.h> 55#include <assert.h>
58#include <errno.h> 56#include <errno.h>
59#include <unistd.h> 57#include <unistd.h>
60#include <string.h> 58#include <string.h>
61#include <sys/types.h> 59#include <sys/types.h>
62#include <stdlib.h> 60#include <stdlib.h>
63 61
64using namespace Opie::Core;
65using namespace Opie::Net;
66using namespace Opie::Net;
67using namespace Opie::Core;
68using namespace Opie::Net;
69using namespace Opie::Core;
70Wellenreiter::Wellenreiter( QWidget* parent ) 62Wellenreiter::Wellenreiter( QWidget* parent )
71 : WellenreiterBase( parent, 0, 0 ), 63 : WellenreiterBase( parent, 0, 0 ),
72 sniffing( false ), iface( 0 ), configwindow( 0 ) 64 sniffing( false ), iface( 0 ), configwindow( 0 )
73{ 65{
74 66
75 logwindow->log( "(i) Wellenreiter has been started." ); 67 logwindow->log( "(i) Wellenreiter has been started." );
76 68
77 // 69 //
78 // detect operating system 70 // detect operating system
79 // 71 //
80 72
81 #ifdef QWS 73 #ifdef QWS
82 QString sys; 74 QString sys;
83 sys.sprintf( "(i) Running on '%s'.", (const char*) ODevice::inst()->systemString() ); 75 sys.sprintf( "(i) Running on '%s'.", (const char*) ODevice::inst()->systemString() );
84 _system = ODevice::inst()->system(); 76 _system = ODevice::inst()->system();
85 logwindow->log( sys ); 77 logwindow->log( sys );
86 #endif 78 #endif
87 79
88 netview->setColumnWidthMode( 1, QListView::Manual ); 80 netview->setColumnWidthMode( 1, QListView::Manual );
89 connect( netview, SIGNAL( joinNetwork(const QString&,const QString&,int,const QString&) ), 81 connect( netview, SIGNAL( joinNetwork(const QString&,const QString&,int,const QString&) ),
90 this, SLOT( joinNetwork(const QString&,const QString&,int,const QString&) ) ); 82 this, SLOT( joinNetwork(const QString&,const QString&,int,const QString&) ) );
91 pcap = new OPacketCapturer(); 83 pcap = new OPacketCapturer();
92 pcap->setAutoDelete( false ); 84 pcap->setAutoDelete( false );
93 85
94 gps = new GPS( this ); 86 gps = new GPS( this );
95 87
96 QTimer::singleShot( 1000, this, SLOT( initialTimer() ) ); 88 QTimer::singleShot( 1000, this, SLOT( initialTimer() ) );
97 89
98} 90}
99 91
100 92
101Wellenreiter::~Wellenreiter() 93Wellenreiter::~Wellenreiter()
102{ 94{
103 delete pcap; 95 delete pcap;
104} 96}
105 97
106 98
107void Wellenreiter::initialTimer() 99void Wellenreiter::initialTimer()
108{ 100{
109 qDebug( "Wellenreiter::preloading manufacturer database..." ); 101 odebug << "Wellenreiter::preloading manufacturer database..." << oendl;
110 OManufacturerDB::instance(); 102 OManufacturerDB::instance();
111} 103}
112 104
113 105
114void Wellenreiter::setConfigWindow( WellenreiterConfigWindow* cw ) 106void Wellenreiter::setConfigWindow( WellenreiterConfigWindow* cw )
115{ 107{
116 configwindow = cw; 108 configwindow = cw;
117} 109}
118 110
119 111
120void Wellenreiter::channelHopped(int c) 112void Wellenreiter::channelHopped(int c)
121{ 113{
122 QString title = "Wellenreiter II -scan- ["; 114 QString title = "Wellenreiter II -scan- [";
123 QString left; 115 QString left;
124 if ( c > 1 ) left.fill( '.', c-1 ); 116 if ( c > 1 ) left.fill( '.', c-1 );
125 title.append( left ); 117 title.append( left );
126 title.append( '|' ); 118 title.append( '|' );
127 if ( c < iface->channels() ) 119 if ( c < iface->channels() )
128 { 120 {
129 QString right; 121 QString right;
130 right.fill( '.', iface->channels()-c ); 122 right.fill( '.', iface->channels()-c );
131 title.append( right ); 123 title.append( right );
132 } 124 }
133 title.append( "]" ); 125 title.append( "]" );
134 //title.append( QString().sprintf( " %02d", c ) ); 126 //title.append( QString().sprintf( " %02d", c ) );
135 assert( parent() ); 127 assert( parent() );
136 ( (QMainWindow*) parent() )->setCaption( title ); 128 ( (QMainWindow*) parent() )->setCaption( title );
137} 129}
138 130
139 131
140void Wellenreiter::handleNotification( OPacket* p ) 132void Wellenreiter::handleNotification( OPacket* p )
141{ 133{
142 QObjectList* l = p->queryList(); 134 QObjectList* l = p->queryList();
143 QObjectListIt it( *l ); 135 QObjectListIt it( *l );
144 QObject* o; 136 QObject* o;
145 137
146 while ( (o = it.current()) != 0 ) 138 while ( (o = it.current()) != 0 )
147 { 139 {
148 QString name = it.current()->name(); 140 QString name = it.current()->name();
149 if ( configwindow->parsePackets->isProtocolChecked( name ) ) 141 if ( configwindow->parsePackets->isProtocolChecked( name ) )
150 { 142 {
151 QString action = configwindow->parsePackets->protocolAction( name ); 143 QString action = configwindow->parsePackets->protocolAction( name );
152 qDebug( "parsePacket-action for '%s' seems to be '%s'", (const char*) name, (const char*) action ); 144 odebug << "parsePacket-action for '" << (const char*) name << "' seems to be '" << (const char*) action << "'" << oendl;
153 doAction( action, name, p ); 145 doAction( action, name, p );
154 } 146 }
155 else 147 else
156 { 148 {
157 qDebug( "protocol '%s' not checked in parsePackets.", (const char*) name ); 149 odebug << "protocol '" << (const char*) name << "' not checked in parsePackets." << oendl;
158 } 150 }
159 ++it; 151 ++it;
160 } 152 }
161} 153}
162 154
163 155
164void Wellenreiter::handleManagementFrame( OPacket* p, OWaveLanManagementPacket* manage ) 156void Wellenreiter::handleManagementFrame( OPacket* p, OWaveLanManagementPacket* manage )
165{ 157{
166 if ( manage->managementType() == "Beacon" ) handleManagementFrameBeacon( p, manage ); 158 if ( manage->managementType() == "Beacon" ) handleManagementFrameBeacon( p, manage );
167 else if ( manage->managementType() == "ProbeRequest" ) handleManagementFrameProbeRequest( p, manage ); 159 else if ( manage->managementType() == "ProbeRequest" ) handleManagementFrameProbeRequest( p, manage );
168 else if ( manage->managementType() == "ProbeResponse" ) handleManagementFrameProbeResponse( p, manage ); 160 else if ( manage->managementType() == "ProbeResponse" ) handleManagementFrameProbeResponse( p, manage );
169 else qWarning( "Wellenreiter::handleManagementFrame(): '%s' - please handle me!", (const char*) manage->managementType() ); 161 else owarn << "Wellenreiter::handleManagementFrame(): '" << (const char*) manage->managementType() << "' - please handle me!" << oendl;
170} 162}
171 163
172 164
173void Wellenreiter::handleManagementFrameProbeRequest( OPacket* p, OWaveLanManagementPacket* request ) 165void Wellenreiter::handleManagementFrameProbeRequest( OPacket* p, OWaveLanManagementPacket* request )
174{ 166{
175 OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) ); 167 OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) );
176 QString essid = ssid ? ssid->ID( true /* decloak */ ) : QString("<unknown>"); 168 QString essid = ssid ? ssid->ID( true /* decloak */ ) : QString("<unknown>");
177 OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) ); 169 OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) );
178 int channel = ds ? ds->channel() : -1; 170 int channel = ds ? ds->channel() : -1;
179 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) ); 171 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
180 172
181 GpsLocation loc( -111, -111 ); 173 GpsLocation loc( -111, -111 );
182 if ( configwindow->enableGPS->isChecked() ) 174 if ( configwindow->enableGPS->isChecked() )
183 { 175 {
184 // TODO: add check if GPS is working!? 176 // TODO: add check if GPS is working!?
185 qDebug( "Wellenreiter::gathering GPS data..." ); 177 odebug << "Wellenreiter::gathering GPS data..." << oendl;
186 loc = gps->position(); 178 loc = gps->position();
187 qDebug( "Wellenreiter::GPS data received is ( %f , %f ) - dms string = '%s'", loc.latitude(), loc.longitude(), loc.dmsPosition().latin1() ); 179 odebug << "Wellenreiter::GPS data received is ( " << loc.latitude() << " , " << loc.longitude() << " ) - dms string = '" << loc.dmsPosition().latin1() << "'" << oendl;
188 } 180 }
189 181
190 if ( essid.length() ) 182 if ( essid.length() )
191 netView()->addNewItem( "adhoc", essid, header->macAddress2(), false /* should check FrameControl field */, -1, 0, loc, true /* only probed */ ); 183 netView()->addNewItem( "adhoc", essid, header->macAddress2(), false /* should check FrameControl field */, -1, 0, loc, true /* only probed */ );
192 qDebug( "Wellenreiter::invalid frame [possibly noise] detected!" ); 184 odebug << "Wellenreiter::invalid frame [possibly noise] detected!" << oendl;
193} 185}
194 186
195 187
196void Wellenreiter::handleManagementFrameProbeResponse( OPacket* p, OWaveLanManagementPacket* response ) 188void Wellenreiter::handleManagementFrameProbeResponse( OPacket* p, OWaveLanManagementPacket* response )
197{ 189{
198} 190}
199 191
200 192
201void Wellenreiter::handleManagementFrameBeacon( OPacket* p, OWaveLanManagementPacket* beacon ) 193void Wellenreiter::handleManagementFrameBeacon( OPacket* p, OWaveLanManagementPacket* beacon )
202{ 194{
203 QString type; 195 QString type;
204 if ( beacon->canIBSS() ) 196 if ( beacon->canIBSS() )
205 { 197 {
206 type = "adhoc"; 198 type = "adhoc";
207 } 199 }
208 else if ( beacon->canESS() ) 200 else if ( beacon->canESS() )
209 { 201 {
210 type = "managed"; 202 type = "managed";
211 } 203 }
212 else 204 else
213 { 205 {
214 qWarning( "Wellenreiter::invalid frame [possibly noise] detected!" ); 206 owarn << "Wellenreiter::invalid frame [possibly noise] detected!" << oendl;
215 return; 207 return;
216 } 208 }
217 209
218 OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) ); 210 OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) );
219 QString essid = ssid ? ssid->ID( true /* decloak */ ) : QString("<unknown>"); 211 QString essid = ssid ? ssid->ID( true /* decloak */ ) : QString("<unknown>");
220 OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) ); 212 OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) );
221 int channel = ds ? ds->channel() : -1; 213 int channel = ds ? ds->channel() : -1;
222 214
223 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) ); 215 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
224 216
225 GpsLocation loc( -111, -111 ); 217 GpsLocation loc( -111, -111 );
226 if ( configwindow->enableGPS->isChecked() ) 218 if ( configwindow->enableGPS->isChecked() )
227 { 219 {
228 // TODO: add check if GPS is working!? 220 // TODO: add check if GPS is working!?
229 qDebug( "Wellenreiter::gathering GPS data..." ); 221 odebug << "Wellenreiter::gathering GPS data..." << oendl;
230 loc = gps->position(); 222 loc = gps->position();
231 qDebug( "Wellenreiter::GPS data received is ( %f , %f ) - dms string = '%s'", loc.latitude(), loc.longitude(), loc.dmsPosition().latin1() ); 223 odebug << "Wellenreiter::GPS data received is ( " << loc.latitude() << " , " << loc.longitude() << " ) - dms string = '" << loc.dmsPosition().latin1() << "'" << oendl;
232 } 224 }
233 225
234 netView()->addNewItem( type, essid, header->macAddress2(), beacon->canPrivacy(), channel, 0, loc ); 226 netView()->addNewItem( type, essid, header->macAddress2(), beacon->canPrivacy(), channel, 0, loc );
235 227
236 // update graph window 228 // update graph window
237 if ( ds ) 229 if ( ds )
238 { 230 {
239 OPrismHeaderPacket* prism = static_cast<OPrismHeaderPacket*>( p->child( "Prism" ) ); 231 OPrismHeaderPacket* prism = static_cast<OPrismHeaderPacket*>( p->child( "Prism" ) );
240 if ( prism ) 232 if ( prism )
241 graphwindow->traffic( ds->channel(), prism->signalStrength() ); 233 graphwindow->traffic( ds->channel(), prism->signalStrength() );
242 else 234 else
243 graphwindow->traffic( ds->channel(), 95 ); 235 graphwindow->traffic( ds->channel(), 95 );
244 } 236 }
245} 237}
246 238
247 239
248void Wellenreiter::handleControlFrame( OPacket* p, OWaveLanControlPacket* control ) 240void Wellenreiter::handleControlFrame( OPacket* p, OWaveLanControlPacket* control )
249{ 241{
250 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) ); 242 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
251 243
252 if ( control->controlType() == "Acknowledge" ) 244 if ( control->controlType() == "Acknowledge" )
253 { 245 {
254 netView()->addNewItem( "adhoc", "<unknown>", header->macAddress1(), false, -1, 0, GpsLocation( -111, -111 ) ); 246 netView()->addNewItem( "adhoc", "<unknown>", header->macAddress1(), false, -1, 0, GpsLocation( -111, -111 ) );
255 } 247 }
256 else 248 else
257 { 249 {
258 qDebug( "Wellenreiter::handleControlFrame - please handle %s in a future version! :D", (const char*) control->controlType() ); 250 odebug << "Wellenreiter::handleControlFrame - please handle " << (const char*) control->controlType() << " in a future version! :D" << oendl;
259 } 251 }
260} 252}
261 253
262 254
263void Wellenreiter::handleWlanData( OPacket* p, OWaveLanDataPacket* data, OMacAddress& from, OMacAddress& to ) 255void Wellenreiter::handleWlanData( OPacket* p, OWaveLanDataPacket* data, OMacAddress& from, OMacAddress& to )
264{ 256{
265 OWaveLanPacket* wlan = (OWaveLanPacket*) p->child( "802.11" ); 257 OWaveLanPacket* wlan = (OWaveLanPacket*) p->child( "802.11" );
266 if ( wlan->fromDS() && !wlan->toDS() ) 258 if ( wlan->fromDS() && !wlan->toDS() )
267 { 259 {
268 netView()->fromDStraffic( wlan->macAddress3(), wlan->macAddress1(), wlan->macAddress2() ); 260 netView()->fromDStraffic( wlan->macAddress3(), wlan->macAddress1(), wlan->macAddress2() );
269 from = wlan->macAddress3(); 261 from = wlan->macAddress3();
270 to = wlan->macAddress2(); 262 to = wlan->macAddress2();
271 } 263 }
272 else if ( !wlan->fromDS() && wlan->toDS() ) 264 else if ( !wlan->fromDS() && wlan->toDS() )
273 { 265 {
274 netView()->toDStraffic( wlan->macAddress2(), wlan->macAddress3(), wlan->macAddress1() ); 266 netView()->toDStraffic( wlan->macAddress2(), wlan->macAddress3(), wlan->macAddress1() );
275 from = wlan->macAddress2(); 267 from = wlan->macAddress2();
276 to = wlan->macAddress3(); 268 to = wlan->macAddress3();
277 } 269 }
278 else if ( wlan->fromDS() && wlan->toDS() ) 270 else if ( wlan->fromDS() && wlan->toDS() )
279 { 271 {
280 netView()->WDStraffic( wlan->macAddress4(), wlan->macAddress3(), wlan->macAddress1(), wlan->macAddress2() ); 272 netView()->WDStraffic( wlan->macAddress4(), wlan->macAddress3(), wlan->macAddress1(), wlan->macAddress2() );
281 from = wlan->macAddress4(); 273 from = wlan->macAddress4();
282 to = wlan->macAddress3(); 274 to = wlan->macAddress3();
283 } 275 }
284 else 276 else
285 { 277 {
286 netView()->IBSStraffic( wlan->macAddress2(), wlan->macAddress1(), wlan->macAddress3() ); 278 netView()->IBSStraffic( wlan->macAddress2(), wlan->macAddress1(), wlan->macAddress3() );
287 from = wlan->macAddress2(); 279 from = wlan->macAddress2();
288 to = wlan->macAddress1(); 280 to = wlan->macAddress1();
289 } 281 }
290} 282}
291 283
292 284
293void Wellenreiter::handleEthernetData( OPacket* p, OEthernetPacket* data, OMacAddress& from, OMacAddress& to ) 285void Wellenreiter::handleEthernetData( OPacket* p, OEthernetPacket* data, OMacAddress& from, OMacAddress& to )
294{ 286{
295 from = data->sourceAddress(); 287 from = data->sourceAddress();
296 to = data->destinationAddress(); 288 to = data->destinationAddress();
297 289
298 netView()->addNewItem( "station", "<wired>", from, false, -1, 0, GpsLocation( -111, -111 ) ); 290 netView()->addNewItem( "station", "<wired>", from, false, -1, 0, GpsLocation( -111, -111 ) );
299} 291}
300 292
301 293
302void Wellenreiter::handleARPData( OPacket* p, OARPPacket*, OMacAddress& source, OMacAddress& dest ) 294void Wellenreiter::handleARPData( OPacket* p, OARPPacket*, OMacAddress& source, OMacAddress& dest )
303{ 295{
304 OARPPacket* arp = (OARPPacket*) p->child( "ARP" ); 296 OARPPacket* arp = (OARPPacket*) p->child( "ARP" );
305 if ( arp ) 297 if ( arp )
306 { 298 {
307 qDebug( "Received ARP traffic (type '%s'): ", (const char*) arp->type() ); 299 odebug << "Received ARP traffic (type '" << (const char*) arp->type() << "'): " << oendl;
308 if ( arp->type() == "REQUEST" ) 300 if ( arp->type() == "REQUEST" )
309 { 301 {
310 netView()->identify( arp->senderMacAddress(), arp->senderIPV4Address().toString() ); 302 netView()->identify( arp->senderMacAddress(), arp->senderIPV4Address().toString() );
311 } 303 }
312 else if ( arp->type() == "REPLY" ) 304 else if ( arp->type() == "REPLY" )
313 { 305 {
314 netView()->identify( arp->senderMacAddress(), arp->senderIPV4Address().toString() ); 306 netView()->identify( arp->senderMacAddress(), arp->senderIPV4Address().toString() );
315 netView()->identify( arp->targetMacAddress(), arp->targetIPV4Address().toString() ); 307 netView()->identify( arp->targetMacAddress(), arp->targetIPV4Address().toString() );
316 } 308 }
317 } 309 }
318} 310}
319 311
320 312
321void Wellenreiter::handleIPData( OPacket* p, OIPPacket* ip, OMacAddress& source, OMacAddress& dest ) 313void Wellenreiter::handleIPData( OPacket* p, OIPPacket* ip, OMacAddress& source, OMacAddress& dest )
322{ 314{
323 //TODO: Implement more IP based protocols 315 //TODO: Implement more IP based protocols
324 316
325 ODHCPPacket* dhcp = (ODHCPPacket*) p->child( "DHCP" ); 317 ODHCPPacket* dhcp = (ODHCPPacket*) p->child( "DHCP" );
326 if ( dhcp ) 318 if ( dhcp )
327 { 319 {
328 qDebug( "Received DHCP '%s' packet", (const char*) dhcp->type() ); 320 odebug << "Received DHCP '" << (const char*) dhcp->type() << "' packet" << oendl;
329 if ( dhcp->type() == "OFFER" ) 321 if ( dhcp->type() == "OFFER" )
330 { 322 {
331 qDebug( "DHCP: '%s' ('%s') seems to be a DHCP server.", (const char*) source.toString(), (const char*) dhcp->serverAddress().toString() ); 323 odebug << "DHCP: '" << (const char*) source.toString() << "' ('" << (const char*) dhcp->serverAddress().toString() << "') seems to be a DHCP server." << oendl;
332 netView()->identify( source, dhcp->serverAddress().toString() ); 324 netView()->identify( source, dhcp->serverAddress().toString() );
333 netView()->addService( "DHCP", source, dhcp->serverAddress().toString() ); 325 netView()->addService( "DHCP", source, dhcp->serverAddress().toString() );
334 } 326 }
335 else if ( dhcp->type() == "ACK" ) 327 else if ( dhcp->type() == "ACK" )
336 { 328 {
337 qDebug( "DHCP: '%s' ('%s') accepted the offered DHCP address.", (const char*) dhcp->clientMacAddress().toString(), (const char*) dhcp->yourAddress().toString() ); 329 odebug << "DHCP: '" << (const char*) dhcp->clientMacAddress().toString() << "' ('" << (const char*) dhcp->yourAddress().toString() << "') accepted the offered DHCP address." << oendl;
338 netView()->identify( dhcp->clientMacAddress(), dhcp->yourAddress().toString() ); 330 netView()->identify( dhcp->clientMacAddress(), dhcp->yourAddress().toString() );
339 } 331 }
340 } 332 }
341} 333}
342 334
343 335
344QObject* Wellenreiter::childIfToParse( OPacket* p, const QString& protocol ) 336QObject* Wellenreiter::childIfToParse( OPacket* p, const QString& protocol )
345{ 337{
346 if ( configwindow->parsePackets->isProtocolChecked( protocol ) ) 338 if ( configwindow->parsePackets->isProtocolChecked( protocol ) )
347 if ( configwindow->parsePackets->protocolAction( protocol ) == "Discard!" ) 339 if ( configwindow->parsePackets->protocolAction( protocol ) == "Discard!" )
348 return 0; 340 return 0;
349 341
350 return p->child( protocol ); 342 return p->child( protocol );
351} 343}
352 344
353 345
354bool Wellenreiter::checkDumpPacket( OPacket* p ) 346bool Wellenreiter::checkDumpPacket( OPacket* p )
355{ 347{
356 // go through all child packets and see if one is inside the child hierarchy for p 348 // go through all child packets and see if one is inside the child hierarchy for p
357 // if so, do what the user requested (protocolAction), e.g. pass or discard 349 // if so, do what the user requested (protocolAction), e.g. pass or discard
358 if ( !configwindow->writeCaptureFile->isChecked() ) 350 if ( !configwindow->writeCaptureFile->isChecked() )
359 return true; // semantic change - we're logging anyway now to /tmp/wellenreiter 351 return true; // semantic change - we're logging anyway now to /tmp/wellenreiter
360 352
361 QObjectList* l = p->queryList(); 353 QObjectList* l = p->queryList();
362 QObjectListIt it( *l ); 354 QObjectListIt it( *l );
363 QObject* o; 355 QObject* o;
364 356
365 while ( (o = it.current()) != 0 ) 357 while ( (o = it.current()) != 0 )
366 { 358 {
367 QString name = it.current()->name(); 359 QString name = it.current()->name();
368 if ( configwindow->capturePackets->isProtocolChecked( name ) ) 360 if ( configwindow->capturePackets->isProtocolChecked( name ) )
369 { 361 {
370 QString action = configwindow->capturePackets->protocolAction( name ); 362 QString action = configwindow->capturePackets->protocolAction( name );
371 qDebug( "capturePackets-action for '%s' seems to be '%s'", (const char*) name, (const char*) action ); 363 odebug << "capturePackets-action for '" << (const char*) name << "' seems to be '" << (const char*) action << "'" << oendl;
372 if ( action == "Discard" ) 364 if ( action == "Discard" )
373 { 365 {
374 logwindow->log( QString().sprintf( "(i) dump-discarding of '%s' packet requested.", (const char*) name ) ); 366 logwindow->log( QString().sprintf( "(i) dump-discarding of '%s' packet requested.", (const char*) name ) );
375 return false; 367 return false;
376 } 368 }
377 } 369 }
378 else 370 else
379 { 371 {
380 qDebug( "protocol '%s' not checked in capturePackets.", (const char*) name ); 372 odebug << "protocol '" << (const char*) name << "' not checked in capturePackets." << oendl;
381 } 373 }
382 ++it; 374 ++it;
383 } 375 }
384 return true; 376 return true;
385} 377}
386 378
387 379
388void Wellenreiter::receivePacket( OPacket* p ) 380void Wellenreiter::receivePacket( OPacket* p )
389{ 381{
390 hexWindow()->add( p ); 382 hexWindow()->add( p );
391 383
392 if ( checkDumpPacket( p ) ) 384 if ( checkDumpPacket( p ) )
393 { 385 {
394 pcap->dump( p ); 386 pcap->dump( p );
395 } 387 }
396 388
397 // check for a management frame 389 // check for a management frame
398 OWaveLanManagementPacket* manage = static_cast<OWaveLanManagementPacket*>( childIfToParse( p, "802.11 Management" ) ); 390 OWaveLanManagementPacket* manage = static_cast<OWaveLanManagementPacket*>( childIfToParse( p, "802.11 Management" ) );
399 if ( manage ) 391 if ( manage )
400 { 392 {
401 handleManagementFrame( p, manage ); 393 handleManagementFrame( p, manage );
402 return; 394 return;
403 } 395 }
404 396
405 // check for a control frame 397 // check for a control frame
406 OWaveLanControlPacket* control = static_cast<OWaveLanControlPacket*>( childIfToParse( p, "802.11 Control" ) ); 398 OWaveLanControlPacket* control = static_cast<OWaveLanControlPacket*>( childIfToParse( p, "802.11 Control" ) );
407 if ( control ) 399 if ( control )
408 { 400 {
409 handleControlFrame( p, control ); 401 handleControlFrame( p, control );
410 return; 402 return;
411 } 403 }
412 404
413 OMacAddress source; 405 OMacAddress source;
414 OMacAddress dest; 406 OMacAddress dest;
415 407
416 //TODO: WEP check here 408 //TODO: WEP check here
417 409
418 // check for a wireless data frame 410 // check for a wireless data frame
419 OWaveLanDataPacket* wlan = static_cast<OWaveLanDataPacket*>( childIfToParse( p, "802.11 Data" ) ); 411 OWaveLanDataPacket* wlan = static_cast<OWaveLanDataPacket*>( childIfToParse( p, "802.11 Data" ) );
420 if ( wlan ) 412 if ( wlan )
421 { 413 {
422 handleWlanData( p, wlan, source, dest ); 414 handleWlanData( p, wlan, source, dest );
423 } 415 }
424 416
425 // check for a wired data frame 417 // check for a wired data frame
426 OEthernetPacket* eth = static_cast<OEthernetPacket*>( childIfToParse( p, "Ethernet" ) ); 418 OEthernetPacket* eth = static_cast<OEthernetPacket*>( childIfToParse( p, "Ethernet" ) );
427 if ( eth ) 419 if ( eth )
428 { 420 {
429 handleEthernetData( p, eth, source, dest ); 421 handleEthernetData( p, eth, source, dest );
430 } 422 }
431 423
432 // check for an arp frame since arp frames come in two flavours: 424 // check for an arp frame since arp frames come in two flavours:
433 // 802.11 encapsulates ARP data within IP packets while wired ethernet doesn't. 425 // 802.11 encapsulates ARP data within IP packets while wired ethernet doesn't.
434 OARPPacket* arp = static_cast<OARPPacket*>( childIfToParse( p, "ARP" ) ); 426 OARPPacket* arp = static_cast<OARPPacket*>( childIfToParse( p, "ARP" ) );
435 if ( arp ) 427 if ( arp )
436 { 428 {
437 handleARPData( p, arp, source, dest ); 429 handleARPData( p, arp, source, dest );
438 } 430 }
439 431
440 // check for a ip frame 432 // check for a ip frame
441 OIPPacket* ip = static_cast<OIPPacket*>( childIfToParse( p, "IP" ) ); 433 OIPPacket* ip = static_cast<OIPPacket*>( childIfToParse( p, "IP" ) );
442 if ( ip ) 434 if ( ip )
443 { 435 {
444 handleIPData( p, ip, source, dest ); 436 handleIPData( p, ip, source, dest );
445 } 437 }
446 438
447 //handleNotification( p ); 439 //handleNotification( p );
448 440
449} 441}
450 442
451 443
452void Wellenreiter::stopClicked() 444void Wellenreiter::stopClicked()
453{ 445{
454 if ( iface ) 446 if ( iface )
455 { 447 {
456 disconnect( SIGNAL( receivedPacket(Opie::Net::OPacket*) ), this, SLOT( receivePacket(Opie::Net::OPacket*) ) ); 448 disconnect( SIGNAL( receivedPacket(Opie::Net::OPacket*) ), this, SLOT( receivePacket(Opie::Net::OPacket*) ) );
457 disconnect( SIGNAL( hopped(int) ), this, SLOT( channelHopped(int) ) ); 449 disconnect( SIGNAL( hopped(int) ), this, SLOT( channelHopped(int) ) );
458 iface->setChannelHopping(); // stop hopping channels 450 iface->setChannelHopping(); // stop hopping channels
459 } 451 }
460 else 452 else
461 killTimers(); 453 killTimers();
462 454
463 pcap->close(); 455 pcap->close();
464 sniffing = false; 456 sniffing = false;
465 457
466 if ( iface ) 458 if ( iface )
467 { 459 {
468 // switch off monitor mode 460 // switch off monitor mode
469 iface->setMode( "managed" ); 461 iface->setMode( "managed" );
470 // switch off promisc flag 462 // switch off promisc flag
471 iface->setPromiscuousMode( false ); 463 iface->setPromiscuousMode( false );
472 464
473 system( "cardctl reset; sleep 1" ); //FIXME: Use OProcess 465 system( "cardctl reset; sleep 1" ); //FIXME: Use OProcess
474 } 466 }
475 467
476 logwindow->log( "(i) Stopped Scanning." ); 468 logwindow->log( "(i) Stopped Scanning." );
477 assert( parent() ); 469 assert( parent() );
478 ( (QMainWindow*) parent() )->setCaption( "Wellenreiter II" ); 470 ( (QMainWindow*) parent() )->setCaption( "Wellenreiter II" );
479 471
480 // message the user 472 // message the user
481 QMessageBox::information( this, "Wellenreiter II", 473 QMessageBox::information( this, "Wellenreiter II",
482 tr( "Your wireless card\nshould now be usable again." ) ); 474 tr( "Your wireless card\nshould now be usable again." ) );
483 475
484 sniffing = false; 476 sniffing = false;
485 emit( stoppedSniffing() ); 477 emit( stoppedSniffing() );
486 478
487 #ifdef QWS 479 #ifdef QWS
488 if ( WellenreiterConfigWindow::instance()->disablePM->isChecked() ) 480 if ( WellenreiterConfigWindow::instance()->disablePM->isChecked() )
489 { 481 {
490 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; 482 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
491 } 483 }
492 #else 484 #else
493 #warning FIXME: setScreenSaverMode is not operational on the X11 build 485 #warning FIXME: setScreenSaverMode is not operational on the X11 build
494 #endif 486 #endif
495 487
496 // print out statistics 488 // print out statistics
497 for( QMap<QString,int>::ConstIterator it = pcap->statistics().begin(); it != pcap->statistics().end(); ++it ) 489 for( QMap<QString,int>::ConstIterator it = pcap->statistics().begin(); it != pcap->statistics().end(); ++it )
498 statwindow->updateCounter( it.key(), it.data() ); 490 statwindow->updateCounter( it.key(), it.data() );
499} 491}
500 492
501 493
502void Wellenreiter::startClicked() 494void Wellenreiter::startClicked()
503{ 495{
504 // get configuration from config window 496 // get configuration from config window
505 497
506 const QString& interface = configwindow->interfaceName->currentText(); 498 const QString& interface = configwindow->interfaceName->currentText();
507 const int cardtype = configwindow->driverType(); 499 const int cardtype = configwindow->driverType();
508 const int interval = configwindow->hoppingInterval(); 500 const int interval = configwindow->hoppingInterval();
509 501
510 if ( ( interface == "" ) || ( cardtype == 0 ) ) 502 if ( ( interface == "" ) || ( cardtype == 0 ) )
511 { 503 {
512 QMessageBox::information( this, "Wellenreiter II", 504 QMessageBox::information( this, "Wellenreiter II",
513 tr( "Your device is not\nproperly configured. Please reconfigure!" ) ); 505 tr( "Your device is not\nproperly configured. Please reconfigure!" ) );
514 return; 506 return;
515 } 507 }
516 508
517 // configure device 509 // configure device
518 ONetwork* net = ONetwork::instance(); 510 ONetwork* net = ONetwork::instance();
519 511
520 // TODO: check if interface is wireless and support sniffing for non-wireless interfaces 512 // TODO: check if interface is wireless and support sniffing for non-wireless interfaces
521 513
522 if ( cardtype != DEVTYPE_FILE ) 514 if ( cardtype != DEVTYPE_FILE )
523 { 515 {
524 516
525 if ( !net->isPresent( interface ) ) 517 if ( !net->isPresent( interface ) )
526 { 518 {
527 QMessageBox::information( this, "Wellenreiter II", 519 QMessageBox::information( this, "Wellenreiter II",
528 tr( "The configured device (%1)\nis not available on this system\n. Please reconfigure!" ).arg( interface ) ); 520 tr( "The configured device (%1)\nis not available on this system\n. Please reconfigure!" ).arg( interface ) );
529 return; 521 return;
530 } 522 }
531 523
532 iface = static_cast<OWirelessNetworkInterface*>(net->interface( interface )); // fails if network is not wireless! 524 iface = static_cast<OWirelessNetworkInterface*>(net->interface( interface )); // fails if network is not wireless!
533 assert( iface ); 525 assert( iface );
534 526
535 // bring device UP 527 // bring device UP
536 iface->setUp( true ); 528 iface->setUp( true );
537 if ( !iface->isUp() ) 529 if ( !iface->isUp() )
538 { 530 {
539 QMessageBox::warning( this, "Wellenreiter II", 531 QMessageBox::warning( this, "Wellenreiter II",
540 tr( "Can't bring interface '%1' up:\n" ).arg( iface->name() ) + strerror( errno ) ); 532 tr( "Can't bring interface '%1' up:\n" ).arg( iface->name() ) + strerror( errno ) );
541 return; 533 return;
542 } 534 }
543 } 535 }
544 // set monitor mode 536 // set monitor mode
545 bool usePrism = configwindow->usePrismHeader(); 537 bool usePrism = configwindow->usePrismHeader();
546 538
547 switch ( cardtype ) 539 switch ( cardtype )
548 { 540 {
549 case DEVTYPE_CISCO: iface->setMonitoring( new OCiscoMonitoringInterface( iface, usePrism ) ); break; 541 case DEVTYPE_CISCO: iface->setMonitoring( new OCiscoMonitoringInterface( iface, usePrism ) ); break;
550 case DEVTYPE_WLAN_NG: iface->setMonitoring( new OWlanNGMonitoringInterface( iface, usePrism ) ); break; 542 case DEVTYPE_WLAN_NG: iface->setMonitoring( new OWlanNGMonitoringInterface( iface, usePrism ) ); break;
551 case DEVTYPE_HOSTAP: iface->setMonitoring( new OHostAPMonitoringInterface( iface, usePrism ) ); break; 543 case DEVTYPE_HOSTAP: iface->setMonitoring( new OHostAPMonitoringInterface( iface, usePrism ) ); break;
552 case DEVTYPE_ORINOCO: iface->setMonitoring( new OOrinocoMonitoringInterface( iface, usePrism ) ); break; 544 case DEVTYPE_ORINOCO: iface->setMonitoring( new OOrinocoMonitoringInterface( iface, usePrism ) ); break;
553 case DEVTYPE_MANUAL: QMessageBox::information( this, "Wellenreiter II", tr( "Bring your device into\nmonitor mode now." ) ); break; 545 case DEVTYPE_MANUAL: QMessageBox::information( this, "Wellenreiter II", tr( "Bring your device into\nmonitor mode now." ) ); break;
554 case DEVTYPE_FILE: qDebug( "Wellenreiter: Capturing from file '%s'", (const char*) interface ); break; 546 case DEVTYPE_FILE: odebug << "Wellenreiter: Capturing from file '" << (const char*) interface << "'" << oendl; break;
555 default: assert( 0 ); // shouldn't reach this 547 default: assert( 0 ); // shouldn't reach this
556 } 548 }
557 549
558 // switch device into monitor mode 550 // switch device into monitor mode
559 if ( cardtype < DEVTYPE_FILE ) 551 if ( cardtype < DEVTYPE_FILE )
560 { 552 {
561 if ( cardtype != DEVTYPE_MANUAL ) 553 if ( cardtype != DEVTYPE_MANUAL )
562 iface->setMode( "monitor" ); 554 iface->setMode( "monitor" );
563 if ( iface->mode() != "monitor" ) 555 if ( iface->mode() != "monitor" )
564 { 556 {
565 if ( QMessageBox::warning( this, "Wellenreiter II", 557 if ( QMessageBox::warning( this, "Wellenreiter II",
566 tr( "Can't set interface '%1'\ninto monitor mode:\n" ).arg( iface->name() ) + strerror( errno ) + 558 tr( "Can't set interface '%1'\ninto monitor mode:\n" ).arg( iface->name() ) + strerror( errno ) +
567 tr( "\nContinue with limited functionality?" ), QMessageBox::Yes, QMessageBox::No ) == QMessageBox::No ) 559 tr( "\nContinue with limited functionality?" ), QMessageBox::Yes, QMessageBox::No ) == QMessageBox::No )
568 return; 560 return;
569 } 561 }
570 } 562 }
571 563
572 // open GPS device 564 // open GPS device
573 if ( configwindow->enableGPS->isChecked() ) 565 if ( configwindow->enableGPS->isChecked() )
574 { 566 {
575 qDebug( "Wellenreiter:GPS enabled @ %s:%d", (const char*) configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() ); 567 odebug << "Wellenreiter:GPS enabled @ " << (const char*) configwindow->gpsdHost->currentText() << ":" << configwindow->gpsdPort->value() << "" << oendl;
576 gps->open( configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() ); 568 gps->open( configwindow->gpsdHost->currentText(), configwindow->gpsdPort->value() );
577 } 569 }
578 570
579 // open pcap and start sniffing 571 // open pcap and start sniffing
580 572
581 if ( configwindow->writeCaptureFile->isChecked() ) // write to a user specified capture file? 573 if ( configwindow->writeCaptureFile->isChecked() ) // write to a user specified capture file?
582 { 574 {
583 dumpname = configwindow->captureFileName->text(); 575 dumpname = configwindow->captureFileName->text();
584 if ( dumpname.isEmpty() ) dumpname = "captureFile"; 576 if ( dumpname.isEmpty() ) dumpname = "captureFile";
585 dumpname.append( '-' ); 577 dumpname.append( '-' );
586 dumpname.append( QTime::currentTime().toString().replace( QRegExp( ":" ), "-" ) ); 578 dumpname.append( QTime::currentTime().toString().replace( QRegExp( ":" ), "-" ) );
587 dumpname.append( ".wellenreiter" ); 579 dumpname.append( ".wellenreiter" );
588 } 580 }
589 else // write it anyway ;) 581 else // write it anyway ;)
590 { 582 {
591 dumpname = "/var/log/dump.wellenreiter"; 583 dumpname = "/var/log/dump.wellenreiter";
592 } 584 }
593 585
594 if ( cardtype != DEVTYPE_FILE ) 586 if ( cardtype != DEVTYPE_FILE )
595 pcap->open( interface ); 587 pcap->open( interface );
596 else 588 else
597 pcap->open( QFile( interface ) ); 589 pcap->open( QFile( interface ) );
598 590
599 qDebug( "Wellenreiter:: dumping to %s", (const char*) dumpname ); 591 odebug << "Wellenreiter:: dumping to " << (const char*) dumpname << "" << oendl;
600 pcap->openDumpFile( dumpname ); 592 pcap->openDumpFile( dumpname );
601 593
602 if ( !pcap->isOpen() ) 594 if ( !pcap->isOpen() )
603 { 595 {
604 QMessageBox::warning( this, "Wellenreiter II", tr( "Can't open packet capturer for\n'%1':\n" ).arg( 596 QMessageBox::warning( this, "Wellenreiter II", tr( "Can't open packet capturer for\n'%1':\n" ).arg(
605 cardtype == DEVTYPE_FILE ? (const char*) interface : iface->name() ) + QString(strerror( errno ) )); 597 cardtype == DEVTYPE_FILE ? (const char*) interface : iface->name() ) + QString(strerror( errno ) ));
606 return; 598 return;
607 } 599 }
608 600
609 // set capturer to non-blocking mode 601 // set capturer to non-blocking mode
610 pcap->setBlocking( false ); 602 pcap->setBlocking( false );
611 603
612 // start channel hopper 604 // start channel hopper
613 if ( cardtype != DEVTYPE_FILE ) 605 if ( cardtype != DEVTYPE_FILE )
614 { 606 {
615 logwindow->log( QString().sprintf( "(i) Starting channel hopper (d=%d ms)", configwindow->hopInterval->value() ) ); 607 logwindow->log( QString().sprintf( "(i) Starting channel hopper (d=%d ms)", configwindow->hopInterval->value() ) );
616 iface->setChannelHopping( configwindow->hopInterval->value() ); //use interval from config window 608 iface->setChannelHopping( configwindow->hopInterval->value() ); //use interval from config window
617 } 609 }
618 610
619 if ( cardtype != DEVTYPE_FILE ) 611 if ( cardtype != DEVTYPE_FILE )
620 { 612 {
621 // connect socket notifier and start channel hopper 613 // connect socket notifier and start channel hopper
622 connect( pcap, SIGNAL( receivedPacket(Opie::Net::OPacket*) ), this, SLOT( receivePacket(Opie::Net::OPacket*) ) ); 614 connect( pcap, SIGNAL( receivedPacket(Opie::Net::OPacket*) ), this, SLOT( receivePacket(Opie::Net::OPacket*) ) );
623 connect( iface->channelHopper(), SIGNAL( hopped(int) ), this, SLOT( channelHopped(int) ) ); 615 connect( iface->channelHopper(), SIGNAL( hopped(int) ), this, SLOT( channelHopped(int) ) );
624 } 616 }
625 else 617 else
626 { 618 {
627 // start timer for reading packets 619 // start timer for reading packets
628 startTimer( 100 ); 620 startTimer( 100 );
629 } 621 }
630 622
631 logwindow->log( "(i) Started Scanning." ); 623 logwindow->log( "(i) Started Scanning." );
632 sniffing = true; 624 sniffing = true;
633 625
634 #ifdef QWS 626 #ifdef QWS
635 if ( WellenreiterConfigWindow::instance()->disablePM->isChecked() ) 627 if ( WellenreiterConfigWindow::instance()->disablePM->isChecked() )
636 { 628 {
637 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Disable; 629 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Disable;
638 } 630 }
639 #else 631 #else
640 #warning FIXME: setScreenSaverMode is not operational on the X11 build 632 #warning FIXME: setScreenSaverMode is not operational on the X11 build
641 #endif 633 #endif
642 634
643 emit( startedSniffing() ); 635 emit( startedSniffing() );
644 if ( cardtype != DEVTYPE_FILE ) channelHopped( 6 ); // set title 636 if ( cardtype != DEVTYPE_FILE ) channelHopped( 6 ); // set title
645 else 637 else
646 { 638 {
647 assert( parent() ); 639 assert( parent() );
648 ( (QMainWindow*) parent() )->setCaption( tr( "Wellenreiter II - replaying capture file..." ) ); 640 ( (QMainWindow*) parent() )->setCaption( tr( "Wellenreiter II - replaying capture file..." ) );
649 } 641 }
650} 642}
651 643
652 644
653void Wellenreiter::timerEvent( QTimerEvent* ) 645void Wellenreiter::timerEvent( QTimerEvent* )
654{ 646{
655 qDebug( "Wellenreiter::timerEvent()" ); 647 odebug << "Wellenreiter::timerEvent()" << oendl;
656 OPacket* p = pcap->next(); 648 OPacket* p = pcap->next();
657 if ( !p ) // no more packets available 649 if ( !p ) // no more packets available
658 { 650 {
659 stopClicked(); 651 stopClicked();
660 } 652 }
661 else 653 else
662 { 654 {
663 receivePacket( p ); 655 receivePacket( p );
664 // We no longer delete packets here. Ownership of the packets is 656 // We no longer delete packets here. Ownership of the packets is
665 // transferred to the PacketView. 657 // transferred to the PacketView.
666 //delete p; 658 //delete p;
667 } 659 }
668} 660}
669 661
670 662
671void Wellenreiter::doAction( const QString& action, const QString& protocol, OPacket* p ) 663void Wellenreiter::doAction( const QString& action, const QString& protocol, OPacket* p )
672{ 664{
673 #ifdef QWS 665 #ifdef QWS
674 if ( action == "TouchSound" ) 666 if ( action == "TouchSound" )
675 ODevice::inst()->playTouchSound(); 667 ODevice::inst()->playTouchSound();
676 else if ( action == "AlarmSound" ) 668 else if ( action == "AlarmSound" )
677 ODevice::inst()->playAlarmSound(); 669 ODevice::inst()->playAlarmSound();
678 else if ( action == "KeySound" ) 670 else if ( action == "KeySound" )
679 ODevice::inst()->playKeySound(); 671 ODevice::inst()->playKeySound();
680 else if ( action == "LedOn" ) 672 else if ( action == "LedOn" )
681 ODevice::inst()->setLedState( Led_Mail, Led_On ); 673 ODevice::inst()->setLedState( Led_Mail, Led_On );
682 else if ( action == "LedOff" ) 674 else if ( action == "LedOff" )
683 ODevice::inst()->setLedState( Led_Mail, Led_Off ); 675 ODevice::inst()->setLedState( Led_Mail, Led_Off );
684 else if ( action == "LogMessage" ) 676 else if ( action == "LogMessage" )
685 logwindow->log( QString().sprintf( "Got packet with protocol '%s'", (const char*) protocol ) ); 677 logwindow->log( QString().sprintf( "Got packet with protocol '%s'", (const char*) protocol ) );
686 else if ( action == "MessageBox" ) 678 else if ( action == "MessageBox" )
687 QMessageBox::information( this, "Notification!", 679 QMessageBox::information( this, "Notification!",
688 QString().sprintf( "Got packet with protocol '%s'", (const char*) protocol ) ); 680 QString().sprintf( "Got packet with protocol '%s'", (const char*) protocol ) );
689 #else 681 #else
690 #warning Actions do not work with Qt/X11 yet 682 #warning Actions do not work with Qt/X11 yet
691 #endif 683 #endif
692} 684}
693 685
694void Wellenreiter::joinNetwork(const QString& type, const QString& essid, int channel, const QString& macaddr) 686void Wellenreiter::joinNetwork(const QString& type, const QString& essid, int channel, const QString& macaddr)
695{ 687{
696 #ifdef QWS 688 #ifdef QWS
697 if ( !iface ) 689 if ( !iface )
698 { 690 {
699 QMessageBox::warning( this, tr( "Can't do that!" ), tr( "No wireless\ninterface available." ) ); 691 QMessageBox::warning( this, tr( "Can't do that!" ), tr( "No wireless\ninterface available." ) );
700 return; 692 return;
701 } 693 }
702 694
703 if ( sniffing ) 695 if ( sniffing )
704 { 696 {
705 QMessageBox::warning( this, tr( "Can't do that!" ), tr( "Stop sniffing before\njoining a net." ) ); 697 QMessageBox::warning( this, tr( "Can't do that!" ), tr( "Stop sniffing before\njoining a net." ) );
706 return; 698 return;
707 } 699 }
708 700
709 qDebug( "joinNetwork() with Interface %s: %s, %s, %d, %s", 701 qDebug( "joinNetwork() with Interface %s: %s, %s, %d, %s",
710 (const char*) iface->name(), 702 (const char*) iface->name(),
711 (const char*) type, 703 (const char*) type,
712 (const char*) essid, 704 (const char*) essid,
713 channel, 705 channel,
714 (const char*) macaddr ); 706 (const char*) macaddr );
715 707
716 QCopEnvelope msg( "QPE/Application/networksettings", "wlan(QString,QString,QString)" ); 708 QCopEnvelope msg( "QPE/Application/networksettings", "wlan(QString,QString,QString)" );
717 int count = 3; 709 int count = 3;
718 qDebug("sending %d messages",count); 710 odebug << "sending " << count << " messages" << oendl;
719 msg << QString("count") << QString::number(count); 711 msg << QString("count") << QString::number(count);
720 qDebug("msg >%s< Mode >%s<", iface->name(),type.latin1() ); 712 odebug << "msg >" << iface->name() << "< Mode >" << type.latin1() << "<" << oendl;
721 msg << QString(iface->name()) << QString("Mode") << type; 713 msg << QString(iface->name()) << QString("Mode") << type;
722 qDebug("msg >%s< essid >%s<", iface->name(),essid.latin1()); 714 odebug << "msg >" << iface->name() << "< essid >" << essid.latin1() << "<" << oendl;
723 msg << QString(iface->name()) << QString("ESSID") << essid; 715 msg << QString(iface->name()) << QString("ESSID") << essid;
724 qDebug("msg >%s< channel >%d<", iface->name(),channel); 716 odebug << "msg >" << iface->name() << "< channel >" << channel << "<" << oendl;
725 msg << QString(iface->name()) << QString("Channel") << channel; 717 msg << QString(iface->name()) << QString("Channel") << channel;
726// qDebug("msg >%s< mac >%s<", iface->name(),macaddr); 718// odebug << "msg >" << iface->name() << "< mac >" << macaddr << "<" << oendl;
727// msg << QString(iface->name()) << QString("MacAddr") << macaddr; 719// msg << QString(iface->name()) << QString("MacAddr") << macaddr;
728 #else 720 #else
729 QMessageBox::warning( this, tr( "Can't do that!" ), tr( "Function only available on Embedded build" ) ); 721 QMessageBox::warning( this, tr( "Can't do that!" ), tr( "Function only available on Embedded build" ) );
730 #endif 722 #endif
731 723
732} 724}
733 725
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 @@
1
2#include "backuprestore.h" 1#include "backuprestore.h"
3#include "errordialog.h" 2#include "errordialog.h"
4 3
5/* OPIE */ 4/* OPIE */
5#include <opie2/odebug.h>
6#include <opie2/ostorageinfo.h> 6#include <opie2/ostorageinfo.h>
7#include <qpe/qpeapplication.h> 7#include <qpe/qpeapplication.h>
8using namespace Opie::Core;
8 9
9/* QT */ 10/* QT */
10#include <qapplication.h> 11#include <qapplication.h>
11#include <qmultilineedit.h> 12#include <qmultilineedit.h>
12#include <qdir.h> 13#include <qdir.h>
13#include <qfile.h> 14#include <qfile.h>
14#include <qfileinfo.h> 15#include <qfileinfo.h>
15#include <qlistview.h> 16#include <qlistview.h>
16#include <qpushbutton.h> 17#include <qpushbutton.h>
17#include <qheader.h> 18#include <qheader.h>
18#include <qpe/resource.h> 19#include <qpe/resource.h>
19#include <qpe/config.h> 20#include <qpe/config.h>
20#include <qmessagebox.h> 21#include <qmessagebox.h>
21#include <qcombobox.h> 22#include <qcombobox.h>
22#include <qlist.h> 23#include <qlist.h>
23#include <stdlib.h> 24#include <stdlib.h>
24#include <qregexp.h> 25#include <qregexp.h>
25#include <qtextstream.h> 26#include <qtextstream.h>
26#include <qtextview.h> 27#include <qtextview.h>
27 28
28/* STD */ 29/* STD */
29#include <errno.h> 30#include <errno.h>
30#include <stdlib.h> 31#include <stdlib.h>
31#include <unistd.h> 32#include <unistd.h>
32#include <sys/stat.h> 33#include <sys/stat.h>
33#include <dirent.h> 34#include <dirent.h>
34 35
35#define HEADER_NAME 0 36#define HEADER_NAME 0
36#define HEADER_BACKUP 1 37#define HEADER_BACKUP 1
37#define BACKUP_LOCATION 2 38#define BACKUP_LOCATION 2
38 39
39#define EXTENSION ".bck" 40#define EXTENSION ".bck"
40 41
41const QString tempFileName = "/tmp/backup.err"; 42const QString tempFileName = "/tmp/backup.err";
42 43
43
44BackupAndRestore::BackupAndRestore( QWidget* parent, const char* name, WFlags fl) 44BackupAndRestore::BackupAndRestore( QWidget* parent, const char* name, WFlags fl)
45 : BackupAndRestoreBase(parent, name, fl) 45 : BackupAndRestoreBase(parent, name, fl)
46{ 46{
47 backupList->header()->hide(); 47 backupList->header()->hide();
48 restoreList->header()->hide(); 48 restoreList->header()->hide();
49 connect(backupButton, SIGNAL(clicked()), 49 connect(backupButton, SIGNAL(clicked()),
50 this, SLOT(backup())); 50 this, SLOT(backup()));
51 connect(restoreButton, SIGNAL(clicked()), 51 connect(restoreButton, SIGNAL(clicked()),
52 this, SLOT(restore())); 52 this, SLOT(restore()));
53 connect(backupList, SIGNAL(clicked(QListViewItem*)), 53 connect(backupList, SIGNAL(clicked(QListViewItem*)),
54 this, SLOT(selectItem(QListViewItem*))); 54 this, SLOT(selectItem(QListViewItem*)));
55 connect(restoreSource, SIGNAL(activated(int)), 55 connect(restoreSource, SIGNAL(activated(int)),
56 this, SLOT(sourceDirChanged(int))); 56 this, SLOT(sourceDirChanged(int)));
57 connect(updateList, SIGNAL(clicked()), 57 connect(updateList, SIGNAL(clicked()),
58 this, SLOT( fileListUpdate())); 58 this, SLOT( fileListUpdate()));
59 59
60 //add directorys for backing up 60 //add directorys for backing up
61 applicationSettings = new QListViewItem(backupList, "Application Settings", "", "Settings/"); 61 applicationSettings = new QListViewItem(backupList, "Application Settings", "", "Settings/");
62 selectItem(applicationSettings); 62 selectItem(applicationSettings);
63 applicationSettings = new QListViewItem(backupList, "Application Data", "", "Applications/"); 63 applicationSettings = new QListViewItem(backupList, "Application Data", "", "Applications/");
64 selectItem(applicationSettings); 64 selectItem(applicationSettings);
65 documents= new QListViewItem(backupList, "Documents", "", "Documents/"); 65 documents= new QListViewItem(backupList, "Documents", "", "Documents/");
66 selectItem(documents); 66 selectItem(documents);
67 67
68 scanForApplicationSettings(); 68 scanForApplicationSettings();
69 69
70 Opie::Core::OStorageInfo storage; 70 Opie::Core::OStorageInfo storage;
71 71
72 backupLocations.insert( "Documents", QDir::homeDirPath() + "/Documents" ); 72 backupLocations.insert( "Documents", QDir::homeDirPath() + "/Documents" );
73 if ( storage.hasCf() ) 73 if ( storage.hasCf() )
74 { 74 {
75 backupLocations.insert( "CF", storage.cfPath() ); 75 backupLocations.insert( "CF", storage.cfPath() );
76 qDebug( "Cf Path: " + storage.cfPath() ); 76 odebug << "Cf Path: " + storage.cfPath() << oendl;
77 } 77 }
78 if ( storage.hasSd() ) 78 if ( storage.hasSd() )
79 { 79 {
80 backupLocations.insert( "SD", storage.sdPath() ); 80 backupLocations.insert( "SD", storage.sdPath() );
81 qDebug( " Sd Path: " + storage.sdPath() ); 81 odebug << " Sd Path: " + storage.sdPath() << oendl;
82 } 82 }
83 if ( storage.hasMmc() ) 83 if ( storage.hasMmc() )
84 { 84 {
85 backupLocations.insert( "MMC", storage.mmcPath() ); 85 backupLocations.insert( "MMC", storage.mmcPath() );
86 qDebug( "Mmc Path: " + storage.mmcPath() ); 86 odebug << "Mmc Path: " + storage.mmcPath() << oendl;
87 } 87 }
88 88
89 Config config("BackupAndRestore"); 89 Config config("BackupAndRestore");
90 //read last locations 90 //read last locations
91 config.setGroup("LastLocation"); 91 config.setGroup("LastLocation");
92 QString lastStoreLocation = config.readEntry( "LastStoreLocation", "" ); 92 QString lastStoreLocation = config.readEntry( "LastStoreLocation", "" );
93 QString lastRestoreLocation = config.readEntry( "LastRestoreLocation", "" ); 93 QString lastRestoreLocation = config.readEntry( "LastRestoreLocation", "" );
94 int locationIndex = 0; 94 int locationIndex = 0;
95 95
96 QMap<QString, QString>::Iterator it; 96 QMap<QString, QString>::Iterator it;
97 for( it = backupLocations.begin(); it != backupLocations.end(); ++it ) 97 for( it = backupLocations.begin(); it != backupLocations.end(); ++it )
98 { 98 {
99 storeToLocation->insertItem(it.key()); 99 storeToLocation->insertItem(it.key());
100 restoreSource->insertItem(it.key()); 100 restoreSource->insertItem(it.key());
101 101
102 //check for last locations 102 //check for last locations
103 if ( it.key() == lastStoreLocation ) 103 if ( it.key() == lastStoreLocation )
104 storeToLocation->setCurrentItem( locationIndex ); 104 storeToLocation->setCurrentItem( locationIndex );
105 if ( it.key() == lastRestoreLocation ) 105 if ( it.key() == lastRestoreLocation )
106 restoreSource->setCurrentItem( locationIndex ); 106 restoreSource->setCurrentItem( locationIndex );
107 locationIndex++; 107 locationIndex++;
108 } 108 }
109 109
110 // Read the list of items to ignore. 110 // Read the list of items to ignore.
111 QList<QString> dontBackupList; 111 QList<QString> dontBackupList;
112 dontBackupList.setAutoDelete(true); 112 dontBackupList.setAutoDelete(true);
113 config.setGroup("DontBackup"); 113 config.setGroup("DontBackup");
114 int total = config.readNumEntry("Total", 0); 114 int total = config.readNumEntry("Total", 0);
115 for(int i = 0; i < total; i++) 115 for(int i = 0; i < total; i++)
116 { 116 {
117 dontBackupList.append(new QString(config.readEntry(QString("%1").arg(i), ""))); 117 dontBackupList.append(new QString(config.readEntry(QString("%1").arg(i), "")));
118 } 118 }
119 119
120 QList<QListViewItem> list; 120 QList<QListViewItem> list;
121 getAllItems(backupList->firstChild(), list); 121 getAllItems(backupList->firstChild(), list);
122 122
123 for(uint i = 0; i < list.count(); i++) 123 for(uint i = 0; i < list.count(); i++)
124 { 124 {
125 QString text = list.at(i)->text(HEADER_NAME); 125 QString text = list.at(i)->text(HEADER_NAME);
126 for(uint i2 = 0; i2 < dontBackupList.count(); i2++) 126 for(uint i2 = 0; i2 < dontBackupList.count(); i2++)
127 { 127 {
128 if(*dontBackupList.at(i2) == text) 128 if(*dontBackupList.at(i2) == text)
129 { 129 {
130 selectItem(list.at(i)); 130 selectItem(list.at(i));
131 break; 131 break;
132 } 132 }
133 } 133 }
134 } 134 }
135 QPEApplication::showWidget( this ); 135 QPEApplication::showWidget( this );
136} 136}
137 137
138BackupAndRestore::~BackupAndRestore() 138BackupAndRestore::~BackupAndRestore()
139{ 139{
140 QList<QListViewItem> list; 140 QList<QListViewItem> list;
141 getAllItems(backupList->firstChild(), list); 141 getAllItems(backupList->firstChild(), list);
142 142
143 Config config("BackupAndRestore"); 143 Config config("BackupAndRestore");
144 config.setGroup("DontBackup"); 144 config.setGroup("DontBackup");
145 config.clearGroup(); 145 config.clearGroup();
146 146
147 int count = 0; 147 int count = 0;
148 for(uint i = 0; i < list.count(); i++) 148 for(uint i = 0; i < list.count(); i++)
149 { 149 {
150 if(list.at(i)->text(HEADER_BACKUP) == "") 150 if(list.at(i)->text(HEADER_BACKUP) == "")
151 { 151 {
152 config.writeEntry(QString("%1").arg(count), list.at(i)->text(HEADER_NAME)); 152 config.writeEntry(QString("%1").arg(count), list.at(i)->text(HEADER_NAME));
153 count++; 153 count++;
154 } 154 }
155 } 155 }
156 config.writeEntry("Total", count); 156 config.writeEntry("Total", count);
157 157
158 // Remove Temp File 158 // Remove Temp File
159 if ( QFile::exists( tempFileName ) ) 159 if ( QFile::exists( tempFileName ) )
160 QFile::remove( tempFileName ); 160 QFile::remove( tempFileName );
161} 161}
162 162
163QList<QListViewItem> BackupAndRestore::getAllItems(QListViewItem *item, QList<QListViewItem> &list) 163QList<QListViewItem> BackupAndRestore::getAllItems(QListViewItem *item, QList<QListViewItem> &list)
164{ 164{
165 while(item) 165 while(item)
166 { 166 {
167 if(item->childCount() > 0) 167 if(item->childCount() > 0)
168 getAllItems(item->firstChild(), list); 168 getAllItems(item->firstChild(), list);
169 list.append(item); 169 list.append(item);
170 item = item->nextSibling(); 170 item = item->nextSibling();
171 } 171 }
172 return list; 172 return list;
173} 173}
174 174
175/** 175/**
176 * Selects and unselects the item by setting the HEADER_BACKUP to B or !. 176 * Selects and unselects the item by setting the HEADER_BACKUP to B or !.
177 * and changing the icon to match 177 * and changing the icon to match
178 * @param currentItem the item to swich the selection choice. 178 * @param currentItem the item to swich the selection choice.
179 */ 179 */
180void BackupAndRestore::selectItem(QListViewItem *currentItem) 180void BackupAndRestore::selectItem(QListViewItem *currentItem)
181{ 181{
182 if(!currentItem) 182 if(!currentItem)
183 return; 183 return;
184 184
185 if(currentItem->text(HEADER_BACKUP) == "B") 185 if(currentItem->text(HEADER_BACKUP) == "B")
186 { 186 {
187 currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/null")); 187 currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/null"));
188 currentItem->setText(HEADER_BACKUP, ""); 188 currentItem->setText(HEADER_BACKUP, "");
189 } 189 }
190 else 190 else
191 { 191 {
192 currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/check")); 192 currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/check"));
193 currentItem->setText(HEADER_BACKUP, "B"); 193 currentItem->setText(HEADER_BACKUP, "B");
194 } 194 }
195} 195}
196 196
197void BackupAndRestore::scanForApplicationSettings() 197void BackupAndRestore::scanForApplicationSettings()
198{ 198{
199 QDir d( QDir::homeDirPath() + "/" + QString( applicationSettings->text(BACKUP_LOCATION) ) ); 199 QDir d( QDir::homeDirPath() + "/" + QString( applicationSettings->text(BACKUP_LOCATION) ) );
200 d.setFilter( QDir::Dirs | QDir::Files | QDir::NoSymLinks ); 200 d.setFilter( QDir::Dirs | QDir::Files | QDir::NoSymLinks );
201 const QFileInfoList *list = d.entryInfoList(); 201 const QFileInfoList *list = d.entryInfoList();
202 QFileInfoListIterator it( *list ); 202 QFileInfoListIterator it( *list );
203 QFileInfo *fi; 203 QFileInfo *fi;
204 while ( (fi=it.current()) ) 204 while ( (fi=it.current()) )
205 { 205 {
206 //qDebug((d.path()+"/"+fi->fileName()).latin1()); 206 //odebug << (d.path()+"/"+fi->fileName()).latin1() << oendl;
207 if ( ( fi->fileName() != "." ) && ( fi->fileName() != ".." ) ) 207 if ( ( fi->fileName() != "." ) && ( fi->fileName() != ".." ) )
208 { 208 {
209 QListViewItem *newItem = new QListViewItem(applicationSettings, fi->fileName()); 209 QListViewItem *newItem = new QListViewItem(applicationSettings, fi->fileName());
210 selectItem(newItem); 210 selectItem(newItem);
211 } 211 }
212 ++it; 212 ++it;
213 } 213 }
214} 214}
215 215
216/** 216/**
217 * The "Backup" button has been pressed. Get a list of all of the files that 217 * The "Backup" button has been pressed. Get a list of all of the files that
218 * should be backed up. If there are no files, emit and error and exit. 218 * should be backed up. If there are no files, emit and error and exit.
219 * Determine the file name to store the backup in. Backup the file(s) using 219 * Determine the file name to store the backup in. Backup the file(s) using
220 * tar and gzip --best. Report failure or success 220 * tar and gzip --best. Report failure or success
221 */ 221 */
222void BackupAndRestore::backup() 222void BackupAndRestore::backup()
223{ 223{
224 QString backupFiles; 224 QString backupFiles;
225 if(getBackupFiles(backupFiles, NULL) == 0) 225 if(getBackupFiles(backupFiles, NULL) == 0)
226 { 226 {
227 QMessageBox::critical(this, "Message", 227 QMessageBox::critical(this, "Message",
228 "No items selected.",QString("Ok") ); 228 "No items selected.",QString("Ok") );
229 return; 229 return;
230 } 230 }
231 231
232 setCaption(tr("Backup and Restore... working...")); 232 setCaption(tr("Backup and Restore... working..."));
233 QString outputFile = backupLocations[storeToLocation->currentText()]; 233 QString outputFile = backupLocations[storeToLocation->currentText()];
234 234
235 QDateTime datetime = QDateTime::currentDateTime(); 235 QDateTime datetime = QDateTime::currentDateTime();
236 QString dateString = QString::number( datetime.date().year() ) + QString::number( datetime.date().month() ).rightJustify(2, '0') + 236 QString dateString = QString::number( datetime.date().year() ) + QString::number( datetime.date().month() ).rightJustify(2, '0') +
237 QString::number( datetime.date().day() ).rightJustify(2, '0'); 237 QString::number( datetime.date().day() ).rightJustify(2, '0');
238 238
239 outputFile += "/" + dateString; 239 outputFile += "/" + dateString;
240 240
241 QString t = outputFile; 241 QString t = outputFile;
242 int c = 1; 242 int c = 1;
243 while(QFile::exists(outputFile + EXTENSION)) 243 while(QFile::exists(outputFile + EXTENSION))
244 { 244 {
245 outputFile = t + QString("%1").arg(c); 245 outputFile = t + QString("%1").arg(c);
246 c++; 246 c++;
247 } 247 }
248 248
249 // We execute tar and compressing its output with gzip.. 249 // We execute tar and compressing its output with gzip..
250 // The error output will be written into a temp-file which could be provided 250 // The error output will be written into a temp-file which could be provided
251 // for debugging.. 251 // for debugging..
252 qDebug( "Storing file: %s", outputFile.latin1() ); 252 odebug << "Storing file: " << outputFile.latin1() << "" << oendl;
253 outputFile += EXTENSION; 253 outputFile += EXTENSION;
254 254
255 QString commandLine = QString( "cd %1 && (tar -X %1 -cz %2 Applications/backup/exclude -f %3 ) 2> %4" ).arg( QDir::homeDirPath() ) 255 QString commandLine = QString( "cd %1 && (tar -X %1 -cz %2 Applications/backup/exclude -f %3 ) 2> %4" ).arg( QDir::homeDirPath() )
256 .arg( getExcludeFile() ) 256 .arg( getExcludeFile() )
257 .arg( backupFiles ) 257 .arg( backupFiles )
258 .arg( outputFile.latin1() ) 258 .arg( outputFile.latin1() )
259 .arg( tempFileName.latin1() ); 259 .arg( tempFileName.latin1() );
260 260
261 qDebug( commandLine ); 261 odebug << commandLine << oendl;
262 262
263 int r = system( commandLine ); 263 int r = system( commandLine );
264 264
265 if(r != 0) 265 if(r != 0)
266 { 266 {
267 perror("Error: "); 267 perror("Error: ");
268 QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno ); 268 QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno );
269 269
270 switch( QMessageBox::critical(this, tr( "Message" ), tr( "Backup Failed!" ) + "\n" 270 switch( QMessageBox::critical(this, tr( "Message" ), tr( "Backup Failed!" ) + "\n"
271 + errorMsg, QString( tr( "Ok" ) ), QString( tr( "Details" ) ) ) ) 271 + errorMsg, QString( tr( "Ok" ) ), QString( tr( "Details" ) ) ) )
272 { 272 {
273 273
274 case 1: 274 case 1:
275 qWarning("Details pressed !"); 275 owarn << "Details pressed !" << oendl;
276 ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true ); 276 ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true );
277 QFile errorFile( tempFileName ); 277 QFile errorFile( tempFileName );
278 if ( errorFile.open(IO_ReadOnly) ) 278 if ( errorFile.open(IO_ReadOnly) )
279 { 279 {
280 QTextStream t( &errorFile ); 280 QTextStream t( &errorFile );
281 QString s; 281 QString s;
282 while ( !t.eof() ) 282 while ( !t.eof() )
283 { // until end of file... 283 { // until end of file...
284 s += t.readLine(); // line of text excluding '\n' 284 s += t.readLine(); // line of text excluding '\n'
285 } 285 }
286 errorFile.close(); 286 errorFile.close();
287 287
288 pErrDialog->m_textarea->setText( s ); 288 pErrDialog->m_textarea->setText( s );
289 } 289 }
290 else 290 else
291 { 291 {
292 pErrDialog->m_textarea->setText( "Unable to open File: /tmp/backup.er" ); 292 pErrDialog->m_textarea->setText( "Unable to open File: /tmp/backup.er" );
293 } 293 }
294 QPEApplication::execDialog( pErrDialog ); 294 QPEApplication::execDialog( pErrDialog );
295 delete pErrDialog; 295 delete pErrDialog;
296 break; 296 break;
297 } 297 }
298 setCaption(tr("Backup and Restore.. Failed !!")); 298 setCaption(tr("Backup and Restore.. Failed !!"));
299 return; 299 return;
300 } 300 }
301 else 301 else
302 { 302 {
303 QMessageBox::information(this, tr( "Message" ), tr( "Backup Successful." ), QString(tr( "Ok" ) ) ); 303 QMessageBox::information(this, tr( "Message" ), tr( "Backup Successful." ), QString(tr( "Ok" ) ) );
304 304
305 } 305 }
306 306
307 //write store-location 307 //write store-location
308 Config config( "BackupAndRestore" ); 308 Config config( "BackupAndRestore" );
309 config.setGroup( "LastLocation" ); 309 config.setGroup( "LastLocation" );
310 config.writeEntry( "LastStoreLocation", storeToLocation->currentText() ); 310 config.writeEntry( "LastStoreLocation", storeToLocation->currentText() );
311 311
312 setCaption(tr("Backup and Restore")); 312 setCaption(tr("Backup and Restore"));
313} 313}
314 314
315/*** 315/***
316 * Get a list of all of the files to backup. 316 * Get a list of all of the files to backup.
317 */ 317 */
318int BackupAndRestore::getBackupFiles(QString &backupFiles, QListViewItem *parent) 318int BackupAndRestore::getBackupFiles(QString &backupFiles, QListViewItem *parent)
319{ 319{
320 QListViewItem * currentItem; 320 QListViewItem * currentItem;
321 QString currentHome; 321 QString currentHome;
322 if(!parent) 322 if(!parent)
323 currentItem = backupList->firstChild(); 323 currentItem = backupList->firstChild();
324 else 324 else
325 { 325 {
326 currentItem = parent->firstChild(); 326 currentItem = parent->firstChild();
327 currentHome = parent->text(BACKUP_LOCATION); 327 currentHome = parent->text(BACKUP_LOCATION);
328 } 328 }
329 329
330 uint count = 0; 330 uint count = 0;
331 while( currentItem != 0 ) 331 while( currentItem != 0 )
332 { 332 {
333 if(currentItem->text(HEADER_BACKUP) == "B" ) 333 if(currentItem->text(HEADER_BACKUP) == "B" )
334 { 334 {
335 if(currentItem->childCount() == 0 ) 335 if(currentItem->childCount() == 0 )
336 { 336 {
337 if(parent == NULL) 337 if(parent == NULL)
338 backupFiles += currentItem->text(BACKUP_LOCATION); 338 backupFiles += currentItem->text(BACKUP_LOCATION);
339 else 339 else
340 backupFiles += currentHome + currentItem->text(HEADER_NAME); 340 backupFiles += currentHome + currentItem->text(HEADER_NAME);
341 backupFiles += " "; 341 backupFiles += " ";
342 count++; 342 count++;
343 } 343 }
344 else 344 else
345 { 345 {
346 count += getBackupFiles(backupFiles, currentItem); 346 count += getBackupFiles(backupFiles, currentItem);
347 } 347 }
348 } 348 }
349 currentItem = currentItem->nextSibling(); 349 currentItem = currentItem->nextSibling();
350 } 350 }
351 return count; 351 return count;
352} 352}
353 353
354void BackupAndRestore::sourceDirChanged(int selection) 354void BackupAndRestore::sourceDirChanged(int selection)
355{ 355{
356 restoreList->clear(); 356 restoreList->clear();
357 rescanFolder(backupLocations[restoreSource->text(selection)]); 357 rescanFolder(backupLocations[restoreSource->text(selection)]);
358} 358}
359 359
360void BackupAndRestore::fileListUpdate() 360void BackupAndRestore::fileListUpdate()
361{ 361{
362 qWarning("void BackupAndRestore::fileListUpdate()"); 362 owarn << "void BackupAndRestore::fileListUpdate()" << oendl;
363 restoreList->clear(); 363 restoreList->clear();
364 rescanFolder( backupLocations[restoreSource->currentText()] ); 364 rescanFolder( backupLocations[restoreSource->currentText()] );
365} 365}
366 366
367/** 367/**
368 * Scans directory for any backup files. Will recursivly go down, 368 * Scans directory for any backup files. Will recursivly go down,
369 * but will not follow symlinks. 369 * but will not follow symlinks.
370 * @param directory - the directory to look in. 370 * @param directory - the directory to look in.
371 */ 371 */
372void BackupAndRestore::rescanFolder(QString directory) 372void BackupAndRestore::rescanFolder(QString directory)
373{ 373{
374 //qDebug(QString("rescanFolder: ") + directory.latin1()); 374 //odebug << QString("rescanFolder: ") + directory.latin1() << oendl;
375 QDir d(directory); 375 QDir d(directory);
376 if(!d.exists()) 376 if(!d.exists())
377 return; 377 return;
378 378
379 d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs); 379 d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs);
380 const QFileInfoList *list = d.entryInfoList(); 380 const QFileInfoList *list = d.entryInfoList();
381 QFileInfoListIterator it( *list ); 381 QFileInfoListIterator it( *list );
382 QFileInfo *file; 382 QFileInfo *file;
383 while ( (file=it.current()) ) 383 while ( (file=it.current()) )
384 { // for each file... 384 { // for each file...
385 // If it is a dir and not .. or . then add it as a tab and go down. 385 // If it is a dir and not .. or . then add it as a tab and go down.
386 if(file->isDir()) 386 if(file->isDir())
387 { 387 {
388 if(file->fileName() != ".." && file->fileName() != ".") 388 if(file->fileName() != ".." && file->fileName() != ".")
389 { 389 {
390 rescanFolder(directory + "/" + file->fileName()); 390 rescanFolder(directory + "/" + file->fileName());
391 } 391 }
392 } 392 }
393 else 393 else
394 { 394 {
395 // If it is a backup file add to list. 395 // If it is a backup file add to list.
396 if(file->fileName().contains(EXTENSION)) 396 if(file->fileName().contains(EXTENSION))
397 (void)new QListViewItem(restoreList, file->fileName()); 397 (void)new QListViewItem(restoreList, file->fileName());
398 } 398 }
399 ++it; 399 ++it;
400 } 400 }
401} 401}
402 402
403/** 403/**
404 * Restore a backup file. 404 * Restore a backup file.
405 * Report errors or success 405 * Report errors or success
406 */ 406 */
407void BackupAndRestore::restore() 407void BackupAndRestore::restore()
408{ 408{
409 QListViewItem *restoreItem = restoreList->currentItem(); 409 QListViewItem *restoreItem = restoreList->currentItem();
410 if(!restoreItem) 410 if(!restoreItem)
411 { 411 {
412 QMessageBox::critical(this, tr( "Message" ), 412 QMessageBox::critical(this, tr( "Message" ),
413 tr( "Please select something to restore." ),QString( tr( "Ok") ) ); 413 tr( "Please select something to restore." ),QString( tr( "Ok") ) );
414 return; 414 return;
415 } 415 }
416 setCaption(tr("Backup and Restore... working...")); 416 setCaption(tr("Backup and Restore... working..."));
417 417
418 QString restoreFile = backupLocations[restoreSource->currentText()]; 418 QString restoreFile = backupLocations[restoreSource->currentText()];
419 419
420 restoreFile += "/" + restoreItem->text(0); 420 restoreFile += "/" + restoreItem->text(0);
421 421
422 qDebug( restoreFile ); 422 odebug << restoreFile << oendl;
423 423
424 //check if backup file come from opie 1.0.x 424 //check if backup file come from opie 1.0.x
425 425
426 QString commandLine = QString( "tar -tzf %1 | grep Applications/backup/exclude" ).arg( restoreFile.latin1() ); 426 QString commandLine = QString( "tar -tzf %1 | grep Applications/backup/exclude" ).arg( restoreFile.latin1() );
427 427
428 int r = system( commandLine ); 428 int r = system( commandLine );
429 429
430 QString startDir; 430 QString startDir;
431 431
432 if( r != 0 ) //Applications/backup/exclude not found - old backup file 432 if( r != 0 ) //Applications/backup/exclude not found - old backup file
433 { 433 {
434 startDir = QString( "/" ); 434 startDir = QString( "/" );
435 } else 435 } else
436 { 436 {
437 startDir = QDir::homeDirPath(); 437 startDir = QDir::homeDirPath();
438 } 438 }
439 439
440 //unpack backup file 440 //unpack backup file
441 commandLine = QString( "cd %1 && tar -zxf %2 2> %3" ).arg( startDir ) 441 commandLine = QString( "cd %1 && tar -zxf %2 2> %3" ).arg( startDir )
442 .arg( restoreFile.latin1() ) 442 .arg( restoreFile.latin1() )
443 .arg( tempFileName.latin1() ); 443 .arg( tempFileName.latin1() );
444 444
445 qDebug( commandLine ); 445 odebug << commandLine << oendl;
446 446
447 r = system( commandLine ); 447 r = system( commandLine );
448 448
449 //error handling 449 //error handling
450 if(r != 0) 450 if(r != 0)
451 { 451 {
452 QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno ); 452 QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno );
453 switch( QMessageBox::critical(this, tr( "Message" ), tr( "Restore Failed." ) + "\n" 453 switch( QMessageBox::critical(this, tr( "Message" ), tr( "Restore Failed." ) + "\n"
454 + errorMsg, QString( tr( "Ok") ), QString( tr( "Details" ) ) ) ) 454 + errorMsg, QString( tr( "Ok") ), QString( tr( "Details" ) ) ) )
455 { 455 {
456 case 1: 456 case 1:
457 qWarning("Details pressed !"); 457 owarn << "Details pressed !" << oendl;
458 ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true ); 458 ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true );
459 QFile errorFile( tempFileName ); 459 QFile errorFile( tempFileName );
460 if ( errorFile.open(IO_ReadOnly) ) 460 if ( errorFile.open(IO_ReadOnly) )
461 { 461 {
462 QTextStream t( &errorFile ); 462 QTextStream t( &errorFile );
463 QString s; 463 QString s;
464 while ( !t.eof() ) 464 while ( !t.eof() )
465 { // until end of file... 465 { // until end of file...
466 s += t.readLine(); // line of text excluding '\n' 466 s += t.readLine(); // line of text excluding '\n'
467 } 467 }
468 errorFile.close(); 468 errorFile.close();
469 469
470 pErrDialog->m_textarea->setText( s ); 470 pErrDialog->m_textarea->setText( s );
471 } 471 }
472 else 472 else
473 { 473 {
474 pErrDialog->m_textarea->setText( tr( "Unable to open File: %1" ).arg( "/tmp/backup.er" ) ); 474 pErrDialog->m_textarea->setText( tr( "Unable to open File: %1" ).arg( "/tmp/backup.er" ) );
475 } 475 }
476 QPEApplication::execDialog( pErrDialog ); 476 QPEApplication::execDialog( pErrDialog );
477 delete pErrDialog; 477 delete pErrDialog;
478 478
479 setCaption(tr("Backup and Restore.. Failed !!")); 479 setCaption(tr("Backup and Restore.. Failed !!"));
480 return; 480 return;
481 481
482 break; 482 break;
483 483
484 } 484 }
485 } 485 }
486 else 486 else
487 { 487 {
488 QMessageBox::information(this, tr( "Message" ), tr( "Restore Successful." ), QString( tr( "Ok") ) ); 488 QMessageBox::information(this, tr( "Message" ), tr( "Restore Successful." ), QString( tr( "Ok") ) );
489 } 489 }
490 490
491 //write restore-location 491 //write restore-location
492 Config config( "BackupAndRestore" ); 492 Config config( "BackupAndRestore" );
493 config.setGroup( "LastLocation" ); 493 config.setGroup( "LastLocation" );
494 config.writeEntry( "LastRestoreLocation", restoreSource->currentText() ); 494 config.writeEntry( "LastRestoreLocation", restoreSource->currentText() );
495 495
496 setCaption(tr("Backup and Restore")); 496 setCaption(tr("Backup and Restore"));
497} 497}
498 498
499/** 499/**
500 * Check for exclude in Applications/backup 500 * Check for exclude in Applications/backup
501 * If it does not exist, the function will create the file with *.bck as content 501 * If it does not exist, the function will create the file with *.bck as content
502 * The exclude_files is read by tar and will provide to exclude special files out from backup. 502 * The exclude_files is read by tar and will provide to exclude special files out from backup.
503 * e.g. alle *.bck files (backup-files) will not be backed up by default 503 * e.g. alle *.bck files (backup-files) will not be backed up by default
504 */ 504 */
505 505
506QString BackupAndRestore::getExcludeFile() 506QString BackupAndRestore::getExcludeFile()
507{ 507{
508 QString excludeFileName = Global::applicationFileName( "backup", "exclude" ); 508 QString excludeFileName = Global::applicationFileName( "backup", "exclude" );
509 if ( !QFile::exists( excludeFileName ) ) 509 if ( !QFile::exists( excludeFileName ) )
510 { 510 {
511 QFile excludeFile( excludeFileName); 511 QFile excludeFile( excludeFileName);
512 if ( excludeFile.open( IO_WriteOnly ) == true ) 512 if ( excludeFile.open( IO_WriteOnly ) == true )
513 { 513 {
514 QTextStream writeStream( &excludeFile ); 514 QTextStream writeStream( &excludeFile );
515 writeStream << "*.bck" << "\n"; 515 writeStream << "*.bck" << "\n";
516 excludeFile.close(); 516 excludeFile.close();
517 } 517 }
518 else 518 else
519 { 519 {
520 return QString::null; 520 return QString::null;
521 } 521 }
522 } 522 }
523 523
524 return excludeFileName; 524 return excludeFileName;
525} 525}
526 526
527// backuprestore.cpp 527// backuprestore.cpp
528 528
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 )
46 tmpvb->addWidget( sv, 0, 0 ); 46 tmpvb->addWidget( sv, 0, 0 );
47 sv->setResizePolicy( QScrollView::AutoOneFit ); 47 sv->setResizePolicy( QScrollView::AutoOneFit );
48 sv->setFrameStyle( QFrame::NoFrame ); 48 sv->setFrameStyle( QFrame::NoFrame );
49 QWidget *container = new QWidget( sv->viewport() ); 49 QWidget *container = new QWidget( sv->viewport() );
50 sv->addChild( container ); 50 sv->addChild( container );
51 51
52 QGridLayout *layout = new QGridLayout( container ); 52 QGridLayout *layout = new QGridLayout( container );
53 layout->setMargin( 2 ); 53 layout->setMargin( 2 );
54 layout->setSpacing( 4 ); 54 layout->setSpacing( 4 );
55 55
56 // Time server selector 56 // Time server selector
57 layout->addWidget( new QLabel( tr( "Time server" ), container ), 0, 0 ); 57 layout->addWidget( new QLabel( tr( "Time server" ), container ), 0, 0 );
58 cbTimeServer = new QComboBox( TRUE, container ); 58 cbTimeServer = new QComboBox( TRUE, container );
59 layout->addMultiCellWidget( cbTimeServer, 1, 1, 0, 1 ); 59 layout->addMultiCellWidget( cbTimeServer, 1, 1, 0, 1 );
60 60
61 // Lookup delay selector 61 // Lookup delay selector
62 layout->addWidget( new QLabel( tr( "minutes between time updates" ), container ), 2, 1 ); 62 layout->addWidget( new QLabel( tr( "minutes between time updates" ), container ), 2, 1 );
63 sbNtpDelay = new QSpinBox( 1, 9999999, 1, container ); 63 sbNtpDelay = new QSpinBox( 1, 9999999, 1, container );
64 sbNtpDelay->setWrapping( TRUE ); 64 sbNtpDelay->setWrapping( TRUE );
65 sbNtpDelay->setMaximumWidth( 50 ); 65 sbNtpDelay->setMaximumWidth( 50 );
66 connect( sbNtpDelay, SIGNAL(valueChanged(int)), this, SIGNAL(ntpDelayChanged(int)) ); 66 connect( sbNtpDelay, SIGNAL(valueChanged(int)), this, SIGNAL(ntpDelayChanged(int)) );
67 layout->addWidget( sbNtpDelay, 2, 0 ); 67 layout->addWidget( sbNtpDelay, 2, 0 );
68 68
69 // Prediction delay selector 69 // Prediction delay selector
70 layout->addWidget( new QLabel( tr( "minutes between prediction updates" ), container ), 3, 1 ); 70 layout->addWidget( new QLabel( tr( "minutes between prediction updates" ), container ), 3, 1 );
71 sbPredictDelay = new QSpinBox( 42, 9999999, 1, container ); 71 sbPredictDelay = new QSpinBox( 42, 9999999, 1, container );
72 sbPredictDelay->setWrapping( TRUE ); 72 sbPredictDelay->setWrapping( TRUE );
73 sbPredictDelay->setMaximumWidth( 50 ); 73 sbPredictDelay->setMaximumWidth( 50 );
74 layout->addWidget( sbPredictDelay, 3, 0 ); 74 layout->addWidget( sbPredictDelay, 3, 0 );
75 75
76 // Space filler 76 // Space filler
77 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 4, 0 ); 77 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 4, 0 );
78 78
79 // Display time server information selector 79 // Display time server information selector
80 chNtpTab = new QCheckBox( tr( "Display time server information" ), container ); 80 chNtpTab = new QCheckBox( tr( "Display time server information" ), container );
81 connect( chNtpTab, SIGNAL( toggled(bool) ), this, SIGNAL( displayNTPTab(bool) ) ); 81 connect( chNtpTab, SIGNAL( toggled(bool) ), this, SIGNAL( displayNTPTab(bool) ) );
82 layout->addMultiCellWidget( chNtpTab, 5, 5, 0, 1 ); 82 layout->addMultiCellWidget( chNtpTab, 5, 5, 0, 1 );
83 83
84 // Display time prediction information selector 84 // Display time prediction information selector
85 chPredictTab = new QCheckBox( tr( "Display time prediction information" ), container ); 85 chPredictTab = new QCheckBox( tr( "Display time prediction information" ), container );
86 connect( chPredictTab, SIGNAL( toggled(bool) ), this, SIGNAL( displayPredictTab(bool) ) ); 86 connect( chPredictTab, SIGNAL( toggled(bool) ), this, SIGNAL( displayPredictTab(bool) ) );
87 layout->addMultiCellWidget( chPredictTab, 6, 6, 0, 1 ); 87 layout->addMultiCellWidget( chPredictTab, 6, 6, 0, 1 );
88 88
89 // Space filler 89 // Space filler
90 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 7, 0 ); 90 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 7, 0 );
91 91
92 // Initialize values 92 // Initialize values
93 QString ntpSrvsFile = QPEApplication::qpeDir(); 93 QString ntpSrvsFile = QPEApplication::qpeDir();
94 ntpSrvsFile.append( "etc/ntpservers" ); 94 ntpSrvsFile.append( "etc/ntpservers" );
95 Config ntpSrvs( ntpSrvsFile, Config::File ); 95 Config ntpSrvs( ntpSrvsFile, Config::File );
96 ntpSrvs.setGroup( "servers" ); 96 ntpSrvs.setGroup( "servers" );
97 int srvCount = ntpSrvs.readNumEntry( "count", 0 ); 97 int srvCount = ntpSrvs.readNumEntry( "count", 0 );
98 for ( int i = 0; i < srvCount; i++ ) 98 for ( int i = 0; i < srvCount; i++ )
99 { 99 {
100 ntpSrvs.setGroup( QString::number( i ) ); 100 ntpSrvs.setGroup( QString::number( i ) );
101 cbTimeServer->insertItem( ntpSrvs.readEntry( "name" ) ); 101 cbTimeServer->insertItem( ntpSrvs.readEntry( "name" ) );
102 } 102 }
103 if ( srvCount==0 ) 103 if ( srvCount==0 )
104 cbTimeServer->insertItem( "time.fu-berlin.de" ); 104 cbTimeServer->insertItem( "time.fu-berlin.de" );
105 105
106 Config config( "ntp" ); 106 Config config( "ntp" );
107 config.setGroup( "settings" ); 107 config.setGroup( "settings" );
108 sbPredictDelay->setValue( config.readNumEntry( "minLookupDiff", 720 ) ); 108 sbPredictDelay->setValue( config.readNumEntry( "minLookupDiff", 720 ) );
109 sbNtpDelay->setValue( config.readNumEntry( "ntpRefreshFreq", 1440 ) ); 109 sbNtpDelay->setValue( config.readNumEntry( "ntpRefreshFreq", 1440 ) );
110 cbTimeServer->setCurrentItem( config.readNumEntry( "ntpServer", 0 ) ); 110 cbTimeServer->setCurrentItem( config.readNumEntry( "ntpServer", 0 ) );
111 chNtpTab->setChecked( config.readBoolEntry( "displayNtpTab", FALSE ) ); 111 chNtpTab->setChecked( config.readBoolEntry( "displayNtpTab", FALSE ) );
112 chPredictTab->setChecked( config.readBoolEntry( "displayPredictTab", FALSE ) ); 112 chPredictTab->setChecked( config.readBoolEntry( "displayPredictTab", FALSE ) );
113} 113}
114 114
115SettingsTabWidget::~SettingsTabWidget() 115SettingsTabWidget::~SettingsTabWidget()
116{ 116{
117} 117}
118 118
119void SettingsTabWidget::saveSettings() 119void SettingsTabWidget::saveSettings()
120{ 120{
121 int srvCount = cbTimeServer->count(); 121 int srvCount = cbTimeServer->count();
122 bool serversChanged = TRUE; 122 bool serversChanged = TRUE;
123 int curSrv = cbTimeServer->currentItem(); 123 int curSrv = cbTimeServer->currentItem();
124 QString edit = cbTimeServer->currentText(); 124 QString edit = cbTimeServer->currentText();
125 for ( int i = 0; i < srvCount; i++ ) 125 for ( int i = 0; i < srvCount; i++ )
126 { 126 {
127 if ( edit == cbTimeServer->text( i ) ) 127 if ( edit == cbTimeServer->text( i ) )
128 serversChanged = FALSE; 128 serversChanged = FALSE;
129 } 129 }
130 if ( serversChanged ) 130 if ( serversChanged )
131 { 131 {
132 QString ntpSrvsFile = QPEApplication::qpeDir(); 132 QString ntpSrvsFile = QPEApplication::qpeDir();
133 ntpSrvsFile.append( "etc/ntpservers" ); 133 ntpSrvsFile.append( "etc/ntpservers" );
134 Config ntpSrvs( ntpSrvsFile, Config::File ); 134 Config ntpSrvs( ntpSrvsFile, Config::File );
135 ntpSrvs.setGroup( "servers" ); 135 ntpSrvs.setGroup( "servers" );
136 ntpSrvs.writeEntry( "count", ++srvCount ); 136 ntpSrvs.writeEntry( "count", ++srvCount );
137 ntpSrvs.setGroup( "0" ); 137 ntpSrvs.setGroup( "0" );
138 ntpSrvs.writeEntry( "name", edit ); 138 ntpSrvs.writeEntry( "name", edit );
139 curSrv = 0; 139 curSrv = 0;
140 for ( int i = 1; i < srvCount; i++ ) 140 for ( int i = 1; i < srvCount; i++ )
141 { 141 {
142 // qDebug( "ntpSrvs[%i/%i]=%s", i, srvCount, cbTimeServer->text( i ).latin1() ); 142 // odebug << "ntpSrvs[" << i << "/" << srvCount << "]=" << cbTimeServer->text( i ).latin1() << "" << oendl;
143 ntpSrvs.setGroup( QString::number( i ) ); 143 ntpSrvs.setGroup( QString::number( i ) );
144 ntpSrvs.writeEntry( "name", cbTimeServer->text( i-1 ) ); 144 ntpSrvs.writeEntry( "name", cbTimeServer->text( i-1 ) );
145 } 145 }
146 } 146 }
147 Config config( "ntp", Config::User ); 147 Config config( "ntp", Config::User );
148 config.setGroup( "settings" ); 148 config.setGroup( "settings" );
149 config.writeEntry( "ntpServer", curSrv ); 149 config.writeEntry( "ntpServer", curSrv );
150 config.writeEntry( "minLookupDiff", sbPredictDelay->value() ); 150 config.writeEntry( "minLookupDiff", sbPredictDelay->value() );
151 config.writeEntry( "ntpRefreshFreq", sbNtpDelay->value() ); 151 config.writeEntry( "ntpRefreshFreq", sbNtpDelay->value() );
152 config.writeEntry( "displayNtpTab", chNtpTab->isChecked() ); 152 config.writeEntry( "displayNtpTab", chNtpTab->isChecked() );
153 config.writeEntry( "displayPredictTab", chPredictTab->isChecked() ); 153 config.writeEntry( "displayPredictTab", chPredictTab->isChecked() );
154} 154}
155 155
156QString SettingsTabWidget::ntpServer() 156QString SettingsTabWidget::ntpServer()
157{ 157{
158 return cbTimeServer->currentText(); 158 return cbTimeServer->currentText();
159} 159}
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){
44 44
45/** 45/**
46 * Set Hardware name 46 * Set Hardware name
47 * @param name - the new name 47 * @param name - the new name
48 * emit updateInterface 48 * emit updateInterface
49 */ 49 */
50void Interface::setHardwareName(const QString &name){ 50void Interface::setHardwareName(const QString &name){
51 hardwareName = name; 51 hardwareName = name;
52 emit(updateInterface(this)); 52 emit(updateInterface(this));
53}; 53};
54 54
55/** 55/**
56 * Set Module owner 56 * Set Module owner
57 * @param owner - the new owner 57 * @param owner - the new owner
58 * emit updateInterface 58 * emit updateInterface
59 */ 59 */
60void Interface::setModuleOwner(Module *owner){ 60void Interface::setModuleOwner(Module *owner){
61 moduleOwner = owner; 61 moduleOwner = owner;
62 emit(updateInterface(this)); 62 emit(updateInterface(this));
63}; 63};
64 64
65 65
66/** 66/**
67 * Try to start the interface. 67 * Try to start the interface.
68 */ 68 */
69void Interface::start(){ 69void Interface::start(){
70 // check to see if we are already running. 70 // check to see if we are already running.
71 if(true == status){ 71 if(true == status){
72 emit (updateMessage("Unable to start interface,\n already started")); 72 emit (updateMessage("Unable to start interface,\n already started"));
73 return; 73 return;
74 } 74 }
75 75
76 int ret = system(QString("%1 %2 up").arg(IFCONFIG).arg(this->name()).latin1()); 76 int ret = system(QString("%1 %2 up").arg(IFCONFIG).arg(this->name()).latin1());
77 // See if it was successful... 77 // See if it was successful...
78 if(ret != 0){ 78 if(ret != 0){
79 emit (updateMessage("Starting interface failed")); 79 emit (updateMessage("Starting interface failed"));
80 return; 80 return;
81 } 81 }
82 82
83 status = true; 83 status = true;
84 refresh(); 84 refresh();
85 emit (updateMessage("Start successful")); 85 emit (updateMessage("Start successful"));
86} 86}
87 87
88/** 88/**
89 * Try to stop the interface. 89 * Try to stop the interface.
90 */ 90 */
91void Interface::stop(){ 91void Interface::stop(){
92 // check to see if we are already stopped. 92 // check to see if we are already stopped.
93 if(false == status){ 93 if(false == status){
94 emit (updateMessage("Unable to stop interface,\n already stopped")); 94 emit (updateMessage("Unable to stop interface,\n already stopped"));
95 return; 95 return;
96 } 96 }
97 97
98 int ret = system(QString("%1 %2 down").arg(IFCONFIG).arg(this->name()).latin1()); 98 int ret = system(QString("%1 %2 down").arg(IFCONFIG).arg(this->name()).latin1());
99 if(ret != 0){ 99 if(ret != 0){
100 emit (updateMessage("Stopping interface failed")); 100 emit (updateMessage("Stopping interface failed"));
101 return; 101 return;
102 } 102 }
103 103
104 status = false; 104 status = false;
105 refresh(); 105 refresh();
106 emit (updateMessage("Stop successful")); 106 emit (updateMessage("Stop successful"));
107} 107}
108 108
109/** 109/**
110 * Try to restart the interface. 110 * Try to restart the interface.
111 */ 111 */
112void Interface::restart(){ 112void Interface::restart(){
113 stop(); 113 stop();
114 start(); 114 start();
115} 115}
116 116
117/** 117/**
118 * Try to refresh the information about the interface. 118 * Try to refresh the information about the interface.
119 * First call ifconfig, then check the dhcp-info file 119 * First call ifconfig, then check the dhcp-info file
120 * @return bool true if successful. 120 * @return bool true if successful.
121 */ 121 */
122bool Interface::refresh(){ 122bool Interface::refresh(){
123 // See if we are up. 123 // See if we are up.
124 if(status == false){ 124 if(status == false){
125 macAddress = ""; 125 macAddress = "";
126 ip = "0.0.0.0"; 126 ip = "0.0.0.0";
127 subnetMask = "0.0.0.0"; 127 subnetMask = "0.0.0.0";
128 broadcast = ""; 128 broadcast = "";
129 dhcp = false; 129 dhcp = false;
130 dhcpServerIp = ""; 130 dhcpServerIp = "";
131 leaseObtained = ""; 131 leaseObtained = "";
132 leaseExpires = ""; 132 leaseExpires = "";
133 emit(updateInterface(this)); 133 emit(updateInterface(this));
134 return true; 134 return true;
135 } 135 }
136 136
137 QString fileName = QString("/tmp/%1_ifconfig_info").arg(this->name()); 137 QString fileName = QString("/tmp/%1_ifconfig_info").arg(this->name());
138 int ret = system(QString("LANG=C %1 %2 > %3").arg(IFCONFIG).arg(this->name()).arg(fileName).latin1()); 138 int ret = system(QString("LANG=C %1 %2 > %3").arg(IFCONFIG).arg(this->name()).arg(fileName).latin1());
139 if(ret != 0){ 139 if(ret != 0){
140 qDebug(QString("Interface: Ifconfig return value: %1, is not 0").arg(ret).latin1()); 140 odebug << QString("Interface: Ifconfig return value: %1, is not 0").arg(ret).latin1() << oendl;
141 return false; 141 return false;
142 } 142 }
143 143
144 QFile file(fileName); 144 QFile file(fileName);
145 if (!file.open(IO_ReadOnly)){ 145 if (!file.open(IO_ReadOnly)){
146 qDebug(QString("Interface: Can't open file: %1").arg(fileName).latin1()); 146 odebug << QString("Interface: Can't open file: %1").arg(fileName).latin1() << oendl;
147 return false; 147 return false;
148 } 148 }
149 149
150 // Set to the defaults 150 // Set to the defaults
151 macAddress = ""; 151 macAddress = "";
152 ip = "0.0.0.0"; 152 ip = "0.0.0.0";
153 subnetMask = "0.0.0.0"; 153 subnetMask = "0.0.0.0";
154 broadcast = ""; 154 broadcast = "";
155 155
156 QTextStream stream( &file ); 156 QTextStream stream( &file );
157 QString line; 157 QString line;
158 while ( !stream.eof() ) { 158 while ( !stream.eof() ) {
159 line = stream.readLine(); 159 line = stream.readLine();
160 if(line.contains("HWaddr")){ 160 if(line.contains("HWaddr")){
161 int mac = line.find("HWaddr"); 161 int mac = line.find("HWaddr");
162 macAddress = line.mid(mac+7, line.length()); 162 macAddress = line.mid(mac+7, line.length());
163 } 163 }
164 if(line.contains("inet addr")){ 164 if(line.contains("inet addr")){
165 int ipl = line.find("inet addr"); 165 int ipl = line.find("inet addr");
166 int space = line.find(" ", ipl+10); 166 int space = line.find(" ", ipl+10);
167 ip = line.mid(ipl+10, space-ipl-10); 167 ip = line.mid(ipl+10, space-ipl-10);
168 } 168 }
169 if(line.contains("Mask")){ 169 if(line.contains("Mask")){
170 int mask = line.find("Mask"); 170 int mask = line.find("Mask");
171 subnetMask = line.mid(mask+5, line.length()); 171 subnetMask = line.mid(mask+5, line.length());
172 } 172 }
173 if(line.contains("Bcast")){ 173 if(line.contains("Bcast")){
174 int mask = line.find("Bcast"); 174 int mask = line.find("Bcast");
175 int space = line.find(" ", mask+6); 175 int space = line.find(" ", mask+6);
176 broadcast = line.mid(mask+6, space-mask-6); 176 broadcast = line.mid(mask+6, space-mask-6);
177 } 177 }
178 } 178 }
179 file.close(); 179 file.close();
180 QFile::remove(fileName); 180 QFile::remove(fileName);
181 181
182 // DHCP TESTING 182 // DHCP TESTING
183 // reset DHCP info 183 // reset DHCP info
184 dhcpServerIp = ""; 184 dhcpServerIp = "";
185 leaseObtained = ""; 185 leaseObtained = "";
186 leaseExpires = ""; 186 leaseExpires = "";
187 dhcp = false; 187 dhcp = false;
188 188
189 QString dhcpDirectory(DHCP_INFO_DIR); 189 QString dhcpDirectory(DHCP_INFO_DIR);
190 QDir d(dhcpDirectory); 190 QDir d(dhcpDirectory);
191 if(!d.exists(dhcpDirectory)) 191 if(!d.exists(dhcpDirectory))
192 dhcpDirectory = "/var/run"; 192 dhcpDirectory = "/var/run";
193 193
194 // See if we have 194 // See if we have
195 QString dhcpFile(QString(dhcpDirectory+"/dhcpcd-%1.info").arg(this->name())); 195 QString dhcpFile(QString(dhcpDirectory+"/dhcpcd-%1.info").arg(this->name()));
196 // If there is no DHCP information then exit now with no errors. 196 // If there is no DHCP information then exit now with no errors.
197 if(!QFile::exists(dhcpFile)){ 197 if(!QFile::exists(dhcpFile)){
198 emit(updateInterface(this)); 198 emit(updateInterface(this));
199 return true; 199 return true;
200 } 200 }
201 201
202 file.setName(dhcpFile); 202 file.setName(dhcpFile);
203 if (!file.open(IO_ReadOnly)){ 203 if (!file.open(IO_ReadOnly)){
204 qDebug(QString("Interface: Can't open file: %1").arg(dhcpFile).latin1()); 204 odebug << QString("Interface: Can't open file: %1").arg(dhcpFile).latin1() << oendl;
205 return false; 205 return false;
206 } 206 }
207 207
208 // leaseTime and renewalTime and used if pid and deamon exe can be accessed. 208 // leaseTime and renewalTime and used if pid and deamon exe can be accessed.
209 int leaseTime = 0; 209 int leaseTime = 0;
210 int renewalTime = 0; 210 int renewalTime = 0;
211 211
212 stream.setDevice( &file ); 212 stream.setDevice( &file );
213 while ( !stream.eof() ) { 213 while ( !stream.eof() ) {
214 line = stream.readLine(); 214 line = stream.readLine();
215 if(line.contains("DHCPSIADDR=")) 215 if(line.contains("DHCPSIADDR="))
216 dhcpServerIp = line.mid(11, line.length()); 216 dhcpServerIp = line.mid(11, line.length());
217 if(line.contains("LEASETIME=")) 217 if(line.contains("LEASETIME="))
218 leaseTime = line.mid(10, line.length()).toInt(); 218 leaseTime = line.mid(10, line.length()).toInt();
219 if(line.contains("RENEWALTIME=")) 219 if(line.contains("RENEWALTIME="))
220 renewalTime = line.mid(12, line.length()).toInt(); 220 renewalTime = line.mid(12, line.length()).toInt();
221 } 221 }
222 file.close(); 222 file.close();
223 //qDebug(QString("Interface: leaseTime: %1").arg(leaseTime).latin1()); 223 //odebug << QString("Interface: leaseTime: %1").arg(leaseTime).latin1() << oendl;
224 //qDebug(QString("Interface: renewalTime: %1").arg(renewalTime).latin1()); 224 //odebug << QString("Interface: renewalTime: %1").arg(renewalTime).latin1() << oendl;
225 225
226 // Get the pid of the deamond 226 // Get the pid of the deamond
227 dhcpFile = (QString(dhcpDirectory+"/dhcpcd-%1.pid").arg(this->name())); 227 dhcpFile = (QString(dhcpDirectory+"/dhcpcd-%1.pid").arg(this->name()));
228 file.setName(dhcpFile); 228 file.setName(dhcpFile);
229 if (!file.open(IO_ReadOnly)){ 229 if (!file.open(IO_ReadOnly)){
230 qDebug(QString("Interface: Can't open file: %1").arg(dhcpFile).latin1()); 230 odebug << QString("Interface: Can't open file: %1").arg(dhcpFile).latin1() << oendl;
231 return false; 231 return false;
232 } 232 }
233 233
234 int pid = -1; 234 int pid = -1;
235 stream.setDevice( &file ); 235 stream.setDevice( &file );
236 while ( !stream.eof() ) { 236 while ( !stream.eof() ) {
237 line = stream.readLine(); 237 line = stream.readLine();
238 pid = line.toInt(); 238 pid = line.toInt();
239 } 239 }
240 file.close(); 240 file.close();
241 241
242 if( pid == -1){ 242 if( pid == -1){
243 qDebug("Interface: Could not get pid of dhcpc deamon."); 243 odebug << "Interface: Could not get pid of dhcpc deamon." << oendl;
244 return false; 244 return false;
245 } 245 }
246 246
247 // Get the start running time of the deamon 247 // Get the start running time of the deamon
248 fileName = (QString("/proc/%1/stat").arg(pid)); 248 fileName = (QString("/proc/%1/stat").arg(pid));
249 file.setName(fileName); 249 file.setName(fileName);
250 stream.setDevice( &file ); 250 stream.setDevice( &file );
251 if (!file.open(IO_ReadOnly)){ 251 if (!file.open(IO_ReadOnly)){
252 qDebug(QString("Interface: Can't open file: %1").arg(fileName).latin1()); 252 odebug << QString("Interface: Can't open file: %1").arg(fileName).latin1() << oendl;
253 return false; 253 return false;
254 } 254 }
255 while ( !stream.eof() ) { 255 while ( !stream.eof() ) {
256 line = stream.readLine(); 256 line = stream.readLine();
257 } 257 }
258 file.close(); 258 file.close();
259 long time = 0; 259 long time = 0;
260 // Grab the start time 260 // Grab the start time
261 // pid com state ppid pgrp session tty_nr tpgid flags 261 // pid com state ppid pgrp session tty_nr tpgid flags
262 sscanf(line.latin1(), "%*d %*s %*c %*d %*d %*d %*d %*d %*u " 262 sscanf(line.latin1(), "%*d %*s %*c %*d %*d %*d %*d %*d %*u "
263 // minflt cminflt majflt cmajflt utime stime cutime cstime priority 263 // minflt cminflt majflt cmajflt utime stime cutime cstime priority
264 "%*u %*u %*u %*u %*u %*u %*d %*d %*d " 264 "%*u %*u %*u %*u %*u %*u %*d %*d %*d "
265 // nice 0 itrealvalue starttime 265 // nice 0 itrealvalue starttime
266 "%*d %*d %*d %lu", (long*) &time); 266 "%*d %*d %*d %lu", (long*) &time);
267 time = time/100; 267 time = time/100;
268 268
269 QDateTime datetime(QDateTime::currentDateTime()); 269 QDateTime datetime(QDateTime::currentDateTime());
270 270
271 // Get the uptime of the computer. 271 // Get the uptime of the computer.
272 QFile f("/proc/uptime"); 272 QFile f("/proc/uptime");
273 if ( f.open(IO_ReadOnly) ) { // file opened successfully 273 if ( f.open(IO_ReadOnly) ) { // file opened successfully
274 QTextStream t( &f ); // use a text stream 274 QTextStream t( &f ); // use a text stream
275 int sec = 0; 275 int sec = 0;
276 t >> sec; 276 t >> sec;
277 datetime = datetime.addSecs((-1*sec)); 277 datetime = datetime.addSecs((-1*sec));
278 f.close(); 278 f.close();
279 } 279 }
280 else{ 280 else{
281 qDebug("Interface: Can't open /proc/uptime to retrive uptime."); 281 odebug << "Interface: Can't open /proc/uptime to retrive uptime." << oendl;
282 return false; 282 return false;
283 } 283 }
284 284
285 datetime = datetime.addSecs(time); 285 datetime = datetime.addSecs(time);
286 //qDebug(QString("Interface: %1 %2").arg(datetime.toString()).arg(pid).latin1()); 286 //odebug << QString("Interface: %1 %2").arg(datetime.toString()).arg(pid).latin1() << oendl;
287 287
288 // Calculate the start and renew times 288 // Calculate the start and renew times
289 leaseObtained= datetime.toString(); 289 leaseObtained= datetime.toString();
290 290
291 // Calculate the start and renew times 291 // Calculate the start and renew times
292 datetime = datetime.addSecs(leaseTime); 292 datetime = datetime.addSecs(leaseTime);
293 leaseExpires = datetime.toString(); 293 leaseExpires = datetime.toString();
294 294
295 dhcp = true; 295 dhcp = true;
296 296
297 emit(updateInterface(this)); 297 emit(updateInterface(this));
298 return true; 298 return true;
299} 299}
300 300
301// interface.cpp 301// interface.cpp
302 302
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 @@
1#include "interfaces.h" 1#include "interfaces.h"
2 2
3#include <qcheckbox.h> 3#include <qcheckbox.h>
4#include <qfile.h> 4#include <qfile.h>
5#include <qtextstream.h> 5#include <qtextstream.h>
6#include <qregexp.h> 6#include <qregexp.h>
7 7
8// The three stanza's 8// The three stanza's
9#define AUTO "auto" 9#define AUTO "auto"
10#define IFACE "iface" 10#define IFACE "iface"
11#define MAPPING "mapping" 11#define MAPPING "mapping"
12 12
13/** 13/**
14 * Constructor. Reads in the interfaces file and then split the file up by 14 * Constructor. Reads in the interfaces file and then split the file up by
15 * the \n for interfaces variable. 15 * the \n for interfaces variable.
16 * @param useInterfacesFile if an interface file other then the default is 16 * @param useInterfacesFile if an interface file other then the default is
17 * desired to be used it should be passed in. 17 * desired to be used it should be passed in.
18 */ 18 */
19Interfaces::Interfaces(QString useInterfacesFile){ 19Interfaces::Interfaces(QString useInterfacesFile){
20 acceptedFamily.append(INTERFACES_FAMILY_INET); 20 acceptedFamily.append(INTERFACES_FAMILY_INET);
21 acceptedFamily.append(INTERFACES_FAMILY_IPX); 21 acceptedFamily.append(INTERFACES_FAMILY_IPX);
22 acceptedFamily.append(INTERFACES_FAMILY_INET6); 22 acceptedFamily.append(INTERFACES_FAMILY_INET6);
23 23
24 interfacesFile = useInterfacesFile; 24 interfacesFile = useInterfacesFile;
25 QFile file(interfacesFile); 25 QFile file(interfacesFile);
26 if (!file.open(IO_ReadOnly)){ 26 if (!file.open(IO_ReadOnly)){
27 qDebug("Interfaces: Can't open file: %s for reading.", interfacesFile.latin1() ); 27 odebug << "Interfaces: Can't open file: " << interfacesFile.latin1() << " for reading." << oendl;
28 currentIface = interfaces.end(); 28 currentIface = interfaces.end();
29 currentMapping = interfaces.end(); 29 currentMapping = interfaces.end();
30 return; 30 return;
31 } 31 }
32 QTextStream stream( &file ); 32 QTextStream stream( &file );
33 QString line; 33 QString line;
34 while ( !stream.eof() ) { 34 while ( !stream.eof() ) {
35 line += stream.readLine(); 35 line += stream.readLine();
36 line += "\n"; 36 line += "\n";
37 } 37 }
38 file.close(); 38 file.close();
39 interfaces = QStringList::split("\n", line, true); 39 interfaces = QStringList::split("\n", line, true);
40 40
41 currentIface = interfaces.end(); 41 currentIface = interfaces.end();
42 currentMapping = interfaces.end(); 42 currentMapping = interfaces.end();
43} 43}
44 44
45 45
46/** 46/**
47 * Get a list of all interfaces in the interface file. Useful for 47 * Get a list of all interfaces in the interface file. Useful for
48 * hardware that is not currently connected such as an 802.11b card 48 * hardware that is not currently connected such as an 802.11b card
49 * not plugged in, but configured for when it is plugged in. 49 * not plugged in, but configured for when it is plugged in.
50 * @return Return string list of interfaces. 50 * @return Return string list of interfaces.
51 **/ 51 **/
52QStringList Interfaces::getInterfaceList(){ 52QStringList Interfaces::getInterfaceList(){
53 QStringList list; 53 QStringList list;
54 for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) { 54 for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) {
55 QString line = (*it).simplifyWhiteSpace(); 55 QString line = (*it).simplifyWhiteSpace();
56 if(line.contains(IFACE) && line.at(0) != '#'){ 56 if(line.contains(IFACE) && line.at(0) != '#'){
57 line = line.mid(QString(IFACE).length() +1, line.length()); 57 line = line.mid(QString(IFACE).length() +1, line.length());
58 line = line.simplifyWhiteSpace(); 58 line = line.simplifyWhiteSpace();
59 int findSpace = line.find(" "); 59 int findSpace = line.find(" ");
60 if( findSpace >= 0){ 60 if( findSpace >= 0){
61 line = line.mid(0, findSpace); 61 line = line.mid(0, findSpace);
62 list.append(line); 62 list.append(line);
63 } 63 }
64 } 64 }
65 } 65 }
66 return list; 66 return list;
67} 67}
68 68
69/** 69/**
70 * Find out if interface is in an "auto" group or not. 70 * Find out if interface is in an "auto" group or not.
71 * Report any duplicates such as eth0 being in two differnt auto's 71 * Report any duplicates such as eth0 being in two differnt auto's
72 * @param interface interface to check to see if it is on or not. 72 * @param interface interface to check to see if it is on or not.
73 * @return true is interface is in auto 73 * @return true is interface is in auto
74 */ 74 */
75bool Interfaces::isAuto(const QString &interface) const { 75bool Interfaces::isAuto(const QString &interface) const {
76 QStringList autoLines = interfaces.grep(QRegExp(AUTO)); 76 QStringList autoLines = interfaces.grep(QRegExp(AUTO));
77 QStringList awi = autoLines.grep(QRegExp(interface)); 77 QStringList awi = autoLines.grep(QRegExp(interface));
78 if(awi.count() > 1) 78 if(awi.count() > 1)
79 qDebug(QString("Interfaces: Found more then auto group with interface: %1.").arg(interface).latin1()); 79 odebug << QString("Interfaces: Found more then auto group with interface: %1.").arg(interface).latin1() << oendl;
80 return awi.count() > 0; 80 return awi.count() > 0;
81} 81}
82 82
83/** 83/**
84 * Attempt to set the auto option for interface to setAuto. 84 * Attempt to set the auto option for interface to setAuto.
85 * @param interface the interface to set 85 * @param interface the interface to set
86 * @param setAuto the value to set interface to. 86 * @param setAuto the value to set interface to.
87 * @return false if already set to setAuto. 87 * @return false if already set to setAuto.
88 * */ 88 * */
89bool Interfaces::setAuto(const QString &interface, bool setAuto){ 89bool Interfaces::setAuto(const QString &interface, bool setAuto){
90 // Don't need to set it if it is already set. 90 // Don't need to set it if it is already set.
91 if(isAuto(interface) == setAuto) 91 if(isAuto(interface) == setAuto)
92 return false; 92 return false;
93 93
94 bool changed = false; 94 bool changed = false;
95 for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) { 95 for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) {
96 if((*it).contains(AUTO)){ 96 if((*it).contains(AUTO)){
97 //We know that they are not in any group so let add to this auto. 97 //We know that they are not in any group so let add to this auto.
98 if(setAuto){ 98 if(setAuto){
99 (*it) = (*it) += " " + interface; 99 (*it) = (*it) += " " + interface;
100 // Don't care to have such thins as: auto eth0 lo usb0 100 // Don't care to have such thins as: auto eth0 lo usb0
101 (*it) = (*it).simplifyWhiteSpace(); 101 (*it) = (*it).simplifyWhiteSpace();
102 changed = true; 102 changed = true;
103 break; 103 break;
104 } 104 }
105 // else see if we need to remove from this one 105 // else see if we need to remove from this one
106 else{ 106 else{
107 if((*it).contains(interface)){ 107 if((*it).contains(interface)){
108 (*it) = (*it).replace(QRegExp(interface), ""); 108 (*it) = (*it).replace(QRegExp(interface), "");
109 // if AUTO is the only thing left clear the line 109 // if AUTO is the only thing left clear the line
110 if(((*it).simplifyWhiteSpace()).replace(QRegExp(" "),"") == AUTO) 110 if(((*it).simplifyWhiteSpace()).replace(QRegExp(" "),"") == AUTO)
111 (*it) = ""; 111 (*it) = "";
112 changed = true; 112 changed = true;
113 // Don't break because we want to make sure we remove all cases. 113 // Don't break because we want to make sure we remove all cases.
114 } 114 }
115 } 115 }
116 } 116 }
117 } 117 }
118 // In the case where there is no AUTO field add one. 118 // In the case where there is no AUTO field add one.
119 if(!changed && setAuto) 119 if(!changed && setAuto)
120 interfaces.append(QString(AUTO" %1").arg(interface)); 120 interfaces.append(QString(AUTO" %1").arg(interface));
121 return true; 121 return true;
122} 122}
123 123
124/** 124/**
125 * Set the current interface to interface. This needs to be done before you 125 * Set the current interface to interface. This needs to be done before you
126 * can call getFamily(), getMethod, and get/setOption(). 126 * can call getFamily(), getMethod, and get/setOption().
127 * @param interface the name of the interface to set. All whitespace is 127 * @param interface the name of the interface to set. All whitespace is
128 * removed from the interface name. 128 * removed from the interface name.
129 * @return bool true if it is successful. 129 * @return bool true if it is successful.
130 */ 130 */
131bool Interfaces::setInterface(QString interface){ 131bool Interfaces::setInterface(QString interface){
132 interface = interface.simplifyWhiteSpace(); 132 interface = interface.simplifyWhiteSpace();
133 interface = interface.replace(QRegExp(" "), ""); 133 interface = interface.replace(QRegExp(" "), "");
134 return setStanza(IFACE, interface, currentIface); 134 return setStanza(IFACE, interface, currentIface);
135} 135}
136 136
137/** 137/**
138 * A quick helper funtion to see if the current interface is set. 138 * A quick helper funtion to see if the current interface is set.
139 * @return bool true if set, false otherwise. 139 * @return bool true if set, false otherwise.
140 */ 140 */
141bool Interfaces::isInterfaceSet() const { 141bool Interfaces::isInterfaceSet() const {
142 return (interfaces.end() != currentIface); 142 return (interfaces.end() != currentIface);
143} 143}
144 144
145/** 145/**
146 * Add a new interface of with the settings - family and method 146 * Add a new interface of with the settings - family and method
147 * @param interface the name of the interface to set. All whitespace is 147 * @param interface the name of the interface to set. All whitespace is
148 * removed from the interface name. 148 * removed from the interface name.
149 * @param family the family of this interface inet or inet, ipx or inet6 149 * @param family the family of this interface inet or inet, ipx or inet6
150 * Must of one of the families defined in interfaces.h 150 * Must of one of the families defined in interfaces.h
151 * @param method for the family. see interfaces man page for family methods. 151 * @param method for the family. see interfaces man page for family methods.
152 * @return true if successful. 152 * @return true if successful.
153 */ 153 */
154bool Interfaces::addInterface(const QString &interface, const QString &family, const QString &method){ 154bool Interfaces::addInterface(const QString &interface, const QString &family, const QString &method){
155 qDebug("Interfaces::addInterface(%s)",interface.latin1()); 155 odebug << "Interfaces::addInterface(" << interface.latin1() << ")" << oendl;
156 if(0 == acceptedFamily.contains(family)) 156 if(0 == acceptedFamily.contains(family))
157 return false; 157 return false;
158 QString newInterface = interface.simplifyWhiteSpace(); 158 QString newInterface = interface.simplifyWhiteSpace();
159 newInterface = newInterface.replace(QRegExp(" "), ""); 159 newInterface = newInterface.replace(QRegExp(" "), "");
160 interfaces.append(""); 160 interfaces.append("");
161 interfaces.append(QString(IFACE " %1 %2 %3").arg(newInterface).arg(family).arg(method)); 161 interfaces.append(QString(IFACE " %1 %2 %3").arg(newInterface).arg(family).arg(method));
162 return true; 162 return true;
163} 163}
164 164
165/** 165/**
166 * Copies interface with name interface to name newInterface 166 * Copies interface with name interface to name newInterface
167 * @param newInterface name of the new interface. 167 * @param newInterface name of the new interface.
168 * @return bool true if successful 168 * @return bool true if successful
169 */ 169 */
170bool Interfaces::copyInterface(const QString &interface, const QString &newInterface){ 170bool Interfaces::copyInterface(const QString &interface, const QString &newInterface){
171 qDebug("copy interface %s to %s", interface.latin1(), newInterface.latin1()); 171 odebug << "copy interface " << interface.latin1() << " to " << newInterface.latin1() << "" << oendl;
172 if(!setInterface(interface)) 172 if(!setInterface(interface))
173 return false; 173 return false;
174 174
175 // Store the old interface and bump past the stanza line. 175 // Store the old interface and bump past the stanza line.
176 QStringList::Iterator it = currentIface; 176 QStringList::Iterator it = currentIface;
177 it++; 177 it++;
178 178
179 // Add the new interface 179 // Add the new interface
180 bool error; 180 bool error;
181 addInterface(newInterface, getInterfaceFamily(error), getInterfaceMethod(error)); 181 addInterface(newInterface, getInterfaceFamily(error), getInterfaceMethod(error));
182 if(!setInterface(newInterface)) 182 if(!setInterface(newInterface))
183 return false; 183 return false;
184 184
185 QStringList::Iterator newIface = currentIface; 185 QStringList::Iterator newIface = currentIface;
186 newIface++; 186 newIface++;
187 187
188 // Copy all of the lines 188 // Copy all of the lines
189 for ( ; it != interfaces.end(); ++it ){ 189 for ( ; it != interfaces.end(); ++it ){
190 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO))) 190 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)))
191 break; 191 break;
192 newIface = interfaces.insert(newIface, *it); 192 newIface = interfaces.insert(newIface, *it);
193 } 193 }
194 194
195 return true; 195 return true;
196} 196}
197 197
198/** 198/**
199 * Remove the currently selected interface and all of its options. 199 * Remove the currently selected interface and all of its options.
200 * @return bool if successful or not. 200 * @return bool if successful or not.
201 */ 201 */
202bool Interfaces::removeInterface(){ 202bool Interfaces::removeInterface(){
203 return removeStanza(currentIface); 203 return removeStanza(currentIface);
204} 204}
205 205
206/** 206/**
207 * Gets the hardware name of the interface that is currently selected. 207 * Gets the hardware name of the interface that is currently selected.
208 * @return QString name of the hardware interface (eth0, usb2, wlan1...). 208 * @return QString name of the hardware interface (eth0, usb2, wlan1...).
209 * @param error set to true if any error occurs, false otherwise. 209 * @param error set to true if any error occurs, false otherwise.
210 */ 210 */
211QString Interfaces::getInterfaceName(bool &error){ 211QString Interfaces::getInterfaceName(bool &error){
212 if(currentIface == interfaces.end()){ 212 if(currentIface == interfaces.end()){
213 error = true; 213 error = true;
214 return QString(); 214 return QString();
215 } 215 }
216 QString line = (*currentIface); 216 QString line = (*currentIface);
217 line = line.mid(QString(IFACE).length() +1, line.length()); 217 line = line.mid(QString(IFACE).length() +1, line.length());
218 line = line.simplifyWhiteSpace(); 218 line = line.simplifyWhiteSpace();
219 int findSpace = line.find(" "); 219 int findSpace = line.find(" ");
220 if( findSpace < 0){ 220 if( findSpace < 0){
221 error = true; 221 error = true;
222 return QString(); 222 return QString();
223 } 223 }
224 error = false; 224 error = false;
225 return line.mid(0, findSpace); 225 return line.mid(0, findSpace);
226} 226}
227 227
228/** 228/**
229 * Gets the family name of the interface that is currently selected. 229 * Gets the family name of the interface that is currently selected.
230 * @return QString name of the family (inet, inet6, ipx). 230 * @return QString name of the family (inet, inet6, ipx).
231 * @param error set to true if any error occurs, false otherwise. 231 * @param error set to true if any error occurs, false otherwise.
232 */ 232 */
233QString Interfaces::getInterfaceFamily(bool &error){ 233QString Interfaces::getInterfaceFamily(bool &error){
234 QString name = getInterfaceName(error); 234 QString name = getInterfaceName(error);
235 if(error) 235 if(error)
236 return QString(); 236 return QString();
237 QString line = (*currentIface); 237 QString line = (*currentIface);
238 line = line.mid(QString(IFACE).length() +1, line.length()); 238 line = line.mid(QString(IFACE).length() +1, line.length());
239 line = line.mid(name.length()+1, line.length()); 239 line = line.mid(name.length()+1, line.length());
240 line = line.simplifyWhiteSpace(); 240 line = line.simplifyWhiteSpace();
241 int findSpace = line.find(" "); 241 int findSpace = line.find(" ");
242 if( findSpace < 0){ 242 if( findSpace < 0){
243 error = true; 243 error = true;
244 return QString(); 244 return QString();
245 } 245 }
246 error = false; 246 error = false;
247 return line.mid(0, findSpace); 247 return line.mid(0, findSpace);
248} 248}
249 249
250/** 250/**
251 * Gets the method of the interface that is currently selected. 251 * Gets the method of the interface that is currently selected.
252 * @return QString name of the method such as staic or dhcp. 252 * @return QString name of the method such as staic or dhcp.
253 * See the man page of interfaces for possible methods depending on the family. 253 * See the man page of interfaces for possible methods depending on the family.
254 * @param error set to true if any error occurs, false otherwise. 254 * @param error set to true if any error occurs, false otherwise.
255 */ 255 */
256QString Interfaces::getInterfaceMethod(bool &error){ 256QString Interfaces::getInterfaceMethod(bool &error){
257 QString name = getInterfaceName(error); 257 QString name = getInterfaceName(error);
258 if(error) 258 if(error)
259 return QString(); 259 return QString();
260 QString family = getInterfaceFamily(error); 260 QString family = getInterfaceFamily(error);
261 if(error) 261 if(error)
262 return QString(); 262 return QString();
263 QString line = (*currentIface); 263 QString line = (*currentIface);
264 line = line.mid(QString(IFACE).length()+1, line.length()); 264 line = line.mid(QString(IFACE).length()+1, line.length());
265 line = line.mid(name.length()+1, line.length()); 265 line = line.mid(name.length()+1, line.length());
266 line = line.mid(family.length()+1, line.length()); 266 line = line.mid(family.length()+1, line.length());
267 line = line.simplifyWhiteSpace(); 267 line = line.simplifyWhiteSpace();
268 error = false; 268 error = false;
269 return line; 269 return line;
270} 270}
271 271
272/** 272/**
273 * Sets the interface name to newName. 273 * Sets the interface name to newName.
274 * @param newName the new name of the interface. All whitespace is removed. 274 * @param newName the new name of the interface. All whitespace is removed.
275 * @return bool true if successful. 275 * @return bool true if successful.
276 */ 276 */
277bool Interfaces::setInterfaceName(const QString &newName){ 277bool Interfaces::setInterfaceName(const QString &newName){
278 qDebug("setInterfaceName %s", newName.latin1()); 278 odebug << "setInterfaceName " << newName.latin1() << "" << oendl;
279 if(currentIface == interfaces.end()) 279 if(currentIface == interfaces.end())
280 return false; 280 return false;
281 QString name = newName.simplifyWhiteSpace(); 281 QString name = newName.simplifyWhiteSpace();
282 name = name.replace(QRegExp(" "), ""); 282 name = name.replace(QRegExp(" "), "");
283 bool returnValue = false; 283 bool returnValue = false;
284 QString tmp = QString("iface %1 %2 %3").arg(name).arg(getInterfaceFamily(returnValue)).arg(getInterfaceMethod(returnValue)); 284 QString tmp = QString("iface %1 %2 %3").arg(name).arg(getInterfaceFamily(returnValue)).arg(getInterfaceMethod(returnValue));
285 qDebug("setting %s",tmp.latin1()); 285 odebug << "setting " << tmp.latin1() << "" << oendl;
286 286
287 (*currentIface) = tmp; 287 (*currentIface) = tmp;
288 return !returnValue; 288 return !returnValue;
289} 289}
290 290
291/** 291/**
292 * Sets the interface family to newName. 292 * Sets the interface family to newName.
293 * @param newName the new name of the interface. Must be one of the families 293 * @param newName the new name of the interface. Must be one of the families
294 * defined in the interfaces.h file. 294 * defined in the interfaces.h file.
295 * @return bool true if successful. 295 * @return bool true if successful.
296 */ 296 */
297bool Interfaces::setInterfaceFamily(const QString &newName){ 297bool Interfaces::setInterfaceFamily(const QString &newName){
298 if(currentIface == interfaces.end()) 298 if(currentIface == interfaces.end())
299 return false; 299 return false;
300 if(acceptedFamily.contains(newName)==0) 300 if(acceptedFamily.contains(newName)==0)
301 return false; 301 return false;
302 bool returnValue = false; 302 bool returnValue = false;
303 (*currentIface) = QString("iface %1 %2 %3").arg(getInterfaceName(returnValue)).arg(newName).arg(getInterfaceMethod(returnValue)); 303 (*currentIface) = QString("iface %1 %2 %3").arg(getInterfaceName(returnValue)).arg(newName).arg(getInterfaceMethod(returnValue));
304 return !returnValue; 304 return !returnValue;
305} 305}
306 306
307/** 307/**
308 * Sets the interface method to newName 308 * Sets the interface method to newName
309 * @param newName the new name of the interface 309 * @param newName the new name of the interface
310 * @return bool true if successful. 310 * @return bool true if successful.
311 */ 311 */
312bool Interfaces::setInterfaceMethod(const QString &newName){ 312bool Interfaces::setInterfaceMethod(const QString &newName){
313 if(currentIface == interfaces.end()) 313 if(currentIface == interfaces.end())
314 return false; 314 return false;
315 bool returnValue = false; 315 bool returnValue = false;
316 (*currentIface) = QString("iface %1 %2 %3").arg(getInterfaceName(returnValue)).arg(getInterfaceFamily(returnValue)).arg(newName); 316 (*currentIface) = QString("iface %1 %2 %3").arg(getInterfaceName(returnValue)).arg(getInterfaceFamily(returnValue)).arg(newName);
317 return !returnValue; 317 return !returnValue;
318} 318}
319 319
320/** 320/**
321 * Get a value for an option in the currently selected interface. For example 321 * Get a value for an option in the currently selected interface. For example
322 * calling getInterfaceOption("address") on the following stanza would 322 * calling getInterfaceOption("address") on the following stanza would
323 * return 192.168.1.1. 323 * return 192.168.1.1.
324 * iface eth0 static 324 * iface eth0 static
325 * address 192.168.1.1 325 * address 192.168.1.1
326 * @param option the options to get the value. 326 * @param option the options to get the value.
327 * @param error set to true if any error occurs, false otherwise. 327 * @param error set to true if any error occurs, false otherwise.
328 * @return QString the options value. QString::null if error == true 328 * @return QString the options value. QString::null if error == true
329 */ 329 */
330QString Interfaces::getInterfaceOption(const QString &option, bool &error){ 330QString Interfaces::getInterfaceOption(const QString &option, bool &error){
331 return getOption(currentIface, option, error); 331 return getOption(currentIface, option, error);
332} 332}
333 333
334/** 334/**
335 * Set a value for an option in the currently selected interface. If option 335 * Set a value for an option in the currently selected interface. If option
336 * doesn't exist then it is added along with the value. 336 * doesn't exist then it is added along with the value.
337 * If value isEmpty() then we will remove the option 337 * If value isEmpty() then we will remove the option
338 * 338 *
339 * @param option the options to set the value. 339 * @param option the options to set the value.
340 * @param value the value that option should be set to. 340 * @param value the value that option should be set to.
341 * @param error set to true if any error occurs, false otherwise. 341 * @param error set to true if any error occurs, false otherwise.
342 * @return QString the options value. QString::null if error == true 342 * @return QString the options value. QString::null if error == true
343 */ 343 */
344bool Interfaces::setInterfaceOption(const QString &option, const QString &value){ 344bool Interfaces::setInterfaceOption(const QString &option, const QString &value){
345 if( value.stripWhiteSpace().isEmpty() ) 345 if( value.stripWhiteSpace().isEmpty() )
346 return removeInterfaceOption( option ); 346 return removeInterfaceOption( option );
347 347
348 qDebug("iface >%s< option >%s< value >%s<", (*currentIface).latin1(), option.latin1(),value.latin1()); 348 odebug << "iface >" << (*currentIface).latin1() << "< option >" << option.latin1() << "< value >" << value.latin1() << "<" << oendl;
349 return setOption(currentIface, option, value); 349 return setOption(currentIface, option, value);
350} 350}
351 351
352/** 352/**
353 * Removes a value for an option in the currently selected interface. 353 * Removes a value for an option in the currently selected interface.
354 * @param option the options to set the value. 354 * @param option the options to set the value.
355 * @param error set to true if any error occurs, false otherwise. 355 * @param error set to true if any error occurs, false otherwise.
356 * @return QString the options value. QString::null if error == true 356 * @return QString the options value. QString::null if error == true
357 */ 357 */
358bool Interfaces::removeInterfaceOption(const QString &option){ 358bool Interfaces::removeInterfaceOption(const QString &option){
359 return removeOption(currentIface, option); 359 return removeOption(currentIface, option);
360} 360}
361 361
362/** 362/**
363 * Removes a value for an option in the currently selected interface. 363 * Removes a value for an option in the currently selected interface.
364 * @param option the options to set the value. 364 * @param option the options to set the value.
365 * @param value the value that option should be set to. 365 * @param value the value that option should be set to.
366 * @param error set to true if any error occurs, false otherwise. 366 * @param error set to true if any error occurs, false otherwise.
367 * @return QString the options value. QString::null if error == true 367 * @return QString the options value. QString::null if error == true
368 */ 368 */
369bool Interfaces::removeInterfaceOption(const QString &option, const QString &value){ 369bool Interfaces::removeInterfaceOption(const QString &option, const QString &value){
370 return removeOption(currentIface, option, value); 370 return removeOption(currentIface, option, value);
371} 371}
372 372
373/** 373/**
374 * Removes all of the options from the currently selected interface. 374 * Removes all of the options from the currently selected interface.
375 * @return bool error if if successful 375 * @return bool error if if successful
376 */ 376 */
377bool Interfaces::removeAllInterfaceOptions(){ 377bool Interfaces::removeAllInterfaceOptions(){
378 return removeAllOptions(currentIface); 378 return removeAllOptions(currentIface);
379} 379}
380 380
381/** 381/**
382 * Set the current map to interface's map. This needs to be done before you 382 * Set the current map to interface's map. This needs to be done before you
383 * can call addMapping(), set/getMap(), and get/setScript(). 383 * can call addMapping(), set/getMap(), and get/setScript().
384 * @param interface the name of the interface to set. All whitespace is 384 * @param interface the name of the interface to set. All whitespace is
385 * removed from the interface name. 385 * removed from the interface name.
386 * @return bool true if it is successful. 386 * @return bool true if it is successful.
387 */ 387 */
388bool Interfaces::setMapping(const QString &interface){ 388bool Interfaces::setMapping(const QString &interface){
389 QString interfaceName = interface.simplifyWhiteSpace(); 389 QString interfaceName = interface.simplifyWhiteSpace();
390 interfaceName = interfaceName.replace(QRegExp(" "), ""); 390 interfaceName = interfaceName.replace(QRegExp(" "), "");
391 return setStanza(MAPPING, interfaceName, currentMapping); 391 return setStanza(MAPPING, interfaceName, currentMapping);
392} 392}
393 393
394/** 394/**
395 * Adds a new Mapping to the interfaces file with interfaces. 395 * Adds a new Mapping to the interfaces file with interfaces.
396 * @param interface the name(s) of the interfaces to set to this mapping 396 * @param interface the name(s) of the interfaces to set to this mapping
397 */ 397 */
398void Interfaces::addMapping(const QString &option){ 398void Interfaces::addMapping(const QString &option){
399 interfaces.append(""); 399 interfaces.append("");
400 interfaces.append(QString(MAPPING " %1").arg(option)); 400 interfaces.append(QString(MAPPING " %1").arg(option));
401} 401}
402 402
403/** 403/**
404 * Remove the currently selected map and all of its options. 404 * Remove the currently selected map and all of its options.
405 * @return bool if successful or not. 405 * @return bool if successful or not.
406 */ 406 */
407bool Interfaces::removeMapping(){ 407bool Interfaces::removeMapping(){
408 return removeStanza(currentMapping); 408 return removeStanza(currentMapping);
409} 409}
410 410
411/** 411/**
412 * Set a map option within a mapping. 412 * Set a map option within a mapping.
413 * @param map map to use 413 * @param map map to use
414 * @param value value to go with map 414 * @param value value to go with map
415 * @return bool true if it is successful. 415 * @return bool true if it is successful.
416 */ 416 */
417bool Interfaces::setMap(const QString &map, const QString &value){ 417bool Interfaces::setMap(const QString &map, const QString &value){
418 return setOption(currentMapping, map, value); 418 return setOption(currentMapping, map, value);
419} 419}
420 420
421/** 421/**
422 * Removes a map option within a mapping. 422 * Removes a map option within a mapping.
423 * @param map map to use 423 * @param map map to use
424 * @param value value to go with map 424 * @param value value to go with map
425 * @return bool true if it is successful. 425 * @return bool true if it is successful.
426 */ 426 */
427bool Interfaces::removeMap(const QString &map, const QString &value){ 427bool Interfaces::removeMap(const QString &map, const QString &value){
428 return removeOption(currentMapping, map, value); 428 return removeOption(currentMapping, map, value);
429} 429}
430 430
431/** 431/**
432 * Get a map value within a mapping. 432 * Get a map value within a mapping.
433 * @param map map to get value of 433 * @param map map to get value of
434 * @param bool true if it is successful. 434 * @param bool true if it is successful.
435 * @return value that goes to the map 435 * @return value that goes to the map
436 */ 436 */
437QString Interfaces::getMap(const QString &map, bool &error){ 437QString Interfaces::getMap(const QString &map, bool &error){
438 return getOption(currentMapping, map, error); 438 return getOption(currentMapping, map, error);
439} 439}
440 440
441/** 441/**
442 * Sets a script value of the current mapping to argument. 442 * Sets a script value of the current mapping to argument.
443 * @param argument the script name. 443 * @param argument the script name.
444 * @return true if successful. 444 * @return true if successful.
445 */ 445 */
446bool Interfaces::setScript(const QString &argument){ 446bool Interfaces::setScript(const QString &argument){
447 return setOption(currentMapping, "script", argument); 447 return setOption(currentMapping, "script", argument);
448} 448}
449 449
450/** 450/**
451 * @param error true if could not retrieve the current script argument. 451 * @param error true if could not retrieve the current script argument.
452 * @return QString the argument of the script for the current mapping. 452 * @return QString the argument of the script for the current mapping.
453 */ 453 */
454QString Interfaces::getScript(bool &error){ 454QString Interfaces::getScript(bool &error){
455 return getOption(currentMapping, "script", error); 455 return getOption(currentMapping, "script", error);
456} 456}
457 457
458 458
459 459
460/** 460/**
461 * Helper function used to parse through the QStringList and put pointers in 461 * Helper function used to parse through the QStringList and put pointers in
462 * the correct place. 462 * the correct place.
463 * @param stanza The stanza (auto, iface, mapping) to look for. 463 * @param stanza The stanza (auto, iface, mapping) to look for.
464 * @param option string that must be in the stanza's main line. 464 * @param option string that must be in the stanza's main line.
465 * @param interator interator to place at location of stanza if successful. 465 * @param interator interator to place at location of stanza if successful.
466 * @return bool true if the stanza is found. 466 * @return bool true if the stanza is found.
467 */ 467 */
468bool Interfaces::setStanza(const QString &stanza, const QString &option, QStringList::Iterator &iterator){ 468bool Interfaces::setStanza(const QString &stanza, const QString &option, QStringList::Iterator &iterator){
469 bool found = false; 469 bool found = false;
470 iterator = interfaces.end(); 470 iterator = interfaces.end();
471 for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) { 471 for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) {
472 QString line = (*it).simplifyWhiteSpace(); 472 QString line = (*it).simplifyWhiteSpace();
473 if(line.contains(stanza) && line.contains(option) && line.at(0) != '#'){ 473 if(line.contains(stanza) && line.contains(option) && line.at(0) != '#'){
474 uint point = line.find(option); 474 uint point = line.find(option);
475 bool valid = true; 475 bool valid = true;
476 if(point > 0){ 476 if(point > 0){
477 // There are more chars in the line. check +1 477 // There are more chars in the line. check +1
478 if(line.at(point-1) != ' ') 478 if(line.at(point-1) != ' ')
479 valid = false; 479 valid = false;
480 } 480 }
481 point += option.length(); 481 point += option.length();
482 if(point < line.length()-1){ 482 if(point < line.length()-1){
483 // There are more chars in the line. check -1 483 // There are more chars in the line. check -1
484 if(line.at(point) != ' ') 484 if(line.at(point) != ' ')
485 valid = false; 485 valid = false;
486 } 486 }
487 if(valid){ 487 if(valid){
488 if(found == true){ 488 if(found == true){
489 qDebug(QString("Interfaces: Found multiple stanza's for search: %1 %2").arg(stanza).arg(option).latin1()); 489 odebug << QString("Interfaces: Found multiple stanza's for search: %1 %2").arg(stanza).arg(option).latin1() << oendl;
490 } 490 }
491 found = true; 491 found = true;
492 iterator = it; 492 iterator = it;
493 } 493 }
494 } 494 }
495 } 495 }
496 return found; 496 return found;
497} 497}
498 498
499/** 499/**
500 * Sets a value of an option in a stanza 500 * Sets a value of an option in a stanza
501 * @param start the start of the stanza 501 * @param start the start of the stanza
502 * @param option the option to use when setting value. 502 * @param option the option to use when setting value.
503 * @return bool true if successful, false otherwise. 503 * @return bool true if successful, false otherwise.
504 */ 504 */
505bool Interfaces::setOption(const QStringList::Iterator &start, const QString &option, const QString &value){ 505bool Interfaces::setOption(const QStringList::Iterator &start, const QString &option, const QString &value){
506 if(start == interfaces.end()) 506 if(start == interfaces.end())
507 return false; 507 return false;
508 qDebug("setting option"); 508 odebug << "setting option" << oendl;
509 bool found = false; 509 bool found = false;
510 bool replaced = false; 510 bool replaced = false;
511 QStringList::Iterator insertAt = NULL; 511 QStringList::Iterator insertAt = NULL;
512 for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) { 512 for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) {
513 qDebug(" Interfaces::setOption got line >%s<",(*it).latin1()); 513 odebug << " Interfaces::setOption got line >" << (*it).latin1() << "<" << oendl;
514 // FIXME: was not completly stupid just wrong sice all options got inserted bevore the iface line 514 // FIXME: was not completly stupid just wrong sice all options got inserted bevore the iface line
515 // but since it works with an empty interfaces file I (tille) will not do anything more 515 // but since it works with an empty interfaces file I (tille) will not do anything more
516 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) ){ 516 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) ){
517 if (found) break; 517 if (found) break;
518// && it != start){ 518// && it != start){
519// if(!found && value != ""){ 519// if(!found && value != ""){
520// // Got to the end of the stanza without finding it, so append it. 520// // Got to the end of the stanza without finding it, so append it.
521// qDebug(" Got to the end of the stanza without finding it, so append it."); 521// odebug << " Got to the end of the stanza without finding it, so append it." << oendl;
522// interfaces.insert(--it, QString("\t%1 %2").arg(option).arg(value)); 522// interfaces.insert(--it, QString("\t%1 %2").arg(option).arg(value));
523// } 523// }
524 qDebug("found 1"); 524 odebug << "found 1" << oendl;
525// interfaces.insert(++it, QString("\t%1 %2").arg(option).arg(value)); 525// interfaces.insert(++it, QString("\t%1 %2").arg(option).arg(value));
526 found = true; 526 found = true;
527 insertAt = it; 527 insertAt = it;
528 528
529 } 529 }
530 if((*it).contains(option) && it != start && (*it).at(0) != '#'){ 530 if((*it).contains(option) && it != start && (*it).at(0) != '#'){
531 // Found it in stanza so replace it. 531 // Found it in stanza so replace it.
532 qDebug("found 2"); 532 odebug << "found 2" << oendl;
533 if(found) 533 if(found)
534 qDebug(QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1()); 534 odebug << QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1() << oendl;
535 found = true; 535 found = true;
536 replaced = true; 536 replaced = true;
537 (*it) = QString("\t%1 %2").arg(option).arg(value); 537 (*it) = QString("\t%1 %2").arg(option).arg(value);
538 } 538 }
539 } 539 }
540 if(!found){ 540 if(!found){
541 qDebug("! found insert anyway"); 541 odebug << "! found insert anyway" << oendl;
542 QStringList::Iterator p = start; 542 QStringList::Iterator p = start;
543 interfaces.insert(++p, QString("\t%1 %2").arg(option).arg(value)); 543 interfaces.insert(++p, QString("\t%1 %2").arg(option).arg(value));
544 found = true; 544 found = true;
545 } 545 }
546 546
547 if(found && !replaced){ 547 if(found && !replaced){
548 qDebug("found iface but not the option so insert it here..."); 548 odebug << "found iface but not the option so insert it here..." << oendl;
549 interfaces.insert(++insertAt, QString("\t%1 %2").arg(option).arg(value)); 549 interfaces.insert(++insertAt, QString("\t%1 %2").arg(option).arg(value));
550 } 550 }
551 return found; 551 return found;
552} 552}
553 553
554/** 554/**
555 * Removes a stanza and all of its options 555 * Removes a stanza and all of its options
556 * @param stanza the stanza to remove 556 * @param stanza the stanza to remove
557 * @return bool true if successful. 557 * @return bool true if successful.
558 */ 558 */
559bool Interfaces::removeStanza(QStringList::Iterator &stanza){ 559bool Interfaces::removeStanza(QStringList::Iterator &stanza){
560 if(stanza == interfaces.end()) 560 if(stanza == interfaces.end())
561 return false; 561 return false;
562 (*stanza) = ""; 562 (*stanza) = "";
563 return removeAllOptions(stanza); 563 return removeAllOptions(stanza);
564} 564}
565 565
566/** 566/**
567 * Removes a option in a stanza 567 * Removes a option in a stanza
568 * @param start the start of the stanza 568 * @param start the start of the stanza
569 * @param option the option to remove 569 * @param option the option to remove
570 * @return bool true if successful, false otherwise. 570 * @return bool true if successful, false otherwise.
571 */ 571 */
572bool Interfaces::removeOption(const QStringList::Iterator &start, const QString &option){ 572bool Interfaces::removeOption(const QStringList::Iterator &start, const QString &option){
573 if(start == interfaces.end()) 573 if(start == interfaces.end())
574 return false; 574 return false;
575 575
576 bool found = false; 576 bool found = false;
577 for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) { 577 for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) {
578 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){ 578 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){
579 // got to the end without finding it 579 // got to the end without finding it
580 break; 580 break;
581 } 581 }
582 if((*it).contains(option) && it != start && (*it).at(0) != '#'){ 582 if((*it).contains(option) && it != start && (*it).at(0) != '#'){
583 // Found it in stanza so replace it. 583 // Found it in stanza so replace it.
584 if(found) 584 if(found)
585 qDebug(QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1()); 585 odebug << QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1() << oendl;
586 found = true; 586 found = true;
587 it = interfaces.remove( it ); // we really want to remove the line 587 it = interfaces.remove( it ); // we really want to remove the line
588 --it; // we do ++it later in the head of the for loop 588 --it; // we do ++it later in the head of the for loop
589 } 589 }
590 } 590 }
591 return found; 591 return found;
592} 592}
593 593
594/** 594/**
595 * Removes a option in a stanza 595 * Removes a option in a stanza
596 * @param start the start of the stanza 596 * @param start the start of the stanza
597 * @param option the option to use when setting value. 597 * @param option the option to use when setting value.
598 * @return bool true if successful, false otherwise. 598 * @return bool true if successful, false otherwise.
599 */ 599 */
600bool Interfaces::removeOption(const QStringList::Iterator &start, const QString &option, const QString &value){ 600bool Interfaces::removeOption(const QStringList::Iterator &start, const QString &option, const QString &value){
601 if(start == interfaces.end()) 601 if(start == interfaces.end())
602 return false; 602 return false;
603 603
604 bool found = false; 604 bool found = false;
605 for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) { 605 for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) {
606 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){ 606 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){
607 // got to the end without finding it 607 // got to the end without finding it
608 break; 608 break;
609 } 609 }
610 if((*it).contains(option) && (*it).contains(value) && it != start && (*it).at(0) != '#'){ 610 if((*it).contains(option) && (*it).contains(value) && it != start && (*it).at(0) != '#'){
611 // Found it in stanza so replace it. 611 // Found it in stanza so replace it.
612 if(found) 612 if(found)
613 qDebug(QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1()); 613 odebug << QString("Interfaces: Set Options found more then one value for option: %1 in stanza: %1").arg(option).arg((*start)).latin1() << oendl;
614 found = true; 614 found = true;
615 it = interfaces.remove( it ); // we really want to remove the line 615 it = interfaces.remove( it ); // we really want to remove the line
616 --it; // we do ++it later in the head of the for loop 616 --it; // we do ++it later in the head of the for loop
617 } 617 }
618 } 618 }
619 return found; 619 return found;
620} 620}
621 621
622/** 622/**
623 * Removes all options in a stanza 623 * Removes all options in a stanza
624 * @param start the start of the stanza 624 * @param start the start of the stanza
625 * @return bool true if successful, false otherwise. 625 * @return bool true if successful, false otherwise.
626 */ 626 */
627bool Interfaces::removeAllOptions(const QStringList::Iterator &start){ 627bool Interfaces::removeAllOptions(const QStringList::Iterator &start){
628 if(start == interfaces.end()) 628 if(start == interfaces.end())
629 return false; 629 return false;
630 630
631 QStringList::Iterator it = start; 631 QStringList::Iterator it = start;
632 it = ++it; 632 it = ++it;
633 for (; it != interfaces.end(); ++it ) { 633 for (; it != interfaces.end(); ++it ) {
634 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){ 634 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){
635 break; 635 break;
636 } 636 }
637 it = interfaces.remove(it); 637 it = interfaces.remove(it);
638 it = --it; 638 it = --it;
639 } 639 }
640 // Leave a space between this interface and the next. 640 // Leave a space between this interface and the next.
641 interfaces.insert(it, QString("")); 641 interfaces.insert(it, QString(""));
642 return true; 642 return true;
643} 643}
644 644
645/** 645/**
646 * Gets a value of an option in a stanza 646 * Gets a value of an option in a stanza
647 * @param start the start of the stanza 647 * @param start the start of the stanza
648 * @param option the option to use when getting the value. 648 * @param option the option to use when getting the value.
649 * @param bool true if errors false otherwise. 649 * @param bool true if errors false otherwise.
650 * @return QString the value of option QString::null() if error == true. 650 * @return QString the value of option QString::null() if error == true.
651 */ 651 */
652QString Interfaces::getOption(const QStringList::Iterator &start, const QString &option, bool &error){ 652QString Interfaces::getOption(const QStringList::Iterator &start, const QString &option, bool &error){
653 if(start == interfaces.end()){ 653 if(start == interfaces.end()){
654 error = false; 654 error = false;
655 return QString(); 655 return QString();
656 } 656 }
657 657
658 QString value; 658 QString value;
659 bool found = false; 659 bool found = false;
660 for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) { 660 for ( QStringList::Iterator it = start; it != interfaces.end(); ++it ) {
661 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){ 661 if(((*it).contains(IFACE) || (*it).contains(MAPPING) || (*it).contains(AUTO)) && it != start){
662 break; 662 break;
663 } 663 }
664 if((*it).contains(option) && (*it).at(0) != '#'){ 664 if((*it).contains(option) && (*it).at(0) != '#'){
665 if(found) 665 if(found)
666 qDebug(QString("Interfaces: getOption found more then one value: %1 for option: %2 in stanza %3").arg((*it)).arg(option).arg((*start)).latin1()); 666 odebug << QString("Interfaces: getOption found more then one value: %1 for option: %2 in stanza %3").arg((*it)).arg(option).arg((*start)).latin1() << oendl;
667 found = true; 667 found = true;
668 QString line = (*it).simplifyWhiteSpace(); 668 QString line = (*it).simplifyWhiteSpace();
669 int space = line.find(" ", option.length()); 669 int space = line.find(" ", option.length());
670 if(space != -1){ 670 if(space != -1){
671 value = line.mid(space+1, line.length()); 671 value = line.mid(space+1, line.length());
672 break; 672 break;
673 } 673 }
674 } 674 }
675 } 675 }
676 error = !found; 676 error = !found;
677 return value; 677 return value;
678} 678}
679 679
680/** 680/**
681 * Write out the interfaces file to the file passed into the constructor. 681 * Write out the interfaces file to the file passed into the constructor.
682 * Removes any excess blank lines over 1 line long. 682 * Removes any excess blank lines over 1 line long.
683 * @return bool true if successful, false if not. 683 * @return bool true if successful, false if not.
684 */ 684 */
685bool Interfaces::write(){ 685bool Interfaces::write(){
686 QFile::remove(interfacesFile); 686 QFile::remove(interfacesFile);
687 QFile file(interfacesFile); 687 QFile file(interfacesFile);
688 688
689 if (!file.open(IO_ReadWrite)){ 689 if (!file.open(IO_ReadWrite)){
690 qDebug(QString("Interfaces: Can't open file: %1 for writing.").arg(interfacesFile).latin1()); 690 odebug << QString("Interfaces: Can't open file: %1 for writing.").arg(interfacesFile).latin1() << oendl;
691 return false; 691 return false;
692 } 692 }
693 QTextStream stream( &file ); 693 QTextStream stream( &file );
694 int whiteSpaceCount = 0; 694 int whiteSpaceCount = 0;
695 for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) { 695 for ( QStringList::Iterator it = interfaces.begin(); it != interfaces.end(); ++it ) {
696 QString line = (*it).simplifyWhiteSpace(); 696 QString line = (*it).simplifyWhiteSpace();
697 line = line.replace(QRegExp(" "),""); 697 line = line.replace(QRegExp(" "),"");
698 if(line.length() == 0) 698 if(line.length() == 0)
699 whiteSpaceCount++; 699 whiteSpaceCount++;
700 else 700 else
701 whiteSpaceCount = 0; 701 whiteSpaceCount = 0;
702 if(whiteSpaceCount < 2){ 702 if(whiteSpaceCount < 2){
703 qDebug((*it).latin1()); 703 odebug << (*it).latin1() << oendl;
704 stream << (*it) << '\n'; 704 stream << (*it) << '\n';
705 } 705 }
706 } 706 }
707 file.close(); 707 file.close();
708 return true; 708 return true;
709} 709}
710 710
711// interfaces.cpp 711// interfaces.cpp
712 712
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 @@
1#include "interfacesetupimp.h" 1#include "interfacesetupimp.h"
2#include "interface.h" 2#include "interface.h"
3 3
4#include <qcheckbox.h> 4#include <qcheckbox.h>
5#include <qlineedit.h> 5#include <qlineedit.h>
6#include <qspinbox.h> 6#include <qspinbox.h>
7#include <qgroupbox.h> 7#include <qgroupbox.h>
8#include <qlabel.h> 8#include <qlabel.h>
9 9
10#include <qmessagebox.h> 10#include <qmessagebox.h>
11 11
12#include <opie2/oprocess.h> 12#include <opie2/oprocess.h>
13 13
14#ifdef QWS 14#ifdef QWS
15#include <opie2/owait.h> 15#include <opie2/owait.h>
16#include <qpe/global.h> 16#include <qpe/global.h>
17#include <qapplication.h> 17#include <qapplication.h>
18#endif 18#endif
19 19
20#define DNSSCRIPT "changedns" 20#define DNSSCRIPT "changedns"
21 21
22/** 22/**
23 * Constuctor. Set up the connection. A profile must be set. 23 * Constuctor. Set up the connection. A profile must be set.
24 */ 24 */
25using namespace Opie::Ui; 25using namespace Opie::Ui;
26using namespace Opie::Core; 26using namespace Opie::Core;
27InterfaceSetupImp::InterfaceSetupImp(QWidget* parent, const char* name, Interface *i, Interfaces *j, WFlags fl) : InterfaceSetup(parent, name, fl), interface(i), interfaces(j), delInterfaces(false){ 27InterfaceSetupImp::InterfaceSetupImp(QWidget* parent, const char* name, Interface *i, Interfaces *j, WFlags fl) : InterfaceSetup(parent, name, fl), interface(i), interfaces(j), delInterfaces(false){
28 if (j == 0) { 28 if (j == 0) {
29 delInterfaces = true; 29 delInterfaces = true;
30 interfaces = new Interfaces; 30 interfaces = new Interfaces;
31 } 31 }
32} 32}
33 33
34/** 34/**
35 * Destructor 35 * Destructor
36 */ 36 */
37InterfaceSetupImp::~InterfaceSetupImp(){ 37InterfaceSetupImp::~InterfaceSetupImp(){
38 if(delInterfaces) { 38 if(delInterfaces) {
39 delete interfaces; 39 delete interfaces;
40 } 40 }
41} 41}
42 42
43/** 43/**
44 * Save the current settings, then write out the interfaces file and close. 44 * Save the current settings, then write out the interfaces file and close.
45 */ 45 */
46bool InterfaceSetupImp::saveChanges(){ 46bool InterfaceSetupImp::saveChanges(){
47 bool error; 47 bool error;
48 QString iface = interfaces->getInterfaceName(error); 48 QString iface = interfaces->getInterfaceName(error);
49 qDebug("InterfaceSetupImp::saveChanges saves interface %s", iface.latin1() ); 49 odebug << "InterfaceSetupImp::saveChanges saves interface " << iface.latin1() << "" << oendl;
50 if(!saveSettings()) 50 if(!saveSettings())
51 return false; 51 return false;
52 52
53 interfaces->write(); 53 interfaces->write();
54 54
55 if (interface->getStatus()) { 55 if (interface->getStatus()) {
56 QString ifup; 56 QString ifup;
57 ifup += "ifdown "; 57 ifup += "ifdown ";
58 ifup += iface; 58 ifup += iface;
59 ifup += "; ifup "; 59 ifup += "; ifup ";
60 ifup += iface; 60 ifup += iface;
61 ifup += ";"; 61 ifup += ";";
62 62
63 OProcess restart; 63 OProcess restart;
64 restart << "sh"; 64 restart << "sh";
65 restart << "-c"; 65 restart << "-c";
66 restart << ifup; 66 restart << ifup;
67 67
68 OWait *owait = new OWait(); 68 OWait *owait = new OWait();
69 Global::statusMessage( tr( "Restarting interface" ) ); 69 Global::statusMessage( tr( "Restarting interface" ) );
70 70
71 owait->show(); 71 owait->show();
72 qApp->processEvents(); 72 qApp->processEvents();
73 73
74 if (!restart.start(OProcess::Block, OProcess::NoCommunication) ) { 74 if (!restart.start(OProcess::Block, OProcess::NoCommunication) ) {
75 qWarning("unstable to spawn ifdown/ifup"); 75 owarn << "unstable to spawn ifdown/ifup" << oendl;
76 } 76 }
77 77
78 owait->hide(); 78 owait->hide();
79 delete owait; 79 delete owait;
80 80
81 interface->refresh(); 81 interface->refresh();
82 } 82 }
83 return true; 83 return true;
84} 84}
85 85
86/** 86/**
87 * Save the settings for the current Interface. 87 * Save the settings for the current Interface.
88 * @return bool true if successful, false otherwise 88 * @return bool true if successful, false otherwise
89 */ 89 */
90bool InterfaceSetupImp::saveSettings(){ 90bool InterfaceSetupImp::saveSettings(){
91 // eh can't really do anything about it other then return. :-D 91 // eh can't really do anything about it other then return. :-D
92 if(!interfaces->isInterfaceSet()) 92 if(!interfaces->isInterfaceSet())
93 return true; 93 return true;
94 94
95 bool error = false; 95 bool error = false;
96 // Loopback case 96 // Loopback case
97 if(interfaces->getInterfaceMethod(error) == INTERFACES_LOOPBACK){ 97 if(interfaces->getInterfaceMethod(error) == INTERFACES_LOOPBACK){
98 interfaces->setAuto(interface->getInterfaceName(), autoStart->isChecked()); 98 interfaces->setAuto(interface->getInterfaceName(), autoStart->isChecked());
99 return true; 99 return true;
100 } 100 }
101 101
102 if(!dhcpCheckBox->isChecked() && (ipAddressEdit->text().isEmpty() || subnetMaskEdit->text().isEmpty())){ 102 if(!dhcpCheckBox->isChecked() && (ipAddressEdit->text().isEmpty() || subnetMaskEdit->text().isEmpty())){
103 QMessageBox::information(this, "Not Saved.", "Please fill in the IP address and\n subnet entries.", QMessageBox::Ok); 103 QMessageBox::information(this, "Not Saved.", "Please fill in the IP address and\n subnet entries.", QMessageBox::Ok);
104 return false; 104 return false;
105 } 105 }
106 // DHCP 106 // DHCP
107 if(dhcpCheckBox->isChecked()) { 107 if(dhcpCheckBox->isChecked()) {
108 interfaces->setInterfaceMethod(INTERFACES_METHOD_DHCP); 108 interfaces->setInterfaceMethod(INTERFACES_METHOD_DHCP);
109 interfaces->removeInterfaceOption("address"); 109 interfaces->removeInterfaceOption("address");
110 interfaces->removeInterfaceOption("netmask"); 110 interfaces->removeInterfaceOption("netmask");
111 interfaces->removeInterfaceOption("gateway"); 111 interfaces->removeInterfaceOption("gateway");
112 interfaces->removeInterfaceOption("up "DNSSCRIPT" -a "); 112 interfaces->removeInterfaceOption("up "DNSSCRIPT" -a ");
113 interfaces->removeInterfaceOption("down "DNSSCRIPT" -r "); 113 interfaces->removeInterfaceOption("down "DNSSCRIPT" -r ");
114 } else{ 114 } else{
115 interfaces->setInterfaceMethod("static"); 115 interfaces->setInterfaceMethod("static");
116 interfaces->setInterfaceOption("address", ipAddressEdit->text()); 116 interfaces->setInterfaceOption("address", ipAddressEdit->text());
117 interfaces->setInterfaceOption("netmask", subnetMaskEdit->text()); 117 interfaces->setInterfaceOption("netmask", subnetMaskEdit->text());
118 interfaces->setInterfaceOption("gateway", gatewayEdit->text()); 118 interfaces->setInterfaceOption("gateway", gatewayEdit->text());
119 if(!firstDNSLineEdit->text().isEmpty() || !secondDNSLineEdit->text().isEmpty()){ 119 if(!firstDNSLineEdit->text().isEmpty() || !secondDNSLineEdit->text().isEmpty()){
120 QString dns = firstDNSLineEdit->text() + " " + secondDNSLineEdit->text(); 120 QString dns = firstDNSLineEdit->text() + " " + secondDNSLineEdit->text();
121 interfaces->setInterfaceOption("up "DNSSCRIPT" -a ", dns); 121 interfaces->setInterfaceOption("up "DNSSCRIPT" -a ", dns);
122 interfaces->setInterfaceOption("down "DNSSCRIPT" -r ", dns); 122 interfaces->setInterfaceOption("down "DNSSCRIPT" -r ", dns);
123 }else{ 123 }else{
124 interfaces->removeInterfaceOption("up "DNSSCRIPT" -a "); 124 interfaces->removeInterfaceOption("up "DNSSCRIPT" -a ");
125 interfaces->removeInterfaceOption("down "DNSSCRIPT" -r"); 125 interfaces->removeInterfaceOption("down "DNSSCRIPT" -r");
126 } 126 }
127 } 127 }
128 128
129 // IP Information 129 // IP Information
130 interfaces->setAuto(interface->getInterfaceName(), autoStart->isChecked()); 130 interfaces->setAuto(interface->getInterfaceName(), autoStart->isChecked());
131 return true; 131 return true;
132} 132}
133 133
134/** 134/**
135 * The Profile has changed. 135 * The Profile has changed.
136 * @param QString profile the new profile. 136 * @param QString profile the new profile.
137 */ 137 */
138void InterfaceSetupImp::setProfile(const QString &profile){ 138void InterfaceSetupImp::setProfile(const QString &profile){
139 /* 139 /*
140 bool error = false; 140 bool error = false;
141 if(interfaces->getInterfaceMethod(error) == INTERFACES_LOOPBACK){ 141 if(interfaces->getInterfaceMethod(error) == INTERFACES_LOOPBACK){
142 staticGroupBox->hide(); 142 staticGroupBox->hide();
143 dhcpCheckBox->hide(); 143 dhcpCheckBox->hide();
144 leaseTime->hide(); 144 leaseTime->hide();
145 leaseHoursLabel->hide(); 145 leaseHoursLabel->hide();
146 } 146 }
147 */ 147 */
148 148
149 QString newInterfaceName = interface->getInterfaceName(); 149 QString newInterfaceName = interface->getInterfaceName();
150 if(profile.length() > 0) 150 if(profile.length() > 0)
151 newInterfaceName += "_" + profile; 151 newInterfaceName += "_" + profile;
152 // See if we have to make a interface. 152 // See if we have to make a interface.
153 if(!interfaces->setInterface(newInterfaceName)){ 153 if(!interfaces->setInterface(newInterfaceName)){
154 // Add making for this new interface if need too 154 // Add making for this new interface if need too
155 if(profile != ""){ 155 if(profile != ""){
156 interfaces->copyInterface(interface->getInterfaceName(), newInterfaceName); 156 interfaces->copyInterface(interface->getInterfaceName(), newInterfaceName);
157 if(!interfaces->setMapping(interface->getInterfaceName())){ 157 if(!interfaces->setMapping(interface->getInterfaceName())){
158 interfaces->addMapping(interface->getInterfaceName()); 158 interfaces->addMapping(interface->getInterfaceName());
159 if(!interfaces->setMapping(interface->getInterfaceName())){ 159 if(!interfaces->setMapping(interface->getInterfaceName())){
160 qDebug("InterfaceSetupImp: Added Mapping, but still can't setInterface."); 160 odebug << "InterfaceSetupImp: Added Mapping, but still can't setInterface." << oendl;
161 return; 161 return;
162 } 162 }
163 } 163 }
164 interfaces->setMap("map", newInterfaceName); 164 interfaces->setMap("map", newInterfaceName);
165 interfaces->setScript("getprofile.sh"); 165 interfaces->setScript("getprofile.sh");
166 } 166 }
167 else{ 167 else{
168 interfaces->addInterface(newInterfaceName, INTERFACES_FAMILY_INET, INTERFACES_METHOD_DHCP); 168 interfaces->addInterface(newInterfaceName, INTERFACES_FAMILY_INET, INTERFACES_METHOD_DHCP);
169 if(!interfaces->setInterface(newInterfaceName)){ 169 if(!interfaces->setInterface(newInterfaceName)){
170 qDebug("InterfaceSetupImp: Added interface, but still can't setInterface."); 170 odebug << "InterfaceSetupImp: Added interface, but still can't setInterface." << oendl;
171 return; 171 return;
172 } 172 }
173 } 173 }
174 } 174 }
175 175
176 // We must have a valid interface to get this far so read some settings. 176 // We must have a valid interface to get this far so read some settings.
177 177
178 // DHCP 178 // DHCP
179 bool error = false; 179 bool error = false;
180 if(interfaces->getInterfaceMethod(error) == INTERFACES_METHOD_DHCP) 180 if(interfaces->getInterfaceMethod(error) == INTERFACES_METHOD_DHCP)
181 dhcpCheckBox->setChecked(true); 181 dhcpCheckBox->setChecked(true);
182 else 182 else
183 dhcpCheckBox->setChecked(false); 183 dhcpCheckBox->setChecked(false);
184 184
185 // IP Information 185 // IP Information
186 autoStart->setChecked(interfaces->isAuto(interface->getInterfaceName())); 186 autoStart->setChecked(interfaces->isAuto(interface->getInterfaceName()));
187 QString dns = interfaces->getInterfaceOption("up "DNSSCRIPT" -a", error); 187 QString dns = interfaces->getInterfaceOption("up "DNSSCRIPT" -a", error);
188 qDebug("dns >%s<",dns.latin1()); 188 odebug << "dns >" << dns.latin1() << "<" << oendl;
189 if(dns.contains(" ")){ 189 if(dns.contains(" ")){
190 firstDNSLineEdit->setText(dns.mid(0, dns.find(" "))); 190 firstDNSLineEdit->setText(dns.mid(0, dns.find(" ")));
191 secondDNSLineEdit->setText(dns.mid(dns.find(" ")+1, dns.length())); 191 secondDNSLineEdit->setText(dns.mid(dns.find(" ")+1, dns.length()));
192 }else firstDNSLineEdit->setText(dns); 192 }else firstDNSLineEdit->setText(dns);
193 193
194 ipAddressEdit->setText(interfaces->getInterfaceOption("address", error)); 194 ipAddressEdit->setText(interfaces->getInterfaceOption("address", error));
195 subnetMaskEdit->setText(interfaces->getInterfaceOption("netmask", error)); 195 subnetMaskEdit->setText(interfaces->getInterfaceOption("netmask", error));
196 if (subnetMaskEdit->text().isEmpty()) 196 if (subnetMaskEdit->text().isEmpty())
197 subnetMaskEdit->setText( "255.255.255.0" ); 197 subnetMaskEdit->setText( "255.255.255.0" );
198 gatewayEdit->setText(interfaces->getInterfaceOption("gateway", error)); 198 gatewayEdit->setText(interfaces->getInterfaceOption("gateway", error));
199 199
200 200
201 201
202 qWarning("InterfaceSetupImp::setProfile(%s)\n", profile.latin1()); 202 owarn << "InterfaceSetupImp::setProfile(" << profile.latin1() << ")\n" << oendl;
203 qWarning("InterfaceSetupImp::setProfile: iface is %s\n", interfaces->getInterfaceName(error).latin1()); 203 owarn << "InterfaceSetupImp::setProfile: iface is " << interfaces->getInterfaceName(error).latin1() << "\n" << oendl;
204 204
205} 205}
206 206
207// interfacesetup.cpp 207// interfacesetup.cpp
208 208
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 @@
1 1
2#include "mainwindowimp.h" 2#include "mainwindowimp.h"
3#include "addconnectionimp.h" 3#include "addconnectionimp.h"
4#include "interfaceinformationimp.h" 4#include "interfaceinformationimp.h"
5#include "interfacesetupimp.h" 5#include "interfacesetupimp.h"
6#include "interfaces.h" 6#include "interfaces.h"
7#include "module.h" 7#include "module.h"
8 8
9/* OPIE */ 9/* OPIE */
10#include <qpe/qcopenvelope_qws.h> 10#include <qpe/qcopenvelope_qws.h>
11#include <qpe/qpeapplication.h> 11#include <qpe/qpeapplication.h>
12#include <qpe/config.h> 12#include <qpe/config.h>
13#include <qpe/qlibrary.h> 13#include <qpe/qlibrary.h>
14#include <qpe/resource.h> 14#include <qpe/resource.h>
15 15
16/* QT */ 16/* QT */
17#include <qpushbutton.h> 17#include <qpushbutton.h>
18#include <qlistbox.h> 18#include <qlistbox.h>
19#include <qlineedit.h> 19#include <qlineedit.h>
20#include <qlistview.h> 20#include <qlistview.h>
21#include <qheader.h> 21#include <qheader.h>
22#include <qlabel.h> 22#include <qlabel.h>
23#include <qtabwidget.h> // in order to disable the profiles tab 23#include <qtabwidget.h> // in order to disable the profiles tab
24#include <qmessagebox.h> 24#include <qmessagebox.h>
25 25
26 26
27#if QT_VERSION < 300 27#if QT_VERSION < 300
28#include <qlist.h> 28#include <qlist.h>
29#else 29#else
30#include <qptrlist.h> 30#include <qptrlist.h>
31#endif 31#endif
32#include <qdir.h> 32#include <qdir.h>
33#include <qfile.h> 33#include <qfile.h>
34#include <qtextstream.h> 34#include <qtextstream.h>
35#include <qregexp.h> 35#include <qregexp.h>
36 36
37/* STD */ 37/* STD */
38#include <net/if.h> 38#include <net/if.h>
39#include <sys/ioctl.h> 39#include <sys/ioctl.h>
40#include <sys/socket.h> 40#include <sys/socket.h>
41 41
42#define DEFAULT_SCHEME "/var/lib/pcmcia/scheme" 42#define DEFAULT_SCHEME "/var/lib/pcmcia/scheme"
43#define _PROCNETDEV "/proc/net/dev" 43#define _PROCNETDEV "/proc/net/dev"
44 44
45MainWindowImp::MainWindowImp(QWidget *parent, const char *name, WFlags) : MainWindow(parent, name, Qt::WStyle_ContextHelp), advancedUserMode(true), scheme(DEFAULT_SCHEME) 45MainWindowImp::MainWindowImp(QWidget *parent, const char *name, WFlags) : MainWindow(parent, name, Qt::WStyle_ContextHelp), advancedUserMode(true), scheme(DEFAULT_SCHEME)
46{ 46{
47 connect(addConnectionButton, SIGNAL(clicked()), this, SLOT(addClicked())); 47 connect(addConnectionButton, SIGNAL(clicked()), this, SLOT(addClicked()));
48 connect(removeConnectionButton, SIGNAL(clicked()), this, SLOT(removeClicked())); 48 connect(removeConnectionButton, SIGNAL(clicked()), this, SLOT(removeClicked()));
49 connect(informationConnectionButton, SIGNAL(clicked()), this, SLOT(informationClicked())); 49 connect(informationConnectionButton, SIGNAL(clicked()), this, SLOT(informationClicked()));
50 connect(configureConnectionButton, SIGNAL(clicked()), this, SLOT(configureClicked())); 50 connect(configureConnectionButton, SIGNAL(clicked()), this, SLOT(configureClicked()));
51 51
52 connect(newProfileButton, SIGNAL(clicked()), this, SLOT(addProfile())); 52 connect(newProfileButton, SIGNAL(clicked()), this, SLOT(addProfile()));
53 connect(removeProfileButton, SIGNAL(clicked()), this, SLOT(removeProfile())); 53 connect(removeProfileButton, SIGNAL(clicked()), this, SLOT(removeProfile()));
54 connect(setCurrentProfileButton, SIGNAL(clicked()), this, SLOT(changeProfile())); 54 connect(setCurrentProfileButton, SIGNAL(clicked()), this, SLOT(changeProfile()));
55 55
56 connect(newProfile, SIGNAL(textChanged(const QString&)), this, SLOT(newProfileChanged(const QString&))); 56 connect(newProfile, SIGNAL(textChanged(const QString&)), this, SLOT(newProfileChanged(const QString&)));
57 57
58 //FIXME: disable profiles for the moment: 58 //FIXME: disable profiles for the moment:
59 tabWidget->setTabEnabled( tab, false ); 59 tabWidget->setTabEnabled( tab, false );
60 60
61 // Load connections. 61 // Load connections.
62 // /usr/local/kde/lib/libinterfaces.la 62 // /usr/local/kde/lib/libinterfaces.la
63#ifdef QWS 63#ifdef QWS
64 loadModules(QPEApplication::qpeDir() + "plugins/networksettings"); 64 loadModules(QPEApplication::qpeDir() + "plugins/networksettings");
65#else 65#else
66 loader = KLibLoader::self(); 66 loader = KLibLoader::self();
67 loadModules(QString("/usr/")+KStandardDirs::kde_default("lib")); 67 loadModules(QString("/usr/")+KStandardDirs::kde_default("lib"));
68#endif 68#endif
69 getAllInterfaces(); 69 getAllInterfaces();
70 70
71 Interfaces i; 71 Interfaces i;
72 QStringList list = i.getInterfaceList(); 72 QStringList list = i.getInterfaceList();
73 QMap<QString, Interface*>::Iterator it; 73 QMap<QString, Interface*>::Iterator it;
74 for ( QStringList::Iterator ni = list.begin(); ni != list.end(); ++ni ) 74 for ( QStringList::Iterator ni = list.begin(); ni != list.end(); ++ni )
75 { 75 {
76 /* 76 /*
77 * we skipped it in getAllInterfaces now 77 * we skipped it in getAllInterfaces now
78 * we need to ignore it as well 78 * we need to ignore it as well
79 */ 79 */
80 if (m_handledIfaces.contains( *ni) ) 80 if (m_handledIfaces.contains( *ni) )
81 { 81 {
82 qDebug("Not up iface handled by module"); 82 odebug << "Not up iface handled by module" << oendl;
83 continue; 83 continue;
84 } 84 }
85 bool found = false; 85 bool found = false;
86 for( it = interfaceNames.begin(); it != interfaceNames.end(); ++it ) 86 for( it = interfaceNames.begin(); it != interfaceNames.end(); ++it )
87 { 87 {
88 if(it.key() == (*ni)) 88 if(it.key() == (*ni))
89 found = true; 89 found = true;
90 } 90 }
91 if(!found) 91 if(!found)
92 { 92 {
93 if(!(*ni).contains("_")) 93 if(!(*ni).contains("_"))
94 { 94 {
95 Interface *i = new Interface(this, *ni, false); 95 Interface *i = new Interface(this, *ni, false);
96 i->setAttached(false); 96 i->setAttached(false);
97 i->setHardwareName(tr("Disconnected")); 97 i->setHardwareName(tr("Disconnected"));
98 interfaceNames.insert(i->getInterfaceName(), i); 98 interfaceNames.insert(i->getInterfaceName(), i);
99 updateInterface(i); 99 updateInterface(i);
100 connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*))); 100 connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*)));
101 } 101 }
102 } 102 }
103 } 103 }
104 104
105 //getInterfaceList(); 105 //getInterfaceList();
106 connectionList->header()->hide(); 106 connectionList->header()->hide();
107 107
108 Config cfg("NetworkSetup"); 108 Config cfg("NetworkSetup");
109 profiles = QStringList::split(" ", cfg.readEntry("Profiles", "All")); 109 profiles = QStringList::split(" ", cfg.readEntry("Profiles", "All"));
110 for ( QStringList::Iterator it = profiles.begin(); 110 for ( QStringList::Iterator it = profiles.begin();
111 it != profiles.end(); ++it) 111 it != profiles.end(); ++it)
112 profilesList->insertItem((*it)); 112 profilesList->insertItem((*it));
113 currentProfileLabel->setText(cfg.readEntry("CurrentProfile", "All")); 113 currentProfileLabel->setText(cfg.readEntry("CurrentProfile", "All"));
114 advancedUserMode = cfg.readBoolEntry("AdvancedUserMode", false); 114 advancedUserMode = cfg.readBoolEntry("AdvancedUserMode", false);
115 scheme = cfg.readEntry("SchemeFile", DEFAULT_SCHEME); 115 scheme = cfg.readEntry("SchemeFile", DEFAULT_SCHEME);
116 116
117 QFile file(scheme); 117 QFile file(scheme);
118 if ( file.open(IO_ReadOnly) ) 118 if ( file.open(IO_ReadOnly) )
119 { // file opened successfully 119 { // file opened successfully
120 QTextStream stream( &file ); // use a text stream 120 QTextStream stream( &file ); // use a text stream
121 while ( !stream.eof() ) 121 while ( !stream.eof() )
122 { // until end of file... 122 { // until end of file...
123 QString line = stream.readLine(); // line of text excluding '\n' 123 QString line = stream.readLine(); // line of text excluding '\n'
124 if(line.contains("SCHEME")) 124 if(line.contains("SCHEME"))
125 { 125 {
126 line = line.mid(7, line.length()); 126 line = line.mid(7, line.length());
127 currentProfileLabel->setText(line); 127 currentProfileLabel->setText(line);
128 break; 128 break;
129 } 129 }
130 } 130 }
131 file.close(); 131 file.close();
132 } 132 }
133 makeChannel(); 133 makeChannel();
134} 134}
135 135
136/** 136/**
137 * Deconstructor. Save profiles. Delete loaded libraries. 137 * Deconstructor. Save profiles. Delete loaded libraries.
138 */ 138 */
139MainWindowImp::~MainWindowImp() 139MainWindowImp::~MainWindowImp()
140{ 140{
141 // Save profiles. 141 // Save profiles.
142 Config cfg("NetworkSetup"); 142 Config cfg("NetworkSetup");
143 cfg.setGroup("General"); 143 cfg.setGroup("General");
144 cfg.writeEntry("Profiles", profiles.join(" ")); 144 cfg.writeEntry("Profiles", profiles.join(" "));
145 145
146 // Delete all interfaces that don't have owners. 146 // Delete all interfaces that don't have owners.
147 QMap<Interface*, QListViewItem*>::Iterator iIt; 147 QMap<Interface*, QListViewItem*>::Iterator iIt;
148 for( iIt = items.begin(); iIt != items.end(); ++iIt ) 148 for( iIt = items.begin(); iIt != items.end(); ++iIt )
149 { 149 {
150 if(iIt.key()->getModuleOwner() == NULL) 150 if(iIt.key()->getModuleOwner() == NULL)
151 delete iIt.key(); 151 delete iIt.key();
152 } 152 }
153 153
154#ifdef QWS 154#ifdef QWS
155 // Delete Modules and Libraries 155 // Delete Modules and Libraries
156 QMap<Module*, QLibrary*>::Iterator it; 156 QMap<Module*, QLibrary*>::Iterator it;
157 for( it = libraries.begin(); it != libraries.end(); ++it ) 157 for( it = libraries.begin(); it != libraries.end(); ++it )
158 { 158 {
159 delete it.key(); 159 delete it.key();
160 // I wonder why I can't delete the libraries 160 // I wonder why I can't delete the libraries
161 // What fucking shit this is. 161 // What fucking shit this is.
162 //delete it.data(); 162 //delete it.data();
163 } 163 }
164#else 164#else
165 // klibloader automaticly deletes the libraries for us... 165 // klibloader automaticly deletes the libraries for us...
166#endif 166#endif
167} 167}
168 168
169/** 169/**
170 * Query the kernel for all of the interfaces. 170 * Query the kernel for all of the interfaces.
171 */ 171 */
172void MainWindowImp::getAllInterfaces() 172void MainWindowImp::getAllInterfaces()
173{ 173{
174 int sockfd = socket(PF_INET, SOCK_DGRAM, 0); 174 int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
175 if(sockfd == -1) 175 if(sockfd == -1)
176 return; 176 return;
177 177
178 struct ifreq ifr; 178 struct ifreq ifr;
179 QStringList ifaces; 179 QStringList ifaces;
180 QFile procFile(QString(_PROCNETDEV)); 180 QFile procFile(QString(_PROCNETDEV));
181 int result; 181 int result;
182 Interface *i; 182 Interface *i;
183 183
184 if (! procFile.exists()) 184 if (! procFile.exists())
185 { 185 {
186 struct ifreq ifrs[100]; 186 struct ifreq ifrs[100];
187 struct ifconf ifc; 187 struct ifconf ifc;
188 ifc.ifc_len = sizeof(ifrs); 188 ifc.ifc_len = sizeof(ifrs);
189 ifc.ifc_req = ifrs; 189 ifc.ifc_req = ifrs;
190 result = ioctl(sockfd, SIOCGIFCONF, &ifc); 190 result = ioctl(sockfd, SIOCGIFCONF, &ifc);
191 191
192 for (unsigned int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++) 192 for (unsigned int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++)
193 { 193 {
194 struct ifreq *pifr = &ifrs[i]; 194 struct ifreq *pifr = &ifrs[i];
195 195
196 ifaces += pifr->ifr_name; 196 ifaces += pifr->ifr_name;
197 } 197 }
198 } 198 }
199 else 199 else
200 { 200 {
201 procFile.open(IO_ReadOnly); 201 procFile.open(IO_ReadOnly);
202 QString line; 202 QString line;
203 QTextStream procTs(&procFile); 203 QTextStream procTs(&procFile);
204 int loc = -1; 204 int loc = -1;
205 205
206 procTs.readLine(); // eat a line 206 procTs.readLine(); // eat a line
207 procTs.readLine(); // eat a line 207 procTs.readLine(); // eat a line
208 while((line = procTs.readLine().simplifyWhiteSpace()) != QString::null) 208 while((line = procTs.readLine().simplifyWhiteSpace()) != QString::null)
209 { 209 {
210 if((loc = line.find(":")) != -1) 210 if((loc = line.find(":")) != -1)
211 { 211 {
212 ifaces += line.left(loc); 212 ifaces += line.left(loc);
213 } 213 }
214 } 214 }
215 } 215 }
216 216
217 for (QStringList::Iterator it = ifaces.begin(); it != ifaces.end(); ++it) 217 for (QStringList::Iterator it = ifaces.begin(); it != ifaces.end(); ++it)
218 { 218 {
219 int flags = 0; 219 int flags = 0;
220 if ( m_handledIfaces.contains( (*it) ) ) 220 if ( m_handledIfaces.contains( (*it) ) )
221 { 221 {
222 qDebug(" %s is handled by a module", (*it).latin1() ); 222 odebug << " " << (*it).latin1() << " is handled by a module" << oendl;
223 continue; 223 continue;
224 } 224 }
225 // int family; 225 // int family;
226 i = NULL; 226 i = NULL;
227 227
228 strcpy(ifr.ifr_name, (*it).latin1()); 228 strcpy(ifr.ifr_name, (*it).latin1());
229 229
230 struct ifreq ifcopy; 230 struct ifreq ifcopy;
231 ifcopy = ifr; 231 ifcopy = ifr;
232 result = ioctl(sockfd, SIOCGIFFLAGS, &ifcopy); 232 result = ioctl(sockfd, SIOCGIFFLAGS, &ifcopy);
233 flags = ifcopy.ifr_flags; 233 flags = ifcopy.ifr_flags;
234 i = new Interface(this, ifr.ifr_name, false); 234 i = new Interface(this, ifr.ifr_name, false);
235 i->setAttached(true); 235 i->setAttached(true);
236 if ((flags & IFF_UP) == IFF_UP) 236 if ((flags & IFF_UP) == IFF_UP)
237 i->setStatus(true); 237 i->setStatus(true);
238 else 238 else
239 i->setStatus(false); 239 i->setStatus(false);
240 240
241 if ((flags & IFF_BROADCAST) == IFF_BROADCAST) 241 if ((flags & IFF_BROADCAST) == IFF_BROADCAST)
242 i->setHardwareName("Ethernet"); 242 i->setHardwareName("Ethernet");
243 else if ((flags & IFF_POINTOPOINT) == IFF_POINTOPOINT) 243 else if ((flags & IFF_POINTOPOINT) == IFF_POINTOPOINT)
244 i->setHardwareName("Point to Point"); 244 i->setHardwareName("Point to Point");
245 else if ((flags & IFF_MULTICAST) == IFF_MULTICAST) 245 else if ((flags & IFF_MULTICAST) == IFF_MULTICAST)
246 i->setHardwareName("Multicast"); 246 i->setHardwareName("Multicast");
247 else if ((flags & IFF_LOOPBACK) == IFF_LOOPBACK) 247 else if ((flags & IFF_LOOPBACK) == IFF_LOOPBACK)
248 i->setHardwareName("Loopback"); 248 i->setHardwareName("Loopback");
249 else 249 else
250 i->setHardwareName("Unknown"); 250 i->setHardwareName("Unknown");
251 251
252 qWarning("Adding interface %s to interfaceNames\n", ifr.ifr_name); 252 owarn << "Adding interface " << ifr.ifr_name << " to interfaceNames\n" << oendl;
253 interfaceNames.insert(i->getInterfaceName(), i); 253 interfaceNames.insert(i->getInterfaceName(), i);
254 updateInterface(i); 254 updateInterface(i);
255 connect(i, SIGNAL(updateInterface(Interface*)), 255 connect(i, SIGNAL(updateInterface(Interface*)),
256 this, SLOT(updateInterface(Interface*))); 256 this, SLOT(updateInterface(Interface*)));
257 } 257 }
258 // now lets ask the plugins too ;) 258 // now lets ask the plugins too ;)
259 QMap<Module*, QLibrary*>::Iterator it; 259 QMap<Module*, QLibrary*>::Iterator it;
260 QList<Interface> ilist; 260 QList<Interface> ilist;
261 for( it = libraries.begin(); it != libraries.end(); ++it ) 261 for( it = libraries.begin(); it != libraries.end(); ++it )
262 { 262 {
263 if(it.key()) 263 if(it.key())
264 { 264 {
265 ilist = it.key()->getInterfaces(); 265 ilist = it.key()->getInterfaces();
266 for( i = ilist.first(); i != 0; i = ilist.next() ) 266 for( i = ilist.first(); i != 0; i = ilist.next() )
267 { 267 {
268 qWarning("Adding interface %s to interfaceNames\n", i->getInterfaceName().latin1() ); 268 owarn << "Adding interface " << i->getInterfaceName().latin1() << " to interfaceNames\n" << oendl;
269 interfaceNames.insert(i->getInterfaceName(), i); 269 interfaceNames.insert(i->getInterfaceName(), i);
270 updateInterface(i); 270 updateInterface(i);
271 connect(i, SIGNAL(updateInterface(Interface*)), 271 connect(i, SIGNAL(updateInterface(Interface*)),
272 this, SLOT(updateInterface(Interface*))); 272 this, SLOT(updateInterface(Interface*)));
273 } 273 }
274 } 274 }
275 } 275 }
276} 276}
277 277
278/** 278/**
279 * Load all modules that are found in the path 279 * Load all modules that are found in the path
280 * @param path a directory that is scaned for any plugins that can be loaded 280 * @param path a directory that is scaned for any plugins that can be loaded
281 * and attempts to load them 281 * and attempts to load them
282 */ 282 */
283void MainWindowImp::loadModules(const QString &path) 283void MainWindowImp::loadModules(const QString &path)
284{ 284{
285#ifdef DEBUG 285#ifdef DEBUG
286 qDebug("MainWindowImp::loadModules: %s", path.latin1()); 286 odebug << "MainWindowImp::loadModules: " << path.latin1() << "" << oendl;
287#endif 287#endif
288 QDir d(path); 288 QDir d(path);
289 if(!d.exists()) 289 if(!d.exists())
290 return; 290 return;
291 291
292 // Don't want sym links 292 // Don't want sym links
293 d.setFilter( QDir::Files | QDir::NoSymLinks ); 293 d.setFilter( QDir::Files | QDir::NoSymLinks );
294 const QFileInfoList *list = d.entryInfoList(); 294 const QFileInfoList *list = d.entryInfoList();
295 QFileInfoListIterator it( *list ); 295 QFileInfoListIterator it( *list );
296 QFileInfo *fi; 296 QFileInfo *fi;
297 while ( (fi=it.current()) ) 297 while ( (fi=it.current()) )
298 { 298 {
299#ifdef QWS 299#ifdef QWS
300 if(fi->fileName().contains(".so")) 300 if(fi->fileName().contains(".so"))
301 { 301 {
302#else 302#else
303 if(fi->fileName().contains(".so") && fi->fileName().contains("networksettings_")) 303 if(fi->fileName().contains(".so") && fi->fileName().contains("networksettings_"))
304 { 304 {
305#endif 305#endif
306 loadPlugin(path + "/" + fi->fileName()); 306 loadPlugin(path + "/" + fi->fileName());
307 qDebug("loaded plugin: >%s< ",QString(path + "/" + fi->fileName()).latin1()); 307 odebug << "loaded plugin: >" << QString(path + "/" + fi->fileName()).latin1() << "< " << oendl;
308 } 308 }
309 ++it; 309 ++it;
310 } 310 }
311} 311}
312 312
313/** 313/**
314 * Attempt to load a function and resolve a function. 314 * Attempt to load a function and resolve a function.
315 * @param pluginFileName - the name of the file in which to attempt to load 315 * @param pluginFileName - the name of the file in which to attempt to load
316 * @param resolveString - function pointer to resolve 316 * @param resolveString - function pointer to resolve
317 * @return pointer to the function with name resolveString or NULL 317 * @return pointer to the function with name resolveString or NULL
318 */ 318 */
319Module* MainWindowImp::loadPlugin(const QString &pluginFileName, const QString &resolveString) 319Module* MainWindowImp::loadPlugin(const QString &pluginFileName, const QString &resolveString)
320{ 320{
321#ifdef DEBUG 321#ifdef DEBUG
322 qDebug("MainWindowImp::loadPlugin: %s: resolving %s", pluginFileName.latin1(), resolveString.latin1()); 322 odebug << "MainWindowImp::loadPlugin: " << pluginFileName.latin1() << ": resolving " << resolveString.latin1() << "" << oendl;
323#endif 323#endif
324#ifdef QWS 324#ifdef QWS
325 QLibrary *lib = new QLibrary(pluginFileName); 325 QLibrary *lib = new QLibrary(pluginFileName);
326 void *functionPointer = lib->resolve(resolveString); 326 void *functionPointer = lib->resolve(resolveString);
327 if( !functionPointer ) 327 if( !functionPointer )
328 { 328 {
329#ifdef DEBUG 329#ifdef DEBUG
330 qDebug("MainWindowImp::loadPlugin: Warning: %s is not a plugin", pluginFileName.latin1()); 330 odebug << "MainWindowImp::loadPlugin: Warning: " << pluginFileName.latin1() << " is not a plugin" << oendl;
331#endif 331#endif
332 delete lib; 332 delete lib;
333 return NULL; 333 return NULL;
334 } 334 }
335 // Try to get an object. 335 // Try to get an object.
336 Module *object = ((Module* (*)()) functionPointer)(); 336 Module *object = ((Module* (*)()) functionPointer)();
337 if(object == NULL) 337 if(object == NULL)
338 { 338 {
339#ifdef DEBUG 339#ifdef DEBUG
340 qDebug("MainWindowImp: Couldn't create object, but did load library!"); 340 odebug << "MainWindowImp: Couldn't create object, but did load library!" << oendl;
341#endif 341#endif
342 delete lib; 342 delete lib;
343 return NULL; 343 return NULL;
344 } 344 }
345 345
346 m_handledIfaces += object->handledInterfaceNames(); 346 m_handledIfaces += object->handledInterfaceNames();
347 // Store for deletion later 347 // Store for deletion later
348 libraries.insert(object, lib); 348 libraries.insert(object, lib);
349 return object; 349 return object;
350 350
351#else 351#else
352 QLibrary *lib = loader->library(pluginFileName); 352 QLibrary *lib = loader->library(pluginFileName);
353 if( !lib || !lib->hasSymbol(resolveString) ) 353 if( !lib || !lib->hasSymbol(resolveString) )
354 { 354 {
355 qDebug(QString("MainWindowImp::loadPlugin: File: %1 is not a plugin, but though was.").arg(pluginFileName).latin1()); 355 odebug << QString("MainWindowImp::loadPlugin: File: %1 is not a plugin, but though was.").arg(pluginFileName).latin1() << oendl;
356 return NULL; 356 return NULL;
357 } 357 }
358 // Try to get an object. 358 // Try to get an object.
359 Module *object = ((Module* (*)()) lib->symbol(resolveString))(); 359 Module *object = ((Module* (*)()) lib->symbol(resolveString))();
360 if(object == NULL) 360 if(object == NULL)
361 { 361 {
362#ifdef DEBUG 362#ifdef DEBUG
363 qDebug("MainWindowImp: Couldn't create object, but did load library!"); 363 odebug << "MainWindowImp: Couldn't create object, but did load library!" << oendl;
364#endif 364#endif
365 return NULL; 365 return NULL;
366 } 366 }
367#ifdef DEBUG 367#ifdef DEBUG
368 qDebug("MainWindowImp::loadPlugin:: Found object, storing."); 368 odebug << "MainWindowImp::loadPlugin:: Found object, storing." << oendl;
369#endif 369#endif
370 // Store for deletion later 370 // Store for deletion later
371 libraries.insert(object, lib); 371 libraries.insert(object, lib);
372 return object; 372 return object;
373#endif 373#endif
374} 374}
375 375
376/** 376/**
377 * The Add button was clicked. Bring up the add dialog and if OK is hit 377 * The Add button was clicked. Bring up the add dialog and if OK is hit
378 * load the plugin and append it to the list 378 * load the plugin and append it to the list
379 */ 379 */
380void MainWindowImp::addClicked() 380void MainWindowImp::addClicked()
381{ 381{
382 QMap<Module*, QLibrary*>::Iterator it; 382 QMap<Module*, QLibrary*>::Iterator it;
383 QMap<QString, QString> list; 383 QMap<QString, QString> list;
384 QMap<QString, Module*> newInterfaceOwners; 384 QMap<QString, Module*> newInterfaceOwners;
385 385
386 for( it = libraries.begin(); it != libraries.end(); ++it ) 386 for( it = libraries.begin(); it != libraries.end(); ++it )
387 { 387 {
388 if(it.key()) 388 if(it.key())
389 { 389 {
390 (it.key())->possibleNewInterfaces(list); 390 (it.key())->possibleNewInterfaces(list);
391 } 391 }
392 } 392 }
393 // See if the list has anything that we can add. 393 // See if the list has anything that we can add.
394 if(list.count() == 0) 394 if(list.count() == 0)
395 { 395 {
396 QMessageBox::information(this, "Sorry", "Nothing to add.", QMessageBox::Ok); 396 QMessageBox::information(this, "Sorry", "Nothing to add.", QMessageBox::Ok);
397 return; 397 return;
398 } 398 }
399 AddConnectionImp addNewConnection(this, "AddConnectionImp", true); 399 AddConnectionImp addNewConnection(this, "AddConnectionImp", true);
400 addNewConnection.addConnections(list); 400 addNewConnection.addConnections(list);
401 if( QDialog::Accepted == QPEApplication::execDialog( &addNewConnection ) ) 401 if( QDialog::Accepted == QPEApplication::execDialog( &addNewConnection ) )
402 { 402 {
403 QListViewItem *item = addNewConnection.registeredServicesList->currentItem(); 403 QListViewItem *item = addNewConnection.registeredServicesList->currentItem();
404 if(!item) 404 if(!item)
405 return; 405 return;
406 406
407 for( it = libraries.begin(); it != libraries.end(); ++it ) 407 for( it = libraries.begin(); it != libraries.end(); ++it )
408 { 408 {
409 if(it.key()) 409 if(it.key())
410 { 410 {
411 Interface *i = (it.key())->addNewInterface(item->text(0)); 411 Interface *i = (it.key())->addNewInterface(item->text(0));
412 if(i) 412 if(i)
413 { 413 {
414 qDebug("iface name %s",i->getInterfaceName().latin1()); 414 odebug << "iface name " << i->getInterfaceName().latin1() << "" << oendl;
415 interfaceNames.insert(i->getInterfaceName(), i); 415 interfaceNames.insert(i->getInterfaceName(), i);
416 updateInterface(i); 416 updateInterface(i);
417 } 417 }
418 } 418 }
419 } 419 }
420 } 420 }
421} 421}
422 422
423/** 423/**
424 * Prompt the user to see if they really want to do this. 424 * Prompt the user to see if they really want to do this.
425 * If they do then remove from the list and unload. 425 * If they do then remove from the list and unload.
426 */ 426 */
427void MainWindowImp::removeClicked() 427void MainWindowImp::removeClicked()
428{ 428{
429 QListViewItem *item = connectionList->currentItem(); 429 QListViewItem *item = connectionList->currentItem();
430 if(!item) 430 if(!item)
431 { 431 {
432 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok); 432 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok);
433 return; 433 return;
434 } 434 }
435 435
436 Interface *i = interfaceItems[item]; 436 Interface *i = interfaceItems[item];
437 if(i->getModuleOwner() == NULL) 437 if(i->getModuleOwner() == NULL)
438 { 438 {
439 QMessageBox::information(this, "Can't remove interface.", "Interface is built in.", QMessageBox::Ok); 439 QMessageBox::information(this, "Can't remove interface.", "Interface is built in.", QMessageBox::Ok);
440 } 440 }
441 else 441 else
442 { 442 {
443 if(!i->getModuleOwner()->remove(i)) 443 if(!i->getModuleOwner()->remove(i))
444 QMessageBox::information(this, tr("Error"), tr("Unable to remove."), QMessageBox::Ok); 444 QMessageBox::information(this, tr("Error"), tr("Unable to remove."), QMessageBox::Ok);
445 else 445 else
446 { 446 {
447 delete item; 447 delete item;
448 // QMessageBox::information(this, "Success", "Interface was removed.", QMessageBox::Ok); 448 // QMessageBox::information(this, "Success", "Interface was removed.", QMessageBox::Ok);
449 } 449 }
450 } 450 }
451} 451}
452 452
453/** 453/**
454 * Pull up the configure about the currently selected interface. 454 * Pull up the configure about the currently selected interface.
455 * Report an error if no interface is selected. 455 * Report an error if no interface is selected.
456 * If the interface has a module owner then request its configure. 456 * If the interface has a module owner then request its configure.
457 */ 457 */
458void MainWindowImp::configureClicked() 458void MainWindowImp::configureClicked()
459{ 459{
460 QListViewItem *item = connectionList->currentItem(); 460 QListViewItem *item = connectionList->currentItem();
461 if(!item) 461 if(!item)
462 { 462 {
463 QMessageBox::information(this, tr("Sorry"),tr("Please select an interface first."), QMessageBox::Ok); 463 QMessageBox::information(this, tr("Sorry"),tr("Please select an interface first."), QMessageBox::Ok);
464 return; 464 return;
465 } 465 }
466 466
467 QString currentProfileText = currentProfileLabel->text(); 467 QString currentProfileText = currentProfileLabel->text();
468 if(currentProfileText.upper() == "ALL"); 468 if(currentProfileText.upper() == "ALL");
469 currentProfileText = ""; 469 currentProfileText = "";
470 470
471 Interface *i = interfaceItems[item]; 471 Interface *i = interfaceItems[item];
472 472
473 if(i->getModuleOwner()) 473 if(i->getModuleOwner())
474 { 474 {
475 QWidget *moduleConfigure = i->getModuleOwner()->configure(i); 475 QWidget *moduleConfigure = i->getModuleOwner()->configure(i);
476 if(moduleConfigure != NULL) 476 if(moduleConfigure != NULL)
477 { 477 {
478 i->getModuleOwner()->setProfile(currentProfileText); 478 i->getModuleOwner()->setProfile(currentProfileText);
479 QPEApplication::showWidget( moduleConfigure ); 479 QPEApplication::showWidget( moduleConfigure );
480 return; 480 return;
481 } 481 }
482 } 482 }
483 483
484 InterfaceSetupImpDialog *configure = new InterfaceSetupImpDialog(this, "InterfaceSetupImp", i, true, Qt::WDestructiveClose | Qt::WStyle_ContextHelp ); 484 InterfaceSetupImpDialog *configure = new InterfaceSetupImpDialog(this, "InterfaceSetupImp", i, true, Qt::WDestructiveClose | Qt::WStyle_ContextHelp );
485 configure->setProfile(currentProfileText); 485 configure->setProfile(currentProfileText);
486 QPEApplication::showDialog( configure ); 486 QPEApplication::showDialog( configure );
487} 487}
488 488
489/** 489/**
490 * Pull up the information about the currently selected interface. 490 * Pull up the information about the currently selected interface.
491 * Report an error if no interface is selected. 491 * Report an error if no interface is selected.
492 * If the interface has a module owner then request its configure. 492 * If the interface has a module owner then request its configure.
493 */ 493 */
494void MainWindowImp::informationClicked() 494void MainWindowImp::informationClicked()
495{ 495{
496 QListViewItem *item = connectionList->currentItem(); 496 QListViewItem *item = connectionList->currentItem();
497 if(!item) 497 if(!item)
498 { 498 {
499 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok); 499 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok);
500 return; 500 return;
501 } 501 }
502 502
503 Interface *i = interfaceItems[item]; 503 Interface *i = interfaceItems[item];
504 // if(!i->isAttached()){ 504 // if(!i->isAttached()){
505 // QMessageBox::information(this, "Sorry","No information about\na disconnected interface.", QMessageBox::Ok); 505 // QMessageBox::information(this, "Sorry","No information about\na disconnected interface.", QMessageBox::Ok);
506 // return; 506 // return;
507 // } 507 // }
508 508
509 if(i->getModuleOwner()) 509 if(i->getModuleOwner())
510 { 510 {
511 QWidget *moduleInformation = i->getModuleOwner()->information(i); 511 QWidget *moduleInformation = i->getModuleOwner()->information(i);
512 if(moduleInformation != NULL) 512 if(moduleInformation != NULL)
513 { 513 {
514 QPEApplication::showWidget( moduleInformation ); 514 QPEApplication::showWidget( moduleInformation );
515#ifdef DEBUG 515#ifdef DEBUG
516 qDebug("MainWindowImp::informationClicked:: Module owner has created, we showed."); 516 odebug << "MainWindowImp::informationClicked:: Module owner has created, we showed." << oendl;
517#endif 517#endif
518 return; 518 return;
519 } 519 }
520 } 520 }
521 InterfaceInformationImp *information = new InterfaceInformationImp(this, "InterfaceSetupImp", i, Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog | Qt::WStyle_ContextHelp); 521 InterfaceInformationImp *information = new InterfaceInformationImp(this, "InterfaceSetupImp", i, Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog | Qt::WStyle_ContextHelp);
522 QPEApplication::showWidget( information ); 522 QPEApplication::showWidget( information );
523} 523}
524 524
525/** 525/**
526 * Update this interface. If no QListViewItem exists create one. 526 * Update this interface. If no QListViewItem exists create one.
527 * @param Interface* pointer to the interface that needs to be updated. 527 * @param Interface* pointer to the interface that needs to be updated.
528 */ 528 */
529void MainWindowImp::updateInterface(Interface *i) 529void MainWindowImp::updateInterface(Interface *i)
530{ 530{
531 if(!advancedUserMode) 531 if(!advancedUserMode)
532 { 532 {
533 if(i->getInterfaceName() == "lo") 533 if(i->getInterfaceName() == "lo")
534 return; 534 return;
535 } 535 }
536 536
537 QListViewItem *item = NULL; 537 QListViewItem *item = NULL;
538 538
539 // Find the interface, making it if needed. 539 // Find the interface, making it if needed.
540 if(items.find(i) == items.end()) 540 if(items.find(i) == items.end())
541 { 541 {
542 item = new QListViewItem(connectionList, "", "", ""); 542 item = new QListViewItem(connectionList, "", "", "");
543 // See if you can't find a module owner for this interface 543 // See if you can't find a module owner for this interface
544 QMap<Module*, QLibrary*>::Iterator it; 544 QMap<Module*, QLibrary*>::Iterator it;
545 for( it = libraries.begin(); it != libraries.end(); ++it ) 545 for( it = libraries.begin(); it != libraries.end(); ++it )
546 { 546 {
547 if(it.key()->isOwner(i)) 547 if(it.key()->isOwner(i))
548 i->setModuleOwner(it.key()); 548 i->setModuleOwner(it.key());
549 } 549 }
550 items.insert(i, item); 550 items.insert(i, item);
551 interfaceItems.insert(item, i); 551 interfaceItems.insert(item, i);
552 } 552 }
553 else 553 else
554 item = items[i]; 554 item = items[i];
555 555
556 // Update the icons and information 556 // Update the icons and information
557#ifdef QWS 557#ifdef QWS
558 item->setPixmap(0, (Resource::loadPixmap(i->getStatus() ? "up": "down"))); 558 item->setPixmap(0, (Resource::loadPixmap(i->getStatus() ? "up": "down")));
559#else 559#else
560 item->setPixmap(0, (SmallIcon(i->getStatus() ? "up": "down"))); 560 item->setPixmap(0, (SmallIcon(i->getStatus() ? "up": "down")));
561#endif 561#endif
562 562
563 QString typeName = "lan"; 563 QString typeName = "lan";
564 if(i->getInterfaceName() == "lo") 564 if(i->getInterfaceName() == "lo")
565 typeName = "lo"; 565 typeName = "lo";
566 if(i->getInterfaceName().contains("irda")) 566 if(i->getInterfaceName().contains("irda"))
567 typeName = "irda"; 567 typeName = "irda";
568 if(i->getInterfaceName().contains("wlan")) 568 if(i->getInterfaceName().contains("wlan"))
569 typeName = "wlan"; 569 typeName = "wlan";
570 if(i->getInterfaceName().contains("usb")) 570 if(i->getInterfaceName().contains("usb"))
571 typeName = "usb"; 571 typeName = "usb";
572 572
573 if(!i->isAttached()) 573 if(!i->isAttached())
574 typeName = "connect_no"; 574 typeName = "connect_no";
575 // Actually try to use the Module 575 // Actually try to use the Module
576 if(i->getModuleOwner() != NULL) 576 if(i->getModuleOwner() != NULL)
577 typeName = i->getModuleOwner()->getPixmapName(i); 577 typeName = i->getModuleOwner()->getPixmapName(i);
578 578
579#ifdef QWS 579#ifdef QWS
580 item->setPixmap(1, (Resource::loadPixmap(QString("networksettings/") + typeName))); 580 item->setPixmap(1, (Resource::loadPixmap(QString("networksettings/") + typeName)));
581#else 581#else
582 item->setPixmap(1, (SmallIcon(typeName))); 582 item->setPixmap(1, (SmallIcon(typeName)));
583#endif 583#endif
584 item->setText(2, i->getHardwareName()); 584 item->setText(2, i->getHardwareName());
585 item->setText(3, QString("(%1)").arg(i->getInterfaceName())); 585 item->setText(3, QString("(%1)").arg(i->getInterfaceName()));
586 item->setText(4, (i->getStatus()) ? i->getIp() : QString("")); 586 item->setText(4, (i->getStatus()) ? i->getIp() : QString(""));
587} 587}
588 588
589void MainWindowImp::newProfileChanged(const QString& newText) 589void MainWindowImp::newProfileChanged(const QString& newText)
590{ 590{
591 if(newText.length() > 0) 591 if(newText.length() > 0)
592 newProfileButton->setEnabled(true); 592 newProfileButton->setEnabled(true);
593 else 593 else
594 newProfileButton->setEnabled(false); 594 newProfileButton->setEnabled(false);
595} 595}
596 596
597/** 597/**
598 * Adds a new profile to the list of profiles. 598 * Adds a new profile to the list of profiles.
599 * Don't add profiles that already exists. 599 * Don't add profiles that already exists.
600 * Appends to the list and QStringList 600 * Appends to the list and QStringList
601 */ 601 */
602void MainWindowImp::addProfile() 602void MainWindowImp::addProfile()
603{ 603{
604 QString newProfileName = newProfile->text(); 604 QString newProfileName = newProfile->text();
605 if(profiles.grep(newProfileName).count() > 0) 605 if(profiles.grep(newProfileName).count() > 0)
606 { 606 {
607 QMessageBox::information(this, "Can't Add","Profile already exists.", QMessageBox::Ok); 607 QMessageBox::information(this, "Can't Add","Profile already exists.", QMessageBox::Ok);
608 return; 608 return;
609 } 609 }
610 profiles.append(newProfileName); 610 profiles.append(newProfileName);
611 profilesList->insertItem(newProfileName); 611 profilesList->insertItem(newProfileName);
612} 612}
613 613
614/** 614/**
615 * Removes the currently selected profile in the combo. 615 * Removes the currently selected profile in the combo.
616 * Doesn't delete if there are less then 2 profiles. 616 * Doesn't delete if there are less then 2 profiles.
617 */ 617 */
618void MainWindowImp::removeProfile() 618void MainWindowImp::removeProfile()
619{ 619{
620 if(profilesList->count() <= 1) 620 if(profilesList->count() <= 1)
621 { 621 {
622 QMessageBox::information(this, "Can't remove.","At least one profile\nis needed.", QMessageBox::Ok); 622 QMessageBox::information(this, "Can't remove.","At least one profile\nis needed.", QMessageBox::Ok);
623 return; 623 return;
624 } 624 }
625 QString profileToRemove = profilesList->currentText(); 625 QString profileToRemove = profilesList->currentText();
626 if(profileToRemove == "All") 626 if(profileToRemove == "All")
627 { 627 {
628 QMessageBox::information(this, "Can't remove.","Can't remove default.", QMessageBox::Ok); 628 QMessageBox::information(this, "Can't remove.","Can't remove default.", QMessageBox::Ok);
629 return; 629 return;
630 } 630 }
631 // Can't remove the curent profile 631 // Can't remove the curent profile
632 if(profileToRemove == currentProfileLabel->text()) 632 if(profileToRemove == currentProfileLabel->text())
633 { 633 {
634 QMessageBox::information(this, "Can't remove.",QString("%1 is the current profile.").arg(profileToRemove), QMessageBox::Ok); 634 QMessageBox::information(this, "Can't remove.",QString("%1 is the current profile.").arg(profileToRemove), QMessageBox::Ok);
635 return; 635 return;
636 636
637 } 637 }
638 638
639 if(QMessageBox::information(this, "Question",QString("Remove profile: %1").arg(profileToRemove), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok) 639 if(QMessageBox::information(this, "Question",QString("Remove profile: %1").arg(profileToRemove), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
640 { 640 {
641 profiles = QStringList::split(" ", profiles.join(" ").replace(QRegExp(profileToRemove), "")); 641 profiles = QStringList::split(" ", profiles.join(" ").replace(QRegExp(profileToRemove), ""));
642 profilesList->clear(); 642 profilesList->clear();
643 for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it) 643 for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it)
644 profilesList->insertItem((*it)); 644 profilesList->insertItem((*it));
645 645
646 // Remove any interface settings and mappings. 646 // Remove any interface settings and mappings.
647 Interfaces interfaces; 647 Interfaces interfaces;
648 // Go through them one by one 648 // Go through them one by one
649 QMap<Interface*, QListViewItem*>::Iterator it; 649 QMap<Interface*, QListViewItem*>::Iterator it;
650 for( it = items.begin(); it != items.end(); ++it ) 650 for( it = items.begin(); it != items.end(); ++it )
651 { 651 {
652 QString interfaceName = it.key()->getInterfaceName(); 652 QString interfaceName = it.key()->getInterfaceName();
653 qDebug(interfaceName.latin1()); 653 odebug << interfaceName.latin1() << oendl;
654 if(interfaces.setInterface(interfaceName + "_" + profileToRemove)) 654 if(interfaces.setInterface(interfaceName + "_" + profileToRemove))
655 { 655 {
656 interfaces.removeInterface(); 656 interfaces.removeInterface();
657 if(interfaces.setMapping(interfaceName)) 657 if(interfaces.setMapping(interfaceName))
658 { 658 {
659 if(profilesList->count() == 1) 659 if(profilesList->count() == 1)
660 interfaces.removeMapping(); 660 interfaces.removeMapping();
661 else 661 else
662 { 662 {
663 interfaces.removeMap("map", interfaceName + "_" + profileToRemove); 663 interfaces.removeMap("map", interfaceName + "_" + profileToRemove);
664 } 664 }
665 } 665 }
666 interfaces.write(); 666 interfaces.write();
667 break; 667 break;
668 } 668 }
669 } 669 }
670 } 670 }
671} 671}
672 672
673/** 673/**
674 * A new profile has been selected, change. 674 * A new profile has been selected, change.
675 * @param newProfile the new profile. 675 * @param newProfile the new profile.
676 */ 676 */
677void MainWindowImp::changeProfile() 677void MainWindowImp::changeProfile()
678{ 678{
679 if(profilesList->currentItem() == -1) 679 if(profilesList->currentItem() == -1)
680 { 680 {
681 QMessageBox::information(this, "Can't Change.","Please select a profile.", QMessageBox::Ok); 681 QMessageBox::information(this, "Can't Change.","Please select a profile.", QMessageBox::Ok);
682 return; 682 return;
683 } 683 }
684 QString newProfile = profilesList->text(profilesList->currentItem()); 684 QString newProfile = profilesList->text(profilesList->currentItem());
685 if(newProfile != currentProfileLabel->text()) 685 if(newProfile != currentProfileLabel->text())
686 { 686 {
687 currentProfileLabel->setText(newProfile); 687 currentProfileLabel->setText(newProfile);
688 QFile::remove(scheme); 688 QFile::remove(scheme);
689 QFile file(scheme); 689 QFile file(scheme);
690 if ( file.open(IO_ReadWrite) ) 690 if ( file.open(IO_ReadWrite) )
691 { 691 {
692 QTextStream stream( &file ); 692 QTextStream stream( &file );
693 stream << QString("SCHEME=%1").arg(newProfile); 693 stream << QString("SCHEME=%1").arg(newProfile);
694 file.close(); 694 file.close();
695 } 695 }
696 // restart all up devices? 696 // restart all up devices?
697 if(QMessageBox::information(this, "Question","Restart all running interfaces?", QMessageBox::Ok, QMessageBox::No) == QMessageBox::Ok) 697 if(QMessageBox::information(this, "Question","Restart all running interfaces?", QMessageBox::Ok, QMessageBox::No) == QMessageBox::Ok)
698 { 698 {
699 // Go through them one by one 699 // Go through them one by one
700 QMap<Interface*, QListViewItem*>::Iterator it; 700 QMap<Interface*, QListViewItem*>::Iterator it;
701 for( it = items.begin(); it != items.end(); ++it ) 701 for( it = items.begin(); it != items.end(); ++it )
702 { 702 {
703 if(it.key()->getStatus() == true) 703 if(it.key()->getStatus() == true)
704 it.key()->restart(); 704 it.key()->restart();
705 } 705 }
706 } 706 }
707 } 707 }
708 // TODO change the profile in the modules 708 // TODO change the profile in the modules
709} 709}
710 710
711 711
712void MainWindowImp::makeChannel() 712void MainWindowImp::makeChannel()
713{ 713{
714 channel = new QCopChannel( "QPE/Application/networksettings", this ); 714 channel = new QCopChannel( "QPE/Application/networksettings", this );
715 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), 715 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
716 this, SLOT(receive(const QCString&,const QByteArray&)) ); 716 this, SLOT(receive(const QCString&,const QByteArray&)) );
717} 717}
718 718
719void MainWindowImp::receive(const QCString &msg, const QByteArray &arg) 719void MainWindowImp::receive(const QCString &msg, const QByteArray &arg)
720{ 720{
721 bool found = false; 721 bool found = false;
722 qDebug("MainWindowImp::receive QCop msg >"+msg+"<"); 722 odebug << "MainWindowImp::receive QCop msg >"+msg+"<" << oendl;
723 if (msg == "raise") 723 if (msg == "raise")
724 { 724 {
725 raise(); 725 raise();
726 return; 726 return;
727 } 727 }
728 728
729 QString dest = msg.left(msg.find("(")); 729 QString dest = msg.left(msg.find("("));
730 QCString param = msg.right(msg.length() - msg.find("(") - 1); 730 QCString param = msg.right(msg.length() - msg.find("(") - 1);
731 param = param.left( param.length() - 1 ); 731 param = param.left( param.length() - 1 );
732 qDebug("dest >%s< param >"+param+"<",dest.latin1()); 732 odebug << "dest >" << dest.latin1() << "< param >"+param+"<" << oendl;
733 733
734 QMap<Module*, QLibrary*>::Iterator it; 734 QMap<Module*, QLibrary*>::Iterator it;
735 for( it = libraries.begin(); it != libraries.end(); ++it ) 735 for( it = libraries.begin(); it != libraries.end(); ++it )
736 { 736 {
737 qDebug("plugin >%s<", it.key()->type().latin1() ); 737 odebug << "plugin >" << it.key()->type().latin1() << "<" << oendl;
738 if(it.key()->type() == dest) 738 if(it.key()->type() == dest)
739 { 739 {
740 it.key()->receive( param, arg ); 740 it.key()->receive( param, arg );
741 found = true; 741 found = true;
742 } 742 }
743 } 743 }
744 744
745 745
746 if (found) QPEApplication::setKeepRunning(); 746 if (found) QPEApplication::setKeepRunning();
747 else qDebug("Huh what do ya want"); 747 else odebug << "Huh what do ya want" << oendl;
748} 748}
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 @@
25 */ 25 */
26 26
27#include "accounts.h" 27#include "accounts.h"
28#include "authwidget.h" 28#include "authwidget.h"
29#include "pppdata.h" 29#include "pppdata.h"
30#include "edit.h" 30#include "edit.h"
31 31
32/* OPIE */ 32/* OPIE */
33#include <qpe/qpeapplication.h> 33#include <qpe/qpeapplication.h>
34 34
35/* QT */ 35/* QT */
36#include <qdir.h> 36#include <qdir.h>
37#include <qlayout.h> 37#include <qlayout.h>
38#include <qtabwidget.h> 38#include <qtabwidget.h>
39#include <qtabdialog.h> 39#include <qtabdialog.h>
40#include <qwhatsthis.h> 40#include <qwhatsthis.h>
41#include <qmessagebox.h> 41#include <qmessagebox.h>
42#include <qapplication.h> 42#include <qapplication.h>
43#include <qbuttongroup.h> 43#include <qbuttongroup.h>
44#include <qmessagebox.h> 44#include <qmessagebox.h>
45#include <qvgroupbox.h> 45#include <qvgroupbox.h>
46 46
47/* STD */ 47/* STD */
48#include <stdlib.h> 48#include <stdlib.h>
49 49
50void parseargs(char* buf, char** args); 50void parseargs(char* buf, char** args);
51 51
52 52
53AccountWidget::AccountWidget( PPPData *pd, QWidget *parent, const char *name, WFlags f ) 53AccountWidget::AccountWidget( PPPData *pd, QWidget *parent, const char *name, WFlags f )
54 : ChooserWidget( pd, parent, name, f ) 54 : ChooserWidget( pd, parent, name, f )
55{ 55{
56 56
57 QWhatsThis::add(edit_b, tr("Allows you to modify the selected account")); 57 QWhatsThis::add(edit_b, tr("Allows you to modify the selected account"));
58 QWhatsThis::add(new_b, tr("Create a new dialup connection\n" 58 QWhatsThis::add(new_b, tr("Create a new dialup connection\n"
59 "to the Internet")); 59 "to the Internet"));
60 QWhatsThis::add(copy_b, 60 QWhatsThis::add(copy_b,
61 tr("Makes a copy of the selected account. All\n" 61 tr("Makes a copy of the selected account. All\n"
62 "settings of the selected account are copied\n" 62 "settings of the selected account are copied\n"
63 "to a new account, that you can modify to fit your\n" 63 "to a new account, that you can modify to fit your\n"
64 "needs")); 64 "needs"));
65 QWhatsThis::add(delete_b, 65 QWhatsThis::add(delete_b,
66 tr("<p>Deletes the selected account\n\n" 66 tr("<p>Deletes the selected account\n\n"
67 "<font color=\"red\"><b>Use with care!</b></font>")); 67 "<font color=\"red\"><b>Use with care!</b></font>"));
68 68
69 69
70 70
71 copy_b->setEnabled( false ); //FIXME 71 copy_b->setEnabled( false ); //FIXME
72 // delete_b->setEnabled( false ); //FIXME 72 // delete_b->setEnabled( false ); //FIXME
73 73
74 listListbox->insertStringList(_pppdata->getAccountList()); 74 listListbox->insertStringList(_pppdata->getAccountList());
75 75
76 for (uint i = 0; i < listListbox->count(); i++) 76 for (uint i = 0; i < listListbox->count(); i++)
77 { 77 {
78 if ( listListbox->text(i) == _pppdata->accname() ) 78 if ( listListbox->text(i) == _pppdata->accname() )
79 listListbox->setCurrentItem( i ); 79 listListbox->setCurrentItem( i );
80 } 80 }
81} 81}
82 82
83 83
84 84
85void AccountWidget::slotListBoxSelect(int idx) 85void AccountWidget::slotListBoxSelect(int idx)
86{ 86{
87 bool ok = _pppdata->setAccount( listListbox->text(idx) ); 87 bool ok = _pppdata->setAccount( listListbox->text(idx) );
88 ok = (bool)(idx != -1); 88 ok = (bool)(idx != -1);
89 delete_b->setEnabled(ok); 89 delete_b->setEnabled(ok);
90 edit_b->setEnabled(ok); 90 edit_b->setEnabled(ok);
91 //FIXME copy_b->setEnabled(ok); 91 //FIXME copy_b->setEnabled(ok);
92} 92}
93 93
94void AccountWidget::edit() 94void AccountWidget::edit()
95{ 95{
96 _pppdata->setAccount(listListbox->text(listListbox->currentItem())); 96 _pppdata->setAccount(listListbox->text(listListbox->currentItem()));
97 97
98 int result = doTab(); 98 int result = doTab();
99 99
100 if(result == QDialog::Accepted) 100 if(result == QDialog::Accepted)
101 { 101 {
102 listListbox->changeItem(_pppdata->accname(),listListbox->currentItem()); 102 listListbox->changeItem(_pppdata->accname(),listListbox->currentItem());
103 // emit resetaccounts(); 103 // emit resetaccounts();
104 _pppdata->save(); 104 _pppdata->save();
105 } 105 }
106} 106}
107 107
108 108
109void AccountWidget::create() 109void AccountWidget::create()
110{ 110{
111 111
112 // if(listListbox->count() == MAX_ACCOUNTS) { 112 // if(listListbox->count() == MAX_ACCOUNTS) {
113 // QMessageBox::information(this, "sorry", 113 // QMessageBox::information(this, "sorry",
114 // tr("Maximum number of accounts reached.")); 114 // tr("Maximum number of accounts reached."));
115 // return; 115 // return;
116 // } 116 // }
117 117
118 int result; 118 int result;
119 if (_pppdata->newaccount() == -1) 119 if (_pppdata->newaccount() == -1)
120 { 120 {
121 qDebug("_pppdata->newaccount() == -1"); 121 odebug << "_pppdata->newaccount() == -1" << oendl;
122 return; 122 return;
123 } 123 }
124 result = doTab(); 124 result = doTab();
125 125
126 if(result == QDialog::Accepted) 126 if(result == QDialog::Accepted)
127 { 127 {
128 listListbox->insertItem(_pppdata->accname()); 128 listListbox->insertItem(_pppdata->accname());
129 listListbox->setSelected(listListbox->findItem(_pppdata->accname()),true); 129 listListbox->setSelected(listListbox->findItem(_pppdata->accname()),true);
130 130
131 _pppdata->save(); 131 _pppdata->save();
132 } 132 }
133 else 133 else
134 _pppdata->deleteAccount(); 134 _pppdata->deleteAccount();
135} 135}
136 136
137 137
138void AccountWidget::copy() 138void AccountWidget::copy()
139{ 139{
140 // if(listListbox->count() == MAX_ACCOUNTS) { 140 // if(listListbox->count() == MAX_ACCOUNTS) {
141 // QMessageBox::information(this, "sorry", tr("Maximum number of accounts reached.")); 141 // QMessageBox::information(this, "sorry", tr("Maximum number of accounts reached."));
142 // return; 142 // return;
143 // } 143 // }
144 144
145 if(listListbox->currentItem()<0) 145 if(listListbox->currentItem()<0)
146 { 146 {
147 QMessageBox::information(this, "sorry", tr("No account selected.")); 147 QMessageBox::information(this, "sorry", tr("No account selected."));
148 return; 148 return;
149 } 149 }
150 150
151 _pppdata->copyaccount(listListbox->currentText()); 151 _pppdata->copyaccount(listListbox->currentText());
152 152
153 listListbox->insertItem(_pppdata->accname()); 153 listListbox->insertItem(_pppdata->accname());
154 // emit resetaccounts(); 154 // emit resetaccounts();
155 _pppdata->save(); 155 _pppdata->save();
156} 156}
157 157
158 158
159void AccountWidget::remove() 159void AccountWidget::remove()
160{ 160{
161 161
162 QString s = tr("Are you sure you want to delete\nthe account \"%1\"?") 162 QString s = tr("Are you sure you want to delete\nthe account \"%1\"?")
163 .arg(listListbox->text(listListbox->currentItem())); 163 .arg(listListbox->text(listListbox->currentItem()));
164 164
165 if(QMessageBox::warning(this,tr("Confirm"),s, 165 if(QMessageBox::warning(this,tr("Confirm"),s,
166 QMessageBox::Yes,QMessageBox::No 166 QMessageBox::Yes,QMessageBox::No
167 ) != QMessageBox::Yes) 167 ) != QMessageBox::Yes)
168 return; 168 return;
169 169
170 if(_pppdata->deleteAccount(listListbox->text(listListbox->currentItem()))) 170 if(_pppdata->deleteAccount(listListbox->text(listListbox->currentItem())))
171 listListbox->removeItem(listListbox->currentItem()); 171 listListbox->removeItem(listListbox->currentItem());
172 172
173 173
174 // emit resetaccounts(); 174 // emit resetaccounts();
175 // _pppdata->save(); 175 // _pppdata->save();
176 176
177 177
178 slotListBoxSelect(listListbox->currentItem()); 178 slotListBoxSelect(listListbox->currentItem());
179 179
180} 180}
181 181
182 182
183int AccountWidget::doTab() 183int AccountWidget::doTab()
184{ 184{
185 QDialog *dlg = new QDialog( 0, "newAccount", true, Qt::WStyle_ContextHelp ); 185 QDialog *dlg = new QDialog( 0, "newAccount", true, Qt::WStyle_ContextHelp );
186 QVBoxLayout *layout = new QVBoxLayout( dlg ); 186 QVBoxLayout *layout = new QVBoxLayout( dlg );
187 layout->setSpacing( 0 ); 187 layout->setSpacing( 0 );
188 layout->setMargin( 1 ); 188 layout->setMargin( 1 );
189 189
190 QTabWidget *tabWindow = new QTabWidget( dlg, "tabWindow" ); 190 QTabWidget *tabWindow = new QTabWidget( dlg, "tabWindow" );
191 layout->addWidget( tabWindow ); 191 layout->addWidget( tabWindow );
192 192
193 bool isnewaccount; 193 bool isnewaccount;
194 194
195 if(_pppdata->accname().isEmpty()) 195 if(_pppdata->accname().isEmpty())
196 { 196 {
197 dlg->setCaption(tr("New Account")); 197 dlg->setCaption(tr("New Account"));
198 isnewaccount = true; 198 isnewaccount = true;
199 } 199 }
200 else 200 else
201 { 201 {
202 QString tit = tr("Edit Account: "); 202 QString tit = tr("Edit Account: ");
203 tit += _pppdata->accname(); 203 tit += _pppdata->accname();
204 dlg->setCaption(tit); 204 dlg->setCaption(tit);
205 isnewaccount = false; 205 isnewaccount = false;
206 } 206 }
207 207
208 // // DIAL WIDGET 208 // // DIAL WIDGET
209 dial_w = new DialWidget( _pppdata, tabWindow, isnewaccount, "Dial Setup"); 209 dial_w = new DialWidget( _pppdata, tabWindow, isnewaccount, "Dial Setup");
210 tabWindow->addTab( dial_w, tr("Dial") ); 210 tabWindow->addTab( dial_w, tr("Dial") );
211 211
212 // // AUTH WIDGET 212 // // AUTH WIDGET
213 auth_w = new AuthWidget( _pppdata, tabWindow, isnewaccount, tr("Edit Login Script")); 213 auth_w = new AuthWidget( _pppdata, tabWindow, isnewaccount, tr("Edit Login Script"));
214 tabWindow->addTab( auth_w, tr("Authentication") ); 214 tabWindow->addTab( auth_w, tr("Authentication") );
215 215
216 // // IP WIDGET 216 // // IP WIDGET
217 ip_w = new IPWidget( _pppdata, tabWindow, isnewaccount, tr("IP Setup")); 217 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
49 auth->insertItem(tr("Terminal-based")); 49 auth->insertItem(tr("Terminal-based"));
50 auth->insertItem(tr("CHAP")); 50 auth->insertItem(tr("CHAP"));
51 auth->insertItem(tr("PAP/CHAP")); 51 auth->insertItem(tr("PAP/CHAP"));
52 layout->addWidget(auth, 0, 1); 52 layout->addWidget(auth, 0, 1);
53 53
54 connect( auth, SIGNAL(activated(const QString&)), 54 connect( auth, SIGNAL(activated(const QString&)),
55 SLOT(authChanged(const QString&))); 55 SLOT(authChanged(const QString&)));
56 56
57 QString tmp = tr("<p>Specifies the method used to identify yourself to\n" 57 QString tmp = tr("<p>Specifies the method used to identify yourself to\n"
58 "the PPP server. Most universities still use\n" 58 "the PPP server. Most universities still use\n"
59 "<b>Terminal</b>- or <b>Script</b>-based authentication,\n" 59 "<b>Terminal</b>- or <b>Script</b>-based authentication,\n"
60 "while most ISP use <b>PAP</b> and/or <b>CHAP</b>. If\n" 60 "while most ISP use <b>PAP</b> and/or <b>CHAP</b>. If\n"
61 "unsure, contact your ISP.\n" 61 "unsure, contact your ISP.\n"
62 "\n" 62 "\n"
63 "If you can choose between PAP and CHAP,\n" 63 "If you can choose between PAP and CHAP,\n"
64 "choose CHAP, because it's much safer. If you don't know\n" 64 "choose CHAP, because it's much safer. If you don't know\n"
65 "whether PAP or CHAP is right, choose PAP/CHAP."); 65 "whether PAP or CHAP is right, choose PAP/CHAP.");
66 66
67 QWhatsThis::add(auth_l,tmp); 67 QWhatsThis::add(auth_l,tmp);
68 QWhatsThis::add(auth,tmp); 68 QWhatsThis::add(auth,tmp);
69 69
70 user_l = new QLabel( tr("Username: "), this); 70 user_l = new QLabel( tr("Username: "), this);
71 layout->addWidget( user_l, 1, 0 ); 71 layout->addWidget( user_l, 1, 0 );
72 userName = new QLineEdit( this, "usernameEdit" ); 72 userName = new QLineEdit( this, "usernameEdit" );
73 layout->addWidget( userName, 1, 1 ); 73 layout->addWidget( userName, 1, 1 );
74 tmp = tr("Enter your username here..."); 74 tmp = tr("Enter your username here...");
75 QWhatsThis::add( user_l, tmp ); 75 QWhatsThis::add( user_l, tmp );
76 QWhatsThis::add( userName, tmp ); 76 QWhatsThis::add( userName, tmp );
77 77
78 pw_l = new QLabel( tr("Password: "), this); 78 pw_l = new QLabel( tr("Password: "), this);
79 layout->addWidget( pw_l, 2, 0 ); 79 layout->addWidget( pw_l, 2, 0 );
80 passWord = new QLineEdit( this, "pw" ); 80 passWord = new QLineEdit( this, "pw" );
81 passWord->setAutoMask( true ); 81 passWord->setAutoMask( true );
82 passWord->setEchoMode( QLineEdit::Password ); 82 passWord->setEchoMode( QLineEdit::Password );
83 layout->addWidget( passWord, 2, 1 ); 83 layout->addWidget( passWord, 2, 1 );
84 hidePw = new QToolButton( this ); 84 hidePw = new QToolButton( this );
85 hidePw->setPixmap( QPixmap( ( const char** ) image0_data ) ); 85 hidePw->setPixmap( QPixmap( ( const char** ) image0_data ) );
86 hidePw->setToggleButton( true ); 86 hidePw->setToggleButton( true );
87 layout->addWidget( hidePw, 2, 2 ); 87 layout->addWidget( hidePw, 2, 2 );
88 88
89 connect(hidePw, SIGNAL(toggled(bool)), SLOT(toggleEchoMode(bool))); 89 connect(hidePw, SIGNAL(toggled(bool)), SLOT(toggleEchoMode(bool)));
90 90
91 tmp = tr("Enter your password here"); 91 tmp = tr("Enter your password here");
92 QWhatsThis::add( pw_l, tmp ); 92 QWhatsThis::add( pw_l, tmp );
93 QWhatsThis::add( passWord, tmp ); 93 QWhatsThis::add( passWord, tmp );
94 94
95 store_password = new QCheckBox(tr("Store password"), this); 95 store_password = new QCheckBox(tr("Store password"), this);
96 layout->addMultiCellWidget(store_password, 3, 3, 0, 1, AlignRight); 96 layout->addMultiCellWidget(store_password, 3, 3, 0, 1, AlignRight);
97 QWhatsThis::add(store_password, 97 QWhatsThis::add(store_password,
98 tr("<p>When this is turned on, your ISP password\n" 98 tr("<p>When this is turned on, your ISP password\n"
99 "will be saved in <i>kppp</i>'s config file, so\n" 99 "will be saved in <i>kppp</i>'s config file, so\n"
100 "you do not need to type it in every time.\n" 100 "you do not need to type it in every time.\n"
101 "\n" 101 "\n"
102 "<b><font color=\"red\">Warning:</font> your password will be stored as\n" 102 "<b><font color=\"red\">Warning:</font> your password will be stored as\n"
103 "plain text in the config file, which is\n" 103 "plain text in the config file, which is\n"
104 "readable only to you. Make sure nobody\n" 104 "readable only to you. Make sure nobody\n"
105 "gains access to this file!")); 105 "gains access to this file!"));
106 106
107 if (isNewAccount){ 107 if (isNewAccount){
108 // select PAP/CHAP as default 108 // select PAP/CHAP as default
109 auth->setCurrentItem(AUTH_PAPCHAP); 109 auth->setCurrentItem(AUTH_PAPCHAP);
110 store_password->setChecked(true); 110 store_password->setChecked(true);
111 }else{ 111 }else{
112 auth->setCurrentItem(_pppdata->authMethod()); 112 auth->setCurrentItem(_pppdata->authMethod());
113 authChanged( auth->currentText() ); 113 authChanged( auth->currentText() );
114 userName->setText( _pppdata->storedUsername() ); 114 userName->setText( _pppdata->storedUsername() );
115 store_password->setChecked(_pppdata->storePassword()); 115 store_password->setChecked(_pppdata->storePassword());
116 if (store_password->isChecked()) 116 if (store_password->isChecked())
117 passWord->setText( _pppdata->storedPassword() ); 117 passWord->setText( _pppdata->storedPassword() );
118 } 118 }
119} 119}
120 120
121bool AuthWidget::check() 121bool AuthWidget::check()
122{ 122{
123 bool ret = true; 123 bool ret = true;
124 if (scriptWidget){ 124 if (scriptWidget){
125 if (!scriptWidget->check()){ 125 if (!scriptWidget->check()){
126 QMessageBox::critical(this, tr("error"), tr("<qt>Login script has unbalanced loop Start/End<qt>")); 126 QMessageBox::critical(this, tr("error"), tr("<qt>Login script has unbalanced loop Start/End<qt>"));
127 ret = false; 127 ret = false;
128 } 128 }
129 } 129 }
130 return ret; 130 return ret;
131} 131}
132 132
133void AuthWidget::save() 133void AuthWidget::save()
134{ 134{
135 _pppdata->setAuthMethod(auth->currentItem()); 135 _pppdata->setAuthMethod(auth->currentItem());
136 if (scriptWidget) scriptWidget->save(); 136 if (scriptWidget) scriptWidget->save();
137 _pppdata->setStoredUsername( userName->text() ); 137 _pppdata->setStoredUsername( userName->text() );
138 _pppdata->setStorePassword(store_password->isChecked()); 138 _pppdata->setStorePassword(store_password->isChecked());
139 if (store_password->isChecked()) 139 if (store_password->isChecked())
140 _pppdata->setStoredPassword( passWord->text() ); 140 _pppdata->setStoredPassword( passWord->text() );
141} 141}
142 142
143void AuthWidget::authChanged( const QString &authStr ) 143void AuthWidget::authChanged( const QString &authStr )
144{ 144{
145 qDebug("AuthWidget::authChanged( %s )", authStr.latin1() ); 145 odebug << "AuthWidget::authChanged( " << authStr.latin1() << " )" << oendl;
146 if ( authStr.contains( tr("Script-based") ) ){ 146 if ( authStr.contains( tr("Script-based") ) ){
147 showUsernamePassword( false ); 147 showUsernamePassword( false );
148 showScriptWindow( true ); 148 showScriptWindow( true );
149 } else if ( authStr.contains( tr("PAP") ) || 149 } else if ( authStr.contains( tr("PAP") ) ||
150 authStr.contains( tr("CHAP") ) ){ 150 authStr.contains( tr("CHAP") ) ){
151 showUsernamePassword( true ); 151 showUsernamePassword( true );
152 showScriptWindow( false ); 152 showScriptWindow( false );
153 } else { 153 } else {
154 qDebug("do not really know how to handle"); 154 odebug << "do not really know how to handle" << oendl;
155 showUsernamePassword( false ); 155 showUsernamePassword( false );
156 showScriptWindow( false ); 156 showScriptWindow( false );
157 } 157 }
158} 158}
159 159
160 160
161void AuthWidget::showUsernamePassword( bool show ) 161void AuthWidget::showUsernamePassword( bool show )
162{ 162{
163 if (show){ 163 if (show){
164 user_l->show(); 164 user_l->show();
165 userName->show(); 165 userName->show();
166 pw_l->show(); 166 pw_l->show();
167 passWord->show(); 167 passWord->show();
168 store_password->show(); 168 store_password->show();
169 hidePw->show(); 169 hidePw->show();
170 }else{//!show 170 }else{//!show
171 user_l->hide(); 171 user_l->hide();
172 userName->hide(); 172 userName->hide();
173 pw_l->hide(); 173 pw_l->hide();
174 passWord->hide(); 174 passWord->hide();
175 store_password->hide(); 175 store_password->hide();
176 hidePw->hide(); 176 hidePw->hide();
177 } 177 }
178} 178}
179 179
180void AuthWidget::showScriptWindow( bool show ) 180void AuthWidget::showScriptWindow( bool show )
181{ 181{
182 if (show){ 182 if (show){
183 if (!scriptWidget){ 183 if (!scriptWidget){
184 scriptWidget = new ScriptWidget( _pppdata, this, isNewAccount, "scriptWid"); 184 scriptWidget = new ScriptWidget( _pppdata, this, isNewAccount, "scriptWid");
185 layout->addMultiCellWidget( scriptWidget, 1, 4, 0, 1 ); 185 layout->addMultiCellWidget( scriptWidget, 1, 4, 0, 1 );
186 } 186 }
187 scriptWidget->show(); 187 scriptWidget->show();
188 }else{ // !show 188 }else{ // !show
189 if (scriptWidget) scriptWidget->hide(); 189 if (scriptWidget) scriptWidget->hide();
190 } 190 }
191} 191}
192 192
193void AuthWidget::toggleEchoMode( bool t ) 193void AuthWidget::toggleEchoMode( bool t )
194{ 194{
195 passWord->setEchoMode( t ? QLineEdit::Normal : QLineEdit::Password ); 195 passWord->setEchoMode( t ? QLineEdit::Normal : QLineEdit::Password );
196} 196}
197 197
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 *) {
379 QString bm = QObject::tr("Dialing %1").arg(bmarg); 379 QString bm = QObject::tr("Dialing %1").arg(bmarg);
380 messg->setText(bm); 380 messg->setText(bm);
381 emit debugMessage(bm); 381 emit debugMessage(bm);
382 382
383 QString pn = _ifaceppp->data()->modemDialStr(); 383 QString pn = _ifaceppp->data()->modemDialStr();
384 pn += _ifaceppp->data()->dialPrefix(); 384 pn += _ifaceppp->data()->dialPrefix();
385 pn += *plist.at(dialnumber); 385 pn += *plist.at(dialnumber);
386 if(++dialnumber >= plist.count()) 386 if(++dialnumber >= plist.count())
387 dialnumber = 0; 387 dialnumber = 0;
388 writeline(pn); 388 writeline(pn);
389 389
390 setExpect(_ifaceppp->data()->modemConnectResp()); 390 setExpect(_ifaceppp->data()->modemConnectResp());
391 vmain = 100; 391 vmain = 100;
392 return; 392 return;
393 } 393 }
394 } 394 }
395 395
396 // wait for connect, but redial if BUSY or wait for user cancel 396 // wait for connect, but redial if BUSY or wait for user cancel
397 // if NO CARRIER or NO DIALTONE 397 // if NO CARRIER or NO DIALTONE
398 if(vmain == 100) { 398 if(vmain == 100) {
399 if(!expecting) { 399 if(!expecting) {
400 myreadbuffer = _ifaceppp->data()->modemConnectResp(); 400 myreadbuffer = _ifaceppp->data()->modemConnectResp();
401 setExpect("\n"); 401 setExpect("\n");
402 vmain = 101; 402 vmain = 101;
403 return; 403 return;
404 } 404 }
405 405
406 if(readbuffer.contains(_ifaceppp->data()->modemBusyResp())) { 406 if(readbuffer.contains(_ifaceppp->data()->modemBusyResp())) {
407 timeout_timer->stop(); 407 timeout_timer->stop();
408 timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000); 408 timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000);
409 409
410 messg->setText(QObject::tr("Line busy. Hanging up...")); 410 messg->setText(QObject::tr("Line busy. Hanging up..."));
411 emit debugPutChar('\n'); 411 emit debugPutChar('\n');
412 _ifaceppp->modem()->hangup(); 412 _ifaceppp->modem()->hangup();
413 413
414 if(_ifaceppp->data()->busyWait() > 0) { 414 if(_ifaceppp->data()->busyWait() > 0) {
415 QString bm = QObject::tr("Line busy. Waiting: %1 seconds").arg(_ifaceppp->data()->busyWait()); 415 QString bm = QObject::tr("Line busy. Waiting: %1 seconds").arg(_ifaceppp->data()->busyWait());
416 messg->setText(bm); 416 messg->setText(bm);
417 emit debugMessage(bm); 417 emit debugMessage(bm);
418 418
419 pausing = true; 419 pausing = true;
420 420
421 pausetimer->start(_ifaceppp->data()->busyWait()*1000, true); 421 pausetimer->start(_ifaceppp->data()->busyWait()*1000, true);
422 timeout_timer->stop(); 422 timeout_timer->stop();
423 } 423 }
424 424
425 _ifaceppp->modem()->setDataMode(false); 425 _ifaceppp->modem()->setDataMode(false);
426 vmain = 0; 426 vmain = 0;
427 substate = -1; 427 substate = -1;
428 return; 428 return;
429 } 429 }
430 430
431 if(readbuffer.contains(_ifaceppp->data()->modemNoDialtoneResp())) { 431 if(readbuffer.contains(_ifaceppp->data()->modemNoDialtoneResp())) {
432 timeout_timer->stop(); 432 timeout_timer->stop();
433 433
434 messg->setText(QObject::tr("No Dialtone")); 434 messg->setText(QObject::tr("No Dialtone"));
435 vmain = 20; 435 vmain = 20;
436 _ifaceppp->modem()->unlockdevice(); 436 _ifaceppp->modem()->unlockdevice();
437 return; 437 return;
438 } 438 }
439 439
440 if(readbuffer.contains(_ifaceppp->data()->modemNoCarrierResp())) { 440 if(readbuffer.contains(_ifaceppp->data()->modemNoCarrierResp())) {
441 timeout_timer->stop(); 441 timeout_timer->stop();
442 442
443 messg->setText(QObject::tr("No Carrier")); 443 messg->setText(QObject::tr("No Carrier"));
444 vmain = 20; 444 vmain = 20;
445 _ifaceppp->modem()->unlockdevice(); 445 _ifaceppp->modem()->unlockdevice();
446 return; 446 return;
447 } 447 }
448 } 448 }
449 449
450 // wait for newline after CONNECT response (so we get the speed) 450 // wait for newline after CONNECT response (so we get the speed)
451 if(vmain == 101) { 451 if(vmain == 101) {
452 if(!expecting) { 452 if(!expecting) {
453 _ifaceppp->modem()->setDataMode(true); // modem will no longer respond to AT commands 453 _ifaceppp->modem()->setDataMode(true); // modem will no longer respond to AT commands
454 454
455 emit startAccounting(); 455 emit startAccounting();
456// p_kppp->con_win->startClock(); 456// p_kppp->con_win->startClock();
457 457
458 vmain = 2; 458 vmain = 2;
459 scriptTimeout=_ifaceppp->data()->modemTimeout()*1000; 459 scriptTimeout=_ifaceppp->data()->modemTimeout()*1000;
460 return; 460 return;
461 } 461 }
462 } 462 }
463 463
464 // execute the script 464 // execute the script
465 if(vmain == 2) { 465 if(vmain == 2) {
466 if(!expecting && !pausing && !scanning) { 466 if(!expecting && !pausing && !scanning) {
467 467
468 timeout_timer->stop(); 468 timeout_timer->stop();
469 timeout_timer->start(scriptTimeout); 469 timeout_timer->start(scriptTimeout);
470 470
471 if((unsigned) scriptindex < comlist->count()) { 471 if((unsigned) scriptindex < comlist->count()) {
472 scriptCommand = *(comlist->at(scriptindex)); 472 scriptCommand = *(comlist->at(scriptindex));
473 scriptArgument = *(arglist->at(scriptindex)); 473 scriptArgument = *(arglist->at(scriptindex));
474 } else { 474 } else {
475 qDebug( "End of script" ); 475 odebug << "End of script" << oendl;
476 vmain = 10; 476 vmain = 10;
477 return; 477 return;
478 } 478 }
479 479
480 if (scriptCommand == "Scan") { 480 if (scriptCommand == "Scan") {
481 QString bm = QObject::tr("Scanning %1").arg(scriptArgument); 481 QString bm = QObject::tr("Scanning %1").arg(scriptArgument);
482 messg->setText(bm); 482 messg->setText(bm);
483 emit debugMessage(bm); 483 emit debugMessage(bm);
484 484
485 setScan(scriptArgument); 485 setScan(scriptArgument);
486 scriptindex++; 486 scriptindex++;
487 return; 487 return;
488 } 488 }
489 489
490 if (scriptCommand == "Save") { 490 if (scriptCommand == "Save") {
491 QString bm = QObject::tr("Saving %1").arg(scriptArgument); 491 QString bm = QObject::tr("Saving %1").arg(scriptArgument);
492 messg->setText(bm); 492 messg->setText(bm);
493 emit debugMessage(bm); 493 emit debugMessage(bm);
494 494
495 if (scriptArgument.lower() == "password") { 495 if (scriptArgument.lower() == "password") {
496 _ifaceppp->data()->setPassword(scanvar); 496 _ifaceppp->data()->setPassword(scanvar);
497 // p_kppp->setPW_Edit(scanvar); 497 // p_kppp->setPW_Edit(scanvar);
498 if(_ifaceppp->data()->storePassword()) 498 if(_ifaceppp->data()->storePassword())
499 _ifaceppp->data()->setStoredPassword(scanvar); 499 _ifaceppp->data()->setStoredPassword(scanvar);
500 firstrunPW = true; 500 firstrunPW = true;
501 } 501 }
502 502
503 scriptindex++; 503 scriptindex++;
504 return; 504 return;
505 } 505 }
506 506
507 507
508 if (scriptCommand == "Send" || scriptCommand == "SendNoEcho") { 508 if (scriptCommand == "Send" || scriptCommand == "SendNoEcho") {
509 QString bm = QObject::tr("Sending %1"); 509 QString bm = QObject::tr("Sending %1");
510 510
511 // replace %USERNAME% and %PASSWORD% 511 // replace %USERNAME% and %PASSWORD%
512 QString arg = scriptArgument; 512 QString arg = scriptArgument;
513 QRegExp re1("%USERNAME%"); 513 QRegExp re1("%USERNAME%");
514 QRegExp re2("%PASSWORD%"); 514 QRegExp re2("%PASSWORD%");
515 arg = arg.replace(re1, _ifaceppp->data()->storedUsername()); 515 arg = arg.replace(re1, _ifaceppp->data()->storedUsername());
516 arg = arg.replace(re2, _ifaceppp->data()->storedPassword()); 516 arg = arg.replace(re2, _ifaceppp->data()->storedPassword());
517 517
518 if (scriptCommand == "Send") 518 if (scriptCommand == "Send")
519 bm = bm.arg(scriptArgument); 519 bm = bm.arg(scriptArgument);
520 else { 520 else {
521 for(uint i = 0; i < scriptArgument.length(); i++) 521 for(uint i = 0; i < scriptArgument.length(); i++)
522 bm = bm.arg("*"); 522 bm = bm.arg("*");
523 } 523 }
524 524
525 messg->setText(bm); 525 messg->setText(bm);
526 emit debugMessage(bm); 526 emit debugMessage(bm);
527 527
528 writeline(scriptArgument); 528 writeline(scriptArgument);
529 scriptindex++; 529 scriptindex++;
530 return; 530 return;
531 } 531 }
532 532
533 if (scriptCommand == "Expect") { 533 if (scriptCommand == "Expect") {
534 QString bm = QObject::tr("Expecting %1").arg(scriptArgument); 534 QString bm = QObject::tr("Expecting %1").arg(scriptArgument);
535 messg->setText(bm); 535 messg->setText(bm);
536 emit debugMessage(bm); 536 emit debugMessage(bm);
537 537
538 // The incrementing of the scriptindex MUST be before the 538 // The incrementing of the scriptindex MUST be before the
539 // call to setExpect otherwise the expect will miss a string that is 539 // call to setExpect otherwise the expect will miss a string that is
540 // already in the buffer. 540 // already in the buffer.
541 scriptindex++; 541 scriptindex++;
542 setExpect(scriptArgument); 542 setExpect(scriptArgument);
543 return; 543 return;
544 } 544 }
545 545
546 546
547 if (scriptCommand == "Pause") { 547 if (scriptCommand == "Pause") {
548 QString bm = QObject::tr("Pause %1 seconds").arg(scriptArgument); 548 QString bm = QObject::tr("Pause %1 seconds").arg(scriptArgument);
549 messg->setText(bm); 549 messg->setText(bm);
550 emit debugMessage(bm); 550 emit debugMessage(bm);
551 551
552 pausing = true; 552 pausing = true;
553 553
554 pausetimer->start(scriptArgument.toInt()*1000, true); 554 pausetimer->start(scriptArgument.toInt()*1000, true);
555 timeout_timer->stop(); 555 timeout_timer->stop();
556 556
557 scriptindex++; 557 scriptindex++;
558 return; 558 return;
559 } 559 }
560 560
561 if (scriptCommand == "Timeout") { 561 if (scriptCommand == "Timeout") {
562 562
563 timeout_timer->stop(); 563 timeout_timer->stop();
564 564
565 QString bm = QObject::tr("Timeout %1 seconds").arg(scriptArgument); 565 QString bm = QObject::tr("Timeout %1 seconds").arg(scriptArgument);
566 messg->setText(bm); 566 messg->setText(bm);
567 emit debugMessage(bm); 567 emit debugMessage(bm);
568 568
569 scriptTimeout=scriptArgument.toInt()*1000; 569 scriptTimeout=scriptArgument.toInt()*1000;
570 timeout_timer->start(scriptTimeout); 570 timeout_timer->start(scriptTimeout);
571 571
@@ -745,203 +745,203 @@ void ConnectWidget::timerEvent(QTimerEvent *) {
745 cancelbutton(); 745 cancelbutton();
746 QMessageBox::critical(0, "error", QObject::tr("Loops nested too deeply!")); 746 QMessageBox::critical(0, "error", QObject::tr("Loops nested too deeply!"));
747 } else { 747 } else {
748 setExpect(scriptArgument); 748 setExpect(scriptArgument);
749 loopstartindex[loopnest] = scriptindex; 749 loopstartindex[loopnest] = scriptindex;
750 loopstr[loopnest] = scriptArgument; 750 loopstr[loopnest] = scriptArgument;
751 loopend = false; 751 loopend = false;
752 loopnest++; 752 loopnest++;
753 } 753 }
754 messg->setText(bm); 754 messg->setText(bm);
755 emit debugMessage(bm); 755 emit debugMessage(bm);
756 756
757 } 757 }
758 758
759 if (scriptCommand == "LoopEnd") { 759 if (scriptCommand == "LoopEnd") {
760 QString bm = QObject::tr("Loop End %1").arg(scriptArgument); 760 QString bm = QObject::tr("Loop End %1").arg(scriptArgument);
761 if ( loopnest <= 0 ) { 761 if ( loopnest <= 0 ) {
762 bm = QObject::tr("LoopEnd without matching Start! Line: %1").arg(bm); 762 bm = QObject::tr("LoopEnd without matching Start! Line: %1").arg(bm);
763 vmain=20; 763 vmain=20;
764 cancelbutton(); 764 cancelbutton();
765 QMessageBox::critical(0, "error", bm); 765 QMessageBox::critical(0, "error", bm);
766 return; 766 return;
767 } else { 767 } else {
768 // NB! The incrementing of the scriptindex MUST be before the 768 // NB! The incrementing of the scriptindex MUST be before the
769 // call to setExpect otherwise the expect will miss a string 769 // call to setExpect otherwise the expect will miss a string
770 // that is already in the buffer. 770 // that is already in the buffer.
771 scriptindex++; 771 scriptindex++;
772 setExpect(scriptArgument); 772 setExpect(scriptArgument);
773 loopnest--; 773 loopnest--;
774 loopend = true; 774 loopend = true;
775 } 775 }
776 messg->setText(bm); 776 messg->setText(bm);
777 emit debugMessage(bm); 777 emit debugMessage(bm);
778 778
779 } 779 }
780 } 780 }
781 } 781 }
782 782
783 // this is a subroutine for the "Answer" script option 783 // this is a subroutine for the "Answer" script option
784 784
785 if(vmain == 150) { 785 if(vmain == 150) {
786 if(!expecting) { 786 if(!expecting) {
787 writeline(_ifaceppp->data()->modemAnswerStr()); 787 writeline(_ifaceppp->data()->modemAnswerStr());
788 setExpect(_ifaceppp->data()->modemAnswerResp()); 788 setExpect(_ifaceppp->data()->modemAnswerResp());
789 789
790 vmain = 2; 790 vmain = 2;
791 scriptindex++; 791 scriptindex++;
792 return; 792 return;
793 } 793 }
794 } 794 }
795 795
796 if(vmain == 30) { 796 if(vmain == 30) {
797// if (termwindow->isVisible()) 797// if (termwindow->isVisible())
798// return; 798// return;
799// if (termwindow->pressedContinue()) 799// if (termwindow->pressedContinue())
800// vmain = 10; 800// vmain = 10;
801// else 801// else
802 cancelbutton(); 802 cancelbutton();
803 } 803 }
804 804
805 if(vmain == 10) { 805 if(vmain == 10) {
806 if(!expecting) { 806 if(!expecting) {
807 807
808 int result; 808 int result;
809 809
810 timeout_timer->stop(); 810 timeout_timer->stop();
811 if_timeout_timer->stop(); // better be sure. 811 if_timeout_timer->stop(); // better be sure.
812 812
813 // stop reading of data 813 // stop reading of data
814 _ifaceppp->modem()->stop(); 814 _ifaceppp->modem()->stop();
815 815
816 if(_ifaceppp->data()->authMethod() == AUTH_TERMINAL) { 816 if(_ifaceppp->data()->authMethod() == AUTH_TERMINAL) {
817 // if (termwindow) { 817 // if (termwindow) {
818 // delete termwindow; 818 // delete termwindow;
819 // termwindow = 0L; 819 // termwindow = 0L;
820 // this->show(); 820 // this->show();
821 // } else { 821 // } else {
822 // termwindow = new LoginTerm(0L, 0L); 822 // termwindow = new LoginTerm(0L, 0L);
823 // hide(); 823 // hide();
824 // termwindow->show(); 824 // termwindow->show();
825 // vmain = 30; 825 // vmain = 30;
826 // return; 826 // return;
827 // } 827 // }
828 } 828 }
829 829
830 // Close the tty. This prevents the QTimer::singleShot() in 830 // Close the tty. This prevents the QTimer::singleShot() in
831 // Modem::readtty() from re-enabling the socket notifier. 831 // Modem::readtty() from re-enabling the socket notifier.
832 // The port is still held open by the helper process. 832 // The port is still held open by the helper process.
833 833
834 /* Er, there _is_ not QTimer::singleShot() in Modem::readtty(), 834 /* Er, there _is_ not QTimer::singleShot() in Modem::readtty(),
835 and closing the thing prevents pppd from using it later. */ 835 and closing the thing prevents pppd from using it later. */
836 //_ifaceppp->modem()->closetty(); 836 //_ifaceppp->modem()->closetty();
837 837
838 killTimer( main_timer_ID ); 838 killTimer( main_timer_ID );
839 839
840 if_timeout_timer->start(_ifaceppp->data()->pppdTimeout()*1000); 840 if_timeout_timer->start(_ifaceppp->data()->pppdTimeout()*1000);
841 qDebug( "started if timeout timer with %i", _ifaceppp->data()->pppdTimeout()*1000); 841 odebug << "started if timeout timer with " << _ifaceppp->data()->pppdTimeout()*1000 << "" << oendl;
842 842
843 // find out PPP interface and notify the stats module 843 // find out PPP interface and notify the stats module
844// stats->setUnit(pppInterfaceNumber()); 844// stats->setUnit(pppInterfaceNumber());
845 845
846 qApp->flushX(); 846 qApp->flushX();
847 semaphore = true; 847 semaphore = true;
848 result = execppp(); 848 result = execppp();
849 849
850 emit debugMessage(QObject::tr("Starting pppd...")); 850 emit debugMessage(QObject::tr("Starting pppd..."));
851 qDebug("execppp() returned with return-code %i", result ); 851 odebug << "execppp() returned with return-code " << result << "" << oendl;
852 852
853 if(result) { 853 if(result) {
854 if(!_ifaceppp->data()->autoDNS()) 854 if(!_ifaceppp->data()->autoDNS())
855 adddns( _ifaceppp ); 855 adddns( _ifaceppp );
856 856
857 // O.K we are done here, let's change over to the if_waiting loop 857 // O.K we are done here, let's change over to the if_waiting loop
858 // where we wait for the ppp if (interface) to come up. 858 // where we wait for the ppp if (interface) to come up.
859 859
860 emit if_waiting_signal(); 860 emit if_waiting_signal();
861 } else { 861 } else {
862 862
863 // starting pppd wasn't successful. Error messages were 863 // starting pppd wasn't successful. Error messages were
864 // handled by execppp(); 864 // handled by execppp();
865 if_timeout_timer->stop(); 865 if_timeout_timer->stop();
866 this->hide(); 866 this->hide();
867 messg->setText(""); 867 messg->setText("");
868 //p_kppp->quit_b->setFocus(); 868 //p_kppp->quit_b->setFocus();
869 //p_kppp->show(); 869 //p_kppp->show();
870 qApp->processEvents(); 870 qApp->processEvents();
871 _ifaceppp->modem()->hangup(); 871 _ifaceppp->modem()->hangup();
872 emit stopAccounting(); 872 emit stopAccounting();
873 //p_kppp->con_win->stopClock(); 873 //p_kppp->con_win->stopClock();
874 _ifaceppp->modem()->closetty(); 874 _ifaceppp->modem()->closetty();
875 _ifaceppp->modem()->unlockdevice(); 875 _ifaceppp->modem()->unlockdevice();
876 876
877 } 877 }
878 878
879 return; 879 return;
880 } 880 }
881 } 881 }
882 882
883 // this is a "wait until cancel" entry 883 // this is a "wait until cancel" entry
884 884
885 if(vmain == 20) { 885 if(vmain == 20) {
886 } 886 }
887} 887}
888 888
889 889
890void ConnectWidget::set_con_speed_string() { 890void ConnectWidget::set_con_speed_string() {
891 // Here we are trying to determine the speed at which we are connected. 891 // Here we are trying to determine the speed at which we are connected.
892 // Usually the modem responds after connect with something like 892 // Usually the modem responds after connect with something like
893 // CONNECT 115200, so all we need to do is find the number after CONNECT 893 // CONNECT 115200, so all we need to do is find the number after CONNECT
894 // or whatever the modemConnectResp() is. 894 // or whatever the modemConnectResp() is.
895// p_kppp->con_speed = _ifaceppp->modem()->parseModemSpeed(myreadbuffer); 895// p_kppp->con_speed = _ifaceppp->modem()->parseModemSpeed(myreadbuffer);
896} 896}
897 897
898 898
899 899
900void ConnectWidget::readChar(unsigned char c) { 900void ConnectWidget::readChar(unsigned char c) {
901 if(semaphore) 901 if(semaphore)
902 return; 902 return;
903 903
904 readbuffer += c; 904 readbuffer += c;
905 myreadbuffer += c; 905 myreadbuffer += c;
906 906
907 // While in scanning mode store each char to the scan buffer 907 // While in scanning mode store each char to the scan buffer
908 // for use in the prompt command 908 // for use in the prompt command
909 if( scanning ) 909 if( scanning )
910 scanbuffer += c; 910 scanbuffer += c;
911 911
912 // add to debug window 912 // add to debug window
913 emit debugPutChar(c); 913 emit debugPutChar(c);
914 914
915 checkBuffers(); 915 checkBuffers();
916} 916}
917 917
918 918
919void ConnectWidget::checkBuffers() { 919void ConnectWidget::checkBuffers() {
920 // Let's check if we are finished with scanning: 920 // Let's check if we are finished with scanning:
921 // The scanstring have to be in the buffer and the latest character 921 // The scanstring have to be in the buffer and the latest character
922 // was a carriage return or an linefeed (depending on modem setup) 922 // was a carriage return or an linefeed (depending on modem setup)
923 if( scanning && scanbuffer.contains(scanstr) && 923 if( scanning && scanbuffer.contains(scanstr) &&
924 ( scanbuffer.right(1) == "\n" || scanbuffer.right(1) == "\r") ) { 924 ( scanbuffer.right(1) == "\n" || scanbuffer.right(1) == "\r") ) {
925 scanning = false; 925 scanning = false;
926 926
927 int vstart = scanbuffer.find( scanstr ) + scanstr.length(); 927 int vstart = scanbuffer.find( scanstr ) + scanstr.length();
928 scanvar = scanbuffer.mid( vstart, scanbuffer.length() - vstart); 928 scanvar = scanbuffer.mid( vstart, scanbuffer.length() - vstart);
929 scanvar = scanvar.stripWhiteSpace(); 929 scanvar = scanvar.stripWhiteSpace();
930 930
931 // Show the Variabel content in the debug window 931 // Show the Variabel content in the debug window
932 QString sv = QObject::tr("Scan Var: %1").arg(scanvar); 932 QString sv = QObject::tr("Scan Var: %1").arg(scanvar);
933 emit debugMessage(sv); 933 emit debugMessage(sv);
934 } 934 }
935 935
936 if(expecting) { 936 if(expecting) {
937 if(readbuffer.contains(expectstr)) { 937 if(readbuffer.contains(expectstr)) {
938 expecting = false; 938 expecting = false;
939 // keep everything after the expected string 939 // keep everything after the expected string
940 readbuffer.remove(0, readbuffer.find(expectstr) + expectstr.length()); 940 readbuffer.remove(0, readbuffer.find(expectstr) + expectstr.length());
941 941
942 QString ts = QObject::tr("Found: %1").arg(expectstr); 942 QString ts = QObject::tr("Found: %1").arg(expectstr);
943 emit debugMessage(ts); 943 emit debugMessage(ts);
944 944
945 if (loopend) { 945 if (loopend) {
946 loopend=false; 946 loopend=false;
947 } 947 }
@@ -971,193 +971,193 @@ void ConnectWidget::pause() {
971 971
972 972
973void ConnectWidget::cancelbutton() { 973void ConnectWidget::cancelbutton() {
974 _ifaceppp->modem()->stop(); 974 _ifaceppp->modem()->stop();
975 killTimer(main_timer_ID); 975 killTimer(main_timer_ID);
976 timeout_timer->stop(); 976 timeout_timer->stop();
977 if_timer->stop(); 977 if_timer->stop();
978 if_timeout_timer->stop(); 978 if_timeout_timer->stop();
979 979
980// if (termwindow) { 980// if (termwindow) {
981// delete termwindow; 981// delete termwindow;
982// termwindow = 0L; 982// termwindow = 0L;
983// this->show(); 983// this->show();
984// } 984// }
985 985
986 messg->setText(QObject::tr("One moment please...")); 986 messg->setText(QObject::tr("One moment please..."));
987 987
988 // just to be sure 988 // just to be sure
989 _ifaceppp->modem()->removeSecret(AUTH_PAP); 989 _ifaceppp->modem()->removeSecret(AUTH_PAP);
990 _ifaceppp->modem()->removeSecret(AUTH_CHAP); 990 _ifaceppp->modem()->removeSecret(AUTH_CHAP);
991 removedns(_ifaceppp); 991 removedns(_ifaceppp);
992 992
993 qApp->processEvents(); 993 qApp->processEvents();
994 994
995 _ifaceppp->modem()->killPPPDaemon(); 995 _ifaceppp->modem()->killPPPDaemon();
996 _ifaceppp->modem()->hangup(); 996 _ifaceppp->modem()->hangup();
997 997
998 998
999// p_kppp->quit_b->setFocus(); 999// p_kppp->quit_b->setFocus();
1000// p_kppp->show(); 1000// p_kppp->show();
1001 // emit stopAccounting();// just to be sure 1001 // emit stopAccounting();// just to be sure
1002// p_kppp->con_win->stopClock(); 1002// p_kppp->con_win->stopClock();
1003 _ifaceppp->modem()->closetty(); 1003 _ifaceppp->modem()->closetty();
1004 _ifaceppp->modem()->unlockdevice(); 1004 _ifaceppp->modem()->unlockdevice();
1005 1005
1006 //abort prompt window... 1006 //abort prompt window...
1007 if (prompt->isVisible()) { 1007 if (prompt->isVisible()) {
1008 prompt->hide(); 1008 prompt->hide();
1009 } 1009 }
1010 prompt->setConsumed(); 1010 prompt->setConsumed();
1011 1011
1012 _ifaceppp->setStatus( false ); 1012 _ifaceppp->setStatus( false );
1013 _ifaceppp->refresh(); 1013 _ifaceppp->refresh();
1014// messg->setText(tr("offline")); 1014// messg->setText(tr("offline"));
1015 refresh(); 1015 refresh();
1016} 1016}
1017 1017
1018 1018
1019void ConnectWidget::script_timed_out() { 1019void ConnectWidget::script_timed_out() {
1020 if(vmain == 20) { // we are in the 'wait for the user to cancel' state 1020 if(vmain == 20) { // we are in the 'wait for the user to cancel' state
1021 timeout_timer->stop(); 1021 timeout_timer->stop();
1022 emit stopAccounting(); 1022 emit stopAccounting();
1023// p_kppp->con_win->stopClock(); 1023// p_kppp->con_win->stopClock();
1024 return; 1024 return;
1025 } 1025 }
1026 1026
1027 if (prompt->isVisible()) 1027 if (prompt->isVisible())
1028 prompt->hide(); 1028 prompt->hide();
1029 1029
1030 prompt->setConsumed(); 1030 prompt->setConsumed();
1031 messg->setText(QObject::tr("Script timed out!")); 1031 messg->setText(QObject::tr("Script timed out!"));
1032 _ifaceppp->modem()->hangup(); 1032 _ifaceppp->modem()->hangup();
1033 emit stopAccounting(); 1033 emit stopAccounting();
1034// p_kppp->con_win->stopClock(); 1034// p_kppp->con_win->stopClock();
1035 1035
1036 vmain = 0; // let's try again. 1036 vmain = 0; // let's try again.
1037 substate = -1; 1037 substate = -1;
1038} 1038}
1039 1039
1040 1040
1041void ConnectWidget::setScan(const QString &n) { 1041void ConnectWidget::setScan(const QString &n) {
1042 scanning = true; 1042 scanning = true;
1043 scanstr = n; 1043 scanstr = n;
1044 scanbuffer = ""; 1044 scanbuffer = "";
1045 1045
1046 QString ts = QObject::tr("Scanning: %1").arg(n); 1046 QString ts = QObject::tr("Scanning: %1").arg(n);
1047 emit debugMessage(ts); 1047 emit debugMessage(ts);
1048} 1048}
1049 1049
1050 1050
1051void ConnectWidget::setExpect(const QString &n) { 1051void ConnectWidget::setExpect(const QString &n) {
1052 expecting = true; 1052 expecting = true;
1053 expectstr = n; 1053 expectstr = n;
1054 1054
1055 QString ts = QObject::tr("Expecting: %1").arg(n); 1055 QString ts = QObject::tr("Expecting: %1").arg(n);
1056 ts.replace(QRegExp("\n"), "<LF>"); 1056 ts.replace(QRegExp("\n"), "<LF>");
1057 emit debugMessage(ts); 1057 emit debugMessage(ts);
1058 1058
1059 // check if the expected string is in the read buffer already. 1059 // check if the expected string is in the read buffer already.
1060 checkBuffers(); 1060 checkBuffers();
1061} 1061}
1062 1062
1063 1063
1064void ConnectWidget::if_waiting_timed_out() { 1064void ConnectWidget::if_waiting_timed_out() {
1065 if_timer->stop(); 1065 if_timer->stop();
1066 if_timeout_timer->stop(); 1066 if_timeout_timer->stop();
1067 qDebug("if_waiting_timed_out()"); 1067 odebug << "if_waiting_timed_out()" << oendl;
1068 1068
1069 _ifaceppp->data()->setpppdError(E_IF_TIMEOUT); 1069 _ifaceppp->data()->setpppdError(E_IF_TIMEOUT);
1070 1070
1071 // let's kill the stuck pppd 1071 // let's kill the stuck pppd
1072 _ifaceppp->modem()->killPPPDaemon(); 1072 _ifaceppp->modem()->killPPPDaemon();
1073 1073
1074 emit stopAccounting(); 1074 emit stopAccounting();
1075// p_kppp->con_win->stopClock(); 1075// p_kppp->con_win->stopClock();
1076 1076
1077 1077
1078 // killing ppp will generate a SIGCHLD which will be caught in pppdie() 1078 // killing ppp will generate a SIGCHLD which will be caught in pppdie()
1079 // in main.cpp what happens next will depend on the boolean 1079 // in main.cpp what happens next will depend on the boolean
1080 // reconnect_on_disconnect which is set in ConnectWidget::init(); 1080 // reconnect_on_disconnect which is set in ConnectWidget::init();
1081} 1081}
1082 1082
1083void ConnectWidget::pppdDied() 1083void ConnectWidget::pppdDied()
1084{ 1084{
1085 if_timer->stop(); 1085 if_timer->stop();
1086 if_timeout_timer->stop(); 1086 if_timeout_timer->stop();
1087} 1087}
1088 1088
1089void ConnectWidget::if_waiting_slot() { 1089void ConnectWidget::if_waiting_slot() {
1090 messg->setText(QObject::tr("Logging on to network...")); 1090 messg->setText(QObject::tr("Logging on to network..."));
1091 1091
1092// if(!stats->ifIsUp()) { 1092// if(!stats->ifIsUp()) {
1093 1093
1094// if(_ifaceppp->data()->pppdError() != 0) { 1094// if(_ifaceppp->data()->pppdError() != 0) {
1095// // we are here if pppd died immediately after starting it. 1095// // we are here if pppd died immediately after starting it.
1096// pppdDied(); 1096// pppdDied();
1097// // error message handled in main.cpp: sigPPPDDied() 1097// // error message handled in main.cpp: sigPPPDDied()
1098// return; 1098// return;
1099// } 1099// }
1100 1100
1101// if_timer->start(100, TRUE); // single shot 1101// if_timer->start(100, TRUE); // single shot
1102// return; 1102// return;
1103// } 1103// }
1104 1104
1105 // O.K the ppp interface is up and running 1105 // O.K the ppp interface is up and running
1106 // give it a few time to come up completly (0.2 seconds) 1106 // give it a few time to come up completly (0.2 seconds)
1107 if_timeout_timer->stop(); 1107 if_timeout_timer->stop();
1108 if_timer->stop(); 1108 if_timer->stop();
1109 usleep(200000); 1109 usleep(200000);
1110 1110
1111 if(_ifaceppp->data()->autoDNS()) 1111 if(_ifaceppp->data()->autoDNS())
1112 addpeerdns( _ifaceppp ); 1112 addpeerdns( _ifaceppp );
1113 1113
1114 // Close the debugging window. If we are connected, we 1114 // Close the debugging window. If we are connected, we
1115 // are not really interested in debug output 1115 // are not really interested in debug output
1116 emit closeDebugWindow(); 1116 emit closeDebugWindow();
1117// p_kppp->statdlg->take_stats(); // start taking ppp statistics 1117// p_kppp->statdlg->take_stats(); // start taking ppp statistics
1118 auto_hostname(_ifaceppp); 1118 auto_hostname(_ifaceppp);
1119 1119
1120 if(!_ifaceppp->data()->command_on_connect().isEmpty()) { 1120 if(!_ifaceppp->data()->command_on_connect().isEmpty()) {
1121 messg->setText(QObject::tr("Running startup command...")); 1121 messg->setText(QObject::tr("Running startup command..."));
1122 1122
1123 // make sure that we don't get any async errors 1123 // make sure that we don't get any async errors
1124 qApp->flushX(); 1124 qApp->flushX();
1125 execute_command(_ifaceppp->data()->command_on_connect()); 1125 execute_command(_ifaceppp->data()->command_on_connect());
1126 messg->setText(QObject::tr("Done")); 1126 messg->setText(QObject::tr("Done"));
1127 } 1127 }
1128 1128
1129 // remove the authentication file 1129 // remove the authentication file
1130 _ifaceppp->modem()->removeSecret(AUTH_PAP); 1130 _ifaceppp->modem()->removeSecret(AUTH_PAP);
1131 _ifaceppp->modem()->removeSecret(AUTH_CHAP); 1131 _ifaceppp->modem()->removeSecret(AUTH_CHAP);
1132 1132
1133 emit debugMessage(QObject::tr("Done")); 1133 emit debugMessage(QObject::tr("Done"));
1134 set_con_speed_string(); 1134 set_con_speed_string();
1135 1135
1136// p_kppp->con_win->setConnectionSpeed(p_kppp->con_speed); 1136// p_kppp->con_win->setConnectionSpeed(p_kppp->con_speed);
1137// this->hide(); 1137// this->hide();
1138// messg->setText(""); 1138// messg->setText("");
1139 1139
1140 _ifaceppp->setStatus( true ); 1140 _ifaceppp->setStatus( true );
1141 1141
1142 m_refreshTimer = new QTimer( this ); 1142 m_refreshTimer = new QTimer( this );
1143 connect( m_refreshTimer, SIGNAL( timeout() ), this, SLOT( refresh() ) ); 1143 connect( m_refreshTimer, SIGNAL( timeout() ), this, SLOT( refresh() ) );
1144 m_refreshTimer->start( 3000 ); 1144 m_refreshTimer->start( 3000 );
1145 //_ifaceppp->refresh(); 1145 //_ifaceppp->refresh();
1146 // emit _ifaceppp->updateInterface(_ifaceppp); 1146 // emit _ifaceppp->updateInterface(_ifaceppp);
1147 1147
1148 // prepare the con_win so as to have the right size for 1148 // prepare the con_win so as to have the right size for
1149 // accounting / non-accounting mode 1149 // accounting / non-accounting mode
1150// if(p_kppp->acct != 0) 1150// if(p_kppp->acct != 0)
1151// p_kppp->con_win->accounting(p_kppp->acct->running()); 1151// p_kppp->con_win->accounting(p_kppp->acct->running());
1152// else 1152// else
1153// p_kppp->con_win->accounting(false); 1153// p_kppp->con_win->accounting(false);
1154 1154
1155// if (_ifaceppp->data()->get_dock_into_panel()) { 1155// if (_ifaceppp->data()->get_dock_into_panel()) {
1156// // DockWidget::dock_widget->show(); 1156// // DockWidget::dock_widget->show();
1157// // DockWidget::dock_widget->take_stats(); 1157// // DockWidget::dock_widget->take_stats();
1158// // this->hide(); 1158// // this->hide();
1159// } 1159// }
1160// else { 1160// else {
1161// // p_kppp->con_win->show(); 1161// // p_kppp->con_win->show();
1162 1162
1163// if(_ifaceppp->data()->get_iconify_on_connect()) { 1163// if(_ifaceppp->data()->get_iconify_on_connect()) {
@@ -1178,193 +1178,193 @@ void ConnectWidget::refresh() {
1178} 1178}
1179 1179
1180 1180
1181bool ConnectWidget::execppp() { 1181bool ConnectWidget::execppp() {
1182 QString command; 1182 QString command;
1183 1183
1184 command = "pppd"; 1184 command = "pppd";
1185 1185
1186 // as of version 2.3.6 pppd falls back to the real user rights when 1186 // as of version 2.3.6 pppd falls back to the real user rights when
1187 // opening a device given in a command line. To avoid permission conflicts 1187 // opening a device given in a command line. To avoid permission conflicts
1188 // we'll simply leave this argument away. pppd will then use the default tty 1188 // we'll simply leave this argument away. pppd will then use the default tty
1189 // which is the serial port we connected stdin/stdout to in opener.cpp. 1189 // which is the serial port we connected stdin/stdout to in opener.cpp.
1190 // command += " "; 1190 // command += " ";
1191 // command += _ifaceppp->data()->modemDevice(); 1191 // command += _ifaceppp->data()->modemDevice();
1192 1192
1193 command += " " + _ifaceppp->data()->speed(); 1193 command += " " + _ifaceppp->data()->speed();
1194 1194
1195 command += " -detach"; 1195 command += " -detach";
1196 1196
1197 if(_ifaceppp->data()->ipaddr() != "0.0.0.0" || 1197 if(_ifaceppp->data()->ipaddr() != "0.0.0.0" ||
1198 _ifaceppp->data()->gateway() != "0.0.0.0") { 1198 _ifaceppp->data()->gateway() != "0.0.0.0") {
1199 if(_ifaceppp->data()->ipaddr() != "0.0.0.0") { 1199 if(_ifaceppp->data()->ipaddr() != "0.0.0.0") {
1200 command += " "; 1200 command += " ";
1201 command += _ifaceppp->data()->ipaddr(); 1201 command += _ifaceppp->data()->ipaddr();
1202 command += ":"; 1202 command += ":";
1203 } 1203 }
1204 else { 1204 else {
1205 command += " "; 1205 command += " ";
1206 command += ":"; 1206 command += ":";
1207 } 1207 }
1208 1208
1209 if(_ifaceppp->data()->gateway() != "0.0.0.0") 1209 if(_ifaceppp->data()->gateway() != "0.0.0.0")
1210 command += _ifaceppp->data()->gateway(); 1210 command += _ifaceppp->data()->gateway();
1211 } 1211 }
1212 1212
1213 if(_ifaceppp->data()->subnetmask() != "0.0.0.0") 1213 if(_ifaceppp->data()->subnetmask() != "0.0.0.0")
1214 command += " netmask " + _ifaceppp->data()->subnetmask(); 1214 command += " netmask " + _ifaceppp->data()->subnetmask();
1215 1215
1216 if(_ifaceppp->data()->flowcontrol() != "None") { 1216 if(_ifaceppp->data()->flowcontrol() != "None") {
1217 if(_ifaceppp->data()->flowcontrol() == "CRTSCTS") 1217 if(_ifaceppp->data()->flowcontrol() == "CRTSCTS")
1218 command += " crtscts"; 1218 command += " crtscts";
1219 else 1219 else
1220 command += " xonxoff"; 1220 command += " xonxoff";
1221 } 1221 }
1222 1222
1223 if(_ifaceppp->data()->defaultroute()) 1223 if(_ifaceppp->data()->defaultroute())
1224 command += " defaultroute"; 1224 command += " defaultroute";
1225 1225
1226 if(_ifaceppp->data()->autoDNS()) 1226 if(_ifaceppp->data()->autoDNS())
1227 command += " usepeerdns"; 1227 command += " usepeerdns";
1228 1228
1229 1229
1230 // PAP settings 1230 // PAP settings
1231 if(_ifaceppp->data()->authMethod() == AUTH_PAP) { 1231 if(_ifaceppp->data()->authMethod() == AUTH_PAP) {
1232 command += " -chap user "; 1232 command += " -chap user ";
1233 command = command + _ifaceppp->data()->storedUsername(); 1233 command = command + _ifaceppp->data()->storedUsername();
1234 } 1234 }
1235 1235
1236 // CHAP settings 1236 // CHAP settings
1237 if(_ifaceppp->data()->authMethod() == AUTH_CHAP) { 1237 if(_ifaceppp->data()->authMethod() == AUTH_CHAP) {
1238 command += " -pap user "; 1238 command += " -pap user ";
1239 command = command + _ifaceppp->data()->storedUsername(); 1239 command = command + _ifaceppp->data()->storedUsername();
1240 } 1240 }
1241 1241
1242 // PAP/CHAP settings 1242 // PAP/CHAP settings
1243 if(_ifaceppp->data()->authMethod() == AUTH_PAPCHAP) { 1243 if(_ifaceppp->data()->authMethod() == AUTH_PAPCHAP) {
1244 QString tmpName = _ifaceppp->data()->storedUsername(); 1244 QString tmpName = _ifaceppp->data()->storedUsername();
1245 if ( !tmpName.isEmpty() ) { 1245 if ( !tmpName.isEmpty() ) {
1246 command += " user "; 1246 command += " user ";
1247 command = command + tmpName; 1247 command = command + tmpName;
1248 } 1248 }
1249 } 1249 }
1250 1250
1251 // check for debug 1251 // check for debug
1252 if(_ifaceppp->data()->getPPPDebug()) 1252 if(_ifaceppp->data()->getPPPDebug())
1253 command += " debug"; 1253 command += " debug";
1254 1254
1255 QStringList &arglist = _ifaceppp->data()->pppdArgument(); 1255 QStringList &arglist = _ifaceppp->data()->pppdArgument();
1256 for ( QStringList::Iterator it = arglist.begin(); 1256 for ( QStringList::Iterator it = arglist.begin();
1257 it != arglist.end(); 1257 it != arglist.end();
1258 ++it ) 1258 ++it )
1259 { 1259 {
1260 command += " " + *it; 1260 command += " " + *it;
1261 } 1261 }
1262 1262
1263 command += " call opie-kppp logfd 11"; 1263 command += " call opie-kppp logfd 11";
1264 1264
1265 if (command.length() > MAX_CMDLEN) { 1265 if (command.length() > MAX_CMDLEN) {
1266 QMessageBox::critical(this, "error", QObject::tr( 1266 QMessageBox::critical(this, "error", QObject::tr(
1267 "pppd command + command-line arguments exceed " 1267 "pppd command + command-line arguments exceed "
1268 "2024 characters in length." 1268 "2024 characters in length."
1269 )); 1269 ));
1270 1270
1271 return false; // nonsensically long command which would bust my buffer buf. 1271 return false; // nonsensically long command which would bust my buffer buf.
1272 } 1272 }
1273 1273
1274 qWarning("Command IS: %s",command.latin1() ); 1274 owarn << "Command IS: " << command.latin1() << "" << oendl;
1275 1275
1276 qApp->flushX(); 1276 qApp->flushX();
1277 1277
1278 return _ifaceppp->modem()->execPPPDaemon(command); 1278 return _ifaceppp->modem()->execPPPDaemon(command);
1279} 1279}
1280 1280
1281 1281
1282void ConnectWidget::closeEvent( QCloseEvent *e ) { 1282void ConnectWidget::closeEvent( QCloseEvent *e ) {
1283 e->ignore(); 1283 e->ignore();
1284 emit cancelbutton(); 1284 emit cancelbutton();
1285} 1285}
1286 1286
1287 1287
1288void ConnectWidget::setMsg(const QString &msg) { 1288void ConnectWidget::setMsg(const QString &msg) {
1289 messg->setText(msg); 1289 messg->setText(msg);
1290} 1290}
1291 1291
1292void ConnectWidget::writeline(const QString &s) { 1292void ConnectWidget::writeline(const QString &s) {
1293 _ifaceppp->modem()->writeLine(s.local8Bit()); 1293 _ifaceppp->modem()->writeLine(s.local8Bit());
1294} 1294}
1295 1295
1296// Set the hostname and domain from DNS Server 1296// Set the hostname and domain from DNS Server
1297void auto_hostname(InterfacePPP *_ifaceppp) { 1297void auto_hostname(InterfacePPP *_ifaceppp) {
1298 struct in_addr local_ip; 1298 struct in_addr local_ip;
1299 struct hostent *hostname_entry; 1299 struct hostent *hostname_entry;
1300 QString new_hostname; 1300 QString new_hostname;
1301 int dot; 1301 int dot;
1302 char tmp_str[100]; // buffer overflow safe 1302 char tmp_str[100]; // buffer overflow safe
1303 1303
1304 gethostname(tmp_str, sizeof(tmp_str)); 1304 gethostname(tmp_str, sizeof(tmp_str));
1305 tmp_str[sizeof(tmp_str)-1]=0; // panic 1305 tmp_str[sizeof(tmp_str)-1]=0; // panic
1306 old_hostname=tmp_str; // copy to QString 1306 old_hostname=tmp_str; // copy to QString
1307 1307
1308 // if (!p_kppp->stats->local_ip_address.isEmpty() && _ifaceppp->data()->autoname()) { 1308 // if (!p_kppp->stats->local_ip_address.isEmpty() && _ifaceppp->data()->autoname()) {
1309 if ( _ifaceppp->data()->autoname()) { 1309 if ( _ifaceppp->data()->autoname()) {
1310// local_ip.s_addr=inet_addr(p_kppp->stats->local_ip_address.ascii()); 1310// local_ip.s_addr=inet_addr(p_kppp->stats->local_ip_address.ascii());
1311 hostname_entry=gethostbyaddr((const char *)&local_ip,sizeof(in_addr),AF_INET); 1311 hostname_entry=gethostbyaddr((const char *)&local_ip,sizeof(in_addr),AF_INET);
1312 1312
1313 if (hostname_entry != 0L) { 1313 if (hostname_entry != 0L) {
1314 new_hostname=hostname_entry->h_name; 1314 new_hostname=hostname_entry->h_name;
1315 dot=new_hostname.find('.'); 1315 dot=new_hostname.find('.');
1316 new_hostname=new_hostname.remove(dot,new_hostname.length()-dot); 1316 new_hostname=new_hostname.remove(dot,new_hostname.length()-dot);
1317 _ifaceppp->modem()->setHostname(new_hostname); 1317 _ifaceppp->modem()->setHostname(new_hostname);
1318 modified_hostname = TRUE; 1318 modified_hostname = TRUE;
1319 1319
1320 new_hostname=hostname_entry->h_name; 1320 new_hostname=hostname_entry->h_name;
1321 new_hostname.remove(0,dot+1); 1321 new_hostname.remove(0,dot+1);
1322 1322
1323 add_domain(new_hostname, _ifaceppp); 1323 add_domain(new_hostname, _ifaceppp);
1324 } 1324 }
1325 } 1325 }
1326 1326
1327} 1327}
1328 1328
1329// Replace the DNS domain entry in the /etc/resolv.conf file and 1329// Replace the DNS domain entry in the /etc/resolv.conf file and
1330// disable the nameserver entries if option is enabled 1330// disable the nameserver entries if option is enabled
1331void add_domain(const QString &domain, InterfacePPP *_ifaceppp) { 1331void add_domain(const QString &domain, InterfacePPP *_ifaceppp) {
1332 1332
1333 int fd; 1333 int fd;
1334 char c; 1334 char c;
1335 QString resolv[MAX_RESOLVCONF_LINES]; 1335 QString resolv[MAX_RESOLVCONF_LINES];
1336 1336
1337 if (domain.isEmpty()) 1337 if (domain.isEmpty())
1338 return; 1338 return;
1339 1339
1340 if((fd = _ifaceppp->modem()->openResolv(O_RDONLY)) >= 0) { 1340 if((fd = _ifaceppp->modem()->openResolv(O_RDONLY)) >= 0) {
1341 1341
1342 int i=0; 1342 int i=0;
1343 while((read(fd, &c, 1) == 1) && (i < MAX_RESOLVCONF_LINES)) { 1343 while((read(fd, &c, 1) == 1) && (i < MAX_RESOLVCONF_LINES)) {
1344 if(c == '\n') { 1344 if(c == '\n') {
1345 i++; 1345 i++;
1346 } 1346 }
1347 else { 1347 else {
1348 resolv[i] += c; 1348 resolv[i] += c;
1349 } 1349 }
1350 } 1350 }
1351 close(fd); 1351 close(fd);
1352 if ((c != '\n') && (i < MAX_RESOLVCONF_LINES)) i++; 1352 if ((c != '\n') && (i < MAX_RESOLVCONF_LINES)) i++;
1353 1353
1354 if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_TRUNC)) >= 0) { 1354 if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_TRUNC)) >= 0) {
1355 QCString tmp = "domain " + domain.local8Bit() + 1355 QCString tmp = "domain " + domain.local8Bit() +
1356 " \t\t#kppp temp entry\n"; 1356 " \t\t#kppp temp entry\n";
1357 write(fd, tmp.data(), tmp.length()); 1357 write(fd, tmp.data(), tmp.length());
1358 1358
1359 for(int j=0; j < i; j++) { 1359 for(int j=0; j < i; j++) {
1360 if((resolv[j].contains("domain") || 1360 if((resolv[j].contains("domain") ||
1361 ( resolv[j].contains("nameserver") 1361 ( resolv[j].contains("nameserver")
1362 && !resolv[j].contains("#kppp temp entry") 1362 && !resolv[j].contains("#kppp temp entry")
1363 && _ifaceppp->data()->exDNSDisabled())) 1363 && _ifaceppp->data()->exDNSDisabled()))
1364 && !resolv[j].contains("#entry disabled by kppp")) { 1364 && !resolv[j].contains("#entry disabled by kppp")) {
1365 QCString tmp = "# " + resolv[j].local8Bit() + 1365 QCString tmp = "# " + resolv[j].local8Bit() +
1366 " \t#entry disabled by kppp\n"; 1366 " \t#entry disabled by kppp\n";
1367 write(fd, tmp, tmp.length()); 1367 write(fd, tmp, tmp.length());
1368 } 1368 }
1369 else { 1369 else {
1370 QCString tmp = resolv[j].local8Bit() + "\n"; 1370 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 @@
1/* 1/*
2 * kPPP: A pppd front end for the KDE project 2 * kPPP: A pppd front end for the KDE project
3 * 3 *
4 * $Id$ 4 * $Id$
5 * 5 *
6 * Copyright (C) 1997 Bernd Johannes Wuebben 6 * Copyright (C) 1997 Bernd Johannes Wuebben
7 * wuebben@math.cornell.edu 7 * wuebben@math.cornell.edu
8 * 8 *
9 * based on EzPPP: 9 * based on EzPPP:
10 * Copyright (C) 1997 Jay Painter 10 * Copyright (C) 1997 Jay Painter
11 * 11 *
12 * This program is free software; you can redistribute it and/or 12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public 13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either 14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version. 15 * version 2 of the License, or (at your option) any later version.
16 * 16 *
17 * This program is distributed in the hope that it will be useful, 17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details. 20 * Library General Public License for more details.
21 * 21 *
22 * You should have received a copy of the GNU Library General Public 22 * You should have received a copy of the GNU Library General Public
23 * License along with this program; if not, write to the Free 23 * License along with this program; if not, write to the Free
24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 */ 25 */
26 26
27#include "interfaceppp.h" 27#include "interfaceppp.h"
28#include "devices.h" 28#include "devices.h"
29#include "authwidget.h" 29#include "authwidget.h"
30#include "pppdata.h" 30#include "pppdata.h"
31#include "edit.h" 31#include "edit.h"
32#include "general.h" 32#include "general.h"
33 33
34/* OPIE */ 34/* OPIE */
35#include <qpe/qpeapplication.h> 35#include <qpe/qpeapplication.h>
36 36
37/* QT */ 37/* QT */
38#include <qdir.h> 38#include <qdir.h>
39#include <qlayout.h> 39#include <qlayout.h>
40#include <qtabwidget.h> 40#include <qtabwidget.h>
41#include <qtabdialog.h> 41#include <qtabdialog.h>
42#include <qwhatsthis.h> 42#include <qwhatsthis.h>
43#include <qmessagebox.h> 43#include <qmessagebox.h>
44#include <qapplication.h> 44#include <qapplication.h>
45#include <qbuttongroup.h> 45#include <qbuttongroup.h>
46#include <qmessagebox.h> 46#include <qmessagebox.h>
47#include <qvgroupbox.h> 47#include <qvgroupbox.h>
48 48
49/* STD */ 49/* STD */
50#include <stdlib.h> 50#include <stdlib.h>
51 51
52 52
53void parseargs(char* buf, char** args); 53void parseargs(char* buf, char** args);
54 54
55DevicesWidget::DevicesWidget( InterfacePPP* ip, QWidget *parent, const char *name, WFlags f ) 55DevicesWidget::DevicesWidget( InterfacePPP* ip, QWidget *parent, const char *name, WFlags f )
56 : ChooserWidget(ip->data(), parent, name, f) 56 : ChooserWidget(ip->data(), parent, name, f)
57{ 57{
58 _ifaceppp = ip; 58 _ifaceppp = ip;
59 QWhatsThis::add(edit_b, tr("Allows you to modify the selected device")); 59 QWhatsThis::add(edit_b, tr("Allows you to modify the selected device"));
60 QWhatsThis::add(new_b, tr("Create a new device") ); 60 QWhatsThis::add(new_b, tr("Create a new device") );
61 61
62 QWhatsThis::add(copy_b, 62 QWhatsThis::add(copy_b,
63 tr("Makes a copy of the selected device. All\n" 63 tr("Makes a copy of the selected device. All\n"
64 "settings of the selected device are copied\n" 64 "settings of the selected device are copied\n"
65 "to a new device, that you can modify to fit your\n" 65 "to a new device, that you can modify to fit your\n"
66 "needs")); 66 "needs"));
67 QWhatsThis::add(delete_b, 67 QWhatsThis::add(delete_b,
68 tr("<p>Deletes the selected device\n\n" 68 tr("<p>Deletes the selected device\n\n"
69 "<font color=\"red\"><b>Use with care!</b></font>")); 69 "<font color=\"red\"><b>Use with care!</b></font>"));
70 70
71 copy_b->setEnabled( false ); //FIXME 71 copy_b->setEnabled( false ); //FIXME
72// delete_b->setEnabled( false ); //FIXME 72// delete_b->setEnabled( false ); //FIXME
73 73
74 QStringList tmp = _pppdata->getDevicesNamesList(); 74 QStringList tmp = _pppdata->getDevicesNamesList();
75 qDebug("DevicesWidget::DevicesWidget got devices %s",tmp.join("--").latin1()); 75 odebug << "DevicesWidget::DevicesWidget got devices " << tmp.join("--").latin1() << "" << oendl;
76 listListbox->insertStringList(tmp); 76 listListbox->insertStringList(tmp);
77 77
78 for (uint i = 0; i < listListbox->count(); i++){ 78 for (uint i = 0; i < listListbox->count(); i++){
79 qDebug("listListbox->text(i) %s == _pppdata->devname() %s",listListbox->text(i).latin1(), _pppdata->devname().latin1()); 79 odebug << "listListbox->text(i) " << listListbox->text(i).latin1() << " == _pppdata->devname() " << _pppdata->devname().latin1() << "" << oendl;
80 if ( listListbox->text(i) == _pppdata->devname() ) 80 if ( listListbox->text(i) == _pppdata->devname() )
81 listListbox->setCurrentItem( i ); 81 listListbox->setCurrentItem( i );
82 } 82 }
83} 83}
84 84
85 85
86 86
87void DevicesWidget::slotListBoxSelect(int idx) { 87void DevicesWidget::slotListBoxSelect(int idx) {
88 bool ok = _pppdata->setDevice( listListbox->text(idx) ); 88 bool ok = _pppdata->setDevice( listListbox->text(idx) );
89 delete_b->setEnabled((bool)(idx != -1)); 89 delete_b->setEnabled((bool)(idx != -1));
90 edit_b->setEnabled((bool)(idx != -1)); 90 edit_b->setEnabled((bool)(idx != -1));
91//FIXME copy_b->setEnabled((bool)(idx != -1)); 91//FIXME copy_b->setEnabled((bool)(idx != -1));
92} 92}
93 93
94void DevicesWidget::edit() { 94void DevicesWidget::edit() {
95 _pppdata->setDevice(listListbox->text(listListbox->currentItem())); 95 _pppdata->setDevice(listListbox->text(listListbox->currentItem()));
96 96
97 int result = doTab(); 97 int result = doTab();
98 98
99 if(result == QDialog::Accepted) { 99 if(result == QDialog::Accepted) {
100 listListbox->changeItem(_pppdata->devname(),listListbox->currentItem()); 100 listListbox->changeItem(_pppdata->devname(),listListbox->currentItem());
101 _pppdata->save(); 101 _pppdata->save();
102 } 102 }
103} 103}
104 104
105 105
106void DevicesWidget::create() { 106void DevicesWidget::create() {
107 107
108// if(listListbox->count() == MAX_ACCOUNTS) { 108// if(listListbox->count() == MAX_ACCOUNTS) {
109// QMessageBox::information(this, "sorry", 109// QMessageBox::information(this, "sorry",
110// tr("Maximum number of accounts reached.")); 110// tr("Maximum number of accounts reached."));
111// return; 111// return;
112// } 112// }
113 113
114 int result; 114 int result;
115 if (_pppdata->newdevice() == -1){ 115 if (_pppdata->newdevice() == -1){
116 return; 116 return;
117 } 117 }
118 result = doTab(); 118 result = doTab();
119 119
120 if(result == QDialog::Accepted) { 120 if(result == QDialog::Accepted) {
121 listListbox->insertItem(_pppdata->devname()); 121 listListbox->insertItem(_pppdata->devname());
122 listListbox->setSelected(listListbox->findItem(_pppdata->devname()),true ); 122 listListbox->setSelected(listListbox->findItem(_pppdata->devname()),true );
123 123
124 _pppdata->save(); 124 _pppdata->save();
125 } else 125 } else
126 _pppdata->deleteDevice(); 126 _pppdata->deleteDevice();
127} 127}
128 128
129 129
130void DevicesWidget::copy() { 130void DevicesWidget::copy() {
131// if(listListbox->count() == MAX_ACCOUNTS) { 131// if(listListbox->count() == MAX_ACCOUNTS) {
132// QMessageBox::information(this, "sorry", tr("Maximum number of accounts reached.")); 132// QMessageBox::information(this, "sorry", tr("Maximum number of accounts reached."));
133// return; 133// return;
134// } 134// }
135 135
136 if(listListbox->currentItem()<0) { 136 if(listListbox->currentItem()<0) {
137 QMessageBox::information(this, "sorry", tr("No devices selected.")); 137 QMessageBox::information(this, "sorry", tr("No devices selected."));
138 return; 138 return;
139 } 139 }
140 140
141 _pppdata->copydevice(listListbox->currentText()); 141 _pppdata->copydevice(listListbox->currentText());
142 142
143 listListbox->insertItem(_pppdata->devname()); 143 listListbox->insertItem(_pppdata->devname());
144 _pppdata->save(); 144 _pppdata->save();
145} 145}
146 146
147 147
148void DevicesWidget::remove() { 148void DevicesWidget::remove() {
149 149
150 QString s = tr("Are you sure you want to delete\nthe device \"%1\"?") 150 QString s = tr("Are you sure you want to delete\nthe device \"%1\"?")
151 .arg(listListbox->text(listListbox->currentItem())); 151 .arg(listListbox->text(listListbox->currentItem()));
152 152
153 if(QMessageBox::warning(this,tr("Confirm"),s, 153 if(QMessageBox::warning(this,tr("Confirm"),s,
154 QMessageBox::Yes,QMessageBox::No 154 QMessageBox::Yes,QMessageBox::No
155 ) != QMessageBox::Yes) 155 ) != QMessageBox::Yes)
156 return; 156 return;
157 157
158 if(_pppdata->deleteDevice(listListbox->text(listListbox->currentItem()))) 158 if(_pppdata->deleteDevice(listListbox->text(listListbox->currentItem())))
159 listListbox->removeItem(listListbox->currentItem()); 159 listListbox->removeItem(listListbox->currentItem());
160 160
161 161
162// _pppdata->save(); 162// _pppdata->save();
163 163
164 164
165 slotListBoxSelect(listListbox->currentItem()); 165 slotListBoxSelect(listListbox->currentItem());
166 166
167} 167}
168 168
169 169
170int DevicesWidget::doTab(){ 170int DevicesWidget::doTab(){
171 QDialog *dlg = new QDialog( 0, "newDevice", true, Qt::WStyle_ContextHelp ); 171 QDialog *dlg = new QDialog( 0, "newDevice", true, Qt::WStyle_ContextHelp );
172 QVBoxLayout *layout = new QVBoxLayout( dlg ); 172 QVBoxLayout *layout = new QVBoxLayout( dlg );
173 layout->setSpacing( 0 ); 173 layout->setSpacing( 0 );
174 layout->setMargin( 1 ); 174 layout->setMargin( 1 );
175 175
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 )
242 { 242 {
243 if(_pppdata->enter() == enter->text(i)) 243 if(_pppdata->enter() == enter->text(i))
244 enter->setCurrentItem(i); 244 enter->setCurrentItem(i);
245 } 245 }
246 246
247 for(int i=0; i <= modemdevice->count()-1; i++) 247 for(int i=0; i <= modemdevice->count()-1; i++)
248 { 248 {
249 if(_pppdata->modemDevice() == modemdevice->text(i)) 249 if(_pppdata->modemDevice() == modemdevice->text(i))
250 modemdevice->setCurrentItem(i); 250 modemdevice->setCurrentItem(i);
251 } 251 }
252 252
253 for(int i=0; i <= flowcontrol->count()-1; i++) 253 for(int i=0; i <= flowcontrol->count()-1; i++)
254 { 254 {
255 if(_pppdata->flowcontrol() == flowcontrol->text(i)) 255 if(_pppdata->flowcontrol() == flowcontrol->text(i))
256 flowcontrol->setCurrentItem(i); 256 flowcontrol->setCurrentItem(i);
257 } 257 }
258 258
259 //set the modem speed 259 //set the modem speed
260 for(int i=0; i < baud_c->count(); i++) 260 for(int i=0; i < baud_c->count(); i++)
261 if(baud_c->text(i) == _pppdata->speed()) 261 if(baud_c->text(i) == _pppdata->speed())
262 baud_c->setCurrentItem(i); 262 baud_c->setCurrentItem(i);
263 263
264 tl->setRowStretch(1, 1); 264 tl->setRowStretch(1, 1);
265} 265}
266 266
267ModemWidget::~ModemWidget() 267ModemWidget::~ModemWidget()
268{ 268{
269 QStringList devs; 269 QStringList devs;
270 270
271 for (int i=0;i<modemdevice->count();i++) 271 for (int i=0;i<modemdevice->count();i++)
272 { 272 {
273 QString s = modemdevice->text(i); 273 QString s = modemdevice->text(i);
274 s.simplifyWhiteSpace(); 274 s.simplifyWhiteSpace();
275 if (! s.isEmpty() ) devs << s; 275 if (! s.isEmpty() ) devs << s;
276 } 276 }
277 277
278 278
279 QString edited = modemdevice->currentText(); 279 QString edited = modemdevice->currentText();
280 if ( !( edited ).isEmpty() ) 280 if ( !( edited ).isEmpty() )
281 { 281 {
282 edited.simplifyWhiteSpace(); 282 edited.simplifyWhiteSpace();
283 if ( devs.contains( edited ) == 0 ) 283 if ( devs.contains( edited ) == 0 )
284 { 284 {
285 devs << edited; 285 devs << edited;
286 } 286 }
287 _pppdata->setModemDevice( edited ); 287 _pppdata->setModemDevice( edited );
288 } 288 }
289 289
290 290
291 Config cfg("NetworkSetupPPP"); 291 Config cfg("NetworkSetupPPP");
292 cfg.setGroup("Devices_General"); 292 cfg.setGroup("Devices_General");
293 cfg.writeEntry("devices",devs,','); 293 cfg.writeEntry("devices",devs,',');
294 294
295} 295}
296 296
297// void ModemWidget::speed_selection(int) { 297// void ModemWidget::speed_selection(int) {
298// _pppdata->setSpeed(baud_c->text(baud_c->currentItem())); 298// _pppdata->setSpeed(baud_c->text(baud_c->currentItem()));
299// } 299// }
300 300
301 301
302// void ModemWidget::setenter(int ) { 302// void ModemWidget::setenter(int ) {
303// _pppdata->setEnter(enter->text(enter->currentItem())); 303// _pppdata->setEnter(enter->text(enter->currentItem()));
304// } 304// }
305 305
306 306
307// void ModemWidget::setmodemdc(int i) { 307// void ModemWidget::setmodemdc(int i) {
308// _pppdata->setModemDevice(modemdevice->text(i)); 308// _pppdata->setModemDevice(modemdevice->text(i));
309// } 309// }
310 310
311// void ModemWidget::setmodemdc( const QString &string ) { 311// void ModemWidget::setmodemdc( const QString &string ) {
312// _pppdata->setModemDevice( string ); 312// _pppdata->setModemDevice( string );
313// } 313// }
314 314
315// void ModemWidget::setflowcontrol(int i) { 315// void ModemWidget::setflowcontrol(int i) {
316// _pppdata->setFlowcontrol(flowcontrol->text(i)); 316// _pppdata->setFlowcontrol(flowcontrol->text(i));
317// } 317// }
318 318
319 319
320// void ModemWidget::modemlockfilechanged(bool set) { 320// void ModemWidget::modemlockfilechanged(bool set) {
321// _pppdata->setModemLockFile(set); 321// _pppdata->setModemLockFile(set);
322// } 322// }
323 323
324 324
325// void ModemWidget::modemtimeoutchanged(int n) { 325// void ModemWidget::modemtimeoutchanged(int n) {
326// _pppdata->setModemTimeout(n); 326// _pppdata->setModemTimeout(n);
327// } 327// }
328 328
329 329
330 330
331bool ModemWidget::save() 331bool ModemWidget::save()
332{ 332{
333 //first check to make sure that the device name is unique! 333 //first check to make sure that the device name is unique!
334 if(modemname->text().isEmpty() || 334 if(modemname->text().isEmpty() ||
335 !_pppdata->isUniqueDevname(modemname->text())) 335 !_pppdata->isUniqueDevname(modemname->text()))
336 return false; 336 return false;
337 337
338 qDebug("ModemWidget::save saving modem1 data"); 338 odebug << "ModemWidget::save saving modem1 data" << oendl;
339 _pppdata->setDevname( modemname->text() ); 339 _pppdata->setDevname( modemname->text() );
340 _pppdata->setModemDevice( modemdevice->currentText() ); 340 _pppdata->setModemDevice( modemdevice->currentText() );
341 _pppdata->setFlowcontrol(flowcontrol->currentText()); 341 _pppdata->setFlowcontrol(flowcontrol->currentText());
342 _pppdata->setFlowcontrol(flowcontrol->currentText()); 342 _pppdata->setFlowcontrol(flowcontrol->currentText());
343 _pppdata->setSpeed(baud_c->currentText()); 343 _pppdata->setSpeed(baud_c->currentText());
344 _pppdata->setModemLockFile( modemlockfile->isChecked()); 344 _pppdata->setModemLockFile( modemlockfile->isChecked());
345 _pppdata->setModemTimeout( modemtimeout->value() ); 345 _pppdata->setModemTimeout( modemtimeout->value() );
346 return true; 346 return true;
347 347
348} 348}
349 349
350ModemWidget2::ModemWidget2( PPPData *pd, InterfacePPP *ip, QWidget *parent, 350ModemWidget2::ModemWidget2( PPPData *pd, InterfacePPP *ip, QWidget *parent,
351 const char *name) 351 const char *name)
352 : QWidget(parent, name), _pppdata(pd), _ifaceppp(ip) 352 : QWidget(parent, name), _pppdata(pd), _ifaceppp(ip)
353{ 353{
354 QVBoxLayout *l1 = new QVBoxLayout(this, 0 );//, KDialog::spacingHint()); 354 QVBoxLayout *l1 = new QVBoxLayout(this, 0 );//, KDialog::spacingHint());
355 355
356 356
357 waitfordt = new QCheckBox(tr("&Wait for dial tone before dialing"), this); 357 waitfordt = new QCheckBox(tr("&Wait for dial tone before dialing"), this);
358 waitfordt->setChecked(_pppdata->waitForDialTone()); 358 waitfordt->setChecked(_pppdata->waitForDialTone());
359 // connect(waitfordt, SIGNAL(toggled(bool)), SLOT(waitfordtchanged(bool))); 359 // connect(waitfordt, SIGNAL(toggled(bool)), SLOT(waitfordtchanged(bool)));
360 l1->addWidget(waitfordt); 360 l1->addWidget(waitfordt);
361 QWhatsThis::add(waitfordt, 361 QWhatsThis::add(waitfordt,
362 tr("<p>Normally the modem waits for a dial tone\n" 362 tr("<p>Normally the modem waits for a dial tone\n"
363 "from your phone line, indicating that it can\n" 363 "from your phone line, indicating that it can\n"
364 "start to dial a number. If your modem does not\n" 364 "start to dial a number. If your modem does not\n"
365 "recognize this sound, or your local phone system\n" 365 "recognize this sound, or your local phone system\n"
366 "does not emit such a tone, uncheck this option\n" 366 "does not emit such a tone, uncheck this option\n"
367 "\n" 367 "\n"
368 "<b>Default:</b>: On")); 368 "<b>Default:</b>: On"));
369 369
370 QHBoxLayout *waitLayout = new QHBoxLayout( this ); 370 QHBoxLayout *waitLayout = new QHBoxLayout( this );
371 QLabel *waitLabel = new QLabel( tr("Busy wait:"), this, "busyWait" ); 371 QLabel *waitLabel = new QLabel( tr("Busy wait:"), this, "busyWait" );
372 busywait = new QSpinBox( 0, 300, 5, this, "busyWait" ); 372 busywait = new QSpinBox( 0, 300, 5, this, "busyWait" );
373 // busywait = new KIntNumInput(_pppdata->busyWait(), this); 373 // busywait = new KIntNumInput(_pppdata->busyWait(), this);
374 // busywait->setLabel(tr("B&usy wait:")); 374 // busywait->setLabel(tr("B&usy wait:"));
375 // busywait->setRange(0, 300, 5, true); 375 // busywait->setRange(0, 300, 5, true);
376 busywait->setSuffix(tr(" sec")); 376 busywait->setSuffix(tr(" sec"));
377 // connect(busywait, SIGNAL(valueChanged(int)), SLOT(busywaitchanged(int))); 377 // connect(busywait, SIGNAL(valueChanged(int)), SLOT(busywaitchanged(int)));
378 waitLayout->addWidget(waitLabel); 378 waitLayout->addWidget(waitLabel);
379 waitLayout->addWidget(busywait); 379 waitLayout->addWidget(busywait);
380 l1->addLayout( waitLayout ); 380 l1->addLayout( waitLayout );
381 381
382 QWhatsThis::add(busywait, 382 QWhatsThis::add(busywait,
383 tr("Specifies the number of seconds to wait before\n" 383 tr("Specifies the number of seconds to wait before\n"
384 "redial if all dialed numbers are busy. This is\n" 384 "redial if all dialed numbers are busy. This is\n"
385 "necessary because some modems get stuck if the\n" 385 "necessary because some modems get stuck if the\n"
386 "same number is busy too often.\n" 386 "same number is busy too often.\n"
387 "\n" 387 "\n"
388 "The default is 0 seconds, you should not change\n" 388 "The default is 0 seconds, you should not change\n"
389 "this unless you need to.")); 389 "this unless you need to."));
390 390
391 l1->addSpacing(10); 391 l1->addSpacing(10);
392 392
393 QHBoxLayout *hbl = new QHBoxLayout; 393 QHBoxLayout *hbl = new QHBoxLayout;
394 hbl->setSpacing(2);//KDialog::spacingHint()); 394 hbl->setSpacing(2);//KDialog::spacingHint());
395 395
396 QLabel *volumeLabel = new QLabel(tr("Modem &volume:"), this); 396 QLabel *volumeLabel = new QLabel(tr("Modem &volume:"), this);
397 hbl->addWidget(volumeLabel); 397 hbl->addWidget(volumeLabel);
398 volume = new QSlider(0, 2, 1, _pppdata->volume(), 398 volume = new QSlider(0, 2, 1, _pppdata->volume(),
399 QSlider::Horizontal, this); 399 QSlider::Horizontal, this);
400 volumeLabel->setBuddy(volume); 400 volumeLabel->setBuddy(volume);
401 volume->setTickmarks(QSlider::Below); 401 volume->setTickmarks(QSlider::Below);
402 hbl->addWidget(volume); 402 hbl->addWidget(volume);
403 403
404 l1->addLayout(hbl); 404 l1->addLayout(hbl);
405 405
406 // connect(volume, SIGNAL(valueChanged(int)), 406 // connect(volume, SIGNAL(valueChanged(int)),
407 // this, SLOT(volumeChanged(int))); 407 // this, SLOT(volumeChanged(int)));
408 QString tmp = tr("Most modems have a speaker which makes\n" 408 QString tmp = tr("Most modems have a speaker which makes\n"
409 "a lot of noise when dialing. Here you can\n" 409 "a lot of noise when dialing. Here you can\n"
410 "either turn this completely off or select a\n" 410 "either turn this completely off or select a\n"
411 "lower volume.\n" 411 "lower volume.\n"
412 "\n" 412 "\n"
413 "If this does not work for your modem,\n" 413 "If this does not work for your modem,\n"
414 "you must modify the modem volume command."); 414 "you must modify the modem volume command.");
415 415
416 QWhatsThis::add(volumeLabel,tmp); 416 QWhatsThis::add(volumeLabel,tmp);
417 QWhatsThis::add(volume, tmp); 417 QWhatsThis::add(volume, tmp);
418 418
419 l1->addSpacing(20); 419 l1->addSpacing(20);
420 420
421#if 0 421#if 0
422 chkbox1 = new QCheckBox(tr("Modem asserts CD line"), this); 422 chkbox1 = new QCheckBox(tr("Modem asserts CD line"), this);
423 chkbox1->setChecked(_pppdata->UseCDLine()); 423 chkbox1->setChecked(_pppdata->UseCDLine());
424 connect(chkbox1,SIGNAL(toggled(bool)), 424 connect(chkbox1,SIGNAL(toggled(bool)),
425 this,SLOT(use_cdline_toggled(bool))); 425 this,SLOT(use_cdline_toggled(bool)));
426 l12->addWidget(chkbox1); 426 l12->addWidget(chkbox1);
427 l12->addStretch(1); 427 l12->addStretch(1);
428 l1->addStretch(1); 428 l1->addStretch(1);
429 QWhatsThis::add(chkbox1, 429 QWhatsThis::add(chkbox1,
430 tr("This controls how <i>kppp</i> detects that the modem\n" 430 tr("This controls how <i>kppp</i> detects that the modem\n"
431 "is not responding. Unless you are having\n" 431 "is not responding. Unless you are having\n"
432 "problems with this, do not modify this setting.\n" 432 "problems with this, do not modify this setting.\n"
433 "\n" 433 "\n"
434 "<b>Default</b>: Off")); 434 "<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 @@
1#include "interfaceinformationppp.h" 1#include "interfaceinformationppp.h"
2 2
3#include <qpushbutton.h> 3#include <qpushbutton.h>
4#include <qlabel.h> 4#include <qlabel.h>
5#include <qmessagebox.h> 5#include <qmessagebox.h>
6#include <qabstractlayout.h> 6#include <qabstractlayout.h>
7 7
8#include "connect.h" 8#include "connect.h"
9#include "conwindow.h" 9#include "conwindow.h"
10 10
11#ifdef QWS 11#ifdef QWS
12#else 12#else
13 #define showMaximized show 13 #define showMaximized show
14#endif 14#endif
15 15
16/** 16/**
17 * Constructor for the InterfaceInformationImp class. This class pretty much 17 * Constructor for the InterfaceInformationImp class. This class pretty much
18 * just display's information about the interface that is passed to it. 18 * just display's information about the interface that is passed to it.
19 */ 19 */
20InterfaceInformationPPP::InterfaceInformationPPP(QWidget *parent, const char *name, Interface *i, WFlags f) 20InterfaceInformationPPP::InterfaceInformationPPP(QWidget *parent, const char *name, Interface *i, WFlags f)
21 :InterfaceInformationImp(parent, name, i, Qt::WStyle_ContextHelp) 21 :InterfaceInformationImp(parent, name, i, Qt::WStyle_ContextHelp)
22{ 22{
23 qDebug("InterfaceInformationPPP::InterfaceInformationPPP %s", name); 23 odebug << "InterfaceInformationPPP::InterfaceInformationPPP " << name << "" << oendl;
24 con = new ConnectWidget( (InterfacePPP*)i, this, "con" ); 24 con = new ConnectWidget( (InterfacePPP*)i, this, "con" );
25 con->setSizePolicy( QSizePolicy(QSizePolicy::MinimumExpanding, 25 con->setSizePolicy( QSizePolicy(QSizePolicy::MinimumExpanding,
26 QSizePolicy::Fixed) ); 26 QSizePolicy::Fixed) );
27 27
28 macAddressLabel->hide(); 28 macAddressLabel->hide();
29 subnetMaskLabel->hide(); 29 subnetMaskLabel->hide();
30 broadcastLabel->hide(); 30 broadcastLabel->hide();
31 TextLabel23->hide(); 31 TextLabel23->hide();
32 TextLabel21->hide(); 32 TextLabel21->hide();
33 TextLabel24->hide(); 33 TextLabel24->hide();
34 34
35 InterfaceInformationLayout->addWidget( con, 1, 0 ); 35 InterfaceInformationLayout->addWidget( con, 1, 0 );
36 connect(i, SIGNAL(begin_connect()),con, SLOT(preinit())); 36 connect(i, SIGNAL(begin_connect()),con, SLOT(preinit()));
37 connect(i, SIGNAL(hangup_now() ), con, SLOT(cancelbutton() ) ); 37 connect(i, SIGNAL(hangup_now() ), con, SLOT(cancelbutton() ) );
38} 38}
39 39
40 40
41 41
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 @@
1 1
2#include <qmessagebox.h> 2#include <qmessagebox.h>
3#include <qlayout.h> 3#include <qlayout.h>
4#include <qlineedit.h> 4#include <qlineedit.h>
5#include <qlabel.h> 5#include <qlabel.h>
6 6
7#include "auth.h" 7#include "auth.h"
8#include "interfaceppp.h" 8#include "interfaceppp.h"
9#include "modem.h" 9#include "modem.h"
10#include "pppdata.h" 10#include "pppdata.h"
11 11
12InterfacePPP::InterfacePPP(QObject *parent, const char *name, bool status) 12InterfacePPP::InterfacePPP(QObject *parent, const char *name, bool status)
13 : Interface(parent, name, status), 13 : Interface(parent, name, status),
14 _modemPtr(0), 14 _modemPtr(0),
15 _dataPtr(0) 15 _dataPtr(0)
16{ 16{
17 qDebug("InterfacePPP::InterfacePPP("); 17 odebug << "InterfacePPP::InterfacePPP(" << oendl;
18} 18}
19 19
20PPPData* InterfacePPP::data()const 20PPPData* InterfacePPP::data()const
21{ 21{
22 if (!_dataPtr){ 22 if (!_dataPtr){
23 qDebug("creating new Data obj"); 23 odebug << "creating new Data obj" << oendl;
24 _dataPtr = new PPPData(); 24 _dataPtr = new PPPData();
25 _dataPtr->setDevice( getInterfaceName() ); 25 _dataPtr->setDevice( getInterfaceName() );
26 _dataPtr->setAccount( getHardwareName() ); 26 _dataPtr->setAccount( getHardwareName() );
27 } 27 }
28 return _dataPtr; 28 return _dataPtr;
29} 29}
30 30
31Modem* InterfacePPP::modem()const 31Modem* InterfacePPP::modem()const
32{ 32{
33 if (!_modemPtr){ 33 if (!_modemPtr){
34 qDebug("creating new modem obj"); 34 odebug << "creating new modem obj" << oendl;
35 _modemPtr = new Modem( data() ); 35 _modemPtr = new Modem( data() );
36 } 36 }
37 return _modemPtr; 37 return _modemPtr;
38} 38}
39 39
40bool InterfacePPP::refresh() 40bool InterfacePPP::refresh()
41{ 41{
42 qDebug("InterfacePPP::refresh()"); 42 odebug << "InterfacePPP::refresh()" << oendl;
43 QString old = getInterfaceName(); 43 QString old = getInterfaceName();
44 setInterfaceName( modem()->pppDevice() ); 44 setInterfaceName( modem()->pppDevice() );
45 45
46 (void)Interface::refresh(); 46 (void)Interface::refresh();
47 47
48 setInterfaceName( old ); 48 setInterfaceName( old );
49 emit updateInterface(this); 49 emit updateInterface(this);
50 50
51 return true; 51 return true;
52} 52}
53 53
54void InterfacePPP::start() 54void InterfacePPP::start()
55{ 55{
56 qDebug("InterfacePPP::start"); 56 odebug << "InterfacePPP::start" << oendl;
57 57
58 if (data()->password().isEmpty() && !data()->storedUsername().isEmpty() ) { 58 if (data()->password().isEmpty() && !data()->storedUsername().isEmpty() ) {
59 59
60 QDialog mb( 0, "Dialog", true ); 60 QDialog mb( 0, "Dialog", true );
61 mb.setCaption( tr( "No password" ) ); 61 mb.setCaption( tr( "No password" ) );
62 QVBoxLayout layout( &mb ); 62 QVBoxLayout layout( &mb );
63 QLabel text ( &mb ); 63 QLabel text ( &mb );
64 text.setText( tr("Username defined but no password\n Please enter a password") ); 64 text.setText( tr("Username defined but no password\n Please enter a password") );
65 QLineEdit lineedit( &mb ); 65 QLineEdit lineedit( &mb );
66 lineedit.setEchoMode( QLineEdit::Password ); 66 lineedit.setEchoMode( QLineEdit::Password );
67 layout.addWidget( &text ); 67 layout.addWidget( &text );
68 layout.addWidget( &lineedit ); 68 layout.addWidget( &lineedit );
69 if ( mb.exec() == QDialog::Accepted ) { 69 if ( mb.exec() == QDialog::Accepted ) {
70 data()->setPassword( lineedit.text() ); 70 data()->setPassword( lineedit.text() );
71 } 71 }
72 } 72 }
73 73
74 QFileInfo info(pppdPath()); 74 QFileInfo info(pppdPath());
75 75
76 if(!info.exists()){ 76 if(!info.exists()){
77 QMessageBox::warning(0, tr("Error"), 77 QMessageBox::warning(0, tr("Error"),
78 QObject::tr("<qt>Cannot find the PPP daemon!<br>" 78 QObject::tr("<qt>Cannot find the PPP daemon!<br>"
79 "Make sure that pppd is installed and " 79 "Make sure that pppd is installed and "
80 "that you have entered the correct path.</qt>")); 80 "that you have entered the correct path.</qt>"));
81 return; 81 return;
82 } 82 }
83//#if 0 83//#if 0
84 if(!info.isExecutable()){ 84 if(!info.isExecutable()){
85 85
86 QString string; 86 QString string;
87 string = QObject::tr( "<qt>Cannot execute:<br> %1<br>" 87 string = QObject::tr( "<qt>Cannot execute:<br> %1<br>"
88 "Please make sure that you have given " 88 "Please make sure that you have given "
89 "setuid permission and that " 89 "setuid permission and that "
90 "pppd is executable.<br>").arg(pppdPath()); 90 "pppd is executable.<br>").arg(pppdPath());
91 QMessageBox::warning(0, tr("Error"), string); 91 QMessageBox::warning(0, tr("Error"), string);
92 return; 92 return;
93 93
94 } 94 }
95//#endif 95//#endif
96 96
97 QFileInfo info2(data()->modemDevice()); 97 QFileInfo info2(data()->modemDevice());
98 98
99 if(!info2.exists()){ 99 if(!info2.exists()){
100 QString string; 100 QString string;
101 string = QObject::tr( "<qt>Cannot find:<br> %1<br>" 101 string = QObject::tr( "<qt>Cannot find:<br> %1<br>"
102 "Please make sure you have setup " 102 "Please make sure you have setup "
103 "your modem device properly " 103 "your modem device properly "
104 "and/or adjust the location of the modem device on " 104 "and/or adjust the location of the modem device on "
105 "the modem tab of " 105 "the modem tab of "
106 "the setup dialog.</qt>").arg(data()->modemDevice()); 106 "the setup dialog.</qt>").arg(data()->modemDevice());
107 QMessageBox::warning(0, tr("Error"), string); 107 QMessageBox::warning(0, tr("Error"), string);
108 return; 108 return;
109 } 109 }
110 110
111 // if this is a PAP or CHAP account, ensure that username is 111 // if this is a PAP or CHAP account, ensure that username is
112 // supplied 112 // supplied
113 if(data()->authMethod() == AUTH_PAP || 113 if(data()->authMethod() == AUTH_PAP ||
114 data()->authMethod() == AUTH_CHAP || 114 data()->authMethod() == AUTH_CHAP ||
115 data()->authMethod() == AUTH_PAPCHAP ) { 115 data()->authMethod() == AUTH_PAPCHAP ) {
116 if(false){ //FIXME: ID_Edit->text().isEmpty()) { 116 if(false){ //FIXME: ID_Edit->text().isEmpty()) {
117 QMessageBox::warning(0,tr("Error"), 117 QMessageBox::warning(0,tr("Error"),
118 QObject::tr("<qt>You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!</qt>")); 118 QObject::tr("<qt>You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!</qt>"));
119// FIXME: return; 119// FIXME: return;
120 } else { 120 } else {
121 if(!modem()->setSecret(data()->authMethod(), 121 if(!modem()->setSecret(data()->authMethod(),
122 PPPData::encodeWord(data()->storedUsername()), 122 PPPData::encodeWord(data()->storedUsername()),
123 PPPData::encodeWord(data()->password())) 123 PPPData::encodeWord(data()->password()))
124 ) { 124 ) {
125 QString s; 125 QString s;
126 s = QObject::tr("<qt>Cannot create PAP/CHAP authentication<br>" 126 s = QObject::tr("<qt>Cannot create PAP/CHAP authentication<br>"
127 "file \"%1\"</qt>").arg(PAP_AUTH_FILE); 127 "file \"%1\"</qt>").arg(PAP_AUTH_FILE);
128 QMessageBox::warning(0, tr("Error"), s); 128 QMessageBox::warning(0, tr("Error"), s);
129 return; 129 return;
130 } 130 }
131 } 131 }
132 } 132 }
133 133
134 if (data()->phonenumber().isEmpty()) { 134 if (data()->phonenumber().isEmpty()) {
135 QString s = QObject::tr("You must specify a telephone number!"); 135 QString s = QObject::tr("You must specify a telephone number!");
136 QMessageBox::warning(0, tr("Error"), s); 136 QMessageBox::warning(0, tr("Error"), s);
137 return; 137 return;
138 } 138 }
139 139
140 // SEGFAULTS: 140 // SEGFAULTS:
141// setStatus( true ); 141// setStatus( true );
142// emit updateInterface((Interface*) this); 142// emit updateInterface((Interface*) this);
143 143
144 emit begin_connect(); 144 emit begin_connect();
145 145
146 qDebug("InterfacePPP::start END"); 146 odebug << "InterfacePPP::start END" << oendl;
147} 147}
148 148
149void InterfacePPP::stop() 149void InterfacePPP::stop()
150{ 150{
151 qDebug("InterfacePPP::stop"); 151 odebug << "InterfacePPP::stop" << oendl;
152 // emit hangup_now(); 152 // emit hangup_now();
153 status = false; // not connected 153 status = false; // not connected
154 setStatus( false ); 154 setStatus( false );
155 emit hangup_now(); 155 emit hangup_now();
156 refresh(); 156 refresh();
157 157
158} 158}
159 159
160void InterfacePPP::save() 160void InterfacePPP::save()
161{ 161{
162 data()->save(); 162 data()->save();
163 emit updateInterface((Interface*) this); 163 emit updateInterface((Interface*) this);
164} 164}
165QString InterfacePPP::pppDev()const { 165QString InterfacePPP::pppDev()const {
166 return modem()->pppDevice(); 166 return modem()->pppDevice();
167} 167}
168pid_t InterfacePPP::pppPID()const{ 168pid_t InterfacePPP::pppPID()const{
169 return modem()->pppPID(); 169 return modem()->pppPID();
170} 170}
171void InterfacePPP::setPPPDpid( pid_t pid) { 171void InterfacePPP::setPPPDpid( pid_t pid) {
172 setStatus( true ); 172 setStatus( true );
173 modem()->setPPPDPid( pid ); 173 modem()->setPPPDPid( pid );
174} 174}
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 @@
1/* 1/*
2 * 2 *
3 * kPPP: A pppd front end for the KDE project 3 * kPPP: A pppd front end for the KDE project
4 * 4 *
5 * $Id$ 5 * $Id$
6 * 6 *
7 * Copyright (C) 1997 Bernd Johannes Wuebben 7 * Copyright (C) 1997 Bernd Johannes Wuebben
8 * wuebben@math.cornell.edu 8 * wuebben@math.cornell.edu
9 * 9 *
10 * Copyright (C) 1998-2002 Harri Porten <porten@kde.org> 10 * Copyright (C) 1998-2002 Harri Porten <porten@kde.org>
11 * 11 *
12 * This program is free software; you can redistribute it and/or 12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public 13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either 14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version. 15 * version 2 of the License, or (at your option) any later version.
16 * 16 *
17 * This program is distributed in the hope that it will be useful, 17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details. 20 * Library General Public License for more details.
21 * 21 *
22 * You should have received a copy of the GNU Library General Public 22 * You should have received a copy of the GNU Library General Public
23 * License along with this program; if not, write to the Free 23 * License along with this program; if not, write to the Free
24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 */ 25 */
26 26
27#include "kpppwidget.h" 27#include "kpppwidget.h"
28 28
29#include <qapplication.h> 29#include <qapplication.h>
30#include <qcombobox.h> 30#include <qcombobox.h>
31#include <qdir.h> 31#include <qdir.h>
32#include <qevent.h> 32#include <qevent.h>
33#include <qdialog.h> 33#include <qdialog.h>
34#include <qlabel.h> 34#include <qlabel.h>
35#include <qpushbutton.h> 35#include <qpushbutton.h>
36#include <qregexp.h> 36#include <qregexp.h>
37#include <qtabwidget.h> 37#include <qtabwidget.h>
38#include <qdialog.h> 38#include <qdialog.h>
39#include <qwhatsthis.h> 39#include <qwhatsthis.h>
40#include <qcheckbox.h> 40#include <qcheckbox.h>
41 41
42// #include <kaboutdata.h> 42// #include <kaboutdata.h>
43// #include <kapplication.h> 43// #include <kapplication.h>
44#include <qbuttongroup.h> 44#include <qbuttongroup.h>
45#include <qmessagebox.h> 45#include <qmessagebox.h>
46#include <qpushbutton.h> 46#include <qpushbutton.h>
47 47
48#include <stdlib.h> 48#include <stdlib.h>
49#include <errno.h> 49#include <errno.h>
50#include <signal.h> 50#include <signal.h>
51 51
52#include "runtests.h" 52#include "runtests.h"
53 53
54//#include "main.h" 54//#include "main.h"
55#include "auth.h" 55#include "auth.h"
56#include "modem.h" 56#include "modem.h"
57//#include "ppplog.h" 57//#include "ppplog.h"
58//#include "opener.h" 58//#include "opener.h"
59//#include "requester.h" 59//#include "requester.h"
60//#include "pppstats.h" 60//#include "pppstats.h"
61#include "pppdata.h" 61#include "pppdata.h"
62#include "general.h" 62#include "general.h"
63#include "interface.h" 63#include "interface.h"
64 64
65#define execute_command system 65#define execute_command system
66 66
67KPPPWidget *p_kppp = 0; 67KPPPWidget *p_kppp = 0;
68 68
69KPPPWidget::KPPPWidget(PPPData*pd, Interface *i, QWidget *parent, const char *name, bool modal, WFlags fl ) 69KPPPWidget::KPPPWidget(PPPData*pd, Interface *i, QWidget *parent, const char *name, bool modal, WFlags fl )
70 : QDialog(parent, name, modal, Qt::WStyle_ContextHelp ), _pppdata(pd) 70 : QDialog(parent, name, modal, Qt::WStyle_ContextHelp ), _pppdata(pd)
71{ 71{
72// tabWindow = 0; 72// tabWindow = 0;
73 p_kppp = this; 73 p_kppp = this;
74 // before doing anything else, run a few tests 74 // before doing anything else, run a few tests
75 if (!_pppdata->setModemDevice( i->getInterfaceName() )) 75 if (!_pppdata->setModemDevice( i->getInterfaceName() ))
76 _pppdata->setModemDevice("/dev/modem"); 76 _pppdata->setModemDevice("/dev/modem");
77 qDebug("PPPConfigWidget::PPPConfigWidget"); 77 odebug << "PPPConfigWidget::PPPConfigWidget" << oendl;
78 qDebug(" interface->getHardwareName >%s<", i->getHardwareName().latin1()); 78 odebug << " interface->getHardwareName >" << i->getHardwareName().latin1() << "<" << oendl;
79 if (!_pppdata->setAccount( i->getHardwareName() )) 79 if (!_pppdata->setAccount( i->getHardwareName() ))
80 _pppdata->setAccount( 0 ); 80 _pppdata->setAccount( 0 );
81 81
82 qDebug(" _pppdata->accname >%s<",_pppdata->accname().latin1()); 82 odebug << " _pppdata->accname >" << _pppdata->accname().latin1() << "<" << oendl;
83 qDebug(" _pppdata->currentAccountID() >%i<",_pppdata->currentAccountID()); 83 odebug << " _pppdata->currentAccountID() >" << _pppdata->currentAccountID() << "<" << oendl;
84 84
85 int result = runTests(); 85 int result = runTests();
86 if(result == TEST_CRITICAL) 86 if(result == TEST_CRITICAL)
87 exit(4); 87 exit(4);
88 88
89// installEventFilter(this); 89// installEventFilter(this);
90 90
91 QVBoxLayout *tl = new QVBoxLayout(this, 10, 10); 91 QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
92 92
93 QGridLayout *l1 = new QGridLayout(3, 4); 93 QGridLayout *l1 = new QGridLayout(3, 4);
94 tl->addLayout(l1); 94 tl->addLayout(l1);
95 l1->addColSpacing(0, 10); 95 l1->addColSpacing(0, 10);
96 l1->addColSpacing(3, 10); 96 l1->addColSpacing(3, 10);
97 l1->setColStretch(1, 3); 97 l1->setColStretch(1, 3);
98 l1->setColStretch(2, 4); 98 l1->setColStretch(2, 4);
99 99
100 label1 = new QLabel(QObject::tr("C&onnect to: "), this); 100 label1 = new QLabel(QObject::tr("C&onnect to: "), this);
101 l1->addWidget(label1, 0, 1); 101 l1->addWidget(label1, 0, 1);
102 102
103 connectto_c = new QComboBox(false, this); 103 connectto_c = new QComboBox(false, this);
104 label1->setBuddy(connectto_c); 104 label1->setBuddy(connectto_c);
105 105
106 connect(connectto_c, SIGNAL(activated(int)), 106 connect(connectto_c, SIGNAL(activated(int)),
107 SLOT(newdefaultaccount(int))); 107 SLOT(newdefaultaccount(int)));
108 l1->addWidget(connectto_c, 0, 2); 108 l1->addWidget(connectto_c, 0, 2);
109 109
110 ID_Label = new QLabel(QObject::tr("&Login ID:"), this); 110 ID_Label = new QLabel(QObject::tr("&Login ID:"), this);
111 l1->addWidget(ID_Label, 1, 1); 111 l1->addWidget(ID_Label, 1, 1);
112 112
113 // the entry line for usernames 113 // the entry line for usernames
114 ID_Edit = new QLineEdit(this); 114 ID_Edit = new QLineEdit(this);
115 ID_Label->setBuddy(ID_Edit); 115 ID_Label->setBuddy(ID_Edit);
116 l1->addWidget(ID_Edit, 1, 2); 116 l1->addWidget(ID_Edit, 1, 2);
117 connect(ID_Edit, SIGNAL(returnPressed()), 117 connect(ID_Edit, SIGNAL(returnPressed()),
118 this, SLOT(enterPressedInID())); 118 this, SLOT(enterPressedInID()));
119 QString tmp = QObject::tr("<p>Type in the username that you got from your\n" 119 QString tmp = QObject::tr("<p>Type in the username that you got from your\n"
120 "ISP. This is especially important for PAP\n" 120 "ISP. This is especially important for PAP\n"
121 "and CHAP. You may omit this when you use\n" 121 "and CHAP. You may omit this when you use\n"
122 "terminal-based or script-based authentication.\n" 122 "terminal-based or script-based authentication.\n"
123 "\n" 123 "\n"
124 "<b>Important</b>: case is important here:\n" 124 "<b>Important</b>: case is important here:\n"
125 "<i>myusername</i> is not the same as <i>MyUserName</i>!"); 125 "<i>myusername</i> is not the same as <i>MyUserName</i>!");
126 126
127 QWhatsThis::add(ID_Label,tmp); 127 QWhatsThis::add(ID_Label,tmp);
128 QWhatsThis::add(ID_Edit,tmp); 128 QWhatsThis::add(ID_Edit,tmp);
129 129
130 PW_Label = new QLabel(QObject::tr("&Password:"), this); 130 PW_Label = new QLabel(QObject::tr("&Password:"), this);
131 l1->addWidget(PW_Label, 2, 1); 131 l1->addWidget(PW_Label, 2, 1);
132 132
133 PW_Edit= new QLineEdit(this); 133 PW_Edit= new QLineEdit(this);
134 PW_Label->setBuddy(PW_Edit); 134 PW_Label->setBuddy(PW_Edit);
135 PW_Edit->setEchoMode(QLineEdit::Password); 135 PW_Edit->setEchoMode(QLineEdit::Password);
136 l1->addWidget(PW_Edit, 2, 2); 136 l1->addWidget(PW_Edit, 2, 2);
137 connect(PW_Edit, SIGNAL(returnPressed()), 137 connect(PW_Edit, SIGNAL(returnPressed()),
138 this, SLOT(enterPressedInPW())); 138 this, SLOT(enterPressedInPW()));
139 139
140 tmp = QObject::tr("<p>Type in the password that you got from your\n" 140 tmp = QObject::tr("<p>Type in the password that you got from your\n"
141 "ISP. This is especially important for PAP\n" 141 "ISP. This is especially important for PAP\n"
142 "and CHAP. You may omit this when you use\n" 142 "and CHAP. You may omit this when you use\n"
143 "terminal-based or script-based authentication.\n" 143 "terminal-based or script-based authentication.\n"
144 "\n" 144 "\n"
145 "<b>Important</b>: case is important here:\n" 145 "<b>Important</b>: case is important here:\n"
146 "<i>mypassword</i> is not the same as <i>MyPassword</i>!"); 146 "<i>mypassword</i> is not the same as <i>MyPassword</i>!");
147 147
148 QWhatsThis::add(PW_Label,tmp); 148 QWhatsThis::add(PW_Label,tmp);
149 QWhatsThis::add(PW_Edit,tmp); 149 QWhatsThis::add(PW_Edit,tmp);
150 150
151 QHBoxLayout *l3 = new QHBoxLayout; 151 QHBoxLayout *l3 = new QHBoxLayout;
152 tl->addSpacing(5); 152 tl->addSpacing(5);
153 tl->addLayout(l3); 153 tl->addLayout(l3);
154 tl->addSpacing(5); 154 tl->addSpacing(5);
155 l3->addSpacing(10); 155 l3->addSpacing(10);
156 log = new QCheckBox(QObject::tr("Show lo&g window"), this); 156 log = new QCheckBox(QObject::tr("Show lo&g window"), this);
157 connect(log, SIGNAL(toggled(bool)), 157 connect(log, SIGNAL(toggled(bool)),
158 this, SLOT(log_window_toggled(bool))); 158 this, SLOT(log_window_toggled(bool)));
159 log->setChecked(_pppdata->get_show_log_window()); 159 log->setChecked(_pppdata->get_show_log_window());
160 l3->addWidget(log); 160 l3->addWidget(log);
161 161
162 QWhatsThis::add(log, 162 QWhatsThis::add(log,
163 QObject::tr("<p>This controls whether a log window is shown.\n" 163 QObject::tr("<p>This controls whether a log window is shown.\n"
164 "A log window shows the communication between\n" 164 "A log window shows the communication between\n"
165 "<i>kppp</i> and your modem. This will help you\n" 165 "<i>kppp</i> and your modem. This will help you\n"
166 "in tracking down problems.\n" 166 "in tracking down problems.\n"
167 "\n" 167 "\n"
168 "Turn it off if <i>kppp</i> routinely connects without\n" 168 "Turn it off if <i>kppp</i> routinely connects without\n"
169 "problems")); 169 "problems"));
170 170
171// fline = new QSeparator( KSeparator::HLine, this); 171// fline = new QSeparator( KSeparator::HLine, this);
172// tl->addWidget(fline); 172// tl->addWidget(fline);
173 173
174 QHBoxLayout *l2 = new QHBoxLayout(this); 174 QHBoxLayout *l2 = new QHBoxLayout(this);
175 tl->addLayout(l2); 175 tl->addLayout(l2);
176 176
177 int minw = 0; 177 int minw = 0;
178 quit_b = new QPushButton(QObject::tr("&Quit"), this); 178 quit_b = new QPushButton(QObject::tr("&Quit"), this);
179 // quit_b-> setGuiItem (KGuiItem(QObject::tr("&Quit"), "exit" ) ); 179 // quit_b-> setGuiItem (KGuiItem(QObject::tr("&Quit"), "exit" ) );
@@ -212,399 +212,399 @@ KPPPWidget::KPPPWidget(PPPData*pd, Interface *i, QWidget *parent, const char *na
212 quit_b->setFixedWidth(minw); 212 quit_b->setFixedWidth(minw);
213 setup_b->setFixedWidth(minw); 213 setup_b->setFixedWidth(minw);
214// help_b->setFixedWidth(help_b->sizeHint().width()); 214// help_b->setFixedWidth(help_b->sizeHint().width());
215 connect_b->setFixedWidth(minw); 215 connect_b->setFixedWidth(minw);
216 216
217 l2->addWidget(quit_b); 217 l2->addWidget(quit_b);
218 l2->addWidget(setup_b); 218 l2->addWidget(setup_b);
219// l2->addWidget(help_b); 219// l2->addWidget(help_b);
220 l2->addSpacing(20); 220 l2->addSpacing(20);
221 l2->addWidget(connect_b); 221 l2->addWidget(connect_b);
222 222
223 setFixedSize(sizeHint()); 223 setFixedSize(sizeHint());
224 224
225 (void)new Modem(_pppdata); 225 (void)new Modem(_pppdata);
226 226
227 // we also connect cmld_start to the beginConnect so that I can run 227 // we also connect cmld_start to the beginConnect so that I can run
228 // the dialer through a command line argument 228 // the dialer through a command line argument
229 connect(this,SIGNAL(cmdl_start()),this,SLOT(beginConnect())); 229 connect(this,SIGNAL(cmdl_start()),this,SLOT(beginConnect()));
230 230
231// stats = new PPPStats; 231// stats = new PPPStats;
232 232
233 // KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon()); 233 // KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());
234 234
235 // constructor of con_win reads position from config file 235 // constructor of con_win reads position from config file
236 con_win = new ConWindow(_pppdata, 0, "conw", this); 236 con_win = new ConWindow(_pppdata, 0, "conw", this);
237 // KWin::setIcons(con_win->winId(), kapp->icon(), kapp->miniIcon()); 237 // KWin::setIcons(con_win->winId(), kapp->icon(), kapp->miniIcon());
238 238
239// statdlg = new PPPStatsDlg(0, "stats", this, stats); 239// statdlg = new PPPStatsDlg(0, "stats", this, stats);
240// statdlg->hide(); 240// statdlg->hide();
241 241
242 // load up the accounts combo box 242 // load up the accounts combo box
243 243
244// resetaccounts(); 244// resetaccounts();
245 con = new ConnectWidget(_pppdata, 0, "con"); 245 con = new ConnectWidget(_pppdata, 0, "con");
246 //KWin::setIcons(con->winId(), kapp->icon(), kapp->miniIcon() ); 246 //KWin::setIcons(con->winId(), kapp->icon(), kapp->miniIcon() );
247 connect(this, SIGNAL(begin_connect()),con, SLOT(preinit())); 247 connect(this, SIGNAL(begin_connect()),con, SLOT(preinit()));
248 // Is this the best we can do here? it's not right. 248 // Is this the best we can do here? it's not right.
249// QRect desk = QApplication::desktop()->screenGeometry( 249// QRect desk = QApplication::desktop()->screenGeometry(
250// QApplication::desktop()->screenNumber(topLevelWidget())); 250// QApplication::desktop()->screenNumber(topLevelWidget()));
251// con->setGeometry(desk.center().x()-175, desk.center().y()-55, 350,110); 251// con->setGeometry(desk.center().x()-175, desk.center().y()-55, 350,110);
252 252
253 // connect the ConnectWidgets various signals 253 // connect the ConnectWidgets various signals
254 connect(con, SIGNAL(startAccounting()), 254 connect(con, SIGNAL(startAccounting()),
255 this, SLOT(startAccounting())); 255 this, SLOT(startAccounting()));
256 connect(con, SIGNAL(stopAccounting()), 256 connect(con, SIGNAL(stopAccounting()),
257 this, SLOT(stopAccounting())); 257 this, SLOT(stopAccounting()));
258 connect(qApp, SIGNAL(saveYourself()), 258 connect(qApp, SIGNAL(saveYourself()),
259 this, SLOT(saveMyself())); 259 this, SLOT(saveMyself()));
260 connect(qApp, SIGNAL(shutDown()), 260 connect(qApp, SIGNAL(shutDown()),
261 this, SLOT(shutDown())); 261 this, SLOT(shutDown()));
262 262
263 263
264// KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); 264// KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
265 265
266// m_strCmdlAccount = args->getOption("c"); 266// m_strCmdlAccount = args->getOption("c");
267// m_bQuitOnDisconnect = args->isSet("q"); 267// m_bQuitOnDisconnect = args->isSet("q");
268 268
269// if(!m_strCmdlAccount.isEmpty()) { 269// if(!m_strCmdlAccount.isEmpty()) {
270// m_bCmdlAccount = true; 270// m_bCmdlAccount = true;
271// kdDebug(5002) << "cmdl_account: " << m_bCmdlAccount << endl; 271// kdDebug(5002) << "cmdl_account: " << m_bCmdlAccount << endl;
272// } 272// }
273 273
274// if(m_bCmdlAccount){ 274// if(m_bCmdlAccount){
275// bool result = _pppdata->setAccount(m_strCmdlAccount); 275// bool result = _pppdata->setAccount(m_strCmdlAccount);
276// if (!result){ 276// if (!result){
277// QString string; 277// QString string;
278// string = QObject::tr("No such Account:\n%1").arg(m_strCmdlAccount); 278// string = QObject::tr("No such Account:\n%1").arg(m_strCmdlAccount);
279// KMessageBox::error(this, string); 279// KMessageBox::error(this, string);
280// m_bCmdlAccount = false; 280// m_bCmdlAccount = false;
281// this->show(); 281// this->show();
282// } else { 282// } else {
283// beginConnect(); 283// beginConnect();
284// } 284// }
285// } else 285// } else
286// expandbutton(); 286// expandbutton();
287// show(); 287// show();
288 288
289 289
290//#define KPPP_SHOW_NEWS 290//#define KPPP_SHOW_NEWS
291#ifdef KPPP_SHOW_NEWS 291#ifdef KPPP_SHOW_NEWS
292 // keep user informed about recent changes 292 // keep user informed about recent changes
293 if(!m_bCmdlAccount) 293 if(!m_bCmdlAccount)
294 showNews(); 294 showNews();
295#endif 295#endif
296} 296}
297 297
298KPPPWidget::~KPPPWidget() 298KPPPWidget::~KPPPWidget()
299{ 299{
300 p_kppp = 0; 300 p_kppp = 0;
301// delete stats; 301// delete stats;
302} 302}
303 303
304// bool KPPPWidget::eventFilter(QObject *o, QEvent *e) { 304// bool KPPPWidget::eventFilter(QObject *o, QEvent *e) {
305// if(e->type() == QEvent::User) { 305// if(e->type() == QEvent::User) {
306// switch(((SignalEvent*)e)->sigType()) { 306// switch(((SignalEvent*)e)->sigType()) {
307// case SIGINT: 307// case SIGINT:
308// qDebug( "Received a SIGINT" ); 308// odebug << "Received a SIGINT" << oendl;
309// interruptConnection(); 309// interruptConnection();
310// break; 310// break;
311// case SIGCHLD: 311// case SIGCHLD:
312// sigChld(); 312// sigChld();
313// break; 313// break;
314// case SIGUSR1: 314// case SIGUSR1:
315// sigPPPDDied(); 315// sigPPPDDied();
316// break; 316// break;
317// } 317// }
318// return true; 318// return true;
319// } 319// }
320 320
321// if(o == connect_b) { 321// if(o == connect_b) {
322// if(e->type() == QEvent::KeyPress) { 322// if(e->type() == QEvent::KeyPress) {
323// if(connect_b->hasFocus() && ((QKeyEvent *)e)->key() == Qt::Key_Return) { 323// if(connect_b->hasFocus() && ((QKeyEvent *)e)->key() == Qt::Key_Return) {
324// beginConnect(); 324// beginConnect();
325// return true; 325// return true;
326// } 326// }
327// } 327// }
328// } 328// }
329 329
330// return false; 330// return false;
331// } 331// }
332 332
333 333
334 334
335 335
336void KPPPWidget::enterPressedInID() { 336void KPPPWidget::enterPressedInID() {
337 PW_Edit->setFocus(); 337 PW_Edit->setFocus();
338} 338}
339 339
340 340
341void KPPPWidget::enterPressedInPW() { 341void KPPPWidget::enterPressedInPW() {
342 connect_b->setFocus(); 342 connect_b->setFocus();
343} 343}
344 344
345// triggered by the session manager 345// triggered by the session manager
346void KPPPWidget::saveMyself() { 346void KPPPWidget::saveMyself() {
347 _pppdata->save(); 347 _pppdata->save();
348} 348}
349 349
350void KPPPWidget::shutDown() { 350void KPPPWidget::shutDown() {
351 interruptConnection(); 351 interruptConnection();
352 saveMyself(); 352 saveMyself();
353} 353}
354 354
355void KPPPWidget::log_window_toggled(bool on) { 355void KPPPWidget::log_window_toggled(bool on) {
356 _pppdata->set_show_log_window(on); 356 _pppdata->set_show_log_window(on);
357} 357}
358 358
359 359
360 360
361 361
362// void KPPPWidget::resetaccounts() { 362// void KPPPWidget::resetaccounts() {
363// connectto_c->clear(); 363// connectto_c->clear();
364 364
365// int count = _pppdata->count(); 365// int count = _pppdata->count();
366 366
367// // enable/disable controls 367// // enable/disable controls
368// connectto_c->setEnabled(count > 0); 368// connectto_c->setEnabled(count > 0);
369// connect_b->setEnabled(count > 0); 369// connect_b->setEnabled(count > 0);
370// log->setEnabled(count > 0); 370// log->setEnabled(count > 0);
371// ID_Edit->setEnabled(count > 0); 371// ID_Edit->setEnabled(count > 0);
372// PW_Edit->setEnabled(count > 0); 372// PW_Edit->setEnabled(count > 0);
373 373
374// //load the accounts 374// //load the accounts
375// for(int i=0; i < count; i++) { 375// for(int i=0; i < count; i++) {
376// _pppdata->setAccountbyIndex(i); 376// _pppdata->setAccountbyIndex(i);
377// connectto_c->insertItem(_pppdata->accname()); 377// connectto_c->insertItem(_pppdata->accname());
378// } 378// }
379 379
380// //set the default account 380// //set the default account
381// if(!_pppdata->defaultAccount().isEmpty()) { 381// if(!_pppdata->defaultAccount().isEmpty()) {
382// for(int i=0; i < count; i++) 382// for(int i=0; i < count; i++)
383// if(_pppdata->defaultAccount() == connectto_c->text(i)) { 383// if(_pppdata->defaultAccount() == connectto_c->text(i)) {
384 // connectto_c->setCurrentItem(i); 384 // connectto_c->setCurrentItem(i);
385 // _pppdata->setAccountbyIndex(i); 385 // _pppdata->setAccountbyIndex(i);
386 386
387 // ID_Edit->setText(_pppdata->storedUsername()); 387 // ID_Edit->setText(_pppdata->storedUsername());
388 // PW_Edit->setText(_pppdata->storedPassword()); 388 // PW_Edit->setText(_pppdata->storedPassword());
389// } 389// }
390// } 390// }
391// else 391// else
392// if(count > 0) { 392// if(count > 0) {
393// _pppdata->setDefaultAccount(connectto_c->text(0)); 393// _pppdata->setDefaultAccount(connectto_c->text(0));
394// _pppdata->save(); 394// _pppdata->save();
395 // ID_Edit->setText(_pppdata->storedUsername()); 395 // ID_Edit->setText(_pppdata->storedUsername());
396 // PW_Edit->setText(_pppdata->storedPassword()); 396 // PW_Edit->setText(_pppdata->storedPassword());
397// } 397// }
398 398
399// connect(ID_Edit, SIGNAL(textChanged(const QString&)), 399// connect(ID_Edit, SIGNAL(textChanged(const QString&)),
400 // this, SLOT(usernameChanged(const QString&))); 400 // this, SLOT(usernameChanged(const QString&)));
401 401
402// connect(PW_Edit, SIGNAL(textChanged(const QString&)), 402// connect(PW_Edit, SIGNAL(textChanged(const QString&)),
403 // this, SLOT(passwordChanged(const QString&))); 403 // this, SLOT(passwordChanged(const QString&)));
404 404
405// if (ID_Edit->text().isEmpty()) 405// if (ID_Edit->text().isEmpty())
406// ID_Edit->setFocus(); 406// ID_Edit->setFocus();
407// else if (PW_Edit->text().isEmpty()) 407// else if (PW_Edit->text().isEmpty())
408// PW_Edit->setFocus(); 408// PW_Edit->setFocus();
409// } 409// }
410 410
411 411
412void KPPPWidget::interruptConnection() { 412void KPPPWidget::interruptConnection() {
413 // interrupt dial up 413 // interrupt dial up
414// 414//
415 415
416 if (con->isVisible()) 416 if (con->isVisible())
417 emit con->cancelbutton(); 417 emit con->cancelbutton();
418 418
419 // disconnect if online 419 // disconnect if online
420 if (_pppdata->pppdRunning()) 420 if (_pppdata->pppdRunning())
421 emit disconnect(); 421 emit disconnect();
422} 422}
423 423
424 424
425void KPPPWidget::sigPPPDDied() { 425void KPPPWidget::sigPPPDDied() {
426 qDebug( "Received a SIGUSR1" ); 426 odebug << "Received a SIGUSR1" << oendl;
427 427
428 // if we are not connected pppdpid is -1 so have have to check for that 428 // if we are not connected pppdpid is -1 so have have to check for that
429 // in the followin line to make sure that we don't raise a false alarm 429 // in the followin line to make sure that we don't raise a false alarm
430 // such as would be the case when the log file viewer exits. 430 // such as would be the case when the log file viewer exits.
431 if(_pppdata->pppdRunning() || _pppdata->pppdError()) { 431 if(_pppdata->pppdRunning() || _pppdata->pppdError()) {
432 qDebug( "It was pppd that died" ); 432 odebug << "It was pppd that died" << oendl;
433 433
434 // when we killpppd() on Cancel in ConnectWidget 434 // when we killpppd() on Cancel in ConnectWidget
435 // we set pppid to -1 so we won't 435 // we set pppid to -1 so we won't
436 // enter this block 436 // enter this block
437 437
438 // just to be sure 438 // just to be sure
439 439
440 Modem::modem->removeSecret(AUTH_PAP); 440 Modem::modem->removeSecret(AUTH_PAP);
441 Modem::modem->removeSecret(AUTH_CHAP); 441 Modem::modem->removeSecret(AUTH_CHAP);
442 442
443 _pppdata->setpppdRunning(false); 443 _pppdata->setpppdRunning(false);
444 444
445 qDebug( "Executing command on disconnect since pppd has died." ); 445 odebug << "Executing command on disconnect since pppd has died." << oendl;
446 QApplication::flushX(); 446 QApplication::flushX();
447 execute_command(_pppdata->command_on_disconnect()); 447 execute_command(_pppdata->command_on_disconnect());
448 448
449// stopAccounting(); 449// stopAccounting();
450 450
451 con_win->stopClock(); 451 con_win->stopClock();
452// DockWidget::dock_widget->stop_stats(); 452// DockWidget::dock_widget->stop_stats();
453// DockWidget::dock_widget->hide(); 453// DockWidget::dock_widget->hide();
454 454
455 if(!_pppdata->pppdError()) 455 if(!_pppdata->pppdError())
456 _pppdata->setpppdError(E_PPPD_DIED); 456 _pppdata->setpppdError(E_PPPD_DIED);
457 removedns(); 457 removedns();
458 Modem::modem->unlockdevice(); 458 Modem::modem->unlockdevice();
459 // 459 //
460 con->pppdDied(); 460 con->pppdDied();
461 461
462 if(!_pppdata->automatic_redial()) { 462 if(!_pppdata->automatic_redial()) {
463 quit_b->setFocus(); 463 quit_b->setFocus();
464 show(); 464 show();
465 con_win->stopClock(); 465 con_win->stopClock();
466 //stopAccounting(); 466 //stopAccounting();
467 con_win->hide(); 467 con_win->hide();
468 con->hide(); 468 con->hide();
469 469
470 _pppdata->setpppdRunning(false); 470 _pppdata->setpppdRunning(false);
471 // // not in a signal handler !!! KNotifyClient::beep(); 471 // // not in a signal handler !!! KNotifyClient::beep();
472 QString msg; 472 QString msg;
473 if (_pppdata->pppdError() == E_IF_TIMEOUT) 473 if (_pppdata->pppdError() == E_IF_TIMEOUT)
474 msg = QObject::tr("Timeout expired while waiting for the PPP interface " 474 msg = QObject::tr("Timeout expired while waiting for the PPP interface "
475 "to come up!"); 475 "to come up!");
476 else { 476 else {
477 msg = QObject::tr("<p>The pppd daemon died unexpectedly!</p>"); 477 msg = QObject::tr("<p>The pppd daemon died unexpectedly!</p>");
478 Modem::modem->pppdExitStatus(); 478 Modem::modem->pppdExitStatus();
479 if (Modem::modem->lastStatus != 99) {// more recent pppds only 479 if (Modem::modem->lastStatus != 99) {// more recent pppds only
480 msg += QObject::tr("<p>Exit status: %1").arg(Modem::modem->lastStatus); 480 msg += QObject::tr("<p>Exit status: %1").arg(Modem::modem->lastStatus);
481 msg += QObject::tr("</p><p>See 'man pppd' for an explanation of the error " 481 msg += QObject::tr("</p><p>See 'man pppd' for an explanation of the error "
482 "codes or take a look at the kppp FAQ on " 482 "codes or take a look at the kppp FAQ on "
483 " <a href=http://devel-home.kde.org/~kppp/index.html>" 483 " <a href=http://devel-home.kde.org/~kppp/index.html>"
484 "http://devel-home.kde.org/~kppp/index.html</a></p>"); 484 "http://devel-home.kde.org/~kppp/index.html</a></p>");
485 } 485 }
486 } 486 }
487 487
488 // if(QMessageBox::warning(0, msg, QObject::tr("Error"), QObject::tr("&OK"), QObject::tr("&Details...")) == QMessageBox::No) 488 // if(QMessageBox::warning(0, msg, QObject::tr("Error"), QObject::tr("&OK"), QObject::tr("&Details...")) == QMessageBox::No)
489 // // PPPL_ShowLog(); 489 // // PPPL_ShowLog();
490// } else { /* reconnect on disconnect */ 490// } else { /* reconnect on disconnect */
491 if (false){ 491 if (false){
492 qDebug( "Trying to reconnect... " ); 492 odebug << "Trying to reconnect... " << oendl;
493 493
494 if(_pppdata->authMethod() == AUTH_PAP || 494 if(_pppdata->authMethod() == AUTH_PAP ||
495 _pppdata->authMethod() == AUTH_CHAP || 495 _pppdata->authMethod() == AUTH_CHAP ||
496 _pppdata->authMethod() == AUTH_PAPCHAP) 496 _pppdata->authMethod() == AUTH_PAPCHAP)
497 Modem::modem->setSecret(_pppdata->authMethod(), 497 Modem::modem->setSecret(_pppdata->authMethod(),
498 encodeWord(_pppdata->storedUsername()), 498 encodeWord(_pppdata->storedUsername()),
499 encodeWord(_pppdata->password())); 499 encodeWord(_pppdata->password()));
500 500
501 con_win->hide(); 501 con_win->hide();
502 con_win->stopClock(); 502 con_win->stopClock();
503 //stopAccounting(); 503 //stopAccounting();
504 _pppdata->setpppdRunning(false); 504 _pppdata->setpppdRunning(false);
505 // not in a signal handler !!!KNotifyClient::beep(); 505 // not in a signal handler !!!KNotifyClient::beep();
506 emit cmdl_start(); 506 emit cmdl_start();
507 } 507 }
508 } 508 }
509 _pppdata->setpppdError(0); 509 _pppdata->setpppdError(0);
510 } 510 }
511} 511}
512 512
513// void KPPPWidget::sigChld() { 513// void KPPPWidget::sigChld() {
514// qDebug( "sigchld()" ); 514// odebug << "sigchld()" << oendl;
515// // pid_t id = wait(0L); 515// // pid_t id = wait(0L);
516// // if(id == helperPid && helperPid != -1) { 516// // if(id == helperPid && helperPid != -1) {
517// // kdDebug(5002) << "It was the setuid child that died" << endl; 517// // kdDebug(5002) << "It was the setuid child that died" << endl;
518// // helperPid = -1; 518// // helperPid = -1;
519// QString msg = QObject::tr("kppp's helper process just died.\n" 519// QString msg = QObject::tr("kppp's helper process just died.\n"
520// "Since a further execution would be pointless, " 520// "Since a further execution would be pointless, "
521// "kppp will shut down now."); 521// "kppp will shut down now.");
522// QMessageBox::warning(0L,"error", msg); 522// QMessageBox::warning(0L,"error", msg);
523// //remove_pidfile(); 523// //remove_pidfile();
524// exit(1); 524// exit(1);
525// // } 525// // }
526// } 526// }
527 527
528 528
529void KPPPWidget::newdefaultaccount(int i) { 529void KPPPWidget::newdefaultaccount(int i) {
530 _pppdata->setDefaultAccount(connectto_c->text(i)); 530 _pppdata->setDefaultAccount(connectto_c->text(i));
531 _pppdata->save(); 531 _pppdata->save();
532 ID_Edit->setText(_pppdata->storedUsername()); 532 ID_Edit->setText(_pppdata->storedUsername());
533 PW_Edit->setText(_pppdata->storedPassword()); 533 PW_Edit->setText(_pppdata->storedPassword());
534} 534}
535 535
536 536
537 537
538 538
539void KPPPWidget::beginConnect() { 539void KPPPWidget::beginConnect() {
540 // make sure to connect to the account that is selected in the combo box 540 // make sure to connect to the account that is selected in the combo box
541 // (exeption: an account given by a command line argument) 541 // (exeption: an account given by a command line argument)
542 // if(!m_bCmdlAccount) { 542 // if(!m_bCmdlAccount) {
543// _pppdata->setAccount(connectto_c->currentText()); 543// _pppdata->setAccount(connectto_c->currentText());
544// _pppdata->setPassword(PW_Edit->text()); 544// _pppdata->setPassword(PW_Edit->text());
545// } else { 545// } else {
546 _pppdata->setPassword(_pppdata->storedPassword()); 546 _pppdata->setPassword(_pppdata->storedPassword());
547// } 547// }
548 548
549 QFileInfo info(pppdPath()); 549 QFileInfo info(pppdPath());
550 550
551 if(!info.exists()){ 551 if(!info.exists()){
552 QMessageBox::warning(this, "error", QObject::tr("Cannot find the PPP daemon!\n" 552 QMessageBox::warning(this, "error", QObject::tr("Cannot find the PPP daemon!\n"
553 "Make sure that pppd is installed and " 553 "Make sure that pppd is installed and "
554 "that you have entered the correct path.")); 554 "that you have entered the correct path."));
555 return; 555 return;
556 } 556 }
557#if 0 557#if 0
558 if(!info.isExecutable()){ 558 if(!info.isExecutable()){
559 559
560 QString string; 560 QString string;
561 string = QObject::tr("kppp cannot execute:\n %1\n" 561 string = QObject::tr("kppp cannot execute:\n %1\n"
562 "Please make sure that you have given kppp " 562 "Please make sure that you have given kppp "
563 "setuid permission and that " 563 "setuid permission and that "
564 "pppd is executable.").arg(_pppdata->pppdPath()); 564 "pppd is executable.").arg(_pppdata->pppdPath());
565 KMessageBox::error(this, string); 565 KMessageBox::error(this, string);
566 return; 566 return;
567 567
568 } 568 }
569#endif 569#endif
570 570
571 QFileInfo info2(_pppdata->modemDevice()); 571 QFileInfo info2(_pppdata->modemDevice());
572 572
573 if(!info2.exists()){ 573 if(!info2.exists()){
574 QString string; 574 QString string;
575 string = QObject::tr("kppp can not find:\n %1\nPlease make sure you have setup " 575 string = QObject::tr("kppp can not find:\n %1\nPlease make sure you have setup "
576 "your modem device properly " 576 "your modem device properly "
577 "and/or adjust the location of the modem device on " 577 "and/or adjust the location of the modem device on "
578 "the modem tab of " 578 "the modem tab of "
579 "the setup dialog.").arg(_pppdata->modemDevice()); 579 "the setup dialog.").arg(_pppdata->modemDevice());
580 QMessageBox::warning(this, "error", string); 580 QMessageBox::warning(this, "error", string);
581 return; 581 return;
582 } 582 }
583 583
584 // if this is a PAP or CHAP account, ensure that username is 584 // if this is a PAP or CHAP account, ensure that username is
585 // supplied 585 // supplied
586 if(_pppdata->authMethod() == AUTH_PAP || 586 if(_pppdata->authMethod() == AUTH_PAP ||
587 _pppdata->authMethod() == AUTH_CHAP || 587 _pppdata->authMethod() == AUTH_CHAP ||
588 _pppdata->authMethod() == AUTH_PAPCHAP ) { 588 _pppdata->authMethod() == AUTH_PAPCHAP ) {
589 if(ID_Edit->text().isEmpty()) { 589 if(ID_Edit->text().isEmpty()) {
590 QMessageBox::warning(this,"error", 590 QMessageBox::warning(this,"error",
591 QObject::tr("You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!")); 591 QObject::tr("You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!"));
592 return; 592 return;
593 } else { 593 } else {
594 if(!Modem::modem->setSecret(_pppdata->authMethod(), 594 if(!Modem::modem->setSecret(_pppdata->authMethod(),
595 encodeWord(_pppdata->storedUsername()), 595 encodeWord(_pppdata->storedUsername()),
596 encodeWord(_pppdata->password()))) { 596 encodeWord(_pppdata->password()))) {
597 QString s; 597 QString s;
598 s = QObject::tr("Cannot create PAP/CHAP authentication\n" 598 s = QObject::tr("Cannot create PAP/CHAP authentication\n"
599 "file \"%1\"").arg(PAP_AUTH_FILE); 599 "file \"%1\"").arg(PAP_AUTH_FILE);
600 QMessageBox::warning(this, "error", s); 600 QMessageBox::warning(this, "error", s);
601 return; 601 return;
602 } 602 }
603 } 603 }
604 } 604 }
605 605
606 if (_pppdata->phonenumber().isEmpty()) { 606 if (_pppdata->phonenumber().isEmpty()) {
607 QString s = QObject::tr("You must specify a telephone number!"); 607 QString s = QObject::tr("You must specify a telephone number!");
608 QMessageBox::warning(this, "error", s); 608 QMessageBox::warning(this, "error", s);
609 return; 609 return;
610 } 610 }
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 @@
1/* 1/*
2 * kPPP: A pppd Front End for the KDE project 2 * kPPP: A pppd Front End for the KDE project
3 * 3 *
4 * $Id$ 4 * $Id$
5 * 5 *
6 * Copyright (C) 1997 Bernd Johannes Wuebben 6 * Copyright (C) 1997 Bernd Johannes Wuebben
7 * wuebben@math.cornell.edu 7 * wuebben@math.cornell.edu
8 * 8 *
9 * This file was added by Harri Porten <porten@tu-harburg.de> 9 * This file was added by Harri Porten <porten@tu-harburg.de>
10 * 10 *
11 * 11 *
12 * This program is free software; you can redistribute it and/or 12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public 13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either 14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version. 15 * version 2 of the License, or (at your option) any later version.
16 * 16 *
17 * This program is distributed in the hope that it will be useful, 17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details. 20 * Library General Public License for more details.
21 * 21 *
22 * You should have received a copy of the GNU Library General Public 22 * You should have received a copy of the GNU Library General Public
23 * License along with this program; if not, write to the Free 23 * License along with this program; if not, write to the Free
24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 */ 25 */
26 26
27#include <errno.h> 27#include <errno.h>
28#include <stdlib.h> 28#include <stdlib.h>
29#include <unistd.h> 29#include <unistd.h>
30#include <fcntl.h> 30#include <fcntl.h>
31#include <signal.h> 31#include <signal.h>
32#include <sys/ioctl.h> 32#include <sys/ioctl.h>
33#include <sys/types.h> 33#include <sys/types.h>
34#include <sys/stat.h> 34#include <sys/stat.h>
35#include <setjmp.h> 35#include <setjmp.h>
36#include <regex.h> 36#include <regex.h>
37#include <qregexp.h> 37#include <qregexp.h>
38#include <assert.h> 38#include <assert.h>
39#include <string.h> 39#include <string.h>
40 40
41#ifdef HAVE_RESOLV_H 41#ifdef HAVE_RESOLV_H
42# include <arpa/nameser.h> 42# include <arpa/nameser.h>
43# include <resolv.h> 43# include <resolv.h>
44#endif 44#endif
45 45
46#ifndef _PATH_RESCONF 46#ifndef _PATH_RESCONF
47#define _PATH_RESCONF "/etc/resolv.conf" 47#define _PATH_RESCONF "/etc/resolv.conf"
48#endif 48#endif
49 49
50#define strlcpy strcpy 50#define strlcpy strcpy
51#include "auth.h" 51#include "auth.h"
52#include "modem.h" 52#include "modem.h"
53#include "pppdata.h" 53#include "pppdata.h"
54#define qError qDebug 54#define qError qDebug
55 55
56 56
57#define MY_ASSERT(x) if (!(x)) { \ 57#define MY_ASSERT(x) if (!(x)) { \
58 qFatal( "ASSERT: \"%s\" in %s (%d)\n",#x,__FILE__,__LINE__); \ 58 ofatal << "ASSERT: \"" << #x << "\" in " << __FILE__ << " (" << __LINE__ << ")\n" << oendl; \
59 exit(1); } 59 exit(1); }
60 60
61 61
62static sigjmp_buf jmp_buffer; 62static sigjmp_buf jmp_buffer;
63 63
64//Modem *Modem::modem = 0; 64//Modem *Modem::modem = 0;
65 65
66 66
67const char* pppdPath() { 67const char* pppdPath() {
68 // wasting a few bytes 68 // wasting a few bytes
69 static char buffer[sizeof(PPPDSEARCHPATH)+sizeof(PPPDNAME)]; 69 static char buffer[sizeof(PPPDSEARCHPATH)+sizeof(PPPDNAME)];
70 static char *pppdPath = 0L; 70 static char *pppdPath = 0L;
71 char *p; 71 char *p;
72 72
73 if(pppdPath == 0L) { 73 if(pppdPath == 0L) {
74 const char *c = PPPDSEARCHPATH; 74 const char *c = PPPDSEARCHPATH;
75 while(*c != '\0') { 75 while(*c != '\0') {
76 while(*c == ':') 76 while(*c == ':')
77 c++; 77 c++;
78 p = buffer; 78 p = buffer;
79 while(*c != '\0' && *c != ':') 79 while(*c != '\0' && *c != ':')
80 *p++ = *c++; 80 *p++ = *c++;
81 *p = '\0'; 81 *p = '\0';
82 strcat(p, "/"); 82 strcat(p, "/");
83 strcat(p, PPPDNAME); 83 strcat(p, PPPDNAME);
84 if(access(buffer, F_OK) == 0) 84 if(access(buffer, F_OK) == 0)
85 return (pppdPath = buffer); 85 return (pppdPath = buffer);
86 } 86 }
87 } 87 }
88 88
89 return pppdPath; 89 return pppdPath;
90} 90}
91 91
92 92
93Modem::Modem( PPPData* pd ) 93Modem::Modem( PPPData* pd )
94{ 94{
95 _pppdata = pd; 95 _pppdata = pd;
96 modemfd = -1; 96 modemfd = -1;
97 _pppdExitStatus = -1; 97 _pppdExitStatus = -1;
98 pppdPid = -1; 98 pppdPid = -1;
99 sn = m_modemDebug = 0L; 99 sn = m_modemDebug = 0L;
100 data_mode = false; 100 data_mode = false;
101 modem_is_locked = false; 101 modem_is_locked = false;
102 lockfile[0] = '\0'; 102 lockfile[0] = '\0';
103 device = "/dev/modem"; 103 device = "/dev/modem";
104} 104}
105 105
106 106
107Modem::~Modem() 107Modem::~Modem()
108{ 108{
109} 109}
110 110
111 111
112speed_t Modem::modemspeed() { 112speed_t Modem::modemspeed() {
113 // convert the string modem speed int the gpppdata object to a t_speed type 113 // convert the string modem speed int the gpppdata object to a t_speed type
114 // to set the modem. The constants here should all be ifdef'd because 114 // to set the modem. The constants here should all be ifdef'd because
115 // other systems may not have them 115 // other systems may not have them
116 int i = _pppdata->speed().toInt()/100; 116 int i = _pppdata->speed().toInt()/100;
117 117
118 switch(i) { 118 switch(i) {
119 case 24: 119 case 24:
120 return B2400; 120 return B2400;
121 break; 121 break;
122 case 96: 122 case 96:
123 return B9600; 123 return B9600;
124 break; 124 break;
125 case 192: 125 case 192:
126 return B19200; 126 return B19200;
127 break; 127 break;
128 case 384: 128 case 384:
129 return B38400; 129 return B38400;
130 break; 130 break;
131#ifdef B57600 131#ifdef B57600
132 case 576: 132 case 576:
133 return B57600; 133 return B57600;
134 break; 134 break;
135#endif 135#endif
136 136
137#ifdef B115200 137#ifdef B115200
138 case 1152: 138 case 1152:
139 return B115200; 139 return B115200;
140 break; 140 break;
141#endif 141#endif
142 142
143#ifdef B230400 143#ifdef B230400
144 case 2304: 144 case 2304:
145 return B230400; 145 return B230400;
146 break; 146 break;
147#endif 147#endif
148 148
149#ifdef B460800 149#ifdef B460800
150 case 4608: 150 case 4608:
151 return B460800; 151 return B460800;
152 break; 152 break;
153#endif 153#endif
154 154
155 default: 155 default:
156 return B38400; 156 return B38400;
157 break; 157 break;
158 } 158 }
159} 159}
160 160
161bool Modem::opentty() { 161bool Modem::opentty() {
162 // int flags; 162 // int flags;
163 163
164//begin if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) { 164//begin if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) {
165 close(modemfd); 165 close(modemfd);
166 device = _pppdata->modemDevice(); 166 device = _pppdata->modemDevice();
167 if ((modemfd = open(device, O_RDWR|O_NDELAY|O_NOCTTY)) == -1) { 167 if ((modemfd = open(device, O_RDWR|O_NDELAY|O_NOCTTY)) == -1) {
168 qDebug("error opening modem device !"); 168 odebug << "error opening modem device !" << oendl;
169 errmsg = QObject::tr("Unable to open modem."); 169 errmsg = QObject::tr("Unable to open modem.");
170 return false; 170 return false;
171 } 171 }
172//bend if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) { 172//bend if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) {
173//} 173//}
174 174
175#if 0 175#if 0
176 if(_pppdata->UseCDLine()) { 176 if(_pppdata->UseCDLine()) {
177 if(ioctl(modemfd, TIOCMGET, &flags) == -1) { 177 if(ioctl(modemfd, TIOCMGET, &flags) == -1) {
178 errmsg = QObject::tr("Unable to detect state of CD line."); 178 errmsg = QObject::tr("Unable to detect state of CD line.");
179 ::close(modemfd); 179 ::close(modemfd);
180 modemfd = -1; 180 modemfd = -1;
181 return false; 181 return false;
182 } 182 }
183 if ((flags&TIOCM_CD) == 0) { 183 if ((flags&TIOCM_CD) == 0) {
184 errmsg = QObject::tr("The modem is not ready."); 184 errmsg = QObject::tr("The modem is not ready.");
185 ::close(modemfd); 185 ::close(modemfd);
186 modemfd = -1; 186 modemfd = -1;
187 return false; 187 return false;
188 } 188 }
189 } 189 }
190#endif 190#endif
191 191
192 tcdrain (modemfd); 192 tcdrain (modemfd);
193 tcflush (modemfd, TCIOFLUSH); 193 tcflush (modemfd, TCIOFLUSH);
194 194
195 if(tcgetattr(modemfd, &tty) < 0){ 195 if(tcgetattr(modemfd, &tty) < 0){
196 // this helps in some cases 196 // this helps in some cases
197 tcsendbreak(modemfd, 0); 197 tcsendbreak(modemfd, 0);
198 sleep(1); 198 sleep(1);
199 if(tcgetattr(modemfd, &tty) < 0){ 199 if(tcgetattr(modemfd, &tty) < 0){
200 errmsg = QObject::tr("The modem is busy."); 200 errmsg = QObject::tr("The modem is busy.");
201 ::close(modemfd); 201 ::close(modemfd);
202 modemfd = -1; 202 modemfd = -1;
203 return false; 203 return false;
204 } 204 }
205 } 205 }
206 206
207 memset(&initial_tty,'\0',sizeof(initial_tty)); 207 memset(&initial_tty,'\0',sizeof(initial_tty));
208 208
209 initial_tty = tty; 209 initial_tty = tty;
210 210
211 tty.c_cc[VMIN] = 0; // nonblocking 211 tty.c_cc[VMIN] = 0; // nonblocking
212 tty.c_cc[VTIME] = 0; 212 tty.c_cc[VTIME] = 0;
213 tty.c_oflag = 0; 213 tty.c_oflag = 0;
214 tty.c_lflag = 0; 214 tty.c_lflag = 0;
215 215
216 tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB); 216 tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB);
217 tty.c_cflag |= CS8 | CREAD; 217 tty.c_cflag |= CS8 | CREAD;
218 tty.c_cflag |= CLOCAL; // ignore modem status lines 218 tty.c_cflag |= CLOCAL; // ignore modem status lines
219 tty.c_iflag = IGNBRK | IGNPAR /* | ISTRIP */ ; 219 tty.c_iflag = IGNBRK | IGNPAR /* | ISTRIP */ ;
220 tty.c_lflag &= ~ICANON; // non-canonical mode 220 tty.c_lflag &= ~ICANON; // non-canonical mode
221 tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE); 221 tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE);
222 222
223 223
224 if(_pppdata->flowcontrol() != "None") { 224 if(_pppdata->flowcontrol() != "None") {
225 if(_pppdata->flowcontrol() == "CRTSCTS") { 225 if(_pppdata->flowcontrol() == "CRTSCTS") {
226 tty.c_cflag |= CRTSCTS; 226 tty.c_cflag |= CRTSCTS;
227 } 227 }
228 else { 228 else {
229 tty.c_iflag |= IXON | IXOFF; 229 tty.c_iflag |= IXON | IXOFF;
230 tty.c_cc[VSTOP] = 0x13; /* DC3 = XOFF = ^S */ 230 tty.c_cc[VSTOP] = 0x13; /* DC3 = XOFF = ^S */
231 tty.c_cc[VSTART] = 0x11; /* DC1 = XON = ^Q */ 231 tty.c_cc[VSTART] = 0x11; /* DC1 = XON = ^Q */
232 } 232 }
233 } 233 }
234 else { 234 else {
235 tty.c_cflag &= ~CRTSCTS; 235 tty.c_cflag &= ~CRTSCTS;
236 tty.c_iflag &= ~(IXON | IXOFF); 236 tty.c_iflag &= ~(IXON | IXOFF);
237 } 237 }
238 238
239 cfsetospeed(&tty, modemspeed()); 239 cfsetospeed(&tty, modemspeed());
240 cfsetispeed(&tty, modemspeed()); 240 cfsetispeed(&tty, modemspeed());
241 241
242 tcdrain(modemfd); 242 tcdrain(modemfd);
243 243
244 if(tcsetattr(modemfd, TCSANOW, &tty) < 0){ 244 if(tcsetattr(modemfd, TCSANOW, &tty) < 0){
245 errmsg = QObject::tr("The modem is busy."); 245 errmsg = QObject::tr("The modem is busy.");
246 ::close(modemfd); 246 ::close(modemfd);
247 modemfd=-1; 247 modemfd=-1;
248 return false; 248 return false;
249 } 249 }
250 250
251 errmsg = QObject::tr("Modem Ready."); 251 errmsg = QObject::tr("Modem Ready.");
252 return true; 252 return true;
253} 253}
254 254
255 255
256bool Modem::closetty() { 256bool Modem::closetty() {
257 if(modemfd >=0 ) { 257 if(modemfd >=0 ) {
258 stop(); 258 stop();
259 /* discard data not read or transmitted */ 259 /* discard data not read or transmitted */
260 tcflush(modemfd, TCIOFLUSH); 260 tcflush(modemfd, TCIOFLUSH);
261 261
262 if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){ 262 if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){
263 errmsg = QObject::tr("Can't restore tty settings: tcsetattr()\n"); 263 errmsg = QObject::tr("Can't restore tty settings: tcsetattr()\n");
264 ::close(modemfd); 264 ::close(modemfd);
265 modemfd = -1; 265 modemfd = -1;
266 return false; 266 return false;
267 } 267 }
268 ::close(modemfd); 268 ::close(modemfd);
269 modemfd = -1; 269 modemfd = -1;
270 } 270 }
271 271
272 return true; 272 return true;
273} 273}
274 274
275 275
276void Modem::readtty(int) { 276void Modem::readtty(int) {
277 char buffer[200]; 277 char buffer[200];
278 unsigned char c; 278 unsigned char c;
279 int len; 279 int len;
280 280
281 // read data in chunks of up to 200 bytes 281 // read data in chunks of up to 200 bytes
282 if((len = ::read(modemfd, buffer, 200)) > 0) { 282 if((len = ::read(modemfd, buffer, 200)) > 0) {
283 // split buffer into single characters for further processing 283 // split buffer into single characters for further processing
284 for(int i = 0; i < len; i++) { 284 for(int i = 0; i < len; i++) {
285 c = buffer[i] & 0x7F; 285 c = buffer[i] & 0x7F;
286 emit charWaiting(c); 286 emit charWaiting(c);
287 } 287 }
288 } 288 }
289} 289}
290 290
291 291
292void Modem::notify(const QObject *receiver, const char *member) { 292void Modem::notify(const QObject *receiver, const char *member) {
293 connect(this, SIGNAL(charWaiting(unsigned char)), receiver, member); 293 connect(this, SIGNAL(charWaiting(unsigned char)), receiver, member);
294 startNotifier(); 294 startNotifier();
295} 295}
296 296
297 297
298void Modem::stop() { 298void Modem::stop() {
299 disconnect(SIGNAL(charWaiting(unsigned char))); 299 disconnect(SIGNAL(charWaiting(unsigned char)));
300 stopNotifier(); 300 stopNotifier();
301} 301}
302 302
303 303
304void Modem::startNotifier() { 304void Modem::startNotifier() {
305 if(modemfd >= 0) { 305 if(modemfd >= 0) {
306 if(sn == 0) { 306 if(sn == 0) {
307 sn = new QSocketNotifier(modemfd, QSocketNotifier::Read, this); 307 sn = new QSocketNotifier(modemfd, QSocketNotifier::Read, this);
308 connect(sn, SIGNAL(activated(int)), SLOT(readtty(int))); 308 connect(sn, SIGNAL(activated(int)), SLOT(readtty(int)));
309 qDebug("QSocketNotifier started!"); 309 odebug << "QSocketNotifier started!" << oendl;
310 } else { 310 } else {
311 qDebug("QSocketNotifier re-enabled!"); 311 odebug << "QSocketNotifier re-enabled!" << oendl;
312 sn->setEnabled(true); 312 sn->setEnabled(true);
313 } 313 }
314 } 314 }
315} 315}
316 316
317 317
318void Modem::stopNotifier() { 318void Modem::stopNotifier() {
319 if(sn != 0) { 319 if(sn != 0) {
320 sn->setEnabled(false); 320 sn->setEnabled(false);
321 disconnect(sn); 321 disconnect(sn);
322 delete sn; 322 delete sn;
323 sn = 0; 323 sn = 0;
324 qDebug( "QSocketNotifier stopped!" ); 324 odebug << "QSocketNotifier stopped!" << oendl;
325 } 325 }
326} 326}
327 327
328 328
329void Modem::flush() { 329void Modem::flush() {
330 char c; 330 char c;
331 while(read(modemfd, &c, 1) == 1); 331 while(read(modemfd, &c, 1) == 1);
332} 332}
333 333
334 334
335bool Modem::writeChar(unsigned char c) { 335bool Modem::writeChar(unsigned char c) {
336 int s; 336 int s;
337 do { 337 do {
338 s = write(modemfd, &c, 1); 338 s = write(modemfd, &c, 1);
339 if (s < 0) { 339 if (s < 0) {
340 qError( "write() in Modem::writeChar failed" ); 340 oerr << "write() in Modem::writeChar failed" << oendl;
341 return false; 341 return false;
342 } 342 }
343 } while(s == 0); 343 } while(s == 0);
344 344
345 return true; 345 return true;
346} 346}
347 347
348 348
349bool Modem::writeLine(const char *buf) { 349bool Modem::writeLine(const char *buf) {
350 int len = strlen(buf); 350 int len = strlen(buf);
351 char *b = new char[len+2]; 351 char *b = new char[len+2];
352 memcpy(b, buf, len); 352 memcpy(b, buf, len);
353 // different modems seem to need different line terminations 353 // different modems seem to need different line terminations
354 QString term = _pppdata->enter(); 354 QString term = _pppdata->enter();
355 if(term == "LF") 355 if(term == "LF")
356 b[len++]='\n'; 356 b[len++]='\n';
357 else if(term == "CR") 357 else if(term == "CR")
358 b[len++]='\r'; 358 b[len++]='\r';
359 else if(term == "CR/LF") { 359 else if(term == "CR/LF") {
360 b[len++]='\r'; 360 b[len++]='\r';
361 b[len++]='\n'; 361 b[len++]='\n';
362 } 362 }
363 int l = len; 363 int l = len;
364 while(l) { 364 while(l) {
365 int wr = write(modemfd, &b[len-l], l); 365 int wr = write(modemfd, &b[len-l], l);
366 if(wr < 0) { 366 if(wr < 0) {
367 // TODO do something meaningful with the error code (or ignore it 367 // TODO do something meaningful with the error code (or ignore it
368 qError( "write() in Modem::writeLine failed" ); 368 oerr << "write() in Modem::writeLine failed" << oendl;
369 delete[] b; 369 delete[] b;
370 return false; 370 return false;
371 } 371 }
372 l -= wr; 372 l -= wr;
373 } 373 }
374 delete[] b; 374 delete[] b;
375 return true; 375 return true;
376} 376}
377 377
378 378
379bool Modem::hangup() { 379bool Modem::hangup() {
380 // this should really get the modem to hang up and go into command mode 380 // this should really get the modem to hang up and go into command mode
381 // If anyone sees a fault in the following please let me know, since 381 // If anyone sees a fault in the following please let me know, since
382 // this is probably the most imporant snippet of code in the whole of 382 // this is probably the most imporant snippet of code in the whole of
383 // kppp. If people complain about kppp being stuck, this piece of code 383 // kppp. If people complain about kppp being stuck, this piece of code
384 // is most likely the reason. 384 // is most likely the reason.
385 struct termios temptty; 385 struct termios temptty;
386 386
387 if(modemfd >= 0) { 387 if(modemfd >= 0) {
388 388
389 // is this Escape & HangupStr stuff really necessary ? (Harri) 389 // is this Escape & HangupStr stuff really necessary ? (Harri)
390 390
391 if (data_mode) escape_to_command_mode(); 391 if (data_mode) escape_to_command_mode();
392 392
393 // Then hangup command 393 // Then hangup command
394 writeLine(_pppdata->modemHangupStr().local8Bit()); 394 writeLine(_pppdata->modemHangupStr().local8Bit());
395 395
396 usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 sec 396 usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 sec
397 397
398#ifndef DEBUG_WO_DIALING 398#ifndef DEBUG_WO_DIALING
399 if (sigsetjmp(jmp_buffer, 1) == 0) { 399 if (sigsetjmp(jmp_buffer, 1) == 0) {
400 // set alarm in case tcsendbreak() hangs 400 // set alarm in case tcsendbreak() hangs
401 signal(SIGALRM, alarm_handler); 401 signal(SIGALRM, alarm_handler);
402 alarm(2); 402 alarm(2);
403 403
404 tcsendbreak(modemfd, 0); 404 tcsendbreak(modemfd, 0);
405 405
406 alarm(0); 406 alarm(0);
407 signal(SIGALRM, SIG_IGN); 407 signal(SIGALRM, SIG_IGN);
408 } else { 408 } else {
409 // we reach this point if the alarm handler got called 409 // we reach this point if the alarm handler got called
410 closetty(); 410 closetty();
411 close(modemfd); 411 close(modemfd);
412 modemfd = -1; 412 modemfd = -1;
413 errmsg = QObject::tr("The modem does not respond."); 413 errmsg = QObject::tr("The modem does not respond.");
414 return false; 414 return false;
415 } 415 }
416 416
417#ifndef __svr4__ // drops DTR but doesn't set it afterwards again. not good for init. 417#ifndef __svr4__ // drops DTR but doesn't set it afterwards again. not good for init.
418 tcgetattr(modemfd, &temptty); 418 tcgetattr(modemfd, &temptty);
419 cfsetospeed(&temptty, B0); 419 cfsetospeed(&temptty, B0);
420 cfsetispeed(&temptty, B0); 420 cfsetispeed(&temptty, B0);
421 tcsetattr(modemfd, TCSAFLUSH, &temptty); 421 tcsetattr(modemfd, TCSAFLUSH, &temptty);
422#else 422#else
423 int modemstat; 423 int modemstat;
424 ioctl(modemfd, TIOCMGET, &modemstat); 424 ioctl(modemfd, TIOCMGET, &modemstat);
425 modemstat &= ~TIOCM_DTR; 425 modemstat &= ~TIOCM_DTR;
426 ioctl(modemfd, TIOCMSET, &modemstat); 426 ioctl(modemfd, TIOCMSET, &modemstat);
427 ioctl(modemfd, TIOCMGET, &modemstat); 427 ioctl(modemfd, TIOCMGET, &modemstat);
428 modemstat |= TIOCM_DTR; 428 modemstat |= TIOCM_DTR;
429 ioctl(modemfd, TIOCMSET, &modemstat); 429 ioctl(modemfd, TIOCMSET, &modemstat);
430#endif 430#endif
431 431
432 usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 secs 432 usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 secs
433 433
434 cfsetospeed(&temptty, modemspeed()); 434 cfsetospeed(&temptty, modemspeed());
435 cfsetispeed(&temptty, modemspeed()); 435 cfsetispeed(&temptty, modemspeed());
436 tcsetattr(modemfd, TCSAFLUSH, &temptty); 436 tcsetattr(modemfd, TCSAFLUSH, &temptty);
437#endif 437#endif
438 return true; 438 return true;
439 } else 439 } else
440 return false; 440 return false;
441} 441}
442 442
443 443
444void Modem::escape_to_command_mode() { 444void Modem::escape_to_command_mode() {
445 // Send Properly bracketed escape code to put the modem back into command state. 445 // Send Properly bracketed escape code to put the modem back into command state.
446 // A modem will accept AT commands only when it is in command state. 446 // A modem will accept AT commands only when it is in command state.
447 // When a modem sends the host the CONNECT string, that signals 447 // When a modem sends the host the CONNECT string, that signals
448 // that the modem is now in the connect state (no long accepts AT commands.) 448 // that the modem is now in the connect state (no long accepts AT commands.)
449 // Need to send properly timed escape sequence to put modem in command state. 449 // Need to send properly timed escape sequence to put modem in command state.
450 // Escape codes and guard times are controlled by S2 and S12 values. 450 // Escape codes and guard times are controlled by S2 and S12 values.
451 // 451 //
452 tcflush(modemfd, TCIOFLUSH); 452 tcflush(modemfd, TCIOFLUSH);
453 453
454 // +3 because quiet time must be greater than guard time. 454 // +3 because quiet time must be greater than guard time.
455 usleep((_pppdata->modemEscapeGuardTime()+3)*20000); 455 usleep((_pppdata->modemEscapeGuardTime()+3)*20000);
456 QCString tmp = _pppdata->modemEscapeStr().local8Bit(); 456 QCString tmp = _pppdata->modemEscapeStr().local8Bit();
457 write(modemfd, tmp.data(), tmp.length()); 457 write(modemfd, tmp.data(), tmp.length());
458 tcflush(modemfd, TCIOFLUSH); 458 tcflush(modemfd, TCIOFLUSH);
459 usleep((_pppdata->modemEscapeGuardTime()+3)*20000); 459 usleep((_pppdata->modemEscapeGuardTime()+3)*20000);
460 460
461 data_mode = false; 461 data_mode = false;
462} 462}
463 463
464 464
465const QString Modem::modemMessage() { 465const QString Modem::modemMessage() {
466 return errmsg; 466 return errmsg;
467} 467}
468 468
469 469
470QString Modem::parseModemSpeed(const QString &s) { 470QString Modem::parseModemSpeed(const QString &s) {
471 // this is a small (and bad) parser for modem speeds 471 // this is a small (and bad) parser for modem speeds
472 int rx = -1; 472 int rx = -1;
473 int tx = -1; 473 int tx = -1;
474 int i; 474 int i;
475 QString result; 475 QString result;
476 476
477 qDebug( "Modem reported result string: %s", s.latin1()); 477 odebug << "Modem reported result string: " << s.latin1() << "" << oendl;
478 478
479 const int RXMAX = 7; 479 const int RXMAX = 7;
480 const int TXMAX = 2; 480 const int TXMAX = 2;
481 QRegExp rrx[RXMAX] = { 481 QRegExp rrx[RXMAX] = {
482 QRegExp("[0-9]+[:/ ]RX", false), 482 QRegExp("[0-9]+[:/ ]RX", false),
483 QRegExp("[0-9]+RX", false), 483 QRegExp("[0-9]+RX", false),
484 QRegExp("[/: -][0-9]+[/: ]", false), 484 QRegExp("[/: -][0-9]+[/: ]", false),
485 QRegExp("[/: -][0-9]+$", false), 485 QRegExp("[/: -][0-9]+$", false),
486 QRegExp("CARRIER [^0-9]*[0-9]+", false), 486 QRegExp("CARRIER [^0-9]*[0-9]+", false),
487 QRegExp("CONNECT [^0-9]*[0-9]+", false), 487 QRegExp("CONNECT [^0-9]*[0-9]+", false),
488 QRegExp("[0-9]+") // panic mode 488 QRegExp("[0-9]+") // panic mode
489 }; 489 };
490 490
491 QRegExp trx[TXMAX] = { 491 QRegExp trx[TXMAX] = {
492 QRegExp("[0-9]+[:/ ]TX", false), 492 QRegExp("[0-9]+[:/ ]TX", false),
493 QRegExp("[0-9]+TX", false) 493 QRegExp("[0-9]+TX", false)
494 }; 494 };
495 495
496 for(i = 0; i < RXMAX; i++) { 496 for(i = 0; i < RXMAX; i++) {
497 int len, idx, result; 497 int len, idx, result;
498 if((idx = rrx[i].match(s,0,&len)) > -1) { 498 if((idx = rrx[i].match(s,0,&len)) > -1) {
499// if((idx = rrx[i].search(s)) > -1) { 499// if((idx = rrx[i].search(s)) > -1) {
500 // len = rrx[i].matchedLength(); 500 // len = rrx[i].matchedLength();
501 501
502 // 502 //
503 // rrx[i] has been matched, idx contains the start of the match 503 // rrx[i] has been matched, idx contains the start of the match
504 // and len contains how long the match is. Extract the match. 504 // and len contains how long the match is. Extract the match.
505 // 505 //
506 QString sub = s.mid(idx, len); 506 QString sub = s.mid(idx, len);
507 507
508 // 508 //
509 // Now extract the digits only from the match, which will 509 // Now extract the digits only from the match, which will
510 // then be converted to an int. 510 // then be converted to an int.
511 // 511 //
512 if ((idx = rrx[RXMAX-1].match( sub,0,&len )) > -1) { 512 if ((idx = rrx[RXMAX-1].match( sub,0,&len )) > -1) {
513// if ((idx = rrx[RXMAX-1].search( sub )) > -1) { 513// if ((idx = rrx[RXMAX-1].search( sub )) > -1) {
514// len = rrx[RXMAX-1].matchedLength(); 514// len = rrx[RXMAX-1].matchedLength();
515 sub = sub.mid(idx, len); 515 sub = sub.mid(idx, len);
516 result = sub.toInt(); 516 result = sub.toInt();
517 if(result > 0) { 517 if(result > 0) {
518 rx = result; 518 rx = result;
519 break; 519 break;
520 } 520 }
521 } 521 }
522 } 522 }
523 } 523 }
524 524
525 for(i = 0; i < TXMAX; i++) { 525 for(i = 0; i < TXMAX; i++) {
526 int len, idx, result; 526 int len, idx, result;
527 if((idx = trx[i].match(s,0,&len)) > -1) { 527 if((idx = trx[i].match(s,0,&len)) > -1) {
528// if((idx = trx[i].search(s)) > -1) { 528// if((idx = trx[i].search(s)) > -1) {
529// len = trx[i].matchedLength(); 529// len = trx[i].matchedLength();
530 530
531 // 531 //
532 // trx[i] has been matched, idx contains the start of the match 532 // trx[i] has been matched, idx contains the start of the match
533 // and len contains how long the match is. Extract the match. 533 // and len contains how long the match is. Extract the match.
534 // 534 //
535 QString sub = s.mid(idx, len); 535 QString sub = s.mid(idx, len);
536 536
537 // 537 //
538 // Now extract the digits only from the match, which will then 538 // Now extract the digits only from the match, which will then
539 // be converted to an int. 539 // be converted to an int.
540 // 540 //
541 if((idx = rrx[RXMAX-1].match(sub,0,&len)) > -1) { 541 if((idx = rrx[RXMAX-1].match(sub,0,&len)) > -1) {
542// if((idx = rrx[RXMAX-1].search(sub)) > -1) { 542// if((idx = rrx[RXMAX-1].search(sub)) > -1) {
543// len = rrx[RXMAX-1].matchedLength(); 543// len = rrx[RXMAX-1].matchedLength();
544 sub = sub.mid(idx, len); 544 sub = sub.mid(idx, len);
545 result = sub.toInt(); 545 result = sub.toInt();
546 if(result > 0) { 546 if(result > 0) {
547 tx = result; 547 tx = result;
548 break; 548 break;
549 } 549 }
550 } 550 }
551 } 551 }
552 } 552 }
553 553
554 if(rx == -1 && tx == -1) 554 if(rx == -1 && tx == -1)
555 result = QObject::tr("Unknown speed"); 555 result = QObject::tr("Unknown speed");
556 else if(tx == -1) 556 else if(tx == -1)
557 result.setNum(rx); 557 result.setNum(rx);
558 else if(rx == -1) // should not happen 558 else if(rx == -1) // should not happen
559 result.setNum(tx); 559 result.setNum(tx);
560 else 560 else
561 result.sprintf("%d/%d", rx, tx); 561 result.sprintf("%d/%d", rx, tx);
562 562
563 qDebug( "The parsed result is: %s", result.latin1()); 563 odebug << "The parsed result is: " << result.latin1() << "" << oendl;
564 564
565 return result; 565 return result;
566} 566}
567 567
568 568
569// Lock modem device. Returns 0 on success 1 if the modem is locked and -1 if 569// Lock modem device. Returns 0 on success 1 if the modem is locked and -1 if
570// a lock file can't be created ( permission problem ) 570// a lock file can't be created ( permission problem )
571int Modem::lockdevice() { 571int Modem::lockdevice() {
572 int fd; 572 int fd;
573 char newlock[80]=""; // safe 573 char newlock[80]=""; // safe
574 574
575 if(!_pppdata->modemLockFile()) { 575 if(!_pppdata->modemLockFile()) {
576 qDebug("The user doesn't want a lockfile."); 576 odebug << "The user doesn't want a lockfile." << oendl;
577 return 0; 577 return 0;
578 } 578 }
579 579
580 if (modem_is_locked) 580 if (modem_is_locked)
581 return 1; 581 return 1;
582 582
583 QString lockfile = LOCK_DIR"/LCK.."; 583 QString lockfile = LOCK_DIR"/LCK..";
584 lockfile += _pppdata->modemDevice().mid(5); // append everything after /dev/ 584 lockfile += _pppdata->modemDevice().mid(5); // append everything after /dev/
585 585
586 if(access(QFile::encodeName(lockfile), F_OK) == 0) { 586 if(access(QFile::encodeName(lockfile), F_OK) == 0) {
587// if ((fd = Requester::rq-> 587// if ((fd = Requester::rq->
588if ((fd = openLockfile(QFile::encodeName(lockfile), O_RDONLY)) >= 0) { 588if ((fd = openLockfile(QFile::encodeName(lockfile), O_RDONLY)) >= 0) {
589 // Mario: it's not necessary to read more than lets say 32 bytes. If 589 // Mario: it's not necessary to read more than lets say 32 bytes. If
590 // file has more than 32 bytes, skip the rest 590 // file has more than 32 bytes, skip the rest
591 char oldlock[33]; // safe 591 char oldlock[33]; // safe
592 int sz = read(fd, &oldlock, 32); 592 int sz = read(fd, &oldlock, 32);
593 close (fd); 593 close (fd);
594 if (sz <= 0) 594 if (sz <= 0)
595 return 1; 595 return 1;
596 oldlock[sz] = '\0'; 596 oldlock[sz] = '\0';
597 597
598 qDebug( "Device is locked by: %s", oldlock); 598 odebug << "Device is locked by: " << oldlock << "" << oendl;
599 599
600 int oldpid; 600 int oldpid;
601 int match = sscanf(oldlock, "%d", &oldpid); 601 int match = sscanf(oldlock, "%d", &oldpid);
602 602
603 // found a pid in lockfile ? 603 // found a pid in lockfile ?
604 if (match < 1 || oldpid <= 0) 604 if (match < 1 || oldpid <= 0)
605 return 1; 605 return 1;
606 606
607 // check if process exists 607 // check if process exists
608 if (kill((pid_t)oldpid, 0) == 0 || errno != ESRCH) 608 if (kill((pid_t)oldpid, 0) == 0 || errno != ESRCH)
609 return 1; 609 return 1;
610 610
611 qDebug( "lockfile is stale" ); 611 odebug << "lockfile is stale" << oendl;
612 } 612 }
613 } 613 }
614 614
615 fd = openLockfile(_pppdata->modemDevice(),O_WRONLY|O_TRUNC|O_CREAT); 615 fd = openLockfile(_pppdata->modemDevice(),O_WRONLY|O_TRUNC|O_CREAT);
616 if(fd >= 0) { 616 if(fd >= 0) {
617 sprintf(newlock,"%010d\n", getpid()); 617 sprintf(newlock,"%010d\n", getpid());
618 qDebug("Locking Device: %s", newlock); 618 odebug << "Locking Device: " << newlock << "" << oendl;
619 619
620 write(fd, newlock, strlen(newlock)); 620 write(fd, newlock, strlen(newlock));
621 close(fd); 621 close(fd);
622 modem_is_locked=true; 622 modem_is_locked=true;
623 623
624 return 0; 624 return 0;
625 } 625 }
626 626
627 return -1; 627 return -1;
628 628
629} 629}
630 630
631 631
632// UnLock modem device 632// UnLock modem device
633void Modem::unlockdevice() { 633void Modem::unlockdevice() {
634 if (modem_is_locked) { 634 if (modem_is_locked) {
635 qDebug( "UnLocking Modem Device" ); 635 odebug << "UnLocking Modem Device" << oendl;
636 close(modemfd); 636 close(modemfd);
637 modemfd = -1; 637 modemfd = -1;
638 unlink(lockfile); 638 unlink(lockfile);
639 lockfile[0] = '\0'; 639 lockfile[0] = '\0';
640 modem_is_locked=false; 640 modem_is_locked=false;
641 } 641 }
642} 642}
643 643
644int Modem::openLockfile( QString lockfile, int flags) 644int Modem::openLockfile( QString lockfile, int flags)
645{ 645{
646 int fd; 646 int fd;
647 int mode; 647 int mode;
648 flags = O_RDONLY; 648 flags = O_RDONLY;
649 if(flags == O_WRONLY|O_TRUNC|O_CREAT) 649 if(flags == O_WRONLY|O_TRUNC|O_CREAT)
650 mode = 0644; 650 mode = 0644;
651 else 651 else
652 mode = 0; 652 mode = 0;
653 653
654 lockfile = LOCK_DIR; 654 lockfile = LOCK_DIR;
655 lockfile += "/LCK.."; 655 lockfile += "/LCK..";
656 lockfile += device.right( device.length() - device.findRev("/") -1 ); 656 lockfile += device.right( device.length() - device.findRev("/") -1 );
657 qDebug("lockfile >%s<",lockfile.latin1()); 657 odebug << "lockfile >" << lockfile.latin1() << "<" << oendl;
658 // TODO: 658 // TODO:
659 // struct stat st; 659 // struct stat st;
660 // if(stat(lockfile.data(), &st) == -1) { 660 // if(stat(lockfile.data(), &st) == -1) {
661 // if(errno == EBADF) 661 // if(errno == EBADF)
662 // return -1; 662 // return -1;
663 // } else { 663 // } else {
664 // // make sure that this is a regular file 664 // // make sure that this is a regular file
665 // if(!S_ISREG(st.st_mode)) 665 // if(!S_ISREG(st.st_mode))
666 // return -1; 666 // return -1;
667 // } 667 // }
668 if ((fd = open(lockfile, flags, mode)) == -1) { 668 if ((fd = open(lockfile, flags, mode)) == -1) {
669 qDebug("error opening lockfile!"); 669 odebug << "error opening lockfile!" << oendl;
670 lockfile = QString::null; 670 lockfile = QString::null;
671 fd = open(DEVNULL, O_RDONLY); 671 fd = open(DEVNULL, O_RDONLY);
672 } else 672 } else
673 fchown(fd, 0, 0); 673 fchown(fd, 0, 0);
674 return fd; 674 return fd;
675} 675}
676 676
677 677
678 678
679void alarm_handler(int) { 679void alarm_handler(int) {
680 // fprintf(stderr, "alarm_handler(): Received SIGALRM\n"); 680 // fprintf(stderr, "alarm_handler(): Received SIGALRM\n");
681 681
682 // jump 682 // jump
683 siglongjmp(jmp_buffer, 1); 683 siglongjmp(jmp_buffer, 1);
684} 684}
685 685
686 686
687const char* Modem::authFile(Auth method, int version) { 687const char* Modem::authFile(Auth method, int version) {
688 switch(method|version) { 688 switch(method|version) {
689 case PAP|Original: 689 case PAP|Original:
690 return PAP_AUTH_FILE; 690 return PAP_AUTH_FILE;
691 break; 691 break;
692 case PAP|New: 692 case PAP|New:
693 return PAP_AUTH_FILE".new"; 693 return PAP_AUTH_FILE".new";
694 break; 694 break;
695 case PAP|Old: 695 case PAP|Old:
696 return PAP_AUTH_FILE".old"; 696 return PAP_AUTH_FILE".old";
697 break; 697 break;
698 case CHAP|Original: 698 case CHAP|Original:
699 return CHAP_AUTH_FILE; 699 return CHAP_AUTH_FILE;
700 break; 700 break;
701 case CHAP|New: 701 case CHAP|New:
702 return CHAP_AUTH_FILE".new"; 702 return CHAP_AUTH_FILE".new";
703 break; 703 break;
704 case CHAP|Old: 704 case CHAP|Old:
705 return CHAP_AUTH_FILE".old"; 705 return CHAP_AUTH_FILE".old";
706 break; 706 break;
707 default: 707 default:
708 return 0L; 708 return 0L;
709 } 709 }
710} 710}
711 711
712 712
713bool Modem::createAuthFile(Auth method, const char *username, const char *password) { 713bool Modem::createAuthFile(Auth method, const char *username, const char *password) {
714 const char *authfile, *oldName, *newName; 714 const char *authfile, *oldName, *newName;
715 char line[100]; 715 char line[100];
716 char regexp[2*MaxStrLen+30]; 716 char regexp[2*MaxStrLen+30];
717 regex_t preg; 717 regex_t preg;
718 718
719 if(!(authfile = authFile(method))) 719 if(!(authfile = authFile(method)))
720 return false; 720 return false;
721 721
722 if(!(newName = authFile(method, New))) 722 if(!(newName = authFile(method, New)))
723 return false; 723 return false;
724 724
725 // look for username, "username" or 'username' 725 // look for username, "username" or 'username'
726 // if you modify this RE you have to adapt regexp's size above 726 // if you modify this RE you have to adapt regexp's size above
727 snprintf(regexp, sizeof(regexp), "^[ \t]*%s[ \t]\\|^[ \t]*[\"\']%s[\"\']", 727 snprintf(regexp, sizeof(regexp), "^[ \t]*%s[ \t]\\|^[ \t]*[\"\']%s[\"\']",
728 username,username); 728 username,username);
729 MY_ASSERT(regcomp(&preg, regexp, 0) == 0); 729 MY_ASSERT(regcomp(&preg, regexp, 0) == 0);
730 730
731 // copy to new file pap- or chap-secrets 731 // copy to new file pap- or chap-secrets
732 int old_umask = umask(0077); 732 int old_umask = umask(0077);
733 FILE *fout = fopen(newName, "w"); 733 FILE *fout = fopen(newName, "w");
734 if(fout) { 734 if(fout) {
735 // copy old file 735 // copy old file
736 FILE *fin = fopen(authfile, "r"); 736 FILE *fin = fopen(authfile, "r");
737 if(fin) { 737 if(fin) {
738 while(fgets(line, sizeof(line), fin)) { 738 while(fgets(line, sizeof(line), fin)) {
739 if(regexec(&preg, line, 0, 0L, 0) == 0) 739 if(regexec(&preg, line, 0, 0L, 0) == 0)
740 continue; 740 continue;
741 fputs(line, fout); 741 fputs(line, fout);
742 } 742 }
743 fclose(fin); 743 fclose(fin);
744 } 744 }
745 745
746 // append user/pass pair 746 // append user/pass pair
747 fprintf(fout, "\"%s\"\t*\t\"%s\"\n", username, password); 747 fprintf(fout, "\"%s\"\t*\t\"%s\"\n", username, password);
748 fclose(fout); 748 fclose(fout);
749 } 749 }
750 750
751 // restore umask 751 // restore umask
752 umask(old_umask); 752 umask(old_umask);
753 753
754 // free memory allocated by regcomp 754 // free memory allocated by regcomp
755 regfree(&preg); 755 regfree(&preg);
756 756
757 if(!(oldName = authFile(method, Old))) 757 if(!(oldName = authFile(method, Old)))
758 return false; 758 return false;
759 759
760 // delete old file if any 760 // delete old file if any
761 unlink(oldName); 761 unlink(oldName);
762 762
763 rename(authfile, oldName); 763 rename(authfile, oldName);
764 rename(newName, authfile); 764 rename(newName, authfile);
765 765
@@ -834,247 +834,247 @@ int checkForInterface()
834 // extern char *no_ppp_msg; 834 // extern char *no_ppp_msg;
835 835
836 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) 836 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
837 return 1; /* can't tell */ 837 return 1; /* can't tell */
838 838
839 strlcpy(ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name)); 839 strlcpy(ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name));
840 ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0; 840 ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0;
841 close(s); 841 close(s);
842 842
843 if (ok == -1) { 843 if (ok == -1) {
844// This is ifdef'd FreeBSD, because FreeBSD is the only BSD that supports 844// This is ifdef'd FreeBSD, because FreeBSD is the only BSD that supports
845// KLDs, the old LKM interface couldn't handle loading devices 845// KLDs, the old LKM interface couldn't handle loading devices
846// dynamically, and thus can't load ppp support on the fly 846// dynamically, and thus can't load ppp support on the fly
847#ifdef __FreeBSD__ 847#ifdef __FreeBSD__
848 // If we failed to load ppp support and don't have it already. 848 // If we failed to load ppp support and don't have it already.
849 if (kldload("if_ppp") == -1) { 849 if (kldload("if_ppp") == -1) {
850 return -1; 850 return -1;
851 } 851 }
852 return 0; 852 return 0;
853#else 853#else
854 return -1; 854 return -1;
855#endif 855#endif
856 } 856 }
857 return 0; 857 return 0;
858#else 858#else
859// We attempt to use the SunOS/SysVr4 method and stat /dev/ppp 859// We attempt to use the SunOS/SysVr4 method and stat /dev/ppp
860 struct stat buf; 860 struct stat buf;
861 861
862 memset(&buf, 0, sizeof(buf)); 862 memset(&buf, 0, sizeof(buf));
863 return stat("/dev/ppp", &buf); 863 return stat("/dev/ppp", &buf);
864#endif 864#endif
865} 865}
866 866
867bool Modem::execpppd(const char *arguments) { 867bool Modem::execpppd(const char *arguments) {
868 char buf[MAX_CMDLEN]; 868 char buf[MAX_CMDLEN];
869 char *args[MaxArgs]; 869 char *args[MaxArgs];
870 pid_t pgrpid; 870 pid_t pgrpid;
871 871
872 if(modemfd<0) 872 if(modemfd<0)
873 return false; 873 return false;
874 874
875 _pppdExitStatus = -1; 875 _pppdExitStatus = -1;
876 876
877 (void)::pipe( m_pppdLOG ); 877 (void)::pipe( m_pppdLOG );
878 878
879 switch(pppdPid = fork()) 879 switch(pppdPid = fork())
880 { 880 {
881 case -1: 881 case -1:
882 fprintf(stderr,"In parent: fork() failed\n"); 882 fprintf(stderr,"In parent: fork() failed\n");
883 ::close( m_pppdLOG[0] ); 883 ::close( m_pppdLOG[0] );
884 ::close( m_pppdLOG[1] ); 884 ::close( m_pppdLOG[1] );
885 return false; 885 return false;
886 break; 886 break;
887 887
888 case 0: 888 case 0:
889 // let's parse the arguments the user supplied into UNIX suitable form 889 // let's parse the arguments the user supplied into UNIX suitable form
890 // that is a list of pointers each pointing to exactly one word 890 // that is a list of pointers each pointing to exactly one word
891 strlcpy(buf, arguments); 891 strlcpy(buf, arguments);
892 parseargs(buf, args); 892 parseargs(buf, args);
893 // become a session leader and let /dev/ttySx 893 // become a session leader and let /dev/ttySx
894 // be the controlling terminal. 894 // be the controlling terminal.
895 pgrpid = setsid(); 895 pgrpid = setsid();
896#ifdef TIOCSCTTY 896#ifdef TIOCSCTTY
897 if(ioctl(modemfd, TIOCSCTTY, 0)<0) 897 if(ioctl(modemfd, TIOCSCTTY, 0)<0)
898 fprintf(stderr, "ioctl() failed.\n"); 898 fprintf(stderr, "ioctl() failed.\n");
899#elif defined (TIOCSPGRP) 899#elif defined (TIOCSPGRP)
900 if(ioctl(modemfd, TIOCSPGRP, &pgrpid)<0) 900 if(ioctl(modemfd, TIOCSPGRP, &pgrpid)<0)
901 fprintf(stderr, "ioctl() failed.\n"); 901 fprintf(stderr, "ioctl() failed.\n");
902#endif 902#endif
903 if(tcsetpgrp(modemfd, pgrpid)<0) 903 if(tcsetpgrp(modemfd, pgrpid)<0)
904 fprintf(stderr, "tcsetpgrp() failed.\n"); 904 fprintf(stderr, "tcsetpgrp() failed.\n");
905 905
906 ::close( m_pppdLOG[0] ); 906 ::close( m_pppdLOG[0] );
907 ::setenv( "LANG", "C", 1 ); // overwrite 907 ::setenv( "LANG", "C", 1 ); // overwrite
908 dup2(m_pppdLOG[1], 11 ); // for logfd 11 908 dup2(m_pppdLOG[1], 11 ); // for logfd 11
909 dup2(modemfd, 0); 909 dup2(modemfd, 0);
910 dup2(modemfd, 1); 910 dup2(modemfd, 1);
911 911
912 912
913 switch (checkForInterface()) { 913 switch (checkForInterface()) {
914 case 1: 914 case 1:
915 fprintf(stderr, "Cannot determine if kernel supports ppp.\n"); 915 fprintf(stderr, "Cannot determine if kernel supports ppp.\n");
916 break; 916 break;
917 case -1: 917 case -1:
918 fprintf(stderr, "Kernel does not support ppp, oops.\n"); 918 fprintf(stderr, "Kernel does not support ppp, oops.\n");
919 break; 919 break;
920 case 0: 920 case 0:
921 fprintf(stderr, "Kernel supports ppp alright.\n"); 921 fprintf(stderr, "Kernel supports ppp alright.\n");
922 break; 922 break;
923 } 923 }
924 924
925 execve(pppdPath(), args, 0L); 925 execve(pppdPath(), args, 0L);
926 _exit(0); 926 _exit(0);
927 break; 927 break;
928 928
929 default: 929 default:
930 qDebug("In parent: pppd pid %d\n",pppdPid); 930 odebug << "In parent: pppd pid " << pppdPid << "\n" << oendl;
931 close(modemfd); 931 close(modemfd);
932 932
933 ::close( m_pppdLOG[1] ); 933 ::close( m_pppdLOG[1] );
934 // set it to nonblocking io 934 // set it to nonblocking io
935 int flag = ::fcntl( m_pppdLOG[0], F_GETFL ); 935 int flag = ::fcntl( m_pppdLOG[0], F_GETFL );
936 936
937 if ( !(flag & O_NONBLOCK) ) { 937 if ( !(flag & O_NONBLOCK) ) {
938 qDebug("Setting nonblocking io"); 938 odebug << "Setting nonblocking io" << oendl;
939 flag |= O_NONBLOCK; 939 flag |= O_NONBLOCK;
940 ::fcntl(m_pppdLOG[0], F_SETFL, flag ); 940 ::fcntl(m_pppdLOG[0], F_SETFL, flag );
941 } 941 }
942 942
943 delete m_modemDebug; 943 delete m_modemDebug;
944 m_modemDebug = new QSocketNotifier(m_pppdLOG[0], QSocketNotifier::Read, this ); 944 m_modemDebug = new QSocketNotifier(m_pppdLOG[0], QSocketNotifier::Read, this );
945 connect(m_modemDebug, SIGNAL(activated(int) ), 945 connect(m_modemDebug, SIGNAL(activated(int) ),
946 this, SLOT(slotModemDebug(int) ) ); 946 this, SLOT(slotModemDebug(int) ) );
947 947
948 modemfd = -1; 948 modemfd = -1;
949 m_pppdDev = QString::fromLatin1("ppp0"); 949 m_pppdDev = QString::fromLatin1("ppp0");
950 return true; 950 return true;
951 break; 951 break;
952 } 952 }
953} 953}
954 954
955 955
956bool Modem::killpppd() { 956bool Modem::killpppd() {
957 qDebug("In killpppd and pid is %d", pppdPid ); 957 odebug << "In killpppd and pid is " << pppdPid << "" << oendl;
958 if(pppdPid > 0) { 958 if(pppdPid > 0) {
959 delete m_modemDebug; 959 delete m_modemDebug;
960 m_modemDebug = 0; 960 m_modemDebug = 0;
961 qDebug("In killpppd(): Sending SIGTERM to %d\n", pppdPid); 961 odebug << "In killpppd(): Sending SIGTERM to " << pppdPid << "\n" << oendl;
962 if(kill(pppdPid, SIGTERM) < 0) { 962 if(kill(pppdPid, SIGTERM) < 0) {
963 qDebug("Error terminating %d. Sending SIGKILL\n", pppdPid); 963 odebug << "Error terminating " << pppdPid << ". Sending SIGKILL\n" << oendl;
964 if(kill(pppdPid, SIGKILL) < 0) { 964 if(kill(pppdPid, SIGKILL) < 0) {
965 qDebug("Error killing %d\n", pppdPid); 965 odebug << "Error killing " << pppdPid << "\n" << oendl;
966 return false; 966 return false;
967 } 967 }
968 } 968 }
969 } 969 }
970 return true; 970 return true;
971} 971}
972 972
973 973
974void Modem::parseargs(char* buf, char** args) { 974void Modem::parseargs(char* buf, char** args) {
975 int nargs = 0; 975 int nargs = 0;
976 int quotes; 976 int quotes;
977 977
978 while(nargs < MaxArgs-1 && *buf != '\0') { 978 while(nargs < MaxArgs-1 && *buf != '\0') {
979 979
980 quotes = 0; 980 quotes = 0;
981 981
982 // Strip whitespace. Use nulls, so that the previous argument is 982 // Strip whitespace. Use nulls, so that the previous argument is
983 // terminated automatically. 983 // terminated automatically.
984 984
985 while ((*buf == ' ' ) || (*buf == '\t' ) || (*buf == '\n' ) ) 985 while ((*buf == ' ' ) || (*buf == '\t' ) || (*buf == '\n' ) )
986 *buf++ = '\0'; 986 *buf++ = '\0';
987 987
988 // detect begin of quoted argument 988 // detect begin of quoted argument
989 if (*buf == '"' || *buf == '\'') { 989 if (*buf == '"' || *buf == '\'') {
990 quotes = *buf; 990 quotes = *buf;
991 *buf++ = '\0'; 991 *buf++ = '\0';
992 } 992 }
993 993
994 // save the argument 994 // save the argument
995 if(*buf != '\0') { 995 if(*buf != '\0') {
996 *args++ = buf; 996 *args++ = buf;
997 nargs++; 997 nargs++;
998 } 998 }
999 999
1000 if (!quotes) 1000 if (!quotes)
1001 while ((*buf != '\0') && (*buf != '\n') && 1001 while ((*buf != '\0') && (*buf != '\n') &&
1002 (*buf != '\t') && (*buf != ' ')) 1002 (*buf != '\t') && (*buf != ' '))
1003 buf++; 1003 buf++;
1004 else { 1004 else {
1005 while ((*buf != '\0') && (*buf != quotes)) 1005 while ((*buf != '\0') && (*buf != quotes))
1006 buf++; 1006 buf++;
1007 *buf++ = '\0'; 1007 *buf++ = '\0';
1008 } 1008 }
1009 } 1009 }
1010 1010
1011 *args = 0L; 1011 *args = 0L;
1012} 1012}
1013 1013
1014bool Modem::execPPPDaemon(const QString & arguments) 1014bool Modem::execPPPDaemon(const QString & arguments)
1015{ 1015{
1016 if(execpppd(arguments)) { 1016 if(execpppd(arguments)) {
1017 _pppdata->setpppdRunning(true); 1017 _pppdata->setpppdRunning(true);
1018 return true; 1018 return true;
1019 } else 1019 } else
1020 return false; 1020 return false;
1021} 1021}
1022 1022
1023void Modem::killPPPDaemon() 1023void Modem::killPPPDaemon()
1024{ 1024{
1025 _pppdata->setpppdRunning(false); 1025 _pppdata->setpppdRunning(false);
1026 killpppd(); 1026 killpppd();
1027} 1027}
1028 1028
1029int Modem::pppdExitStatus() 1029int Modem::pppdExitStatus()
1030{ 1030{
1031 return _pppdExitStatus; 1031 return _pppdExitStatus;
1032} 1032}
1033 1033
1034int Modem::openResolv(int flags) 1034int Modem::openResolv(int flags)
1035{ 1035{
1036 int fd; 1036 int fd;
1037 if ((fd = open(_PATH_RESCONF, flags)) == -1) { 1037 if ((fd = open(_PATH_RESCONF, flags)) == -1) {
1038 qDebug("error opening resolv.conf!"); 1038 odebug << "error opening resolv.conf!" << oendl;
1039 fd = open(DEVNULL, O_RDONLY); 1039 fd = open(DEVNULL, O_RDONLY);
1040 } 1040 }
1041 return fd; 1041 return fd;
1042} 1042}
1043 1043
1044bool Modem::setHostname(const QString & name) 1044bool Modem::setHostname(const QString & name)
1045{ 1045{
1046 return sethostname(name, name.length()) == 0; 1046 return sethostname(name, name.length()) == 0;
1047} 1047}
1048 1048
1049QString Modem::pppDevice()const { 1049QString Modem::pppDevice()const {
1050 return m_pppdDev; 1050 return m_pppdDev;
1051} 1051}
1052void Modem::setPPPDevice( const QString& dev ) { 1052void Modem::setPPPDevice( const QString& dev ) {
1053 m_pppdDev = dev; 1053 m_pppdDev = dev;
1054} 1054}
1055pid_t Modem::pppPID()const { 1055pid_t Modem::pppPID()const {
1056 return pppdPid; 1056 return pppdPid;
1057} 1057}
1058void Modem::setPPPDPid( pid_t pid ) { 1058void Modem::setPPPDPid( pid_t pid ) {
1059 qDebug("Modem setting pid"); 1059 odebug << "Modem setting pid" << oendl;
1060 _pppdExitStatus = -1; 1060 _pppdExitStatus = -1;
1061 pppdPid = pid; 1061 pppdPid = pid;
1062 modemfd = -1; 1062 modemfd = -1;
1063} 1063}
1064void Modem::slotModemDebug(int fd) { 1064void Modem::slotModemDebug(int fd) {
1065 char buf[2049]; 1065 char buf[2049];
1066 int len; 1066 int len;
1067 1067
1068 // read in pppd data look for Using interface 1068 // read in pppd data look for Using interface
1069 // then read the interface 1069 // then read the interface
1070 // we limit to 10 device now 0-9 1070 // we limit to 10 device now 0-9
1071 if((len = ::read(fd, buf, 2048)) > 0) { 1071 if((len = ::read(fd, buf, 2048)) > 0) {
1072 buf[len+1] = '\0'; 1072 buf[len+1] = '\0';
1073 char *found; 1073 char *found;
1074 if ( (found = ::strstr(buf, "Using interface ") ) ) { 1074 if ( (found = ::strstr(buf, "Using interface ") ) ) {
1075 found += 16; 1075 found += 16;
1076 m_pppdDev = QString::fromLatin1(found, 5 ); 1076 m_pppdDev = QString::fromLatin1(found, 5 );
1077 m_pppdDev = m_pppdDev.simplifyWhiteSpace(); 1077 m_pppdDev = m_pppdDev.simplifyWhiteSpace();
1078 } 1078 }
1079 } 1079 }
1080} 1080}
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 @@
1 1
2#include <qlayout.h> 2#include <qlayout.h>
3#include <qmessagebox.h> 3#include <qmessagebox.h>
4#include <qtabwidget.h> 4#include <qtabwidget.h>
5 5
6#include "accounts.h" 6#include "accounts.h"
7#include "devices.h" 7#include "devices.h"
8#include "general.h" 8#include "general.h"
9#include "interfaceppp.h" 9#include "interfaceppp.h"
10#include "modem.h" 10#include "modem.h"
11#include "pppconfig.h" 11#include "pppconfig.h"
12#include "pppdata.h" 12#include "pppdata.h"
13#include "runtests.h" 13#include "runtests.h"
14 14
15PPPConfigWidget::PPPConfigWidget( InterfacePPP* iface, QWidget *parent, 15PPPConfigWidget::PPPConfigWidget( InterfacePPP* iface, QWidget *parent,
16 const char *name, 16 const char *name,
17 bool modal, WFlags fl ) 17 bool modal, WFlags fl )
18 : QDialog(parent, name, modal, fl) 18 : QDialog(parent, name, modal, fl)
19{ 19{
20 setCaption(tr("Configure Modem")); 20 setCaption(tr("Configure Modem"));
21 int result = runTests(); 21 int result = runTests();
22 if(result == TEST_CRITICAL){ 22 if(result == TEST_CRITICAL){
23 QMessageBox::critical(0, tr("Modem failure"), tr("A critical failure appeard while testing the modem") ); 23 QMessageBox::critical(0, tr("Modem failure"), tr("A critical failure appeard while testing the modem") );
24 return; 24 return;
25 } 25 }
26 26
27 interface = iface; 27 interface = iface;
28 qDebug("PPPConfigWidget::PPPConfigWidget"); 28 odebug << "PPPConfigWidget::PPPConfigWidget" << oendl;
29 qDebug(" interface->getHardwareName >%s<", interface->getHardwareName().latin1()); 29 odebug << " interface->getHardwareName >" << interface->getHardwareName().latin1() << "<" << oendl;
30 30
31 qDebug(" _pppdata->accname >%s<",interface->data()->accname().latin1()); 31 odebug << " _pppdata->accname >" << interface->data()->accname().latin1() << "<" << oendl;
32 32
33 33
34 QVBoxLayout *layout = new QVBoxLayout( this ); 34 QVBoxLayout *layout = new QVBoxLayout( this );
35 layout->setSpacing( 0 ); 35 layout->setSpacing( 0 );
36 layout->setMargin( 1 ); 36 layout->setMargin( 1 );
37 tabWindow = new QTabWidget( this, "tabWidget" ); 37 tabWindow = new QTabWidget( this, "tabWidget" );
38 layout->addWidget( tabWindow ); 38 layout->addWidget( tabWindow );
39 39
40 accounts = new AccountWidget( interface->data(), tabWindow, "accounts", Qt::WStyle_ContextHelp ); 40 accounts = new AccountWidget( interface->data(), tabWindow, "accounts", Qt::WStyle_ContextHelp );
41 tabWindow->addTab( accounts, tr("&Accounts") ); 41 tabWindow->addTab( accounts, tr("&Accounts") );
42 devices = new DevicesWidget( interface, tabWindow, "devices", Qt::WStyle_ContextHelp ); 42 devices = new DevicesWidget( interface, tabWindow, "devices", Qt::WStyle_ContextHelp );
43 tabWindow->addTab( devices, tr("&Devices") ); 43 tabWindow->addTab( devices, tr("&Devices") );
44 44
45//OLD: 45//OLD:
46// modem1 = new ModemWidget( interface, tabWindow, "modem1" ); 46// modem1 = new ModemWidget( interface, tabWindow, "modem1" );
47// tabWindow->addTab( modem1, tr("&Device") ); 47// tabWindow->addTab( modem1, tr("&Device") );
48// modem2 = new ModemWidget2( interface, tabWindow, "modem2" ); 48// modem2 = new ModemWidget2( interface, tabWindow, "modem2" );
49// tabWindow->addTab( modem2, tr("&Modem") ); 49// tabWindow->addTab( modem2, tr("&Modem") );
50 50
51} 51}
52 52
53 53
54PPPConfigWidget::~PPPConfigWidget() 54PPPConfigWidget::~PPPConfigWidget()
55{ 55{
56 56
57} 57}
58 58
59void PPPConfigWidget::accept() 59void PPPConfigWidget::accept()
60{ 60{
61 qDebug("PPPConfigWidget::accept"); 61 odebug << "PPPConfigWidget::accept" << oendl;
62 qDebug(" _pppdata->accname >%s<",interface->data()->accname().latin1()); 62 odebug << " _pppdata->accname >" << interface->data()->accname().latin1() << "<" << oendl;
63 qDebug(" interface->getHardwareName >%s<", interface->getHardwareName().latin1()); 63 odebug << " interface->getHardwareName >" << interface->getHardwareName().latin1() << "<" << oendl;
64 interface->setInterfaceName( interface->data()->devname() ); 64 interface->setInterfaceName( interface->data()->devname() );
65 interface->setHardwareName( interface->data()->accname() ); 65 interface->setHardwareName( interface->data()->accname() );
66 interface->save(); 66 interface->save();
67 QDialog::accept(); 67 QDialog::accept();
68} 68}
69 69
70 70
71void PPPConfigWidget::reject() 71void PPPConfigWidget::reject()
72{ 72{
73 interface->data()->cancel(); 73 interface->data()->cancel();
74 QDialog::reject(); 74 QDialog::reject();
75} 75}
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 @@
1/* 1/*
2 * kPPP: A pppd front end for the KDE project 2 * kPPP: A pppd front end for the KDE project
3 * 3 *
4 * $Id$ 4 * $Id$
5 * 5 *
6 * Copyright (C) 1997 Bernd Johannes Wuebben 6 * Copyright (C) 1997 Bernd Johannes Wuebben
7 * wuebben@math.cornell.edu 7 * wuebben@math.cornell.edu
8 * 8 *
9 * based on EzPPP: 9 * based on EzPPP:
10 * Copyright (C) 1997 Jay Painter 10 * Copyright (C) 1997 Jay Painter
11 * 11 *
12 * This program is free software; you can redistribute it and/or 12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public 13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either 14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version. 15 * version 2 of the License, or (at your option) any later version.
16 * 16 *
17 * This program is distributed in the hope that it will be useful, 17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details. 20 * Library General Public License for more details.
21 * 21 *
22 * You should have received a copy of the GNU Library General Public 22 * You should have received a copy of the GNU Library General Public
23 * License along with this program; if not, write to the Free 23 * License along with this program; if not, write to the Free
24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 */ 25 */
26 26
27#include "pppdata.h" 27#include "pppdata.h"
28#include "runtests.h" 28#include "runtests.h"
29//#include "devices.h" 29//#include "devices.h"
30//#include <klocale.h> 30//#include <klocale.h>
31#include <qpe/config.h> 31#include <qpe/config.h>
32#include <qmessagebox.h> 32#include <qmessagebox.h>
33#include <qapplication.h> 33#include <qapplication.h>
34// #include <klocale.h> 34// #include <klocale.h>
35// #include <kconfig.h> 35// #include <kconfig.h>
36// #include <kmessagebox.h> 36// #include <kmessagebox.h>
37// #include <kapplication.h> 37// #include <kapplication.h>
38#include <assert.h> 38#include <assert.h>
39 39
40#define SEPARATOR -sseepp- 40#define SEPARATOR -sseepp-
41#define SEP QString("%1SEPARATOR%1") 41#define SEP QString("%1SEPARATOR%1")
42 42
43PPPData::PPPData() 43PPPData::PPPData()
44 : passwd(""), 44 : passwd(""),
45 _modemName(""), 45 _modemName(""),
46 highcount(-1), // start out with no entries 46 highcount(-1), // start out with no entries
47 highcountdev(-1), // start out with no entries 47 highcountdev(-1), // start out with no entries
48// caccount(-1), // set the current account index also 48// caccount(-1), // set the current account index also
49 suidprocessid(-1), // process ID of setuid child 49 suidprocessid(-1), // process ID of setuid child
50 pppdisrunning(false), 50 pppdisrunning(false),
51 pppderror(0) 51 pppderror(0)
52{ 52{
53 highcount = readNumConfig(GENERAL_GRP, NUMACCOUNTS_KEY, 0) - 1; 53 highcount = readNumConfig(GENERAL_GRP, NUMACCOUNTS_KEY, 0) - 1;
54 highcountdev = readNumConfig(GENERAL_GRP, NUMDEVICES_KEY, 0) - 1; 54 highcountdev = readNumConfig(GENERAL_GRP, NUMDEVICES_KEY, 0) - 1;
55 Config cfg = config(); 55 Config cfg = config();
56 cfg.setGroup(GENERAL_GRP); 56 cfg.setGroup(GENERAL_GRP);
57 accountList = cfg.readListEntry(ACCOUNT_LIST, ',' ); 57 accountList = cfg.readListEntry(ACCOUNT_LIST, ',' );
58 deviceList = cfg.readListEntry(DEVICESNAMES_LIST, ',' ); 58 deviceList = cfg.readListEntry(DEVICESNAMES_LIST, ',' );
59 qDebug("PPPData::PPPData has a accountList %s", accountList.join("---").latin1()); 59 odebug << "PPPData::PPPData has a accountList " << accountList.join("---").latin1() << "" << oendl;
60 qDebug("PPPData::PPPData has a deviceList %s", deviceList.join("---").latin1()); 60 odebug << "PPPData::PPPData has a deviceList " << deviceList.join("---").latin1() << "" << oendl;
61 61
62// if (highcount > MAX_ACCOUNTS) 62// if (highcount > MAX_ACCOUNTS)
63// highcount = MAX_ACCOUNTS; 63// highcount = MAX_ACCOUNTS;
64 64
65 // if(highcount >= 0 && defaultAccount().isEmpty()) { 65 // if(highcount >= 0 && defaultAccount().isEmpty()) {
66// setAccountbyIndex(0); 66// setAccountbyIndex(0);
67// setDefaultAccount(accname()); 67// setDefaultAccount(accname());
68// } else if(!setAccount(defaultAccount())) 68// } else if(!setAccount(defaultAccount()))
69 setDefaultAccount(accname()); 69 setDefaultAccount(accname());
70 70
71 // start out with internal debugging disabled 71 // start out with internal debugging disabled
72 // the user is still free to specify `debug' on his own 72 // the user is still free to specify `debug' on his own
73 setPPPDebug(false); 73 setPPPDebug(false);
74 74
75 ::pppdVersion(&pppdVer, &pppdMod, &pppdPatch); 75 ::pppdVersion(&pppdVer, &pppdMod, &pppdPatch);
76 76
77} 77}
78 78
79Config PPPData::config() 79Config PPPData::config()
80{ 80{
81 return Config("NetworkSetupPPP"); 81 return Config("NetworkSetupPPP");
82} 82}
83 83
84// 84//
85// save configuration 85// save configuration
86// 86//
87void PPPData::save() 87void PPPData::save()
88{ 88{
89 qDebug("PPPData saving data"); 89 odebug << "PPPData saving data" << oendl;
90 writeConfig(GENERAL_GRP, NUMACCOUNTS_KEY, count()); 90 writeConfig(GENERAL_GRP, NUMACCOUNTS_KEY, count());
91 writeConfig(GENERAL_GRP, NUMDEVICES_KEY, highcountdev + 1); 91 writeConfig(GENERAL_GRP, NUMDEVICES_KEY, highcountdev + 1);
92 QString key; 92 QString key;
93 QStringList keys; 93 QStringList keys;
94 Config cfg = config(); 94 Config cfg = config();
95 cfg.setGroup(GENERAL_GRP); 95 cfg.setGroup(GENERAL_GRP);
96 cfg.writeEntry(ACCOUNT_LIST, accountList, ',' ); 96 cfg.writeEntry(ACCOUNT_LIST, accountList, ',' );
97 cfg.writeEntry(DEVICESNAMES_LIST, deviceList, ',' ); 97 cfg.writeEntry(DEVICESNAMES_LIST, deviceList, ',' );
98 98
99 for( QMap<QString,QString>::Iterator it = stringEntries.begin(); 99 for( QMap<QString,QString>::Iterator it = stringEntries.begin();
100 it != stringEntries.end(); ++it ){ 100 it != stringEntries.end(); ++it ){
101 QString val = it.data(); 101 QString val = it.data();
102 key = it.key(); 102 key = it.key();
103// qDebug("saving %s -> %s", key.latin1(), val.latin1() ); 103// odebug << "saving " << key.latin1() << " -> " << val.latin1() << "" << oendl;
104 keys = QStringList::split( "SEPARATOR", key ); 104 keys = QStringList::split( "SEPARATOR", key );
105 //qDebug("group >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.latin1() ); 105 //odebug << "group >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl;
106 cfg.setGroup(keys[0]); 106 cfg.setGroup(keys[0]);
107 cfg.writeEntry(keys[1], val); 107 cfg.writeEntry(keys[1], val);
108 } 108 }
109 for( QMap<QString,int>::Iterator it = intEntries.begin(); 109 for( QMap<QString,int>::Iterator it = intEntries.begin();
110 it != intEntries.end(); ++it ){ 110 it != intEntries.end(); ++it ){
111 int val = it.data(); 111 int val = it.data();
112 key = it.key(); 112 key = it.key();
113// qDebug("saving %s -> %i", key.latin1(), val ); 113// odebug << "saving " << key.latin1() << " -> " << val << "" << oendl;
114 keys = QStringList::split( "SEPARATOR", key ); 114 keys = QStringList::split( "SEPARATOR", key );
115 //qDebug("group >%s< key >%s< val %i", keys[0].latin1(), keys[1].latin1(), val ); 115 //odebug << "group >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< val " << val << "" << oendl;
116 cfg.setGroup(keys[0]); 116 cfg.setGroup(keys[0]);
117 cfg.writeEntry(keys[1], val); 117 cfg.writeEntry(keys[1], val);
118 } 118 }
119 for( QMap<QString,QStringList>::Iterator it = listEntries.begin(); 119 for( QMap<QString,QStringList>::Iterator it = listEntries.begin();
120 it != listEntries.end(); ++it ){ 120 it != listEntries.end(); ++it ){
121 QStringList val = it.data(); 121 QStringList val = it.data();
122 key = it.key(); 122 key = it.key();
123 QChar sep = sepEntries[key]; 123 QChar sep = sepEntries[key];
124// qDebug("saving %s -> %s", key.latin1(), val.join(sep).latin1() ); 124// odebug << "saving " << key.latin1() << " -> " << val.join(sep).latin1() << "" << oendl;
125 keys = QStringList::split( "SEPARATOR", key ); 125 keys = QStringList::split( "SEPARATOR", key );
126 cfg.setGroup(keys[0]); 126 cfg.setGroup(keys[0]);
127 cfg.writeEntry(keys[1], val, sep); 127 cfg.writeEntry(keys[1], val, sep);
128 } 128 }
129} 129}
130 130
131 131
132// 132//
133// cancel changes 133// cancel changes
134// 134//
135void PPPData::cancel() { 135void PPPData::cancel() {
136 stringEntries.clear(); 136 stringEntries.clear();
137 intEntries.clear(); 137 intEntries.clear();
138 listEntries.clear(); 138 listEntries.clear();
139} 139}
140 140
141// functions to read/write date to configuration file 141// functions to read/write date to configuration file
142QString PPPData::readConfig(const QString &group, const QString &key, 142QString PPPData::readConfig(const QString &group, const QString &key,
143 const QString &defvalue = "") 143 const QString &defvalue = "")
144{ 144{
145// qDebug("PPPData::readConfig key >%s< group >%s<",key.latin1(), group.latin1()); 145// odebug << "PPPData::readConfig key >" << key.latin1() << "< group >" << group.latin1() << "<" << oendl;
146 QString idx = SEP.arg(group).arg(key); 146 QString idx = SEP.arg(group).arg(key);
147 if (stringEntries.find(idx) != stringEntries.end()) 147 if (stringEntries.find(idx) != stringEntries.end())
148 return stringEntries[idx]; 148 return stringEntries[idx];
149 Config cfg = config(); 149 Config cfg = config();
150 cfg.setGroup(group); 150 cfg.setGroup(group);
151 return cfg.readEntry(key, defvalue); 151 return cfg.readEntry(key, defvalue);
152} 152}
153 153
154 154
155int PPPData::readNumConfig(const QString &group, const QString &key, 155int PPPData::readNumConfig(const QString &group, const QString &key,
156 int defvalue) 156 int defvalue)
157{ 157{
158 QString idx = SEP.arg(group).arg(key); 158 QString idx = SEP.arg(group).arg(key);
159 if (intEntries.find(idx) != intEntries.end()) 159 if (intEntries.find(idx) != intEntries.end())
160 return intEntries[idx]; 160 return intEntries[idx];
161 Config cfg = config(); 161 Config cfg = config();
162 cfg.setGroup(group); 162 cfg.setGroup(group);
163 return cfg.readNumEntry(key, defvalue); 163 return cfg.readNumEntry(key, defvalue);
164 164
165// if (config) { 165// if (config) {
166// config->setGroup(group); 166// config->setGroup(group);
167// return config->readNumEntry(key, defvalue); 167// return config->readNumEntry(key, defvalue);
168// } else 168// } else
169// return defvalue; 169// return defvalue;
170 170
171} 171}
172 172
173 173
174bool PPPData::readListConfig(const QString &group, const QString &key, 174bool PPPData::readListConfig(const QString &group, const QString &key,
175 QStringList &list, char sep) { 175 QStringList &list, char sep) {
176 list.clear(); 176 list.clear();
177 QString idx = SEP.arg(group).arg(key); 177 QString idx = SEP.arg(group).arg(key);
178 if (listEntries.find(idx) != listEntries.end()){ 178 if (listEntries.find(idx) != listEntries.end()){
179 list = listEntries[idx]; 179 list = listEntries[idx];
180 return true; 180 return true;
181 } 181 }
182 Config cfg = config(); 182 Config cfg = config();
183 cfg.setGroup(group); 183 cfg.setGroup(group);
184 list = cfg.readListEntry(key, sep); 184 list = cfg.readListEntry(key, sep);
185 if (list.count() > 0) return true; 185 if (list.count() > 0) return true;
186 return false; 186 return false;
187 187
188// if (config) { 188// if (config) {
189// config->setGroup(group); 189// config->setGroup(group);
190// list = config->readListEntry(key, sep); 190// list = config->readListEntry(key, sep);
191// return true; 191// return true;
192// } else 192// } else
193// return false; 193// return false;
194} 194}
195 195
196 196
197void PPPData::writeConfig(const QString &group, const QString &key, 197void PPPData::writeConfig(const QString &group, const QString &key,
198 const QString &value) { 198 const QString &value) {
199 stringEntries.insert( SEP.arg(group).arg(key), value ); 199 stringEntries.insert( SEP.arg(group).arg(key), value );
200// if (config) { 200// if (config) {
201// config->setGroup(group); 201// config->setGroup(group);
202// config->writeEntry(key, value); 202// config->writeEntry(key, value);
203// } 203// }
204} 204}
205 205
206 206
207void PPPData::writeConfig(const QString &group, const QString &key, int value) 207void PPPData::writeConfig(const QString &group, const QString &key, int value)
208{ 208{
209 intEntries.insert( SEP.arg(group).arg(key), value ); 209 intEntries.insert( SEP.arg(group).arg(key), value );
210// if (config) { 210// if (config) {
211// config->setGroup(group); 211// config->setGroup(group);
212// config->writeEntry(key, value); 212// config->writeEntry(key, value);
213// } 213// }
214} 214}
215 215
216 216
217void PPPData::writeListConfig(const QString &group, const QString &key, 217void PPPData::writeListConfig(const QString &group, const QString &key,
218 QStringList &list, char sep) 218 QStringList &list, char sep)
219{ 219{
220 listEntries.insert( SEP.arg(group).arg(key), list ); 220 listEntries.insert( SEP.arg(group).arg(key), list );
221 sepEntries.insert( SEP.arg(group).arg(key), sep ); 221 sepEntries.insert( SEP.arg(group).arg(key), sep );
222// if (config) { 222// if (config) {
223// config->setGroup(group); 223// config->setGroup(group);
224// config->writeEntry(key, list, sep); 224// config->writeEntry(key, list, sep);
225// } 225// }
226} 226}
227 227
228 228
229// 229//
230// functions to set/return general information 230// functions to set/return general information
231// 231//
232QString PPPData::password(){ 232QString PPPData::password(){
233 if ( storePassword() ) return storedPassword(); 233 if ( storePassword() ) return storedPassword();
234 else return passwd; 234 else return passwd;
235} 235}
236 236
237 237
238void PPPData::setPassword(const QString &pw) { 238void PPPData::setPassword(const QString &pw) {
239 passwd = pw; 239 passwd = pw;
240} 240}
241 241
@@ -272,207 +272,207 @@ void PPPData::setPPPDebug(bool set) {
272 writeConfig(GENERAL_GRP, PPP_DEBUG_OPTION, (int)set); 272 writeConfig(GENERAL_GRP, PPP_DEBUG_OPTION, (int)set);
273} 273}
274 274
275 275
276bool PPPData::getPPPDebug() { 276bool PPPData::getPPPDebug() {
277 return (bool)readNumConfig(GENERAL_GRP, PPP_DEBUG_OPTION, false); 277 return (bool)readNumConfig(GENERAL_GRP, PPP_DEBUG_OPTION, false);
278} 278}
279 279
280 280
281void PPPData::set_xserver_exit_disconnect(bool set) { 281void PPPData::set_xserver_exit_disconnect(bool set) {
282 writeConfig(GENERAL_GRP, DISCONNECT_KEY, (int) set); 282 writeConfig(GENERAL_GRP, DISCONNECT_KEY, (int) set);
283} 283}
284 284
285 285
286bool PPPData::quit_on_disconnect() { 286bool PPPData::quit_on_disconnect() {
287 return (bool) readNumConfig(GENERAL_GRP, QUITONDISCONNECT_KEY, false); 287 return (bool) readNumConfig(GENERAL_GRP, QUITONDISCONNECT_KEY, false);
288} 288}
289 289
290 290
291void PPPData::set_quit_on_disconnect(bool set) { 291void PPPData::set_quit_on_disconnect(bool set) {
292 writeConfig(GENERAL_GRP, QUITONDISCONNECT_KEY, (int) set); 292 writeConfig(GENERAL_GRP, QUITONDISCONNECT_KEY, (int) set);
293} 293}
294 294
295 295
296bool PPPData::get_show_log_window() { 296bool PPPData::get_show_log_window() {
297 return (bool) readNumConfig (GENERAL_GRP, SHOWLOGWIN_KEY, false); 297 return (bool) readNumConfig (GENERAL_GRP, SHOWLOGWIN_KEY, false);
298} 298}
299 299
300 300
301void PPPData::set_show_log_window(bool set) { 301void PPPData::set_show_log_window(bool set) {
302 writeConfig(GENERAL_GRP, SHOWLOGWIN_KEY, (int) set); 302 writeConfig(GENERAL_GRP, SHOWLOGWIN_KEY, (int) set);
303} 303}
304 304
305 305
306bool PPPData::automatic_redial() { 306bool PPPData::automatic_redial() {
307 return (bool) readNumConfig(GENERAL_GRP, AUTOREDIAL_KEY, FALSE); 307 return (bool) readNumConfig(GENERAL_GRP, AUTOREDIAL_KEY, FALSE);
308} 308}
309 309
310 310
311void PPPData::set_automatic_redial(bool set) { 311void PPPData::set_automatic_redial(bool set) {
312 writeConfig(GENERAL_GRP, AUTOREDIAL_KEY, (int) set); 312 writeConfig(GENERAL_GRP, AUTOREDIAL_KEY, (int) set);
313} 313}
314 314
315 315
316// bool PPPData::get_iconify_on_connect() { 316// bool PPPData::get_iconify_on_connect() {
317// return (bool) readNumConfig(GENERAL_GRP, ICONIFY_ON_CONNECT_KEY, TRUE); 317// return (bool) readNumConfig(GENERAL_GRP, ICONIFY_ON_CONNECT_KEY, TRUE);
318// } 318// }
319 319
320 320
321// void PPPData::set_iconify_on_connect(bool set) { 321// void PPPData::set_iconify_on_connect(bool set) {
322// writeConfig(GENERAL_GRP, ICONIFY_ON_CONNECT_KEY, (int) set); 322// writeConfig(GENERAL_GRP, ICONIFY_ON_CONNECT_KEY, (int) set);
323// } 323// }
324 324
325 325
326// bool PPPData::get_dock_into_panel() { 326// bool PPPData::get_dock_into_panel() {
327// return (bool) readNumConfig(GENERAL_GRP, DOCKING_KEY, false); 327// return (bool) readNumConfig(GENERAL_GRP, DOCKING_KEY, false);
328// } 328// }
329 329
330 330
331// void PPPData::set_dock_into_panel(bool set) { 331// void PPPData::set_dock_into_panel(bool set) {
332// writeConfig(GENERAL_GRP, DOCKING_KEY, (int) set); 332// writeConfig(GENERAL_GRP, DOCKING_KEY, (int) set);
333// } 333// }
334 334
335 335
336QString PPPData::pppdVersion() { 336QString PPPData::pppdVersion() {
337 return QString("%1.%2.%3").arg(pppdVer).arg(pppdMod).arg(pppdPatch); 337 return QString("%1.%2.%3").arg(pppdVer).arg(pppdMod).arg(pppdPatch);
338} 338}
339 339
340bool PPPData::pppdVersionMin(int ver, int mod, int patch) { 340bool PPPData::pppdVersionMin(int ver, int mod, int patch) {
341 // check if pppd version fulfills minimum requirement 341 // check if pppd version fulfills minimum requirement
342 return (pppdVer > ver 342 return (pppdVer > ver
343 || (pppdVer == ver && pppdMod > mod) 343 || (pppdVer == ver && pppdMod > mod)
344 || (pppdVer == ver && pppdMod == mod && pppdPatch >= patch)); 344 || (pppdVer == ver && pppdMod == mod && pppdPatch >= patch));
345} 345}
346 346
347int PPPData::pppdTimeout() { 347int PPPData::pppdTimeout() {
348 return readNumConfig(GENERAL_GRP, PPPDTIMEOUT_KEY, PPPD_TIMEOUT); 348 return readNumConfig(GENERAL_GRP, PPPDTIMEOUT_KEY, PPPD_TIMEOUT);
349} 349}
350 350
351 351
352void PPPData::setpppdTimeout(int n) { 352void PPPData::setpppdTimeout(int n) {
353 writeConfig(GENERAL_GRP, PPPDTIMEOUT_KEY, n); 353 writeConfig(GENERAL_GRP, PPPDTIMEOUT_KEY, n);
354} 354}
355 355
356 356
357const QString PPPData::modemDevice() { 357const QString PPPData::modemDevice() {
358 return readConfig (modemGroup(), MODEMDEV_KEY, "/dev/modem" ); 358 return readConfig (modemGroup(), MODEMDEV_KEY, "/dev/modem" );
359} 359}
360 360
361 361
362// const QString PPPData::modemName() 362// const QString PPPData::modemName()
363// { 363// {
364// return readConfig(modemGroup(), MODEMNAME_KEY); 364// return readConfig(modemGroup(), MODEMNAME_KEY);
365// } 365// }
366 366
367// bool PPPData::setModemName(const QString &n) { 367// bool PPPData::setModemName(const QString &n) {
368// qDebug("Setting modem name to >%s<", n.latin1()); 368// odebug << "Setting modem name to >" << n.latin1() << "<" << oendl;
369// _modemName = n; 369// _modemName = n;
370// writeConfig(cgroup, MODEMNAME_KEY, n); 370// writeConfig(cgroup, MODEMNAME_KEY, n);
371// return true; //FIXME 371// return true; //FIXME
372// } 372// }
373 373
374// bool PPPData::changeModemName(const QString &n) { 374// bool PPPData::changeModemName(const QString &n) {
375// qDebug("Setting modem name to >%s<", n.latin1()); 375// odebug << "Setting modem name to >" << n.latin1() << "<" << oendl;
376// _modemName = n; 376// _modemName = n;
377// writeConfig(modemGroup(), MODEMNAME_KEY, n); 377// writeConfig(modemGroup(), MODEMNAME_KEY, n);
378// return true; //FIXME 378// return true; //FIXME
379// } 379// }
380 380
381bool PPPData::setModemDevice(const QString &n) { 381bool PPPData::setModemDevice(const QString &n) {
382 qDebug("Setting modem dev to >%s<", n.latin1()); 382 odebug << "Setting modem dev to >" << n.latin1() << "<" << oendl;
383 writeConfig(modemGroup(), MODEMDEV_KEY, n); 383 writeConfig(modemGroup(), MODEMDEV_KEY, n);
384 return true; //FIXME 384 return true; //FIXME
385} 385}
386 386
387 387
388const QString PPPData::flowcontrol() { 388const QString PPPData::flowcontrol() {
389 return readConfig(modemGroup(), FLOWCONTROL_KEY, "CRTSCTS"); 389 return readConfig(modemGroup(), FLOWCONTROL_KEY, "CRTSCTS");
390} 390}
391 391
392 392
393void PPPData::setFlowcontrol(const QString &n) { 393void PPPData::setFlowcontrol(const QString &n) {
394 writeConfig(modemGroup(), FLOWCONTROL_KEY, n); 394 writeConfig(modemGroup(), FLOWCONTROL_KEY, n);
395} 395}
396 396
397 397
398const QString PPPData::speed() { 398const QString PPPData::speed() {
399 QString s = readConfig(modemGroup(), SPEED_KEY, "57600"); 399 QString s = readConfig(modemGroup(), SPEED_KEY, "57600");
400 // undo the damage of a bug in former versions. It left an empty Speed= 400 // undo the damage of a bug in former versions. It left an empty Speed=
401 // entry in kppprc. kppp did set the serial port to 57600 as default but 401 // entry in kppprc. kppp did set the serial port to 57600 as default but
402 // pppd wouldn't receive the speed via the command line. 402 // pppd wouldn't receive the speed via the command line.
403 if(s.toUInt() == 0) 403 if(s.toUInt() == 0)
404 s = "57600"; 404 s = "57600";
405 return s; 405 return s;
406} 406}
407 407
408 408
409void PPPData::setSpeed(const QString &n) { 409void PPPData::setSpeed(const QString &n) {
410 writeConfig(modemGroup(), SPEED_KEY, n); 410 writeConfig(modemGroup(), SPEED_KEY, n);
411} 411}
412 412
413 413
414#if 0 414#if 0
415void PPPData::setUseCDLine(const int n) { 415void PPPData::setUseCDLine(const int n) {
416 writeConfig(modemGroup(),USECDLINE_KEY,n); 416 writeConfig(modemGroup(),USECDLINE_KEY,n);
417} 417}
418 418
419 419
420int PPPData::UseCDLine() { 420int PPPData::UseCDLine() {
421 return readNumConfig(modemGroup(),USECDLINE_KEY,0); 421 return readNumConfig(modemGroup(),USECDLINE_KEY,0);
422} 422}
423#endif 423#endif
424 424
425const QString PPPData::modemEscapeStr() { 425const QString PPPData::modemEscapeStr() {
426 return readConfig(modemGroup(),ESCAPESTR_KEY,"+++"); 426 return readConfig(modemGroup(),ESCAPESTR_KEY,"+++");
427} 427}
428 428
429 429
430void PPPData::setModemEscapeStr(const QString &n) { 430void PPPData::setModemEscapeStr(const QString &n) {
431 writeConfig(modemGroup(),ESCAPESTR_KEY,n); 431 writeConfig(modemGroup(),ESCAPESTR_KEY,n);
432} 432}
433 433
434 434
435const QString PPPData::modemEscapeResp() { 435const QString PPPData::modemEscapeResp() {
436 return readConfig(modemGroup(),ESCAPERESP_KEY,"OK"); 436 return readConfig(modemGroup(),ESCAPERESP_KEY,"OK");
437} 437}
438 438
439 439
440void PPPData::setModemEscapeResp(const QString &n) { 440void PPPData::setModemEscapeResp(const QString &n) {
441 writeConfig(modemGroup(),ESCAPERESP_KEY,n); 441 writeConfig(modemGroup(),ESCAPERESP_KEY,n);
442} 442}
443 443
444 444
445int PPPData::modemEscapeGuardTime() { 445int PPPData::modemEscapeGuardTime() {
446 return readNumConfig(modemGroup(),ESCAPEGUARDTIME_KEY,50); 446 return readNumConfig(modemGroup(),ESCAPEGUARDTIME_KEY,50);
447} 447}
448 448
449 449
450void PPPData::setModemEscapeGuardTime(int n) { 450void PPPData::setModemEscapeGuardTime(int n) {
451 writeConfig(modemGroup(),ESCAPEGUARDTIME_KEY,n); 451 writeConfig(modemGroup(),ESCAPEGUARDTIME_KEY,n);
452} 452}
453 453
454 454
455bool PPPData::modemLockFile() { 455bool PPPData::modemLockFile() {
456 return readNumConfig(modemGroup(), LOCKFILE_KEY, 1); 456 return readNumConfig(modemGroup(), LOCKFILE_KEY, 1);
457} 457}
458 458
459 459
460void PPPData::setModemLockFile(bool set) { 460void PPPData::setModemLockFile(bool set) {
461 writeConfig(modemGroup(), LOCKFILE_KEY, set); 461 writeConfig(modemGroup(), LOCKFILE_KEY, set);
462} 462}
463 463
464 464
465int PPPData::modemTimeout() { 465int PPPData::modemTimeout() {
466 return readNumConfig(modemGroup(), TIMEOUT_KEY, MODEM_TIMEOUT); 466 return readNumConfig(modemGroup(), TIMEOUT_KEY, MODEM_TIMEOUT);
467} 467}
468 468
469 469
470void PPPData::setModemTimeout(int n) { 470void PPPData::setModemTimeout(int n) {
471 writeConfig(modemGroup(), TIMEOUT_KEY, n); 471 writeConfig(modemGroup(), TIMEOUT_KEY, n);
472} 472}
473 473
474 474
475int PPPData::modemToneDuration() { 475int PPPData::modemToneDuration() {
476 return readNumConfig(modemGroup(), TONEDURATION_KEY,MODEM_TONEDURATION); 476 return readNumConfig(modemGroup(), TONEDURATION_KEY,MODEM_TONEDURATION);
477} 477}
478 478
@@ -646,421 +646,421 @@ QString PPPData::volumeHigh() {
646 QString tmp = readConfig(modemGroup(), VOLUME_HIGH, "M1L3"); 646 QString tmp = readConfig(modemGroup(), VOLUME_HIGH, "M1L3");
647 if(tmp == "M1L4") 647 if(tmp == "M1L4")
648 tmp = "M1L3"; 648 tmp = "M1L3";
649 return tmp; 649 return tmp;
650} 650}
651 651
652 652
653void PPPData::setVolumeHigh(const QString &s) { 653void PPPData::setVolumeHigh(const QString &s) {
654 writeConfig(modemGroup(), VOLUME_HIGH, s); 654 writeConfig(modemGroup(), VOLUME_HIGH, s);
655} 655}
656 656
657 657
658QString PPPData::volumeInitString() { 658QString PPPData::volumeInitString() {
659 QString s; 659 QString s;
660 660
661 switch(volume()) { 661 switch(volume()) {
662 case 0: 662 case 0:
663 s = volumeOff(); 663 s = volumeOff();
664 break; 664 break;
665 case 1: 665 case 1:
666 s = volumeMedium(); 666 s = volumeMedium();
667 break; 667 break;
668 case 2: 668 case 2:
669 s = volumeHigh(); 669 s = volumeHigh();
670 break; 670 break;
671 default: 671 default:
672 s = volumeMedium(); 672 s = volumeMedium();
673 } 673 }
674 674
675 return s; 675 return s;
676} 676}
677 677
678 678
679int PPPData::volume() { 679int PPPData::volume() {
680 return readNumConfig(modemGroup(), VOLUME_KEY, 1); 680 return readNumConfig(modemGroup(), VOLUME_KEY, 1);
681} 681}
682 682
683 683
684void PPPData::setVolume(int i) { 684void PPPData::setVolume(int i) {
685 writeConfig(modemGroup(), VOLUME_KEY, i); 685 writeConfig(modemGroup(), VOLUME_KEY, i);
686} 686}
687 687
688int PPPData::waitForDialTone() { 688int PPPData::waitForDialTone() {
689 return readNumConfig(modemGroup(), DIALTONEWAIT_KEY, 1); 689 return readNumConfig(modemGroup(), DIALTONEWAIT_KEY, 1);
690} 690}
691 691
692void PPPData::setWaitForDialTone(int i) { 692void PPPData::setWaitForDialTone(int i) {
693 writeConfig(modemGroup(), DIALTONEWAIT_KEY, i); 693 writeConfig(modemGroup(), DIALTONEWAIT_KEY, i);
694} 694}
695 695
696void PPPData::setModemAnswerStr(const QString &n) { 696void PPPData::setModemAnswerStr(const QString &n) {
697 writeConfig(modemGroup(), ANSWERSTR_KEY, n); 697 writeConfig(modemGroup(), ANSWERSTR_KEY, n);
698} 698}
699 699
700 700
701const QString PPPData::modemRingResp() { 701const QString PPPData::modemRingResp() {
702 return readConfig(modemGroup(), RINGRESP_KEY, "RING"); 702 return readConfig(modemGroup(), RINGRESP_KEY, "RING");
703} 703}
704 704
705 705
706void PPPData::setModemRingResp(const QString &n) { 706void PPPData::setModemRingResp(const QString &n) {
707 writeConfig(modemGroup(), RINGRESP_KEY, n); 707 writeConfig(modemGroup(), RINGRESP_KEY, n);
708} 708}
709 709
710 710
711const QString PPPData::modemAnswerResp() { 711const QString PPPData::modemAnswerResp() {
712 return readConfig(modemGroup(), ANSWERRESP_KEY, "CONNECT"); 712 return readConfig(modemGroup(), ANSWERRESP_KEY, "CONNECT");
713} 713}
714 714
715 715
716void PPPData::setModemAnswerResp(const QString &n) { 716void PPPData::setModemAnswerResp(const QString &n) {
717 writeConfig(modemGroup(), ANSWERRESP_KEY, n); 717 writeConfig(modemGroup(), ANSWERRESP_KEY, n);
718} 718}
719 719
720 720
721const QString PPPData::enter() { 721const QString PPPData::enter() {
722 return readConfig(modemGroup(), ENTER_KEY, "CR"); 722 return readConfig(modemGroup(), ENTER_KEY, "CR");
723} 723}
724 724
725 725
726void PPPData::setEnter(const QString &n) { 726void PPPData::setEnter(const QString &n) {
727 writeConfig(modemGroup(), ENTER_KEY, n); 727 writeConfig(modemGroup(), ENTER_KEY, n);
728} 728}
729 729
730 730
731// 731//
732// functions to set/return account information 732// functions to set/return account information
733// 733//
734 734
735//returns number of accounts 735//returns number of accounts
736int PPPData::count() const { 736int PPPData::count() const {
737 return highcount + 1; 737 return highcount + 1;
738} 738}
739 739
740 740
741bool PPPData::setAccount(const QString &aname) { 741bool PPPData::setAccount(const QString &aname) {
742 qDebug("setting account to >%s<", aname.latin1()); 742 odebug << "setting account to >" << aname.latin1() << "<" << oendl;
743 for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) { 743 for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) {
744 cgroup = *it; 744 cgroup = *it;
745 qDebug("PPPData::setAccount %s", cgroup.latin1()); 745 odebug << "PPPData::setAccount " << cgroup.latin1() << "" << oendl;
746 qDebug( "iterator %s", (*it).latin1() ); 746 odebug << "iterator " << (*it).latin1() << "" << oendl;
747 if(accname() == aname) { 747 if(accname() == aname) {
748 qDebug("SUCCESS"); 748 odebug << "SUCCESS" << oendl;
749 return true; 749 return true;
750 } 750 }
751 751
752 } 752 }
753 qDebug("FAILURE"); 753 odebug << "FAILURE" << oendl;
754 return false; 754 return false;
755} 755}
756 756
757/* 757/*
758bool PPPData::setAccountbyIndex(int i) { 758bool PPPData::setAccountbyIndex(int i) {
759 if(i >= 0 && i <= highcount) { 759 if(i >= 0 && i <= highcount) {
760 QString tmp; 760 QString tmp;
761 tmp.sprintf("%s%i", ACCOUNT_GRP, i); 761 tmp.sprintf("%s%i", ACCOUNT_GRP, i);
762 if (_deleted.find(tmp)!=_deleted.end()) return false; 762 if (_deleted.find(tmp)!=_deleted.end()) return false;
763 caccount = i; 763 caccount = i;
764 cgroup = tmp; 764 cgroup = tmp;
765 return true; 765 return true;
766 } 766 }
767 return false; 767 return false;
768} 768}
769*/ 769*/
770 770
771bool PPPData::isUniqueAccname(const QString &n) { 771bool PPPData::isUniqueAccname(const QString &n) {
772 QString save_cgroup = cgroup; 772 QString save_cgroup = cgroup;
773 for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) { 773 for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) {
774 cgroup = *it; 774 cgroup = *it;
775 qDebug("PPPData::setAccount %s", cgroup.latin1()); 775 odebug << "PPPData::setAccount " << cgroup.latin1() << "" << oendl;
776 qDebug( "%s \n", (*it).latin1() ); 776 odebug << "" << (*it).latin1() << " \n" << oendl;
777 if(accname() == n && cgroup != save_cgroup) { 777 if(accname() == n && cgroup != save_cgroup) {
778 cgroup = save_cgroup; 778 cgroup = save_cgroup;
779 qDebug("SUCCESS"); 779 odebug << "SUCCESS" << oendl;
780 return false; 780 return false;
781 } 781 }
782 782
783 } 783 }
784 cgroup = save_cgroup; 784 cgroup = save_cgroup;
785 return true; 785 return true;
786} 786}
787 787
788 788
789bool PPPData::isUniqueDevname(const QString &n) { 789bool PPPData::isUniqueDevname(const QString &n) {
790 QString save_mName = _modemName; 790 QString save_mName = _modemName;
791 qDebug("PPPData::isUniqueDevname checking if %s is unique", n.latin1()); 791 odebug << "PPPData::isUniqueDevname checking if " << n.latin1() << " is unique" << oendl;
792 for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) { 792 for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) {
793 _modemName = *it; 793 _modemName = *it;
794 qDebug("PPPData::isUniqueDevname %s == %s", n.latin1() , devname().latin1()); 794 odebug << "PPPData::isUniqueDevname " << n.latin1() << " == " << devname().latin1() << "" << oendl;
795 if(devname() == n && _modemName != save_mName) { 795 if(devname() == n && _modemName != save_mName) {
796 _modemName = save_mName; 796 _modemName = save_mName;
797 qDebug("NOT UNIQUE"); 797 odebug << "NOT UNIQUE" << oendl;
798 return false; 798 return false;
799 } 799 }
800 800
801 } 801 }
802 _modemName = save_mName; 802 _modemName = save_mName;
803 return true; 803 return true;
804} 804}
805 805
806 806
807bool PPPData::deleteAccount() { 807bool PPPData::deleteAccount() {
808 // FIXME: check if this account exists in a config... 808 // FIXME: check if this account exists in a config...
809 Config cfg = PPPData::config(); 809 Config cfg = PPPData::config();
810 cfg.setGroup(cgroup); 810 cfg.setGroup(cgroup);
811 cfg.clearGroup(); 811 cfg.clearGroup();
812 accountList.remove(cgroup); 812 accountList.remove(cgroup);
813 813
814 QString key; 814 QString key;
815 QStringList keys; 815 QStringList keys;
816 for( QMap<QString,QString>::Iterator it = stringEntries.begin(); 816 for( QMap<QString,QString>::Iterator it = stringEntries.begin();
817 it != stringEntries.end(); ++it ){ 817 it != stringEntries.end(); ++it ){
818 QString val = it.data(); 818 QString val = it.data();
819 key = it.key(); 819 key = it.key();
820 keys = QStringList::split( "SEPARATOR", key ); 820 keys = QStringList::split( "SEPARATOR", key );
821 if(keys[0]==cgroup){ 821 if(keys[0]==cgroup){
822 stringEntries.remove( it ); 822 stringEntries.remove( it );
823 qDebug("deleting >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.latin1() ); 823 odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl;
824 } 824 }
825 } 825 }
826 for( QMap<QString,int>::Iterator it = intEntries.begin(); 826 for( QMap<QString,int>::Iterator it = intEntries.begin();
827 it != intEntries.end(); ++it ){ 827 it != intEntries.end(); ++it ){
828 int val = it.data(); 828 int val = it.data();
829 key = it.key(); 829 key = it.key();
830 keys = QStringList::split( "SEPARATOR", key ); 830 keys = QStringList::split( "SEPARATOR", key );
831 if(keys[0]==cgroup){ 831 if(keys[0]==cgroup){
832 intEntries.remove( it ); 832 intEntries.remove( it );
833 qDebug("deleting >%s< key >%s< value >%i<", keys[0].latin1(), keys[1].latin1(), val ); 833 odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val << "<" << oendl;
834 } 834 }
835 } 835 }
836 for( QMap<QString,QStringList>::Iterator it = listEntries.begin(); 836 for( QMap<QString,QStringList>::Iterator it = listEntries.begin();
837 it != listEntries.end(); ++it ){ 837 it != listEntries.end(); ++it ){
838 QStringList val = it.data(); 838 QStringList val = it.data();
839 key = it.key(); 839 key = it.key();
840 if(keys[0]==cgroup){ 840 if(keys[0]==cgroup){
841 listEntries.remove( it ); 841 listEntries.remove( it );
842 sepEntries.remove( key ); 842 sepEntries.remove( key );
843 qDebug("deleting >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.join("").latin1() ); 843 odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.join("").latin1() << "<" << oendl;
844 } 844 }
845 } 845 }
846 846
847 return true; 847 return true;
848} 848}
849 849
850 850
851bool PPPData::deleteAccount(const QString &aname) { 851bool PPPData::deleteAccount(const QString &aname) {
852 if(!setAccount(aname)) 852 if(!setAccount(aname))
853 return false; 853 return false;
854 854
855 deleteAccount(); 855 deleteAccount();
856 856
857 return true; 857 return true;
858} 858}
859 859
860 860
861int PPPData::newaccount() { 861int PPPData::newaccount() {
862 862
863 qDebug("PPPData::newaccount highcount %i/%i",highcount,MAX_ACCOUNTS); 863 odebug << "PPPData::newaccount highcount " << highcount << "/" << MAX_ACCOUNTS << "" << oendl;
864// if(!config) open(); 864// if(!config) open();
865// if (highcount >= MAX_ACCOUNTS) return -1; 865// if (highcount >= MAX_ACCOUNTS) return -1;
866 866
867 867
868 QString tmp; 868 QString tmp;
869 tmp.sprintf("%s%i", ACCOUNT_GRP, ++highcount); 869 tmp.sprintf("%s%i", ACCOUNT_GRP, ++highcount);
870 cgroup = QString(tmp); 870 cgroup = QString(tmp);
871 accountList << tmp; 871 accountList << tmp;
872 qDebug("PPPData::newaccount() Group: >%s<",cgroup.latin1()); 872 odebug << "PPPData::newaccount() Group: >" << cgroup.latin1() << "<" << oendl;
873 setpppdArgumentDefaults(); 873 setpppdArgumentDefaults();
874 return highcount; 874 return highcount;
875} 875}
876 876
877int PPPData::copyaccount(const QString&) { 877int PPPData::copyaccount(const QString&) {
878// FIXME: PPPData::copyaccount 878// FIXME: PPPData::copyaccount
879// if(highcount >= MAX_ACCOUNTS) 879// if(highcount >= MAX_ACCOUNTS)
880 return -1; 880 return -1;
881 881
882// setAccountbyIndex(i); 882// setAccountbyIndex(i);
883 883
884// QMap <QString, QString> map = config->entryMap(cgroup); 884// QMap <QString, QString> map = config->entryMap(cgroup);
885// QMap <QString, QString>::ConstIterator it = map.begin(); 885// QMap <QString, QString>::ConstIterator it = map.begin();
886 886
887// QString newname = QObject::tr("%1_copy").arg(accname()); 887// QString newname = QObject::tr("%1_copy").arg(accname());
888 888
889// newaccount(); 889// newaccount();
890 890
891// while (it != map.end()) { 891// while (it != map.end()) {
892// config->writeEntry(it.key(), *it); 892// config->writeEntry(it.key(), *it);
893// it++; 893// it++;
894// } 894// }
895 895
896// setAccname(newname); 896// setAccname(newname);
897 897
898// return caccount; 898// return caccount;
899} 899}
900 900
901 901
902const QString PPPData::accname() { 902const QString PPPData::accname() {
903 return readConfig(cgroup, NAME_KEY); 903 return readConfig(cgroup, NAME_KEY);
904} 904}
905 905
906void PPPData::setAccname(const QString &n) { 906void PPPData::setAccname(const QString &n) {
907 if(!cgroup.isNull()) { 907 if(!cgroup.isNull()) {
908 // are we manipulating the default account's name ? then change it, too. 908 // are we manipulating the default account's name ? then change it, too.
909 bool def = accname() == defaultAccount(); 909 bool def = accname() == defaultAccount();
910 writeConfig(cgroup, NAME_KEY, n); 910 writeConfig(cgroup, NAME_KEY, n);
911 if (def) 911 if (def)
912 setDefaultAccount(n); 912 setDefaultAccount(n);
913 } 913 }
914 writeConfig(cgroup, NAME_KEY, n); 914 writeConfig(cgroup, NAME_KEY, n);
915} 915}
916 916
917 917
918#define SEPARATOR_CHAR '&' 918#define SEPARATOR_CHAR '&'
919QStringList &PPPData::phonenumbers() { 919QStringList &PPPData::phonenumbers() {
920 920
921 readListConfig(cgroup, PHONENUMBER_KEY, phonelist, SEPARATOR_CHAR); 921 readListConfig(cgroup, PHONENUMBER_KEY, phonelist, SEPARATOR_CHAR);
922 return phonelist; 922 return phonelist;
923 923
924} 924}
925 925
926 926
927const QString PPPData::phonenumber() { 927const QString PPPData::phonenumber() {
928 return readConfig(cgroup, PHONENUMBER_KEY); 928 return readConfig(cgroup, PHONENUMBER_KEY);
929} 929}
930 930
931 931
932void PPPData::setPhonenumber(const QString &n) { 932void PPPData::setPhonenumber(const QString &n) {
933 writeConfig(cgroup, PHONENUMBER_KEY, n); 933 writeConfig(cgroup, PHONENUMBER_KEY, n);
934} 934}
935 935
936 936
937const QString PPPData::dialPrefix() { 937const QString PPPData::dialPrefix() {
938 return readConfig(cgroup, DIAL_PREFIX_KEY, ""); 938 return readConfig(cgroup, DIAL_PREFIX_KEY, "");
939} 939}
940 940
941 941
942void PPPData::setDialPrefix(const QString &s) { 942void PPPData::setDialPrefix(const QString &s) {
943 writeConfig(cgroup, DIAL_PREFIX_KEY, s); 943 writeConfig(cgroup, DIAL_PREFIX_KEY, s);
944} 944}
945 945
946 946
947int PPPData::authMethod() { 947int PPPData::authMethod() {
948 return readNumConfig(cgroup, AUTH_KEY, 0); 948 return readNumConfig(cgroup, AUTH_KEY, 0);
949} 949}
950 950
951 951
952void PPPData::setAuthMethod(int value) { 952void PPPData::setAuthMethod(int value) {
953 writeConfig(cgroup, AUTH_KEY, value); 953 writeConfig(cgroup, AUTH_KEY, value);
954} 954}
955 955
956 956
957const QString PPPData::storedUsername() { 957const QString PPPData::storedUsername() {
958 return readConfig(cgroup, STORED_USERNAME_KEY, ""); 958 return readConfig(cgroup, STORED_USERNAME_KEY, "");
959} 959}
960 960
961 961
962void PPPData::setStoredUsername(const QString &b) { 962void PPPData::setStoredUsername(const QString &b) {
963 writeConfig(cgroup, STORED_USERNAME_KEY, b); 963 writeConfig(cgroup, STORED_USERNAME_KEY, b);
964} 964}
965 965
966 966
967const QString PPPData::storedPassword() { 967const QString PPPData::storedPassword() {
968 qDebug("getting stored pw"); 968 odebug << "getting stored pw" << oendl;
969 qDebug("g %s", cgroup.latin1() ); 969 odebug << "g " << cgroup.latin1() << "" << oendl;
970 qDebug("k %s", STORED_PASSWORD_KEY); 970 odebug << "k " << STORED_PASSWORD_KEY << "" << oendl;
971 return readConfig(cgroup, STORED_PASSWORD_KEY, ""); 971 return readConfig(cgroup, STORED_PASSWORD_KEY, "");
972} 972}
973 973
974 974
975void PPPData::setStoredPassword(const QString &b) { 975void PPPData::setStoredPassword(const QString &b) {
976 writeConfig(cgroup, STORED_PASSWORD_KEY, b); 976 writeConfig(cgroup, STORED_PASSWORD_KEY, b);
977} 977}
978 978
979 979
980bool PPPData::storePassword() { 980bool PPPData::storePassword() {
981 return (bool)readNumConfig(cgroup, STORE_PASSWORD_KEY, 1); 981 return (bool)readNumConfig(cgroup, STORE_PASSWORD_KEY, 1);
982} 982}
983 983
984 984
985const QString PPPData::command_before_connect() { 985const QString PPPData::command_before_connect() {
986 return readConfig(cgroup, BEFORE_CONNECT_KEY); 986 return readConfig(cgroup, BEFORE_CONNECT_KEY);
987} 987}
988 988
989 989
990void PPPData::setCommand_before_connect(const QString &n) { 990void PPPData::setCommand_before_connect(const QString &n) {
991 writeConfig(cgroup, BEFORE_CONNECT_KEY, n); 991 writeConfig(cgroup, BEFORE_CONNECT_KEY, n);
992} 992}
993 993
994 994
995void PPPData::setStorePassword(bool b) { 995void PPPData::setStorePassword(bool b) {
996 writeConfig(cgroup, STORE_PASSWORD_KEY, (int)b); 996 writeConfig(cgroup, STORE_PASSWORD_KEY, (int)b);
997} 997}
998 998
999 999
1000const QString PPPData::command_on_connect() { 1000const QString PPPData::command_on_connect() {
1001 return readConfig(cgroup, COMMAND_KEY); 1001 return readConfig(cgroup, COMMAND_KEY);
1002} 1002}
1003 1003
1004 1004
1005void PPPData::setCommand_on_connect(const QString &n) { 1005void PPPData::setCommand_on_connect(const QString &n) {
1006 writeConfig(cgroup, COMMAND_KEY, n); 1006 writeConfig(cgroup, COMMAND_KEY, n);
1007} 1007}
1008 1008
1009 1009
1010const QString PPPData::command_on_disconnect() { 1010const QString PPPData::command_on_disconnect() {
1011 return readConfig(cgroup, DISCONNECT_COMMAND_KEY); 1011 return readConfig(cgroup, DISCONNECT_COMMAND_KEY);
1012} 1012}
1013 1013
1014 1014
1015void PPPData::setCommand_on_disconnect(const QString &n) { 1015void PPPData::setCommand_on_disconnect(const QString &n) {
1016 writeConfig(cgroup, DISCONNECT_COMMAND_KEY, n); 1016 writeConfig(cgroup, DISCONNECT_COMMAND_KEY, n);
1017} 1017}
1018 1018
1019 1019
1020const QString PPPData::command_before_disconnect() { 1020const QString PPPData::command_before_disconnect() {
1021 return readConfig(cgroup, BEFORE_DISCONNECT_KEY); 1021 return readConfig(cgroup, BEFORE_DISCONNECT_KEY);
1022} 1022}
1023 1023
1024 1024
1025void PPPData::setCommand_before_disconnect(const QString &n) { 1025void PPPData::setCommand_before_disconnect(const QString &n) {
1026 writeConfig(cgroup, BEFORE_DISCONNECT_KEY, n); 1026 writeConfig(cgroup, BEFORE_DISCONNECT_KEY, n);
1027} 1027}
1028 1028
1029 1029
1030const QString PPPData::ipaddr() { 1030const QString PPPData::ipaddr() {
1031 return readConfig(cgroup, IPADDR_KEY); 1031 return readConfig(cgroup, IPADDR_KEY);
1032} 1032}
1033 1033
1034 1034
1035void PPPData::setIpaddr(const QString &n) { 1035void PPPData::setIpaddr(const QString &n) {
1036 writeConfig(cgroup, IPADDR_KEY, n); 1036 writeConfig(cgroup, IPADDR_KEY, n);
1037} 1037}
1038 1038
1039 1039
1040const QString PPPData::subnetmask() { 1040const QString PPPData::subnetmask() {
1041 return readConfig(cgroup, SUBNETMASK_KEY); 1041 return readConfig(cgroup, SUBNETMASK_KEY);
1042} 1042}
1043 1043
1044 1044
1045void PPPData::setSubnetmask(const QString &n) { 1045void PPPData::setSubnetmask(const QString &n) {
1046 writeConfig(cgroup, SUBNETMASK_KEY, n); 1046 writeConfig(cgroup, SUBNETMASK_KEY, n);
1047} 1047}
1048 1048
1049 1049
1050bool PPPData::autoname() { 1050bool PPPData::autoname() {
1051 return (bool) readNumConfig(cgroup, AUTONAME_KEY, false); 1051 return (bool) readNumConfig(cgroup, AUTONAME_KEY, false);
1052} 1052}
1053 1053
1054 1054
1055void PPPData::setAutoname(bool set) { 1055void PPPData::setAutoname(bool set) {
1056 writeConfig(cgroup, AUTONAME_KEY, (int) set); 1056 writeConfig(cgroup, AUTONAME_KEY, (int) set);
1057} 1057}
1058 1058
1059 1059
1060bool PPPData::AcctEnabled() { 1060bool PPPData::AcctEnabled() {
1061 return (bool) readNumConfig(cgroup, ACCTENABLED_KEY, false); 1061 return (bool) readNumConfig(cgroup, ACCTENABLED_KEY, false);
1062} 1062}
1063 1063
1064 1064
1065void PPPData::setAcctEnabled(bool set) { 1065void PPPData::setAcctEnabled(bool set) {
1066 writeConfig(cgroup, ACCTENABLED_KEY, (int) set); 1066 writeConfig(cgroup, ACCTENABLED_KEY, (int) set);
@@ -1236,260 +1236,260 @@ void PPPData::setpppdArgumentDefaults() {
1236 // QColor in, 1236 // QColor in,
1237 // QColor out) 1237 // QColor out)
1238// { 1238// {
1239// if(config) { 1239// if(config) {
1240// config->setGroup(GRAPH_GRP); 1240// config->setGroup(GRAPH_GRP);
1241// config->writeEntry(GENABLED, enable); 1241// config->writeEntry(GENABLED, enable);
1242// // config->writeEntry(GCOLOR_BG, bg); 1242// // config->writeEntry(GCOLOR_BG, bg);
1243// // config->writeEntry(GCOLOR_TEXT, text); 1243// // config->writeEntry(GCOLOR_TEXT, text);
1244// // config->writeEntry(GCOLOR_IN, in); 1244// // config->writeEntry(GCOLOR_IN, in);
1245// // config->writeEntry(GCOLOR_OUT, out); 1245// // config->writeEntry(GCOLOR_OUT, out);
1246// } 1246// }
1247// } 1247// }
1248 1248
1249// void PPPData::graphingOptions(bool &enable, 1249// void PPPData::graphingOptions(bool &enable,
1250 // QColor &bg, 1250 // QColor &bg,
1251 // QColor &text, 1251 // QColor &text,
1252 // QColor &in, 1252 // QColor &in,
1253 // QColor &out) 1253 // QColor &out)
1254// { 1254// {
1255// QColor c; 1255// QColor c;
1256 1256
1257// if(config) { 1257// if(config) {
1258// config->setGroup(GRAPH_GRP); 1258// config->setGroup(GRAPH_GRP);
1259// enable = config->readBoolEntry(GENABLED, true); 1259// enable = config->readBoolEntry(GENABLED, true);
1260// bg = Qt::white; 1260// bg = Qt::white;
1261// //bg = config->readColorEntry(GCOLOR_BG, &c); 1261// //bg = config->readColorEntry(GCOLOR_BG, &c);
1262// text = Qt::black; 1262// text = Qt::black;
1263// //text = config->readColorEntry(GCOLOR_TEXT, &c); 1263// //text = config->readColorEntry(GCOLOR_TEXT, &c);
1264// in = Qt::blue; 1264// in = Qt::blue;
1265// //in = config->readColorEntry(GCOLOR_IN, &c); 1265// //in = config->readColorEntry(GCOLOR_IN, &c);
1266// out = Qt::red; 1266// out = Qt::red;
1267// //out = config->readColorEntry(GCOLOR_OUT, &c); 1267// //out = config->readColorEntry(GCOLOR_OUT, &c);
1268// } 1268// }
1269// } 1269// }
1270 1270
1271 1271
1272// bool PPPData::graphingEnabled() { 1272// bool PPPData::graphingEnabled() {
1273// return (bool) readNumConfig(GRAPH_GRP, GENABLED, true); 1273// return (bool) readNumConfig(GRAPH_GRP, GENABLED, true);
1274// } 1274// }
1275 1275
1276 1276
1277 1277
1278// 1278//
1279//functions to change/set the child pppd process info 1279//functions to change/set the child pppd process info
1280// 1280//
1281bool PPPData::pppdRunning() const { 1281bool PPPData::pppdRunning() const {
1282 return pppdisrunning; 1282 return pppdisrunning;
1283} 1283}
1284 1284
1285void PPPData::setpppdRunning(bool set) { 1285void PPPData::setpppdRunning(bool set) {
1286 pppdisrunning = set; 1286 pppdisrunning = set;
1287} 1287}
1288 1288
1289int PPPData::pppdError() const { 1289int PPPData::pppdError() const {
1290 return pppderror; 1290 return pppderror;
1291} 1291}
1292 1292
1293void PPPData::setpppdError(int err) { 1293void PPPData::setpppdError(int err) {
1294 pppderror = err; 1294 pppderror = err;
1295} 1295}
1296 1296
1297QString PPPData::modemGroup() 1297QString PPPData::modemGroup()
1298{ 1298{
1299 if (_modemName.isEmpty()) 1299 if (_modemName.isEmpty())
1300 _modemName = deviceList[0]; 1300 _modemName = deviceList[0];
1301 return _modemName; 1301 return _modemName;
1302} 1302}
1303 1303
1304 1304
1305QMap<QString,QString> PPPData::getConfiguredInterfaces() 1305QMap<QString,QString> PPPData::getConfiguredInterfaces()
1306{ 1306{
1307 QMap<QString,QString> ifaces; 1307 QMap<QString,QString> ifaces;
1308 Config config = PPPData::config(); 1308 Config config = PPPData::config();
1309 config.setGroup(ACCLIST_GRP); 1309 config.setGroup(ACCLIST_GRP);
1310 int count = config.readNumEntry( ACCOUNTS_COUNT, -1 ); 1310 int count = config.readNumEntry( ACCOUNTS_COUNT, -1 );
1311 QString accGrp, dev, acc; 1311 QString accGrp, dev, acc;
1312 for (int i = 0; i < count; i++){ 1312 for (int i = 0; i < count; i++){
1313 accGrp = QString("%1_%1").arg(ACCLIST_GRP).arg(i); 1313 accGrp = QString("%1_%1").arg(ACCLIST_GRP).arg(i);
1314 config.setGroup(accGrp); 1314 config.setGroup(accGrp);
1315 dev = config.readEntry( ACOUNTS_DEV, "error" ); 1315 dev = config.readEntry( ACOUNTS_DEV, "error" );
1316 acc = config.readEntry( ACOUNTS_ACC, "error" ); 1316 acc = config.readEntry( ACOUNTS_ACC, "error" );
1317 ifaces.insert( dev, acc ); 1317 ifaces.insert( dev, acc );
1318 } 1318 }
1319 1319
1320 return ifaces; 1320 return ifaces;
1321} 1321}
1322 1322
1323void PPPData::setConfiguredInterfaces( QMap<QString,QString> ifaces ) 1323void PPPData::setConfiguredInterfaces( QMap<QString,QString> ifaces )
1324{ 1324{
1325 QMap<QString,QString>::Iterator it; 1325 QMap<QString,QString>::Iterator it;
1326 int i = 0; 1326 int i = 0;
1327 Config cfg = config(); 1327 Config cfg = config();
1328 for( it = ifaces.begin(); it != ifaces.end(); ++it ){ 1328 for( it = ifaces.begin(); it != ifaces.end(); ++it ){
1329 cfg.setGroup(QString("%1_%1").arg(ACCLIST_GRP).arg(i++)); 1329 cfg.setGroup(QString("%1_%1").arg(ACCLIST_GRP).arg(i++));
1330 cfg.writeEntry( ACOUNTS_DEV, it.key() ); 1330 cfg.writeEntry( ACOUNTS_DEV, it.key() );
1331 cfg.writeEntry( ACOUNTS_ACC, it.data() ); 1331 cfg.writeEntry( ACOUNTS_ACC, it.data() );
1332 qDebug("I %i",i); 1332 odebug << "I " << i << "" << oendl;
1333 } 1333 }
1334 cfg.setGroup( ACCLIST_GRP ); 1334 cfg.setGroup( ACCLIST_GRP );
1335 qDebug("saved %i account settings", i); 1335 odebug << "saved " << i << " account settings" << oendl;
1336 cfg.writeEntry( ACCOUNTS_COUNT, i ); 1336 cfg.writeEntry( ACCOUNTS_COUNT, i );
1337 1337
1338} 1338}
1339 1339
1340/** 1340/**
1341 * pppd's getword() function knows about escape characters. 1341 * pppd's getword() function knows about escape characters.
1342 * If we write the username and password to the secrets file 1342 * If we write the username and password to the secrets file
1343 * we'll therefore have to escape back slashes. 1343 * we'll therefore have to escape back slashes.
1344 */ 1344 */
1345QString PPPData::encodeWord(const QString &s) { 1345QString PPPData::encodeWord(const QString &s) {
1346 QString r = s; 1346 QString r = s;
1347 r.replace(QRegExp("\\"), "\\\\"); 1347 r.replace(QRegExp("\\"), "\\\\");
1348 return r; 1348 return r;
1349} 1349}
1350 1350
1351QStringList PPPData::getDevicesList() 1351QStringList PPPData::getDevicesList()
1352{ 1352{
1353 Config cfg("NetworkSetupPPP"); 1353 Config cfg("NetworkSetupPPP");
1354 cfg.setGroup("Devices_General"); 1354 cfg.setGroup("Devices_General");
1355 return cfg.readListEntry(DEVICES_LIST,DEVICES_LIST_SEP); 1355 return cfg.readListEntry(DEVICES_LIST,DEVICES_LIST_SEP);
1356} 1356}
1357 1357
1358QStringList PPPData::getAccountList() 1358QStringList PPPData::getAccountList()
1359{ 1359{
1360 QStringList list; 1360 QStringList list;
1361 QString save_cgroup; 1361 QString save_cgroup;
1362 save_cgroup = cgroup; 1362 save_cgroup = cgroup;
1363 for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) { 1363 for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) {
1364 cgroup = *it; 1364 cgroup = *it;
1365 list << accname(); 1365 list << accname();
1366 } 1366 }
1367 cgroup = save_cgroup; 1367 cgroup = save_cgroup;
1368 return list; 1368 return list;
1369}; 1369};
1370 1370
1371 1371
1372const QString PPPData::devname() 1372const QString PPPData::devname()
1373{ 1373{
1374 QString tmp = readConfig(modemGroup(), MODEMNAME_KEY ); 1374 QString tmp = readConfig(modemGroup(), MODEMNAME_KEY );
1375 qDebug("PPPData::devname() of %s is %s", modemGroup().latin1(), tmp.latin1()); 1375 odebug << "PPPData::devname() of " << modemGroup().latin1() << " is " << tmp.latin1() << "" << oendl;
1376 return tmp; 1376 return tmp;
1377} 1377}
1378 1378
1379void PPPData::setDevname(const QString &n) { 1379void PPPData::setDevname(const QString &n) {
1380 // if(!cgroup.isNull()) { 1380 // if(!cgroup.isNull()) {
1381// // are we manipulating the default account's name ? then change it, too. 1381// // are we manipulating the default account's name ? then change it, too.
1382// bool def = accname() == defaultAccount(); 1382// bool def = accname() == defaultAccount();
1383// writeConfig(cgroup, NAME_KEY, n); 1383// writeConfig(cgroup, NAME_KEY, n);
1384// if (def) 1384// if (def)
1385// setDefaultAccount(n); 1385// setDefaultAccount(n);
1386// } 1386// }
1387 writeConfig(modemGroup(), MODEMNAME_KEY, n ); 1387 writeConfig(modemGroup(), MODEMNAME_KEY, n );
1388} 1388}
1389 1389
1390 1390
1391bool PPPData::setDevice(const QString &dev ) 1391bool PPPData::setDevice(const QString &dev )
1392{ 1392{
1393 qDebug("setting device to >%s<", dev.latin1()); 1393 odebug << "setting device to >" << dev.latin1() << "<" << oendl;
1394 QString save_mName = _modemName; 1394 QString save_mName = _modemName;
1395 for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) { 1395 for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) {
1396 _modemName = *it; 1396 _modemName = *it;
1397 qDebug("PPPData::setDevice %s is named %s", _modemName.latin1(), devname().latin1() ); 1397 odebug << "PPPData::setDevice " << _modemName.latin1() << " is named " << devname().latin1() << "" << oendl;
1398 qDebug( "iterator %s", (*it).latin1() ); 1398 odebug << "iterator " << (*it).latin1() << "" << oendl;
1399 if(devname() == dev) { 1399 if(devname() == dev) {
1400 qDebug("SUCCESS"); 1400 odebug << "SUCCESS" << oendl;
1401 return true; 1401 return true;
1402 } 1402 }
1403 1403
1404 } 1404 }
1405 _modemName = save_mName; 1405 _modemName = save_mName;
1406 qDebug("FAILURE"); 1406 odebug << "FAILURE" << oendl;
1407 return false; 1407 return false;
1408} 1408}
1409 1409
1410bool PPPData::deleteDevice() 1410bool PPPData::deleteDevice()
1411{ 1411{
1412 // FIXME: check if this account exists in a config... 1412 // FIXME: check if this account exists in a config...
1413 Config cfg = PPPData::config(); 1413 Config cfg = PPPData::config();
1414 cfg.setGroup(modemGroup()); 1414 cfg.setGroup(modemGroup());
1415 cfg.clearGroup(); 1415 cfg.clearGroup();
1416 deviceList.remove(modemGroup()); 1416 deviceList.remove(modemGroup());
1417 1417
1418 QString key; 1418 QString key;
1419 QStringList keys; 1419 QStringList keys;
1420 for( QMap<QString,QString>::Iterator it = stringEntries.begin(); 1420 for( QMap<QString,QString>::Iterator it = stringEntries.begin();
1421 it != stringEntries.end(); ++it ){ 1421 it != stringEntries.end(); ++it ){
1422 QString val = it.data(); 1422 QString val = it.data();
1423 key = it.key(); 1423 key = it.key();
1424 keys = QStringList::split( "SEPARATOR", key ); 1424 keys = QStringList::split( "SEPARATOR", key );
1425 if(keys[0]==modemGroup()){ 1425 if(keys[0]==modemGroup()){
1426 stringEntries.remove( it ); 1426 stringEntries.remove( it );
1427 qDebug("deleting >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.latin1() ); 1427 odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl;
1428 } 1428 }
1429 } 1429 }
1430 for( QMap<QString,int>::Iterator it = intEntries.begin(); 1430 for( QMap<QString,int>::Iterator it = intEntries.begin();
1431 it != intEntries.end(); ++it ){ 1431 it != intEntries.end(); ++it ){
1432 int val = it.data(); 1432 int val = it.data();
1433 key = it.key(); 1433 key = it.key();
1434 keys = QStringList::split( "SEPARATOR", key ); 1434 keys = QStringList::split( "SEPARATOR", key );
1435 if(keys[0]==modemGroup()){ 1435 if(keys[0]==modemGroup()){
1436 intEntries.remove( it ); 1436 intEntries.remove( it );
1437 qDebug("deleting >%s< key >%s< value >%i<", keys[0].latin1(), keys[1].latin1(), val ); 1437 odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val << "<" << oendl;
1438 } 1438 }
1439 } 1439 }
1440 for( QMap<QString,QStringList>::Iterator it = listEntries.begin(); 1440 for( QMap<QString,QStringList>::Iterator it = listEntries.begin();
1441 it != listEntries.end(); ++it ){ 1441 it != listEntries.end(); ++it ){
1442 QStringList val = it.data(); 1442 QStringList val = it.data();
1443 key = it.key(); 1443 key = it.key();
1444 if(keys[0]==modemGroup()){ 1444 if(keys[0]==modemGroup()){
1445 listEntries.remove( it ); 1445 listEntries.remove( it );
1446 sepEntries.remove( key ); 1446 sepEntries.remove( key );
1447 qDebug("deleting >%s< key >%s< value >%s<", keys[0].latin1(), keys[1].latin1(), val.join("").latin1() ); 1447 odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.join("").latin1() << "<" << oendl;
1448 } 1448 }
1449 } 1449 }
1450 1450
1451 return true; 1451 return true;
1452 1452
1453} 1453}
1454 1454
1455bool PPPData::deleteDevice(const QString &dev) 1455bool PPPData::deleteDevice(const QString &dev)
1456{ 1456{
1457 if(!setDevice(dev)) 1457 if(!setDevice(dev))
1458 return false; 1458 return false;
1459 1459
1460 return deleteDevice(); 1460 return deleteDevice();
1461} 1461}
1462 1462
1463int PPPData::newdevice() 1463int PPPData::newdevice()
1464{ 1464{
1465 1465
1466 qDebug("PPPData::newdevice highcount %i",highcountdev); 1466 odebug << "PPPData::newdevice highcount " << highcountdev << "" << oendl;
1467 1467
1468 1468
1469 QString tmp; 1469 QString tmp;
1470 tmp.sprintf("%s%i", MODEM_GRP, ++highcountdev); 1470 tmp.sprintf("%s%i", MODEM_GRP, ++highcountdev);
1471 _modemName = QString(tmp); 1471 _modemName = QString(tmp);
1472 deviceList << tmp; 1472 deviceList << tmp;
1473 qDebug("PPPData::newdevice() Group: >%s<",cgroup.latin1()); 1473 odebug << "PPPData::newdevice() Group: >" << cgroup.latin1() << "<" << oendl;
1474 return highcountdev; 1474 return highcountdev;
1475} 1475}
1476 1476
1477int PPPData::copydevice(const QString&) 1477int PPPData::copydevice(const QString&)
1478{ 1478{
1479 return false; 1479 return false;
1480} 1480}
1481 1481
1482 1482
1483QStringList PPPData::getDevicesNamesList() 1483QStringList PPPData::getDevicesNamesList()
1484{ 1484{
1485 QStringList list; 1485 QStringList list;
1486 QString save_mName = _modemName; 1486 QString save_mName = _modemName;
1487 qDebug("PPPData::getDevicesNamesList has %s", deviceList.join("---").latin1()); 1487 odebug << "PPPData::getDevicesNamesList has " << deviceList.join("---").latin1() << "" << oendl;
1488 for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) { 1488 for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) {
1489 _modemName = *it; 1489 _modemName = *it;
1490 qDebug("PPPData::getDevicesNamesList adding %s as %s",_modemName.latin1(), devname().latin1()); 1490 odebug << "PPPData::getDevicesNamesList adding " << _modemName.latin1() << " as " << devname().latin1() << "" << oendl;
1491 list << devname(); 1491 list << devname();
1492 } 1492 }
1493 _modemName = save_mName; 1493 _modemName = save_mName;
1494 return list; 1494 return list;
1495}; 1495};
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 @@
1 1
2#include "modem.h" 2#include "modem.h"
3#include "pppconfig.h" 3#include "pppconfig.h"
4#include "pppmodule.h" 4#include "pppmodule.h"
5#include "pppdata.h" 5#include "pppdata.h"
6#include "interfaceinformationppp.h" 6#include "interfaceinformationppp.h"
7#include "interfaceppp.h" 7#include "interfaceppp.h"
8 8
9/* OPIE */ 9/* OPIE */
10#include <qpe/config.h> 10#include <qpe/config.h>
11#include <qpe/qpeapplication.h> 11#include <qpe/qpeapplication.h>
12 12
13/* QT */ 13/* QT */
14 14
15/* STD */ 15/* STD */
16#include <errno.h> 16#include <errno.h>
17#include <signal.h> 17#include <signal.h>
18 18
19// don't polute global namespace 19// don't polute global namespace
20namespace 20namespace
21{ 21{
22 /* 22 /*
23 * If network settings is qutting and we've ppp 23 * If network settings is qutting and we've ppp
24 * devices open we need to save the pid_t the PPData 24 * devices open we need to save the pid_t the PPData
25 * and the interface number 25 * and the interface number
26 */ 26 */
27 struct Connection 27 struct Connection
28 { 28 {
29 pid_t pid; 29 pid_t pid;
30 QString device; 30 QString device;
31 QString name; 31 QString name;
32 }; 32 };
33 class InterfaceKeeper 33 class InterfaceKeeper
34 { 34 {
35 public: 35 public:
36 InterfaceKeeper(); 36 InterfaceKeeper();
37 ~InterfaceKeeper(); 37 ~InterfaceKeeper();
38 38
39 void addInterface( pid_t, const QString& pppDev, const QString& name ); 39 void addInterface( pid_t, const QString& pppDev, const QString& name );
40 QMap<QString, Connection> interfaces()const; // will check if still available 40 QMap<QString, Connection> interfaces()const; // will check if still available
41 private: 41 private:
42 bool isAvailable( pid_t )const; 42 bool isAvailable( pid_t )const;
43 QMap<QString, Connection> m_interfaces; 43 QMap<QString, Connection> m_interfaces;
44 }; 44 };
45} 45}
46 46
47 47
48/** 48/**
49 * Constructor, find all of the possible interfaces 49 * Constructor, find all of the possible interfaces
50 * We also need to restore the state.. it could be that 50 * We also need to restore the state.. it could be that
51 * an interface was up while closing the application 51 * an interface was up while closing the application
52 * we need to be able to shut it down... 52 * we need to be able to shut it down...
53 */ 53 */
54PPPModule::PPPModule() : Module() 54PPPModule::PPPModule() : Module()
55{ 55{
56 InterfaceKeeper inFace; 56 InterfaceKeeper inFace;
57 QMap<QString,Connection> running = inFace.interfaces(); 57 QMap<QString,Connection> running = inFace.interfaces();
58 QStringList handledInterfaceNames; 58 QStringList handledInterfaceNames;
59 59
60 QMap<QString,QString> ifaces = PPPData::getConfiguredInterfaces(); 60 QMap<QString,QString> ifaces = PPPData::getConfiguredInterfaces();
61 QMap<QString,QString>::Iterator it; 61 QMap<QString,QString>::Iterator it;
62 InterfacePPP *iface; 62 InterfacePPP *iface;
63 qDebug("getting interfaces"); 63 odebug << "getting interfaces" << oendl;
64 for( it = ifaces.begin(); it != ifaces.end(); ++it ) 64 for( it = ifaces.begin(); it != ifaces.end(); ++it )
65 { 65 {
66 qDebug("ifaces %s %s", it.key().latin1(), it.data().latin1() ); 66 odebug << "ifaces " << it.key().latin1() << " " << it.data().latin1() << "" << oendl;
67 iface = new InterfacePPP( 0, it.key() ); 67 iface = new InterfacePPP( 0, it.key() );
68 iface->setHardwareName( it.data() ); 68 iface->setHardwareName( it.data() );
69 list.append( (Interface*)iface ); 69 list.append( (Interface*)iface );
70 70
71 // check if (*it) is one of the running ifaces 71 // check if (*it) is one of the running ifaces
72 if ( running.contains( it.data() ) ) 72 if ( running.contains( it.data() ) )
73 { 73 {
74 qDebug("iface is running %s", it.key().latin1() ); 74 odebug << "iface is running " << it.key().latin1() << "" << oendl;
75 handledInterfaceNames << running[it.data()].device; 75 handledInterfaceNames << running[it.data()].device;
76 iface->setStatus( true ); 76 iface->setStatus( true );
77 iface->setPPPDpid( running[it.data()].pid ); 77 iface->setPPPDpid( running[it.data()].pid );
78 iface->modem()->setPPPDevice( running[it.data()].device ); 78 iface->modem()->setPPPDevice( running[it.data()].device );
79 iface->refresh(); 79 iface->refresh();
80 } 80 }
81 } 81 }
82 82
83 setHandledInterfaceNames( handledInterfaceNames ); 83 setHandledInterfaceNames( handledInterfaceNames );
84} 84}
85 85
86/** 86/**
87 * Delete any interfaces that we own. 87 * Delete any interfaces that we own.
88 */ 88 */
89PPPModule::~PPPModule() 89PPPModule::~PPPModule()
90{ 90{
91 qDebug("PPPModule::~PPPModule() " ); 91 odebug << "PPPModule::~PPPModule() " << oendl;
92 QMap<QString,QString> ifaces; 92 QMap<QString,QString> ifaces;
93 InterfaceKeeper keeper; 93 InterfaceKeeper keeper;
94 Interface *i; 94 Interface *i;
95 for ( i=list.first(); i != 0; i=list.next() ) 95 for ( i=list.first(); i != 0; i=list.next() )
96 { 96 {
97 /* if online save the state */ 97 /* if online save the state */
98 if ( i->getStatus() ) 98 if ( i->getStatus() )
99 { 99 {
100 qDebug("Iface %s is still up", i->getHardwareName().latin1() ); 100 odebug << "Iface " << i->getHardwareName().latin1() << " is still up" << oendl;
101 InterfacePPP* ppp = static_cast<InterfacePPP*>(i); 101 InterfacePPP* ppp = static_cast<InterfacePPP*>(i);
102 keeper.addInterface( ppp->pppPID(), ppp->pppDev(), ppp->getHardwareName() ); 102 keeper.addInterface( ppp->pppPID(), ppp->pppDev(), ppp->getHardwareName() );
103 } 103 }
104 ifaces.insert( i->getInterfaceName(), i->getHardwareName() ); 104 ifaces.insert( i->getInterfaceName(), i->getHardwareName() );
105 delete i; 105 delete i;
106 } 106 }
107 PPPData::setConfiguredInterfaces( ifaces ); 107 PPPData::setConfiguredInterfaces( ifaces );
108} 108}
109 109
110/** 110/**
111 * Change the current profile 111 * Change the current profile
112 */ 112 */
113void PPPModule::setProfile(const QString &newProfile) 113void PPPModule::setProfile(const QString &newProfile)
114{ 114{
115 profile = newProfile; 115 profile = newProfile;
116} 116}
117 117
118/** 118/**
119 * get the icon name for this device. 119 * get the icon name for this device.
120 * @param Interface* can be used in determining the icon. 120 * @param Interface* can be used in determining the icon.
121 * @return QString the icon name (minus .png, .gif etc) 121 * @return QString the icon name (minus .png, .gif etc)
122 */ 122 */
123QString PPPModule::getPixmapName(Interface* ) 123QString PPPModule::getPixmapName(Interface* )
124{ 124{
125 return "ppp"; 125 return "ppp";
126} 126}
127 127
128/** 128/**
129 * Check to see if the interface i is owned by this module. 129 * Check to see if the interface i is owned by this module.
130 * @param Interface* interface to check against 130 * @param Interface* interface to check against
131 * @return bool true if i is owned by this module, false otherwise. 131 * @return bool true if i is owned by this module, false otherwise.
132 */ 132 */
133bool PPPModule::isOwner(Interface *i) 133bool PPPModule::isOwner(Interface *i)
134{ 134{
135 return list.find( i ) != -1; 135 return list.find( i ) != -1;
136} 136}
137 137
138/** 138/**
139 * Create, and return the WLANConfigure Module 139 * Create, and return the WLANConfigure Module
140 * @return QWidget* pointer to this modules configure. 140 * @return QWidget* pointer to this modules configure.
141 */ 141 */
142QWidget *PPPModule::configure(Interface *i) 142QWidget *PPPModule::configure(Interface *i)
143{ 143{
144 qDebug("return ModemWidget"); 144 odebug << "return ModemWidget" << oendl;
145 PPPConfigWidget *pppconfig = new PPPConfigWidget( (InterfacePPP*)i, 145 PPPConfigWidget *pppconfig = new PPPConfigWidget( (InterfacePPP*)i,
146 0, "PPPConfig", false, 146 0, "PPPConfig", false,
147 (Qt::WDestructiveClose | Qt::WStyle_ContextHelp)); 147 (Qt::WDestructiveClose | Qt::WStyle_ContextHelp));
148 return pppconfig; 148 return pppconfig;
149} 149}
150 150
151/** 151/**
152 * Create, and return the Information Module 152 * Create, and return the Information Module
153 * @return QWidget* pointer to this modules info. 153 * @return QWidget* pointer to this modules info.
154 */ 154 */
155QWidget *PPPModule::information(Interface *i) 155QWidget *PPPModule::information(Interface *i)
156{ 156{
157 // We don't have any advanced pppd information widget yet :-D 157 // We don't have any advanced pppd information widget yet :-D
158 // TODO ^ 158 // TODO ^
159 159
160 return new InterfaceInformationPPP( 0, "InterfaceInformationPPP", i ); 160 return new InterfaceInformationPPP( 0, "InterfaceInformationPPP", i );
161} 161}
162 162
163/** 163/**
164 * Get all active (up or down) interfaces 164 * Get all active (up or down) interfaces
165 * @return QList<Interface> A list of interfaces that exsist that havn't 165 * @return QList<Interface> A list of interfaces that exsist that havn't
166 * been called by isOwner() 166 * been called by isOwner()
167 */ 167 */
168QList<Interface> PPPModule::getInterfaces() 168QList<Interface> PPPModule::getInterfaces()
169{ 169{
170 // List all of the files in the peer directory 170 // List all of the files in the peer directory
171 qDebug("PPPModule::getInterfaces"); 171 odebug << "PPPModule::getInterfaces" << oendl;
172 return list; 172 return list;
173} 173}
174 174
175/** 175/**
176 * Attempt to add a new interface as defined by name 176 * Attempt to add a new interface as defined by name
177 * @param name the name of the type of interface that should be created given 177 * @param name the name of the type of interface that should be created given
178 * by possibleNewInterfaces(); 178 * by possibleNewInterfaces();
179 * @return Interface* NULL if it was unable to be created. 179 * @return Interface* NULL if it was unable to be created.
180 */ 180 */
181Interface *PPPModule::addNewInterface(const QString &newInterface) 181Interface *PPPModule::addNewInterface(const QString &newInterface)
182{ 182{
183 183
184 InterfacePPP *ifaceppp; 184 InterfacePPP *ifaceppp;
185 Interface *iface; 185 Interface *iface;
186 ifaceppp = new InterfacePPP(); 186 ifaceppp = new InterfacePPP();
187 PPPConfigWidget imp(ifaceppp, 0, "PPPConfigImp", true); 187 PPPConfigWidget imp(ifaceppp, 0, "PPPConfigImp", true);
188 188
189 if( QPEApplication::execDialog( &imp ) == QDialog::Accepted ) 189 if( QPEApplication::execDialog( &imp ) == QDialog::Accepted )
190 { 190 {
191 iface = (InterfacePPP*) ifaceppp; 191 iface = (InterfacePPP*) ifaceppp;
192 iface->setModuleOwner( this ); 192 iface->setModuleOwner( this );
193 list.append( iface ); 193 list.append( iface );
194 return iface; 194 return iface;
195 } 195 }
196 else 196 else
197 { 197 {
198 delete ifaceppp; 198 delete ifaceppp;
199 iface = NULL; 199 iface = NULL;
200 } 200 }
201 return iface; 201 return iface;
202} 202}
203 203
204/** 204/**
205 * Attempts to remove the interface, doesn't delete i 205 * Attempts to remove the interface, doesn't delete i
206 * @return bool true if successful, false otherwise. 206 * @return bool true if successful, false otherwise.
207 */ 207 */
208bool PPPModule::remove(Interface *i) 208bool PPPModule::remove(Interface *i)
209{ 209{
210 return list.remove(i); 210 return list.remove(i);
211} 211}
212 212
213void PPPModule::possibleNewInterfaces(QMap<QString, QString> &newIfaces) 213void PPPModule::possibleNewInterfaces(QMap<QString, QString> &newIfaces)
214{ 214{
215 newIfaces.insert(QObject::tr("PPP") , 215 newIfaces.insert(QObject::tr("PPP") ,
216 QObject::tr("generic ppp device")); 216 QObject::tr("generic ppp device"));
217} 217}
218 218
219 219
220 220
221namespace 221namespace
222{ 222{
223 InterfaceKeeper::InterfaceKeeper( ) 223 InterfaceKeeper::InterfaceKeeper( )
224 {} 224 {}
225 InterfaceKeeper::~InterfaceKeeper() 225 InterfaceKeeper::~InterfaceKeeper()
226 { 226 {
227 Config cfg("ppp_plugin_keeper"); 227 Config cfg("ppp_plugin_keeper");
228 QStringList lst = cfg.groupList(); 228 QStringList lst = cfg.groupList();
229 for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) 229 for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
230 { 230 {
231 Connection con; 231 Connection con;
232 cfg.setGroup( (*it) ); 232 cfg.setGroup( (*it) );
233 cfg.clearGroup(); 233 cfg.clearGroup();
234 } 234 }
235 235
236 for (QMap<QString, Connection>::Iterator it = m_interfaces.begin(); it != m_interfaces.end(); ++it ) 236 for (QMap<QString, Connection>::Iterator it = m_interfaces.begin(); it != m_interfaces.end(); ++it )
237 { 237 {
238 Connection con = it.data(); 238 Connection con = it.data();
239 cfg.setGroup( con.name ); 239 cfg.setGroup( con.name );
240 cfg.writeEntry( "pid", con.pid ); 240 cfg.writeEntry( "pid", con.pid );
241 cfg.writeEntry( "device", con.device ); 241 cfg.writeEntry( "device", con.device );
242 } 242 }
243 } 243 }
244 void InterfaceKeeper::addInterface(pid_t pid, const QString& dev, const QString& name ) 244 void InterfaceKeeper::addInterface(pid_t pid, const QString& dev, const QString& name )
245 { 245 {
246 Connection con; 246 Connection con;
247 con.pid = pid; 247 con.pid = pid;
248 con.device = dev; 248 con.device = dev;
249 con.name = name; 249 con.name = name;
250 m_interfaces.insert( name, con ); 250 m_interfaces.insert( name, con );
251 } 251 }
252 QMap<QString, Connection> InterfaceKeeper::interfaces()const 252 QMap<QString, Connection> InterfaceKeeper::interfaces()const
253 { 253 {
254 Config cfg("ppp_plugin_keeper"); 254 Config cfg("ppp_plugin_keeper");
255 QMap<QString, Connection> ifaces; 255 QMap<QString, Connection> ifaces;
256 QStringList lst = cfg.groupList(); 256 QStringList lst = cfg.groupList();
257 for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) 257 for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
258 { 258 {
259 Connection con; 259 Connection con;
260 cfg.setGroup( (*it) ); 260 cfg.setGroup( (*it) );
261 con.name = (*it); 261 con.name = (*it);
262 con.pid = cfg.readNumEntry("pid"); 262 con.pid = cfg.readNumEntry("pid");
263 con.device = cfg.readEntry("device"); 263 con.device = cfg.readEntry("device");
264 qDebug(" %s %s %d", con.name.latin1(), con.device.latin1(), con.pid ); 264 odebug << " " << con.name.latin1() << " " << con.device.latin1() << " " << con.pid << "" << oendl;
265 265
266 if ( con.pid != -1 && isAvailable( con.pid ) ) 266 if ( con.pid != -1 && isAvailable( con.pid ) )
267 ifaces.insert( con.name, con ); 267 ifaces.insert( con.name, con );
268 } 268 }
269 return ifaces; 269 return ifaces;
270 } 270 }
271 bool InterfaceKeeper::isAvailable( pid_t p)const 271 bool InterfaceKeeper::isAvailable( pid_t p)const
272 { 272 {
273 if (::kill(p, 0 ) == 0 || errno != ESRCH ) 273 if (::kill(p, 0 ) == 0 || errno != ESRCH )
274 { 274 {
275 qDebug("isAvailable %d", p); 275 odebug << "isAvailable " << p << "" << oendl;
276 return true; 276 return true;
277 } 277 }
278 278
279 qDebug("notAvailable %d", p); 279 odebug << "notAvailable " << p << "" << oendl;
280 return false; 280 return false;
281 } 281 }
282 282
283} 283}
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 @@
1#include "infoimp.h" 1#include "infoimp.h"
2#include "wextensions.h" 2#include "wextensions.h"
3 3
4#include <qtimer.h> 4#include <qtimer.h>
5#include <qprogressbar.h> 5#include <qprogressbar.h>
6#include <qlabel.h> 6#include <qlabel.h>
7 7
8/** 8/**
9 * Constructor. If wireless extensions are enabled on device name then 9 * Constructor. If wireless extensions are enabled on device name then
10 * start a timer that every second will update the information. 10 * start a timer that every second will update the information.
11 */ 11 */
12WlanInfoImp::WlanInfoImp( QWidget* parent, const char* name, WFlags fl): WlanInfo(parent, name, fl){ 12WlanInfoImp::WlanInfoImp( QWidget* parent, const char* name, WFlags fl): WlanInfo(parent, name, fl){
13 WExtensions *wExtensions = new WExtensions(name); 13 WExtensions *wExtensions = new WExtensions(name);
14 if(!wExtensions->doesHaveWirelessExtensions()){ 14 if(!wExtensions->doesHaveWirelessExtensions()){
15 delete wExtensions; 15 delete wExtensions;
16 qDebug("WlanInfoImp::No wireless extension"); 16 odebug << "WlanInfoImp::No wireless extension" << oendl;
17 return; 17 return;
18 } 18 }
19 delete wExtensions; 19 delete wExtensions;
20 timer = new QTimer( this ); 20 timer = new QTimer( this );
21 connect( timer, SIGNAL(timeout()), this, SLOT(update())); 21 connect( timer, SIGNAL(timeout()), this, SLOT(update()));
22 timer->start( 1000, false ); 22 timer->start( 1000, false );
23} 23}
24 24
25/** 25/**
26 * Updates the information about the wireless device. 26 * Updates the information about the wireless device.
27 */ 27 */
28void WlanInfoImp::update(){ 28void WlanInfoImp::update(){
29 WExtensions *wExtensions = new WExtensions(this->name()); 29 WExtensions *wExtensions = new WExtensions(this->name());
30 if(!wExtensions->doesHaveWirelessExtensions()){ 30 if(!wExtensions->doesHaveWirelessExtensions()){
31 qDebug("No extension"); 31 odebug << "No extension" << oendl;
32 delete wExtensions; 32 delete wExtensions;
33 timer->stop(); 33 timer->stop();
34 return; 34 return;
35 } 35 }
36 essidLabel->setText(wExtensions->essid()); 36 essidLabel->setText(wExtensions->essid());
37 apLabel->setText(wExtensions->ap()); 37 apLabel->setText(wExtensions->ap());
38 stationLabel->setText(wExtensions->station()); 38 stationLabel->setText(wExtensions->station());
39 modeLabel->setText(wExtensions->mode()); 39 modeLabel->setText(wExtensions->mode());
40 channelLabel->setText(QString("%1").arg(wExtensions->channel())); 40 channelLabel->setText(QString("%1").arg(wExtensions->channel()));
41 int signal = 0; 41 int signal = 0;
42 int noise = 0; 42 int noise = 0;
43 int quality = 0; 43 int quality = 0;
44 wExtensions->stats(signal, noise, quality); 44 wExtensions->stats(signal, noise, quality);
45 if(signalProgressBar->progress() != signal) 45 if(signalProgressBar->progress() != signal)
46 signalProgressBar->setProgress(signal); 46 signalProgressBar->setProgress(signal);
47 if(noiseProgressBar->progress() != noise) 47 if(noiseProgressBar->progress() != noise)
48 noiseProgressBar->setProgress(noise); 48 noiseProgressBar->setProgress(noise);
49 if(qualityProgressBar->progress() != quality) 49 if(qualityProgressBar->progress() != quality)
50 qualityProgressBar->setProgress(quality); 50 qualityProgressBar->setProgress(quality);
51 rateLabel->setText(QString("%1 Mb/s").arg(wExtensions->rate())); 51 rateLabel->setText(QString("%1 Mb/s").arg(wExtensions->rate()));
52 delete wExtensions; 52 delete wExtensions;
53} 53}
54 54
55// infoimp.cpp 55// infoimp.cpp
56 56
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 @@
19WExtensions::WExtensions(QString interfaceName): hasWirelessExtensions(false), interface(interfaceName) { 19WExtensions::WExtensions(QString interfaceName): hasWirelessExtensions(false), interface(interfaceName) {
20 fd = socket( AF_INET, SOCK_DGRAM, 0 ); 20 fd = socket( AF_INET, SOCK_DGRAM, 0 );
21 if(fd == -1) 21 if(fd == -1)
22 return; 22 return;
23 23
24 const char* buffer[200]; 24 const char* buffer[200];
25 memset( &iwr, 0, sizeof( iwr ) ); 25 memset( &iwr, 0, sizeof( iwr ) );
26 iwr.u.essid.pointer = (caddr_t) buffer; 26 iwr.u.essid.pointer = (caddr_t) buffer;
27 iwr.u.essid.length = IW_ESSID_MAX_SIZE; 27 iwr.u.essid.length = IW_ESSID_MAX_SIZE;
28 iwr.u.essid.flags = 0; 28 iwr.u.essid.flags = 0;
29 29
30 // check if it is an IEEE 802.11 standard conform 30 // check if it is an IEEE 802.11 standard conform
31 // wireless device by sending SIOCGIWESSID 31 // wireless device by sending SIOCGIWESSID
32 // which also gives back the Extended Service Set ID 32 // which also gives back the Extended Service Set ID
33 // (see IEEE 802.11 for more information) 33 // (see IEEE 802.11 for more information)
34 34
35 const char* iname = interface.latin1(); 35 const char* iname = interface.latin1();
36 strcpy( iwr.ifr_ifrn.ifrn_name, (const char *)iname ); 36 strcpy( iwr.ifr_ifrn.ifrn_name, (const char *)iname );
37 if ( 0 == ioctl( fd, SIOCGIWESSID, &iwr ) ) 37 if ( 0 == ioctl( fd, SIOCGIWESSID, &iwr ) )
38 hasWirelessExtensions = true; 38 hasWirelessExtensions = true;
39} 39}
40 40
41/** 41/**
42 * @return QString the station name of the access point. 42 * @return QString the station name of the access point.
43 */ 43 */
44QString WExtensions::station(){ 44QString WExtensions::station(){
45 if(!hasWirelessExtensions) 45 if(!hasWirelessExtensions)
46 return QString(); 46 return QString();
47 const char* buffer[200]; 47 const char* buffer[200];
48 iwr.u.data.pointer = (caddr_t) buffer; 48 iwr.u.data.pointer = (caddr_t) buffer;
49 iwr.u.data.length = IW_ESSID_MAX_SIZE; 49 iwr.u.data.length = IW_ESSID_MAX_SIZE;
50 iwr.u.data.flags = 0; 50 iwr.u.data.flags = 0;
51 if ( 0 == ioctl( fd, SIOCGIWNICKN, &iwr )){ 51 if ( 0 == ioctl( fd, SIOCGIWNICKN, &iwr )){
52 iwr.u.data.pointer[(unsigned int) iwr.u.data.length-1] = '\0'; 52 iwr.u.data.pointer[(unsigned int) iwr.u.data.length-1] = '\0';
53 return QString(iwr.u.data.pointer); 53 return QString(iwr.u.data.pointer);
54 } 54 }
55 return QString(); 55 return QString();
56} 56}
57 57
58/** 58/**
59 * @return QString the essid of the host 802.11 access point. 59 * @return QString the essid of the host 802.11 access point.
60 */ 60 */
61QString WExtensions::essid(){ 61QString WExtensions::essid(){
62 if(!hasWirelessExtensions) 62 if(!hasWirelessExtensions)
63 return QString(); 63 return QString();
64 if ( 0 == ioctl( fd, SIOCGIWESSID, &iwr )){ 64 if ( 0 == ioctl( fd, SIOCGIWESSID, &iwr )){
65 iwr.u.essid.pointer[(unsigned int) iwr.u.essid.length] = '\0'; 65 iwr.u.essid.pointer[(unsigned int) iwr.u.essid.length] = '\0';
66 return QString(iwr.u.essid.pointer); 66 return QString(iwr.u.essid.pointer);
67 } 67 }
68 return QString(); 68 return QString();
69} 69}
70 70
71/** 71/**
72 * @return QString the mode of interface 72 * @return QString the mode of interface
73 */ 73 */
74QString WExtensions::mode(){ 74QString WExtensions::mode(){
75 if(!hasWirelessExtensions) 75 if(!hasWirelessExtensions)
76 return QString(); 76 return QString();
77 if ( 0 == ioctl( fd, SIOCGIWMODE, &iwr ) ) 77 if ( 0 == ioctl( fd, SIOCGIWMODE, &iwr ) )
78 return QString("%1").arg(iwr.u.mode == IW_MODE_ADHOC ? "Ad-Hoc" : "Managed"); 78 return QString("%1").arg(iwr.u.mode == IW_MODE_ADHOC ? "Ad-Hoc" : "Managed");
79 return QString(); 79 return QString();
80} 80}
81 81
82/** 82/**
83 * Get the frequency that the interface is running at. 83 * Get the frequency that the interface is running at.
84 * @return int the frequency that the interfacae is running at. 84 * @return int the frequency that the interfacae is running at.
85 */ 85 */
86double WExtensions::frequency(){ 86double WExtensions::frequency(){
87 if(!hasWirelessExtensions) 87 if(!hasWirelessExtensions)
88 return 0; 88 return 0;
89 if ( 0 == ioctl( fd, SIOCGIWFREQ, &iwr )) 89 if ( 0 == ioctl( fd, SIOCGIWFREQ, &iwr ))
90 return (double( iwr.u.freq.m ) * pow( 10, iwr.u.freq.e ) / 1000000000); 90 return (double( iwr.u.freq.m ) * pow( 10, iwr.u.freq.e ) / 1000000000);
91 return 0; 91 return 0;
92} 92}
93 93
94/** 94/**
95 * Get the channel that the interface is running at. 95 * Get the channel that the interface is running at.
96 * @return int the channel that the interfacae is running at. 96 * @return int the channel that the interfacae is running at.
97 */ 97 */
98int WExtensions::channel(){ 98int WExtensions::channel(){
99 if(!hasWirelessExtensions) 99 if(!hasWirelessExtensions)
100 return 0; 100 return 0;
101 if ( 0 != ioctl( fd, SIOCGIWFREQ, &iwr )) 101 if ( 0 != ioctl( fd, SIOCGIWFREQ, &iwr ))
102 return 0; 102 return 0;
103 103
104 // http://www.elanix.com/pdf/an137e.pdf 104 // http://www.elanix.com/pdf/an137e.pdf
105 105
106 double num = (double( iwr.u.freq.m ) * pow( 10, iwr.u.freq.e ) / 1000000000); 106 double num = (double( iwr.u.freq.m ) * pow( 10, iwr.u.freq.e ) / 1000000000);
107 double left = 2.401; 107 double left = 2.401;
108 double right = 2.416; 108 double right = 2.416;
109 for(int channel = 1; channel<= 15; channel++){ 109 for(int channel = 1; channel<= 15; channel++){
110 if( num >= left && num <= right ) 110 if( num >= left && num <= right )
111 return channel; 111 return channel;
112 left += 0.005; 112 left += 0.005;
113 right += 0.005; 113 right += 0.005;
114 } 114 }
115 qDebug(QString("Unknown frequency: %1, returning -1 for the channel.").arg(num).latin1()); 115 odebug << QString("Unknown frequency: %1, returning -1 for the channel.").arg(num).latin1() << oendl;
116 return -1; 116 return -1;
117} 117}
118 118
119/*** 119/***
120 * Get the current rate that the card is transmiting at. 120 * Get the current rate that the card is transmiting at.
121 * @return double the rate, 0 if error. 121 * @return double the rate, 0 if error.
122 */ 122 */
123double WExtensions::rate(){ 123double WExtensions::rate(){
124 if(!hasWirelessExtensions) 124 if(!hasWirelessExtensions)
125 return 0; 125 return 0;
126 if(0 == ioctl(fd, SIOCGIWRATE, &iwr)){ 126 if(0 == ioctl(fd, SIOCGIWRATE, &iwr)){
127 return ((double)iwr.u.bitrate.value)/1000000; 127 return ((double)iwr.u.bitrate.value)/1000000;
128 } 128 }
129 return 0; 129 return 0;
130} 130}
131 131
132 132
133/** 133/**
134 * @return QString the AccessPoint that the interface is connected to. 134 * @return QString the AccessPoint that the interface is connected to.
135 */ 135 */
136QString WExtensions::ap(){ 136QString WExtensions::ap(){
137 if(!hasWirelessExtensions) 137 if(!hasWirelessExtensions)
138 return QString(); 138 return QString();
139 if ( 0 == ioctl( fd, SIOCGIWAP, &iwr )){ 139 if ( 0 == ioctl( fd, SIOCGIWAP, &iwr )){
140 QString ap; 140 QString ap;
141 ap = ap.sprintf( "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X", 141 ap = ap.sprintf( "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X",
142 iwr.u.ap_addr.sa_data[0]&0xff, 142 iwr.u.ap_addr.sa_data[0]&0xff,
143 iwr.u.ap_addr.sa_data[1]&0xff, 143 iwr.u.ap_addr.sa_data[1]&0xff,
144 iwr.u.ap_addr.sa_data[2]&0xff, 144 iwr.u.ap_addr.sa_data[2]&0xff,
145 iwr.u.ap_addr.sa_data[3]&0xff, 145 iwr.u.ap_addr.sa_data[3]&0xff,
146 iwr.u.ap_addr.sa_data[4]&0xff, 146 iwr.u.ap_addr.sa_data[4]&0xff,
147 iwr.u.ap_addr.sa_data[5]&0xff ); 147 iwr.u.ap_addr.sa_data[5]&0xff );
148 return ap; 148 return ap;
149 } 149 }
150 else return QString(); 150 else return QString();
151} 151}
152 152
153/** 153/**
154 * Get the stats for interfaces 154 * Get the stats for interfaces
155 * @param signal the signal strength of interface 155 * @param signal the signal strength of interface
156 * @param noise the noise level of the interface 156 * @param noise the noise level of the interface
157 * @param quality the quality level of the interface 157 * @param quality the quality level of the interface
158 * @return bool true if successful 158 * @return bool true if successful
159 */ 159 */
160bool WExtensions::stats(int &signal, int &noise, int &quality){ 160bool WExtensions::stats(int &signal, int &noise, int &quality){
161 // gather link quality from /proc/net/wireless 161 // gather link quality from /proc/net/wireless
162 if(!QFile::exists(PROCNETWIRELESS)) 162 if(!QFile::exists(PROCNETWIRELESS))
163 return false; 163 return false;
164 164
165 char c; 165 char c;
166 QString status; 166 QString status;
167 QString name; 167 QString name;
168 168
169 QFile wfile( PROCNETWIRELESS ); 169 QFile wfile( PROCNETWIRELESS );
170 if(!wfile.open( IO_ReadOnly )) 170 if(!wfile.open( IO_ReadOnly ))
171 return false; 171 return false;
172 172
173 QTextStream wstream( &wfile ); 173 QTextStream wstream( &wfile );
174 wstream.readLine(); // skip the first two lines 174 wstream.readLine(); // skip the first two lines
175 wstream.readLine(); // because they only contain headers 175 wstream.readLine(); // because they only contain headers
176 while(!wstream.atEnd()){ 176 while(!wstream.atEnd()){
177 wstream >> name >> status >> quality >> c >> signal >> c >> noise; 177 wstream >> name >> status >> quality >> c >> signal >> c >> noise;
178 if(name == QString("%1:").arg(interface)){ 178 if(name == QString("%1:").arg(interface)){
179 if ( quality > 92 ) 179 if ( quality > 92 )
180 qDebug( "WIFIAPPLET: D'oh! Quality %d > estimated max!\n", quality ); 180 odebug << "WIFIAPPLET: D'oh! Quality " << quality << " > estimated max!\n" << oendl;
181 if ( ( signal > IW_UPPER ) || ( signal < IW_LOWER ) ) 181 if ( ( signal > IW_UPPER ) || ( signal < IW_LOWER ) )
182 qDebug( "WIFIAPPLET: Doh! Strength %d > estimated max!\n", signal ); 182 odebug << "WIFIAPPLET: Doh! Strength " << signal << " > estimated max!\n" << oendl;
183 if ( ( noise > IW_UPPER ) || ( noise < IW_LOWER ) ) 183 if ( ( noise > IW_UPPER ) || ( noise < IW_LOWER ) )
184 qDebug( "WIFIAPPLET: Doh! Noise %d > estimated max!\n", noise ); 184 odebug << "WIFIAPPLET: Doh! Noise " << noise << " > estimated max!\n" << oendl;
185 //qDebug(QString("q:%1, s:%2, n:%3").arg(quality).arg(signal).arg(noise).latin1()); 185 //odebug << QString("q:%1, s:%2, n:%3").arg(quality).arg(signal).arg(noise).latin1() << oendl;
186 signal = ( ( signal-IW_LOWER ) * 100 ) / IW_UPPER; 186 signal = ( ( signal-IW_LOWER ) * 100 ) / IW_UPPER;
187 noise = ( ( noise-IW_LOWER ) * 100 ) / IW_UPPER; 187 noise = ( ( noise-IW_LOWER ) * 100 ) / IW_UPPER;
188 quality = ( quality*100 ) / 92; 188 quality = ( quality*100 ) / 92;
189 return true; 189 return true;
190 } 190 }
191 } 191 }
192 192
193 qDebug("WExtensions::statsCard no longer present."); 193 odebug << "WExtensions::statsCard no longer present." << oendl;
194 quality = -1; 194 quality = -1;
195 signal = IW_LOWER; 195 signal = IW_LOWER;
196 noise = IW_LOWER; 196 noise = IW_LOWER;
197 return false; 197 return false;
198} 198}
199 199
200// wextensions.cpp 200// 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 @@
1#include "wlanimp.h" 1#include "wlanimp.h"
2#include "interfacesetupimp.h" 2#include "interfacesetupimp.h"
3 3
4#include <qfile.h> 4#include <qfile.h>
5#include <qdir.h> 5#include <qdir.h>
6#include <qtextstream.h> 6#include <qtextstream.h>
7#include <qmessagebox.h> 7#include <qmessagebox.h>
8#include <qlineedit.h> 8#include <qlineedit.h>
9#include <qlabel.h> 9#include <qlabel.h>
10#include <qspinbox.h> 10#include <qspinbox.h>
11#include <qradiobutton.h> 11#include <qradiobutton.h>
12#include <qcheckbox.h> 12#include <qcheckbox.h>
13#include <qtabwidget.h> 13#include <qtabwidget.h>
14#include <qcombobox.h> 14#include <qcombobox.h>
15 15
16#ifdef QWS 16#ifdef QWS
17 #include <opie2/oprocess.h> 17 #include <opie2/oprocess.h>
18#else 18#else
19 #define OProcess KProcess 19 #define OProcess KProcess
20 #include <kprocess.h> 20 #include <kprocess.h>
21#endif 21#endif
22 22
23#define WIRELESS_OPTS "/etc/pcmcia/wireless.opts" 23#define WIRELESS_OPTS "/etc/pcmcia/wireless.opts"
24 24
25/** 25/**
26 * Constructor, read in the wireless.opts file for parsing later. 26 * Constructor, read in the wireless.opts file for parsing later.
27 */ 27 */
28using namespace Opie::Core; 28using namespace Opie::Core;
29WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl):WLAN(parent, name, modal, fl), currentProfile("*") { 29WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl):WLAN(parent, name, modal, fl), currentProfile("*") {
30 interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i); 30 interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i);
31 tabWidget->insertTab(interfaceSetup, "TCP/IP"); 31 tabWidget->insertTab(interfaceSetup, "TCP/IP");
32 32
33 // Read in the config file. 33 // Read in the config file.
34 QString wlanFile = WIRELESS_OPTS; 34 QString wlanFile = WIRELESS_OPTS;
35 QFile file(wlanFile); 35 QFile file(wlanFile);
36 if (file.open(IO_ReadOnly)){ 36 if (file.open(IO_ReadOnly)){
37 QTextStream stream( &file ); 37 QTextStream stream( &file );
38 QString line = ""; 38 QString line = "";
39 while ( !stream.eof() ) { 39 while ( !stream.eof() ) {
40 line += stream.readLine(); 40 line += stream.readLine();
41 line += "\n"; 41 line += "\n";
42 } 42 }
43 file.close(); 43 file.close();
44 settingsFileText = QStringList::split("\n", line, true); 44 settingsFileText = QStringList::split("\n", line, true);
45 parseSettingFile(); 45 parseSettingFile();
46 } 46 }
47 else 47 else
48 qDebug(QString("WLANImp: Can't open file: %1 for reading.").arg(wlanFile).latin1()); 48 odebug << QString("WLANImp: Can't open file: %1 for reading.").arg(wlanFile).latin1() << oendl;
49 connect(networkType, SIGNAL(activated(int)), this, SLOT(typeChanged(int))); 49 connect(networkType, SIGNAL(activated(int)), this, SLOT(typeChanged(int)));
50} 50}
51 51
52void WLANImp::typeChanged(int mod){ 52void WLANImp::typeChanged(int mod){
53 networkChannel->setEnabled(mod); 53 networkChannel->setEnabled(mod);
54 channelLabel->setEnabled(mod); 54 channelLabel->setEnabled(mod);
55} 55}
56 56
57/** 57/**
58 * Change the profile for both wireless settings and network settings. 58 * Change the profile for both wireless settings and network settings.
59 */ 59 */
60void WLANImp::setProfile(const QString &profile){ 60void WLANImp::setProfile(const QString &profile){
61 interfaceSetup->setProfile(profile); 61 interfaceSetup->setProfile(profile);
62 parseSettingFile(); 62 parseSettingFile();
63} 63}
64 64
65/** 65/**
66 * Parses the settings file that was read in and gets any setting from it. 66 * Parses the settings file that was read in and gets any setting from it.
67 */ 67 */
68void WLANImp::parseSettingFile(){ 68void WLANImp::parseSettingFile(){
69 bool foundCase = false; 69 bool foundCase = false;
70 bool found = false; 70 bool found = false;
71 for ( QStringList::Iterator it = settingsFileText.begin(); it != settingsFileText.end(); ++it ) { 71 for ( QStringList::Iterator it = settingsFileText.begin(); it != settingsFileText.end(); ++it ) {
72 QString line = (*it).simplifyWhiteSpace(); 72 QString line = (*it).simplifyWhiteSpace();
73 if(line.contains("case")) 73 if(line.contains("case"))
74 foundCase = true; 74 foundCase = true;
75 // See if we found our scheme to write or the sceme couldn't be found 75 // See if we found our scheme to write or the sceme couldn't be found
76 if((foundCase && line.contains("esac")) || 76 if((foundCase && line.contains("esac")) ||
77 (foundCase && line.left(currentProfile.length()+7) == currentProfile + ",*,*,*)" && line.at(0) != '#')) 77 (foundCase && line.left(currentProfile.length()+7) == currentProfile + ",*,*,*)" && line.at(0) != '#'))
78 found = true; 78 found = true;
79 79
80 if(line.contains(";;")) 80 if(line.contains(";;"))
81 found = false; 81 found = false;
82 if(found){ 82 if(found){
83 // write out scheme 83 // write out scheme
84 if(line.contains("ESSID=")){ 84 if(line.contains("ESSID=")){
85 QString id = line.mid(line.find("ESSID=")+6, line.length()); 85 QString id = line.mid(line.find("ESSID=")+6, line.length());
86 if(id == "any"){ 86 if(id == "any"){
87 essAny->setChecked(false); 87 essAny->setChecked(false);
88 }else{ 88 }else{
89 essAny->setChecked(true); 89 essAny->setChecked(true);
90 essSpecificLineEdit->setText(id); 90 essSpecificLineEdit->setText(id);
91 } 91 }
92 } 92 }
93 if(line.contains("MODE=")){ 93 if(line.contains("MODE=")){
94 QString mode = line.mid(line.find("MODE=")+5, line.length()); 94 QString mode = line.mid(line.find("MODE=")+5, line.length());
95 if(mode == "Managed"){ 95 if(mode == "Managed"){
96 networkType->setCurrentItem(0); 96 networkType->setCurrentItem(0);
97 channelLabel->setEnabled(false); 97 channelLabel->setEnabled(false);
98 networkChannel->setEnabled(false); 98 networkChannel->setEnabled(false);
99 } 99 }
100 else{ 100 else{
101 networkType->setCurrentItem(1); 101 networkType->setCurrentItem(1);
102 networkChannel->setEnabled(true); 102 networkChannel->setEnabled(true);
103 channelLabel->setEnabled(true); 103 channelLabel->setEnabled(true);
104 } 104 }
105 } 105 }
106 if(line.contains("#KEY0=")) 106 if(line.contains("#KEY0="))
107 keyLineEdit0->setText(line.mid(6, line.length())); 107 keyLineEdit0->setText(line.mid(6, line.length()));
108 if(line.contains("#KEY1=")) 108 if(line.contains("#KEY1="))
109 keyLineEdit1->setText(line.mid(6, line.length())); 109 keyLineEdit1->setText(line.mid(6, line.length()));
110 if(line.contains("#KEY2=")) 110 if(line.contains("#KEY2="))
111 keyLineEdit2->setText(line.mid(6, line.length())); 111 keyLineEdit2->setText(line.mid(6, line.length()));
112 if(line.contains("#KEY3=")) 112 if(line.contains("#KEY3="))
113 keyLineEdit3->setText(line.mid(6, line.length())); 113 keyLineEdit3->setText(line.mid(6, line.length()));
114 114
115 if(line.contains("KEY=")){ 115 if(line.contains("KEY=")){
116 wepEnabled->setChecked(true); 116 wepEnabled->setChecked(true);
117 QString key; 117 QString key;
118 if(line.right(5) == (" open")){ 118 if(line.right(5) == (" open")){
119 key = line.mid(4, line.length()-5); 119 key = line.mid(4, line.length()-5);
120 authOpen->setChecked(true); 120 authOpen->setChecked(true);
121 authShared->setChecked(false); 121 authShared->setChecked(false);
122 } 122 }
123 else{ 123 else{
124 authOpen->setChecked(false); 124 authOpen->setChecked(false);
125 authShared->setChecked(true); 125 authShared->setChecked(true);
126 key = line.mid(4, line.length()); 126 key = line.mid(4, line.length());
127 } 127 }
128 if(key == keyLineEdit0->text()) keyRadio0->setChecked(true); 128 if(key == keyLineEdit0->text()) keyRadio0->setChecked(true);
129 if(key == keyLineEdit1->text()) keyRadio1->setChecked(true); 129 if(key == keyLineEdit1->text()) keyRadio1->setChecked(true);
130 if(key == keyLineEdit2->text()) keyRadio2->setChecked(true); 130 if(key == keyLineEdit2->text()) keyRadio2->setChecked(true);
131 if(key == keyLineEdit3->text()) keyRadio3->setChecked(true); 131 if(key == keyLineEdit3->text()) keyRadio3->setChecked(true);
132 } 132 }
133 if(line.contains("CHANNEL=")){ 133 if(line.contains("CHANNEL=")){
134 networkChannel->setValue(line.mid(line.find("CHANNEL=")+8, line.length()).toInt()); 134 networkChannel->setValue(line.mid(line.find("CHANNEL=")+8, line.length()).toInt());
135 } 135 }
136 } 136 }
137 } 137 }
138} 138}
139 139
140/** 140/**
141 * Saves settings to the wireless.opts file using the current profile 141 * Saves settings to the wireless.opts file using the current profile
142 */ 142 */
143void WLANImp::changeAndSaveSettingFile(){ 143void WLANImp::changeAndSaveSettingFile(){
144 QString wlanFile = WIRELESS_OPTS; 144 QString wlanFile = WIRELESS_OPTS;
145 QFile::remove(wlanFile); 145 QFile::remove(wlanFile);
146 QFile file(wlanFile); 146 QFile file(wlanFile);
147 147
148 if (!file.open(IO_ReadWrite)){ 148 if (!file.open(IO_ReadWrite)){
149 qDebug(QString("WLANImp::changeAndSaveSettingFile(): Can't open file: %1 for writing.").arg(wlanFile).latin1()); 149 odebug << QString("WLANImp::changeAndSaveSettingFile(): Can't open file: %1 for writing.").arg(wlanFile).latin1() << oendl;
150 return; 150 return;
151 } 151 }
152 152
153 QTextStream stream( &file ); 153 QTextStream stream( &file );
154 bool foundCase = false; 154 bool foundCase = false;
155 bool found = false; 155 bool found = false;
156 bool output = true; 156 bool output = true;
157 for ( QStringList::Iterator it = settingsFileText.begin(); it != settingsFileText.end(); ++it ) { 157 for ( QStringList::Iterator it = settingsFileText.begin(); it != settingsFileText.end(); ++it ) {
158 QString line = (*it).simplifyWhiteSpace(); 158 QString line = (*it).simplifyWhiteSpace();
159 if(line.contains("case")) 159 if(line.contains("case"))
160 foundCase = true; 160 foundCase = true;
161 // See if we found our scheme to write or the sceme couldn't be found 161 // See if we found our scheme to write or the sceme couldn't be found
162 if((foundCase && line.contains("esac") && !found) || 162 if((foundCase && line.contains("esac") && !found) ||
163 (foundCase && line.left(currentProfile.length()+7) == currentProfile + ",*,*,*)" && line.at(0) != '#')){ 163 (foundCase && line.left(currentProfile.length()+7) == currentProfile + ",*,*,*)" && line.at(0) != '#')){
164 // write out scheme 164 // write out scheme
165 found = true; 165 found = true;
166 output = false; 166 output = false;
167 167
168 if(!line.contains("esac")) 168 if(!line.contains("esac"))
169 stream << line << "\n"; 169 stream << line << "\n";
170 if(!essAny->isChecked() == true){ 170 if(!essAny->isChecked() == true){
171 stream << "\tESSID=any\n"; 171 stream << "\tESSID=any\n";
172 stream << "\tMODE=Managed\n"; 172 stream << "\tMODE=Managed\n";
173 } 173 }
174 else{ 174 else{
175 stream << "\tESSID=" << essSpecificLineEdit->text() << '\n'; 175 stream << "\tESSID=" << essSpecificLineEdit->text() << '\n';
176 stream << "\tMODE=" << ( networkType->currentItem() == 0 ? "Managed" : "ad-hoc") << '\n'; 176 stream << "\tMODE=" << ( networkType->currentItem() == 0 ? "Managed" : "ad-hoc") << '\n';
177 stream << "\tCHANNEL=" << networkChannel->value() << "\n"; 177 stream << "\tCHANNEL=" << networkChannel->value() << "\n";
178 } 178 }
179 179
180 stream << "\t#KEY0=" << keyLineEdit0->text() << "\n"; 180 stream << "\t#KEY0=" << keyLineEdit0->text() << "\n";
181 stream << "\t#KEY1=" << keyLineEdit1->text() << "\n"; 181 stream << "\t#KEY1=" << keyLineEdit1->text() << "\n";
182 stream << "\t#KEY2=" << keyLineEdit2->text() << "\n"; 182 stream << "\t#KEY2=" << keyLineEdit2->text() << "\n";
183 stream << "\t#KEY3=" << keyLineEdit3->text() << "\n"; 183 stream << "\t#KEY3=" << keyLineEdit3->text() << "\n";
184 184
185 if(wepEnabled->isChecked()){ 185 if(wepEnabled->isChecked()){
186 stream << "\tKEY=\""; 186 stream << "\tKEY=\"";
187 if(keyRadio0->isChecked()) stream << keyLineEdit0->text(); 187 if(keyRadio0->isChecked()) stream << keyLineEdit0->text();
188 if(keyRadio1->isChecked()) stream << keyLineEdit1->text(); 188 if(keyRadio1->isChecked()) stream << keyLineEdit1->text();
189 if(keyRadio2->isChecked()) stream << keyLineEdit2->text(); 189 if(keyRadio2->isChecked()) stream << keyLineEdit2->text();
190 if(keyRadio3->isChecked()) stream << keyLineEdit3->text(); 190 if(keyRadio3->isChecked()) stream << keyLineEdit3->text();
191 if(authOpen->isChecked()) 191 if(authOpen->isChecked())
192 stream << " open"; 192 stream << " open";
193 else 193 else
194 stream << " restricted"; 194 stream << " restricted";
195 stream << "\"\n"; 195 stream << "\"\n";
196 } 196 }
197 stream << "\tRATE=auto\n"; 197 stream << "\tRATE=auto\n";
198 if(line.contains("esac")) 198 if(line.contains("esac"))
199 stream << line << "\n"; 199 stream << line << "\n";
200 } 200 }
201 if(line.contains(";;")) 201 if(line.contains(";;"))
202 output = true; 202 output = true;
203 if(output && (*it).length() ) 203 if(output && (*it).length() )
204 stream << (*it) << '\n'; 204 stream << (*it) << '\n';
205 } 205 }
206 file.close(); 206 file.close();
207} 207}
208 208
209/** 209/**
210 * Check to see if the current config is valid 210 * Check to see if the current config is valid
211 * Save wireless.opts, save interfaces 211 * Save wireless.opts, save interfaces
212 */ 212 */
213void WLANImp::accept(){ 213void WLANImp::accept(){
214 if(wepEnabled->isChecked()){ 214 if(wepEnabled->isChecked()){
215 if(keyLineEdit0->text().isEmpty() && keyLineEdit1->text().isEmpty() && keyLineEdit2->text().isEmpty() && keyLineEdit3->text().isEmpty() ){ 215 if(keyLineEdit0->text().isEmpty() && keyLineEdit1->text().isEmpty() && keyLineEdit2->text().isEmpty() && keyLineEdit3->text().isEmpty() ){
216 QMessageBox::information(this, "Error", "Please enter a key for WEP.", QMessageBox::Ok); 216 QMessageBox::information(this, "Error", "Please enter a key for WEP.", QMessageBox::Ok);
217 return; 217 return;
218 } 218 }
219 } 219 }
220 220
221 if(essAny->isChecked() && essSpecificLineEdit->text().isEmpty()){ 221 if(essAny->isChecked() && essSpecificLineEdit->text().isEmpty()){
222 QMessageBox::information(this, "Error", "Please enter a SSID.", QMessageBox::Ok); 222 QMessageBox::information(this, "Error", "Please enter a SSID.", QMessageBox::Ok);
223 return; 223 return;
224 } 224 }
225 225
226 // Ok settings are good here, save 226 // Ok settings are good here, save
227 changeAndSaveSettingFile(); 227 changeAndSaveSettingFile();
228 228
229 // Try to save the interfaces settings. 229 // Try to save the interfaces settings.
230 if(!interfaceSetup->saveChanges()) 230 if(!interfaceSetup->saveChanges())
231 return; 231 return;
232 232
233 OProcess insert; 233 OProcess insert;
234 insert << "sh"; 234 insert << "sh";
235 insert << "-c"; 235 insert << "-c";
236 insert << "cardctl eject && cardctl insert"; 236 insert << "cardctl eject && cardctl insert";
237 237
238 if (!insert.start(OProcess::DontCare, OProcess::NoCommunication) ) { 238 if (!insert.start(OProcess::DontCare, OProcess::NoCommunication) ) {
239 qWarning("could not start cardctl"); 239 owarn << "could not start cardctl" << oendl;
240 } 240 }
241 241
242 // Close out the dialog 242 // Close out the dialog
243 QDialog::accept(); 243 QDialog::accept();
244} 244}
245 245
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 @@
1#include "wlanimp2.h" 1#include "wlanimp2.h"
2#include "keyedit.h" 2#include "keyedit.h"
3#include "interfacesetupimp.h" 3#include "interfacesetupimp.h"
4 4
5#include "../interfaces/interface.h" 5#include "../interfaces/interface.h"
6 6
7#include <assert.h> 7#include <assert.h>
8#include <errno.h> 8#include <errno.h>
9#include <string.h> 9#include <string.h>
10 10
11#include <qapplication.h> 11#include <qapplication.h>
12#include <qfile.h> 12#include <qfile.h>
13#include <qdir.h> 13#include <qdir.h>
14#include <qdialog.h> 14#include <qdialog.h>
15#include <qtextstream.h> 15#include <qtextstream.h>
16#include <qmessagebox.h> 16#include <qmessagebox.h>
17#include <qlineedit.h> 17#include <qlineedit.h>
18#include <qlabel.h> 18#include <qlabel.h>
19#include <qspinbox.h> 19#include <qspinbox.h>
20#include <qradiobutton.h> 20#include <qradiobutton.h>
21#include <qpushbutton.h> 21#include <qpushbutton.h>
22#include <qcheckbox.h> 22#include <qcheckbox.h>
23#include <qtabwidget.h> 23#include <qtabwidget.h>
24#include <qcombobox.h> 24#include <qcombobox.h>
25#include <qlistview.h> 25#include <qlistview.h>
26#include <qvbox.h> 26#include <qvbox.h>
27#include <qprogressbar.h> 27#include <qprogressbar.h>
28 28
29#ifdef QWS 29#ifdef QWS
30 #include <qpe/resource.h> 30 #include <qpe/resource.h>
31 #include <opie2/oprocess.h> 31 #include <opie2/oprocess.h>
32 #include <opie2/onetwork.h> 32 #include <opie2/onetwork.h>
33 #include <opie2/opcap.h> 33 #include <opie2/opcap.h>
34#else 34#else
35 #define OProcess KProcess 35 #define OProcess KProcess
36 #include <kprocess.h> 36 #include <kprocess.h>
37#endif 37#endif
38 38
39#define WIRELESS_OPTS "/etc/pcmcia/wireless.opts" 39#define WIRELESS_OPTS "/etc/pcmcia/wireless.opts"
40#define PREUP "/etc/network/if-pre-up.d/wireless-tools" 40#define PREUP "/etc/network/if-pre-up.d/wireless-tools"
41 41
42/** 42/**
43 * Constructor, read in the wireless.opts file for parsing later. 43 * Constructor, read in the wireless.opts file for parsing later.
44 */ 44 */
45using namespace Opie::Net; 45using namespace Opie::Net;
46using namespace Opie::Core; 46using namespace Opie::Core;
47WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl) : WLAN(parent, name, modal, fl), interface(i), currentProfile("*") { 47WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl) : WLAN(parent, name, modal, fl), interface(i), currentProfile("*") {
48 interfaces = new Interfaces(); 48 interfaces = new Interfaces();
49 interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i, interfaces); 49 interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i, interfaces);
50 tabWidget->insertTab(interfaceSetup, "TCP/IP"); 50 tabWidget->insertTab(interfaceSetup, "TCP/IP");
51 51
52 // Check sanity - the existance of the wireless-tools if-pre-up script 52 // Check sanity - the existance of the wireless-tools if-pre-up script
53 QFile file(QString(PREUP)); 53 QFile file(QString(PREUP));
54 if (file.exists()) { 54 if (file.exists()) {
55 qWarning(QString("WLANImp: Unable to open /etc/network/if-pre-up.d/wireless-tools")); 55 owarn << QString("WLANImp: Unable to open /etc/network/if-pre-up.d/wireless-tools") << oendl;
56 } 56 }
57 57
58 connect( rescanButton, SIGNAL( clicked() ), this, SLOT( rescanNeighbourhood() ) ); 58 connect( rescanButton, SIGNAL( clicked() ), this, SLOT( rescanNeighbourhood() ) );
59 connect( netView, SIGNAL( clicked(QListViewItem*) ), this, SLOT( selectNetwork(QListViewItem*) ) ); 59 connect( netView, SIGNAL( clicked(QListViewItem*) ), this, SLOT( selectNetwork(QListViewItem*) ) );
60 netView->setColumnAlignment( col_chn, AlignCenter ); 60 netView->setColumnAlignment( col_chn, AlignCenter );
61 netView->setItemMargin( 3 ); 61 netView->setItemMargin( 3 );
62 netView->setAllColumnsShowFocus( true ); 62 netView->setAllColumnsShowFocus( true );
63 63
64} 64}
65 65
66WLANImp::~WLANImp() { 66WLANImp::~WLANImp() {
67//FIXME: delete interfaces; 67//FIXME: delete interfaces;
68} 68}
69 69
70/** 70/**
71 * Change the profile for both wireless settings and network settings. 71 * Change the profile for both wireless settings and network settings.
72 */ 72 */
73void WLANImp::setProfile(const QString &profile){ 73void WLANImp::setProfile(const QString &profile){
74 interfaceSetup->setProfile(profile); 74 interfaceSetup->setProfile(profile);
75 parseOpts(); 75 parseOpts();
76} 76}
77 77
78void WLANImp::parseOpts() { 78void WLANImp::parseOpts() {
79 bool error; 79 bool error;
80 QString opt; 80 QString opt;
81 81
82 if (! interfaces->isInterfaceSet()) 82 if (! interfaces->isInterfaceSet())
83 return; 83 return;
84 84
85 85
86 opt = interfaces->getInterfaceOption("wireless_essid", error); 86 opt = interfaces->getInterfaceOption("wireless_essid", error);
87 if(opt == "any" || opt == "off" || opt.isNull()){ 87 if(opt == "any" || opt == "off" || opt.isNull()){
88 essid->setEditText("any"); 88 essid->setEditText("any");
89 } else { 89 } else {
90 essid->setEditText(opt); 90 essid->setEditText(opt);
91 } 91 }
92 92
93 opt = interfaces->getInterfaceOption("wireless_mode", error).simplifyWhiteSpace(); 93 opt = interfaces->getInterfaceOption("wireless_mode", error).simplifyWhiteSpace();
94 94
95 for ( int i = 0; i < mode->count(); i++) 95 for ( int i = 0; i < mode->count(); i++)
96 if ( mode->text( i ) == opt ) mode->setCurrentItem( i ); 96 if ( mode->text( i ) == opt ) mode->setCurrentItem( i );
97 97
98 opt = interfaces->getInterfaceOption("wireless_ap", error).simplifyWhiteSpace(); 98 opt = interfaces->getInterfaceOption("wireless_ap", error).simplifyWhiteSpace();
99 if (! opt.isNull()) { 99 if (! opt.isNull()) {
100 specifyAp->setChecked(true); 100 specifyAp->setChecked(true);
101 macEdit->setText(opt); 101 macEdit->setText(opt);
102 } 102 }
103 103
104 opt = interfaces->getInterfaceOption("wireless_channel", error).simplifyWhiteSpace(); 104 opt = interfaces->getInterfaceOption("wireless_channel", error).simplifyWhiteSpace();
105 if (! opt.isNull()) { 105 if (! opt.isNull()) {
106 specifyChan->setChecked(true); 106 specifyChan->setChecked(true);
107 networkChannel->setValue(opt.toInt()); 107 networkChannel->setValue(opt.toInt());
108 } 108 }
109 109
110 opt = interfaces->getInterfaceOption("wireless_key", error).simplifyWhiteSpace(); 110 opt = interfaces->getInterfaceOption("wireless_key", error).simplifyWhiteSpace();
111 if (opt.isNull()) 111 if (opt.isNull())
112 opt = interfaces->getInterfaceOption("wireless_enc", error).simplifyWhiteSpace(); 112 opt = interfaces->getInterfaceOption("wireless_enc", error).simplifyWhiteSpace();
113 parseKeyStr(opt); 113 parseKeyStr(opt);
114} 114}
115 115
116void WLANImp::parseKeyStr(QString keystr) { 116void WLANImp::parseKeyStr(QString keystr) {
117 int loc = 0; 117 int loc = 0;
118 int index = 1; 118 int index = 1;
119 QString key; 119 QString key;
120 QStringList keys = QStringList::split(QRegExp("\\s+"), keystr); 120 QStringList keys = QStringList::split(QRegExp("\\s+"), keystr);
121 int enc = -1; // encryption state 121 int enc = -1; // encryption state
122 122
123 for (QStringList::Iterator it = keys.begin(); it != keys.end(); ++it) { 123 for (QStringList::Iterator it = keys.begin(); it != keys.end(); ++it) {
124 if ((*it).left(3) == "off") { 124 if ((*it).left(3) == "off") {
125 // encryption disabled 125 // encryption disabled
126 enc = 0; 126 enc = 0;
127 } else if ((*it).left(2) == "on") { 127 } else if ((*it).left(2) == "on") {
128 // encryption enabled 128 // encryption enabled
129 enc = 1; 129 enc = 1;
130 } else if ((*it).left(4) == "open") { 130 } else if ((*it).left(4) == "open") {
131 // open mode, accept non encrypted packets 131 // open mode, accept non encrypted packets
132 acceptNonEnc->setChecked(true); 132 acceptNonEnc->setChecked(true);
133 } else if ((*it).left(10) == "restricted") { 133 } else if ((*it).left(10) == "restricted") {
134 // restricted mode, only accept encrypted packets 134 // restricted mode, only accept encrypted packets
135 rejectNonEnc->setChecked(true); 135 rejectNonEnc->setChecked(true);
136 } else if ((*it).left(3) == "key") { 136 } else if ((*it).left(3) == "key") {
137 // new set of options 137 // new set of options
138 } else if ((*it).left(1) == "[") { 138 } else if ((*it).left(1) == "[") {
139 index = (*it).mid(1, 1).toInt(); 139 index = (*it).mid(1, 1).toInt();
140 // switch current key to index 140 // switch current key to index
141 switch (index) { 141 switch (index) {
142 case 1: 142 case 1:
143 keyRadio0->setChecked(true); 143 keyRadio0->setChecked(true);
144 break; 144 break;
145 case 2: 145 case 2:
146 keyRadio1->setChecked(true); 146 keyRadio1->setChecked(true);
147 break; 147 break;
148 case 3: 148 case 3:
149 keyRadio2->setChecked(true); 149 keyRadio2->setChecked(true);
150 break; 150 break;
151 case 4: 151 case 4:
152 keyRadio3->setChecked(true); 152 keyRadio3->setChecked(true);
153 break; 153 break;
154 } 154 }
155 } else { 155 } else {
156 // key 156 // key
157 key = (*it); 157 key = (*it);
158 } 158 }
159 if (! key.isNull()) { 159 if (! key.isNull()) {
160 if (enc == -1) 160 if (enc == -1)
161 enc = 1; 161 enc = 1;
162 QStringList::Iterator next = ++it; 162 QStringList::Iterator next = ++it;
163 if (it == keys.end()) { 163 if (it == keys.end()) {
164 break; 164 break;
165 } 165 }
166 if ((*(next)).left(1) == "[") { 166 if ((*(next)).left(1) == "[") {
167 // set key at index 167 // set key at index
168 index = (*(next)).mid(1, 1).toInt(); 168 index = (*(next)).mid(1, 1).toInt();
169 } else { 169 } else {
170 index = 1; 170 index = 1;
171 } 171 }
172 switch (index) { 172 switch (index) {
173 case 1: 173 case 1:
174 keyLineEdit0->setText(key); 174 keyLineEdit0->setText(key);
175 break; 175 break;
176 case 2: 176 case 2:
177 keyLineEdit1->setText(key); 177 keyLineEdit1->setText(key);
178 break; 178 break;
179 case 3: 179 case 3:
180 keyLineEdit2->setText(key); 180 keyLineEdit2->setText(key);
181 break; 181 break;
182 case 4: 182 case 4:
183 keyLineEdit3->setText(key); 183 keyLineEdit3->setText(key);
184 break; 184 break;
185 } 185 }
186 key = QString::null; 186 key = QString::null;
187 } 187 }
188 } 188 }
189 if (enc == 1) { 189 if (enc == 1) {
190 wepEnabled->setChecked(true); 190 wepEnabled->setChecked(true);
191 } else { 191 } else {
192 wepEnabled->setChecked(false); 192 wepEnabled->setChecked(false);
193 } 193 }
194} 194}
195 195
196/** 196/**
197 * Check to see if the current config is valid 197 * Check to see if the current config is valid
198 * Save interfaces 198 * Save interfaces
199 */ 199 */
200void WLANImp::accept() { 200void WLANImp::accept() {
201 if (wepEnabled->isChecked()) { 201 if (wepEnabled->isChecked()) {
202 if ((keyRadio0->isChecked() && keyLineEdit0->text().isEmpty()) || 202 if ((keyRadio0->isChecked() && keyLineEdit0->text().isEmpty()) ||
203 (keyRadio1->isChecked() && keyLineEdit1->text().isEmpty()) || 203 (keyRadio1->isChecked() && keyLineEdit1->text().isEmpty()) ||
204 (keyRadio2->isChecked() && keyLineEdit2->text().isEmpty()) || 204 (keyRadio2->isChecked() && keyLineEdit2->text().isEmpty()) ||
205 (keyRadio3->isChecked() && keyLineEdit3->text().isEmpty())) { 205 (keyRadio3->isChecked() && keyLineEdit3->text().isEmpty())) {
206 QMessageBox::information(this, "Error", "Please enter a WEP key.", QMessageBox::Ok); 206 QMessageBox::information(this, "Error", "Please enter a WEP key.", QMessageBox::Ok);
207 return; 207 return;
208 } 208 }
209 } 209 }
210 210
211 if (essid->currentText().isEmpty()) { 211 if (essid->currentText().isEmpty()) {
212 QMessageBox::information(this, "Error", "Please select/enter an ESSID.", QMessageBox::Ok); 212 QMessageBox::information(this, "Error", "Please select/enter an ESSID.", QMessageBox::Ok);
213 return; 213 return;
214 } 214 }
215 215
216 if (specifyAp->isChecked() && macEdit->text().isEmpty()) { 216 if (specifyAp->isChecked() && macEdit->text().isEmpty()) {
217 QMessageBox::information(this, "Error", "Please enter the MAC address of the Access Point.", QMessageBox::Ok); 217 QMessageBox::information(this, "Error", "Please enter the MAC address of the Access Point.", QMessageBox::Ok);
218 return; 218 return;
219 } 219 }
220 220
221 // Try to save the interfaces settings. 221 // Try to save the interfaces settings.
222 writeOpts(); 222 writeOpts();
223 223
224 // Close out the dialog 224 // Close out the dialog
225// FIXME: QDialog::accept(); 225// FIXME: QDialog::accept();
226} 226}
227 227
228void WLANImp::writeOpts() { 228void WLANImp::writeOpts() {
229 // eh can't really do anything about it other then return. :-D 229 // eh can't really do anything about it other then return. :-D
230 if(!interfaces->isInterfaceSet()){ 230 if(!interfaces->isInterfaceSet()){
231 QMessageBox::warning(0,"Inface not set","should not happen!!!"); 231 QMessageBox::warning(0,"Inface not set","should not happen!!!");
232 return; 232 return;
233 } 233 }
234 bool error = false; 234 bool error = false;
235 235
236 qDebug("setting wlan interface %s", interfaces->getInterfaceName( error ).latin1() ); 236 odebug << "setting wlan interface " << interfaces->getInterfaceName( error ).latin1() << "" << oendl;
237 237
238 if (error) QMessageBox::warning(0,"Inface not set","should not happen!!!"); 238 if (error) QMessageBox::warning(0,"Inface not set","should not happen!!!");
239 239
240 interfaces->setInterfaceOption(QString("wireless_mode"), mode->currentText()); 240 interfaces->setInterfaceOption(QString("wireless_mode"), mode->currentText());
241 interfaces->setInterfaceOption(QString("wireless_essid"), essid->currentText()); 241 interfaces->setInterfaceOption(QString("wireless_essid"), essid->currentText());
242 242
243 if (specifyAp->isChecked()) { 243 if (specifyAp->isChecked()) {
244 interfaces->setInterfaceOption(QString("wireless_ap"), macEdit->text()); 244 interfaces->setInterfaceOption(QString("wireless_ap"), macEdit->text());
245 } else { 245 } else {
246 interfaces->removeInterfaceOption(QString("wireless_ap")); 246 interfaces->removeInterfaceOption(QString("wireless_ap"));
247 } 247 }
248 248
249 if (specifyChan->isChecked()) { 249 if (specifyChan->isChecked()) {
250 interfaces->setInterfaceOption(QString("wireless_channel"), networkChannel->text()); 250 interfaces->setInterfaceOption(QString("wireless_channel"), networkChannel->text());
251 } else { 251 } else {
252 interfaces->removeInterfaceOption(QString("wireless_channel")); 252 interfaces->removeInterfaceOption(QString("wireless_channel"));
253 } 253 }
254 254
255 if (wepEnabled->isChecked()) { 255 if (wepEnabled->isChecked()) {
256 QStringList keyList; 256 QStringList keyList;
257 257
258 if (! keyLineEdit0->text().isNull()) { 258 if (! keyLineEdit0->text().isNull()) {
259 keyList += keyLineEdit0->text(); 259 keyList += keyLineEdit0->text();
260 keyList += "[1]"; 260 keyList += "[1]";
261 } //else 261 } //else
262 if (! keyLineEdit1->text().isNull()) { 262 if (! keyLineEdit1->text().isNull()) {
263 keyList += keyLineEdit1->text(); 263 keyList += keyLineEdit1->text();
264 keyList += "[2]"; 264 keyList += "[2]";
265 } //else 265 } //else
266 if (! keyLineEdit2->text().isNull()) { 266 if (! keyLineEdit2->text().isNull()) {
267 keyList += keyLineEdit2->text(); 267 keyList += keyLineEdit2->text();
268 keyList += "[3]"; 268 keyList += "[3]";
269 } //else 269 } //else
270 if (! keyLineEdit3->text().isNull()) { 270 if (! keyLineEdit3->text().isNull()) {
271 keyList += keyLineEdit3->text(); 271 keyList += keyLineEdit3->text();
272 keyList += "[4]"; 272 keyList += "[4]";
273 } 273 }
274 if (acceptNonEnc->isChecked()) { 274 if (acceptNonEnc->isChecked()) {
275 keyList += "open"; 275 keyList += "open";
276 } else { 276 } else {
277 keyList += "restricted"; 277 keyList += "restricted";
278 } 278 }
279 279
280 keyList += "key"; 280 keyList += "key";
281 if (keyRadio0->isChecked()) { 281 if (keyRadio0->isChecked()) {
282 keyList += "[1]"; 282 keyList += "[1]";
283 } else if (keyRadio1->isChecked()) { 283 } else if (keyRadio1->isChecked()) {
284 keyList += "[2]"; 284 keyList += "[2]";
285 } else if (keyRadio2->isChecked()) { 285 } else if (keyRadio2->isChecked()) {
286 keyList += "[3]"; 286 keyList += "[3]";
287 } else if (keyRadio3->isChecked()) { 287 } else if (keyRadio3->isChecked()) {
288 keyList += "[4]"; 288 keyList += "[4]";
289 } 289 }
290 interfaces->setInterfaceOption(QString("wireless_key"), keyList.join(QString(" "))); 290 interfaces->setInterfaceOption(QString("wireless_key"), keyList.join(QString(" ")));
291 } else { 291 } else {
292 interfaces->removeInterfaceOption(QString("wireless_key")); 292 interfaces->removeInterfaceOption(QString("wireless_key"));
293 } 293 }
294 interfaces->removeInterfaceOption(QString("wireless_enc")); 294 interfaces->removeInterfaceOption(QString("wireless_enc"));
295 295
296 if(!interfaceSetup->saveChanges()) 296 if(!interfaceSetup->saveChanges())
297 return; 297 return;
298 298
299 QDialog::accept(); 299 QDialog::accept();
300} 300}
301 301
302/* 302/*
303 * Scan for possible wireless networks around... 303 * Scan for possible wireless networks around...
304 * ... powered by Wellenreiter II technology (C) Michael 'Mickey' Lauer <mickeyl@handhelds.org> 304 * ... powered by Wellenreiter II technology (C) Michael 'Mickey' Lauer <mickeyl@handhelds.org>
305 */ 305 */
306 306
307void WLANImp::rescanNeighbourhood() 307void WLANImp::rescanNeighbourhood()
308{ 308{
309 QString name = interface->getInterfaceName(); 309 QString name = interface->getInterfaceName();
310 qDebug( "rescanNeighbourhood via '%s'", (const char*) name ); 310 odebug << "rescanNeighbourhood via '" << (const char*) name << "'" << oendl;
311 311
312 OWirelessNetworkInterface* wiface = static_cast<OWirelessNetworkInterface*>( ONetwork::instance()->interface( name ) ); 312 OWirelessNetworkInterface* wiface = static_cast<OWirelessNetworkInterface*>( ONetwork::instance()->interface( name ) );
313 assert( wiface ); 313 assert( wiface );
314 314
315 // try to guess device type 315 // try to guess device type
316 QString devicetype; 316 QString devicetype;
317 QFile m( "/proc/modules" ); 317 QFile m( "/proc/modules" );
318 if ( m.open( IO_ReadOnly ) ) 318 if ( m.open( IO_ReadOnly ) )
319 { 319 {
320 QString line; 320 QString line;
321 QTextStream modules( &m ); 321 QTextStream modules( &m );
322 while( !modules.atEnd() && !devicetype ) 322 while( !modules.atEnd() && !devicetype )
323 { 323 {
324 modules >> line; 324 modules >> line;
325 if ( line.contains( "cisco" ) ) devicetype = "cisco"; 325 if ( line.contains( "cisco" ) ) devicetype = "cisco";
326 else if ( line.contains( "hostap" ) ) devicetype = "hostap"; 326 else if ( line.contains( "hostap" ) ) devicetype = "hostap";
327 else if ( line.contains( "prism" ) ) devicetype = "wlan-ng"; /* puke */ 327 else if ( line.contains( "prism" ) ) devicetype = "wlan-ng"; /* puke */
328 else if ( line.contains( "orinoco" ) ) devicetype = "orinoco"; 328 else if ( line.contains( "orinoco" ) ) devicetype = "orinoco";
329 } 329 }
330 } 330 }
331 if ( devicetype.isEmpty() ) 331 if ( devicetype.isEmpty() )
332 { 332 {
333 qWarning( "rescanNeighbourhood(): couldn't guess device type :(" ); 333 owarn << "rescanNeighbourhood(): couldn't guess device type :(" << oendl;
334 return; 334 return;
335 } 335 }
336 else 336 else
337 { 337 {
338 qDebug( "rescanNeighbourhood(): device type seems to be '%s'", (const char*) devicetype ); 338 odebug << "rescanNeighbourhood(): device type seems to be '" << (const char*) devicetype << "'" << oendl;
339 } 339 }
340 340
341 // configure interface to receive 802.11 management frames 341 // configure interface to receive 802.11 management frames
342 342
343 wiface->setUp( true ); 343 wiface->setUp( true );
344 wiface->setPromiscuousMode( true ); 344 wiface->setPromiscuousMode( true );
345 345
346 if ( devicetype == "cisco" ) wiface->setMonitoring( new OCiscoMonitoringInterface( wiface, false ) ); 346 if ( devicetype == "cisco" ) wiface->setMonitoring( new OCiscoMonitoringInterface( wiface, false ) );
347 else if ( devicetype == "hostap" ) wiface->setMonitoring( new OHostAPMonitoringInterface( wiface, false ) ); 347 else if ( devicetype == "hostap" ) wiface->setMonitoring( new OHostAPMonitoringInterface( wiface, false ) );
348 else if ( devicetype == "wlan-ng" ) wiface->setMonitoring( new OWlanNGMonitoringInterface( wiface, false ) ); 348 else if ( devicetype == "wlan-ng" ) wiface->setMonitoring( new OWlanNGMonitoringInterface( wiface, false ) );
349 else if ( devicetype == "orinoco" ) wiface->setMonitoring( new OOrinocoMonitoringInterface( wiface, false ) ); 349 else if ( devicetype == "orinoco" ) wiface->setMonitoring( new OOrinocoMonitoringInterface( wiface, false ) );
350 else 350 else
351 { 351 {
352 qDebug( "rescanNeighbourhood(): unsupported device type for monitoring :(" ); 352 odebug << "rescanNeighbourhood(): unsupported device type for monitoring :(" << oendl;
353 return; 353 return;
354 } 354 }
355 355
356 wiface->setMode( "monitor" ); 356 wiface->setMode( "monitor" );
357 if ( wiface->mode() != "monitor" ) 357 if ( wiface->mode() != "monitor" )
358 { 358 {
359 qWarning( "rescanNeighbourhood(): Unable to bring device into monitor mode (%s).", strerror( errno ) ); 359 owarn << "rescanNeighbourhood(): Unable to bring device into monitor mode (" << strerror( errno ) << ")." << oendl;
360 return; 360 return;
361 } 361 }
362 362
363 // open a packet capturer 363 // open a packet capturer
364 OPacketCapturer* cap = new OPacketCapturer(); 364 OPacketCapturer* cap = new OPacketCapturer();
365 cap->open( name ); 365 cap->open( name );
366 if ( !cap->isOpen() ) 366 if ( !cap->isOpen() )
367 { 367 {
368 qWarning( "rescanNeighbourhood(): Unable to open libpcap (%s).", strerror( errno ) ); 368 owarn << "rescanNeighbourhood(): Unable to open libpcap (" << strerror( errno ) << ")." << oendl;
369 return; 369 return;
370 } 370 }
371 371
372 // display splash screen 372 // display splash screen
373 QFrame* splash = new QFrame( this, "splash", false, WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_Customize ); 373 QFrame* splash = new QFrame( this, "splash", false, WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_Customize );
374 splash->setLineWidth( 2 ); 374 splash->setLineWidth( 2 );
375 splash->setFrameStyle( QFrame::Panel | QFrame::Raised ); 375 splash->setFrameStyle( QFrame::Panel | QFrame::Raised );
376 QVBoxLayout* vbox = new QVBoxLayout( splash, 4, 4 ); 376 QVBoxLayout* vbox = new QVBoxLayout( splash, 4, 4 );
377 QLabel* lab = new QLabel( "<center><b>Scanning...</b><br>Please Wait...</center>", splash ); 377 QLabel* lab = new QLabel( "<center><b>Scanning...</b><br>Please Wait...</center>", splash );
378 QProgressBar* pb = new QProgressBar( wiface->channels(), splash ); 378 QProgressBar* pb = new QProgressBar( wiface->channels(), splash );
379 vbox->addWidget( lab ); 379 vbox->addWidget( lab );
380 vbox->addWidget( pb ); 380 vbox->addWidget( pb );
381 pb->setCenterIndicator( true ); 381 pb->setCenterIndicator( true );
382 pb->setFixedHeight( pb->sizeHint().height() ); 382 pb->setFixedHeight( pb->sizeHint().height() );
383 QWidget* widgetDesktop = qApp->desktop(); 383 QWidget* widgetDesktop = qApp->desktop();
384 int dw = widgetDesktop->width(); 384 int dw = widgetDesktop->width();
385 int dh = widgetDesktop->height(); 385 int dh = widgetDesktop->height();
386 int pw = vbox->sizeHint().width(); 386 int pw = vbox->sizeHint().width();
387 int ph = vbox->sizeHint().height(); 387 int ph = vbox->sizeHint().height();
388 splash->setGeometry((dw-pw)/2,(dh-ph)/2,pw,ph); 388 splash->setGeometry((dw-pw)/2,(dh-ph)/2,pw,ph);
389 splash->show(); 389 splash->show();
390 splash->raise(); 390 splash->raise();
391 qApp->processEvents(); 391 qApp->processEvents();
392 392
393 // set capturer to non-blocking mode 393 // set capturer to non-blocking mode
394 cap->setBlocking( false ); 394 cap->setBlocking( false );
395 395
396 for ( int i = 1; i <= wiface->channels(); ++i ) 396 for ( int i = 1; i <= wiface->channels(); ++i )
397 { 397 {
398 wiface->setChannel( i ); 398 wiface->setChannel( i );
399 pb->setProgress( i ); 399 pb->setProgress( i );
400 qApp->processEvents(); 400 qApp->processEvents();
401 qDebug( "rescanNeighbourhood(): listening on channel %d...", i ); 401 odebug << "rescanNeighbourhood(): listening on channel " << i << "..." << oendl;
402 OPacket* p = cap->next( 1000 ); 402 OPacket* p = cap->next( 1000 );
403 if ( !p ) 403 if ( !p )
404 { 404 {
405 qDebug( "rescanNeighbourhood(): nothing received on channel %d", i ); 405 odebug << "rescanNeighbourhood(): nothing received on channel " << i << "" << oendl;
406 } 406 }
407 else 407 else
408 { 408 {
409 qDebug( "rescanNeighbourhood(): TADAA - something came in on channel %d", i ); 409 odebug << "rescanNeighbourhood(): TADAA - something came in on channel " << i << "" << oendl;
410 handlePacket( p ); 410 handlePacket( p );
411 } 411 }
412 } 412 }
413 413
414 cap->close(); 414 cap->close();
415 wiface->setMode( "managed" ); // TODO: use previous mode 415 wiface->setMode( "managed" ); // TODO: use previous mode
416 wiface->setPromiscuousMode( false ); 416 wiface->setPromiscuousMode( false );
417 417
418 splash->hide(); 418 splash->hide();
419 delete splash; 419 delete splash;
420 420
421} 421}
422 422
423void WLANImp::handlePacket( OPacket* p ) 423void WLANImp::handlePacket( OPacket* p )
424{ 424{
425 425
426 // check if we received a beacon frame 426 // check if we received a beacon frame
427 OWaveLanManagementPacket* beacon = static_cast<OWaveLanManagementPacket*>( p->child( "802.11 Management" ) ); 427 OWaveLanManagementPacket* beacon = static_cast<OWaveLanManagementPacket*>( p->child( "802.11 Management" ) );
428 if ( beacon && beacon->managementType() == "Beacon" ) 428 if ( beacon && beacon->managementType() == "Beacon" )
429 { 429 {
430 430
431 QString type; 431 QString type;
432 if ( beacon->canIBSS() ) 432 if ( beacon->canIBSS() )
433 { 433 {
434 type = "adhoc"; 434 type = "adhoc";
435 } 435 }
436 else if ( beacon->canESS() ) 436 else if ( beacon->canESS() )
437 { 437 {
438 type = "managed"; 438 type = "managed";
439 } 439 }
440 else 440 else
441 { 441 {
442 qWarning( "handlePacket(): invalid frame [possibly noise] detected!" ); 442 owarn << "handlePacket(): invalid frame [possibly noise] detected!" << oendl;
443 return; 443 return;
444 } 444 }
445 445
446 OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) ); 446 OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) );
447 QString essid = ssid ? ssid->ID() : QString("<unknown>"); 447 QString essid = ssid ? ssid->ID() : QString("<unknown>");
448 OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) ); 448 OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) );
449 int channel = ds ? ds->channel() : -1; 449 int channel = ds ? ds->channel() : -1;
450 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) ); 450 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
451 displayFoundNetwork( type, channel, essid, header->macAddress2() ); 451 displayFoundNetwork( type, channel, essid, header->macAddress2() );
452 } 452 }
453} 453}
454 454
455 455
456void WLANImp::displayFoundNetwork( const QString& mode, int channel, const QString& ssid, const OMacAddress& mac ) 456void WLANImp::displayFoundNetwork( const QString& mode, int channel, const QString& ssid, const OMacAddress& mac )
457{ 457{
458 458
459 qDebug( "found network: <%s>, chn %d, ssid '%s', mac '%s'", (const char*) mode, channel, 459 qDebug( "found network: <%s>, chn %d, ssid '%s', mac '%s'", (const char*) mode, channel,
460 (const char*) ssid, 460 (const char*) ssid,
461 (const char*) mac.toString() ); 461 (const char*) mac.toString() );
462 462
463 QListViewItemIterator it( netView ); 463 QListViewItemIterator it( netView );
464 while ( it.current() && it.current()->text( col_ssid ) != ssid ) ++it; 464 while ( it.current() && it.current()->text( col_ssid ) != ssid ) ++it;
465 if ( !it.current() ) // ssid didn't show up yet 465 if ( !it.current() ) // ssid didn't show up yet
466 { 466 {
467 QListViewItem* item = new QListViewItem( netView, mode.left( 1 ).upper(), ssid, QString::number( channel ), mac.toString() ); 467 QListViewItem* item = new QListViewItem( netView, mode.left( 1 ).upper(), ssid, QString::number( channel ), mac.toString() );
468 QString name; 468 QString name;
469 name.sprintf( "networksettings/%s", (const char*) mode ); 469 name.sprintf( "networksettings/%s", (const char*) mode );
470 item->setPixmap( col_mode, Resource::loadPixmap( name ) ); 470 item->setPixmap( col_mode, Resource::loadPixmap( name ) );
471 qApp->processEvents(); 471 qApp->processEvents();
472 } 472 }
473 473
474} 474}
475 475
476 476
477void WLANImp::selectNetwork( QListViewItem* item ) 477void WLANImp::selectNetwork( QListViewItem* item )
478{ 478{
479 bool ok; 479 bool ok;
480 if ( item ) 480 if ( item )
481 { 481 {
482 specifyAp->setChecked(true); 482 specifyAp->setChecked(true);
483 macEdit->setText( item->text( col_mac ) ); 483 macEdit->setText( item->text( col_mac ) );
484 specifyChan->setChecked( item->text( col_mode ) == "A" ); 484 specifyChan->setChecked( item->text( col_mode ) == "A" );
485 networkChannel->setValue( item->text( col_chn ).toInt( &ok ) ); 485 networkChannel->setValue( item->text( col_chn ).toInt( &ok ) );
486 essid->setEditText( item->text( col_ssid ) ); 486 essid->setEditText( item->text( col_ssid ) );
487 if ( item->text( col_mode ) == "A" ) 487 if ( item->text( col_mode ) == "A" )
488 mode->setCurrentItem( 3 ); 488 mode->setCurrentItem( 3 );
489 else 489 else
490 mode->setCurrentItem( 2 ); 490 mode->setCurrentItem( 2 );
491 } 491 }
492} 492}
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()
29 29
30/** 30/**
31 * Delete any interfaces that we own. 31 * Delete any interfaces that we own.
32 */ 32 */
33WLANModule::~WLANModule(){ 33WLANModule::~WLANModule(){
34 Interface *i; 34 Interface *i;
35 for ( i=list.first(); i != 0; i=list.next() ) 35 for ( i=list.first(); i != 0; i=list.next() )
36 delete i; 36 delete i;
37 37
38} 38}
39 39
40/** 40/**
41 * Change the current profile 41 * Change the current profile
42 */ 42 */
43void WLANModule::setProfile(const QString &newProfile){ 43void WLANModule::setProfile(const QString &newProfile){
44 profile = newProfile; 44 profile = newProfile;
45} 45}
46 46
47/** 47/**
48 * get the icon name for this device. 48 * get the icon name for this device.
49 * @param Interface* can be used in determining the icon. 49 * @param Interface* can be used in determining the icon.
50 * @return QString the icon name (minus .png, .gif etc) 50 * @return QString the icon name (minus .png, .gif etc)
51 */ 51 */
52QString WLANModule::getPixmapName(Interface* ){ 52QString WLANModule::getPixmapName(Interface* ){
53 return "wlan"; 53 return "wlan";
54} 54}
55 55
56/** 56/**
57 * Check to see if the interface i is owned by this module. 57 * Check to see if the interface i is owned by this module.
58 * @param Interface* interface to check against 58 * @param Interface* interface to check against
59 * @return bool true if i is owned by this module, false otherwise. 59 * @return bool true if i is owned by this module, false otherwise.
60 */ 60 */
61bool WLANModule::isOwner(Interface *i){ 61bool WLANModule::isOwner(Interface *i){
62 WExtensions we(i->getInterfaceName()); 62 WExtensions we(i->getInterfaceName());
63 if(!we.doesHaveWirelessExtensions()) 63 if(!we.doesHaveWirelessExtensions())
64 return false; 64 return false;
65 65
66 i->setHardwareName("802.11b"); 66 i->setHardwareName("802.11b");
67 list.append(i); 67 list.append(i);
68 return true; 68 return true;
69} 69}
70 70
71/** 71/**
72 * Create, and return the WLANConfigure Module 72 * Create, and return the WLANConfigure Module
73 * @return QWidget* pointer to this modules configure. 73 * @return QWidget* pointer to this modules configure.
74 */ 74 */
75QWidget *WLANModule::configure(Interface *i){ 75QWidget *WLANModule::configure(Interface *i){
76 WLANImp *wlanconfig = new WLANImp(0, "WlanConfig", i, true, Qt::WDestructiveClose); 76 WLANImp *wlanconfig = new WLANImp(0, "WlanConfig", i, true, Qt::WDestructiveClose);
77 wlanconfig->setProfile(profile); 77 wlanconfig->setProfile(profile);
78 return wlanconfig; 78 return wlanconfig;
79} 79}
80 80
81/** 81/**
82 * Create, and return the Information Module 82 * Create, and return the Information Module
83 * @return QWidget* pointer to this modules info. 83 * @return QWidget* pointer to this modules info.
84 */ 84 */
85QWidget *WLANModule::information(Interface *i){ 85QWidget *WLANModule::information(Interface *i){
86 WExtensions we(i->getInterfaceName()); 86 WExtensions we(i->getInterfaceName());
87 if(!we.doesHaveWirelessExtensions()) 87 if(!we.doesHaveWirelessExtensions())
88 return NULL; 88 return NULL;
89 89
90 return getInfo( i ); 90 return getInfo( i );
91} 91}
92 92
93/** 93/**
94 * Get all active (up or down) interfaces 94 * Get all active (up or down) interfaces
95 * @return QList<Interface> A list of interfaces that exsist that havn't 95 * @return QList<Interface> A list of interfaces that exsist that havn't
96 * been called by isOwner() 96 * been called by isOwner()
97 */ 97 */
98QList<Interface> WLANModule::getInterfaces(){ 98QList<Interface> WLANModule::getInterfaces(){
99 return list; 99 return list;
100} 100}
101 101
102/** 102/**
103 * Attempt to add a new interface as defined by name 103 * Attempt to add a new interface as defined by name
104 * @param name the name of the type of interface that should be created given 104 * @param name the name of the type of interface that should be created given
105 * by possibleNewInterfaces(); 105 * by possibleNewInterfaces();
106 * @return Interface* NULL if it was unable to be created. 106 * @return Interface* NULL if it was unable to be created.
107 */ 107 */
108Interface *WLANModule::addNewInterface(const QString &){ 108Interface *WLANModule::addNewInterface(const QString &){
109 // We can't add a 802.11 interface, either the hardware will be there 109 // We can't add a 802.11 interface, either the hardware will be there
110 // or it wont. 110 // or it wont.
111 return NULL; 111 return NULL;
112} 112}
113 113
114/** 114/**
115 * Attempts to remove the interface, doesn't delete i 115 * Attempts to remove the interface, doesn't delete i
116 * @return bool true if successful, false otherwise. 116 * @return bool true if successful, false otherwise.
117 */ 117 */
118bool WLANModule::remove(Interface*){ 118bool WLANModule::remove(Interface*){
119 // Can't remove a hardware device, you can stop it though. 119 // Can't remove a hardware device, you can stop it though.
120 return false; 120 return false;
121} 121}
122 122
123void WLANModule::receive(const QCString &param, const QByteArray &arg) 123void WLANModule::receive(const QCString &param, const QByteArray &arg)
124{ 124{
125 qDebug("WLANModule::receive "+param); 125 odebug << "WLANModule::receive "+param << oendl;
126 QStringList params = QStringList::split(",",param); 126 QStringList params = QStringList::split(",",param);
127 int count = params.count(); 127 int count = params.count();
128 qDebug("WLANModule got %i params", count ); 128 odebug << "WLANModule got " << count << " params" << oendl;
129 if (count < 2){ 129 if (count < 2){
130 qDebug("Erorr less than 2 parameter"); 130 odebug << "Erorr less than 2 parameter" << oendl;
131 qDebug("RETURNING"); 131 odebug << "RETURNING" << oendl;
132 return; 132 return;
133 } 133 }
134 134
135 QDataStream stream(arg,IO_ReadOnly); 135 QDataStream stream(arg,IO_ReadOnly);
136 QString interface; 136 QString interface;
137 QString action; 137 QString action;
138 int countMsgs = 0; 138 int countMsgs = 0;
139 stream >> interface; 139 stream >> interface;
140 qDebug("got count? >%s<",interface.latin1()); 140 odebug << "got count? >" << interface.latin1() << "<" << oendl;
141 if (interface == "count"){ 141 if (interface == "count"){
142 qDebug("got count"); 142 odebug << "got count" << oendl;
143 stream >> action; 143 stream >> action;
144 qDebug("Got count num >%s<", action.latin1()); 144 odebug << "Got count num >" << action.latin1() << "<" << oendl;
145 countMsgs = action.toInt(); 145 countMsgs = action.toInt();
146 } 146 }
147 147
148 QDialog *toShow; 148 QDialog *toShow;
149 //while (! stream.atEnd() ){ 149 //while (! stream.atEnd() ){
150 for (int i = 0; i < countMsgs; i++){ 150 for (int i = 0; i < countMsgs; i++){
151 qDebug("start stream %d/%d",i,countMsgs); 151 odebug << "start stream " << i << "/" << countMsgs << "" << oendl;
152 if (stream.atEnd()){ 152 if (stream.atEnd()){
153 qDebug("end of stream"); 153 odebug << "end of stream" << oendl;
154 return; 154 return;
155 } 155 }
156 stream >> interface; 156 stream >> interface;
157 qDebug("got iface"); 157 odebug << "got iface" << oendl;
158 stream >> action; 158 stream >> action;
159 qDebug("WLANModule got interface %s and acion %s", interface.latin1(), action.latin1()); 159 odebug << "WLANModule got interface " << interface.latin1() << " and acion " << action.latin1() << "" << oendl;
160 // find interfaces 160 // find interfaces
161 Interface *ifa=0; 161 Interface *ifa=0;
162 for ( Interface *i=list.first(); i != 0; i=list.next() ){ 162 for ( Interface *i=list.first(); i != 0; i=list.next() ){
163 if (i->getInterfaceName() == interface){ 163 if (i->getInterfaceName() == interface){
164 qDebug("WLANModule found interface %s",interface.latin1()); 164 odebug << "WLANModule found interface " << interface.latin1() << "" << oendl;
165 ifa = i; 165 ifa = i;
166 } 166 }
167 } 167 }
168 168
169 if (ifa == 0){ 169 if (ifa == 0){
170 qDebug("WLANModule Did not find %s",interface.latin1()); 170 odebug << "WLANModule Did not find " << interface.latin1() << "" << oendl;
171 qDebug("skipping"); 171 odebug << "skipping" << oendl;
172 count = 0; 172 count = 0;
173 } 173 }
174 174
175 if (count == 2){ 175 if (count == 2){
176 // those should call the interface directly 176 // those should call the interface directly
177 QWidget *info = getInfo( ifa ); 177 QWidget *info = getInfo( ifa );
178 QPEApplication::showWidget( info ); 178 QPEApplication::showWidget( info );
179 179
180 if ( action.contains("start" ) ){ 180 if ( action.contains("start" ) ){
181 ifa->start(); 181 ifa->start();
182 } else if ( action.contains("restart" ) ){ 182 } else if ( action.contains("restart" ) ){
183 ifa->restart(); 183 ifa->restart();
184 } else if ( action.contains("stop" ) ){ 184 } else if ( action.contains("stop" ) ){
185 ifa->stop(); 185 ifa->stop();
186 }else if ( action.contains("refresh" ) ){ 186 }else if ( action.contains("refresh" ) ){
187 ifa->refresh(); 187 ifa->refresh();
188 } 188 }
189 }else if (count == 3){ 189 }else if (count == 3){
190 QString value; 190 QString value;
191 if (!wlanconfigWiget){ 191 if (!wlanconfigWiget){
192 //FIXME: what if it got closed meanwhile? 192 //FIXME: what if it got closed meanwhile?
193 wlanconfigWiget = (WLANImp*) configure(ifa); 193 wlanconfigWiget = (WLANImp*) configure(ifa);
194 toShow = (QDialog*) wlanconfigWiget; 194 toShow = (QDialog*) wlanconfigWiget;
195 } 195 }
196 QPEApplication::showWidget( wlanconfigWiget ); 196 QPEApplication::showWidget( wlanconfigWiget );
197 stream >> value; 197 stream >> value;
198 qDebug("WLANModule (build 4) is setting %s of %s to %s", action.latin1(), interface.latin1(), value.latin1() ); 198 odebug << "WLANModule (build 4) is setting " << action.latin1() << " of " << interface.latin1() << " to " << value.latin1() << "" << oendl;
199 if (value.isEmpty()){ 199 if (value.isEmpty()){
200 qDebug("value is empty!!!\nreturning"); 200 odebug << "value is empty!!!\nreturning" << oendl;
201 return; 201 return;
202 } 202 }
203 if ( action.contains("ESSID") ){ 203 if ( action.contains("ESSID") ){
204 QComboBox *combo = wlanconfigWiget->essid; 204 QComboBox *combo = wlanconfigWiget->essid;
205 bool found = false; 205 bool found = false;
206 for ( int i = 0; i < combo->count(); i++) 206 for ( int i = 0; i < combo->count(); i++)
207 if ( combo->text( i ) == value ){ 207 if ( combo->text( i ) == value ){
208 combo->setCurrentItem( i ); 208 combo->setCurrentItem( i );
209 found = true; 209 found = true;
210 } 210 }
211 if (!found) combo->insertItem( value, 0 ); 211 if (!found) combo->insertItem( value, 0 );
212 }else if ( action.contains("Mode") ){ 212 }else if ( action.contains("Mode") ){
213 QComboBox *combo = wlanconfigWiget->mode; 213 QComboBox *combo = wlanconfigWiget->mode;
214 for ( int i = 0; i < combo->count(); i++) 214 for ( int i = 0; i < combo->count(); i++)
215 if ( combo->text( i ) == value ){ 215 if ( combo->text( i ) == value ){
216 combo->setCurrentItem( i ); 216 combo->setCurrentItem( i );
217 } 217 }
218 218
219 }else if (action.contains("Channel")){ 219 }else if (action.contains("Channel")){
220 bool ok; 220 bool ok;
221 qDebug("converting channel"); 221 odebug << "converting channel" << oendl;
222 int chan = value.toInt( &ok ); 222 int chan = value.toInt( &ok );
223 if (ok){ 223 if (ok){
224 qDebug("ok setting channel"); 224 odebug << "ok setting channel" << oendl;
225 wlanconfigWiget->specifyChan->setChecked( true ); 225 wlanconfigWiget->specifyChan->setChecked( true );
226 wlanconfigWiget->networkChannel->setValue( chan ); 226 wlanconfigWiget->networkChannel->setValue( chan );
227 } 227 }
228 }else if (action.contains("MacAddr")){ 228 }else if (action.contains("MacAddr")){
229 wlanconfigWiget->specifyAp->setChecked( true ); 229 wlanconfigWiget->specifyAp->setChecked( true );
230 wlanconfigWiget->macEdit->setText( value ); 230 wlanconfigWiget->macEdit->setText( value );
231 }else 231 }else
232 qDebug("wlan plugin has no clue"); 232 odebug << "wlan plugin has no clue" << oendl;
233 } 233 }
234 qDebug("next stream"); 234 odebug << "next stream" << oendl;
235 }// while stream 235 }// while stream
236 qDebug("end of stream"); 236 odebug << "end of stream" << oendl;
237 if (toShow) toShow->exec(); 237 if (toShow) toShow->exec();
238 qDebug("returning"); 238 odebug << "returning" << oendl;
239} 239}
240 240
241QWidget *WLANModule::getInfo( Interface *i) 241QWidget *WLANModule::getInfo( Interface *i)
242{ 242{
243 qDebug("WLANModule::getInfo start"); 243 odebug << "WLANModule::getInfo start" << oendl;
244 WlanInfoImp *info = new WlanInfoImp(0, i->getInterfaceName(), Qt::WDestructiveClose); 244 WlanInfoImp *info = new WlanInfoImp(0, i->getInterfaceName(), Qt::WDestructiveClose);
245 InterfaceInformationImp *information = new InterfaceInformationImp(info->tabWidget, "InterfaceSetupImp", i); 245 InterfaceInformationImp *information = new InterfaceInformationImp(info->tabWidget, "InterfaceSetupImp", i);
246 info->tabWidget->insertTab(information, "TCP/IP", 0); 246 info->tabWidget->insertTab(information, "TCP/IP", 0);
247 info->tabWidget->setCurrentPage( 0 ); 247 info->tabWidget->setCurrentPage( 0 );
248 info->tabWidget->showPage( information ); 248 info->tabWidget->showPage( information );
249 if (info->tabWidget->currentPage() == information ) qDebug("infotab OK"); 249 if (info->tabWidget->currentPage() == information ) odebug << "infotab OK" << oendl;
250 else qDebug("infotab NOT OK"); 250 else odebug << "infotab NOT OK" << oendl;
251 qDebug("current idx %d", info->tabWidget->currentPageIndex()); 251 odebug << "current idx " << info->tabWidget->currentPageIndex() << "" << oendl;
252 qDebug("WLANModule::getInfo return"); 252 odebug << "WLANModule::getInfo return" << oendl;
253 return info; 253 return info;
254} 254}
255 255
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 @@
1CONFIG += qt warn_on quick-app 1CONFIG += qt warn_on quick-app
2HEADERS = soundsettings.h soundsettingsbase.h 2HEADERS = soundsettings.h soundsettingsbase.h
3SOURCES = soundsettings.cpp soundsettingsbase.cpp main.cpp 3SOURCES = soundsettings.cpp soundsettingsbase.cpp main.cpp
4#INTERFACES = soundsettingsbase.ui
5INCLUDEPATH += $(OPIEDIR)/include 4INCLUDEPATH += $(OPIEDIR)/include
6DEPENDPATH += $(OPIEDIR)/include 5DEPENDPATH += $(OPIEDIR)/include
7LIBS += -lqpe -lopiecore2 6LIBS += -lqpe -lopiecore2
8TARGET = sound 7TARGET = sound
9 8
10include ( $(OPIEDIR)/include.pro ) 9include ( $(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 @@
1/********************************************************************** 1/**********************************************************************
2 ** Copyright (C) 2000 Trolltech AS. All rights reserved. 2 ** Copyright (C) 2000 Trolltech AS. All rights reserved.
3 ** 3 **
4 ** This file is part of Qtopia Environment. 4 ** This file is part of Qtopia Environment.
5 ** 5 **
6 ** This file may be distributed and/or modified under the terms of the 6 ** This file may be distributed and/or modified under the terms of the
7 ** GNU General Public License version 2 as published by the Free Software 7 ** GNU General Public License version 2 as published by the Free Software
8 ** Foundation and appearing in the file LICENSE.GPL included in the 8 ** Foundation and appearing in the file LICENSE.GPL included in the
9 ** packaging of this file. 9 ** packaging of this file.
10 ** 10 **
11 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13 ** 13 **
14 ** See http://www.trolltech.com/gpl/ for GPL licensing information. 14 ** See http://www.trolltech.com/gpl/ for GPL licensing information.
15 ** 15 **
16 ** Contact info@trolltech.com if any conditions of this licensing are 16 ** Contact info@trolltech.com if any conditions of this licensing are
17 ** not clear to you. 17 ** not clear to you.
18 ** 18 **
19 **********************************************************************/ 19 **********************************************************************/
20// parts copyright 2002 L.J. Potter 20// parts copyright 2002 L.J. Potter
21 21
22#include "soundsettings.h" 22#include "soundsettings.h"
23 23
24/* OPIE */
25#include <opie2/odebug.h>
24#include <qpe/qpeapplication.h> 26#include <qpe/qpeapplication.h>
25#include <qpe/config.h> 27#include <qpe/config.h>
26#include <qpe/qcopenvelope_qws.h> 28#include <qpe/qcopenvelope_qws.h>
27#include <qpe/storage.h> 29#include <qpe/storage.h>
30using namespace Opie::Core;
28 31
32/* QT */
29#include <qcheckbox.h> 33#include <qcheckbox.h>
30#include <qcombobox.h> 34#include <qcombobox.h>
31#include <qlabel.h> 35#include <qlabel.h>
32 36
37/* STD */
33#include <sys/utsname.h> 38#include <sys/utsname.h>
34#include <sys/time.h> 39#include <sys/time.h>
35#include <sys/types.h> 40#include <sys/types.h>
36#include <unistd.h> 41#include <unistd.h>
37#include <stdio.h>
38#include <sys/stat.h> 42#include <sys/stat.h>
39 43
40 44
41SoundSettings::SoundSettings( QWidget* parent, const char* objname, WFlags fl ) 45SoundSettings::SoundSettings( QWidget* parent, const char* objname, WFlags fl )
42 : SoundSettingsBase( parent, objname, TRUE, fl ) 46 : SoundSettingsBase( parent, objname, TRUE, fl )
43{ 47{
44 keyReset=FALSE; 48 keyReset=FALSE;
45 noWarning=false; 49 noWarning=false;
46 Config config( "qpe"); 50 Config config( "qpe");
47 config.setGroup( "Volume" ); 51 config.setGroup( "Volume" );
48 Config cfg("Vmemo"); 52 Config cfg("Vmemo");
49 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 53 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
50 AlertCheckBox->setChecked(cfg.readBoolEntry("Alert")); 54 AlertCheckBox->setChecked(cfg.readBoolEntry("Alert"));
51 55
52 cfg.setGroup("Record"); 56 cfg.setGroup("Record");
53 int rate=config.readNumEntry("SampleRate", 22050); 57 int rate=config.readNumEntry("SampleRate", 22050);
54 if(rate == 8000) 58 if(rate == 8000)
55 sampleRate->setCurrentItem(0); 59 sampleRate->setCurrentItem(0);
56 else if(rate == 11025) 60 else if(rate == 11025)
57 sampleRate->setCurrentItem(1); 61 sampleRate->setCurrentItem(1);
58 else if(rate == 22050) 62 else if(rate == 22050)
59 sampleRate->setCurrentItem(2); 63 sampleRate->setCurrentItem(2);
60 else if(rate == 33075) 64 else if(rate == 33075)
61 sampleRate->setCurrentItem(3); 65 sampleRate->setCurrentItem(3);
62 else if(rate==44100) 66 else if(rate==44100)
63 sampleRate->setCurrentItem(4); 67 sampleRate->setCurrentItem(4);
64 68
65 stereoCheckBox->setChecked(cfg.readNumEntry("Stereo", 0)); 69 stereoCheckBox->setChecked(cfg.readNumEntry("Stereo", 0));
66//TODO hide if zaurus- mono only 70//TODO hide if zaurus- mono only
67 71
68#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) 72#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX)
69//since ipaq and zaurus have particular 73//since ipaq and zaurus have particular
70//devices 74//devices
71 bool systemZaurus=FALSE; 75 bool systemZaurus=FALSE;
72 struct utsname name; /* check for embedix kernel running on the zaurus*/ 76 struct utsname name; /* check for embedix kernel running on the zaurus*/
73 if (uname(&name) != -1) {// TODO change this here,... 77 if (uname(&name) != -1) {// TODO change this here,...
74 QString release=name.release; 78 QString release=name.release;
75 if( release.find("embedix",0,TRUE) != -1) { 79 if( release.find("embedix",0,TRUE) != -1) {
76 qDebug("IS System Zaurus"); 80 odebug << "IS System Zaurus" << oendl;
77 systemZaurus=TRUE; 81 systemZaurus=TRUE;
78 } 82 }
79 } 83 }
80 if(!systemZaurus) { 84 if(!systemZaurus) {
81 stereoCheckBox->setChecked(TRUE); 85 stereoCheckBox->setChecked(TRUE);
82 } 86 }
83 stereoCheckBox->setEnabled(FALSE); 87 stereoCheckBox->setEnabled(FALSE);
84 sixteenBitCheckBox->setEnabled(FALSE); 88 sixteenBitCheckBox->setEnabled(FALSE);
85#else 89#else
86#endif 90#endif
87 int sRate=cfg.readNumEntry("SizeLimit", 30); 91 int sRate=cfg.readNumEntry("SizeLimit", 30);
88 qDebug("%d",sRate); 92 odebug << "" << sRate << "" << oendl;
89 93
90 if(sRate ==30) 94 if(sRate ==30)
91 timeLimitComboBox->setCurrentItem(0); 95 timeLimitComboBox->setCurrentItem(0);
92 else if(sRate==20) 96 else if(sRate==20)
93 timeLimitComboBox->setCurrentItem(1); 97 timeLimitComboBox->setCurrentItem(1);
94 else if(sRate == 15) 98 else if(sRate == 15)
95 timeLimitComboBox->setCurrentItem(2); 99 timeLimitComboBox->setCurrentItem(2);
96 else if(sRate == 10) 100 else if(sRate == 10)
97 timeLimitComboBox->setCurrentItem(3); 101 timeLimitComboBox->setCurrentItem(3);
98 else if(sRate == 5) 102 else if(sRate == 5)
99 timeLimitComboBox->setCurrentItem(4); 103 timeLimitComboBox->setCurrentItem(4);
100 else 104 else
101 timeLimitComboBox->setCurrentItem(5); 105 timeLimitComboBox->setCurrentItem(5);
102 106
103 sixteenBitCheckBox->setChecked(cfg.readNumEntry("SixteenBit", 1)); 107 sixteenBitCheckBox->setChecked(cfg.readNumEntry("SixteenBit", 1));
104 108
105 cfg.setGroup("Defaults"); 109 cfg.setGroup("Defaults");
106 keyComboBox->setCurrentItem(cfg.readNumEntry("toggleKey") ); 110 keyComboBox->setCurrentItem(cfg.readNumEntry("toggleKey") );
107 111
108 updateStorageCombo(); 112 updateStorageCombo();
109 113
110 Config vmCfg("Vmemo"); 114 Config vmCfg("Vmemo");
111 vmCfg.setGroup("Defaults"); 115 vmCfg.setGroup("Defaults");
112 adpcmCheckBox->setChecked( vmCfg.readBoolEntry("use_ADPCM", 0)); 116 adpcmCheckBox->setChecked( vmCfg.readBoolEntry("use_ADPCM", 0));
113 117
114 connect( LocationComboBox,SIGNAL(activated(const QString&)), this, 118 connect( LocationComboBox,SIGNAL(activated(const QString&)), this,
115 SLOT( setLocation(const QString&))); 119 SLOT( setLocation(const QString&)));
116 connect( keyComboBox,SIGNAL(activated(int)), this, 120 connect( keyComboBox,SIGNAL(activated(int)), this,
117 SLOT( setKeyButton(int))); 121 SLOT( setKeyButton(int)));
118 connect( timeLimitComboBox,SIGNAL(activated(const QString&)), this, 122 connect( timeLimitComboBox,SIGNAL(activated(const QString&)), this,
119 SLOT( setSizeLimitButton(const QString&))); 123 SLOT( setSizeLimitButton(const QString&)));
120 connect( restartCheckBox,SIGNAL( toggled(bool)), this, 124 connect( restartCheckBox,SIGNAL( toggled(bool)), this,
121 SLOT( restartOpie(bool))); 125 SLOT( restartOpie(bool)));
122 connect( adpcmCheckBox,SIGNAL( toggled(bool)), this, 126 connect( adpcmCheckBox,SIGNAL( toggled(bool)), this,
123 SLOT( slotAdpcm(bool))); 127 SLOT( slotAdpcm(bool)));
124 128
125 // connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 129 // connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
126} 130}
127 131
128void SoundSettings::updateStorageCombo() { 132void SoundSettings::updateStorageCombo() {
129 133
130 Config config( "Vmemo" ); 134 Config config( "Vmemo" );
131 config.setGroup( "System" ); 135 config.setGroup( "System" );
132 QString loc = config.readEntry("RecLocation","/"); 136 QString loc = config.readEntry("RecLocation","/");
133 int i=0; 137 int i=0;
134 int set=0; 138 int set=0;
135 StorageInfo storageInfo; 139 StorageInfo storageInfo;
136 QString sName, sPath; 140 QString sName, sPath;
137 QStringList list; 141 QStringList list;
138 list << "Documents : "+QPEApplication::documentDir(); 142 list << "Documents : "+QPEApplication::documentDir();
139 list << "tmp : /tmp"; 143 list << "tmp : /tmp";
140 144
141 const QList<FileSystem> &fs = storageInfo.fileSystems(); 145 const QList<FileSystem> &fs = storageInfo.fileSystems();
142 QListIterator<FileSystem> it ( fs ); 146 QListIterator<FileSystem> it ( fs );
143 for( ; it.current(); ++it ){ 147 for( ; it.current(); ++it ){
144 const QString name = (*it)->name(); 148 const QString name = (*it)->name();
145 const QString path = (*it)->path(); 149 const QString path = (*it)->path();
146 qDebug("storage name "+name +" storage path is "+path); 150 odebug << "storage name "+name +" storage path is "+path << oendl;
147 list << name + ": " +path; 151 list << name + ": " +path;
148 if( loc.find( path,0,TRUE) != -1) 152 if( loc.find( path,0,TRUE) != -1)
149 set = i; 153 set = i;
150// if(dit.current()->file().find(path) != -1 ) storage=name; 154// if(dit.current()->file().find(path) != -1 ) storage=name;
151 i++; 155 i++;
152 } 156 }
153 157
154 LocationComboBox->insertStringList(list); 158 LocationComboBox->insertStringList(list);
155 qDebug("set item %d", set); 159 odebug << "set item " << set << "" << oendl;
156 LocationComboBox->setCurrentItem(set); 160 LocationComboBox->setCurrentItem(set);
157} 161}
158 162
159void SoundSettings::setLocation(const QString & string) { 163void SoundSettings::setLocation(const QString & string) {
160 Config config( "Vmemo" ); 164 Config config( "Vmemo" );
161 config.setGroup( "System" ); 165 config.setGroup( "System" );
162 config.writeEntry("RecLocation",string); 166 config.writeEntry("RecLocation",string);
163 qDebug("set location "+string); 167 odebug << "set location "+string << oendl;
164 config.write(); 168 config.write();
165} 169}
166 170
167void SoundSettings::cleanUp() { 171void SoundSettings::cleanUp() {
168 Config cfg("Vmemo"); 172 Config cfg("Vmemo");
169 cfg.writeEntry("Alert",AlertCheckBox->isChecked()); 173 cfg.writeEntry("Alert",AlertCheckBox->isChecked());
170 174
171 cfg.setGroup("Record"); 175 cfg.setGroup("Record");
172 cfg.writeEntry("SampleRate",sampleRate->currentText()); 176 cfg.writeEntry("SampleRate",sampleRate->currentText());
173 cfg.writeEntry("Stereo",stereoCheckBox->isChecked()); 177 cfg.writeEntry("Stereo",stereoCheckBox->isChecked());
174 cfg.writeEntry("SixteenBit",sixteenBitCheckBox->isChecked()); 178 cfg.writeEntry("SixteenBit",sixteenBitCheckBox->isChecked());
175 if(keyReset && noWarning) { 179 if(keyReset && noWarning) {
176 QCopEnvelope ("QPE/System", "restart()"); 180 QCopEnvelope ("QPE/System", "restart()");
177 } 181 }
178} 182}
179 183
180void SoundSettings::setKeyButton( int index) { 184void SoundSettings::setKeyButton( int index) {
181 Config cfg("Vmemo"); 185 Config cfg("Vmemo");
182 cfg.setGroup("Defaults"); 186 cfg.setGroup("Defaults");
183 cfg.writeEntry( "toggleKey", index ); 187 cfg.writeEntry( "toggleKey", index );
184 keyReset = TRUE; 188 keyReset = TRUE;
185 if( index == 1) { 189 if( index == 1) {
186 cfg.writeEntry( "hideIcon", 0 ); 190 cfg.writeEntry( "hideIcon", 0 );
187 keyLabel->setText(tr("Shows icon")); 191 keyLabel->setText(tr("Shows icon"));
188 } 192 }
189 else { 193 else {
190 cfg.writeEntry( "hideIcon", 1); 194 cfg.writeEntry( "hideIcon", 1);
191 keyLabel->setText(tr("Hides icon")); 195 keyLabel->setText(tr("Hides icon"));
192 } 196 }
193 cfg.write(); 197 cfg.write();
194} 198}
195 199
196void SoundSettings::updateLocationCombo() { 200void SoundSettings::updateLocationCombo() {
197 201
198} 202}
199 203
200void SoundSettings::setSizeLimitButton(const QString &index) { 204void SoundSettings::setSizeLimitButton(const QString &index) {
201 205
202 Config cfg("Vmemo"); 206 Config cfg("Vmemo");
203 cfg.setGroup("Record"); 207 cfg.setGroup("Record");
204 if(index.find("Unlimited",0,TRUE) != -1) 208 if(index.find("Unlimited",0,TRUE) != -1)
205 cfg.writeEntry("SizeLimit", -1); 209 cfg.writeEntry("SizeLimit", -1);
206 else 210 else
207 cfg.writeEntry("SizeLimit", index); 211 cfg.writeEntry("SizeLimit", index);
208 cfg.write(); 212 cfg.write();
209} 213}
210 214
211void SoundSettings::restartOpie(bool b) { 215void SoundSettings::restartOpie(bool b) {
212 noWarning=b; 216 noWarning=b;
213} 217}
214 218
215void SoundSettings::slotAdpcm(bool b) { 219void SoundSettings::slotAdpcm(bool b) {
216 Config vmCfg("Vmemo"); 220 Config vmCfg("Vmemo");
217 vmCfg.setGroup("Defaults"); 221 vmCfg.setGroup("Defaults");
218 vmCfg.writeEntry("use_ADPCM", b); 222 vmCfg.writeEntry("use_ADPCM", b);
219 vmCfg.write(); 223 vmCfg.write();
220} 224}
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 @@
1/********************************************************************** 1/**********************************************************************
2** BenchmarkInfo 2** BenchmarkInfo
3** 3**
4** A benchmark for Qt/Embedded 4** A benchmark for Qt/Embedded
5** 5**
6** Copyright (C) 2004 Michael Lauer <mickey@vanille.de> 6** Copyright (C) 2004 Michael Lauer <mickey@vanille.de>
7** Inspired by ZBench (C) 2002 Satoshi <af230533@im07.alpha-net.ne.jp> 7** Inspired by ZBench (C) 2002 Satoshi <af230533@im07.alpha-net.ne.jp>
8** 8**
9** This file may be distributed and/or modified under the terms of the 9** This file may be distributed and/or modified under the terms of the
10** GNU General Public License version 2 as published by the Free Software 10** GNU General Public License version 2 as published by the Free Software
11** Foundation and appearing in the file LICENSE.GPL included in the 11** Foundation and appearing in the file LICENSE.GPL included in the
12** packaging of this file. 12** packaging of this file.
13** 13**
14** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 14** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
15** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 15** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16** 16**
17**********************************************************************/ 17**********************************************************************/
18 18
19#include "benchmarkinfo.h" 19#include "benchmarkinfo.h"
20 20
21/* OPIE */ 21/* OPIE */
22#include <opie2/odebug.h>
22#include <opie2/ostorageinfo.h> 23#include <opie2/ostorageinfo.h>
23#include <opie2/olistview.h> 24#include <opie2/olistview.h>
24#include <qpe/qpeapplication.h> 25#include <qpe/qpeapplication.h>
25#include <qpe/qcopenvelope_qws.h> 26#include <qpe/qcopenvelope_qws.h>
26#include <qpe/qpedecoration_qws.h> 27#include <qpe/qpedecoration_qws.h>
27#include <qpe/resource.h> 28#include <qpe/resource.h>
28#include <qpe/config.h> 29#include <qpe/config.h>
30using namespace Opie::Core;
31using namespace Opie::Ui;
29 32
30/* QT */ 33/* QT */
31#include <qclipboard.h> 34#include <qclipboard.h>
32#include <qcolor.h> 35#include <qcolor.h>
33#include <qcombobox.h> 36#include <qcombobox.h>
34#include <qdirectpainter_qws.h> 37#include <qdirectpainter_qws.h>
35#include <qfile.h> 38#include <qfile.h>
36#include <qtextstream.h> 39#include <qtextstream.h>
37#include <qfiledialog.h> 40#include <qfiledialog.h>
38#include <qlabel.h> 41#include <qlabel.h>
39#include <qlayout.h> 42#include <qlayout.h>
40#include <qpainter.h> 43#include <qpainter.h>
41#include <qpushbutton.h> 44#include <qpushbutton.h>
42#include <qtimer.h> 45#include <qtimer.h>
43#include <qwhatsthis.h> 46#include <qwhatsthis.h>
44 47
45/* STD */ 48/* STD */
46#include <time.h> 49#include <time.h>
47#include <stdio.h> 50#include <stdio.h>
48#include <stdlib.h> 51#include <stdlib.h>
49#include <math.h> 52#include <math.h>
50#if defined (__GNUC__) && (__GNUC__ < 3) 53#if defined (__GNUC__) && (__GNUC__ < 3)
51#define round qRound 54#define round qRound
52#endif 55#endif
53 56
54using namespace Opie::Ui;
55using namespace Opie::Core;
56extern "C" 57extern "C"
57
58{ 58{
59 void BenchFFT( void ); 59 void BenchFFT( void );
60 double dhry_main( int ); 60 double dhry_main( int );
61} 61}
62 62
63#define DHRYSTONE_RUNS 20000000 63#define DHRYSTONE_RUNS 20000000
64#define TEST_DURATION 3 64#define TEST_DURATION 3
65 65
66#define BUFF_SIZE 8192 66#define BUFF_SIZE 8192
67#define FILE_SIZE 1024 * 1024 // 1Mb 67#define FILE_SIZE 1024 * 1024 // 1Mb
68 68
69//=========================================================================== 69//===========================================================================
70 70
71class BenchmarkPaintWidget : public QWidget 71class BenchmarkPaintWidget : public QWidget
72{ 72{
73 public: 73 public:
74 BenchmarkPaintWidget() : QWidget( 0, "Benchmark Paint Widget", WStyle_Customize|WStyle_StaysOnTop|WPaintUnclipped|WPaintClever ) 74 BenchmarkPaintWidget() : QWidget( 0, "Benchmark Paint Widget", WStyle_Customize|WStyle_StaysOnTop|WPaintUnclipped|WPaintClever )
75 { 75 {
76 resize( QApplication::desktop()->size() ); 76 resize( QApplication::desktop()->size() );
77 show(); 77 show();
78 p.begin( this ); 78 p.begin( this );
79 }; 79 };
80 80
81 ~BenchmarkPaintWidget() 81 ~BenchmarkPaintWidget()
82 { 82 {
83 p.end(); 83 p.end();
84 hide(); 84 hide();
85 }; 85 };
86 86
87 QPainter p; 87 QPainter p;
88}; 88};
89 89
90//=========================================================================== 90//===========================================================================
91 91
92BenchmarkInfo::BenchmarkInfo( QWidget *parent, const char *name, int wFlags ) 92BenchmarkInfo::BenchmarkInfo( QWidget *parent, const char *name, int wFlags )
93 : QWidget( parent, name, wFlags ) 93 : QWidget( parent, name, wFlags )
94{ 94{
95 95
96 setMinimumSize( 200, 150 ); 96 setMinimumSize( 200, 150 );
97 97
98 QVBoxLayout* vb = new QVBoxLayout( this ); 98 QVBoxLayout* vb = new QVBoxLayout( this );
99 vb->setSpacing( 4 ); 99 vb->setSpacing( 4 );
100 vb->setMargin( 4 ); 100 vb->setMargin( 4 );
101 101
102 tests = new OListView( this ); 102 tests = new OListView( this );
103 QWhatsThis::add( tests->viewport(), tr( "This area shows the available tests, the results for which the tests " 103 QWhatsThis::add( tests->viewport(), tr( "This area shows the available tests, the results for which the tests "
104 "have been performed, and comparison values for one selected device. " 104 "have been performed, and comparison values for one selected device. "
105 "Use the checkboxes to define which tests you want to perform." ) ); 105 "Use the checkboxes to define which tests you want to perform." ) );
106 tests->setMargin( 0 ); 106 tests->setMargin( 0 );
107 tests->addColumn( tr( "Tests" ) ); 107 tests->addColumn( tr( "Tests" ) );
108 tests->addColumn( tr( "Results" ) ); 108 tests->addColumn( tr( "Results" ) );
109 tests->addColumn( tr( "Comparison" ) ); 109 tests->addColumn( tr( "Comparison" ) );
110 tests->setShowSortIndicator( true ); 110 tests->setShowSortIndicator( true );
111 111
112 test_alu = new OCheckListItem( tests, tr( "1. Integer Arithmetic " ), OCheckListItem::CheckBox ); 112 test_alu = new OCheckListItem( tests, tr( "1. Integer Arithmetic " ), OCheckListItem::CheckBox );
113 test_fpu = new OCheckListItem( tests, tr( "2. Floating Point Unit " ), OCheckListItem::CheckBox ); 113 test_fpu = new OCheckListItem( tests, tr( "2. Floating Point Unit " ), OCheckListItem::CheckBox );
114 test_txt = new OCheckListItem( tests, tr( "3. Text Rendering " ), OCheckListItem::CheckBox ); 114 test_txt = new OCheckListItem( tests, tr( "3. Text Rendering " ), OCheckListItem::CheckBox );
115 test_gfx = new OCheckListItem( tests, tr( "4. Gfx Rendering " ), OCheckListItem::CheckBox ); 115 test_gfx = new OCheckListItem( tests, tr( "4. Gfx Rendering " ), OCheckListItem::CheckBox );
116 test_ram = new OCheckListItem( tests, tr( "5. RAM Performance " ), OCheckListItem::CheckBox ); 116 test_ram = new OCheckListItem( tests, tr( "5. RAM Performance " ), OCheckListItem::CheckBox );
117 test_sd = new OCheckListItem( tests, tr( "6. SD Card Performance " ), OCheckListItem::CheckBox ); 117 test_sd = new OCheckListItem( tests, tr( "6. SD Card Performance " ), OCheckListItem::CheckBox );
118 test_cf = new OCheckListItem( tests, tr( "7. CF Card Performance " ), OCheckListItem::CheckBox ); 118 test_cf = new OCheckListItem( tests, tr( "7. CF Card Performance " ), OCheckListItem::CheckBox );
119 119
120 test_alu->setText( 1, "n/a" ); 120 test_alu->setText( 1, "n/a" );
121 test_fpu->setText( 1, "n/a" ); 121 test_fpu->setText( 1, "n/a" );
122 test_txt->setText( 1, "n/a" ); 122 test_txt->setText( 1, "n/a" );
123 test_gfx->setText( 1, "n/a" ); 123 test_gfx->setText( 1, "n/a" );
124 test_ram->setText( 1, "n/a" ); 124 test_ram->setText( 1, "n/a" );
125 test_sd->setText( 1, "n/a" ); 125 test_sd->setText( 1, "n/a" );
126 test_cf->setText( 1, "n/a" ); 126 test_cf->setText( 1, "n/a" );
127 127
128 test_alu->setText( 2, "n/a" ); 128 test_alu->setText( 2, "n/a" );
129 test_fpu->setText( 2, "n/a" ); 129 test_fpu->setText( 2, "n/a" );
130 test_txt->setText( 2, "n/a" ); 130 test_txt->setText( 2, "n/a" );
131 test_gfx->setText( 2, "n/a" ); 131 test_gfx->setText( 2, "n/a" );
132 test_ram->setText( 2, "n/a" ); 132 test_ram->setText( 2, "n/a" );
133 test_sd->setText( 2, "n/a" ); 133 test_sd->setText( 2, "n/a" );
134 test_cf->setText( 2, "n/a" ); 134 test_cf->setText( 2, "n/a" );
135 135
136 startButton = new QPushButton( tr( "&Start Tests!" ), this ); 136 startButton = new QPushButton( tr( "&Start Tests!" ), this );
137 QWhatsThis::add( startButton, tr( "Click here to perform the selected tests." ) ); 137 QWhatsThis::add( startButton, tr( "Click here to perform the selected tests." ) );
138 connect( startButton, SIGNAL( clicked() ), this, SLOT( run() ) ); 138 connect( startButton, SIGNAL( clicked() ), this, SLOT( run() ) );
139 vb->addWidget( tests, 2 ); 139 vb->addWidget( tests, 2 );
140 140
141 QFile f( QPEApplication::qpeDir() + "/share/sysinfo/results" ); 141 QFile f( QPEApplication::qpeDir() + "/share/sysinfo/results" );
142 if ( f.open( IO_ReadOnly ) ) 142 if ( f.open( IO_ReadOnly ) )
143 { 143 {
144 machineCombo = new QComboBox( this ); 144 machineCombo = new QComboBox( this );
145 QWhatsThis::add( machineCombo, tr( "Choose a model to compare your results with." ) ); 145 QWhatsThis::add( machineCombo, tr( "Choose a model to compare your results with." ) );
146 146
147 QTextStream ts( &f ); 147 QTextStream ts( &f );
148 while( !ts.eof() ) 148 while( !ts.eof() )
149 { 149 {
150 QString machline = ts.readLine(); 150 QString machline = ts.readLine();
151 qDebug( "sysinfo: parsing benchmark results for '%s'", (const char*) machline ); 151 odebug << "sysinfo: parsing benchmark results for '" << (const char*) machline << "'" << oendl;
152 QString resline = ts.readLine(); 152 QString resline = ts.readLine();
153 machines.insert( machline, new QStringList( QStringList::split( ",", resline ) ) ); 153 machines.insert( machline, new QStringList( QStringList::split( ",", resline ) ) );
154 machineCombo->insertItem( machline ); 154 machineCombo->insertItem( machline );
155 } 155 }
156 156
157 QHBoxLayout* hb = new QHBoxLayout( vb ); 157 QHBoxLayout* hb = new QHBoxLayout( vb );
158 hb->addWidget( new QLabel( tr( "Compare To:" ), this ) ); 158 hb->addWidget( new QLabel( tr( "Compare To:" ), this ) );
159 hb->addWidget( machineCombo, 2 ); 159 hb->addWidget( machineCombo, 2 );
160 connect( machineCombo, SIGNAL( activated(int) ), this, SLOT( machineActivated(int) ) ); 160 connect( machineCombo, SIGNAL( activated(int) ), this, SLOT( machineActivated(int) ) );
161 } 161 }
162 162
163 vb->addWidget( startButton, 2 ); 163 vb->addWidget( startButton, 2 );
164} 164}
165 165
166 166
167BenchmarkInfo::~BenchmarkInfo() 167BenchmarkInfo::~BenchmarkInfo()
168{} 168{}
169 169
170 170
171void BenchmarkInfo::machineActivated( int index ) 171void BenchmarkInfo::machineActivated( int index )
172{ 172{
173 QStringList* results = machines[ machineCombo->text( index ) ]; 173 QStringList* results = machines[ machineCombo->text( index ) ];
174 if ( !results ) 174 if ( !results )
175 { 175 {
176 qDebug( "sysinfo: no results available." ); 176 odebug << "sysinfo: no results available." << oendl;
177 return; 177 return;
178 } 178 }
179 QStringList::Iterator it = results->begin(); 179 QStringList::Iterator it = results->begin();
180 test_alu->setText( 2, *(it++) ); 180 test_alu->setText( 2, *(it++) );
181 test_fpu->setText( 2, *(it++) ); 181 test_fpu->setText( 2, *(it++) );
182 test_txt->setText( 2, *(it++) ); 182 test_txt->setText( 2, *(it++) );
183 test_gfx->setText( 2, *(it++) ); 183 test_gfx->setText( 2, *(it++) );
184 test_ram->setText( 2, *(it++) ); 184 test_ram->setText( 2, *(it++) );
185 test_sd->setText( 2, *(it++) ); 185 test_sd->setText( 2, *(it++) );
186 test_cf->setText( 2, *(it++) ); 186 test_cf->setText( 2, *(it++) );
187} 187}
188 188
189 189
190void BenchmarkInfo::run() 190void BenchmarkInfo::run()
191{ 191{
192 startButton->setText( "> Don't touch! Running Tests! Don't touch! <" ); 192 startButton->setText( "> Don't touch! Running Tests! Don't touch! <" );
193 qApp->processEvents(); 193 qApp->processEvents();
194 QTime t; 194 QTime t;
195 195
196 if ( test_alu->isOn() ) 196 if ( test_alu->isOn() )
197 { 197 {
198 int d = round( dhry_main( DHRYSTONE_RUNS ) ); 198 int d = round( dhry_main( DHRYSTONE_RUNS ) );
199 test_alu->setText( 1, QString( "%1 dhrys" ).arg( QString::number( d ) ) ); 199 test_alu->setText( 1, QString( "%1 dhrys" ).arg( QString::number( d ) ) );
200 test_alu->setOn( false ); 200 test_alu->setOn( false );
201 } 201 }
202 202
203 if ( test_fpu->isOn() ) 203 if ( test_fpu->isOn() )
204 { 204 {
205 t.start(); 205 t.start();
206 BenchFFT(); 206 BenchFFT();
207 test_fpu->setText( 1, QString( "%1 secs" ).arg( QString::number( t.elapsed() / 1000.0 ) ) ); 207 test_fpu->setText( 1, QString( "%1 secs" ).arg( QString::number( t.elapsed() / 1000.0 ) ) );
208 test_fpu->setOn( false ); 208 test_fpu->setOn( false );
209 } 209 }
210 210
211 if ( test_txt->isOn() ) 211 if ( test_txt->isOn() )
212 { 212 {
213 int value = textRendering( TEST_DURATION ); 213 int value = textRendering( TEST_DURATION );
214 test_txt->setText( 1, QString( "%1 chars/sec" ).arg( QString::number( value / TEST_DURATION ) ) ); 214 test_txt->setText( 1, QString( "%1 chars/sec" ).arg( QString::number( value / TEST_DURATION ) ) );
215 test_txt->setOn( false ); 215 test_txt->setOn( false );
216 } 216 }
217 217
218 if ( test_gfx->isOn() ) 218 if ( test_gfx->isOn() )
219 { 219 {
220 int value = gfxRendering( TEST_DURATION ); 220 int value = gfxRendering( TEST_DURATION );
221 test_gfx->setText( 1, QString( "%1 gops/sec" ).arg( QString::number( value / 4 / TEST_DURATION ) ) ); // 4 tests 221 test_gfx->setText( 1, QString( "%1 gops/sec" ).arg( QString::number( value / 4 / TEST_DURATION ) ) ); // 4 tests
222 test_gfx->setOn( false ); 222 test_gfx->setOn( false );
223 } 223 }
224 224
225 if ( test_ram->isOn() ) // /tmp is supposed to be in RAM on a PDA 225 if ( test_ram->isOn() ) // /tmp is supposed to be in RAM on a PDA
226 { 226 {
227 performFileTest( "/tmp/benchmarkFile.dat", test_ram ); 227 performFileTest( "/tmp/benchmarkFile.dat", test_ram );
228 } 228 }
229 229
230 if ( test_cf->isOn() ) 230 if ( test_cf->isOn() )
231 { 231 {
232 OStorageInfo storage; 232 OStorageInfo storage;
233 performFileTest( storage.cfPath() + "/benchmarkFile.dat", test_cf ); 233 performFileTest( storage.cfPath() + "/benchmarkFile.dat", test_cf );
234 } 234 }
235 235
236 if ( test_sd->isOn() ) 236 if ( test_sd->isOn() )
237 { 237 {
238 OStorageInfo storage; 238 OStorageInfo storage;
239 performFileTest( storage.sdPath() + "/benchmarkFile.dat", test_sd ); 239 performFileTest( storage.sdPath() + "/benchmarkFile.dat", test_sd );
240 } 240 }
241 241
242 startButton->setText( tr( "&Start Tests!" ) ); 242 startButton->setText( tr( "&Start Tests!" ) );
243} 243}
244 244
245 245
246int BenchmarkInfo::textRendering( int seconds ) 246int BenchmarkInfo::textRendering( int seconds )
247{ 247{
248 QTime t; 248 QTime t;
249 t.start(); 249 t.start();
250 int stop = t.elapsed() + seconds * 1000; 250 int stop = t.elapsed() + seconds * 1000;
251 251
252 int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 }; 252 int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 };
253 int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 }; 253 int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 };
254 int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 }; 254 int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 };
255 const QString text( "Opie Benchmark Test" ); 255 const QString text( "Opie Benchmark Test" );
256 256
257 int w = QApplication::desktop()->width(); 257 int w = QApplication::desktop()->width();
258 int h = QApplication::desktop()->height(); 258 int h = QApplication::desktop()->height();
259 259
260 srand( time( NULL ) ); 260 srand( time( NULL ) );
261 261
262 BenchmarkPaintWidget bpw; 262 BenchmarkPaintWidget bpw;
263 263
264 int loops = 0; 264 int loops = 0;
265 265
266 while ( t.elapsed() < stop ) 266 while ( t.elapsed() < stop )
267 { 267 {
268 int k = rand() % 9; 268 int k = rand() % 9;
269 int s = rand() % 100; 269 int s = rand() % 100;
270 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) ); 270 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
271 bpw.p.setFont( QFont( "Vera", s ) ); 271 bpw.p.setFont( QFont( "Vera", s ) );
272 bpw.p.drawText( rand() % w, rand() % h, text, text.length() ); 272 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 @@
1#include "tabmanager.h" 1#include "tabmanager.h"
2#include "app.h" 2#include "app.h"
3#include "wait.h" 3#include "wait.h"
4#include "tabapplnk.h" 4#include "tabapplnk.h"
5 5
6#include <qpe/applnk.h> 6#include <qpe/applnk.h>
7#include <qdir.h> 7#include <qdir.h>
8#include <qfile.h> 8#include <qfile.h>
9#include <qtextstream.h> 9#include <qtextstream.h>
10#include <qlistview.h> 10#include <qlistview.h>
11#include <qheader.h> 11#include <qheader.h>
12#include <qcombobox.h> 12#include <qcombobox.h>
13#include <qlineedit.h> 13#include <qlineedit.h>
14#include <qlabel.h> 14#include <qlabel.h>
15#include <qmessagebox.h> 15#include <qmessagebox.h>
16#include <stdlib.h> 16#include <stdlib.h>
17#include <qpe/qcopenvelope_qws.h> 17#include <qpe/qcopenvelope_qws.h>
18#include <qpe/qpeapplication.h> 18#include <qpe/qpeapplication.h>
19#include <qpe/resource.h> 19#include <qpe/resource.h>
20 20
21 21
22#define HOME_APP_DIR QPEApplication::qpeDir()+"/apps" 22#define HOME_APP_DIR QPEApplication::qpeDir()+"/apps"
23#define HOME_APP_INSTALL_DIR "/usr/lib/ipkg/info" 23#define HOME_APP_INSTALL_DIR "/usr/lib/ipkg/info"
24#define NEW_FOLDER "EmptyTab" 24#define NEW_FOLDER "EmptyTab"
25#define NEW_APPLICATION "NewApp" 25#define NEW_APPLICATION "NewApp"
26#define APPLICATION_EXTENSION ".desktop" 26#define APPLICATION_EXTENSION ".desktop"
27#define APPLICATION_EXTENSION_LENGTH 8 27#define APPLICATION_EXTENSION_LENGTH 8
28 28
29/** 29/**
30 * Constructor. Sets up signals. Performs initial scan of applications 30 * Constructor. Sets up signals. Performs initial scan of applications
31 * and tabs 31 * and tabs
32 */ 32 */
33TabManager::TabManager( QWidget* parent, const char* name):TabManagerBase(parent, name), changed(false), application(NULL){ 33TabManager::TabManager( QWidget* parent, const char* name):TabManagerBase(parent, name), changed(false), application(NULL){
34 rescanFolder(HOME_APP_DIR); 34 rescanFolder(HOME_APP_DIR);
35 35
36 // Connect the signals and slots 36 // Connect the signals and slots
37 connect(tabList, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(editItem(QListViewItem*))); 37 connect(tabList, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(editItem(QListViewItem*)));
38 (tabList->header())->hide(); 38 (tabList->header())->hide();
39 connect(tabList, SIGNAL(moveItem(QListViewItem*,QListViewItem*)), this, SLOT(moveApplication(QListViewItem*,QListViewItem*))); 39 connect(tabList, SIGNAL(moveItem(QListViewItem*,QListViewItem*)), this, SLOT(moveApplication(QListViewItem*,QListViewItem*)));
40} 40}
41 41
42/** 42/**
43 * If anything in the tab's have been changed then update the system or alert 43 * If anything in the tab's have been changed then update the system or alert
44 * the user. 44 * the user.
45 */ 45 */
46TabManager::~TabManager(){ 46TabManager::~TabManager(){
47 if(changed){ 47 if(changed){
48 // Prompt. 48 // Prompt.
49 //int answer = QMessageBox::warning(this, "Message", "Should your desktop be","Yes", "Cancel", 0, 1 ); 49 //int answer = QMessageBox::warning(this, "Message", "Should your desktop be","Yes", "Cancel", 0, 1 );
50 //if (answer) 50 //if (answer)
51 // return; 51 // return;
52 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 52 QCopEnvelope e("QPE/System", "linkChanged(QString)");
53 QString link; //we'll just send an empty string 53 QString link; //we'll just send an empty string
54 e << link; 54 e << link;
55 } 55 }
56} 56}
57 57
58/** 58/**
59 * Scans root directory for any tabs or applications. Will recursivly go down, 59 * Scans root directory for any tabs or applications. Will recursivly go down,
60 * but will not follow symlinks. 60 * but will not follow symlinks.
61 * @param directory - the directory to look in. 61 * @param directory - the directory to look in.
62 * @param parent - the parent to place any new tabs or apps into. If parent is 62 * @param parent - the parent to place any new tabs or apps into. If parent is
63 * NULL then the item is a tab and should be placed as a child of the window. 63 * NULL then the item is a tab and should be placed as a child of the window.
64 */ 64 */
65void TabManager::rescanFolder(QString directory, QListViewItem* parent){ 65void TabManager::rescanFolder(QString directory, QListViewItem* parent){
66 //qDebug(QString("rescanFolder: ") + directory.latin1()); 66 //odebug << QString("rescanFolder: ") + directory.latin1() << oendl;
67 67
68 QDir d; 68 QDir d;
69 d.setPath(directory); 69 d.setPath(directory);
70 // Show hidden files for .directories 70 // Show hidden files for .directories
71 d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs); 71 d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs);
72 72
73 const QFileInfoList *list = d.entryInfoList(); 73 const QFileInfoList *list = d.entryInfoList();
74 QFileInfoListIterator it( *list ); // create list iterator 74 QFileInfoListIterator it( *list ); // create list iterator
75 QFileInfo *fi; // pointer for traversing 75 QFileInfo *fi; // pointer for traversing
76 76
77 while ( (fi=it.current()) ) { // for each file... 77 while ( (fi=it.current()) ) { // for each file...
78 // If it is a dir and not .. or . then add it as a tab and go down. 78 // If it is a dir and not .. or . then add it as a tab and go down.
79 if(fi->isDir()){ 79 if(fi->isDir()){
80 if(fi->fileName() != ".." && fi->fileName() != ".") { 80 if(fi->fileName() != ".." && fi->fileName() != ".") {
81 QListViewItem* newItem; 81 QListViewItem* newItem;
82 if(!parent) 82 if(!parent)
83 newItem = new QListViewItem(tabList, fi->fileName()); 83 newItem = new QListViewItem(tabList, fi->fileName());
84 else 84 else
85 newItem = new QListViewItem(parent, fi->fileName()); 85 newItem = new QListViewItem(parent, fi->fileName());
86 itemList.insert(newItem, directory + "/" + fi->fileName() + "/.directory" ); 86 itemList.insert(newItem, directory + "/" + fi->fileName() + "/.directory" );
87 rescanFolder(directory + "/" + fi->fileName(), newItem); 87 rescanFolder(directory + "/" + fi->fileName(), newItem);
88 } 88 }
89 } 89 }
90 else{ 90 else{
91 // it is a file, if not a .directory add to parent. 91 // it is a file, if not a .directory add to parent.
92 92
93 // Change parents name and icon to reflect icon. 93 // Change parents name and icon to reflect icon.
94 if(fi->fileName() == ".directory"){ 94 if(fi->fileName() == ".directory"){
95 AppLnk app(directory + "/" + fi->fileName()); 95 AppLnk app(directory + "/" + fi->fileName());
96 if(parent){ 96 if(parent){
97 parent->setPixmap(0,app.pixmap()); 97 parent->setPixmap(0,app.pixmap());
98 parent->setText(0, app.name()); 98 parent->setText(0, app.name());
99 } 99 }
100 } 100 }
101 else{ 101 else{
102 // Add any desktop files found. 102 // Add any desktop files found.
103 QListViewItem* newItem; 103 QListViewItem* newItem;
104 if(directory != HOME_APP_DIR){ 104 if(directory != HOME_APP_DIR){
105 if(!parent) 105 if(!parent)
106 newItem = new QListViewItem(tabList, fi->fileName()); 106 newItem = new QListViewItem(tabList, fi->fileName());
107 else 107 else
108 newItem = new QListViewItem(parent, fi->fileName()); 108 newItem = new QListViewItem(parent, fi->fileName());
109 if(fi->fileName().right(APPLICATION_EXTENSION_LENGTH) == APPLICATION_EXTENSION){ 109 if(fi->fileName().right(APPLICATION_EXTENSION_LENGTH) == APPLICATION_EXTENSION){
110 AppLnk app(directory + "/" + fi->fileName()); 110 AppLnk app(directory + "/" + fi->fileName());
111 newItem->setPixmap(0,app.pixmap()); 111 newItem->setPixmap(0,app.pixmap());
112 newItem->setText(0, app.name()); 112 newItem->setText(0, app.name());
113 itemList.insert(newItem, directory + "/" + fi->fileName()); 113 itemList.insert(newItem, directory + "/" + fi->fileName());
114 } 114 }
115 } 115 }
116 } 116 }
117 } 117 }
118 ++it; // goto next list element 118 ++it; // goto next list element
119 } 119 }
120} 120}
121 121
122/** 122/**
123 * Create a new blank Tab. 123 * Create a new blank Tab.
124 * Create a physical folder with .directory file 124 * Create a physical folder with .directory file
125 * Create a item on the list 125 * Create a item on the list
126 */ 126 */
127void TabManager::newFolder(){ 127void TabManager::newFolder(){
128 QDir r; 128 QDir r;
129 r.mkdir(QString(HOME_APP_DIR) + "/" + NEW_FOLDER); 129 r.mkdir(QString(HOME_APP_DIR) + "/" + NEW_FOLDER);
130 system((QString("echo [Desktop Entry] | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1()); 130 system((QString("echo [Desktop Entry] | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1());
131 system((QString("echo Name=" NEW_FOLDER " | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1()); 131 system((QString("echo Name=" NEW_FOLDER " | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1());
132 132
133 QString homeLocation = QString(HOME_APP_DIR) + "/" + NEW_FOLDER + "/.directory"; 133 QString homeLocation = QString(HOME_APP_DIR) + "/" + NEW_FOLDER + "/.directory";
134 QListViewItem *newItem = new QListViewItem(tabList, NEW_FOLDER); 134 QListViewItem *newItem = new QListViewItem(tabList, NEW_FOLDER);
135 itemList.insert(newItem, homeLocation ); 135 itemList.insert(newItem, homeLocation );
136 136
137 // We have changed something. 137 // We have changed something.
138 changed = true; 138 changed = true;
139} 139}
140 140
141/** 141/**
142 * Create a new blank application 142 * Create a new blank application
143 * Make sure a tab is selected 143 * Make sure a tab is selected
144 * create physical file 144 * create physical file
145 * fill file with default information (entry, name, type). 145 * fill file with default information (entry, name, type).
146 */ 146 */
147void TabManager::newApplication(){ 147void TabManager::newApplication(){
148 QListViewItem *item = tabList->currentItem(); 148 QListViewItem *item = tabList->currentItem();
149 if(!item || item->parent()) 149 if(!item || item->parent())
150 return; 150 return;
151 151
152 QString parentDir = itemList[item].mid(0,itemList[item].length()-11); 152 QString parentDir = itemList[item].mid(0,itemList[item].length()-11);
153 QString homeLocation = parentDir + "/" NEW_APPLICATION APPLICATION_EXTENSION; 153 QString homeLocation = parentDir + "/" NEW_APPLICATION APPLICATION_EXTENSION;
154 system((QString("echo [Desktop Entry] | cat >> ") + homeLocation).latin1()); 154 system((QString("echo [Desktop Entry] | cat >> ") + homeLocation).latin1());
155 system((QString("echo Name=" NEW_APPLICATION " | cat >> ") + homeLocation).latin1()); 155 system((QString("echo Name=" NEW_APPLICATION " | cat >> ") + homeLocation).latin1());
156 int slash = parentDir.findRev('/', -1); 156 int slash = parentDir.findRev('/', -1);
157 QString folderName = parentDir.mid(slash+1, parentDir.length()); 157 QString folderName = parentDir.mid(slash+1, parentDir.length());
158 158
159 system((QString("echo Type=") + folderName + " | cat >> " + homeLocation).latin1()); 159 system((QString("echo Type=") + folderName + " | cat >> " + homeLocation).latin1());
160 160
161 // Insert into the tree 161 // Insert into the tree
162 QListViewItem *newItem = new QListViewItem(item, NEW_APPLICATION); 162 QListViewItem *newItem = new QListViewItem(item, NEW_APPLICATION);
163 itemList.insert(newItem, homeLocation ); 163 itemList.insert(newItem, homeLocation );
164 164
165 // We have changed something. 165 // We have changed something.
166 changed = true; 166 changed = true;
167} 167}
168 168
169/** 169/**
170 * Remove the item. 170 * Remove the item.
171 * Check if we can 171 * Check if we can
172 * Prompt user 172 * Prompt user
173 * Delete physical file (Dir, remove .dir, then dir. File, remove file) 173 * Delete physical file (Dir, remove .dir, then dir. File, remove file)
174 * Remove from installer if need too. 174 * Remove from installer if need too.
175 */ 175 */
176void TabManager::removeItem(){ 176void TabManager::removeItem(){
177 // Make sure we can delete 177 // Make sure we can delete
178 QListViewItem *item = tabList->currentItem(); 178 QListViewItem *item = tabList->currentItem();
179 if(!item) 179 if(!item)
180 return; 180 return;
181 if(item->childCount() > 0){ 181 if(item->childCount() > 0){
182 QMessageBox::critical(this, tr("Message"), tr("Can't remove with applications\nstill in the group."), tr("Ok") ); 182 QMessageBox::critical(this, tr("Message"), tr("Can't remove with applications\nstill in the group."), tr("Ok") );
183 return; 183 return;
184 } 184 }
185 185
186 // Prompt. 186 // Prompt.
187 int answer = QMessageBox::warning(this, tr("Message"), tr("Are you sure you want to delete?"), tr("Yes"), tr("Cancel"), 0, 1 ); 187 int answer = QMessageBox::warning(this, tr("Message"), tr("Are you sure you want to delete?"), tr("Yes"), tr("Cancel"), 0, 1 );
188 if (answer) 188 if (answer)
189 return; 189 return;
190 190
191 bool removeSuccessful = true; 191 bool removeSuccessful = true;
192 QString location = itemList[item]; 192 QString location = itemList[item];
193 // Remove file (.directory in a Directory case) 193 // Remove file (.directory in a Directory case)
194 if(!QFile::remove(location)) 194 if(!QFile::remove(location))
195 removeSuccessful = false; 195 removeSuccessful = false;
196 196
197 // Remove directory 197 // Remove directory
198 if(item->parent() == NULL){ 198 if(item->parent() == NULL){
199 // Remove .directory file string 199 // Remove .directory file string
200 location = location.mid(0,location.length()-10); 200 location = location.mid(0,location.length()-10);
201 QDir dir; 201 QDir dir;
202 if(!dir.rmdir(location)) 202 if(!dir.rmdir(location))
203 removeSuccessful = false; 203 removeSuccessful = false;
204 else 204 else
205 removeSuccessful = true; 205 removeSuccessful = true;
206 } 206 }
207 207
208 // If removing failed. 208 // If removing failed.
209 if(!removeSuccessful){ 209 if(!removeSuccessful){
210 qDebug((QString("removeItem: ") + location).latin1()); 210 odebug << (QString("removeItem: ") + location).latin1() << oendl;
211 QMessageBox::critical(this, tr("Message"), tr("Can't remove."), tr("Ok") ); 211 QMessageBox::critical(this, tr("Message"), tr("Can't remove."), tr("Ok") );
212 return; 212 return;
213 } 213 }
214 214
215 // Remove from the installer so it wont fail. 215 // Remove from the installer so it wont fail.
216 // Don't need to do this sense the current install uses rm -f so no error 216 // Don't need to do this sense the current install uses rm -f so no error
217 217
218 // Remove from the gui list. 218 // Remove from the gui list.
219 itemList.remove(item); 219 itemList.remove(item);
220 if(item->parent()) 220 if(item->parent())
221 item->parent()->takeItem(item); 221 item->parent()->takeItem(item);
222 delete item; 222 delete item;
223 223
224 // We have changed something. 224 // We have changed something.
225 changed = true; 225 changed = true;
226} 226}
227 227
228/** 228/**
229 * Helper function. Edits the current item. 229 * Helper function. Edits the current item.
230 * calls editItem with the currently selected item. 230 * calls editItem with the currently selected item.
231 */ 231 */
232void TabManager::editCurrentItem(){ 232void TabManager::editCurrentItem(){
233 editItem(tabList->currentItem()); 233 editItem(tabList->currentItem());
234} 234}
235 235
236/** 236/**
237 * Edit the item that is passed in. 237 * Edit the item that is passed in.
238 * Show application dialog and if anything changed 238 * Show application dialog and if anything changed
239 * @param item the item to edit. 239 * @param item the item to edit.
240 */ 240 */
241void TabManager::editItem( QListViewItem * item){ 241void TabManager::editItem( QListViewItem * item){
242 if(!item) 242 if(!item)
243 return; 243 return;
244 244
245 TabAppLnk app(itemList[item]); 245 TabAppLnk app(itemList[item]);
246 if(!app.isValid()){ 246 if(!app.isValid()){
247 qDebug(QString("editItem: Not a valid applnk file: ") + itemList[item].latin1()); 247 odebug << QString("editItem: Not a valid applnk file: ") + itemList[item].latin1() << oendl;
248 return; 248 return;
249 } 249 }
250 250
251 // Fill with all of the icons 251 // Fill with all of the icons
252 if(!application){ 252 if(!application){
253 Wait waitDialog(this, "Wait dialog"); 253 Wait waitDialog(this, "Wait dialog");
254 waitDialog.waitLabel->setText(tr("Gathering icons...")); 254 waitDialog.waitLabel->setText(tr("Gathering icons..."));
255 waitDialog.show(); 255 waitDialog.show();
256 qApp->processEvents(); 256 qApp->processEvents();
257 application = new AppEdit(this, "Application edit", true); 257 application = new AppEdit(this, "Application edit", true);
258 258
259 QDir d(QPEApplication::qpeDir() + "/pics/"); 259 QDir d(QPEApplication::qpeDir() + "/pics/");
260 d.setFilter( QDir::Files); 260 d.setFilter( QDir::Files);
261 261
262 const QFileInfoList *list = d.entryInfoList(); 262 const QFileInfoList *list = d.entryInfoList();
263 QFileInfoListIterator it( *list ); // create list iterator 263 QFileInfoListIterator it( *list ); // create list iterator
264 QFileInfo *fi; // pointer for traversing 264 QFileInfo *fi; // pointer for traversing
265 265
266 while ( (fi=it.current()) ) { // for each file... 266 while ( (fi=it.current()) ) { // for each file...
267 QString fileName = fi->fileName(); 267 QString fileName = fi->fileName();
268 if(fileName.right(4) == ".png"){ 268 if(fileName.right(4) == ".png"){
269 fileName = fileName.mid(0,fileName.length()-4); 269 fileName = fileName.mid(0,fileName.length()-4);
270 QPixmap imageOfFile(Resource::loadPixmap(fileName)); 270 QPixmap imageOfFile(Resource::loadPixmap(fileName));
271 QImage foo = imageOfFile.convertToImage(); 271 QImage foo = imageOfFile.convertToImage();
272 foo = foo.smoothScale(16,16); 272 foo = foo.smoothScale(16,16);
273 imageOfFile.convertFromImage(foo); 273 imageOfFile.convertFromImage(foo);
274 application->iconLineEdit->insertItem(imageOfFile,fileName); 274 application->iconLineEdit->insertItem(imageOfFile,fileName);
275 } 275 }
276 //qDebug(fi->fileName().latin1()); 276 //odebug << fi->fileName().latin1() << oendl;
277 ++it; 277 ++it;
278 } 278 }
279 waitDialog.hide(); 279 waitDialog.hide();
280 } 280 }
281 int pixmap = -1; 281 int pixmap = -1;
282 QString pixmapText = app.pixmapString(); 282 QString pixmapText = app.pixmapString();
283 QComboBox *f = application->iconLineEdit; 283 QComboBox *f = application->iconLineEdit;
284 for(int i = 0; i < application->iconLineEdit->count(); i++){ 284 for(int i = 0; i < application->iconLineEdit->count(); i++){
285 if(f->text(i) == pixmapText){ 285 if(f->text(i) == pixmapText){
286 pixmap = i; 286 pixmap = i;
287 break; 287 break;
288 } 288 }
289 } 289 }
290 if(pixmap != -1) 290 if(pixmap != -1)
291 application->iconLineEdit->setCurrentItem(pixmap); 291 application->iconLineEdit->setCurrentItem(pixmap);
292 else if(pixmapText.isEmpty()){ 292 else if(pixmapText.isEmpty()){
293 application->iconLineEdit->setCurrentItem(0); 293 application->iconLineEdit->setCurrentItem(0);
294 } 294 }
295 else{ 295 else{
296 QPixmap imageOfFile(Resource::loadPixmap(pixmapText)); 296 QPixmap imageOfFile(Resource::loadPixmap(pixmapText));
297 QImage foo = imageOfFile.convertToImage(); 297 QImage foo = imageOfFile.convertToImage();
298 foo = foo.smoothScale(16,16); 298 foo = foo.smoothScale(16,16);
299 imageOfFile.convertFromImage(foo); 299 imageOfFile.convertFromImage(foo);
300 application->iconLineEdit->insertItem(imageOfFile,pixmapText,0); 300 application->iconLineEdit->insertItem(imageOfFile,pixmapText,0);
301 application->iconLineEdit->setCurrentItem(0); 301 application->iconLineEdit->setCurrentItem(0);
302 } 302 }
303 303
304 application->nameLineEdit->setText(app.name()); 304 application->nameLineEdit->setText(app.name());
305 application->execLineEdit->setText(app.exec()); 305 application->execLineEdit->setText(app.exec());
306 application->commentLineEdit->setText(app.comment()); 306 application->commentLineEdit->setText(app.comment());
307 307
308 if(item->parent() == NULL){ 308 if(item->parent() == NULL){
309 application->execLineEdit->setEnabled(false); 309 application->execLineEdit->setEnabled(false);
310 application->TextLabel3->setEnabled(false); 310 application->TextLabel3->setEnabled(false);
311 application->setCaption(tr("Tab")); 311 application->setCaption(tr("Tab"));
312 } 312 }
313 else{ 313 else{
314 application->execLineEdit->setEnabled(true); 314 application->execLineEdit->setEnabled(true);
315 application->TextLabel3->setEnabled(true); 315 application->TextLabel3->setEnabled(true);
316 application->setCaption(tr("Application")); 316 application->setCaption(tr("Application"));
317 } 317 }
318 318
319 // Only do somthing if they hit OK 319 // Only do somthing if they hit OK
320 application->showMaximized(); 320 application->showMaximized();
321 if(application->exec() == 0) 321 if(application->exec() == 0)
322 return; 322 return;
323 323
324 // If nothing has changed exit (hmmm why did they hit ok?) 324 // If nothing has changed exit (hmmm why did they hit ok?)
325 if(app.name() == application->nameLineEdit->text() && 325 if(app.name() == application->nameLineEdit->text() &&
326 app.pixmapString() == application->iconLineEdit->currentText() && 326 app.pixmapString() == application->iconLineEdit->currentText() &&
327 app.comment() == application->commentLineEdit->text() && 327 app.comment() == application->commentLineEdit->text() &&
328 app.exec() == application->execLineEdit->text()) 328 app.exec() == application->execLineEdit->text())
329 return; 329 return;
330 330
331 // Change the applnk file 331 // Change the applnk file
332 QString oldName = app.name(); 332 QString oldName = app.name();
333 app.setName(application->nameLineEdit->text()); 333 app.setName(application->nameLineEdit->text());
334 app.setIcon(application->iconLineEdit->currentText()); 334 app.setIcon(application->iconLineEdit->currentText());
335 app.setComment(application->commentLineEdit->text()); 335 app.setComment(application->commentLineEdit->text());
336 app.setExec(application->execLineEdit->text()); 336 app.setExec(application->execLineEdit->text());
337 if(!app.writeLink()){ 337 if(!app.writeLink()){
338 QMessageBox::critical(this, tr("Message"), "Can't save.", tr("Ok") ); 338 QMessageBox::critical(this, tr("Message"), "Can't save.", tr("Ok") );
339 return; 339 return;
340 } 340 }
341 341
342 // Update the gui icon and name 342 // Update the gui icon and name
343 item->setText(0,app.name()); 343 item->setText(0,app.name());
344 item->setPixmap(0,app.pixmap()); 344 item->setPixmap(0,app.pixmap());
345 345
346 // We have changed something. 346 // We have changed something.
347 changed = true; 347 changed = true;
348 348
349 // If we were dealing with a new folder or new application change 349 // If we were dealing with a new folder or new application change
350 // the file names. Also change the item location in itemList 350 // the file names. Also change the item location in itemList
351 if(oldName == NEW_FOLDER){ 351 if(oldName == NEW_FOLDER){
352 QDir r; 352 QDir r;
353 QString oldName = itemList[item]; 353 QString oldName = itemList[item];
354 oldName = oldName.mid(0,oldName.length()-11); 354 oldName = oldName.mid(0,oldName.length()-11);
355 QString newName = oldName.mid(0,oldName.length()-9); 355 QString newName = oldName.mid(0,oldName.length()-9);
356 newName = newName + "/" + app.name(); 356 newName = newName + "/" + app.name();
357 r.rename(oldName, newName); 357 r.rename(oldName, newName);
358 itemList.remove(item); 358 itemList.remove(item);
359 itemList.insert(item, newName + "/.directory" ); 359 itemList.insert(item, newName + "/.directory" );
360 } 360 }
361 else if(oldName == NEW_APPLICATION){ 361 else if(oldName == NEW_APPLICATION){
362 if(!item->parent()) 362 if(!item->parent())
363 return; 363 return;
364 QString parentDir = itemList[item->parent()]; 364 QString parentDir = itemList[item->parent()];
365 QDir r; 365 QDir r;
366 QString oldName = itemList[item]; 366 QString oldName = itemList[item];
367 QString newName = oldName.mid(0, parentDir.length()-10); 367 QString newName = oldName.mid(0, parentDir.length()-10);
368 newName = newName + app.name() + APPLICATION_EXTENSION; 368 newName = newName + app.name() + APPLICATION_EXTENSION;
369 r.rename(oldName, newName); 369 r.rename(oldName, newName);
370 itemList.remove(item); 370 itemList.remove(item);
371 itemList.insert(item, newName); 371 itemList.insert(item, newName);
372 } 372 }
373} 373}
374 374
375/** 375/**
376 * Move an application from one directory to another. 376 * Move an application from one directory to another.
377 * Move in the gui, move in the applnk file, move in the installer. 377 * Move in the gui, move in the applnk file, move in the installer.
378 * @param item the application to move 378 * @param item the application to move
379 * @pearam newGroup the new parent of this application 379 * @pearam newGroup the new parent of this application
380 */ 380 */
381void TabManager::moveApplication(QListViewItem *item, QListViewItem *newGroup){ 381void TabManager::moveApplication(QListViewItem *item, QListViewItem *newGroup){
382 // Can we even move it? 382 // Can we even move it?
383 if(!item || !item->parent() || newGroup->parent()) 383 if(!item || !item->parent() || newGroup->parent())
384 return; 384 return;
385 if(item->parent() == newGroup) 385 if(item->parent() == newGroup)
386 return; 386 return;
387 387
388 // Get the new folder, new file name, 388 // Get the new folder, new file name,
389 QString newFolder = itemList[newGroup]; 389 QString newFolder = itemList[newGroup];
390 newFolder = newFolder.mid(0,newFolder.length()-11); 390 newFolder = newFolder.mid(0,newFolder.length()-11);
391 int slash = newFolder.findRev('/', -1); 391 int slash = newFolder.findRev('/', -1);
392 QString folderName = newFolder.mid(slash+1, newFolder.length()); 392 QString folderName = newFolder.mid(slash+1, newFolder.length());
393 393
394 QString desktopFile = itemList[item]; 394 QString desktopFile = itemList[item];
395 slash = desktopFile.findRev('/', -1); 395 slash = desktopFile.findRev('/', -1);
396 desktopFile = desktopFile.mid(slash, desktopFile.length()); 396 desktopFile = desktopFile.mid(slash, desktopFile.length());
397 newFolder = newFolder + desktopFile; 397 newFolder = newFolder + desktopFile;
398 398
399 // Move file 399 // Move file
400 QDir r; 400 QDir r;
401 if(!r.rename(itemList[item], newFolder)){ 401 if(!r.rename(itemList[item], newFolder)){
402 QMessageBox::critical(this, tr("Message"), "Can't move application.", tr("Ok") ); 402 QMessageBox::critical(this, tr("Message"), "Can't move application.", tr("Ok") );
403 return; 403 return;
404 } 404 }
405 //qDebug((QString("moveApplication: ") + itemList[item]).latin1()); 405 //odebug << (QString("moveApplication: ") + itemList[item]).latin1() << oendl;
406 //qDebug((QString("moveApplication: ") + newFolder).latin1()); 406 //odebug << (QString("moveApplication: ") + newFolder).latin1() << oendl;
407 407
408 // Move in the gui 408 // Move in the gui
409 item->parent()->takeItem(item); 409 item->parent()->takeItem(item);
410 newGroup->insertItem(item); 410 newGroup->insertItem(item);
411 newGroup->setOpen(true); 411 newGroup->setOpen(true);
412 412
413 // Move file in the installer 413 // Move file in the installer
414 QString installedAppFile; 414 QString installedAppFile;
415 if(findInstalledApplication(desktopFile, installedAppFile)) 415 if(findInstalledApplication(desktopFile, installedAppFile))
416 swapInstalledLocation(installedAppFile, desktopFile, newFolder); 416 swapInstalledLocation(installedAppFile, desktopFile, newFolder);
417 else 417 else
418 qDebug("moveApplication: No installed app found for dekstop file"); 418 odebug << "moveApplication: No installed app found for dekstop file" << oendl;
419 419
420 // Move application type 420 // Move application type
421 AppLnk app(newFolder); 421 AppLnk app(newFolder);
422 app.setType(folderName); 422 app.setType(folderName);
423 app.writeLink(); 423 app.writeLink();
424 424
425 // Move in our internal list 425 // Move in our internal list
426 itemList.remove(item); 426 itemList.remove(item);
427 itemList.insert(item, newFolder); 427 itemList.insert(item, newFolder);
428 428
429 // We have changed something. 429 // We have changed something.
430 changed = true; 430 changed = true;
431} 431}
432 432
433/** 433/**
434 * File the installed application that has this desktop file. 434 * File the installed application that has this desktop file.
435 * Go through each file in HOME_APP_INSTALL_DIR and see if it contains desktop 435 * Go through each file in HOME_APP_INSTALL_DIR and see if it contains desktop
436 * file 436 * file
437 * @param desktopFile - the .desktop file to search for [foo.desktop] 437 * @param desktopFile - the .desktop file to search for [foo.desktop]
438 * @param installedAppFile - location of the app install list 438 * @param installedAppFile - location of the app install list
439 * @return true if successful, false if file not found. 439 * @return true if successful, false if file not found.
440 */ 440 */
441bool TabManager::findInstalledApplication(QString desktopFile, QString &installedAppFile){ 441bool TabManager::findInstalledApplication(QString desktopFile, QString &installedAppFile){
442 442
443 QDir d; 443 QDir d;
444 d.setPath(HOME_APP_INSTALL_DIR); 444 d.setPath(HOME_APP_INSTALL_DIR);
445 d.setFilter( QDir::Files ); 445 d.setFilter( QDir::Files );
446 446
447 const QFileInfoList *list = d.entryInfoList(); 447 const QFileInfoList *list = d.entryInfoList();
448 QFileInfoListIterator it( *list ); // create list iterator 448 QFileInfoListIterator it( *list ); // create list iterator
449 QFileInfo *fi; // pointer for traversing 449 QFileInfo *fi; // pointer for traversing
450 450
451 while ( (fi=it.current()) ) { // for each file... 451 while ( (fi=it.current()) ) { // for each file...
452 QFile file(QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName()); 452 QFile file(QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName());
453 if ( file.open(IO_ReadOnly) ) { // file opened successfully 453 if ( file.open(IO_ReadOnly) ) { // file opened successfully
454 QTextStream stream( &file ); // use a text stream 454 QTextStream stream( &file ); // use a text stream
455 QString line; 455 QString line;
456 while ( !stream.eof() ) { // until end of file... 456 while ( !stream.eof() ) { // until end of file...
457 line = stream.readLine(); // line of text excluding '\n' 457 line = stream.readLine(); // line of text excluding '\n'
458 if(line.contains(desktopFile)){ 458 if(line.contains(desktopFile)){
459 installedAppFile = QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName(); 459 installedAppFile = QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName();
460 file.close(); 460 file.close();
461 return true; 461 return true;
462 } 462 }
463 } 463 }
464 file.close(); 464 file.close();
465 } 465 }
466 else 466 else
467 qDebug((QString("findInstalledApplication: Can't open file") + HOME_APP_INSTALL_DIR + "/" + fi->fileName()).latin1()); 467 odebug << (QString("findInstalledApplication: Can't open file") + HOME_APP_INSTALL_DIR + "/" + fi->fileName()).latin1() << oendl;
468 ++it; // goto next list element 468 ++it; // goto next list element
469 } 469 }
470 return false; 470 return false;
471} 471}
472 472
473/** 473/**
474 * Open a file and replace a file containing the old desktop file with the new. 474 * Open a file and replace a file containing the old desktop file with the new.
475 * @param installedAppFile application installed list 475 * @param installedAppFile application installed list
476 * @param desktopFile old .desktop file 476 * @param desktopFile old .desktop file
477 * @param newLocation new .desktop file 477 * @param newLocation new .desktop file
478 */ 478 */
479void TabManager::swapInstalledLocation( QString installedAppFile, QString desktopFile, QString newLocation ){ 479void TabManager::swapInstalledLocation( QString installedAppFile, QString desktopFile, QString newLocation ){
480 QFile file(installedAppFile); 480 QFile file(installedAppFile);
481 if ( !file.open(IO_ReadOnly) ){ 481 if ( !file.open(IO_ReadOnly) ){
482 qDebug(QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1()); 482 odebug << QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1() << oendl;
483 return; 483 return;
484 } 484 }
485 485
486 QTextStream stream( &file ); // use a text stream 486 QTextStream stream( &file ); // use a text stream
487 QString allLines; 487 QString allLines;
488 while ( !stream.eof() ) { // until end of file... 488 while ( !stream.eof() ) { // until end of file...
489 QString line = stream.readLine(); // line of text excluding '\n' 489 QString line = stream.readLine(); // line of text excluding '\n'
490 if(line.contains(desktopFile)) 490 if(line.contains(desktopFile))
491 allLines += newLocation; 491 allLines += newLocation;
492 else 492 else
493 allLines += line; 493 allLines += line;
494 allLines += '\n'; 494 allLines += '\n';
495 } 495 }
496 file.close(); 496 file.close();
497 497
498 if ( !file.open(IO_ReadWrite) ){ 498 if ( !file.open(IO_ReadWrite) ){
499 qDebug(QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1()); 499 odebug << QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1() << oendl;
500 return; 500 return;
501 } 501 }
502 QTextStream streamOut( &file ); 502 QTextStream streamOut( &file );
503 streamOut << allLines; 503 streamOut << allLines;
504 file.close(); 504 file.close();
505} 505}
506 506
507// tabmanager.cpp 507// tabmanager.cpp
508 508
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 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9 9
10#include "userdialog.h" 10#include "userdialog.h"
11#include "passwd.h" 11#include "passwd.h"
12 12
13/* OPIE */ 13/* OPIE */
14#include <opie2/odebug.h>
14#include <opie2/odevice.h> 15#include <opie2/odevice.h>
15#include <qpe/qpeapplication.h> 16#include <qpe/qpeapplication.h>
17using namespace Opie::Core;
18using namespace Opie::Ui;
16 19
17/* QT */ 20/* QT */
18#include <qlayout.h> 21#include <qlayout.h>
19#include <qlabel.h> 22#include <qlabel.h>
20#include <qmessagebox.h> 23#include <qmessagebox.h>
21#include <qfile.h> 24#include <qfile.h>
22 25
23/* STD */ 26/* STD */
24#include <sys/types.h> 27#include <sys/types.h>
25#include <sys/wait.h> 28#include <sys/wait.h>
26#include <unistd.h> 29#include <unistd.h>
27#include <signal.h> 30#include <signal.h>
28 31
29
30using namespace Opie::Core;
31
32
33/** 32/**
34 * UserDialog constructor. Setup the dialog, fill the groupComboBox & groupsListView with all groups. 33 * UserDialog constructor. Setup the dialog, fill the groupComboBox & groupsListView with all groups.
35 * 34 *
36 */ 35 */
37using namespace Opie::Ui;
38UserDialog::UserDialog(int viewmode, QWidget* parent, const char* name, bool modal, WFlags fl) : QDialog(parent, name, modal, fl) 36UserDialog::UserDialog(int viewmode, QWidget* parent, const char* name, bool modal, WFlags fl) : QDialog(parent, name, modal, fl)
39{ 37{
40 vm=viewmode; 38 vm=viewmode;
41 QVBoxLayout *layout = new QVBoxLayout(this); 39 QVBoxLayout *layout = new QVBoxLayout(this);
42 myTabWidget=new QTabWidget(this,"User Tab Widget"); 40 myTabWidget=new QTabWidget(this,"User Tab Widget");
43 layout->addWidget(myTabWidget); 41 layout->addWidget(myTabWidget);
44 setupTab1(); 42 setupTab1();
45 setupTab2(); 43 setupTab2();
46 44
47 accounts->groupStringList.sort(); 45 accounts->groupStringList.sort();
48 // And also fill the listview & the combobox with all available groups. 46 // And also fill the listview & the combobox with all available groups.
49 for( QStringList::Iterator it = accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it) 47 for( QStringList::Iterator it = accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it)
50 { 48 {
51 accounts->splitGroupEntry(*it); 49 accounts->splitGroupEntry(*it);
52 if(accounts->gr_name.find(QRegExp("^#"),0)) 50 if(accounts->gr_name.find(QRegExp("^#"),0))
53 { // Skip commented lines. 51 { // Skip commented lines.
54 new QCheckListItem(groupsListView,accounts->gr_name,QCheckListItem::CheckBox); 52 new QCheckListItem(groupsListView,accounts->gr_name,QCheckListItem::CheckBox);
55 groupComboBox->insertItem(accounts->gr_name); 53 groupComboBox->insertItem(accounts->gr_name);
56 } 54 }
57 } 55 }
58 QPEApplication::showDialog( this ); 56 QPEApplication::showDialog( this );
59} 57}
60 58
61/** 59/**
62 * Empty destructor. 60 * Empty destructor.
63 * 61 *
64 */ 62 */
65UserDialog::~UserDialog() 63UserDialog::~UserDialog()
66{} 64{}
67 65
68/** 66/**
69 * Creates the first tab, all userinfo is here. 67 * Creates the first tab, all userinfo is here.
70 * 68 *
71 */ 69 */
72void UserDialog::setupTab1() 70void UserDialog::setupTab1()
73{ 71{
74 QPixmap mypixmap; 72 QPixmap mypixmap;
75 QWidget *tabpage = new QWidget(myTabWidget,"page1"); 73 QWidget *tabpage = new QWidget(myTabWidget,"page1");
76 QVBoxLayout *layout = new QVBoxLayout(tabpage); 74 QVBoxLayout *layout = new QVBoxLayout(tabpage);
77 layout->setMargin(5); 75 layout->setMargin(5);
78 76
79 // Picture 77 // Picture
80 picturePushButton = new QPushButton(tabpage,"Label"); 78 picturePushButton = new QPushButton(tabpage,"Label");
81 picturePushButton->setMinimumSize(48,48); 79 picturePushButton->setMinimumSize(48,48);
82 picturePushButton->setMaximumSize(48,48); 80 picturePushButton->setMaximumSize(48,48);
83 picturePushButton->setPixmap(Resource::loadPixmap("usermanager/usericon")); // Load default usericon. 81 picturePushButton->setPixmap(Resource::loadPixmap("usermanager/usericon")); // Load default usericon.
84 connect(picturePushButton,SIGNAL(clicked()),this,SLOT(clickedPicture())); // Clicking the picture should invoke pictureselector. 82 connect(picturePushButton,SIGNAL(clicked()),this,SLOT(clickedPicture())); // Clicking the picture should invoke pictureselector.
85 83
86 // Login 84 // Login
87 QLabel *loginLabel=new QLabel(tabpage,"Login: "); 85 QLabel *loginLabel=new QLabel(tabpage,"Login: ");
88 loginLabel->setText("Login: "); 86 loginLabel->setText("Login: ");
89 loginLineEdit=new QLineEdit(tabpage,"Login: "); 87 loginLineEdit=new QLineEdit(tabpage,"Login: ");
90 88
91 // UID 89 // UID
92 QLabel *uidLabel=new QLabel(tabpage,"uid: "); 90 QLabel *uidLabel=new QLabel(tabpage,"uid: ");
93 uidLabel->setText("UserID: "); 91 uidLabel->setText("UserID: ");
94 uidLineEdit=new QLineEdit(tabpage,"uid: "); 92 uidLineEdit=new QLineEdit(tabpage,"uid: ");
95 uidLineEdit->setEnabled(false); 93 uidLineEdit->setEnabled(false);
96 94
97 // Username (gecos) 95 // Username (gecos)
98 QLabel *gecosLabel=new QLabel(tabpage,"gecos"); 96 QLabel *gecosLabel=new QLabel(tabpage,"gecos");
99 gecosLabel->setText("Username: "); 97 gecosLabel->setText("Username: ");
100 gecosLineEdit=new QLineEdit(tabpage,"gecos"); 98 gecosLineEdit=new QLineEdit(tabpage,"gecos");
101 99
102 // Password 100 // Password
103 QLabel *passwordLabel=new QLabel(tabpage,"password"); 101 QLabel *passwordLabel=new QLabel(tabpage,"password");
104 passwordLabel->setText("Password: "); 102 passwordLabel->setText("Password: ");
105 passwordLineEdit=new QLineEdit(tabpage,"password"); 103 passwordLineEdit=new QLineEdit(tabpage,"password");
106 passwordLineEdit->setEchoMode(QLineEdit::Password); 104 passwordLineEdit->setEchoMode(QLineEdit::Password);
107 105
108 // Shell 106 // Shell
109 QLabel *shellLabel=new QLabel(tabpage,"shell"); 107 QLabel *shellLabel=new QLabel(tabpage,"shell");
110 shellLabel->setText("Shell: "); 108 shellLabel->setText("Shell: ");
111 shellComboBox=new QComboBox(tabpage,"shell"); 109 shellComboBox=new QComboBox(tabpage,"shell");
112 shellComboBox->setEditable(true); 110 shellComboBox->setEditable(true);
113 shellComboBox->insertItem("/bin/sh"); 111 shellComboBox->insertItem("/bin/sh");
114 shellComboBox->insertItem("/bin/ash"); 112 shellComboBox->insertItem("/bin/ash");
115 shellComboBox->insertItem("/bin/false"); 113 shellComboBox->insertItem("/bin/false");
116 114
117 // Primary Group 115 // Primary Group
118 QLabel *groupLabel=new QLabel(tabpage,"group"); 116 QLabel *groupLabel=new QLabel(tabpage,"group");
119 groupLabel->setText("Primary group: "); 117 groupLabel->setText("Primary group: ");
120 groupComboBox=new QComboBox(tabpage,"PrimaryGroup"); 118 groupComboBox=new QComboBox(tabpage,"PrimaryGroup");
121 119
122 if(vm==VIEWMODE_NEW) 120 if(vm==VIEWMODE_NEW)
123 { 121 {
124 // Copy /etc/skel 122 // Copy /etc/skel
125 skelLabel=new QLabel(tabpage,"skel"); 123 skelLabel=new QLabel(tabpage,"skel");
126 skelLabel->setText("Copy /etc/skel: "); 124 skelLabel->setText("Copy /etc/skel: ");
127 skelCheckBox=new QCheckBox(tabpage); 125 skelCheckBox=new QCheckBox(tabpage);
128 skelCheckBox->setChecked(true); 126 skelCheckBox->setChecked(true);
129 } 127 }
130 128
131 // Widget layout 129 // Widget layout
132 QHBoxLayout *hlayout=new QHBoxLayout(-1,"hlayout"); 130 QHBoxLayout *hlayout=new QHBoxLayout(-1,"hlayout");
133 layout->addWidget(picturePushButton); 131 layout->addWidget(picturePushButton);
@@ -152,337 +150,337 @@ void UserDialog::setupTab1()
152 vlayout1->addSpacing(5); 150 vlayout1->addSpacing(5);
153 vlayout1->addWidget(skelLabel); 151 vlayout1->addWidget(skelLabel);
154 } 152 }
155 // Second column, data 153 // Second column, data
156 vlayout2->addWidget(loginLineEdit); 154 vlayout2->addWidget(loginLineEdit);
157 vlayout2->addSpacing(5); 155 vlayout2->addSpacing(5);
158 vlayout2->addWidget(uidLineEdit); 156 vlayout2->addWidget(uidLineEdit);
159 vlayout2->addSpacing(5); 157 vlayout2->addSpacing(5);
160 vlayout2->addWidget(gecosLineEdit); 158 vlayout2->addWidget(gecosLineEdit);
161 vlayout2->addSpacing(5); 159 vlayout2->addSpacing(5);
162 vlayout2->addWidget(passwordLineEdit); 160 vlayout2->addWidget(passwordLineEdit);
163 vlayout2->addSpacing(5); 161 vlayout2->addSpacing(5);
164 vlayout2->addWidget(shellComboBox); 162 vlayout2->addWidget(shellComboBox);
165 vlayout2->addSpacing(5); 163 vlayout2->addSpacing(5);
166 vlayout2->addWidget(groupComboBox); 164 vlayout2->addWidget(groupComboBox);
167 if(vm==VIEWMODE_NEW) 165 if(vm==VIEWMODE_NEW)
168 { 166 {
169 vlayout2->addSpacing(5); 167 vlayout2->addSpacing(5);
170 vlayout2->addWidget(skelCheckBox); 168 vlayout2->addWidget(skelCheckBox);
171 } 169 }
172 hlayout->addLayout(vlayout1); 170 hlayout->addLayout(vlayout1);
173 hlayout->addLayout(vlayout2); 171 hlayout->addLayout(vlayout2);
174 172
175 myTabWidget->addTab(tabpage,"User Info"); 173 myTabWidget->addTab(tabpage,"User Info");
176} 174}
177 175
178/** 176/**
179 * Creates the second tab containing additional groups for the user. 177 * Creates the second tab containing additional groups for the user.
180 * 178 *
181 */ 179 */
182void UserDialog::setupTab2() 180void UserDialog::setupTab2()
183{ 181{
184 QWidget *tabpage = new QWidget(myTabWidget,"page2"); 182 QWidget *tabpage = new QWidget(myTabWidget,"page2");
185 QVBoxLayout *layout = new QVBoxLayout(tabpage); 183 QVBoxLayout *layout = new QVBoxLayout(tabpage);
186 layout->setMargin(5); 184 layout->setMargin(5);
187 185
188 // Additional groups 186 // Additional groups
189 groupsListView=new QListView(tabpage,"groups"); 187 groupsListView=new QListView(tabpage,"groups");
190 groupsListView->addColumn("Additional groups"); 188 groupsListView->addColumn("Additional groups");
191 groupsListView->setColumnWidthMode(0,QListView::Maximum); 189 groupsListView->setColumnWidthMode(0,QListView::Maximum);
192 groupsListView->setMultiSelection(false); 190 groupsListView->setMultiSelection(false);
193 groupsListView->setAllColumnsShowFocus(false); 191 groupsListView->setAllColumnsShowFocus(false);
194 192
195 layout->addSpacing(5); 193 layout->addSpacing(5);
196 // Grouplist 194 // Grouplist
197 layout->addWidget(groupsListView); 195 layout->addWidget(groupsListView);
198 196
199 myTabWidget->addTab(tabpage,"User Groups"); 197 myTabWidget->addTab(tabpage,"User Groups");
200} 198}
201 199
202/** 200/**
203 * Static function that creates the userinfo dialog. 201 * Static function that creates the userinfo dialog.
204 * The user will be prompted to add a user. 202 * The user will be prompted to add a user.
205 * 203 *
206 * @param uid This is a suggested available UID. 204 * @param uid This is a suggested available UID.
207 * @param gid This is a suggested available GID. 205 * @param gid This is a suggested available GID.
208 * 206 *
209 * @return <code>true</code> if the user was successfully added, otherwise <code>false</code>. 207 * @return <code>true</code> if the user was successfully added, otherwise <code>false</code>.
210 * 208 *
211 */ 209 */
212bool UserDialog::addUser(int uid, int gid) 210bool UserDialog::addUser(int uid, int gid)
213{ 211{
214 QCheckListItem *temp; 212 QCheckListItem *temp;
215 QFile ozTest; 213 QFile ozTest;
216 int oz=false; 214 int oz=false;
217 if(ODevice::inst()->system()==System_OpenZaurus) oz=true; 215 if(ODevice::inst()->system()==System_OpenZaurus) oz=true;
218 // viewmode is a workaround for a bug in qte-2.3.4 that gives bus error on manipulating adduserDialog's widgets here. 216 // viewmode is a workaround for a bug in qte-2.3.4 that gives bus error on manipulating adduserDialog's widgets here.
219 UserDialog *adduserDialog=new UserDialog(VIEWMODE_NEW); 217 UserDialog *adduserDialog=new UserDialog(VIEWMODE_NEW);
220 adduserDialog->setCaption(tr("Add User")); 218 adduserDialog->setCaption(tr("Add User"));
221 adduserDialog->userID=uid; // Set next available UID as default uid. 219 adduserDialog->userID=uid; // Set next available UID as default uid.
222 adduserDialog->groupID=gid; // Set next available GID as default gid. 220 adduserDialog->groupID=gid; // Set next available GID as default gid.
223 // Insert default group into groupComboBox 221 // Insert default group into groupComboBox
224 adduserDialog->groupComboBox->insertItem("<create new group>",0); 222 adduserDialog->groupComboBox->insertItem("<create new group>",0);
225 adduserDialog->uidLineEdit->setText(QString::number(uid)); 223 adduserDialog->uidLineEdit->setText(QString::number(uid));
226 // If we're running on OZ, add new users to some default groups. 224 // If we're running on OZ, add new users to some default groups.
227 if(oz) 225 if(oz)
228 { 226 {
229 QListViewItemIterator iter( adduserDialog->groupsListView ); 227 QListViewItemIterator iter( adduserDialog->groupsListView );
230 for ( ; iter.current(); ++iter ) 228 for ( ; iter.current(); ++iter )
231 { 229 {
232 temp=(QCheckListItem*)iter.current(); 230 temp=(QCheckListItem*)iter.current();
233 if (temp->text()=="video") temp->setOn(true); 231 if (temp->text()=="video") temp->setOn(true);
234 if (temp->text()=="audio") temp->setOn(true); 232 if (temp->text()=="audio") temp->setOn(true);
235 if (temp->text()=="time") temp->setOn(true); 233 if (temp->text()=="time") temp->setOn(true);
236 if (temp->text()=="power") temp->setOn(true); 234 if (temp->text()=="power") temp->setOn(true);
237 if (temp->text()=="input") temp->setOn(true); 235 if (temp->text()=="input") temp->setOn(true);
238 if (temp->text()=="sharp") temp->setOn(true); 236 if (temp->text()=="sharp") temp->setOn(true);
239 if (temp->text()=="tty") temp->setOn(true); 237 if (temp->text()=="tty") temp->setOn(true);
240 } 238 }
241 } 239 }
242 // Show the dialog! 240 // Show the dialog!
243 if(!(adduserDialog->exec())) return false; 241 if(!(adduserDialog->exec())) return false;
244 if((adduserDialog->groupComboBox->currentItem()!=0)) 242 if((adduserDialog->groupComboBox->currentItem()!=0))
245 { 243 {
246 accounts->findGroup(adduserDialog->groupComboBox->currentText()); 244 accounts->findGroup(adduserDialog->groupComboBox->currentText());
247 adduserDialog->groupID=accounts->gr_gid; 245 adduserDialog->groupID=accounts->gr_gid;
248 qWarning(QString::number(accounts->gr_gid)); 246 owarn << QString::number(accounts->gr_gid) << oendl;
249 } 247 }
250 if(!(accounts->addUser(adduserDialog->loginLineEdit->text(), adduserDialog->passwordLineEdit->text(), 248 if(!(accounts->addUser(adduserDialog->loginLineEdit->text(), adduserDialog->passwordLineEdit->text(),
251 adduserDialog->uidLineEdit->text().toInt(), adduserDialog->groupID, adduserDialog->gecosLineEdit->text(), 249 adduserDialog->uidLineEdit->text().toInt(), adduserDialog->groupID, adduserDialog->gecosLineEdit->text(),
252 QString("/home/")+adduserDialog->loginLineEdit->text() , adduserDialog->shellComboBox->currentText()))) 250 QString("/home/")+adduserDialog->loginLineEdit->text() , adduserDialog->shellComboBox->currentText())))
253 { 251 {
254 QMessageBox::information(0,"Ooops!","Something went wrong!\nUnable to add user."); 252 QMessageBox::information(0,"Ooops!","Something went wrong!\nUnable to add user.");
255 return false; 253 return false;
256 } 254 }
257 255
258 // Add User to additional groups. 256 // Add User to additional groups.
259 QListViewItemIterator it( adduserDialog->groupsListView ); 257 QListViewItemIterator it( adduserDialog->groupsListView );
260 for ( ; it.current(); ++it ) 258 for ( ; it.current(); ++it )
261 { 259 {
262 temp=(QCheckListItem*)it.current(); 260 temp=(QCheckListItem*)it.current();
263 if (temp->isOn() ) 261 if (temp->isOn() )
264 accounts->addGroupMember(it.current()->text(0),adduserDialog->loginLineEdit->text()); 262 accounts->addGroupMember(it.current()->text(0),adduserDialog->loginLineEdit->text());
265 } 263 }
266 // Copy image to pics/users/ 264 // Copy image to pics/users/
267 if(!(adduserDialog->userImage.isNull())) 265 if(!(adduserDialog->userImage.isNull()))
268 { 266 {
269 QDir d; 267 QDir d;
270 if(!(d.exists("/opt/QtPalmtop/pics/users"))) 268 if(!(d.exists("/opt/QtPalmtop/pics/users")))
271 { 269 {
272 d.mkdir("/opt/QtPalmtop/pics/users"); 270 d.mkdir("/opt/QtPalmtop/pics/users");
273 } 271 }
274 QString filename="/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png"; 272 QString filename="/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png";
275 // adduserDialog->userImage=adduserDialog->userImage.smoothScale(48,48); 273 // adduserDialog->userImage=adduserDialog->userImage.smoothScale(48,48);
276 adduserDialog->userImage.save(filename,"PNG"); 274 adduserDialog->userImage.save(filename,"PNG");
277 } 275 }
278 276
279 // Should we copy the skeleton homedirectory /etc/skel to the user's homedirectory? 277 // Should we copy the skeleton homedirectory /etc/skel to the user's homedirectory?
280 accounts->findUser(adduserDialog->loginLineEdit->text()); 278 accounts->findUser(adduserDialog->loginLineEdit->text());
281 if(adduserDialog->skelCheckBox->isChecked()) 279 if(adduserDialog->skelCheckBox->isChecked())
282 { 280 {
283 QString command_cp; 281 QString command_cp;
284 QString command_chown; 282 QString command_chown;
285 command_cp.sprintf("cp -a /etc/skel/* %s/",accounts->pw_dir.latin1()); 283 command_cp.sprintf("cp -a /etc/skel/* %s/",accounts->pw_dir.latin1());
286 system(command_cp); 284 system(command_cp);
287 285
288 command_cp.sprintf("cp -a /etc/skel/.[!.]* %s/",accounts->pw_dir.latin1()); // Bug in busybox, ".*" includes parent directory, does this work as a workaround? 286 command_cp.sprintf("cp -a /etc/skel/.[!.]* %s/",accounts->pw_dir.latin1()); // Bug in busybox, ".*" includes parent directory, does this work as a workaround?
289 system(command_cp); 287 system(command_cp);
290 288
291 command_chown.sprintf("chown -R %d:%d %s",accounts->pw_uid,accounts->pw_gid,accounts->pw_dir.latin1()); 289 command_chown.sprintf("chown -R %d:%d %s",accounts->pw_uid,accounts->pw_gid,accounts->pw_dir.latin1());
292 system(command_chown); 290 system(command_chown);
293 } 291 }
294 292
295 return true; 293 return true;
296} 294}
297 295
298/** 296/**
299 * Deletes the user account. 297 * Deletes the user account.
300 * 298 *
301 * @param username User to be deleted. 299 * @param username User to be deleted.
302 * 300 *
303 * @return <code>true</code> if the user was successfully deleted, otherwise <code>false</code>. 301 * @return <code>true</code> if the user was successfully deleted, otherwise <code>false</code>.
304 * 302 *
305 */ 303 */
306bool UserDialog::delUser(const char *username) 304bool UserDialog::delUser(const char *username)
307{ 305{
308 if((accounts->findUser(username))) 306 if((accounts->findUser(username)))
309 { // Does that user exist? 307 { // Does that user exist?
310 if(!(accounts->delUser(username))) 308 if(!(accounts->delUser(username)))
311 { // Delete the user. 309 { // Delete the user.
312 QMessageBox::information(0,"Ooops!","Something went wrong\nUnable to delete user: "+QString(username)+"."); 310 QMessageBox::information(0,"Ooops!","Something went wrong\nUnable to delete user: "+QString(username)+".");
313 } 311 }
314 } 312 }
315 else 313 else
316 { 314 {
317 QMessageBox::information(0,"Invalid Username","That username ("+QString(username)+")does not exist."); 315 QMessageBox::information(0,"Invalid Username","That username ("+QString(username)+")does not exist.");
318 return false; 316 return false;
319 } 317 }
320 return true; 318 return true;
321} 319}
322 320
323/** 321/**
324 * This displays a confirmation dialog wether a user should be deleted or not. 322 * This displays a confirmation dialog wether a user should be deleted or not.
325 * (And also deletes the account) 323 * (And also deletes the account)
326 * 324 *
327 * @param username User to be deleted. 325 * @param username User to be deleted.
328 * 326 *
329 * @return <code>true</code> if the user was successfully deleted, otherwise <code>false</code>. 327 * @return <code>true</code> if the user was successfully deleted, otherwise <code>false</code>.
330 * 328 *
331 */ 329 */
332bool UserDialog::editUser(const char *username) 330bool UserDialog::editUser(const char *username)
333{ 331{
334 int invalid_group=0; 332 int invalid_group=0;
335 // viewmode is a workaround for a bug in qte-2.3.4 that gives bus error on manipulating edituserDialog's widgets here. 333 // viewmode is a workaround for a bug in qte-2.3.4 that gives bus error on manipulating edituserDialog's widgets here.
336 UserDialog *edituserDialog=new UserDialog(VIEWMODE_EDIT); // Create Dialog 334 UserDialog *edituserDialog=new UserDialog(VIEWMODE_EDIT); // Create Dialog
337 edituserDialog->setCaption(tr("Edit User")); 335 edituserDialog->setCaption(tr("Edit User"));
338 accounts->findUser(username); // Locate user in database and fill variables in 'accounts' object. 336 accounts->findUser(username); // Locate user in database and fill variables in 'accounts' object.
339 if(!(accounts->findGroup(accounts->pw_gid))) 337 if(!(accounts->findGroup(accounts->pw_gid)))
340 { // Locate the user's primary group, and fill group variables in 'accounts' object. 338 { // Locate the user's primary group, and fill group variables in 'accounts' object.
341 invalid_group=1; 339 invalid_group=1;
342 } 340 }
343 // Fill widgets with userinfo. 341 // Fill widgets with userinfo.
344 edituserDialog->loginLineEdit->setText(accounts->pw_name); 342 edituserDialog->loginLineEdit->setText(accounts->pw_name);
345 edituserDialog->uidLineEdit->setText(QString::number(accounts->pw_uid)); 343 edituserDialog->uidLineEdit->setText(QString::number(accounts->pw_uid));
346 edituserDialog->gecosLineEdit->setText(accounts->pw_gecos); 344 edituserDialog->gecosLineEdit->setText(accounts->pw_gecos);
347 // Set password to '........', we will later check if this still is the contents, if not, the password has been changed. 345 // Set password to '........', we will later check if this still is the contents, if not, the password has been changed.
348 edituserDialog->passwordLineEdit->setText("........"); 346 edituserDialog->passwordLineEdit->setText("........");
349 // If this user is not using /bin/sh,/bin/ash or /bin/false as shell, add that entry to the shell-combobox. 347 // If this user is not using /bin/sh,/bin/ash or /bin/false as shell, add that entry to the shell-combobox.
350 if(accounts->pw_shell!="/bin/sh" && accounts->pw_shell!="/bin/ash" && accounts->pw_shell!="/bin/false") 348 if(accounts->pw_shell!="/bin/sh" && accounts->pw_shell!="/bin/ash" && accounts->pw_shell!="/bin/false")
351 { 349 {
352 edituserDialog->shellComboBox->insertItem(accounts->pw_shell,0); 350 edituserDialog->shellComboBox->insertItem(accounts->pw_shell,0);
353 edituserDialog->shellComboBox->setCurrentItem(0); 351 edituserDialog->shellComboBox->setCurrentItem(0);
354 } 352 }
355 // Select the primary group for this user. 353 // Select the primary group for this user.
356 for(int i=0;i<edituserDialog->groupComboBox->count();++i) 354 for(int i=0;i<edituserDialog->groupComboBox->count();++i)
357 { 355 {
358 if(accounts->gr_name==edituserDialog->groupComboBox->text(i)) 356 if(accounts->gr_name==edituserDialog->groupComboBox->text(i))
359 { 357 {
360 edituserDialog->groupComboBox->setCurrentItem(i); 358 edituserDialog->groupComboBox->setCurrentItem(i);
361 break; 359 break;
362 } 360 }
363 } 361 }
364 if(invalid_group) 362 if(invalid_group)
365 { 363 {
366 edituserDialog->groupComboBox->insertItem("<Undefined group>",0); 364 edituserDialog->groupComboBox->insertItem("<Undefined group>",0);
367 edituserDialog->groupComboBox->setCurrentItem(0); 365 edituserDialog->groupComboBox->setCurrentItem(0);
368 } 366 }
369 367
370 // Select the groups in the listview, to which the user belongs. 368 // Select the groups in the listview, to which the user belongs.
371 QCheckListItem *temp; 369 QCheckListItem *temp;
372 // 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. 370 // 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.
373 QRegExp userRegExp(QString("[:,]%1$").arg(username)); // The end of line variant. 371 QRegExp userRegExp(QString("[:,]%1$").arg(username)); // The end of line variant.
374 QStringList tempList=accounts->groupStringList.grep(userRegExp); // Find all entries in the group database, that the user is a member of. 372 QStringList tempList=accounts->groupStringList.grep(userRegExp); // Find all entries in the group database, that the user is a member of.
375 for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it) 373 for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it)
376 { // Iterate over all of them. 374 { // Iterate over all of them.
377 qWarning(*it); 375 owarn << *it << oendl;
378 QListViewItemIterator lvit( edituserDialog->groupsListView ); // Compare to all groups. 376 QListViewItemIterator lvit( edituserDialog->groupsListView ); // Compare to all groups.
379 for ( ; lvit.current(); ++lvit ) 377 for ( ; lvit.current(); ++lvit )
380 { 378 {
381 if(lvit.current()->text(0)==(*it).left((*it).find(":"))) 379 if(lvit.current()->text(0)==(*it).left((*it).find(":")))
382 { 380 {
383 temp=(QCheckListItem*)lvit.current(); 381 temp=(QCheckListItem*)lvit.current();
384 temp->setOn(true); // If we find a line with that groupname, select it.; 382 temp->setOn(true); // If we find a line with that groupname, select it.;
385 } 383 }
386 } 384 }
387 } 385 }
388 userRegExp=QRegExp(QString("[:,]%1,").arg(username)); // And the other one. (not end of line.) 386 userRegExp=QRegExp(QString("[:,]%1,").arg(username)); // And the other one. (not end of line.)
389 tempList=accounts->groupStringList.grep(userRegExp); // Find all entries in the group database, that the user is a member of. 387 tempList=accounts->groupStringList.grep(userRegExp); // Find all entries in the group database, that the user is a member of.
390 for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it) 388 for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it)
391 { // Iterate over all of them. 389 { // Iterate over all of them.
392 qWarning(*it); 390 owarn << *it << oendl;
393 QListViewItemIterator lvit( edituserDialog->groupsListView ); // Compare to all groups. 391 QListViewItemIterator lvit( edituserDialog->groupsListView ); // Compare to all groups.
394 for ( ; lvit.current(); ++lvit ) 392 for ( ; lvit.current(); ++lvit )
395 { 393 {
396 if(lvit.current()->text(0)==(*it).left((*it).find(":"))) 394 if(lvit.current()->text(0)==(*it).left((*it).find(":")))
397 { 395 {
398 temp=(QCheckListItem*)lvit.current(); 396 temp=(QCheckListItem*)lvit.current();
399 temp->setOn(true); // If we find a line with that groupname, select it.; 397 temp->setOn(true); // If we find a line with that groupname, select it.;
400 } 398 }
401 } 399 }
402 } 400 }
403 401
404 if(!(edituserDialog->exec())) return false; // SHOW THE DIALOG! 402 if(!(edituserDialog->exec())) return false; // SHOW THE DIALOG!
405 403
406 accounts->findUser(username); // Fill user variables in 'acccounts' object. 404 accounts->findUser(username); // Fill user variables in 'acccounts' object.
407 accounts->pw_name=edituserDialog->loginLineEdit->text(); 405 accounts->pw_name=edituserDialog->loginLineEdit->text();
408 // Has the password been changed ? Make a new "crypt":ed password. 406 // Has the password been changed ? Make a new "crypt":ed password.
409 if(edituserDialog->passwordLineEdit->text()!="........") accounts->pw_passwd=crypt(edituserDialog->passwordLineEdit->text(), accounts->crypt_make_salt()); 407 if(edituserDialog->passwordLineEdit->text()!="........") accounts->pw_passwd=crypt(edituserDialog->passwordLineEdit->text(), accounts->crypt_make_salt());
410 408
411 // Set all variables in accounts object, that will be used when calling 'updateUser()' 409 // Set all variables in accounts object, that will be used when calling 'updateUser()'
412 accounts->pw_uid=edituserDialog->uidLineEdit->text().toInt(); 410 accounts->pw_uid=edituserDialog->uidLineEdit->text().toInt();
413 if(accounts->findGroup(edituserDialog->groupComboBox->currentText())) 411 if(accounts->findGroup(edituserDialog->groupComboBox->currentText()))
414 { // Fill all group variables in 'accounts' object. 412 { // Fill all group variables in 'accounts' object.
415 accounts->pw_gid=accounts->gr_gid; // Only do this if the group is a valid group (ie. "<Undefined group>"), otherwise keep the old group. 413 accounts->pw_gid=accounts->gr_gid; // Only do this if the group is a valid group (ie. "<Undefined group>"), otherwise keep the old group.
416 } 414 }
417 accounts->pw_gecos=edituserDialog->gecosLineEdit->text(); 415 accounts->pw_gecos=edituserDialog->gecosLineEdit->text();
418 accounts->pw_shell=edituserDialog->shellComboBox->currentText(); 416 accounts->pw_shell=edituserDialog->shellComboBox->currentText();
419 // Update userinfo, using the information stored in the user variables stored in the accounts object. 417 // Update userinfo, using the information stored in the user variables stored in the accounts object.
420 accounts->updateUser(username); 418 accounts->updateUser(username);
421 419
422 // Remove user from all groups he/she is a member of. (could be done in a better way I guess, this was simple though.) 420 // Remove user from all groups he/she is a member of. (could be done in a better way I guess, this was simple though.)
423 for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it) 421 for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it)
424 { 422 {
425 accounts->delGroupMember((*it).left((*it).find(":")),username); 423 accounts->delGroupMember((*it).left((*it).find(":")),username);
426 } 424 }
427 425
428 // Add User to additional groups that he/she is a member of. 426 // Add User to additional groups that he/she is a member of.
429 QListViewItemIterator it( edituserDialog->groupsListView ); 427 QListViewItemIterator it( edituserDialog->groupsListView );
430 for ( ; it.current(); ++it ) 428 for ( ; it.current(); ++it )
431 { 429 {
432 temp=(QCheckListItem*)it.current(); 430 temp=(QCheckListItem*)it.current();
433 if ( temp->isOn() ) 431 if ( temp->isOn() )
434 accounts->addGroupMember(it.current()->text(0),edituserDialog->loginLineEdit->text()); 432 accounts->addGroupMember(it.current()->text(0),edituserDialog->loginLineEdit->text());
435 } 433 }
436 434
437 // Copy image to pics/users/ 435 // Copy image to pics/users/
438 if(!(edituserDialog->userImage.isNull())) 436 if(!(edituserDialog->userImage.isNull()))
439 { 437 {
440 QDir d; 438 QDir d;
441 if(!(d.exists("/opt/QtPalmtop/pics/users"))) 439 if(!(d.exists("/opt/QtPalmtop/pics/users")))
442 { 440 {
443 d.mkdir("/opt/QtPalmtop/pics/users"); 441 d.mkdir("/opt/QtPalmtop/pics/users");
444 } 442 }
445 QString filename="/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png"; 443 QString filename="/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png";
446 // edituserDialog->userImage=edituserDialog->userImage.smoothScale(48,48); 444 // edituserDialog->userImage=edituserDialog->userImage.smoothScale(48,48);
447 edituserDialog->userImage.save(filename,"PNG"); 445 edituserDialog->userImage.save(filename,"PNG");
448 } 446 }
449 return true; 447 return true;
450} 448}
451 449
452/** 450/**
453 * "OK" has been clicked. Verify some information before closing the dialog. 451 * "OK" has been clicked. Verify some information before closing the dialog.
454 * 452 *
455 */ 453 */
456void UserDialog::accept() 454void UserDialog::accept()
457{ 455{
458 // Add checking... valid username? username taken? 456 // Add checking... valid username? username taken?
459 if(loginLineEdit->text().isEmpty()) 457 if(loginLineEdit->text().isEmpty())
460 { 458 {
461 QMessageBox::information(0,"Empty Login","Please enter a login."); 459 QMessageBox::information(0,"Empty Login","Please enter a login.");
462 return; 460 return;
463 } 461 }
464 QDialog::accept(); 462 QDialog::accept();
465} 463}
466 464
467/** 465/**
468 * This slot is called when the usericon is clicked, this loads (should) the iconselector. 466 * This slot is called when the usericon is clicked, this loads (should) the iconselector.
469 * 467 *
470 */ 468 */
471void UserDialog::clickedPicture() 469void UserDialog::clickedPicture()
472{ 470{
473 QString filename=OFileDialog::getOpenFileName(OFileSelector::EXTENDED, QString::null); 471 QString filename=OFileDialog::getOpenFileName(OFileSelector::EXTENDED, QString::null);
474 if(!(filename.isEmpty())) 472 if(!(filename.isEmpty()))
475 { 473 {
476 userImage.reset(); 474 userImage.reset();
477 if(!(userImage.load(filename))) 475 if(!(userImage.load(filename)))
478 { 476 {
479 QMessageBox::information(0,"Sorry!","That icon could not be loaded.\nLoading failed on: "+filename); 477 QMessageBox::information(0,"Sorry!","That icon could not be loaded.\nLoading failed on: "+filename);
480 } 478 }
481 else 479 else
482 { 480 {
483 // userImage=userImage.smoothScale(48,48); 481 // userImage=userImage.smoothScale(48,48);
484 QPixmap *picture; 482 QPixmap *picture;
485 picture=(QPixmap *)picturePushButton->pixmap(); 483 picture=(QPixmap *)picturePushButton->pixmap();
486 picture->convertFromImage(userImage,0); 484 picture->convertFromImage(userImage,0);
487 picturePushButton->update(); 485 picturePushButton->update();
488 } 486 }
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 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9 9
10#include "usermanager.h" 10#include "usermanager.h"
11 11
12#include <qlayout.h> 12/* OPIE */
13#include <opie2/odebug.h>
14#include <qpe/resource.h>
15using namespace Opie::Core;
13 16
17/* QT */
18#include <qlayout.h>
14#include <qmessagebox.h> 19#include <qmessagebox.h>
15#include <qfile.h> 20#include <qfile.h>
16#include <qpe/resource.h>
17
18#include <qregexp.h> 21#include <qregexp.h>
19 22
20/** 23/**
21 * The mainwindow constructor. 24 * The mainwindow constructor.
22 * 25 *
23 * @param QWidget *parent 26 * @param QWidget *parent
24 * @param const char *name 27 * @param const char *name
25 * @ param WFlags fl 28 * @ param WFlags fl
26 * 29 *
27 */ 30 */
28UserConfig::UserConfig(QWidget* parent, const char* name, WFlags fl) : QMainWindow(parent, name, fl) { 31UserConfig::UserConfig(QWidget* parent, const char* name, WFlags fl) : QMainWindow(parent, name, fl) {
29 setCaption(tr("Opie User Manager")); 32 setCaption(tr("Opie User Manager"));
30 33
31 // Create an instance of the global object 'accounts'. This holds all user/group info, and functions to modify them. 34 // Create an instance of the global object 'accounts'. This holds all user/group info, and functions to modify them.
32 accounts=new Passwd(); 35 accounts=new Passwd();
33 accounts->open();// This actually loads the files /etc/passwd & /etc/group into memory. 36 accounts->open();// This actually loads the files /etc/passwd & /etc/group into memory.
34 37
35 // Create the toolbar. 38 // Create the toolbar.
36 QToolBar *toolbar = new QToolBar(this,"Toolbar"); 39 QToolBar *toolbar = new QToolBar(this,"Toolbar");
37 toolbar->setHorizontalStretchable(1); // Is there any other way to get the toolbar to stretch of the full screen!? 40 toolbar->setHorizontalStretchable(1); // Is there any other way to get the toolbar to stretch of the full screen!?
38 adduserToolButton = new QToolButton(Resource::loadPixmap("usermanager/adduser"),"Add User",0,this,SLOT(addUser()),toolbar,"Add User"); 41 adduserToolButton = new QToolButton(Resource::loadPixmap("usermanager/adduser"),"Add User",0,this,SLOT(addUser()),toolbar,"Add User");
39 edituserToolButton = new QToolButton(Resource::loadPixmap("usermanager/edituser"),"Edit User",0,this,SLOT(editUser()),toolbar,"Edit User"); 42 edituserToolButton = new QToolButton(Resource::loadPixmap("usermanager/edituser"),"Edit User",0,this,SLOT(editUser()),toolbar,"Edit User");
40 deleteuserToolButton = new QToolButton(Resource::loadPixmap("usermanager/deleteuser"),"Delete User",0,this,SLOT(delUser()),toolbar,"Delete User"); 43 deleteuserToolButton = new QToolButton(Resource::loadPixmap("usermanager/deleteuser"),"Delete User",0,this,SLOT(delUser()),toolbar,"Delete User");
41 QToolButton *userstext = new QToolButton(0,"User",0,0,0,toolbar,"User"); 44 QToolButton *userstext = new QToolButton(0,"User",0,0,0,toolbar,"User");
42 userstext->setUsesTextLabel(true); 45 userstext->setUsesTextLabel(true);
43 toolbar->addSeparator(); 46 toolbar->addSeparator();
44 addgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/addgroup"),"Add Group",0,this,SLOT(addGroup()),toolbar,"Add Group"); 47 addgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/addgroup"),"Add Group",0,this,SLOT(addGroup()),toolbar,"Add Group");
45 editgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/editgroup"),"Edit Group",0,this,SLOT(editGroup()),toolbar,"Edit Group"); 48 editgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/editgroup"),"Edit Group",0,this,SLOT(editGroup()),toolbar,"Edit Group");
46 deletegroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/deletegroup"),"Delete Group",0,this,SLOT(delGroup()),toolbar,"Delete Group"); 49 deletegroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/deletegroup"),"Delete Group",0,this,SLOT(delGroup()),toolbar,"Delete Group");
47 QToolButton *groupstext = new QToolButton(0,"Group",0,0,0,toolbar,"Group"); 50 QToolButton *groupstext = new QToolButton(0,"Group",0,0,0,toolbar,"Group");
48 groupstext->setUsesTextLabel(true); 51 groupstext->setUsesTextLabel(true);
49 addToolBar(toolbar,"myToolBar"); 52 addToolBar(toolbar,"myToolBar");
50 53
51 // Add a tabwidget and all the tabs. 54 // Add a tabwidget and all the tabs.
52 myTabWidget = new QTabWidget(this,"My Tab Widget"); 55 myTabWidget = new QTabWidget(this,"My Tab Widget");
53 setupTabAccounts(); 56 setupTabAccounts();
54 setupTabAllUsers(); 57 setupTabAllUsers();
55 setupTabAllGroups(); 58 setupTabAllGroups();
56 userPopupMenu.insertItem("Copy",0); 59 userPopupMenu.insertItem("Copy",0);
57 60
58 getUsers(); // Fill out the iconview & listview with all users. 61 getUsers(); // Fill out the iconview & listview with all users.
59 getGroups(); // Fill out the group listview with all groups. 62 getGroups(); // Fill out the group listview with all groups.
60 63
61 setCentralWidget(myTabWidget); 64 setCentralWidget(myTabWidget);
62} 65}
63 66
64UserConfig::~UserConfig() { 67UserConfig::~UserConfig() {
65 accounts->close(); 68 accounts->close();
66 delete accounts; 69 delete accounts;
67} 70}
68 71
69void UserConfig::setupTabAccounts() { 72void UserConfig::setupTabAccounts() {
70 QWidget *tabpage = new QWidget(this); 73 QWidget *tabpage = new QWidget(this);
71 QVBoxLayout *layout = new QVBoxLayout(tabpage); 74 QVBoxLayout *layout = new QVBoxLayout(tabpage);
72 layout->setMargin(5); 75 layout->setMargin(5);
73 76
74 usersIconView=new QListView(tabpage,"users"); 77 usersIconView=new QListView(tabpage,"users");
75 usersIconView->addColumn("Icon"); 78 usersIconView->addColumn("Icon");
76 usersIconView->addColumn("Username"); 79 usersIconView->addColumn("Username");
77 usersIconView->setAllColumnsShowFocus(true); 80 usersIconView->setAllColumnsShowFocus(true);
78 layout->addWidget(usersIconView); 81 layout->addWidget(usersIconView);
79 82
80 connect(usersIconView,SIGNAL(returnPressed(QListViewItem*)),this,SLOT(showUserMenu(QListViewItem*))); 83 connect(usersIconView,SIGNAL(returnPressed(QListViewItem*)),this,SLOT(showUserMenu(QListViewItem*)));
81 84
82 myTabWidget->addTab(tabpage,"Users"); 85 myTabWidget->addTab(tabpage,"Users");
83} 86}
84 87
85void UserConfig::setupTabAllUsers() { 88void UserConfig::setupTabAllUsers() {
86 QWidget *tabpage = new QWidget(this); 89 QWidget *tabpage = new QWidget(this);
87 QVBoxLayout *layout = new QVBoxLayout(tabpage); 90 QVBoxLayout *layout = new QVBoxLayout(tabpage);
88 layout->setMargin(5); 91 layout->setMargin(5);
89 92
90 usersListView=new QListView(tabpage,"allusers"); 93 usersListView=new QListView(tabpage,"allusers");
91 usersListView->addColumn("UID"); 94 usersListView->addColumn("UID");
92 usersListView->addColumn("Login"); 95 usersListView->addColumn("Login");
93 usersListView->addColumn("Username"); 96 usersListView->addColumn("Username");
94 layout->addWidget(usersListView); 97 layout->addWidget(usersListView);
95 usersListView->setSorting(1,1); 98 usersListView->setSorting(1,1);
96 usersListView->setAllColumnsShowFocus(true); 99 usersListView->setAllColumnsShowFocus(true);
97 100
98 myTabWidget->addTab(tabpage,"All Users"); 101 myTabWidget->addTab(tabpage,"All Users");
99} 102}
100 103
101void UserConfig::setupTabAllGroups() { 104void UserConfig::setupTabAllGroups() {
102 QWidget *tabpage = new QWidget(this); 105 QWidget *tabpage = new QWidget(this);
103 QVBoxLayout *layout = new QVBoxLayout(tabpage); 106 QVBoxLayout *layout = new QVBoxLayout(tabpage);
104 layout->setMargin(5); 107 layout->setMargin(5);
105 108
106 groupsListView=new QListView(tabpage,"groups"); 109 groupsListView=new QListView(tabpage,"groups");
107 groupsListView->addColumn("GID"); 110 groupsListView->addColumn("GID");
108 groupsListView->addColumn("Groupname"); 111 groupsListView->addColumn("Groupname");
109 layout->addWidget(groupsListView); 112 layout->addWidget(groupsListView);
110 groupsListView->setSorting(1,1); 113 groupsListView->setSorting(1,1);
111 groupsListView->setAllColumnsShowFocus(true); 114 groupsListView->setAllColumnsShowFocus(true);
112 115
113 myTabWidget->addTab(tabpage,"All Groups"); 116 myTabWidget->addTab(tabpage,"All Groups");
@@ -160,98 +163,98 @@ void UserConfig::editUser() {
160 getGroups(); 163 getGroups();
161 } 164 }
162 } else { 165 } else {
163 QMessageBox::information(this,"No selection.","No user has been selected."); 166 QMessageBox::information(this,"No selection.","No user has been selected.");
164 } 167 }
165 } 168 }
166 if(myTabWidget->currentPageIndex()==1) {// All users 169 if(myTabWidget->currentPageIndex()==1) {// All users
167 if(usersListView->currentItem()) {// Anything changed!? 170 if(usersListView->currentItem()) {// Anything changed!?
168 username=usersListView->currentItem()->text(1);// Get the username. 171 username=usersListView->currentItem()->text(1);// Get the username.
169 if(UserDialog::editUser(username)) {// Bring up the userinfo dialog. 172 if(UserDialog::editUser(username)) {// Bring up the userinfo dialog.
170 // And again update the views if there were any changes. 173 // And again update the views if there were any changes.
171 getUsers(); 174 getUsers();
172 getGroups(); 175 getGroups();
173 } 176 }
174 } else { 177 } else {
175 QMessageBox::information(this,"No selection.","No user has been selected."); 178 QMessageBox::information(this,"No selection.","No user has been selected.");
176 } 179 }
177 } 180 }
178} 181}
179 182
180void UserConfig::delUser() { 183void UserConfig::delUser() {
181 QString username; 184 QString username;
182 185
183 if(myTabWidget->currentPageIndex()==0) {// Users, Iconview. 186 if(myTabWidget->currentPageIndex()==0) {// Users, Iconview.
184 if(usersIconView->currentItem()) {// Anything selected? 187 if(usersIconView->currentItem()) {// Anything selected?
185 username=usersIconView->currentItem()->text(1);// Get string associated with icon. 188 username=usersIconView->currentItem()->text(1);// Get string associated with icon.
186 username=username.left(username.find(" - (",0,true));// Strip out the username. 189 username=username.left(username.find(" - (",0,true));// Strip out the username.
187 if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) { 190 if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) {
188 if(UserDialog::delUser(username)) {// Delete the user if possible. 191 if(UserDialog::delUser(username)) {// Delete the user if possible.
189 // Update views. 192 // Update views.
190 getUsers(); 193 getUsers();
191 getGroups(); 194 getGroups();
192 } 195 }
193 } 196 }
194 } else { 197 } else {
195 QMessageBox::information(this,"No selection","No user has been selected."); 198 QMessageBox::information(this,"No selection","No user has been selected.");
196 } 199 }
197 } 200 }
198 if(myTabWidget->currentPageIndex()==1) {// All users 201 if(myTabWidget->currentPageIndex()==1) {// All users
199 if(usersListView->currentItem()) {// Anything changed!? 202 if(usersListView->currentItem()) {// Anything changed!?
200 username=usersListView->currentItem()->text(1);// Get the username. 203 username=usersListView->currentItem()->text(1);// Get the username.
201 if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) { 204 if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) {
202 if(UserDialog::delUser(username)) {// Try to delete the user. 205 if(UserDialog::delUser(username)) {// Try to delete the user.
203 // Update views. 206 // Update views.
204 getUsers(); 207 getUsers();
205 getGroups(); 208 getGroups();
206 } 209 }
207 } 210 }
208 } else { 211 } else {
209 QMessageBox::information(this,"No selection","No user has been selected."); 212 QMessageBox::information(this,"No selection","No user has been selected.");
210 } 213 }
211 } 214 }
212 215
213} 216}
214 217
215void UserConfig::getGroups() { 218void UserConfig::getGroups() {
216 groupsListView->clear();// Empty the listview. 219 groupsListView->clear();// Empty the listview.
217 availableGID=500;// We need to find the next free GID, and are only interested in values between 500 & 65000. 220 availableGID=500;// We need to find the next free GID, and are only interested in values between 500 & 65000.
218 for(QStringList::Iterator it=accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it) {// Split the list into lines. 221 for(QStringList::Iterator it=accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it) {// Split the list into lines.
219 accounts->splitGroupEntry(*it);// Split the line into its components and fill the variables of 'accounts'. (gr_name, gr_uid & gr_mem). 222 accounts->splitGroupEntry(*it);// Split the line into its components and fill the variables of 'accounts'. (gr_name, gr_uid & gr_mem).
220 if(accounts->gr_name.find(QRegExp("^#"),0)) {// Skip commented lines. 223 if(accounts->gr_name.find(QRegExp("^#"),0)) {// Skip commented lines.
221 new QListViewItem(groupsListView,QString::number(accounts->gr_gid),accounts->gr_name); 224 new QListViewItem(groupsListView,QString::number(accounts->gr_gid),accounts->gr_name);
222 if((accounts->gr_gid>=availableGID) && (accounts->gr_gid<65000)) availableGID=accounts->gr_gid+1;// Maybe a new free GID. 225 if((accounts->gr_gid>=availableGID) && (accounts->gr_gid<65000)) availableGID=accounts->gr_gid+1;// Maybe a new free GID.
223 } 226 }
224 } 227 }
225} 228}
226 229
227void UserConfig::addGroup() { 230void UserConfig::addGroup() {
228 if(GroupDialog::addGroup(availableGID)) getGroups();// Bring up the add group dialog. 231 if(GroupDialog::addGroup(availableGID)) getGroups();// Bring up the add group dialog.
229} 232}
230 233
231void UserConfig::editGroup() { 234void UserConfig::editGroup() {
232 int gid; 235 int gid;
233 if(groupsListView->currentItem()) {// Any group selected? 236 if(groupsListView->currentItem()) {// Any group selected?
234 gid=groupsListView->currentItem()->text(0).toInt();// Get the GID from the listview. 237 gid=groupsListView->currentItem()->text(0).toInt();// Get the GID from the listview.
235 if(GroupDialog::editGroup(gid)) getGroups();// Bring up the edit group dialog. 238 if(GroupDialog::editGroup(gid)) getGroups();// Bring up the edit group dialog.
236 } else { 239 } else {
237 QMessageBox::information(this,"No selection","No group has been selected."); 240 QMessageBox::information(this,"No selection","No group has been selected.");
238 } 241 }
239} 242}
240 243
241void UserConfig::delGroup() { 244void UserConfig::delGroup() {
242 const char *groupname; 245 const char *groupname;
243 if(groupsListView->currentItem()) {// Any group selected? 246 if(groupsListView->currentItem()) {// Any group selected?
244 groupname=groupsListView->currentItem()->text(1);// Get the groupname from the listview. 247 groupname=groupsListView->currentItem()->text(1);// Get the groupname from the listview.
245 if(QMessageBox::warning(this,"Delete group","Are you sure you want to\ndelete the group \""+QString(groupname)+"\" ?","&No","&Yes",0,0,1)) { 248 if(QMessageBox::warning(this,"Delete group","Are you sure you want to\ndelete the group \""+QString(groupname)+"\" ?","&No","&Yes",0,0,1)) {
246 // If confirmed, try to delete the group. 249 // If confirmed, try to delete the group.
247 if(GroupDialog::delGroup(groupname)) getGroups(); // And also update the view afterwards if the user was deleted. 250 if(GroupDialog::delGroup(groupname)) getGroups(); // And also update the view afterwards if the user was deleted.
248 } 251 }
249 } else { 252 } else {
250 QMessageBox::information(this,"No selection","No group has been selected."); 253 QMessageBox::information(this,"No selection","No group has been selected.");
251 } 254 }
252} 255}
253 256
254void UserConfig::showUserMenu(QListViewItem *item) { 257void UserConfig::showUserMenu(QListViewItem *item) {
255 //userPopupMenu.exec(item->mapToGlobal(QPoint(0,0))); 258 //userPopupMenu.exec(item->mapToGlobal(QPoint(0,0)));
256 qWarning("Pressed!"); 259 owarn << "Pressed!" << oendl;
257} 260}
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 @@
1#CONFIG = qt warn_on 1CONFIG = qt warn_on quick-app
2CONFIG = qt warn_on quick-app
3HEADERS = usermanager.h userdialog.h groupdialog.h passwd.h 2HEADERS = usermanager.h userdialog.h groupdialog.h passwd.h
4SOURCES = usermanager.cpp userdialog.cpp groupdialog.cpp passwd.cpp main.cpp 3SOURCES = usermanager.cpp userdialog.cpp groupdialog.cpp passwd.cpp main.cpp
5INCLUDEPATH += $(OPIEDIR)/include 4INCLUDEPATH += $(OPIEDIR)/include
6DEPENDPATH += $(OPIEDIR)/include 5DEPENDPATH += $(OPIEDIR)/include
7LIBS += -lqpe -lopiecore2 -lopieui2 -lcrypt 6LIBS += -lqpe -lopiecore2 -lopieui2 -lcrypt
8TARGET = usermanager 7TARGET = usermanager
9 8
10include ( $(OPIEDIR)/include.pro ) 9include ( $(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 @@
1 config LIQUID 1 config LIQUID
2 boolean "opie-liquid (Mosfet's well known Liquid GUI style from KDE)" 2 boolean "opie-liquid (Mosfet's well known Liquid GUI style from KDE)"
3 default "y" 3 default "y"
4 depends ( LIBQPE || LIBQPE-X11 ) && LIBQTAUX 4 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 @@
1/*- 1/*-
2 * Copyright (C)QPL 2001 Daniel M. Duley. All rights reserved. 2 * Copyright (C)QPL 2001 Daniel M. Duley. All rights reserved.
3 */ 3 */
4 4
5// 5//
6// (c) 2002 Robert 'sandman' Griebl 6// (c) 2002 Robert 'sandman' Griebl
7// 7//
8 8
9 9
10#ifndef INCLUDE_MENUITEM_DEF 10#ifndef INCLUDE_MENUITEM_DEF
11#define INCLUDE_MENUITEM_DEF 11#define INCLUDE_MENUITEM_DEF
12#endif 12#endif
13 13
14#include <qmenudata.h>
15#include "liquid.h" 14#include "liquid.h"
16//#include "liquiddeco.h" 15#include "effects.h"
17#include <qapplication.h> 16#include "htmlmasks.h"
17#include "embeddata.h"
18
19/* OPIE */
20#include <opie2/odebug.h>
18#include <qpe/config.h> 21#include <qpe/config.h>
19#include "effects.h" 22using namespace Opie::Core;
23
24/* QT */
25#include <qmenudata.h>
26#include <qapplication.h>
20#include <qpalette.h> 27#include <qpalette.h>
21#include <qbitmap.h> 28#include <qbitmap.h>
22#include <qtabbar.h> 29#include <qtabbar.h>
23#include <qpopupmenu.h> 30#include <qpopupmenu.h>
24#include <qobjectlist.h> 31#include <qobjectlist.h>
25#include <qimage.h> 32#include <qimage.h>
26#include <qtimer.h> 33#include <qtimer.h>
27#include <qpixmapcache.h> 34#include <qpixmapcache.h>
28#include <qradiobutton.h> 35#include <qradiobutton.h>
29#include <qcombobox.h> 36#include <qcombobox.h>
30#include <qdrawutil.h> 37#include <qdrawutil.h>
31#include <qwidgetlist.h> 38#include <qwidgetlist.h>
32#include <qtoolbutton.h> 39#include <qtoolbutton.h>
33#include <qheader.h> 40#include <qheader.h>
34#include <unistd.h>
35#include <qmenubar.h> 41#include <qmenubar.h>
36#include <qprogressbar.h> 42#include <qprogressbar.h>
37#include <qlineedit.h> 43#include <qlineedit.h>
38#include <qlistbox.h> 44#include <qlistbox.h>
39 45
46/* STD */
47#include <unistd.h>
40#include <stdio.h> 48#include <stdio.h>
41 49
42#include "htmlmasks.h"
43#include "embeddata.h"
44
45 50
46typedef void (QStyle::*QDrawMenuBarItemImpl) (QPainter *, int, int, int, int, QMenuItem *, 51typedef void (QStyle::*QDrawMenuBarItemImpl) (QPainter *, int, int, int, int, QMenuItem *,
47 QColorGroup &, bool, bool); 52 QColorGroup &, bool, bool);
48 53
49QDrawMenuBarItemImpl qt_set_draw_menu_bar_impl(QDrawMenuBarItemImpl impl); 54QDrawMenuBarItemImpl qt_set_draw_menu_bar_impl(QDrawMenuBarItemImpl impl);
50 55
51void TransMenuHandler::stripePixmap(QPixmap &pix, const QColor &color) 56void TransMenuHandler::stripePixmap(QPixmap &pix, const QColor &color)
52{ 57{
53 QImage img(pix.convertToImage()); 58 QImage img(pix.convertToImage());
54 QImageEffect::fade(img, 0.9, color); 59 QImageEffect::fade(img, 0.9, color);
55 int x, y; 60 int x, y;
56 int r, g, b; 61 int r, g, b;
57 for(y=0; y < img.height(); y+=3){ 62 for(y=0; y < img.height(); y+=3){
58 unsigned int *data = (unsigned int *) img.scanLine(y); 63 unsigned int *data = (unsigned int *) img.scanLine(y);
59 for(x=0; x < img.width(); ++x){ 64 for(x=0; x < img.width(); ++x){
60 r = qRed(data[x]); 65 r = qRed(data[x]);
61 g = qGreen(data[x]); 66 g = qGreen(data[x]);
62 b = qBlue(data[x]); 67 b = qBlue(data[x]);
63 if(r-10) 68 if(r-10)
64 r-=10; 69 r-=10;
65 if(g-10) 70 if(g-10)
66 g-=10; 71 g-=10;
67 if(b-10) 72 if(b-10)
68 b-=10; 73 b-=10;
69 data[x] = qRgb(r, g, b); 74 data[x] = qRgb(r, g, b);
70 } 75 }
71 } 76 }
72 pix.convertFromImage(img); 77 pix.convertFromImage(img);
73} 78}
74 79
75TransMenuHandler::TransMenuHandler(QObject *parent) 80TransMenuHandler::TransMenuHandler(QObject *parent)
76 : QObject(parent) 81 : QObject(parent)
77{ 82{
78 pixDict.setAutoDelete(true); 83 pixDict.setAutoDelete(true);
79 reloadSettings(); 84 reloadSettings();
80} 85}
81 86
82void TransMenuHandler::reloadSettings() 87void TransMenuHandler::reloadSettings()
83{ 88{
84 pixDict.clear(); 89 pixDict.clear();
85 90
86 Config config ( "qpe" ); 91 Config config ( "qpe" );
87 config. setGroup ( "Liquid-Style" ); 92 config. setGroup ( "Liquid-Style" );
88 93
89 type = config. readNumEntry("Type", TransStippleBg); 94 type = config. readNumEntry("Type", TransStippleBg);
90 color = QColor ( config. readEntry("Color", QApplication::palette().active().button().name())); 95 color = QColor ( config. readEntry("Color", QApplication::palette().active().button().name()));
91 fgColor = QColor ( config. readEntry("TextColor", QApplication::palette().active().text().name())); 96 fgColor = QColor ( config. readEntry("TextColor", QApplication::palette().active().text().name()));
92 opacity = config. readNumEntry("Opacity", 10); 97 opacity = config. readNumEntry("Opacity", 10);
93 if ( opacity < -20 ) 98 if ( opacity < -20 )
94 opacity = 20; 99 opacity = 20;
95 else if ( opacity > 20 ) 100 else if ( opacity > 20 )
96 opacity = 20; 101 opacity = 20;
97 102
98 shadowText = config. readBoolEntry("ShadowText", true); 103 shadowText = config. readBoolEntry("ShadowText", true);
99} 104}
100 105
101bool TransMenuHandler::eventFilter(QObject *obj, QEvent *ev) 106bool TransMenuHandler::eventFilter(QObject *obj, QEvent *ev)
102{ 107{
103 QWidget *p = (QWidget *)obj; 108 QWidget *p = (QWidget *)obj;
104 109
105 if(ev->type() == QEvent::Show){ 110 if(ev->type() == QEvent::Show){
106 if(type == TransStippleBg || type == TransStippleBtn || 111 if(type == TransStippleBg || type == TransStippleBtn ||
107 type == Custom){ 112 type == Custom){
108 QApplication::syncX(); 113 QApplication::syncX();
109 QPixmap *pix = new QPixmap; 114 QPixmap *pix = new QPixmap;
110 if(p->testWFlags(Qt::WType_Popup)){ 115 if(p->testWFlags(Qt::WType_Popup)){
111 QRect r(p->x(), p->y(), p->width(), p->height()); 116 QRect r(p->x(), p->y(), p->width(), p->height());
112 QRect deskR = QApplication::desktop()->rect(); 117 QRect deskR = QApplication::desktop()->rect();
113 if(r.right() > deskR.right() || r.bottom() > deskR.bottom()){ 118 if(r.right() > deskR.right() || r.bottom() > deskR.bottom()){
114 r.setBottom(deskR.bottom()); 119 r.setBottom(deskR.bottom());
115 r.setRight(deskR.right()); 120 r.setRight(deskR.right());
116 } 121 }
117 *pix = QPixmap::grabWindow(QApplication::desktop()-> winId(), r.x(), r.y(), 122 *pix = QPixmap::grabWindow(QApplication::desktop()-> winId(), r.x(), r.y(),
118 r.width(), r.height()); 123 r.width(), r.height());
119 } 124 }
120 else{ // tear off menu 125 else{ // tear off menu
121 pix->resize(p->width(), p->height()); 126 pix->resize(p->width(), p->height());
122 pix->fill(Qt::black.rgb()); 127 pix->fill(Qt::black.rgb());
123 } 128 }
124 if(type == TransStippleBg){ 129 if(type == TransStippleBg){
125 stripePixmap(*pix, p->colorGroup().background()); 130 stripePixmap(*pix, p->colorGroup().background());
126 } 131 }
127 else if(type == TransStippleBtn){ 132 else if(type == TransStippleBtn){
128 stripePixmap(*pix, p->colorGroup().button()); 133 stripePixmap(*pix, p->colorGroup().button());
129 } 134 }
130 else{ 135 else{
131 QPixmapEffect::fade(*pix, (((float)opacity)+80)*0.01, color); 136 QPixmapEffect::fade(*pix, (((float)opacity)+80)*0.01, color);
132 } 137 }
133 138
134 pixDict.insert(p->winId(), pix); 139 pixDict.insert(p->winId(), pix);
135 140
136 if ( !p->inherits("QPopupMenu")) 141 if ( !p->inherits("QPopupMenu"))
137 p->setBackgroundPixmap(*pix); 142 p->setBackgroundPixmap(*pix);
138 143
139 QObjectList *ol = p-> queryList("QWidget"); 144 QObjectList *ol = p-> queryList("QWidget");
140 for ( QObjectListIt it( *ol ); it. current ( ); ++it ) { 145 for ( QObjectListIt it( *ol ); it. current ( ); ++it ) {
141 QWidget *wid = (QWidget *) it.current ( ); 146 QWidget *wid = (QWidget *) it.current ( );
142 147
143 wid-> setBackgroundPixmap(*pix); 148 wid-> setBackgroundPixmap(*pix);
144 wid-> setBackgroundOrigin(QWidget::ParentOrigin); 149 wid-> setBackgroundOrigin(QWidget::ParentOrigin);
145 } 150 }
146 delete ol; 151 delete ol;
147 } 152 }
148 } 153 }
149 else if(ev->type() == QEvent::Hide){ 154 else if(ev->type() == QEvent::Hide){
150 if(type == TransStippleBg || type == TransStippleBtn || 155 if(type == TransStippleBg || type == TransStippleBtn ||
151 type == Custom){ 156 type == Custom){
152// qWarning("Deleting menu pixmap, width %d", pixDict.find(p->winId())->width()); 157// owarn << "Deleting menu pixmap, width " << pixDict.find(p->winId())->width() << "" << oendl;
153 158
154 pixDict.remove(p->winId()); 159 pixDict.remove(p->winId());
155 if ( !p->inherits("QPopupMenu")) 160 if ( !p->inherits("QPopupMenu"))
156 p->setBackgroundMode(QWidget::PaletteBackground); 161 p->setBackgroundMode(QWidget::PaletteBackground);
157 162
158 QObjectList *ol = p-> queryList("QWidget"); 163 QObjectList *ol = p-> queryList("QWidget");
159 for ( QObjectListIt it( *ol ); it. current ( ); ++it ) { 164 for ( QObjectListIt it( *ol ); it. current ( ); ++it ) {
160 QWidget *wid = (QWidget *) it.current ( ); 165 QWidget *wid = (QWidget *) it.current ( );
161 166
162 wid-> setBackgroundMode( QWidget::PaletteBackground ); 167 wid-> setBackgroundMode( QWidget::PaletteBackground );
163 } 168 }
164 delete ol; 169 delete ol;
165 } 170 }
166 } 171 }
167 return(false); 172 return(false);
168} 173}
169 174
170 175
171 176
172 177
173LiquidStyle::LiquidStyle() 178LiquidStyle::LiquidStyle()
174 :QWindowsStyle() 179 :QWindowsStyle()
175{ 180{
176 setName ( "LiquidStyle" ); 181 setName ( "LiquidStyle" );
177 182
178 flatTBButtons = false; 183 flatTBButtons = false;
179 currentHeader = 0; 184 currentHeader = 0;
180 185
181 btnMaskBmp = QBitmap(37, 26, buttonmask_bits, true); 186 btnMaskBmp = QBitmap(37, 26, buttonmask_bits, true);
182 btnMaskBmp.setMask(btnMaskBmp); 187 btnMaskBmp.setMask(btnMaskBmp);
183 htmlBtnMaskBmp = QBitmap(37, 26, htmlbuttonmask_bits, true); 188 htmlBtnMaskBmp = QBitmap(37, 26, htmlbuttonmask_bits, true);
184 htmlBtnMaskBmp.setMask(htmlBtnMaskBmp); 189 htmlBtnMaskBmp.setMask(htmlBtnMaskBmp);
185 headerHoverID = -1; 190 headerHoverID = -1;
186 highlightWidget = NULL; 191 highlightWidget = NULL;
187 setButtonDefaultIndicatorWidth(0); 192 setButtonDefaultIndicatorWidth(0);
188 btnDict.setAutoDelete(true); 193 btnDict.setAutoDelete(true);
189 bevelFillDict.setAutoDelete(true); 194 bevelFillDict.setAutoDelete(true);
190 smallBevelFillDict.setAutoDelete(true); 195 smallBevelFillDict.setAutoDelete(true);
191 196
192 rMatrix.rotate(270.0); 197 rMatrix.rotate(270.0);
193 btnBorderPix = new QPixmap; 198 btnBorderPix = new QPixmap;
194 btnBorderPix->convertFromImage(qembed_findImage("buttonfill")); 199 btnBorderPix->convertFromImage(qembed_findImage("buttonfill"));
195 btnBlendPix = new QPixmap; 200 btnBlendPix = new QPixmap;
196 btnBlendPix->convertFromImage(qembed_findImage("buttonborder")); 201 btnBlendPix->convertFromImage(qembed_findImage("buttonborder"));
197 bevelFillPix = new QPixmap; 202 bevelFillPix = new QPixmap;
198 bevelFillPix->convertFromImage(qembed_findImage("clear_fill_large")); 203 bevelFillPix->convertFromImage(qembed_findImage("clear_fill_large"));
199 smallBevelFillPix = new QPixmap; 204 smallBevelFillPix = new QPixmap;
200 smallBevelFillPix->convertFromImage(qembed_findImage("clear_fill_small")); 205 smallBevelFillPix->convertFromImage(qembed_findImage("clear_fill_small"));
201 // new stuff 206 // new stuff
202 vsbSliderFillPix = menuPix = NULL; 207 vsbSliderFillPix = menuPix = NULL;
203 menuHandler = new TransMenuHandler(this); 208 menuHandler = new TransMenuHandler(this);
204 setScrollBarExtent(15, 15); 209 setScrollBarExtent(15, 15);
205 int i; 210 int i;
206 for(i=0; i < BITMAP_ITEMS; ++i){ 211 for(i=0; i < BITMAP_ITEMS; ++i){
207 pixmaps[i] = NULL; 212 pixmaps[i] = NULL;
208 } 213 }
209 oldSliderThickness = sliderThickness(); 214 oldSliderThickness = sliderThickness();
210 setSliderThickness(11); 215 setSliderThickness(11);
211} 216}
212 217
213LiquidStyle::~LiquidStyle() 218LiquidStyle::~LiquidStyle()
214{ 219{
215 if(btnBorderPix) 220 if(btnBorderPix)
216 delete btnBorderPix; 221 delete btnBorderPix;
217 if(btnBlendPix) 222 if(btnBlendPix)
218 delete btnBlendPix; 223 delete btnBlendPix;
219 if(bevelFillPix) 224 if(bevelFillPix)
220 delete bevelFillPix; 225 delete bevelFillPix;
221 if(smallBevelFillPix) 226 if(smallBevelFillPix)
222 delete smallBevelFillPix; 227 delete smallBevelFillPix;
223 if(vsbSliderFillPix) 228 if(vsbSliderFillPix)
224 delete vsbSliderFillPix; 229 delete vsbSliderFillPix;
225 if(menuPix) 230 if(menuPix)
226 delete menuPix; 231 delete menuPix;
227 232
228 setScrollBarExtent(16, 16); 233 setScrollBarExtent(16, 16);
229 setSliderThickness(oldSliderThickness); 234 setSliderThickness(oldSliderThickness);
230 int i; 235 int i;
231 for(i=0; i < BITMAP_ITEMS; ++i){ 236 for(i=0; i < BITMAP_ITEMS; ++i){
232 if(pixmaps[i]) 237 if(pixmaps[i])
233 delete pixmaps[i]; 238 delete pixmaps[i];
234 } 239 }
235} 240}
236 241
237void LiquidStyle::drawClearBevel(QPainter *p, int x, int y, int w, int h, 242void LiquidStyle::drawClearBevel(QPainter *p, int x, int y, int w, int h,
238 const QColor &c, const QColor &bg) 243 const QColor &c, const QColor &bg)
239{ 244{
240 245
241 QPen oldPen = p->pen(); // headers need this 246 QPen oldPen = p->pen(); // headers need this
242 int x2 = x+w-1; 247 int x2 = x+w-1;
243 int y2 = y+h-1; 248 int y2 = y+h-1;
244 // outer dark rect 249 // outer dark rect
245 p->setPen(c.dark(130)); 250 p->setPen(c.dark(130));
246 p->drawLine(x, y+2, x, y2-2); // l 251 p->drawLine(x, y+2, x, y2-2); // l
247 p->drawLine(x2, y+2, x2, y2-2); // r 252 p->drawLine(x2, y+2, x2, y2-2); // r
248 p->drawLine(x+2, y, x2-2, y); // t 253 p->drawLine(x+2, y, x2-2, y); // t
@@ -401,193 +406,193 @@ void LiquidStyle::drawRoundButton(QPainter *painter, const QColor &c,
401 //r = (int)(qRed(bgRgb)*0.75 + qRed(fgRgb)*0.25); 406 //r = (int)(qRed(bgRgb)*0.75 + qRed(fgRgb)*0.25);
402 //g = (int)(qGreen(bgRgb)*0.75 + qGreen(fgRgb)*0.25); 407 //g = (int)(qGreen(bgRgb)*0.75 + qGreen(fgRgb)*0.25);
403 //b = (int)(qBlue(bgRgb)*0.75 + qBlue(fgRgb)*0.25); 408 //b = (int)(qBlue(bgRgb)*0.75 + qBlue(fgRgb)*0.25);
404 //QColor blendColor(r, g, b); 409 //QColor blendColor(r, g, b);
405 int hue, sat, v1, v2; 410 int hue, sat, v1, v2;
406 QColor blendColor(autoDefault ? c : back); 411 QColor blendColor(autoDefault ? c : back);
407 back.hsv(&hue, &sat, &v1); 412 back.hsv(&hue, &sat, &v1);
408 blendColor.hsv(&hue, &sat, &v2); 413 blendColor.hsv(&hue, &sat, &v2);
409 if(v2 > v1) 414 if(v2 > v1)
410 blendColor.setHsv(hue, sat, (int)(v1*0.75 + v2*0.25)); 415 blendColor.setHsv(hue, sat, (int)(v1*0.75 + v2*0.25));
411 416
412 pix = btnBorderDict.find(blendColor.rgb()); 417 pix = btnBorderDict.find(blendColor.rgb());
413 if(!pix){ 418 if(!pix){
414 int h, s, v; 419 int h, s, v;
415 blendColor.hsv(&h, &s, &v); 420 blendColor.hsv(&h, &s, &v);
416 pix = new QPixmap(*btnBlendPix); 421 pix = new QPixmap(*btnBlendPix);
417 adjustHSV(*pix, h, s, v); 422 adjustHSV(*pix, h, s, v);
418 btnBorderDict.insert(blendColor.rgb(), pix); 423 btnBorderDict.insert(blendColor.rgb(), pix);
419 } 424 }
420 } 425 }
421 else{ 426 else{
422 pix = pushedDown ? getPixmap(HTMLBtnBorderDown) : 427 pix = pushedDown ? getPixmap(HTMLBtnBorderDown) :
423 getPixmap(HTMLBtnBorder); 428 getPixmap(HTMLBtnBorder);
424 } 429 }
425 p.drawPixmap(0, 0, *pix, 0, 0, 10, 10); // tl 430 p.drawPixmap(0, 0, *pix, 0, 0, 10, 10); // tl
426 p.drawPixmap(x2-9, 0, *pix, bx2-9, 0, 10, 10); // tr 431 p.drawPixmap(x2-9, 0, *pix, bx2-9, 0, 10, 10); // tr
427 p.drawPixmap(0, y2-9, *pix, 0, by2-9, 10, 10); // bl 432 p.drawPixmap(0, y2-9, *pix, 0, by2-9, 10, 10); // bl
428 p.drawPixmap(x2-9, y2-9, *pix, bx2-9, by2-9, 10, 10); // br 433 p.drawPixmap(x2-9, y2-9, *pix, bx2-9, by2-9, 10, 10); // br
429 434
430 // edges 435 // edges
431 tilePix.resize(pix->width()-20, 10); 436 tilePix.resize(pix->width()-20, 10);
432 blendMask.resize(pix->width()-20, 10); 437 blendMask.resize(pix->width()-20, 10);
433 // top 438 // top
434 bitBlt(&tilePix, 0, 0, pix, 10, 0, pix->width()-20, 10); 439 bitBlt(&tilePix, 0, 0, pix, 10, 0, pix->width()-20, 10);
435 bitBlt(&blendMask, 0, 0, pix->mask(), 10, 0, pix->width()-20, 10); 440 bitBlt(&blendMask, 0, 0, pix->mask(), 10, 0, pix->width()-20, 10);
436 tilePix.setMask(blendMask); 441 tilePix.setMask(blendMask);
437 p.drawTiledPixmap(10, 0, w-20, 10, tilePix); 442 p.drawTiledPixmap(10, 0, w-20, 10, tilePix);
438 // bottom 443 // bottom
439 bitBlt(&tilePix, 0, 0, pix, 10, by2-9, pix->width()-20, 20); 444 bitBlt(&tilePix, 0, 0, pix, 10, by2-9, pix->width()-20, 20);
440 bitBlt(&blendMask, 0, 0, pix->mask(), 10, by2-9, pix->width()-20, 20); 445 bitBlt(&blendMask, 0, 0, pix->mask(), 10, by2-9, pix->width()-20, 20);
441 tilePix.setMask(blendMask); 446 tilePix.setMask(blendMask);
442 p.drawTiledPixmap(10, y2-9, w-20, 10, tilePix); 447 p.drawTiledPixmap(10, y2-9, w-20, 10, tilePix);
443 // left 448 // left
444 tilePix.resize(10, pix->height()-20); 449 tilePix.resize(10, pix->height()-20);
445 blendMask.resize(10, pix->height()-20); 450 blendMask.resize(10, pix->height()-20);
446 bitBlt(&tilePix, 0, 0, pix, 0, 10, 10, pix->height()-20); 451 bitBlt(&tilePix, 0, 0, pix, 0, 10, 10, pix->height()-20);
447 bitBlt(&blendMask, 0, 0, pix->mask(), 0, 10, 10, pix->height()-20); 452 bitBlt(&blendMask, 0, 0, pix->mask(), 0, 10, 10, pix->height()-20);
448 tilePix.setMask(blendMask); 453 tilePix.setMask(blendMask);
449 p.drawTiledPixmap(0, 10, 10, h-20, tilePix); 454 p.drawTiledPixmap(0, 10, 10, h-20, tilePix);
450 // right 455 // right
451 bitBlt(&tilePix, 0, 0, pix, bx2-9, 10, 10, pix->height()-20); 456 bitBlt(&tilePix, 0, 0, pix, bx2-9, 10, 10, pix->height()-20);
452 bitBlt(&blendMask, 0, 0, pix->mask(), bx2-9, 10, 10, pix->height()-20); 457 bitBlt(&blendMask, 0, 0, pix->mask(), bx2-9, 10, 10, pix->height()-20);
453 tilePix.setMask(blendMask); 458 tilePix.setMask(blendMask);
454 p.drawTiledPixmap(x2-9, 10, 10, h-20, tilePix); 459 p.drawTiledPixmap(x2-9, 10, 10, h-20, tilePix);
455 460
456 p.end(); 461 p.end();
457 462
458 // do the button mask - we don't automask buttons 463 // do the button mask - we don't automask buttons
459 QBitmap btnMask(w, h); 464 QBitmap btnMask(w, h);
460 QBitmap *mask = isMasked ? &htmlBtnMaskBmp : &btnMaskBmp; 465 QBitmap *mask = isMasked ? &htmlBtnMaskBmp : &btnMaskBmp;
461 p.begin(&btnMask); 466 p.begin(&btnMask);
462 p.fillRect(0, 0, w, h, Qt::color0); 467 p.fillRect(0, 0, w, h, Qt::color0);
463 p.drawPixmap(0, 0, *mask, 0, 0, 10, 10); // tl 468 p.drawPixmap(0, 0, *mask, 0, 0, 10, 10); // tl
464 p.drawPixmap(x2-9, 0, *mask, bx2-9, 0, 10, 10); // tr 469 p.drawPixmap(x2-9, 0, *mask, bx2-9, 0, 10, 10); // tr
465 p.drawPixmap(0, y2-9, *mask, 0, by2-9, 10, 10); // bl 470 p.drawPixmap(0, y2-9, *mask, 0, by2-9, 10, 10); // bl
466 p.drawPixmap(x2-9, y2-9, *mask, bx2-9, by2-9, 10, 10); // br 471 p.drawPixmap(x2-9, y2-9, *mask, bx2-9, by2-9, 10, 10); // br
467 // fills 472 // fills
468 p.fillRect(10, 0, w-20, 10, Qt::color1); // top 473 p.fillRect(10, 0, w-20, 10, Qt::color1); // top
469 p.fillRect(10, y2-9, w-20, 10, Qt::color1); // bottom 474 p.fillRect(10, y2-9, w-20, 10, Qt::color1); // bottom
470 p.fillRect(0, 10, w, h-20, Qt::color1); // middle 475 p.fillRect(0, 10, w, h-20, Qt::color1); // middle
471 p.end(); 476 p.end();
472 tmpPix.setMask(btnMask); 477 tmpPix.setMask(btnMask);
473 /*if(autoDefault){ 478 /*if(autoDefault){
474 if(supportPushDown && pushedDown){ 479 if(supportPushDown && pushedDown){
475 painter->drawPixmap(x+3, y+3, tmpPix); 480 painter->drawPixmap(x+3, y+3, tmpPix);
476 } 481 }
477 else{ 482 else{
478 painter->drawPixmap(x+2, y+2, tmpPix); 483 painter->drawPixmap(x+2, y+2, tmpPix);
479 } 484 }
480 } 485 }
481 else */if(supportPushDown && pushedDown) 486 else */if(supportPushDown && pushedDown)
482 painter->drawPixmap(x+1, y+1, tmpPix); 487 painter->drawPixmap(x+1, y+1, tmpPix);
483 else 488 else
484 painter->drawPixmap(x, y, tmpPix); 489 painter->drawPixmap(x, y, tmpPix);
485 490
486 491
487 492
488} 493}
489 494
490 495
491QPixmap* LiquidStyle::processEmbedded(const char *label, int h, int s, int v, 496QPixmap* LiquidStyle::processEmbedded(const char *label, int h, int s, int v,
492 bool blend) 497 bool blend)
493{ 498{
494 QImage img(qembed_findImage(label)); 499 QImage img(qembed_findImage(label));
495 img.detach(); 500 img.detach();
496 if(img.isNull()){ // shouldn't happen, been tested 501 if(img.isNull()){ // shouldn't happen, been tested
497 qWarning("Invalid embedded label %s", label); 502 owarn << "Invalid embedded label " << label << "" << oendl;
498 return(NULL); 503 return(NULL);
499 } 504 }
500 if(img.depth() != 32) 505 if(img.depth() != 32)
501 img = img.convertDepth(32); 506 img = img.convertDepth(32);
502 unsigned int *data = (unsigned int *)img.bits(); 507 unsigned int *data = (unsigned int *)img.bits();
503 int total = img.width()*img.height(); 508 int total = img.width()*img.height();
504 int current; 509 int current;
505 QColor c; 510 QColor c;
506 int oldH, oldS, oldV; 511 int oldH, oldS, oldV;
507 int alpha; 512 int alpha;
508 if(v < 235) 513 if(v < 235)
509 v += 20; 514 v += 20;
510 else 515 else
511 v = 255; 516 v = 255;
512 float intensity = v/255.0; 517 float intensity = v/255.0;
513 518
514 for(current=0; current<total; ++current){ 519 for(current=0; current<total; ++current){
515 alpha = qAlpha(data[current]); 520 alpha = qAlpha(data[current]);
516 c.setRgb(data[current]); 521 c.setRgb(data[current]);
517 c.hsv(&oldH, &oldS, &oldV); 522 c.hsv(&oldH, &oldS, &oldV);
518 oldV = (int)(oldV*intensity); 523 oldV = (int)(oldV*intensity);
519 c.setHsv(h, s, oldV); 524 c.setHsv(h, s, oldV);
520 if(blend && alpha != 255 && alpha != 0){ 525 if(blend && alpha != 255 && alpha != 0){
521 float srcPercent = ((float)alpha)/255.0; 526 float srcPercent = ((float)alpha)/255.0;
522 float destPercent = 1.0-srcPercent; 527 float destPercent = 1.0-srcPercent;
523 oldH = (int)((srcPercent*h) + (destPercent*bH)); 528 oldH = (int)((srcPercent*h) + (destPercent*bH));
524 oldS = (int)((srcPercent*s) + (destPercent*bS)); 529 oldS = (int)((srcPercent*s) + (destPercent*bS));
525 oldV = (int)((srcPercent*oldV) + (destPercent*bV)); 530 oldV = (int)((srcPercent*oldV) + (destPercent*bV));
526 c.setHsv(oldH, oldS, oldV); 531 c.setHsv(oldH, oldS, oldV);
527 alpha = 255; 532 alpha = 255;
528 } 533 }
529 data[current] = qRgba(c.red(), c.green(), c.blue(), alpha); 534 data[current] = qRgba(c.red(), c.green(), c.blue(), alpha);
530 } 535 }
531 QPixmap *pix = new QPixmap; 536 QPixmap *pix = new QPixmap;
532 pix->convertFromImage(img); 537 pix->convertFromImage(img);
533 return(pix); 538 return(pix);
534} 539}
535 540
536 541
537 542
538 543
539QPixmap* LiquidStyle::getPixmap(BitmapData item) 544QPixmap* LiquidStyle::getPixmap(BitmapData item)
540{ 545{
541 546
542 if(pixmaps[item]) 547 if(pixmaps[item])
543 return(pixmaps[item]); 548 return(pixmaps[item]);
544 549
545 switch(item){ 550 switch(item){
546 case HTMLBtnBorder: 551 case HTMLBtnBorder:
547 pixmaps[HTMLBtnBorder] = processEmbedded("htmlbtnborder", btnH, btnS, btnV); 552 pixmaps[HTMLBtnBorder] = processEmbedded("htmlbtnborder", btnH, btnS, btnV);
548 break; 553 break;
549 case HTMLBtnBorderDown: 554 case HTMLBtnBorderDown:
550 pixmaps[HTMLBtnBorderDown] = processEmbedded("htmlbtnborder", btnHoverH, btnHoverS, btnHoverV); 555 pixmaps[HTMLBtnBorderDown] = processEmbedded("htmlbtnborder", btnHoverH, btnHoverS, btnHoverV);
551 break; 556 break;
552 557
553 case HTMLCB: 558 case HTMLCB:
554 pixmaps[HTMLCB] = processEmbedded("htmlcheckbox", bH, bS, bV); 559 pixmaps[HTMLCB] = processEmbedded("htmlcheckbox", bH, bS, bV);
555 break; 560 break;
556 case HTMLCBHover: 561 case HTMLCBHover:
557 pixmaps[HTMLCBHover] = processEmbedded("htmlcheckbox", btnHoverH, btnHoverS, btnHoverV); 562 pixmaps[HTMLCBHover] = processEmbedded("htmlcheckbox", btnHoverH, btnHoverS, btnHoverV);
558 break; 563 break;
559 case HTMLCBDown: 564 case HTMLCBDown:
560 pixmaps[HTMLCBDown] = processEmbedded("htmlcheckboxdown", btnH, btnS, btnV); 565 pixmaps[HTMLCBDown] = processEmbedded("htmlcheckboxdown", btnH, btnS, btnV);
561 break; 566 break;
562 case HTMLCBDownHover: 567 case HTMLCBDownHover:
563 pixmaps[HTMLCBDownHover] = processEmbedded("htmlcheckboxdown", btnHoverH, btnHoverS, btnHoverV); 568 pixmaps[HTMLCBDownHover] = processEmbedded("htmlcheckboxdown", btnHoverH, btnHoverS, btnHoverV);
564 break; 569 break;
565 570
566 case HTMLRadio: 571 case HTMLRadio:
567 pixmaps[HTMLRadio] = processEmbedded("htmlradio", bH, bS, bV); 572 pixmaps[HTMLRadio] = processEmbedded("htmlradio", bH, bS, bV);
568 break; 573 break;
569 case HTMLRadioHover: 574 case HTMLRadioHover:
570 pixmaps[HTMLRadioHover] = processEmbedded("htmlradio", btnHoverH, btnHoverS, btnHoverV); 575 pixmaps[HTMLRadioHover] = processEmbedded("htmlradio", btnHoverH, btnHoverS, btnHoverV);
571 break; 576 break;
572 case HTMLRadioDown: 577 case HTMLRadioDown:
573 pixmaps[HTMLRadioDown] = processEmbedded("htmlradiodown", btnH, btnS, btnV); 578 pixmaps[HTMLRadioDown] = processEmbedded("htmlradiodown", btnH, btnS, btnV);
574 break; 579 break;
575 case HTMLRadioDownHover: 580 case HTMLRadioDownHover:
576 pixmaps[HTMLRadioDownHover] = processEmbedded("htmlradiodown", btnHoverH, btnHoverS, btnHoverV); 581 pixmaps[HTMLRadioDownHover] = processEmbedded("htmlradiodown", btnHoverH, btnHoverS, btnHoverV);
577 break; 582 break;
578 583
579 case RadioOff: 584 case RadioOff:
580 pixmaps[RadioOff] = processEmbedded("radio", bH, bS, bV /*, true*/); 585 pixmaps[RadioOff] = processEmbedded("radio", bH, bS, bV /*, true*/);
581 break; 586 break;
582 case RadioOffHover: 587 case RadioOffHover:
583 pixmaps[RadioOffHover] = processEmbedded("radio", btnHoverH, btnHoverS, btnHoverV /*, true*/); 588 pixmaps[RadioOffHover] = processEmbedded("radio", btnHoverH, btnHoverS, btnHoverV /*, true*/);
584 break; 589 break;
585 case RadioOn: 590 case RadioOn:
586 pixmaps[RadioOn] = processEmbedded("radio_down", btnH, btnS, btnV /*, true*/); 591 pixmaps[RadioOn] = processEmbedded("radio_down", btnH, btnS, btnV /*, true*/);
587 break; 592 break;
588 case RadioOnHover: 593 case RadioOnHover:
589 pixmaps[RadioOnHover] = processEmbedded("radio_down", btnHoverH, btnHoverS, btnHoverV /*, true*/); 594 pixmaps[RadioOnHover] = processEmbedded("radio_down", btnHoverH, btnHoverS, btnHoverV /*, true*/);
590 break; 595 break;
591 596
592 case Tab: 597 case Tab:
593 pixmaps[Tab] = processEmbedded("tab", bH, bS, bV /*, true*/); 598 pixmaps[Tab] = processEmbedded("tab", bH, bS, bV /*, true*/);
@@ -767,193 +772,193 @@ void LiquidStyle::polish(QPalette &appPal)
767 // background brush 772 // background brush
768 QPixmap wallPaper(32, 32); 773 QPixmap wallPaper(32, 32);
769 wallPaper.fill(c.rgb()); 774 wallPaper.fill(c.rgb());
770 painter.begin(&wallPaper); 775 painter.begin(&wallPaper);
771 for(i=0; i < 32; i+=4){ 776 for(i=0; i < 32; i+=4){
772 painter.setPen(c.dark(100 + contrast)); 777 painter.setPen(c.dark(100 + contrast));
773 painter.drawLine(0, i, 32, i); 778 painter.drawLine(0, i, 32, i);
774 painter.setPen(c.dark(100 + 3 * contrast / 5 ) ); 779 painter.setPen(c.dark(100 + 3 * contrast / 5 ) );
775 painter.drawLine(0, i+1, 32, i+1); 780 painter.drawLine(0, i+1, 32, i+1);
776 }; 781 };
777 painter.end(); 782 painter.end();
778 bgBrush.setColor(c); 783 bgBrush.setColor(c);
779 bgBrush.setPixmap(wallPaper); 784 bgBrush.setPixmap(wallPaper);
780 appPal.setBrush(QColorGroup::Background, bgBrush); 785 appPal.setBrush(QColorGroup::Background, bgBrush);
781} 786}
782 787
783void LiquidStyle::polish(QWidget *w) 788void LiquidStyle::polish(QWidget *w)
784{ 789{
785 if(w->inherits("QMenuBar")){ 790 if(w->inherits("QMenuBar")){
786 //((QFrame*)w)->setLineWidth(0); 791 //((QFrame*)w)->setLineWidth(0);
787 w->setBackgroundMode(QWidget::PaletteBackground); 792 w->setBackgroundMode(QWidget::PaletteBackground);
788 w->setBackgroundOrigin(QWidget::ParentOrigin); 793 w->setBackgroundOrigin(QWidget::ParentOrigin);
789 return; 794 return;
790 } 795 }
791 if(w->inherits("QToolBar")){ 796 if(w->inherits("QToolBar")){
792 w->installEventFilter(this); 797 w->installEventFilter(this);
793 w->setBackgroundMode(QWidget::PaletteBackground); 798 w->setBackgroundMode(QWidget::PaletteBackground);
794 w->setBackgroundOrigin(QWidget::WidgetOrigin); 799 w->setBackgroundOrigin(QWidget::WidgetOrigin);
795 return; 800 return;
796 } 801 }
797 if(w->inherits("QPopupMenu")) 802 if(w->inherits("QPopupMenu"))
798 w->setBackgroundMode(QWidget::NoBackground); 803 w->setBackgroundMode(QWidget::NoBackground);
799 else if(w-> testWFlags(Qt::WType_Popup) && 804 else if(w-> testWFlags(Qt::WType_Popup) &&
800 !w->inherits("QListBox") && 805 !w->inherits("QListBox") &&
801 ( qstrcmp ( w-> name(), "automatic what's this? widget" ) != 0 )) { 806 ( qstrcmp ( w-> name(), "automatic what's this? widget" ) != 0 )) {
802 w->installEventFilter(menuHandler); 807 w->installEventFilter(menuHandler);
803 } 808 }
804 809
805 if(w->isTopLevel()){ 810 if(w->isTopLevel()){
806 return; 811 return;
807 } 812 }
808 813
809 if(w->inherits("QRadioButton") || w->inherits("QCheckBox") || w->inherits("QProgressBar")) { 814 if(w->inherits("QRadioButton") || w->inherits("QCheckBox") || w->inherits("QProgressBar")) {
810 w->installEventFilter(this); 815 w->installEventFilter(this);
811 } 816 }
812 817
813 if(w->inherits("QButton") || w-> inherits("QComboBox")){ 818 if(w->inherits("QButton") || w-> inherits("QComboBox")){
814 w-> setBackgroundMode ( QWidget::PaletteBackground ); 819 w-> setBackgroundMode ( QWidget::PaletteBackground );
815 w->setBackgroundOrigin ( QWidget::ParentOrigin); 820 w->setBackgroundOrigin ( QWidget::ParentOrigin);
816 } 821 }
817 822
818 bool isViewport = qstrcmp(w->name(), "qt_viewport") == 0 || 823 bool isViewport = qstrcmp(w->name(), "qt_viewport") == 0 ||
819 qstrcmp(w->name(), "qt_clipped_viewport") == 0; 824 qstrcmp(w->name(), "qt_clipped_viewport") == 0;
820 bool isViewportChild = w->parent() && 825 bool isViewportChild = w->parent() &&
821 ((qstrcmp(w->parent()->name(), "qt_viewport") == 0) || 826 ((qstrcmp(w->parent()->name(), "qt_viewport") == 0) ||
822 (qstrcmp(w->parent()->name(), "qt_clipped_viewport") == 0)); 827 (qstrcmp(w->parent()->name(), "qt_clipped_viewport") == 0));
823 828
824 if(isViewport && w->parent() && qstrcmp(w->parent()->name(), "proxyview") == 0){ 829 if(isViewport && w->parent() && qstrcmp(w->parent()->name(), "proxyview") == 0){
825 w->setBackgroundMode(QWidget::X11ParentRelative); 830 w->setBackgroundMode(QWidget::X11ParentRelative);
826 return; 831 return;
827 } 832 }
828 if(isViewportChild){ 833 if(isViewportChild){
829 if(w->inherits("QButton") || w->inherits("QComboBox")){ 834 if(w->inherits("QButton") || w->inherits("QComboBox")){
830 if(w->parent()){ // heh, only way to test for KHTML children ;-) 835 if(w->parent()){ // heh, only way to test for KHTML children ;-)
831 if(w->parent()->parent()){ 836 if(w->parent()->parent()){
832 if(w->parent()->parent()->parent() && 837 if(w->parent()->parent()->parent() &&
833 w->parent()->parent()->parent()->inherits("KHTMLView")){ 838 w->parent()->parent()->parent()->inherits("KHTMLView")){
834 w->setAutoMask(true); 839 w->setAutoMask(true);
835 w->setBackgroundMode(QWidget::NoBackground); 840 w->setBackgroundMode(QWidget::NoBackground);
836 } 841 }
837 } 842 }
838 } 843 }
839 return; 844 return;
840 } 845 }
841 } 846 }
842 if(w->inherits("QHeader")){ 847 if(w->inherits("QHeader")){
843 w->setMouseTracking(true); 848 w->setMouseTracking(true);
844 w->installEventFilter(this); 849 w->installEventFilter(this);
845 } 850 }
846 if(w-> inherits("QToolButton")) { 851 if(w-> inherits("QToolButton")) {
847 if (w->parent()->inherits("QToolBar")) { 852 if (w->parent()->inherits("QToolBar")) {
848 ((QToolButton*)w)->setAutoRaise (flatTBButtons); 853 ((QToolButton*)w)->setAutoRaise (flatTBButtons);
849 if ( flatTBButtons ) 854 if ( flatTBButtons )
850 w->setBackgroundOrigin(QWidget::ParentOrigin); 855 w->setBackgroundOrigin(QWidget::ParentOrigin);
851 } 856 }
852 w-> installEventFilter ( this ); 857 w-> installEventFilter ( this );
853 } 858 }
854 if(w-> inherits("QToolBarSeparator")&&w->parent()->inherits("QToolBar")) { 859 if(w-> inherits("QToolBarSeparator")&&w->parent()->inherits("QToolBar")) {
855 ((QFrame *) w)-> setFrameShape ( QFrame::NoFrame ); 860 ((QFrame *) w)-> setFrameShape ( QFrame::NoFrame );
856 } 861 }
857 if(w->ownPalette() && !w->inherits("QButton") && !w->inherits("QComboBox")){ 862 if(w->ownPalette() && !w->inherits("QButton") && !w->inherits("QComboBox")){
858 return; 863 return;
859 } 864 }
860 865
861 if(w->parent() && w->parent()->isWidgetType() && !((QWidget*)w->parent())-> 866 if(w->parent() && w->parent()->isWidgetType() && !((QWidget*)w->parent())->
862 palette().active().brush(QColorGroup::Background).pixmap()){ 867 palette().active().brush(QColorGroup::Background).pixmap()){
863 qWarning("No parent pixmap for child widget %s", w->className()); 868 owarn << "No parent pixmap for child widget " << w->className() << "" << oendl;
864 return; 869 return;
865 } 870 }
866 if(!isViewport && !isViewportChild && !w->testWFlags(WType_Popup) && 871 if(!isViewport && !isViewportChild && !w->testWFlags(WType_Popup) &&
867 !( !w-> inherits("QLineEdit") && w-> parent() && w-> parent()-> isWidgetType ( ) && w-> parent()-> inherits ( "QMultiLineEdit" ))) { 872 !( !w-> inherits("QLineEdit") && w-> parent() && w-> parent()-> isWidgetType ( ) && w-> parent()-> inherits ( "QMultiLineEdit" ))) {
868 if(w->backgroundMode() == QWidget::PaletteBackground || 873 if(w->backgroundMode() == QWidget::PaletteBackground ||
869 w->backgroundMode() == QWidget::PaletteButton){ 874 w->backgroundMode() == QWidget::PaletteButton){
870 w->setBackgroundMode(w->parentWidget()->backgroundMode( )/*QWidget::X11ParentRelative*/); 875 w->setBackgroundMode(w->parentWidget()->backgroundMode( )/*QWidget::X11ParentRelative*/);
871 w->setBackgroundOrigin(QWidget::ParentOrigin); 876 w->setBackgroundOrigin(QWidget::ParentOrigin);
872 // w->setBackgroundMode(QWidget::NoBackground); 877 // w->setBackgroundMode(QWidget::NoBackground);
873 } 878 }
874 } 879 }
875 if ( !w-> inherits("QFrame") || (((QFrame*) w)-> frameShape () == QFrame::NoFrame )) 880 if ( !w-> inherits("QFrame") || (((QFrame*) w)-> frameShape () == QFrame::NoFrame ))
876 w-> setBackgroundOrigin ( QWidget::ParentOrigin ); 881 w-> setBackgroundOrigin ( QWidget::ParentOrigin );
877 else if ( w-> inherits("QFrame") ) 882 else if ( w-> inherits("QFrame") )
878 w->setBackgroundOrigin ( QWidget::WidgetOrigin ); 883 w->setBackgroundOrigin ( QWidget::WidgetOrigin );
879 884
880 if ( w->parentWidget()->inherits ( "QWidgetStack" )) { 885 if ( w->parentWidget()->inherits ( "QWidgetStack" )) {
881 w->setBackgroundOrigin ( QWidget::WidgetOrigin ); 886 w->setBackgroundOrigin ( QWidget::WidgetOrigin );
882 } 887 }
883} 888}
884 889
885void LiquidStyle::unPolish(QWidget *w) 890void LiquidStyle::unPolish(QWidget *w)
886{ 891{
887 if(w->inherits("QMenuBar")){ 892 if(w->inherits("QMenuBar")){
888 ((QFrame *)w)->setLineWidth(1); 893 ((QFrame *)w)->setLineWidth(1);
889 w->setBackgroundMode(QWidget::PaletteBackground); 894 w->setBackgroundMode(QWidget::PaletteBackground);
890 return; 895 return;
891 } 896 }
892 897
893 if(w->inherits("QPopupMenu")) 898 if(w->inherits("QPopupMenu"))
894 w->setBackgroundMode(QWidget::PaletteButton); 899 w->setBackgroundMode(QWidget::PaletteButton);
895 else if(w-> testWFlags(Qt::WType_Popup) && 900 else if(w-> testWFlags(Qt::WType_Popup) &&
896 !w->inherits("QListBox") && 901 !w->inherits("QListBox") &&
897 ( qstrcmp ( w-> name(), "automatic what's this? widget" ) != 0 )) { 902 ( qstrcmp ( w-> name(), "automatic what's this? widget" ) != 0 )) {
898 w->removeEventFilter(menuHandler); 903 w->removeEventFilter(menuHandler);
899 } 904 }
900 905
901 if(w->isTopLevel()) 906 if(w->isTopLevel())
902 return; 907 return;
903 908
904 // for viewport children, don't just check for NoBackground.... 909 // for viewport children, don't just check for NoBackground....
905 bool isViewportChild = w->parent() && 910 bool isViewportChild = w->parent() &&
906 ((qstrcmp(w->parent()->name(), "qt_viewport") == 0) || 911 ((qstrcmp(w->parent()->name(), "qt_viewport") == 0) ||
907 (qstrcmp(w->parent()->name(), "qt_clipped_viewport") == 0)); 912 (qstrcmp(w->parent()->name(), "qt_clipped_viewport") == 0));
908 913
909 w->unsetPalette(); 914 w->unsetPalette();
910 if(w->backgroundMode() == QWidget::X11ParentRelative || isViewportChild){ 915 if(w->backgroundMode() == QWidget::X11ParentRelative || isViewportChild){
911 if(w->inherits("QPushButton")) 916 if(w->inherits("QPushButton"))
912 w->setBackgroundMode(QWidget::PaletteButton); 917 w->setBackgroundMode(QWidget::PaletteButton);
913 else 918 else
914 w->setBackgroundMode(QWidget::PaletteBackground); 919 w->setBackgroundMode(QWidget::PaletteBackground);
915 } 920 }
916 921
917 if(isViewportChild) 922 if(isViewportChild)
918 w->setAutoMask(false); 923 w->setAutoMask(false);
919 924
920/* 925/*
921 if(w->inherits("QPushButton") || w-> inherits("QComboBox")){ 926 if(w->inherits("QPushButton") || w-> inherits("QComboBox")){
922 w-> setBackgroundMode ( PaletteBackground ); 927 w-> setBackgroundMode ( PaletteBackground );
923 } 928 }
924*/ 929*/
925 if( w->inherits("QRadioButton") || w->inherits("QCheckBox") || w->inherits("QProgressBar")) { 930 if( w->inherits("QRadioButton") || w->inherits("QCheckBox") || w->inherits("QProgressBar")) {
926 w->removeEventFilter(this); 931 w->removeEventFilter(this);
927 } 932 }
928 if(w->inherits("QButton") || w->inherits("QComboBox")){ 933 if(w->inherits("QButton") || w->inherits("QComboBox")){
929 if(w->parent() && w->parent()->inherits("KHTMLPart")){ 934 if(w->parent() && w->parent()->inherits("KHTMLPart")){
930 w->setAutoMask(false); 935 w->setAutoMask(false);
931 } 936 }
932 } 937 }
933 if(w-> inherits("QToolButton")) { 938 if(w-> inherits("QToolButton")) {
934 w-> removeEventFilter ( this ); 939 w-> removeEventFilter ( this );
935 } 940 }
936 if(w->inherits("QToolBar")){ 941 if(w->inherits("QToolBar")){
937 w->removeEventFilter(this); 942 w->removeEventFilter(this);
938 w->setBackgroundMode(QWidget::PaletteBackground); 943 w->setBackgroundMode(QWidget::PaletteBackground);
939 return; 944 return;
940 } 945 }
941 if(w->inherits("QHeader")){ 946 if(w->inherits("QHeader")){
942 w->setMouseTracking(false); 947 w->setMouseTracking(false);
943 w->removeEventFilter(this); 948 w->removeEventFilter(this);
944 } 949 }
945} 950}
946 951
947void LiquidStyle::polish(QApplication *app) 952void LiquidStyle::polish(QApplication *app)
948{ 953{
949 954
950 QWindowsStyle::polish(app); 955 QWindowsStyle::polish(app);
951 menuAni = app->isEffectEnabled(UI_AnimateMenu); 956 menuAni = app->isEffectEnabled(UI_AnimateMenu);
952 menuFade = app->isEffectEnabled(UI_FadeMenu); 957 menuFade = app->isEffectEnabled(UI_FadeMenu);
953 if(menuAni) 958 if(menuAni)
954 app->setEffectEnabled(UI_AnimateMenu, false); 959 app->setEffectEnabled(UI_AnimateMenu, false);
955 if(menuFade) 960 if(menuFade)
956 app->setEffectEnabled(UI_FadeMenu, false); 961 app->setEffectEnabled(UI_FadeMenu, false);
957 962
958 qt_set_draw_menu_bar_impl((QDrawMenuBarItemImpl) &LiquidStyle::drawMenuBarItem); 963 qt_set_draw_menu_bar_impl((QDrawMenuBarItemImpl) &LiquidStyle::drawMenuBarItem);
959 964
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 @@
1TEMPLATE = lib 1TEMPLATE = lib
2CONFIG = qt plugin embedded warn_on 2CONFIG = qt plugin embedded warn_on
3SOURCES = liquid.cpp \ 3SOURCES = liquid.cpp \
4 effects.cpp \ 4 effects.cpp \
5 liquidset.cpp \ 5 liquidset.cpp \
6 plugin.cpp 6 plugin.cpp
7 7
8HEADERS = liquid.h \ 8HEADERS = liquid.h \
9 effects.h \ 9 effects.h \
10 liquidset.h \ 10 liquidset.h \
11 plugin.h 11 plugin.h
12 12
13LIBS += -lqpe -lqtaux2 13LIBS += -lqpe -lqtaux2 -lopiecore2
14INCLUDEPATH += $(OPIEDIR)/include 14INCLUDEPATH += $(OPIEDIR)/include
15DESTDIR = $(OPIEDIR)/plugins/styles 15DESTDIR = $(OPIEDIR)/plugins/styles
16TARGET = liquid 16TARGET = liquid
17VERSION = 1.0.0 17VERSION = 1.0.1
18 18
19include ( $(OPIEDIR)/include.pro ) 19include ( $(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 @@
1/* This file is part of the KDE libraries 1/* This file is part of the KDE libraries
2 Copyright (C) 1999 Daniel M. Duley <mosfet@kde.org> 2 Copyright (C) 1999 Daniel M. Duley <mosfet@kde.org>
3 3
4 This library is free software; you can redistribute it and/or 4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public 5 modify it under the terms of the GNU Library General Public
6 License version 2 as published by the Free Software Foundation. 6 License version 2 as published by the Free Software Foundation.
7 7
8 This library is distributed in the hope that it will be useful, 8 This library is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of 9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 Library General Public License for more details. 11 Library General Public License for more details.
12 12
13 You should have received a copy of the GNU Library General Public License 13 You should have received a copy of the GNU Library General Public License
14 along with this library; see the file COPYING.LIB. If not, write to 14 along with this library; see the file COPYING.LIB. If not, write to
15 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 15 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 Boston, MA 02111-1307, USA. 16 Boston, MA 02111-1307, USA.
17*/ 17*/
18
18#include "othemebase.h" 19#include "othemebase.h"
19#include "ogfxeffect.h" 20#include "ogfxeffect.h"
21
22/* OPIE */
23#include <opie2/odebug.h>
20#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
21//#include <kdebug.h> 25#include <qpe/config.h>
22//#include <klocale.h> 26using namespace Opie::Core;
23#include <qpe/config.h> 27
24//#include <kglobal.h> 28/* QT */
25//#include <kglobalsettings.h>
26//#include <kstddirs.h>
27#include <qfile.h> 29#include <qfile.h>
28#include <qtextstream.h> 30#include <qtextstream.h>
29#include <qdir.h> 31#include <qdir.h>
30#include <qpainter.h> 32#include <qpainter.h>
31#include <qbitmap.h> 33#include <qbitmap.h>
32#include <stdlib.h>
33#include <qstringlist.h> 34#include <qstringlist.h>
34 35
35#include <stdio.h> 36/* STD */
37#include <stdlib.h>
36 38
37 39
38template class QIntCache<OThemePixmap> 40template class QIntCache<OThemePixmap>
39; 41;
40 42
41static const char *widgetEntries[] = 43static const char *widgetEntries[] =
42 { // unsunken widgets (see header) 44 { // unsunken widgets (see header)
43 "PushButton", "ComboBox", "HSBarSlider", "VSBarSlider", "Bevel", "ToolButton", 45 "PushButton", "ComboBox", "HSBarSlider", "VSBarSlider", "Bevel", "ToolButton",
44 "ScrollButton", "HScrollDeco", "VScrollDeco", "ComboDeco", "MenuItem", "Tab", 46 "ScrollButton", "HScrollDeco", "VScrollDeco", "ComboDeco", "MenuItem", "Tab",
45 "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", 47 "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight",
46 // sunken widgets 48 // sunken widgets
47 "PushButtonDown", "ComboBoxDown", "HSBarSliderDown", "VSBarSliderDown", 49 "PushButtonDown", "ComboBoxDown", "HSBarSliderDown", "VSBarSliderDown",
48 "BevelDown", "ToolButtonDown", "ScrollButtonDown", "HScrollDecoDown", 50 "BevelDown", "ToolButtonDown", "ScrollButtonDown", "HScrollDecoDown",
49 "VScrollDecoDown", "ComboDecoDown", "MenuItemDown", "TabDown", "SunkenArrowUp", 51 "VScrollDecoDown", "ComboDecoDown", "MenuItemDown", "TabDown", "SunkenArrowUp",
50 "SunkenArrowDown", "SunkenArrowLeft", "SunkenArrowRight", 52 "SunkenArrowDown", "SunkenArrowLeft", "SunkenArrowRight",
51 // everything else 53 // everything else
52 "HScrollGroove", "VScrollGroove", "Slider", "SliderGroove", "CheckBoxDown", 54 "HScrollGroove", "VScrollGroove", "Slider", "SliderGroove", "CheckBoxDown",
53 "CheckBox", "RadioDown", "Radio", "HBarHandle", "VBarHandle", 55 "CheckBox", "RadioDown", "Radio", "HBarHandle", "VBarHandle",
54 "ToolBar", "Splitter", "CheckMark", "MenuBar", "DisableArrowUp", 56 "ToolBar", "Splitter", "CheckMark", "MenuBar", "DisableArrowUp",
55 "DisableArrowDown", "DisableArrowLeft", "DisableArrowRight", "ProgressBar", 57 "DisableArrowDown", "DisableArrowLeft", "DisableArrowRight", "ProgressBar",
56 "ProgressBackground", "MenuBarItem", "Background" 58 "ProgressBackground", "MenuBarItem", "Background"
57 }; 59 };
58 60
59#define INHERIT_ITEMS 16 61#define INHERIT_ITEMS 16
60 62
61 63
62// This is used to encode the keys. I used to use masks but I think this 64// This is used to encode the keys. I used to use masks but I think this
63// bitfield is nicer :) I don't know why C++ coders don't use these more.. 65// bitfield is nicer :) I don't know why C++ coders don't use these more..
64// (mosfet) 66// (mosfet)
65struct kthemeKeyData 67struct kthemeKeyData
66{ 68{
67unsigned int id : 69unsigned int id :
68 6; 70 6;
69unsigned int width : 71unsigned int width :
70 12; 72 12;
71unsigned int height : 73unsigned int height :
72 12; 74 12;
73unsigned int border : 75unsigned int border :
74 1; 76 1;
75unsigned int mask : 77unsigned int mask :
76 1; 78 1;
77}; 79};
78 80
79union kthemeKey{ 81union kthemeKey{
80 kthemeKeyData data; 82 kthemeKeyData data;
81 unsigned int cacheKey; 83 unsigned int cacheKey;
82}; 84};
83 85
84 86
85void OThemeBase::generateBorderPix( int i ) 87void OThemeBase::generateBorderPix( int i )
86{ 88{
87 // separate pixmap into separate components 89 // separate pixmap into separate components
88 if ( pbPixmaps[ i ] ) { 90 if ( pbPixmaps[ i ] ) {
89 // evidently I have to do masks manually... 91 // evidently I have to do masks manually...
90 const QBitmap * srcMask = pbPixmaps[ i ] ->mask(); 92 const QBitmap * srcMask = pbPixmaps[ i ] ->mask();
91 QBitmap destMask( pbWidth[ i ], pbWidth[ i ] ); 93 QBitmap destMask( pbWidth[ i ], pbWidth[ i ] );
92 QPixmap tmp( pbWidth[ i ], pbWidth[ i ] ); 94 QPixmap tmp( pbWidth[ i ], pbWidth[ i ] );
93 95
94 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], 0, 0, pbWidth[ i ], pbWidth[ i ], 96 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], 0, 0, pbWidth[ i ], pbWidth[ i ],
95 Qt::CopyROP, false ); 97 Qt::CopyROP, false );
96 if ( srcMask ) { 98 if ( srcMask ) {
97 bitBlt( &destMask, 0, 0, srcMask, 0, 0, pbWidth[ i ], pbWidth[ i ], 99 bitBlt( &destMask, 0, 0, srcMask, 0, 0, pbWidth[ i ], pbWidth[ i ],
98 Qt::CopyROP, false ); 100 Qt::CopyROP, false );
99 tmp.setMask( destMask ); 101 tmp.setMask( destMask );
100 } 102 }
101 pbPixmaps[ i ] ->setBorder( OThemePixmap::TopLeft, tmp ); 103 pbPixmaps[ i ] ->setBorder( OThemePixmap::TopLeft, tmp );
102 104
103 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbPixmaps[ i ] ->width() - pbWidth[ i ], 0, 105 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbPixmaps[ i ] ->width() - pbWidth[ i ], 0,
104 pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false ); 106 pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false );
105 if ( srcMask ) { 107 if ( srcMask ) {
106 bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ], 108 bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ],
107 0, pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false ); 109 0, pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false );
108 tmp.setMask( destMask ); 110 tmp.setMask( destMask );
109 } 111 }
110 pbPixmaps[ i ] ->setBorder( OThemePixmap::TopRight, tmp ); 112 pbPixmaps[ i ] ->setBorder( OThemePixmap::TopRight, tmp );
111 113
112 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], 0, pbPixmaps[ i ] ->height() - pbWidth[ i ], 114 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], 0, pbPixmaps[ i ] ->height() - pbWidth[ i ],
113 pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false ); 115 pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false );
114 if ( srcMask ) { 116 if ( srcMask ) {
115 bitBlt( &destMask, 0, 0, srcMask, 0, pbPixmaps[ i ] ->height() - pbWidth[ i ], 117 bitBlt( &destMask, 0, 0, srcMask, 0, pbPixmaps[ i ] ->height() - pbWidth[ i ],
116 pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false ); 118 pbWidth[ i ], pbWidth[ i ], Qt::CopyROP, false );
117 tmp.setMask( destMask ); 119 tmp.setMask( destMask );
118 } 120 }
119 pbPixmaps[ i ] ->setBorder( OThemePixmap::BottomLeft, tmp ); 121 pbPixmaps[ i ] ->setBorder( OThemePixmap::BottomLeft, tmp );
120 122
121 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbPixmaps[ i ] ->width() - pbWidth[ i ], 123 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbPixmaps[ i ] ->width() - pbWidth[ i ],
122 pbPixmaps[ i ] ->height() - pbWidth[ i ], pbWidth[ i ], pbWidth[ i ], 124 pbPixmaps[ i ] ->height() - pbWidth[ i ], pbWidth[ i ], pbWidth[ i ],
123 Qt::CopyROP, false ); 125 Qt::CopyROP, false );
124 if ( srcMask ) { 126 if ( srcMask ) {
125 bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ], 127 bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ],
126 pbPixmaps[ i ] ->height() - pbWidth[ i ], pbWidth[ i ], pbWidth[ i ], 128 pbPixmaps[ i ] ->height() - pbWidth[ i ], pbWidth[ i ], pbWidth[ i ],
127 Qt::CopyROP, false ); 129 Qt::CopyROP, false );
128 tmp.setMask( destMask ); 130 tmp.setMask( destMask );
129 } 131 }
130 pbPixmaps[ i ] ->setBorder( OThemePixmap::BottomRight, tmp ); 132 pbPixmaps[ i ] ->setBorder( OThemePixmap::BottomRight, tmp );
131 133
@@ -169,338 +171,331 @@ void OThemeBase::generateBorderPix( int i )
169 Qt::CopyROP, false ); 171 Qt::CopyROP, false );
170 if ( srcMask ) { 172 if ( srcMask ) {
171 bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ], 173 bitBlt( &destMask, 0, 0, srcMask, pbPixmaps[ i ] ->width() - pbWidth[ i ],
172 pbWidth[ i ], pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2, 174 pbWidth[ i ], pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2,
173 Qt::CopyROP, false ); 175 Qt::CopyROP, false );
174 tmp.setMask( destMask ); 176 tmp.setMask( destMask );
175 } 177 }
176 pbPixmaps[ i ] ->setBorder( OThemePixmap::Right, tmp ); 178 pbPixmaps[ i ] ->setBorder( OThemePixmap::Right, tmp );
177 } 179 }
178 else 180 else
179 qDebug ( "OThemeBase: Tried making border from empty pixmap" ); 181 qDebug ( "OThemeBase: Tried making border from empty pixmap" );
180} 182}
181 183
182 184
183void OThemeBase::copyWidgetConfig( int sourceID, int destID, QString *pixnames, 185void OThemeBase::copyWidgetConfig( int sourceID, int destID, QString *pixnames,
184 QString *brdnames ) 186 QString *brdnames )
185{ 187{
186 scaleHints[ destID ] = scaleHints[ sourceID ]; 188 scaleHints[ destID ] = scaleHints[ sourceID ];
187 gradients[ destID ] = gradients[ sourceID ]; 189 gradients[ destID ] = gradients[ sourceID ];
188 blends[ destID ] = blends[ sourceID ]; 190 blends[ destID ] = blends[ sourceID ];
189 bContrasts[ destID ] = bContrasts[ sourceID ]; 191 bContrasts[ destID ] = bContrasts[ sourceID ];
190 borders[ destID ] = borders[ sourceID ]; 192 borders[ destID ] = borders[ sourceID ];
191 highlights[ destID ] = highlights[ sourceID ]; 193 highlights[ destID ] = highlights[ sourceID ];
192 194
193 if ( grLowColors[ sourceID ] ) 195 if ( grLowColors[ sourceID ] )
194 grLowColors[ destID ] = new QColor( *grLowColors[ sourceID ] ); 196 grLowColors[ destID ] = new QColor( *grLowColors[ sourceID ] );
195 else 197 else
196 grLowColors[ destID ] = NULL; 198 grLowColors[ destID ] = NULL;
197 199
198 if ( grHighColors[ sourceID ] ) 200 if ( grHighColors[ sourceID ] )
199 grHighColors[ destID ] = new QColor( *grHighColors[ sourceID ] ); 201 grHighColors[ destID ] = new QColor( *grHighColors[ sourceID ] );
200 else 202 else
201 grHighColors[ destID ] = NULL; 203 grHighColors[ destID ] = NULL;
202 204
203 if ( colors[ sourceID ] ) 205 if ( colors[ sourceID ] )
204 colors[ destID ] = new QColorGroup( *colors[ sourceID ] ); 206 colors[ destID ] = new QColorGroup( *colors[ sourceID ] );
205 else 207 else
206 colors[ destID ] = NULL; 208 colors[ destID ] = NULL;
207 209
208 // pixmap 210 // pixmap
209 pixnames[ destID ] = pixnames[ sourceID ]; 211 pixnames[ destID ] = pixnames[ sourceID ];
210 duplicate[ destID ] = false; 212 duplicate[ destID ] = false;
211 pixmaps[ destID ] = NULL; 213 pixmaps[ destID ] = NULL;
212 images[ destID ] = NULL; 214 images[ destID ] = NULL;
213 if ( !pixnames[ destID ].isEmpty() ) { 215 if ( !pixnames[ destID ].isEmpty() ) {
214 if ( scaleHints[ sourceID ] == TileScale && blends[ sourceID ] == 0.0 ) { 216 if ( scaleHints[ sourceID ] == TileScale && blends[ sourceID ] == 0.0 ) {
215 pixmaps[ destID ] = pixmaps[ sourceID ]; 217 pixmaps[ destID ] = pixmaps[ sourceID ];
216 duplicate[ destID ] = true; 218 duplicate[ destID ] = true;
217 } 219 }
218 if ( !duplicate[ destID ] ) { 220 if ( !duplicate[ destID ] ) {
219 pixmaps[ destID ] = loadPixmap( pixnames[ destID ] ); 221 pixmaps[ destID ] = loadPixmap( pixnames[ destID ] );
220 if ( scaleHints[ destID ] == TileScale && blends[ destID ] == 0.0 ) 222 if ( scaleHints[ destID ] == TileScale && blends[ destID ] == 0.0 )
221 images[ destID ] = NULL; 223 images[ destID ] = NULL;
222 else 224 else
223 images[ destID ] = loadImage( pixnames[ destID ] ); 225 images[ destID ] = loadImage( pixnames[ destID ] );
224 } 226 }
225 } 227 }
226 228
227 // border pixmap 229 // border pixmap
228 pbDuplicate[ destID ] = false; 230 pbDuplicate[ destID ] = false;
229 pbPixmaps[ destID ] = NULL; 231 pbPixmaps[ destID ] = NULL;
230 pbWidth[ destID ] = pbWidth[ sourceID ]; 232 pbWidth[ destID ] = pbWidth[ sourceID ];
231 brdnames[ destID ] = brdnames[ sourceID ]; 233 brdnames[ destID ] = brdnames[ sourceID ];
232 if ( !brdnames[ destID ].isEmpty() ) { 234 if ( !brdnames[ destID ].isEmpty() ) {
233 pbPixmaps[ destID ] = pbPixmaps[ sourceID ]; 235 pbPixmaps[ destID ] = pbPixmaps[ sourceID ];
234 pbDuplicate[ destID ] = true; 236 pbDuplicate[ destID ] = true;
235 } 237 }
236 238
237 if ( sourceID == ActiveTab && destID == InactiveTab ) 239 if ( sourceID == ActiveTab && destID == InactiveTab )
238 aTabLine = iTabLine; 240 aTabLine = iTabLine;
239 else if ( sourceID == InactiveTab && destID == ActiveTab ) 241 else if ( sourceID == InactiveTab && destID == ActiveTab )
240 iTabLine = aTabLine; 242 iTabLine = aTabLine;
241} 243}
242 244
243void OThemeBase::readConfig( Qt::GUIStyle /*style*/ ) 245void OThemeBase::readConfig( Qt::GUIStyle /*style*/ )
244{ 246{
245#define PREBLEND_ITEMS 12 247#define PREBLEND_ITEMS 12
246 static WidgetType preBlend[] = {Slider, IndicatorOn, IndicatorOff, 248 static WidgetType preBlend[] = {Slider, IndicatorOn, IndicatorOff,
247 ExIndicatorOn, ExIndicatorOff, HScrollDeco, VScrollDeco, HScrollDecoDown, 249 ExIndicatorOn, ExIndicatorOff, HScrollDeco, VScrollDeco, HScrollDecoDown,
248 VScrollDecoDown, ComboDeco, ComboDecoDown, CheckMark}; 250 VScrollDecoDown, ComboDeco, ComboDecoDown, CheckMark};
249 251
250 int i; 252 int i;
251 QString tmpStr; 253 QString tmpStr;
252 QString copyfrom[ WIDGETS ]; 254 QString copyfrom[ WIDGETS ];
253 QString pixnames[ WIDGETS ]; // used for duplicate check 255 QString pixnames[ WIDGETS ]; // used for duplicate check
254 QString brdnames[ WIDGETS ]; 256 QString brdnames[ WIDGETS ];
255 bool loaded[ WIDGETS ]; // used for preloading for CopyWidget 257 bool loaded[ WIDGETS ]; // used for preloading for CopyWidget
256 258
257 if ( configFileName.isEmpty() ) { 259 if ( configFileName.isEmpty() ) {
258 Config cfg ( "qpe" ); 260 Config cfg ( "qpe" );
259 cfg. setGroup ( "Appearance" ); 261 cfg. setGroup ( "Appearance" );
260 262
261 configFileName = cfg. readEntry ( "Theme", "default" ); 263 configFileName = cfg. readEntry ( "Theme", "default" );
262 } 264 }
263 Config config( configFilePath + "/themes/" + configFileName + ".themerc" , Config::File ); 265 Config config( configFilePath + "/themes/" + configFileName + ".themerc" , Config::File );
264 266
265 //printf ( "Opened config file: %s\n", ( configFilePath + "/themes/" + configFileName + ".themerc" ). ascii());
266
267 // Are we initalized? 267 // Are we initalized?
268 applyMiscResourceGroup( &config ); 268 applyMiscResourceGroup( &config );
269 for ( i = 0; i < INHERIT_ITEMS; ++i ) { 269 for ( i = 0; i < INHERIT_ITEMS; ++i ) {
270 applyResourceGroup( &config, i, copyfrom, pixnames, brdnames ); 270 applyResourceGroup( &config, i, copyfrom, pixnames, brdnames );
271 // printf ( "%d [%s]: copy=%s, pix=%s, brd=%s\n", i, widgetEntries [i], copyfrom [i].latin1(), pixnames[i].latin1(),brdnames[i].latin1() );
272 } 271 }
273 for ( ; i < INHERIT_ITEMS*2; ++i ) { 272 for ( ; i < INHERIT_ITEMS*2; ++i ) {
274 if ( config.hasGroup( QString( widgetEntries[ i ] ) ) ) { 273 if ( config.hasGroup( QString( widgetEntries[ i ] ) ) ) {
275 applyResourceGroup( &config, i, copyfrom, pixnames, brdnames ); 274 applyResourceGroup( &config, i, copyfrom, pixnames, brdnames );
276 // printf ( "%d [%s]: copy=%s, pix=%s, brd=%s\n", i, widgetEntries [i], copyfrom [i].latin1(), pixnames[i].latin1(),brdnames[i].latin1() );
277 } 275 }
278 else { 276 else {
279 copyfrom [ i ] = widgetEntries[ i - INHERIT_ITEMS ]; 277 copyfrom [ i ] = widgetEntries[ i - INHERIT_ITEMS ];
280 // printf ( "%d [%s]: copy=%s\n", i, widgetEntries [i], copyfrom [i].latin1());
281 } 278 }
282 } 279 }
283 for ( ; i < WIDGETS; ++i ) { 280 for ( ; i < WIDGETS; ++i ) {
284 applyResourceGroup( &config, i, copyfrom, pixnames, brdnames ); 281 applyResourceGroup( &config, i, copyfrom, pixnames, brdnames );
285 // printf ( "%d [%s]: copy=%s, pix=%s, brd=%s\n", i, widgetEntries [i], copyfrom [i].latin1(), pixnames[i].latin1(),brdnames[i].latin1() );
286 } 282 }
287 283
288 // initalize defaults that may not be read 284 // initalize defaults that may not be read
289 for ( i = 0; i < WIDGETS; ++i ) 285 for ( i = 0; i < WIDGETS; ++i )
290 loaded[ i ] = false; 286 loaded[ i ] = false;
291 btnXShift = btnYShift = focus3DOffset = 0; 287 btnXShift = btnYShift = focus3DOffset = 0;
292 aTabLine = iTabLine = true; 288 aTabLine = iTabLine = true;
293 roundedButton = roundedCombo = roundedSlider = focus3D = false; 289 roundedButton = roundedCombo = roundedSlider = focus3D = false;
294 splitterWidth = 10; 290 splitterWidth = 10;
295 291
296 for ( i = 0; i < WIDGETS; ++i ) { 292 for ( i = 0; i < WIDGETS; ++i ) {
297 readResourceGroup( i, copyfrom, pixnames, brdnames, loaded ); 293 readResourceGroup( i, copyfrom, pixnames, brdnames, loaded );
298 // 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)" ));
299 } 294 }
300 295
301 // misc items 296 // misc items
302 readMiscResourceGroup(); 297 readMiscResourceGroup();
303 298
304 // Handle preblend items 299 // Handle preblend items
305 for ( i = 0; i < PREBLEND_ITEMS; ++i ) { 300 for ( i = 0; i < PREBLEND_ITEMS; ++i ) {
306 if ( pixmaps[ preBlend[ i ] ] != NULL && blends[ preBlend[ i ] ] != 0.0 ) 301 if ( pixmaps[ preBlend[ i ] ] != NULL && blends[ preBlend[ i ] ] != 0.0 )
307 blend( preBlend[ i ] ); 302 blend( preBlend[ i ] );
308 } 303 }
309} 304}
310 305
311OThemeBase::OThemeBase( const QString & configFile ) 306OThemeBase::OThemeBase( const QString & configFile )
312 : QWindowsStyle() 307 : QWindowsStyle()
313{ 308{
314 configFilePath = QPEApplication::qpeDir ( ) + "/plugins/styles/"; 309 configFilePath = QPEApplication::qpeDir ( ) + "/plugins/styles/";
315 configFileName = configFile; 310 configFileName = configFile;
316 311
317 readConfig( Qt::WindowsStyle ); 312 readConfig( Qt::WindowsStyle );
318 cache = new OThemeCache( cacheSize ); 313 cache = new OThemeCache( cacheSize );
319} 314}
320 315
321void OThemeBase::applyConfigFile( const QString &/*file*/ ) 316void OThemeBase::applyConfigFile( const QString &/*file*/ )
322{ 317{
323#if 0 318#if 0
324 // handle std color scheme 319 // handle std color scheme
325 Config inConfig( file, Config::File ); 320 Config inConfig( file, Config::File );
326 Config globalConfig ( "qpe" ); 321 Config globalConfig ( "qpe" );
327 322
328 globalConfig. setGroup ( "Apperance" ); 323 globalConfig. setGroup ( "Apperance" );
329 inConfig. setGroup( "General" ); 324 inConfig. setGroup( "General" );
330 325
331 if ( inConfig.hasKey( "foreground" ) ) 326 if ( inConfig.hasKey( "foreground" ) )
332 globalConfig.writeEntry( "Text", inConfig.readEntry( "foreground", " " ) ); 327 globalConfig.writeEntry( "Text", inConfig.readEntry( "foreground", " " ) );
333 if ( inConfig.hasKey( "background" ) ) 328 if ( inConfig.hasKey( "background" ) )
334 globalConfig.writeEntry( "Background", inConfig.readEntry( "background", " " ) ); 329 globalConfig.writeEntry( "Background", inConfig.readEntry( "background", " " ) );
335 if ( inConfig.hasKey( "selectForeground" ) ) 330 if ( inConfig.hasKey( "selectForeground" ) )
336 globalConfig.writeEntry( "HighlightedText", inConfig.readEntry( "selectForeground", " " ) ); 331 globalConfig.writeEntry( "HighlightedText", inConfig.readEntry( "selectForeground", " " ) );
337 if ( inConfig.hasKey( "selectBackground" ) ) 332 if ( inConfig.hasKey( "selectBackground" ) )
338 globalConfig.writeEntry( "Highlight", inConfig.readEntry( "selectBackground", " " ) ); 333 globalConfig.writeEntry( "Highlight", inConfig.readEntry( "selectBackground", " " ) );
339 if ( inConfig.hasKey( "windowForeground" ) ) 334 if ( inConfig.hasKey( "windowForeground" ) )
340 globalConfig.writeEntry( "Text", inConfig.readEntry( "windowForeground", " " ) ); 335 globalConfig.writeEntry( "Text", inConfig.readEntry( "windowForeground", " " ) );
341 if ( inConfig.hasKey( "windowBackground" ) ) 336 if ( inConfig.hasKey( "windowBackground" ) )
342 globalConfig.writeEntry( "Base", inConfig.readEntry( "windowBackground", " " ) ); 337 globalConfig.writeEntry( "Base", inConfig.readEntry( "windowBackground", " " ) );
343 338
344 // Keep track of the current theme so that we can select the right one 339 // Keep track of the current theme so that we can select the right one
345 // in the KControl module. 340 // in the KControl module.
346 globalConfig.writeEntry ( "CurrentTheme", file ); 341 globalConfig.writeEntry ( "CurrentTheme", file );
347 342
348 globalConfig.write(); 343 globalConfig.write();
349#endif 344#endif
350} 345}
351 346
352OThemeBase::~OThemeBase() 347OThemeBase::~OThemeBase()
353{ 348{
354 int i; 349 int i;
355 for ( i = 0; i < WIDGETS; ++i ) { 350 for ( i = 0; i < WIDGETS; ++i ) {
356 if ( !duplicate[ i ] ) { 351 if ( !duplicate[ i ] ) {
357 if ( images[ i ] ) 352 if ( images[ i ] )
358 delete images[ i ]; 353 delete images[ i ];
359 if ( pixmaps[ i ] ) 354 if ( pixmaps[ i ] )
360 delete pixmaps[ i ]; 355 delete pixmaps[ i ];
361 } 356 }
362 if ( !pbDuplicate[ i ] && pbPixmaps[ i ] ) 357 if ( !pbDuplicate[ i ] && pbPixmaps[ i ] )
363 delete pbPixmaps[ i ]; 358 delete pbPixmaps[ i ];
364 if ( colors[ i ] ) 359 if ( colors[ i ] )
365 delete( colors[ i ] ); 360 delete( colors[ i ] );
366 if ( grLowColors[ i ] ) 361 if ( grLowColors[ i ] )
367 delete( grLowColors[ i ] ); 362 delete( grLowColors[ i ] );
368 if ( grHighColors[ i ] ) 363 if ( grHighColors[ i ] )
369 delete( grHighColors[ i ] ); 364 delete( grHighColors[ i ] );
370 } 365 }
371 delete cache; 366 delete cache;
372} 367}
373 368
374QImage* OThemeBase::loadImage( QString &name ) 369QImage* OThemeBase::loadImage( QString &name )
375{ 370{
376 QImage * image = new QImage; 371 QImage * image = new QImage;
377 QString path = configFilePath + "/pixmaps/" + name; 372 QString path = configFilePath + "/pixmaps/" + name;
378 image->load( path ); 373 image->load( path );
379 if ( !image->isNull() ) 374 if ( !image->isNull() )
380 return ( image ); 375 return ( image );
381 qDebug ( "OThemeBase: Unable to load image %s\n", name.ascii ( ) ); 376 qDebug ( "OThemeBase: Unable to load image %s\n", name.ascii ( ) );
382 delete image; 377 delete image;
383 return ( NULL ); 378 return ( NULL );
384} 379}
385 380
386OThemePixmap* OThemeBase::loadPixmap( QString &name ) 381OThemePixmap* OThemeBase::loadPixmap( QString &name )
387{ 382{
388 OThemePixmap * pixmap = new OThemePixmap( false ); 383 OThemePixmap * pixmap = new OThemePixmap( false );
389 QString path = configFilePath + "/pixmaps/" + name; 384 QString path = configFilePath + "/pixmaps/" + name;
390 pixmap->load( path ); 385 pixmap->load( path );
391 if ( !pixmap->isNull() ) 386 if ( !pixmap->isNull() )
392 return pixmap; 387 return pixmap;
393 qDebug ( "OThemeBase: Unable to load pixmap %s\n", name.ascii() ); 388 qDebug ( "OThemeBase: Unable to load pixmap %s\n", name.ascii() );
394 delete pixmap; 389 delete pixmap;
395 return ( NULL ); 390 return ( NULL );
396} 391}
397 392
398OThemePixmap* OThemeBase::scale( int w, int h, WidgetType widget ) 393OThemePixmap* OThemeBase::scale( int w, int h, WidgetType widget )
399{ 394{
400 if ( scaleHints[ widget ] == FullScale ) { 395 if ( scaleHints[ widget ] == FullScale ) {
401 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w || 396 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w ||
402 pixmaps[ widget ] ->height() != h ) { 397 pixmaps[ widget ] ->height() != h ) {
403 OThemePixmap * cachePix = cache->pixmap( w, h, widget ); 398 OThemePixmap * cachePix = cache->pixmap( w, h, widget );
404 if ( cachePix ) { 399 if ( cachePix ) {
405 cachePix = new OThemePixmap( *cachePix ); 400 cachePix = new OThemePixmap( *cachePix );
406 if ( pixmaps[ widget ] ) 401 if ( pixmaps[ widget ] )
407 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, 402 cache->insert( pixmaps[ widget ], OThemeCache::FullScale,
408 widget ); 403 widget );
409 else 404 else
410 qDebug( "We would have inserted a null pixmap!\n" ); 405 odebug << "We would have inserted a null pixmap!\n" << oendl;
411 pixmaps[ widget ] = cachePix; 406 pixmaps[ widget ] = cachePix;
412 } 407 }
413 else { 408 else {
414 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget ); 409 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget );
415 QImage tmpImg = images[ widget ] ->smoothScale( w, h ); 410 QImage tmpImg = images[ widget ] ->smoothScale( w, h );
416 pixmaps[ widget ] = new OThemePixmap; 411 pixmaps[ widget ] = new OThemePixmap;
417 pixmaps[ widget ] ->convertFromImage( tmpImg ); 412 pixmaps[ widget ] ->convertFromImage( tmpImg );
418 if ( blends[ widget ] != 0.0 ) 413 if ( blends[ widget ] != 0.0 )
419 blend( widget ); 414 blend( widget );
420 } 415 }
421 } 416 }
422 } 417 }
423 else if ( scaleHints[ widget ] == HorizontalScale ) { 418 else if ( scaleHints[ widget ] == HorizontalScale ) {
424 if ( pixmaps[ widget ] ->width() != w ) { 419 if ( pixmaps[ widget ] ->width() != w ) {
425 OThemePixmap * cachePix = cache->horizontalPixmap( w, widget ); 420 OThemePixmap * cachePix = cache->horizontalPixmap( w, widget );
426 if ( cachePix ) { 421 if ( cachePix ) {
427 cachePix = new OThemePixmap( *cachePix ); 422 cachePix = new OThemePixmap( *cachePix );
428 if ( pixmaps[ widget ] ) 423 if ( pixmaps[ widget ] )
429 cache->insert( pixmaps[ widget ], OThemeCache::HorizontalScale, widget ); 424 cache->insert( pixmaps[ widget ], OThemeCache::HorizontalScale, widget );
430 else 425 else
431 qDebug ( "We would have inserted a null pixmap!\n" ); 426 qDebug ( "We would have inserted a null pixmap!\n" );
432 pixmaps[ widget ] = cachePix; 427 pixmaps[ widget ] = cachePix;
433 } 428 }
434 else { 429 else {
435 cache->insert( pixmaps[ widget ], OThemeCache::HorizontalScale, widget ); 430 cache->insert( pixmaps[ widget ], OThemeCache::HorizontalScale, widget );
436 QImage tmpImg = images[ widget ] -> 431 QImage tmpImg = images[ widget ] ->
437 smoothScale( w, images[ widget ] ->height() ); 432 smoothScale( w, images[ widget ] ->height() );
438 pixmaps[ widget ] = new OThemePixmap; 433 pixmaps[ widget ] = new OThemePixmap;
439 pixmaps[ widget ] ->convertFromImage( tmpImg ); 434 pixmaps[ widget ] ->convertFromImage( tmpImg );
440 if ( blends[ widget ] != 0.0 ) 435 if ( blends[ widget ] != 0.0 )
441 blend( widget ); 436 blend( widget );
442 } 437 }
443 } 438 }
444 } 439 }
445 else if ( scaleHints[ widget ] == VerticalScale ) { 440 else if ( scaleHints[ widget ] == VerticalScale ) {
446 if ( pixmaps[ widget ] ->height() != h ) { 441 if ( pixmaps[ widget ] ->height() != h ) {
447 OThemePixmap * cachePix = cache->verticalPixmap( w, widget ); 442 OThemePixmap * cachePix = cache->verticalPixmap( w, widget );
448 if ( cachePix ) { 443 if ( cachePix ) {
449 cachePix = new OThemePixmap( *cachePix ); 444 cachePix = new OThemePixmap( *cachePix );
450 if ( pixmaps[ widget ] ) 445 if ( pixmaps[ widget ] )
451 cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale, widget ); 446 cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale, widget );
452 else 447 else
453 qDebug ( "We would have inserted a null pixmap!\n" ); 448 qDebug ( "We would have inserted a null pixmap!\n" );
454 pixmaps[ widget ] = cachePix; 449 pixmaps[ widget ] = cachePix;
455 } 450 }
456 else { 451 else {
457 cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale, widget ); 452 cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale, widget );
458 QImage tmpImg = 453 QImage tmpImg =
459 images[ widget ] ->smoothScale( images[ widget ] ->width(), h ); 454 images[ widget ] ->smoothScale( images[ widget ] ->width(), h );
460 pixmaps[ widget ] = new OThemePixmap; 455 pixmaps[ widget ] = new OThemePixmap;
461 pixmaps[ widget ] ->convertFromImage( tmpImg ); 456 pixmaps[ widget ] ->convertFromImage( tmpImg );
462 if ( blends[ widget ] != 0.0 ) 457 if ( blends[ widget ] != 0.0 )
463 blend( widget ); 458 blend( widget );
464 } 459 }
465 } 460 }
466 } 461 }
467 // If blended tile here so the blend is scaled properly 462 // If blended tile here so the blend is scaled properly
468 else if ( scaleHints[ widget ] == TileScale && blends[ widget ] != 0.0 ) { 463 else if ( scaleHints[ widget ] == TileScale && blends[ widget ] != 0.0 ) {
469 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w || 464 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w ||
470 pixmaps[ widget ] ->height() != h ) { 465 pixmaps[ widget ] ->height() != h ) {
471 OThemePixmap * cachePix = cache->pixmap( w, h, widget ); 466 OThemePixmap * cachePix = cache->pixmap( w, h, widget );
472 if ( cachePix ) { 467 if ( cachePix ) {
473 cachePix = new OThemePixmap( *cachePix ); 468 cachePix = new OThemePixmap( *cachePix );
474 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget ); 469 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget );
475 pixmaps[ widget ] = cachePix; 470 pixmaps[ widget ] = cachePix;
476 } 471 }
477 else { 472 else {
478 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget ); 473 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, widget );
479 QPixmap tile; 474 QPixmap tile;
480 tile.convertFromImage( *images[ widget ] ); 475 tile.convertFromImage( *images[ widget ] );
481 pixmaps[ widget ] = new OThemePixmap; 476 pixmaps[ widget ] = new OThemePixmap;
482 pixmaps[ widget ] ->resize( w, h ); 477 pixmaps[ widget ] ->resize( w, h );
483 QPainter p( pixmaps[ widget ] ); 478 QPainter p( pixmaps[ widget ] );
484 p.drawTiledPixmap( 0, 0, w, h, tile ); 479 p.drawTiledPixmap( 0, 0, w, h, tile );
485 if ( blends[ widget ] != 0.0 ) 480 if ( blends[ widget ] != 0.0 )
486 blend( widget ); 481 blend( widget );
487 } 482 }
488 } 483 }
489 } 484 }
490 return ( pixmaps[ widget ] ); 485 return ( pixmaps[ widget ] );
491} 486}
492 487
493OThemePixmap* OThemeBase::scaleBorder( int w, int h, WidgetType widget ) 488OThemePixmap* OThemeBase::scaleBorder( int w, int h, WidgetType widget )
494{ 489{
495 OThemePixmap * pixmap = NULL; 490 OThemePixmap * pixmap = NULL;
496 if ( !pbPixmaps[ widget ] && !pbWidth[ widget ] ) 491 if ( !pbPixmaps[ widget ] && !pbWidth[ widget ] )
497 return ( NULL ); 492 return ( NULL );
498 pixmap = cache->pixmap( w, h, widget, true ); 493 pixmap = cache->pixmap( w, h, widget, true );
499 if ( pixmap ) { 494 if ( pixmap ) {
500 pixmap = new OThemePixmap( *pixmap ); 495 pixmap = new OThemePixmap( *pixmap );
501 } 496 }
502 else { 497 else {
503 pixmap = new OThemePixmap(); 498 pixmap = new OThemePixmap();
504 pixmap->resize( w, h ); 499 pixmap->resize( w, h );
505 QBitmap mask; 500 QBitmap mask;
506 mask.resize( w, h ); 501 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 @@
1TEMPLATE = lib 1TEMPLATE = lib
2#CONFIG -= moc
3CONFIG += qt plugin 2CONFIG += qt plugin
4 3
5# Input 4# Input
6HEADERS = fortuneplugin.h fortunepluginimpl.h \ 5HEADERS = fortuneplugin.h fortunepluginimpl.h \
7 fortunepluginwidget.h 6 fortunepluginwidget.h
8SOURCES = fortuneplugin.cpp fortunepluginimpl.cpp \ 7SOURCES = fortuneplugin.cpp fortunepluginimpl.cpp \
9 fortunepluginwidget.cpp 8 fortunepluginwidget.cpp
10 9
11INCLUDEPATH += $(OPIEDIR)/include \ 10INCLUDEPATH += $(OPIEDIR)/include \
12 ../ ../library 11 ../ ../library
13DEPENDPATH += $(OPIEDIR)/include \ 12DEPENDPATH += $(OPIEDIR)/include \
14 ../ ../library 13 ../ ../library
15 14
16LIBS+= -lqpe -lopiecore2 -lopiepim2 -lopieui2 15LIBS+= -lqpe -lopiecore2 -lopiepim2 -lopieui2
17 16
18DESTDIR = $(OPIEDIR)/plugins/today 17DESTDIR = $(OPIEDIR)/plugins/today
19TARGET = todayfortuneplugin 18TARGET = todayfortuneplugin
20 19
21include ( $(OPIEDIR)/include.pro ) 20include ( $(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 @@
1/* 1/*
2 * fortunepluginwidget.cpp 2 * fortunepluginwidget.cpp
3 * 3 *
4 * copyright : (c) 2002 by Maximilian Reiß 4 * copyright : (c) 2002 by Maximilian Reiß
5 * email : harlekin@handhelds.org 5 * email : harlekin@handhelds.org
6 * 6 *
7 */ 7 */
8/*************************************************************************** 8/***************************************************************************
9 * * 9 * *
10 * This program is free software; you can redistribute it and/or modify * 10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by * 11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or * 12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. * 13 * (at your option) any later version. *
14 * * 14 * *
15 ***************************************************************************/ 15 ***************************************************************************/
16 16
17#include "fortunepluginwidget.h" 17#include "fortunepluginwidget.h"
18 18
19/* OPIE */
20#include <opie2/odebug.h>
19#include <qpe/config.h> 21#include <qpe/config.h>
20#include <qpe/qcopenvelope_qws.h> 22#include <qpe/qcopenvelope_qws.h>
23using namespace Opie::Core;
24using namespace Opie::Ui;
21 25
26/* QT */
22#include <qvaluelist.h> 27#include <qvaluelist.h>
23#include <qtl.h> 28#include <qtl.h>
24#include <qstring.h> 29#include <qstring.h>
25#include <qscrollview.h> 30#include <qscrollview.h>
26#include <qobject.h> 31#include <qobject.h>
27#include <qlayout.h> 32#include <qlayout.h>
28 33
29using namespace Opie::Core;
30using namespace Opie::Ui;
31FortunePluginWidget::FortunePluginWidget( QWidget *parent, const char* name ) 34FortunePluginWidget::FortunePluginWidget( QWidget *parent, const char* name )
32 : QWidget( parent, name ) 35 : QWidget( parent, name )
33{ 36{
34 37
35 fortune = NULL; 38 fortune = NULL;
36 getFortune(); 39 getFortune();
37} 40}
38 41
39FortunePluginWidget::~FortunePluginWidget() { 42FortunePluginWidget::~FortunePluginWidget() {
40 if( fortuneProcess ){ 43 if( fortuneProcess ){
41 delete fortuneProcess; 44 delete fortuneProcess;
42 } 45 }
43} 46}
44 47
45/** 48/**
46 * Get the fortunes 49 * Get the fortunes
47 */ 50 */
48void FortunePluginWidget::getFortune() { 51void FortunePluginWidget::getFortune() {
49 52
50 QVBoxLayout* layoutFortune = new QVBoxLayout( this ); 53 QVBoxLayout* layoutFortune = new QVBoxLayout( this );
51 54
52 if ( fortune ) { 55 if ( fortune ) {
53 delete fortune; 56 delete fortune;
54 } 57 }
55 58
56 fortune = new OTicker( this ); 59 fortune = new OTicker( this );
57 //fortune->setReadOnly( TRUE ); 60 //fortune->setReadOnly( TRUE );
58 //fortune->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) ); 61 //fortune->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) );
59 62
60 fortune->setText( QString("Obtaining fortune...") ); 63 fortune->setText( QString("Obtaining fortune...") );
61 layoutFortune->addWidget( fortune ); 64 layoutFortune->addWidget( fortune );
62 65
63 fortuneProcess = new OProcess(); 66 fortuneProcess = new OProcess();
64 *fortuneProcess << "fortune"; 67 *fortuneProcess << "fortune";
65 68
66 connect(fortuneProcess, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int) ), 69 connect(fortuneProcess, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int) ),
67 this, SLOT(slotStdOut(Opie::Core::OProcess*,char*,int) ) ); 70 this, SLOT(slotStdOut(Opie::Core::OProcess*,char*,int) ) );
68 71
69 if(!fortuneProcess->start(OProcess::NotifyOnExit, OProcess::AllOutput) ) { 72 if(!fortuneProcess->start(OProcess::NotifyOnExit, OProcess::AllOutput) ) {
70 qWarning("could not start :("); 73 owarn << "could not start :(" << oendl;
71 fortune->setText( QString("Failed to obtain fortune.") ); 74 fortune->setText( QString("Failed to obtain fortune.") );
72 delete fortuneProcess; 75 delete fortuneProcess;
73 fortuneProcess = 0; 76 fortuneProcess = 0;
74 } 77 }
75 78
76} 79}
77 80
78void FortunePluginWidget::slotStdOut( OProcess* /*proc*/, char* buf, int len ) 81void FortunePluginWidget::slotStdOut( OProcess* /*proc*/, char* buf, int len )
79{ 82{
80 QCString s( buf, len ); 83 QCString s( buf, len );
81 s.replace( QRegExp("\n"), "" ); 84 s.replace( QRegExp("\n"), "" );
82 fortune->setText( s ); 85 fortune->setText( s );
83} 86}
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 @@
1#include "inputDialog.h" 1#include "inputDialog.h"
2#include "helpwindow.h"
3
4/* OPIE */
5#include <opie2/odebug.h>
6#include <qpe/config.h>
7using namespace Opie::Core;
2 8
9/* QT */
3#include <qapplication.h> 10#include <qapplication.h>
4#include <qlayout.h> 11#include <qlayout.h>
5#include <qcheckbox.h> 12#include <qcheckbox.h>
6#include <qlineedit.h> 13#include <qlineedit.h>
7#include <qvariant.h> 14#include <qvariant.h>
8#include <qpushbutton.h> 15#include <qpushbutton.h>
9#include <qwhatsthis.h> 16#include <qwhatsthis.h>
10#include <qlabel.h> 17#include <qlabel.h>
11#include <qlayout.h> 18#include <qlayout.h>
12#include <qpe/config.h>
13#include <qstringlist.h> 19#include <qstringlist.h>
14using namespace Opie::Core;
15using namespace Opie::Core;
16#include <qmainwindow.h> 20#include <qmainwindow.h>
17#include "helpwindow.h"
18 21
22/* STD */
19#include <stdlib.h> 23#include <stdlib.h>
20// #include <sys/stat.h>
21// #include <unistd.h>
22 24
23InputDialog::InputDialog( ) 25InputDialog::InputDialog( )
24 : QMainWindow( 0x0, 0x0, WStyle_ContextHelp ) { 26 : QMainWindow( 0x0, 0x0, WStyle_ContextHelp ) {
25 setCaption( tr("Symbol Lookup")); 27 setCaption( tr("Symbol Lookup"));
26 28
27 QGridLayout *layout = new QGridLayout( this ); 29 QGridLayout *layout = new QGridLayout( this );
28 layout->setSpacing(6); 30 layout->setSpacing(6);
29 layout->setMargin( 2); 31 layout->setMargin( 2);
30 32
31 LineEdit1 = new QLineEdit( this, "LineEdit1" ); 33 LineEdit1 = new QLineEdit( this, "LineEdit1" );
32 LineEdit1->setFocus(); 34 LineEdit1->setFocus();
33 35
34 layout->addMultiCellWidget( LineEdit1, 0, 0, 0, 3); 36 layout->addMultiCellWidget( LineEdit1, 0, 0, 0, 3);
35 37
36 QLabel *label; 38 QLabel *label;
37 label = new QLabel(this); 39 label = new QLabel(this);
38 label->setText( tr("Enter something to lookup / search.")); 40 label->setText( tr("Enter something to lookup / search."));
39 label->setMaximumHeight(60); 41 label->setMaximumHeight(60);
40 layout->addMultiCellWidget( label, 1, 1, 0, 3); 42 layout->addMultiCellWidget( label, 1, 1, 0, 3);
41 43
42 connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(doLookup())); 44 connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(doLookup()));
43 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Expanding ); 45 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Expanding );
44 layout->addItem( spacer, 8, 0 ); 46 layout->addItem( spacer, 8, 0 );
45 47
46} 48}
47 49
48InputDialog::~InputDialog() { 50InputDialog::~InputDialog() {
49} 51}
50 52
51void InputDialog::doLookup() { 53void InputDialog::doLookup() {
52// http://finance.yahoo.com/l?m=&s=siemens&t= 54// http://finance.yahoo.com/l?m=&s=siemens&t=
53 55
54 QString url = "\"http://finance.yahoo.com/l?m=&s="+LineEdit1->text()+"\""; 56 QString url = "\"http://finance.yahoo.com/l?m=&s="+LineEdit1->text()+"\"";
55 QString tempHtml = "/tmp/stockticker.html"; 57 QString tempHtml = "/tmp/stockticker.html";
56 QString cmd = "wget -O "+tempHtml+" "+url; 58 QString cmd = "wget -O "+tempHtml+" "+url;
57 qDebug(cmd); 59 odebug << cmd << oendl;
58 60
59 61
60/* 62/*
61 OProcess proc; 63 OProcess proc;
62 proc << "/usr/bin/wget"; 64 proc << "/usr/bin/wget";
63 proc<<"-O"<< tempHtml<< url; 65 proc<<"-O"<< tempHtml<< url;
64 66
65 connect( &proc, SIGNAL( processExited(Opie::Core::OProcess*)),this, SLOT( showBrowser(Opie::Core::OProcess*))); 67 connect( &proc, SIGNAL( processExited(Opie::Core::OProcess*)),this, SLOT( showBrowser(Opie::Core::OProcess*)));
66 proc.start( OProcess::NotifyOnExit); 68 proc.start( OProcess::NotifyOnExit);
67*/ 69*/
68 system(cmd.latin1()); 70 system(cmd.latin1());
69 HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup"); 71 HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup");
70 StockLookup->setCaption("Symbol"); 72 StockLookup->setCaption("Symbol");
71 StockLookup->showMaximized(); 73 StockLookup->showMaximized();
72 StockLookup->show(); 74 StockLookup->show();
73 LineEdit1->text(); 75 LineEdit1->text();
74 76
75 77
76} 78}
77 79
78void InputDialog::showBrowser(OProcess*) { 80void InputDialog::showBrowser(OProcess*) {
79 qDebug("BLAH"); 81 odebug << "BLAH" << oendl;
80 QString tempHtml = "/tmp/stockticker.html"; 82 QString tempHtml = "/tmp/stockticker.html";
81 83
82 HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup"); 84 HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup");
83 StockLookup->setCaption("Symbol"); 85 StockLookup->setCaption("Symbol");
84 StockLookup->showMaximized(); 86 StockLookup->showMaximized();
85 StockLookup->show(); 87 StockLookup->show();
86 LineEdit1->text(); 88 LineEdit1->text();
87 89
88} 90}
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 @@
1config TODAY_STOCKTICKERLIB 1config TODAY_STOCKTICKERLIB
2 boolean 2 boolean
3 default "y" if TODAY_STOCKTICKER 3 default "y" if TODAY_STOCKTICKER
4 depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI && LIBOPIE2PIM && TODAY 4 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 @@
1TEMPLATE = lib 1TEMPLATE = lib
2CONFIG -= moc
3CONFIG += qt plugin 2CONFIG += qt plugin
4 3
5HEADERS = stocktickerplugin.h stocktickerpluginimpl.h stocktickerpluginwidget.h stocktickerconfig.h \ 4HEADERS = stocktickerplugin.h stocktickerpluginimpl.h stocktickerpluginwidget.h stocktickerconfig.h \
6 ../libstocks/csv.h \ 5 ../libstocks/csv.h \
7 ../libstocks/http.h \ 6 ../libstocks/http.h \
8 ../libstocks/lists.h \ 7 ../libstocks/lists.h \
9 ../libstocks/stocks.h 8 ../libstocks/stocks.h
10SOURCES = stocktickerplugin.cpp stocktickerpluginimpl.cpp stocktickerpluginwidget.cpp stocktickerconfig.cpp \ 9SOURCES = stocktickerplugin.cpp stocktickerpluginimpl.cpp stocktickerpluginwidget.cpp stocktickerconfig.cpp \
11 ../libstocks/csv.c \ 10 ../libstocks/csv.c \
12 ../libstocks/currency.c \ 11 ../libstocks/currency.c \
13 ../libstocks/history.c \ 12 ../libstocks/history.c \
14 ../libstocks/http.c \ 13 ../libstocks/http.c \
15 ../libstocks/lists.c \ 14 ../libstocks/lists.c \
16 ../libstocks/stocks.c 15 ../libstocks/stocks.c
17 16
18INCLUDEPATH += $(OPIEDIR)/include \ 17INCLUDEPATH += $(OPIEDIR)/include \
19 ../ ../library 18 ../ ../library
20DEPENDPATH += $(OPIEDIR)/include \ 19DEPENDPATH += $(OPIEDIR)/include \
21 ../ ../library 20 ../ ../library
22 21
23LIBS+= -lqpe -lopieui2 -lopiepim2 -lpthread 22LIBS += -lqpe -lopiecore2 -lopieui2 -lopiepim2 -lpthread
24TMAKE_CFLAGS += -D__UNIX__ 23DEFINES += __UNIX__
25 24
26DESTDIR = $(OPIEDIR)/plugins/today 25DESTDIR = $(OPIEDIR)/plugins/today
27TARGET = todaystocktickerplugin 26TARGET = todaystocktickerplugin
28 27
29include ( $(OPIEDIR)/include.pro ) 28include ( $(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 @@
1 /* 1 /*
2 * stocktickerpluginwidget.cpp 2 * stocktickerpluginwidget.cpp
3 * 3 *
4 * copyright : (c) 2002 by L.J. Potter 4 * copyright : (c) 2002 by L.J. Potter
5 * email : llornkcor@handhelds.org 5 * email : llornkcor@handhelds.org
6 * 6 *
7 */ 7 */
8 /*************************************************************************** 8 /***************************************************************************
9 * * 9 * *
10 * This program is free software; you can redistribute it and/or modify * 10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by * 11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or * 12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. * 13 * (at your option) any later version. *
14 * * 14 * *
15 ***************************************************************************/ 15 ***************************************************************************/
16 16
17 #include <opie2/oticker.h> 17 #include <opie2/oticker.h>
18 18
19 #include <qpe/config.h> 19 #include <qpe/config.h>
20 20
21 #include <qlayout.h> 21 #include <qlayout.h>
22 22
23using namespace Opie::Ui; 23using namespace Opie::Ui;
24using namespace Opie::Ui; 24using namespace Opie::Ui;
25extern "C" { 25extern "C" {
26 #include "libstocks/stocks.h" 26 #include "libstocks/stocks.h"
27 } 27 }
28 28
29 #include <pthread.h> 29 #include <pthread.h>
30 30
31 #include "stocktickerpluginwidget.h" 31 #include "stocktickerpluginwidget.h"
32 32
33 QString output; 33 QString output;
34 OTicker *stocktickerTicker; 34 OTicker *stocktickerTicker;
35 QCString stock_liste; 35 QCString stock_liste;
36 bool dotimeCheck, dodateCheck, dosymbolCheck, donameCheck; 36 bool dotimeCheck, dodateCheck, dosymbolCheck, donameCheck;
37 bool docurrentPriceCheck, dolastPriceCheck, doopenPriceCheck; 37 bool docurrentPriceCheck, dolastPriceCheck, doopenPriceCheck;
38 bool dominPriceCheck, domaxPriceCheck, dovariationCheck, dovolumeCheck; 38 bool dominPriceCheck, domaxPriceCheck, dovariationCheck, dovolumeCheck;
39 39
40void getStocks(char *blah) { 40void getStocks(char *blah) {
41 41
42 // stocktickerTicker->setText( "Downloading stock data."); 42 // stocktickerTicker->setText( "Downloading stock data.");
43 stock *stocks_quotes=NULL; 43 stock *stocks_quotes=NULL;
44 stock *stocks_tmp; 44 stock *stocks_tmp;
45 stock_liste = blah; 45 stock_liste = blah;
46 ::free ( blah ); 46 ::free ( blah );
47 // char *stock_liste = (char *)blah->latin1(); 47 // char *stock_liste = (char *)blah->latin1();
48 // qDebug("%s", stock_liste.data() ); 48 // odebug << "" << stock_liste.data() << "" << oendl;
49 output = ""; 49 output = "";
50 QString tempString; 50 QString tempString;
51 libstocks_return_code error; 51 libstocks_return_code error;
52 52
53// Config cfg( "stockticker"); 53// Config cfg( "stockticker");
54// cfg.setGroup( "Fields" ); 54// cfg.setGroup( "Fields" );
55// bool dotimeCheck, dodateCheck, dosymbolCheck, donameCheck; 55// bool dotimeCheck, dodateCheck, dosymbolCheck, donameCheck;
56// bool docurrentPriceCheck, dolastPriceCheck, doopenPriceCheck; 56// bool docurrentPriceCheck, dolastPriceCheck, doopenPriceCheck;
57// bool dominPriceCheck, domaxPriceCheck, dovariationCheck, dovolumeCheck; 57// bool dominPriceCheck, domaxPriceCheck, dovariationCheck, dovolumeCheck;
58 58
59 dotimeCheck=dodateCheck=dosymbolCheck=donameCheck= docurrentPriceCheck=dolastPriceCheck=doopenPriceCheck=dominPriceCheck=domaxPriceCheck=dovariationCheck=dovolumeCheck=false; 59 dotimeCheck=dodateCheck=dosymbolCheck=donameCheck= docurrentPriceCheck=dolastPriceCheck=doopenPriceCheck=dominPriceCheck=domaxPriceCheck=dovariationCheck=dovolumeCheck=false;
60 60
61 dotimeCheck=1; 61 dotimeCheck=1;
62 dodateCheck=1; 62 dodateCheck=1;
63 dosymbolCheck=1; 63 dosymbolCheck=1;
64 donameCheck=1; 64 donameCheck=1;
65 docurrentPriceCheck=1; 65 docurrentPriceCheck=1;
66 dolastPriceCheck=1; 66 dolastPriceCheck=1;
67 doopenPriceCheck=1; 67 doopenPriceCheck=1;
68 dominPriceCheck=1; 68 dominPriceCheck=1;
69 domaxPriceCheck=1; 69 domaxPriceCheck=1;
70 dovariationCheck=1; 70 dovariationCheck=1;
71 dovolumeCheck=1; 71 dovolumeCheck=1;
72 72
73// dotimeCheck=cfg.readBoolEntry("timeCheck",1); 73// dotimeCheck=cfg.readBoolEntry("timeCheck",1);
74// dodateCheck=cfg.readBoolEntry("dateCheck",1); 74// dodateCheck=cfg.readBoolEntry("dateCheck",1);
75// dosymbolCheck=cfg.readBoolEntry("symbolCheck",1); 75// dosymbolCheck=cfg.readBoolEntry("symbolCheck",1);
76// donameCheck=cfg.readBoolEntry("nameCheck",1); 76// donameCheck=cfg.readBoolEntry("nameCheck",1);
77// docurrentPriceCheck=cfg.readBoolEntry("currentPriceCheck",1); 77// docurrentPriceCheck=cfg.readBoolEntry("currentPriceCheck",1);
78// dolastPriceCheck=cfg.readBoolEntry("lastPriceCheck",1); 78// dolastPriceCheck=cfg.readBoolEntry("lastPriceCheck",1);
79// doopenPriceCheck=cfg.readBoolEntry("openPriceCheck",1); 79// doopenPriceCheck=cfg.readBoolEntry("openPriceCheck",1);
80// dominPriceCheck=cfg.readBoolEntry("minPriceCheck",1); 80// dominPriceCheck=cfg.readBoolEntry("minPriceCheck",1);
81// domaxPriceCheck=cfg.readBoolEntry("maxPriceCheck",1); 81// domaxPriceCheck=cfg.readBoolEntry("maxPriceCheck",1);
82// dovariationCheck=cfg.readBoolEntry("variationCheck",1); 82// dovariationCheck=cfg.readBoolEntry("variationCheck",1);
83// dovolumeCheck=cfg.readBoolEntry("volumeCheck",1); 83// dovolumeCheck=cfg.readBoolEntry("volumeCheck",1);
84 84
85 // DefProxy(); 85 // DefProxy();
86 // { 86 // {
87 char *proxy; 87 char *proxy;
88 // libstocks_return_code error; 88 // libstocks_return_code error;
89 89
90 /* Proxy support */ 90 /* Proxy support */
91 /* Checks for "http_proxy" environment variable */ 91 /* Checks for "http_proxy" environment variable */
92 proxy = getenv("http_proxy"); 92 proxy = getenv("http_proxy");
93 if(proxy) { 93 if(proxy) {
94 /* printf("proxy set\n"); */ 94 /* printf("proxy set\n"); */
95 error = set_proxy(proxy); 95 error = set_proxy(proxy);
96 if (error) { 96 if (error) {
97// printf("Proxy error (%d)\n", error); 97// printf("Proxy error (%d)\n", error);
98// QString tempString2; 98// QString tempString2;
99// tempString2.sprintf("Proxy error (%d)\n", error); 99// tempString2.sprintf("Proxy error (%d)\n", error);
100// output = tempString2; 100// output = tempString2;
101 // delete tempString2; 101 // delete tempString2;
102 return; 102 return;
103 // exit(1); 103 // exit(1);
104 } 104 }
105 } 105 }
106 ::free(proxy); 106 ::free(proxy);
107 // } 107 // }
108 /* Get the stocks and process errors */ 108 /* Get the stocks and process errors */
109 error = get_stocks( stock_liste.data(), &stocks_quotes); 109 error = get_stocks( stock_liste.data(), &stocks_quotes);
110 110
111 if (error) { 111 if (error) {
112 printf("Error in getting stocks (%d)\n", error); 112 printf("Error in getting stocks (%d)\n", error);
113 tempString.sprintf("Error in getting stocks (%d)\n", error); 113 tempString.sprintf("Error in getting stocks (%d)\n", error);
114 output =tempString; 114 output =tempString;
115 return; 115 return;
116 } 116 }
117 117
118 stocks_tmp = stocks_quotes; 118 stocks_tmp = stocks_quotes;
119 119
120 /* Displays the stocks */ 120 /* Displays the stocks */
121 while(stocks_tmp!=0){ 121 while(stocks_tmp!=0){
122 122
123 if (stocks_tmp->Time) { 123 if (stocks_tmp->Time) {
124 // printf("%s ", stocks_tmp->Time); 124 // printf("%s ", stocks_tmp->Time);
125 tempString.sprintf("| %s ", stocks_tmp->Time); 125 tempString.sprintf("| %s ", stocks_tmp->Time);
126 tempString.replace(QRegExp("\""),""); 126 tempString.replace(QRegExp("\""),"");
127 if( dotimeCheck) 127 if( dotimeCheck)
128 output +=tempString; 128 output +=tempString;
129 } 129 }
130 if (stocks_tmp->Date) { 130 if (stocks_tmp->Date) {
131 // printf("%s ", stocks_tmp->Date); 131 // printf("%s ", stocks_tmp->Date);
132 tempString.sprintf("| %s ", stocks_tmp->Date); 132 tempString.sprintf("| %s ", stocks_tmp->Date);
133 tempString.replace(QRegExp("\""),""); 133 tempString.replace(QRegExp("\""),"");
134 if(dodateCheck) 134 if(dodateCheck)
135 output +=tempString; 135 output +=tempString;
136 } 136 }
137 // printf("\n"); 137 // printf("\n");
138 138
139 // printf("----------------------------------------\n"); 139 // printf("----------------------------------------\n");
140 140
141 if ( strlen(stocks_tmp->Symbol) > 20 ) { 141 if ( strlen(stocks_tmp->Symbol) > 20 ) {
142 // printf("| Symbol | %.20s |\n",stocks_tmp->Symbol); 142 // printf("| Symbol | %.20s |\n",stocks_tmp->Symbol);
143 tempString.sprintf("| Symbol %s ",stocks_tmp->Symbol); 143 tempString.sprintf("| Symbol %s ",stocks_tmp->Symbol);
144 if(dosymbolCheck) 144 if(dosymbolCheck)
@@ -185,145 +185,145 @@ void getStocks(char *blah) {
185 185
186 // printf("| Open | %-7.2f |\n",stocks_tmp->OpenPrice); 186 // printf("| Open | %-7.2f |\n",stocks_tmp->OpenPrice);
187 tempString.sprintf("| Open %-7.2f ",stocks_tmp->OpenPrice); 187 tempString.sprintf("| Open %-7.2f ",stocks_tmp->OpenPrice);
188 if(doopenPriceCheck) 188 if(doopenPriceCheck)
189 output +=tempString; 189 output +=tempString;
190 190
191 // printf("| Min | %-7.2f |\n", stocks_tmp->MinPrice); 191 // printf("| Min | %-7.2f |\n", stocks_tmp->MinPrice);
192 tempString.sprintf("| Min %-7.2f ", stocks_tmp->MinPrice); 192 tempString.sprintf("| Min %-7.2f ", stocks_tmp->MinPrice);
193 if(dominPriceCheck) 193 if(dominPriceCheck)
194 output +=tempString; 194 output +=tempString;
195 195
196 // printf("| Max | %-7.2f |\n",stocks_tmp->MaxPrice); 196 // printf("| Max | %-7.2f |\n",stocks_tmp->MaxPrice);
197 tempString.sprintf("| Max %-7.2f ",stocks_tmp->MaxPrice); 197 tempString.sprintf("| Max %-7.2f ",stocks_tmp->MaxPrice);
198 if(domaxPriceCheck) 198 if(domaxPriceCheck)
199 output +=tempString; 199 output +=tempString;
200 200
201 // printf("| Var | %-6.2f (%5.2f %%) |\n", stocks_tmp->Variation, stocks_tmp->Pourcentage); 201 // printf("| Var | %-6.2f (%5.2f %%) |\n", stocks_tmp->Variation, stocks_tmp->Pourcentage);
202 tempString.sprintf("| Var %-6.2f (%5.2f %%) ", stocks_tmp->Variation, stocks_tmp->Pourcentage); 202 tempString.sprintf("| Var %-6.2f (%5.2f %%) ", stocks_tmp->Variation, stocks_tmp->Pourcentage);
203 if(dovariationCheck) 203 if(dovariationCheck)
204 output +=tempString; 204 output +=tempString;
205 205
206 // printf("| Volume | %-9d |\n", stocks_tmp->Volume); 206 // printf("| Volume | %-9d |\n", stocks_tmp->Volume);
207 tempString.sprintf("| Volume %-9d ", stocks_tmp->Volume); 207 tempString.sprintf("| Volume %-9d ", stocks_tmp->Volume);
208 if(dovolumeCheck) 208 if(dovolumeCheck)
209 output +=tempString; 209 output +=tempString;
210 210
211 // printf("----------------------------------------\n\n"); 211 // printf("----------------------------------------\n\n");
212 tempString.sprintf("||==++==|"); 212 tempString.sprintf("||==++==|");
213 output +=tempString; 213 output +=tempString;
214 214
215 /* Simple function which help to browse in the stocks list */ 215 /* Simple function which help to browse in the stocks list */
216 stocks_tmp = next_stock(stocks_tmp); 216 stocks_tmp = next_stock(stocks_tmp);
217 } 217 }
218 218
219 stocktickerTicker->setText( output.latin1() ); 219 stocktickerTicker->setText( output.latin1() );
220 220
221 /* frees stocks */ 221 /* frees stocks */
222 free_stocks(stocks_quotes); 222 free_stocks(stocks_quotes);
223 free_stocks(stocks_tmp); 223 free_stocks(stocks_tmp);
224 224
225 stock_liste=""; 225 stock_liste="";
226 //delete stock_liste; 226 //delete stock_liste;
227 tempString=""; 227 tempString="";
228 output=""; 228 output="";
229 } 229 }
230 230
231 StockTickerPluginWidget::StockTickerPluginWidget( QWidget *parent, const char* name) 231 StockTickerPluginWidget::StockTickerPluginWidget( QWidget *parent, const char* name)
232 : QWidget(parent, name ) { 232 : QWidget(parent, name ) {
233 init(); 233 init();
234 startTimer(1000); 234 startTimer(1000);
235 235
236 stocktickerTicker->setTextFormat(Qt::RichText); 236 stocktickerTicker->setTextFormat(Qt::RichText);
237 // checkConnection(); 237 // checkConnection();
238 } 238 }
239 239
240 StockTickerPluginWidget::~StockTickerPluginWidget() { 240 StockTickerPluginWidget::~StockTickerPluginWidget() {
241 } 241 }
242 242
243 void StockTickerPluginWidget::init() { 243 void StockTickerPluginWidget::init() {
244 244
245 QHBoxLayout* layout = new QHBoxLayout( this ); 245 QHBoxLayout* layout = new QHBoxLayout( this );
246 stocktickerTicker = new OTicker(this); 246 stocktickerTicker = new OTicker(this);
247 // stocktickerTicker->setMinimumHeight(15); 247 // stocktickerTicker->setMinimumHeight(15);
248 connect( stocktickerTicker, SIGNAL( mousePressed()), this, SLOT( checkConnection() )); 248 connect( stocktickerTicker, SIGNAL( mousePressed()), this, SLOT( checkConnection() ));
249 layout->addWidget( stocktickerTicker); 249 layout->addWidget( stocktickerTicker);
250 wasError = true; 250 wasError = true;
251 } 251 }
252 252
253 void StockTickerPluginWidget::doStocks() { 253 void StockTickerPluginWidget::doStocks() {
254 Config cfg( "stockticker"); 254 Config cfg( "stockticker");
255 cfg.setGroup( "Symbols" ); 255 cfg.setGroup( "Symbols" );
256 symbollist=""; 256 symbollist="";
257 symbollist = cfg.readEntry("Symbols", ""); 257 symbollist = cfg.readEntry("Symbols", "");
258 symbollist.replace(QRegExp(" "),"+");//seperated by + 258 symbollist.replace(QRegExp(" "),"+");//seperated by +
259 259
260 cfg.setGroup("Timer"); 260 cfg.setGroup("Timer");
261 stocktickerTicker->setUpdateTime( cfg.readNumEntry("ScrollSpeed",50)); 261 stocktickerTicker->setUpdateTime( cfg.readNumEntry("ScrollSpeed",50));
262 stocktickerTicker->setScrollLength( cfg.readNumEntry("ScrollLength",10)); 262 stocktickerTicker->setScrollLength( cfg.readNumEntry("ScrollLength",10));
263 263
264 if (!symbollist.isEmpty()) { 264 if (!symbollist.isEmpty()) {
265 pthread_t thread1; 265 pthread_t thread1;
266 char *blah = ::strdup(symbollist.latin1()); 266 char *blah = ::strdup(symbollist.latin1());
267 pthread_create( &thread1, NULL, (void * (*)(void *))getStocks, (void *) blah); 267 pthread_create( &thread1, NULL, (void * (*)(void *))getStocks, (void *) blah);
268 pthread_detach( thread1); 268 pthread_detach( thread1);
269 269
270 //::free((void*)thread1); 270 //::free((void*)thread1);
271 //getStocks(blah); 271 //getStocks(blah);
272 } 272 }
273 } 273 }
274 274
275 void StockTickerPluginWidget::timerEvent( QTimerEvent *e ) { 275 void StockTickerPluginWidget::timerEvent( QTimerEvent *e ) {
276 killTimer(e->timerId()); 276 killTimer(e->timerId());
277 checkConnection(); 277 checkConnection();
278 } 278 }
279 279
280 void StockTickerPluginWidget::checkConnection() { 280 void StockTickerPluginWidget::checkConnection() {
281 // qDebug("checking connection"); 281 // odebug << "checking connection" << oendl;
282 // Sock = new QSocket( this ); 282 // Sock = new QSocket( this );
283 283
284 // if( wasError) 284 // if( wasError)
285 // stocktickerTicker->setText("Checking connection"); 285 // stocktickerTicker->setText("Checking connection");
286 286
287 // if(Sock->state() == QSocket::Idle) { 287 // if(Sock->state() == QSocket::Idle) {
288 // Sock->connectToHost("finance.yahoo.com", 80); 288 // Sock->connectToHost("finance.yahoo.com", 80);
289 // connect( Sock, SIGNAL( error(int) ), SLOT(socketError(int)) ); 289 // connect( Sock, SIGNAL( error(int) ), SLOT(socketError(int)) );
290 // connect( Sock, SIGNAL( hostFound() ), SLOT(isConnected()) ); 290 // connect( Sock, SIGNAL( hostFound() ), SLOT(isConnected()) );
291 // } else { 291 // } else {
292 // qDebug("State is not Idle"); 292 // odebug << "State is not Idle" << oendl;
293 isConnected(); 293 isConnected();
294 // } 294 // }
295 } 295 }
296 296
297 void StockTickerPluginWidget::isConnected() { 297 void StockTickerPluginWidget::isConnected() {
298 // qDebug("We connect, so ok to grab stocks"); 298 // odebug << "We connect, so ok to grab stocks" << oendl;
299 if(this->isVisible()) 299 if(this->isVisible())
300 doStocks(); 300 doStocks();
301 301
302 Config cfg( "stockticker"); 302 Config cfg( "stockticker");
303 cfg.setGroup("Timer"); 303 cfg.setGroup("Timer");
304 timerDelay= cfg.readNumEntry("Delay",0); 304 timerDelay= cfg.readNumEntry("Delay",0);
305 if(timerDelay > 0) 305 if(timerDelay > 0)
306 startTimer(timerDelay*60000); 306 startTimer(timerDelay*60000);
307 // qDebug("timer set for %d",(timerDelay*60000)/60000); 307 // odebug << "timer set for " << (timerDelay*60000)/60000 << "" << oendl;
308 wasError = false; 308 wasError = false;
309 309
310 // Sock->close(); 310 // Sock->close();
311 } 311 }
312 312
313 void StockTickerPluginWidget::socketError(int errcode) { 313 void StockTickerPluginWidget::socketError(int errcode) {
314 switch(errcode) { 314 switch(errcode) {
315 case QSocket::ErrConnectionRefused: 315 case QSocket::ErrConnectionRefused:
316 output = tr("Connection refused."); 316 output = tr("Connection refused.");
317 break; 317 break;
318 case QSocket::ErrHostNotFound: 318 case QSocket::ErrHostNotFound:
319 output = tr("Could not find server."); 319 output = tr("Could not find server.");
320 break; 320 break;
321 case QSocket::ErrSocketRead : 321 case QSocket::ErrSocketRead :
322 output = tr("Socket read error."); 322 output = tr("Socket read error.");
323 break; 323 break;
324 }; 324 };
325 stocktickerTicker->setText( output ); 325 stocktickerTicker->setText( output );
326 wasError = true; 326 wasError = true;
327 // Sock->close(); 327 // Sock->close();
328 328
329 } 329 }
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 @@
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include "engine.h" 21#include "engine.h"
22#include <qstring.h> 22#include <qstring.h>
23#include <math.h> 23#include <math.h>
24#include <qlcdnumber.h> 24#include <qlcdnumber.h>
25 25
26Data Engine::evalStack (Data num, bool inbrace = FALSE) 26Data Engine::evalStack (Data num, bool inbrace = FALSE)
27{ 27{
28 if (state != sError) { 28 if (state != sError) {
29 Instruction *i; 29 Instruction *i;
30 30
31// Pop the next op from the stack 31// Pop the next op from the stack
32 while (!stack.isEmpty () && (braces || !inbrace)) { 32 while (!stack.isEmpty () && (braces || !inbrace)) {
33 i = stack.pop (); 33 i = stack.pop ();
34 34
35// Check this ops prec vs next ops prec 35// Check this ops prec vs next ops prec
36 if (!stack.isEmpty ()) 36 if (!stack.isEmpty ())
37 if (i->precedence <= stack.top()->precedence) 37 if (i->precedence <= stack.top()->precedence)
38 i->acc = evalStack (i->acc, inbrace); 38 i->acc = evalStack (i->acc, inbrace);
39 39
40// Evaluate this instruction 40// Evaluate this instruction
41 num = i->eval (num); 41 num = i->eval (num);
42 42
43// Error-check ( change this to work for all types ) 43// Error-check ( change this to work for all types )
44 if (isnan (num.dbl) || isinf (num.dbl)) { 44 if (isnan (num.dbl) || isinf (num.dbl)) {
45 qDebug ("bad result from operation"); 45 qDebug ("bad result from operation");
46 state = sError; 46 state = sError;
47 clearData(&num); 47 clearData(&num);
48 return num; 48 return num;
49 } 49 }
50 } 50 }
51 } 51 }
52 return num; 52 return num;
53} 53}
54 54
55// Plugins call this to request the stack be evaluated 55// Plugins call this to request the stack be evaluated
56void Engine::eval () 56void Engine::eval ()
57{ 57{
58 num = evalStack (num); 58 num = evalStack (num);
59 if (state != sError) { 59 if (state != sError) {
60 displayData(num); 60 displayData(num);
61 state = sStart; 61 state = sStart;
62 } 62 }
63// if the user didnt close all their braces, its no big deal 63// if the user didnt close all their braces, its no big deal
64 braces = 0; 64 braces = 0;
65} 65}
66 66
67void Engine::immediateInstruction (Instruction * i) 67void Engine::immediateInstruction (Instruction * i)
68{ 68{
69 if (state != sError) { 69 if (state != sError) {
70 i->setRep(currentRep); 70 i->setRep(currentRep);
71 num = i->eval (num); 71 num = i->eval (num);
72 displayData(num); 72 displayData(num);
73 state = sStart; 73 state = sStart;
74 } 74 }
75} 75}
76 76
77void Engine::pushInstruction (Instruction * i) 77void Engine::pushInstruction (Instruction * i)
78{ 78{
79 if (state != sError) { 79 if (state != sError) {
80 i->setRep(currentRep); 80 i->setRep(currentRep);
81 i->acc = num; 81 i->acc = num;
82 stack.push (i); 82 stack.push (i);
83 state = sStart; 83 state = sStart;
84 } 84 }
85} 85}
86 86
87void Engine::pushValue (char v) 87void Engine::pushValue (char v)
88{ 88{
89 if (state == sAppend) { 89 if (state == sAppend) {
90 bool ok = FALSE; 90 bool ok = FALSE;
91 switch (currentRep) { 91 switch (currentRep) {
92 case rDouble: 92 case rDouble:
93 displayString.append(v); 93 displayString.append(v);
94 num.dbl=displayString.toDouble(&ok); 94 num.dbl=displayString.toDouble(&ok);
95 break; 95 break;
96 case rFraction: 96 case rFraction:
97 break; 97 break;
98 default: 98 default:
99 displayString.append(v); 99 displayString.append(v);
100 num.i=displayString.toInt(&ok, calcBase()); 100 num.i=displayString.toInt(&ok, calcBase());
101 }; 101 };
102 if (!ok) { 102 if (!ok) {
103 state = sError; 103 state = sError;
104 qDebug("pushValue() - num->string conversion"); 104 odebug << "pushValue() - num->string conversion" << oendl;
105 } else { 105 } else {
106 const QString constString = displayString; 106 const QString constString = displayString;
107 emit(display(constString)); 107 emit(display(constString));
108 }; 108 };
109 109
110 } else if (state == sStart) { 110 } else if (state == sStart) {
111 softReset(); 111 softReset();
112 displayString.truncate(0); 112 displayString.truncate(0);
113 state = sAppend; 113 state = sAppend;
114 pushValue (v); 114 pushValue (v);
115 } else if (state == sError) { 115 } else if (state == sError) {
116 qDebug ("in error state"); 116 qDebug ("in error state");
117 return; 117 return;
118 } 118 }
119} 119}
120 120
121void Engine::del () 121void Engine::del ()
122{ 122{
123 bool ok; 123 bool ok;
124 switch (currentRep) { 124 switch (currentRep) {
125 case rDouble: 125 case rDouble:
126 displayString.truncate(displayString.length()); 126 displayString.truncate(displayString.length());
127 num.dbl=displayString.toDouble(&ok); 127 num.dbl=displayString.toDouble(&ok);
128 break; 128 break;
129 case rFraction: 129 case rFraction:
130 qDebug("not available"); 130 odebug << "not available" << oendl;
131 break; 131 break;
132 default: 132 default:
133 displayString.truncate(displayString.length()); 133 displayString.truncate(displayString.length());
134 num.i = displayString.toInt(&ok, calcBase()); 134 num.i = displayString.toInt(&ok, calcBase());
135 }; 135 };
136 136
137 if (!ok) { 137 if (!ok) {
138 state = sError; 138 state = sError;
139 qDebug("del() - num->string conversion"); 139 odebug << "del() - num->string conversion" << oendl;
140 } else { 140 } else {
141 const QString constString = displayString; 141 const QString constString = displayString;
142 emit(display(constString)); 142 emit(display(constString));
143 }; 143 };
144} 144}
145 145
146void Engine::displayData(Data d) { 146void Engine::displayData(Data d) {
147 switch (currentRep) { 147 switch (currentRep) {
148 case rDouble: 148 case rDouble:
149 displayString.setNum(d.dbl); 149 displayString.setNum(d.dbl);
150 break; 150 break;
151 case rFraction: 151 case rFraction:
152 qDebug("fractional display not yet impl"); 152 odebug << "fractional display not yet impl" << oendl;
153 break; 153 break;
154 default: 154 default:
155 displayString.setNum(d.i, calcBase()); 155 displayString.setNum(d.i, calcBase());
156 break; 156 break;
157 }; 157 };
158 const QString constString= displayString; 158 const QString constString= displayString;
159 emit(display(constString)); 159 emit(display(constString));
160} 160}
161 161
162// Returns the base when Rep is an integer type 162// Returns the base when Rep is an integer type
163int Engine::calcBase () { 163int Engine::calcBase () {
164 switch (currentRep) { 164 switch (currentRep) {
165 case rBin: 165 case rBin:
166 return 2; 166 return 2;
167 case rOct: 167 case rOct:
168 return 8; 168 return 8;
169 case rDec: 169 case rDec:
170 return 10; 170 return 10;
171 case rHex: 171 case rHex:
172 return 16; 172 return 16;
173 default: 173 default:
174 state = sError; 174 state = sError;
175 qDebug("Error - attempt to calc base for non-integer"); 175 odebug << "Error - attempt to calc base for non-integer" << oendl;
176 return 10; 176 return 10;
177 }; 177 };
178} 178}
179 179
180// Special instruction for internal use only 180// Special instruction for internal use only
181class iOpenBrace:public Instruction { 181class iOpenBrace:public Instruction {
182 public: 182 public:
183 iOpenBrace (Engine *e):Instruction (100) {engine = e;}; 183 iOpenBrace (Engine *e):Instruction (100) {engine = e;};
184 ~iOpenBrace () {}; 184 ~iOpenBrace () {};
185 185
186 Data eval (Data num) { 186 Data eval (Data num) {
187 engine->decBraces(); 187 engine->decBraces();
188 return num; 188 return num;
189 }; 189 };
190 private: 190 private:
191 Engine *engine; 191 Engine *engine;
192}; 192};
193 193
194void Engine::openBrace() { 194void Engine::openBrace() {
195 pushInstruction(new iOpenBrace(this)); 195 pushInstruction(new iOpenBrace(this));
196} 196}
197 197
198void Engine::closeBrace() { 198void Engine::closeBrace() {
199 braces++;evalStack(num,TRUE); 199 braces++;evalStack(num,TRUE);
200} 200}
201 201
202// will need to show and hide display widgets 202// will need to show and hide display widgets
203void Engine::setRepresentation(Representation r) { 203void Engine::setRepresentation(Representation r) {
204 currentRep = r; 204 currentRep = r;
205 clearData(&num); 205 clearData(&num);
206 clearData(&mem); 206 clearData(&mem);
207 state = sStart; 207 state = sStart;
208} 208}
209 209
210void Engine::clearData(Data *d) { 210void Engine::clearData(Data *d) {
211 d->i = d->fraction.numerator = d->fraction.denominator = 0; 211 d->i = d->fraction.numerator = d->fraction.denominator = 0;
212 d->dbl = 0; 212 d->dbl = 0;
213} 213}
214 214
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 @@
1 CONFIG = qt warn_on quick-app 1 CONFIG = qt warn_on quick-app
2 HEADERS = calculatorimpl.h 2 HEADERS = calculatorimpl.h
3 SOURCES = calculatorimpl.cpp \ 3 SOURCES = calculatorimpl.cpp \
4 main.cpp 4 main.cpp
5INCLUDEPATH += $(OPIEDIR)/include 5INCLUDEPATH += $(OPIEDIR)/include
6 DEPENDPATH+= $(OPIEDIR)/include 6 DEPENDPATH+= $(OPIEDIR)/include
7LIBS += -lqpe -lopiecore2 7LIBS += -lqpe -lopiecore2
8 INTERFACES= calculator.ui 8 INTERFACES= calculator.ui
9 TARGET = calculator 9 TARGET = calculator
10 10
11include ( $(OPIEDIR)/include.pro ) 11include ( $(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 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21/* 21/*
22 * 01/14/2002 Charles-Edouard Ruault <ce@ruault.com> 22 * 01/14/2002 Charles-Edouard Ruault <ce@ruault.com>
23 * Added support for Temperature conversions. 23 * Added support for Temperature conversions.
24 */ 24 */
25// Sat 03-09-2002 L.J. Potter added the inlined pixmaps here 25// Sat 03-09-2002 L.J. Potter added the inlined pixmaps here
26 26
27#include "calculatorimpl.h" 27#include "calculatorimpl.h"
28 28
29/* OPIE */
30#include <opie2/odebug.h>
29#include <qpe/resource.h> 31#include <qpe/resource.h>
30#include <qpe/qmath.h> 32#include <qpe/qmath.h>
31#include <qpe/qpeapplication.h> 33#include <qpe/qpeapplication.h>
34using namespace Opie::Core;
32 35
36/* QT */
33#include <qpushbutton.h> 37#include <qpushbutton.h>
34#include <qcombobox.h> 38#include <qcombobox.h>
35#include <qlabel.h> 39#include <qlabel.h>
36#include <qfont.h> 40#include <qfont.h>
37#include <qlayout.h> 41#include <qlayout.h>
38#include <qstringlist.h> 42#include <qstringlist.h>
39#include <qfile.h> 43#include <qfile.h>
40#include <qtextstream.h> 44#include <qtextstream.h>
41#include <qmessagebox.h> 45#include <qmessagebox.h>
46
47/* STD */
42#include <math.h> 48#include <math.h>
49
43/* XPM */ 50/* XPM */
44static char *oneoverx_xpm[] = { 51static char *oneoverx_xpm[] = {
45/* width height num_colors chars_per_pixel */ 52/* width height num_colors chars_per_pixel */
46" 13 11 2 1", 53" 13 11 2 1",
47/* colors */ 54/* colors */
48". c None", 55". c None",
49"# c #000000", 56"# c #000000",
50/* pixels */ 57/* pixels */
51"......#......", 58"......#......",
52".....##......", 59".....##......",
53"......#......" 60"......#......"
54".....###.....", 61".....###.....",
55".............", 62".............",
56"..#########..", 63"..#########..",
57".............", 64".............",
58"....##.##....", 65"....##.##....",
59"......#......", 66"......#......",
60"......#......", 67"......#......",
61"....##.##....", 68"....##.##....",
62}; 69};
63/* XPM */ 70/* XPM */
64static char *ythrootofx_xpm[] = { 71static char *ythrootofx_xpm[] = {
65/* width height num_colors chars_per_pixel */ 72/* width height num_colors chars_per_pixel */
66" 13 11 2 1", 73" 13 11 2 1",
67/* colors */ 74/* colors */
68". c None", 75". c None",
69"# c #000000", 76"# c #000000",
70/* pixels */ 77/* pixels */
71"#.#..........", 78"#.#..........",
72"#.#..........", 79"#.#..........",
73"###...#######", 80"###...#######",
74"..#..#.......", 81"..#..#.......",
75"###..#.......", 82"###..#.......",
76".....#.#...#.", 83".....#.#...#.",
77".#..#...#.#..", 84".#..#...#.#..",
78"#.#.#....#...", 85"#.#.#....#...",
79"..#.#...#.#..", 86"..#.#...#.#..",
80"...#...#...#.", 87"...#...#...#.",
81"...#........." 88"...#........."
82}; 89};
83/* XPM */ 90/* XPM */
84static char *xtopowerofy_xpm[] = { 91static char *xtopowerofy_xpm[] = {
85/* width height num_colors chars_per_pixel */ 92/* width height num_colors chars_per_pixel */
86" 9 8 2 1", 93" 9 8 2 1",
87/* colors */ 94/* colors */
88". c None", 95". c None",
89"# c #000000", 96"# c #000000",
90/* pixels */ 97/* pixels */
91"......#.#", 98"......#.#",
92"......#.#", 99"......#.#",
93"......###", 100"......###",
94"#...#...#", 101"#...#...#",
95".#.#..###", 102".#.#..###",
96"..#......", 103"..#......",
97".#.#.....", 104".#.#.....",
98"#...#...." 105"#...#...."
99}; 106};
100 107
101CalculatorImpl::CalculatorImpl( QWidget * parent, const char * name, 108CalculatorImpl::CalculatorImpl( QWidget * parent, const char * name,
102 WFlags f ) 109 WFlags f )
103 : Calculator( parent, name, f ) 110 : Calculator( parent, name, f )
104{ 111{
105// xtopowerofy = Resource::loadPixmap("xtopowerofy"); 112// xtopowerofy = Resource::loadPixmap("xtopowerofy");
106// ythrootofx = Resource::loadPixmap("ythrootofx"); 113// ythrootofx = Resource::loadPixmap("ythrootofx");
107// oneoverx = Resource::loadPixmap("oneoverx"); 114// oneoverx = Resource::loadPixmap("oneoverx");
108 115
109 memMark = new QLabel( "m", LCD ); 116 memMark = new QLabel( "m", LCD );
110 memMark->setFont( QFont( "helvetica", 12, QFont::Bold, TRUE ) ); 117 memMark->setFont( QFont( "helvetica", 12, QFont::Bold, TRUE ) );
111 memMark->resize( 12, 12 ); 118 memMark->resize( 12, 12 );
112 memMark->move( 4, 2 ); 119 memMark->move( 4, 2 );
113 memMark->hide(); 120 memMark->hide();
114 mem = 0; 121 mem = 0;
115 122
116 PushButtonMR->setEnabled( FALSE ); 123 PushButtonMR->setEnabled( FALSE );
117 124
118 current_mode = max_mode = conversion_mode_count = 0; 125 current_mode = max_mode = conversion_mode_count = 0;
119 last_conversion = -1; 126 last_conversion = -1;
120 127
121 // translation trick mode - with this stuff parsed in from a file is translatable 128 // translation trick mode - with this stuff parsed in from a file is translatable
122 QObject::tr("Standard"); 129 QObject::tr("Standard");
123 QObject::tr("Weight"); 130 QObject::tr("Weight");
124 QObject::tr("Distance"); 131 QObject::tr("Distance");
125 QObject::tr("Area"); 132 QObject::tr("Area");
126 QObject::tr("Temperatures"); 133 QObject::tr("Temperatures");
127 QObject::tr("Volume"); 134 QObject::tr("Volume");
128 QObject::tr("acres"); 135 QObject::tr("acres");
129 QObject::tr("°C"); 136 QObject::tr("°C");
130 QObject::tr("carats"); 137 QObject::tr("carats");
131 QObject::tr("cm"); 138 QObject::tr("cm");
132 QObject::tr("cu cm"); 139 QObject::tr("cu cm");
133 QObject::tr("cu ft"); 140 QObject::tr("cu ft");
134 QObject::tr("cu in"); 141 QObject::tr("cu in");
135 QObject::tr("°F"); 142 QObject::tr("°F");
136 QObject::tr("fl oz (US)"); 143 QObject::tr("fl oz (US)");
137 QObject::tr("ft"); 144 QObject::tr("ft");
138 QObject::tr("g"); 145 QObject::tr("g");
@@ -140,193 +147,193 @@ CalculatorImpl::CalculatorImpl( QWidget * parent, const char * name,
140 QObject::tr("hectares"); 147 QObject::tr("hectares");
141 QObject::tr("in"); 148 QObject::tr("in");
142 QObject::tr("kg"); 149 QObject::tr("kg");
143 QObject::tr("km"); 150 QObject::tr("km");
144 QObject::tr("l"); 151 QObject::tr("l");
145 QObject::tr("lb"); 152 QObject::tr("lb");
146 QObject::tr("Lg tons"); 153 QObject::tr("Lg tons");
147 QObject::tr("m"); 154 QObject::tr("m");
148 QObject::tr("mg"); 155 QObject::tr("mg");
149 QObject::tr("mi"); 156 QObject::tr("mi");
150 QObject::tr("ml"); 157 QObject::tr("ml");
151 QObject::tr("mm"); 158 QObject::tr("mm");
152 QObject::tr("naut. mi"); 159 QObject::tr("naut. mi");
153 QObject::tr("oz"); 160 QObject::tr("oz");
154 QObject::tr("points"); 161 QObject::tr("points");
155 QObject::tr("pt"); 162 QObject::tr("pt");
156 QObject::tr("qt"); 163 QObject::tr("qt");
157 QObject::tr("sq cm"); 164 QObject::tr("sq cm");
158 QObject::tr("sq ft"); 165 QObject::tr("sq ft");
159 QObject::tr("sq in"); 166 QObject::tr("sq in");
160 QObject::tr("sq km"); 167 QObject::tr("sq km");
161 QObject::tr("sq m"); 168 QObject::tr("sq m");
162 QObject::tr("sq mi"); 169 QObject::tr("sq mi");
163 QObject::tr("sq mm"); 170 QObject::tr("sq mm");
164 QObject::tr("sq yd"); 171 QObject::tr("sq yd");
165 QObject::tr("st"); 172 QObject::tr("st");
166 QObject::tr("St tons"); 173 QObject::tr("St tons");
167 QObject::tr("tblspoon"); 174 QObject::tr("tblspoon");
168 QObject::tr("teaspoons"); 175 QObject::tr("teaspoons");
169 QObject::tr("tonnes"); 176 QObject::tr("tonnes");
170 QObject::tr("yd"); 177 QObject::tr("yd");
171 178
172 179
173//bgr_command.insert( PushButtonFunction); 180//bgr_command.insert( PushButtonFunction);
174 bgr_command.insert( PushButtonMPlus); 181 bgr_command.insert( PushButtonMPlus);
175 bgr_command.insert( PushButtonMR); 182 bgr_command.insert( PushButtonMR);
176 bgr_command.insert( PushButtonMC); 183 bgr_command.insert( PushButtonMC);
177 bgr_command.insert( PushButtonCE); 184 bgr_command.insert( PushButtonCE);
178 connect( &bgr_command, SIGNAL(clicked(int) ), this, SLOT(command_buttons(int))); 185 connect( &bgr_command, SIGNAL(clicked(int) ), this, SLOT(command_buttons(int)));
179 186
180 bgr_digits.insert(PushButton0); 187 bgr_digits.insert(PushButton0);
181 bgr_digits.insert(PushButton1); 188 bgr_digits.insert(PushButton1);
182 bgr_digits.insert(PushButton2); 189 bgr_digits.insert(PushButton2);
183 bgr_digits.insert(PushButton3); 190 bgr_digits.insert(PushButton3);
184 bgr_digits.insert(PushButton4); 191 bgr_digits.insert(PushButton4);
185 bgr_digits.insert(PushButton5); 192 bgr_digits.insert(PushButton5);
186 bgr_digits.insert(PushButton6); 193 bgr_digits.insert(PushButton6);
187 bgr_digits.insert(PushButton7); 194 bgr_digits.insert(PushButton7);
188 bgr_digits.insert(PushButton8); 195 bgr_digits.insert(PushButton8);
189 bgr_digits.insert(PushButton9); 196 bgr_digits.insert(PushButton9);
190 connect( &bgr_digits, SIGNAL(clicked(int) ), this, SLOT(enterNumber(int))); 197 connect( &bgr_digits, SIGNAL(clicked(int) ), this, SLOT(enterNumber(int)));
191 198
192 199
193 bgr_std.insert(PushButtonEquals); 200 bgr_std.insert(PushButtonEquals);
194 bgr_std.insert(PushButtonDecimal); 201 bgr_std.insert(PushButtonDecimal);
195 bgr_std.insert(PushButtonAdd); 202 bgr_std.insert(PushButtonAdd);
196 bgr_std.insert(PushButtonMinus); 203 bgr_std.insert(PushButtonMinus);
197 bgr_std.insert(PushButtonDivide); 204 bgr_std.insert(PushButtonDivide);
198 bgr_std.insert(PushButtonTimes); 205 bgr_std.insert(PushButtonTimes);
199 connect( &bgr_std, SIGNAL(clicked(int) ), this, SLOT(std_buttons(int))); 206 connect( &bgr_std, SIGNAL(clicked(int) ), this, SLOT(std_buttons(int)));
200 207
201// change the / to a proper division signal 208// change the / to a proper division signal
202 PushButtonDivide->setText(QChar(0xF7)); 209 PushButtonDivide->setText(QChar(0xF7));
203 210
204 func_buttons[0] = PushButtonF1; 211 func_buttons[0] = PushButtonF1;
205 func_buttons[1] = PushButtonF2; 212 func_buttons[1] = PushButtonF2;
206 func_buttons[2] = PushButtonF3; 213 func_buttons[2] = PushButtonF3;
207 func_buttons[3] = PushButtonF4; 214 func_buttons[3] = PushButtonF4;
208 func_buttons[4] = PushButtonF5; 215 func_buttons[4] = PushButtonF5;
209 func_buttons[5] = PushButtonF6; 216 func_buttons[5] = PushButtonF6;
210 func_buttons[6] = PushButtonF7; 217 func_buttons[6] = PushButtonF7;
211 func_buttons[7] = PushButtonF8; 218 func_buttons[7] = PushButtonF8;
212 func_buttons[8] = PushButtonF9; 219 func_buttons[8] = PushButtonF9;
213 func_buttons[9] = PushButtonF10; 220 func_buttons[9] = PushButtonF10;
214 func_buttons[10] = PushButtonF11; 221 func_buttons[10] = PushButtonF11;
215 func_buttons[11] = PushButtonF12; 222 func_buttons[11] = PushButtonF12;
216 223
217 for ( int x = 0 ; x < func_button_count ; x++ ) { 224 for ( int x = 0 ; x < func_button_count ; x++ ) {
218 QPushButton* tmpbutton = func_buttons[x]; 225 QPushButton* tmpbutton = func_buttons[x];
219 faces << tmpbutton->text(); 226 faces << tmpbutton->text();
220 bgr_function.insert(tmpbutton); 227 bgr_function.insert(tmpbutton);
221 } 228 }
222 connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(do_convert(int) ) ); 229 connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(do_convert(int) ) );
223 connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(std_funcs(int) ) ); 230 connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(std_funcs(int) ) );
224 231
225 connect(ComboBoxFunction, SIGNAL(activated(int) ), this, SLOT(function_button(int) ) ); 232 connect(ComboBoxFunction, SIGNAL(activated(int) ), this, SLOT(function_button(int) ) );
226 233
227 captions.append(tr("Standard")); 234 captions.append(tr("Standard"));
228 ComboBoxFunction->insertItem(captions.last()); 235 ComboBoxFunction->insertItem(captions.last());
229 236
230 // now add in the conversion modes 237 // now add in the conversion modes
231 // when the menu gets done, these should be in a submenu 238 // when the menu gets done, these should be in a submenu
232 QString tmp = QPEApplication::qpeDir(); 239 QString tmp = QPEApplication::qpeDir();
233 tmp += "etc/unit_conversion.dat"; 240 tmp += "etc/unit_conversion.dat";
234 QFile myfile(tmp); 241 QFile myfile(tmp);
235 if ( !myfile.open( IO_Translate | IO_ReadOnly ) ) { 242 if ( !myfile.open( IO_Translate | IO_ReadOnly ) ) {
236 qDebug("Data file unit_conversion.dat not found\nNo conversion features will be available\n"+tmp); 243 odebug << "Data file unit_conversion.dat not found\nNo conversion features will be available\n"+tmp << oendl;
237 // disable the f button if no conv file available 244 // disable the f button if no conv file available
238 ComboBoxFunction->setEnabled(FALSE); 245 ComboBoxFunction->setEnabled(FALSE);
239 } 246 }
240 else { 247 else {
241 QString line, line2; 248 QString line, line2;
242 QTextStream ts(&myfile); 249 QTextStream ts(&myfile);
243 250
244 // first pass, see how many conversion types there are in order to allocate for them 251 // first pass, see how many conversion types there are in order to allocate for them
245 while ( ! ts.eof() ) { 252 while ( ! ts.eof() ) {
246 line = ts.readLine(); 253 line = ts.readLine();
247 if ( line.contains ("STARTTYPE" ) ) 254 if ( line.contains ("STARTTYPE" ) )
248 conversion_mode_count++; 255 conversion_mode_count++;
249 } 256 }
250 257
251 entry_list = new double[conversion_mode_count*func_button_count]; 258 entry_list = new double[conversion_mode_count*func_button_count];
252 preoffset_list = new double[conversion_mode_count*func_button_count]; 259 preoffset_list = new double[conversion_mode_count*func_button_count];
253 postoffset_list = new double[conversion_mode_count*func_button_count]; 260 postoffset_list = new double[conversion_mode_count*func_button_count];
254 myfile.close(); 261 myfile.close();
255 myfile.open( IO_Translate | IO_ReadOnly ); 262 myfile.open( IO_Translate | IO_ReadOnly );
256 QTextStream ts2(&myfile); 263 QTextStream ts2(&myfile);
257 264
258 // second pass, read in values 265 // second pass, read in values
259 int x = 0; 266 int x = 0;
260 while ( ! ts2.eof() ) { 267 while ( ! ts2.eof() ) {
261 line = ts2.readLine(); 268 line = ts2.readLine();
262 if ( line.contains("STARTTYPE") ) { 269 if ( line.contains("STARTTYPE") ) {
263 captions << tr( line.remove(0,10) ); 270 captions << tr( line.remove(0,10) );
264 ComboBoxFunction->insertItem(captions.last()); 271 ComboBoxFunction->insertItem(captions.last());
265 while ( !line.contains("ENDTYPE") ) { 272 while ( !line.contains("ENDTYPE") ) {
266 line = ts2.readLine(); 273 line = ts2.readLine();
267 if ( line.contains("NAME") ) { 274 if ( line.contains("NAME") ) {
268 faces << tr( line.remove(0,5) ); 275 faces << tr( line.remove(0,5) );
269 line2 = ts2.readLine(); 276 line2 = ts2.readLine();
270 line2.remove(0,6); 277 line2.remove(0,6);
271 entry_list[x] = line2.toDouble(); 278 entry_list[x] = line2.toDouble();
272 line2 = ts2.readLine(); 279 line2 = ts2.readLine();
273 line2.remove(0,7); 280 line2.remove(0,7);
274 preoffset_list[x] = line2.toDouble(); 281 preoffset_list[x] = line2.toDouble();
275 line2 = ts2.readLine(); 282 line2 = ts2.readLine();
276 line2.remove(0,8); 283 line2.remove(0,8);
277 postoffset_list[x] = line2.toDouble(); 284 postoffset_list[x] = line2.toDouble();
278 x++; 285 x++;
279 } 286 }
280 } 287 }
281 } 288 }
282 } 289 }
283 } 290 }
284 myfile.close(); 291 myfile.close();
285 clear(); 292 clear();
286 max_mode = pre_conv_modes_count + conversion_mode_count + post_conv_modes_count - 1; 293 max_mode = pre_conv_modes_count + conversion_mode_count + post_conv_modes_count - 1;
287 display_pixmap_faces(); 294 display_pixmap_faces();
288 295
289 qApp->installEventFilter( this ); 296 qApp->installEventFilter( this );
290} 297}
291 298
292bool CalculatorImpl::eventFilter( QObject *o, QEvent *e ) 299bool CalculatorImpl::eventFilter( QObject *o, QEvent *e )
293{ 300{
294 if ( e->type() == QEvent::KeyPress && state != sError ) { 301 if ( e->type() == QEvent::KeyPress && state != sError ) {
295 QKeyEvent *k = (QKeyEvent*)e; 302 QKeyEvent *k = (QKeyEvent*)e;
296 if ( k->key() >= Key_0 && k->key() <= Key_9 ) { 303 if ( k->key() >= Key_0 && k->key() <= Key_9 ) {
297 enterNumber( k->key() - Key_0 ); 304 enterNumber( k->key() - Key_0 );
298 return true; 305 return true;
299 } else { 306 } else {
300 switch ( k->key() ) { 307 switch ( k->key() ) {
301 case Key_Equal: 308 case Key_Equal:
302 std_buttons(0); 309 std_buttons(0);
303 return true; 310 return true;
304 case Key_Period: 311 case Key_Period:
305 std_buttons(1); 312 std_buttons(1);
306 return true; 313 return true;
307 case Key_Plus: 314 case Key_Plus:
308 std_buttons(2); 315 std_buttons(2);
309 return true; 316 return true;
310 case Key_Minus: 317 case Key_Minus:
311 std_buttons(3); 318 std_buttons(3);
312 return true; 319 return true;
313 case Key_Slash: 320 case Key_Slash:
314 std_buttons(4); 321 std_buttons(4);
315 return true; 322 return true;
316 case Key_Asterisk: 323 case Key_Asterisk:
317 std_buttons(5); 324 std_buttons(5);
318 return true; 325 return true;
319 case Key_Percent: 326 case Key_Percent:
320 execOp( oPercent ); 327 execOp( oPercent );
321 return true; 328 return true;
322 case Key_ParenLeft: 329 case Key_ParenLeft:
323 if ( current_mode < pre_conv_modes_count ) 330 if ( current_mode < pre_conv_modes_count )
324 execOp( oOpenBrace ); 331 execOp( oOpenBrace );
325 return true; 332 return true;
326 case Key_ParenRight: 333 case Key_ParenRight:
327 if ( current_mode < pre_conv_modes_count ) 334 if ( current_mode < pre_conv_modes_count )
328 execOp( oCloseBrace ); 335 execOp( oCloseBrace );
329 return true; 336 return true;
330 default: 337 default:
331 break; 338 break;
332 } 339 }
@@ -414,193 +421,193 @@ void CalculatorImpl::display_pixmap_faces() {
414 421
415void CalculatorImpl::clear() { 422void CalculatorImpl::clear() {
416 acc = num = 0; 423 acc = num = 0;
417 operationStack.clear(); 424 operationStack.clear();
418 state = sStart; 425 state = sStart;
419 numDecimals = 0; 426 numDecimals = 0;
420 numOpenBraces = 0; 427 numOpenBraces = 0;
421 flPoint = FALSE; 428 flPoint = FALSE;
422 LCD->display( 0 ); 429 LCD->display( 0 );
423 fake = QString::null; 430 fake = QString::null;
424 431
425 reset_conv(); 432 reset_conv();
426} 433}
427 434
428void CalculatorImpl::reset_conv() { 435void CalculatorImpl::reset_conv() {
429 for ( int x = 0 ; x < changeable_func_button_count ; x++ ) { 436 for ( int x = 0 ; x < changeable_func_button_count ; x++ ) {
430 QPushButton* tmpbutton = func_buttons[x]; 437 QPushButton* tmpbutton = func_buttons[x];
431 438
432 // dont carry any selections into the next mode 439 // dont carry any selections into the next mode
433 if ( tmpbutton->state() == QPushButton::On ) { 440 if ( tmpbutton->state() == QPushButton::On ) {
434 tmpbutton->toggle(); 441 tmpbutton->toggle();
435 } 442 }
436 } 443 }
437 444
438 last_conversion = -1; 445 last_conversion = -1;
439} 446}
440 447
441void CalculatorImpl::std_buttons(int button) 448void CalculatorImpl::std_buttons(int button)
442{ 449{
443 if ( state == sError ) 450 if ( state == sError )
444 return; 451 return;
445 execOp( (Operation)(button + oSum) ); 452 execOp( (Operation)(button + oSum) );
446} 453}
447 454
448void CalculatorImpl::std_funcs(int button) { 455void CalculatorImpl::std_funcs(int button) {
449 if ( state == sError ) 456 if ( state == sError )
450 return; 457 return;
451 if ( current_mode < pre_conv_modes_count || 458 if ( current_mode < pre_conv_modes_count ||
452 button > changeable_func_button_count-1 ) { 459 button > changeable_func_button_count-1 ) {
453 Operation op; 460 Operation op;
454 if ( button < 10 ) 461 if ( button < 10 )
455 op = (Operation)(button + oSin); 462 op = (Operation)(button + oSin);
456 else if ( button == 10 ) 463 else if ( button == 10 )
457 op = oOpenBrace; 464 op = oOpenBrace;
458 else 465 else
459 op = oCloseBrace; 466 op = oCloseBrace;
460 execOp( op ); 467 execOp( op );
461 } 468 }
462} 469}
463 470
464void CalculatorImpl::execOp( Operation i ) 471void CalculatorImpl::execOp( Operation i )
465{ 472{
466 switch (i) { 473 switch (i) {
467 // these operators only affect the current number. 474 // these operators only affect the current number.
468 case oDivX: 475 case oDivX:
469 case oLog: 476 case oLog:
470 case oLn: 477 case oLn:
471 case oSin: 478 case oSin:
472 case oCos: 479 case oCos:
473 case oTan: 480 case oTan:
474 num = evalExpr(i); 481 num = evalExpr(i);
475 break; 482 break;
476 483
477 case oAdd: 484 case oAdd:
478 case oSub: { 485 case oSub: {
479 processStack( oAdd ); 486 processStack( oAdd );
480 Op op( num, i ); 487 Op op( num, i );
481 operationStack.push( op ); 488 operationStack.push( op );
482 break; 489 break;
483 } 490 }
484 case oDiv: 491 case oDiv:
485 case oMult: 492 case oMult:
486 case oRoot: 493 case oRoot:
487 case oXsquared: { 494 case oXsquared: {
488 processStack( oDiv ); 495 processStack( oDiv );
489 Op op( num, i ); 496 Op op( num, i );
490 operationStack.push( op ); 497 operationStack.push( op );
491 break; 498 break;
492 } 499 }
493 case oChSign: 500 case oChSign:
494 num = -num; 501 num = -num;
495 LCD->display(num); 502 LCD->display(num);
496 return; 503 return;
497 504
498 case oOpenBrace: { 505 case oOpenBrace: {
499 Op op( 0, oOpenBrace ); 506 Op op( 0, oOpenBrace );
500 operationStack.push( op ); 507 operationStack.push( op );
501 numOpenBraces++; 508 numOpenBraces++;
502 state = sNewNumber; 509 state = sNewNumber;
503 return; 510 return;
504 } 511 }
505 case oCloseBrace: { 512 case oCloseBrace: {
506 if ( numOpenBraces == 0 ) 513 if ( numOpenBraces == 0 )
507 return; 514 return;
508 processStack( oAdd ); 515 processStack( oAdd );
509 if ( operationStack.top().operation != oOpenBrace ) 516 if ( operationStack.top().operation != oOpenBrace )
510 qDebug( "Calculator: internal Error" ); 517 odebug << "Calculator: internal Error" << oendl;
511 operationStack.pop(); 518 operationStack.pop();
512 state = sNewNumber; 519 state = sNewNumber;
513 numOpenBraces--; 520 numOpenBraces--;
514 break; 521 break;
515 } 522 }
516 523
517 case oPoint: 524 case oPoint:
518 flPoint = TRUE; 525 flPoint = TRUE;
519 return; 526 return;
520 527
521 case oPercent: 528 case oPercent:
522 processStack( oPercent ); 529 processStack( oPercent );
523 break; 530 break;
524 531
525 532
526 case oSum: 533 case oSum:
527 processStack( oSum ); 534 processStack( oSum );
528 break; 535 break;
529 536
530 default: 537 default:
531 return; 538 return;
532 }; 539 };
533 540
534 if ( state == sError ) { 541 if ( state == sError ) {
535 LCD->display( "Error" ); 542 LCD->display( "Error" );
536 return; 543 return;
537 } else { 544 } else {
538 LCD->display(num); 545 LCD->display(num);
539 } 546 }
540 state = sNewNumber; 547 state = sNewNumber;
541 numDecimals = 0; 548 numDecimals = 0;
542 flPoint = FALSE; 549 flPoint = FALSE;
543} 550}
544 551
545 552
546void CalculatorImpl::processStack( int op ) 553void CalculatorImpl::processStack( int op )
547{ 554{
548 //dubious percent hack, since the changeable operator precedences are 555 //dubious percent hack, since the changeable operator precedences are
549 //pretty much hardwired to be less than the non-changeable 556 //pretty much hardwired to be less than the non-changeable
550 bool percent = FALSE; 557 bool percent = FALSE;
551 if ( op == oPercent ) { 558 if ( op == oPercent ) {
552 percent = TRUE; 559 percent = TRUE;
553 op = oSum; 560 op = oSum;
554 } 561 }
555 while( !operationStack.isEmpty() && operationStack.top().operation >= op ) { 562 while( !operationStack.isEmpty() && operationStack.top().operation >= op ) {
556 Op operation = operationStack.pop(); 563 Op operation = operationStack.pop();
557 acc = operation.number; 564 acc = operation.number;
558 if ( percent ) { 565 if ( percent ) {
559 if ( operation.operation == oAdd || operation.operation == oSub ) 566 if ( operation.operation == oAdd || operation.operation == oSub )
560 num = acc*num/100; 567 num = acc*num/100;
561 else 568 else
562 num = num / 100; 569 num = num / 100;
563 } 570 }
564 num = evalExpr( operation.operation ); 571 num = evalExpr( operation.operation );
565 percent = FALSE; 572 percent = FALSE;
566 } 573 }
567} 574}
568 575
569 576
570double CalculatorImpl::evalExpr( int op ) { 577double CalculatorImpl::evalExpr( int op ) {
571 double sum = 0; 578 double sum = 0;
572 579
573 switch( op ){ 580 switch( op ){
574 case oPercent: sum = num / 100.; break; 581 case oPercent: sum = num / 100.; break;
575 case oDivX: 582 case oDivX:
576 if (num == 0) 583 if (num == 0)
577 state = sError; 584 state = sError;
578 else 585 else
579 sum = 1 / num; 586 sum = 1 / num;
580 break; 587 break;
581 case oXsquared: 588 case oXsquared:
582 sum = pow(acc,num); 589 sum = pow(acc,num);
583 break; 590 break;
584 case oChSign: (state == sStart) ? sum = -num : sum = -acc; break; 591 case oChSign: (state == sStart) ? sum = -num : sum = -acc; break;
585 case oSub: sum = acc - num; break; 592 case oSub: sum = acc - num; break;
586 case oMult: sum = acc * num; break; 593 case oMult: sum = acc * num; break;
587 case oAdd: sum = acc + num; break; 594 case oAdd: sum = acc + num; break;
588 case oDiv: { 595 case oDiv: {
589 if (num == 0) { 596 if (num == 0) {
590 state = sError; 597 state = sError;
591 } else { 598 } else {
592 sum = acc / num; 599 sum = acc / num;
593 } 600 }
594 break; 601 break;
595 } 602 }
596 case oRoot: 603 case oRoot:
597 /* the linux library is dumb, and can't to -x to 1/n 604 /* the linux library is dumb, and can't to -x to 1/n
598 when n is odd. (even and error of course is acceptable */ 605 when n is odd. (even and error of course is acceptable */
599 if((acc < 0) && (int(num) == num) && (int(num) % 2 == 1 )) { 606 if((acc < 0) && (int(num) == num) && (int(num) % 2 == 1 )) {
600 sum = pow(-acc, 1 / num); 607 sum = pow(-acc, 1 / num);
601 sum = -sum; 608 sum = -sum;
602 } else { 609 } else {
603 sum = pow(acc, 1 / num); 610 sum = pow(acc, 1 / num);
604 } 611 }
605 break; 612 break;
606 case oLog: 613 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 @@
1/**************************************************************************** 1/****************************************************************************
2 ** formatter.cpp 2 ** formatter.cpp
3 ** 3 **
4 ** Copyright: Thu Apr 11 11:01:13 2002 4 ** Copyright: Thu Apr 11 11:01:13 2002
5 ** by: L. J. Potter 5 ** by: L. J. Potter
6 ** 6 **
7 ****************************************************************************/ 7 ****************************************************************************/
8 8
9#include "formatter.h" 9#include "formatter.h"
10#include "inputDialog.h" 10#include "inputDialog.h"
11#include "output.h" 11#include "output.h"
12 12
13/* OPIE */ 13/* OPIE */
14#include <qtoolbar.h> 14#include <opie2/odebug.h>
15#include <qpe/qpeapplication.h> 15#include <qpe/qpeapplication.h>
16#include <qpe/resource.h> 16#include <qpe/resource.h>
17#include <qpe/config.h> 17#include <qpe/config.h>
18#include <qpe/mimetype.h> 18#include <qpe/mimetype.h>
19#include <qpe/qcopenvelope_qws.h> 19#include <qpe/qcopenvelope_qws.h>
20#include <qpe/storage.h> 20#include <qpe/storage.h>
21using namespace Opie::Core;
21 22
22/* QT */ 23/* QT */
23#include <qmenubar.h> 24#include <qmenubar.h>
24#include <qmultilineedit.h> 25#include <qmultilineedit.h>
25#include <qstring.h> 26#include <qstring.h>
26#include <qlist.h> 27#include <qlist.h>
27#include <qstringlist.h> 28#include <qstringlist.h>
28#include <qdir.h> 29#include <qdir.h>
29#include <qfile.h> 30#include <qfile.h>
30#include <qtstream.h> 31#include <qtstream.h>
31#include <qcombobox.h> 32#include <qcombobox.h>
32#include <qpopupmenu.h> 33#include <qpopupmenu.h>
33#include <qmessagebox.h> 34#include <qmessagebox.h>
34#include <qregexp.h> 35#include <qregexp.h>
35#include <qlabel.h> 36#include <qlabel.h>
36#include <qlineedit.h> 37#include <qlineedit.h>
37#include <qpushbutton.h> 38#include <qpushbutton.h>
39#include <qtoolbar.h>
38#include <qtabwidget.h> 40#include <qtabwidget.h>
39#include <qwidget.h> 41#include <qwidget.h>
40#include <qlayout.h> 42#include <qlayout.h>
41#include <qvariant.h> 43#include <qvariant.h>
42 44
43/* STD */ 45/* STD */
44#include <unistd.h> 46#include <unistd.h>
45#include <stdio.h> 47#include <stdio.h>
46#include <stdlib.h> 48#include <stdlib.h>
47#include <sys/vfs.h> 49#include <sys/vfs.h>
48#include <mntent.h> 50#include <mntent.h>
49#include <string.h> 51#include <string.h>
50#include <errno.h> 52#include <errno.h>
51 53
52#define BLANK ' ' 54#define BLANK ' '
53#define DELIMITER '#' 55#define DELIMITER '#'
54 56
55/* 57/*
56 Blah blah blah blah */ 58 Blah blah blah blah */
57FormatterApp::FormatterApp( QWidget* parent, const char* name, WFlags fl, bool modal ) 59FormatterApp::FormatterApp( QWidget* parent, const char* name, WFlags fl, bool modal )
58 : QMainWindow( parent, name, fl ) 60 : QMainWindow( parent, name, fl )
59 // : QDialog( parent, name, modal, fl ) 61 // : QDialog( parent, name, modal, fl )
60{ 62{
61 if ( !name ) 63 if ( !name )
62 setName( "FormatterApp" ); 64 setName( "FormatterApp" );
63 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 65 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
64 66
65 setCaption( tr( "Formatter" ) ); 67 setCaption( tr( "Formatter" ) );
66 FormatterAppLayout = new QGridLayout( this ); 68 FormatterAppLayout = new QGridLayout( this );
67 FormatterAppLayout->setSpacing( 2); 69 FormatterAppLayout->setSpacing( 2);
68 FormatterAppLayout->setMargin( 2 ); 70 FormatterAppLayout->setMargin( 2 );
69 71
70 TabWidget = new QTabWidget( this, "TabWidget" ); 72 TabWidget = new QTabWidget( this, "TabWidget" );
71 73
72 tab = new QWidget( TabWidget, "tab" ); 74 tab = new QWidget( TabWidget, "tab" );
73 tabLayout = new QGridLayout( tab ); 75 tabLayout = new QGridLayout( tab );
74 tabLayout->setSpacing( 3); 76 tabLayout->setSpacing( 3);
75 tabLayout->setMargin( 2); 77 tabLayout->setMargin( 2);
76 78
77 storageComboBox = new QComboBox( FALSE, tab, "storageComboBox" ); 79 storageComboBox = new QComboBox( FALSE, tab, "storageComboBox" );
78 storageComboBox->setMaximumWidth(220); 80 storageComboBox->setMaximumWidth(220);
79 81
80 tabLayout->addMultiCellWidget( storageComboBox, 0, 0, 0, 1); 82 tabLayout->addMultiCellWidget( storageComboBox, 0, 0, 0, 1);
81 83
82 TextLabel4 = new QLabel( tab, "TextLabel4" ); 84 TextLabel4 = new QLabel( tab, "TextLabel4" );
83 TextLabel4->setText( tr( "Storage Type" ) ); 85 TextLabel4->setText( tr( "Storage Type" ) );
84 86
85 tabLayout->addMultiCellWidget( TextLabel4, 1, 1, 0, 1); 87 tabLayout->addMultiCellWidget( TextLabel4, 1, 1, 0, 1);
86 88
87 TextLabel2 = new QLabel( tab, "TextLabel2" ); 89 TextLabel2 = new QLabel( tab, "TextLabel2" );
88 TextLabel2->setText( tr( "File Systems" ) ); 90 TextLabel2->setText( tr( "File Systems" ) );
89 91
90 tabLayout->addMultiCellWidget( TextLabel2, 4, 4, 0, 1); 92 tabLayout->addMultiCellWidget( TextLabel2, 4, 4, 0, 1);
91 93
92 fileSystemsCombo = new QComboBox( FALSE, tab, "fileSystemsCombo" ); 94 fileSystemsCombo = new QComboBox( FALSE, tab, "fileSystemsCombo" );
93 fileSystemsCombo->setMaximumWidth(220); 95 fileSystemsCombo->setMaximumWidth(220);
94 96
95 tabLayout->addMultiCellWidget( fileSystemsCombo, 3, 3, 0, 1); 97 tabLayout->addMultiCellWidget( fileSystemsCombo, 3, 3, 0, 1);
96 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum ); 98 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum );
97 tabLayout->addItem( spacer, 2, 0 ); 99 tabLayout->addItem( spacer, 2, 0 );
98 100
99 formatPushButton = new QPushButton( tab, "formatPushButton" ); 101 formatPushButton = new QPushButton( tab, "formatPushButton" );
100 formatPushButton->setText( tr( "Format" ) ); 102 formatPushButton->setText( tr( "Format" ) );
101 formatPushButton->setMaximumWidth(170); 103 formatPushButton->setMaximumWidth(170);
102 104
103 tabLayout->addMultiCellWidget( formatPushButton, 6, 6, 0, 1); 105 tabLayout->addMultiCellWidget( formatPushButton, 6, 6, 0, 1);
104 QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum ); 106 QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum );
105 tabLayout->addItem( spacer_2, 5, 0 ); 107 tabLayout->addItem( spacer_2, 5, 0 );
106 108
107 TabWidget->insertTab( tab, tr( "Main" ) ); 109 TabWidget->insertTab( tab, tr( "Main" ) );
108 110
109 tab_2 = new QWidget( TabWidget, "tab_2" ); 111 tab_2 = new QWidget( TabWidget, "tab_2" );
110 tabLayout_2 = new QGridLayout( tab_2 ); 112 tabLayout_2 = new QGridLayout( tab_2 );
111 tabLayout_2->setSpacing(3); 113 tabLayout_2->setSpacing(3);
112 tabLayout_2->setMargin(2); 114 tabLayout_2->setMargin(2);
113 115
114 mountPointLineEdit = new QLineEdit( tab_2, "mountPointLineEdit" ); 116 mountPointLineEdit = new QLineEdit( tab_2, "mountPointLineEdit" );
115 117
116 tabLayout_2->addMultiCellWidget( mountPointLineEdit, 0, 0, 0, 1); 118 tabLayout_2->addMultiCellWidget( mountPointLineEdit, 0, 0, 0, 1);
117 119
118 deviceComboBox = new QComboBox( FALSE, tab_2, "deviceComboBox" ); 120 deviceComboBox = new QComboBox( FALSE, tab_2, "deviceComboBox" );
119 121
120 tabLayout_2->addMultiCellWidget( deviceComboBox, 3, 3, 0, 1); 122 tabLayout_2->addMultiCellWidget( deviceComboBox, 3, 3, 0, 1);
121 123
122 TextLabel5 = new QLabel( tab_2, "TextLabel5" ); 124 TextLabel5 = new QLabel( tab_2, "TextLabel5" );
123 TextLabel5->setText( tr( "CAUTION:\n" 125 TextLabel5->setText( tr( "CAUTION:\n"
124 "Changing parameters on this\n" 126 "Changing parameters on this\n"
125 "page may cause your system\n" 127 "page may cause your system\n"
126 "to stop functioning properly!" ) );//idiot message 128 "to stop functioning properly!" ) );//idiot message
127 129
128 tabLayout_2->addMultiCellWidget( TextLabel5, 6, 6, 0, 1); 130 tabLayout_2->addMultiCellWidget( TextLabel5, 6, 6, 0, 1);
129 131
130 editPushButton = new QPushButton( tab_2, "editPushButton" ); 132 editPushButton = new QPushButton( tab_2, "editPushButton" );
131 editPushButton->setText( tr( "Edit fstab" ) ); 133 editPushButton->setText( tr( "Edit fstab" ) );
132 editPushButton->setMaximumWidth(100); 134 editPushButton->setMaximumWidth(100);
133 135
@@ -145,488 +147,488 @@ FormatterApp::FormatterApp( QWidget* parent, const char* name, WFlags fl, bool
145 tabLayout_2->addMultiCellWidget( TextLabel3, 4, 4, 0, 1 ); 147 tabLayout_2->addMultiCellWidget( TextLabel3, 4, 4, 0, 1 );
146 QSpacerItem* spacer_3 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); 148 QSpacerItem* spacer_3 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
147 tabLayout_2->addItem( spacer_3, 5, 0 ); 149 tabLayout_2->addItem( spacer_3, 5, 0 );
148 150
149 TextLabel1 = new QLabel( tab_2, "TextLabel1" ); 151 TextLabel1 = new QLabel( tab_2, "TextLabel1" );
150 TextLabel1->setText( tr( "Mount Point" ) ); 152 TextLabel1->setText( tr( "Mount Point" ) );
151 153
152 tabLayout_2->addMultiCellWidget( TextLabel1, 1, 1, 0, 1 ); 154 tabLayout_2->addMultiCellWidget( TextLabel1, 1, 1, 0, 1 );
153 QSpacerItem* spacer_4 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); 155 QSpacerItem* spacer_4 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
154 tabLayout_2->addItem( spacer_4, 2, 1 ); 156 tabLayout_2->addItem( spacer_4, 2, 1 );
155 TabWidget->insertTab( tab_2, tr( "Advanced" ) ); 157 TabWidget->insertTab( tab_2, tr( "Advanced" ) );
156 158
157 FormatterAppLayout->addWidget( TabWidget, 0, 1 ); 159 FormatterAppLayout->addWidget( TabWidget, 0, 1 );
158 160
159 connect( formatPushButton ,SIGNAL(released()),this,SLOT( doFormat()) ); 161 connect( formatPushButton ,SIGNAL(released()),this,SLOT( doFormat()) );
160 connect( editPushButton ,SIGNAL(released()),this,SLOT( editFstab()) ); 162 connect( editPushButton ,SIGNAL(released()),this,SLOT( editFstab()) );
161 connect( fsckButton ,SIGNAL(released()),this,SLOT( doFsck()) ); 163 connect( fsckButton ,SIGNAL(released()),this,SLOT( doFsck()) );
162 164
163 connect( fileSystemsCombo,SIGNAL(activated(int)),this,SLOT( fsComboSelected(int) )); 165 connect( fileSystemsCombo,SIGNAL(activated(int)),this,SLOT( fsComboSelected(int) ));
164 connect( storageComboBox,SIGNAL(activated(int)),this,SLOT( storageComboSelected(int) )); 166 connect( storageComboBox,SIGNAL(activated(int)),this,SLOT( storageComboSelected(int) ));
165 connect( deviceComboBox,SIGNAL(activated(int)),this,SLOT( deviceComboSelected(int) )); 167 connect( deviceComboBox,SIGNAL(activated(int)),this,SLOT( deviceComboSelected(int) ));
166 168
167 169
168 fillCombos(); 170 fillCombos();
169} 171}
170 172
171FormatterApp::~FormatterApp() 173FormatterApp::~FormatterApp()
172{} 174{}
173 175
174void FormatterApp::doFormat() 176void FormatterApp::doFormat()
175{ 177{
176 int err=0; 178 int err=0;
177 Output *outDlg; 179 Output *outDlg;
178 QString umountS, remountS; 180 QString umountS, remountS;
179 QString text = storageComboBox->currentText(); 181 QString text = storageComboBox->currentText();
180 QString currentText = storageComboBox->currentText(); 182 QString currentText = storageComboBox->currentText();
181 QString cmd; 183 QString cmd;
182 QString diskDevice = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4); 184 QString diskDevice = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4);
183 QString diskName = currentText.left(currentText.find(" -> ",0,TRUE)); 185 QString diskName = currentText.left(currentText.find(" -> ",0,TRUE));
184 QString fs = fileSystemsCombo->currentText(); 186 QString fs = fileSystemsCombo->currentText();
185 187
186#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) // lets test on something cheap 188#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) // lets test on something cheap
187#else 189#else
188 currentText = diskDevice = "/dev/fd0"; 190 currentText = diskDevice = "/dev/fd0";
189 umountS = "umount -v /floppy 2>&1"; 191 umountS = "umount -v /floppy 2>&1";
190 remountS = "mount -v /floppy 2>&1"; 192 remountS = "mount -v /floppy 2>&1";
191#endif 193#endif
192 194
193 if( currentText.find("CF",0,TRUE) != -1) 195 if( currentText.find("CF",0,TRUE) != -1)
194 { 196 {
195 umountS = "umount "; 197 umountS = "umount ";
196 remountS = "mount "; 198 remountS = "mount ";
197 199
198 // umountS = "/sbin/cardctl eject"; 200 // umountS = "/sbin/cardctl eject";
199 // remountS = "/sbin/cardctl insert"; 201 // remountS = "/sbin/cardctl insert";
200 } 202 }
201 if( currentText.find("SD",0,TRUE) != -1) 203 if( currentText.find("SD",0,TRUE) != -1)
202 { 204 {
203 umountS = "umount "; 205 umountS = "umount ";
204 remountS = "mount "; 206 remountS = "mount ";
205 // umountS = "/etc/sdcontrol compeject"; 207 // umountS = "/etc/sdcontrol compeject";
206 // remountS = "/etc/sdcontrol insert"; 208 // remountS = "/etc/sdcontrol insert";
207 } 209 }
208 210
209 switch ( QMessageBox::warning(this,tr("Format?") 211 switch ( QMessageBox::warning(this,tr("Format?")
210 , tr("Really format\n") +diskName+" "+ currentText + 212 , tr("Really format\n") +diskName+" "+ currentText +
211 tr("\nwith %1 filesystem?\nYou will loose all data!!").arg( fs ) 213 tr("\nwith %1 filesystem?\nYou will loose all data!!").arg( fs )
212 ,tr("Yes") 214 ,tr("Yes")
213 ,tr("No") 215 ,tr("No")
214 ,0 216 ,0
215 ,1 217 ,1
216 ,1) ) 218 ,1) )
217 { 219 {
218 case 0: 220 case 0:
219 { 221 {
220 if(fs == "vfat") 222 if(fs == "vfat")
221 cmd = "mkdosfs -v " + diskDevice+" 2>&1"; 223 cmd = "mkdosfs -v " + diskDevice+" 2>&1";
222 else if(fs == "ext2") 224 else if(fs == "ext2")
223 cmd = "mke2fs -v " + diskDevice+" 2>&1"; 225 cmd = "mke2fs -v " + diskDevice+" 2>&1";
224 else 226 else
225 { 227 {
226 QMessageBox::warning(this, tr("Formatter"),tr("Could not format.\nUnknown type"), tr("Ok")); 228 QMessageBox::warning(this, tr("Formatter"),tr("Could not format.\nUnknown type"), tr("Ok"));
227 break; 229 break;
228 } 230 }
229 // cmd = "ls -l"; 231 // cmd = "ls -l";
230 outDlg = new Output(this, tr("Formatter Output"),FALSE); 232 outDlg = new Output(this, tr("Formatter Output"),FALSE);
231 QPEApplication::showDialog( outDlg); 233 QPEApplication::showDialog( outDlg);
232 qApp->processEvents(); 234 qApp->processEvents();
233 FILE *fp; 235 FILE *fp;
234 char line[130]; 236 char line[130];
235 237
236 238
237 outDlg->OutputEdit->append( tr("Trying to umount %1.").arg( currentText) ); 239 outDlg->OutputEdit->append( tr("Trying to umount %1.").arg( currentText) );
238 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 240 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
239 241
240 sleep(1); 242 sleep(1);
241 qDebug("Command is "+umountS); 243 odebug << "Command is "+umountS << oendl;
242 fp = popen( (const char *) umountS, "r"); 244 fp = popen( (const char *) umountS, "r");
243 // qDebug("%d", fp); 245 // odebug << "" << fp << "" << oendl;
244 if ( !fp ) 246 if ( !fp )
245 { 247 {
246 qDebug("Could not execute '" + umountS + "'! err=%d\n" +(QString)strerror(errno), err); 248 odebug << "Could not execute '" + umountS + "'! err=" << err << "\n" +(QString)strerror(errno) << oendl;
247 QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") ); 249 QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") );
248 pclose(fp); 250 pclose(fp);
249 return; 251 return;
250 } 252 }
251 else 253 else
252 { 254 {
253 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted.")); 255 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted."));
254 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 256 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
255 while ( fgets( line, sizeof line, fp)) 257 while ( fgets( line, sizeof line, fp))
256 { 258 {
257 if( ((QString)line).find("busy",0,TRUE) != -1) 259 if( ((QString)line).find("busy",0,TRUE) != -1)
258 { 260 {
259 qDebug("Could not find '" + umountS); 261 odebug << "Could not find '" + umountS << oendl;
260 QMessageBox::warning( this, tr("Formatter"), tr("Could not umount.\nDevice is busy!"), tr("&OK") ); 262 QMessageBox::warning( this, tr("Formatter"), tr("Could not umount.\nDevice is busy!"), tr("&OK") );
261 pclose(fp); 263 pclose(fp);
262 return; 264 return;
263 } 265 }
264 else 266 else
265 { 267 {
266 QString lineStr = line; 268 QString lineStr = line;
267 lineStr=lineStr.left(lineStr.length()-1); 269 lineStr=lineStr.left(lineStr.length()-1);
268 outDlg->OutputEdit->append(lineStr); 270 outDlg->OutputEdit->append(lineStr);
269 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 271 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
270 } 272 }
271 } 273 }
272 } 274 }
273 pclose(fp); 275 pclose(fp);
274 276
275 qDebug("Command would be: "+cmd); 277 odebug << "Command would be: "+cmd << oendl;
276 outDlg->OutputEdit->append( tr("Trying to format.") ); 278 outDlg->OutputEdit->append( tr("Trying to format.") );
277 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 279 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
278 280
279 fp = popen( (const char *) cmd, "r"); 281 fp = popen( (const char *) cmd, "r");
280 while ( fgets( line, sizeof line, fp)) 282 while ( fgets( line, sizeof line, fp))
281 { 283 {
282 if( ((QString)line).find("No such device",0,TRUE) != -1) 284 if( ((QString)line).find("No such device",0,TRUE) != -1)
283 { 285 {
284 qDebug("No such device '" + umountS); 286 odebug << "No such device '" + umountS << oendl;
285 QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") ); 287 QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") );
286 pclose(fp); 288 pclose(fp);
287 // outDlg->OutputEdit->append("No such device"); 289 // outDlg->OutputEdit->append("No such device");
288 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 290 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
289 return; 291 return;
290 } 292 }
291 else 293 else
292 { 294 {
293 QString lineStr = line; 295 QString lineStr = line;
294 lineStr=lineStr.left(lineStr.length()-1); 296 lineStr=lineStr.left(lineStr.length()-1);
295 outDlg->OutputEdit->append(lineStr); 297 outDlg->OutputEdit->append(lineStr);
296 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 298 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
297 } 299 }
298 } 300 }
299 outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted.")); 301 outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted."));
300 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 302 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
301 pclose(fp); 303 pclose(fp);
302 304
303 outDlg->OutputEdit->append( tr("Trying to mount %1.").arg( currentText) ); 305 outDlg->OutputEdit->append( tr("Trying to mount %1.").arg( currentText) );
304 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 306 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
305 fp = popen( (const char *) remountS, "r"); 307 fp = popen( (const char *) remountS, "r");
306 if ( !fp) 308 if ( !fp)
307 { 309 {
308 qDebug("Could not execute '" + remountS + "'! err=%d\n" +(QString)strerror(errno), err); 310 odebug << "Could not execute '" + remountS + "'! err=" << err << "\n" +(QString)strerror(errno) << oendl;
309 QMessageBox::warning( this, tr("Formatter"), tr("Card mount failed!"), tr("&OK") ); 311 QMessageBox::warning( this, tr("Formatter"), tr("Card mount failed!"), tr("&OK") );
310 312
311 } 313 }
312 else 314 else
313 { 315 {
314 outDlg->OutputEdit->append(tr("%1\nhas been successfully mounted.").arg( currentText )); 316 outDlg->OutputEdit->append(tr("%1\nhas been successfully mounted.").arg( currentText ));
315 while ( fgets( line, sizeof line, fp)) 317 while ( fgets( line, sizeof line, fp))
316 { 318 {
317 QString lineStr = line; 319 QString lineStr = line;
318 lineStr=lineStr.left(lineStr.length()-1); 320 lineStr=lineStr.left(lineStr.length()-1);
319 outDlg->OutputEdit->append(lineStr); 321 outDlg->OutputEdit->append(lineStr);
320 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 322 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
321 } 323 }
322 } 324 }
323 pclose(fp); 325 pclose(fp);
324 sleep(1); 326 sleep(1);
325 327
326 outDlg->OutputEdit->append(tr("You can now close the output window.")); 328 outDlg->OutputEdit->append(tr("You can now close the output window."));
327 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 329 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
328 // outDlg->close(); 330 // outDlg->close();
329 // if(outDlg) 331 // if(outDlg)
330 // delete outDlg; 332 // delete outDlg;
331 } 333 }
332 break; 334 break;
333 }; 335 };
334} 336}
335 337
336bool FormatterApp::doFdisk() 338bool FormatterApp::doFdisk()
337{ 339{
338 return FALSE; 340 return FALSE;
339 341
340} 342}
341 343
342void FormatterApp::fillCombos() 344void FormatterApp::fillCombos()
343{ 345{
344 346
345 StorageInfo storageInfo; 347 StorageInfo storageInfo;
346 const QList<FileSystem> &fs = storageInfo.fileSystems(); 348 const QList<FileSystem> &fs = storageInfo.fileSystems();
347 QListIterator<FileSystem> it ( fs ); 349 QListIterator<FileSystem> it ( fs );
348 QString storage; 350 QString storage;
349 for( ; it.current(); ++it ) 351 for( ; it.current(); ++it )
350 { 352 {
351 const QString name = (*it)->name(); 353 const QString name = (*it)->name();
352 const QString path = (*it)->path(); 354 const QString path = (*it)->path();
353 const QString disk = (*it)->disk(); 355 const QString disk = (*it)->disk();
354 const QString options = (*it)->options(); 356 const QString options = (*it)->options();
355 if( name.find( tr("Internal"),0,TRUE) == -1) 357 if( name.find( tr("Internal"),0,TRUE) == -1)
356 { 358 {
357 storageComboBox->insertItem(name +" -> "+disk); 359 storageComboBox->insertItem(name +" -> "+disk);
358 } 360 }
359 // deviceComboBox->insertItem(disk); 361 // deviceComboBox->insertItem(disk);
360 } 362 }
361 parsetab("/etc/mtab"); 363 parsetab("/etc/mtab");
362 // parsetab("/etc/fstab"); 364 // parsetab("/etc/fstab");
363 fileSystemsCombo->insertStringList( fsList,-1); 365 fileSystemsCombo->insertStringList( fsList,-1);
364 deviceComboBox->insertStringList( deviceList,-1); 366 deviceComboBox->insertStringList( deviceList,-1);
365 storageComboSelected(0); 367 storageComboSelected(0);
366 deviceComboSelected(0); 368 deviceComboSelected(0);
367} 369}
368 370
369 371
370void FormatterApp::fsComboSelected(int ) 372void FormatterApp::fsComboSelected(int )
371{} 373{}
372 374
373void FormatterApp::storageComboSelected(int index ) 375void FormatterApp::storageComboSelected(int index )
374{ 376{
375 377
376 QString currentText = storageComboBox->text(index); 378 QString currentText = storageComboBox->text(index);
377 QString nameS = currentText.left( currentText.find("->",0,TRUE)); 379 QString nameS = currentText.left( currentText.find("->",0,TRUE));
378 380
379 TextLabel4->setText( tr( "Storage Type: %1").arg( nameS) ); 381 TextLabel4->setText( tr( "Storage Type: %1").arg( nameS) );
380 currentText = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4); 382 currentText = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4);
381 383
382 QString fsType = getFileSystemType((const QString &) currentText); 384 QString fsType = getFileSystemType((const QString &) currentText);
383 // qDebug(fsType); 385 // odebug << fsType << oendl;
384 for(int i = 0; i < fileSystemsCombo->count(); i++) 386 for(int i = 0; i < fileSystemsCombo->count(); i++)
385 { 387 {
386 if( fsType == fileSystemsCombo->text(i)) 388 if( fsType == fileSystemsCombo->text(i))
387 fileSystemsCombo->setCurrentItem(i); 389 fileSystemsCombo->setCurrentItem(i);
388 } 390 }
389 // deviceComboSelected(index); 391 // deviceComboSelected(index);
390} 392}
391 393
392void FormatterApp::deviceComboSelected(int index) 394void FormatterApp::deviceComboSelected(int index)
393{ 395{
394 396
395 StorageInfo storageInfo; 397 StorageInfo storageInfo;
396 QString totalS, usedS, avS, diskS, nameS, fsType, selectedText; 398 QString totalS, usedS, avS, diskS, nameS, fsType, selectedText;
397 399
398 selectedText = deviceComboBox->text(index); 400 selectedText = deviceComboBox->text(index);
399 401
400 const QList<FileSystem> &fs = storageInfo.fileSystems(); 402 const QList<FileSystem> &fs = storageInfo.fileSystems();
401 QListIterator<FileSystem> it ( fs ); 403 QListIterator<FileSystem> it ( fs );
402 QString storage; 404 QString storage;
403 for( ; it.current(); ++it ) 405 for( ; it.current(); ++it )
404 { 406 {
405 const QString name = (*it)->name(); 407 const QString name = (*it)->name();
406 const QString path = (*it)->path(); 408 const QString path = (*it)->path();
407 const QString disk = (*it)->disk(); 409 const QString disk = (*it)->disk();
408 // const QString options = (*it)->options(); 410 // const QString options = (*it)->options();
409 if( selectedText == disk) 411 if( selectedText == disk)
410 { 412 {
411 diskS = disk; nameS= name; 413 diskS = disk; nameS= name;
412 mountPointLineEdit->setText(path); 414 mountPointLineEdit->setText(path);
413 long mult = (*it)->blockSize() / 1024; 415 long mult = (*it)->blockSize() / 1024;
414 long div = 1024 / (*it)->blockSize(); 416 long div = 1024 / (*it)->blockSize();
415 if ( !mult ) mult = 1; 417 if ( !mult ) mult = 1;
416 if ( !div ) div = 1; 418 if ( !div ) div = 1;
417 long total = (*it)->totalBlocks() * mult / div; 419 long total = (*it)->totalBlocks() * mult / div;
418 long totalMb = total/1024; 420 long totalMb = total/1024;
419 long avail = (*it)->availBlocks() * mult / div; 421 long avail = (*it)->availBlocks() * mult / div;
420 long availMb = avail/1024; 422 long availMb = avail/1024;
421 long used = total - avail; 423 long used = total - avail;
422 long usedMb = used/1024; 424 long usedMb = used/1024;
423 totalS.sprintf(tr("Total: %1 kB ( %d mB)\n").arg( total ), totalMb ); 425 totalS.sprintf(tr("Total: %1 kB ( %d mB)\n").arg( total ), totalMb );
424 usedS.sprintf(tr("Used: %1 kB ( %d mB)\n").arg(used) ,usedMb); 426 usedS.sprintf(tr("Used: %1 kB ( %d mB)\n").arg(used) ,usedMb);
425 avS.sprintf( tr("Available: %1 kB ( %d mB)").arg(avail), availMb ); 427 avS.sprintf( tr("Available: %1 kB ( %d mB)").arg(avail), availMb );
426 } 428 }
427 } 429 }
428 fsType = getFileSystemType((const QString &)selectedText); 430 fsType = getFileSystemType((const QString &)selectedText);
429 431
430 TextLabel5->setText(tr("Type: %1\nFormatted with %2\n%3, %4, %5").arg( nameS).arg( fsType).arg(totalS).arg( usedS).arg( avS )); 432 TextLabel5->setText(tr("Type: %1\nFormatted with %2\n%3, %4, %5").arg( nameS).arg( fsType).arg(totalS).arg( usedS).arg( avS ));
431 TextLabel5->setTextFormat( Qt::RichText ); 433 TextLabel5->setTextFormat( Qt::RichText );
432 // storageComboSelected(0); 434 // storageComboSelected(0);
433} 435}
434 436
435void FormatterApp::cleanUp() 437void FormatterApp::cleanUp()
436{} 438{}
437 439
438 440
439void FormatterApp::editFstab() 441void FormatterApp::editFstab()
440{ 442{
441 QCopEnvelope e("QPE/Application/textedit","setDocument(QString)"); 443 QCopEnvelope e("QPE/Application/textedit","setDocument(QString)");
442 e << (const QString &)"/etc/fstab"; 444 e << (const QString &)"/etc/fstab";
443} 445}
444 446
445void FormatterApp::parsetab(const QString &fileName) 447void FormatterApp::parsetab(const QString &fileName)
446{ 448{
447 449
448 fileSystemTypeList.clear(); 450 fileSystemTypeList.clear();
449 fsList.clear(); 451 fsList.clear();
450 struct mntent *me; 452 struct mntent *me;
451 // if(fileName == "/etc/mtab") { 453 // if(fileName == "/etc/mtab") {
452 FILE *mntfp = setmntent( fileName.latin1(), "r" ); 454 FILE *mntfp = setmntent( fileName.latin1(), "r" );
453 if ( mntfp ) 455 if ( mntfp )
454 { 456 {
455 while ( (me = getmntent( mntfp )) != 0 ) 457 while ( (me = getmntent( mntfp )) != 0 )
456 { 458 {
457 QString deviceName = me->mnt_fsname; 459 QString deviceName = me->mnt_fsname;
458 QString filesystemType = me->mnt_type; 460 QString filesystemType = me->mnt_type;
459 if(deviceName != "none") 461 if(deviceName != "none")
460 { 462 {
461 if( fsList.contains(filesystemType) == 0 463 if( fsList.contains(filesystemType) == 0
462 & filesystemType.find("proc",0,TRUE) == -1 464 & filesystemType.find("proc",0,TRUE) == -1
463 & filesystemType.find("cramfs",0,TRUE) == -1 465 & filesystemType.find("cramfs",0,TRUE) == -1
464 & filesystemType.find("auto",0,TRUE) == -1) 466 & filesystemType.find("auto",0,TRUE) == -1)
465 fsList << filesystemType; 467 fsList << filesystemType;
466 deviceList << deviceName; 468 deviceList << deviceName;
467 qDebug(deviceName+"::"+filesystemType); 469 odebug << deviceName+"::"+filesystemType << oendl;
468 fileSystemTypeList << deviceName+"::"+filesystemType; 470 fileSystemTypeList << deviceName+"::"+filesystemType;
469 } 471 }
470 } 472 }
471 } 473 }
472 endmntent( mntfp ); 474 endmntent( mntfp );
473 // } else if(fileName == "/etc/fstab") { 475 // } else if(fileName == "/etc/fstab") {
474 // QFile f("/etc/fstab"); 476 // QFile f("/etc/fstab");
475 // if ( f.open(IO_ReadOnly) ) { 477 // if ( f.open(IO_ReadOnly) ) {
476 // QTextStream t (&f); 478 // QTextStream t (&f);
477 // QString s; 479 // QString s;
478 // while (! t.eof()) { 480 // while (! t.eof()) {
479 // s=t.readLine(); 481 // s=t.readLine();
480 // s=s.simplifyWhiteSpace(); 482 // s=s.simplifyWhiteSpace();
481 // if ( (!s.isEmpty() ) && (s.find(" ")!=0) ) { 483 // if ( (!s.isEmpty() ) && (s.find(" ")!=0) ) {
482 // // = me->mnt_fsname; 484 // // = me->mnt_fsname;
483 // QString filesystemType = me->mnt_type; 485 // QString filesystemType = me->mnt_type;
484 // QString deviceName = s.left(0,s.find(BLANK) ); 486 // QString deviceName = s.left(0,s.find(BLANK) );
485 // s=s.remove(0,s.find(BLANK)+1 ); // devicename 487 // s=s.remove(0,s.find(BLANK)+1 ); // devicename
486 488
487 // s=s.remove(0,s.find(BLANK)+1 ); // mountpoint 489 // s=s.remove(0,s.find(BLANK)+1 ); // mountpoint
488 // QStringt mountPoint= s.left(0,s.find(BLANK) ); 490 // QStringt mountPoint= s.left(0,s.find(BLANK) );
489 // s=s.remove(0,s.find(BLANK)+1 ); // fs 491 // s=s.remove(0,s.find(BLANK)+1 ); // fs
490 // QString filesystemType= s.left(0,s.find(BLANK) ); 492 // QString filesystemType= s.left(0,s.find(BLANK) );
491 // } 493 // }
492 // } 494 // }
493 // } 495 // }
494 // f.close(); 496 // f.close();
495 // } 497 // }
496} 498}
497 499
498QString FormatterApp::getFileSystemType(const QString &currentText) 500QString FormatterApp::getFileSystemType(const QString &currentText)
499{ 501{
500 502
501 parsetab("/etc/mtab"); //why did TT forget filesystem type? 503 parsetab("/etc/mtab"); //why did TT forget filesystem type?
502 504
503 for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it ) 505 for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it )
504 { 506 {
505 QString temp = (*it); 507 QString temp = (*it);
506 if( temp.find( currentText,0,TRUE) != -1) 508 if( temp.find( currentText,0,TRUE) != -1)
507 { 509 {
508 return temp.right( temp.length() - temp.find("::",0,TRUE) - 2); 510 return temp.right( temp.length() - temp.find("::",0,TRUE) - 2);
509 // qDebug(fsType); 511 // odebug << fsType << oendl;
510 } 512 }
511 } 513 }
512 return ""; 514 return "";
513} 515}
514 516
515bool FormatterApp::doFsck() 517bool FormatterApp::doFsck()
516{ 518{
517 519
518 Output *outDlg; 520 Output *outDlg;
519 QString selectedDevice; 521 QString selectedDevice;
520 // #if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) 522 // #if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX)
521 selectedDevice = deviceComboBox->currentText(); 523 selectedDevice = deviceComboBox->currentText();
522 QString mountPoint = mountPointLineEdit->text(); 524 QString mountPoint = mountPointLineEdit->text();
523 QString umountS = "umount -v "+mountPoint+" 2>&1"; 525 QString umountS = "umount -v "+mountPoint+" 2>&1";
524 QString remountS = "mount -v "+mountPoint+" 2>&1"; 526 QString remountS = "mount -v "+mountPoint+" 2>&1";
525 // #else 527 // #else
526 // // for testing 528 // // for testing
527 // // currentText = diskDevice = "/dev/fd0"; 529 // // currentText = diskDevice = "/dev/fd0";
528 // QString umountS = "umount -v /floppy 2>&1"; 530 // QString umountS = "umount -v /floppy 2>&1";
529 // QString remountS = "mount -v /floppy 2>&1"; 531 // QString remountS = "mount -v /floppy 2>&1";
530 // selectedDevice ="/dev/fd0"; 532 // selectedDevice ="/dev/fd0";
531 533
532 // #endif 534 // #endif
533 535
534 QString fsType = getFileSystemType((const QString &)selectedDevice); 536 QString fsType = getFileSystemType((const QString &)selectedDevice);
535 QString cmd; 537 QString cmd;
536 qDebug( selectedDevice +" "+ fsType); 538 odebug << selectedDevice +" "+ fsType << oendl;
537 if(fsType == "vfat") cmd = "dosfsck -vy "; 539 if(fsType == "vfat") cmd = "dosfsck -vy ";
538 if(fsType == "ext2") cmd = "e2fsck -cpvy "; 540 if(fsType == "ext2") cmd = "e2fsck -cpvy ";
539 cmd += selectedDevice + " 2>&1"; 541 cmd += selectedDevice + " 2>&1";
540 542
541 outDlg = new Output(this, tr("Formatter Output"),FALSE); 543 outDlg = new Output(this, tr("Formatter Output"),FALSE);
542 QPEApplication::showDialog( outDlg ); 544 QPEApplication::showDialog( outDlg );
543 qApp->processEvents(); 545 qApp->processEvents();
544 FILE *fp; 546 FILE *fp;
545 char line[130]; 547 char line[130];
546 outDlg->OutputEdit->append( tr("Trying to umount.")); 548 outDlg->OutputEdit->append( tr("Trying to umount."));
547 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 549 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
548 550
549 sleep(1); 551 sleep(1);
550 // qDebug("Command is "+umountS); 552 // odebug << "Command is "+umountS << oendl;
551 fp = popen( (const char *) umountS, "r"); 553 fp = popen( (const char *) umountS, "r");
552 // qDebug("%d", fp); 554 // odebug << "" << fp << "" << oendl;
553 if ( !fp ) 555 if ( !fp )
554 { 556 {
555 qDebug("Could not execute '" + umountS + "'!\n" +(QString)strerror(errno)); 557 odebug << "Could not execute '" + umountS + "'!\n" +(QString)strerror(errno) << oendl;
556 QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") ); 558 QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") );
557 pclose(fp); 559 pclose(fp);
558 return false; 560 return false;
559 } 561 }
560 else 562 else
561 { 563 {
562 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted.")); 564 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted."));
563 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 565 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
564 while ( fgets( line, sizeof line, fp)) 566 while ( fgets( line, sizeof line, fp))
565 { 567 {
566 if( ((QString)line).find("busy",0,TRUE) != -1) 568 if( ((QString)line).find("busy",0,TRUE) != -1)
567 { 569 {
568 qDebug("Could not find '" + umountS); 570 odebug << "Could not find '" + umountS << oendl;
569 QMessageBox::warning( this, tr("Formatter"), 571 QMessageBox::warning( this, tr("Formatter"),
570 tr("Could not umount.\nDevice is busy!"), tr("&OK") ); 572 tr("Could not umount.\nDevice is busy!"), tr("&OK") );
571 pclose(fp); 573 pclose(fp);
572 return false; 574 return false;
573 } 575 }
574 else 576 else
575 { 577 {
576 QString lineStr = line; 578 QString lineStr = line;
577 lineStr=lineStr.left(lineStr.length()-1); 579 lineStr=lineStr.left(lineStr.length()-1);
578 outDlg->OutputEdit->append(lineStr); 580 outDlg->OutputEdit->append(lineStr);
579 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 581 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
580 } 582 }
581 } 583 }
582 } 584 }
583 pclose(fp); 585 pclose(fp);
584 ///////////////////////////////////// 586 /////////////////////////////////////
585 fp = popen( (const char *) cmd, "r"); 587 fp = popen( (const char *) cmd, "r");
586 while ( fgets( line, sizeof line, fp)) 588 while ( fgets( line, sizeof line, fp))
587 { 589 {
588 if( ((QString)line).find("No such device",0,TRUE) != -1) 590 if( ((QString)line).find("No such device",0,TRUE) != -1)
589 { 591 {
590 qDebug("No such device '" + umountS); 592 odebug << "No such device '" + umountS << oendl;
591 QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") ); 593 QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") );
592 pclose(fp); 594 pclose(fp);
593 // outDlg->OutputEdit->append("No such device"); 595 // outDlg->OutputEdit->append("No such device");
594 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 596 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
595 return false; 597 return false;
596 } 598 }
597 else 599 else
598 { 600 {
599 QString lineStr = line; 601 QString lineStr = line;
600 lineStr=lineStr.left(lineStr.length()-1); 602 lineStr=lineStr.left(lineStr.length()-1);
601 outDlg->OutputEdit->append(lineStr); 603 outDlg->OutputEdit->append(lineStr);
602 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 604 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
603 } 605 }
604 } 606 }
605 outDlg->OutputEdit->append(tr("You can now close the output window.")); 607 outDlg->OutputEdit->append(tr("You can now close the output window."));
606 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 608 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
607 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted.")); 609 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted."));
608 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 610 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
609 pclose(fp); 611 pclose(fp);
610 612
611 ///////////////////////////////////////// 613 /////////////////////////////////////////
612 614
613 return true; 615 return true;
614} 616}
615 617
616bool FormatterApp::doFsckCheck() 618bool FormatterApp::doFsckCheck()
617{ 619{
618 620
619 return FALSE; 621 return FALSE;
620} 622}
621 623
622int FormatterApp::formatCheck(const QString &) 624int FormatterApp::formatCheck(const QString &)
623{ 625{
624 626
625 return -1; 627 return -1;
626} 628}
627 629
628int FormatterApp::runCommand(const QString &) 630int FormatterApp::runCommand(const QString &)
629{ 631{
630 632
631 return -1; 633 return -1;
632} 634}
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 @@
1CONFIG += qt warn_on quick-app 1CONFIG += qt warn_on quick-app
2HEADERS = formatter.h inputDialog.h output.h 2HEADERS = formatter.h inputDialog.h output.h
3SOURCES = formatter.cpp inputDialog.cpp output.cpp main.cpp 3SOURCES = formatter.cpp inputDialog.cpp output.cpp main.cpp
4TARGET = formatter 4TARGET = formatter
5INCLUDEPATH += $(OPIEDIR)/include 5INCLUDEPATH += $(OPIEDIR)/include
6DEPENDPATH += $(OPIEDIR)/include 6DEPENDPATH += $(OPIEDIR)/include
7LIBS += -lqpe -lopiecore2 7LIBS += -lqpe -lopiecore2
8 8
9include ( $(OPIEDIR)/include.pro ) 9include ( $(OPIEDIR)/include.pro )