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,434 +1,439 @@
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)
313 { 318 {
314 Swapfile::swapPath1->insert("/home/swapfile"); 319 Swapfile::swapPath1->insert("/home/swapfile");
315 } 320 }
316 if (Swapfile::sdRB->isChecked() == TRUE) 321 if (Swapfile::sdRB->isChecked() == TRUE)
317 { 322 {
318 Swapfile::swapPath1->insert("/mnt/card/swapfile"); 323 Swapfile::swapPath1->insert("/mnt/card/swapfile");
319 } 324 }
320 if (Swapfile::cfRB->isChecked() == TRUE) 325 if (Swapfile::cfRB->isChecked() == TRUE)
321 { 326 {
322 Swapfile::swapPath1->insert("/mnt/cf/swapfile"); 327 Swapfile::swapPath1->insert("/mnt/cf/swapfile");
323 } 328 }
324 /*Swapfile::swapPath->insert(Swapfile::swapPath1->text());*/ 329 /*Swapfile::swapPath->insert(Swapfile::swapPath1->text());*/
325} 330}
326 331
327void Swapfile::makeswapfile() 332void Swapfile::makeswapfile()
328{ 333{
329 int i = swapSize->currentItem(); 334 int i = swapSize->currentItem();
330 335
331 mkswapProgress->setProgress(1); 336 mkswapProgress->setProgress(1);
332 switch ( i ) { 337 switch ( i ) {
333 case 0: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=2048").arg(swapPath1->text())); 338 case 0: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=2048").arg(swapPath1->text()));
334 break; 339 break;
335 case 1: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=4096").arg(swapPath1->text())); 340 case 1: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=4096").arg(swapPath1->text()));
336 break; 341 break;
337 case 2: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=6144").arg(swapPath1->text())); 342 case 2: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=6144").arg(swapPath1->text()));
338 break; 343 break;
339 case 3: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=8192").arg(swapPath1->text())); 344 case 3: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=8192").arg(swapPath1->text()));
340 break; 345 break;
341 } 346 }
342 if (rc != 0) { 347 if (rc != 0) {
343 setStatusMessage(tr("Failed to create swapfile."), true); 348 setStatusMessage(tr("Failed to create swapfile."), true);
344 } 349 }
345 350
346 mkswapProgress->setProgress(2); 351 mkswapProgress->setProgress(2);
347 rc=exec(QString("mkswap %1").arg(swapPath1->text())); 352 rc=exec(QString("mkswap %1").arg(swapPath1->text()));
348 if (rc != 0) { 353 if (rc != 0) {
349 setStatusMessage(tr("Failed to initialize swapfile."), true); 354 setStatusMessage(tr("Failed to initialize swapfile."), true);
350 } 355 }
351 mkswapProgress->setProgress(3); 356 mkswapProgress->setProgress(3);
352 mkswapProgress->reset(); 357 mkswapProgress->reset();
353 setStatusMessage(tr("Swapfile created.")); 358 setStatusMessage(tr("Swapfile created."));
354} 359}
355 360
356void Swapfile::removeswapfile() 361void Swapfile::removeswapfile()
357{ 362{
358 exec(QString("swapoff %1").arg(swapPath1->text())); 363 exec(QString("swapoff %1").arg(swapPath1->text()));
359 rc=exec(QString("rm -rf %1").arg(swapPath1->text())); 364 rc=exec(QString("rm -rf %1").arg(swapPath1->text()));
360 if (rc != 0) { 365 if (rc != 0) {
361 setStatusMessage(tr("Failed to remove swapfile."), true); 366 setStatusMessage(tr("Failed to remove swapfile."), true);
362 } 367 }
363 Swapfile::status(); 368 Swapfile::status();
364 Swapfile::cfsdchecked(); 369 Swapfile::cfsdchecked();
365 setStatusMessage(tr("Swapfile removed.")); 370 setStatusMessage(tr("Swapfile removed."));
366} 371}
367 372
368void Swapfile::status() 373void Swapfile::status()
369{ 374{
370 FILE *fp; 375 FILE *fp;
371 char buffer[128], swapfile[128], temp[128]; 376 char buffer[128], swapfile[128], temp[128];
372 int swapsize=2000, i=1; 377 int swapsize=2000, i=1;
373 378
374 fp=fopen("/proc/swaps", "r"); 379 fp=fopen("/proc/swaps", "r");
375 while ( (fgets(buffer,128,fp)) != NULL ) { 380 while ( (fgets(buffer,128,fp)) != NULL ) {
376 sscanf(buffer, "%s %s %d %s %s\n", swapfile, temp, &swapsize, temp, temp); 381 sscanf(buffer, "%s %s %d %s %s\n", swapfile, temp, &swapsize, temp, temp);
377 } 382 }
378 fclose(fp); 383 fclose(fp);
379 384
380 ramRB->setChecked(FALSE); 385 ramRB->setChecked(FALSE);
381 cfRB->setChecked(FALSE); 386 cfRB->setChecked(FALSE);
382 sdRB->setChecked(FALSE); 387 sdRB->setChecked(FALSE);
383 388
384 i=strcmp(swapfile, "/home/swapfile"); 389 i=strcmp(swapfile, "/home/swapfile");
385 if ( i == 0 ) { 390 if ( i == 0 ) {
386 ramRB->setChecked(TRUE); 391 ramRB->setChecked(TRUE);
387 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 392 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
388 setStatusMessage(tr("Swapfile activated.")); 393 setStatusMessage(tr("Swapfile activated."));
389 } 394 }
390 i=strcmp(swapfile, "/usr/mnt.rom/cf/swapfile"); 395 i=strcmp(swapfile, "/usr/mnt.rom/cf/swapfile");
391 if ( i == 0 ) { 396 if ( i == 0 ) {
392 cfRB->setChecked(TRUE); 397 cfRB->setChecked(TRUE);
393 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 398 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
394 setStatusMessage(tr("Swapfile activated.")); 399 setStatusMessage(tr("Swapfile activated."));
395 } 400 }
396 i=strcmp(swapfile, "/mnt/cf/swapfile"); 401 i=strcmp(swapfile, "/mnt/cf/swapfile");
397 if ( i == 0 ) { 402 if ( i == 0 ) {
398 cfRB->setChecked(TRUE); 403 cfRB->setChecked(TRUE);
399 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 404 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
400 setStatusMessage(tr("Swapfile activated.")); 405 setStatusMessage(tr("Swapfile activated."));
401 } 406 }
402 i=strcmp(swapfile, "/usr/mnt.rom/card/swapfile"); 407 i=strcmp(swapfile, "/usr/mnt.rom/card/swapfile");
403 if ( i == 0 ) { 408 if ( i == 0 ) {
404 sdRB->setChecked(TRUE); 409 sdRB->setChecked(TRUE);
405 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 410 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
406 setStatusMessage(tr("Swapfile activated.")); 411 setStatusMessage(tr("Swapfile activated."));
407 } 412 }
408 i=strcmp(swapfile, "/mnt/card/swapfile"); 413 i=strcmp(swapfile, "/mnt/card/swapfile");
409 if ( i == 0 ) { 414 if ( i == 0 ) {
410 sdRB->setChecked(TRUE); 415 sdRB->setChecked(TRUE);
411 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 416 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
412 setStatusMessage(tr("Swapfile activated.")); 417 setStatusMessage(tr("Swapfile activated."));
413 } 418 }
414 419
415 Swapfile::cfsdchecked(); 420 Swapfile::cfsdchecked();
416 421
417 422
418 swapsize /=1000; 423 swapsize /=1000;
419 424
420 switch ( swapsize ) { 425 switch ( swapsize ) {
421 case 2: swapSize->setCurrentItem(0); 426 case 2: swapSize->setCurrentItem(0);
422 break; 427 break;
423 case 4: swapSize->setCurrentItem(1); 428 case 4: swapSize->setCurrentItem(1);
424 break; 429 break;
425 case 6: swapSize->setCurrentItem(2); 430 case 6: swapSize->setCurrentItem(2);
426 break; 431 break;
427 case 8: swapSize->setCurrentItem(3); 432 case 8: swapSize->setCurrentItem(3);
428 break; 433 break;
429 } 434 }
430 435
431 436
432} 437}
433 438
434 439
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,885 +1,885 @@
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);
480 populateView(); 480 populateView();
481 update(); 481 update();
482} 482}
483 483
484void AdvancedFm::parsetab(const QString &fileName) { 484void AdvancedFm::parsetab(const QString &fileName) {
485 485
486 fileSystemTypeList.clear(); 486 fileSystemTypeList.clear();
487 fsList.clear(); 487 fsList.clear();
488 struct mntent *me; 488 struct mntent *me;
489 FILE *mntfp = setmntent( fileName.latin1(), "r" ); 489 FILE *mntfp = setmntent( fileName.latin1(), "r" );
490 if ( mntfp ) { 490 if ( mntfp ) {
491 while ( (me = getmntent( mntfp )) != 0 ) { 491 while ( (me = getmntent( mntfp )) != 0 ) {
492 QString deviceName = me->mnt_fsname; 492 QString deviceName = me->mnt_fsname;
493 QString filesystemType = me->mnt_type; 493 QString filesystemType = me->mnt_type;
494 QString mountDir = me->mnt_dir; 494 QString mountDir = me->mnt_dir;
495 if(deviceName != "none") { 495 if(deviceName != "none") {
496 if( fsList.contains(filesystemType) == 0 496 if( fsList.contains(filesystemType) == 0
497 & filesystemType.find("proc",0,TRUE) == -1 497 & filesystemType.find("proc",0,TRUE) == -1
498 & filesystemType.find("cramfs",0,TRUE) == -1 498 & filesystemType.find("cramfs",0,TRUE) == -1
499 & filesystemType.find("auto",0,TRUE) == -1) 499 & filesystemType.find("auto",0,TRUE) == -1)
500 fsList << filesystemType; 500 fsList << filesystemType;
501 fileSystemTypeList << mountDir+"::"+filesystemType; 501 fileSystemTypeList << mountDir+"::"+filesystemType;
502 } 502 }
503 } 503 }
504 } 504 }
505 endmntent( mntfp ); 505 endmntent( mntfp );
506} 506}
507 507
508QString AdvancedFm::getFileSystemType(const QString &currentText) { 508QString AdvancedFm::getFileSystemType(const QString &currentText) {
509 parsetab("/etc/mtab"); //why did TT forget filesystem type? 509 parsetab("/etc/mtab"); //why did TT forget filesystem type?
510 QString current = currentText;//.right( currentText.length()-1); 510 QString current = currentText;//.right( currentText.length()-1);
511 QString baseFs; 511 QString baseFs;
512 for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it ) { 512 for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it ) {
513 QString temp = (*it); 513 QString temp = (*it);
514 QString path = temp.left(temp.find("::",0,TRUE) ); 514 QString path = temp.left(temp.find("::",0,TRUE) );
515 path = path.right( path.length()-1); 515 path = path.right( path.length()-1);
516 if(path.isEmpty()) baseFs = temp.right( temp.length() - temp.find("::",0,TRUE) - 2); 516 if(path.isEmpty()) baseFs = temp.right( temp.length() - temp.find("::",0,TRUE) - 2);
517 if( current.find( path,0,TRUE) != -1 && !path.isEmpty()) { 517 if( current.find( path,0,TRUE) != -1 && !path.isEmpty()) {
518 return temp.right( temp.length() - temp.find("::",0,TRUE) - 2); 518 return temp.right( temp.length() - temp.find("::",0,TRUE) - 2);
519 } 519 }
520 } 520 }
521 return baseFs; 521 return baseFs;
522} 522}
523 523
524QString AdvancedFm::getDiskSpace( const QString &path) { 524QString AdvancedFm::getDiskSpace( const QString &path) {
525 struct statfs fss; 525 struct statfs fss;
526 if ( !statfs( path.latin1(), &fss ) ) { 526 if ( !statfs( path.latin1(), &fss ) ) {
527 int blkSize = fss.f_bsize; 527 int blkSize = fss.f_bsize;
528 // int totalBlks = fs.f_blocks; 528 // int totalBlks = fs.f_blocks;
529 int availBlks = fss.f_bavail; 529 int availBlks = fss.f_bavail;
530 530
531 long mult = blkSize / 1024; 531 long mult = blkSize / 1024;
532 long div = 1024 / blkSize; 532 long div = 1024 / blkSize;
533 if ( !mult ) mult = 1; 533 if ( !mult ) mult = 1;
534 if ( !div ) div = 1; 534 if ( !div ) div = 1;
535 535
536 return QString::number(availBlks * mult / div); 536 return QString::number(availBlks * mult / div);
537 } 537 }
538 return ""; 538 return "";
539} 539}
540 540
541 541
542void AdvancedFm::showFileMenu() { 542void AdvancedFm::showFileMenu() {
543 QString curApp; 543 QString curApp;
544 curApp = CurrentView()->currentItem()->text(0); 544 curApp = CurrentView()->currentItem()->text(0);
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,270 +1,270 @@
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);
132 132
133 LineEdit1->setText( file); 133 LineEdit1->setText( file);
134 OwnerLineEdit->setText( fi.owner()); 134 OwnerLineEdit->setText( fi.owner());
135 GroupLineEdit->setText( fi.group()); 135 GroupLineEdit->setText( fi.group());
136 136
137 if( fi.permission( QFileInfo::ReadUser)) { CheckBox1->setChecked(true); } 137 if( fi.permission( QFileInfo::ReadUser)) { CheckBox1->setChecked(true); }
138 if( fi.permission( QFileInfo::WriteUser)) { CheckBox1_2->setChecked(true); } 138 if( fi.permission( QFileInfo::WriteUser)) { CheckBox1_2->setChecked(true); }
139 if( fi.permission( QFileInfo::ExeUser)) { CheckBox1_3->setChecked(true); } 139 if( fi.permission( QFileInfo::ExeUser)) { CheckBox1_3->setChecked(true); }
140 140
141 if( fi.permission( QFileInfo::ReadGroup)) { CheckBox1_4->setChecked(true); } 141 if( fi.permission( QFileInfo::ReadGroup)) { CheckBox1_4->setChecked(true); }
142 if( fi.permission( QFileInfo::WriteGroup)) { CheckBox1_5->setChecked(true); } 142 if( fi.permission( QFileInfo::WriteGroup)) { CheckBox1_5->setChecked(true); }
143 if( fi.permission( QFileInfo::ExeGroup)) { CheckBox1_6->setChecked(true); } 143 if( fi.permission( QFileInfo::ExeGroup)) { CheckBox1_6->setChecked(true); }
144 144
145 if( fi.permission( QFileInfo::ReadOther)) { CheckBox1_7->setChecked(true); } 145 if( fi.permission( QFileInfo::ReadOther)) { CheckBox1_7->setChecked(true); }
146 if( fi.permission( QFileInfo::WriteOther)) { CheckBox1_8->setChecked(true); } 146 if( fi.permission( QFileInfo::WriteOther)) { CheckBox1_8->setChecked(true); }
147 if( fi.permission( QFileInfo::ExeOther)) { CheckBox1_8_2->setChecked(true); } 147 if( fi.permission( QFileInfo::ExeOther)) { CheckBox1_8_2->setChecked(true); }
148 148
149 stat(file.latin1(), &buf); 149 stat(file.latin1(), &buf);
150 mode = buf.st_mode; 150 mode = buf.st_mode;
151 modeStr.sprintf("%#o", buf.st_mode & ~(S_IFMT) ); 151 modeStr.sprintf("%#o", buf.st_mode & ~(S_IFMT) );
152 ModeLine->setText(modeStr); 152 ModeLine->setText(modeStr);
153 bool ok; 153 bool ok;
154 i_mode = modeStr.toInt(&ok,10); 154 i_mode = modeStr.toInt(&ok,10);
155 155
156} 156}
157 157
158/* 158/*
159 * Destroys the object and frees any allocated resources 159 * Destroys the object and frees any allocated resources
160 */ 160 */
161filePermissions::~filePermissions() 161filePermissions::~filePermissions()
162{ 162{
163} 163}
164 164
165 165
166// might this be better as a callback routine??? 166// might this be better as a callback routine???
167void filePermissions::ownReadCheck() { 167void filePermissions::ownReadCheck() {
168 if(CheckBox1->isChecked()) { i_mode +=400; } 168 if(CheckBox1->isChecked()) { i_mode +=400; }
169 else i_mode -=400; 169 else i_mode -=400;
170 modeStr.sprintf("0%d",i_mode); 170 modeStr.sprintf("0%d",i_mode);
171 ModeLine->setText( modeStr); 171 ModeLine->setText( modeStr);
172// 0400 172// 0400
173} 173}
174 174
175void filePermissions::ownWriteCheck() { 175void filePermissions::ownWriteCheck() {
176 if(CheckBox1_2->isChecked()) { i_mode +=200; } 176 if(CheckBox1_2->isChecked()) { i_mode +=200; }
177 else i_mode -=200; 177 else i_mode -=200;
178 modeStr.sprintf("0%d",i_mode); 178 modeStr.sprintf("0%d",i_mode);
179 ModeLine->setText(modeStr); 179 ModeLine->setText(modeStr);
180// 0200 180// 0200
181} 181}
182 182
183void filePermissions::ownExeCheck() { 183void filePermissions::ownExeCheck() {
184 if(CheckBox1_3->isChecked()) { i_mode +=100; } 184 if(CheckBox1_3->isChecked()) { i_mode +=100; }
185 else i_mode -=100; 185 else i_mode -=100;
186 modeStr.sprintf("0%d",i_mode); 186 modeStr.sprintf("0%d",i_mode);
187 ModeLine->setText(modeStr); 187 ModeLine->setText(modeStr);
188// 0100 188// 0100
189} 189}
190 190
191void filePermissions::grpReadCheck() { 191void filePermissions::grpReadCheck() {
192 if(CheckBox1_4->isChecked()) { i_mode +=40; } 192 if(CheckBox1_4->isChecked()) { i_mode +=40; }
193 else i_mode -=40; 193 else i_mode -=40;
194 modeStr.sprintf("0%d",i_mode); 194 modeStr.sprintf("0%d",i_mode);
195 ModeLine->setText(modeStr); 195 ModeLine->setText(modeStr);
196// 0040 196// 0040
197} 197}
198 198
199void filePermissions::grpWriteCheck() { 199void filePermissions::grpWriteCheck() {
200 if(CheckBox1_5->isChecked()) { i_mode +=20; } 200 if(CheckBox1_5->isChecked()) { i_mode +=20; }
201 else i_mode -=20; 201 else i_mode -=20;
202 modeStr.sprintf("0%d",i_mode); 202 modeStr.sprintf("0%d",i_mode);
203 ModeLine->setText(modeStr); 203 ModeLine->setText(modeStr);
204// 0020 204// 0020
205} 205}
206 206
207void filePermissions::grpExeCheck() { 207void filePermissions::grpExeCheck() {
208 if(CheckBox1_6->isChecked()) { i_mode +=10; } 208 if(CheckBox1_6->isChecked()) { i_mode +=10; }
209 else i_mode -=10; 209 else i_mode -=10;
210 modeStr.sprintf("0%d",i_mode); 210 modeStr.sprintf("0%d",i_mode);
211 ModeLine->setText(modeStr); 211 ModeLine->setText(modeStr);
212// 0010 212// 0010
213} 213}
214 214
215void filePermissions::wrldReadCheck() { 215void filePermissions::wrldReadCheck() {
216 if(CheckBox1_7->isChecked()) { i_mode +=4; } 216 if(CheckBox1_7->isChecked()) { i_mode +=4; }
217 else i_mode -=4; 217 else i_mode -=4;
218 modeStr.sprintf("0%d",i_mode); 218 modeStr.sprintf("0%d",i_mode);
219 ModeLine->setText(modeStr); 219 ModeLine->setText(modeStr);
220// 0004 220// 0004
221} 221}
222 222
223void filePermissions::wrldWriteCheck() { 223void filePermissions::wrldWriteCheck() {
224 if(CheckBox1_8->isChecked()) { i_mode +=2; } 224 if(CheckBox1_8->isChecked()) { i_mode +=2; }
225 else i_mode -=2; 225 else i_mode -=2;
226 modeStr.sprintf("0%d",i_mode); 226 modeStr.sprintf("0%d",i_mode);
227 ModeLine->setText(modeStr); 227 ModeLine->setText(modeStr);
228// 0002 228// 0002
229} 229}
230 230
231void filePermissions::wrldExeCheck() { 231void filePermissions::wrldExeCheck() {
232 if(CheckBox1_8_2->isChecked()) { i_mode +=1; } 232 if(CheckBox1_8_2->isChecked()) { i_mode +=1; }
233 else i_mode -=1; 233 else i_mode -=1;
234 modeStr.sprintf("0%d",i_mode); 234 modeStr.sprintf("0%d",i_mode);
235 ModeLine->setText(modeStr); 235 ModeLine->setText(modeStr);
236// 0001 236// 0001
237} 237}
238 238
239void filePermissions::accept() { 239void filePermissions::accept() {
240 240
241 QFileInfo fi(file); 241 QFileInfo fi(file);
242 struct passwd *pwd=0; 242 struct passwd *pwd=0;
243 struct group *grp=0; 243 struct group *grp=0;
244 pwd = getpwnam(OwnerLineEdit->text().latin1() ); 244 pwd = getpwnam(OwnerLineEdit->text().latin1() );
245 if(pwd == NULL) { 245 if(pwd == NULL) {
246 perror("getpwnam"); 246 perror("getpwnam");
247 QMessageBox::warning(this,tr("Warning"),tr("Error- no user") ); 247 QMessageBox::warning(this,tr("Warning"),tr("Error- no user") );
248 return; 248 return;
249 } else { 249 } else {
250 grp = getgrnam(GroupLineEdit->text().latin1()); 250 grp = getgrnam(GroupLineEdit->text().latin1());
251 if(grp==NULL) { 251 if(grp==NULL) {
252 perror("getgrnam"); 252 perror("getgrnam");
253 QMessageBox::warning(this,tr("Warning"),tr("Error- no group")); 253 QMessageBox::warning(this,tr("Warning"),tr("Error- no group"));
254 return; 254 return;
255 } 255 }
256 if( chown( file.latin1(), pwd->pw_uid, grp->gr_gid) <0) { 256 if( chown( file.latin1(), pwd->pw_uid, grp->gr_gid) <0) {
257 perror("chown"); 257 perror("chown");
258 QMessageBox::warning(this,tr("Warning"),tr("Error setting ownership or group") ); 258 QMessageBox::warning(this,tr("Warning"),tr("Error setting ownership or group") );
259 return; 259 return;
260 } 260 }
261 bool ok; 261 bool ok;
262 uint moder = modeStr.toUInt(&ok,8); 262 uint moder = modeStr.toUInt(&ok,8);
263 if( chmod( file.latin1(), moder) < 0) { 263 if( chmod( file.latin1(), moder) < 0) {
264 perror("chmod"); 264 perror("chmod");
265 QMessageBox::warning(this,tr("Warning"),tr("Error setting mode") ); 265 QMessageBox::warning(this,tr("Warning"),tr("Error setting mode") );
266 return; 266 return;
267 } 267 }
268 } 268 }
269 close(); 269 close();
270} 270}
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,344 +1,349 @@
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}
134 139
135 140
136// --- fixTypes ---------------------------------------------------------------- 141// --- fixTypes ----------------------------------------------------------------
137// Makes sure all entries have a unique name and empty entries are replaced 142// Makes sure all entries have a unique name and empty entries are replaced
138// by a generic string. The first version performs the operation on a particular 143// by a generic string. The first version performs the operation on a particular
139// column, whereas the 2nd does it for all unique columns. 144// column, whereas the 2nd does it for all unique columns.
140class ColMap { 145class ColMap {
141 public: 146 public:
142 ColMap(QString sValue, QListViewItem *pEntry) { 147 ColMap(QString sValue, QListViewItem *pEntry) {
143 _sValue=sValue; 148 _sValue=sValue;
144 _pEntry=pEntry; 149 _pEntry=pEntry;
145 } 150 }
146 QString &getValue() { return(_sValue); } 151 QString &getValue() { return(_sValue); }
147 QListViewItem *getItem() { return(_pEntry); } 152 QListViewItem *getItem() { return(_pEntry); }
148 153
149 protected: 154 protected:
150 QString _sValue; 155 QString _sValue;
151 QListViewItem *_pEntry; 156 QListViewItem *_pEntry;
152}; 157};
153 158
154class ColList : public QList<QString> 159class ColList : public QList<QString>
155{ 160{
156 public: 161 public:
157 ColList() : QList<QString>() { } 162 ColList() : QList<QString>() { }
158 163
159 protected: 164 protected:
160 int compareItems(QCollection::Item, QCollection::Item); 165 int compareItems(QCollection::Item, QCollection::Item);
161}; 166};
162 167
163int ColList::compareItems(QCollection::Item i1, QCollection::Item i2) { 168int ColList::compareItems(QCollection::Item i1, QCollection::Item i2) {
164 return( ((QString *)i1)->compare(*(QString *)i2) ); 169 return( ((QString *)i1)->compare(*(QString *)i2) );
165} 170}
166 171
167void ListEdit::fixTypes(int iColumn) 172void ListEdit::fixTypes(int iColumn)
168{ 173{
169 // get column def 174 // get column def
170 ColumnDef *pDef=this->at(iColumn); 175 ColumnDef *pDef=this->at(iColumn);
171 176
172 // create map of entries 177 // create map of entries
173 if( !_typeTable->childCount() ) return; 178 if( !_typeTable->childCount() ) return;
174 ColMap **colMap=new (ColMap *)[_typeTable->childCount()]; 179 ColMap **colMap=new (ColMap *)[_typeTable->childCount()];
175 QListViewItem *cur=_typeTable->firstChild(); 180 QListViewItem *cur=_typeTable->firstChild();
176 ColList lst; 181 ColList lst;
177 for(int i=0; i<_typeTable->childCount(); i++) { 182 for(int i=0; i<_typeTable->childCount(); i++) {
178 colMap[i]=new ColMap(cur->text(iColumn), cur); 183 colMap[i]=new ColMap(cur->text(iColumn), cur);
179 lst.append( &(colMap[i]->getValue()) ); 184 lst.append( &(colMap[i]->getValue()) );
180 cur=cur->nextSibling(); 185 cur=cur->nextSibling();
181 } 186 }
182 187
183 // fix empty entries 188 // fix empty entries
184 int i=0; 189 int i=0;
185 for(QString *ptr=lst.first(); ptr; ptr=lst.next()) { 190 for(QString *ptr=lst.first(); ptr; ptr=lst.next()) {
186 *ptr=ptr->stripWhiteSpace(); 191 *ptr=ptr->stripWhiteSpace();
187 if( ptr->isEmpty() ) { 192 if( ptr->isEmpty() ) {
188 i++; 193 i++;
189 if( i==1 ) *ptr=pDef->getNewValue(); 194 if( i==1 ) *ptr=pDef->getNewValue();
190 else ptr->sprintf("%s %d", (const char *)pDef->getNewValue(), i); 195 else ptr->sprintf("%s %d", (const char *)pDef->getNewValue(), i);
191 } 196 }
192 } 197 }
193 198
194 // fix dups 199 // fix dups
195 lst.sort(); 200 lst.sort();
196 QString repl; 201 QString repl;
197 for(uint iCur=0; iCur<lst.count()-1; iCur++) { 202 for(uint iCur=0; iCur<lst.count()-1; iCur++) {
198 QString *current=lst.at(iCur); 203 QString *current=lst.at(iCur);
199 for(uint iNext=iCur+1; iNext<lst.count(); iNext++ ) { 204 for(uint iNext=iCur+1; iNext<lst.count(); iNext++ ) {
200 if( *current!=*lst.at(iNext) ) continue; 205 if( *current!=*lst.at(iNext) ) continue;
201 for(int i=2; ; i++) { 206 for(int i=2; ; i++) {
202 repl.sprintf("%s %d", (const char *)*current, i); 207 repl.sprintf("%s %d", (const char *)*current, i);
203 bool bDup=false; 208 bool bDup=false;
204 uint iChk=iNext+1; 209 uint iChk=iNext+1;
205 while( iChk<lst.count() ) { 210 while( iChk<lst.count() ) {
206 QString *chk=lst.at(iChk); 211 QString *chk=lst.at(iChk);
207 if( !chk->startsWith(*current) ) break; 212 if( !chk->startsWith(*current) ) break;
208 if( *chk==repl ) { 213 if( *chk==repl ) {
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,337 +1,341 @@
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." ) );
132 layout->addMultiCellWidget( catList, 3, 3, 1, 3 ); 136 layout->addMultiCellWidget( catList, 3, 3, 1, 3 );
133 137
134 // Type 138 // Type
135 label = new QLabel( tr( "Type:" ), container ); 139 label = new QLabel( tr( "Type:" ), container );
136 QWhatsThis::add( label, tr( "Select transaction type here.\n\nThe options available vary based on whether the transaction is a deposit or withdrawal." ) ); 140 QWhatsThis::add( label, tr( "Select transaction type here.\n\nThe options available vary based on whether the transaction is a deposit or withdrawal." ) );
137 layout->addWidget( label, 4, 0 ); 141 layout->addWidget( label, 4, 0 );
138 typeList = new QComboBox( container ); 142 typeList = new QComboBox( container );
139 QWhatsThis::add( typeList, tr( "Select transaction type here.\n\nThe options available vary based on whether the transaction is a deposit or withdrawal." ) ); 143 QWhatsThis::add( typeList, tr( "Select transaction type here.\n\nThe options available vary based on whether the transaction is a deposit or withdrawal." ) );
140 layout->addMultiCellWidget( typeList, 4, 4, 1, 3 ); 144 layout->addMultiCellWidget( typeList, 4, 4, 1, 3 );
141 145
142 146
143 // Amount 147 // Amount
144 label = new QLabel( tr( "Amount:" ), container ); 148 label = new QLabel( tr( "Amount:" ), container );
145 QWhatsThis::add( label, tr( "Enter the amount of transaction here.\n\nThe value entered should always be positive." ) ); 149 QWhatsThis::add( label, tr( "Enter the amount of transaction here.\n\nThe value entered should always be positive." ) );
146 layout->addWidget( label, 5, 0 ); 150 layout->addWidget( label, 5, 0 );
147 amtEdit = new QLineEdit( container ); 151 amtEdit = new QLineEdit( container );
148 QWhatsThis::add( amtEdit, tr( "Enter the amount of transaction here.\n\nThe value entered should always be positive." ) ); 152 QWhatsThis::add( amtEdit, tr( "Enter the amount of transaction here.\n\nThe value entered should always be positive." ) );
149 layout->addMultiCellWidget( amtEdit, 5, 5, 1, 3 ); 153 layout->addMultiCellWidget( amtEdit, 5, 5, 1, 3 );
150 154
151 // Fee 155 // Fee
152 label = new QLabel( tr( "Fee:" ), container ); 156 label = new QLabel( tr( "Fee:" ), container );
153 QWhatsThis::add( label, tr( "Enter any fee amount assoiciated with this transaction.\n\nThe value entered should always be positive." ) ); 157 QWhatsThis::add( label, tr( "Enter any fee amount assoiciated with this transaction.\n\nThe value entered should always be positive." ) );
154 layout->addWidget( label, 6, 0 ); 158 layout->addWidget( label, 6, 0 );
155 feeEdit = new QLineEdit( container ); 159 feeEdit = new QLineEdit( container );
156 QWhatsThis::add( feeEdit, tr( "Enter any fee amount assoiciated with this transaction.\n\nThe value entered should always be positive." ) ); 160 QWhatsThis::add( feeEdit, tr( "Enter any fee amount assoiciated with this transaction.\n\nThe value entered should always be positive." ) );
157 layout->addMultiCellWidget( feeEdit, 6, 6, 1, 3 ); 161 layout->addMultiCellWidget( feeEdit, 6, 6, 1, 3 );
158 162
159 // Notes 163 // Notes
160 label = new QLabel( tr( "Notes:" ), container ); 164 label = new QLabel( tr( "Notes:" ), container );
161 QWhatsThis::add( label, tr( "Enter any additional information for this transaction here." ) ); 165 QWhatsThis::add( label, tr( "Enter any additional information for this transaction here." ) );
162 layout->addWidget( label, 7, 0 ); 166 layout->addWidget( label, 7, 0 );
163 noteEdit = new QMultiLineEdit( container ); 167 noteEdit = new QMultiLineEdit( container );
164 QWhatsThis::add( noteEdit, tr( "Enter any additional information for this transaction here." ) ); 168 QWhatsThis::add( noteEdit, tr( "Enter any additional information for this transaction here." ) );
165 layout->addMultiCellWidget( noteEdit, 8, 8, 0, 3 ); 169 layout->addMultiCellWidget( noteEdit, 8, 8, 0, 3 );
166 170
167 // init date 171 // init date
168 initFromInfo( info ); 172 initFromInfo( info );
169 173
170 // not new handlers 174 // not new handlers
171 connect( withBtn, SIGNAL( toggled(bool) ), this, SLOT( slotNotNew() ) ); 175 connect( withBtn, SIGNAL( toggled(bool) ), this, SLOT( slotNotNew() ) );
172 connect( depBtn, SIGNAL( toggled(bool) ), this, SLOT( slotNotNew() ) ); 176 connect( depBtn, SIGNAL( toggled(bool) ), this, SLOT( slotNotNew() ) );
173 connect( catList, SIGNAL(activated(const QString&)), this, SLOT( slotNotNew() ) ); 177 connect( catList, SIGNAL(activated(const QString&)), this, SLOT( slotNotNew() ) );
174 connect( typeList, SIGNAL(activated(const QString&)), this, SLOT( slotNotNew() ) ); 178 connect( typeList, SIGNAL(activated(const QString&)), this, SLOT( slotNotNew() ) );
175 connect( amtEdit, SIGNAL(textChanged(const QString&)), this, SLOT( slotNotNew() ) ); 179 connect( amtEdit, SIGNAL(textChanged(const QString&)), this, SLOT( slotNotNew() ) );
176 connect( feeEdit, SIGNAL(textChanged(const QString&)), this, SLOT( slotNotNew() ) ); 180 connect( feeEdit, SIGNAL(textChanged(const QString&)), this, SLOT( slotNotNew() ) );
177 connect( noteEdit, SIGNAL(textChanged()), this, SLOT( slotNotNew() ) ); 181 connect( noteEdit, SIGNAL(textChanged()), this, SLOT( slotNotNew() ) );
178} 182}
179 183
180// --- initFromInfo ----------------------------------------------------------- 184// --- initFromInfo -----------------------------------------------------------
181void Transaction::initFromInfo(TranInfo *info, bool bPopulateOld) 185void Transaction::initFromInfo(TranInfo *info, bool bPopulateOld)
182{ 186{
183 // Populate current values if provided 187 // Populate current values if provided
184 if ( info ) 188 if ( info )
185 { 189 {
186 if ( info->withdrawal() ) 190 if ( info->withdrawal() )
187 { 191 {
188 withBtn->setChecked( TRUE ); 192 withBtn->setChecked( TRUE );
189 slotWithdrawalClicked(); 193 slotWithdrawalClicked();
190 } 194 }
191 else 195 else
192 { 196 {
193 depBtn->setChecked( TRUE ); 197 depBtn->setChecked( TRUE );
194 slotDepositClicked(); 198 slotDepositClicked();
195 } 199 }
196 200
197 if( !bPopulateOld ) { 201 if( !bPopulateOld ) {
198 QDate dt = info->date(); 202 QDate dt = info->date();
199 slotDateChanged( dt.year(), dt.month(), dt.day() ); 203 slotDateChanged( dt.year(), dt.month(), dt.day() );
200 datePicker->setDate( dt ); 204 datePicker->setDate( dt );
201 numEdit->setText( info->number() ); 205 numEdit->setText( info->number() );
202 } 206 }
203 QString temptext = info->category(); 207 QString temptext = info->category();
204 208
205 // set description field 209 // set description field
206 int i; 210 int i;
207 for(i=_cbDesc->count()-1; i>=0; i--) { 211 for(i=_cbDesc->count()-1; i>=0; i--) {
208 if( _cbDesc->text(i)==info->desc() ) { 212 if( _cbDesc->text(i)==info->desc() ) {
209 _cbDesc->setCurrentItem(i); 213 _cbDesc->setCurrentItem(i);
210 break; 214 break;
211 } 215 }
212 } 216 }
213 if( i<=0 ) 217 if( i<=0 )
214 _cbDesc->setEditText( info->desc() ); 218 _cbDesc->setEditText( info->desc() );
215 219
216 i = catList->count(); 220 i = catList->count();
217 while ( i > 0 ) 221 while ( i > 0 )
218 { 222 {
219 i--; 223 i--;
220 catList->setCurrentItem( i ); 224 catList->setCurrentItem( i );
221 if ( catList->currentText() == temptext ) 225 if ( catList->currentText() == temptext )
222 { 226 {
223 break; 227 break;
224 } 228 }
225 } 229 }
226 temptext = info->type(); 230 temptext = info->type();
227 i = typeList->count(); 231 i = typeList->count();
228 while ( i > 0 ) 232 while ( i > 0 )
229 { 233 {
230 i--; 234 i--;
231 typeList->setCurrentItem( i ); 235 typeList->setCurrentItem( i );
232 if ( typeList->currentText() == temptext ) 236 if ( typeList->currentText() == temptext )
233 { 237 {
234 break; 238 break;
235 } 239 }
236 } 240 }
237 amtEdit->setText( QString( "%1" ).arg( info->amount(), 0, 'f', 2 ) ); 241 amtEdit->setText( QString( "%1" ).arg( info->amount(), 0, 'f', 2 ) );
238 feeEdit->setText( QString( "%1" ).arg( info->fee(), 0, 'f', 2 ) ); 242 feeEdit->setText( QString( "%1" ).arg( info->fee(), 0, 'f', 2 ) );
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,338 +1,344 @@
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) {
206 includes.insert(file, prefix); 212 includes.insert(file, prefix);
207 includeList.append(&includes.find(file).key()); 213 includeList.append(&includes.find(file).key());
208} 214}
209 215
210QString CfgParser::errorString() { 216QString CfgParser::errorString() {
211 return err; 217 return err;
212} 218}
213 219
214bool CfgParser::warning(const QXmlParseException& e) { 220bool CfgParser::warning(const QXmlParseException& e) {
215 QString tmp; 221 QString tmp;
216 222
217 tmp.sprintf("%d: warning: %s\n", e.lineNumber(), 223 tmp.sprintf("%d: warning: %s\n", e.lineNumber(),
218 (const char*) e.message().utf8()); 224 (const char*) e.message().utf8());
219 225
220 err += tmp; 226 err += tmp;
221 227
222 return true; 228 return true;
223} 229}
224 230
225bool CfgParser::error(const QXmlParseException& e) { 231bool CfgParser::error(const QXmlParseException& e) {
226 QString tmp; 232 QString tmp;
227 233
228 tmp.sprintf("%d: error: %s\n", e.lineNumber(), 234 tmp.sprintf("%d: error: %s\n", e.lineNumber(),
229 (const char*) e.message().utf8()); 235 (const char*) e.message().utf8());
230 236
231 err += tmp; 237 err += tmp;
232 238
233 return true; 239 return true;
234} 240}
235 241
236bool CfgParser::fatalError(const QXmlParseException& e) { 242bool CfgParser::fatalError(const QXmlParseException& e) {
237 QString tmp; 243 QString tmp;
238 244
239 tmp.sprintf("%d: fatal error: %s\n", e.lineNumber(), 245 tmp.sprintf("%d: fatal error: %s\n", e.lineNumber(),
240 (const char*) e.message().utf8()); 246 (const char*) e.message().utf8());
241 247
242 err += tmp; 248 err += tmp;
243 249
244 return false; 250 return false;
245} 251}
246 252
247// CfgHandler implementation 253// CfgHandler implementation
248CfgHandler::CfgHandler(CfgParser& c):cfg(c) { 254CfgHandler::CfgHandler(CfgParser& c):cfg(c) {
249} 255}
250 256
251CfgHandler::~CfgHandler() { 257CfgHandler::~CfgHandler() {
252} 258}
253 259
254bool CfgHandler::startKeymapElement(int ard, int arp, const QString& author) { 260bool CfgHandler::startKeymapElement(int ard, int arp, const QString& author) {
255 if (author != "keyzcfg") { 261 if (author != "keyzcfg") {
256 bool ret; 262 bool ret;
257 ret = QMessageBox::warning(0, "keyz configurator", 263 ret = QMessageBox::warning(0, "keyz configurator",
258 "Your zkb.xml doesn't seem created by keyz configurator.\n" 264 "Your zkb.xml doesn't seem created by keyz configurator.\n"
259 "By using keyz configurator you may loose your current " 265 "By using keyz configurator you may loose your current "
260 "configuration\n Do you want to continue\n\n", 266 "configuration\n Do you want to continue\n\n",
261 "Yes", "No", 0, 0, 1); 267 "Yes", "No", 0, 0, 1);
262 268
263 if (ret != 0) { 269 if (ret != 0) {
264 err = "cancelled by user"; 270 err = "cancelled by user";
265 return false; 271 return false;
266 } 272 }
267 } 273 }
268 274
269 if (ard != -1) { 275 if (ard != -1) {
270 cfg.setAutorepeatDelay(ard); 276 cfg.setAutorepeatDelay(ard);
271 } 277 }
272 278
273 if (arp != -1) { 279 if (arp != -1) {
274 cfg.setAutorepeatPeriod(arp); 280 cfg.setAutorepeatPeriod(arp);
275 } 281 }
276 282
277 return true; 283 return true;
278} 284}
279 285
280bool CfgHandler::startIncludeElement(const QString& file, 286bool CfgHandler::startIncludeElement(const QString& file,
281 const QString& pref) { 287 const QString& pref) {
282 288
283 cfg.addFile(file, pref); 289 cfg.addFile(file, pref);
284 return true; 290 return true;
285} 291}
286 292
287bool CfgHandler::startLabelElement(const QString& label, 293bool CfgHandler::startLabelElement(const QString& label,
288 const QString& state) { 294 const QString& state) {
289 295
290 cfg.addLabel(label, state); 296 cfg.addLabel(label, state);
291 return true; 297 return true;
292} 298}
293 299
294bool CfgHandler::startStateElement(const QString&, const QString&, bool) { 300bool CfgHandler::startStateElement(const QString&, const QString&, bool) {
295 301
296 return true; 302 return true;
297} 303}
298 304
299bool CfgHandler::startMapElement(int, bool) { 305bool CfgHandler::startMapElement(int, bool) {
300 return true; 306 return true;
301} 307}
302 308
303bool CfgHandler::startEventElement(int, int, int, bool, bool) { 309bool CfgHandler::startEventElement(int, int, int, bool, bool) {
304 return true; 310 return true;
305} 311}
306 312
307bool CfgHandler::startNextStateElement(const QString&) { 313bool CfgHandler::startNextStateElement(const QString&) {
308 return true; 314 return true;
309} 315}
310 316
311 317
312bool CfgHandler::endKeymapElement() { 318bool CfgHandler::endKeymapElement() {
313 return true; 319 return true;
314} 320}
315 321
316bool CfgHandler::endIncludeElement() { 322bool CfgHandler::endIncludeElement() {
317 return true; 323 return true;
318} 324}
319 325
320bool CfgHandler::endLabelElement() { 326bool CfgHandler::endLabelElement() {
321 return true; 327 return true;
322} 328}
323 329
324bool CfgHandler::endStateElement() { 330bool CfgHandler::endStateElement() {
325 return true; 331 return true;
326} 332}
327 333
328bool CfgHandler::endMapElement() { 334bool CfgHandler::endMapElement() {
329 return true; 335 return true;
330} 336}
331 337
332bool CfgHandler::endEventElement() { 338bool CfgHandler::endEventElement() {
333 return true; 339 return true;
334} 340}
335 341
336bool CfgHandler::endNextStateElement() { 342bool CfgHandler::endNextStateElement() {
337 return true; 343 return true;
338} 344}
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
@@ -1,589 +1,589 @@
1#include "zkb.h" 1#include "zkb.h"
2#include <stdio.h> 2#include <stdio.h>
3 3
4// Implementation of Action class 4// Implementation of Action class
5Action::Action():state(0), keycode(0), unicode(0), flags(0) { 5Action::Action():state(0), keycode(0), unicode(0), flags(0) {
6} 6}
7 7
8Action::Action(State* s, ushort kc, ushort uni, int f): 8Action::Action(State* s, ushort kc, ushort uni, int f):
9 state(s), keycode(kc), unicode(uni), flags(f) { 9 state(s), keycode(kc), unicode(uni), flags(f) {
10} 10}
11 11
12Action::~Action() { 12Action::~Action() {
13} 13}
14 14
15State* Action::getState() const { 15State* Action::getState() const {
16 return state; 16 return state;
17} 17}
18 18
19void Action::setState(State* s) { 19void Action::setState(State* s) {
20 state = s; 20 state = s;
21 setDefined(true); 21 setDefined(true);
22} 22}
23 23
24bool Action::hasEvent() const { 24bool Action::hasEvent() const {
25 return flags & Event; 25 return flags & Event;
26} 26}
27 27
28void Action::setEvent(bool e) { 28void Action::setEvent(bool e) {
29 flags = (flags & ~Event) | ((e) ? Event : 0); 29 flags = (flags & ~Event) | ((e) ? Event : 0);
30 30
31 if (e) { 31 if (e) {
32 setDefined(true); 32 setDefined(true);
33 } else { 33 } else {
34 if (state == 0) { 34 if (state == 0) {
35 setDefined(false); 35 setDefined(false);
36 } 36 }
37 } 37 }
38} 38}
39 39
40bool Action::isDefined() const { 40bool Action::isDefined() const {
41 return flags & Defined; 41 return flags & Defined;
42} 42}
43 43
44void Action::setDefined(bool d) { 44void Action::setDefined(bool d) {
45 flags = (flags & ~Defined) | ((d) ? Defined : 0); 45 flags = (flags & ~Defined) | ((d) ? Defined : 0);
46} 46}
47 47
48int Action::getKeycode() const { 48int Action::getKeycode() const {
49 return keycode; 49 return keycode;
50} 50}
51 51
52void Action::setKeycode(int c) { 52void Action::setKeycode(int c) {
53 keycode = (ushort) c; 53 keycode = (ushort) c;
54 setEvent(true); 54 setEvent(true);
55} 55}
56 56
57int Action::getUnicode() const { 57int Action::getUnicode() const {
58 return unicode; 58 return unicode;
59} 59}
60 60
61void Action::setUnicode(int u) { 61void Action::setUnicode(int u) {
62 unicode = (ushort) u; 62 unicode = (ushort) u;
63 setEvent(true); 63 setEvent(true);
64} 64}
65 65
66int Action::getModifiers() const { 66int Action::getModifiers() const {
67 int ret = 0; 67 int ret = 0;
68 if (flags & Shift_Mod) { 68 if (flags & Shift_Mod) {
69 ret |= Qt::ShiftButton; 69 ret |= Qt::ShiftButton;
70 } 70 }
71 71
72 if (flags & Ctrl_Mod) { 72 if (flags & Ctrl_Mod) {
73 ret |= Qt::ControlButton; 73 ret |= Qt::ControlButton;
74 } 74 }
75 75
76 if (flags & Alt_Mod) { 76 if (flags & Alt_Mod) {
77 ret |= Qt::AltButton; 77 ret |= Qt::AltButton;
78 } 78 }
79 79
80 if (flags & Keypad_Mod) { 80 if (flags & Keypad_Mod) {
81 ret |= Qt::Keypad; 81 ret |= Qt::Keypad;
82 } 82 }
83 83
84 return ret; 84 return ret;
85} 85}
86 86
87void Action::setModifiers(int m) { 87void Action::setModifiers(int m) {
88 int n = 0; 88 int n = 0;
89 89
90 if (m & Qt::ShiftButton) { 90 if (m & Qt::ShiftButton) {
91 n |= Shift_Mod; 91 n |= Shift_Mod;
92 } 92 }
93 93
94 if (m & Qt::ControlButton) { 94 if (m & Qt::ControlButton) {
95 n |= Ctrl_Mod; 95 n |= Ctrl_Mod;
96 } 96 }
97 97
98 if (m & Qt::AltButton) { 98 if (m & Qt::AltButton) {
99 n |= Alt_Mod; 99 n |= Alt_Mod;
100 } 100 }
101 101
102 if (m & Qt::Keypad) { 102 if (m & Qt::Keypad) {
103 n |= Keypad_Mod; 103 n |= Keypad_Mod;
104 } 104 }
105 105
106 flags = flags & ~Mod_Bits | n; 106 flags = flags & ~Mod_Bits | n;
107 setEvent(true); 107 setEvent(true);
108} 108}
109 109
110bool Action::isPressed() const { 110bool Action::isPressed() const {
111 return (flags & Press) != 0; 111 return (flags & Press) != 0;
112} 112}
113 113
114void Action::setPressed(bool p) { 114void Action::setPressed(bool p) {
115 flags = (flags & ~Press) | ((p) ? Press : 0); 115 flags = (flags & ~Press) | ((p) ? Press : 0);
116 setEvent(true); 116 setEvent(true);
117} 117}
118 118
119bool Action::isAutorepeat() const { 119bool Action::isAutorepeat() const {
120 return (flags & Autorepeat) != 0; 120 return (flags & Autorepeat) != 0;
121} 121}
122 122
123void Action::setAutorepeat(bool p) { 123void Action::setAutorepeat(bool p) {
124 flags = (flags & ~Autorepeat) | ((p) ? Autorepeat : 0); 124 flags = (flags & ~Autorepeat) | ((p) ? Autorepeat : 0);
125 setEvent(true); 125 setEvent(true);
126} 126}
127 127
128// Implementation of State class 128// Implementation of State class
129const short State::x1[] = { /* from 0x20 to 0x5f */ 129const short State::x1[] = { /* from 0x20 to 0x5f */
130 31, 0, 28, 3, 5, 6, 9, 28, /* 0x20 - 0x27 */ 130 31, 0, 28, 3, 5, 6, 9, 28, /* 0x20 - 0x27 */
131 11, 26, 10, 13, 26, 1, 29, 27, /* 0x28 - 0x2f */ 131 11, 26, 10, 13, 26, 1, 29, 27, /* 0x28 - 0x2f */
132 15, 16, 22, 4, 17, 19, 24, 20, /* 0x30 - 0x37 */ 132 15, 16, 22, 4, 17, 19, 24, 20, /* 0x30 - 0x37 */
133 8, 14, 29, 26, 29, 12, 32, 27, /* 0x38 - 0x3f */ 133 8, 14, 29, 26, 29, 12, 32, 27, /* 0x38 - 0x3f */
134 18, 0, 1, 2, 3, 4, 5, 6, /* 0x40 - 0x47 */ 134 18, 0, 1, 2, 3, 4, 5, 6, /* 0x40 - 0x47 */
135 7, 8, 9, 10, 11, 12, 13, 14, /* 0x48 - 0x4f */ 135 7, 8, 9, 10, 11, 12, 13, 14, /* 0x48 - 0x4f */
136 15, 16, 17, 18, 19, 20, 21, 22, /* 0x50 - 0x57 */ 136 15, 16, 17, 18, 19, 20, 21, 22, /* 0x50 - 0x57 */
137 23, 24, 25, 30, -1, 26, 28, 7, /* 0x58 - 0x5f */ 137 23, 24, 25, 30, -1, 26, 28, 7, /* 0x58 - 0x5f */
138 31, -1, -1, -1, -1, -1, -1, -1, /* 0x60 - 0x67 */ 138 31, -1, -1, -1, -1, -1, -1, -1, /* 0x60 - 0x67 */
139 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x68 - 0x6f */ 139 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x68 - 0x6f */
140 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x70 - 0x77 */ 140 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x70 - 0x77 */
141 -1, -1, -1, 29, 31, 32, 32, 28, /* 0x78 - 0x7f */ 141 -1, -1, -1, 29, 31, 32, 32, 28, /* 0x78 - 0x7f */
142}; 142};
143 143
144const short State::x2[] = { /* from 0x1000 to 0x1057*/ 144const short State::x2[] = { /* from 0x1000 to 0x1057*/
145 42, 36, -1, 30, 32, -1, -1, -1, /* 0x1000 - 0x1007 */ 145 42, 36, -1, 30, 32, -1, -1, -1, /* 0x1000 - 0x1007 */
146 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1008 - 0x100f */ 146 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1008 - 0x100f */
147 -1, -1, 44, 45, 46, 47, -1, -1, /* 0x1010 - 0x1017 */ 147 -1, -1, 44, 45, 46, 47, -1, -1, /* 0x1010 - 0x1017 */
148 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1018 - 0x101f */ 148 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1018 - 0x101f */
149 33, 35, 34, -1, 36, 27, -1, -1, /* 0x1020 - 0x1027 */ 149 33, 35, 34, -1, 36, 27, -1, -1, /* 0x1020 - 0x1027 */
150 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1028 - 0x102f */ 150 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1028 - 0x102f */
151 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1030 - 0x1037 */ 151 -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1030 - 0x1037 */
152 37, 38, 40, 39, 41, -1, -1, -1, /* 0x1038 - 0x103f */ 152 37, 38, 40, 39, 41, -1, -1, -1, /* 0x1038 - 0x103f */
153 -1, -1, -1, -1, -1, 35, -1, -1, /* 0x1040 - 0x1047 */ 153 -1, -1, -1, -1, -1, 35, -1, -1, /* 0x1040 - 0x1047 */
154 -1, -1, -1, -1, -1, 48, -1, -1, /* 0x1048 - 0x104f */ 154 -1, -1, -1, -1, -1, 48, -1, -1, /* 0x1048 - 0x104f */
155 43, 49, 50, -1, -1, -1, -1, -1, /* 0x1050 - 0x1057 */ 155 43, 49, 50, -1, -1, -1, -1, -1, /* 0x1050 - 0x1057 */
156}; 156};
157 157
158State::State(State* p):parent(p), keys(0) { 158State::State(State* p):parent(p), keys(0) {
159 keys = new Action[Key_Max * 2 + 1]; 159 keys = new Action[Key_Max * 2 + 1];
160} 160}
161 161
162State::State(const State& s) { 162State::State(const State& s) {
163 parent = s.parent; 163 parent = s.parent;
164 keys = new Action[Key_Max * 2 + 1]; 164 keys = new Action[Key_Max * 2 + 1];
165 memcpy(keys, s.keys, sizeof(Action) * (Key_Max * 2 + 1)); 165 memcpy(keys, s.keys, sizeof(Action) * (Key_Max * 2 + 1));
166} 166}
167 167
168State::~State() { 168State::~State() {
169 if (keys!=0) { 169 if (keys!=0) {
170 delete [] keys; 170 delete [] keys;
171 } 171 }
172} 172}
173 173
174Action* State::get(int keycode, bool pressed, bool follow) const { 174Action* State::get(int keycode, bool pressed, bool follow) const {
175 Action* ret = 0; 175 Action* ret = 0;
176 int n = translateKeycode(keycode); 176 int n = translateKeycode(keycode);
177 177
178 if (n != -1 && keys != 0) { 178 if (n != -1 && keys != 0) {
179 if (pressed) { 179 if (pressed) {
180 n += Key_Max; 180 n += Key_Max;
181 } 181 }
182 ret = &keys[n]; 182 ret = &keys[n];
183 } 183 }
184 184
185 if (ret==0 || !ret->isDefined()) { 185 if (ret==0 || !ret->isDefined()) {
186 if (follow && parent!=0) { 186 if (follow && parent!=0) {
187 ret = parent->get(keycode, pressed, follow); 187 ret = parent->get(keycode, pressed, follow);
188 } 188 }
189 } 189 }
190 190
191 return ret; 191 return ret;
192} 192}
193 193
194bool State::set(int keycode, bool pressed, Action& action) { 194bool State::set(int keycode, bool pressed, Action& action) {
195 int n = translateKeycode(keycode); 195 int n = translateKeycode(keycode);
196 196
197 if (n==-1 || keys==0) { 197 if (n==-1 || keys==0) {
198 return false; 198 return false;
199 } 199 }
200 200
201 if (pressed) { 201 if (pressed) {
202 n += Key_Max + 1; 202 n += Key_Max + 1;
203 } 203 }
204 204
205 keys[n] = action; 205 keys[n] = action;
206 return true; 206 return true;
207} 207}
208 208
209State* State::getParent() const { 209State* State::getParent() const {
210 return parent; 210 return parent;
211} 211}
212 212
213void State::setParent(State* s) { 213void State::setParent(State* s) {
214 parent = s; 214 parent = s;
215} 215}
216 216
217int State::translateKeycode(int keycode) const { 217int State::translateKeycode(int keycode) const {
218 if (keycode < 0x20) { 218 if (keycode < 0x20) {
219 return -1; 219 return -1;
220 } 220 }
221 221
222 if (keycode < 0x80) { 222 if (keycode < 0x80) {
223 return x1[keycode - 0x20]; 223 return x1[keycode - 0x20];
224 } 224 }
225 225
226 if (keycode < 0x1000) { 226 if (keycode < 0x1000) {
227 return -1; 227 return -1;
228 } 228 }
229 229
230 if (keycode < 0x1057) { 230 if (keycode < 0x1057) {
231 return x2[keycode - 0x1000]; 231 return x2[keycode - 0x1000];
232 } 232 }
233 233
234 return -1; 234 return -1;
235} 235}
236 236
237// Implementation of Keymap class 237// Implementation of Keymap class
238Keymap::Keymap():enabled(true), currentState(0), autoRepeatAction(0), repeater(this) { 238Keymap::Keymap():enabled(true), currentState(0), autoRepeatAction(0), repeater(this) {
239 repeatDelay=400; 239 repeatDelay=400;
240 repeatPeriod=80; 240 repeatPeriod=80;
241 connect(&repeater, SIGNAL(timeout()), this, SLOT(autoRepeat())); 241 connect(&repeater, SIGNAL(timeout()), this, SLOT(autoRepeat()));
242} 242}
243 243
244Keymap::~Keymap() { 244Keymap::~Keymap() {
245 QMap<QString, State*>::Iterator it; 245 QMap<QString, State*>::Iterator it;
246 for(it = states.begin(); it != states.end(); ++it) { 246 for(it = states.begin(); it != states.end(); ++it) {
247 delete it.data(); 247 delete it.data();
248 } 248 }
249 states.clear(); 249 states.clear();
250} 250}
251 251
252bool Keymap::filter(int unicode, int keycode, int modifiers, 252bool Keymap::filter(int unicode, int keycode, int modifiers,
253 bool isPress, bool autoRepeat) { 253 bool isPress, bool autoRepeat) {
254 254
255 qDebug("filter: >>> unicode=%x, keycode=%x, modifiers=%x, " 255 qDebug("filter: >>> unicode=%x, keycode=%x, modifiers=%x, "
256 "ispressed=%x\n", unicode, keycode, modifiers, isPress); 256 "ispressed=%x\n", unicode, keycode, modifiers, isPress);
257 257
258 if (!enabled) { 258 if (!enabled) {
259 return false; 259 return false;
260 } 260 }
261 261
262 // the second check is workaround to make suspend work if 262 // the second check is workaround to make suspend work if
263 // the user pressed it right after he did resume. for some 263 // the user pressed it right after he did resume. for some
264 // reason the event sent by qt has autoRepeat true in this 264 // reason the event sent by qt has autoRepeat true in this
265 // case 265 // case
266 if (autoRepeat && keycode != 4177) { 266 if (autoRepeat && keycode != 4177) {
267 return true; 267 return true;
268 } 268 }
269 269
270 (void) unicode; (void) modifiers; 270 (void) unicode; (void) 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
516int Keymap::getAutorepeatDelay() const { 516int Keymap::getAutorepeatDelay() const {
517 return repeatDelay; 517 return repeatDelay;
518} 518}
519 519
520void Keymap::setAutorepeatDelay(int n) { 520void Keymap::setAutorepeatDelay(int n) {
521 repeatDelay = n; 521 repeatDelay = n;
522} 522}
523 523
524int Keymap::getAutorepeatPeriod() const { 524int Keymap::getAutorepeatPeriod() const {
525 return repeatPeriod; 525 return repeatPeriod;
526} 526}
527 527
528void Keymap::setAutorepeatPeriod(int n) { 528void Keymap::setAutorepeatPeriod(int n) {
529 repeatPeriod = n; 529 repeatPeriod = n;
530} 530}
531 531
532QList<Action> Keymap::findStateUsage(State* s) { 532QList<Action> Keymap::findStateUsage(State* s) {
533 QList<Action> ret; 533 QList<Action> ret;
534 534
535 QMap<QString, State*>::Iterator it; 535 QMap<QString, State*>::Iterator it;
536 for(it = states.begin(); it != states.end(); ++it) { 536 for(it = states.begin(); it != states.end(); ++it) {
537 State* state = it.data(); 537 State* state = it.data();
538 538
539 for(int i = 0; i < 0x1100; i++) { 539 for(int i = 0; i < 0x1100; i++) {
540 Action* action = state->get(i, false); 540 Action* action = state->get(i, false);
541 if (action!=0 && action->getState()==s) { 541 if (action!=0 && action->getState()==s) {
542 ret.append(action); 542 ret.append(action);
543 } 543 }
544 544
545 action = state->get(i, true); 545 action = state->get(i, true);
546 if (action!=0 && action->getState()==s) { 546 if (action!=0 && action->getState()==s) {
547 ret.append(action); 547 ret.append(action);
548 } 548 }
549 } 549 }
550 } 550 }
551 551
552 return ret; 552 return ret;
553} 553}
554 554
555void Keymap::generateLabelStateMaps() { 555void Keymap::generateLabelStateMaps() {
556 stateLabelMap.clear(); 556 stateLabelMap.clear();
557 557
558 QMap<QString, QString>::Iterator lit; 558 QMap<QString, QString>::Iterator lit;
559 for(lit = labels.begin(); lit != labels.end(); ++lit) { 559 for(lit = labels.begin(); lit != labels.end(); ++lit) {
560 QString label = lit.key(); 560 QString label = lit.key();
561 QString name = lit.data(); 561 QString name = lit.data();
562 562
563 bool wc = false; 563 bool wc = false;
564 int n = name.find("*"); 564 int n = name.find("*");
565 if (n>=0 && n==(int)(name.length()-1)) { 565 if (n>=0 && n==(int)(name.length()-1)) {
566 name=name.left(name.length() - 1); 566 name=name.left(name.length() - 1);
567 wc = true; 567 wc = true;
568 } 568 }
569 569
570 QMap<QString, State*>::Iterator sit; 570 QMap<QString, State*>::Iterator sit;
571 for(sit = states.begin(); sit != states.end(); ++sit) { 571 for(sit = states.begin(); sit != states.end(); ++sit) {
572 QString sname = sit.key(); 572 QString sname = sit.key();
573 State* state = sit.data(); 573 State* state = sit.data();
574 574
575 if (sname.length() < name.length()) { 575 if (sname.length() < name.length()) {
576 continue; 576 continue;
577 } 577 }
578 578
579 if (sname.left(name.length()) == name) { 579 if (sname.left(name.length()) == name) {
580 if (wc || sname.length()==name.length()) { 580 if (wc || sname.length()==name.length()) {
581 stateLabelMap.insert(state, label); 581 stateLabelMap.insert(state, label);
582 } 582 }
583 583
584 } 584 }
585 } 585 }
586 } 586 }
587 587
588 lsmapInSync = true; 588 lsmapInSync = true;
589} 589}
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,228 +1,231 @@
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
222bool ZkbHandler::endEventElement() { 225bool ZkbHandler::endEventElement() {
223 return true; 226 return true;
224} 227}
225 228
226bool ZkbHandler::endNextStateElement() { 229bool ZkbHandler::endNextStateElement() {
227 return true; 230 return true;
228} 231}
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,366 +1,370 @@
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()));
197 connect(m_sn_e,SIGNAL(activated(int)),this,SLOT(error())); 201 connect(m_sn_e,SIGNAL(activated(int)),this,SLOT(error()));
198 202
199 return 0; 203 return 0;
200} 204}
201 205
202int MyPty::openPty() 206int MyPty::openPty()
203{ 207{
204 // This is code from the Qt DumbTerminal example 208 // This is code from the Qt DumbTerminal example
205 int ptyfd = -1; 209 int ptyfd = -1;
206 210
207#ifdef HAVE_OPENPTY 211#ifdef HAVE_OPENPTY
208 int ttyfd; 212 int ttyfd;
209 if ( openpty(&ptyfd,&ttyfd,m_ttynam,0,0) ) 213 if ( openpty(&ptyfd,&ttyfd,m_ttynam,0,0) )
210 ptyfd = -1; 214 ptyfd = -1;
211 else 215 else
212 ::close(ttyfd); // we open the ttynam ourselves. 216 ::close(ttyfd); // we open the ttynam ourselves.
213#else 217#else
214 for (const char* c0 = "pqrstuvwxyzabcde"; ptyfd < 0 && *c0 != 0; c0++) { 218 for (const char* c0 = "pqrstuvwxyzabcde"; ptyfd < 0 && *c0 != 0; c0++) {
215 for (const char* c1 = "0123456789abcdef"; ptyfd < 0 && *c1 != 0; c1++) { 219 for (const char* c1 = "0123456789abcdef"; ptyfd < 0 && *c1 != 0; c1++) {
216 sprintf(m_ptynam,"/dev/pty%c%c",*c0,*c1); 220 sprintf(m_ptynam,"/dev/pty%c%c",*c0,*c1);
217 sprintf(m_ttynam,"/dev/tty%c%c",*c0,*c1); 221 sprintf(m_ttynam,"/dev/tty%c%c",*c0,*c1);
218 if ((ptyfd = ::open(m_ptynam,O_RDWR)) >= 0) { 222 if ((ptyfd = ::open(m_ptynam,O_RDWR)) >= 0) {
219 if (geteuid() != 0 && !access(m_ttynam,R_OK|W_OK) == 0) { 223 if (geteuid() != 0 && !access(m_ttynam,R_OK|W_OK) == 0) {
220 ::close(ptyfd); 224 ::close(ptyfd);
221 ptyfd = -1; 225 ptyfd = -1;
222 } 226 }
223 } 227 }
224 } 228 }
225 } 229 }
226#endif 230#endif
227 231
228 if ( ptyfd < 0 ) { 232 if ( ptyfd < 0 ) {
229 //qApp->exit(1); 233 //qApp->exit(1);
230 return -1; 234 return -1;
231 } 235 }
232 236
233 return ptyfd; 237 return ptyfd;
234} 238}
235 239
236/*! 240/*!
237 Create an instance. 241 Create an instance.
238*/ 242*/
239MyPty::MyPty(const Profile& prof) : m_cpid(0) 243MyPty::MyPty(const Profile& prof) : m_cpid(0)
240{ 244{
241 245
242 int term = prof.readNumEntry("Terminal", Profile::VT100 ); 246 int term = prof.readNumEntry("Terminal", Profile::VT100 );
243 switch( term ) { 247 switch( term ) {
244 default: 248 default:
245 case Profile::VT100: 249 case Profile::VT100:
246 case Profile::VT102: 250 case Profile::VT102:
247 m_term = "vt100"; 251 m_term = "vt100";
248 break; 252 break;
249 case Profile::Linux: 253 case Profile::Linux:
250 m_term = "linux"; 254 m_term = "linux";
251 break; 255 break;
252 case Profile::XTerm: 256 case Profile::XTerm:
253 m_term = "xterm"; 257 m_term = "xterm";
254 break; 258 break;
255 } 259 }
256 m_sn_e = 0l; 260 m_sn_e = 0l;
257 m_sn_r = 0l; 261 m_sn_r = 0l;
258 m_fd = openPty(); 262 m_fd = openPty();
259 ProcCtl* ctl = ProcCtl::self(); 263 ProcCtl* ctl = ProcCtl::self();
260 Q_UNUSED(ctl); 264 Q_UNUSED(ctl);
261 reload(prof); 265 reload(prof);
262} 266}
263 267
264/*! 268/*!
265 Destructor. 269 Destructor.
266 Note that the related client program is not killed 270 Note that the related client program is not killed
267 (yet) when a instance is deleted. 271 (yet) when a instance is deleted.
268*/ 272*/
269MyPty::~MyPty() 273MyPty::~MyPty()
270{ 274{
271 donePty(); 275 donePty();
272} 276}
273QString MyPty::identifier()const { 277QString MyPty::identifier()const {
274 return QString::fromLatin1("term"); 278 return QString::fromLatin1("term");
275} 279}
276QString MyPty::name()const{ 280QString MyPty::name()const{
277 return identifier(); 281 return identifier();
278} 282}
279bool MyPty::open() { 283bool MyPty::open() {
280 if (m_fd < 0) 284 if (m_fd < 0)
281 m_fd = openPty(); 285 m_fd = openPty();
282 286
283 start(); 287 start();
284 return true; 288 return true;
285} 289}
286void MyPty::close() { 290void MyPty::close() {
287 donePty(); 291 donePty();
288 m_fd = openPty(); 292 m_fd = openPty();
289} 293}
290void MyPty::reload( const Profile& prof) { 294void MyPty::reload( const Profile& prof) {
291 m_env.clear(); 295 m_env.clear();
292 m_cmd = prof.readEntry("Command", "/bin/sh"); 296 m_cmd = prof.readEntry("Command", "/bin/sh");
293 297
294 /* 298 /*
295 * Lets check if m_cmd actually 299 * Lets check if m_cmd actually
296 * exists.... 300 * exists....
297 * we try to use bin/bash and if 301 * we try to use bin/bash and if
298 * this fails we 302 * this fails we
299 * will fallback to /bin/sh 303 * will fallback to /bin/sh
300 * which should be there 100% 304 * which should be there 100%
301 */ 305 */
302 if ( m_cmd.stripWhiteSpace() == "/bin/bash" && !QFile::exists(QFile::encodeName(m_cmd) ) ) 306 if ( m_cmd.stripWhiteSpace() == "/bin/bash" && !QFile::exists(QFile::encodeName(m_cmd) ) )
303 m_cmd = "/bin/sh"; 307 m_cmd = "/bin/sh";
304 308
305 309
306 int envcount = prof.readNumEntry("EnvVars", 0); 310 int envcount = prof.readNumEntry("EnvVars", 0);
307 for (int i=0; i<envcount; i++) { 311 for (int i=0; i<envcount; i++) {
308 QString name = prof.readEntry("Env_Name_" + QString::number(i), ""); 312 QString name = prof.readEntry("Env_Name_" + QString::number(i), "");
309 QString value = prof.readEntry("Env_Value_" + QString::number(i), ""); 313 QString value = prof.readEntry("Env_Value_" + QString::number(i), "");
310 if (!(name.isEmpty() || value.isEmpty())) { 314 if (!(name.isEmpty() || value.isEmpty())) {
311 m_env.insert(name, value); 315 m_env.insert(name, value);
312 } 316 }
313 } 317 }
314} 318}
315/*! sends len bytes through the line */ 319/*! sends len bytes through the line */
316void MyPty::send(const QByteArray& ar) 320void MyPty::send(const QByteArray& ar)
317{ 321{
318#ifdef VERBOSE_DEBUG 322#ifdef VERBOSE_DEBUG
319 // verbose debug 323 // verbose debug
320 printf("sending bytes:\n"); 324 printf("sending bytes:\n");
321 for (uint i = 0; i < ar.count(); i++) 325 for (uint i = 0; i < ar.count(); i++)
322 printf("%c", ar[i]); 326 printf("%c", ar[i]);
323 printf("\n"); 327 printf("\n");
324#endif 328#endif
325 329
326 ::write(m_fd, ar.data(), ar.count()); 330 ::write(m_fd, ar.data(), ar.count());
327} 331}
328 332
329/*! indicates that a block of data is received */ 333/*! indicates that a block of data is received */
330void MyPty::readPty() 334void MyPty::readPty()
331{ 335{
332 QByteArray buf(4096); 336 QByteArray buf(4096);
333 337
334 int len = ::read( m_fd, buf.data(), 4096 ); 338 int len = ::read( m_fd, buf.data(), 4096 );
335 339
336 if (len == -1 || len == 0) { 340 if (len == -1 || len == 0) {
337 donePty(); 341 donePty();
338 return; 342 return;
339 } 343 }
340 344
341 if (len < 0) 345 if (len < 0)
342 return; 346 return;
343 347
344 348
345 buf.resize(len); 349 buf.resize(len);
346 emit received(buf); 350 emit received(buf);
347 351
348#ifdef VERBOSE_DEBUG 352#ifdef VERBOSE_DEBUG
349 // verbose debug 353 // verbose debug
350 printf("read bytes:\n"); 354 printf("read bytes:\n");
351 for (uint i = 0; i < buf.count(); i++) 355 for (uint i = 0; i < buf.count(); i++)
352 printf("%c", buf[i]); 356 printf("%c", buf[i]);
353 printf("\n"); 357 printf("\n");
354#endif 358#endif
355 359
356} 360}
357QBitArray MyPty::supports()const { 361QBitArray MyPty::supports()const {
358 QBitArray ar(3); 362 QBitArray ar(3);
359 //autoconnect 363 //autoconnect
360 ar[0] = 1; 364 ar[0] = 1;
361 // 365 //
362 ar[1] = 0; 366 ar[1] = 0;
363 ar[2] = 0; 367 ar[2] = 0;
364 368
365 return ar; 369 return ar;
366} 370}
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
@@ -1,1356 +1,1356 @@
1/* ------------------------------------------------------------------------ */ 1/* ------------------------------------------------------------------------ */
2/* */ 2/* */
3/* [TEWidget.C] Terminal Emulation Widget */ 3/* [TEWidget.C] Terminal Emulation Widget */
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/*! \class TEWidget 18/*! \class TEWidget
19 19
20 \brief Visible screen contents 20 \brief Visible screen contents
21 21
22 This class is responsible to map the `image' of a terminal emulation to the 22 This class is responsible to map the `image' of a terminal emulation to the
23 display. All the dependency of the emulation to a specific GUI or toolkit is 23 display. All the dependency of the emulation to a specific GUI or toolkit is
24 localized here. Further, this widget has no knowledge about being part of an 24 localized here. Further, this widget has no knowledge about being part of an
25 emulation, it simply work within the terminal emulation framework by exposing 25 emulation, it simply work within the terminal emulation framework by exposing
26 size and key events and by being ordered to show a new image. 26 size and key events and by being ordered to show a new image.
27 27
28 <ul> 28 <ul>
29 <li> The internal image has the size of the widget (evtl. rounded up) 29 <li> The internal image has the size of the widget (evtl. rounded up)
30 <li> The external image used in setImage can have any size. 30 <li> The external image used in setImage can have any size.
31 <li> (internally) the external image is simply copied to the internal 31 <li> (internally) the external image is simply copied to the internal
32 when a setImage happens. During a resizeEvent no painting is done 32 when a setImage happens. During a resizeEvent no painting is done
33 a paintEvent is expected to follow anyway. 33 a paintEvent is expected to follow anyway.
34 </ul> 34 </ul>
35 35
36 \sa TEScreen \sa Emulation 36 \sa TEScreen \sa Emulation
37*/ 37*/
38 38
39/* FIXME: 39/* FIXME:
40 - 'image' may also be used uninitialized (it isn't in fact) in resizeEvent 40 - 'image' may also be used uninitialized (it isn't in fact) in resizeEvent
41 - 'font_a' not used in mouse events 41 - 'font_a' not used in mouse events
42 - add destructor 42 - add destructor
43*/ 43*/
44 44
45/* TODO 45/* TODO
46 - evtl. be sensitive to `paletteChange' while using default colors. 46 - evtl. be sensitive to `paletteChange' while using default colors.
47 - set different 'rounding' styles? I.e. have a mode to show clipped chars? 47 - set different 'rounding' styles? I.e. have a mode to show clipped chars?
48*/ 48*/
49 49
50// #include "config.h" 50// #include "config.h"
51#include "TEWidget.h" 51#include "TEWidget.h"
52#include <qpe/config.h> 52#include <qpe/config.h>
53 53
54#include <qapplication.h> 54#include <qapplication.h>
55#include <qclipboard.h> 55#include <qclipboard.h>
56 56
57#include <stdio.h> 57#include <stdio.h>
58#include <stdlib.h> 58#include <stdlib.h>
59#include <unistd.h> 59#include <unistd.h>
60#include <ctype.h> 60#include <ctype.h>
61#include <sys/stat.h> 61#include <sys/stat.h>
62#include <sys/types.h> 62#include <sys/types.h>
63#include <signal.h> 63#include <signal.h>
64 64
65#include <assert.h> 65#include <assert.h>
66 66
67 67
68 68
69// #include "TEWidget.moc" 69// #include "TEWidget.moc"
70//#include <kapp.h> 70//#include <kapp.h>
71//#include <kcursor.h> 71//#include <kcursor.h>
72//#include <kurl.h> 72//#include <kurl.h>
73//#include <kdebug.h> 73//#include <kdebug.h>
74//#include <klocale.h> 74//#include <klocale.h>
75 75
76#define HERE printf("%s(%d): %s\n",__FILE__,__LINE__,__FUNCTION__) 76#define HERE printf("%s(%d): %s\n",__FILE__,__LINE__,__FUNCTION__)
77#define HCNT(Name) // { static int cnt = 1; printf("%s(%d): %s %d\n",__FILE__,__LINE__,Name,cnt++); } 77#define HCNT(Name) // { static int cnt = 1; printf("%s(%d): %s %d\n",__FILE__,__LINE__,Name,cnt++); }
78 78
79#define loc(X,Y) ((Y)*columns+(X)) 79#define loc(X,Y) ((Y)*columns+(X))
80 80
81//FIXME: the rim should normally be 1, 0 only when running in full screen mode. 81//FIXME: the rim should normally be 1, 0 only when running in full screen mode.
82#define rimX 0 // left/right rim width 82#define rimX 0 // left/right rim width
83#define rimY 0 // top/bottom rim high 83#define rimY 0 // top/bottom rim high
84 84
85#define yMouseScroll 1 85#define yMouseScroll 1
86// scroll increment used when dragging selection at top/bottom of window. 86// scroll increment used when dragging selection at top/bottom of window.
87 87
88/* Button XPM */ 88/* Button XPM */
89namespace { 89namespace {
90static char * menu_xpm[] = { 90static char * menu_xpm[] = {
91"12 12 5 1", 91"12 12 5 1",
92 " c None", 92 " c None",
93 ".c #000000", 93 ".c #000000",
94 "+c #FFFDAD", 94 "+c #FFFDAD",
95 "@c #FFFF00", 95 "@c #FFFF00",
96 "#c #E5E100", 96 "#c #E5E100",
97" ", 97" ",
98" ", 98" ",
99" ......... ", 99" ......... ",
100" .+++++++. ", 100" .+++++++. ",
101" .+@@@@#. ", 101" .+@@@@#. ",
102" .+@@@#. ", 102" .+@@@#. ",
103" .+@@#. ", 103" .+@@#. ",
104" .+@#. ", 104" .+@#. ",
105" .+#. ", 105" .+#. ",
106" .+. ", 106" .+. ",
107" .. ", 107" .. ",
108" "}; 108" "};
109 109
110} 110}
111 111
112 112
113/* ------------------------------------------------------------------------- */ 113/* ------------------------------------------------------------------------- */
114/* */ 114/* */
115/* Colors */ 115/* Colors */
116/* */ 116/* */
117/* ------------------------------------------------------------------------- */ 117/* ------------------------------------------------------------------------- */
118 118
119//FIXME: the default color table is in session.C now. 119//FIXME: the default color table is in session.C now.
120// We need a way to get rid of this one, here. 120// We need a way to get rid of this one, here.
121static const ColorEntry base_color_table[TABLE_COLORS] = 121static const ColorEntry base_color_table[TABLE_COLORS] =
122// The following are almost IBM standard color codes, with some slight 122// The following are almost IBM standard color codes, with some slight
123// gamma correction for the dim colors to compensate for bright X screens. 123// gamma correction for the dim colors to compensate for bright X screens.
124// It contains the 8 ansiterm/xterm colors in 2 intensities. 124// It contains the 8 ansiterm/xterm colors in 2 intensities.
125{ 125{
126 // Fixme: could add faint colors here, also. 126 // Fixme: could add faint colors here, also.
127 // normal 127 // normal
128 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback 128 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback
129 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red 129 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red
130 ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow 130 ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow
131 ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta 131 ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta
132 ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White 132 ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White
133 // intensiv 133 // intensiv
134 ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ), 134 ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ),
135 ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ), 135 ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ),
136 ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ), 136 ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ),
137 ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), 137 ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ),
138 ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 ) 138 ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 )
139}; 139};
140 140
141/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) 141/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb)
142 142
143 Code 0 1 2 3 4 5 6 7 143 Code 0 1 2 3 4 5 6 7
144 ----------- ------- ------- ------- ------- ------- ------- ------- ------- 144 ----------- ------- ------- ------- ------- ------- ------- ------- -------
145 ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White 145 ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White
146 IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White 146 IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White
147*/ 147*/
148 148
149QColor TEWidget::getDefaultBackColor() 149QColor TEWidget::getDefaultBackColor()
150{ 150{
151 return color_table[DEFAULT_BACK_COLOR].color; 151 return color_table[DEFAULT_BACK_COLOR].color;
152} 152}
153 153
154const ColorEntry* TEWidget::getColorTable() const 154const ColorEntry* TEWidget::getColorTable() const
155{ 155{
156 return color_table; 156 return color_table;
157} 157}
158 158
159const ColorEntry* TEWidget::getdefaultColorTable() const 159const ColorEntry* TEWidget::getdefaultColorTable() const
160{ 160{
161 return base_color_table; 161 return base_color_table;
162} 162}
163 163
164 164
165const QPixmap *TEWidget::backgroundPixmap() 165const QPixmap *TEWidget::backgroundPixmap()
166{ 166{
167 static QPixmap *bg = new QPixmap("~/qpim/main/pics/faded_bg.xpm"); 167 static QPixmap *bg = new QPixmap("~/qpim/main/pics/faded_bg.xpm");
168 const QPixmap *pm = bg; 168 const QPixmap *pm = bg;
169 return pm; 169 return pm;
170} 170}
171 171
172void TEWidget::setColorTable(const ColorEntry table[]) 172void TEWidget::setColorTable(const ColorEntry table[])
173{ 173{
174 for (int i = 0; i < TABLE_COLORS; i++) color_table[i] = table[i]; 174 for (int i = 0; i < TABLE_COLORS; i++) color_table[i] = table[i];
175 175
176 const QPixmap* pm = backgroundPixmap(); 176 const QPixmap* pm = backgroundPixmap();
177 if (!pm) setBackgroundColor(color_table[DEFAULT_BACK_COLOR].color); 177 if (!pm) setBackgroundColor(color_table[DEFAULT_BACK_COLOR].color);
178 update(); 178 update();
179} 179}
180 180
181//FIXME: add backgroundPixmapChanged. 181//FIXME: add backgroundPixmapChanged.
182 182
183/* ------------------------------------------------------------------------- */ 183/* ------------------------------------------------------------------------- */
184/* */ 184/* */
185/* Font */ 185/* Font */
186/* */ 186/* */
187/* ------------------------------------------------------------------------- */ 187/* ------------------------------------------------------------------------- */
188 188
189/* 189/*
190 The VT100 has 32 special graphical characters. The usual vt100 extended 190 The VT100 has 32 special graphical characters. The usual vt100 extended
191 xterm fonts have these at 0x00..0x1f. 191 xterm fonts have these at 0x00..0x1f.
192 192
193 QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals 193 QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals
194 come in here as proper unicode characters. 194 come in here as proper unicode characters.
195 195
196 We treat non-iso10646 fonts as VT100 extended and do the requiered mapping 196 We treat non-iso10646 fonts as VT100 extended and do the requiered mapping
197 from unicode to 0x00..0x1f. The remaining translation is then left to the 197 from unicode to 0x00..0x1f. The remaining translation is then left to the
198 QCodec. 198 QCodec.
199*/ 199*/
200 200
201// assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. 201// assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i.
202 202
203unsigned short vt100_graphics[32] = 203unsigned short vt100_graphics[32] =
204{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 204{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15
205 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 205 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0,
206 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 206 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c,
207 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, 207 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534,
208 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 208 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7
209}; 209};
210 210
211static QChar vt100extended(QChar c) 211static QChar vt100extended(QChar c)
212{ 212{
213 switch (c.unicode()) 213 switch (c.unicode())
214 { 214 {
215 case 0x25c6 : return 1; 215 case 0x25c6 : return 1;
216 case 0x2592 : return 2; 216 case 0x2592 : return 2;
217 case 0x2409 : return 3; 217 case 0x2409 : return 3;
218 case 0x240c : return 4; 218 case 0x240c : return 4;
219 case 0x240d : return 5; 219 case 0x240d : return 5;
220 case 0x240a : return 6; 220 case 0x240a : return 6;
221 case 0x00b0 : return 7; 221 case 0x00b0 : return 7;
222 case 0x00b1 : return 8; 222 case 0x00b1 : return 8;
223 case 0x2424 : return 9; 223 case 0x2424 : return 9;
224 case 0x240b : return 10; 224 case 0x240b : return 10;
225 case 0x2518 : return 11; 225 case 0x2518 : return 11;
226 case 0x2510 : return 12; 226 case 0x2510 : return 12;
227 case 0x250c : return 13; 227 case 0x250c : return 13;
228 case 0x2514 : return 14; 228 case 0x2514 : return 14;
229 case 0x253c : return 15; 229 case 0x253c : return 15;
230 case 0xf800 : return 16; 230 case 0xf800 : return 16;
231 case 0xf801 : return 17; 231 case 0xf801 : return 17;
232 case 0x2500 : return 18; 232 case 0x2500 : return 18;
233 case 0xf803 : return 19; 233 case 0xf803 : return 19;
234 case 0xf804 : return 20; 234 case 0xf804 : return 20;
235 case 0x251c : return 21; 235 case 0x251c : return 21;
236 case 0x2524 : return 22; 236 case 0x2524 : return 22;
237 case 0x2534 : return 23; 237 case 0x2534 : return 23;
238 case 0x252c : return 24; 238 case 0x252c : return 24;
239 case 0x2502 : return 25; 239 case 0x2502 : return 25;
240 case 0x2264 : return 26; 240 case 0x2264 : return 26;
241 case 0x2265 : return 27; 241 case 0x2265 : return 27;
242 case 0x03c0 : return 28; 242 case 0x03c0 : return 28;
243 case 0x2260 : return 29; 243 case 0x2260 : return 29;
244 case 0x00a3 : return 30; 244 case 0x00a3 : return 30;
245 case 0x00b7 : return 31; 245 case 0x00b7 : return 31;
246 } 246 }
247 return c; 247 return c;
248} 248}
249 249
250static QChar identicalMap(QChar c) 250static QChar identicalMap(QChar c)
251{ 251{
252 return c; 252 return c;
253} 253}
254 254
255void TEWidget::fontChange(const QFont &) 255void TEWidget::fontChange(const QFont &)
256{ 256{
257 QFontMetrics fm(font()); 257 QFontMetrics fm(font());
258 font_h = fm.height(); 258 font_h = fm.height();
259 font_w = fm.maxWidth(); 259 font_w = fm.maxWidth();
260 font_a = fm.ascent(); 260 font_a = fm.ascent();
261//printf("font_h: %d\n",font_h); 261//printf("font_h: %d\n",font_h);
262//printf("font_w: %d\n",font_w); 262//printf("font_w: %d\n",font_w);
263//printf("font_a: %d\n",font_a); 263//printf("font_a: %d\n",font_a);
264//printf("charset: %s\n",QFont::encodingName(font().charSet()).ascii()); 264//printf("charset: %s\n",QFont::encodingName(font().charSet()).ascii());
265//printf("rawname: %s\n",font().rawName().ascii()); 265//printf("rawname: %s\n",font().rawName().ascii());
266 fontMap = 266 fontMap =
267#if QT_VERSION < 300 267#if QT_VERSION < 300
268 strcmp(QFont::encodingName(font().charSet()).ascii(),"iso10646") 268 strcmp(QFont::encodingName(font().charSet()).ascii(),"iso10646")
269 ? vt100extended 269 ? vt100extended
270 : 270 :
271#endif 271#endif
272 identicalMap; 272 identicalMap;
273 propagateSize(); 273 propagateSize();
274 update(); 274 update();
275} 275}
276 276
277void TEWidget::setVTFont(const QFont& f) 277void TEWidget::setVTFont(const QFont& f)
278{ 278{
279 QFrame::setFont(f); 279 QFrame::setFont(f);
280} 280}
281 281
282QFont TEWidget::getVTFont() { 282QFont TEWidget::getVTFont() {
283 return font(); 283 return font();
284} 284}
285 285
286void TEWidget::setFont(const QFont &) 286void TEWidget::setFont(const QFont &)
287{ 287{
288 // ignore font change request if not coming from konsole itself 288 // ignore font change request if not coming from konsole itself
289} 289}
290 290
291/* ------------------------------------------------------------------------- */ 291/* ------------------------------------------------------------------------- */
292/* */ 292/* */
293/* Constructor / Destructor */ 293/* Constructor / Destructor */
294/* */ 294/* */
295/* ----------------------------------------------------------------------- */ 295/* ----------------------------------------------------------------------- */
296 296
297 297
298 298
299TEWidget::TEWidget(QWidget *parent, const char *name) : QFrame(parent,name) 299TEWidget::TEWidget(QWidget *parent, const char *name) : QFrame(parent,name)
300{ 300{
301#ifndef QT_NO_CLIPBOARD 301#ifndef QT_NO_CLIPBOARD
302 cb = QApplication::clipboard(); 302 cb = QApplication::clipboard();
303 QObject::connect( (QObject*)cb, SIGNAL(dataChanged()), 303 QObject::connect( (QObject*)cb, SIGNAL(dataChanged()),
304 this, SLOT(onClearSelection()) ); 304 this, SLOT(onClearSelection()) );
305#endif 305#endif
306 306
307 307
308 scrollbar = new QScrollBar( this ); 308 scrollbar = new QScrollBar( this );
309 scrollbar->setCursor( arrowCursor ); 309 scrollbar->setCursor( arrowCursor );
310 connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); 310 connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int)));
311 311
312 hscrollbar = new QScrollBar( Qt::Horizontal, this ); 312 hscrollbar = new QScrollBar( Qt::Horizontal, this );
313 hscrollbar->setCursor( arrowCursor ); 313 hscrollbar->setCursor( arrowCursor );
314 connect(hscrollbar, SIGNAL(valueChanged(int)), this, SLOT(hscrollChanged(int))); 314 connect(hscrollbar, SIGNAL(valueChanged(int)), this, SLOT(hscrollChanged(int)));
315 315
316 m_cornerButton = new QPushButton( this ); 316 m_cornerButton = new QPushButton( this );
317 m_cornerButton->setPixmap( QPixmap( (const char**)menu_xpm ) ); 317 m_cornerButton->setPixmap( QPixmap( (const char**)menu_xpm ) );
318 m_cornerButton->setMaximumSize( 14, 14 ); 318 m_cornerButton->setMaximumSize( 14, 14 );
319 m_cornerButton->hide(); 319 m_cornerButton->hide();
320 320
321 Config cfg("Konsole"); 321 Config cfg("Konsole");
322 cfg.setGroup("ScrollBar"); 322 cfg.setGroup("ScrollBar");
323 switch( cfg.readNumEntry("Position",2)){ 323 switch( cfg.readNumEntry("Position",2)){
324 case 0: 324 case 0:
325 scrollLoc = SCRNONE; 325 scrollLoc = SCRNONE;
326 break; 326 break;
327 case 1: 327 case 1:
328 scrollLoc = SCRLEFT; 328 scrollLoc = SCRLEFT;
329 break; 329 break;
330 case 2: 330 case 2:
331 scrollLoc = SCRRIGHT; 331 scrollLoc = SCRRIGHT;
332 break; 332 break;
333 }; 333 };
334 334
335 blinkT = new QTimer(this); 335 blinkT = new QTimer(this);
336 connect(blinkT, SIGNAL(timeout()), this, SLOT(blinkEvent())); 336 connect(blinkT, SIGNAL(timeout()), this, SLOT(blinkEvent()));
337 // blinking = FALSE; 337 // blinking = FALSE;
338 blinking = TRUE; 338 blinking = TRUE;
339 339
340 resizing = FALSE; 340 resizing = FALSE;
341 actSel = 0; 341 actSel = 0;
342 image = 0; 342 image = 0;
343 lines = 1; 343 lines = 1;
344 columns = 1; 344 columns = 1;
345 font_w = 1; 345 font_w = 1;
346 font_h = 1; 346 font_h = 1;
347 font_a = 1; 347 font_a = 1;
348 word_selection_mode = FALSE; 348 word_selection_mode = FALSE;
349 vcolumns = 0; 349 vcolumns = 0;
350 hposition = 0; 350 hposition = 0;
351 351
352 setMouseMarks(TRUE); 352 setMouseMarks(TRUE);
353 setVTFont( QFont("fixed") ); 353 setVTFont( QFont("fixed") );
354 setColorTable(base_color_table); // init color table 354 setColorTable(base_color_table); // init color table
355 355
356 qApp->installEventFilter( this ); //FIXME: see below 356 qApp->installEventFilter( this ); //FIXME: see below
357// KCursor::setAutoHideCursor( this, true ); 357// KCursor::setAutoHideCursor( this, true );
358 358
359 // Init DnD //////////////////////////////////////////////////////////////// 359 // Init DnD ////////////////////////////////////////////////////////////////
360 currentSession = NULL; 360 currentSession = NULL;
361// setAcceptDrops(true); // attempt 361// setAcceptDrops(true); // attempt
362// m_drop = new QPopupMenu(this); 362// m_drop = new QPopupMenu(this);
363// m_drop->insertItem( QString("Paste"), 0); 363// m_drop->insertItem( QString("Paste"), 0);
364// m_drop->insertItem( QString("cd"), 1); 364// m_drop->insertItem( QString("cd"), 1);
365// connect(m_drop, SIGNAL(activated(int)), SLOT(drop_menu_activated(int))); 365// connect(m_drop, SIGNAL(activated(int)), SLOT(drop_menu_activated(int)));
366 366
367 // we need focus so that the auto-hide cursor feature works 367 // we need focus so that the auto-hide cursor feature works
368 setFocus(); 368 setFocus();
369 setFocusPolicy( WheelFocus ); 369 setFocusPolicy( WheelFocus );
370} 370}
371 371
372//FIXME: make proper destructor 372//FIXME: make proper destructor
373// Here's a start (David) 373// Here's a start (David)
374TEWidget::~TEWidget() 374TEWidget::~TEWidget()
375{ 375{
376 qApp->removeEventFilter( this ); 376 qApp->removeEventFilter( this );
377 if (image) free(image); 377 if (image) free(image);
378} 378}
379 379
380/* ------------------------------------------------------------------------- */ 380/* ------------------------------------------------------------------------- */
381/* */ 381/* */
382/* Display Operations */ 382/* Display Operations */
383/* */ 383/* */
384/* ------------------------------------------------------------------------- */ 384/* ------------------------------------------------------------------------- */
385 385
386/*! 386/*!
387 attributed string draw primitive 387 attributed string draw primitive
388*/ 388*/
389 389
390void TEWidget::drawAttrStr(QPainter &paint, QRect rect, 390void TEWidget::drawAttrStr(QPainter &paint, QRect rect,
391 QString& str, ca attr, BOOL pm, BOOL clear) 391 QString& str, ca attr, BOOL pm, BOOL clear)
392{ 392{
393 if (pm && color_table[attr.b].transparent) 393 if (pm && color_table[attr.b].transparent)
394 { 394 {
395 paint.setBackgroundMode( TransparentMode ); 395 paint.setBackgroundMode( TransparentMode );
396 if (clear) erase(rect); 396 if (clear) erase(rect);
397 } 397 }
398 else 398 else
399 { 399 {
400 if (blinking) 400 if (blinking)
401 paint.fillRect(rect, color_table[attr.b].color); 401 paint.fillRect(rect, color_table[attr.b].color);
402 else 402 else
403 { 403 {
404 paint.setBackgroundMode( OpaqueMode ); 404 paint.setBackgroundMode( OpaqueMode );
405 paint.setBackgroundColor( color_table[attr.b].color ); 405 paint.setBackgroundColor( color_table[attr.b].color );
406 } 406 }
407 } 407 }
408 408
409 if (color_table[attr.f].bold) 409 if (color_table[attr.f].bold)
410 paint.setPen(QColor( 0x8F, 0x00, 0x00 )); 410 paint.setPen(QColor( 0x8F, 0x00, 0x00 ));
411 else 411 else
412 paint.setPen(color_table[attr.f].color); 412 paint.setPen(color_table[attr.f].color);
413 413
414 paint.drawText(rect.x(),rect.y()+font_a, str); 414 paint.drawText(rect.x(),rect.y()+font_a, str);
415 415
416 if (attr.r & RE_UNDERLINE) 416 if (attr.r & RE_UNDERLINE)
417 paint.drawLine(rect.left(), rect.y()+font_a+1, rect.right(),rect.y()+font_a+1 ); 417 paint.drawLine(rect.left(), rect.y()+font_a+1, rect.right(),rect.y()+font_a+1 );
418} 418}
419 419
420/*! 420/*!
421 The image can only be set completely. 421 The image can only be set completely.
422 422
423 The size of the new image may or may not match the size of the widget. 423 The size of the new image may or may not match the size of the widget.
424*/ 424*/
425 425
426void TEWidget::setImage(const ca* const newimg, int lines, int columns) 426void TEWidget::setImage(const ca* const newimg, int lines, int columns)
427{ int y,x,len; 427{ int y,x,len;
428 const QPixmap* pm = backgroundPixmap(); 428 const QPixmap* pm = backgroundPixmap();
429 QPainter paint; 429 QPainter paint;
430 setUpdatesEnabled(FALSE); 430 setUpdatesEnabled(FALSE);
431 paint.begin( this ); 431 paint.begin( this );
432HCNT("setImage"); 432HCNT("setImage");
433 433
434 QPoint tL = contentsRect().topLeft(); 434 QPoint tL = contentsRect().topLeft();
435 int tLx = tL.x(); 435 int tLx = tL.x();
436 int tLy = tL.y(); 436 int tLy = tL.y();
437 hasBlinker = FALSE; 437 hasBlinker = FALSE;
438 438
439 int cf = -1; // undefined 439 int cf = -1; // undefined
440 int cb = -1; // undefined 440 int cb = -1; // undefined
441 int cr = -1; // undefined 441 int cr = -1; // undefined
442 442
443 int lins = QMIN(this->lines, QMAX(0,lines )); 443 int lins = QMIN(this->lines, QMAX(0,lines ));
444 int cols = QMIN(this->columns,QMAX(0,columns)); 444 int cols = QMIN(this->columns,QMAX(0,columns));
445 QChar *disstrU = new QChar[cols]; 445 QChar *disstrU = new QChar[cols];
446 446
447//{ static int cnt = 0; printf("setImage %d\n",cnt++); } 447//{ static int cnt = 0; printf("setImage %d\n",cnt++); }
448 for (y = 0; y < lins; y++) 448 for (y = 0; y < lins; y++)
449 { 449 {
450 const ca* lcl = &image[y*this->columns]; 450 const ca* lcl = &image[y*this->columns];
451 const ca* const ext = &newimg[y*columns]; 451 const ca* const ext = &newimg[y*columns];
452 if (!resizing) // not while resizing, we're expecting a paintEvent 452 if (!resizing) // not while resizing, we're expecting a paintEvent
453 for (x = 0; x < cols; x++) 453 for (x = 0; x < cols; x++)
454 { 454 {
455 hasBlinker |= (ext[x].r & RE_BLINK); 455 hasBlinker |= (ext[x].r & RE_BLINK);
456 if (ext[x] != lcl[x]) 456 if (ext[x] != lcl[x])
457 { 457 {
458 cr = ext[x].r; 458 cr = ext[x].r;
459 cb = ext[x].b; 459 cb = ext[x].b;
460 if (ext[x].f != cf) cf = ext[x].f; 460 if (ext[x].f != cf) cf = ext[x].f;
461 int lln = cols - x; 461 int lln = cols - x;
462 disstrU[0] = fontMap(ext[x+0].c); 462 disstrU[0] = fontMap(ext[x+0].c);
463 for (len = 1; len < lln; len++) 463 for (len = 1; len < lln; len++)
464 { 464 {
465 if (ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr || 465 if (ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr ||
466 ext[x+len] == lcl[x+len] ) 466 ext[x+len] == lcl[x+len] )
467 break; 467 break;
468 disstrU[len] = fontMap(ext[x+len].c); 468 disstrU[len] = fontMap(ext[x+len].c);
469 } 469 }
470 QString unistr(disstrU,len); 470 QString unistr(disstrU,len);
471 drawAttrStr(paint, 471 drawAttrStr(paint,
472 QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), 472 QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h),
473 unistr, ext[x], pm != NULL, true); 473 unistr, ext[x], pm != NULL, true);
474 x += len - 1; 474 x += len - 1;
475 } 475 }
476 } 476 }
477 // finally, make `image' become `newimg'. 477 // finally, make `image' become `newimg'.
478 memcpy((void*)lcl,(const void*)ext,cols*sizeof(ca)); 478 memcpy((void*)lcl,(const void*)ext,cols*sizeof(ca));
479 } 479 }
480 drawFrame( &paint ); 480 drawFrame( &paint );
481 paint.end(); 481 paint.end();
482 setUpdatesEnabled(TRUE); 482 setUpdatesEnabled(TRUE);
483 if ( hasBlinker && !blinkT->isActive()) blinkT->start(1000); // 1000 ms 483 if ( hasBlinker && !blinkT->isActive()) blinkT->start(1000); // 1000 ms
484 if (!hasBlinker && blinkT->isActive()) { blinkT->stop(); blinking = FALSE; } 484 if (!hasBlinker && blinkT->isActive()) { blinkT->stop(); blinking = FALSE; }
485 delete [] disstrU; 485 delete [] disstrU;
486} 486}
487 487
488// paint Event //////////////////////////////////////////////////// 488// paint Event ////////////////////////////////////////////////////
489 489
490/*! 490/*!
491 The difference of this routine vs. the `setImage' is, 491 The difference of this routine vs. the `setImage' is,
492 that the drawing does not include a difference analysis 492 that the drawing does not include a difference analysis
493 between the old and the new image. Instead, the internal 493 between the old and the new image. Instead, the internal
494 image is used and the painting bound by the PaintEvent box. 494 image is used and the painting bound by the PaintEvent box.
495*/ 495*/
496 496
497void TEWidget::paintEvent( QPaintEvent* pe ) 497void TEWidget::paintEvent( QPaintEvent* pe )
498{ 498{
499 499
500//{ static int cnt = 0; printf("paint %d\n",cnt++); } 500//{ static int cnt = 0; printf("paint %d\n",cnt++); }
501 const QPixmap* pm = backgroundPixmap(); 501 const QPixmap* pm = backgroundPixmap();
502 QPainter paint; 502 QPainter paint;
503 setUpdatesEnabled(FALSE); 503 setUpdatesEnabled(FALSE);
504 paint.begin( this ); 504 paint.begin( this );
505 paint.setBackgroundMode( TransparentMode ); 505 paint.setBackgroundMode( TransparentMode );
506HCNT("paintEvent"); 506HCNT("paintEvent");
507 507
508 // Note that the actual widget size can be slightly larger 508 // Note that the actual widget size can be slightly larger
509 // that the image (the size is truncated towards the smaller 509 // that the image (the size is truncated towards the smaller
510 // number of characters in `resizeEvent'. The paint rectangle 510 // number of characters in `resizeEvent'. The paint rectangle
511 // can thus be larger than the image, but less then the size 511 // can thus be larger than the image, but less then the size
512 // of one character. 512 // of one character.
513 513
514 QRect rect = pe->rect().intersect(contentsRect()); 514 QRect rect = pe->rect().intersect(contentsRect());
515 515
516 QPoint tL = contentsRect().topLeft(); 516 QPoint tL = contentsRect().topLeft();
517 int tLx = tL.x(); 517 int tLx = tL.x();
518 int tLy = tL.y(); 518 int tLy = tL.y();
519 519
520 int lux = QMIN(columns-1, QMAX(0,(rect.left() - tLx - blX ) / font_w)); 520 int lux = QMIN(columns-1, QMAX(0,(rect.left() - tLx - blX ) / font_w));
521 int luy = QMIN(lines-1, QMAX(0,(rect.top() - tLy - bY ) / font_h)); 521 int luy = QMIN(lines-1, QMAX(0,(rect.top() - tLy - bY ) / font_h));
522 int rlx = QMIN(columns-1, QMAX(0,(rect.right() - tLx - blX ) / font_w)); 522 int rlx = QMIN(columns-1, QMAX(0,(rect.right() - tLx - blX ) / font_w));
523 int rly = QMIN(lines-1, QMAX(0,(rect.bottom() - tLy - bY ) / font_h)); 523 int rly = QMIN(lines-1, QMAX(0,(rect.bottom() - tLy - bY ) / font_h));
524 524
525 /* 525 /*
526 printf("paintEvent: %d..%d, %d..%d (%d..%d, %d..%d)\n",lux,rlx,luy,rly, 526 printf("paintEvent: %d..%d, %d..%d (%d..%d, %d..%d)\n",lux,rlx,luy,rly,
527 rect.left(), rect.right(), rect.top(), rect.bottom()); 527 rect.left(), rect.right(), rect.top(), rect.bottom());
528 */ 528 */
529 529
530 // if (pm != NULL && color_table[image->b].transparent) 530 // if (pm != NULL && color_table[image->b].transparent)
531 // erase(rect); 531 // erase(rect);
532 // BL: I have no idea why we need this, and it breaks the refresh. 532 // BL: I have no idea why we need this, and it breaks the refresh.
533 533
534 QChar *disstrU = new QChar[columns]; 534 QChar *disstrU = new QChar[columns];
535 for (int y = luy; y <= rly; y++) 535 for (int y = luy; y <= rly; y++)
536 for (int x = lux; x <= rlx; x++) 536 for (int x = lux; x <= rlx; x++)
537 { 537 {
538 int len = 1; 538 int len = 1;
539 disstrU[0] = fontMap(image[loc(x,y)].c); 539 disstrU[0] = fontMap(image[loc(x,y)].c);
540 int cf = image[loc(x,y)].f; 540 int cf = image[loc(x,y)].f;
541 int cb = image[loc(x,y)].b; 541 int cb = image[loc(x,y)].b;
542 int cr = image[loc(x,y)].r; 542 int cr = image[loc(x,y)].r;
543 while (x+len <= rlx && 543 while (x+len <= rlx &&
544 image[loc(x+len,y)].f == cf && 544 image[loc(x+len,y)].f == cf &&
545 image[loc(x+len,y)].b == cb && 545 image[loc(x+len,y)].b == cb &&
546 image[loc(x+len,y)].r == cr ) 546 image[loc(x+len,y)].r == cr )
547 { 547 {
548 disstrU[len] = fontMap(image[loc(x+len,y)].c); 548 disstrU[len] = fontMap(image[loc(x+len,y)].c);
549 len += 1; 549 len += 1;
550 } 550 }
551 QString unistr(disstrU,len); 551 QString unistr(disstrU,len);
552 drawAttrStr(paint, 552 drawAttrStr(paint,
553 QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), 553 QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h),
554 unistr, image[loc(x,y)], pm != NULL, false); 554 unistr, image[loc(x,y)], pm != NULL, false);
555 x += len - 1; 555 x += len - 1;
556 } 556 }
557 delete [] disstrU; 557 delete [] disstrU;
558 drawFrame( &paint ); 558 drawFrame( &paint );
559 paint.end(); 559 paint.end();
560 setUpdatesEnabled(TRUE); 560 setUpdatesEnabled(TRUE);
561} 561}
562 562
563void TEWidget::blinkEvent() 563void TEWidget::blinkEvent()
564{ 564{
565 blinking = !blinking; 565 blinking = !blinking;
566 repaint(FALSE); 566 repaint(FALSE);
567} 567}
568 568
569/* ------------------------------------------------------------------------- */ 569/* ------------------------------------------------------------------------- */
570/* */ 570/* */
571/* Resizing */ 571/* Resizing */
572/* */ 572/* */
573/* ------------------------------------------------------------------------- */ 573/* ------------------------------------------------------------------------- */
574 574
575void TEWidget::resizeEvent(QResizeEvent* ev) 575void TEWidget::resizeEvent(QResizeEvent* ev)
576{ 576{
577// printf("resize: %d,%d\n",ev->size().width(),ev->size().height()); 577// printf("resize: %d,%d\n",ev->size().width(),ev->size().height());
578 //printf("approx: %d,%d\n",ev->size().width()/font_w,ev->size().height()/font_h); 578 //printf("approx: %d,%d\n",ev->size().width()/font_w,ev->size().height()/font_h);
579 //printf("leaves: %d,%d\n",ev->size().width()%font_w,ev->size().height()%font_h); 579 //printf("leaves: %d,%d\n",ev->size().width()%font_w,ev->size().height()%font_h);
580 //printf("curren: %d,%d\n",width(),height()); 580 //printf("curren: %d,%d\n",width(),height());
581HCNT("resizeEvent"); 581HCNT("resizeEvent");
582 582
583 // see comment in `paintEvent' concerning the rounding. 583 // see comment in `paintEvent' concerning the rounding.
584 //FIXME: could make a routine here; check width(),height() 584 //FIXME: could make a routine here; check width(),height()
585 assert(ev->size().width() == width()); 585 assert(ev->size().width() == width());
586 assert(ev->size().height() == height()); 586 assert(ev->size().height() == height());
587 587
588 propagateSize(); 588 propagateSize();
589} 589}
590 590
591void TEWidget::propagateSize() 591void TEWidget::propagateSize()
592{ 592{
593 ca* oldimg = image; 593 ca* oldimg = image;
594 int oldlin = lines; 594 int oldlin = lines;
595 int oldcol = columns; 595 int oldcol = columns;
596 makeImage(); 596 makeImage();
597 // we copy the old image to reduce flicker 597 // we copy the old image to reduce flicker
598 int lins = QMIN(oldlin,lines); 598 int lins = QMIN(oldlin,lines);
599 int cols = QMIN(oldcol,columns); 599 int cols = QMIN(oldcol,columns);
600 if (oldimg) 600 if (oldimg)
601 { 601 {
602 for (int lin = 0; lin < lins; lin++) 602 for (int lin = 0; lin < lins; lin++)
603 memcpy((void*)&image[columns*lin], 603 memcpy((void*)&image[columns*lin],
604 (void*)&oldimg[oldcol*lin],cols*sizeof(ca)); 604 (void*)&oldimg[oldcol*lin],cols*sizeof(ca));
605 free(oldimg); //FIXME: try new,delete 605 free(oldimg); //FIXME: try new,delete
606 } 606 }
607 else 607 else
608 clearImage(); 608 clearImage();
609 609
610 //NOTE: control flows from the back through the chest right into the eye. 610 //NOTE: control flows from the back through the chest right into the eye.
611 // `emu' will call back via `setImage'. 611 // `emu' will call back via `setImage'.
612 612
613 resizing = TRUE; 613 resizing = TRUE;
614 emit changedImageSizeSignal(lines, columns); // expose resizeEvent 614 emit changedImageSizeSignal(lines, columns); // expose resizeEvent
615 resizing = FALSE; 615 resizing = FALSE;
616} 616}
617 617
618/* ------------------------------------------------------------------------- */ 618/* ------------------------------------------------------------------------- */
619/* */ 619/* */
620/* Scrollbar */ 620/* Scrollbar */
621/* */ 621/* */
622/* ------------------------------------------------------------------------- */ 622/* ------------------------------------------------------------------------- */
623 623
624void TEWidget::scrollChanged(int) 624void TEWidget::scrollChanged(int)
625{ 625{
626 emit changedHistoryCursor(scrollbar->value()); //expose 626 emit changedHistoryCursor(scrollbar->value()); //expose
627} 627}
628 628
629void TEWidget::hscrollChanged(int loc) 629void TEWidget::hscrollChanged(int loc)
630{ 630{
631 hposition = loc; 631 hposition = loc;
632 propagateSize(); 632 propagateSize();
633 update(); 633 update();
634} 634}
635 635
636void TEWidget::setScroll(int cursor, int slines) 636void TEWidget::setScroll(int cursor, int slines)
637{ 637{
638 disconnect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); 638 disconnect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int)));
639 scrollbar->setRange(0,slines); 639 scrollbar->setRange(0,slines);
640 scrollbar->setSteps(1,lines); 640 scrollbar->setSteps(1,lines);
641 scrollbar->setValue(cursor); 641 scrollbar->setValue(cursor);
642 connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); 642 connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int)));
643} 643}
644 644
645void TEWidget::setScrollbarLocation(int loc) 645void TEWidget::setScrollbarLocation(int loc)
646{ 646{
647 if (scrollLoc == loc) return; // quickly 647 if (scrollLoc == loc) return; // quickly
648 scrollLoc = loc; 648 scrollLoc = loc;
649 propagateSize(); 649 propagateSize();
650 update(); 650 update();
651} 651}
652 652
653/* ------------------------------------------------------------------------- */ 653/* ------------------------------------------------------------------------- */
654/* */ 654/* */
655/* Mouse */ 655/* Mouse */
656/* */ 656/* */
657/* ------------------------------------------------------------------------- */ 657/* ------------------------------------------------------------------------- */
658 658
659/*! 659/*!
660 Three different operations can be performed using the mouse, and the 660 Three different operations can be performed using the mouse, and the
661 routines in this section serve all of them: 661 routines in this section serve all of them:
662 662
663 1) The press/release events are exposed to the application 663 1) The press/release events are exposed to the application
664 2) Marking (press and move left button) and Pasting (press middle button) 664 2) Marking (press and move left button) and Pasting (press middle button)
665 3) The right mouse button is used from the configuration menu 665 3) The right mouse button is used from the configuration menu
666 666
667 NOTE: During the marking process we attempt to keep the cursor within 667 NOTE: During the marking process we attempt to keep the cursor within
668 the bounds of the text as being displayed by setting the mouse position 668 the bounds of the text as being displayed by setting the mouse position
669 whenever the mouse has left the text area. 669 whenever the mouse has left the text area.
670 670
671 Two reasons to do so: 671 Two reasons to do so:
672 1) QT does not allow the `grabMouse' to confine-to the TEWidget. 672 1) QT does not allow the `grabMouse' to confine-to the TEWidget.
673 Thus a `XGrapPointer' would have to be used instead. 673 Thus a `XGrapPointer' would have to be used instead.
674 2) Even if so, this would not help too much, since the text area 674 2) Even if so, this would not help too much, since the text area
675 of the TEWidget is normally not identical with it's bounds. 675 of the TEWidget is normally not identical with it's bounds.
676 676
677 The disadvantage of the current handling is, that the mouse can visibly 677 The disadvantage of the current handling is, that the mouse can visibly
678 leave the bounds of the widget and is then moved back. Because of the 678 leave the bounds of the widget and is then moved back. Because of the
679 current construction, and the reasons mentioned above, we cannot do better 679 current construction, and the reasons mentioned above, we cannot do better
680 without changing the overall construction. 680 without changing the overall construction.
681*/ 681*/
682 682
683/*! 683/*!
684*/ 684*/
685 685
686void TEWidget::mousePressEvent(QMouseEvent* ev) 686void TEWidget::mousePressEvent(QMouseEvent* ev)
687{ 687{
688//printf("press [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button()); 688//printf("press [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button());
689 if ( !contentsRect().contains(ev->pos()) ) return; 689 if ( !contentsRect().contains(ev->pos()) ) return;
690 QPoint tL = contentsRect().topLeft(); 690 QPoint tL = contentsRect().topLeft();
691 int tLx = tL.x(); 691 int tLx = tL.x();
692 int tLy = tL.y(); 692 int tLy = tL.y();
693 693
694 word_selection_mode = FALSE; 694 word_selection_mode = FALSE;
695 695
696//printf("press top left [%d,%d] by=%d\n",tLx,tLy, bY); 696//printf("press top left [%d,%d] by=%d\n",tLx,tLy, bY);
697 if ( ev->button() == LeftButton) 697 if ( ev->button() == LeftButton)
698 { 698 {
699 QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); 699 QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h);
700 700
701 if ( ev->state() & ControlButton ) preserve_line_breaks = FALSE ; 701 if ( ev->state() & ControlButton ) preserve_line_breaks = FALSE ;
702 702
703 if (mouse_marks || (ev->state() & ShiftButton)) 703 if (mouse_marks || (ev->state() & ShiftButton))
704 { 704 {
705 emit clearSelectionSignal(); 705 emit clearSelectionSignal();
706 iPntSel = pntSel = pos; 706 iPntSel = pntSel = pos;
707 actSel = 1; // left mouse button pressed but nothing selected yet. 707 actSel = 1; // left mouse button pressed but nothing selected yet.
708 grabMouse( /*crossCursor*/ ); // handle with care! 708 grabMouse( /*crossCursor*/ ); // handle with care!
709 } 709 }
710 else 710 else
711 { 711 {
712 emit mouseSignal( 0, pos.x() + 1, pos.y() + 1 ); // left button 712 emit mouseSignal( 0, pos.x() + 1, pos.y() + 1 ); // left button
713 } 713 }
714 } 714 }
715 if ( ev->button() == MidButton ) 715 if ( ev->button() == MidButton )
716 { 716 {
717 emitSelection(); 717 emitSelection();
718 } 718 }
719 if ( ev->button() == RightButton ) // Configure 719 if ( ev->button() == RightButton ) // Configure
720 { 720 {
721 emit configureRequest( this, ev->state()&(ShiftButton|ControlButton), ev->x(), ev->y() ); 721 emit configureRequest( this, ev->state()&(ShiftButton|ControlButton), ev->x(), ev->y() );
722 } 722 }
723} 723}
724 724
725void TEWidget::mouseMoveEvent(QMouseEvent* ev) 725void TEWidget::mouseMoveEvent(QMouseEvent* ev)
726{ 726{
727 // for auto-hiding the cursor, we need mouseTracking 727 // for auto-hiding the cursor, we need mouseTracking
728 if (ev->state() == NoButton ) return; 728 if (ev->state() == NoButton ) return;
729 729
730 if (actSel == 0) return; 730 if (actSel == 0) return;
731 731
732 // don't extend selection while pasting 732 // don't extend selection while pasting
733 if (ev->state() & MidButton) return; 733 if (ev->state() & MidButton) return;
734 734
735 //if ( !contentsRect().contains(ev->pos()) ) return; 735 //if ( !contentsRect().contains(ev->pos()) ) return;
736 QPoint tL = contentsRect().topLeft(); 736 QPoint tL = contentsRect().topLeft();
737 int tLx = tL.x(); 737 int tLx = tL.x();
738 int tLy = tL.y(); 738 int tLy = tL.y();
739 int scroll = scrollbar->value(); 739 int scroll = scrollbar->value();
740 740
741 // we're in the process of moving the mouse with the left button pressed 741 // we're in the process of moving the mouse with the left button pressed
742 // the mouse cursor will kept catched within the bounds of the text in 742 // the mouse cursor will kept catched within the bounds of the text in
743 // this widget. 743 // this widget.
744 744
745 // Adjust position within text area bounds. See FIXME above. 745 // Adjust position within text area bounds. See FIXME above.
746 QPoint pos = ev->pos(); 746 QPoint pos = ev->pos();
747 if ( pos.x() < tLx+blX ) pos.setX( tLx+blX ); 747 if ( pos.x() < tLx+blX ) pos.setX( tLx+blX );
748 if ( pos.x() > tLx+blX+columns*font_w-1 ) pos.setX( tLx+blX+columns*font_w ); 748 if ( pos.x() > tLx+blX+columns*font_w-1 ) pos.setX( tLx+blX+columns*font_w );
749 if ( pos.y() < tLy+bY ) pos.setY( tLy+bY ); 749 if ( pos.y() < tLy+bY ) pos.setY( tLy+bY );
750 if ( pos.y() > tLy+bY+lines*font_h-1 ) pos.setY( tLy+bY+lines*font_h-1 ); 750 if ( pos.y() > tLy+bY+lines*font_h-1 ) pos.setY( tLy+bY+lines*font_h-1 );
751 // check if we produce a mouse move event by this 751 // check if we produce a mouse move event by this
752 if ( pos != ev->pos() ) cursor().setPos(mapToGlobal(pos)); 752 if ( pos != ev->pos() ) cursor().setPos(mapToGlobal(pos));
753 753
754 if ( pos.y() == tLy+bY+lines*font_h-1 ) 754 if ( pos.y() == tLy+bY+lines*font_h-1 )
755 { 755 {
756 scrollbar->setValue(scrollbar->value()+yMouseScroll); // scrollforward 756 scrollbar->setValue(scrollbar->value()+yMouseScroll); // scrollforward
757 } 757 }
758 if ( pos.y() == tLy+bY ) 758 if ( pos.y() == tLy+bY )
759 { 759 {
760 scrollbar->setValue(scrollbar->value()-yMouseScroll); // scrollback 760 scrollbar->setValue(scrollbar->value()-yMouseScroll); // scrollback
761 } 761 }
762 762
763 QPoint here = QPoint((pos.x()-tLx-blX)/font_w,(pos.y()-tLy-bY)/font_h); 763 QPoint here = QPoint((pos.x()-tLx-blX)/font_w,(pos.y()-tLy-bY)/font_h);
764 QPoint ohere; 764 QPoint ohere;
765 bool swapping = FALSE; 765 bool swapping = FALSE;
766 766
767 if ( word_selection_mode ) 767 if ( word_selection_mode )
768 { 768 {
769 // Extend to word boundaries 769 // Extend to word boundaries
770 int i; 770 int i;
771 int selClass; 771 int selClass;
772 772
773 bool left_not_right = ( here.y() < iPntSel.y() || 773 bool left_not_right = ( here.y() < iPntSel.y() ||
774 here.y() == iPntSel.y() && here.x() < iPntSel.x() ); 774 here.y() == iPntSel.y() && here.x() < iPntSel.x() );
775 bool old_left_not_right = ( pntSel.y() < iPntSel.y() || 775 bool old_left_not_right = ( pntSel.y() < iPntSel.y() ||
776 pntSel.y() == iPntSel.y() && pntSel.x() < iPntSel.x() ); 776 pntSel.y() == iPntSel.y() && pntSel.x() < iPntSel.x() );
777 swapping = left_not_right != old_left_not_right; 777 swapping = left_not_right != old_left_not_right;
778 778
779 // Find left (left_not_right ? from here : from start) 779 // Find left (left_not_right ? from here : from start)
780 QPoint left = left_not_right ? here : iPntSel; 780 QPoint left = left_not_right ? here : iPntSel;
781 i = loc(left.x(),left.y()); 781 i = loc(left.x(),left.y());
782 selClass = charClass(image[i].c); 782 selClass = charClass(image[i].c);
783 while ( left.x() > 0 && charClass(image[i-1].c) == selClass ) 783 while ( left.x() > 0 && charClass(image[i-1].c) == selClass )
784 { i--; left.rx()--; } 784 { i--; left.rx()--; }
785 785
786 // Find left (left_not_right ? from start : from here) 786 // Find left (left_not_right ? from start : from here)
787 QPoint right = left_not_right ? iPntSel : here; 787 QPoint right = left_not_right ? iPntSel : here;
788 i = loc(right.x(),right.y()); 788 i = loc(right.x(),right.y());
789 selClass = charClass(image[i].c); 789 selClass = charClass(image[i].c);
790 while ( right.x() < columns-1 && charClass(image[i+1].c) == selClass ) 790 while ( right.x() < columns-1 && charClass(image[i+1].c) == selClass )
791 { i++; right.rx()++; } 791 { i++; right.rx()++; }
792 792
793 // Pick which is start (ohere) and which is extension (here) 793 // Pick which is start (ohere) and which is extension (here)
794 if ( left_not_right ) 794 if ( left_not_right )
795 { 795 {
796 here = left; ohere = right; 796 here = left; ohere = right;
797 } 797 }
798 else 798 else
799 { 799 {
800 here = right; ohere = left; 800 here = right; ohere = left;
801 } 801 }
802 } 802 }
803 803
804 if (here == pntSel && scroll == scrollbar->value()) return; // not moved 804 if (here == pntSel && scroll == scrollbar->value()) return; // not moved
805 805
806 if ( word_selection_mode ) { 806 if ( word_selection_mode ) {
807 if ( actSel < 2 || swapping ) { 807 if ( actSel < 2 || swapping ) {
808 emit beginSelectionSignal( ohere.x(), ohere.y() ); 808 emit beginSelectionSignal( ohere.x(), ohere.y() );
809 } 809 }
810 } else if ( actSel < 2 ) { 810 } else if ( actSel < 2 ) {
811 emit beginSelectionSignal( pntSel.x(), pntSel.y() ); 811 emit beginSelectionSignal( pntSel.x(), pntSel.y() );
812 } 812 }
813 813
814 actSel = 2; // within selection 814 actSel = 2; // within selection
815 pntSel = here; 815 pntSel = here;
816 emit extendSelectionSignal( here.x(), here.y() ); 816 emit extendSelectionSignal( here.x(), here.y() );
817} 817}
818 818
819void TEWidget::mouseReleaseEvent(QMouseEvent* ev) 819void TEWidget::mouseReleaseEvent(QMouseEvent* ev)
820{ 820{
821//printf("release [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button()); 821//printf("release [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button());
822 if ( ev->button() == LeftButton) 822 if ( ev->button() == LeftButton)
823 { 823 {
824 if ( actSel > 1 ) emit endSelectionSignal(preserve_line_breaks); 824 if ( actSel > 1 ) emit endSelectionSignal(preserve_line_breaks);
825 preserve_line_breaks = TRUE; 825 preserve_line_breaks = TRUE;
826 actSel = 0; 826 actSel = 0;
827 827
828 //FIXME: emits a release event even if the mouse is 828 //FIXME: emits a release event even if the mouse is
829 // outside the range. The procedure used in `mouseMoveEvent' 829 // outside the range. The procedure used in `mouseMoveEvent'
830 // applies here, too. 830 // applies here, too.
831 831
832 QPoint tL = contentsRect().topLeft(); 832 QPoint tL = contentsRect().topLeft();
833 int tLx = tL.x(); 833 int tLx = tL.x();
834 int tLy = tL.y(); 834 int tLy = tL.y();
835 835
836 if (!mouse_marks && !(ev->state() & ShiftButton)) 836 if (!mouse_marks && !(ev->state() & ShiftButton))
837 emit mouseSignal( 3, // release 837 emit mouseSignal( 3, // release
838 (ev->x()-tLx-blX)/font_w + 1, 838 (ev->x()-tLx-blX)/font_w + 1,
839 (ev->y()-tLy-bY)/font_h + 1 ); 839 (ev->y()-tLy-bY)/font_h + 1 );
840 releaseMouse(); 840 releaseMouse();
841 } 841 }
842} 842}
843 843
844void TEWidget::mouseDoubleClickEvent(QMouseEvent* ev) 844void TEWidget::mouseDoubleClickEvent(QMouseEvent* ev)
845{ 845{
846 if ( ev->button() != LeftButton) return; 846 if ( ev->button() != LeftButton) return;
847 847
848 QPoint tL = contentsRect().topLeft(); 848 QPoint tL = contentsRect().topLeft();
849 int tLx = tL.x(); 849 int tLx = tL.x();
850 int tLy = tL.y(); 850 int tLy = tL.y();
851 QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); 851 QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h);
852 852
853 // pass on double click as two clicks. 853 // pass on double click as two clicks.
854 if (!mouse_marks && !(ev->state() & ShiftButton)) 854 if (!mouse_marks && !(ev->state() & ShiftButton))
855 { 855 {
856 emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button 856 emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button
857 emit mouseSignal( 3, pos.x()+1, pos.y()+1 ); // release 857 emit mouseSignal( 3, pos.x()+1, pos.y()+1 ); // release
858 emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button 858 emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button
859 return; 859 return;
860 } 860 }
861 861
862 862
863 emit clearSelectionSignal(); 863 emit clearSelectionSignal();
864 QPoint bgnSel = pos; 864 QPoint bgnSel = pos;
865 QPoint endSel = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); 865 QPoint endSel = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h);
866 int i = loc(bgnSel.x(),bgnSel.y()); 866 int i = loc(bgnSel.x(),bgnSel.y());
867 iPntSel = bgnSel; 867 iPntSel = bgnSel;
868 868
869 word_selection_mode = TRUE; 869 word_selection_mode = TRUE;
870 870
871 // find word boundaries... 871 // find word boundaries...
872 int selClass = charClass(image[i].c); 872 int selClass = charClass(image[i].c);
873 { 873 {
874 // set the start... 874 // set the start...
875 int x = bgnSel.x(); 875 int x = bgnSel.x();
876 while ( x > 0 && charClass(image[i-1].c) == selClass ) 876 while ( x > 0 && charClass(image[i-1].c) == selClass )
877 { i--; x--; } 877 { i--; x--; }
878 bgnSel.setX(x); 878 bgnSel.setX(x);
879 emit beginSelectionSignal( bgnSel.x(), bgnSel.y() ); 879 emit beginSelectionSignal( bgnSel.x(), bgnSel.y() );
880 880
881 // set the end... 881 // set the end...
882 i = loc( endSel.x(), endSel.y() ); 882 i = loc( endSel.x(), endSel.y() );
883 x = endSel.x(); 883 x = endSel.x();
884 while( x < columns-1 && charClass(image[i+1].c) == selClass ) 884 while( x < columns-1 && charClass(image[i+1].c) == selClass )
885 { i++; x++ ; } 885 { i++; x++ ; }
886 endSel.setX(x); 886 endSel.setX(x);
887 actSel = 2; // within selection 887 actSel = 2; // within selection
888 emit extendSelectionSignal( endSel.x(), endSel.y() ); 888 emit extendSelectionSignal( endSel.x(), endSel.y() );
889 emit endSelectionSignal(preserve_line_breaks); 889 emit endSelectionSignal(preserve_line_breaks);
890 preserve_line_breaks = TRUE; 890 preserve_line_breaks = TRUE;
891 } 891 }
892} 892}
893 893
894void TEWidget::focusInEvent( QFocusEvent * ) 894void TEWidget::focusInEvent( QFocusEvent * )
895{ 895{
896 896
897 // do nothing, to prevent repainting 897 // do nothing, to prevent repainting
898} 898}
899 899
900 900
901void TEWidget::focusOutEvent( QFocusEvent * ) 901void TEWidget::focusOutEvent( QFocusEvent * )
902{ 902{
903 // do nothing, to prevent repainting 903 // do nothing, to prevent repainting
904} 904}
905 905
906bool TEWidget::focusNextPrevChild( bool next ) 906bool TEWidget::focusNextPrevChild( bool next )
907{ 907{
908 if (next) 908 if (next)
909 return false; // This disables changing the active part in konqueror 909 return false; // This disables changing the active part in konqueror
910 // when pressing Tab 910 // when pressing Tab
911 return QFrame::focusNextPrevChild( next ); 911 return QFrame::focusNextPrevChild( next );
912} 912}
913 913
914 914
915int TEWidget::charClass(char ch) const 915int TEWidget::charClass(char ch) const
916{ 916{
917 // This might seem like overkill, but imagine if ch was a Unicode 917 // This might seem like overkill, but imagine if ch was a Unicode
918 // character (Qt 2.0 QChar) - it might then be sensible to separate 918 // character (Qt 2.0 QChar) - it might then be sensible to separate
919 // the different language ranges, etc. 919 // the different language ranges, etc.
920 920
921 if ( isspace(ch) ) return ' '; 921 if ( isspace(ch) ) return ' ';
922 922
923 static const char *word_characters = ":@-./_~"; 923 static const char *word_characters = ":@-./_~";
924 if ( isalnum(ch) || strchr(word_characters, ch) ) 924 if ( isalnum(ch) || strchr(word_characters, ch) )
925 return 'a'; 925 return 'a';
926 926
927 // Everything else is weird 927 // Everything else is weird
928 return 1; 928 return 1;
929} 929}
930 930
931void TEWidget::setMouseMarks(bool on) 931void TEWidget::setMouseMarks(bool on)
932{ 932{
933 mouse_marks = on; 933 mouse_marks = on;
934 setCursor( mouse_marks ? ibeamCursor : arrowCursor ); 934 setCursor( mouse_marks ? ibeamCursor : arrowCursor );
935} 935}
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 :
1172 columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w; 1172 columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w;
1173 dcolumns = columns; 1173 dcolumns = columns;
1174 if(vcolumns) columns = vcolumns; 1174 if(vcolumns) columns = vcolumns;
1175 brX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2; 1175 brX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2;
1176 if(showhscrollbar) 1176 if(showhscrollbar)
1177 brX = -hposition * font_w; 1177 brX = -hposition * font_w;
1178 blX = brX + scrollbar->width(); 1178 blX = brX + scrollbar->width();
1179 scrollbar->move(contentsRect().topLeft()); 1179 scrollbar->move(contentsRect().topLeft());
1180 scrollbar->show(); 1180 scrollbar->show();
1181 break; 1181 break;
1182 case SCRRIGHT: 1182 case SCRRIGHT:
1183 columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w; 1183 columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w;
1184 dcolumns = columns; 1184 dcolumns = columns;
1185 if(vcolumns) columns = vcolumns; 1185 if(vcolumns) columns = vcolumns;
1186 blX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2; 1186 blX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2;
1187 if(showhscrollbar) 1187 if(showhscrollbar)
1188 blX = -hposition * font_w; 1188 blX = -hposition * font_w;
1189 brX = blX; 1189 brX = blX;
1190 scrollbar->move(contentsRect().topRight() - QPoint(scrollbar->width()-1,0)); 1190 scrollbar->move(contentsRect().topRight() - QPoint(scrollbar->width()-1,0));
1191 scrollbar->show(); 1191 scrollbar->show();
1192 break; 1192 break;
1193 } 1193 }
1194 //FIXME: support 'rounding' styles 1194 //FIXME: support 'rounding' styles
1195 lines = ( contentsRect().height() - 2 * rimY ) / font_h; 1195 lines = ( contentsRect().height() - 2 * rimY ) / font_h;
1196 bY = (contentsRect().height() - (lines *font_h)) / 2; 1196 bY = (contentsRect().height() - (lines *font_h)) / 2;
1197 1197
1198 if(showhscrollbar == 1) 1198 if(showhscrollbar == 1)
1199 { 1199 {
1200 hscrollbar->resize(contentsRect().width() - hwidth, hwidth); 1200 hscrollbar->resize(contentsRect().width() - hwidth, hwidth);
1201 hscrollbar->setRange(0, vcolumns - dcolumns); 1201 hscrollbar->setRange(0, vcolumns - dcolumns);
1202 1202
1203 QPoint p = contentsRect().bottomLeft(); 1203 QPoint p = contentsRect().bottomLeft();
1204 hscrollbar->move(QPoint(p.x(), p.y() - hwidth)); 1204 hscrollbar->move(QPoint(p.x(), p.y() - hwidth));
1205 hscrollbar->show(); 1205 hscrollbar->show();
1206 } 1206 }
1207 else hscrollbar->hide(); 1207 else hscrollbar->hide();
1208 1208
1209 if(showhscrollbar == 1) 1209 if(showhscrollbar == 1)
1210 { 1210 {
1211 lines = lines - (hwidth / font_h) - 1; 1211 lines = lines - (hwidth / font_h) - 1;
1212 if(lines < 1) lines = 1; 1212 if(lines < 1) lines = 1;
1213 } 1213 }
1214} 1214}
1215 1215
1216void TEWidget::makeImage() 1216void TEWidget::makeImage()
1217//FIXME: rename 'calcGeometry? 1217//FIXME: rename 'calcGeometry?
1218{ 1218{
1219 calcGeometry(); 1219 calcGeometry();
1220 image = (ca*) malloc(lines*columns*sizeof(ca)); 1220 image = (ca*) malloc(lines*columns*sizeof(ca));
1221 clearImage(); 1221 clearImage();
1222} 1222}
1223 1223
1224// calculate the needed size 1224// calculate the needed size
1225QSize TEWidget::calcSize(int cols, int lins) const 1225QSize TEWidget::calcSize(int cols, int lins) const
1226{ 1226{
1227 int frw = width() - contentsRect().width(); 1227 int frw = width() - contentsRect().width();
1228 int frh = height() - contentsRect().height(); 1228 int frh = height() - contentsRect().height();
1229 int scw = (scrollLoc==SCRNONE?0:scrollbar->width()); 1229 int scw = (scrollLoc==SCRNONE?0:scrollbar->width());
1230 return QSize( font_w*cols + 2*rimX + frw + scw, font_h*lins + 2*rimY + frh ); 1230 return QSize( font_w*cols + 2*rimX + frw + scw, font_h*lins + 2*rimY + frh );
1231} 1231}
1232 1232
1233QSize TEWidget::sizeHint() const 1233QSize TEWidget::sizeHint() const
1234{ 1234{
1235 return size(); 1235 return size();
1236} 1236}
1237 1237
1238void TEWidget::styleChange(QStyle &) 1238void TEWidget::styleChange(QStyle &)
1239{ 1239{
1240 propagateSize(); 1240 propagateSize();
1241} 1241}
1242 1242
1243#ifdef QT_NO_DRAGANDDROP_FOO 1243#ifdef QT_NO_DRAGANDDROP_FOO
1244 1244
1245/* --------------------------------------------------------------------- */ 1245/* --------------------------------------------------------------------- */
1246/* */ 1246/* */
1247/* Drag & Drop */ 1247/* Drag & Drop */
1248/* */ 1248/* */
1249/* --------------------------------------------------------------------- */ 1249/* --------------------------------------------------------------------- */
1250 1250
1251 1251
1252void TEWidget::dragEnterEvent(QDragEnterEvent* e) 1252void TEWidget::dragEnterEvent(QDragEnterEvent* e)
1253{ 1253{
1254 e->accept(QTextDrag::canDecode(e) || 1254 e->accept(QTextDrag::canDecode(e) ||
1255 QUriDrag::canDecode(e)); 1255 QUriDrag::canDecode(e));
1256} 1256}
1257 1257
1258void TEWidget::dropEvent(QDropEvent* event) 1258void TEWidget::dropEvent(QDropEvent* event)
1259{ 1259{
1260 // The current behaviour when url(s) are dropped is 1260 // The current behaviour when url(s) are dropped is
1261 // * if there is only ONE url and if it's a LOCAL one, ask for paste or cd 1261 // * if there is only ONE url and if it's a LOCAL one, ask for paste or cd
1262 // * in all other cases, just paste 1262 // * in all other cases, just paste
1263 // (for non-local ones, or for a list of URLs, 'cd' is nonsense) 1263 // (for non-local ones, or for a list of URLs, 'cd' is nonsense)
1264 QStrList strlist; 1264 QStrList strlist;
1265 int file_count = 0; 1265 int file_count = 0;
1266 dropText = ""; 1266 dropText = "";
1267 bool bPopup = true; 1267 bool bPopup = true;
1268 1268
1269 if(QUriDrag::decode(event, strlist)) { 1269 if(QUriDrag::decode(event, strlist)) {
1270 if (strlist.count()) { 1270 if (strlist.count()) {
1271 for(const char* p = strlist.first(); p; p = strlist.next()) { 1271 for(const char* p = strlist.first(); p; p = strlist.next()) {
1272 if(file_count++ > 0) { 1272 if(file_count++ > 0) {
1273 dropText += " "; 1273 dropText += " ";
1274 bPopup = false; // more than one file, don't popup 1274 bPopup = false; // more than one file, don't popup
1275 } 1275 }
1276 1276
1277/* 1277/*
1278 KURL url(p); 1278 KURL url(p);
1279 if (url.isLocalFile()) { 1279 if (url.isLocalFile()) {
1280 dropText += url.path(); // local URL : remove protocol 1280 dropText += url.path(); // local URL : remove protocol
1281 } 1281 }
1282 else { 1282 else {
1283 dropText += url.prettyURL(); 1283 dropText += url.prettyURL();
1284 bPopup = false; // a non-local file, don't popup 1284 bPopup = false; // a non-local file, don't popup
1285 } 1285 }
1286*/ 1286*/
1287 1287
1288 } 1288 }
1289 1289
1290 if (bPopup) 1290 if (bPopup)
1291 // m_drop->popup(pos() + event->pos()); 1291 // m_drop->popup(pos() + event->pos());
1292 m_drop->popup(mapToGlobal(event->pos())); 1292 m_drop->popup(mapToGlobal(event->pos()));
1293 else 1293 else
1294 { 1294 {
1295 if (currentSession) { 1295 if (currentSession) {
1296 currentSession->getEmulation()->sendString(dropText.local8Bit()); 1296 currentSession->getEmulation()->sendString(dropText.local8Bit());
1297 } 1297 }
1298// kdDebug() << "Drop:" << dropText.local8Bit() << "\n"; 1298// kdDebug() << "Drop:" << dropText.local8Bit() << "\n";
1299 } 1299 }
1300 } 1300 }
1301 } 1301 }
1302 else if(QTextDrag::decode(event, dropText)) { 1302 else if(QTextDrag::decode(event, dropText)) {
1303// kdDebug() << "Drop:" << dropText.local8Bit() << "\n"; 1303// kdDebug() << "Drop:" << dropText.local8Bit() << "\n";
1304 if (currentSession) { 1304 if (currentSession) {
1305 currentSession->getEmulation()->sendString(dropText.local8Bit()); 1305 currentSession->getEmulation()->sendString(dropText.local8Bit());
1306 } 1306 }
1307 // Paste it 1307 // Paste it
1308 } 1308 }
1309} 1309}
1310#endif 1310#endif
1311 1311
1312 1312
1313void TEWidget::drop_menu_activated(int) 1313void TEWidget::drop_menu_activated(int)
1314{ 1314{
1315#ifdef QT_NO_DRAGANDDROP_FOO 1315#ifdef QT_NO_DRAGANDDROP_FOO
1316 switch (item) 1316 switch (item)
1317 { 1317 {
1318 case 0: // paste 1318 case 0: // paste
1319 currentSession->getEmulation()->sendString(dropText.local8Bit()); 1319 currentSession->getEmulation()->sendString(dropText.local8Bit());
1320// KWM::activate((Window)this->winId()); 1320// KWM::activate((Window)this->winId());
1321 break; 1321 break;
1322 case 1: // cd ... 1322 case 1: // cd ...
1323 currentSession->getEmulation()->sendString("cd "); 1323 currentSession->getEmulation()->sendString("cd ");
1324 struct stat statbuf; 1324 struct stat statbuf;
1325 if ( ::stat( QFile::encodeName( dropText ), &statbuf ) == 0 ) 1325 if ( ::stat( QFile::encodeName( dropText ), &statbuf ) == 0 )
1326 { 1326 {
1327 if ( !S_ISDIR(statbuf.st_mode) ) 1327 if ( !S_ISDIR(statbuf.st_mode) )
1328 { 1328 {
1329/* 1329/*
1330 KURL url; 1330 KURL url;
1331 url.setPath( dropText ); 1331 url.setPath( dropText );
1332 dropText = url.directory( true, false ); // remove filename 1332 dropText = url.directory( true, false ); // remove filename
1333*/ 1333*/
1334 } 1334 }
1335 } 1335 }
1336 dropText.replace(QRegExp(" "), "\\ "); // escape spaces 1336 dropText.replace(QRegExp(" "), "\\ "); // escape spaces
1337 currentSession->getEmulation()->sendString(dropText.local8Bit()); 1337 currentSession->getEmulation()->sendString(dropText.local8Bit());
1338 currentSession->getEmulation()->sendString("\n"); 1338 currentSession->getEmulation()->sendString("\n");
1339// KWM::activate((Window)this->winId()); 1339// KWM::activate((Window)this->winId());
1340 break; 1340 break;
1341 } 1341 }
1342#endif 1342#endif
1343} 1343}
1344 1344
1345QPushButton* TEWidget::cornerButton() { 1345QPushButton* TEWidget::cornerButton() {
1346 return m_cornerButton; 1346 return m_cornerButton;
1347} 1347}
1348 1348
1349void TEWidget::setWrapAt(int columns) 1349void TEWidget::setWrapAt(int columns)
1350{ 1350{
1351 vcolumns = columns; 1351 vcolumns = columns;
1352 propagateSize(); 1352 propagateSize();
1353 update(); 1353 update();
1354} 1354}
1355 1355
1356 1356
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,363 +1,369 @@
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());
304 } 310 }
305} 311}
306 312
307void TEmulation::bulkStart() 313void TEmulation::bulkStart()
308{ 314{
309 if (bulk_timer.isActive()) bulk_timer.stop(); 315 if (bulk_timer.isActive()) bulk_timer.stop();
310} 316}
311 317
312void TEmulation::bulkEnd() 318void TEmulation::bulkEnd()
313{ 319{
314 if ( bulk_nlcnt > gui->Lines() || bulk_incnt > 20 ) 320 if ( bulk_nlcnt > gui->Lines() || bulk_incnt > 20 )
315 showBulk(); // resets bulk_??cnt to 0, too. 321 showBulk(); // resets bulk_??cnt to 0, too.
316 else 322 else
317 bulk_timer.start(BULK_TIMEOUT,TRUE); 323 bulk_timer.start(BULK_TIMEOUT,TRUE);
318} 324}
319 325
320void TEmulation::setConnect(bool c) 326void TEmulation::setConnect(bool c)
321{ 327{
322 connected = c; 328 connected = c;
323 if ( connected) 329 if ( connected)
324 { 330 {
325 onImageSizeChange(gui->Lines(), gui->Columns()); 331 onImageSizeChange(gui->Lines(), gui->Columns());
326 showBulk(); 332 showBulk();
327 } 333 }
328 else 334 else
329 { 335 {
330 scr->clearSelection(); 336 scr->clearSelection();
331 } 337 }
332} 338}
333 339
334// --------------------------------------------------------------------------- 340// ---------------------------------------------------------------------------
335 341
336/*! triggered by image size change of the TEWidget `gui'. 342/*! triggered by image size change of the TEWidget `gui'.
337 343
338 This event is simply propagated to the attached screens 344 This event is simply propagated to the attached screens
339 and to the related serial line. 345 and to the related serial line.
340*/ 346*/
341 347
342void TEmulation::onImageSizeChange(int lines, int columns) 348void TEmulation::onImageSizeChange(int lines, int columns)
343{ 349{
344 if (!connected) return; 350 if (!connected) return;
345 screen[0]->resizeImage(lines,columns); 351 screen[0]->resizeImage(lines,columns);
346 screen[1]->resizeImage(lines,columns); 352 screen[1]->resizeImage(lines,columns);
347 showBulk(); 353 showBulk();
348 emit ImageSizeChanged(lines,columns); // propagate event to serial line 354 emit ImageSizeChanged(lines,columns); // propagate event to serial line
349} 355}
350 356
351void TEmulation::onHistoryCursorChange(int cursor) 357void TEmulation::onHistoryCursorChange(int cursor)
352{ 358{
353 if (!connected) return; 359 if (!connected) return;
354 scr->setHistCursor(cursor); 360 scr->setHistCursor(cursor);
355 showBulk(); 361 showBulk();
356} 362}
357 363
358void TEmulation::setColumns(int columns) 364void TEmulation::setColumns(int columns)
359{ 365{
360 //FIXME: this goes strange ways. 366 //FIXME: this goes strange ways.
361 // Can we put this straight or explain it at least? 367 // Can we put this straight or explain it at least?
362 emit changeColumns(columns); 368 emit changeColumns(columns);
363} 369}
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
@@ -1,301 +1,301 @@
1// opie-console includes 1// opie-console includes
2#include "emulation_widget.h" 2#include "emulation_widget.h"
3 3
4// qt includes 4// qt includes
5#include <qscrollbar.h> 5#include <qscrollbar.h>
6 6
7#define rimX 0 // left/right rim width 7#define rimX 0 // left/right rim width
8#define rimY 0 // top/bottom rim high 8#define rimY 0 // top/bottom rim high
9 9
10static const ColorEntry color_table[TABLE_COLORS] = 10static const ColorEntry color_table[TABLE_COLORS] =
11{ 11{
12 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback 12 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback
13 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red 13 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red
14 ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow 14 ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow
15 ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta 15 ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta
16 ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White 16 ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White
17 // intensiv 17 // intensiv
18 ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ), 18 ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ),
19 ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ), 19 ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ),
20 ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ), 20 ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ),
21 ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), 21 ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ),
22 ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 ) 22 ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 )
23}; 23};
24 24
25EmulationWidget::EmulationWidget( const Profile& config, QWidget *parent, const char* name ) : WidgetLayer( config, parent, name ) 25EmulationWidget::EmulationWidget( const Profile& config, QWidget *parent, const char* name ) : WidgetLayer( config, parent, name )
26{ 26{
27 27
28 // initialize font attributes 28 // initialize font attributes
29 QFontMetrics fm( font() ); 29 QFontMetrics fm( font() );
30 f_height = fm.height(); 30 f_height = fm.height();
31 f_width = fm.maxWidth(); 31 f_width = fm.maxWidth();
32 f_ascent = fm.ascent(); 32 f_ascent = fm.ascent();
33 33
34 34
35 // initialize scrollbar related vars 35 // initialize scrollbar related vars
36 m_scrollbar = new QScrollBar( this ); 36 m_scrollbar = new QScrollBar( this );
37 m_scrollbar->setCursor( arrowCursor ); 37 m_scrollbar->setCursor( arrowCursor );
38 38
39 // give reasonable defaults to m_columns, m_lines 39 // give reasonable defaults to m_columns, m_lines
40 calcGeometry(); 40 calcGeometry();
41 41
42 // load config 42 // load config
43 reloadConfig( config ); 43 reloadConfig( config );
44 44
45 m_resizing = false; 45 m_resizing = false;
46} 46}
47 47
48void EmulationWidget::reloadConfig( const Profile& config ) 48void EmulationWidget::reloadConfig( const Profile& config )
49{ 49{
50 50
51 // nothing yet 51 // nothing yet
52} 52}
53 53
54EmulationWidget::~EmulationWidget() 54EmulationWidget::~EmulationWidget()
55{ 55{
56 //clean up 56 //clean up
57} 57}
58 58
59static QChar vt100extended(QChar c) 59static QChar vt100extended(QChar c)
60{ 60{
61 switch (c.unicode()) 61 switch (c.unicode())
62 { 62 {
63 case 0x25c6 : return 1; 63 case 0x25c6 : return 1;
64 case 0x2592 : return 2; 64 case 0x2592 : return 2;
65 case 0x2409 : return 3; 65 case 0x2409 : return 3;
66 case 0x240c : return 4; 66 case 0x240c : return 4;
67 case 0x240d : return 5; 67 case 0x240d : return 5;
68 case 0x240a : return 6; 68 case 0x240a : return 6;
69 case 0x00b0 : return 7; 69 case 0x00b0 : return 7;
70 case 0x00b1 : return 8; 70 case 0x00b1 : return 8;
71 case 0x2424 : return 9; 71 case 0x2424 : return 9;
72 case 0x240b : return 10; 72 case 0x240b : return 10;
73 case 0x2518 : return 11; 73 case 0x2518 : return 11;
74 case 0x2510 : return 12; 74 case 0x2510 : return 12;
75 case 0x250c : return 13; 75 case 0x250c : return 13;
76 case 0x2514 : return 14; 76 case 0x2514 : return 14;
77 case 0x253c : return 15; 77 case 0x253c : return 15;
78 case 0xf800 : return 16; 78 case 0xf800 : return 16;
79 case 0xf801 : return 17; 79 case 0xf801 : return 17;
80 case 0x2500 : return 18; 80 case 0x2500 : return 18;
81 case 0xf803 : return 19; 81 case 0xf803 : return 19;
82 case 0xf804 : return 20; 82 case 0xf804 : return 20;
83 case 0x251c : return 21; 83 case 0x251c : return 21;
84 case 0x2524 : return 22; 84 case 0x2524 : return 22;
85 case 0x2534 : return 23; 85 case 0x2534 : return 23;
86 case 0x252c : return 24; 86 case 0x252c : return 24;
87 case 0x2502 : return 25; 87 case 0x2502 : return 25;
88 case 0x2264 : return 26; 88 case 0x2264 : return 26;
89 case 0x2265 : return 27; 89 case 0x2265 : return 27;
90 case 0x03c0 : return 28; 90 case 0x03c0 : return 28;
91 case 0x2260 : return 29; 91 case 0x2260 : return 29;
92 case 0x00a3 : return 30; 92 case 0x00a3 : return 30;
93 case 0x00b7 : return 31; 93 case 0x00b7 : return 31;
94 } 94 }
95 return c; 95 return c;
96} 96}
97 97
98 98
99QSize EmulationWidget::calcSize( int cols, int lins ) const 99QSize EmulationWidget::calcSize( int cols, int lins ) const
100{ 100{
101 int frw = width() - contentsRect().width(); 101 int frw = width() - contentsRect().width();
102 102
103 int frh = height() - contentsRect().height(); 103 int frh = height() - contentsRect().height();
104 int scw = (scrollLoc == SCRNONE? 0 : m_scrollbar->width() ); 104 int scw = (scrollLoc == SCRNONE? 0 : m_scrollbar->width() );
105 return QSize( f_width * cols + 2 * rimX + frw + scw, f_height * lins + 2 * rimY + frh ); 105 return QSize( f_width * cols + 2 * rimX + frw + scw, f_height * lins + 2 * rimY + frh );
106} 106}
107 107
108void EmulationWidget::setImage( QArray<Character> const newimg, int lines, int columns ) 108void EmulationWidget::setImage( QArray<Character> const newimg, int lines, int columns )
109{ 109{
110 const QPixmap* pm = backgroundPixmap(); 110 const QPixmap* pm = backgroundPixmap();
111 QPainter paint; 111 QPainter paint;
112 112
113 // dont allow updates, while drawing 113 // dont allow updates, while drawing
114 setUpdatesEnabled( false ); 114 setUpdatesEnabled( false );
115 115
116 paint.begin( this ); 116 paint.begin( this );
117 117
118 QPoint tL = contentsRect().topLeft(); 118 QPoint tL = contentsRect().topLeft();
119 int tLx = tL.x(); 119 int tLx = tL.x();
120 int tLy = tL.y(); 120 int tLy = tL.y();
121 //hasBlinker = false; 121 //hasBlinker = false;
122 122
123 int cf = -1; 123 int cf = -1;
124 int cb = -1; 124 int cb = -1;
125 int cr = -1; 125 int cr = -1;
126 126
127 int lins = QMIN( m_lines, QMAX( 0, lines ) ); 127 int lins = QMIN( m_lines, QMAX( 0, lines ) );
128 int cols = QMIN( m_columns, QMAX( 0, columns ) ); 128 int cols = QMIN( m_columns, QMAX( 0, columns ) );
129 QArray<QChar> disstrU = QArray<QChar>( cols ); 129 QArray<QChar> disstrU = QArray<QChar>( cols );
130 130
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,426 +1,431 @@
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);
137 } 142 }
138 } 143 }
139 } 144 }
140 } 145 }
141} 146}
142 147
143void FunctionKeyboard::paintKey(uint row, uint col) { 148void FunctionKeyboard::paintKey(uint row, uint col) {
144 149
145 QPainter p(this); 150 QPainter p(this);
146 151
147 p.fillRect(QRect(QPoint(col * keyWidth + 1, row * keyHeight + 1), 152 p.fillRect(QRect(QPoint(col * keyWidth + 1, row * keyHeight + 1),
148 QPoint((col + 1) * keyWidth - 1, row * keyHeight + keyHeight- 1)), 153 QPoint((col + 1) * keyWidth - 1, row * keyHeight + keyHeight- 1)),
149 (pressedRow != -1 && pressedCol != -1 ) ? QColor(97,119,155) : QColor(255,255,255)); 154 (pressedRow != -1 && pressedCol != -1 ) ? QColor(97,119,155) : QColor(255,255,255));
150 155
151 QString handle ("r" + QString::number(row) + "c" + QString::number(col)); 156 QString handle ("r" + QString::number(row) + "c" + QString::number(col));
152 if (keys[handle].pixFile.isEmpty()) 157 if (keys[handle].pixFile.isEmpty())
153 p.drawText( 158 p.drawText(
154 col * keyWidth + 1, row * keyHeight + 1, 159 col * keyWidth + 1, row * keyHeight + 1,
155 keyWidth, keyHeight, 160 keyWidth, keyHeight,
156 Qt::AlignHCenter | Qt::AlignVCenter, 161 Qt::AlignHCenter | Qt::AlignVCenter,
157 keys[handle].label 162 keys[handle].label
158 ); 163 );
159 else { 164 else {
160 165
161 ushort centerX = (ushort)(col *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2; 166 ushort centerX = (ushort)(col *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2;
162 ushort centerY = row * keyHeight + (keyHeight - keys[handle].pix->height()) / 2; 167 ushort centerY = row * keyHeight + (keyHeight - keys[handle].pix->height()) / 2;
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
356 } 361 }
357 362
358} 363}
359void FunctionKeyboardConfig::slotChangeRows(int r) { 364void FunctionKeyboardConfig::slotChangeRows(int r) {
360 365
361 kb->changeRows(r); 366 kb->changeRows(r);
362 367
363} 368}
364void FunctionKeyboardConfig::slotChangeCols(int c) { 369void FunctionKeyboardConfig::slotChangeCols(int c) {
365 370
366 kb->changeCols(c); 371 kb->changeCols(c);
367} 372}
368void FunctionKeyboardConfig::slotKeyPressed(FKey k, ushort r, ushort c, bool pressed) { 373void FunctionKeyboardConfig::slotKeyPressed(FKey k, ushort r, ushort c, bool pressed) {
369 374
370 if (!pressed) return; 375 if (!pressed) return;
371 376
372 selectedHandle = "r" + QString::number(r) + 377 selectedHandle = "r" + QString::number(r) +
373 "c" + QString::number(c); 378 "c" + QString::number(c);
374 selectedRow = r; 379 selectedRow = r;
375 selectedCol = c; 380 selectedCol = c;
376 381
377 if (k.pixFile.isEmpty()) { 382 if (k.pixFile.isEmpty()) {
378 383
379 m_labels->setEditable(true); 384 m_labels->setEditable(true);
380 m_labels->setCurrentItem(0); 385 m_labels->setCurrentItem(0);
381 m_labels->changeItem(k.label, 0); 386 m_labels->changeItem(k.label, 0);
382 387
383 } else { 388 } else {
384 389
385 // any better way to select the pixmap? 390 // any better way to select the pixmap?
386 m_labels->setCurrentItem((m_labels->listBox())->index((m_labels->listBox())->findItem(kb->keys[selectedHandle].pixFile))); 391 m_labels->setCurrentItem((m_labels->listBox())->index((m_labels->listBox())->findItem(kb->keys[selectedHandle].pixFile)));
387 m_labels->setEditable(false); 392 m_labels->setEditable(false);
388 } 393 }
389 m_qvalues->changeItem(QString::number(k.qcode), 0); 394 m_qvalues->changeItem(QString::number(k.qcode), 0);
390 m_uniValues->changeItem(QString::number(k.unicode), 0); 395 m_uniValues->changeItem(QString::number(k.unicode), 0);
391} 396}
392void FunctionKeyboardConfig::slotChangeIcon(int index) { 397void FunctionKeyboardConfig::slotChangeIcon(int index) {
393 398
394 if (index == 0) { 399 if (index == 0) {
395 400
396 // is text 401 // is text
397 m_labels->setEditable(true); 402 m_labels->setEditable(true);
398 // why tf does the text get erased unless i do this? 403 // why tf does the text get erased unless i do this?
399 m_labels->changeItem(m_labels->text(0), 0); 404 m_labels->changeItem(m_labels->text(0), 0);
400 405
401 kb->keys[selectedHandle].pixFile = ""; 406 kb->keys[selectedHandle].pixFile = "";
402 delete kb->keys[selectedHandle].pix; 407 delete kb->keys[selectedHandle].pix;
403 408
404 } else { 409 } else {
405 410
406 // is a pixmap 411 // is a pixmap
407 m_labels->setEditable(false); 412 m_labels->setEditable(false);
408 kb->keys[selectedHandle].pixFile = m_labels->currentText(); 413 kb->keys[selectedHandle].pixFile = m_labels->currentText();
409 kb->keys[selectedHandle].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + m_labels->currentText() ) ); 414 kb->keys[selectedHandle].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + m_labels->currentText() ) );
410 } 415 }
411 kb->paintKey(selectedRow, selectedCol); 416 kb->paintKey(selectedRow, selectedCol);
412} 417}
413void FunctionKeyboardConfig::slotChangeLabelText(const QString &label) { 418void FunctionKeyboardConfig::slotChangeLabelText(const QString &label) {
414 419
415 kb->keys[selectedHandle].label = label; 420 kb->keys[selectedHandle].label = label;
416 421
417 kb->paintKey(selectedRow, selectedCol); 422 kb->paintKey(selectedRow, selectedCol);
418} 423}
419void FunctionKeyboardConfig::slotChangeQCode(const QString& qcode) { 424void FunctionKeyboardConfig::slotChangeQCode(const QString& qcode) {
420 425
421 kb->keys[selectedHandle].qcode = qcode.toUInt(); 426 kb->keys[selectedHandle].qcode = qcode.toUInt();
422} 427}
423void FunctionKeyboardConfig::slotChangeUnicode(const QString& uni) { 428void FunctionKeyboardConfig::slotChangeUnicode(const QString& uni) {
424 429
425 kb->keys[selectedHandle].unicode = uni.toUInt(); 430 kb->keys[selectedHandle].unicode = uni.toUInt();
426} 431}
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,728 +1,731 @@
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,
124 0, this, 0 ); 127 0, this, 0 );
125 m_transfer->addTo( m_console ); 128 m_transfer->addTo( m_console );
126 connect(m_transfer, SIGNAL(activated() ), 129 connect(m_transfer, SIGNAL(activated() ),
127 this, SLOT(slotTransfer() ) ); 130 this, SLOT(slotTransfer() ) );
128 131
129 132
130 133
131 /* 134 /*
132 * immediate change of line wrap policy 135 * immediate change of line wrap policy
133 */ 136 */
134 m_isWrapped = false; 137 m_isWrapped = false;
135 m_wrap = new QAction( tr("Line wrap"), Resource::loadPixmap( "linewrap" ), QString::null, 0, this, 0 ); 138 m_wrap = new QAction( tr("Line wrap"), Resource::loadPixmap( "linewrap" ), QString::null, 0, this, 0 );
136 m_wrap->addTo( m_console ); 139 m_wrap->addTo( m_console );
137 connect( m_wrap, SIGNAL( activated() ), SLOT( slotWrap() ) ); 140 connect( m_wrap, SIGNAL( activated() ), SLOT( slotWrap() ) );
138 141
139 /* 142 /*
140 * fullscreen 143 * fullscreen
141 */ 144 */
142 m_isFullscreen = false; 145 m_isFullscreen = false;
143 146
144 m_fullscreen = new QAction( tr("Full screen"), Resource::loadPixmap( "fullscreen" ) 147 m_fullscreen = new QAction( tr("Full screen"), Resource::loadPixmap( "fullscreen" )
145 , QString::null, 0, this, 0); 148 , QString::null, 0, this, 0);
146 m_fullscreen->addTo( m_console ); 149 m_fullscreen->addTo( m_console );
147 connect( m_fullscreen, SIGNAL( activated() ), 150 connect( m_fullscreen, SIGNAL( activated() ),
148 this, SLOT( slotFullscreen() ) ); 151 this, SLOT( slotFullscreen() ) );
149 152
150 m_console->insertSeparator(); 153 m_console->insertSeparator();
151 154
152 QAction *a = new QAction(); 155 QAction *a = new QAction();
153 a->setText( tr("Save history") ); 156 a->setText( tr("Save history") );
154 a->addTo( m_console ); 157 a->addTo( m_console );
155 connect(a, SIGNAL(activated() ), 158 connect(a, SIGNAL(activated() ),
156 this, SLOT(slotSaveHistory() ) ); 159 this, SLOT(slotSaveHistory() ) );
157 /* 160 /*
158 * terminate action 161 * terminate action
159 */ 162 */
160 m_terminate = new QAction(); 163 m_terminate = new QAction();
161 m_terminate->setText( tr("Terminate") ); 164 m_terminate->setText( tr("Terminate") );
162 m_terminate->addTo( m_console ); 165 m_terminate->addTo( m_console );
163 connect(m_terminate, SIGNAL(activated() ), 166 connect(m_terminate, SIGNAL(activated() ),
164 this, SLOT(slotTerminate() ) ); 167 this, SLOT(slotTerminate() ) );
165 168
166 m_closewindow = new QAction(); 169 m_closewindow = new QAction();
167 m_closewindow->setText( tr("Close Window") ); 170 m_closewindow->setText( tr("Close Window") );
168 m_closewindow->addTo( m_console ); 171 m_closewindow->addTo( m_console );
169 connect( m_closewindow, SIGNAL(activated() ), 172 connect( m_closewindow, SIGNAL(activated() ),
170 this, SLOT(slotClose() ) ); 173 this, SLOT(slotClose() ) );
171 174
172 175
173 /* 176 /*
174 * script actions 177 * script actions
175 */ 178 */
176 m_runScript_id = m_scripts->insertItem(tr("Run Script"), m_scriptsPop, -1, 0); 179 m_runScript_id = m_scripts->insertItem(tr("Run Script"), m_scriptsPop, -1, 0);
177 connect(m_scriptsPop, SIGNAL(activated(int)), this, SLOT(slotRunScript(int))); 180 connect(m_scriptsPop, SIGNAL(activated(int)), this, SLOT(slotRunScript(int)));
178 181
179 m_recordScript = new QAction(tr("Record Script"), QString::null, 0, this, 0); 182 m_recordScript = new QAction(tr("Record Script"), QString::null, 0, this, 0);
180 m_recordScript->addTo(m_scripts); 183 m_recordScript->addTo(m_scripts);
181 connect(m_recordScript, SIGNAL(activated()), this, SLOT(slotRecordScript())); 184 connect(m_recordScript, SIGNAL(activated()), this, SLOT(slotRecordScript()));
182 185
183 m_saveScript = new QAction(tr("Save Script"), QString::null, 0, this, 0); 186 m_saveScript = new QAction(tr("Save Script"), QString::null, 0, this, 0);
184 m_saveScript->addTo(m_scripts); 187 m_saveScript->addTo(m_scripts);
185 connect(m_saveScript, SIGNAL(activated()), this, SLOT(slotSaveScript())); 188 connect(m_saveScript, SIGNAL(activated()), this, SLOT(slotSaveScript()));
186 189
187 190
188 /* 191 /*
189 * action that open/closes the keyboard 192 * action that open/closes the keyboard
190 */ 193 */
191 m_openKeys = new QAction (tr("Open Keyboard..."), 194 m_openKeys = new QAction (tr("Open Keyboard..."),
192 Resource::loadPixmap( "console/keys/keyboard_icon" ), 195 Resource::loadPixmap( "console/keys/keyboard_icon" ),
193 QString::null, 0, this, 0); 196 QString::null, 0, this, 0);
194 m_openKeys->setToggleAction(true); 197 m_openKeys->setToggleAction(true);
195 connect (m_openKeys, SIGNAL(toggled(bool)), this, SLOT(slotOpenKeb(bool))); 198 connect (m_openKeys, SIGNAL(toggled(bool)), this, SLOT(slotOpenKeb(bool)));
196 199
197 /* insert the submenu */ 200 /* insert the submenu */
198 m_console->insertItem(tr("New from Profile"), m_sessionsPop, 201 m_console->insertItem(tr("New from Profile"), m_sessionsPop,
199 -1, 0); 202 -1, 0);
200 203
201 /* insert the connection menu */ 204 /* insert the connection menu */
202 m_bar->insertItem( tr("Connection"), m_console ); 205 m_bar->insertItem( tr("Connection"), m_console );
203 206
204 /* the scripts menu */ 207 /* the scripts menu */
205 m_bar->insertItem( tr("Scripts"), m_scripts ); 208 m_bar->insertItem( tr("Scripts"), m_scripts );
206 209
207 /* and the keyboard */ 210 /* and the keyboard */
208 m_keyBar = new QToolBar(this); 211 m_keyBar = new QToolBar(this);
209 addToolBar( m_keyBar, "Keyboard", QMainWindow::Top, TRUE ); 212 addToolBar( m_keyBar, "Keyboard", QMainWindow::Top, TRUE );
210 m_keyBar->setHorizontalStretchable( TRUE ); 213 m_keyBar->setHorizontalStretchable( TRUE );
211 m_keyBar->hide(); 214 m_keyBar->hide();
212 215
213 m_kb = new FunctionKeyboard(m_keyBar); 216 m_kb = new FunctionKeyboard(m_keyBar);
214 connect(m_kb, SIGNAL(keyPressed(FKey,ushort,ushort,bool)), 217 connect(m_kb, SIGNAL(keyPressed(FKey,ushort,ushort,bool)),
215 this, SLOT(slotKeyReceived(FKey,ushort,ushort,bool))); 218 this, SLOT(slotKeyReceived(FKey,ushort,ushort,bool)));
216 219
217 220
218 a = new QAction(tr("Copy"), 221 a = new QAction(tr("Copy"),
219 Resource::loadPixmap("copy"), QString::null, 222 Resource::loadPixmap("copy"), QString::null,
220 0, this, 0 ); 223 0, this, 0 );
221 //a->addTo( m_icons ); 224 //a->addTo( m_icons );
222 connect( a, SIGNAL(activated() ), 225 connect( a, SIGNAL(activated() ),
223 this, SLOT(slotCopy() ) ); 226 this, SLOT(slotCopy() ) );
224 227
225 QAction *paste = new QAction(tr("Paste"), 228 QAction *paste = new QAction(tr("Paste"),
226 Resource::loadPixmap("paste"), QString::null, 229 Resource::loadPixmap("paste"), QString::null,
227 0, this, 0 ); 230 0, this, 0 );
228 connect( paste, SIGNAL(activated() ), 231 connect( paste, SIGNAL(activated() ),
229 this, SLOT(slotPaste() ) ); 232 this, SLOT(slotPaste() ) );
230 233
231 234
232 newCon->addTo( m_icons ); 235 newCon->addTo( m_icons );
233 //m_setProfiles->addTo( m_icons ); 236 //m_setProfiles->addTo( m_icons );
234 paste->addTo( m_icons ); 237 paste->addTo( m_icons );
235 m_openKeys->addTo(m_icons); 238 m_openKeys->addTo(m_icons);
236 m_fullscreen->addTo( m_icons ); 239 m_fullscreen->addTo( m_icons );
237 240
238 m_connect->setEnabled( false ); 241 m_connect->setEnabled( false );
239 m_disconnect->setEnabled( false ); 242 m_disconnect->setEnabled( false );
240 m_terminate->setEnabled( false ); 243 m_terminate->setEnabled( false );
241 m_transfer->setEnabled( false ); 244 m_transfer->setEnabled( false );
242 m_scripts->setItemEnabled(m_runScript_id, false); 245 m_scripts->setItemEnabled(m_runScript_id, false);
243 m_recordScript->setEnabled( false ); 246 m_recordScript->setEnabled( false );
244 m_saveScript->setEnabled( false ); 247 m_saveScript->setEnabled( false );
245 m_fullscreen->setEnabled( false ); 248 m_fullscreen->setEnabled( false );
246 m_closewindow->setEnabled( false ); 249 m_closewindow->setEnabled( false );
247 m_wrap->setEnabled( false ); 250 m_wrap->setEnabled( false );
248 251
249 /* 252 /*
250 * connect to the menu activation 253 * connect to the menu activation
251 */ 254 */
252 connect( m_sessionsPop, SIGNAL(activated(int) ), 255 connect( m_sessionsPop, SIGNAL(activated(int) ),
253 this, SLOT(slotProfile(int) ) ); 256 this, SLOT(slotProfile(int) ) );
254 257
255 m_consoleWindow = new TabWidget( this, "blah"); 258 m_consoleWindow = new TabWidget( this, "blah");
256 connect(m_consoleWindow, SIGNAL(activated(Session*) ), 259 connect(m_consoleWindow, SIGNAL(activated(Session*) ),
257 this, SLOT(slotSessionChanged(Session*) ) ); 260 this, SLOT(slotSessionChanged(Session*) ) );
258 setCentralWidget( m_consoleWindow ); 261 setCentralWidget( m_consoleWindow );
259 262
260 slotQuickLaunch(); 263 slotQuickLaunch();
261} 264}
262 265
263ProfileManager* MainWindow::manager() { 266ProfileManager* MainWindow::manager() {
264 return m_manager; 267 return m_manager;
265} 268}
266TabWidget* MainWindow::tabWidget() { 269TabWidget* MainWindow::tabWidget() {
267 return m_consoleWindow; 270 return m_consoleWindow;
268} 271}
269void MainWindow::populateProfiles() { 272void MainWindow::populateProfiles() {
270 m_sessionsPop->clear(); 273 m_sessionsPop->clear();
271 Profile::ValueList list = manager()->all(); 274 Profile::ValueList list = manager()->all();
272 for (Profile::ValueList::Iterator it = list.begin(); it != list.end(); ++it ) { 275 for (Profile::ValueList::Iterator it = list.begin(); it != list.end(); ++it ) {
273 m_sessionsPop->insertItem( (*it).name() ); 276 m_sessionsPop->insertItem( (*it).name() );
274 } 277 }
275 278
276} 279}
277 280
278void MainWindow::populateScripts() { 281void MainWindow::populateScripts() {
279 m_scriptsPop->clear(); 282 m_scriptsPop->clear();
280 m_scriptsData.clear(); 283 m_scriptsData.clear();
281 DocLnkSet files(QPEApplication::documentDir(), "text/plain"); 284 DocLnkSet files(QPEApplication::documentDir(), "text/plain");
282 QListIterator<DocLnk> dit(files.children()); 285 QListIterator<DocLnk> dit(files.children());
283 for (; dit.current(); ++dit) { 286 for (; dit.current(); ++dit) {
284 if (*dit && (*dit)->name().length()>0) { 287 if (*dit && (*dit)->name().length()>0) {
285 QFileInfo info((*dit)->file()); 288 QFileInfo info((*dit)->file());
286 if (info.extension(false) == "script") { 289 if (info.extension(false) == "script") {
287 m_scriptsData.append(new DocLnk(**dit)); 290 m_scriptsData.append(new DocLnk(**dit));
288 m_scriptsPop->insertItem((*dit)->name()); 291 m_scriptsPop->insertItem((*dit)->name());
289 } 292 }
290 } 293 }
291 } 294 }
292 295
293} 296}
294 297
295MainWindow::~MainWindow() { 298MainWindow::~MainWindow() {
296 delete m_factory; 299 delete m_factory;
297 manager()->save(); 300 manager()->save();
298} 301}
299 302
300MetaFactory* MainWindow::factory() { 303MetaFactory* MainWindow::factory() {
301 return m_factory; 304 return m_factory;
302} 305}
303 306
304Session* MainWindow::currentSession() { 307Session* MainWindow::currentSession() {
305 return m_curSession; 308 return m_curSession;
306} 309}
307 310
308QList<Session> MainWindow::sessions() { 311QList<Session> MainWindow::sessions() {
309 return m_sessions; 312 return m_sessions;
310} 313}
311 314
312void MainWindow::slotNew() { 315void MainWindow::slotNew() {
313 ProfileEditorDialog dlg(factory() ); 316 ProfileEditorDialog dlg(factory() );
314 dlg.setCaption( tr("New Connection") ); 317 dlg.setCaption( tr("New Connection") );
315 int ret = QPEApplication::execDialog( &dlg ); 318 int ret = QPEApplication::execDialog( &dlg );
316 319
317 if ( ret == QDialog::Accepted ) { 320 if ( ret == QDialog::Accepted ) {
318 create( dlg.profile() ); 321 create( dlg.profile() );
319 } 322 }
320} 323}
321 324
322void MainWindow::slotRecordScript() { 325void MainWindow::slotRecordScript() {
323 if (currentSession()) { 326 if (currentSession()) {
324 currentSession()->emulationHandler()->startRecording(); 327 currentSession()->emulationHandler()->startRecording();
325 m_saveScript->setEnabled(true); 328 m_saveScript->setEnabled(true);
326 m_recordScript->setEnabled(false); 329 m_recordScript->setEnabled(false);
327 } 330 }
328} 331}
329 332
330void MainWindow::slotSaveScript() { 333void MainWindow::slotSaveScript() {
331 if (currentSession() && currentSession()->emulationHandler()->isRecording()) { 334 if (currentSession() && currentSession()->emulationHandler()->isRecording()) {
332 QMap<QString, QStringList> map; 335 QMap<QString, QStringList> map;
333 QStringList text; 336 QStringList text;
334 text << "text/plain"; 337 text << "text/plain";
335 map.insert(tr("Script"), text ); 338 map.insert(tr("Script"), text );
336 QString filename = OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map); 339 QString filename = OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map);
337 if (!filename.isEmpty()) { 340 if (!filename.isEmpty()) {
338 QFileInfo info(filename); 341 QFileInfo info(filename);
339 if (info.extension(FALSE) != "script") 342 if (info.extension(FALSE) != "script")
340 filename += ".script"; 343 filename += ".script";
341 DocLnk nf; 344 DocLnk nf;
342 nf.setType("text/plain"); 345 nf.setType("text/plain");
343 nf.setFile(filename); 346 nf.setFile(filename);
344 nf.setName(info.fileName()); 347 nf.setName(info.fileName());
345 FileManager fm; 348 FileManager fm;
346 fm.saveFile(nf, currentSession()->emulationHandler()->script()->script()); 349 fm.saveFile(nf, currentSession()->emulationHandler()->script()->script());
347 currentSession()->emulationHandler()->clearScript(); 350 currentSession()->emulationHandler()->clearScript();
348 m_saveScript->setEnabled(false); 351 m_saveScript->setEnabled(false);
349 m_recordScript->setEnabled(true); 352 m_recordScript->setEnabled(true);
350 populateScripts(); 353 populateScripts();
351 } 354 }
352 } 355 }
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();
679 } 682 }
680} 683}
681void MainWindow::slotCopy() { 684void MainWindow::slotCopy() {
682 if (!currentSession() ) return; 685 if (!currentSession() ) return;
683 currentSession()->emulationHandler()->copy(); 686 currentSession()->emulationHandler()->copy();
684} 687}
685void MainWindow::slotPaste() { 688void MainWindow::slotPaste() {
686 if (!currentSession() ) return; 689 if (!currentSession() ) return;
687 currentSession()->emulationHandler()->paste(); 690 currentSession()->emulationHandler()->paste();
688} 691}
689 692
690/* 693/*
691 * Save the session 694 * Save the session
692 */ 695 */
693 696
694void MainWindow::slotSaveSession() { 697void MainWindow::slotSaveSession() {
695 if (!currentSession() ) { 698 if (!currentSession() ) {
696 QMessageBox::information(this, tr("Save Connection"), 699 QMessageBox::information(this, tr("Save Connection"),
697 tr("<qt>There is no Connection.</qt>"), 1 ); 700 tr("<qt>There is no Connection.</qt>"), 1 );
698 return; 701 return;
699 } 702 }
700 manager()->add( currentSession()->profile() ); 703 manager()->add( currentSession()->profile() );
701 manager()->save(); 704 manager()->save();
702 populateProfiles(); 705 populateProfiles();
703} 706}
704void MainWindow::slotSaveHistory() { 707void MainWindow::slotSaveHistory() {
705 QMap<QString, QStringList> map; 708 QMap<QString, QStringList> map;
706 QStringList text; 709 QStringList text;
707 text << "text/plain"; 710 text << "text/plain";
708 map.insert(tr("History"), text ); 711 map.insert(tr("History"), text );
709 QString filename = OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map); 712 QString filename = OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map);
710 if (filename.isEmpty() ) return; 713 if (filename.isEmpty() ) return;
711 714
712 QFileInfo info(filename); 715 QFileInfo info(filename);
713 716
714 DocLnk nf; 717 DocLnk nf;
715 nf.setType("text/plain"); 718 nf.setType("text/plain");
716 nf.setFile(filename); 719 nf.setFile(filename);
717 nf.setName(info.fileName()); 720 nf.setName(info.fileName());
718 721
719 722
720 QFile file(filename); 723 QFile file(filename);
721 file.open(IO_WriteOnly ); 724 file.open(IO_WriteOnly );
722 QTextStream str(&file ); 725 QTextStream str(&file );
723 if ( currentSession() ) 726 if ( currentSession() )
724 currentSession()->emulationHandler()->emulation()->streamHistory(&str); 727 currentSession()->emulationHandler()->emulation()->streamHistory(&str);
725 728
726 file.close(); 729 file.close();
727 nf.writeLink(); 730 nf.writeLink();
728} 731}
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,256 +1,259 @@
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);
235} 238}
236 239
237void ModemConfigWidget::slotAT() { 240void ModemConfigWidget::slotAT() {
238 // ATConfigDialog conf( this, "ATConfig", true ); 241 // ATConfigDialog conf( this, "ATConfig", true );
239 // josef/Max I know why don't you create the stuff on the stack 242 // josef/Max I know why don't you create the stuff on the stack
240 // but making it a TopLevel Dialog and ignoring 243 // but making it a TopLevel Dialog and ignoring
241 // cancel is not fun either... 244 // cancel is not fun either...
242 // what to do? FIXME!!! -zecke 245 // what to do? FIXME!!! -zecke
243 if ( QPEApplication::execDialog( atConf ) != QDialog::Accepted ) { 246 if ( QPEApplication::execDialog( atConf ) != QDialog::Accepted ) {
244 // reload old settings 247 // reload old settings
245 } 248 }
246} 249}
247 250
248void ModemConfigWidget::slotDial() { 251void ModemConfigWidget::slotDial() {
249 DialDialog dial( this, "DialConfig", true ); 252 DialDialog dial( this, "DialConfig", true );
250 if(!m_telNumber->text().isEmpty()) { 253 if(!m_telNumber->text().isEmpty()) {
251 dial.setNumber(m_telNumber->text().replace(QRegExp("[\\-\\/\\ \\.\\,]"), "")); 254 dial.setNumber(m_telNumber->text().replace(QRegExp("[\\-\\/\\ \\.\\,]"), ""));
252 } 255 }
253 if ( QPEApplication::execDialog( &dial ) == QDialog::Accepted ) { 256 if ( QPEApplication::execDialog( &dial ) == QDialog::Accepted ) {
254 m_telNumber->setText( dial.number() ); 257 m_telNumber->setText( dial.number() );
255 } 258 }
256} 259}
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,221 +1,226 @@
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
169} 174}
170void TerminalWidget::save( Profile& profile ) { 175void TerminalWidget::save( Profile& profile ) {
171 switch(m_terminalBox->currentItem() ) { 176 switch(m_terminalBox->currentItem() ) {
172 case id_term_vt100: 177 case id_term_vt100:
173 profile.writeEntry("Terminal", Profile::VT100 ); 178 profile.writeEntry("Terminal", Profile::VT100 );
174 break; 179 break;
175 case id_term_vt102: 180 case id_term_vt102:
176 profile.writeEntry("Terminal", Profile::VT102 ); 181 profile.writeEntry("Terminal", Profile::VT102 );
177 break; 182 break;
178 case id_term_linux: 183 case id_term_linux:
179 profile.writeEntry("Terminal", Profile::Linux ); 184 profile.writeEntry("Terminal", Profile::Linux );
180 break; 185 break;
181 case id_term_xterm: 186 case id_term_xterm:
182 profile.writeEntry("Terminal", Profile::XTerm ); 187 profile.writeEntry("Terminal", Profile::XTerm );
183 break; 188 break;
184 //case id_term_ansi: 189 //case id_term_ansi:
185 // profile.writeEntry("Terminal", Profile::VT102 ); 190 // profile.writeEntry("Terminal", Profile::VT102 );
186 // break; 191 // break;
187 default: 192 default:
188 break; 193 break;
189 }; 194 };
190 195
191 // color 196 // color
192 switch(m_colorCmb->currentItem() ) { 197 switch(m_colorCmb->currentItem() ) {
193 case id_term_black: 198 case id_term_black:
194 profile.writeEntry("Color", Profile::Black ); 199 profile.writeEntry("Color", Profile::Black );
195 break; 200 break;
196 case id_term_white: 201 case id_term_white:
197 profile.writeEntry("Color", Profile::White ); 202 profile.writeEntry("Color", Profile::White );
198 break; 203 break;
199 case id_term_green: 204 case id_term_green:
200 profile.writeEntry("Color", Profile::Green ); 205 profile.writeEntry("Color", Profile::Green );
201 break; 206 break;
202 case id_term_orange: 207 case id_term_orange:
203 profile.writeEntry("Color", Profile::Orange ); 208 profile.writeEntry("Color", Profile::Orange );
204 break; 209 break;
205 default: 210 default:
206 break; 211 break;
207 }; 212 };
208 213
209 if (m_sizeSmall->isChecked() ) { 214 if (m_sizeSmall->isChecked() ) {
210 profile.writeEntry("Font", Profile::Micro ); 215 profile.writeEntry("Font", Profile::Micro );
211 }else if (m_sizeMedium->isChecked() ) { 216 }else if (m_sizeMedium->isChecked() ) {
212 profile.writeEntry("Font", Profile::Small ); 217 profile.writeEntry("Font", Profile::Small );
213 }else { 218 }else {
214 profile.writeEntry("Font", Profile::Medium ); 219 profile.writeEntry("Font", Profile::Medium );
215 } 220 }
216 221
217 profile.writeEntry("Echo", m_optionEcho->isChecked() ); 222 profile.writeEntry("Echo", m_optionEcho->isChecked() );
218 profile.writeEntry("Wrap", m_optionWrap->isChecked() ); 223 profile.writeEntry("Wrap", m_optionWrap->isChecked() );
219 profile.writeEntry("Inbound", m_convInbound->isChecked() ); 224 profile.writeEntry("Inbound", m_convInbound->isChecked() );
220 profile.writeEntry("Outbound",m_convOutbound->isChecked() ); 225 profile.writeEntry("Outbound",m_convOutbound->isChecked() );
221} 226}
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
@@ -1,1283 +1,1283 @@
1/* ------------------------------------------------------------------------ */ 1/* ------------------------------------------------------------------------ */
2/* */ 2/* */
3/* [TEWidget.C] Terminal Emulation Widget */ 3/* [TEWidget.C] Terminal Emulation Widget */
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/* ibot: 19/* ibot:
20 i changed 20 i changed
21 "currentSession->getEmulation()->sendString()" to 21 "currentSession->getEmulation()->sendString()" to
22 "currentSession->layer()->send()" 22 "currentSession->layer()->send()"
23 # this is not right! EmulationLayer should send it... 23 # this is not right! EmulationLayer should send it...
24 i changed all those to use emulationLayer()->send() instead 24 i changed all those to use emulationLayer()->send() instead
25 i had to create a QByteArray before... 25 i had to create a QByteArray before...
26 26
27TODO: 27TODO:
28alter Widget to use only QByteArray, where applicable. 28alter Widget to use only QByteArray, where applicable.
29*/ 29*/
30 30
31 31
32 32
33/*! \class Widget 33/*! \class Widget
34 34
35 \brief Visible screen contents 35 \brief Visible screen contents
36 36
37 This class is responsible to map the `image' of a terminal emulation to the 37 This class is responsible to map the `image' of a terminal emulation to the
38 display. All the dependency of the emulation to a specific GUI or toolkit is 38 display. All the dependency of the emulation to a specific GUI or toolkit is
39 localized here. Further, this widget has no knowledge about being part of an 39 localized here. Further, this widget has no knowledge about being part of an
40 emulation, it simply work within the terminal emulation framework by exposing 40 emulation, it simply work within the terminal emulation framework by exposing
41 size and key events and by being ordered to show a new image. 41 size and key events and by being ordered to show a new image.
42 42
43 <ul> 43 <ul>
44 <li> The internal image has the size of the widget (evtl. rounded up) 44 <li> The internal image has the size of the widget (evtl. rounded up)
45 <li> The external image used in setImage can have any size. 45 <li> The external image used in setImage can have any size.
46 <li> (internally) the external image is simply copied to the internal 46 <li> (internally) the external image is simply copied to the internal
47 when a setImage happens. During a resizeEvent no painting is done 47 when a setImage happens. During a resizeEvent no painting is done
48 a paintEvent is expected to follow anyway. 48 a paintEvent is expected to follow anyway.
49 </ul> 49 </ul>
50 50
51 \sa TEScreen \sa Emulation 51 \sa TEScreen \sa Emulation
52*/ 52*/
53 53
54/* FIXME: 54/* FIXME:
55 - 'image' may also be used uninitialized (it isn't in fact) in resizeEvent 55 - 'image' may also be used uninitialized (it isn't in fact) in resizeEvent
56 - 'font_a' not used in mouse events 56 - 'font_a' not used in mouse events
57 - add destructor 57 - add destructor
58*/ 58*/
59 59
60/* TODO 60/* TODO
61 - evtl. be sensitive to `paletteChange' while using default colors. 61 - evtl. be sensitive to `paletteChange' while using default colors.
62 - set different 'rounding' styles? I.e. have a mode to show clipped chars? 62 - set different 'rounding' styles? I.e. have a mode to show clipped chars?
63*/ 63*/
64 64
65// #include "config.h" 65// #include "config.h"
66#include "widget.h" 66#include "widget.h"
67#include <qpe/config.h> 67#include <qpe/config.h>
68 68
69#include <qclipboard.h> 69#include <qclipboard.h>
70 70
71#include <stdio.h> 71#include <stdio.h>
72#include <stdlib.h> 72#include <stdlib.h>
73#include <unistd.h> 73#include <unistd.h>
74#include <ctype.h> 74#include <ctype.h>
75#include <sys/stat.h> 75#include <sys/stat.h>
76#include <sys/types.h> 76#include <sys/types.h>
77#include <signal.h> 77#include <signal.h>
78 78
79#include <assert.h> 79#include <assert.h>
80 80
81// #include "widget.moc" 81// #include "widget.moc"
82//#include <kapp.h> 82//#include <kapp.h>
83//#include <kcursor.h> 83//#include <kcursor.h>
84//#include <kurl.h> 84//#include <kurl.h>
85//#include <kdebug.h> 85//#include <kdebug.h>
86//#include <klocale.h> 86//#include <klocale.h>
87 87
88#define HERE printf("%s(%d): %s\n",__FILE__,__LINE__,__FUNCTION__) 88#define HERE printf("%s(%d): %s\n",__FILE__,__LINE__,__FUNCTION__)
89#define HCNT(Name) // { static int cnt = 1; printf("%s(%d): %s %d\n",__FILE__,__LINE__,Name,cnt++); } 89#define HCNT(Name) // { static int cnt = 1; printf("%s(%d): %s %d\n",__FILE__,__LINE__,Name,cnt++); }
90 90
91#define loc(X,Y) ((Y)*columns+(X)) 91#define loc(X,Y) ((Y)*columns+(X))
92 92
93//FIXME: the rim should normally be 1, 0 only when running in full screen mode. 93//FIXME: the rim should normally be 1, 0 only when running in full screen mode.
94#define rimX 0 // left/right rim width 94#define rimX 0 // left/right rim width
95#define rimY 0 // top/bottom rim high 95#define rimY 0 // top/bottom rim high
96 96
97#define yMouseScroll 1 97#define yMouseScroll 1
98// scroll increment used when dragging selection at top/bottom of window. 98// scroll increment used when dragging selection at top/bottom of window.
99 99
100/* ------------------------------------------------------------------------- */ 100/* ------------------------------------------------------------------------- */
101/* */ 101/* */
102/* Colors */ 102/* Colors */
103/* */ 103/* */
104/* ------------------------------------------------------------------------- */ 104/* ------------------------------------------------------------------------- */
105 105
106//FIXME: the default color table is in session.C now. 106//FIXME: the default color table is in session.C now.
107// We need a way to get rid of this one, here. 107// We need a way to get rid of this one, here.
108static const ColorEntry base_color_table[TABLE_COLORS] = 108static const ColorEntry base_color_table[TABLE_COLORS] =
109// The following are almost IBM standard color codes, with some slight 109// The following are almost IBM standard color codes, with some slight
110// gamma correction for the dim colors to compensate for bright X screens. 110// gamma correction for the dim colors to compensate for bright X screens.
111// It contains the 8 ansiterm/xterm colors in 2 intensities. 111// It contains the 8 ansiterm/xterm colors in 2 intensities.
112{ 112{
113 // Fixme: could add faint colors here, also. 113 // Fixme: could add faint colors here, also.
114 // normal 114 // normal
115 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback 115 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback
116 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red 116 ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red
117 ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow 117 ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow
118 ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta 118 ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta
119 ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White 119 ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White
120 // intensiv 120 // intensiv
121 ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ), 121 ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ),
122 ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ), 122 ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ),
123 ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ), 123 ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ),
124 ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), 124 ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ),
125 ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 ) 125 ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 )
126}; 126};
127 127
128/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) 128/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb)
129 129
130 Code 0 1 2 3 4 5 6 7 130 Code 0 1 2 3 4 5 6 7
131 ----------- ------- ------- ------- ------- ------- ------- ------- ------- 131 ----------- ------- ------- ------- ------- ------- ------- ------- -------
132 ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White 132 ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White
133 IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White 133 IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White
134*/ 134*/
135 135
136QColor Widget::getDefaultBackColor() 136QColor Widget::getDefaultBackColor()
137{ 137{
138 return color_table[DEFAULT_BACK_COLOR].color; 138 return color_table[DEFAULT_BACK_COLOR].color;
139} 139}
140 140
141const ColorEntry* Widget::getColorTable() const 141const ColorEntry* Widget::getColorTable() const
142{ 142{
143 return color_table; 143 return color_table;
144} 144}
145 145
146const ColorEntry* Widget::getdefaultColorTable() const 146const ColorEntry* Widget::getdefaultColorTable() const
147{ 147{
148 return base_color_table; 148 return base_color_table;
149} 149}
150 150
151 151
152const QPixmap *Widget::backgroundPixmap() 152const QPixmap *Widget::backgroundPixmap()
153{ 153{
154 static QPixmap *bg = new QPixmap("~/qpim/main/pics/faded_bg.xpm"); 154 static QPixmap *bg = new QPixmap("~/qpim/main/pics/faded_bg.xpm");
155 const QPixmap *pm = bg; 155 const QPixmap *pm = bg;
156 return pm; 156 return pm;
157} 157}
158 158
159void Widget::setColorTable(const ColorEntry table[]) 159void Widget::setColorTable(const ColorEntry table[])
160{ 160{
161 for (int i = 0; i < TABLE_COLORS; i++) color_table[i] = table[i]; 161 for (int i = 0; i < TABLE_COLORS; i++) color_table[i] = table[i];
162 162
163 const QPixmap* pm = backgroundPixmap(); 163 const QPixmap* pm = backgroundPixmap();
164 if (!pm) setBackgroundColor(color_table[DEFAULT_BACK_COLOR].color); 164 if (!pm) setBackgroundColor(color_table[DEFAULT_BACK_COLOR].color);
165 update(); 165 update();
166} 166}
167 167
168//FIXME: add backgroundPixmapChanged. 168//FIXME: add backgroundPixmapChanged.
169 169
170/* ------------------------------------------------------------------------- */ 170/* ------------------------------------------------------------------------- */
171/* */ 171/* */
172/* Font */ 172/* Font */
173/* */ 173/* */
174/* ------------------------------------------------------------------------- */ 174/* ------------------------------------------------------------------------- */
175 175
176/* 176/*
177 The VT100 has 32 special graphical characters. The usual vt100 extended 177 The VT100 has 32 special graphical characters. The usual vt100 extended
178 xterm fonts have these at 0x00..0x1f. 178 xterm fonts have these at 0x00..0x1f.
179 179
180 QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals 180 QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals
181 come in here as proper unicode characters. 181 come in here as proper unicode characters.
182 182
183 We treat non-iso10646 fonts as VT100 extended and do the requiered mapping 183 We treat non-iso10646 fonts as VT100 extended and do the requiered mapping
184 from unicode to 0x00..0x1f. The remaining translation is then left to the 184 from unicode to 0x00..0x1f. The remaining translation is then left to the
185 QCodec. 185 QCodec.
186*/ 186*/
187 187
188// assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. 188// assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i.
189 189
190unsigned short vt100_graphics[32] = 190unsigned short vt100_graphics[32] =
191{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 191{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15
192 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 192 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0,
193 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 193 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c,
194 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, 194 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534,
195 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 195 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7
196}; 196};
197 197
198static QChar vt100extended(QChar c) 198static QChar vt100extended(QChar c)
199{ 199{
200 switch (c.unicode()) 200 switch (c.unicode())
201 { 201 {
202 case 0x25c6 : return 1; 202 case 0x25c6 : return 1;
203 case 0x2592 : return 2; 203 case 0x2592 : return 2;
204 case 0x2409 : return 3; 204 case 0x2409 : return 3;
205 case 0x240c : return 4; 205 case 0x240c : return 4;
206 case 0x240d : return 5; 206 case 0x240d : return 5;
207 case 0x240a : return 6; 207 case 0x240a : return 6;
208 case 0x00b0 : return 7; 208 case 0x00b0 : return 7;
209 case 0x00b1 : return 8; 209 case 0x00b1 : return 8;
210 case 0x2424 : return 9; 210 case 0x2424 : return 9;
211 case 0x240b : return 10; 211 case 0x240b : return 10;
212 case 0x2518 : return 11; 212 case 0x2518 : return 11;
213 case 0x2510 : return 12; 213 case 0x2510 : return 12;
214 case 0x250c : return 13; 214 case 0x250c : return 13;
215 case 0x2514 : return 14; 215 case 0x2514 : return 14;
216 case 0x253c : return 15; 216 case 0x253c : return 15;
217 case 0xf800 : return 16; 217 case 0xf800 : return 16;
218 case 0xf801 : return 17; 218 case 0xf801 : return 17;
219 case 0x2500 : return 18; 219 case 0x2500 : return 18;
220 case 0xf803 : return 19; 220 case 0xf803 : return 19;
221 case 0xf804 : return 20; 221 case 0xf804 : return 20;
222 case 0x251c : return 21; 222 case 0x251c : return 21;
223 case 0x2524 : return 22; 223 case 0x2524 : return 22;
224 case 0x2534 : return 23; 224 case 0x2534 : return 23;
225 case 0x252c : return 24; 225 case 0x252c : return 24;
226 case 0x2502 : return 25; 226 case 0x2502 : return 25;
227 case 0x2264 : return 26; 227 case 0x2264 : return 26;
228 case 0x2265 : return 27; 228 case 0x2265 : return 27;
229 case 0x03c0 : return 28; 229 case 0x03c0 : return 28;
230 case 0x2260 : return 29; 230 case 0x2260 : return 29;
231 case 0x00a3 : return 30; 231 case 0x00a3 : return 30;
232 case 0x00b7 : return 31; 232 case 0x00b7 : return 31;
233 } 233 }
234 return c; 234 return c;
235} 235}
236 236
237static QChar identicalMap(QChar c) 237static QChar identicalMap(QChar c)
238{ 238{
239 return c; 239 return c;
240} 240}
241 241
242void Widget::fontChange(const QFont &) 242void Widget::fontChange(const QFont &)
243{ 243{
244 QFontMetrics fm(font()); 244 QFontMetrics fm(font());
245 font_h = fm.height(); 245 font_h = fm.height();
246 font_w = fm.maxWidth(); 246 font_w = fm.maxWidth();
247 font_a = fm.ascent(); 247 font_a = fm.ascent();
248//printf("font_h: %d\n",font_h); 248//printf("font_h: %d\n",font_h);
249//printf("font_w: %d\n",font_w); 249//printf("font_w: %d\n",font_w);
250//printf("font_a: %d\n",font_a); 250//printf("font_a: %d\n",font_a);
251//printf("charset: %s\n",QFont::encodingName(font().charSet()).ascii()); 251//printf("charset: %s\n",QFont::encodingName(font().charSet()).ascii());
252//printf("rawname: %s\n",font().rawName().ascii()); 252//printf("rawname: %s\n",font().rawName().ascii());
253 fontMap = 253 fontMap =
254#if QT_VERSION < 300 254#if QT_VERSION < 300
255 strcmp(QFont::encodingName(font().charSet()).ascii(),"iso10646") 255 strcmp(QFont::encodingName(font().charSet()).ascii(),"iso10646")
256 ? vt100extended 256 ? vt100extended
257 : 257 :
258#endif 258#endif
259 identicalMap; 259 identicalMap;
260 propagateSize(); 260 propagateSize();
261 update(); 261 update();
262} 262}
263 263
264void Widget::setVTFont(const QFont& f) 264void Widget::setVTFont(const QFont& f)
265{ 265{
266 QFrame::setFont(f); 266 QFrame::setFont(f);
267} 267}
268 268
269QFont Widget::getVTFont() { 269QFont Widget::getVTFont() {
270 return font(); 270 return font();
271} 271}
272 272
273void Widget::setFont(const QFont &) 273void Widget::setFont(const QFont &)
274{ 274{
275 // ignore font change request if not coming from konsole itself 275 // ignore font change request if not coming from konsole itself
276} 276}
277 277
278/* ------------------------------------------------------------------------- */ 278/* ------------------------------------------------------------------------- */
279/* */ 279/* */
280/* Constructor / Destructor */ 280/* Constructor / Destructor */
281/* */ 281/* */
282/* ------------------------------------------------------------------------- */ 282/* ------------------------------------------------------------------------- */
283 283
284Widget::Widget(QWidget *parent, const char *name) : QFrame(parent,name) 284Widget::Widget(QWidget *parent, const char *name) : QFrame(parent,name)
285{ 285{
286#ifndef QT_NO_CLIPBOARD 286#ifndef QT_NO_CLIPBOARD
287 cb = QApplication::clipboard(); 287 cb = QApplication::clipboard();
288 QObject::connect( (QObject*)cb, SIGNAL(dataChanged()), 288 QObject::connect( (QObject*)cb, SIGNAL(dataChanged()),
289 this, SLOT(onClearSelection()) ); 289 this, SLOT(onClearSelection()) );
290#endif 290#endif
291 291
292 scrollbar = new QScrollBar(this); 292 scrollbar = new QScrollBar(this);
293 scrollbar->setCursor( arrowCursor ); 293 scrollbar->setCursor( arrowCursor );
294 connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); 294 connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int)));
295 295
296 Config cfg("Konsole"); 296 Config cfg("Konsole");
297 cfg.setGroup("ScrollBar"); 297 cfg.setGroup("ScrollBar");
298 switch( cfg.readNumEntry("Position",2)){ 298 switch( cfg.readNumEntry("Position",2)){
299 case 0: 299 case 0:
300 scrollLoc = SCRNONE; 300 scrollLoc = SCRNONE;
301 break; 301 break;
302 case 1: 302 case 1:
303 scrollLoc = SCRLEFT; 303 scrollLoc = SCRLEFT;
304 break; 304 break;
305 case 2: 305 case 2:
306 scrollLoc = SCRRIGHT; 306 scrollLoc = SCRRIGHT;
307 break; 307 break;
308 }; 308 };
309 309
310 blinkT = new QTimer(this); 310 blinkT = new QTimer(this);
311 connect(blinkT, SIGNAL(timeout()), this, SLOT(blinkEvent())); 311 connect(blinkT, SIGNAL(timeout()), this, SLOT(blinkEvent()));
312 // blinking = FALSE; 312 // blinking = FALSE;
313 blinking = TRUE; 313 blinking = TRUE;
314 314
315 resizing = FALSE; 315 resizing = FALSE;
316 actSel = 0; 316 actSel = 0;
317 image = 0; 317 image = 0;
318 lines = 1; 318 lines = 1;
319 columns = 1; 319 columns = 1;
320 font_w = 1; 320 font_w = 1;
321 font_h = 1; 321 font_h = 1;
322 font_a = 1; 322 font_a = 1;
323 word_selection_mode = FALSE; 323 word_selection_mode = FALSE;
324 324
325 setMouseMarks(TRUE); 325 setMouseMarks(TRUE);
326 setVTFont( QFont("fixed") ); 326 setVTFont( QFont("fixed") );
327 setColorTable(base_color_table); // init color table 327 setColorTable(base_color_table); // init color table
328 328
329 qApp->installEventFilter( this ); //FIXME: see below 329 qApp->installEventFilter( this ); //FIXME: see below
330// KCursor::setAutoHideCursor( this, true ); 330// KCursor::setAutoHideCursor( this, true );
331 331
332 // Init DnD //////////////////////////////////////////////////////////////// 332 // Init DnD ////////////////////////////////////////////////////////////////
333 currentSession = NULL; 333 currentSession = NULL;
334// setAcceptDrops(true); // attempt 334// setAcceptDrops(true); // attempt
335// m_drop = new QPopupMenu(this); 335// m_drop = new QPopupMenu(this);
336// m_drop->insertItem( QString("Paste"), 0); 336// m_drop->insertItem( QString("Paste"), 0);
337// m_drop->insertItem( QString("cd"), 1); 337// m_drop->insertItem( QString("cd"), 1);
338// connect(m_drop, SIGNAL(activated(int)), SLOT(drop_menu_activated(int))); 338// connect(m_drop, SIGNAL(activated(int)), SLOT(drop_menu_activated(int)));
339 339
340 // we need focus so that the auto-hide cursor feature works 340 // we need focus so that the auto-hide cursor feature works
341 setFocus(); 341 setFocus();
342 setFocusPolicy( WheelFocus ); 342 setFocusPolicy( WheelFocus );
343} 343}
344 344
345//FIXME: make proper destructor 345//FIXME: make proper destructor
346// Here's a start (David) 346// Here's a start (David)
347Widget::~Widget() 347Widget::~Widget()
348{ 348{
349 qApp->removeEventFilter( this ); 349 qApp->removeEventFilter( this );
350 if (image) free(image); 350 if (image) free(image);
351} 351}
352 352
353/* ------------------------------------------------------------------------- */ 353/* ------------------------------------------------------------------------- */
354/* */ 354/* */
355/* Display Operations */ 355/* Display Operations */
356/* */ 356/* */
357/* ------------------------------------------------------------------------- */ 357/* ------------------------------------------------------------------------- */
358 358
359/*! 359/*!
360 attributed string draw primitive 360 attributed string draw primitive
361*/ 361*/
362 362
363void Widget::drawAttrStr(QPainter &paint, QRect rect, 363void Widget::drawAttrStr(QPainter &paint, QRect rect,
364 QString& str, Character attr, BOOL pm, BOOL clear) 364 QString& str, Character attr, BOOL pm, BOOL clear)
365{ 365{
366 if (pm && color_table[attr.b].transparent) 366 if (pm && color_table[attr.b].transparent)
367 { 367 {
368 paint.setBackgroundMode( TransparentMode ); 368 paint.setBackgroundMode( TransparentMode );
369 if (clear) erase(rect); 369 if (clear) erase(rect);
370 } 370 }
371 else 371 else
372 { 372 {
373 if (blinking) 373 if (blinking)
374 paint.fillRect(rect, color_table[attr.b].color); 374 paint.fillRect(rect, color_table[attr.b].color);
375 else 375 else
376 { 376 {
377 paint.setBackgroundMode( OpaqueMode ); 377 paint.setBackgroundMode( OpaqueMode );
378 paint.setBackgroundColor( color_table[attr.b].color ); 378 paint.setBackgroundColor( color_table[attr.b].color );
379 } 379 }
380 } 380 }
381 381
382 if (color_table[attr.f].bold) 382 if (color_table[attr.f].bold)
383 paint.setPen(QColor( 0x8F, 0x00, 0x00 )); 383 paint.setPen(QColor( 0x8F, 0x00, 0x00 ));
384 else 384 else
385 paint.setPen(color_table[attr.f].color); 385 paint.setPen(color_table[attr.f].color);
386 386
387 paint.drawText(rect.x(),rect.y()+font_a, str); 387 paint.drawText(rect.x(),rect.y()+font_a, str);
388 388
389 if (attr.r & RE_UNDERLINE) 389 if (attr.r & RE_UNDERLINE)
390 paint.drawLine(rect.left(), rect.y()+font_a+1, rect.right(),rect.y()+font_a+1 ); 390 paint.drawLine(rect.left(), rect.y()+font_a+1, rect.right(),rect.y()+font_a+1 );
391} 391}
392 392
393/*! 393/*!
394 The image can only be set completely. 394 The image can only be set completely.
395 395
396 The size of the new image may or may not match the size of the widget. 396 The size of the new image may or may not match the size of the widget.
397*/ 397*/
398 398
399void Widget::setImage(const Character* const newimg, int lines, int columns) 399void Widget::setImage(const Character* const newimg, int lines, int columns)
400{ int y,x,len; 400{ int y,x,len;
401 const QPixmap* pm = backgroundPixmap(); 401 const QPixmap* pm = backgroundPixmap();
402 QPainter paint; 402 QPainter paint;
403 setUpdatesEnabled(FALSE); 403 setUpdatesEnabled(FALSE);
404 paint.begin( this ); 404 paint.begin( this );
405HCNT("setImage"); 405HCNT("setImage");
406 406
407 QPoint tL = contentsRect().topLeft(); 407 QPoint tL = contentsRect().topLeft();
408 int tLx = tL.x(); 408 int tLx = tL.x();
409 int tLy = tL.y(); 409 int tLy = tL.y();
410 hasBlinker = FALSE; 410 hasBlinker = FALSE;
411 411
412 int cf = -1; // undefined 412 int cf = -1; // undefined
413 int cb = -1; // undefined 413 int cb = -1; // undefined
414 int cr = -1; // undefined 414 int cr = -1; // undefined
415 415
416 int lins = QMIN(this->lines, QMAX(0,lines )); 416 int lins = QMIN(this->lines, QMAX(0,lines ));
417 int cols = QMIN(this->columns,QMAX(0,columns)); 417 int cols = QMIN(this->columns,QMAX(0,columns));
418 QChar *disstrU = new QChar[cols]; 418 QChar *disstrU = new QChar[cols];
419 419
420//{ static int cnt = 0; printf("setImage %d\n",cnt++); } 420//{ static int cnt = 0; printf("setImage %d\n",cnt++); }
421 for (y = 0; y < lins; y++) 421 for (y = 0; y < lins; y++)
422 { 422 {
423 const Character* lcl = &image[y*this->columns]; 423 const Character* lcl = &image[y*this->columns];
424 const Character* const ext = &newimg[y*columns]; 424 const Character* const ext = &newimg[y*columns];
425 if (!resizing) // not while resizing, we're expecting a paintEvent 425 if (!resizing) // not while resizing, we're expecting a paintEvent
426 for (x = 0; x < cols; x++) 426 for (x = 0; x < cols; x++)
427 { 427 {
428 hasBlinker |= (ext[x].r & RE_BLINK); 428 hasBlinker |= (ext[x].r & RE_BLINK);
429 if (ext[x] != lcl[x]) 429 if (ext[x] != lcl[x])
430 { 430 {
431 cr = ext[x].r; 431 cr = ext[x].r;
432 cb = ext[x].b; 432 cb = ext[x].b;
433 if (ext[x].f != cf) cf = ext[x].f; 433 if (ext[x].f != cf) cf = ext[x].f;
434 int lln = cols - x; 434 int lln = cols - x;
435 disstrU[0] = fontMap(ext[x+0].c); 435 disstrU[0] = fontMap(ext[x+0].c);
436 for (len = 1; len < lln; len++) 436 for (len = 1; len < lln; len++)
437 { 437 {
438 if (ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr || 438 if (ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr ||
439 ext[x+len] == lcl[x+len] ) 439 ext[x+len] == lcl[x+len] )
440 break; 440 break;
441 disstrU[len] = fontMap(ext[x+len].c); 441 disstrU[len] = fontMap(ext[x+len].c);
442 } 442 }
443 QString unistr(disstrU,len); 443 QString unistr(disstrU,len);
444 drawAttrStr(paint, 444 drawAttrStr(paint,
445 QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), 445 QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h),
446 unistr, ext[x], pm != NULL, true); 446 unistr, ext[x], pm != NULL, true);
447 x += len - 1; 447 x += len - 1;
448 } 448 }
449 } 449 }
450 // finally, make `image' become `newimg'. 450 // finally, make `image' become `newimg'.
451 memcpy((void*)lcl,(const void*)ext,cols*sizeof(Character)); 451 memcpy((void*)lcl,(const void*)ext,cols*sizeof(Character));
452 } 452 }
453 drawFrame( &paint ); 453 drawFrame( &paint );
454 paint.end(); 454 paint.end();
455 setUpdatesEnabled(TRUE); 455 setUpdatesEnabled(TRUE);
456 if ( hasBlinker && !blinkT->isActive()) blinkT->start(1000); // 1000 ms 456 if ( hasBlinker && !blinkT->isActive()) blinkT->start(1000); // 1000 ms
457 if (!hasBlinker && blinkT->isActive()) { blinkT->stop(); blinking = FALSE; } 457 if (!hasBlinker && blinkT->isActive()) { blinkT->stop(); blinking = FALSE; }
458 delete [] disstrU; 458 delete [] disstrU;
459} 459}
460 460
461// paint Event //////////////////////////////////////////////////// 461// paint Event ////////////////////////////////////////////////////
462 462
463/*! 463/*!
464 The difference of this routine vs. the `setImage' is, 464 The difference of this routine vs. the `setImage' is,
465 that the drawing does not include a difference analysis 465 that the drawing does not include a difference analysis
466 between the old and the new image. Instead, the internal 466 between the old and the new image. Instead, the internal
467 image is used and the painting bound by the PaintEvent box. 467 image is used and the painting bound by the PaintEvent box.
468*/ 468*/
469 469
470void Widget::paintEvent( QPaintEvent* pe ) 470void Widget::paintEvent( QPaintEvent* pe )
471{ 471{
472 472
473//{ static int cnt = 0; printf("paint %d\n",cnt++); } 473//{ static int cnt = 0; printf("paint %d\n",cnt++); }
474 const QPixmap* pm = backgroundPixmap(); 474 const QPixmap* pm = backgroundPixmap();
475 QPainter paint; 475 QPainter paint;
476 setUpdatesEnabled(FALSE); 476 setUpdatesEnabled(FALSE);
477 paint.begin( this ); 477 paint.begin( this );
478 paint.setBackgroundMode( TransparentMode ); 478 paint.setBackgroundMode( TransparentMode );
479HCNT("paintEvent"); 479HCNT("paintEvent");
480 480
481 // Note that the actual widget size can be slightly larger 481 // Note that the actual widget size can be slightly larger
482 // that the image (the size is truncated towards the smaller 482 // that the image (the size is truncated towards the smaller
483 // number of characters in `resizeEvent'. The paint rectangle 483 // number of characters in `resizeEvent'. The paint rectangle
484 // can thus be larger than the image, but less then the size 484 // can thus be larger than the image, but less then the size
485 // of one character. 485 // of one character.
486 486
487 QRect rect = pe->rect().intersect(contentsRect()); 487 QRect rect = pe->rect().intersect(contentsRect());
488 488
489 QPoint tL = contentsRect().topLeft(); 489 QPoint tL = contentsRect().topLeft();
490 int tLx = tL.x(); 490 int tLx = tL.x();
491 int tLy = tL.y(); 491 int tLy = tL.y();
492 492
493 int lux = QMIN(columns-1, QMAX(0,(rect.left() - tLx - blX ) / font_w)); 493 int lux = QMIN(columns-1, QMAX(0,(rect.left() - tLx - blX ) / font_w));
494 int luy = QMIN(lines-1, QMAX(0,(rect.top() - tLy - bY ) / font_h)); 494 int luy = QMIN(lines-1, QMAX(0,(rect.top() - tLy - bY ) / font_h));
495 int rlx = QMIN(columns-1, QMAX(0,(rect.right() - tLx - blX ) / font_w)); 495 int rlx = QMIN(columns-1, QMAX(0,(rect.right() - tLx - blX ) / font_w));
496 int rly = QMIN(lines-1, QMAX(0,(rect.bottom() - tLy - bY ) / font_h)); 496 int rly = QMIN(lines-1, QMAX(0,(rect.bottom() - tLy - bY ) / font_h));
497 497
498 /* 498 /*
499 printf("paintEvent: %d..%d, %d..%d (%d..%d, %d..%d)\n",lux,rlx,luy,rly, 499 printf("paintEvent: %d..%d, %d..%d (%d..%d, %d..%d)\n",lux,rlx,luy,rly,
500 rect.left(), rect.right(), rect.top(), rect.bottom()); 500 rect.left(), rect.right(), rect.top(), rect.bottom());
501 */ 501 */
502 502
503 // if (pm != NULL && color_table[image->b].transparent) 503 // if (pm != NULL && color_table[image->b].transparent)
504 // erase(rect); 504 // erase(rect);
505 // BL: I have no idea why we need this, and it breaks the refresh. 505 // BL: I have no idea why we need this, and it breaks the refresh.
506 506
507 QChar *disstrU = new QChar[columns]; 507 QChar *disstrU = new QChar[columns];
508 for (int y = luy; y <= rly; y++) 508 for (int y = luy; y <= rly; y++)
509 for (int x = lux; x <= rlx; x++) 509 for (int x = lux; x <= rlx; x++)
510 { 510 {
511 int len = 1; 511 int len = 1;
512 disstrU[0] = fontMap(image[loc(x,y)].c); 512 disstrU[0] = fontMap(image[loc(x,y)].c);
513 int cf = image[loc(x,y)].f; 513 int cf = image[loc(x,y)].f;
514 int cb = image[loc(x,y)].b; 514 int cb = image[loc(x,y)].b;
515 int cr = image[loc(x,y)].r; 515 int cr = image[loc(x,y)].r;
516 while (x+len <= rlx && 516 while (x+len <= rlx &&
517 image[loc(x+len,y)].f == cf && 517 image[loc(x+len,y)].f == cf &&
518 image[loc(x+len,y)].b == cb && 518 image[loc(x+len,y)].b == cb &&
519 image[loc(x+len,y)].r == cr ) 519 image[loc(x+len,y)].r == cr )
520 { 520 {
521 disstrU[len] = fontMap(image[loc(x+len,y)].c); 521 disstrU[len] = fontMap(image[loc(x+len,y)].c);
522 len += 1; 522 len += 1;
523 } 523 }
524 QString unistr(disstrU,len); 524 QString unistr(disstrU,len);
525 drawAttrStr(paint, 525 drawAttrStr(paint,
526 QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), 526 QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h),
527 unistr, image[loc(x,y)], pm != NULL, false); 527 unistr, image[loc(x,y)], pm != NULL, false);
528 x += len - 1; 528 x += len - 1;
529 } 529 }
530 delete [] disstrU; 530 delete [] disstrU;
531 drawFrame( &paint ); 531 drawFrame( &paint );
532 paint.end(); 532 paint.end();
533 setUpdatesEnabled(TRUE); 533 setUpdatesEnabled(TRUE);
534} 534}
535 535
536void Widget::blinkEvent() 536void Widget::blinkEvent()
537{ 537{
538 blinking = !blinking; 538 blinking = !blinking;
539 repaint(FALSE); 539 repaint(FALSE);
540} 540}
541 541
542/* ------------------------------------------------------------------------- */ 542/* ------------------------------------------------------------------------- */
543/* */ 543/* */
544/* Resizing */ 544/* Resizing */
545/* */ 545/* */
546/* ------------------------------------------------------------------------- */ 546/* ------------------------------------------------------------------------- */
547 547
548void Widget::resizeEvent(QResizeEvent* ev) 548void Widget::resizeEvent(QResizeEvent* ev)
549{ 549{
550// printf("resize: %d,%d\n",ev->size().width(),ev->size().height()); 550// printf("resize: %d,%d\n",ev->size().width(),ev->size().height());
551 //printf("approx: %d,%d\n",ev->size().width()/font_w,ev->size().height()/font_h); 551 //printf("approx: %d,%d\n",ev->size().width()/font_w,ev->size().height()/font_h);
552 //printf("leaves: %d,%d\n",ev->size().width()%font_w,ev->size().height()%font_h); 552 //printf("leaves: %d,%d\n",ev->size().width()%font_w,ev->size().height()%font_h);
553 //printf("curren: %d,%d\n",width(),height()); 553 //printf("curren: %d,%d\n",width(),height());
554HCNT("resizeEvent"); 554HCNT("resizeEvent");
555 555
556 // see comment in `paintEvent' concerning the rounding. 556 // see comment in `paintEvent' concerning the rounding.
557 //FIXME: could make a routine here; check width(),height() 557 //FIXME: could make a routine here; check width(),height()
558 assert(ev->size().width() == width()); 558 assert(ev->size().width() == width());
559 assert(ev->size().height() == height()); 559 assert(ev->size().height() == height());
560 560
561 propagateSize(); 561 propagateSize();
562} 562}
563 563
564void Widget::propagateSize() 564void Widget::propagateSize()
565{ 565{
566 Character* oldimg = image; 566 Character* oldimg = image;
567 int oldlin = lines; 567 int oldlin = lines;
568 int oldcol = columns; 568 int oldcol = columns;
569 makeImage(); 569 makeImage();
570 // we copy the old image to reduce flicker 570 // we copy the old image to reduce flicker
571 int lins = QMIN(oldlin,lines); 571 int lins = QMIN(oldlin,lines);
572 int cols = QMIN(oldcol,columns); 572 int cols = QMIN(oldcol,columns);
573 if (oldimg) 573 if (oldimg)
574 { 574 {
575 for (int lin = 0; lin < lins; lin++) 575 for (int lin = 0; lin < lins; lin++)
576 memcpy((void*)&image[columns*lin], 576 memcpy((void*)&image[columns*lin],
577 (void*)&oldimg[oldcol*lin],cols*sizeof(Character)); 577 (void*)&oldimg[oldcol*lin],cols*sizeof(Character));
578 free(oldimg); //FIXME: try new,delete 578 free(oldimg); //FIXME: try new,delete
579 } 579 }
580 else 580 else
581 clearImage(); 581 clearImage();
582 582
583 //NOTE: control flows from the back through the chest right into the eye. 583 //NOTE: control flows from the back through the chest right into the eye.
584 // `emu' will call back via `setImage'. 584 // `emu' will call back via `setImage'.
585 585
586 resizing = TRUE; 586 resizing = TRUE;
587 emit changedImageSizeSignal(lines, columns); // expose resizeEvent 587 emit changedImageSizeSignal(lines, columns); // expose resizeEvent
588 resizing = FALSE; 588 resizing = FALSE;
589} 589}
590 590
591/* ------------------------------------------------------------------------- */ 591/* ------------------------------------------------------------------------- */
592/* */ 592/* */
593/* Scrollbar */ 593/* Scrollbar */
594/* */ 594/* */
595/* ------------------------------------------------------------------------- */ 595/* ------------------------------------------------------------------------- */
596 596
597void Widget::scrollChanged(int) 597void Widget::scrollChanged(int)
598{ 598{
599 emit changedHistoryCursor(scrollbar->value()); //expose 599 emit changedHistoryCursor(scrollbar->value()); //expose
600} 600}
601 601
602void Widget::setScroll(int cursor, int slines) 602void Widget::setScroll(int cursor, int slines)
603{ 603{
604 disconnect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); 604 disconnect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int)));
605 scrollbar->setRange(0,slines); 605 scrollbar->setRange(0,slines);
606 scrollbar->setSteps(1,lines); 606 scrollbar->setSteps(1,lines);
607 scrollbar->setValue(cursor); 607 scrollbar->setValue(cursor);
608 connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); 608 connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int)));
609} 609}
610 610
611void Widget::setScrollbarLocation(int loc) 611void Widget::setScrollbarLocation(int loc)
612{ 612{
613 if (scrollLoc == loc) return; // quickly 613 if (scrollLoc == loc) return; // quickly
614 scrollLoc = loc; 614 scrollLoc = loc;
615 propagateSize(); 615 propagateSize();
616 update(); 616 update();
617} 617}
618 618
619/* ------------------------------------------------------------------------- */ 619/* ------------------------------------------------------------------------- */
620/* */ 620/* */
621/* Mouse */ 621/* Mouse */
622/* */ 622/* */
623/* ------------------------------------------------------------------------- */ 623/* ------------------------------------------------------------------------- */
624 624
625/*! 625/*!
626 Three different operations can be performed using the mouse, and the 626 Three different operations can be performed using the mouse, and the
627 routines in this section serve all of them: 627 routines in this section serve all of them:
628 628
629 1) The press/release events are exposed to the application 629 1) The press/release events are exposed to the application
630 2) Marking (press and move left button) and Pasting (press middle button) 630 2) Marking (press and move left button) and Pasting (press middle button)
631 3) The right mouse button is used from the configuration menu 631 3) The right mouse button is used from the configuration menu
632 632
633 NOTE: During the marking process we attempt to keep the cursor within 633 NOTE: During the marking process we attempt to keep the cursor within
634 the bounds of the text as being displayed by setting the mouse position 634 the bounds of the text as being displayed by setting the mouse position
635 whenever the mouse has left the text area. 635 whenever the mouse has left the text area.
636 636
637 Two reasons to do so: 637 Two reasons to do so:
638 1) QT does not allow the `grabMouse' to confine-to the Widget. 638 1) QT does not allow the `grabMouse' to confine-to the Widget.
639 Thus a `XGrapPointer' would have to be used instead. 639 Thus a `XGrapPointer' would have to be used instead.
640 2) Even if so, this would not help too much, since the text area 640 2) Even if so, this would not help too much, since the text area
641 of the Widget is normally not identical with it's bounds. 641 of the Widget is normally not identical with it's bounds.
642 642
643 The disadvantage of the current handling is, that the mouse can visibly 643 The disadvantage of the current handling is, that the mouse can visibly
644 leave the bounds of the widget and is then moved back. Because of the 644 leave the bounds of the widget and is then moved back. Because of the
645 current construction, and the reasons mentioned above, we cannot do better 645 current construction, and the reasons mentioned above, we cannot do better
646 without changing the overall construction. 646 without changing the overall construction.
647*/ 647*/
648 648
649/*! 649/*!
650*/ 650*/
651 651
652void Widget::mousePressEvent(QMouseEvent* ev) 652void Widget::mousePressEvent(QMouseEvent* ev)
653{ 653{
654//printf("press [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button()); 654//printf("press [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button());
655 if ( !contentsRect().contains(ev->pos()) ) return; 655 if ( !contentsRect().contains(ev->pos()) ) return;
656 QPoint tL = contentsRect().topLeft(); 656 QPoint tL = contentsRect().topLeft();
657 int tLx = tL.x(); 657 int tLx = tL.x();
658 int tLy = tL.y(); 658 int tLy = tL.y();
659 659
660 word_selection_mode = FALSE; 660 word_selection_mode = FALSE;
661 661
662//printf("press top left [%d,%d] by=%d\n",tLx,tLy, bY); 662//printf("press top left [%d,%d] by=%d\n",tLx,tLy, bY);
663 if ( ev->button() == LeftButton) 663 if ( ev->button() == LeftButton)
664 { 664 {
665 QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); 665 QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h);
666 666
667 if ( ev->state() & ControlButton ) preserve_line_breaks = FALSE ; 667 if ( ev->state() & ControlButton ) preserve_line_breaks = FALSE ;
668 668
669 if (mouse_marks || (ev->state() & ShiftButton)) 669 if (mouse_marks || (ev->state() & ShiftButton))
670 { 670 {
671 emit clearSelectionSignal(); 671 emit clearSelectionSignal();
672 iPntSel = pntSel = pos; 672 iPntSel = pntSel = pos;
673 actSel = 1; // left mouse button pressed but nothing selected yet. 673 actSel = 1; // left mouse button pressed but nothing selected yet.
674 grabMouse( /*crossCursor*/ ); // handle with care! 674 grabMouse( /*crossCursor*/ ); // handle with care!
675 } 675 }
676 else 676 else
677 { 677 {
678 emit mouseSignal( 0, pos.x() + 1, pos.y() + 1 ); // left button 678 emit mouseSignal( 0, pos.x() + 1, pos.y() + 1 ); // left button
679 } 679 }
680 } 680 }
681 if ( ev->button() == MidButton ) 681 if ( ev->button() == MidButton )
682 { 682 {
683 emitSelection(); 683 emitSelection();
684 } 684 }
685 if ( ev->button() == RightButton ) // Configure 685 if ( ev->button() == RightButton ) // Configure
686 { 686 {
687 emit configureRequest( this, ev->state()&(ShiftButton|ControlButton), ev->x(), ev->y() ); 687 emit configureRequest( this, ev->state()&(ShiftButton|ControlButton), ev->x(), ev->y() );
688 } 688 }
689} 689}
690 690
691void Widget::mouseMoveEvent(QMouseEvent* ev) 691void Widget::mouseMoveEvent(QMouseEvent* ev)
692{ 692{
693 // for auto-hiding the cursor, we need mouseTracking 693 // for auto-hiding the cursor, we need mouseTracking
694 if (ev->state() == NoButton ) return; 694 if (ev->state() == NoButton ) return;
695 695
696 if (actSel == 0) return; 696 if (actSel == 0) return;
697 697
698 // don't extend selection while pasting 698 // don't extend selection while pasting
699 if (ev->state() & MidButton) return; 699 if (ev->state() & MidButton) return;
700 700
701 //if ( !contentsRect().contains(ev->pos()) ) return; 701 //if ( !contentsRect().contains(ev->pos()) ) return;
702 QPoint tL = contentsRect().topLeft(); 702 QPoint tL = contentsRect().topLeft();
703 int tLx = tL.x(); 703 int tLx = tL.x();
704 int tLy = tL.y(); 704 int tLy = tL.y();
705 int scroll = scrollbar->value(); 705 int scroll = scrollbar->value();
706 706
707 // we're in the process of moving the mouse with the left button pressed 707 // we're in the process of moving the mouse with the left button pressed
708 // the mouse cursor will kept catched within the bounds of the text in 708 // the mouse cursor will kept catched within the bounds of the text in
709 // this widget. 709 // this widget.
710 710
711 // Adjust position within text area bounds. See FIXME above. 711 // Adjust position within text area bounds. See FIXME above.
712 QPoint pos = ev->pos(); 712 QPoint pos = ev->pos();
713 if ( pos.x() < tLx+blX ) pos.setX( tLx+blX ); 713 if ( pos.x() < tLx+blX ) pos.setX( tLx+blX );
714 if ( pos.x() > tLx+blX+columns*font_w-1 ) pos.setX( tLx+blX+columns*font_w ); 714 if ( pos.x() > tLx+blX+columns*font_w-1 ) pos.setX( tLx+blX+columns*font_w );
715 if ( pos.y() < tLy+bY ) pos.setY( tLy+bY ); 715 if ( pos.y() < tLy+bY ) pos.setY( tLy+bY );
716 if ( pos.y() > tLy+bY+lines*font_h-1 ) pos.setY( tLy+bY+lines*font_h-1 ); 716 if ( pos.y() > tLy+bY+lines*font_h-1 ) pos.setY( tLy+bY+lines*font_h-1 );
717 // check if we produce a mouse move event by this 717 // check if we produce a mouse move event by this
718 if ( pos != ev->pos() ) cursor().setPos(mapToGlobal(pos)); 718 if ( pos != ev->pos() ) cursor().setPos(mapToGlobal(pos));
719 719
720 if ( pos.y() == tLy+bY+lines*font_h-1 ) 720 if ( pos.y() == tLy+bY+lines*font_h-1 )
721 { 721 {
722 scrollbar->setValue(scrollbar->value()+yMouseScroll); // scrollforward 722 scrollbar->setValue(scrollbar->value()+yMouseScroll); // scrollforward
723 } 723 }
724 if ( pos.y() == tLy+bY ) 724 if ( pos.y() == tLy+bY )
725 { 725 {
726 scrollbar->setValue(scrollbar->value()-yMouseScroll); // scrollback 726 scrollbar->setValue(scrollbar->value()-yMouseScroll); // scrollback
727 } 727 }
728 728
729 QPoint here = QPoint((pos.x()-tLx-blX)/font_w,(pos.y()-tLy-bY)/font_h); 729 QPoint here = QPoint((pos.x()-tLx-blX)/font_w,(pos.y()-tLy-bY)/font_h);
730 QPoint ohere; 730 QPoint ohere;
731 bool swapping = FALSE; 731 bool swapping = FALSE;
732 732
733 if ( word_selection_mode ) 733 if ( word_selection_mode )
734 { 734 {
735 // Extend to word boundaries 735 // Extend to word boundaries
736 int i; 736 int i;
737 int selClass; 737 int selClass;
738 738
739 bool left_not_right = ( here.y() < iPntSel.y() || 739 bool left_not_right = ( here.y() < iPntSel.y() ||
740 here.y() == iPntSel.y() && here.x() < iPntSel.x() ); 740 here.y() == iPntSel.y() && here.x() < iPntSel.x() );
741 bool old_left_not_right = ( pntSel.y() < iPntSel.y() || 741 bool old_left_not_right = ( pntSel.y() < iPntSel.y() ||
742 pntSel.y() == iPntSel.y() && pntSel.x() < iPntSel.x() ); 742 pntSel.y() == iPntSel.y() && pntSel.x() < iPntSel.x() );
743 swapping = left_not_right != old_left_not_right; 743 swapping = left_not_right != old_left_not_right;
744 744
745 // Find left (left_not_right ? from here : from start) 745 // Find left (left_not_right ? from here : from start)
746 QPoint left = left_not_right ? here : iPntSel; 746 QPoint left = left_not_right ? here : iPntSel;
747 i = loc(left.x(),left.y()); 747 i = loc(left.x(),left.y());
748 selClass = charClass(image[i].c); 748 selClass = charClass(image[i].c);
749 while ( left.x() > 0 && charClass(image[i-1].c) == selClass ) 749 while ( left.x() > 0 && charClass(image[i-1].c) == selClass )
750 { i--; left.rx()--; } 750 { i--; left.rx()--; }
751 751
752 // Find left (left_not_right ? from start : from here) 752 // Find left (left_not_right ? from start : from here)
753 QPoint right = left_not_right ? iPntSel : here; 753 QPoint right = left_not_right ? iPntSel : here;
754 i = loc(right.x(),right.y()); 754 i = loc(right.x(),right.y());
755 selClass = charClass(image[i].c); 755 selClass = charClass(image[i].c);
756 while ( right.x() < columns-1 && charClass(image[i+1].c) == selClass ) 756 while ( right.x() < columns-1 && charClass(image[i+1].c) == selClass )
757 { i++; right.rx()++; } 757 { i++; right.rx()++; }
758 758
759 // Pick which is start (ohere) and which is extension (here) 759 // Pick which is start (ohere) and which is extension (here)
760 if ( left_not_right ) 760 if ( left_not_right )
761 { 761 {
762 here = left; ohere = right; 762 here = left; ohere = right;
763 } 763 }
764 else 764 else
765 { 765 {
766 here = right; ohere = left; 766 here = right; ohere = left;
767 } 767 }
768 } 768 }
769 769
770 if (here == pntSel && scroll == scrollbar->value()) return; // not moved 770 if (here == pntSel && scroll == scrollbar->value()) return; // not moved
771 771
772 if ( word_selection_mode ) { 772 if ( word_selection_mode ) {
773 if ( actSel < 2 || swapping ) { 773 if ( actSel < 2 || swapping ) {
774 emit beginSelectionSignal( ohere.x(), ohere.y() ); 774 emit beginSelectionSignal( ohere.x(), ohere.y() );
775 } 775 }
776 } else if ( actSel < 2 ) { 776 } else if ( actSel < 2 ) {
777 emit beginSelectionSignal( pntSel.x(), pntSel.y() ); 777 emit beginSelectionSignal( pntSel.x(), pntSel.y() );
778 } 778 }
779 779
780 actSel = 2; // within selection 780 actSel = 2; // within selection
781 pntSel = here; 781 pntSel = here;
782 emit extendSelectionSignal( here.x(), here.y() ); 782 emit extendSelectionSignal( here.x(), here.y() );
783} 783}
784 784
785void Widget::mouseReleaseEvent(QMouseEvent* ev) 785void Widget::mouseReleaseEvent(QMouseEvent* ev)
786{ 786{
787//printf("release [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button()); 787//printf("release [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button());
788 if ( ev->button() == LeftButton) 788 if ( ev->button() == LeftButton)
789 { 789 {
790 if ( actSel > 1 ) emit endSelectionSignal(preserve_line_breaks); 790 if ( actSel > 1 ) emit endSelectionSignal(preserve_line_breaks);
791 preserve_line_breaks = TRUE; 791 preserve_line_breaks = TRUE;
792 actSel = 0; 792 actSel = 0;
793 793
794 //FIXME: emits a release event even if the mouse is 794 //FIXME: emits a release event even if the mouse is
795 // outside the range. The procedure used in `mouseMoveEvent' 795 // outside the range. The procedure used in `mouseMoveEvent'
796 // applies here, too. 796 // applies here, too.
797 797
798 QPoint tL = contentsRect().topLeft(); 798 QPoint tL = contentsRect().topLeft();
799 int tLx = tL.x(); 799 int tLx = tL.x();
800 int tLy = tL.y(); 800 int tLy = tL.y();
801 801
802 if (!mouse_marks && !(ev->state() & ShiftButton)) 802 if (!mouse_marks && !(ev->state() & ShiftButton))
803 emit mouseSignal( 3, // release 803 emit mouseSignal( 3, // release
804 (ev->x()-tLx-blX)/font_w + 1, 804 (ev->x()-tLx-blX)/font_w + 1,
805 (ev->y()-tLy-bY)/font_h + 1 ); 805 (ev->y()-tLy-bY)/font_h + 1 );
806 releaseMouse(); 806 releaseMouse();
807 } 807 }
808} 808}
809 809
810void Widget::mouseDoubleClickEvent(QMouseEvent* ev) 810void Widget::mouseDoubleClickEvent(QMouseEvent* ev)
811{ 811{
812 if ( ev->button() != LeftButton) return; 812 if ( ev->button() != LeftButton) return;
813 813
814 QPoint tL = contentsRect().topLeft(); 814 QPoint tL = contentsRect().topLeft();
815 int tLx = tL.x(); 815 int tLx = tL.x();
816 int tLy = tL.y(); 816 int tLy = tL.y();
817 QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); 817 QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h);
818 818
819 // pass on double click as two clicks. 819 // pass on double click as two clicks.
820 if (!mouse_marks && !(ev->state() & ShiftButton)) 820 if (!mouse_marks && !(ev->state() & ShiftButton))
821 { 821 {
822 emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button 822 emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button
823 emit mouseSignal( 3, pos.x()+1, pos.y()+1 ); // release 823 emit mouseSignal( 3, pos.x()+1, pos.y()+1 ); // release
824 emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button 824 emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button
825 return; 825 return;
826 } 826 }
827 827
828 828
829 emit clearSelectionSignal(); 829 emit clearSelectionSignal();
830 QPoint bgnSel = pos; 830 QPoint bgnSel = pos;
831 QPoint endSel = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); 831 QPoint endSel = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h);
832 int i = loc(bgnSel.x(),bgnSel.y()); 832 int i = loc(bgnSel.x(),bgnSel.y());
833 iPntSel = bgnSel; 833 iPntSel = bgnSel;
834 834
835 word_selection_mode = TRUE; 835 word_selection_mode = TRUE;
836 836
837 // find word boundaries... 837 // find word boundaries...
838 int selClass = charClass(image[i].c); 838 int selClass = charClass(image[i].c);
839 { 839 {
840 // set the start... 840 // set the start...
841 int x = bgnSel.x(); 841 int x = bgnSel.x();
842 while ( x > 0 && charClass(image[i-1].c) == selClass ) 842 while ( x > 0 && charClass(image[i-1].c) == selClass )
843 { i--; x--; } 843 { i--; x--; }
844 bgnSel.setX(x); 844 bgnSel.setX(x);
845 emit beginSelectionSignal( bgnSel.x(), bgnSel.y() ); 845 emit beginSelectionSignal( bgnSel.x(), bgnSel.y() );
846 846
847 // set the end... 847 // set the end...
848 i = loc( endSel.x(), endSel.y() ); 848 i = loc( endSel.x(), endSel.y() );
849 x = endSel.x(); 849 x = endSel.x();
850 while( x < columns-1 && charClass(image[i+1].c) == selClass ) 850 while( x < columns-1 && charClass(image[i+1].c) == selClass )
851 { i++; x++ ; } 851 { i++; x++ ; }
852 endSel.setX(x); 852 endSel.setX(x);
853 actSel = 2; // within selection 853 actSel = 2; // within selection
854 emit extendSelectionSignal( endSel.x(), endSel.y() ); 854 emit extendSelectionSignal( endSel.x(), endSel.y() );
855 emit endSelectionSignal(preserve_line_breaks); 855 emit endSelectionSignal(preserve_line_breaks);
856 preserve_line_breaks = TRUE; 856 preserve_line_breaks = TRUE;
857 } 857 }
858} 858}
859 859
860void Widget::focusInEvent( QFocusEvent * ) 860void Widget::focusInEvent( QFocusEvent * )
861{ 861{
862 862
863 // do nothing, to prevent repainting 863 // do nothing, to prevent repainting
864} 864}
865 865
866 866
867void Widget::focusOutEvent( QFocusEvent * ) 867void Widget::focusOutEvent( QFocusEvent * )
868{ 868{
869 // do nothing, to prevent repainting 869 // do nothing, to prevent repainting
870} 870}
871 871
872bool Widget::focusNextPrevChild( bool next ) 872bool Widget::focusNextPrevChild( bool next )
873{ 873{
874 if (next) 874 if (next)
875 return false; // This disables changing the active part in konqueror 875 return false; // This disables changing the active part in konqueror
876 // when pressing Tab 876 // when pressing Tab
877 return QFrame::focusNextPrevChild( next ); 877 return QFrame::focusNextPrevChild( next );
878} 878}
879 879
880 880
881int Widget::charClass(char ch) const 881int Widget::charClass(char ch) const
882{ 882{
883 // This might seem like overkill, but imagine if ch was a Unicode 883 // This might seem like overkill, but imagine if ch was a Unicode
884 // character (Qt 2.0 QChar) - it might then be sensible to separate 884 // character (Qt 2.0 QChar) - it might then be sensible to separate
885 // the different language ranges, etc. 885 // the different language ranges, etc.
886 886
887 if ( isspace(ch) ) return ' '; 887 if ( isspace(ch) ) return ' ';
888 888
889 static const char *word_characters = ":@-./_~"; 889 static const char *word_characters = ":@-./_~";
890 if ( isalnum(ch) || strchr(word_characters, ch) ) 890 if ( isalnum(ch) || strchr(word_characters, ch) )
891 return 'a'; 891 return 'a';
892 892
893 // Everything else is weird 893 // Everything else is weird
894 return 1; 894 return 1;
895} 895}
896 896
897void Widget::setMouseMarks(bool on) 897void Widget::setMouseMarks(bool on)
898{ 898{
899 mouse_marks = on; 899 mouse_marks = on;
900 setCursor( mouse_marks ? ibeamCursor : arrowCursor ); 900 setCursor( mouse_marks ? ibeamCursor : arrowCursor );
901} 901}
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;
1138 bY = (contentsRect().height() - (lines *font_h)) / 2; 1138 bY = (contentsRect().height() - (lines *font_h)) / 2;
1139} 1139}
1140 1140
1141void Widget::makeImage() 1141void Widget::makeImage()
1142//FIXME: rename 'calcGeometry? 1142//FIXME: rename 'calcGeometry?
1143{ 1143{
1144 calcGeometry(); 1144 calcGeometry();
1145 image = (Character*) malloc(lines*columns*sizeof(Character)); 1145 image = (Character*) malloc(lines*columns*sizeof(Character));
1146 clearImage(); 1146 clearImage();
1147} 1147}
1148 1148
1149// calculate the needed size 1149// calculate the needed size
1150QSize Widget::calcSize(int cols, int lins) const 1150QSize Widget::calcSize(int cols, int lins) const
1151{ 1151{
1152 int frw = width() - contentsRect().width(); 1152 int frw = width() - contentsRect().width();
1153 int frh = height() - contentsRect().height(); 1153 int frh = height() - contentsRect().height();
1154 int scw = (scrollLoc==SCRNONE?0:scrollbar->width()); 1154 int scw = (scrollLoc==SCRNONE?0:scrollbar->width());
1155 return QSize( font_w*cols + 2*rimX + frw + scw, font_h*lins + 2*rimY + frh ); 1155 return QSize( font_w*cols + 2*rimX + frw + scw, font_h*lins + 2*rimY + frh );
1156} 1156}
1157 1157
1158QSize Widget::sizeHint() const 1158QSize Widget::sizeHint() const
1159{ 1159{
1160 return size(); 1160 return size();
1161} 1161}
1162 1162
1163void Widget::styleChange(QStyle &) 1163void Widget::styleChange(QStyle &)
1164{ 1164{
1165 propagateSize(); 1165 propagateSize();
1166} 1166}
1167 1167
1168#ifndef QT_NO_DRAGANDDROP 1168#ifndef QT_NO_DRAGANDDROP
1169 1169
1170/* --------------------------------------------------------------------- */ 1170/* --------------------------------------------------------------------- */
1171/* */ 1171/* */
1172/* Drag & Drop */ 1172/* Drag & Drop */
1173/* */ 1173/* */
1174/* --------------------------------------------------------------------- */ 1174/* --------------------------------------------------------------------- */
1175 1175
1176 1176
1177void Widget::dragEnterEvent(QDragEnterEvent* e) 1177void Widget::dragEnterEvent(QDragEnterEvent* e)
1178{ 1178{
1179 e->accept(QTextDrag::canDecode(e) || 1179 e->accept(QTextDrag::canDecode(e) ||
1180 QUriDrag::canDecode(e)); 1180 QUriDrag::canDecode(e));
1181} 1181}
1182 1182
1183void Widget::dropEvent(QDropEvent* event) 1183void Widget::dropEvent(QDropEvent* event)
1184{ 1184{
1185 // The current behaviour when url(s) are dropped is 1185 // The current behaviour when url(s) are dropped is
1186 // * if there is only ONE url and if it's a LOCAL one, ask for paste or cd 1186 // * if there is only ONE url and if it's a LOCAL one, ask for paste or cd
1187 // * in all other cases, just paste 1187 // * in all other cases, just paste
1188 // (for non-local ones, or for a list of URLs, 'cd' is nonsense) 1188 // (for non-local ones, or for a list of URLs, 'cd' is nonsense)
1189 QStrList strlist; 1189 QStrList strlist;
1190 int file_count = 0; 1190 int file_count = 0;
1191 dropText = ""; 1191 dropText = "";
1192 bool bPopup = true; 1192 bool bPopup = true;
1193 1193
1194 if(QUriDrag::decode(event, strlist)) { 1194 if(QUriDrag::decode(event, strlist)) {
1195 if (strlist.count()) { 1195 if (strlist.count()) {
1196 for(const char* p = strlist.first(); p; p = strlist.next()) { 1196 for(const char* p = strlist.first(); p; p = strlist.next()) {
1197 if(file_count++ > 0) { 1197 if(file_count++ > 0) {
1198 dropText += " "; 1198 dropText += " ";
1199 bPopup = false; // more than one file, don't popup 1199 bPopup = false; // more than one file, don't popup
1200 } 1200 }
1201 1201
1202/* 1202/*
1203 KURL url(p); 1203 KURL url(p);
1204 if (url.isLocalFile()) { 1204 if (url.isLocalFile()) {
1205 dropText += url.path(); // local URL : remove protocol 1205 dropText += url.path(); // local URL : remove protocol
1206 } 1206 }
1207 else { 1207 else {
1208 dropText += url.prettyURL(); 1208 dropText += url.prettyURL();
1209 bPopup = false; // a non-local file, don't popup 1209 bPopup = false; // a non-local file, don't popup
1210 } 1210 }
1211*/ 1211*/
1212 1212
1213 } 1213 }
1214 1214
1215 if (bPopup) 1215 if (bPopup)
1216 // m_drop->popup(pos() + event->pos()); 1216 // m_drop->popup(pos() + event->pos());
1217 m_drop->popup(mapToGlobal(event->pos())); 1217 m_drop->popup(mapToGlobal(event->pos()));
1218 else 1218 else
1219 { 1219 {
1220 if (currentSession) { 1220 if (currentSession) {
1221 //currentSession->getEmulation()->sendString(dropText.local8Bit()); 1221 //currentSession->getEmulation()->sendString(dropText.local8Bit());
1222 QByteArray tmp; 1222 QByteArray tmp;
1223 // ibot: this should be pretty wrong... 1223 // ibot: this should be pretty wrong...
1224 // now it sends to the right layer 1224 // now it sends to the right layer
1225 currentSession-> emulationLayer()->send( tmp.setRawData( dropText.local8Bit())); 1225 currentSession-> emulationLayer()->send( tmp.setRawData( dropText.local8Bit()));
1226 } 1226 }
1227 // kdDebug() << "Drop:" << dropText.local8Bit() << "\n"; 1227 // kdDebug() << "Drop:" << dropText.local8Bit() << "\n";
1228 } 1228 }
1229 } 1229 }
1230 } 1230 }
1231 else if(QTextDrag::decode(event, dropText)) { 1231 else if(QTextDrag::decode(event, dropText)) {
1232// kdDebug() << "Drop:" << dropText.local8Bit() << "\n"; 1232// kdDebug() << "Drop:" << dropText.local8Bit() << "\n";
1233 if (currentSession) { 1233 if (currentSession) {
1234 //currentSession->getEmulation()->sendString(dropText.local8Bit()); 1234 //currentSession->getEmulation()->sendString(dropText.local8Bit());
1235 QByteArray tmp; 1235 QByteArray tmp;
1236 currentSession->emulationLayer()->send( tmp.setRawData( dropText.local8Bit())); 1236 currentSession->emulationLayer()->send( tmp.setRawData( dropText.local8Bit()));
1237 } 1237 }
1238 // Paste it 1238 // Paste it
1239 } 1239 }
1240} 1240}
1241#endif 1241#endif
1242 1242
1243 1243
1244void Widget::drop_menu_activated(int item) 1244void Widget::drop_menu_activated(int item)
1245{ 1245{
1246#ifndef QT_NO_DRAGANDDROP 1246#ifndef QT_NO_DRAGANDDROP
1247 QByteArray tmp; 1247 QByteArray tmp;
1248 switch (item) 1248 switch (item)
1249 { 1249 {
1250 case 0: // paste 1250 case 0: // paste
1251 //currentSession->getEmulation()->sendString(dropText.local8Bit()); 1251 //currentSession->getEmulation()->sendString(dropText.local8Bit());
1252 currentSession->emulationLayer()->send( tmp.setRawData( dropText.local8Bit())); 1252 currentSession->emulationLayer()->send( tmp.setRawData( dropText.local8Bit()));
1253 1253
1254// KWM::activate((Window)this->winId()); 1254// KWM::activate((Window)this->winId());
1255 break; 1255 break;
1256 case 1: // cd ... 1256 case 1: // cd ...
1257 //currentSession->getEmulation()->sendString("cd "); 1257 //currentSession->getEmulation()->sendString("cd ");
1258 tmp.setRawData( "cd " ); 1258 tmp.setRawData( "cd " );
1259 currentSession->emulationLayer()->send( tmp ); 1259 currentSession->emulationLayer()->send( tmp );
1260 struct stat statbuf; 1260 struct stat statbuf;
1261 if ( ::stat( QFile::encodeName( dropText ), &statbuf ) == 0 ) 1261 if ( ::stat( QFile::encodeName( dropText ), &statbuf ) == 0 )
1262 { 1262 {
1263 if ( !S_ISDIR(statbuf.st_mode) ) 1263 if ( !S_ISDIR(statbuf.st_mode) )
1264 { 1264 {
1265/* 1265/*
1266 KURL url; 1266 KURL url;
1267 url.setPath( dropText ); 1267 url.setPath( dropText );
1268 dropText = url.directory( true, false ); // remove filename 1268 dropText = url.directory( true, false ); // remove filename
1269*/ 1269*/
1270 } 1270 }
1271 } 1271 }
1272 dropText.replace(QRegExp(" "), "\\ "); // escape spaces 1272 dropText.replace(QRegExp(" "), "\\ "); // escape spaces
1273 QByteArray tmp2; 1273 QByteArray tmp2;
1274 tmp.setRawDate( dropText.local8Bit() + "\n" ); 1274 tmp.setRawDate( dropText.local8Bit() + "\n" );
1275 //currentSession->getEmulation()->sendString(dropText.local8Bit()); 1275 //currentSession->getEmulation()->sendString(dropText.local8Bit());
1276 //currentSession->getEmulation()->sendString("\n"); 1276 //currentSession->getEmulation()->sendString("\n");
1277 currentSession->emulationLayer()->send( tmp ); 1277 currentSession->emulationLayer()->send( tmp );
1278// KWM::activate((Window)this->winId()); 1278// KWM::activate((Window)this->winId());
1279 break; 1279 break;
1280 } 1280 }
1281#endif 1281#endif
1282} 1282}
1283 1283
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,245 +1,245 @@
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()
215{ 215{
216 emit selectionCleared(); 216 emit selectionCleared();
217} 217}
218 218
219void WidgetLayer::setSelection( const QString& text ) 219void WidgetLayer::setSelection( const QString& text )
220{ 220{
221 // why get the clipboard, we have it as instance var... 221 // why get the clipboard, we have it as instance var...
222 QObject *m_clipboard = QApplication::clipboard(); 222 QObject *m_clipboard = QApplication::clipboard();
223 223
224 // we know, that cliboard changes, when we change clipboard 224 // we know, that cliboard changes, when we change clipboard
225 QObject::disconnect( (QObject*) m_clipboard, SIGNAL( dataChanged() ), 225 QObject::disconnect( (QObject*) m_clipboard, SIGNAL( dataChanged() ),
226 (QObject*) this, SLOT( selectionCleared() ) ); 226 (QObject*) this, SLOT( selectionCleared() ) );
227 227
228 QApplication::clipboard()->setText( text ); 228 QApplication::clipboard()->setText( text );
229 229
230 QObject::connect( (QObject*) m_clipboard, SIGNAL( dataChanged() ), 230 QObject::connect( (QObject*) m_clipboard, SIGNAL( dataChanged() ),
231 (QObject*) this, SLOT( selectionCleared() ) ); 231 (QObject*) this, SLOT( selectionCleared() ) );
232} 232}
233 233
234 234
235///////// 235/////////
236// special font characters 236// special font characters
237///////// 237/////////
238unsigned short vt100_graphics[32] = 238unsigned short vt100_graphics[32] =
239{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 239{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15
240 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 240 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0,
241 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 241 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c,
242 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, 242 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534,
243 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 243 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7
244}; 244};
245 245
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,574 +1,578 @@
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()),
125 this, SLOT(showEditTools()) ); 129 this, SLOT(showEditTools()) );
126 QObject::connect( fileSelector, SIGNAL(fileSelected(const DocLnk&)), 130 QObject::connect( fileSelector, SIGNAL(fileSelected(const DocLnk&)),
127 this, SLOT(openFile(const DocLnk&)) ); 131 this, SLOT(openFile(const DocLnk&)) );
128 QObject::connect( fileSelector, SIGNAL(newSelected(const DocLnk&)), 132 QObject::connect( fileSelector, SIGNAL(newSelected(const DocLnk&)),
129 this, SLOT(newFile(const DocLnk&)) ); 133 this, SLOT(newFile(const DocLnk&)) );
130 134
131 if ( fileSelector->fileCount() < 1 ) 135 if ( fileSelector->fileCount() < 1 )
132 fileNew(); 136 fileNew();
133 else { 137 else {
134 fileOpen(); 138 fileOpen();
135 } 139 }
136 doConnections( editor ); 140 doConnections( editor );
137 141
138 setCentralWidget( editorStack ); 142 setCentralWidget( editorStack );
139} 143}
140 144
141MainWindow::~MainWindow() 145MainWindow::~MainWindow()
142{ 146{
143 save(); 147 save();
144} 148}
145 149
146void MainWindow::setupActions() 150void MainWindow::setupActions()
147{ 151{
148 setToolBarsMovable(false); 152 setToolBarsMovable(false);
149 153
150 tbMenu = new QToolBar( this ); 154 tbMenu = new QToolBar( this );
151 tbMenu->setHorizontalStretchable( TRUE ); 155 tbMenu->setHorizontalStretchable( TRUE );
152 156
153 QMenuBar *menu = new QMenuBar( tbMenu ); 157 QMenuBar *menu = new QMenuBar( tbMenu );
154 158
155 tbEdit = new QToolBar( this ); 159 tbEdit = new QToolBar( this );
156 160
157 QPopupMenu *file = new QPopupMenu( this ); 161 QPopupMenu *file = new QPopupMenu( this );
158 menu->insertItem( tr("File"), file ); 162 menu->insertItem( tr("File"), file );
159 163
160 QPopupMenu *edit = new QPopupMenu( this ); 164 QPopupMenu *edit = new QPopupMenu( this );
161 menu->insertItem( tr("Edit"), edit ); 165 menu->insertItem( tr("Edit"), edit );
162 166
163 // ### perhaps these shortcut keys should have some 167 // ### perhaps these shortcut keys should have some
164 // IPaq keys defined??? 168 // IPaq keys defined???
165 QAction *a; 169 QAction *a;
166 170
167 a = new QAction( tr( "New" ), Resource::loadPixmap("new"), QString::null, 0, this, 0 ); 171 a = new QAction( tr( "New" ), Resource::loadPixmap("new"), QString::null, 0, this, 0 );
168 connect( a, SIGNAL(activated()), this, SLOT(fileNew()) ); 172 connect( a, SIGNAL(activated()), this, SLOT(fileNew()) );
169 a->addTo( file ); 173 a->addTo( file );
170 174
171 a = new QAction( tr( "Open" ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 ); 175 a = new QAction( tr( "Open" ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 );
172 connect( a, SIGNAL(activated()), this, SLOT(fileOpen()) ); 176 connect( a, SIGNAL(activated()), this, SLOT(fileOpen()) );
173 a->addTo( file ); 177 a->addTo( file );
174 178
175 a = new QAction( tr( "Undo" ), Resource::loadIconSet("undo"), 179 a = new QAction( tr( "Undo" ), Resource::loadIconSet("undo"),
176 QString::null, 0, this, "editUndo" ); 180 QString::null, 0, this, "editUndo" );
177 connect( a, SIGNAL( activated() ), this, SLOT( editUndo() ) ); 181 connect( a, SIGNAL( activated() ), this, SLOT( editUndo() ) );
178 connect( editor, SIGNAL(undoAvailable(bool)), a, SLOT(setEnabled(bool)) ); 182 connect( editor, SIGNAL(undoAvailable(bool)), a, SLOT(setEnabled(bool)) );
179 a->addTo( tbEdit ); 183 a->addTo( tbEdit );
180 a->addTo( edit ); 184 a->addTo( edit );
181 a = new QAction( tr( "Redo" ), Resource::loadIconSet("redo"), 185 a = new QAction( tr( "Redo" ), Resource::loadIconSet("redo"),
182 QString::null, 0, this, "editRedo" ); 186 QString::null, 0, this, "editRedo" );
183 connect( a, SIGNAL( activated() ), this, SLOT( editRedo() ) ); 187 connect( a, SIGNAL( activated() ), this, SLOT( editRedo() ) );
184 connect( editor, SIGNAL(redoAvailable(bool)), a, SLOT(setEnabled(bool)) ); 188 connect( editor, SIGNAL(redoAvailable(bool)), a, SLOT(setEnabled(bool)) );
185 a->addTo( tbEdit ); 189 a->addTo( tbEdit );
186 a->addTo( edit ); 190 a->addTo( edit );
187 191
188 edit->insertSeparator(); 192 edit->insertSeparator();
189 193
190 a = new QAction( tr( "Copy" ), Resource::loadIconSet("copy"), 194 a = new QAction( tr( "Copy" ), Resource::loadIconSet("copy"),
191 QString::null, 0, this, "editCopy" ); 195 QString::null, 0, this, "editCopy" );
192 connect( a, SIGNAL( activated() ), this, SLOT( editCopy() ) ); 196 connect( a, SIGNAL( activated() ), this, SLOT( editCopy() ) );
193 connect( editor, SIGNAL(copyAvailable(bool)), a, SLOT(setEnabled(bool)) ); 197 connect( editor, SIGNAL(copyAvailable(bool)), a, SLOT(setEnabled(bool)) );
194 a->addTo( tbEdit ); 198 a->addTo( tbEdit );
195 a->addTo( edit ); 199 a->addTo( edit );
196 a = new QAction( tr( "Cut" ), Resource::loadIconSet("cut"), 200 a = new QAction( tr( "Cut" ), Resource::loadIconSet("cut"),
197 QString::null, 0, this, "editCut" ); 201 QString::null, 0, this, "editCut" );
198 connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) ); 202 connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) );
199 connect( editor, SIGNAL(copyAvailable(bool)), a, SLOT(setEnabled(bool)) ); 203 connect( editor, SIGNAL(copyAvailable(bool)), a, SLOT(setEnabled(bool)) );
200 a->addTo( tbEdit ); 204 a->addTo( tbEdit );
201 a->addTo( edit ); 205 a->addTo( edit );
202 a = new QAction( tr( "Paste" ), Resource::loadPixmap("paste"), 206 a = new QAction( tr( "Paste" ), Resource::loadPixmap("paste"),
203 QString::null, 0, this, "editPaste" ); 207 QString::null, 0, this, "editPaste" );
204 connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) ); 208 connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) );
205 a->addTo( tbEdit ); 209 a->addTo( tbEdit );
206 a->addTo( edit ); 210 a->addTo( edit );
207 211
208 tbFont = new QToolBar( this ); 212 tbFont = new QToolBar( this );
209 tbFont->setLabel( "Font Actions" ); 213 tbFont->setLabel( "Font Actions" );
210 tbFont->setHorizontalStretchable(TRUE); 214 tbFont->setHorizontalStretchable(TRUE);
211 215
212 comboFont = new QComboBox( FALSE, tbFont ); 216 comboFont = new QComboBox( FALSE, tbFont );
213 FontDatabase db; 217 FontDatabase db;
214 QStringList f= db.families(); 218 QStringList f= db.families();
215 comboFont->insertStringList( db.families() ); 219 comboFont->insertStringList( db.families() );
216 connect( comboFont, SIGNAL( activated(const QString&) ), 220 connect( comboFont, SIGNAL( activated(const QString&) ),
217 this, SLOT( textFamily(const QString&) ) ); 221 this, SLOT( textFamily(const QString&) ) );
218 comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( QApplication::font().family() ) ) ); 222 comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( QApplication::font().family() ) ) );
219 comboFont->setMaximumWidth(90); 223 comboFont->setMaximumWidth(90);
220 224
221 comboSize = new QComboBox( TRUE, tbFont ); 225 comboSize = new QComboBox( TRUE, tbFont );
222 QValueList<int> sizes = db.standardSizes(); 226 QValueList<int> sizes = db.standardSizes();
223 QValueList<int>::Iterator it = sizes.begin(); 227 QValueList<int>::Iterator it = sizes.begin();
224 for ( ; it != sizes.end(); ++it ) 228 for ( ; it != sizes.end(); ++it )
225 comboSize->insertItem( QString::number( *it ) ); 229 comboSize->insertItem( QString::number( *it ) );
226 connect( comboSize, SIGNAL( activated(const QString&) ), 230 connect( comboSize, SIGNAL( activated(const QString&) ),
227 this, SLOT( textSize(const QString&) ) ); 231 this, SLOT( textSize(const QString&) ) );
228 comboSize->lineEdit()->setText( QString::number( QApplication::font().pointSize() ) ); 232 comboSize->lineEdit()->setText( QString::number( QApplication::font().pointSize() ) );
229 comboSize->setFixedWidth( 38 ); 233 comboSize->setFixedWidth( 38 );
230 234
231 tbStyle = new QToolBar( this ); 235 tbStyle = new QToolBar( this );
232 tbStyle->setLabel( "Style Actions" ); 236 tbStyle->setLabel( "Style Actions" );
233 237
234 actionTextBold = new QAction( tr( "Bold" ), 238 actionTextBold = new QAction( tr( "Bold" ),
235 Resource::loadPixmap("bold"), 239 Resource::loadPixmap("bold"),
236 QString::null, CTRL + Key_B, 240 QString::null, CTRL + Key_B,
237 this, "textBold" ); 241 this, "textBold" );
238 connect( actionTextBold, SIGNAL( activated() ), this, SLOT( textBold() ) ); 242 connect( actionTextBold, SIGNAL( activated() ), this, SLOT( textBold() ) );
239 actionTextBold->addTo( tbStyle ); 243 actionTextBold->addTo( tbStyle );
240 actionTextBold->setToggleAction( TRUE ); 244 actionTextBold->setToggleAction( TRUE );
241 actionTextItalic = new QAction( tr( "Italic" ), 245 actionTextItalic = new QAction( tr( "Italic" ),
242 Resource::loadPixmap("italic"), 246 Resource::loadPixmap("italic"),
243 tr( "&Italic" ), CTRL + Key_I, 247 tr( "&Italic" ), CTRL + Key_I,
244 this, "textItalic" ); 248 this, "textItalic" );
245 connect( actionTextItalic, SIGNAL( activated() ), this, 249 connect( actionTextItalic, SIGNAL( activated() ), this,
246 SLOT( textItalic() ) ); 250 SLOT( textItalic() ) );
247 actionTextItalic->addTo( tbStyle ); 251 actionTextItalic->addTo( tbStyle );
248 actionTextItalic->setToggleAction( TRUE ); 252 actionTextItalic->setToggleAction( TRUE );
249 actionTextUnderline = new QAction( tr( "Underline" ), 253 actionTextUnderline = new QAction( tr( "Underline" ),
250 Resource::loadPixmap("underline"), 254 Resource::loadPixmap("underline"),
251 tr( "&Underline" ), CTRL + Key_U, 255 tr( "&Underline" ), CTRL + Key_U,
252 this, "textUnderline" ); 256 this, "textUnderline" );
253 connect( actionTextUnderline, SIGNAL( activated() ), 257 connect( actionTextUnderline, SIGNAL( activated() ),
254 this, SLOT( textUnderline() ) ); 258 this, SLOT( textUnderline() ) );
255 actionTextUnderline->addTo( tbStyle ); 259 actionTextUnderline->addTo( tbStyle );
256 actionTextUnderline->setToggleAction( TRUE ); 260 actionTextUnderline->setToggleAction( TRUE );
257 261
258 alignMenu = new ButtonMenu( tbStyle ); 262 alignMenu = new ButtonMenu( tbStyle );
259 alignMenu->insertItem( Resource::loadPixmap("left"), tr("Left"), AlignLeft ); 263 alignMenu->insertItem( Resource::loadPixmap("left"), tr("Left"), AlignLeft );
260 alignMenu->insertItem( Resource::loadPixmap("center"), tr("Center"), AlignCenter ); 264 alignMenu->insertItem( Resource::loadPixmap("center"), tr("Center"), AlignCenter );
261 alignMenu->insertItem( Resource::loadPixmap("right"), tr("Right"), AlignRight ); 265 alignMenu->insertItem( Resource::loadPixmap("right"), tr("Right"), AlignRight );
262 alignMenu->insertItem( Resource::loadPixmap("opie-write/justify"), tr("Full"), Qt3::AlignJustify ); 266 alignMenu->insertItem( Resource::loadPixmap("opie-write/justify"), tr("Full"), Qt3::AlignJustify );
263 connect( alignMenu, SIGNAL(activated(int)), this, SLOT(textAlign(int)) ); 267 connect( alignMenu, SIGNAL(activated(int)), this, SLOT(textAlign(int)) );
264} 268}
265 269
266Qt3::QTextEdit *MainWindow::currentEditor() const 270Qt3::QTextEdit *MainWindow::currentEditor() const
267{ 271{
268 return editor; 272 return editor;
269} 273}
270 274
271void MainWindow::doConnections( Qt3::QTextEdit *e ) 275void MainWindow::doConnections( Qt3::QTextEdit *e )
272{ 276{
273 connect( e, SIGNAL( currentFontChanged(const QFont&) ), 277 connect( e, SIGNAL( currentFontChanged(const QFont&) ),
274 this, SLOT( fontChanged(const QFont&) ) ); 278 this, SLOT( fontChanged(const QFont&) ) );
275 connect( e, SIGNAL( currentColorChanged(const QColor&) ), 279 connect( e, SIGNAL( currentColorChanged(const QColor&) ),
276 this, SLOT( colorChanged(const QColor&) ) ); 280 this, SLOT( colorChanged(const QColor&) ) );
277 connect( e, SIGNAL( currentAlignmentChanged(int) ), 281 connect( e, SIGNAL( currentAlignmentChanged(int) ),
278 this, SLOT( alignmentChanged(int) ) ); 282 this, SLOT( alignmentChanged(int) ) );
279} 283}
280 284
281void MainWindow::updateFontSizeCombo( const QFont &f ) 285void MainWindow::updateFontSizeCombo( const QFont &f )
282{ 286{
283 comboSize->clear(); 287 comboSize->clear();
284 FontDatabase fdb; 288 FontDatabase fdb;
285 QValueList<int> sizes = fdb.pointSizes( f.family() ); 289 QValueList<int> sizes = fdb.pointSizes( f.family() );
286 QValueList<int>::Iterator it = sizes.begin(); 290 QValueList<int>::Iterator it = sizes.begin();
287 for ( ; it != sizes.end(); ++it ) 291 for ( ; it != sizes.end(); ++it )
288 comboSize->insertItem( QString::number( *it ) ); 292 comboSize->insertItem( QString::number( *it ) );
289} 293}
290 294
291void MainWindow::editUndo() 295void MainWindow::editUndo()
292{ 296{
293 if ( !currentEditor() ) 297 if ( !currentEditor() )
294 return; 298 return;
295 currentEditor()->undo(); 299 currentEditor()->undo();
296} 300}
297 301
298void MainWindow::editRedo() 302void MainWindow::editRedo()
299{ 303{
300 if ( !currentEditor() ) 304 if ( !currentEditor() )
301 return; 305 return;
302 currentEditor()->redo(); 306 currentEditor()->redo();
303} 307}
304 308
305void MainWindow::editCut() 309void MainWindow::editCut()
306{ 310{
307 if ( !currentEditor() ) 311 if ( !currentEditor() )
308 return; 312 return;
309 currentEditor()->cut(); 313 currentEditor()->cut();
310} 314}
311 315
312void MainWindow::editCopy() 316void MainWindow::editCopy()
313{ 317{
314 if ( !currentEditor() ) 318 if ( !currentEditor() )
315 return; 319 return;
316 currentEditor()->copy(); 320 currentEditor()->copy();
317} 321}
318 322
319void MainWindow::editPaste() 323void MainWindow::editPaste()
320{ 324{
321 if ( !currentEditor() ) 325 if ( !currentEditor() )
322 return; 326 return;
323 currentEditor()->paste(); 327 currentEditor()->paste();
324} 328}
325 329
326void MainWindow::textBold() 330void MainWindow::textBold()
327{ 331{
328 if ( !currentEditor() ) 332 if ( !currentEditor() )
329 return; 333 return;
330 currentEditor()->setBold( actionTextBold->isOn() ); 334 currentEditor()->setBold( actionTextBold->isOn() );
331} 335}
332 336
333void MainWindow::textUnderline() 337void MainWindow::textUnderline()
334{ 338{
335 if ( !currentEditor() ) 339 if ( !currentEditor() )
336 return; 340 return;
337 currentEditor()->setUnderline( actionTextUnderline->isOn() ); 341 currentEditor()->setUnderline( actionTextUnderline->isOn() );
338} 342}
339 343
340void MainWindow::textItalic() 344void MainWindow::textItalic()
341{ 345{
342 if ( !currentEditor() ) 346 if ( !currentEditor() )
343 return; 347 return;
344 currentEditor()->setItalic( actionTextItalic->isOn() ); 348 currentEditor()->setItalic( actionTextItalic->isOn() );
345} 349}
346 350
347void MainWindow::textFamily( const QString &f ) 351void MainWindow::textFamily( const QString &f )
348{ 352{
349 if ( !currentEditor() ) 353 if ( !currentEditor() )
350 return; 354 return;
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
@@ -1,146 +1,146 @@
1/**************************************************************************** 1/****************************************************************************
2** $Id$ 2** $Id$
3** 3**
4** Implementation of some internal classes 4** Implementation of some internal classes
5** 5**
6** Created : 6** Created :
7** 7**
8** Copyright (C) 2001 Trolltech AS. All rights reserved. 8** Copyright (C) 2001 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 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,7829 +1,7835 @@
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() );
312 if ( sp == ep ) 318 if ( sp == ep )
313 break; 319 break;
314 sp = sp->next(); 320 sp = sp->next();
315 idx = 0; 321 idx = 0;
316 } 322 }
317 fIndex++; 323 fIndex++;
318 } 324 }
319 if ( oldFormats.at( fIndex ).format() ) 325 if ( oldFormats.at( fIndex ).format() )
320 sp->setFormat( idx, 1, oldFormats.at( fIndex ).format() ); 326 sp->setFormat( idx, 1, oldFormats.at( fIndex ).format() );
321 idx++; 327 idx++;
322 fIndex++; 328 fIndex++;
323 if ( fIndex >= (int)oldFormats.size() ) 329 if ( fIndex >= (int)oldFormats.size() )
324 break; 330 break;
325 if ( idx >= sp->length() ) { 331 if ( idx >= sp->length() ) {
326 if ( sp == ep ) 332 if ( sp == ep )
327 break; 333 break;
328 sp = sp->next(); 334 sp = sp->next();
329 idx = 0; 335 idx = 0;
330 } 336 }
331 } 337 }
332 338
333 QTextCursor end( doc ); 339 QTextCursor end( doc );
334 end.setParagraph( ep ); 340 end.setParagraph( ep );
335 end.setIndex( endIndex ); 341 end.setIndex( endIndex );
336 if ( endIndex == ep->length() ) 342 if ( endIndex == ep->length() )
337 end.gotoLeft(); 343 end.gotoLeft();
338 *c = end; 344 *c = end;
339 return c; 345 return c;
340} 346}
341 347
342QTextStyleCommand::QTextStyleCommand( QTextDocument *d, int fParag, int lParag, const QByteArray& beforeChange ) 348QTextStyleCommand::QTextStyleCommand( QTextDocument *d, int fParag, int lParag, const QByteArray& beforeChange )
343 : QTextCommand( d ), firstParag( fParag ), lastParag( lParag ), before( beforeChange ) 349 : QTextCommand( d ), firstParag( fParag ), lastParag( lParag ), before( beforeChange )
344{ 350{
345 after = readStyleInformation( d, fParag, lParag ); 351 after = readStyleInformation( d, fParag, lParag );
346} 352}
347 353
348 354
349QByteArray QTextStyleCommand::readStyleInformation( QTextDocument* doc, int fParag, int lParag ) 355QByteArray QTextStyleCommand::readStyleInformation( QTextDocument* doc, int fParag, int lParag )
350{ 356{
351 QByteArray style; 357 QByteArray style;
352 QTextParagraph *p = doc->paragAt( fParag ); 358 QTextParagraph *p = doc->paragAt( fParag );
353 if ( !p ) 359 if ( !p )
354 return style; 360 return style;
355 QDataStream styleStream( style, IO_WriteOnly ); 361 QDataStream styleStream( style, IO_WriteOnly );
356 int num = lParag - fParag + 1; 362 int num = lParag - fParag + 1;
357 styleStream << num; 363 styleStream << num;
358 while ( num -- && p ) { 364 while ( num -- && p ) {
359 p->writeStyleInformation( styleStream ); 365 p->writeStyleInformation( styleStream );
360 p = p->next(); 366 p = p->next();
361 } 367 }
362 return style; 368 return style;
363} 369}
364 370
365void QTextStyleCommand::writeStyleInformation( QTextDocument* doc, int fParag, const QByteArray& style ) 371void QTextStyleCommand::writeStyleInformation( QTextDocument* doc, int fParag, const QByteArray& style )
366{ 372{
367 QTextParagraph *p = doc->paragAt( fParag ); 373 QTextParagraph *p = doc->paragAt( fParag );
368 if ( !p ) 374 if ( !p )
369 return; 375 return;
370 QDataStream styleStream( style, IO_ReadOnly ); 376 QDataStream styleStream( style, IO_ReadOnly );
371 int num; 377 int num;
372 styleStream >> num; 378 styleStream >> num;
373 while ( num-- && p ) { 379 while ( num-- && p ) {
374 p->readStyleInformation( styleStream ); 380 p->readStyleInformation( styleStream );
375 p = p->next(); 381 p = p->next();
376 } 382 }
377} 383}
378 384
379QTextCursor *QTextStyleCommand::execute( QTextCursor *c ) 385QTextCursor *QTextStyleCommand::execute( QTextCursor *c )
380{ 386{
381 writeStyleInformation( doc, firstParag, after ); 387 writeStyleInformation( doc, firstParag, after );
382 return c; 388 return c;
383} 389}
384 390
385QTextCursor *QTextStyleCommand::unexecute( QTextCursor *c ) 391QTextCursor *QTextStyleCommand::unexecute( QTextCursor *c )
386{ 392{
387 writeStyleInformation( doc, firstParag, before ); 393 writeStyleInformation( doc, firstParag, before );
388 return c; 394 return c;
389} 395}
390 396
391// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 397// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
392 398
393QTextCursor::QTextCursor( QTextDocument *d ) 399QTextCursor::QTextCursor( QTextDocument *d )
394 : idx( 0 ), tmpIndex( -1 ), ox( 0 ), oy( 0 ), 400 : idx( 0 ), tmpIndex( -1 ), ox( 0 ), oy( 0 ),
395 valid( TRUE ) 401 valid( TRUE )
396{ 402{
397 para = d ? d->firstParagraph() : 0; 403 para = d ? d->firstParagraph() : 0;
398} 404}
399 405
400QTextCursor::QTextCursor( const QTextCursor &c ) 406QTextCursor::QTextCursor( const QTextCursor &c )
401{ 407{
402 ox = c.ox; 408 ox = c.ox;
403 oy = c.oy; 409 oy = c.oy;
404 idx = c.idx; 410 idx = c.idx;
405 para = c.para; 411 para = c.para;
406 tmpIndex = c.tmpIndex; 412 tmpIndex = c.tmpIndex;
407 indices = c.indices; 413 indices = c.indices;
408 paras = c.paras; 414 paras = c.paras;
409 xOffsets = c.xOffsets; 415 xOffsets = c.xOffsets;
410 yOffsets = c.yOffsets; 416 yOffsets = c.yOffsets;
411 valid = c.valid; 417 valid = c.valid;
412} 418}
413 419
414QTextCursor &QTextCursor::operator=( const QTextCursor &c ) 420QTextCursor &QTextCursor::operator=( const QTextCursor &c )
415{ 421{
416 ox = c.ox; 422 ox = c.ox;
417 oy = c.oy; 423 oy = c.oy;
418 idx = c.idx; 424 idx = c.idx;
419 para = c.para; 425 para = c.para;
420 tmpIndex = c.tmpIndex; 426 tmpIndex = c.tmpIndex;
421 indices = c.indices; 427 indices = c.indices;
422 paras = c.paras; 428 paras = c.paras;
423 xOffsets = c.xOffsets; 429 xOffsets = c.xOffsets;
424 yOffsets = c.yOffsets; 430 yOffsets = c.yOffsets;
425 valid = c.valid; 431 valid = c.valid;
426 432
427 return *this; 433 return *this;
428} 434}
429 435
430bool QTextCursor::operator==( const QTextCursor &c ) const 436bool QTextCursor::operator==( const QTextCursor &c ) const
431{ 437{
432 return para == c.para && idx == c.idx; 438 return para == c.para && idx == c.idx;
433} 439}
434 440
435int QTextCursor::totalOffsetX() const 441int QTextCursor::totalOffsetX() const
436{ 442{
437 int xoff = ox; 443 int xoff = ox;
438 for ( QValueStack<int>::ConstIterator xit = xOffsets.begin(); xit != xOffsets.end(); ++xit ) 444 for ( QValueStack<int>::ConstIterator xit = xOffsets.begin(); xit != xOffsets.end(); ++xit )
439 xoff += *xit; 445 xoff += *xit;
440 return xoff; 446 return xoff;
441} 447}
442 448
443int QTextCursor::totalOffsetY() const 449int QTextCursor::totalOffsetY() const
444{ 450{
445 int yoff = oy; 451 int yoff = oy;
446 for ( QValueStack<int>::ConstIterator yit = yOffsets.begin(); yit != yOffsets.end(); ++yit ) 452 for ( QValueStack<int>::ConstIterator yit = yOffsets.begin(); yit != yOffsets.end(); ++yit )
447 yoff += *yit; 453 yoff += *yit;
448 return yoff; 454 return yoff;
449} 455}
450 456
451void QTextCursor::gotoIntoNested( const QPoint &globalPos ) 457void QTextCursor::gotoIntoNested( const QPoint &globalPos )
452{ 458{
453 if ( !para ) 459 if ( !para )
454 return; 460 return;
455 push(); 461 push();
456 ox = 0; 462 ox = 0;
457 int bl, y; 463 int bl, y;
458 para->lineHeightOfChar( idx, &bl, &y ); 464 para->lineHeightOfChar( idx, &bl, &y );
459 oy = y + para->rect().y(); 465 oy = y + para->rect().y();
460 QPoint p( globalPos.x() - offsetX(), globalPos.y() - offsetY() ); 466 QPoint p( globalPos.x() - offsetX(), globalPos.y() - offsetY() );
461 Q_ASSERT( para->at( idx )->isCustom() ); 467 Q_ASSERT( para->at( idx )->isCustom() );
462 ox = para->at( idx )->x; 468 ox = para->at( idx )->x;
463 469
464 QTextDocument* doc = document(); 470 QTextDocument* doc = document();
465 para->at( idx )->customItem()->enterAt( this, doc, para, idx, ox, oy, p ); 471 para->at( idx )->customItem()->enterAt( this, doc, para, idx, ox, oy, p );
466} 472}
467 473
468void QTextCursor::invalidateNested() 474void QTextCursor::invalidateNested()
469{ 475{
470 QValueStack<QTextParagraph*>::Iterator it = paras.begin(); 476 QValueStack<QTextParagraph*>::Iterator it = paras.begin();
471 QValueStack<int>::Iterator it2 = indices.begin(); 477 QValueStack<int>::Iterator it2 = indices.begin();
472 for ( ; it != paras.end(); ++it, ++it2 ) { 478 for ( ; it != paras.end(); ++it, ++it2 ) {
473 if ( *it == para ) 479 if ( *it == para )
474 continue; 480 continue;
475 (*it)->invalidate( 0 ); 481 (*it)->invalidate( 0 );
476 if ( (*it)->at( *it2 )->isCustom() ) 482 if ( (*it)->at( *it2 )->isCustom() )
477 (*it)->at( *it2 )->customItem()->invalidate(); 483 (*it)->at( *it2 )->customItem()->invalidate();
478 } 484 }
479} 485}
480 486
481void QTextCursor::insert( const QString &str, bool checkNewLine, QMemArray<QTextStringChar> *formatting ) 487void QTextCursor::insert( const QString &str, bool checkNewLine, QMemArray<QTextStringChar> *formatting )
482{ 488{
483 tmpIndex = -1; 489 tmpIndex = -1;
484 bool justInsert = TRUE; 490 bool justInsert = TRUE;
485 QString s( str ); 491 QString s( str );
486#if defined(Q_WS_WIN) 492#if defined(Q_WS_WIN)
487 if ( checkNewLine ) { 493 if ( checkNewLine ) {
488 int i = 0; 494 int i = 0;
489 while ( ( i = s.find( '\r', i ) ) != -1 ) 495 while ( ( i = s.find( '\r', i ) ) != -1 )
490 s.remove( i ,1 ); 496 s.remove( i ,1 );
491 } 497 }
492#endif 498#endif
493 if ( checkNewLine ) 499 if ( checkNewLine )
494 justInsert = s.find( '\n' ) == -1; 500 justInsert = s.find( '\n' ) == -1;
495 if ( justInsert ) { // we ignore new lines and insert all in the current para at the current index 501 if ( justInsert ) { // we ignore new lines and insert all in the current para at the current index
496 para->insert( idx, s.unicode(), s.length() ); 502 para->insert( idx, s.unicode(), s.length() );
497 if ( formatting ) { 503 if ( formatting ) {
498 for ( int i = 0; i < (int)s.length(); ++i ) { 504 for ( int i = 0; i < (int)s.length(); ++i ) {
499 if ( formatting->at( i ).format() ) { 505 if ( formatting->at( i ).format() ) {
500 formatting->at( i ).format()->addRef(); 506 formatting->at( i ).format()->addRef();
501 para->string()->setFormat( idx + i, formatting->at( i ).format(), TRUE ); 507 para->string()->setFormat( idx + i, formatting->at( i ).format(), TRUE );
502 } 508 }
503 } 509 }
504 } 510 }
505 idx += s.length(); 511 idx += s.length();
506 } else { // we split at new lines 512 } else { // we split at new lines
507 int start = -1; 513 int start = -1;
508 int end; 514 int end;
509 int y = para->rect().y() + para->rect().height(); 515 int y = para->rect().y() + para->rect().height();
510 int lastIndex = 0; 516 int lastIndex = 0;
511 do { 517 do {
512 end = s.find( '\n', start + 1 ); // find line break 518 end = s.find( '\n', start + 1 ); // find line break
513 if ( end == -1 ) // didn't find one, so end of line is end of string 519 if ( end == -1 ) // didn't find one, so end of line is end of string
514 end = s.length(); 520 end = s.length();
515 int len = (start == -1 ? end : end - start - 1); 521 int len = (start == -1 ? end : end - start - 1);
516 if ( len > 0 ) // insert the line 522 if ( len > 0 ) // insert the line
517 para->insert( idx, s.unicode() + start + 1, len ); 523 para->insert( idx, s.unicode() + start + 1, len );
518 else 524 else
519 para->invalidate( 0 ); 525 para->invalidate( 0 );
520 if ( formatting ) { // set formats to the chars of the line 526 if ( formatting ) { // set formats to the chars of the line
521 for ( int i = 0; i < len; ++i ) { 527 for ( int i = 0; i < len; ++i ) {
522 if ( formatting->at( i + lastIndex ).format() ) { 528 if ( formatting->at( i + lastIndex ).format() ) {
523 formatting->at( i + lastIndex ).format()->addRef(); 529 formatting->at( i + lastIndex ).format()->addRef();
524 para->string()->setFormat( i + idx, formatting->at( i + lastIndex ).format(), TRUE ); 530 para->string()->setFormat( i + idx, formatting->at( i + lastIndex ).format(), TRUE );
525 } 531 }
526 } 532 }
527 lastIndex += len; 533 lastIndex += len;
528 } 534 }
529 start = end; // next start is at the end of this line 535 start = end; // next start is at the end of this line
530 idx += len; // increase the index of the cursor to the end of the inserted text 536 idx += len; // increase the index of the cursor to the end of the inserted text
531 if ( s[end] == '\n' ) { // if at the end was a line break, break the line 537 if ( s[end] == '\n' ) { // if at the end was a line break, break the line
532 splitAndInsertEmptyParagraph( FALSE, TRUE ); 538 splitAndInsertEmptyParagraph( FALSE, TRUE );
533 para->setEndState( -1 ); 539 para->setEndState( -1 );
534 para->prev()->format( -1, FALSE ); 540 para->prev()->format( -1, FALSE );
535 lastIndex++; 541 lastIndex++;
536 } 542 }
537 543
538 } while ( end < (int)s.length() ); 544 } while ( end < (int)s.length() );
539 545
540 para->format( -1, FALSE ); 546 para->format( -1, FALSE );
541 int dy = para->rect().y() + para->rect().height() - y; 547 int dy = para->rect().y() + para->rect().height() - y;
542 QTextParagraph *p = para; 548 QTextParagraph *p = para;
543 p->setParagId( p->prev() ? p->prev()->paragId() + 1 : 0 ); 549 p->setParagId( p->prev() ? p->prev()->paragId() + 1 : 0 );
544 p = p->next(); 550 p = p->next();
545 while ( p ) { 551 while ( p ) {
546 p->setParagId( p->prev()->paragId() + 1 ); 552 p->setParagId( p->prev()->paragId() + 1 );
547 p->move( dy ); 553 p->move( dy );
548 p->invalidate( 0 ); 554 p->invalidate( 0 );
549 p->setEndState( -1 ); 555 p->setEndState( -1 );
550 p = p->next(); 556 p = p->next();
551 } 557 }
552 } 558 }
553 559
554 int h = para->rect().height(); 560 int h = para->rect().height();
555 para->format( -1, TRUE ); 561 para->format( -1, TRUE );
556 if ( h != para->rect().height() ) 562 if ( h != para->rect().height() )
557 invalidateNested(); 563 invalidateNested();
558 else if ( para->document() && para->document()->parent() ) 564 else if ( para->document() && para->document()->parent() )
559 para->document()->nextDoubleBuffered = TRUE; 565 para->document()->nextDoubleBuffered = TRUE;
560} 566}
561 567
562void QTextCursor::gotoLeft() 568void QTextCursor::gotoLeft()
563{ 569{
564 if ( para->string()->isRightToLeft() ) 570 if ( para->string()->isRightToLeft() )
565 gotoNextLetter(); 571 gotoNextLetter();
566 else 572 else
567 gotoPreviousLetter(); 573 gotoPreviousLetter();
568} 574}
569 575
570void QTextCursor::gotoPreviousLetter() 576void QTextCursor::gotoPreviousLetter()
571{ 577{
572 tmpIndex = -1; 578 tmpIndex = -1;
573 579
574 if ( idx > 0 ) { 580 if ( idx > 0 ) {
575 idx--; 581 idx--;
576 const QTextStringChar *tsc = para->at( idx ); 582 const QTextStringChar *tsc = para->at( idx );
577 if ( tsc && tsc->isCustom() && tsc->customItem()->isNested() ) 583 if ( tsc && tsc->isCustom() && tsc->customItem()->isNested() )
578 processNesting( EnterEnd ); 584 processNesting( EnterEnd );
579 } else if ( para->prev() ) { 585 } else if ( para->prev() ) {
580 para = para->prev(); 586 para = para->prev();
581 while ( !para->isVisible() && para->prev() ) 587 while ( !para->isVisible() && para->prev() )
582 para = para->prev(); 588 para = para->prev();
583 idx = para->length() - 1; 589 idx = para->length() - 1;
584 } else if ( nestedDepth() ) { 590 } else if ( nestedDepth() ) {
585 pop(); 591 pop();
586 processNesting( Prev ); 592 processNesting( Prev );
587 if ( idx == -1 ) { 593 if ( idx == -1 ) {
588 pop(); 594 pop();
589 if ( idx > 0 ) { 595 if ( idx > 0 ) {
590 idx--; 596 idx--;
591 } else if ( para->prev() ) { 597 } else if ( para->prev() ) {
592 para = para->prev(); 598 para = para->prev();
593 idx = para->length() - 1; 599 idx = para->length() - 1;
594 } 600 }
595 } 601 }
596 } 602 }
597} 603}
598 604
599void QTextCursor::push() 605void QTextCursor::push()
600{ 606{
601 indices.push( idx ); 607 indices.push( idx );
602 paras.push( para ); 608 paras.push( para );
603 xOffsets.push( ox ); 609 xOffsets.push( ox );
604 yOffsets.push( oy ); 610 yOffsets.push( oy );
605} 611}
606 612
607void QTextCursor::pop() 613void QTextCursor::pop()
608{ 614{
609 if ( indices.isEmpty() ) 615 if ( indices.isEmpty() )
610 return; 616 return;
611 idx = indices.pop(); 617 idx = indices.pop();
612 para = paras.pop(); 618 para = paras.pop();
613 ox = xOffsets.pop(); 619 ox = xOffsets.pop();
614 oy = yOffsets.pop(); 620 oy = yOffsets.pop();
615} 621}
616 622
617void QTextCursor::restoreState() 623void QTextCursor::restoreState()
618{ 624{
619 while ( !indices.isEmpty() ) 625 while ( !indices.isEmpty() )
620 pop(); 626 pop();
621} 627}
622 628
623bool QTextCursor::place( const QPoint &p, QTextParagraph *s, bool link ) 629bool QTextCursor::place( const QPoint &p, QTextParagraph *s, bool link )
624{ 630{
625 QPoint pos( p ); 631 QPoint pos( p );
626 QRect r; 632 QRect r;
627 QTextParagraph *str = s; 633 QTextParagraph *str = s;
628 if ( pos.y() < s->rect().y() ) 634 if ( pos.y() < s->rect().y() )
629 pos.setY( s->rect().y() ); 635 pos.setY( s->rect().y() );
630 while ( s ) { 636 while ( s ) {
631 r = s->rect(); 637 r = s->rect();
632 r.setWidth( document() ? document()->width() : QWIDGETSIZE_MAX ); 638 r.setWidth( document() ? document()->width() : QWIDGETSIZE_MAX );
633 if ( s->isVisible() ) 639 if ( s->isVisible() )
634 str = s; 640 str = s;
635 if ( pos.y() >= r.y() && pos.y() <= r.y() + r.height() || !s->next() ) 641 if ( pos.y() >= r.y() && pos.y() <= r.y() + r.height() || !s->next() )
636 break; 642 break;
637 s = s->next(); 643 s = s->next();
638 } 644 }
639 645
640 if ( !s || !str ) 646 if ( !s || !str )
641 return FALSE; 647 return FALSE;
642 648
643 s = str; 649 s = str;
644 650
645 setParagraph( s ); 651 setParagraph( s );
646 int y = s->rect().y(); 652 int y = s->rect().y();
647 int lines = s->lines(); 653 int lines = s->lines();
648 QTextStringChar *chr = 0; 654 QTextStringChar *chr = 0;
649 int index = 0; 655 int index = 0;
650 int i = 0; 656 int i = 0;
651 int cy = 0; 657 int cy = 0;
652 int ch = 0; 658 int ch = 0;
653 for ( ; i < lines; ++i ) { 659 for ( ; i < lines; ++i ) {
654 chr = s->lineStartOfLine( i, &index ); 660 chr = s->lineStartOfLine( i, &index );
655 cy = s->lineY( i ); 661 cy = s->lineY( i );
656 ch = s->lineHeight( i ); 662 ch = s->lineHeight( i );
657 if ( !chr ) 663 if ( !chr )
658 return FALSE; 664 return FALSE;
659 if ( pos.y() <= y + cy + ch ) 665 if ( pos.y() <= y + cy + ch )
660 break; 666 break;
661 } 667 }
662 int nextLine; 668 int nextLine;
663 if ( i < lines - 1 ) 669 if ( i < lines - 1 )
664 s->lineStartOfLine( i+1, &nextLine ); 670 s->lineStartOfLine( i+1, &nextLine );
665 else 671 else
666 nextLine = s->length(); 672 nextLine = s->length();
667 i = index; 673 i = index;
668 int x = s->rect().x(); 674 int x = s->rect().x();
669 if ( pos.x() < x ) 675 if ( pos.x() < x )
670 pos.setX( x + 1 ); 676 pos.setX( x + 1 );
671 int cw; 677 int cw;
672 int curpos = s->length()-1; 678 int curpos = s->length()-1;
673 int dist = 10000000; 679 int dist = 10000000;
674 bool inCustom = FALSE; 680 bool inCustom = FALSE;
675 while ( i < nextLine ) { 681 while ( i < nextLine ) {
676 chr = s->at(i); 682 chr = s->at(i);
677 int cpos = x + chr->x; 683 int cpos = x + chr->x;
678 cw = s->string()->width( i ); 684 cw = s->string()->width( i );
679 if ( chr->isCustom() && chr->customItem()->isNested() ) { 685 if ( chr->isCustom() && chr->customItem()->isNested() ) {
680 if ( pos.x() >= cpos && pos.x() <= cpos + cw && 686 if ( pos.x() >= cpos && pos.x() <= cpos + cw &&
681 pos.y() >= y + cy && pos.y() <= y + cy + chr->height() ) { 687 pos.y() >= y + cy && pos.y() <= y + cy + chr->height() ) {
682 inCustom = TRUE; 688 inCustom = TRUE;
683 curpos = i; 689 curpos = i;
684 break; 690 break;
685 } 691 }
686 } else { 692 } else {
687 if( chr->rightToLeft ) 693 if( chr->rightToLeft )
688 cpos += cw; 694 cpos += cw;
689 int d = cpos - pos.x(); 695 int d = cpos - pos.x();
690 bool dm = d < 0 ? !chr->rightToLeft : chr->rightToLeft; 696 bool dm = d < 0 ? !chr->rightToLeft : chr->rightToLeft;
691 if ( QABS( d ) < dist || (dist == d && dm == TRUE ) ) { 697 if ( QABS( d ) < dist || (dist == d && dm == TRUE ) ) {
692 dist = QABS( d ); 698 dist = QABS( d );
693 if ( !link || pos.x() >= x + chr->x ) 699 if ( !link || pos.x() >= x + chr->x )
694 curpos = i; 700 curpos = i;
695 } 701 }
696 } 702 }
697 i++; 703 i++;
698 } 704 }
699 setIndex( curpos ); 705 setIndex( curpos );
700 706
701 if ( inCustom && para->document() && para->at( curpos )->isCustom() && para->at( curpos )->customItem()->isNested() ) { 707 if ( inCustom && para->document() && para->at( curpos )->isCustom() && para->at( curpos )->customItem()->isNested() ) {
702 QTextDocument *oldDoc = para->document(); 708 QTextDocument *oldDoc = para->document();
703 gotoIntoNested( pos ); 709 gotoIntoNested( pos );
704 if ( oldDoc == para->document() ) 710 if ( oldDoc == para->document() )
705 return TRUE; 711 return TRUE;
706 QPoint p( pos.x() - offsetX(), pos.y() - offsetY() ); 712 QPoint p( pos.x() - offsetX(), pos.y() - offsetY() );
707 if ( !place( p, document()->firstParagraph(), link ) ) 713 if ( !place( p, document()->firstParagraph(), link ) )
708 pop(); 714 pop();
709 } 715 }
710 return TRUE; 716 return TRUE;
711} 717}
712 718
713void QTextCursor::processNesting( Operation op ) 719void QTextCursor::processNesting( Operation op )
714{ 720{
715 if ( !para->document() ) 721 if ( !para->document() )
716 return; 722 return;
717 QTextDocument* doc = para->document(); 723 QTextDocument* doc = para->document();
718 push(); 724 push();
719 ox = para->at( idx )->x; 725 ox = para->at( idx )->x;
720 int bl, y; 726 int bl, y;
721 para->lineHeightOfChar( idx, &bl, &y ); 727 para->lineHeightOfChar( idx, &bl, &y );
722 oy = y + para->rect().y(); 728 oy = y + para->rect().y();
723 bool ok = FALSE; 729 bool ok = FALSE;
724 730
725 switch ( op ) { 731 switch ( op ) {
726 case EnterBegin: 732 case EnterBegin:
727 ok = para->at( idx )->customItem()->enter( this, doc, para, idx, ox, oy ); 733 ok = para->at( idx )->customItem()->enter( this, doc, para, idx, ox, oy );
728 break; 734 break;
729 case EnterEnd: 735 case EnterEnd:
730 ok = para->at( idx )->customItem()->enter( this, doc, para, idx, ox, oy, TRUE ); 736 ok = para->at( idx )->customItem()->enter( this, doc, para, idx, ox, oy, TRUE );
731 break; 737 break;
732 case Next: 738 case Next:
733 ok = para->at( idx )->customItem()->next( this, doc, para, idx, ox, oy ); 739 ok = para->at( idx )->customItem()->next( this, doc, para, idx, ox, oy );
734 break; 740 break;
735 case Prev: 741 case Prev:
736 ok = para->at( idx )->customItem()->prev( this, doc, para, idx, ox, oy ); 742 ok = para->at( idx )->customItem()->prev( this, doc, para, idx, ox, oy );
737 break; 743 break;
738 case Down: 744 case Down:
739 ok = para->at( idx )->customItem()->down( this, doc, para, idx, ox, oy ); 745 ok = para->at( idx )->customItem()->down( this, doc, para, idx, ox, oy );
740 break; 746 break;
741 case Up: 747 case Up:
742 ok = para->at( idx )->customItem()->up( this, doc, para, idx, ox, oy ); 748 ok = para->at( idx )->customItem()->up( this, doc, para, idx, ox, oy );
743 break; 749 break;
744 } 750 }
745 if ( !ok ) 751 if ( !ok )
746 pop(); 752 pop();
747} 753}
748 754
749void QTextCursor::gotoRight() 755void QTextCursor::gotoRight()
750{ 756{
751 if ( para->string()->isRightToLeft() ) 757 if ( para->string()->isRightToLeft() )
752 gotoPreviousLetter(); 758 gotoPreviousLetter();
753 else 759 else
754 gotoNextLetter(); 760 gotoNextLetter();
755} 761}
756 762
757void QTextCursor::gotoNextLetter() 763void QTextCursor::gotoNextLetter()
758{ 764{
759 tmpIndex = -1; 765 tmpIndex = -1;
760 766
761 const QTextStringChar *tsc = para->at( idx ); 767 const QTextStringChar *tsc = para->at( idx );
762 if ( tsc && tsc->isCustom() && tsc->customItem()->isNested() ) { 768 if ( tsc && tsc->isCustom() && tsc->customItem()->isNested() ) {
763 processNesting( EnterBegin ); 769 processNesting( EnterBegin );
764 return; 770 return;
765 } 771 }
766 772
767 if ( idx < para->length() - 1 ) { 773 if ( idx < para->length() - 1 ) {
768 idx++; 774 idx++;
769 } else if ( para->next() ) { 775 } else if ( para->next() ) {
770 para = para->next(); 776 para = para->next();
771 while ( !para->isVisible() && para->next() ) 777 while ( !para->isVisible() && para->next() )
772 para = para->next(); 778 para = para->next();
773 idx = 0; 779 idx = 0;
774 } else if ( nestedDepth() ) { 780 } else if ( nestedDepth() ) {
775 pop(); 781 pop();
776 processNesting( Next ); 782 processNesting( Next );
777 if ( idx == -1 ) { 783 if ( idx == -1 ) {
778 pop(); 784 pop();
779 if ( idx < para->length() - 1 ) { 785 if ( idx < para->length() - 1 ) {
780 idx++; 786 idx++;
781 } else if ( para->next() ) { 787 } else if ( para->next() ) {
782 para = para->next(); 788 para = para->next();
783 idx = 0; 789 idx = 0;
784 } 790 }
785 } 791 }
786 } 792 }
787} 793}
788 794
789void QTextCursor::gotoUp() 795void QTextCursor::gotoUp()
790{ 796{
791 int indexOfLineStart; 797 int indexOfLineStart;
792 int line; 798 int line;
793 QTextStringChar *c = para->lineStartOfChar( idx, &indexOfLineStart, &line ); 799 QTextStringChar *c = para->lineStartOfChar( idx, &indexOfLineStart, &line );
794 if ( !c ) 800 if ( !c )
795 return; 801 return;
796 802
797 tmpIndex = QMAX( tmpIndex, idx - indexOfLineStart ); 803 tmpIndex = QMAX( tmpIndex, idx - indexOfLineStart );
798 if ( indexOfLineStart == 0 ) { 804 if ( indexOfLineStart == 0 ) {
799 if ( !para->prev() ) { 805 if ( !para->prev() ) {
800 if ( !nestedDepth() ) 806 if ( !nestedDepth() )
801 return; 807 return;
802 pop(); 808 pop();
803 processNesting( Up ); 809 processNesting( Up );
804 if ( idx == -1 ) { 810 if ( idx == -1 ) {
805 pop(); 811 pop();
806 if ( !para->prev() ) 812 if ( !para->prev() )
807 return; 813 return;
808 idx = tmpIndex = 0; 814 idx = tmpIndex = 0;
809 } else { 815 } else {
810 tmpIndex = -1; 816 tmpIndex = -1;
811 return; 817 return;
812 } 818 }
813 } 819 }
814 QTextParagraph *p = para->prev(); 820 QTextParagraph *p = para->prev();
815 while ( p && !p->isVisible() ) 821 while ( p && !p->isVisible() )
816 p = p->prev(); 822 p = p->prev();
817 if ( p ) 823 if ( p )
818 para = p; 824 para = p;
819 int lastLine = para->lines() - 1; 825 int lastLine = para->lines() - 1;
820 if ( !para->lineStartOfLine( lastLine, &indexOfLineStart ) ) 826 if ( !para->lineStartOfLine( lastLine, &indexOfLineStart ) )
821 return; 827 return;
822 if ( indexOfLineStart + tmpIndex < para->length() ) 828 if ( indexOfLineStart + tmpIndex < para->length() )
823 idx = indexOfLineStart + tmpIndex; 829 idx = indexOfLineStart + tmpIndex;
824 else 830 else
825 idx = para->length() - 1; 831 idx = para->length() - 1;
826 } else { 832 } else {
827 --line; 833 --line;
828 int oldIndexOfLineStart = indexOfLineStart; 834 int oldIndexOfLineStart = indexOfLineStart;
829 if ( !para->lineStartOfLine( line, &indexOfLineStart ) ) 835 if ( !para->lineStartOfLine( line, &indexOfLineStart ) )
830 return; 836 return;
831 if ( indexOfLineStart + tmpIndex < oldIndexOfLineStart ) 837 if ( indexOfLineStart + tmpIndex < oldIndexOfLineStart )
832 idx = indexOfLineStart + tmpIndex; 838 idx = indexOfLineStart + tmpIndex;
833 else 839 else
834 idx = oldIndexOfLineStart - 1; 840 idx = oldIndexOfLineStart - 1;
835 } 841 }
836} 842}
837 843
838void QTextCursor::gotoDown() 844void QTextCursor::gotoDown()
839{ 845{
840 int indexOfLineStart; 846 int indexOfLineStart;
841 int line; 847 int line;
842 QTextStringChar *c = para->lineStartOfChar( idx, &indexOfLineStart, &line ); 848 QTextStringChar *c = para->lineStartOfChar( idx, &indexOfLineStart, &line );
843 if ( !c ) 849 if ( !c )
844 return; 850 return;
845 851
846 tmpIndex = QMAX( tmpIndex, idx - indexOfLineStart ); 852 tmpIndex = QMAX( tmpIndex, idx - indexOfLineStart );
847 if ( line == para->lines() - 1 ) { 853 if ( line == para->lines() - 1 ) {
848 if ( !para->next() ) { 854 if ( !para->next() ) {
849 if ( !nestedDepth() ) 855 if ( !nestedDepth() )
850 return; 856 return;
851 pop(); 857 pop();
852 processNesting( Down ); 858 processNesting( Down );
853 if ( idx == -1 ) { 859 if ( idx == -1 ) {
854 pop(); 860 pop();
855 if ( !para->next() ) 861 if ( !para->next() )
856 return; 862 return;
857 idx = tmpIndex = 0; 863 idx = tmpIndex = 0;
858 } else { 864 } else {
859 tmpIndex = -1; 865 tmpIndex = -1;
860 return; 866 return;
861 } 867 }
862 } 868 }
863 QTextParagraph *s = para->next(); 869 QTextParagraph *s = para->next();
864 while ( s && !s->isVisible() ) 870 while ( s && !s->isVisible() )
865 s = s->next(); 871 s = s->next();
866 if ( s ) 872 if ( s )
867 para = s; 873 para = s;
868 if ( !para->lineStartOfLine( 0, &indexOfLineStart ) ) 874 if ( !para->lineStartOfLine( 0, &indexOfLineStart ) )
869 return; 875 return;
870 int end; 876 int end;
871 if ( para->lines() == 1 ) 877 if ( para->lines() == 1 )
872 end = para->length(); 878 end = para->length();
873 else 879 else
874 para->lineStartOfLine( 1, &end ); 880 para->lineStartOfLine( 1, &end );
875 if ( indexOfLineStart + tmpIndex < end ) 881 if ( indexOfLineStart + tmpIndex < end )
876 idx = indexOfLineStart + tmpIndex; 882 idx = indexOfLineStart + tmpIndex;
877 else 883 else
878 idx = end - 1; 884 idx = end - 1;
879 } else { 885 } else {
880 ++line; 886 ++line;
881 int end; 887 int end;
882 if ( line == para->lines() - 1 ) 888 if ( line == para->lines() - 1 )
883 end = para->length(); 889 end = para->length();
884 else 890 else
885 para->lineStartOfLine( line + 1, &end ); 891 para->lineStartOfLine( line + 1, &end );
886 if ( !para->lineStartOfLine( line, &indexOfLineStart ) ) 892 if ( !para->lineStartOfLine( line, &indexOfLineStart ) )
887 return; 893 return;
888 if ( indexOfLineStart + tmpIndex < end ) 894 if ( indexOfLineStart + tmpIndex < end )
889 idx = indexOfLineStart + tmpIndex; 895 idx = indexOfLineStart + tmpIndex;
890 else 896 else
891 idx = end - 1; 897 idx = end - 1;
892 } 898 }
893} 899}
894 900
895void QTextCursor::gotoLineEnd() 901void QTextCursor::gotoLineEnd()
896{ 902{
897 tmpIndex = -1; 903 tmpIndex = -1;
898 int indexOfLineStart; 904 int indexOfLineStart;
899 int line; 905 int line;
900 QTextStringChar *c = para->lineStartOfChar( idx, &indexOfLineStart, &line ); 906 QTextStringChar *c = para->lineStartOfChar( idx, &indexOfLineStart, &line );
901 if ( !c ) 907 if ( !c )
902 return; 908 return;
903 909
904 if ( line == para->lines() - 1 ) { 910 if ( line == para->lines() - 1 ) {
905 idx = para->length() - 1; 911 idx = para->length() - 1;
906 } else { 912 } else {
907 c = para->lineStartOfLine( ++line, &indexOfLineStart ); 913 c = para->lineStartOfLine( ++line, &indexOfLineStart );
908 indexOfLineStart--; 914 indexOfLineStart--;
909 idx = indexOfLineStart; 915 idx = indexOfLineStart;
910 } 916 }
911} 917}
912 918
913void QTextCursor::gotoLineStart() 919void QTextCursor::gotoLineStart()
914{ 920{
915 tmpIndex = -1; 921 tmpIndex = -1;
916 int indexOfLineStart; 922 int indexOfLineStart;
917 int line; 923 int line;
918 QTextStringChar *c = para->lineStartOfChar( idx, &indexOfLineStart, &line ); 924 QTextStringChar *c = para->lineStartOfChar( idx, &indexOfLineStart, &line );
919 if ( !c ) 925 if ( !c )
920 return; 926 return;
921 927
922 idx = indexOfLineStart; 928 idx = indexOfLineStart;
923} 929}
924 930
925void QTextCursor::gotoHome() 931void QTextCursor::gotoHome()
926{ 932{
927 if ( topParagraph()->document() ) 933 if ( topParagraph()->document() )
928 gotoPosition( topParagraph()->document()->firstParagraph() ); 934 gotoPosition( topParagraph()->document()->firstParagraph() );
929 else 935 else
930 gotoLineStart(); 936 gotoLineStart();
931} 937}
932 938
933void QTextCursor::gotoEnd() 939void QTextCursor::gotoEnd()
934{ 940{
935 if ( topParagraph()->document() && topParagraph()->document()->lastParagraph()->isValid() ) 941 if ( topParagraph()->document() && topParagraph()->document()->lastParagraph()->isValid() )
936 gotoPosition( topParagraph()->document()->lastParagraph(), 942 gotoPosition( topParagraph()->document()->lastParagraph(),
937 topParagraph()->document()->lastParagraph()->length() - 1); 943 topParagraph()->document()->lastParagraph()->length() - 1);
938 else 944 else
939 gotoLineEnd(); 945 gotoLineEnd();
940} 946}
941 947
942void QTextCursor::gotoPageUp( int visibleHeight ) 948void QTextCursor::gotoPageUp( int visibleHeight )
943{ 949{
944 int targetY = globalY() - visibleHeight; 950 int targetY = globalY() - visibleHeight;
945 QTextParagraph* old; int index; 951 QTextParagraph* old; int index;
946 do { 952 do {
947 old = para; index = idx; 953 old = para; index = idx;
948 gotoUp(); 954 gotoUp();
949 } while ( (old != para || index != idx) && globalY() > targetY ); 955 } while ( (old != para || index != idx) && globalY() > targetY );
950} 956}
951 957
952void QTextCursor::gotoPageDown( int visibleHeight ) 958void QTextCursor::gotoPageDown( int visibleHeight )
953{ 959{
954 int targetY = globalY() + visibleHeight; 960 int targetY = globalY() + visibleHeight;
955 QTextParagraph* old; int index; 961 QTextParagraph* old; int index;
956 do { 962 do {
957 old = para; index = idx; 963 old = para; index = idx;
958 gotoDown(); 964 gotoDown();
959 } while ( (old != para || index != idx) && globalY() < targetY ); 965 } while ( (old != para || index != idx) && globalY() < targetY );
960} 966}
961 967
962void QTextCursor::gotoWordRight() 968void QTextCursor::gotoWordRight()
963{ 969{
964 if ( para->string()->isRightToLeft() ) 970 if ( para->string()->isRightToLeft() )
965 gotoPreviousWord(); 971 gotoPreviousWord();
966 else 972 else
967 gotoNextWord(); 973 gotoNextWord();
968} 974}
969 975
970void QTextCursor::gotoWordLeft() 976void QTextCursor::gotoWordLeft()
971{ 977{
972 if ( para->string()->isRightToLeft() ) 978 if ( para->string()->isRightToLeft() )
973 gotoNextWord(); 979 gotoNextWord();
974 else 980 else
975 gotoPreviousWord(); 981 gotoPreviousWord();
976} 982}
977 983
978void QTextCursor::gotoPreviousWord() 984void QTextCursor::gotoPreviousWord()
979{ 985{
980 gotoPreviousLetter(); 986 gotoPreviousLetter();
981 tmpIndex = -1; 987 tmpIndex = -1;
982 QTextString *s = para->string(); 988 QTextString *s = para->string();
983 bool allowSame = FALSE; 989 bool allowSame = FALSE;
984 if ( idx == ((int)s->length()-1) ) 990 if ( idx == ((int)s->length()-1) )
985 return; 991 return;
986 for ( int i = idx; i >= 0; --i ) { 992 for ( int i = idx; i >= 0; --i ) {
987 if ( s->at( i ).c.isSpace() || s->at( i ).c == '\t' || s->at( i ).c == '.' || 993 if ( s->at( i ).c.isSpace() || s->at( i ).c == '\t' || s->at( i ).c == '.' ||
988 s->at( i ).c == ',' || s->at( i ).c == ':' || s->at( i ).c == ';' ) { 994 s->at( i ).c == ',' || s->at( i ).c == ':' || s->at( i ).c == ';' ) {
989 if ( !allowSame ) 995 if ( !allowSame )
990 continue; 996 continue;
991 idx = i + 1; 997 idx = i + 1;
992 return; 998 return;
993 } 999 }
994 if ( !allowSame && !( s->at( i ).c.isSpace() || s->at( i ).c == '\t' || s->at( i ).c == '.' || 1000 if ( !allowSame && !( s->at( i ).c.isSpace() || s->at( i ).c == '\t' || s->at( i ).c == '.' ||
995 s->at( i ).c == ',' || s->at( i ).c == ':' || s->at( i ).c == ';' ) ) 1001 s->at( i ).c == ',' || s->at( i ).c == ':' || s->at( i ).c == ';' ) )
996 allowSame = TRUE; 1002 allowSame = TRUE;
997 } 1003 }
998 idx = 0; 1004 idx = 0;
999} 1005}
1000 1006
1001void QTextCursor::gotoNextWord() 1007void QTextCursor::gotoNextWord()
1002{ 1008{
1003 tmpIndex = -1; 1009 tmpIndex = -1;
1004 QTextString *s = para->string(); 1010 QTextString *s = para->string();
1005 bool allowSame = FALSE; 1011 bool allowSame = FALSE;
1006 for ( int i = idx; i < (int)s->length(); ++i ) { 1012 for ( int i = idx; i < (int)s->length(); ++i ) {
1007 if ( ! (s->at( i ).c.isSpace() || s->at( i ).c == '\t' || s->at( i ).c == '.' || 1013 if ( ! (s->at( i ).c.isSpace() || s->at( i ).c == '\t' || s->at( i ).c == '.' ||
1008 s->at( i ).c == ',' || s->at( i ).c == ':' || s->at( i ).c == ';') ) { 1014 s->at( i ).c == ',' || s->at( i ).c == ':' || s->at( i ).c == ';') ) {
1009 if ( !allowSame ) 1015 if ( !allowSame )
1010 continue; 1016 continue;
1011 idx = i; 1017 idx = i;
1012 return; 1018 return;
1013 } 1019 }
1014 if ( !allowSame && ( s->at( i ).c.isSpace() || s->at( i ).c == '\t' || s->at( i ).c == '.' || 1020 if ( !allowSame && ( s->at( i ).c.isSpace() || s->at( i ).c == '\t' || s->at( i ).c == '.' ||
1015 s->at( i ).c == ',' || s->at( i ).c == ':' || s->at( i ).c == ';' ) ) 1021 s->at( i ).c == ',' || s->at( i ).c == ':' || s->at( i ).c == ';' ) )
1016 allowSame = TRUE; 1022 allowSame = TRUE;
1017 1023
1018 } 1024 }
1019 1025
1020 if ( idx < ((int)s->length()-1) ) { 1026 if ( idx < ((int)s->length()-1) ) {
1021 gotoLineEnd(); 1027 gotoLineEnd();
1022 } else if ( para->next() ) { 1028 } else if ( para->next() ) {
1023 QTextParagraph *p = para->next(); 1029 QTextParagraph *p = para->next();
1024 while ( p && !p->isVisible() ) 1030 while ( p && !p->isVisible() )
1025 p = p->next(); 1031 p = p->next();
1026 if ( s ) { 1032 if ( s ) {
1027 para = p; 1033 para = p;
1028 idx = 0; 1034 idx = 0;
1029 } 1035 }
1030 } else { 1036 } else {
1031 gotoLineEnd(); 1037 gotoLineEnd();
1032 } 1038 }
1033} 1039}
1034 1040
1035bool QTextCursor::atParagStart() 1041bool QTextCursor::atParagStart()
1036{ 1042{
1037 return idx == 0; 1043 return idx == 0;
1038} 1044}
1039 1045
1040bool QTextCursor::atParagEnd() 1046bool QTextCursor::atParagEnd()
1041{ 1047{
1042 return idx == para->length() - 1; 1048 return idx == para->length() - 1;
1043} 1049}
1044 1050
1045void QTextCursor::splitAndInsertEmptyParagraph( bool ind, bool updateIds ) 1051void QTextCursor::splitAndInsertEmptyParagraph( bool ind, bool updateIds )
1046{ 1052{
1047 if ( !para->document() ) 1053 if ( !para->document() )
1048 return; 1054 return;
1049 tmpIndex = -1; 1055 tmpIndex = -1;
1050 QTextFormat *f = 0; 1056 QTextFormat *f = 0;
1051 if ( para->document()->useFormatCollection() ) { 1057 if ( para->document()->useFormatCollection() ) {
1052 f = para->at( idx )->format(); 1058 f = para->at( idx )->format();
1053 if ( idx == para->length() - 1 && idx > 0 ) 1059 if ( idx == para->length() - 1 && idx > 0 )
1054 f = para->at( idx - 1 )->format(); 1060 f = para->at( idx - 1 )->format();
1055 if ( f->isMisspelled() ) { 1061 if ( f->isMisspelled() ) {
1056 f->removeRef(); 1062 f->removeRef();
1057 f = para->document()->formatCollection()->format( f->font(), f->color() ); 1063 f = para->document()->formatCollection()->format( f->font(), f->color() );
1058 } 1064 }
1059 } 1065 }
1060 1066
1061 if ( atParagEnd() ) { 1067 if ( atParagEnd() ) {
1062 QTextParagraph *n = para->next(); 1068 QTextParagraph *n = para->next();
1063 QTextParagraph *s = para->document()->createParagraph( para->document(), para, n, updateIds ); 1069 QTextParagraph *s = para->document()->createParagraph( para->document(), para, n, updateIds );
1064 if ( f ) 1070 if ( f )
1065 s->setFormat( 0, 1, f, TRUE ); 1071 s->setFormat( 0, 1, f, TRUE );
1066 s->copyParagData( para ); 1072 s->copyParagData( para );
1067 if ( ind ) { 1073 if ( ind ) {
1068 int oi, ni; 1074 int oi, ni;
1069 s->indent( &oi, &ni ); 1075 s->indent( &oi, &ni );
1070 para = s; 1076 para = s;
1071 idx = ni; 1077 idx = ni;
1072 } else { 1078 } else {
1073 para = s; 1079 para = s;
1074 idx = 0; 1080 idx = 0;
1075 } 1081 }
1076 } else if ( atParagStart() ) { 1082 } else if ( atParagStart() ) {
1077 QTextParagraph *p = para->prev(); 1083 QTextParagraph *p = para->prev();
1078 QTextParagraph *s = para->document()->createParagraph( para->document(), p, para, updateIds ); 1084 QTextParagraph *s = para->document()->createParagraph( para->document(), p, para, updateIds );
1079 if ( f ) 1085 if ( f )
1080 s->setFormat( 0, 1, f, TRUE ); 1086 s->setFormat( 0, 1, f, TRUE );
1081 s->copyParagData( para ); 1087 s->copyParagData( para );
1082 if ( ind ) { 1088 if ( ind ) {
1083 s->indent(); 1089 s->indent();
1084 s->format(); 1090 s->format();
1085 indent(); 1091 indent();
1086 para->format(); 1092 para->format();
1087 } 1093 }
1088 } else { 1094 } else {
1089 QString str = para->string()->toString().mid( idx, 0xFFFFFF ); 1095 QString str = para->string()->toString().mid( idx, 0xFFFFFF );
1090 QTextParagraph *n = para->next(); 1096 QTextParagraph *n = para->next();
1091 QTextParagraph *s = para->document()->createParagraph( para->document(), para, n, updateIds ); 1097 QTextParagraph *s = para->document()->createParagraph( para->document(), para, n, updateIds );
1092 s->copyParagData( para ); 1098 s->copyParagData( para );
1093 s->remove( 0, 1 ); 1099 s->remove( 0, 1 );
1094 s->append( str, TRUE ); 1100 s->append( str, TRUE );
1095 for ( uint i = 0; i < str.length(); ++i ) { 1101 for ( uint i = 0; i < str.length(); ++i ) {
1096 QTextStringChar* tsc = para->at( idx + i ); 1102 QTextStringChar* tsc = para->at( idx + i );
1097 s->setFormat( i, 1, tsc->format(), TRUE ); 1103 s->setFormat( i, 1, tsc->format(), TRUE );
1098 if ( tsc->isCustom() ) { 1104 if ( tsc->isCustom() ) {
1099 QTextCustomItem * item = tsc->customItem(); 1105 QTextCustomItem * item = tsc->customItem();
1100 s->at( i )->setCustomItem( item ); 1106 s->at( i )->setCustomItem( item );
1101 tsc->loseCustomItem(); 1107 tsc->loseCustomItem();
1102 } 1108 }
1103 if ( tsc->isAnchor() ) 1109 if ( tsc->isAnchor() )
1104 s->at( i )->setAnchor( tsc->anchorName(), 1110 s->at( i )->setAnchor( tsc->anchorName(),
1105 tsc->anchorHref() ); 1111 tsc->anchorHref() );
1106 } 1112 }
1107 para->truncate( idx ); 1113 para->truncate( idx );
1108 if ( ind ) { 1114 if ( ind ) {
1109 int oi, ni; 1115 int oi, ni;
1110 s->indent( &oi, &ni ); 1116 s->indent( &oi, &ni );
1111 para = s; 1117 para = s;
1112 idx = ni; 1118 idx = ni;
1113 } else { 1119 } else {
1114 para = s; 1120 para = s;
1115 idx = 0; 1121 idx = 0;
1116 } 1122 }
1117 } 1123 }
1118 1124
1119 invalidateNested(); 1125 invalidateNested();
1120} 1126}
1121 1127
1122bool QTextCursor::remove() 1128bool QTextCursor::remove()
1123{ 1129{
1124 tmpIndex = -1; 1130 tmpIndex = -1;
1125 if ( !atParagEnd() ) { 1131 if ( !atParagEnd() ) {
1126 para->remove( idx, 1 ); 1132 para->remove( idx, 1 );
1127 int h = para->rect().height(); 1133 int h = para->rect().height();
1128 para->format( -1, TRUE ); 1134 para->format( -1, TRUE );
1129 if ( h != para->rect().height() ) 1135 if ( h != para->rect().height() )
1130 invalidateNested(); 1136 invalidateNested();
1131 else if ( para->document() && para->document()->parent() ) 1137 else if ( para->document() && para->document()->parent() )
1132 para->document()->nextDoubleBuffered = TRUE; 1138 para->document()->nextDoubleBuffered = TRUE;
1133 return FALSE; 1139 return FALSE;
1134 } else if ( para->next() ) { 1140 } else if ( para->next() ) {
1135 para->join( para->next() ); 1141 para->join( para->next() );
1136 invalidateNested(); 1142 invalidateNested();
1137 return TRUE; 1143 return TRUE;
1138 } 1144 }
1139 return FALSE; 1145 return FALSE;
1140} 1146}
1141 1147
1142void QTextCursor::indent() 1148void QTextCursor::indent()
1143{ 1149{
1144 int oi = 0, ni = 0; 1150 int oi = 0, ni = 0;
1145 para->indent( &oi, &ni ); 1151 para->indent( &oi, &ni );
1146 if ( oi == ni ) 1152 if ( oi == ni )
1147 return; 1153 return;
1148 1154
1149 if ( idx >= oi ) 1155 if ( idx >= oi )
1150 idx += ni - oi; 1156 idx += ni - oi;
1151 else 1157 else
1152 idx = ni; 1158 idx = ni;
1153} 1159}
1154 1160
1155// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1161// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1156 1162
1157QTextDocument::QTextDocument( QTextDocument *p ) 1163QTextDocument::QTextDocument( QTextDocument *p )
1158 : par( p ), parentPar( 0 ), tc( 0 ), tArray( 0 ), tStopWidth( 0 ) 1164 : par( p ), parentPar( 0 ), tc( 0 ), tArray( 0 ), tStopWidth( 0 )
1159{ 1165{
1160 fCollection = new QTextFormatCollection; 1166 fCollection = new QTextFormatCollection;
1161 init(); 1167 init();
1162} 1168}
1163 1169
1164QTextDocument::QTextDocument( QTextDocument *p, QTextFormatCollection *f ) 1170QTextDocument::QTextDocument( QTextDocument *p, QTextFormatCollection *f )
1165 : par( p ), parentPar( 0 ), tc( 0 ), tArray( 0 ), tStopWidth( 0 ) 1171 : par( p ), parentPar( 0 ), tc( 0 ), tArray( 0 ), tStopWidth( 0 )
1166{ 1172{
1167 fCollection = f; 1173 fCollection = f;
1168 init(); 1174 init();
1169} 1175}
1170 1176
1171void QTextDocument::init() 1177void QTextDocument::init()
1172{ 1178{
1173 oTextValid = TRUE; 1179 oTextValid = TRUE;
1174 mightHaveCustomItems = FALSE; 1180 mightHaveCustomItems = FALSE;
1175 if ( par ) 1181 if ( par )
1176 par->insertChild( this ); 1182 par->insertChild( this );
1177 pProcessor = 0; 1183 pProcessor = 0;
1178 useFC = TRUE; 1184 useFC = TRUE;
1179 pFormatter = 0; 1185 pFormatter = 0;
1180 indenter = 0; 1186 indenter = 0;
1181 fParag = 0; 1187 fParag = 0;
1182 txtFormat = Qt::AutoText; 1188 txtFormat = Qt::AutoText;
1183 preferRichText = FALSE; 1189 preferRichText = FALSE;
1184 pages = FALSE; 1190 pages = FALSE;
1185 focusIndicator.parag = 0; 1191 focusIndicator.parag = 0;
1186 minw = 0; 1192 minw = 0;
1187 wused = 0; 1193 wused = 0;
1188 minwParag = curParag = 0; 1194 minwParag = curParag = 0;
1189 align = AlignAuto; 1195 align = AlignAuto;
1190 nSelections = 1; 1196 nSelections = 1;
1191 1197
1192 setStyleSheet( QStyleSheet::defaultSheet() ); 1198 setStyleSheet( QStyleSheet::defaultSheet() );
1193 factory_ = QMimeSourceFactory::defaultFactory(); 1199 factory_ = QMimeSourceFactory::defaultFactory();
1194 contxt = QString::null; 1200 contxt = QString::null;
1195 1201
1196 underlLinks = par ? par->underlLinks : TRUE; 1202 underlLinks = par ? par->underlLinks : TRUE;
1197 backBrush = 0; 1203 backBrush = 0;
1198 buf_pixmap = 0; 1204 buf_pixmap = 0;
1199 nextDoubleBuffered = FALSE; 1205 nextDoubleBuffered = FALSE;
1200 1206
1201 if ( par ) 1207 if ( par )
1202 withoutDoubleBuffer = par->withoutDoubleBuffer; 1208 withoutDoubleBuffer = par->withoutDoubleBuffer;
1203 else 1209 else
1204 withoutDoubleBuffer = FALSE; 1210 withoutDoubleBuffer = FALSE;
1205 1211
1206 lParag = fParag = createParagraph( this, 0, 0 ); 1212 lParag = fParag = createParagraph( this, 0, 0 );
1207 1213
1208 cx = 0; 1214 cx = 0;
1209 cy = 2; 1215 cy = 2;
1210 if ( par ) 1216 if ( par )
1211 cx = cy = 0; 1217 cx = cy = 0;
1212 cw = 600; 1218 cw = 600;
1213 vw = 0; 1219 vw = 0;
1214 flow_ = new QTextFlow; 1220 flow_ = new QTextFlow;
1215 flow_->setWidth( cw ); 1221 flow_->setWidth( cw );
1216 1222
1217 leftmargin = rightmargin = 4; 1223 leftmargin = rightmargin = 4;
1218 scaleFontsFactor = 1; 1224 scaleFontsFactor = 1;
1219 1225
1220 1226
1221 selectionColors[ Standard ] = QApplication::palette().color( QPalette::Active, QColorGroup::Highlight ); 1227 selectionColors[ Standard ] = QApplication::palette().color( QPalette::Active, QColorGroup::Highlight );
1222 selectionText[ Standard ] = TRUE; 1228 selectionText[ Standard ] = TRUE;
1223 commandHistory = new QTextCommandHistory( 100 ); 1229 commandHistory = new QTextCommandHistory( 100 );
1224 tStopWidth = formatCollection()->defaultFormat()->width( 'x' ) * 8; 1230 tStopWidth = formatCollection()->defaultFormat()->width( 'x' ) * 8;
1225} 1231}
1226 1232
1227QTextDocument::~QTextDocument() 1233QTextDocument::~QTextDocument()
1228{ 1234{
1229 if ( par ) 1235 if ( par )
1230 par->removeChild( this ); 1236 par->removeChild( this );
1231 clear(); 1237 clear();
1232 delete commandHistory; 1238 delete commandHistory;
1233 delete flow_; 1239 delete flow_;
1234 if ( !par ) 1240 if ( !par )
1235 delete pFormatter; 1241 delete pFormatter;
1236 delete fCollection; 1242 delete fCollection;
1237 delete pProcessor; 1243 delete pProcessor;
1238 delete buf_pixmap; 1244 delete buf_pixmap;
1239 delete indenter; 1245 delete indenter;
1240 delete backBrush; 1246 delete backBrush;
1241 if ( tArray ) 1247 if ( tArray )
1242 delete [] tArray; 1248 delete [] tArray;
1243} 1249}
1244 1250
1245void QTextDocument::clear( bool createEmptyParag ) 1251void QTextDocument::clear( bool createEmptyParag )
1246{ 1252{
1247 if ( flow_ ) 1253 if ( flow_ )
1248 flow_->clear(); 1254 flow_->clear();
1249 while ( fParag ) { 1255 while ( fParag ) {
1250 QTextParagraph *p = fParag->next(); 1256 QTextParagraph *p = fParag->next();
1251 delete fParag; 1257 delete fParag;
1252 fParag = p; 1258 fParag = p;
1253 } 1259 }
1254 fParag = lParag = 0; 1260 fParag = lParag = 0;
1255 if ( createEmptyParag ) 1261 if ( createEmptyParag )
1256 fParag = lParag = createParagraph( this ); 1262 fParag = lParag = createParagraph( this );
1257 selections.clear(); 1263 selections.clear();
1258 oText = QString::null; 1264 oText = QString::null;
1259 oTextValid = TRUE; 1265 oTextValid = TRUE;
1260} 1266}
1261 1267
1262int QTextDocument::widthUsed() const 1268int QTextDocument::widthUsed() const
1263{ 1269{
1264 return wused + border_tolerance; 1270 return wused + border_tolerance;
1265} 1271}
1266 1272
1267int QTextDocument::height() const 1273int QTextDocument::height() const
1268{ 1274{
1269 int h = 0; 1275 int h = 0;
1270 if ( lParag ) 1276 if ( lParag )
1271 h = lParag->rect().top() + lParag->rect().height() + 1; 1277 h = lParag->rect().top() + lParag->rect().height() + 1;
1272 int fh = flow_->boundingRect().bottom(); 1278 int fh = flow_->boundingRect().bottom();
1273 return QMAX( h, fh ); 1279 return QMAX( h, fh );
1274} 1280}
1275 1281
1276 1282
1277 1283
1278QTextParagraph *QTextDocument::createParagraph( QTextDocument *d, QTextParagraph *pr, QTextParagraph *nx, bool updateIds ) 1284QTextParagraph *QTextDocument::createParagraph( QTextDocument *d, QTextParagraph *pr, QTextParagraph *nx, bool updateIds )
1279{ 1285{
1280 return new QTextParagraph( d, pr, nx, updateIds ); 1286 return new QTextParagraph( d, pr, nx, updateIds );
1281} 1287}
1282 1288
1283bool QTextDocument::setMinimumWidth( int needed, int used, QTextParagraph *p ) 1289bool QTextDocument::setMinimumWidth( int needed, int used, QTextParagraph *p )
1284{ 1290{
1285 if ( needed == -1 ) { 1291 if ( needed == -1 ) {
1286 minw = 0; 1292 minw = 0;
1287 wused = 0; 1293 wused = 0;
1288 p = 0; 1294 p = 0;
1289 } 1295 }
1290 if ( p == minwParag ) { 1296 if ( p == minwParag ) {
1291 minw = needed; 1297 minw = needed;
1292 emit minimumWidthChanged( minw ); 1298 emit minimumWidthChanged( minw );
1293 } else if ( needed > minw ) { 1299 } else if ( needed > minw ) {
1294 minw = needed; 1300 minw = needed;
1295 minwParag = p; 1301 minwParag = p;
1296 emit minimumWidthChanged( minw ); 1302 emit minimumWidthChanged( minw );
1297 } 1303 }
1298 wused = QMAX( wused, used ); 1304 wused = QMAX( wused, used );
1299 wused = QMAX( wused, minw ); 1305 wused = QMAX( wused, minw );
1300 cw = QMAX( minw, cw ); 1306 cw = QMAX( minw, cw );
1301 return TRUE; 1307 return TRUE;
1302} 1308}
1303 1309
1304void QTextDocument::setPlainText( const QString &text ) 1310void QTextDocument::setPlainText( const QString &text )
1305{ 1311{
1306 clear(); 1312 clear();
1307 preferRichText = FALSE; 1313 preferRichText = FALSE;
1308 oTextValid = TRUE; 1314 oTextValid = TRUE;
1309 oText = text; 1315 oText = text;
1310 1316
1311 int lastNl = 0; 1317 int lastNl = 0;
1312 int nl = text.find( '\n' ); 1318 int nl = text.find( '\n' );
1313 if ( nl == -1 ) { 1319 if ( nl == -1 ) {
1314 lParag = createParagraph( this, lParag, 0 ); 1320 lParag = createParagraph( this, lParag, 0 );
1315 if ( !fParag ) 1321 if ( !fParag )
1316 fParag = lParag; 1322 fParag = lParag;
1317 QString s = text; 1323 QString s = text;
1318 if ( !s.isEmpty() ) { 1324 if ( !s.isEmpty() ) {
1319 if ( s[ (int)s.length() - 1 ] == '\r' ) 1325 if ( s[ (int)s.length() - 1 ] == '\r' )
1320 s.remove( s.length() - 1, 1 ); 1326 s.remove( s.length() - 1, 1 );
1321 lParag->append( s ); 1327 lParag->append( s );
1322 } 1328 }
1323 } else { 1329 } else {
1324 for (;;) { 1330 for (;;) {
1325 lParag = createParagraph( this, lParag, 0 ); 1331 lParag = createParagraph( this, lParag, 0 );
1326 if ( !fParag ) 1332 if ( !fParag )
1327 fParag = lParag; 1333 fParag = lParag;
1328 QString s = text.mid( lastNl, nl - lastNl ); 1334 QString s = text.mid( lastNl, nl - lastNl );
1329 if ( !s.isEmpty() ) { 1335 if ( !s.isEmpty() ) {
1330 if ( s[ (int)s.length() - 1 ] == '\r' ) 1336 if ( s[ (int)s.length() - 1 ] == '\r' )
1331 s.remove( s.length() - 1, 1 ); 1337 s.remove( s.length() - 1, 1 );
1332 lParag->append( s ); 1338 lParag->append( s );
1333 } 1339 }
1334 if ( nl == 0xffffff ) 1340 if ( nl == 0xffffff )
1335 break; 1341 break;
1336 lastNl = nl + 1; 1342 lastNl = nl + 1;
1337 nl = text.find( '\n', nl + 1 ); 1343 nl = text.find( '\n', nl + 1 );
1338 if ( nl == -1 ) 1344 if ( nl == -1 )
1339 nl = 0xffffff; 1345 nl = 0xffffff;
1340 } 1346 }
1341 } 1347 }
1342 if ( !lParag ) 1348 if ( !lParag )
1343 lParag = fParag = createParagraph( this, 0, 0 ); 1349 lParag = fParag = createParagraph( this, 0, 0 );
1344} 1350}
1345 1351
1346struct Q_EXPORT QTextDocumentTag { 1352struct Q_EXPORT QTextDocumentTag {
1347 QTextDocumentTag(){} 1353 QTextDocumentTag(){}
1348 QTextDocumentTag( const QString&n, const QStyleSheetItem* s, const QTextFormat& f ) 1354 QTextDocumentTag( const QString&n, const QStyleSheetItem* s, const QTextFormat& f )
1349 :name(n),style(s), format(f), alignment(Qt3::AlignAuto), direction(QChar::DirON),liststyle(QStyleSheetItem::ListDisc) { 1355 :name(n),style(s), format(f), alignment(Qt3::AlignAuto), direction(QChar::DirON),liststyle(QStyleSheetItem::ListDisc) {
1350 wsm = QStyleSheetItem::WhiteSpaceNormal; 1356 wsm = QStyleSheetItem::WhiteSpaceNormal;
1351 } 1357 }
1352 QString name; 1358 QString name;
1353 const QStyleSheetItem* style; 1359 const QStyleSheetItem* style;
1354 QString anchorHref; 1360 QString anchorHref;
1355 QStyleSheetItem::WhiteSpaceMode wsm; 1361 QStyleSheetItem::WhiteSpaceMode wsm;
1356 QTextFormat format; 1362 QTextFormat format;
1357 int alignment : 16; 1363 int alignment : 16;
1358 int direction : 5; 1364 int direction : 5;
1359 QStyleSheetItem::ListStyle liststyle; 1365 QStyleSheetItem::ListStyle liststyle;
1360 1366
1361 QTextDocumentTag( const QTextDocumentTag& t ) { 1367 QTextDocumentTag( const QTextDocumentTag& t ) {
1362 name = t.name; 1368 name = t.name;
1363 style = t.style; 1369 style = t.style;
1364 anchorHref = t.anchorHref; 1370 anchorHref = t.anchorHref;
1365 wsm = t.wsm; 1371 wsm = t.wsm;
1366 format = t.format; 1372 format = t.format;
1367 alignment = t.alignment; 1373 alignment = t.alignment;
1368 direction = t.direction; 1374 direction = t.direction;
1369 liststyle = t.liststyle; 1375 liststyle = t.liststyle;
1370 } 1376 }
1371 QTextDocumentTag& operator=(const QTextDocumentTag& t) { 1377 QTextDocumentTag& operator=(const QTextDocumentTag& t) {
1372 name = t.name; 1378 name = t.name;
1373 style = t.style; 1379 style = t.style;
1374 anchorHref = t.anchorHref; 1380 anchorHref = t.anchorHref;
1375 wsm = t.wsm; 1381 wsm = t.wsm;
1376 format = t.format; 1382 format = t.format;
1377 alignment = t.alignment; 1383 alignment = t.alignment;
1378 direction = t.direction; 1384 direction = t.direction;
1379 liststyle = t.liststyle; 1385 liststyle = t.liststyle;
1380 return *this; 1386 return *this;
1381 } 1387 }
1382 1388
1383#if defined(Q_FULL_TEMPLATE_INSTANTIATION) 1389#if defined(Q_FULL_TEMPLATE_INSTANTIATION)
1384 bool operator==( const QTextDocumentTag& ) const { return FALSE; } 1390 bool operator==( const QTextDocumentTag& ) const { return FALSE; }
1385#endif 1391#endif
1386}; 1392};
1387 1393
1388 1394
1389#define NEWPAR do{ if ( !hasNewPar) { \ 1395#define NEWPAR do{ if ( !hasNewPar) { \
1390 if ( !textEditMode && curpar && curpar->length()>1 && curpar->at( curpar->length()-2)->c == QChar_linesep ) \ 1396 if ( !textEditMode && curpar && curpar->length()>1 && curpar->at( curpar->length()-2)->c == QChar_linesep ) \
1391 curpar->remove( curpar->length()-2, 1 ); \ 1397 curpar->remove( curpar->length()-2, 1 ); \
1392 curpar = createParagraph( this, curpar, curpar->next() ); styles.append( vec ); vec = 0;} \ 1398 curpar = createParagraph( this, curpar, curpar->next() ); styles.append( vec ); vec = 0;} \
1393 hasNewPar = TRUE; \ 1399 hasNewPar = TRUE; \
1394 curpar->rtext = TRUE; \ 1400 curpar->rtext = TRUE; \
1395 curpar->align = curtag.alignment; \ 1401 curpar->align = curtag.alignment; \
1396 curpar->lstyle = curtag.liststyle; \ 1402 curpar->lstyle = curtag.liststyle; \
1397 curpar->litem = ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ); \ 1403 curpar->litem = ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ); \
1398 curpar->str->setDirection( (QChar::Direction)curtag.direction ); \ 1404 curpar->str->setDirection( (QChar::Direction)curtag.direction ); \
1399 space = TRUE; \ 1405 space = TRUE; \
1400 delete vec; vec = new QPtrVector<QStyleSheetItem>( (uint)tags.count() + 1); \ 1406 delete vec; vec = new QPtrVector<QStyleSheetItem>( (uint)tags.count() + 1); \
1401 int i = 0; \ 1407 int i = 0; \
1402 for ( QValueStack<QTextDocumentTag>::Iterator it = tags.begin(); it != tags.end(); ++it ) \ 1408 for ( QValueStack<QTextDocumentTag>::Iterator it = tags.begin(); it != tags.end(); ++it ) \
1403 vec->insert( i++, (*it).style ); \ 1409 vec->insert( i++, (*it).style ); \
1404 vec->insert( i, curtag.style ); \ 1410 vec->insert( i, curtag.style ); \
1405 }while(FALSE) 1411 }while(FALSE)
1406 1412
1407 1413
1408void QTextDocument::setRichText( const QString &text, const QString &context ) 1414void QTextDocument::setRichText( const QString &text, const QString &context )
1409{ 1415{
1410 if ( !context.isEmpty() ) 1416 if ( !context.isEmpty() )
1411 setContext( context ); 1417 setContext( context );
1412 clear(); 1418 clear();
1413 fParag = lParag = createParagraph( this ); 1419 fParag = lParag = createParagraph( this );
1414 oTextValid = TRUE; 1420 oTextValid = TRUE;
1415 oText = text; 1421 oText = text;
1416 setRichTextInternal( text ); 1422 setRichTextInternal( text );
1417 fParag->rtext = TRUE; 1423 fParag->rtext = TRUE;
1418} 1424}
1419 1425
1420void QTextDocument::setRichTextInternal( const QString &text, QTextCursor* cursor ) 1426void QTextDocument::setRichTextInternal( const QString &text, QTextCursor* cursor )
1421{ 1427{
1422 QTextParagraph* curpar = lParag; 1428 QTextParagraph* curpar = lParag;
1423 int pos = 0; 1429 int pos = 0;
1424 QValueStack<QTextDocumentTag> tags; 1430 QValueStack<QTextDocumentTag> tags;
1425 QTextDocumentTag initag( "", sheet_->item(""), *formatCollection()->defaultFormat() ); 1431 QTextDocumentTag initag( "", sheet_->item(""), *formatCollection()->defaultFormat() );
1426 QTextDocumentTag curtag = initag; 1432 QTextDocumentTag curtag = initag;
1427 bool space = TRUE; 1433 bool space = TRUE;
1428 bool canMergeLi = FALSE; 1434 bool canMergeLi = FALSE;
1429 1435
1430 bool textEditMode = FALSE; 1436 bool textEditMode = FALSE;
1431 1437
1432 const QChar* doc = text.unicode(); 1438 const QChar* doc = text.unicode();
1433 int length = text.length(); 1439 int length = text.length();
1434 bool hasNewPar = curpar->length() <= 1; 1440 bool hasNewPar = curpar->length() <= 1;
1435 QString anchorName; 1441 QString anchorName;
1436 1442
1437 // style sheet handling for margin and line spacing calculation below 1443 // style sheet handling for margin and line spacing calculation below
1438 QTextParagraph* stylesPar = curpar; 1444 QTextParagraph* stylesPar = curpar;
1439 QPtrVector<QStyleSheetItem>* vec = 0; 1445 QPtrVector<QStyleSheetItem>* vec = 0;
1440 QPtrList< QPtrVector<QStyleSheetItem> > styles; 1446 QPtrList< QPtrVector<QStyleSheetItem> > styles;
1441 styles.setAutoDelete( TRUE ); 1447 styles.setAutoDelete( TRUE );
1442 1448
1443 if ( cursor ) { 1449 if ( cursor ) {
1444 cursor->splitAndInsertEmptyParagraph(); 1450 cursor->splitAndInsertEmptyParagraph();
1445 QTextCursor tmp = *cursor; 1451 QTextCursor tmp = *cursor;
1446 tmp.gotoPreviousLetter(); 1452 tmp.gotoPreviousLetter();
1447 stylesPar = curpar = tmp.paragraph(); 1453 stylesPar = curpar = tmp.paragraph();
1448 hasNewPar = TRUE; 1454 hasNewPar = TRUE;
1449 textEditMode = TRUE; 1455 textEditMode = TRUE;
1450 } else { 1456 } else {
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;
1647 curtag.style = nstyle; 1653 curtag.style = nstyle;
1648 if ( int(nstyle->whiteSpaceMode()) != QStyleSheetItem::Undefined ) 1654 if ( int(nstyle->whiteSpaceMode()) != QStyleSheetItem::Undefined )
1649 curtag.wsm = nstyle->whiteSpaceMode(); 1655 curtag.wsm = nstyle->whiteSpaceMode();
1650 1656
1651 /* ignore whitespace for inline elements if there 1657 /* ignore whitespace for inline elements if there
1652 was already one*/ 1658 was already one*/
1653 if ( !textEditMode && curtag.wsm == QStyleSheetItem::WhiteSpaceNormal 1659 if ( !textEditMode && curtag.wsm == QStyleSheetItem::WhiteSpaceNormal
1654 && ( space || nstyle->displayMode() != QStyleSheetItem::DisplayInline ) ) 1660 && ( space || nstyle->displayMode() != QStyleSheetItem::DisplayInline ) )
1655 eatSpace( doc, length, pos ); 1661 eatSpace( doc, length, pos );
1656 1662
1657 curtag.format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor ); 1663 curtag.format = curtag.format.makeTextFormat( nstyle, attr, scaleFontsFactor );
1658 if ( nstyle->isAnchor() ) { 1664 if ( nstyle->isAnchor() ) {
1659 if ( !anchorName.isEmpty() ) 1665 if ( !anchorName.isEmpty() )
1660 anchorName += "#" + attr["name"]; 1666 anchorName += "#" + attr["name"];
1661 else 1667 else
1662 anchorName = attr["name"]; 1668 anchorName = attr["name"];
1663 curtag.anchorHref = attr["href"]; 1669 curtag.anchorHref = attr["href"];
1664 } 1670 }
1665 1671
1666 if ( nstyle->alignment() != QStyleSheetItem::Undefined ) 1672 if ( nstyle->alignment() != QStyleSheetItem::Undefined )
1667 curtag.alignment = nstyle->alignment(); 1673 curtag.alignment = nstyle->alignment();
1668 1674
1669 if ( (int) nstyle->listStyle() != QStyleSheetItem::Undefined ) 1675 if ( (int) nstyle->listStyle() != QStyleSheetItem::Undefined )
1670 curtag.liststyle = nstyle->listStyle(); 1676 curtag.liststyle = nstyle->listStyle();
1671 1677
1672 if ( nstyle->displayMode() == QStyleSheetItem::DisplayBlock 1678 if ( nstyle->displayMode() == QStyleSheetItem::DisplayBlock
1673 || nstyle->displayMode() == QStyleSheetItem::DisplayListItem ) { 1679 || nstyle->displayMode() == QStyleSheetItem::DisplayListItem ) {
1674 1680
1675 if ( nstyle->name() == "ol" || nstyle->name() == "ul" || nstyle->name() == "li") { 1681 if ( nstyle->name() == "ol" || nstyle->name() == "ul" || nstyle->name() == "li") {
1676 QString type = attr["type"]; 1682 QString type = attr["type"];
1677 if ( !type.isEmpty() ) { 1683 if ( !type.isEmpty() ) {
1678 if ( type == "1" ) { 1684 if ( type == "1" ) {
1679 curtag.liststyle = QStyleSheetItem::ListDecimal; 1685 curtag.liststyle = QStyleSheetItem::ListDecimal;
1680 } else if ( type == "a" ) { 1686 } else if ( type == "a" ) {
1681 curtag.liststyle = QStyleSheetItem::ListLowerAlpha; 1687 curtag.liststyle = QStyleSheetItem::ListLowerAlpha;
1682 } else if ( type == "A" ) { 1688 } else if ( type == "A" ) {
1683 curtag.liststyle = QStyleSheetItem::ListUpperAlpha; 1689 curtag.liststyle = QStyleSheetItem::ListUpperAlpha;
1684 } else { 1690 } else {
1685 type = type.lower(); 1691 type = type.lower();
1686 if ( type == "square" ) 1692 if ( type == "square" )
1687 curtag.liststyle = QStyleSheetItem::ListSquare; 1693 curtag.liststyle = QStyleSheetItem::ListSquare;
1688 else if ( type == "disc" ) 1694 else if ( type == "disc" )
1689 curtag.liststyle = QStyleSheetItem::ListDisc; 1695 curtag.liststyle = QStyleSheetItem::ListDisc;
1690 else if ( type == "circle" ) 1696 else if ( type == "circle" )
1691 curtag.liststyle = QStyleSheetItem::ListCircle; 1697 curtag.liststyle = QStyleSheetItem::ListCircle;
1692 } 1698 }
1693 } 1699 }
1694 } 1700 }
1695 1701
1696 1702
1697 /* Internally we treat ordered and bullet 1703 /* Internally we treat ordered and bullet
1698 lists the same for margin calculations. In 1704 lists the same for margin calculations. In
1699 order to have fast pointer compares in the 1705 order to have fast pointer compares in the
1700 xMargin() functions we restrict ourselves to 1706 xMargin() functions we restrict ourselves to
1701 <ol>. Once we calculate the margins in the 1707 <ol>. Once we calculate the margins in the
1702 parser rathern than later, the unelegance of 1708 parser rathern than later, the unelegance of
1703 this approach goes awy 1709 this approach goes awy
1704 */ 1710 */
1705 if ( nstyle->name() == "ul" ) 1711 if ( nstyle->name() == "ul" )
1706 curtag.style = sheet_->item( "ol" ); 1712 curtag.style = sheet_->item( "ol" );
1707 1713
1708 if ( attr.contains( "align" ) ) { 1714 if ( attr.contains( "align" ) ) {
1709 QString align = attr["align"]; 1715 QString align = attr["align"];
1710 if ( align == "center" ) 1716 if ( align == "center" )
1711 curtag.alignment = Qt::AlignCenter; 1717 curtag.alignment = Qt::AlignCenter;
1712 else if ( align == "right" ) 1718 else if ( align == "right" )
1713 curtag.alignment = Qt::AlignRight; 1719 curtag.alignment = Qt::AlignRight;
1714 else if ( align == "justify" ) 1720 else if ( align == "justify" )
1715 curtag.alignment = Qt3::AlignJustify; 1721 curtag.alignment = Qt3::AlignJustify;
1716 } 1722 }
1717 if ( attr.contains( "dir" ) ) { 1723 if ( attr.contains( "dir" ) ) {
1718 QString dir = attr["dir"]; 1724 QString dir = attr["dir"];
1719 if ( dir == "rtl" ) 1725 if ( dir == "rtl" )
1720 curtag.direction = QChar::DirR; 1726 curtag.direction = QChar::DirR;
1721 else if ( dir == "ltr" ) 1727 else if ( dir == "ltr" )
1722 curtag.direction = QChar::DirL; 1728 curtag.direction = QChar::DirL;
1723 } 1729 }
1724 1730
1725 NEWPAR; 1731 NEWPAR;
1726 1732
1727 if ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ) { 1733 if ( curtag.style->displayMode() == QStyleSheetItem::DisplayListItem ) {
1728 if ( attr.contains( "value " ) ) 1734 if ( attr.contains( "value " ) )
1729 curpar->setListValue( attr["value"].toInt() ); 1735 curpar->setListValue( attr["value"].toInt() );
1730 } 1736 }
1731 1737
1732 if ( attr.contains( "style" ) ) { 1738 if ( attr.contains( "style" ) ) {
1733 QString a = attr["style"]; 1739 QString a = attr["style"];
1734 bool ok = TRUE; 1740 bool ok = TRUE;
1735 for ( int s = 0; ok && s < a.contains(';')+1; s++ ) { 1741 for ( int s = 0; ok && s < a.contains(';')+1; s++ ) {
1736 QString style = QTextDocument::section( a, ";", s, s ); 1742 QString style = QTextDocument::section( a, ";", s, s );
1737 if ( style.startsWith("margin-top:" ) && QTextDocument::endsWith(style, "px") ) 1743 if ( style.startsWith("margin-top:" ) && QTextDocument::endsWith(style, "px") )
1738 curpar->utm = 1+style.mid(11, style.length() - 13).toInt(&ok); 1744 curpar->utm = 1+style.mid(11, style.length() - 13).toInt(&ok);
1739 else if ( style.startsWith("margin-bottom:" ) && QTextDocument::endsWith(style, "px") ) 1745 else if ( style.startsWith("margin-bottom:" ) && QTextDocument::endsWith(style, "px") )
1740 curpar->ubm = 1+style.mid(14, style.length() - 16).toInt(&ok); 1746 curpar->ubm = 1+style.mid(14, style.length() - 16).toInt(&ok);
1741 else if ( style.startsWith("margin-left:" ) && QTextDocument::endsWith(style, "px") ) 1747 else if ( style.startsWith("margin-left:" ) && QTextDocument::endsWith(style, "px") )
1742 curpar->ulm = 1+style.mid(12, style.length() - 14).toInt(&ok); 1748 curpar->ulm = 1+style.mid(12, style.length() - 14).toInt(&ok);
1743 else if ( style.startsWith("margin-right:" ) && QTextDocument::endsWith(style, "px") ) 1749 else if ( style.startsWith("margin-right:" ) && QTextDocument::endsWith(style, "px") )
1744 curpar->urm = 1+style.mid(13, style.length() - 15).toInt(&ok); 1750 curpar->urm = 1+style.mid(13, style.length() - 15).toInt(&ok);
1745 else if ( style.startsWith("text-indent:" ) && QTextDocument::endsWith(style, "px") ) 1751 else if ( style.startsWith("text-indent:" ) && QTextDocument::endsWith(style, "px") )
1746 curpar->uflm = 1+style.mid(12, style.length() - 14).toInt(&ok); 1752 curpar->uflm = 1+style.mid(12, style.length() - 14).toInt(&ok);
1747 } 1753 }
1748 if ( !ok ) // be pressmistic 1754 if ( !ok ) // be pressmistic
1749 curpar->utm = curpar->ubm = curpar->urm = curpar->ulm = 0; 1755 curpar->utm = curpar->ubm = curpar->urm = curpar->ulm = 0;
1750 } 1756 }
1751 } 1757 }
1752 } 1758 }
1753 } else { 1759 } else {
1754 QString tagname = parseCloseTag( doc, length, pos ); 1760 QString tagname = parseCloseTag( doc, length, pos );
1755 if ( tagname.isEmpty() ) 1761 if ( tagname.isEmpty() )
1756 continue; // nothing we could do with this, probably parse error 1762 continue; // nothing we could do with this, probably parse error
1757 if ( !sheet_->item( tagname ) ) // ignore unknown tags 1763 if ( !sheet_->item( tagname ) ) // ignore unknown tags
1758 continue; 1764 continue;
1759 1765
1760 // we close a block item. Since the text may continue, we need to have a new paragraph 1766 // we close a block item. Since the text may continue, we need to have a new paragraph
1761 bool needNewPar = curtag.style->displayMode() == QStyleSheetItem::DisplayBlock 1767 bool needNewPar = curtag.style->displayMode() == QStyleSheetItem::DisplayBlock
1762 || curtag.style->displayMode() == QStyleSheetItem::DisplayListItem; 1768 || curtag.style->displayMode() == QStyleSheetItem::DisplayListItem;
1763 1769
1764 1770
1765 // html slopiness: handle unbalanched tag closing 1771 // html slopiness: handle unbalanched tag closing
1766 while ( curtag.name != tagname ) { 1772 while ( curtag.name != tagname ) {
1767 QString msg; 1773 QString msg;
1768 msg.sprintf( "QText Warning: Document not valid ( '%s' not closed before '%s' #%d)", 1774 msg.sprintf( "QText Warning: Document not valid ( '%s' not closed before '%s' #%d)",
1769 curtag.name.ascii(), tagname.ascii(), pos); 1775 curtag.name.ascii(), tagname.ascii(), pos);
1770 sheet_->error( msg ); 1776 sheet_->error( msg );
1771 if ( tags.isEmpty() ) 1777 if ( tags.isEmpty() )
1772 break; 1778 break;
1773 curtag = tags.pop(); 1779 curtag = tags.pop();
1774 } 1780 }
1775 1781
1776 1782
1777 // close the tag 1783 // close the tag
1778 if ( !tags.isEmpty() ) 1784 if ( !tags.isEmpty() )
1779 curtag = tags.pop(); 1785 curtag = tags.pop();
1780 else 1786 else
1781 curtag = initag; 1787 curtag = initag;
1782 1788
1783 if ( needNewPar ) { 1789 if ( needNewPar ) {
1784 if ( textEditMode && tagname == "p" ) // preserve empty paragraphs 1790 if ( textEditMode && tagname == "p" ) // preserve empty paragraphs
1785 hasNewPar = FALSE; 1791 hasNewPar = FALSE;
1786 NEWPAR; 1792 NEWPAR;
1787 } 1793 }
1788 } 1794 }
1789 } else { 1795 } else {
1790 // normal contents 1796 // normal contents
1791 QString s; 1797 QString s;
1792 QChar c; 1798 QChar c;
1793 while ( pos < length && !hasPrefix(doc, length, pos, QChar('<') ) ){ 1799 while ( pos < length && !hasPrefix(doc, length, pos, QChar('<') ) ){
1794 if ( textEditMode ) { 1800 if ( textEditMode ) {
1795 // text edit mode: we handle all white space but ignore newlines 1801 // text edit mode: we handle all white space but ignore newlines
1796 c = parseChar( doc, length, pos, QStyleSheetItem::WhiteSpacePre ); 1802 c = parseChar( doc, length, pos, QStyleSheetItem::WhiteSpacePre );
1797 if ( c == QChar_linesep ) 1803 if ( c == QChar_linesep )
1798 break; 1804 break;
1799 } else { 1805 } else {
1800 int l = pos; 1806 int l = pos;
1801 c = parseChar( doc, length, pos, curtag.wsm ); 1807 c = parseChar( doc, length, pos, curtag.wsm );
1802 1808
1803 // in white space pre mode: treat any space as non breakable 1809 // in white space pre mode: treat any space as non breakable
1804 if ( c == ' ' && curtag.wsm == QStyleSheetItem::WhiteSpacePre ) 1810 if ( c == ' ' && curtag.wsm == QStyleSheetItem::WhiteSpacePre )
1805 c = QChar::nbsp; 1811 c = QChar::nbsp;
1806 1812
1807 if ( c == ' ' || c == QChar_linesep ) { 1813 if ( c == ' ' || c == QChar_linesep ) {
1808 /* avoid overlong paragraphs by forcing a new 1814 /* avoid overlong paragraphs by forcing a new
1809 paragraph after 4096 characters. This case can 1815 paragraph after 4096 characters. This case can
1810 occur when loading undiscovered plain text 1816 occur when loading undiscovered plain text
1811 documents in rich text mode. Instead of hanging 1817 documents in rich text mode. Instead of hanging
1812 forever, we do the trick. 1818 forever, we do the trick.
1813 */ 1819 */
1814 if ( curtag.wsm == QStyleSheetItem::WhiteSpaceNormal && s.length() > 4096 ) do { 1820 if ( curtag.wsm == QStyleSheetItem::WhiteSpaceNormal && s.length() > 4096 ) do {
1815 if ( doc[l] == '\n' ) { 1821 if ( doc[l] == '\n' ) {
1816 hasNewPar = FALSE; // for a new paragraph ... 1822 hasNewPar = FALSE; // for a new paragraph ...
1817 NEWPAR; 1823 NEWPAR;
1818 hasNewPar = FALSE; // ... and make it non-reusable 1824 hasNewPar = FALSE; // ... and make it non-reusable
1819 c = '\n'; // make sure we break below 1825 c = '\n'; // make sure we break below
1820 break; 1826 break;
1821 } 1827 }
1822 } while ( ++l < pos ); 1828 } while ( ++l < pos );
1823 } 1829 }
1824 } 1830 }
1825 1831
1826 if ( c == '\n' ) 1832 if ( c == '\n' )
1827 break; // break on newlines, pre delievers a QChar_linesep 1833 break; // break on newlines, pre delievers a QChar_linesep
1828 1834
1829 bool c_isSpace = c.isSpace() && c.unicode() != 0x00a0U && !textEditMode; 1835 bool c_isSpace = c.isSpace() && c.unicode() != 0x00a0U && !textEditMode;
1830 1836
1831 if ( curtag.wsm == QStyleSheetItem::WhiteSpaceNormal && c_isSpace && space ) 1837 if ( curtag.wsm == QStyleSheetItem::WhiteSpaceNormal && c_isSpace && space )
1832 continue; 1838 continue;
1833 if ( c == '\r' ) 1839 if ( c == '\r' )
1834 continue; 1840 continue;
1835 space = c_isSpace; 1841 space = c_isSpace;
1836 s += c; 1842 s += c;
1837 } 1843 }
1838 if ( !s.isEmpty() && curtag.style->displayMode() != QStyleSheetItem::DisplayNone ) { 1844 if ( !s.isEmpty() && curtag.style->displayMode() != QStyleSheetItem::DisplayNone ) {
1839 hasNewPar = FALSE; 1845 hasNewPar = FALSE;
1840 int index = QMAX( curpar->length(),1) - 1; 1846 int index = QMAX( curpar->length(),1) - 1;
1841 curpar->append( s ); 1847 curpar->append( s );
1842 QTextFormat* f = formatCollection()->format( &curtag.format ); 1848 QTextFormat* f = formatCollection()->format( &curtag.format );
1843 curpar->setFormat( index, s.length(), f, FALSE ); // do not use collection because we have done that already 1849 curpar->setFormat( index, s.length(), f, FALSE ); // do not use collection because we have done that already
1844 f->ref += s.length() -1; // that what friends are for... 1850 f->ref += s.length() -1; // that what friends are for...
1845 if ( !curtag.anchorHref.isEmpty() ) { 1851 if ( !curtag.anchorHref.isEmpty() ) {
1846 for ( int i = 0; i < int(s.length()); i++ ) 1852 for ( int i = 0; i < int(s.length()); i++ )
1847 curpar->at(index + i)->setAnchor( QString::null, curtag.anchorHref ); 1853 curpar->at(index + i)->setAnchor( QString::null, curtag.anchorHref );
1848 } 1854 }
1849 if ( !anchorName.isEmpty() ) { 1855 if ( !anchorName.isEmpty() ) {
1850 curpar->at(index)->setAnchor( anchorName, curpar->at(index)->anchorHref() ); 1856 curpar->at(index)->setAnchor( anchorName, curpar->at(index)->anchorHref() );
1851 anchorName = QString::null; 1857 anchorName = QString::null;
1852 } 1858 }
1853 } 1859 }
1854 } 1860 }
1855 } 1861 }
1856 if ( hasNewPar && curpar != fParag && !cursor ) { 1862 if ( hasNewPar && curpar != fParag && !cursor ) {
1857 // cleanup unused last paragraphs 1863 // cleanup unused last paragraphs
1858 curpar = curpar->p; 1864 curpar = curpar->p;
1859 delete curpar->n; 1865 delete curpar->n;
1860 } 1866 }
1861 if ( !anchorName.isEmpty() ) { 1867 if ( !anchorName.isEmpty() ) {
1862 curpar->at(curpar->length() - 1)->setAnchor( anchorName, curpar->at( curpar->length() - 1 )->anchorHref() ); 1868 curpar->at(curpar->length() - 1)->setAnchor( anchorName, curpar->at( curpar->length() - 1 )->anchorHref() );
1863 anchorName = QString::null; 1869 anchorName = QString::null;
1864 } 1870 }
1865 1871
1866 1872
1867 setRichTextMarginsInternal( styles, stylesPar ); 1873 setRichTextMarginsInternal( styles, stylesPar );
1868 1874
1869 if ( cursor ) { 1875 if ( cursor ) {
1870 cursor->gotoPreviousLetter(); 1876 cursor->gotoPreviousLetter();
1871 cursor->remove(); 1877 cursor->remove();
1872 } 1878 }
1873 1879
1874} 1880}
1875 1881
1876void QTextDocument::setRichTextMarginsInternal( QPtrList< QPtrVector<QStyleSheetItem> >& styles, QTextParagraph* stylesPar ) 1882void QTextDocument::setRichTextMarginsInternal( QPtrList< QPtrVector<QStyleSheetItem> >& styles, QTextParagraph* stylesPar )
1877{ 1883{
1878 // margin and line spacing calculation 1884 // margin and line spacing calculation
1879 QPtrVector<QStyleSheetItem>* prevStyle = 0; 1885 QPtrVector<QStyleSheetItem>* prevStyle = 0;
1880 QPtrVector<QStyleSheetItem>* curStyle = styles.first(); 1886 QPtrVector<QStyleSheetItem>* curStyle = styles.first();
1881 QPtrVector<QStyleSheetItem>* nextStyle = styles.next(); 1887 QPtrVector<QStyleSheetItem>* nextStyle = styles.next();
1882 while ( stylesPar ) { 1888 while ( stylesPar ) {
1883 if ( !curStyle ) { 1889 if ( !curStyle ) {
1884 stylesPar = stylesPar->next(); 1890 stylesPar = stylesPar->next();
1885 prevStyle = curStyle; 1891 prevStyle = curStyle;
1886 curStyle = nextStyle; 1892 curStyle = nextStyle;
1887 nextStyle = styles.next(); 1893 nextStyle = styles.next();
1888 continue; 1894 continue;
1889 } 1895 }
1890 1896
1891 int i, mar; 1897 int i, mar;
1892 QStyleSheetItem* mainStyle = curStyle->size() ? (*curStyle)[curStyle->size()-1] : 0; 1898 QStyleSheetItem* mainStyle = curStyle->size() ? (*curStyle)[curStyle->size()-1] : 0;
1893 if ( mainStyle && mainStyle->displayMode() == QStyleSheetItem::DisplayListItem ) 1899 if ( mainStyle && mainStyle->displayMode() == QStyleSheetItem::DisplayListItem )
1894 stylesPar->setListItem( TRUE ); 1900 stylesPar->setListItem( TRUE );
1895 int numLists = 0; 1901 int numLists = 0;
1896 for ( i = 0; i < (int)curStyle->size(); ++i ) { 1902 for ( i = 0; i < (int)curStyle->size(); ++i ) {
1897 if ( (*curStyle)[ i ]->displayMode() == QStyleSheetItem::DisplayBlock 1903 if ( (*curStyle)[ i ]->displayMode() == QStyleSheetItem::DisplayBlock
1898 && int((*curStyle)[ i ]->listStyle()) != QStyleSheetItem::Undefined ) 1904 && int((*curStyle)[ i ]->listStyle()) != QStyleSheetItem::Undefined )
1899 numLists++; 1905 numLists++;
1900 } 1906 }
1901 stylesPar->ldepth = numLists; 1907 stylesPar->ldepth = numLists;
1902 if ( stylesPar->next() && nextStyle ) { 1908 if ( stylesPar->next() && nextStyle ) {
1903 // also set the depth of the next paragraph, required for the margin calculation 1909 // also set the depth of the next paragraph, required for the margin calculation
1904 numLists = 0; 1910 numLists = 0;
1905 for ( i = 0; i < (int)nextStyle->size(); ++i ) { 1911 for ( i = 0; i < (int)nextStyle->size(); ++i ) {
1906 if ( (*nextStyle)[ i ]->displayMode() == QStyleSheetItem::DisplayBlock 1912 if ( (*nextStyle)[ i ]->displayMode() == QStyleSheetItem::DisplayBlock
1907 && int((*nextStyle)[ i ]->listStyle()) != QStyleSheetItem::Undefined ) 1913 && int((*nextStyle)[ i ]->listStyle()) != QStyleSheetItem::Undefined )
1908 numLists++; 1914 numLists++;
1909 } 1915 }
1910 stylesPar->next()->ldepth = numLists; 1916 stylesPar->next()->ldepth = numLists;
1911 } 1917 }
1912 1918
1913 // do the top margin 1919 // do the top margin
1914 QStyleSheetItem* item = mainStyle; 1920 QStyleSheetItem* item = mainStyle;
1915 int m; 1921 int m;
1916 if (stylesPar->utm > 0 ) { 1922 if (stylesPar->utm > 0 ) {
1917 m = stylesPar->utm-1; 1923 m = stylesPar->utm-1;
1918 stylesPar->utm = 0; 1924 stylesPar->utm = 0;
1919 } else { 1925 } else {
1920 m = QMAX(0, item->margin( QStyleSheetItem::MarginTop ) ); 1926 m = QMAX(0, item->margin( QStyleSheetItem::MarginTop ) );
1921 if ( item->displayMode() == QStyleSheetItem::DisplayListItem 1927 if ( item->displayMode() == QStyleSheetItem::DisplayListItem
1922 && stylesPar->ldepth ) 1928 && stylesPar->ldepth )
1923 m /= stylesPar->ldepth; 1929 m /= stylesPar->ldepth;
1924 } 1930 }
1925 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) { 1931 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) {
1926 item = (*curStyle)[ i ]; 1932 item = (*curStyle)[ i ];
1927 if ( prevStyle && i < (int) prevStyle->size() && 1933 if ( prevStyle && i < (int) prevStyle->size() &&
1928 ( item->displayMode() == QStyleSheetItem::DisplayBlock && 1934 ( item->displayMode() == QStyleSheetItem::DisplayBlock &&
1929 (*prevStyle)[ i ] == item ) ) 1935 (*prevStyle)[ i ] == item ) )
1930 break; 1936 break;
1931 // emulate CSS2' standard 0 vertical margin for multiple ul or ol tags 1937 // emulate CSS2' standard 0 vertical margin for multiple ul or ol tags
1932 if ( int(item->listStyle()) != QStyleSheetItem::Undefined && 1938 if ( int(item->listStyle()) != QStyleSheetItem::Undefined &&
1933 ( ( i> 0 && (*curStyle)[ i-1 ] == item ) || (*curStyle)[i+1] == item ) ) 1939 ( ( i> 0 && (*curStyle)[ i-1 ] == item ) || (*curStyle)[i+1] == item ) )
1934 continue; 1940 continue;
1935 mar = QMAX( 0, item->margin( QStyleSheetItem::MarginTop ) ); 1941 mar = QMAX( 0, item->margin( QStyleSheetItem::MarginTop ) );
1936 m = QMAX( m, mar ); 1942 m = QMAX( m, mar );
1937 } 1943 }
1938 stylesPar->utm = m - stylesPar->topMargin(); 1944 stylesPar->utm = m - stylesPar->topMargin();
1939 1945
1940 // do the bottom margin 1946 // do the bottom margin
1941 item = mainStyle; 1947 item = mainStyle;
1942 if (stylesPar->ubm > 0 ) { 1948 if (stylesPar->ubm > 0 ) {
1943 m = stylesPar->ubm-1; 1949 m = stylesPar->ubm-1;
1944 stylesPar->ubm = 0; 1950 stylesPar->ubm = 0;
1945 } else { 1951 } else {
1946 m = QMAX(0, item->margin( QStyleSheetItem::MarginBottom ) ); 1952 m = QMAX(0, item->margin( QStyleSheetItem::MarginBottom ) );
1947 if ( item->displayMode() == QStyleSheetItem::DisplayListItem 1953 if ( item->displayMode() == QStyleSheetItem::DisplayListItem
1948 && stylesPar->ldepth ) 1954 && stylesPar->ldepth )
1949 m /= stylesPar->ldepth; 1955 m /= stylesPar->ldepth;
1950 } 1956 }
1951 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) { 1957 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) {
1952 item = (*curStyle)[ i ]; 1958 item = (*curStyle)[ i ];
1953 if ( nextStyle && i < (int) nextStyle->size() && 1959 if ( nextStyle && i < (int) nextStyle->size() &&
1954 ( item->displayMode() == QStyleSheetItem::DisplayBlock && 1960 ( item->displayMode() == QStyleSheetItem::DisplayBlock &&
1955 (*nextStyle)[ i ] == item ) ) 1961 (*nextStyle)[ i ] == item ) )
1956 break; 1962 break;
1957 // emulate CSS2' standard 0 vertical margin for multiple ul or ol tags 1963 // emulate CSS2' standard 0 vertical margin for multiple ul or ol tags
1958 if ( int(item->listStyle()) != QStyleSheetItem::Undefined && 1964 if ( int(item->listStyle()) != QStyleSheetItem::Undefined &&
1959 ( ( i> 0 && (*curStyle)[ i-1 ] == item ) || (*curStyle)[i+1] == item ) ) 1965 ( ( i> 0 && (*curStyle)[ i-1 ] == item ) || (*curStyle)[i+1] == item ) )
1960 continue; 1966 continue;
1961 mar = QMAX(0, item->margin( QStyleSheetItem::MarginBottom ) ); 1967 mar = QMAX(0, item->margin( QStyleSheetItem::MarginBottom ) );
1962 m = QMAX( m, mar ); 1968 m = QMAX( m, mar );
1963 } 1969 }
1964 stylesPar->ubm = m - stylesPar->bottomMargin(); 1970 stylesPar->ubm = m - stylesPar->bottomMargin();
1965 1971
1966 // do the left margin, simplyfied 1972 // do the left margin, simplyfied
1967 item = mainStyle; 1973 item = mainStyle;
1968 if (stylesPar->ulm > 0 ) { 1974 if (stylesPar->ulm > 0 ) {
1969 m = stylesPar->ulm-1; 1975 m = stylesPar->ulm-1;
1970 stylesPar->ulm = 0; 1976 stylesPar->ulm = 0;
1971 } else { 1977 } else {
1972 m = QMAX( 0, item->margin( QStyleSheetItem::MarginLeft ) ); 1978 m = QMAX( 0, item->margin( QStyleSheetItem::MarginLeft ) );
1973 } 1979 }
1974 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) { 1980 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) {
1975 item = (*curStyle)[ i ]; 1981 item = (*curStyle)[ i ];
1976 m += QMAX( 0, item->margin( QStyleSheetItem::MarginLeft ) ); 1982 m += QMAX( 0, item->margin( QStyleSheetItem::MarginLeft ) );
1977 } 1983 }
1978 stylesPar->ulm = m - stylesPar->leftMargin(); 1984 stylesPar->ulm = m - stylesPar->leftMargin();
1979 1985
1980 // do the right margin, simplyfied 1986 // do the right margin, simplyfied
1981 item = mainStyle; 1987 item = mainStyle;
1982 if (stylesPar->urm > 0 ) { 1988 if (stylesPar->urm > 0 ) {
1983 m = stylesPar->urm-1; 1989 m = stylesPar->urm-1;
1984 stylesPar->urm = 0; 1990 stylesPar->urm = 0;
1985 } else { 1991 } else {
1986 m = QMAX( 0, item->margin( QStyleSheetItem::MarginRight ) ); 1992 m = QMAX( 0, item->margin( QStyleSheetItem::MarginRight ) );
1987 } 1993 }
1988 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) { 1994 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) {
1989 item = (*curStyle)[ i ]; 1995 item = (*curStyle)[ i ];
1990 m += QMAX( 0, item->margin( QStyleSheetItem::MarginRight ) ); 1996 m += QMAX( 0, item->margin( QStyleSheetItem::MarginRight ) );
1991 } 1997 }
1992 stylesPar->urm = m - stylesPar->rightMargin(); 1998 stylesPar->urm = m - stylesPar->rightMargin();
1993 1999
1994 // do the first line margin, which really should be called text-indent 2000 // do the first line margin, which really should be called text-indent
1995 item = mainStyle; 2001 item = mainStyle;
1996 if (stylesPar->uflm > 0 ) { 2002 if (stylesPar->uflm > 0 ) {
1997 m = stylesPar->uflm-1; 2003 m = stylesPar->uflm-1;
1998 stylesPar->uflm = 0; 2004 stylesPar->uflm = 0;
1999 } else { 2005 } else {
2000 m = QMAX( 0, item->margin( QStyleSheetItem::MarginFirstLine ) ); 2006 m = QMAX( 0, item->margin( QStyleSheetItem::MarginFirstLine ) );
2001 } 2007 }
2002 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) { 2008 for ( i = (int)curStyle->size() - 2 ; i >= 0; --i ) {
2003 item = (*curStyle)[ i ]; 2009 item = (*curStyle)[ i ];
2004 mar = QMAX( 0, item->margin( QStyleSheetItem::MarginFirstLine ) ); 2010 mar = QMAX( 0, item->margin( QStyleSheetItem::MarginFirstLine ) );
2005 m = QMAX( m, mar ); 2011 m = QMAX( m, mar );
2006 } 2012 }
2007 stylesPar->uflm =m - stylesPar->firstLineMargin(); 2013 stylesPar->uflm =m - stylesPar->firstLineMargin();
2008 2014
2009 // do the bogus line "spacing", which really is just an extra margin 2015 // do the bogus line "spacing", which really is just an extra margin
2010 item = mainStyle; 2016 item = mainStyle;
2011 for ( i = (int)curStyle->size() - 1 ; i >= 0; --i ) { 2017 for ( i = (int)curStyle->size() - 1 ; i >= 0; --i ) {
2012 item = (*curStyle)[ i ]; 2018 item = (*curStyle)[ i ];
2013 if ( item->lineSpacing() != QStyleSheetItem::Undefined ) { 2019 if ( item->lineSpacing() != QStyleSheetItem::Undefined ) {
2014 stylesPar->ulinespacing = item->lineSpacing(); 2020 stylesPar->ulinespacing = item->lineSpacing();
2015 if ( formatCollection() && 2021 if ( formatCollection() &&
2016 stylesPar->ulinespacing < formatCollection()->defaultFormat()->height() ) 2022 stylesPar->ulinespacing < formatCollection()->defaultFormat()->height() )
2017 stylesPar->ulinespacing += formatCollection()->defaultFormat()->height(); 2023 stylesPar->ulinespacing += formatCollection()->defaultFormat()->height();
2018 break; 2024 break;
2019 } 2025 }
2020 } 2026 }
2021 2027
2022 stylesPar = stylesPar->next(); 2028 stylesPar = stylesPar->next();
2023 prevStyle = curStyle; 2029 prevStyle = curStyle;
2024 curStyle = nextStyle; 2030 curStyle = nextStyle;
2025 nextStyle = styles.next(); 2031 nextStyle = styles.next();
2026 } 2032 }
2027} 2033}
2028 2034
2029void QTextDocument::setText( const QString &text, const QString &context ) 2035void QTextDocument::setText( const QString &text, const QString &context )
2030{ 2036{
2031 focusIndicator.parag = 0; 2037 focusIndicator.parag = 0;
2032 selections.clear(); 2038 selections.clear();
2033 if ( txtFormat == Qt::AutoText && QStyleSheet::mightBeRichText( text ) || 2039 if ( txtFormat == Qt::AutoText && QStyleSheet::mightBeRichText( text ) ||
2034 txtFormat == Qt::RichText ) 2040 txtFormat == Qt::RichText )
2035 setRichText( text, context ); 2041 setRichText( text, context );
2036 else 2042 else
2037 setPlainText( text ); 2043 setPlainText( text );
2038} 2044}
2039 2045
2040QString QTextDocument::plainText() const 2046QString QTextDocument::plainText() const
2041{ 2047{
2042 QString buffer; 2048 QString buffer;
2043 QString s; 2049 QString s;
2044 QTextParagraph *p = fParag; 2050 QTextParagraph *p = fParag;
2045 while ( p ) { 2051 while ( p ) {
2046 if ( !p->mightHaveCustomItems ) { 2052 if ( !p->mightHaveCustomItems ) {
2047 s = p->string()->toString(); 2053 s = p->string()->toString();
2048 } else { 2054 } else {
2049 for ( int i = 0; i < p->length() - 1; ++i ) { 2055 for ( int i = 0; i < p->length() - 1; ++i ) {
2050 if ( p->at( i )->isCustom() ) { 2056 if ( p->at( i )->isCustom() ) {
2051 if ( p->at( i )->customItem()->isNested() ) { 2057 if ( p->at( i )->customItem()->isNested() ) {
2052 s += "\n"; 2058 s += "\n";
2053 QTextTable *t = (QTextTable*)p->at( i )->customItem(); 2059 QTextTable *t = (QTextTable*)p->at( i )->customItem();
2054 QPtrList<QTextTableCell> cells = t->tableCells(); 2060 QPtrList<QTextTableCell> cells = t->tableCells();
2055 for ( QTextTableCell *c = cells.first(); c; c = cells.next() ) 2061 for ( QTextTableCell *c = cells.first(); c; c = cells.next() )
2056 s += c->richText()->plainText() + "\n"; 2062 s += c->richText()->plainText() + "\n";
2057 s += "\n"; 2063 s += "\n";
2058 } 2064 }
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;
2252 while ( s ) { 2258 while ( s ) {
2253 s->invalidate( 0 ); 2259 s->invalidate( 0 );
2254 s = s->next(); 2260 s = s->next();
2255 } 2261 }
2256} 2262}
2257 2263
2258void QTextDocument::selectionStart( int id, int &paragId, int &index ) 2264void QTextDocument::selectionStart( int id, int &paragId, int &index )
2259{ 2265{
2260 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id ); 2266 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id );
2261 if ( it == selections.end() ) 2267 if ( it == selections.end() )
2262 return; 2268 return;
2263 QTextDocumentSelection &sel = *it; 2269 QTextDocumentSelection &sel = *it;
2264 paragId = !sel.swapped ? sel.startCursor.paragraph()->paragId() : sel.endCursor.paragraph()->paragId(); 2270 paragId = !sel.swapped ? sel.startCursor.paragraph()->paragId() : sel.endCursor.paragraph()->paragId();
2265 index = !sel.swapped ? sel.startCursor.index() : sel.endCursor.index(); 2271 index = !sel.swapped ? sel.startCursor.index() : sel.endCursor.index();
2266} 2272}
2267 2273
2268QTextCursor QTextDocument::selectionStartCursor( int id) 2274QTextCursor QTextDocument::selectionStartCursor( int id)
2269{ 2275{
2270 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id ); 2276 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id );
2271 if ( it == selections.end() ) 2277 if ( it == selections.end() )
2272 return QTextCursor( this ); 2278 return QTextCursor( this );
2273 QTextDocumentSelection &sel = *it; 2279 QTextDocumentSelection &sel = *it;
2274 if ( sel.swapped ) 2280 if ( sel.swapped )
2275 return sel.endCursor; 2281 return sel.endCursor;
2276 return sel.startCursor; 2282 return sel.startCursor;
2277} 2283}
2278 2284
2279QTextCursor QTextDocument::selectionEndCursor( int id) 2285QTextCursor QTextDocument::selectionEndCursor( int id)
2280{ 2286{
2281 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id ); 2287 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id );
2282 if ( it == selections.end() ) 2288 if ( it == selections.end() )
2283 return QTextCursor( this ); 2289 return QTextCursor( this );
2284 QTextDocumentSelection &sel = *it; 2290 QTextDocumentSelection &sel = *it;
2285 if ( !sel.swapped ) 2291 if ( !sel.swapped )
2286 return sel.endCursor; 2292 return sel.endCursor;
2287 return sel.startCursor; 2293 return sel.startCursor;
2288} 2294}
2289 2295
2290void QTextDocument::selectionEnd( int id, int &paragId, int &index ) 2296void QTextDocument::selectionEnd( int id, int &paragId, int &index )
2291{ 2297{
2292 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id ); 2298 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id );
2293 if ( it == selections.end() ) 2299 if ( it == selections.end() )
2294 return; 2300 return;
2295 QTextDocumentSelection &sel = *it; 2301 QTextDocumentSelection &sel = *it;
2296 paragId = sel.swapped ? sel.startCursor.paragraph()->paragId() : sel.endCursor.paragraph()->paragId(); 2302 paragId = sel.swapped ? sel.startCursor.paragraph()->paragId() : sel.endCursor.paragraph()->paragId();
2297 index = sel.swapped ? sel.startCursor.index() : sel.endCursor.index(); 2303 index = sel.swapped ? sel.startCursor.index() : sel.endCursor.index();
2298} 2304}
2299 2305
2300void QTextDocument::addSelection( int id ) 2306void QTextDocument::addSelection( int id )
2301{ 2307{
2302 nSelections = QMAX( nSelections, id + 1 ); 2308 nSelections = QMAX( nSelections, id + 1 );
2303} 2309}
2304 2310
2305static void setSelectionEndHelper( int id, QTextDocumentSelection &sel, QTextCursor &start, QTextCursor &end ) 2311static void setSelectionEndHelper( int id, QTextDocumentSelection &sel, QTextCursor &start, QTextCursor &end )
2306{ 2312{
2307 QTextCursor c1 = start; 2313 QTextCursor c1 = start;
2308 QTextCursor c2 = end; 2314 QTextCursor c2 = end;
2309 if ( sel.swapped ) { 2315 if ( sel.swapped ) {
2310 c1 = end; 2316 c1 = end;
2311 c2 = start; 2317 c2 = start;
2312 } 2318 }
2313 2319
2314 c1.paragraph()->removeSelection( id ); 2320 c1.paragraph()->removeSelection( id );
2315 c2.paragraph()->removeSelection( id ); 2321 c2.paragraph()->removeSelection( id );
2316 if ( c1.paragraph() != c2.paragraph() ) { 2322 if ( c1.paragraph() != c2.paragraph() ) {
2317 c1.paragraph()->setSelection( id, c1.index(), c1.paragraph()->length() - 1 ); 2323 c1.paragraph()->setSelection( id, c1.index(), c1.paragraph()->length() - 1 );
2318 c2.paragraph()->setSelection( id, 0, c2.index() ); 2324 c2.paragraph()->setSelection( id, 0, c2.index() );
2319 } else { 2325 } else {
2320 c1.paragraph()->setSelection( id, QMIN( c1.index(), c2.index() ), QMAX( c1.index(), c2.index() ) ); 2326 c1.paragraph()->setSelection( id, QMIN( c1.index(), c2.index() ), QMAX( c1.index(), c2.index() ) );
2321 } 2327 }
2322 2328
2323 sel.startCursor = start; 2329 sel.startCursor = start;
2324 sel.endCursor = end; 2330 sel.endCursor = end;
2325 if ( sel.startCursor.paragraph() == sel.endCursor.paragraph() ) 2331 if ( sel.startCursor.paragraph() == sel.endCursor.paragraph() )
2326 sel.swapped = sel.startCursor.index() > sel.endCursor.index(); 2332 sel.swapped = sel.startCursor.index() > sel.endCursor.index();
2327} 2333}
2328 2334
2329bool QTextDocument::setSelectionEnd( int id, const QTextCursor &cursor ) 2335bool QTextDocument::setSelectionEnd( int id, const QTextCursor &cursor )
2330{ 2336{
2331 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id ); 2337 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id );
2332 if ( it == selections.end() ) 2338 if ( it == selections.end() )
2333 return FALSE; 2339 return FALSE;
2334 QTextDocumentSelection &sel = *it; 2340 QTextDocumentSelection &sel = *it;
2335 2341
2336 QTextCursor start = sel.startCursor; 2342 QTextCursor start = sel.startCursor;
2337 QTextCursor end = cursor; 2343 QTextCursor end = cursor;
2338 2344
2339 if ( start == end ) { 2345 if ( start == end ) {
2340 removeSelection( id ); 2346 removeSelection( id );
2341 setSelectionStart( id, cursor ); 2347 setSelectionStart( id, cursor );
2342 return TRUE; 2348 return TRUE;
2343 } 2349 }
2344 2350
2345 if ( sel.endCursor.paragraph() == end.paragraph() ) { 2351 if ( sel.endCursor.paragraph() == end.paragraph() ) {
2346 setSelectionEndHelper( id, sel, start, end ); 2352 setSelectionEndHelper( id, sel, start, end );
2347 return TRUE; 2353 return TRUE;
2348 } 2354 }
2349 2355
2350 bool inSelection = FALSE; 2356 bool inSelection = FALSE;
2351 QTextCursor c( this ); 2357 QTextCursor c( this );
2352 QTextCursor tmp = sel.startCursor; 2358 QTextCursor tmp = sel.startCursor;
2353 if ( sel.swapped ) 2359 if ( sel.swapped )
2354 tmp = sel.endCursor; 2360 tmp = sel.endCursor;
2355 tmp.restoreState(); 2361 tmp.restoreState();
2356 QTextCursor tmp2 = cursor; 2362 QTextCursor tmp2 = cursor;
2357 tmp2.restoreState(); 2363 tmp2.restoreState();
2358 c.setParagraph( tmp.paragraph()->paragId() < tmp2.paragraph()->paragId() ? tmp.paragraph() : tmp2.paragraph() ); 2364 c.setParagraph( tmp.paragraph()->paragId() < tmp2.paragraph()->paragId() ? tmp.paragraph() : tmp2.paragraph() );
2359 bool hadStart = FALSE; 2365 bool hadStart = FALSE;
2360 bool hadEnd = FALSE; 2366 bool hadEnd = FALSE;
2361 bool hadStartParag = FALSE; 2367 bool hadStartParag = FALSE;
2362 bool hadEndParag = FALSE; 2368 bool hadEndParag = FALSE;
2363 bool hadOldStart = FALSE; 2369 bool hadOldStart = FALSE;
2364 bool hadOldEnd = FALSE; 2370 bool hadOldEnd = FALSE;
2365 bool leftSelection = FALSE; 2371 bool leftSelection = FALSE;
2366 sel.swapped = FALSE; 2372 sel.swapped = FALSE;
2367 for ( ;; ) { 2373 for ( ;; ) {
2368 if ( c == start ) 2374 if ( c == start )
2369 hadStart = TRUE; 2375 hadStart = TRUE;
2370 if ( c == end ) 2376 if ( c == end )
2371 hadEnd = TRUE; 2377 hadEnd = TRUE;
2372 if ( c.paragraph() == start.paragraph() ) 2378 if ( c.paragraph() == start.paragraph() )
2373 hadStartParag = TRUE; 2379 hadStartParag = TRUE;
2374 if ( c.paragraph() == end.paragraph() ) 2380 if ( c.paragraph() == end.paragraph() )
2375 hadEndParag = TRUE; 2381 hadEndParag = TRUE;
2376 if ( c == sel.startCursor ) 2382 if ( c == sel.startCursor )
2377 hadOldStart = TRUE; 2383 hadOldStart = TRUE;
2378 if ( c == sel.endCursor ) 2384 if ( c == sel.endCursor )
2379 hadOldEnd = TRUE; 2385 hadOldEnd = TRUE;
2380 2386
2381 if ( !sel.swapped && 2387 if ( !sel.swapped &&
2382 ( hadEnd && !hadStart || 2388 ( hadEnd && !hadStart ||
2383 hadEnd && hadStart && start.paragraph() == end.paragraph() && start.index() > end.index() ) ) 2389 hadEnd && hadStart && start.paragraph() == end.paragraph() && start.index() > end.index() ) )
2384 sel.swapped = TRUE; 2390 sel.swapped = TRUE;
2385 2391
2386 if ( c == end && hadStartParag || 2392 if ( c == end && hadStartParag ||
2387 c == start && hadEndParag ) { 2393 c == start && hadEndParag ) {
2388 QTextCursor tmp = c; 2394 QTextCursor tmp = c;
2389 tmp.restoreState(); 2395 tmp.restoreState();
2390 if ( tmp.paragraph() != c.paragraph() ) { 2396 if ( tmp.paragraph() != c.paragraph() ) {
2391 int sstart = tmp.paragraph()->selectionStart( id ); 2397 int sstart = tmp.paragraph()->selectionStart( id );
2392 tmp.paragraph()->removeSelection( id ); 2398 tmp.paragraph()->removeSelection( id );
2393 tmp.paragraph()->setSelection( id, sstart, tmp.index() ); 2399 tmp.paragraph()->setSelection( id, sstart, tmp.index() );
2394 } 2400 }
2395 } 2401 }
2396 2402
2397 if ( inSelection && 2403 if ( inSelection &&
2398 ( c == end && hadStart || c == start && hadEnd ) ) 2404 ( c == end && hadStart || c == start && hadEnd ) )
2399 leftSelection = TRUE; 2405 leftSelection = TRUE;
2400 else if ( !leftSelection && !inSelection && ( hadStart || hadEnd ) ) 2406 else if ( !leftSelection && !inSelection && ( hadStart || hadEnd ) )
2401 inSelection = TRUE; 2407 inSelection = TRUE;
2402 2408
2403 bool noSelectionAnymore = hadOldStart && hadOldEnd && leftSelection && !inSelection && !c.paragraph()->hasSelection( id ) && c.atParagEnd(); 2409 bool noSelectionAnymore = hadOldStart && hadOldEnd && leftSelection && !inSelection && !c.paragraph()->hasSelection( id ) && c.atParagEnd();
2404 c.paragraph()->removeSelection( id ); 2410 c.paragraph()->removeSelection( id );
2405 if ( inSelection ) { 2411 if ( inSelection ) {
2406 if ( c.paragraph() == start.paragraph() && start.paragraph() == end.paragraph() ) { 2412 if ( c.paragraph() == start.paragraph() && start.paragraph() == end.paragraph() ) {
2407 c.paragraph()->setSelection( id, QMIN( start.index(), end.index() ), QMAX( start.index(), end.index() ) ); 2413 c.paragraph()->setSelection( id, QMIN( start.index(), end.index() ), QMAX( start.index(), end.index() ) );
2408 } else if ( c.paragraph() == start.paragraph() && !hadEndParag ) { 2414 } else if ( c.paragraph() == start.paragraph() && !hadEndParag ) {
2409 c.paragraph()->setSelection( id, start.index(), c.paragraph()->length() - 1 ); 2415 c.paragraph()->setSelection( id, start.index(), c.paragraph()->length() - 1 );
2410 } else if ( c.paragraph() == end.paragraph() && !hadStartParag ) { 2416 } else if ( c.paragraph() == end.paragraph() && !hadStartParag ) {
2411 c.paragraph()->setSelection( id, end.index(), c.paragraph()->length() - 1 ); 2417 c.paragraph()->setSelection( id, end.index(), c.paragraph()->length() - 1 );
2412 } else if ( c.paragraph() == end.paragraph() && hadEndParag ) { 2418 } else if ( c.paragraph() == end.paragraph() && hadEndParag ) {
2413 c.paragraph()->setSelection( id, 0, end.index() ); 2419 c.paragraph()->setSelection( id, 0, end.index() );
2414 } else if ( c.paragraph() == start.paragraph() && hadStartParag ) { 2420 } else if ( c.paragraph() == start.paragraph() && hadStartParag ) {
2415 c.paragraph()->setSelection( id, 0, start.index() ); 2421 c.paragraph()->setSelection( id, 0, start.index() );
2416 } else { 2422 } else {
2417 c.paragraph()->setSelection( id, 0, c.paragraph()->length() - 1 ); 2423 c.paragraph()->setSelection( id, 0, c.paragraph()->length() - 1 );
2418 } 2424 }
2419 } 2425 }
2420 2426
2421 if ( leftSelection ) 2427 if ( leftSelection )
2422 inSelection = FALSE; 2428 inSelection = FALSE;
2423 2429
2424 if ( noSelectionAnymore ) 2430 if ( noSelectionAnymore )
2425 break; 2431 break;
2426 // *ugle*hack optimization 2432 // *ugle*hack optimization
2427 QTextParagraph *p = c.paragraph(); 2433 QTextParagraph *p = c.paragraph();
2428 if ( p->mightHaveCustomItems || p == start.paragraph() || p == end.paragraph() || p == lastParagraph() ) { 2434 if ( p->mightHaveCustomItems || p == start.paragraph() || p == end.paragraph() || p == lastParagraph() ) {
2429 c.gotoNextLetter(); 2435 c.gotoNextLetter();
2430 if ( p == lastParagraph() && c.atParagEnd() ) 2436 if ( p == lastParagraph() && c.atParagEnd() )
2431 break; 2437 break;
2432 } else { 2438 } else {
2433 if ( p->document()->parent() ) 2439 if ( p->document()->parent() )
2434 do { 2440 do {
2435 c.gotoNextLetter(); 2441 c.gotoNextLetter();
2436 } while ( c.paragraph() == p ); 2442 } while ( c.paragraph() == p );
2437 else 2443 else
2438 c.setParagraph( p->next() ); 2444 c.setParagraph( p->next() );
2439 } 2445 }
2440 } 2446 }
2441 2447
2442 if ( !sel.swapped ) 2448 if ( !sel.swapped )
2443 sel.startCursor.paragraph()->setSelection( id, sel.startCursor.index(), sel.startCursor.paragraph()->length() - 1 ); 2449 sel.startCursor.paragraph()->setSelection( id, sel.startCursor.index(), sel.startCursor.paragraph()->length() - 1 );
2444 2450
2445 sel.startCursor = start; 2451 sel.startCursor = start;
2446 sel.endCursor = end; 2452 sel.endCursor = end;
2447 if ( sel.startCursor.paragraph() == sel.endCursor.paragraph() ) 2453 if ( sel.startCursor.paragraph() == sel.endCursor.paragraph() )
2448 sel.swapped = sel.startCursor.index() > sel.endCursor.index(); 2454 sel.swapped = sel.startCursor.index() > sel.endCursor.index();
2449 2455
2450 setSelectionEndHelper( id, sel, start, end ); 2456 setSelectionEndHelper( id, sel, start, end );
2451 2457
2452 return TRUE; 2458 return TRUE;
2453} 2459}
2454 2460
2455void QTextDocument::selectAll( int id ) 2461void QTextDocument::selectAll( int id )
2456{ 2462{
2457 removeSelection( id ); 2463 removeSelection( id );
2458 2464
2459 QTextDocumentSelection sel; 2465 QTextDocumentSelection sel;
2460 sel.swapped = FALSE; 2466 sel.swapped = FALSE;
2461 QTextCursor c( this ); 2467 QTextCursor c( this );
2462 2468
2463 c.setParagraph( fParag ); 2469 c.setParagraph( fParag );
2464 c.setIndex( 0 ); 2470 c.setIndex( 0 );
2465 sel.startCursor = c; 2471 sel.startCursor = c;
2466 2472
2467 c.setParagraph( lParag ); 2473 c.setParagraph( lParag );
2468 c.setIndex( lParag->length() - 1 ); 2474 c.setIndex( lParag->length() - 1 );
2469 sel.endCursor = c; 2475 sel.endCursor = c;
2470 2476
2471 selections.insert( id, sel ); 2477 selections.insert( id, sel );
2472 2478
2473 QTextParagraph *p = fParag; 2479 QTextParagraph *p = fParag;
2474 while ( p ) { 2480 while ( p ) {
2475 p->setSelection( id, 0, p->length() - 1 ); 2481 p->setSelection( id, 0, p->length() - 1 );
2476 p = p->next(); 2482 p = p->next();
2477 } 2483 }
2478 2484
2479 for ( QTextDocument *d = childList.first(); d; d = childList.next() ) 2485 for ( QTextDocument *d = childList.first(); d; d = childList.next() )
2480 d->selectAll( id ); 2486 d->selectAll( id );
2481} 2487}
2482 2488
2483bool QTextDocument::removeSelection( int id ) 2489bool QTextDocument::removeSelection( int id )
2484{ 2490{
2485 if ( !selections.contains( id ) ) 2491 if ( !selections.contains( id ) )
2486 return FALSE; 2492 return FALSE;
2487 2493
2488 QTextDocumentSelection &sel = selections[ id ]; 2494 QTextDocumentSelection &sel = selections[ id ];
2489 2495
2490 QTextCursor start = sel.swapped ? sel.endCursor : sel.startCursor; 2496 QTextCursor start = sel.swapped ? sel.endCursor : sel.startCursor;
2491 QTextCursor end = sel.swapped ? sel.startCursor : sel.endCursor; 2497 QTextCursor end = sel.swapped ? sel.startCursor : sel.endCursor;
2492 QTextParagraph* p = 0; 2498 QTextParagraph* p = 0;
2493 while ( start != end ) { 2499 while ( start != end ) {
2494 if ( p != start.paragraph() ) { 2500 if ( p != start.paragraph() ) {
2495 p = start.paragraph(); 2501 p = start.paragraph();
2496 p->removeSelection( id ); 2502 p->removeSelection( id );
2497 } 2503 }
2498 start.gotoNextLetter(); 2504 start.gotoNextLetter();
2499 } 2505 }
2500 selections.remove( id ); 2506 selections.remove( id );
2501 return TRUE; 2507 return TRUE;
2502} 2508}
2503 2509
2504QString QTextDocument::selectedText( int id, bool asRichText ) const 2510QString QTextDocument::selectedText( int id, bool asRichText ) const
2505{ 2511{
2506 QMap<int, QTextDocumentSelection>::ConstIterator it = selections.find( id ); 2512 QMap<int, QTextDocumentSelection>::ConstIterator it = selections.find( id );
2507 if ( it == selections.end() ) 2513 if ( it == selections.end() )
2508 return QString::null; 2514 return QString::null;
2509 2515
2510 QTextDocumentSelection sel = *it; 2516 QTextDocumentSelection sel = *it;
2511 2517
2512 2518
2513 QTextCursor c1 = sel.startCursor; 2519 QTextCursor c1 = sel.startCursor;
2514 QTextCursor c2 = sel.endCursor; 2520 QTextCursor c2 = sel.endCursor;
2515 if ( sel.swapped ) { 2521 if ( sel.swapped ) {
2516 c2 = sel.startCursor; 2522 c2 = sel.startCursor;
2517 c1 = sel.endCursor; 2523 c1 = sel.endCursor;
2518 } 2524 }
2519 2525
2520 /* 3.0.3 improvement: Make it possible to get a reasonable 2526 /* 3.0.3 improvement: Make it possible to get a reasonable
2521 selection inside a table. This approach is very conservative: 2527 selection inside a table. This approach is very conservative:
2522 make sure that both cursors have the same depth level and point 2528 make sure that both cursors have the same depth level and point
2523 to paragraphs within the same text document. 2529 to paragraphs within the same text document.
2524 2530
2525 Meaning if you select text in two table cells, you will get the 2531 Meaning if you select text in two table cells, you will get the
2526 entire table. This is still far better than the 3.0.2, where 2532 entire table. This is still far better than the 3.0.2, where
2527 you always got the entire table. 2533 you always got the entire table.
2528 2534
2529 ### Fix this properly when refactoring 2535 ### Fix this properly when refactoring
2530 */ 2536 */
2531 while ( c2.nestedDepth() > c1.nestedDepth() ) 2537 while ( c2.nestedDepth() > c1.nestedDepth() )
2532 c2.oneUp(); 2538 c2.oneUp();
2533 while ( c1.nestedDepth() > c2.nestedDepth() ) 2539 while ( c1.nestedDepth() > c2.nestedDepth() )
2534 c1.oneUp(); 2540 c1.oneUp();
2535 while ( c1.nestedDepth() && c2.nestedDepth() && 2541 while ( c1.nestedDepth() && c2.nestedDepth() &&
2536 c1.paragraph()->document() != c2.paragraph()->document() ) { 2542 c1.paragraph()->document() != c2.paragraph()->document() ) {
2537 c1.oneUp(); 2543 c1.oneUp();
2538 c2.oneUp(); 2544 c2.oneUp();
2539 } 2545 }
2540 // do not trust sel_swapped with tables. Fix this properly when refactoring as well 2546 // do not trust sel_swapped with tables. Fix this properly when refactoring as well
2541 if ( c1.paragraph()->paragId() > c2.paragraph()->paragId() || 2547 if ( c1.paragraph()->paragId() > c2.paragraph()->paragId() ||
2542 (c1.paragraph() == c2.paragraph() && c1.index() > c2.index() ) ) { 2548 (c1.paragraph() == c2.paragraph() && c1.index() > c2.index() ) ) {
2543 QTextCursor tmp = c1; 2549 QTextCursor tmp = c1;
2544 c2 = c1; 2550 c2 = c1;
2545 c1 = tmp; 2551 c1 = tmp;
2546 } 2552 }
2547 2553
2548 // end selection 3.0.3 improvement 2554 // end selection 3.0.3 improvement
2549 2555
2550 if ( asRichText && !parent() ) { 2556 if ( asRichText && !parent() ) {
2551 richTextExportStart = &c1; 2557 richTextExportStart = &c1;
2552 richTextExportEnd = &c2; 2558 richTextExportEnd = &c2;
2553 2559
2554 QString sel = richText(); 2560 QString sel = richText();
2555 int from = sel.find( "<selstart/>" ); 2561 int from = sel.find( "<selstart/>" );
2556 int to = sel.findRev( "<selend/>" ); 2562 int to = sel.findRev( "<selend/>" );
2557 if ( from >= 0 && from <= to ) 2563 if ( from >= 0 && from <= to )
2558 sel = sel.mid( from, to - from ); 2564 sel = sel.mid( from, to - from );
2559 richTextExportStart = richTextExportEnd = 0; 2565 richTextExportStart = richTextExportEnd = 0;
2560 return sel; 2566 return sel;
2561 } 2567 }
2562 2568
2563 QString s; 2569 QString s;
2564 if ( c1.paragraph() == c2.paragraph() ) { 2570 if ( c1.paragraph() == c2.paragraph() ) {
2565 QTextParagraph *p = c1.paragraph(); 2571 QTextParagraph *p = c1.paragraph();
2566 int end = c2.index(); 2572 int end = c2.index();
2567 if ( p->at( QMAX( 0, end - 1 ) )->isCustom() ) 2573 if ( p->at( QMAX( 0, end - 1 ) )->isCustom() )
2568 ++end; 2574 ++end;
2569 if ( !p->mightHaveCustomItems ) { 2575 if ( !p->mightHaveCustomItems ) {
2570 s += p->string()->toString().mid( c1.index(), end - c1.index() ); 2576 s += p->string()->toString().mid( c1.index(), end - c1.index() );
2571 } else { 2577 } else {
2572 for ( int i = c1.index(); i < end; ++i ) { 2578 for ( int i = c1.index(); i < end; ++i ) {
2573 if ( p->at( i )->isCustom() ) { 2579 if ( p->at( i )->isCustom() ) {
2574 if ( p->at( i )->customItem()->isNested() ) { 2580 if ( p->at( i )->customItem()->isNested() ) {
2575 s += "\n"; 2581 s += "\n";
2576 QTextTable *t = (QTextTable*)p->at( i )->customItem(); 2582 QTextTable *t = (QTextTable*)p->at( i )->customItem();
2577 QPtrList<QTextTableCell> cells = t->tableCells(); 2583 QPtrList<QTextTableCell> cells = t->tableCells();
2578 for ( QTextTableCell *c = cells.first(); c; c = cells.next() ) 2584 for ( QTextTableCell *c = cells.first(); c; c = cells.next() )
2579 s += c->richText()->plainText() + "\n"; 2585 s += c->richText()->plainText() + "\n";
2580 s += "\n"; 2586 s += "\n";
2581 } 2587 }
2582 } else { 2588 } else {
2583 s += p->at( i )->c; 2589 s += p->at( i )->c;
2584 } 2590 }
2585 } 2591 }
2586 } 2592 }
2587 } else { 2593 } else {
2588 QTextParagraph *p = c1.paragraph(); 2594 QTextParagraph *p = c1.paragraph();
2589 int start = c1.index(); 2595 int start = c1.index();
2590 while ( p ) { 2596 while ( p ) {
2591 int end = p == c2.paragraph() ? c2.index() : p->length() - 1; 2597 int end = p == c2.paragraph() ? c2.index() : p->length() - 1;
2592 if ( p == c2.paragraph() && p->at( QMAX( 0, end - 1 ) )->isCustom() ) 2598 if ( p == c2.paragraph() && p->at( QMAX( 0, end - 1 ) )->isCustom() )
2593 ++end; 2599 ++end;
2594 if ( !p->mightHaveCustomItems ) { 2600 if ( !p->mightHaveCustomItems ) {
2595 s += p->string()->toString().mid( start, end - start ); 2601 s += p->string()->toString().mid( start, end - start );
2596 if ( p != c2.paragraph() ) 2602 if ( p != c2.paragraph() )
2597 s += "\n"; 2603 s += "\n";
2598 } else { 2604 } else {
2599 for ( int i = start; i < end; ++i ) { 2605 for ( int i = start; i < end; ++i ) {
2600 if ( p->at( i )->isCustom() ) { 2606 if ( p->at( i )->isCustom() ) {
2601 if ( p->at( i )->customItem()->isNested() ) { 2607 if ( p->at( i )->customItem()->isNested() ) {
2602 s += "\n"; 2608 s += "\n";
2603 QTextTable *t = (QTextTable*)p->at( i )->customItem(); 2609 QTextTable *t = (QTextTable*)p->at( i )->customItem();
2604 QPtrList<QTextTableCell> cells = t->tableCells(); 2610 QPtrList<QTextTableCell> cells = t->tableCells();
2605 for ( QTextTableCell *c = cells.first(); c; c = cells.next() ) 2611 for ( QTextTableCell *c = cells.first(); c; c = cells.next() )
2606 s += c->richText()->plainText() + "\n"; 2612 s += c->richText()->plainText() + "\n";
2607 s += "\n"; 2613 s += "\n";
2608 } 2614 }
2609 } else { 2615 } else {
2610 s += p->at( i )->c; 2616 s += p->at( i )->c;
2611 } 2617 }
2612 } 2618 }
2613 } 2619 }
2614 start = 0; 2620 start = 0;
2615 if ( p == c2.paragraph() ) 2621 if ( p == c2.paragraph() )
2616 break; 2622 break;
2617 p = p->next(); 2623 p = p->next();
2618 } 2624 }
2619 } 2625 }
2620 // ### workaround for plain text export until we get proper 2626 // ### workaround for plain text export until we get proper
2621 // mime types: turn unicode line seperators into the more 2627 // mime types: turn unicode line seperators into the more
2622 // widely understood \n. Makes copy and pasting code snipplets 2628 // widely understood \n. Makes copy and pasting code snipplets
2623 // from within Assistent possible 2629 // from within Assistent possible
2624 QChar* uc = (QChar*) s.unicode(); 2630 QChar* uc = (QChar*) s.unicode();
2625 for ( uint ii = 0; ii < s.length(); ii++ ) 2631 for ( uint ii = 0; ii < s.length(); ii++ )
2626 if ( uc[(int)ii] == QChar_linesep ) 2632 if ( uc[(int)ii] == QChar_linesep )
2627 uc[(int)ii] = QChar('\n'); 2633 uc[(int)ii] = QChar('\n');
2628 return s; 2634 return s;
2629} 2635}
2630 2636
2631void QTextDocument::setFormat( int id, QTextFormat *f, int flags ) 2637void QTextDocument::setFormat( int id, QTextFormat *f, int flags )
2632{ 2638{
2633 QMap<int, QTextDocumentSelection>::ConstIterator it = selections.find( id ); 2639 QMap<int, QTextDocumentSelection>::ConstIterator it = selections.find( id );
2634 if ( it == selections.end() ) 2640 if ( it == selections.end() )
2635 return; 2641 return;
2636 2642
2637 QTextDocumentSelection sel = *it; 2643 QTextDocumentSelection sel = *it;
2638 2644
2639 QTextCursor c1 = sel.startCursor; 2645 QTextCursor c1 = sel.startCursor;
2640 QTextCursor c2 = sel.endCursor; 2646 QTextCursor c2 = sel.endCursor;
2641 if ( sel.swapped ) { 2647 if ( sel.swapped ) {
2642 c2 = sel.startCursor; 2648 c2 = sel.startCursor;
2643 c1 = sel.endCursor; 2649 c1 = sel.endCursor;
2644 } 2650 }
2645 2651
2646 c2.restoreState(); 2652 c2.restoreState();
2647 c1.restoreState(); 2653 c1.restoreState();
2648 2654
2649 if ( c1.paragraph() == c2.paragraph() ) { 2655 if ( c1.paragraph() == c2.paragraph() ) {
2650 c1.paragraph()->setFormat( c1.index(), c2.index() - c1.index(), f, TRUE, flags ); 2656 c1.paragraph()->setFormat( c1.index(), c2.index() - c1.index(), f, TRUE, flags );
2651 return; 2657 return;
2652 } 2658 }
2653 2659
2654 c1.paragraph()->setFormat( c1.index(), c1.paragraph()->length() - c1.index(), f, TRUE, flags ); 2660 c1.paragraph()->setFormat( c1.index(), c1.paragraph()->length() - c1.index(), f, TRUE, flags );
2655 QTextParagraph *p = c1.paragraph()->next(); 2661 QTextParagraph *p = c1.paragraph()->next();
2656 while ( p && p != c2.paragraph() ) { 2662 while ( p && p != c2.paragraph() ) {
2657 p->setFormat( 0, p->length(), f, TRUE, flags ); 2663 p->setFormat( 0, p->length(), f, TRUE, flags );
2658 p = p->next(); 2664 p = p->next();
2659 } 2665 }
2660 c2.paragraph()->setFormat( 0, c2.index(), f, TRUE, flags ); 2666 c2.paragraph()->setFormat( 0, c2.index(), f, TRUE, flags );
2661} 2667}
2662 2668
2663void QTextDocument::removeSelectedText( int id, QTextCursor *cursor ) 2669void QTextDocument::removeSelectedText( int id, QTextCursor *cursor )
2664{ 2670{
2665 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id ); 2671 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id );
2666 if ( it == selections.end() ) 2672 if ( it == selections.end() )
2667 return; 2673 return;
2668 2674
2669 QTextDocumentSelection sel = *it; 2675 QTextDocumentSelection sel = *it;
2670 2676
2671 QTextCursor c1 = sel.startCursor; 2677 QTextCursor c1 = sel.startCursor;
2672 QTextCursor c2 = sel.endCursor; 2678 QTextCursor c2 = sel.endCursor;
2673 if ( sel.swapped ) { 2679 if ( sel.swapped ) {
2674 c2 = sel.startCursor; 2680 c2 = sel.startCursor;
2675 c1 = sel.endCursor; 2681 c1 = sel.endCursor;
2676 } 2682 }
2677 2683
2678 // ### no support for editing tables yet 2684 // ### no support for editing tables yet
2679 if ( c1.nestedDepth() || c2.nestedDepth() ) 2685 if ( c1.nestedDepth() || c2.nestedDepth() )
2680 return; 2686 return;
2681 2687
2682 c2.restoreState(); 2688 c2.restoreState();
2683 c1.restoreState(); 2689 c1.restoreState();
2684 2690
2685 *cursor = c1; 2691 *cursor = c1;
2686 removeSelection( id ); 2692 removeSelection( id );
2687 2693
2688 if ( c1.paragraph() == c2.paragraph() ) { 2694 if ( c1.paragraph() == c2.paragraph() ) {
2689 c1.paragraph()->remove( c1.index(), c2.index() - c1.index() ); 2695 c1.paragraph()->remove( c1.index(), c2.index() - c1.index() );
2690 return; 2696 return;
2691 } 2697 }
2692 2698
2693 if ( c1.paragraph() == fParag && c1.index() == 0 && 2699 if ( c1.paragraph() == fParag && c1.index() == 0 &&
2694 c2.paragraph() == lParag && c2.index() == lParag->length() - 1 ) 2700 c2.paragraph() == lParag && c2.index() == lParag->length() - 1 )
2695 cursor->setValid( FALSE ); 2701 cursor->setValid( FALSE );
2696 2702
2697 bool didGoLeft = FALSE; 2703 bool didGoLeft = FALSE;
2698 if ( c1.index() == 0 && c1.paragraph() != fParag ) { 2704 if ( c1.index() == 0 && c1.paragraph() != fParag ) {
2699 cursor->gotoPreviousLetter(); 2705 cursor->gotoPreviousLetter();
2700 if ( cursor->isValid() ) 2706 if ( cursor->isValid() )
2701 didGoLeft = TRUE; 2707 didGoLeft = TRUE;
2702 } 2708 }
2703 2709
2704 c1.paragraph()->remove( c1.index(), c1.paragraph()->length() - 1 - c1.index() ); 2710 c1.paragraph()->remove( c1.index(), c1.paragraph()->length() - 1 - c1.index() );
2705 QTextParagraph *p = c1.paragraph()->next(); 2711 QTextParagraph *p = c1.paragraph()->next();
2706 int dy = 0; 2712 int dy = 0;
2707 QTextParagraph *tmp; 2713 QTextParagraph *tmp;
2708 while ( p && p != c2.paragraph() ) { 2714 while ( p && p != c2.paragraph() ) {
2709 tmp = p->next(); 2715 tmp = p->next();
2710 dy -= p->rect().height(); 2716 dy -= p->rect().height();
2711 delete p; 2717 delete p;
2712 p = tmp; 2718 p = tmp;
2713 } 2719 }
2714 c2.paragraph()->remove( 0, c2.index() ); 2720 c2.paragraph()->remove( 0, c2.index() );
2715 while ( p ) { 2721 while ( p ) {
2716 p->move( dy ); 2722 p->move( dy );
2717 p->invalidate( 0 ); 2723 p->invalidate( 0 );
2718 p->setEndState( -1 ); 2724 p->setEndState( -1 );
2719 p = p->next(); 2725 p = p->next();
2720 } 2726 }
2721 2727
2722 c1.paragraph()->join( c2.paragraph() ); 2728 c1.paragraph()->join( c2.paragraph() );
2723 2729
2724 if ( didGoLeft ) 2730 if ( didGoLeft )
2725 cursor->gotoNextLetter(); 2731 cursor->gotoNextLetter();
2726} 2732}
2727 2733
2728void QTextDocument::indentSelection( int id ) 2734void QTextDocument::indentSelection( int id )
2729{ 2735{
2730 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id ); 2736 QMap<int, QTextDocumentSelection>::Iterator it = selections.find( id );
2731 if ( it == selections.end() ) 2737 if ( it == selections.end() )
2732 return; 2738 return;
2733 2739
2734 QTextDocumentSelection sel = *it; 2740 QTextDocumentSelection sel = *it;
2735 QTextParagraph *startParag = sel.startCursor.paragraph(); 2741 QTextParagraph *startParag = sel.startCursor.paragraph();
2736 QTextParagraph *endParag = sel.endCursor.paragraph(); 2742 QTextParagraph *endParag = sel.endCursor.paragraph();
2737 if ( sel.endCursor.paragraph()->paragId() < sel.startCursor.paragraph()->paragId() ) { 2743 if ( sel.endCursor.paragraph()->paragId() < sel.startCursor.paragraph()->paragId() ) {
2738 endParag = sel.startCursor.paragraph(); 2744 endParag = sel.startCursor.paragraph();
2739 startParag = sel.endCursor.paragraph(); 2745 startParag = sel.endCursor.paragraph();
2740 } 2746 }
2741 2747
2742 QTextParagraph *p = startParag; 2748 QTextParagraph *p = startParag;
2743 while ( p && p != endParag ) { 2749 while ( p && p != endParag ) {
2744 p->indent(); 2750 p->indent();
2745 p = p->next(); 2751 p = p->next();
2746 } 2752 }
2747} 2753}
2748 2754
2749void QTextDocument::addCommand( QTextCommand *cmd ) 2755void QTextDocument::addCommand( QTextCommand *cmd )
2750{ 2756{
2751 commandHistory->addCommand( cmd ); 2757 commandHistory->addCommand( cmd );
2752} 2758}
2753 2759
2754QTextCursor *QTextDocument::undo( QTextCursor *c ) 2760QTextCursor *QTextDocument::undo( QTextCursor *c )
2755{ 2761{
2756 return commandHistory->undo( c ); 2762 return commandHistory->undo( c );
2757} 2763}
2758 2764
2759QTextCursor *QTextDocument::redo( QTextCursor *c ) 2765QTextCursor *QTextDocument::redo( QTextCursor *c )
2760{ 2766{
2761 return commandHistory->redo( c ); 2767 return commandHistory->redo( c );
2762} 2768}
2763 2769
2764bool QTextDocument::find( QTextCursor& cursor, const QString &e, bool cs, bool wo, bool forward ) 2770bool QTextDocument::find( QTextCursor& cursor, const QString &e, bool cs, bool wo, bool forward )
2765{ 2771{
2766 removeSelection( Standard ); 2772 removeSelection( Standard );
2767 QTextParagraph *p = 0; 2773 QTextParagraph *p = 0;
2768 QString expr = e; 2774 QString expr = e;
2769 // if we search for 'word only' than we have to be sure that 2775 // if we search for 'word only' than we have to be sure that
2770 // the expression contains no space or punct character at the 2776 // the expression contains no space or punct character at the
2771 // beginning or in the end. Otherwise we would run into a 2777 // beginning or in the end. Otherwise we would run into a
2772 // endlessloop. 2778 // endlessloop.
2773 if ( wo ) { 2779 if ( wo ) {
2774 for ( ;; ) { 2780 for ( ;; ) {
2775 if ( expr[ 0 ].isSpace() || expr[ 0 ].isPunct() ) 2781 if ( expr[ 0 ].isSpace() || expr[ 0 ].isPunct() )
2776 expr = expr.right( expr.length() - 1 ); 2782 expr = expr.right( expr.length() - 1 );
2777 else 2783 else
2778 break; 2784 break;
2779 } 2785 }
2780 for ( ;; ) { 2786 for ( ;; ) {
2781 if ( expr.at( expr.length() - 1 ).isSpace() || expr.at( expr.length() - 1 ).isPunct() ) 2787 if ( expr.at( expr.length() - 1 ).isSpace() || expr.at( expr.length() - 1 ).isPunct() )
2782 expr = expr.left( expr.length() - 1 ); 2788 expr = expr.left( expr.length() - 1 );
2783 else 2789 else
2784 break; 2790 break;
2785 } 2791 }
2786 } 2792 }
2787 for (;;) { 2793 for (;;) {
2788 if ( p != cursor.paragraph() ) { 2794 if ( p != cursor.paragraph() ) {
2789 p = cursor.paragraph(); 2795 p = cursor.paragraph();
2790 QString s = cursor.paragraph()->string()->toString(); 2796 QString s = cursor.paragraph()->string()->toString();
2791 int start = cursor.index(); 2797 int start = cursor.index();
2792 for ( ;; ) { 2798 for ( ;; ) {
2793 int res = forward ? s.find( expr, start, cs ) : s.findRev( expr, start, cs ); 2799 int res = forward ? s.find( expr, start, cs ) : s.findRev( expr, start, cs );
2794 int end = res + expr.length(); 2800 int end = res + expr.length();
2795 if ( res == -1 || ( !forward && start < end ) ) 2801 if ( res == -1 || ( !forward && start < end ) )
2796 break; 2802 break;
2797 if ( !wo || ( ( res == 0 || s[ res - 1 ].isSpace() || s[ res - 1 ].isPunct() ) && 2803 if ( !wo || ( ( res == 0 || s[ res - 1 ].isSpace() || s[ res - 1 ].isPunct() ) &&
2798 ( end == (int)s.length() || s[ end ].isSpace() || s[ end ].isPunct() ) ) ) { 2804 ( end == (int)s.length() || s[ end ].isSpace() || s[ end ].isPunct() ) ) ) {
2799 removeSelection( Standard ); 2805 removeSelection( Standard );
2800 cursor.setIndex( forward ? end : res ); 2806 cursor.setIndex( forward ? end : res );
2801 setSelectionStart( Standard, cursor ); 2807 setSelectionStart( Standard, cursor );
2802 cursor.setIndex( forward ? res : end ); 2808 cursor.setIndex( forward ? res : end );
2803 setSelectionEnd( Standard, cursor ); 2809 setSelectionEnd( Standard, cursor );
2804 return TRUE; 2810 return TRUE;
2805 } 2811 }
2806 start = res + (forward ? 1 : -1); 2812 start = res + (forward ? 1 : -1);
2807 } 2813 }
2808 } 2814 }
2809 if ( forward ) { 2815 if ( forward ) {
2810 if ( cursor.paragraph() == lastParagraph() && cursor.atParagEnd () ) 2816 if ( cursor.paragraph() == lastParagraph() && cursor.atParagEnd () )
2811 break; 2817 break;
2812 cursor.gotoNextLetter(); 2818 cursor.gotoNextLetter();
2813 } else { 2819 } else {
2814 if ( cursor.paragraph() == firstParagraph() && cursor.atParagStart() ) 2820 if ( cursor.paragraph() == firstParagraph() && cursor.atParagStart() )
2815 break; 2821 break;
2816 cursor.gotoPreviousLetter(); 2822 cursor.gotoPreviousLetter();
2817 } 2823 }
2818 } 2824 }
2819 return FALSE; 2825 return FALSE;
2820} 2826}
2821 2827
2822void QTextDocument::setTextFormat( Qt::TextFormat f ) 2828void QTextDocument::setTextFormat( Qt::TextFormat f )
2823{ 2829{
2824 txtFormat = f; 2830 txtFormat = f;
2825 if ( fParag == lParag && fParag->length() <= 1 ) 2831 if ( fParag == lParag && fParag->length() <= 1 )
2826 fParag->rtext = ( f == Qt::RichText ); 2832 fParag->rtext = ( f == Qt::RichText );
2827} 2833}
2828 2834
2829Qt::TextFormat QTextDocument::textFormat() const 2835Qt::TextFormat QTextDocument::textFormat() const
2830{ 2836{
2831 return txtFormat; 2837 return txtFormat;
2832} 2838}
2833 2839
2834bool QTextDocument::inSelection( int selId, const QPoint &pos ) const 2840bool QTextDocument::inSelection( int selId, const QPoint &pos ) const
2835{ 2841{
2836 QMap<int, QTextDocumentSelection>::ConstIterator it = selections.find( selId ); 2842 QMap<int, QTextDocumentSelection>::ConstIterator it = selections.find( selId );
2837 if ( it == selections.end() ) 2843 if ( it == selections.end() )
2838 return FALSE; 2844 return FALSE;
2839 2845
2840 QTextDocumentSelection sel = *it; 2846 QTextDocumentSelection sel = *it;
2841 QTextParagraph *startParag = sel.startCursor.paragraph(); 2847 QTextParagraph *startParag = sel.startCursor.paragraph();
2842 QTextParagraph *endParag = sel.endCursor.paragraph(); 2848 QTextParagraph *endParag = sel.endCursor.paragraph();
2843 if ( sel.startCursor.paragraph() == sel.endCursor.paragraph() && 2849 if ( sel.startCursor.paragraph() == sel.endCursor.paragraph() &&
2844 sel.startCursor.paragraph()->selectionStart( selId ) == sel.endCursor.paragraph()->selectionEnd( selId ) ) 2850 sel.startCursor.paragraph()->selectionStart( selId ) == sel.endCursor.paragraph()->selectionEnd( selId ) )
2845 return FALSE; 2851 return FALSE;
2846 if ( sel.endCursor.paragraph()->paragId() < sel.startCursor.paragraph()->paragId() ) { 2852 if ( sel.endCursor.paragraph()->paragId() < sel.startCursor.paragraph()->paragId() ) {
2847 endParag = sel.startCursor.paragraph(); 2853 endParag = sel.startCursor.paragraph();
2848 startParag = sel.endCursor.paragraph(); 2854 startParag = sel.endCursor.paragraph();
2849 } 2855 }
2850 2856
2851 QTextParagraph *p = startParag; 2857 QTextParagraph *p = startParag;
2852 while ( p ) { 2858 while ( p ) {
2853 if ( p->rect().contains( pos ) ) { 2859 if ( p->rect().contains( pos ) ) {
2854 bool inSel = FALSE; 2860 bool inSel = FALSE;
2855 int selStart = p->selectionStart( selId ); 2861 int selStart = p->selectionStart( selId );
2856 int selEnd = p->selectionEnd( selId ); 2862 int selEnd = p->selectionEnd( selId );
2857 int y = 0; 2863 int y = 0;
2858 int h = 0; 2864 int h = 0;
2859 for ( int i = 0; i < p->length(); ++i ) { 2865 for ( int i = 0; i < p->length(); ++i ) {
2860 if ( i == selStart ) 2866 if ( i == selStart )
2861 inSel = TRUE; 2867 inSel = TRUE;
2862 if ( i == selEnd ) 2868 if ( i == selEnd )
2863 break; 2869 break;
2864 if ( p->at( i )->lineStart ) { 2870 if ( p->at( i )->lineStart ) {
2865 y = (*p->lineStarts.find( i ))->y; 2871 y = (*p->lineStarts.find( i ))->y;
2866 h = (*p->lineStarts.find( i ))->h; 2872 h = (*p->lineStarts.find( i ))->h;
2867 } 2873 }
2868 if ( pos.y() - p->rect().y() >= y && pos.y() - p->rect().y() <= y + h ) { 2874 if ( pos.y() - p->rect().y() >= y && pos.y() - p->rect().y() <= y + h ) {
2869 if ( inSel && pos.x() >= p->at( i )->x && 2875 if ( inSel && pos.x() >= p->at( i )->x &&
2870 pos.x() <= p->at( i )->x + p->at( i )->format()->width( p->at( i )->c ) ) 2876 pos.x() <= p->at( i )->x + p->at( i )->format()->width( p->at( i )->c ) )
2871 return TRUE; 2877 return TRUE;
2872 } 2878 }
2873 } 2879 }
2874 } 2880 }
2875 if ( pos.y() < p->rect().y() ) 2881 if ( pos.y() < p->rect().y() )
2876 break; 2882 break;
2877 if ( p == endParag ) 2883 if ( p == endParag )
2878 break; 2884 break;
2879 p = p->next(); 2885 p = p->next();
2880 } 2886 }
2881 2887
2882 return FALSE; 2888 return FALSE;
2883} 2889}
2884 2890
2885void QTextDocument::doLayout( QPainter *p, int w ) 2891void QTextDocument::doLayout( QPainter *p, int w )
2886{ 2892{
2887 minw = wused = 0; 2893 minw = wused = 0;
2888 if ( !is_printer( p ) ) 2894 if ( !is_printer( p ) )
2889 p = 0; 2895 p = 0;
2890 withoutDoubleBuffer = ( p != 0 ); 2896 withoutDoubleBuffer = ( p != 0 );
2891 QPainter * oldPainter = QTextFormat::painter(); 2897 QPainter * oldPainter = QTextFormat::painter();
2892 QTextFormat::setPainter( p ); 2898 QTextFormat::setPainter( p );
2893 flow_->setWidth( w ); 2899 flow_->setWidth( w );
2894 cw = w; 2900 cw = w;
2895 vw = w; 2901 vw = w;
2896 QTextParagraph *parag = fParag; 2902 QTextParagraph *parag = fParag;
2897 while ( parag ) { 2903 while ( parag ) {
2898 parag->invalidate( 0 ); 2904 parag->invalidate( 0 );
2899 if ( p ) 2905 if ( p )
2900 parag->adjustToPainter( p ); 2906 parag->adjustToPainter( p );
2901 parag->format(); 2907 parag->format();
2902 parag = parag->next(); 2908 parag = parag->next();
2903 } 2909 }
2904 QTextFormat::setPainter( oldPainter ); 2910 QTextFormat::setPainter( oldPainter );
2905} 2911}
2906 2912
2907QPixmap *QTextDocument::bufferPixmap( const QSize &s ) 2913QPixmap *QTextDocument::bufferPixmap( const QSize &s )
2908{ 2914{
2909 if ( !buf_pixmap ) 2915 if ( !buf_pixmap )
2910 buf_pixmap = new QPixmap( s.expandedTo( QSize(1,1) ) ); 2916 buf_pixmap = new QPixmap( s.expandedTo( QSize(1,1) ) );
2911 else if ( buf_pixmap->size() != s ) 2917 else if ( buf_pixmap->size() != s )
2912 buf_pixmap->resize( s.expandedTo( buf_pixmap->size() ) ); 2918 buf_pixmap->resize( s.expandedTo( buf_pixmap->size() ) );
2913 return buf_pixmap; 2919 return buf_pixmap;
2914} 2920}
2915 2921
2916void QTextDocument::draw( QPainter *p, const QRect &rect, const QColorGroup &cg, const QBrush *paper ) 2922void QTextDocument::draw( QPainter *p, const QRect &rect, const QColorGroup &cg, const QBrush *paper )
2917{ 2923{
2918 if ( !firstParagraph() ) 2924 if ( !firstParagraph() )
2919 return; 2925 return;
2920 2926
2921 if ( paper ) { 2927 if ( paper ) {
2922 p->setBrushOrigin( 0, 0 ); 2928 p->setBrushOrigin( 0, 0 );
2923 2929
2924 p->fillRect( rect, *paper ); 2930 p->fillRect( rect, *paper );
2925 } 2931 }
2926 2932
2927 if ( formatCollection()->defaultFormat()->color() != cg.text() ) 2933 if ( formatCollection()->defaultFormat()->color() != cg.text() )
2928 setDefaultFormat( formatCollection()->defaultFormat()->font(), cg.text() ); 2934 setDefaultFormat( formatCollection()->defaultFormat()->font(), cg.text() );
2929 2935
2930 QTextParagraph *parag = firstParagraph(); 2936 QTextParagraph *parag = firstParagraph();
2931 while ( parag ) { 2937 while ( parag ) {
2932 if ( !parag->isValid() ) 2938 if ( !parag->isValid() )
2933 parag->format(); 2939 parag->format();
2934 int y = parag->rect().y(); 2940 int y = parag->rect().y();
2935 QRect pr( parag->rect() ); 2941 QRect pr( parag->rect() );
2936 pr.setX( 0 ); 2942 pr.setX( 0 );
2937 pr.setWidth( QWIDGETSIZE_MAX ); 2943 pr.setWidth( QWIDGETSIZE_MAX );
2938 if ( !rect.isNull() && !rect.intersects( pr ) ) { 2944 if ( !rect.isNull() && !rect.intersects( pr ) ) {
2939 parag = parag->next(); 2945 parag = parag->next();
2940 continue; 2946 continue;
2941 } 2947 }
2942 p->translate( 0, y ); 2948 p->translate( 0, y );
2943 if ( rect.isValid() ) 2949 if ( rect.isValid() )
2944 parag->paint( *p, cg, 0, FALSE, rect.x(), rect.y(), rect.width(), rect.height() ); 2950 parag->paint( *p, cg, 0, FALSE, rect.x(), rect.y(), rect.width(), rect.height() );
2945 else 2951 else
2946 parag->paint( *p, cg, 0, FALSE ); 2952 parag->paint( *p, cg, 0, FALSE );
2947 p->translate( 0, -y ); 2953 p->translate( 0, -y );
2948 parag = parag->next(); 2954 parag = parag->next();
2949 if ( !flow()->isEmpty() ) 2955 if ( !flow()->isEmpty() )
2950 flow()->drawFloatingItems( p, rect.x(), rect.y(), rect.width(), rect.height(), cg, FALSE ); 2956 flow()->drawFloatingItems( p, rect.x(), rect.y(), rect.width(), rect.height(), cg, FALSE );
2951 } 2957 }
2952} 2958}
2953 2959
2954void QTextDocument::drawParagraph( QPainter *p, QTextParagraph *parag, int cx, int cy, int cw, int ch, 2960void QTextDocument::drawParagraph( QPainter *p, QTextParagraph *parag, int cx, int cy, int cw, int ch,
2955 QPixmap *&doubleBuffer, const QColorGroup &cg, 2961 QPixmap *&doubleBuffer, const QColorGroup &cg,
2956 bool drawCursor, QTextCursor *cursor, bool resetChanged ) 2962 bool drawCursor, QTextCursor *cursor, bool resetChanged )
2957{ 2963{
2958 QPainter *painter = 0; 2964 QPainter *painter = 0;
2959 if ( resetChanged ) 2965 if ( resetChanged )
2960 parag->setChanged( FALSE ); 2966 parag->setChanged( FALSE );
2961 QRect ir( parag->rect() ); 2967 QRect ir( parag->rect() );
2962 bool useDoubleBuffer = !parag->document()->parent(); 2968 bool useDoubleBuffer = !parag->document()->parent();
2963 if ( !useDoubleBuffer && parag->document()->nextDoubleBuffered ) 2969 if ( !useDoubleBuffer && parag->document()->nextDoubleBuffered )
2964 useDoubleBuffer = TRUE; 2970 useDoubleBuffer = TRUE;
2965 if ( is_printer( p ) ) 2971 if ( is_printer( p ) )
2966 useDoubleBuffer = FALSE; 2972 useDoubleBuffer = FALSE;
2967 2973
2968 if ( useDoubleBuffer ) { 2974 if ( useDoubleBuffer ) {
2969 painter = new QPainter; 2975 painter = new QPainter;
2970 if ( cx >= 0 && cy >= 0 ) 2976 if ( cx >= 0 && cy >= 0 )
2971 ir = ir.intersect( QRect( cx, cy, cw, ch ) ); 2977 ir = ir.intersect( QRect( cx, cy, cw, ch ) );
2972 if ( !doubleBuffer || 2978 if ( !doubleBuffer ||
2973 ir.width() > doubleBuffer->width() || 2979 ir.width() > doubleBuffer->width() ||
2974 ir.height() > doubleBuffer->height() ) { 2980 ir.height() > doubleBuffer->height() ) {
2975 doubleBuffer = bufferPixmap( ir.size() ); 2981 doubleBuffer = bufferPixmap( ir.size() );
2976 painter->begin( doubleBuffer ); 2982 painter->begin( doubleBuffer );
2977 } else { 2983 } else {
2978 painter->begin( doubleBuffer ); 2984 painter->begin( doubleBuffer );
2979 } 2985 }
2980 } else { 2986 } else {
2981 painter = p; 2987 painter = p;
2982 painter->translate( ir.x(), ir.y() ); 2988 painter->translate( ir.x(), ir.y() );
2983 } 2989 }
2984 2990
2985 painter->setBrushOrigin( -ir.x(), -ir.y() ); 2991 painter->setBrushOrigin( -ir.x(), -ir.y() );
2986 2992
2987 if ( useDoubleBuffer || is_printer( painter ) ) 2993 if ( useDoubleBuffer || is_printer( painter ) )
2988 painter->fillRect( QRect( 0, 0, ir.width(), ir.height() ), parag->backgroundBrush( cg ) ); 2994 painter->fillRect( QRect( 0, 0, ir.width(), ir.height() ), parag->backgroundBrush( cg ) );
2989 else if ( cursor && cursor->paragraph() == parag ) 2995 else if ( cursor && cursor->paragraph() == parag )
2990 painter->fillRect( QRect( parag->at( cursor->index() )->x, 0, 2, ir.height() ), 2996 painter->fillRect( QRect( parag->at( cursor->index() )->x, 0, 2, ir.height() ),
2991 parag->backgroundBrush( cg ) ); 2997 parag->backgroundBrush( cg ) );
2992 2998
2993 painter->translate( -( ir.x() - parag->rect().x() ), 2999 painter->translate( -( ir.x() - parag->rect().x() ),
2994 -( ir.y() - parag->rect().y() ) ); 3000 -( ir.y() - parag->rect().y() ) );
2995 parag->paint( *painter, cg, drawCursor ? cursor : 0, TRUE, cx, cy, cw, ch ); 3001 parag->paint( *painter, cg, drawCursor ? cursor : 0, TRUE, cx, cy, cw, ch );
2996 3002
2997 if ( useDoubleBuffer ) { 3003 if ( useDoubleBuffer ) {
2998 delete painter; 3004 delete painter;
2999 painter = 0; 3005 painter = 0;
3000 p->drawPixmap( ir.topLeft(), *doubleBuffer, QRect( QPoint( 0, 0 ), ir.size() ) ); 3006 p->drawPixmap( ir.topLeft(), *doubleBuffer, QRect( QPoint( 0, 0 ), ir.size() ) );
3001 } else { 3007 } else {
3002 painter->translate( -ir.x(), -ir.y() ); 3008 painter->translate( -ir.x(), -ir.y() );
3003 } 3009 }
3004 3010
3005 if ( useDoubleBuffer ) { 3011 if ( useDoubleBuffer ) {
3006 if ( parag->rect().x() + parag->rect().width() < parag->document()->x() + parag->document()->width() ) { 3012 if ( parag->rect().x() + parag->rect().width() < parag->document()->x() + parag->document()->width() ) {
3007 p->fillRect( parag->rect().x() + parag->rect().width(), parag->rect().y(), 3013 p->fillRect( parag->rect().x() + parag->rect().width(), parag->rect().y(),
3008 ( parag->document()->x() + parag->document()->width() ) - 3014 ( parag->document()->x() + parag->document()->width() ) -
3009 ( parag->rect().x() + parag->rect().width() ), 3015 ( parag->rect().x() + parag->rect().width() ),
3010 parag->rect().height(), cg.brush( QColorGroup::Base ) ); 3016 parag->rect().height(), cg.brush( QColorGroup::Base ) );
3011 } 3017 }
3012 } 3018 }
3013 3019
3014 parag->document()->nextDoubleBuffered = FALSE; 3020 parag->document()->nextDoubleBuffered = FALSE;
3015} 3021}
3016 3022
3017QTextParagraph *QTextDocument::draw( QPainter *p, int cx, int cy, int cw, int ch, const QColorGroup &cg, 3023QTextParagraph *QTextDocument::draw( QPainter *p, int cx, int cy, int cw, int ch, const QColorGroup &cg,
3018 bool onlyChanged, bool drawCursor, QTextCursor *cursor, bool resetChanged ) 3024 bool onlyChanged, bool drawCursor, QTextCursor *cursor, bool resetChanged )
3019{ 3025{
3020 if ( withoutDoubleBuffer || par && par->withoutDoubleBuffer ) { 3026 if ( withoutDoubleBuffer || par && par->withoutDoubleBuffer ) {
3021 withoutDoubleBuffer = TRUE; 3027 withoutDoubleBuffer = TRUE;
3022 QRect r; 3028 QRect r;
3023 draw( p, r, cg ); 3029 draw( p, r, cg );
3024 return 0; 3030 return 0;
3025 } 3031 }
3026 withoutDoubleBuffer = FALSE; 3032 withoutDoubleBuffer = FALSE;
3027 3033
3028 if ( !firstParagraph() ) 3034 if ( !firstParagraph() )
3029 return 0; 3035 return 0;
3030 3036
3031 if ( cx < 0 && cy < 0 ) { 3037 if ( cx < 0 && cy < 0 ) {
3032 cx = 0; 3038 cx = 0;
3033 cy = 0; 3039 cy = 0;
3034 cw = width(); 3040 cw = width();
3035 ch = height(); 3041 ch = height();
3036 } 3042 }
3037 3043
3038 QTextParagraph *lastFormatted = 0; 3044 QTextParagraph *lastFormatted = 0;
3039 QTextParagraph *parag = firstParagraph(); 3045 QTextParagraph *parag = firstParagraph();
3040 3046
3041 QPixmap *doubleBuffer = 0; 3047 QPixmap *doubleBuffer = 0;
3042 QPainter painter; 3048 QPainter painter;
3043 3049
3044 bool fullWidthSelection = FALSE; 3050 bool fullWidthSelection = FALSE;
3045 while ( parag ) { 3051 while ( parag ) {
3046 lastFormatted = parag; 3052 lastFormatted = parag;
3047 if ( !parag->isValid() ) 3053 if ( !parag->isValid() )
3048 parag->format(); 3054 parag->format();
3049 3055
3050 QRect pr = parag->rect(); 3056 QRect pr = parag->rect();
3051 if ( fullWidthSelection ) 3057 if ( fullWidthSelection )
3052 pr.setWidth( parag->document()->width() ); 3058 pr.setWidth( parag->document()->width() );
3053 if ( pr.y() > cy + ch ) 3059 if ( pr.y() > cy + ch )
3054 goto floating; 3060 goto floating;
3055 if ( !pr.intersects( QRect( cx, cy, cw, ch ) ) || ( onlyChanged && !parag->hasChanged() ) ) { 3061 if ( !pr.intersects( QRect( cx, cy, cw, ch ) ) || ( onlyChanged && !parag->hasChanged() ) ) {
3056 parag = parag->next(); 3062 parag = parag->next();
3057 continue; 3063 continue;
3058 } 3064 }
3059 3065
3060 drawParagraph( p, parag, cx, cy, cw, ch, doubleBuffer, cg, drawCursor, cursor, resetChanged ); 3066 drawParagraph( p, parag, cx, cy, cw, ch, doubleBuffer, cg, drawCursor, cursor, resetChanged );
3061 parag = parag->next(); 3067 parag = parag->next();
3062 } 3068 }
3063 3069
3064 parag = lastParagraph(); 3070 parag = lastParagraph();
3065 3071
3066 floating: 3072 floating:
3067 if ( parag->rect().y() + parag->rect().height() < parag->document()->height() ) { 3073 if ( parag->rect().y() + parag->rect().height() < parag->document()->height() ) {
3068 if ( !parag->document()->parent() ) { 3074 if ( !parag->document()->parent() ) {
3069 p->fillRect( 0, parag->rect().y() + parag->rect().height(), parag->document()->width(), 3075 p->fillRect( 0, parag->rect().y() + parag->rect().height(), parag->document()->width(),
3070 parag->document()->height() - ( parag->rect().y() + parag->rect().height() ), 3076 parag->document()->height() - ( parag->rect().y() + parag->rect().height() ),
3071 cg.brush( QColorGroup::Base ) ); 3077 cg.brush( QColorGroup::Base ) );
3072 } 3078 }
3073 if ( !flow()->isEmpty() ) { 3079 if ( !flow()->isEmpty() ) {
3074 QRect cr( cx, cy, cw, ch ); 3080 QRect cr( cx, cy, cw, ch );
3075 flow()->drawFloatingItems( p, cr.x(), cr.y(), cr.width(), cr.height(), cg, FALSE ); 3081 flow()->drawFloatingItems( p, cr.x(), cr.y(), cr.width(), cr.height(), cg, FALSE );
3076 } 3082 }
3077 } 3083 }
3078 3084
3079 if ( buf_pixmap && buf_pixmap->height() > 300 ) { 3085 if ( buf_pixmap && buf_pixmap->height() > 300 ) {
3080 delete buf_pixmap; 3086 delete buf_pixmap;
3081 buf_pixmap = 0; 3087 buf_pixmap = 0;
3082 } 3088 }
3083 3089
3084 return lastFormatted; 3090 return lastFormatted;
3085} 3091}
3086 3092
3087/* 3093/*
3088 #### this function only sets the default font size in the format collection 3094 #### this function only sets the default font size in the format collection
3089 */ 3095 */
3090void QTextDocument::setDefaultFormat( const QFont &font, const QColor &color ) 3096void QTextDocument::setDefaultFormat( const QFont &font, const QColor &color )
3091{ 3097{
3092 bool reformat = font != fCollection->defaultFormat()->font(); 3098 bool reformat = font != fCollection->defaultFormat()->font();
3093 for ( QTextDocument *d = childList.first(); d; d = childList.next() ) 3099 for ( QTextDocument *d = childList.first(); d; d = childList.next() )
3094 d->setDefaultFormat( font, color ); 3100 d->setDefaultFormat( font, color );
3095 fCollection->updateDefaultFormat( font, color, sheet_ ); 3101 fCollection->updateDefaultFormat( font, color, sheet_ );
3096 3102
3097 if ( !reformat ) 3103 if ( !reformat )
3098 return; 3104 return;
3099 tStopWidth = formatCollection()->defaultFormat()->width( 'x' ) * 8; 3105 tStopWidth = formatCollection()->defaultFormat()->width( 'x' ) * 8;
3100 3106
3101 // invalidate paragraphs and custom items 3107 // invalidate paragraphs and custom items
3102 QTextParagraph *p = fParag; 3108 QTextParagraph *p = fParag;
3103 while ( p ) { 3109 while ( p ) {
3104 p->invalidate( 0 ); 3110 p->invalidate( 0 );
3105 for ( int i = 0; i < p->length() - 1; ++i ) 3111 for ( int i = 0; i < p->length() - 1; ++i )
3106 if ( p->at( i )->isCustom() ) 3112 if ( p->at( i )->isCustom() )
3107 p->at( i )->customItem()->invalidate(); 3113 p->at( i )->customItem()->invalidate();
3108 p = p->next(); 3114 p = p->next();
3109 } 3115 }
3110} 3116}
3111 3117
3112void QTextDocument::registerCustomItem( QTextCustomItem *i, QTextParagraph *p ) 3118void QTextDocument::registerCustomItem( QTextCustomItem *i, QTextParagraph *p )
3113{ 3119{
3114 if ( i && i->placement() != QTextCustomItem::PlaceInline ) { 3120 if ( i && i->placement() != QTextCustomItem::PlaceInline ) {
3115 flow_->registerFloatingItem( i ); 3121 flow_->registerFloatingItem( i );
3116 p->registerFloatingItem( i ); 3122 p->registerFloatingItem( i );
3117 i->setParagraph( p ); 3123 i->setParagraph( p );
3118 } 3124 }
3119 p->mightHaveCustomItems = mightHaveCustomItems = TRUE; 3125 p->mightHaveCustomItems = mightHaveCustomItems = TRUE;
3120} 3126}
3121 3127
3122void QTextDocument::unregisterCustomItem( QTextCustomItem *i, QTextParagraph *p ) 3128void QTextDocument::unregisterCustomItem( QTextCustomItem *i, QTextParagraph *p )
3123{ 3129{
3124 flow_->unregisterFloatingItem( i ); 3130 flow_->unregisterFloatingItem( i );
3125 p->unregisterFloatingItem( i ); 3131 p->unregisterFloatingItem( i );
3126 i->setParagraph( 0 ); 3132 i->setParagraph( 0 );
3127} 3133}
3128 3134
3129bool QTextDocument::hasFocusParagraph() const 3135bool QTextDocument::hasFocusParagraph() const
3130{ 3136{
3131 return !!focusIndicator.parag; 3137 return !!focusIndicator.parag;
3132} 3138}
3133 3139
3134QString QTextDocument::focusHref() const 3140QString QTextDocument::focusHref() const
3135{ 3141{
3136 return focusIndicator.href; 3142 return focusIndicator.href;
3137} 3143}
3138 3144
3139bool QTextDocument::focusNextPrevChild( bool next ) 3145bool QTextDocument::focusNextPrevChild( bool next )
3140{ 3146{
3141 if ( !focusIndicator.parag ) { 3147 if ( !focusIndicator.parag ) {
3142 if ( next ) { 3148 if ( next ) {
3143 focusIndicator.parag = fParag; 3149 focusIndicator.parag = fParag;
3144 focusIndicator.start = 0; 3150 focusIndicator.start = 0;
3145 focusIndicator.len = 0; 3151 focusIndicator.len = 0;
3146 } else { 3152 } else {
3147 focusIndicator.parag = lParag; 3153 focusIndicator.parag = lParag;
3148 focusIndicator.start = lParag->length(); 3154 focusIndicator.start = lParag->length();
3149 focusIndicator.len = 0; 3155 focusIndicator.len = 0;
3150 } 3156 }
3151 } else { 3157 } else {
3152 focusIndicator.parag->setChanged( TRUE ); 3158 focusIndicator.parag->setChanged( TRUE );
3153 } 3159 }
3154 focusIndicator.href = QString::null; 3160 focusIndicator.href = QString::null;
3155 3161
3156 if ( next ) { 3162 if ( next ) {
3157 QTextParagraph *p = focusIndicator.parag; 3163 QTextParagraph *p = focusIndicator.parag;
3158 int index = focusIndicator.start + focusIndicator.len; 3164 int index = focusIndicator.start + focusIndicator.len;
3159 while ( p ) { 3165 while ( p ) {
3160 for ( int i = index; i < p->length(); ++i ) { 3166 for ( int i = index; i < p->length(); ++i ) {
3161 if ( p->at( i )->isAnchor() ) { 3167 if ( p->at( i )->isAnchor() ) {
3162 p->setChanged( TRUE ); 3168 p->setChanged( TRUE );
3163 focusIndicator.parag = p; 3169 focusIndicator.parag = p;
3164 focusIndicator.start = i; 3170 focusIndicator.start = i;
3165 focusIndicator.len = 0; 3171 focusIndicator.len = 0;
3166 focusIndicator.href = p->at( i )->anchorHref(); 3172 focusIndicator.href = p->at( i )->anchorHref();
3167 while ( i < p->length() ) { 3173 while ( i < p->length() ) {
3168 if ( !p->at( i )->isAnchor() ) 3174 if ( !p->at( i )->isAnchor() )
3169 return TRUE; 3175 return TRUE;
3170 focusIndicator.len++; 3176 focusIndicator.len++;
3171 i++; 3177 i++;
3172 } 3178 }
3173 } else if ( p->at( i )->isCustom() ) { 3179 } else if ( p->at( i )->isCustom() ) {
3174 if ( p->at( i )->customItem()->isNested() ) { 3180 if ( p->at( i )->customItem()->isNested() ) {
3175 QTextTable *t = (QTextTable*)p->at( i )->customItem(); 3181 QTextTable *t = (QTextTable*)p->at( i )->customItem();
3176 QPtrList<QTextTableCell> cells = t->tableCells(); 3182 QPtrList<QTextTableCell> cells = t->tableCells();
3177 // first try to continue 3183 // first try to continue
3178 QTextTableCell *c; 3184 QTextTableCell *c;
3179 bool resetCells = TRUE; 3185 bool resetCells = TRUE;
3180 for ( c = cells.first(); c; c = cells.next() ) { 3186 for ( c = cells.first(); c; c = cells.next() ) {
3181 if ( c->richText()->hasFocusParagraph() ) { 3187 if ( c->richText()->hasFocusParagraph() ) {
3182 if ( c->richText()->focusNextPrevChild( next ) ) { 3188 if ( c->richText()->focusNextPrevChild( next ) ) {
3183 p->setChanged( TRUE ); 3189 p->setChanged( TRUE );
3184 focusIndicator.parag = p; 3190 focusIndicator.parag = p;
3185 focusIndicator.start = i; 3191 focusIndicator.start = i;
3186 focusIndicator.len = 0; 3192 focusIndicator.len = 0;
3187 focusIndicator.href = c->richText()->focusHref(); 3193 focusIndicator.href = c->richText()->focusHref();
3188 return TRUE; 3194 return TRUE;
3189 } else { 3195 } else {
3190 resetCells = FALSE; 3196 resetCells = FALSE;
3191 c = cells.next(); 3197 c = cells.next();
3192 break; 3198 break;
3193 } 3199 }
3194 } 3200 }
3195 } 3201 }
3196 // now really try 3202 // now really try
3197 if ( resetCells ) 3203 if ( resetCells )
3198 c = cells.first(); 3204 c = cells.first();
3199 for ( ; c; c = cells.next() ) { 3205 for ( ; c; c = cells.next() ) {
3200 if ( c->richText()->focusNextPrevChild( next ) ) { 3206 if ( c->richText()->focusNextPrevChild( next ) ) {
3201 p->setChanged( TRUE ); 3207 p->setChanged( TRUE );
3202 focusIndicator.parag = p; 3208 focusIndicator.parag = p;
3203 focusIndicator.start = i; 3209 focusIndicator.start = i;
3204 focusIndicator.len = 0; 3210 focusIndicator.len = 0;
3205 focusIndicator.href = c->richText()->focusHref(); 3211 focusIndicator.href = c->richText()->focusHref();
3206 return TRUE; 3212 return TRUE;
3207 } 3213 }
3208 } 3214 }
3209 } 3215 }
3210 } 3216 }
3211 } 3217 }
3212 index = 0; 3218 index = 0;
3213 p = p->next(); 3219 p = p->next();
3214 } 3220 }
3215 } else { 3221 } else {
3216 QTextParagraph *p = focusIndicator.parag; 3222 QTextParagraph *p = focusIndicator.parag;
3217 int index = focusIndicator.start - 1; 3223 int index = focusIndicator.start - 1;
3218 if ( focusIndicator.len == 0 && index < focusIndicator.parag->length() - 1 ) 3224 if ( focusIndicator.len == 0 && index < focusIndicator.parag->length() - 1 )
3219 index++; 3225 index++;
3220 while ( p ) { 3226 while ( p ) {
3221 for ( int i = index; i >= 0; --i ) { 3227 for ( int i = index; i >= 0; --i ) {
3222 if ( p->at( i )->isAnchor() ) { 3228 if ( p->at( i )->isAnchor() ) {
3223 p->setChanged( TRUE ); 3229 p->setChanged( TRUE );
3224 focusIndicator.parag = p; 3230 focusIndicator.parag = p;
3225 focusIndicator.start = i; 3231 focusIndicator.start = i;
3226 focusIndicator.len = 0; 3232 focusIndicator.len = 0;
3227 focusIndicator.href = p->at( i )->anchorHref(); 3233 focusIndicator.href = p->at( i )->anchorHref();
3228 while ( i >= -1 ) { 3234 while ( i >= -1 ) {
3229 if ( i < 0 || !p->at( i )->isAnchor() ) { 3235 if ( i < 0 || !p->at( i )->isAnchor() ) {
3230 focusIndicator.start++; 3236 focusIndicator.start++;
3231 return TRUE; 3237 return TRUE;
3232 } 3238 }
3233 if ( i < 0 ) 3239 if ( i < 0 )
3234 break; 3240 break;
3235 focusIndicator.len++; 3241 focusIndicator.len++;
3236 focusIndicator.start--; 3242 focusIndicator.start--;
3237 i--; 3243 i--;
3238 } 3244 }
3239 } else if ( p->at( i )->isCustom() ) { 3245 } else if ( p->at( i )->isCustom() ) {
3240 if ( p->at( i )->customItem()->isNested() ) { 3246 if ( p->at( i )->customItem()->isNested() ) {
3241 QTextTable *t = (QTextTable*)p->at( i )->customItem(); 3247 QTextTable *t = (QTextTable*)p->at( i )->customItem();
3242 QPtrList<QTextTableCell> cells = t->tableCells(); 3248 QPtrList<QTextTableCell> cells = t->tableCells();
3243 // first try to continue 3249 // first try to continue
3244 QTextTableCell *c; 3250 QTextTableCell *c;
3245 bool resetCells = TRUE; 3251 bool resetCells = TRUE;
3246 for ( c = cells.last(); c; c = cells.prev() ) { 3252 for ( c = cells.last(); c; c = cells.prev() ) {
3247 if ( c->richText()->hasFocusParagraph() ) { 3253 if ( c->richText()->hasFocusParagraph() ) {
3248 if ( c->richText()->focusNextPrevChild( next ) ) { 3254 if ( c->richText()->focusNextPrevChild( next ) ) {
3249 p->setChanged( TRUE ); 3255 p->setChanged( TRUE );
3250 focusIndicator.parag = p; 3256 focusIndicator.parag = p;
3251 focusIndicator.start = i; 3257 focusIndicator.start = i;
3252 focusIndicator.len = 0; 3258 focusIndicator.len = 0;
3253 focusIndicator.href = c->richText()->focusHref(); 3259 focusIndicator.href = c->richText()->focusHref();
3254 return TRUE; 3260 return TRUE;
3255 } else { 3261 } else {
3256 resetCells = FALSE; 3262 resetCells = FALSE;
3257 c = cells.prev(); 3263 c = cells.prev();
3258 break; 3264 break;
3259 } 3265 }
3260 } 3266 }
3261 if ( cells.at() == 0 ) 3267 if ( cells.at() == 0 )
3262 break; 3268 break;
3263 } 3269 }
3264 // now really try 3270 // now really try
3265 if ( resetCells ) 3271 if ( resetCells )
3266 c = cells.last(); 3272 c = cells.last();
3267 for ( ; c; c = cells.prev() ) { 3273 for ( ; c; c = cells.prev() ) {
3268 if ( c->richText()->focusNextPrevChild( next ) ) { 3274 if ( c->richText()->focusNextPrevChild( next ) ) {
3269 p->setChanged( TRUE ); 3275 p->setChanged( TRUE );
3270 focusIndicator.parag = p; 3276 focusIndicator.parag = p;
3271 focusIndicator.start = i; 3277 focusIndicator.start = i;
3272 focusIndicator.len = 0; 3278 focusIndicator.len = 0;
3273 focusIndicator.href = c->richText()->focusHref(); 3279 focusIndicator.href = c->richText()->focusHref();
3274 return TRUE; 3280 return TRUE;
3275 } 3281 }
3276 if ( cells.at() == 0 ) 3282 if ( cells.at() == 0 )
3277 break; 3283 break;
3278 } 3284 }
3279 } 3285 }
3280 } 3286 }
3281 } 3287 }
3282 p = p->prev(); 3288 p = p->prev();
3283 if ( p ) 3289 if ( p )
3284 index = p->length() - 1; 3290 index = p->length() - 1;
3285 } 3291 }
3286 } 3292 }
3287 3293
3288 focusIndicator.parag = 0; 3294 focusIndicator.parag = 0;
3289 3295
3290 return FALSE; 3296 return FALSE;
3291} 3297}
3292 3298
3293int QTextDocument::length() const 3299int QTextDocument::length() const
3294{ 3300{
3295 int l = 0; 3301 int l = 0;
3296 QTextParagraph *p = fParag; 3302 QTextParagraph *p = fParag;
3297 while ( p ) { 3303 while ( p ) {
3298 l += p->length() - 1; // don't count trailing space 3304 l += p->length() - 1; // don't count trailing space
3299 p = p->next(); 3305 p = p->next();
3300 } 3306 }
3301 return l; 3307 return l;
3302} 3308}
3303 3309
3304// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3310// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3305 3311
3306int QTextFormat::width( const QChar &c ) const 3312int QTextFormat::width( const QChar &c ) const
3307{ 3313{
3308 if ( c.unicode() == 0xad ) // soft hyphen 3314 if ( c.unicode() == 0xad ) // soft hyphen
3309 return 0; 3315 return 0;
3310 if ( !pntr || !pntr->isActive() ) { 3316 if ( !pntr || !pntr->isActive() ) {
3311 if ( c == '\t' ) 3317 if ( c == '\t' )
3312 return fm.width( 'x' ) * 8; 3318 return fm.width( 'x' ) * 8;
3313 if ( ha == AlignNormal ) { 3319 if ( ha == AlignNormal ) {
3314 int w; 3320 int w;
3315 if ( c.row() ) 3321 if ( c.row() )
3316 w = fm.width( c ); 3322 w = fm.width( c );
3317 else 3323 else
3318 w = widths[ c.unicode() ]; 3324 w = widths[ c.unicode() ];
3319 if ( w == 0 && !c.row() ) { 3325 if ( w == 0 && !c.row() ) {
3320 w = fm.width( c ); 3326 w = fm.width( c );
3321 ( (QTextFormat*)this )->widths[ c.unicode() ] = w; 3327 ( (QTextFormat*)this )->widths[ c.unicode() ] = w;
3322 } 3328 }
3323 return w; 3329 return w;
3324 } else { 3330 } else {
3325 QFont f( fn ); 3331 QFont f( fn );
3326 if ( usePixelSizes ) 3332 if ( usePixelSizes )
3327 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 ); 3333 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 );
3328 else 3334 else
3329 f.setPointSize( ( f.pointSize() * 2 ) / 3 ); 3335 f.setPointSize( ( f.pointSize() * 2 ) / 3 );
3330 QFontMetrics fm_( f ); 3336 QFontMetrics fm_( f );
3331 return fm_.width( c ); 3337 return fm_.width( c );
3332 } 3338 }
3333 } 3339 }
3334 3340
3335 QFont f( fn ); 3341 QFont f( fn );
3336 if ( ha != AlignNormal ) { 3342 if ( ha != AlignNormal ) {
3337 if ( usePixelSizes ) 3343 if ( usePixelSizes )
3338 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 ); 3344 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 );
3339 else 3345 else
3340 f.setPointSize( ( f.pointSize() * 2 ) / 3 ); 3346 f.setPointSize( ( f.pointSize() * 2 ) / 3 );
3341 } 3347 }
3342 pntr->setFont( f ); 3348 pntr->setFont( f );
3343 3349
3344 return pntr->fontMetrics().width( c ); 3350 return pntr->fontMetrics().width( c );
3345} 3351}
3346 3352
3347int QTextFormat::width( const QString &str, int pos ) const 3353int QTextFormat::width( const QString &str, int pos ) const
3348{ 3354{
3349 int w = 0; 3355 int w = 0;
3350 if ( str[ pos ].unicode() == 0xad ) 3356 if ( str[ pos ].unicode() == 0xad )
3351 return w; 3357 return w;
3352 if ( !pntr || !pntr->isActive() ) { 3358 if ( !pntr || !pntr->isActive() ) {
3353 if ( ha == AlignNormal ) { 3359 if ( ha == AlignNormal ) {
3354 w = fm.width( str[ pos ] ); 3360 w = fm.width( str[ pos ] );
3355 } else { 3361 } else {
3356 QFont f( fn ); 3362 QFont f( fn );
3357 if ( usePixelSizes ) 3363 if ( usePixelSizes )
3358 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 ); 3364 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 );
3359 else 3365 else
3360 f.setPointSize( ( f.pointSize() * 2 ) / 3 ); 3366 f.setPointSize( ( f.pointSize() * 2 ) / 3 );
3361 QFontMetrics fm_( f ); 3367 QFontMetrics fm_( f );
3362 w = fm_.width( str[ pos ] ); 3368 w = fm_.width( str[ pos ] );
3363 } 3369 }
3364 } else { 3370 } else {
3365 QFont f( fn ); 3371 QFont f( fn );
3366 if ( ha != AlignNormal ) { 3372 if ( ha != AlignNormal ) {
3367 if ( usePixelSizes ) 3373 if ( usePixelSizes )
3368 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 ); 3374 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 );
3369 else 3375 else
3370 f.setPointSize( ( f.pointSize() * 2 ) / 3 ); 3376 f.setPointSize( ( f.pointSize() * 2 ) / 3 );
3371 } 3377 }
3372 pntr->setFont( f ); 3378 pntr->setFont( f );
3373 w = pntr->fontMetrics().width( str[ pos ] ); 3379 w = pntr->fontMetrics().width( str[ pos ] );
3374 } 3380 }
3375 return w; 3381 return w;
3376} 3382}
3377 3383
3378// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3384// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3379 3385
3380QTextString::QTextString() 3386QTextString::QTextString()
3381{ 3387{
3382 bidiDirty = FALSE; 3388 bidiDirty = FALSE;
3383 bidi = FALSE; 3389 bidi = FALSE;
3384 rightToLeft = FALSE; 3390 rightToLeft = FALSE;
3385 dir = QChar::DirON; 3391 dir = QChar::DirON;
3386} 3392}
3387 3393
3388QTextString::QTextString( const QTextString &s ) 3394QTextString::QTextString( const QTextString &s )
3389{ 3395{
3390 bidiDirty = s.bidiDirty; 3396 bidiDirty = s.bidiDirty;
3391 bidi = s.bidi; 3397 bidi = s.bidi;
3392 rightToLeft = s.rightToLeft; 3398 rightToLeft = s.rightToLeft;
3393 dir = s.dir; 3399 dir = s.dir;
3394 data = s.subString(); 3400 data = s.subString();
3395} 3401}
3396 3402
3397void QTextString::insert( int index, const QString &s, QTextFormat *f ) 3403void QTextString::insert( int index, const QString &s, QTextFormat *f )
3398{ 3404{
3399 insert( index, s.unicode(), s.length(), f ); 3405 insert( index, s.unicode(), s.length(), f );
3400} 3406}
3401 3407
3402void QTextString::insert( int index, const QChar *unicode, int len, QTextFormat *f ) 3408void QTextString::insert( int index, const QChar *unicode, int len, QTextFormat *f )
3403{ 3409{
3404 int os = data.size(); 3410 int os = data.size();
3405 data.resize( data.size() + len ); 3411 data.resize( data.size() + len );
3406 if ( index < os ) { 3412 if ( index < os ) {
3407 memmove( data.data() + index + len, data.data() + index, 3413 memmove( data.data() + index + len, data.data() + index,
3408 sizeof( QTextStringChar ) * ( os - index ) ); 3414 sizeof( QTextStringChar ) * ( os - index ) );
3409 } 3415 }
3410 for ( int i = 0; i < len; ++i ) { 3416 for ( int i = 0; i < len; ++i ) {
3411 data[ (int)index + i ].x = 0; 3417 data[ (int)index + i ].x = 0;
3412 data[ (int)index + i ].lineStart = 0; 3418 data[ (int)index + i ].lineStart = 0;
3413 data[ (int)index + i ].d.format = 0; 3419 data[ (int)index + i ].d.format = 0;
3414 data[ (int)index + i ].type = QTextStringChar::Regular; 3420 data[ (int)index + i ].type = QTextStringChar::Regular;
3415 data[ (int)index + i ].rightToLeft = 0; 3421 data[ (int)index + i ].rightToLeft = 0;
3416 data[ (int)index + i ].startOfRun = 0; 3422 data[ (int)index + i ].startOfRun = 0;
3417 data[ (int)index + i ].c = unicode[i]; 3423 data[ (int)index + i ].c = unicode[i];
3418 data[ (int)index + i ].setFormat( f ); 3424 data[ (int)index + i ].setFormat( f );
3419 } 3425 }
3420 bidiDirty = TRUE; 3426 bidiDirty = TRUE;
3421} 3427}
3422 3428
3423QTextString::~QTextString() 3429QTextString::~QTextString()
3424{ 3430{
3425 clear(); 3431 clear();
3426} 3432}
3427 3433
3428void QTextString::insert( int index, QTextStringChar *c, bool doAddRefFormat ) 3434void QTextString::insert( int index, QTextStringChar *c, bool doAddRefFormat )
3429{ 3435{
3430 int os = data.size(); 3436 int os = data.size();
3431 data.resize( data.size() + 1 ); 3437 data.resize( data.size() + 1 );
3432 if ( index < os ) { 3438 if ( index < os ) {
3433 memmove( data.data() + index + 1, data.data() + index, 3439 memmove( data.data() + index + 1, data.data() + index,
3434 sizeof( QTextStringChar ) * ( os - index ) ); 3440 sizeof( QTextStringChar ) * ( os - index ) );
3435 } 3441 }
3436 data[ (int)index ].c = c->c; 3442 data[ (int)index ].c = c->c;
3437 data[ (int)index ].x = 0; 3443 data[ (int)index ].x = 0;
3438 data[ (int)index ].lineStart = 0; 3444 data[ (int)index ].lineStart = 0;
3439 data[ (int)index ].rightToLeft = 0; 3445 data[ (int)index ].rightToLeft = 0;
3440 data[ (int)index ].d.format = 0; 3446 data[ (int)index ].d.format = 0;
3441 data[ (int)index ].type = QTextStringChar::Regular; 3447 data[ (int)index ].type = QTextStringChar::Regular;
3442 if ( doAddRefFormat && c->format() ) 3448 if ( doAddRefFormat && c->format() )
3443 c->format()->addRef(); 3449 c->format()->addRef();
3444 data[ (int)index ].setFormat( c->format() ); 3450 data[ (int)index ].setFormat( c->format() );
3445 bidiDirty = TRUE; 3451 bidiDirty = TRUE;
3446} 3452}
3447 3453
3448void QTextString::truncate( int index ) 3454void QTextString::truncate( int index )
3449{ 3455{
3450 index = QMAX( index, 0 ); 3456 index = QMAX( index, 0 );
3451 index = QMIN( index, (int)data.size() - 1 ); 3457 index = QMIN( index, (int)data.size() - 1 );
3452 if ( index < (int)data.size() ) { 3458 if ( index < (int)data.size() ) {
3453 for ( int i = index + 1; i < (int)data.size(); ++i ) { 3459 for ( int i = index + 1; i < (int)data.size(); ++i ) {
3454 if ( !(data[ i ].type == QTextStringChar::Regular) ) { 3460 if ( !(data[ i ].type == QTextStringChar::Regular) ) {
3455 delete data[ i ].customItem(); 3461 delete data[ i ].customItem();
3456 if ( data[ i ].d.custom->format ) 3462 if ( data[ i ].d.custom->format )
3457 data[ i ].d.custom->format->removeRef(); 3463 data[ i ].d.custom->format->removeRef();
3458 delete data[ i ].d.custom; 3464 delete data[ i ].d.custom;
3459 data[ i ].d.custom = 0; 3465 data[ i ].d.custom = 0;
3460 } else if ( data[ i ].format() ) { 3466 } else if ( data[ i ].format() ) {
3461 data[ i ].format()->removeRef(); 3467 data[ i ].format()->removeRef();
3462 } 3468 }
3463 } 3469 }
3464 } 3470 }
3465 data.truncate( index ); 3471 data.truncate( index );
3466 bidiDirty = TRUE; 3472 bidiDirty = TRUE;
3467} 3473}
3468 3474
3469void QTextString::remove( int index, int len ) 3475void QTextString::remove( int index, int len )
3470{ 3476{
3471 for ( int i = index; i < (int)data.size() && i - index < len; ++i ) { 3477 for ( int i = index; i < (int)data.size() && i - index < len; ++i ) {
3472 if ( !(data[ i ].type == QTextStringChar::Regular) ) { 3478 if ( !(data[ i ].type == QTextStringChar::Regular) ) {
3473 delete data[ i ].customItem(); 3479 delete data[ i ].customItem();
3474 if ( data[ i ].d.custom->format ) 3480 if ( data[ i ].d.custom->format )
3475 data[ i ].d.custom->format->removeRef(); 3481 data[ i ].d.custom->format->removeRef();
3476 delete data[ i ].d.custom; 3482 delete data[ i ].d.custom;
3477 data[ i ].d.custom = 0; 3483 data[ i ].d.custom = 0;
3478 } else if ( data[ i ].format() ) { 3484 } else if ( data[ i ].format() ) {
3479 data[ i ].format()->removeRef(); 3485 data[ i ].format()->removeRef();
3480 } 3486 }
3481 } 3487 }
3482 memmove( data.data() + index, data.data() + index + len, 3488 memmove( data.data() + index, data.data() + index + len,
3483 sizeof( QTextStringChar ) * ( data.size() - index - len ) ); 3489 sizeof( QTextStringChar ) * ( data.size() - index - len ) );
3484 data.resize( data.size() - len ); 3490 data.resize( data.size() - len );
3485 bidiDirty = TRUE; 3491 bidiDirty = TRUE;
3486} 3492}
3487 3493
3488void QTextString::clear() 3494void QTextString::clear()
3489{ 3495{
3490 for ( int i = 0; i < (int)data.count(); ++i ) { 3496 for ( int i = 0; i < (int)data.count(); ++i ) {
3491 if ( !(data[ i ].type == QTextStringChar::Regular) ) { 3497 if ( !(data[ i ].type == QTextStringChar::Regular) ) {
3492 delete data[ i ].customItem(); 3498 delete data[ i ].customItem();
3493 if ( data[ i ].d.custom->format ) 3499 if ( data[ i ].d.custom->format )
3494 data[ i ].d.custom->format->removeRef(); 3500 data[ i ].d.custom->format->removeRef();
3495 delete data[ i ].d.custom; 3501 delete data[ i ].d.custom;
3496 data[ i ].d.custom = 0; 3502 data[ i ].d.custom = 0;
3497 } else if ( data[ i ].format() ) { 3503 } else if ( data[ i ].format() ) {
3498 data[ i ].format()->removeRef(); 3504 data[ i ].format()->removeRef();
3499 } 3505 }
3500 } 3506 }
3501 data.resize( 0 ); 3507 data.resize( 0 );
3502} 3508}
3503 3509
3504void QTextString::setFormat( int index, QTextFormat *f, bool useCollection ) 3510void QTextString::setFormat( int index, QTextFormat *f, bool useCollection )
3505{ 3511{
3506 if ( useCollection && data[ index ].format() ) 3512 if ( useCollection && data[ index ].format() )
3507 data[ index ].format()->removeRef(); 3513 data[ index ].format()->removeRef();
3508 data[ index ].setFormat( f ); 3514 data[ index ].setFormat( f );
3509} 3515}
3510 3516
3511void QTextString::checkBidi() const 3517void QTextString::checkBidi() const
3512{ 3518{
3513 bool rtlKnown = FALSE; 3519 bool rtlKnown = FALSE;
3514 if ( dir == QChar::DirR ) { 3520 if ( dir == QChar::DirR ) {
3515 ((QTextString *)this)->bidi = TRUE; 3521 ((QTextString *)this)->bidi = TRUE;
3516 ((QTextString *)this)->rightToLeft = TRUE; 3522 ((QTextString *)this)->rightToLeft = TRUE;
3517 rtlKnown = TRUE; 3523 rtlKnown = TRUE;
3518 return; 3524 return;
3519 } else if ( dir == QChar::DirL ) { 3525 } else if ( dir == QChar::DirL ) {
3520 ((QTextString *)this)->rightToLeft = FALSE; 3526 ((QTextString *)this)->rightToLeft = FALSE;
3521 rtlKnown = TRUE; 3527 rtlKnown = TRUE;
3522 } else { 3528 } else {
3523 ((QTextString *)this)->rightToLeft = FALSE; 3529 ((QTextString *)this)->rightToLeft = FALSE;
3524 } 3530 }
3525 3531
3526 int len = data.size(); 3532 int len = data.size();
3527 const QTextStringChar *c = data.data(); 3533 const QTextStringChar *c = data.data();
3528 ((QTextString *)this)->bidi = FALSE; 3534 ((QTextString *)this)->bidi = FALSE;
3529 while( len ) { 3535 while( len ) {
3530 if ( !rtlKnown ) { 3536 if ( !rtlKnown ) {
3531 switch( c->c.direction() ) 3537 switch( c->c.direction() )
3532 { 3538 {
3533 case QChar::DirL: 3539 case QChar::DirL:
3534 case QChar::DirLRO: 3540 case QChar::DirLRO:
3535 case QChar::DirLRE: 3541 case QChar::DirLRE:
3536 ((QTextString *)this)->rightToLeft = FALSE; 3542 ((QTextString *)this)->rightToLeft = FALSE;
3537 rtlKnown = TRUE; 3543 rtlKnown = TRUE;
3538 break; 3544 break;
3539 case QChar::DirR: 3545 case QChar::DirR:
3540 case QChar::DirAL: 3546 case QChar::DirAL:
3541 case QChar::DirRLO: 3547 case QChar::DirRLO:
3542 case QChar::DirRLE: 3548 case QChar::DirRLE:
3543 ((QTextString *)this)->rightToLeft = TRUE; 3549 ((QTextString *)this)->rightToLeft = TRUE;
3544 rtlKnown = TRUE; 3550 rtlKnown = TRUE;
3545 break; 3551 break;
3546 default: 3552 default:
3547 break; 3553 break;
3548 } 3554 }
3549 } 3555 }
3550 uchar row = c->c.row(); 3556 uchar row = c->c.row();
3551 if( (row > 0x04 && row < 0x09) || (row > 0xfa && row < 0xff) ) { 3557 if( (row > 0x04 && row < 0x09) || (row > 0xfa && row < 0xff) ) {
3552 ((QTextString *)this)->bidi = TRUE; 3558 ((QTextString *)this)->bidi = TRUE;
3553 if ( rtlKnown ) 3559 if ( rtlKnown )
3554 return; 3560 return;
3555 } 3561 }
3556 len--; 3562 len--;
3557 ++c; 3563 ++c;
3558 } 3564 }
3559} 3565}
3560 3566
3561void QTextDocument::setStyleSheet( QStyleSheet *s ) 3567void QTextDocument::setStyleSheet( QStyleSheet *s )
3562{ 3568{
3563 if ( !s ) 3569 if ( !s )
3564 return; 3570 return;
3565 sheet_ = s; 3571 sheet_ = s;
3566 list_tm = list_bm = par_tm = par_bm = 12; 3572 list_tm = list_bm = par_tm = par_bm = 12;
3567 list_lm = 40; 3573 list_lm = 40;
3568 li_tm = li_bm = 0; 3574 li_tm = li_bm = 0;
3569 QStyleSheetItem* item = s->item( "ol" ); 3575 QStyleSheetItem* item = s->item( "ol" );
3570 if ( item ) { 3576 if ( item ) {
3571 list_tm = QMAX(0,item->margin( QStyleSheetItem::MarginTop )); 3577 list_tm = QMAX(0,item->margin( QStyleSheetItem::MarginTop ));
3572 list_bm = QMAX(0,item->margin( QStyleSheetItem::MarginBottom )); 3578 list_bm = QMAX(0,item->margin( QStyleSheetItem::MarginBottom ));
3573 list_lm = QMAX(0,item->margin( QStyleSheetItem::MarginLeft )); 3579 list_lm = QMAX(0,item->margin( QStyleSheetItem::MarginLeft ));
3574 } 3580 }
3575 if ( (item = s->item( "li" ) ) ) { 3581 if ( (item = s->item( "li" ) ) ) {
3576 li_tm = QMAX(0,item->margin( QStyleSheetItem::MarginTop )); 3582 li_tm = QMAX(0,item->margin( QStyleSheetItem::MarginTop ));
3577 li_bm = QMAX(0,item->margin( QStyleSheetItem::MarginBottom )); 3583 li_bm = QMAX(0,item->margin( QStyleSheetItem::MarginBottom ));
3578 } 3584 }
3579 if ( (item = s->item( "p" ) ) ) { 3585 if ( (item = s->item( "p" ) ) ) {
3580 par_tm = QMAX(0,item->margin( QStyleSheetItem::MarginTop )); 3586 par_tm = QMAX(0,item->margin( QStyleSheetItem::MarginTop ));
3581 par_bm = QMAX(0,item->margin( QStyleSheetItem::MarginBottom )); 3587 par_bm = QMAX(0,item->margin( QStyleSheetItem::MarginBottom ));
3582 } 3588 }
3583} 3589}
3584 3590
3585void QTextDocument::setUnderlineLinks( bool b ) { 3591void QTextDocument::setUnderlineLinks( bool b ) {
3586 underlLinks = b; 3592 underlLinks = b;
3587 for ( QTextDocument *d = childList.first(); d; d = childList.next() ) 3593 for ( QTextDocument *d = childList.first(); d; d = childList.next() )
3588 d->setUnderlineLinks( b ); 3594 d->setUnderlineLinks( b );
3589} 3595}
3590 3596
3591void QTextStringChar::setFormat( QTextFormat *f ) 3597void QTextStringChar::setFormat( QTextFormat *f )
3592{ 3598{
3593 if ( type == Regular ) { 3599 if ( type == Regular ) {
3594 d.format = f; 3600 d.format = f;
3595 } else { 3601 } else {
3596 if ( !d.custom ) { 3602 if ( !d.custom ) {
3597 d.custom = new CustomData; 3603 d.custom = new CustomData;
3598 d.custom->custom = 0; 3604 d.custom->custom = 0;
3599 } 3605 }
3600 d.custom->format = f; 3606 d.custom->format = f;
3601 } 3607 }
3602} 3608}
3603 3609
3604void QTextStringChar::setCustomItem( QTextCustomItem *i ) 3610void QTextStringChar::setCustomItem( QTextCustomItem *i )
3605{ 3611{
3606 if ( type == Regular ) { 3612 if ( type == Regular ) {
3607 QTextFormat *f = format(); 3613 QTextFormat *f = format();
3608 d.custom = new CustomData; 3614 d.custom = new CustomData;
3609 d.custom->format = f; 3615 d.custom->format = f;
3610 } else { 3616 } else {
3611 delete d.custom->custom; 3617 delete d.custom->custom;
3612 } 3618 }
3613 d.custom->custom = i; 3619 d.custom->custom = i;
3614 type = (type == Anchor ? CustomAnchor : Custom); 3620 type = (type == Anchor ? CustomAnchor : Custom);
3615} 3621}
3616 3622
3617void QTextStringChar::loseCustomItem() 3623void QTextStringChar::loseCustomItem()
3618{ 3624{
3619 if ( type == Custom ) { 3625 if ( type == Custom ) {
3620 QTextFormat *f = d.custom->format; 3626 QTextFormat *f = d.custom->format;
3621 d.custom->custom = 0; 3627 d.custom->custom = 0;
3622 delete d.custom; 3628 delete d.custom;
3623 type = Regular; 3629 type = Regular;
3624 d.format = f; 3630 d.format = f;
3625 } else if ( type == CustomAnchor ) { 3631 } else if ( type == CustomAnchor ) {
3626 d.custom->custom = 0; 3632 d.custom->custom = 0;
3627 type = Anchor; 3633 type = Anchor;
3628 } 3634 }
3629} 3635}
3630 3636
3631QString QTextStringChar::anchorName() const 3637QString QTextStringChar::anchorName() const
3632{ 3638{
3633 if ( type == Regular ) 3639 if ( type == Regular )
3634 return QString::null; 3640 return QString::null;
3635 else 3641 else
3636 return d.custom->anchorName; 3642 return d.custom->anchorName;
3637} 3643}
3638 3644
3639QString QTextStringChar::anchorHref() const 3645QString QTextStringChar::anchorHref() const
3640{ 3646{
3641 if ( type == Regular ) 3647 if ( type == Regular )
3642 return QString::null; 3648 return QString::null;
3643 else 3649 else
3644 return d.custom->anchorHref; 3650 return d.custom->anchorHref;
3645} 3651}
3646 3652
3647void QTextStringChar::setAnchor( const QString& name, const QString& href ) 3653void QTextStringChar::setAnchor( const QString& name, const QString& href )
3648{ 3654{
3649 if ( type == Regular ) { 3655 if ( type == Regular ) {
3650 QTextFormat *f = format(); 3656 QTextFormat *f = format();
3651 d.custom = new CustomData; 3657 d.custom = new CustomData;
3652 d.custom->custom = 0; 3658 d.custom->custom = 0;
3653 d.custom->format = f; 3659 d.custom->format = f;
3654 type = Anchor; 3660 type = Anchor;
3655 } else if ( type == Custom ) { 3661 } else if ( type == Custom ) {
3656 type = CustomAnchor; 3662 type = CustomAnchor;
3657 } 3663 }
3658 d.custom->anchorName = name; 3664 d.custom->anchorName = name;
3659 d.custom->anchorHref = href; 3665 d.custom->anchorHref = href;
3660} 3666}
3661 3667
3662 3668
3663int QTextString::width( int idx ) const 3669int QTextString::width( int idx ) const
3664{ 3670{
3665 int w = 0; 3671 int w = 0;
3666 QTextStringChar *c = &at( idx ); 3672 QTextStringChar *c = &at( idx );
3667 if ( c->c.unicode() == 0xad || c->c.unicode() == 0x2028 ) 3673 if ( c->c.unicode() == 0xad || c->c.unicode() == 0x2028 )
3668 return 0; 3674 return 0;
3669 if( c->isCustom() ) { 3675 if( c->isCustom() ) {
3670 if( c->customItem()->placement() == QTextCustomItem::PlaceInline ) 3676 if( c->customItem()->placement() == QTextCustomItem::PlaceInline )
3671 w = c->customItem()->width; 3677 w = c->customItem()->width;
3672 } else { 3678 } else {
3673 int r = c->c.row(); 3679 int r = c->c.row();
3674 if( r < 0x06 || r > 0x1f ) 3680 if( r < 0x06 || r > 0x1f )
3675 w = c->format()->width( c->c ); 3681 w = c->format()->width( c->c );
3676 else { 3682 else {
3677 // complex text. We need some hacks to get the right metric here 3683 // complex text. We need some hacks to get the right metric here
3678 QString str; 3684 QString str;
3679 int pos = 0; 3685 int pos = 0;
3680 if( idx > 4 ) 3686 if( idx > 4 )
3681 pos = idx - 4; 3687 pos = idx - 4;
3682 int off = idx - pos; 3688 int off = idx - pos;
3683 int end = QMIN( length(), idx + 4 ); 3689 int end = QMIN( length(), idx + 4 );
3684 while ( pos < end ) { 3690 while ( pos < end ) {
3685 str += at(pos).c; 3691 str += at(pos).c;
3686 pos++; 3692 pos++;
3687 } 3693 }
3688 w = c->format()->width( str, off ); 3694 w = c->format()->width( str, off );
3689 } 3695 }
3690 } 3696 }
3691 return w; 3697 return w;
3692} 3698}
3693 3699
3694QMemArray<QTextStringChar> QTextString::subString( int start, int len ) const 3700QMemArray<QTextStringChar> QTextString::subString( int start, int len ) const
3695{ 3701{
3696 if ( len == 0xFFFFFF ) 3702 if ( len == 0xFFFFFF )
3697 len = data.size(); 3703 len = data.size();
3698 QMemArray<QTextStringChar> a; 3704 QMemArray<QTextStringChar> a;
3699 a.resize( len ); 3705 a.resize( len );
3700 for ( int i = 0; i < len; ++i ) { 3706 for ( int i = 0; i < len; ++i ) {
3701 QTextStringChar *c = &data[ i + start ]; 3707 QTextStringChar *c = &data[ i + start ];
3702 a[ i ].c = c->c; 3708 a[ i ].c = c->c;
3703 a[ i ].x = 0; 3709 a[ i ].x = 0;
3704 a[ i ].lineStart = 0; 3710 a[ i ].lineStart = 0;
3705 a[ i ].rightToLeft = 0; 3711 a[ i ].rightToLeft = 0;
3706 a[ i ].d.format = 0; 3712 a[ i ].d.format = 0;
3707 a[ i ].type = QTextStringChar::Regular; 3713 a[ i ].type = QTextStringChar::Regular;
3708 a[ i ].setFormat( c->format() ); 3714 a[ i ].setFormat( c->format() );
3709 if ( c->format() ) 3715 if ( c->format() )
3710 c->format()->addRef(); 3716 c->format()->addRef();
3711 } 3717 }
3712 return a; 3718 return a;
3713} 3719}
3714 3720
3715// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3721// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3716 3722
3717QTextParagraph::QTextParagraph( QTextDocument *d, QTextParagraph *pr, QTextParagraph *nx, bool updateIds ) 3723QTextParagraph::QTextParagraph( QTextDocument *d, QTextParagraph *pr, QTextParagraph *nx, bool updateIds )
3718 : invalid( 0 ), p( pr ), n( nx ), docOrPseudo( d ), 3724 : invalid( 0 ), p( pr ), n( nx ), docOrPseudo( d ),
3719 changed(FALSE), firstFormat(TRUE), firstPProcess(TRUE), needPreProcess(FALSE), fullWidth(TRUE), 3725 changed(FALSE), firstFormat(TRUE), firstPProcess(TRUE), needPreProcess(FALSE), fullWidth(TRUE),
3720 lastInFrame(FALSE), visible(TRUE), breakable(TRUE), movedDown(FALSE), 3726 lastInFrame(FALSE), visible(TRUE), breakable(TRUE), movedDown(FALSE),
3721 mightHaveCustomItems(FALSE), hasdoc( d != 0 ), litem(FALSE), rtext(FALSE), 3727 mightHaveCustomItems(FALSE), hasdoc( d != 0 ), litem(FALSE), rtext(FALSE),
3722 align( 0 ),mSelections( 0 ), 3728 align( 0 ),mSelections( 0 ),
3723 mFloatingItems( 0 ), lstyle( QStyleSheetItem::ListDisc ), 3729 mFloatingItems( 0 ), lstyle( QStyleSheetItem::ListDisc ),
3724 utm( 0 ), ubm( 0 ), ulm( 0 ), urm( 0 ), uflm( 0 ), ulinespacing( 0 ), 3730 utm( 0 ), ubm( 0 ), ulm( 0 ), urm( 0 ), uflm( 0 ), ulinespacing( 0 ),
3725 tArray(0), tabStopWidth(0), eData( 0 ), ldepth( 0 ) 3731 tArray(0), tabStopWidth(0), eData( 0 ), ldepth( 0 )
3726{ 3732{
3727 lstyle = QStyleSheetItem::ListDisc; 3733 lstyle = QStyleSheetItem::ListDisc;
3728 if ( !hasdoc ) 3734 if ( !hasdoc )
3729 docOrPseudo = new QTextParagraphPseudoDocument; 3735 docOrPseudo = new QTextParagraphPseudoDocument;
3730 bgcol = 0; 3736 bgcol = 0;
3731 list_val = -1; 3737 list_val = -1;
3732 QTextFormat* defFormat = formatCollection()->defaultFormat(); 3738 QTextFormat* defFormat = formatCollection()->defaultFormat();
3733 if ( !hasdoc ) { 3739 if ( !hasdoc ) {
3734 tabStopWidth = defFormat->width( 'x' ) * 8; 3740 tabStopWidth = defFormat->width( 'x' ) * 8;
3735 pseudoDocument()->commandHistory = new QTextCommandHistory( 100 ); 3741 pseudoDocument()->commandHistory = new QTextCommandHistory( 100 );
3736 } 3742 }
3737 3743
3738 if ( p ) 3744 if ( p )
3739 p->n = this; 3745 p->n = this;
3740 if ( n ) 3746 if ( n )
3741 n->p = this; 3747 n->p = this;
3742 3748
3743 3749
3744 if ( !p && hasdoc ) 3750 if ( !p && hasdoc )
3745 document()->setFirstParagraph( this ); 3751 document()->setFirstParagraph( this );
3746 if ( !n && hasdoc ) 3752 if ( !n && hasdoc )
3747 document()->setLastParagraph( this ); 3753 document()->setLastParagraph( this );
3748 3754
3749 state = -1; 3755 state = -1;
3750 3756
3751 if ( p ) 3757 if ( p )
3752 id = p->id + 1; 3758 id = p->id + 1;
3753 else 3759 else
3754 id = 0; 3760 id = 0;
3755 if ( n && updateIds ) { 3761 if ( n && updateIds ) {
3756 QTextParagraph *s = n; 3762 QTextParagraph *s = n;
3757 while ( s ) { 3763 while ( s ) {
3758 s->id = s->p->id + 1; 3764 s->id = s->p->id + 1;
3759 s->invalidateStyleCache(); 3765 s->invalidateStyleCache();
3760 s = s->n; 3766 s = s->n;
3761 } 3767 }
3762 } 3768 }
3763 3769
3764 str = new QTextString(); 3770 str = new QTextString();
3765 str->insert( 0, " ", formatCollection()->defaultFormat() ); 3771 str->insert( 0, " ", formatCollection()->defaultFormat() );
3766} 3772}
3767 3773
3768QTextParagraph::~QTextParagraph() 3774QTextParagraph::~QTextParagraph()
3769{ 3775{
3770 delete str; 3776 delete str;
3771 if ( hasdoc ) { 3777 if ( hasdoc ) {
3772 register QTextDocument *doc = document(); 3778 register QTextDocument *doc = document();
3773 if ( this == doc->minwParag ) { 3779 if ( this == doc->minwParag ) {
3774 doc->minwParag = 0; 3780 doc->minwParag = 0;
3775 doc->minw = 0; 3781 doc->minw = 0;
3776 } 3782 }
3777 if ( this == doc->curParag ) 3783 if ( this == doc->curParag )
3778 doc->curParag = 0; 3784 doc->curParag = 0;
3779 } else { 3785 } else {
3780 delete pseudoDocument(); 3786 delete pseudoDocument();
3781 } 3787 }
3782 if ( tArray ) 3788 if ( tArray )
3783 delete [] tArray; 3789 delete [] tArray;
3784 delete eData; 3790 delete eData;
3785 QMap<int, QTextLineStart*>::Iterator it = lineStarts.begin(); 3791 QMap<int, QTextLineStart*>::Iterator it = lineStarts.begin();
3786 for ( ; it != lineStarts.end(); ++it ) 3792 for ( ; it != lineStarts.end(); ++it )
3787 delete *it; 3793 delete *it;
3788 if ( mSelections ) 3794 if ( mSelections )
3789 delete mSelections; 3795 delete mSelections;
3790 if ( mFloatingItems ) 3796 if ( mFloatingItems )
3791 delete mFloatingItems; 3797 delete mFloatingItems;
3792 if ( p ) 3798 if ( p )
3793 p->setNext( n ); 3799 p->setNext( n );
3794 if ( n ) 3800 if ( n )
3795 n->setPrev( p ); 3801 n->setPrev( p );
3796} 3802}
3797 3803
3798void QTextParagraph::setNext( QTextParagraph *s ) 3804void QTextParagraph::setNext( QTextParagraph *s )
3799{ 3805{
3800 n = s; 3806 n = s;
3801 if ( !n && hasdoc ) 3807 if ( !n && hasdoc )
3802 document()->setLastParagraph( this ); 3808 document()->setLastParagraph( this );
3803} 3809}
3804 3810
3805void QTextParagraph::setPrev( QTextParagraph *s ) 3811void QTextParagraph::setPrev( QTextParagraph *s )
3806{ 3812{
3807 p = s; 3813 p = s;
3808 if ( !p && hasdoc ) 3814 if ( !p && hasdoc )
3809 document()->setFirstParagraph( this ); 3815 document()->setFirstParagraph( this );
3810} 3816}
3811 3817
3812void QTextParagraph::invalidate( int chr ) 3818void QTextParagraph::invalidate( int chr )
3813{ 3819{
3814 if ( invalid < 0 ) 3820 if ( invalid < 0 )
3815 invalid = chr; 3821 invalid = chr;
3816 else 3822 else
3817 invalid = QMIN( invalid, chr ); 3823 invalid = QMIN( invalid, chr );
3818 if ( mFloatingItems ) { 3824 if ( mFloatingItems ) {
3819 for ( QTextCustomItem *i = mFloatingItems->first(); i; i = mFloatingItems->next() ) 3825 for ( QTextCustomItem *i = mFloatingItems->first(); i; i = mFloatingItems->next() )
3820 i->ypos = -1; 3826 i->ypos = -1;
3821 } 3827 }
3822 invalidateStyleCache(); 3828 invalidateStyleCache();
3823} 3829}
3824 3830
3825void QTextParagraph::invalidateStyleCache() 3831void QTextParagraph::invalidateStyleCache()
3826{ 3832{
3827 if ( list_val < 0 ) 3833 if ( list_val < 0 )
3828 list_val = -1; 3834 list_val = -1;
3829} 3835}
3830 3836
3831 3837
3832void QTextParagraph::insert( int index, const QString &s ) 3838void QTextParagraph::insert( int index, const QString &s )
3833{ 3839{
3834 insert( index, s.unicode(), s.length() ); 3840 insert( index, s.unicode(), s.length() );
3835} 3841}
3836 3842
3837void QTextParagraph::insert( int index, const QChar *unicode, int len ) 3843void QTextParagraph::insert( int index, const QChar *unicode, int len )
3838{ 3844{
3839 if ( hasdoc && !document()->useFormatCollection() && document()->preProcessor() ) 3845 if ( hasdoc && !document()->useFormatCollection() && document()->preProcessor() )
3840 str->insert( index, unicode, len, 3846 str->insert( index, unicode, len,
3841 document()->preProcessor()->format( QTextPreProcessor::Standard ) ); 3847 document()->preProcessor()->format( QTextPreProcessor::Standard ) );
3842 else 3848 else
3843 str->insert( index, unicode, len, formatCollection()->defaultFormat() ); 3849 str->insert( index, unicode, len, formatCollection()->defaultFormat() );
3844 invalidate( index ); 3850 invalidate( index );
3845 needPreProcess = TRUE; 3851 needPreProcess = TRUE;
3846} 3852}
3847 3853
3848void QTextParagraph::truncate( int index ) 3854void QTextParagraph::truncate( int index )
3849{ 3855{
3850 str->truncate( index ); 3856 str->truncate( index );
3851 insert( length(), " " ); 3857 insert( length(), " " );
3852 needPreProcess = TRUE; 3858 needPreProcess = TRUE;
3853} 3859}
3854 3860
3855void QTextParagraph::remove( int index, int len ) 3861void QTextParagraph::remove( int index, int len )
3856{ 3862{
3857 if ( index + len - str->length() > 0 ) 3863 if ( index + len - str->length() > 0 )
3858 return; 3864 return;
3859 for ( int i = index; i < index + len; ++i ) { 3865 for ( int i = index; i < index + len; ++i ) {
3860 QTextStringChar *c = at( i ); 3866 QTextStringChar *c = at( i );
3861 if ( hasdoc && c->isCustom() ) { 3867 if ( hasdoc && c->isCustom() ) {
3862 document()->unregisterCustomItem( c->customItem(), this ); 3868 document()->unregisterCustomItem( c->customItem(), this );
3863 } 3869 }
3864 } 3870 }
3865 str->remove( index, len ); 3871 str->remove( index, len );
3866 invalidate( 0 ); 3872 invalidate( 0 );
3867 needPreProcess = TRUE; 3873 needPreProcess = TRUE;
3868} 3874}
3869 3875
3870void QTextParagraph::join( QTextParagraph *s ) 3876void QTextParagraph::join( QTextParagraph *s )
3871{ 3877{
3872 int oh = r.height() + s->r.height(); 3878 int oh = r.height() + s->r.height();
3873 n = s->n; 3879 n = s->n;
3874 if ( n ) 3880 if ( n )
3875 n->p = this; 3881 n->p = this;
3876 else if ( hasdoc ) 3882 else if ( hasdoc )
3877 document()->setLastParagraph( this ); 3883 document()->setLastParagraph( this );
3878 3884
3879 int start = str->length(); 3885 int start = str->length();
3880 if ( length() > 0 && at( length() - 1 )->c == ' ' ) { 3886 if ( length() > 0 && at( length() - 1 )->c == ' ' ) {
3881 remove( length() - 1, 1 ); 3887 remove( length() - 1, 1 );
3882 --start; 3888 --start;
3883 } 3889 }
3884 append( s->str->toString(), TRUE ); 3890 append( s->str->toString(), TRUE );
3885 3891
3886 for ( int i = 0; i < s->length(); ++i ) { 3892 for ( int i = 0; i < s->length(); ++i ) {
3887 if ( !hasdoc || document()->useFormatCollection() ) { 3893 if ( !hasdoc || document()->useFormatCollection() ) {
3888 s->str->at( i ).format()->addRef(); 3894 s->str->at( i ).format()->addRef();
3889 str->setFormat( i + start, s->str->at( i ).format(), TRUE ); 3895 str->setFormat( i + start, s->str->at( i ).format(), TRUE );
3890 } 3896 }
3891 if ( s->str->at( i ).isCustom() ) { 3897 if ( s->str->at( i ).isCustom() ) {
3892 QTextCustomItem * item = s->str->at( i ).customItem(); 3898 QTextCustomItem * item = s->str->at( i ).customItem();
3893 str->at( i + start ).setCustomItem( item ); 3899 str->at( i + start ).setCustomItem( item );
3894 s->str->at( i ).loseCustomItem(); 3900 s->str->at( i ).loseCustomItem();
3895 if ( hasdoc ) { 3901 if ( hasdoc ) {
3896 document()->unregisterCustomItem( item, s ); 3902 document()->unregisterCustomItem( item, s );
3897 document()->registerCustomItem( item, this ); 3903 document()->registerCustomItem( item, this );
3898 } 3904 }
3899 } 3905 }
3900 if ( s->str->at( i ).isAnchor() ) { 3906 if ( s->str->at( i ).isAnchor() ) {
3901 str->at( i + start ).setAnchor( s->str->at( i ).anchorName(), 3907 str->at( i + start ).setAnchor( s->str->at( i ).anchorName(),
3902 s->str->at( i ).anchorHref() ); 3908 s->str->at( i ).anchorHref() );
3903 } 3909 }
3904 } 3910 }
3905 3911
3906 if ( !extraData() && s->extraData() ) { 3912 if ( !extraData() && s->extraData() ) {
3907 setExtraData( s->extraData() ); 3913 setExtraData( s->extraData() );
3908 s->setExtraData( 0 ); 3914 s->setExtraData( 0 );
3909 } else if ( extraData() && s->extraData() ) { 3915 } else if ( extraData() && s->extraData() ) {
3910 extraData()->join( s->extraData() ); 3916 extraData()->join( s->extraData() );
3911 } 3917 }
3912 delete s; 3918 delete s;
3913 invalidate( 0 ); 3919 invalidate( 0 );
3914 r.setHeight( oh ); 3920 r.setHeight( oh );
3915 needPreProcess = TRUE; 3921 needPreProcess = TRUE;
3916 if ( n ) { 3922 if ( n ) {
3917 QTextParagraph *s = n; 3923 QTextParagraph *s = n;
3918 s->invalidate( 0 ); 3924 s->invalidate( 0 );
3919 while ( s ) { 3925 while ( s ) {
3920 s->id = s->p->id + 1; 3926 s->id = s->p->id + 1;
3921 s->state = -1; 3927 s->state = -1;
3922 s->needPreProcess = TRUE; 3928 s->needPreProcess = TRUE;
3923 s->changed = TRUE; 3929 s->changed = TRUE;
3924 s->invalidateStyleCache(); 3930 s->invalidateStyleCache();
3925 s = s->n; 3931 s = s->n;
3926 } 3932 }
3927 } 3933 }
3928 format(); 3934 format();
3929 state = -1; 3935 state = -1;
3930} 3936}
3931 3937
3932void QTextParagraph::move( int &dy ) 3938void QTextParagraph::move( int &dy )
3933{ 3939{
3934 if ( dy == 0 ) 3940 if ( dy == 0 )
3935 return; 3941 return;
3936 changed = TRUE; 3942 changed = TRUE;
3937 r.moveBy( 0, dy ); 3943 r.moveBy( 0, dy );
3938 if ( mFloatingItems ) { 3944 if ( mFloatingItems ) {
3939 for ( QTextCustomItem *i = mFloatingItems->first(); i; i = mFloatingItems->next() ) 3945 for ( QTextCustomItem *i = mFloatingItems->first(); i; i = mFloatingItems->next() )
3940 i->ypos += dy; 3946 i->ypos += dy;
3941 } 3947 }
3942 if ( p ) 3948 if ( p )
3943 p->lastInFrame = TRUE; 3949 p->lastInFrame = TRUE;
3944 3950
3945 // do page breaks if required 3951 // do page breaks if required
3946 if ( hasdoc && document()->isPageBreakEnabled() ) { 3952 if ( hasdoc && document()->isPageBreakEnabled() ) {
3947 int shift; 3953 int shift;
3948 if ( ( shift = document()->formatter()->formatVertically( document(), this ) ) ) { 3954 if ( ( shift = document()->formatter()->formatVertically( document(), this ) ) ) {
3949 if ( p ) 3955 if ( p )
3950 p->setChanged( TRUE ); 3956 p->setChanged( TRUE );
3951 dy += shift; 3957 dy += shift;
3952 } 3958 }
3953 } 3959 }
3954} 3960}
3955 3961
3956void QTextParagraph::format( int start, bool doMove ) 3962void QTextParagraph::format( int start, bool doMove )
3957{ 3963{
3958 if ( !str || str->length() == 0 || !formatter() ) 3964 if ( !str || str->length() == 0 || !formatter() )
3959 return; 3965 return;
3960 3966
3961 if ( hasdoc && 3967 if ( hasdoc &&
3962 document()->preProcessor() && 3968 document()->preProcessor() &&
3963 ( needPreProcess || state == -1 ) ) 3969 ( needPreProcess || state == -1 ) )
3964 document()->preProcessor()->process( document(), this, invalid <= 0 ? 0 : invalid ); 3970 document()->preProcessor()->process( document(), this, invalid <= 0 ? 0 : invalid );
3965 needPreProcess = FALSE; 3971 needPreProcess = FALSE;
3966 3972
3967 if ( invalid == -1 ) 3973 if ( invalid == -1 )
3968 return; 3974 return;
3969 3975
3970 r.moveTopLeft( QPoint( documentX(), p ? p->r.y() + p->r.height() : documentY() ) ); 3976 r.moveTopLeft( QPoint( documentX(), p ? p->r.y() + p->r.height() : documentY() ) );
3971 if ( p ) 3977 if ( p )
3972 p->lastInFrame = FALSE; 3978 p->lastInFrame = FALSE;
3973 3979
3974 movedDown = FALSE; 3980 movedDown = FALSE;
3975 bool formattedAgain = FALSE; 3981 bool formattedAgain = FALSE;
3976 3982
3977 formatAgain: 3983 formatAgain:
3978 3984
3979 r.setWidth( documentWidth() ); 3985 r.setWidth( documentWidth() );
3980 if ( hasdoc && mFloatingItems ) { 3986 if ( hasdoc && mFloatingItems ) {
3981 for ( QTextCustomItem *i = mFloatingItems->first(); i; i = mFloatingItems->next() ) { 3987 for ( QTextCustomItem *i = mFloatingItems->first(); i; i = mFloatingItems->next() ) {
3982 i->ypos = r.y(); 3988 i->ypos = r.y();
3983 if ( i->placement() == QTextCustomItem::PlaceRight ) { 3989 if ( i->placement() == QTextCustomItem::PlaceRight ) {
3984 i->xpos = r.x() + r.width() - i->width; 3990 i->xpos = r.x() + r.width() - i->width;
3985 } 3991 }
3986 } 3992 }
3987 } 3993 }
3988 QMap<int, QTextLineStart*> oldLineStarts = lineStarts; 3994 QMap<int, QTextLineStart*> oldLineStarts = lineStarts;
3989 lineStarts.clear(); 3995 lineStarts.clear();
3990 int y = formatter()->format( document(), this, start, oldLineStarts ); 3996 int y = formatter()->format( document(), this, start, oldLineStarts );
3991 3997
3992 3998
3993 r.setWidth( QMAX( r.width(), formatter()->minimumWidth() ) ); 3999 r.setWidth( QMAX( r.width(), formatter()->minimumWidth() ) );
3994 4000
3995 4001
3996 QMap<int, QTextLineStart*>::Iterator it = oldLineStarts.begin(); 4002 QMap<int, QTextLineStart*>::Iterator it = oldLineStarts.begin();
3997 4003
3998 for ( ; it != oldLineStarts.end(); ++it ) 4004 for ( ; it != oldLineStarts.end(); ++it )
3999 delete *it; 4005 delete *it;
4000 4006
4001 QTextStringChar *c = 0; 4007 QTextStringChar *c = 0;
4002 // do not do this on mac, as the paragraph 4008 // do not do this on mac, as the paragraph
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
4249 // be fixed in QFont somewhere (under Windows you get ugly boxes 4255 // be fixed in QFont somewhere (under Windows you get ugly boxes
4250 // otherwise) 4256 // otherwise)
4251 QChar* uc = (QChar*) qstr.unicode(); 4257 QChar* uc = (QChar*) qstr.unicode();
4252 for ( uint ii = 0; ii < qstr.length(); ii++ ) 4258 for ( uint ii = 0; ii < qstr.length(); ii++ )
4253 if ( uc[(int)ii]== '\n' || uc[(int)ii] == QChar_linesep || uc[(int)ii] == '\t' ) 4259 if ( uc[(int)ii]== '\n' || uc[(int)ii] == QChar_linesep || uc[(int)ii] == '\t' )
4254 uc[(int)ii] = 0x20; 4260 uc[(int)ii] = 0x20;
4255 4261
4256 int line = -1; 4262 int line = -1;
4257 int paintStart = 0; 4263 int paintStart = 0;
4258 int selection = -1; 4264 int selection = -1;
4259 for ( i = 0; i < length(); i++ ) { 4265 for ( i = 0; i < length(); i++ ) {
4260 chr = at( i ); 4266 chr = at( i );
4261 4267
4262 // we flush at end of document 4268 // we flush at end of document
4263 bool flush = i== length()-1; 4269 bool flush = i== length()-1;
4264 bool selectionStateChanged = FALSE; 4270 bool selectionStateChanged = FALSE;
4265 if ( !flush ) { 4271 if ( !flush ) {
4266 QTextStringChar *nextchr = at( i+1 ); 4272 QTextStringChar *nextchr = at( i+1 );
4267 // we flush at end of line 4273 // we flush at end of line
4268 flush |= nextchr->lineStart; 4274 flush |= nextchr->lineStart;
4269 // we flush on format changes 4275 // we flush on format changes
4270 flush |= ( nextchr->format() != chr->format() ); 4276 flush |= ( nextchr->format() != chr->format() );
4271 // we flush on anchor changes 4277 // we flush on anchor changes
4272 flush |= ( nextchr->isAnchor() != chr->isAnchor() ); 4278 flush |= ( nextchr->isAnchor() != chr->isAnchor() );
4273 // we flush on start of run 4279 // we flush on start of run
4274 flush |= nextchr->startOfRun; 4280 flush |= nextchr->startOfRun;
4275 // we flush on bidi changes 4281 // we flush on bidi changes
4276 flush |= ( nextchr->rightToLeft != chr->rightToLeft ); 4282 flush |= ( nextchr->rightToLeft != chr->rightToLeft );
4277 // we flush on tab 4283 // we flush on tab
4278 flush |= ( chr->c == '\t' ); 4284 flush |= ( chr->c == '\t' );
4279 // we flush on soft hypens 4285 // we flush on soft hypens
4280 flush |= ( chr->c.unicode() == 0xad ); 4286 flush |= ( chr->c.unicode() == 0xad );
4281 // we flush on custom items 4287 // we flush on custom items
4282 flush |= chr->isCustom(); 4288 flush |= chr->isCustom();
4283 // we flush before custom items 4289 // we flush before custom items
4284 flush |= nextchr->isCustom(); 4290 flush |= nextchr->isCustom();
4285 // when painting justified, we flush on spaces 4291 // when painting justified, we flush on spaces
4286 if ((alignment() & Qt3::AlignJustify) == Qt3::AlignJustify ) 4292 if ((alignment() & Qt3::AlignJustify) == Qt3::AlignJustify )
4287 flush |= QTextFormatter::isBreakable( str, i ); 4293 flush |= QTextFormatter::isBreakable( str, i );
4288 // we flush when the string is getting too long 4294 // we flush when the string is getting too long
4289 flush |= ( i - paintStart >= 256 ); 4295 flush |= ( i - paintStart >= 256 );
4290 // we flush when the selection state changes 4296 // we flush when the selection state changes
4291 if ( drawSelections ) { 4297 if ( drawSelections ) {
4292 for ( QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->begin(); 4298 for ( QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->begin();
4293 it != mSelections->end(); ++it ) 4299 it != mSelections->end(); ++it )
4294 selectionStateChanged |=( (*it).start == i || (*it).start == i+1 || (*it).end == i+1 ); 4300 selectionStateChanged |=( (*it).start == i || (*it).start == i+1 || (*it).end == i+1 );
4295 flush |= selectionStateChanged; 4301 flush |= selectionStateChanged;
4296 } 4302 }
4297 } 4303 }
4298 4304
4299 // init a new line 4305 // init a new line
4300 if ( chr->lineStart ) { 4306 if ( chr->lineStart ) {
4301 if (fullWidthStyle && drawSelections && selection >= 0) 4307 if (fullWidthStyle && drawSelections && selection >= 0)
4302 painter.fillRect( xend, y, fullSelectionWidth - xend, h, 4308 painter.fillRect( xend, y, fullSelectionWidth - xend, h,
4303 (selection == QTextDocument::Standard || !hasdoc) ? 4309 (selection == QTextDocument::Standard || !hasdoc) ?
4304 cg.color( QColorGroup::Highlight ) : 4310 cg.color( QColorGroup::Highlight ) :
4305 document()->selectionColor( selection ) ); 4311 document()->selectionColor( selection ) );
4306 ++line; 4312 ++line;
4307 paintStart = i; 4313 paintStart = i;
4308 lineInfo( line, y, h, baseLine ); 4314 lineInfo( line, y, h, baseLine );
4309 if ( clipy != -1 && cliph != 0 && y + r.y() - h > clipy + cliph ) { // outside clip area, leave 4315 if ( clipy != -1 && cliph != 0 && y + r.y() - h > clipy + cliph ) { // outside clip area, leave
4310 break; 4316 break;
4311 } 4317 }
4312 4318
4313 // if this is the first line and we are a list item, draw the the bullet label 4319 // if this is the first line and we are a list item, draw the the bullet label
4314 if ( line == 0 && isListItem() ) 4320 if ( line == 0 && isListItem() )
4315 drawLabel( &painter, chr->x, y, 0, 0, baseLine, cg ); 4321 drawLabel( &painter, chr->x, y, 0, 0, baseLine, cg );
4316 } 4322 }
4317 4323
4318 // check for cursor mark 4324 // check for cursor mark
4319 if ( cursor && this == cursor->paragraph() && i == cursor->index() ) { 4325 if ( cursor && this == cursor->paragraph() && i == cursor->index() ) {
4320 QTextStringChar *c = i == 0 ? chr : chr - 1; 4326 QTextStringChar *c = i == 0 ? chr : chr - 1;
4321 cursorRect.setRect( cursor->x() , y + baseLine - c->format()->ascent(), 4327 cursorRect.setRect( cursor->x() , y + baseLine - c->format()->ascent(),
4322 1, c->format()->height() ); 4328 1, c->format()->height() );
4323 } 4329 }
4324 4330
4325 // check if we are in a selection and store which one it is 4331 // check if we are in a selection and store which one it is
4326 selection = -1; 4332 selection = -1;
4327 if ( drawSelections ) { 4333 if ( drawSelections ) {
4328 for ( QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->begin(); 4334 for ( QMap<int, QTextParagraphSelection>::ConstIterator it = mSelections->begin();
4329 it != mSelections->end(); ++it ) 4335 it != mSelections->end(); ++it )
4330 if ( (*it).start <= i && i < (*it).end + ( (*it).end == length()-1 && n && n->hasSelection(it.key()) ) ? 1:0 4336 if ( (*it).start <= i && i < (*it).end + ( (*it).end == length()-1 && n && n->hasSelection(it.key()) ) ? 1:0
4331 // exclude the standard selection from printing 4337 // exclude the standard selection from printing
4332 && (it.key() != QTextDocument::Standard || !is_printer( &painter) ) ) { 4338 && (it.key() != QTextDocument::Standard || !is_printer( &painter) ) ) {
4333 selection = it.key(); 4339 selection = it.key();
4334 break; 4340 break;
4335 } 4341 }
4336 } 4342 }
4337 4343
4338 if ( flush ) { // something changed, draw what we have so far 4344 if ( flush ) { // something changed, draw what we have so far
4339 if ( chr->rightToLeft ) { 4345 if ( chr->rightToLeft ) {
4340 xstart = chr->x; 4346 xstart = chr->x;
4341 xend = at( paintStart )->x + str->width( paintStart ); 4347 xend = at( paintStart )->x + str->width( paintStart );
4342 } else { 4348 } else {
4343 xstart = at( paintStart )->x; 4349 xstart = at( paintStart )->x;
4344 if ( !selectionStateChanged && i < length() - 1 && !str->at( i + 1 ).lineStart ) 4350 if ( !selectionStateChanged && i < length() - 1 && !str->at( i + 1 ).lineStart )
4345 xend = str->at( i + 1 ).x; 4351 xend = str->at( i + 1 ).x;
4346 else 4352 else
4347 xend = chr->x + str->width( i ); 4353 xend = chr->x + str->width( i );
4348 } 4354 }
4349 4355
4350 if ( (clipx == -1 || clipw == -1) || (xend >= clipx && xstart <= clipx + clipw) ) { 4356 if ( (clipx == -1 || clipw == -1) || (xend >= clipx && xstart <= clipx + clipw) ) {
4351 if ( !chr->isCustom() ) 4357 if ( !chr->isCustom() )
4352 drawString( painter, qstr, paintStart, i - paintStart + 1, xstart, y, 4358 drawString( painter, qstr, paintStart, i - paintStart + 1, xstart, y,
4353 baseLine, xend-xstart, h, selection, 4359 baseLine, xend-xstart, h, selection,
4354 chr, cg, chr->rightToLeft ); 4360 chr, cg, chr->rightToLeft );
4355 else if ( chr->customItem()->placement() == QTextCustomItem::PlaceInline ) 4361 else if ( chr->customItem()->placement() == QTextCustomItem::PlaceInline )
4356 chr->customItem()->draw( &painter, chr->x, y, 4362 chr->customItem()->draw( &painter, chr->x, y,
4357 clipx == -1 ? clipx : (clipx - r.x()), 4363 clipx == -1 ? clipx : (clipx - r.x()),
4358 clipy == -1 ? clipy : (clipy - r.y()), 4364 clipy == -1 ? clipy : (clipy - r.y()),
4359 clipw, cliph, cg, selection >= 0 ); 4365 clipw, cliph, cg, selection >= 0 );
4360 } 4366 }
4361 paintStart = i+1; 4367 paintStart = i+1;
4362 } 4368 }
4363 4369
4364 } 4370 }
4365 4371
4366 if (fullWidthStyle && drawSelections && selection >= 0 && next() && next()->mSelections) 4372 if (fullWidthStyle && drawSelections && selection >= 0 && next() && next()->mSelections)
4367 for ( QMap<int, QTextParagraphSelection>::ConstIterator it = next()->mSelections->begin(); 4373 for ( QMap<int, QTextParagraphSelection>::ConstIterator it = next()->mSelections->begin();
4368 it != next()->mSelections->end(); ++it ) 4374 it != next()->mSelections->end(); ++it )
4369 if (((*it).start) == 0) { 4375 if (((*it).start) == 0) {
4370 painter.fillRect( xend, y, fullSelectionWidth - xend, h, 4376 painter.fillRect( xend, y, fullSelectionWidth - xend, h,
4371 (selection == QTextDocument::Standard || !hasdoc) ? 4377 (selection == QTextDocument::Standard || !hasdoc) ?
4372 cg.color( QColorGroup::Highlight ) : 4378 cg.color( QColorGroup::Highlight ) :
4373 document()->selectionColor( selection ) ); 4379 document()->selectionColor( selection ) );
4374 break; 4380 break;
4375 } 4381 }
4376 4382
4377 // time to draw the cursor 4383 // time to draw the cursor
4378 const int cursor_extent = 4; 4384 const int cursor_extent = 4;
4379 if ( !cursorRect.isNull() && cursor && 4385 if ( !cursorRect.isNull() && cursor &&
4380 ((clipx == -1 || clipw == -1) || (cursorRect.right()+cursor_extent >= clipx && cursorRect.left()-cursor_extent <= clipx + clipw)) ) { 4386 ((clipx == -1 || clipw == -1) || (cursorRect.right()+cursor_extent >= clipx && cursorRect.left()-cursor_extent <= clipx + clipw)) ) {
4381 painter.fillRect( cursorRect, cg.color( QColorGroup::Text ) ); 4387 painter.fillRect( cursorRect, cg.color( QColorGroup::Text ) );
4382 painter.save(); 4388 painter.save();
4383 if ( string()->isBidi() ) { 4389 if ( string()->isBidi() ) {
4384 if ( at( cursor->index() )->rightToLeft ) { 4390 if ( at( cursor->index() )->rightToLeft ) {
4385 painter.setPen( Qt::black ); 4391 painter.setPen( Qt::black );
4386 painter.drawLine( cursorRect.x(), cursorRect.y(), cursorRect.x() - cursor_extent / 2, cursorRect.y() + cursor_extent / 2 ); 4392 painter.drawLine( cursorRect.x(), cursorRect.y(), cursorRect.x() - cursor_extent / 2, cursorRect.y() + cursor_extent / 2 );
4387 painter.drawLine( cursorRect.x(), cursorRect.y() + cursor_extent, cursorRect.x() - cursor_extent / 2, cursorRect.y() + cursor_extent / 2 ); 4393 painter.drawLine( cursorRect.x(), cursorRect.y() + cursor_extent, cursorRect.x() - cursor_extent / 2, cursorRect.y() + cursor_extent / 2 );
4388 } else { 4394 } else {
4389 painter.setPen( Qt::black ); 4395 painter.setPen( Qt::black );
4390 painter.drawLine( cursorRect.x(), cursorRect.y(), cursorRect.x() + cursor_extent / 2, cursorRect.y() + cursor_extent / 2 ); 4396 painter.drawLine( cursorRect.x(), cursorRect.y(), cursorRect.x() + cursor_extent / 2, cursorRect.y() + cursor_extent / 2 );
4391 painter.drawLine( cursorRect.x(), cursorRect.y() + cursor_extent, cursorRect.x() + cursor_extent / 2, cursorRect.y() + cursor_extent / 2 ); 4397 painter.drawLine( cursorRect.x(), cursorRect.y() + cursor_extent, cursorRect.x() + cursor_extent / 2, cursorRect.y() + cursor_extent / 2 );
4392 } 4398 }
4393 } 4399 }
4394 painter.restore(); 4400 painter.restore();
4395 } 4401 }
4396} 4402}
4397 4403
4398//#define BIDI_DEBUG 4404//#define BIDI_DEBUG
4399 4405
4400void QTextParagraph::drawString( QPainter &painter, const QString &s, int start, int len, int xstart, 4406void QTextParagraph::drawString( QPainter &painter, const QString &s, int start, int len, int xstart,
4401 int y, int baseLine, int w, int h, int selection, 4407 int y, int baseLine, int w, int h, int selection,
4402 QTextStringChar *formatChar, const QColorGroup& cg, 4408 QTextStringChar *formatChar, const QColorGroup& cg,
4403 bool rightToLeft ) 4409 bool rightToLeft )
4404{ 4410{
4405 int i = start + len - 1; 4411 int i = start + len - 1;
4406 bool plainText = hasdoc ? document()->textFormat() == Qt::PlainText : FALSE; 4412 bool plainText = hasdoc ? document()->textFormat() == Qt::PlainText : FALSE;
4407 QTextFormat* format = formatChar->format(); 4413 QTextFormat* format = formatChar->format();
4408 QString str( s ); 4414 QString str( s );
4409 if ( str[ (int)str.length() - 1 ].unicode() == 0xad ) 4415 if ( str[ (int)str.length() - 1 ].unicode() == 0xad )
4410 str.remove( str.length() - 1, 1 ); 4416 str.remove( str.length() - 1, 1 );
4411 if ( !plainText || hasdoc && format->color() != document()->formatCollection()->defaultFormat()->color() ) 4417 if ( !plainText || hasdoc && format->color() != document()->formatCollection()->defaultFormat()->color() )
4412 painter.setPen( QPen( format->color() ) ); 4418 painter.setPen( QPen( format->color() ) );
4413 else 4419 else
4414 painter.setPen( cg.text() ); 4420 painter.setPen( cg.text() );
4415 painter.setFont( format->font() ); 4421 painter.setFont( format->font() );
4416 4422
4417 if ( hasdoc && formatChar->isAnchor() && !formatChar->anchorHref().isEmpty() ) { 4423 if ( hasdoc && formatChar->isAnchor() && !formatChar->anchorHref().isEmpty() ) {
4418 if ( format->useLinkColor() ) { 4424 if ( format->useLinkColor() ) {
4419 if ( document()->linkColor.isValid() ) 4425 if ( document()->linkColor.isValid() )
4420 painter.setPen( document()->linkColor ); 4426 painter.setPen( document()->linkColor );
4421 else 4427 else
4422 painter.setPen( QPen( Qt::blue ) ); 4428 painter.setPen( QPen( Qt::blue ) );
4423 } 4429 }
4424 if ( document()->underlineLinks() ) { 4430 if ( document()->underlineLinks() ) {
4425 QFont fn = format->font(); 4431 QFont fn = format->font();
4426 fn.setUnderline( TRUE ); 4432 fn.setUnderline( TRUE );
4427 painter.setFont( fn ); 4433 painter.setFont( fn );
4428 } 4434 }
4429 } 4435 }
4430 4436
4431 if ( selection >= 0 ) { 4437 if ( selection >= 0 ) {
4432 if ( !hasdoc || document()->invertSelectionText( selection ) ) 4438 if ( !hasdoc || document()->invertSelectionText( selection ) )
4433 painter.setPen( cg.color( QColorGroup::HighlightedText ) ); 4439 painter.setPen( cg.color( QColorGroup::HighlightedText ) );
4434 painter.fillRect( xstart, y, w, h, 4440 painter.fillRect( xstart, y, w, h,
4435 (selection == QTextDocument::Standard || !hasdoc) ? 4441 (selection == QTextDocument::Standard || !hasdoc) ?
4436 cg.color( QColorGroup::Highlight ) : document()->selectionColor( selection ) ); 4442 cg.color( QColorGroup::Highlight ) : document()->selectionColor( selection ) );
4437 } 4443 }
4438 4444
4439 if ( str[ start ] != '\t' && str[ start ].unicode() != 0xad ) { 4445 if ( str[ start ] != '\t' && str[ start ].unicode() != 0xad ) {
4440 if ( format->vAlign() == QTextFormat::AlignNormal ) { 4446 if ( format->vAlign() == QTextFormat::AlignNormal ) {
4441 painter.drawText( xstart, y + baseLine, str.mid( start ), len ); 4447 painter.drawText( xstart, y + baseLine, str.mid( start ), len );
4442#ifdef BIDI_DEBUG 4448#ifdef BIDI_DEBUG
4443 painter.save(); 4449 painter.save();
4444 painter.setPen ( Qt::red ); 4450 painter.setPen ( Qt::red );
4445 painter.drawLine( xstart, y, xstart, y + baseLine ); 4451 painter.drawLine( xstart, y, xstart, y + baseLine );
4446 painter.drawLine( xstart, y + baseLine/2, xstart + 10, y + baseLine/2 ); 4452 painter.drawLine( xstart, y + baseLine/2, xstart + 10, y + baseLine/2 );
4447 int w = 0; 4453 int w = 0;
4448 int i = 0; 4454 int i = 0;
4449 while( i < len ) 4455 while( i < len )
4450 w += painter.fontMetrics().charWidth( str, start + i++ ); 4456 w += painter.fontMetrics().charWidth( str, start + i++ );
4451 painter.setPen ( Qt::blue ); 4457 painter.setPen ( Qt::blue );
4452 painter.drawLine( xstart + w - 1, y, xstart + w - 1, y + baseLine ); 4458 painter.drawLine( xstart + w - 1, y, xstart + w - 1, y + baseLine );
4453 painter.drawLine( xstart + w - 1, y + baseLine/2, xstart + w - 1 - 10, y + baseLine/2 ); 4459 painter.drawLine( xstart + w - 1, y + baseLine/2, xstart + w - 1 - 10, y + baseLine/2 );
4454 painter.restore(); 4460 painter.restore();
4455#endif 4461#endif
4456 } else if ( format->vAlign() == QTextFormat::AlignSuperScript ) { 4462 } else if ( format->vAlign() == QTextFormat::AlignSuperScript ) {
4457 QFont f( painter.font() ); 4463 QFont f( painter.font() );
4458 if ( format->fontSizesInPixels() ) 4464 if ( format->fontSizesInPixels() )
4459 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 ); 4465 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 );
4460 else 4466 else
4461 f.setPointSize( ( f.pointSize() * 2 ) / 3 ); 4467 f.setPointSize( ( f.pointSize() * 2 ) / 3 );
4462 painter.setFont( f ); 4468 painter.setFont( f );
4463 painter.drawText( xstart, y + baseLine - ( painter.fontMetrics().height() / 2 ), 4469 painter.drawText( xstart, y + baseLine - ( painter.fontMetrics().height() / 2 ),
4464 str.mid( start ), len ); 4470 str.mid( start ), len );
4465 } else if ( format->vAlign() == QTextFormat::AlignSubScript ) { 4471 } else if ( format->vAlign() == QTextFormat::AlignSubScript ) {
4466 QFont f( painter.font() ); 4472 QFont f( painter.font() );
4467 if ( format->fontSizesInPixels() ) 4473 if ( format->fontSizesInPixels() )
4468 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 ); 4474 f.setPixelSize( ( f.pixelSize() * 2 ) / 3 );
4469 else 4475 else
4470 f.setPointSize( ( f.pointSize() * 2 ) / 3 ); 4476 f.setPointSize( ( f.pointSize() * 2 ) / 3 );
4471 painter.setFont( f ); 4477 painter.setFont( f );
4472 painter.drawText( xstart, y + baseLine + painter.fontMetrics().height() / 6, str.mid( start ), len ); 4478 painter.drawText( xstart, y + baseLine + painter.fontMetrics().height() / 6, str.mid( start ), len );
4473 } 4479 }
4474 } 4480 }
4475 if ( i + 1 < length() && at( i + 1 )->lineStart && at( i )->c.unicode() == 0xad ) { 4481 if ( i + 1 < length() && at( i + 1 )->lineStart && at( i )->c.unicode() == 0xad ) {
4476 painter.drawText( xstart + w, y + baseLine, "\xad" ); 4482 painter.drawText( xstart + w, y + baseLine, "\xad" );
4477 } 4483 }
4478 if ( format->isMisspelled() ) { 4484 if ( format->isMisspelled() ) {
4479 painter.save(); 4485 painter.save();
4480 painter.setPen( QPen( Qt::red, 1, Qt::DotLine ) ); 4486 painter.setPen( QPen( Qt::red, 1, Qt::DotLine ) );
4481 painter.drawLine( xstart, y + baseLine + 1, xstart + w, y + baseLine + 1 ); 4487 painter.drawLine( xstart, y + baseLine + 1, xstart + w, y + baseLine + 1 );
4482 painter.restore(); 4488 painter.restore();
4483 } 4489 }
4484 4490
4485 i -= len; 4491 i -= len;
4486 4492
4487 if ( hasdoc && formatChar->isAnchor() && !formatChar->anchorHref().isEmpty() && 4493 if ( hasdoc && formatChar->isAnchor() && !formatChar->anchorHref().isEmpty() &&
4488 document()->focusIndicator.parag == this && 4494 document()->focusIndicator.parag == this &&
4489 ( document()->focusIndicator.start >= i && 4495 ( document()->focusIndicator.start >= i &&
4490 document()->focusIndicator.start + document()->focusIndicator.len <= i + len || 4496 document()->focusIndicator.start + document()->focusIndicator.len <= i + len ||
4491 document()->focusIndicator.start <= i && 4497 document()->focusIndicator.start <= i &&
4492 document()->focusIndicator.start + document()->focusIndicator.len >= i + len ) ) { 4498 document()->focusIndicator.start + document()->focusIndicator.len >= i + len ) ) {
4493 painter.drawWinFocusRect( QRect( xstart, y, w, h ) ); 4499 painter.drawWinFocusRect( QRect( xstart, y, w, h ) );
4494 } 4500 }
4495 4501
4496} 4502}
4497 4503
4498void QTextParagraph::drawLabel( QPainter* p, int x, int y, int w, int h, int base, const QColorGroup& cg ) 4504void QTextParagraph::drawLabel( QPainter* p, int x, int y, int w, int h, int base, const QColorGroup& cg )
4499{ 4505{
4500 QRect r ( x, y, w, h ); 4506 QRect r ( x, y, w, h );
4501 QStyleSheetItem::ListStyle s = listStyle(); 4507 QStyleSheetItem::ListStyle s = listStyle();
4502 4508
4503 p->save(); 4509 p->save();
4504 QTextFormat *format = at( 0 )->format(); 4510 QTextFormat *format = at( 0 )->format();
4505 if ( format ) { 4511 if ( format ) {
4506 p->setPen( format->color() ); 4512 p->setPen( format->color() );
4507 p->setFont( format->font() ); 4513 p->setFont( format->font() );
4508 } 4514 }
4509 QFontMetrics fm( p->fontMetrics() ); 4515 QFontMetrics fm( p->fontMetrics() );
4510 int size = fm.lineSpacing() / 3; 4516 int size = fm.lineSpacing() / 3;
4511 4517
4512 switch ( s ) { 4518 switch ( s ) {
4513 case QStyleSheetItem::ListDecimal: 4519 case QStyleSheetItem::ListDecimal:
4514 case QStyleSheetItem::ListLowerAlpha: 4520 case QStyleSheetItem::ListLowerAlpha:
4515 case QStyleSheetItem::ListUpperAlpha: 4521 case QStyleSheetItem::ListUpperAlpha:
4516 { 4522 {
4517 if ( list_val == -1 ) { // uninitialised list value, calcluate the right one 4523 if ( list_val == -1 ) { // uninitialised list value, calcluate the right one
4518 int depth = listDepth(); 4524 int depth = listDepth();
4519 list_val--; 4525 list_val--;
4520 // ### evil, square and expensive. This needs to be done when formatting, not when painting 4526 // ### evil, square and expensive. This needs to be done when formatting, not when painting
4521 QTextParagraph* s = prev(); 4527 QTextParagraph* s = prev();
4522 int depth_s; 4528 int depth_s;
4523 while ( s && (depth_s = s->listDepth()) >= depth ) { 4529 while ( s && (depth_s = s->listDepth()) >= depth ) {
4524 if ( depth_s == depth && s->isListItem() ) 4530 if ( depth_s == depth && s->isListItem() )
4525 list_val--; 4531 list_val--;
4526 s = s->prev(); 4532 s = s->prev();
4527 } 4533 }
4528 } 4534 }
4529 4535
4530 int n = list_val; 4536 int n = list_val;
4531 if ( n < -1 ) 4537 if ( n < -1 )
4532 n = -n - 1; 4538 n = -n - 1;
4533 QString l; 4539 QString l;
4534 switch ( s ) { 4540 switch ( s ) {
4535 case QStyleSheetItem::ListLowerAlpha: 4541 case QStyleSheetItem::ListLowerAlpha:
4536 if ( n < 27 ) { 4542 if ( n < 27 ) {
4537 l = QChar( ('a' + (char) (n-1))); 4543 l = QChar( ('a' + (char) (n-1)));
4538 break; 4544 break;
4539 } 4545 }
4540 case QStyleSheetItem::ListUpperAlpha: 4546 case QStyleSheetItem::ListUpperAlpha:
4541 if ( n < 27 ) { 4547 if ( n < 27 ) {
4542 l = QChar( ('A' + (char) (n-1))); 4548 l = QChar( ('A' + (char) (n-1)));
4543 break; 4549 break;
4544 } 4550 }
4545 break; 4551 break;
4546 default: //QStyleSheetItem::ListDecimal: 4552 default: //QStyleSheetItem::ListDecimal:
4547 l.setNum( n ); 4553 l.setNum( n );
4548 break; 4554 break;
4549 } 4555 }
4550 l += QString::fromLatin1(". "); 4556 l += QString::fromLatin1(". ");
4551 p->drawText( r.right() - fm.width( l ), r.top() + base, l ); 4557 p->drawText( r.right() - fm.width( l ), r.top() + base, l );
4552 } 4558 }
4553 break; 4559 break;
4554 case QStyleSheetItem::ListSquare: 4560 case QStyleSheetItem::ListSquare:
4555 { 4561 {
4556 QRect er( r.right() - size * 2, r.top() + fm.height() / 2 - size / 2, size, size ); 4562 QRect er( r.right() - size * 2, r.top() + fm.height() / 2 - size / 2, size, size );
4557 p->fillRect( er , cg.brush( QColorGroup::Text ) ); 4563 p->fillRect( er , cg.brush( QColorGroup::Text ) );
4558 } 4564 }
4559 break; 4565 break;
4560 case QStyleSheetItem::ListCircle: 4566 case QStyleSheetItem::ListCircle:
4561 { 4567 {
4562 QRect er( r.right()-size*2, r.top() + fm.height() / 2 - size / 2, size, size); 4568 QRect er( r.right()-size*2, r.top() + fm.height() / 2 - size / 2, size, size);
4563 p->drawEllipse( er ); 4569 p->drawEllipse( er );
4564 } 4570 }
4565 break; 4571 break;
4566 case QStyleSheetItem::ListDisc: 4572 case QStyleSheetItem::ListDisc:
4567 default: 4573 default:
4568 { 4574 {
4569 p->setBrush( cg.brush( QColorGroup::Text )); 4575 p->setBrush( cg.brush( QColorGroup::Text ));
4570 QRect er( r.right()-size*2, r.top() + fm.height() / 2 - size / 2, size, size); 4576 QRect er( r.right()-size*2, r.top() + fm.height() / 2 - size / 2, size, size);
4571 p->drawEllipse( er ); 4577 p->drawEllipse( er );
4572 p->setBrush( Qt::NoBrush ); 4578 p->setBrush( Qt::NoBrush );
4573 } 4579 }
4574 break; 4580 break;
4575 } 4581 }
4576 4582
4577 p->restore(); 4583 p->restore();
4578} 4584}
4579 4585
4580void QTextParagraph::readStyleInformation( QDataStream& stream ) 4586void QTextParagraph::readStyleInformation( QDataStream& stream )
4581{ 4587{
4582 int int_align, int_lstyle; 4588 int int_align, int_lstyle;
4583 uchar uchar_litem, uchar_rtext, uchar_dir; 4589 uchar uchar_litem, uchar_rtext, uchar_dir;
4584 stream >> int_align >> int_lstyle >> utm >> ubm >> ulm >> urm >> uflm 4590 stream >> int_align >> int_lstyle >> utm >> ubm >> ulm >> urm >> uflm
4585 >> ulinespacing >> ldepth >> uchar_litem >> uchar_rtext >> uchar_dir; 4591 >> ulinespacing >> ldepth >> uchar_litem >> uchar_rtext >> uchar_dir;
4586 align = int_align; lstyle = (QStyleSheetItem::ListStyle) int_lstyle; 4592 align = int_align; lstyle = (QStyleSheetItem::ListStyle) int_lstyle;
4587 litem = uchar_litem; rtext = uchar_rtext; str->setDirection( (QChar::Direction)uchar_dir ); 4593 litem = uchar_litem; rtext = uchar_rtext; str->setDirection( (QChar::Direction)uchar_dir );
4588 QTextParagraph* s = prev() ? prev() : this; 4594 QTextParagraph* s = prev() ? prev() : this;
4589 while ( s ) { 4595 while ( s ) {
4590 s->invalidate( 0 ); 4596 s->invalidate( 0 );
4591 s = s->next(); 4597 s = s->next();
4592 } 4598 }
4593} 4599}
4594 4600
4595void QTextParagraph::writeStyleInformation( QDataStream& stream ) const 4601void QTextParagraph::writeStyleInformation( QDataStream& stream ) const
4596{ 4602{
4597 stream << (int) align << (int) lstyle << utm << ubm << ulm << urm << uflm << ulinespacing << ldepth << (uchar)litem << (uchar)rtext << (uchar)str->direction(); 4603 stream << (int) align << (int) lstyle << utm << ubm << ulm << urm << uflm << ulinespacing << ldepth << (uchar)litem << (uchar)rtext << (uchar)str->direction();
4598} 4604}
4599 4605
4600 4606
4601 4607
4602void QTextParagraph::setListDepth( int depth ) { 4608void QTextParagraph::setListDepth( int depth ) {
4603 if ( !hasdoc || depth == ldepth ) 4609 if ( !hasdoc || depth == ldepth )
4604 return; 4610 return;
4605 ldepth = depth; 4611 ldepth = depth;
4606 QTextParagraph* s = prev() ? prev() : this; 4612 QTextParagraph* s = prev() ? prev() : this;
4607 while ( s ) { 4613 while ( s ) {
4608 s->invalidate( 0 ); 4614 s->invalidate( 0 );
4609 s = s->next(); 4615 s = s->next();
4610 } 4616 }
4611} 4617}
4612 4618
4613int *QTextParagraph::tabArray() const 4619int *QTextParagraph::tabArray() const
4614{ 4620{
4615 int *ta = tArray; 4621 int *ta = tArray;
4616 if ( !ta && hasdoc ) 4622 if ( !ta && hasdoc )
4617 ta = document()->tabArray(); 4623 ta = document()->tabArray();
4618 return ta; 4624 return ta;
4619} 4625}
4620 4626
4621int QTextParagraph::nextTab( int, int x ) 4627int QTextParagraph::nextTab( int, int x )
4622{ 4628{
4623 int *ta = tArray; 4629 int *ta = tArray;
4624 if ( hasdoc ) { 4630 if ( hasdoc ) {
4625 if ( !ta ) 4631 if ( !ta )
4626 ta = document()->tabArray(); 4632 ta = document()->tabArray();
4627 tabStopWidth = document()->tabStopWidth(); 4633 tabStopWidth = document()->tabStopWidth();
4628 } 4634 }
4629 if ( ta ) { 4635 if ( ta ) {
4630 int i = 0; 4636 int i = 0;
4631 while ( ta[ i ] ) { 4637 while ( ta[ i ] ) {
4632 if ( ta[ i ] >= x ) 4638 if ( ta[ i ] >= x )
4633 return tArray[ i ]; 4639 return tArray[ i ];
4634 ++i; 4640 ++i;
4635 } 4641 }
4636 return tArray[ 0 ]; 4642 return tArray[ 0 ];
4637 } else { 4643 } else {
4638 int d; 4644 int d;
4639 if ( tabStopWidth != 0 ) 4645 if ( tabStopWidth != 0 )
4640 d = x / tabStopWidth; 4646 d = x / tabStopWidth;
4641 else 4647 else
4642 return x; 4648 return x;
4643 return tabStopWidth * ( d + 1 ); 4649 return tabStopWidth * ( d + 1 );
4644 } 4650 }
4645} 4651}
4646 4652
4647void QTextParagraph::adjustToPainter( QPainter *p ) 4653void QTextParagraph::adjustToPainter( QPainter *p )
4648{ 4654{
4649 for ( int i = 0; i < length(); ++i ) { 4655 for ( int i = 0; i < length(); ++i ) {
4650 if ( at( i )->isCustom() ) 4656 if ( at( i )->isCustom() )
4651 at( i )->customItem()->adjustToPainter( p ); 4657 at( i )->customItem()->adjustToPainter( p );
4652 } 4658 }
4653} 4659}
4654 4660
4655QTextFormatCollection *QTextParagraph::formatCollection() const 4661QTextFormatCollection *QTextParagraph::formatCollection() const
4656{ 4662{
4657 if ( hasdoc ) 4663 if ( hasdoc )
4658 return document()->formatCollection(); 4664 return document()->formatCollection();
4659 if ( !qFormatCollection ) { 4665 if ( !qFormatCollection ) {
4660 qFormatCollection = new QTextFormatCollection; 4666 qFormatCollection = new QTextFormatCollection;
4661 static QSingleCleanupHandler<QTextFormatCollection> qtfCleanup; 4667 static QSingleCleanupHandler<QTextFormatCollection> qtfCleanup;
4662 qtfCleanup.set( &qFormatCollection ); 4668 qtfCleanup.set( &qFormatCollection );
4663 } 4669 }
4664 return qFormatCollection; 4670 return qFormatCollection;
4665} 4671}
4666 4672
4667QString QTextParagraph::richText() const 4673QString QTextParagraph::richText() const
4668{ 4674{
4669 QString s; 4675 QString s;
4670 QTextStringChar *formatChar = 0; 4676 QTextStringChar *formatChar = 0;
4671 QString spaces; 4677 QString spaces;
4672 bool doStart = richTextExportStart && richTextExportStart->paragraph() == this; 4678 bool doStart = richTextExportStart && richTextExportStart->paragraph() == this;
4673 bool doEnd = richTextExportEnd && richTextExportEnd->paragraph() == this; 4679 bool doEnd = richTextExportEnd && richTextExportEnd->paragraph() == this;
4674 int i; 4680 int i;
4675 for ( i = 0; i < length()-1; ++i ) { 4681 for ( i = 0; i < length()-1; ++i ) {
4676 if ( doStart && i && richTextExportStart->index() == i ) 4682 if ( doStart && i && richTextExportStart->index() == i )
4677 s += "<selstart/>"; 4683 s += "<selstart/>";
4678 if ( doEnd && richTextExportEnd->index() == i ) 4684 if ( doEnd && richTextExportEnd->index() == i )
4679 s += "<selend/>"; 4685 s += "<selend/>";
4680 QTextStringChar *c = &str->at( i ); 4686 QTextStringChar *c = &str->at( i );
4681 if ( c->isAnchor() && !c->anchorName().isEmpty() ) { 4687 if ( c->isAnchor() && !c->anchorName().isEmpty() ) {
4682 if ( c->anchorName().contains( '#' ) ) { 4688 if ( c->anchorName().contains( '#' ) ) {
4683 QStringList l = QStringList::split( '#', c->anchorName() ); 4689 QStringList l = QStringList::split( '#', c->anchorName() );
4684 for ( QStringList::ConstIterator it = l.begin(); it != l.end(); ++it ) 4690 for ( QStringList::ConstIterator it = l.begin(); it != l.end(); ++it )
4685 s += "<a name=\"" + *it + "\"></a>"; 4691 s += "<a name=\"" + *it + "\"></a>";
4686 } else { 4692 } else {
4687 s += "<a name=\"" + c->anchorName() + "\"></a>"; 4693 s += "<a name=\"" + c->anchorName() + "\"></a>";
4688 } 4694 }
4689 } 4695 }
4690 if ( !formatChar ) { 4696 if ( !formatChar ) {
4691 s += c->format()->makeFormatChangeTags( formatCollection()->defaultFormat(), 4697 s += c->format()->makeFormatChangeTags( formatCollection()->defaultFormat(),
4692 0, QString::null, c->anchorHref() ); 4698 0, QString::null, c->anchorHref() );
4693 formatChar = c; 4699 formatChar = c;
4694 } else if ( ( formatChar->format()->key() != c->format()->key() ) || 4700 } else if ( ( formatChar->format()->key() != c->format()->key() ) ||
4695 (c->anchorHref() != formatChar->anchorHref() ) ) { 4701 (c->anchorHref() != formatChar->anchorHref() ) ) {
4696 s += c->format()->makeFormatChangeTags( formatCollection()->defaultFormat(), 4702 s += c->format()->makeFormatChangeTags( formatCollection()->defaultFormat(),
4697 formatChar->format() , formatChar->anchorHref(), c->anchorHref() ); 4703 formatChar->format() , formatChar->anchorHref(), c->anchorHref() );
4698 formatChar = c; 4704 formatChar = c;
4699 } 4705 }
4700 if ( c->c == '<' ) 4706 if ( c->c == '<' )
4701 s += "&lt;"; 4707 s += "&lt;";
4702 else if ( c->c == '>' ) 4708 else if ( c->c == '>' )
4703 s += "&gt;"; 4709 s += "&gt;";
4704 else if ( c->isCustom() ) 4710 else if ( c->isCustom() )
4705 s += c->customItem()->richText(); 4711 s += c->customItem()->richText();
4706 else if ( c->c == '\n' || c->c == QChar_linesep ) 4712 else if ( c->c == '\n' || c->c == QChar_linesep )
4707 s += "<br />"; // space on purpose for compatibility with Netscape, Lynx & Co. 4713 s += "<br />"; // space on purpose for compatibility with Netscape, Lynx & Co.
4708 else 4714 else
4709 s += c->c; 4715 s += c->c;
4710 } 4716 }
4711 if ( doEnd && richTextExportEnd->index() == i ) 4717 if ( doEnd && richTextExportEnd->index() == i )
4712 s += "<selend/>"; 4718 s += "<selend/>";
4713 if ( formatChar ) 4719 if ( formatChar )
4714 s += formatChar->format()->makeFormatEndTags( formatCollection()->defaultFormat(), formatChar->anchorHref() ); 4720 s += formatChar->format()->makeFormatEndTags( formatCollection()->defaultFormat(), formatChar->anchorHref() );
4715 return s; 4721 return s;
4716} 4722}
4717 4723
4718void QTextParagraph::addCommand( QTextCommand *cmd ) 4724void QTextParagraph::addCommand( QTextCommand *cmd )
4719{ 4725{
4720 if ( !hasdoc ) 4726 if ( !hasdoc )
4721 pseudoDocument()->commandHistory->addCommand( cmd ); 4727 pseudoDocument()->commandHistory->addCommand( cmd );
4722 else 4728 else
4723 document()->commands()->addCommand( cmd ); 4729 document()->commands()->addCommand( cmd );
4724} 4730}
4725 4731
4726QTextCursor *QTextParagraph::undo( QTextCursor *c ) 4732QTextCursor *QTextParagraph::undo( QTextCursor *c )
4727{ 4733{
4728 if ( !hasdoc ) 4734 if ( !hasdoc )
4729 return pseudoDocument()->commandHistory->undo( c ); 4735 return pseudoDocument()->commandHistory->undo( c );
4730 return document()->commands()->undo( c ); 4736 return document()->commands()->undo( c );
4731} 4737}
4732 4738
4733QTextCursor *QTextParagraph::redo( QTextCursor *c ) 4739QTextCursor *QTextParagraph::redo( QTextCursor *c )
4734{ 4740{
4735 if ( !hasdoc ) 4741 if ( !hasdoc )
4736 return pseudoDocument()->commandHistory->redo( c ); 4742 return pseudoDocument()->commandHistory->redo( c );
4737 return document()->commands()->redo( c ); 4743 return document()->commands()->redo( c );
4738} 4744}
4739 4745
4740int QTextParagraph::topMargin() const 4746int QTextParagraph::topMargin() const
4741{ 4747{
4742 int m = 0; 4748 int m = 0;
4743 if ( rtext ) { 4749 if ( rtext ) {
4744 m = isListItem() ? (document()->li_tm/QMAX(1,listDepth())) : document()->par_tm; 4750 m = isListItem() ? (document()->li_tm/QMAX(1,listDepth())) : document()->par_tm;
4745 if ( listDepth() == 1 &&( !prev() || prev()->listDepth() < listDepth() ) ) 4751 if ( listDepth() == 1 &&( !prev() || prev()->listDepth() < listDepth() ) )
4746 m = QMAX( m, document()->list_tm ); 4752 m = QMAX( m, document()->list_tm );
4747 } 4753 }
4748 m += utm; 4754 m += utm;
4749 return scale( m, QTextFormat::painter() ); 4755 return scale( m, QTextFormat::painter() );
4750} 4756}
4751 4757
4752int QTextParagraph::bottomMargin() const 4758int QTextParagraph::bottomMargin() const
4753{ 4759{
4754 int m = 0; 4760 int m = 0;
4755 if ( rtext ) { 4761 if ( rtext ) {
4756 m = isListItem() ? (document()->li_bm/QMAX(1,listDepth())) : document()->par_bm; 4762 m = isListItem() ? (document()->li_bm/QMAX(1,listDepth())) : document()->par_bm;
4757 if ( listDepth() == 1 &&( !next() || next()->listDepth() < listDepth() ) ) 4763 if ( listDepth() == 1 &&( !next() || next()->listDepth() < listDepth() ) )
4758 m = QMAX( m, document()->list_bm ); 4764 m = QMAX( m, document()->list_bm );
4759 } 4765 }
4760 m += ubm; 4766 m += ubm;
4761 return scale( m, QTextFormat::painter() ); 4767 return scale( m, QTextFormat::painter() );
4762} 4768}
4763 4769
4764int QTextParagraph::leftMargin() const 4770int QTextParagraph::leftMargin() const
4765{ 4771{
4766 int m = ulm; 4772 int m = ulm;
4767 if ( listDepth() ) 4773 if ( listDepth() )
4768 m += listDepth() * document()->list_lm; 4774 m += listDepth() * document()->list_lm;
4769 return scale( m, QTextFormat::painter() ); 4775 return scale( m, QTextFormat::painter() );
4770} 4776}
4771 4777
4772int QTextParagraph::firstLineMargin() const 4778int QTextParagraph::firstLineMargin() const
4773{ 4779{
4774 int m = uflm; 4780 int m = uflm;
4775 return scale( m, QTextFormat::painter() ); 4781 return scale( m, QTextFormat::painter() );
4776} 4782}
4777 4783
4778int QTextParagraph::rightMargin() const 4784int QTextParagraph::rightMargin() const
4779{ 4785{
4780 int m = urm; 4786 int m = urm;
4781 return scale( m, QTextFormat::painter() ); 4787 return scale( m, QTextFormat::painter() );
4782} 4788}
4783 4789
4784int QTextParagraph::lineSpacing() const 4790int QTextParagraph::lineSpacing() const
4785{ 4791{
4786 int l = ulinespacing; 4792 int l = ulinespacing;
4787 l = scale( l, QTextFormat::painter() ); 4793 l = scale( l, QTextFormat::painter() );
4788 return l; 4794 return l;
4789} 4795}
4790 4796
4791void QTextParagraph::copyParagData( QTextParagraph *parag ) 4797void QTextParagraph::copyParagData( QTextParagraph *parag )
4792{ 4798{
4793 rtext = parag->rtext; 4799 rtext = parag->rtext;
4794 lstyle = parag->lstyle; 4800 lstyle = parag->lstyle;
4795 ldepth = parag->ldepth; 4801 ldepth = parag->ldepth;
4796 litem = parag->litem; 4802 litem = parag->litem;
4797 align = parag->align; 4803 align = parag->align;
4798 utm = parag->utm; 4804 utm = parag->utm;
4799 ubm = parag->ubm; 4805 ubm = parag->ubm;
4800 urm = parag->urm; 4806 urm = parag->urm;
4801 ulm = parag->ulm; 4807 ulm = parag->ulm;
4802 uflm = parag->uflm; 4808 uflm = parag->uflm;
4803 ulinespacing = parag->ulinespacing; 4809 ulinespacing = parag->ulinespacing;
4804 QColor *c = parag->backgroundColor(); 4810 QColor *c = parag->backgroundColor();
4805 if ( c ) 4811 if ( c )
4806 setBackgroundColor( *c ); 4812 setBackgroundColor( *c );
4807 str->setDirection( parag->str->direction() ); 4813 str->setDirection( parag->str->direction() );
4808} 4814}
4809 4815
4810void QTextParagraph::show() 4816void QTextParagraph::show()
4811{ 4817{
4812 if ( visible || !hasdoc ) 4818 if ( visible || !hasdoc )
4813 return; 4819 return;
4814 visible = TRUE; 4820 visible = TRUE;
4815} 4821}
4816 4822
4817void QTextParagraph::hide() 4823void QTextParagraph::hide()
4818{ 4824{
4819 if ( !visible || !hasdoc ) 4825 if ( !visible || !hasdoc )
4820 return; 4826 return;
4821 visible = FALSE; 4827 visible = FALSE;
4822} 4828}
4823 4829
4824void QTextParagraph::setDirection( QChar::Direction d ) 4830void QTextParagraph::setDirection( QChar::Direction d )
4825{ 4831{
4826 if ( str && str->direction() != d ) { 4832 if ( str && str->direction() != d ) {
4827 str->setDirection( d ); 4833 str->setDirection( d );
4828 invalidate( 0 ); 4834 invalidate( 0 );
4829 } 4835 }
4830} 4836}
4831 4837
4832QChar::Direction QTextParagraph::direction() const 4838QChar::Direction QTextParagraph::direction() const
4833{ 4839{
4834 return (str ? str->direction() : QChar::DirON ); 4840 return (str ? str->direction() : QChar::DirON );
4835} 4841}
4836 4842
4837void QTextParagraph::setChanged( bool b, bool recursive ) 4843void QTextParagraph::setChanged( bool b, bool recursive )
4838{ 4844{
4839 changed = b; 4845 changed = b;
4840 if ( recursive ) { 4846 if ( recursive ) {
4841 if ( document() && document()->parentParagraph() ) 4847 if ( document() && document()->parentParagraph() )
4842 document()->parentParagraph()->setChanged( b, recursive ); 4848 document()->parentParagraph()->setChanged( b, recursive );
4843 } 4849 }
4844} 4850}
4845 4851
4846// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4852// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4847 4853
4848 4854
4849QTextPreProcessor::QTextPreProcessor() 4855QTextPreProcessor::QTextPreProcessor()
4850{ 4856{
4851} 4857}
4852 4858
4853// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4859// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4854 4860
4855QTextFormatter::QTextFormatter() 4861QTextFormatter::QTextFormatter()
4856 : thisminw(0), thiswused(0), wrapEnabled( TRUE ), wrapColumn( -1 ), biw( FALSE ) 4862 : thisminw(0), thiswused(0), wrapEnabled( TRUE ), wrapColumn( -1 ), biw( FALSE )
4857{ 4863{
4858} 4864}
4859 4865
4860QTextLineStart *QTextFormatter::formatLine( QTextParagraph *parag, QTextString *string, QTextLineStart *line, 4866QTextLineStart *QTextFormatter::formatLine( QTextParagraph *parag, QTextString *string, QTextLineStart *line,
4861 QTextStringChar *startChar, QTextStringChar *lastChar, int align, int space ) 4867 QTextStringChar *startChar, QTextStringChar *lastChar, int align, int space )
4862{ 4868{
4863#ifndef QT_NO_COMPLEXTEXT 4869#ifndef QT_NO_COMPLEXTEXT
4864 if( string->isBidi() ) 4870 if( string->isBidi() )
4865 return bidiReorderLine( parag, string, line, startChar, lastChar, align, space ); 4871 return bidiReorderLine( parag, string, line, startChar, lastChar, align, space );
4866#endif 4872#endif
4867 int start = (startChar - &string->at(0)); 4873 int start = (startChar - &string->at(0));
4868 int last = (lastChar - &string->at(0) ); 4874 int last = (lastChar - &string->at(0) );
4869 // do alignment Auto == Left in this case 4875 // do alignment Auto == Left in this case
4870 if ( align & Qt::AlignHCenter || align & Qt::AlignRight ) { 4876 if ( align & Qt::AlignHCenter || align & Qt::AlignRight ) {
4871 if ( align & Qt::AlignHCenter ) 4877 if ( align & Qt::AlignHCenter )
4872 space /= 2; 4878 space /= 2;
4873 for ( int j = start; j <= last; ++j ) 4879 for ( int j = start; j <= last; ++j )
4874 string->at( j ).x += space; 4880 string->at( j ).x += space;
4875 } else if ( align & Qt3::AlignJustify ) { 4881 } else if ( align & Qt3::AlignJustify ) {
4876 int numSpaces = 0; 4882 int numSpaces = 0;
4877 // End at "last-1", the last space ends up with a width of 0 4883 // End at "last-1", the last space ends up with a width of 0
4878 for ( int j = last-1; j >= start; --j ) { 4884 for ( int j = last-1; j >= start; --j ) {
4879 // Start at last tab, if any. 4885 // Start at last tab, if any.
4880 if ( string->at( j ).c == '\t' ) { 4886 if ( string->at( j ).c == '\t' ) {
4881 start = j+1; 4887 start = j+1;
4882 break; 4888 break;
4883 } 4889 }
4884 if( isBreakable( string, j ) ) { 4890 if( isBreakable( string, j ) ) {
4885 numSpaces++; 4891 numSpaces++;
4886 } 4892 }
4887 } 4893 }
4888 int toAdd = 0; 4894 int toAdd = 0;
4889 for ( int k = start + 1; k <= last; ++k ) { 4895 for ( int k = start + 1; k <= last; ++k ) {
4890 if( isBreakable( string, k ) && numSpaces ) { 4896 if( isBreakable( string, k ) && numSpaces ) {
4891 int s = space / numSpaces; 4897 int s = space / numSpaces;
4892 toAdd += s; 4898 toAdd += s;
4893 space -= s; 4899 space -= s;
4894 numSpaces--; 4900 numSpaces--;
4895 } 4901 }
4896 string->at( k ).x += toAdd; 4902 string->at( k ).x += toAdd;
4897 } 4903 }
4898 } 4904 }
4899 4905
4900 if ( last >= 0 && last < string->length() ) 4906 if ( last >= 0 && last < string->length() )
4901 line->w = string->at( last ).x + string->width( last ); 4907 line->w = string->at( last ).x + string->width( last );
4902 else 4908 else
4903 line->w = 0; 4909 line->w = 0;
4904 4910
4905 return new QTextLineStart(); 4911 return new QTextLineStart();
4906} 4912}
4907 4913
4908#ifndef QT_NO_COMPLEXTEXT 4914#ifndef QT_NO_COMPLEXTEXT
4909 4915
4910#ifdef BIDI_DEBUG 4916#ifdef BIDI_DEBUG
4911#include <iostream> 4917#include <iostream>
4912#endif 4918#endif
4913 4919
4914// collects one line of the paragraph and transforms it to visual order 4920// collects one line of the paragraph and transforms it to visual order
4915QTextLineStart *QTextFormatter::bidiReorderLine( QTextParagraph * /*parag*/, QTextString *text, QTextLineStart *line, 4921QTextLineStart *QTextFormatter::bidiReorderLine( QTextParagraph * /*parag*/, QTextString *text, QTextLineStart *line,
4916 QTextStringChar *startChar, QTextStringChar *lastChar, int align, int space ) 4922 QTextStringChar *startChar, QTextStringChar *lastChar, int align, int space )
4917{ 4923{
4918 int start = (startChar - &text->at(0)); 4924 int start = (startChar - &text->at(0));
4919 int last = (lastChar - &text->at(0) ); 4925 int last = (lastChar - &text->at(0) );
4920 4926
4921 QBidiControl *control = new QBidiControl( line->context(), line->status ); 4927 QBidiControl *control = new QBidiControl( line->context(), line->status );
4922 QString str; 4928 QString str;
4923 str.setUnicode( 0, last - start + 1 ); 4929 str.setUnicode( 0, last - start + 1 );
4924 // fill string with logically ordered chars. 4930 // fill string with logically ordered chars.
4925 QTextStringChar *ch = startChar; 4931 QTextStringChar *ch = startChar;
4926 QChar *qch = (QChar *)str.unicode(); 4932 QChar *qch = (QChar *)str.unicode();
4927 while ( ch <= lastChar ) { 4933 while ( ch <= lastChar ) {
4928 *qch = ch->c; 4934 *qch = ch->c;
4929 qch++; 4935 qch++;
4930 ch++; 4936 ch++;
4931 } 4937 }
4932 int x = startChar->x; 4938 int x = startChar->x;
4933 4939
4934 QPtrList<QTextRun> *runs; 4940 QPtrList<QTextRun> *runs;
4935 runs = QComplexText::bidiReorderLine(control, str, 0, last - start + 1, 4941 runs = QComplexText::bidiReorderLine(control, str, 0, last - start + 1,
4936 (text->isRightToLeft() ? QChar::DirR : QChar::DirL) ); 4942 (text->isRightToLeft() ? QChar::DirR : QChar::DirL) );
4937 4943
4938 // now construct the reordered string out of the runs... 4944 // now construct the reordered string out of the runs...
4939 4945
4940 int numSpaces = 0; 4946 int numSpaces = 0;
4941 // set the correct alignment. This is a bit messy.... 4947 // set the correct alignment. This is a bit messy....
4942 if( align == Qt3::AlignAuto ) { 4948 if( align == Qt3::AlignAuto ) {
4943 // align according to directionality of the paragraph... 4949 // align according to directionality of the paragraph...
4944 if ( text->isRightToLeft() ) 4950 if ( text->isRightToLeft() )
4945 align = Qt::AlignRight; 4951 align = Qt::AlignRight;
4946 } 4952 }
4947 4953
4948 if ( align & Qt::AlignHCenter ) 4954 if ( align & Qt::AlignHCenter )
4949 x += space/2; 4955 x += space/2;
4950 else if ( align & Qt::AlignRight ) 4956 else if ( align & Qt::AlignRight )
4951 x += space; 4957 x += space;
4952 else if ( align & Qt3::AlignJustify ) { 4958 else if ( align & Qt3::AlignJustify ) {
4953 // End at "last-1", the last space ends up with a width of 0 4959 // End at "last-1", the last space ends up with a width of 0
4954 for ( int j = last-1; j >= start; --j ) { 4960 for ( int j = last-1; j >= start; --j ) {
4955 // Start at last tab, if any. 4961 // Start at last tab, if any.
4956 if ( text->at( j ).c == '\t' ) { 4962 if ( text->at( j ).c == '\t' ) {
4957 start = j+1; 4963 start = j+1;
4958 break; 4964 break;
4959 } 4965 }
4960 if( isBreakable( text, j ) ) { 4966 if( isBreakable( text, j ) ) {
4961 numSpaces++; 4967 numSpaces++;
4962 } 4968 }
4963 } 4969 }
4964 } 4970 }
4965 int toAdd = 0; 4971 int toAdd = 0;
4966 bool first = TRUE; 4972 bool first = TRUE;
4967 QTextRun *r = runs->first(); 4973 QTextRun *r = runs->first();
4968 int xmax = -0xffffff; 4974 int xmax = -0xffffff;
4969 while ( r ) { 4975 while ( r ) {
4970 if(r->level %2) { 4976 if(r->level %2) {
4971 // odd level, need to reverse the string 4977 // odd level, need to reverse the string
4972 int pos = r->stop + start; 4978 int pos = r->stop + start;
4973 while(pos >= r->start + start) { 4979 while(pos >= r->start + start) {
4974 QTextStringChar *c = &text->at(pos); 4980 QTextStringChar *c = &text->at(pos);
4975 if( numSpaces && !first && isBreakable( text, pos ) ) { 4981 if( numSpaces && !first && isBreakable( text, pos ) ) {
4976 int s = space / numSpaces; 4982 int s = space / numSpaces;
4977 toAdd += s; 4983 toAdd += s;
4978 space -= s; 4984 space -= s;
4979 numSpaces--; 4985 numSpaces--;
4980 } else if ( first ) { 4986 } else if ( first ) {
4981 first = FALSE; 4987 first = FALSE;
4982 if ( c->c == ' ' ) 4988 if ( c->c == ' ' )
4983 x -= c->format()->width( ' ' ); 4989 x -= c->format()->width( ' ' );
4984 } 4990 }
4985 c->x = x + toAdd; 4991 c->x = x + toAdd;
4986 c->rightToLeft = TRUE; 4992 c->rightToLeft = TRUE;
4987 c->startOfRun = FALSE; 4993 c->startOfRun = FALSE;
4988 int ww = 0; 4994 int ww = 0;
4989 if ( c->c.unicode() >= 32 || c->c == '\t' || c->c == '\n' || c->isCustom() ) { 4995 if ( c->c.unicode() >= 32 || c->c == '\t' || c->c == '\n' || c->isCustom() ) {
4990 ww = text->width( pos ); 4996 ww = text->width( pos );
4991 } else { 4997 } else {
4992 ww = c->format()->width( ' ' ); 4998 ww = c->format()->width( ' ' );
4993 } 4999 }
4994 if ( xmax < x + toAdd + ww ) xmax = x + toAdd + ww; 5000 if ( xmax < x + toAdd + ww ) xmax = x + toAdd + ww;
4995 x += ww; 5001 x += ww;
4996 pos--; 5002 pos--;
4997 } 5003 }
4998 } else { 5004 } else {
4999 int pos = r->start + start; 5005 int pos = r->start + start;
5000 while(pos <= r->stop + start) { 5006 while(pos <= r->stop + start) {
5001 QTextStringChar* c = &text->at(pos); 5007 QTextStringChar* c = &text->at(pos);
5002 if( numSpaces && !first && isBreakable( text, pos ) ) { 5008 if( numSpaces && !first && isBreakable( text, pos ) ) {
5003 int s = space / numSpaces; 5009 int s = space / numSpaces;
5004 toAdd += s; 5010 toAdd += s;
5005 space -= s; 5011 space -= s;
5006 numSpaces--; 5012 numSpaces--;
5007 } else if ( first ) { 5013 } else if ( first ) {
5008 first = FALSE; 5014 first = FALSE;
5009 if ( c->c == ' ' ) 5015 if ( c->c == ' ' )
5010 x -= c->format()->width( ' ' ); 5016 x -= c->format()->width( ' ' );
5011 } 5017 }
5012 c->x = x + toAdd; 5018 c->x = x + toAdd;
5013 c->rightToLeft = FALSE; 5019 c->rightToLeft = FALSE;
5014 c->startOfRun = FALSE; 5020 c->startOfRun = FALSE;
5015 int ww = 0; 5021 int ww = 0;
5016 if ( c->c.unicode() >= 32 || c->c == '\t' || c->isCustom() ) { 5022 if ( c->c.unicode() >= 32 || c->c == '\t' || c->isCustom() ) {
5017 ww = text->width( pos ); 5023 ww = text->width( pos );
5018 } else { 5024 } else {
5019 ww = c->format()->width( ' ' ); 5025 ww = c->format()->width( ' ' );
5020 } 5026 }
5021 if ( xmax < x + toAdd + ww ) xmax = x + toAdd + ww; 5027 if ( xmax < x + toAdd + ww ) xmax = x + toAdd + ww;
5022 x += ww; 5028 x += ww;
5023 pos++; 5029 pos++;
5024 } 5030 }
5025 } 5031 }
5026 text->at( r->start + start ).startOfRun = TRUE; 5032 text->at( r->start + start ).startOfRun = TRUE;
5027 r = runs->next(); 5033 r = runs->next();
5028 } 5034 }
5029 5035
5030 line->w = xmax + 10; 5036 line->w = xmax + 10;
5031 QTextLineStart *ls = new QTextLineStart( control->context, control->status ); 5037 QTextLineStart *ls = new QTextLineStart( control->context, control->status );
5032 delete control; 5038 delete control;
5033 delete runs; 5039 delete runs;
5034 return ls; 5040 return ls;
5035} 5041}
5036#endif 5042#endif
5037 5043
5038bool QTextFormatter::isBreakable( QTextString *string, int pos ) 5044bool QTextFormatter::isBreakable( QTextString *string, int pos )
5039{ 5045{
5040 const QChar &c = string->at( pos ).c; 5046 const QChar &c = string->at( pos ).c;
5041 char ch = c.latin1(); 5047 char ch = c.latin1();
5042 if ( c == QChar_linesep ) 5048 if ( c == QChar_linesep )
5043 return TRUE; 5049 return TRUE;
5044 if ( c.isSpace() && ch != '\n' && c.unicode() != 0x00a0U ) 5050 if ( c.isSpace() && ch != '\n' && c.unicode() != 0x00a0U )
5045 return TRUE; 5051 return TRUE;
5046 if ( c.unicode() == 0xad ) // soft hyphen 5052 if ( c.unicode() == 0xad ) // soft hyphen
5047 return TRUE; 5053 return TRUE;
5048 if ( !ch ) { 5054 if ( !ch ) {
5049 // not latin1, need to do more sophisticated checks for other scripts 5055 // not latin1, need to do more sophisticated checks for other scripts
5050 uchar row = c.row(); 5056 uchar row = c.row();
5051 if ( row == 0x0e ) { 5057 if ( row == 0x0e ) {
5052 // 0e00 - 0e7f == Thai 5058 // 0e00 - 0e7f == Thai
5053 if ( c.cell() < 0x80 ) { 5059 if ( c.cell() < 0x80 ) {
5054#ifdef HAVE_THAI_BREAKS 5060#ifdef HAVE_THAI_BREAKS
5055 // check for thai 5061 // check for thai
5056 if( string != cachedString ) { 5062 if( string != cachedString ) {
5057 // build up string of thai chars 5063 // build up string of thai chars
5058 QTextCodec *thaiCodec = QTextCodec::codecForMib(2259); 5064 QTextCodec *thaiCodec = QTextCodec::codecForMib(2259);
5059 if ( !thaiCache ) 5065 if ( !thaiCache )
5060 thaiCache = new QCString; 5066 thaiCache = new QCString;
5061 if ( !thaiIt ) 5067 if ( !thaiIt )
5062 thaiIt = ThBreakIterator::createWordInstance(); 5068 thaiIt = ThBreakIterator::createWordInstance();
5063 *thaiCache = thaiCodec->fromUnicode( s->string() ); 5069 *thaiCache = thaiCodec->fromUnicode( s->string() );
5064 } 5070 }
5065 thaiIt->setText(thaiCache->data()); 5071 thaiIt->setText(thaiCache->data());
5066 for(int i = thaiIt->first(); i != thaiIt->DONE; i = thaiIt->next() ) { 5072 for(int i = thaiIt->first(); i != thaiIt->DONE; i = thaiIt->next() ) {
5067 if( i == pos ) 5073 if( i == pos )
5068 return TRUE; 5074 return TRUE;
5069 if( i > pos ) 5075 if( i > pos )
5070 return FALSE; 5076 return FALSE;
5071 } 5077 }
5072 return FALSE; 5078 return FALSE;
5073#else 5079#else
5074 // if we don't have a thai line breaking lib, allow 5080 // if we don't have a thai line breaking lib, allow
5075 // breaks everywhere except directly before punctuation. 5081 // breaks everywhere except directly before punctuation.
5076 return TRUE; 5082 return TRUE;
5077#endif 5083#endif
5078 } else 5084 } else
5079 return FALSE; 5085 return FALSE;
5080 } 5086 }
5081 if ( row < 0x11 ) // no asian font 5087 if ( row < 0x11 ) // no asian font
5082 return FALSE; 5088 return FALSE;
5083 if ( row > 0x2d && row < 0xfb || row == 0x11 ) 5089 if ( row > 0x2d && row < 0xfb || row == 0x11 )
5084 // asian line breaking. Everywhere allowed except directly 5090 // asian line breaking. Everywhere allowed except directly
5085 // in front of a punctuation character. 5091 // in front of a punctuation character.
5086 return TRUE; 5092 return TRUE;
5087 } 5093 }
5088 return FALSE; 5094 return FALSE;
5089} 5095}
5090 5096
5091void QTextFormatter::insertLineStart( QTextParagraph *parag, int index, QTextLineStart *ls ) 5097void QTextFormatter::insertLineStart( QTextParagraph *parag, int index, QTextLineStart *ls )
5092{ 5098{
5093 if ( index > 0 ) { // we can assume that only first line starts are insrted multiple times 5099 if ( index > 0 ) { // we can assume that only first line starts are insrted multiple times
5094 parag->lineStartList().insert( index, ls ); 5100 parag->lineStartList().insert( index, ls );
5095 return; 5101 return;
5096 } 5102 }
5097 QMap<int, QTextLineStart*>::Iterator it; 5103 QMap<int, QTextLineStart*>::Iterator it;
5098 if ( ( it = parag->lineStartList().find( index ) ) == parag->lineStartList().end() ) { 5104 if ( ( it = parag->lineStartList().find( index ) ) == parag->lineStartList().end() ) {
5099 parag->lineStartList().insert( index, ls ); 5105 parag->lineStartList().insert( index, ls );
5100 } else { 5106 } else {
5101 delete *it; 5107 delete *it;
5102 parag->lineStartList().remove( it ); 5108 parag->lineStartList().remove( it );
5103 parag->lineStartList().insert( index, ls ); 5109 parag->lineStartList().insert( index, ls );
5104 } 5110 }
5105} 5111}
5106 5112
5107 5113
5108/* Standard pagebreak algorithm using QTextFlow::adjustFlow. Returns 5114/* Standard pagebreak algorithm using QTextFlow::adjustFlow. Returns
5109 the shift of the paragraphs bottom line. 5115 the shift of the paragraphs bottom line.
5110 */ 5116 */
5111int QTextFormatter::formatVertically( QTextDocument* doc, QTextParagraph* parag ) 5117int QTextFormatter::formatVertically( QTextDocument* doc, QTextParagraph* parag )
5112{ 5118{
5113 int oldHeight = parag->rect().height(); 5119 int oldHeight = parag->rect().height();
5114 QMap<int, QTextLineStart*>& lineStarts = parag->lineStartList(); 5120 QMap<int, QTextLineStart*>& lineStarts = parag->lineStartList();
5115 QMap<int, QTextLineStart*>::Iterator it = lineStarts.begin(); 5121 QMap<int, QTextLineStart*>::Iterator it = lineStarts.begin();
5116 int h = parag->prev() ? QMAX(parag->prev()->bottomMargin(),parag->topMargin() ) / 2: 0; 5122 int h = parag->prev() ? QMAX(parag->prev()->bottomMargin(),parag->topMargin() ) / 2: 0;
5117 for ( ; it != lineStarts.end() ; ++it ) { 5123 for ( ; it != lineStarts.end() ; ++it ) {
5118 QTextLineStart * ls = it.data(); 5124 QTextLineStart * ls = it.data();
5119 ls->y = h; 5125 ls->y = h;
5120 QTextStringChar *c = &parag->string()->at(it.key()); 5126 QTextStringChar *c = &parag->string()->at(it.key());
5121 if ( c && c->customItem() && c->customItem()->ownLine() ) { 5127 if ( c && c->customItem() && c->customItem()->ownLine() ) {
5122 int h = c->customItem()->height; 5128 int h = c->customItem()->height;
5123 c->customItem()->pageBreak( parag->rect().y() + ls->y + ls->baseLine - h, doc->flow() ); 5129 c->customItem()->pageBreak( parag->rect().y() + ls->y + ls->baseLine - h, doc->flow() );
5124 int delta = c->customItem()->height - h; 5130 int delta = c->customItem()->height - h;
5125 ls->h += delta; 5131 ls->h += delta;
5126 if ( delta ) 5132 if ( delta )
5127 parag->setMovedDown( TRUE ); 5133 parag->setMovedDown( TRUE );
5128 } else { 5134 } else {
5129 int shift = doc->flow()->adjustFlow( parag->rect().y() + ls->y, ls->w, ls->h ); 5135 int shift = doc->flow()->adjustFlow( parag->rect().y() + ls->y, ls->w, ls->h );
5130 ls->y += shift; 5136 ls->y += shift;
5131 if ( shift ) 5137 if ( shift )
5132 parag->setMovedDown( TRUE ); 5138 parag->setMovedDown( TRUE );
5133 } 5139 }
5134 h = ls->y + ls->h; 5140 h = ls->y + ls->h;
5135 } 5141 }
5136 int m = parag->bottomMargin(); 5142 int m = parag->bottomMargin();
5137 if ( !parag->next() ) 5143 if ( !parag->next() )
5138 m = 0; 5144 m = 0;
5139 else 5145 else
5140 m = QMAX(m, parag->next()->topMargin() ) / 2; 5146 m = QMAX(m, parag->next()->topMargin() ) / 2;
5141 h += m; 5147 h += m;
5142 parag->setHeight( h ); 5148 parag->setHeight( h );
5143 return h - oldHeight; 5149 return h - oldHeight;
5144} 5150}
5145 5151
5146// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5152// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5147 5153
5148QTextFormatterBreakInWords::QTextFormatterBreakInWords() 5154QTextFormatterBreakInWords::QTextFormatterBreakInWords()
5149{ 5155{
5150} 5156}
5151 5157
5152#define SPACE(s) doc?(s>0?s:0):s 5158#define SPACE(s) doc?(s>0?s:0):s
5153 5159
5154int QTextFormatterBreakInWords::format( QTextDocument *doc,QTextParagraph *parag, 5160int QTextFormatterBreakInWords::format( QTextDocument *doc,QTextParagraph *parag,
5155 int start, const QMap<int, QTextLineStart*> & ) 5161 int start, const QMap<int, QTextLineStart*> & )
5156{ 5162{
5157 QTextStringChar *c = 0; 5163 QTextStringChar *c = 0;
5158 QTextStringChar *firstChar = 0; 5164 QTextStringChar *firstChar = 0;
5159 int left = doc ? parag->leftMargin() + doc->leftMargin() : 0; 5165 int left = doc ? parag->leftMargin() + doc->leftMargin() : 0;
5160 int x = left + ( doc ? parag->firstLineMargin() : 0 ); 5166 int x = left + ( doc ? parag->firstLineMargin() : 0 );
5161 int dw = parag->documentVisibleWidth() - ( doc ? doc->rightMargin() : 0 ); 5167 int dw = parag->documentVisibleWidth() - ( doc ? doc->rightMargin() : 0 );
5162 int y = parag->prev() ? QMAX(parag->prev()->bottomMargin(),parag->topMargin()) / 2: 0; 5168 int y = parag->prev() ? QMAX(parag->prev()->bottomMargin(),parag->topMargin()) / 2: 0;
5163 int h = y; 5169 int h = y;
5164 int len = parag->length(); 5170 int len = parag->length();
5165 if ( doc ) 5171 if ( doc )
5166 x = doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), x, 4 ); 5172 x = doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), x, 4 );
5167 int rm = parag->rightMargin(); 5173 int rm = parag->rightMargin();
5168 int w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 ); 5174 int w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 );
5169 bool fullWidth = TRUE; 5175 bool fullWidth = TRUE;
5170 int minw = 0; 5176 int minw = 0;
5171 int wused = 0; 5177 int wused = 0;
5172 bool wrapEnabled = isWrapEnabled( parag ); 5178 bool wrapEnabled = isWrapEnabled( parag );
5173 5179
5174 start = 0; //######### what is the point with start?! (Matthias) 5180 start = 0; //######### what is the point with start?! (Matthias)
5175 if ( start == 0 ) 5181 if ( start == 0 )
5176 c = &parag->string()->at( 0 ); 5182 c = &parag->string()->at( 0 );
5177 5183
5178 int i = start; 5184 int i = start;
5179 QTextLineStart *lineStart = new QTextLineStart( y, y, 0 ); 5185 QTextLineStart *lineStart = new QTextLineStart( y, y, 0 );
5180 insertLineStart( parag, 0, lineStart ); 5186 insertLineStart( parag, 0, lineStart );
5181 5187
5182 QPainter *painter = QTextFormat::painter(); 5188 QPainter *painter = QTextFormat::painter();
5183 5189
5184 int col = 0; 5190 int col = 0;
5185 int ww = 0; 5191 int ww = 0;
5186 QChar lastChr; 5192 QChar lastChr;
5187 for ( ; i < len; ++i, ++col ) { 5193 for ( ; i < len; ++i, ++col ) {
5188 if ( c ) 5194 if ( c )
5189 lastChr = c->c; 5195 lastChr = c->c;
5190 c = &parag->string()->at( i ); 5196 c = &parag->string()->at( i );
5191 c->rightToLeft = FALSE; 5197 c->rightToLeft = FALSE;
5192 // ### the lines below should not be needed 5198 // ### the lines below should not be needed
5193 if ( painter ) 5199 if ( painter )
5194 c->format()->setPainter( painter ); 5200 c->format()->setPainter( painter );
5195 if ( i > 0 ) { 5201 if ( i > 0 ) {
5196 c->lineStart = 0; 5202 c->lineStart = 0;
5197 } else { 5203 } else {
5198 c->lineStart = 1; 5204 c->lineStart = 1;
5199 firstChar = c; 5205 firstChar = c;
5200 } 5206 }
5201 if ( c->c.unicode() >= 32 || c->isCustom() ) { 5207 if ( c->c.unicode() >= 32 || c->isCustom() ) {
5202 ww = parag->string()->width( i ); 5208 ww = parag->string()->width( i );
5203 } else if ( c->c == '\t' ) { 5209 } else if ( c->c == '\t' ) {
5204 int nx = parag->nextTab( i, x - left ) + left; 5210 int nx = parag->nextTab( i, x - left ) + left;
5205 if ( nx < x ) 5211 if ( nx < x )
5206 ww = w - x; 5212 ww = w - x;
5207 else 5213 else
5208 ww = nx - x; 5214 ww = nx - x;
5209 } else { 5215 } else {
5210 ww = c->format()->width( ' ' ); 5216 ww = c->format()->width( ' ' );
5211 } 5217 }
5212 5218
5213 if ( c->isCustom() && c->customItem()->ownLine() ) { 5219 if ( c->isCustom() && c->customItem()->ownLine() ) {
5214 x = doc ? doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left; 5220 x = doc ? doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left;
5215 w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 ); 5221 w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 );
5216 c->customItem()->resize( w - x ); 5222 c->customItem()->resize( w - x );
5217 w = dw; 5223 w = dw;
5218 y += h; 5224 y += h;
5219 h = c->height(); 5225 h = c->height();
5220 lineStart = new QTextLineStart( y, h, h ); 5226 lineStart = new QTextLineStart( y, h, h );
5221 insertLineStart( parag, i, lineStart ); 5227 insertLineStart( parag, i, lineStart );
5222 c->lineStart = 1; 5228 c->lineStart = 1;
5223 firstChar = c; 5229 firstChar = c;
5224 x = 0xffffff; 5230 x = 0xffffff;
5225 continue; 5231 continue;
5226 } 5232 }
5227 5233
5228 if ( wrapEnabled && 5234 if ( wrapEnabled &&
5229 ( wrapAtColumn() == -1 && x + ww > w || 5235 ( wrapAtColumn() == -1 && x + ww > w ||
5230 wrapAtColumn() != -1 && col >= wrapAtColumn() ) ) { 5236 wrapAtColumn() != -1 && col >= wrapAtColumn() ) ) {
5231 x = doc ? parag->document()->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left; 5237 x = doc ? parag->document()->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left;
5232 w = dw; 5238 w = dw;
5233 y += h; 5239 y += h;
5234 h = c->height(); 5240 h = c->height();
5235 lineStart = formatLine( parag, parag->string(), lineStart, firstChar, SPACE(c-1) ); 5241 lineStart = formatLine( parag, parag->string(), lineStart, firstChar, SPACE(c-1) );
5236 lineStart->y = y; 5242 lineStart->y = y;
5237 insertLineStart( parag, i, lineStart ); 5243 insertLineStart( parag, i, lineStart );
5238 lineStart->baseLine = c->ascent(); 5244 lineStart->baseLine = c->ascent();
5239 lineStart->h = c->height(); 5245 lineStart->h = c->height();
5240 c->lineStart = 1; 5246 c->lineStart = 1;
5241 firstChar = c; 5247 firstChar = c;
5242 col = 0; 5248 col = 0;
5243 if ( wrapAtColumn() != -1 ) 5249 if ( wrapAtColumn() != -1 )
5244 minw = QMAX( minw, w ); 5250 minw = QMAX( minw, w );
5245 } else if ( lineStart ) { 5251 } else if ( lineStart ) {
5246 lineStart->baseLine = QMAX( lineStart->baseLine, c->ascent() ); 5252 lineStart->baseLine = QMAX( lineStart->baseLine, c->ascent() );
5247 h = QMAX( h, c->height() ); 5253 h = QMAX( h, c->height() );
5248 lineStart->h = h; 5254 lineStart->h = h;
5249 } 5255 }
5250 5256
5251 c->x = x; 5257 c->x = x;
5252 x += ww; 5258 x += ww;
5253 wused = QMAX( wused, x ); 5259 wused = QMAX( wused, x );
5254 } 5260 }
5255 5261
5256 int m = parag->bottomMargin(); 5262 int m = parag->bottomMargin();
5257 if ( !parag->next() ) 5263 if ( !parag->next() )
5258 m = 0; 5264 m = 0;
5259 else 5265 else
5260 m = QMAX(m, parag->next()->topMargin() ) / 2; 5266 m = QMAX(m, parag->next()->topMargin() ) / 2;
5261 parag->setFullWidth( fullWidth ); 5267 parag->setFullWidth( fullWidth );
5262 y += h + m; 5268 y += h + m;
5263 if ( doc ) 5269 if ( doc )
5264 minw += doc->rightMargin(); 5270 minw += doc->rightMargin();
5265 if ( !wrapEnabled ) 5271 if ( !wrapEnabled )
5266 minw = QMAX(minw, wused); 5272 minw = QMAX(minw, wused);
5267 5273
5268 thisminw = minw; 5274 thisminw = minw;
5269 thiswused = wused; 5275 thiswused = wused;
5270 return y; 5276 return y;
5271} 5277}
5272 5278
5273// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5279// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5274 5280
5275QTextFormatterBreakWords::QTextFormatterBreakWords() 5281QTextFormatterBreakWords::QTextFormatterBreakWords()
5276{ 5282{
5277} 5283}
5278 5284
5279#define DO_FLOW( lineStart ) do{ if ( doc && doc->isPageBreakEnabled() ) { \ 5285#define DO_FLOW( lineStart ) do{ if ( doc && doc->isPageBreakEnabled() ) { \
5280 int yflow = lineStart->y + parag->rect().y();\ 5286 int yflow = lineStart->y + parag->rect().y();\
5281 int shift = doc->flow()->adjustFlow( yflow, dw, lineStart->h ); \ 5287 int shift = doc->flow()->adjustFlow( yflow, dw, lineStart->h ); \
5282 lineStart->y += shift;\ 5288 lineStart->y += shift;\
5283 y += shift;\ 5289 y += shift;\
5284 }}while(FALSE) 5290 }}while(FALSE)
5285 5291
5286int QTextFormatterBreakWords::format( QTextDocument *doc, QTextParagraph *parag, 5292int QTextFormatterBreakWords::format( QTextDocument *doc, QTextParagraph *parag,
5287 int start, const QMap<int, QTextLineStart*> & ) 5293 int start, const QMap<int, QTextLineStart*> & )
5288{ 5294{
5289 QTextStringChar *c = 0; 5295 QTextStringChar *c = 0;
5290 QTextStringChar *firstChar = 0; 5296 QTextStringChar *firstChar = 0;
5291 QTextString *string = parag->string(); 5297 QTextString *string = parag->string();
5292 int left = doc ? parag->leftMargin() + doc->leftMargin() : 0; 5298 int left = doc ? parag->leftMargin() + doc->leftMargin() : 0;
5293 int x = left + ( doc ? parag->firstLineMargin() : 0 ); 5299 int x = left + ( doc ? parag->firstLineMargin() : 0 );
5294 int y = parag->prev() ? QMAX(parag->prev()->bottomMargin(),parag->topMargin()) / 2: 0; 5300 int y = parag->prev() ? QMAX(parag->prev()->bottomMargin(),parag->topMargin()) / 2: 0;
5295 int h = y; 5301 int h = y;
5296 int len = parag->length(); 5302 int len = parag->length();
5297 if ( doc ) 5303 if ( doc )
5298 x = doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), x, 0 ); 5304 x = doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), x, 0 );
5299 int dw = parag->documentVisibleWidth() - ( doc ? ( left != x ? 0 : doc->rightMargin() ) : 0 ); 5305 int dw = parag->documentVisibleWidth() - ( doc ? ( left != x ? 0 : doc->rightMargin() ) : 0 );
5300 5306
5301 int curLeft = x; 5307 int curLeft = x;
5302 int rm = parag->rightMargin(); 5308 int rm = parag->rightMargin();
5303 int rdiff = doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 0 ) : 0; 5309 int rdiff = doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 0 ) : 0;
5304 int w = dw - rdiff; 5310 int w = dw - rdiff;
5305 bool fullWidth = TRUE; 5311 bool fullWidth = TRUE;
5306 int marg = left + rdiff; 5312 int marg = left + rdiff;
5307 int minw = 0; 5313 int minw = 0;
5308 int wused = 0; 5314 int wused = 0;
5309 int tminw = marg; 5315 int tminw = marg;
5310 int linespacing = doc ? parag->lineSpacing() : 0; 5316 int linespacing = doc ? parag->lineSpacing() : 0;
5311 bool wrapEnabled = isWrapEnabled( parag ); 5317 bool wrapEnabled = isWrapEnabled( parag );
5312 5318
5313 start = 0; 5319 start = 0;
5314 if ( start == 0 ) 5320 if ( start == 0 )
5315 c = &parag->string()->at( 0 ); 5321 c = &parag->string()->at( 0 );
5316 5322
5317 int i = start; 5323 int i = start;
5318 QTextLineStart *lineStart = new QTextLineStart( y, y, 0 ); 5324 QTextLineStart *lineStart = new QTextLineStart( y, y, 0 );
5319 insertLineStart( parag, 0, lineStart ); 5325 insertLineStart( parag, 0, lineStart );
5320 int lastBreak = -1; 5326 int lastBreak = -1;
5321 int tmpBaseLine = 0, tmph = 0; 5327 int tmpBaseLine = 0, tmph = 0;
5322 bool lastWasNonInlineCustom = FALSE; 5328 bool lastWasNonInlineCustom = FALSE;
5323 5329
5324 int align = parag->alignment(); 5330 int align = parag->alignment();
5325 if ( align == Qt3::AlignAuto && doc && doc->alignment() != Qt3::AlignAuto ) 5331 if ( align == Qt3::AlignAuto && doc && doc->alignment() != Qt3::AlignAuto )
5326 align = doc->alignment(); 5332 align = doc->alignment();
5327 5333
5328 align &= Qt3::AlignHorizontal_Mask; 5334 align &= Qt3::AlignHorizontal_Mask;
5329 5335
5330 QPainter *painter = QTextFormat::painter(); 5336 QPainter *painter = QTextFormat::painter();
5331 int col = 0; 5337 int col = 0;
5332 int ww = 0; 5338 int ww = 0;
5333 QChar lastChr; 5339 QChar lastChr;
5334 for ( ; i < len; ++i, ++col ) { 5340 for ( ; i < len; ++i, ++col ) {
5335 if ( c ) 5341 if ( c )
5336 lastChr = c->c; 5342 lastChr = c->c;
5337 // ### next line should not be needed 5343 // ### next line should not be needed
5338 if ( painter ) 5344 if ( painter )
5339 c->format()->setPainter( painter ); 5345 c->format()->setPainter( painter );
5340 c = &string->at( i ); 5346 c = &string->at( i );
5341 c->rightToLeft = FALSE; 5347 c->rightToLeft = FALSE;
5342 if ( i > 0 && (x > curLeft || ww == 0) || lastWasNonInlineCustom ) { 5348 if ( i > 0 && (x > curLeft || ww == 0) || lastWasNonInlineCustom ) {
5343 c->lineStart = 0; 5349 c->lineStart = 0;
5344 } else { 5350 } else {
5345 c->lineStart = 1; 5351 c->lineStart = 1;
5346 firstChar = c; 5352 firstChar = c;
5347 } 5353 }
5348 5354
5349 if ( c->isCustom() && c->customItem()->placement() != QTextCustomItem::PlaceInline ) 5355 if ( c->isCustom() && c->customItem()->placement() != QTextCustomItem::PlaceInline )
5350 lastWasNonInlineCustom = TRUE; 5356 lastWasNonInlineCustom = TRUE;
5351 else 5357 else
5352 lastWasNonInlineCustom = FALSE; 5358 lastWasNonInlineCustom = FALSE;
5353 5359
5354 if ( c->c.unicode() >= 32 || c->isCustom() ) { 5360 if ( c->c.unicode() >= 32 || c->isCustom() ) {
5355 ww = string->width( i ); 5361 ww = string->width( i );
5356 } else if ( c->c == '\t' ) { 5362 } else if ( c->c == '\t' ) {
5357 int nx = parag->nextTab( i, x - left ) + left; 5363 int nx = parag->nextTab( i, x - left ) + left;
5358 if ( nx < x ) 5364 if ( nx < x )
5359 ww = w - x; 5365 ww = w - x;
5360 else 5366 else
5361 ww = nx - x; 5367 ww = nx - x;
5362 } else { 5368 } else {
5363 ww = c->format()->width( ' ' ); 5369 ww = c->format()->width( ' ' );
5364 } 5370 }
5365 5371
5366 // last character ("invisible" space) has no width 5372 // last character ("invisible" space) has no width
5367 if ( i == len - 1 ) 5373 if ( i == len - 1 )
5368 ww = 0; 5374 ww = 0;
5369 5375
5370 QTextCustomItem* ci = c->customItem(); 5376 QTextCustomItem* ci = c->customItem();
5371 if ( c->isCustom() && ci->ownLine() ) { 5377 if ( c->isCustom() && ci->ownLine() ) {
5372 x = doc ? doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left; 5378 x = doc ? doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left;
5373 w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 ); 5379 w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 );
5374 QTextLineStart *lineStart2 = formatLine( parag, string, lineStart, firstChar, c-1, align, SPACE(w - x) ); 5380 QTextLineStart *lineStart2 = formatLine( parag, string, lineStart, firstChar, c-1, align, SPACE(w - x) );
5375 ci->resize( w - x); 5381 ci->resize( w - x);
5376 if ( ci->width < w - x ) { 5382 if ( ci->width < w - x ) {
5377 if ( align & Qt::AlignHCenter ) 5383 if ( align & Qt::AlignHCenter )
5378 x = ( w - ci->width ) / 2; 5384 x = ( w - ci->width ) / 2;
5379 else if ( align & Qt::AlignRight ) { 5385 else if ( align & Qt::AlignRight ) {
5380 x = w - ci->width; 5386 x = w - ci->width;
5381 } 5387 }
5382 } 5388 }
5383 c->x = x; 5389 c->x = x;
5384 curLeft = x; 5390 curLeft = x;
5385 if ( i == 0 || !isBreakable( string, i - 1 ) || string->at( i - 1 ).lineStart == 0 ) { 5391 if ( i == 0 || !isBreakable( string, i - 1 ) || string->at( i - 1 ).lineStart == 0 ) {
5386 y += QMAX( h, QMAX( tmph, linespacing ) ); 5392 y += QMAX( h, QMAX( tmph, linespacing ) );
5387 tmph = c->height(); 5393 tmph = c->height();
5388 h = tmph; 5394 h = tmph;
5389 lineStart = lineStart2; 5395 lineStart = lineStart2;
5390 lineStart->y = y; 5396 lineStart->y = y;
5391 insertLineStart( parag, i, lineStart ); 5397 insertLineStart( parag, i, lineStart );
5392 c->lineStart = 1; 5398 c->lineStart = 1;
5393 firstChar = c; 5399 firstChar = c;
5394 } else { 5400 } else {
5395 tmph = c->height(); 5401 tmph = c->height();
5396 h = tmph; 5402 h = tmph;
5397 delete lineStart2; 5403 delete lineStart2;
5398 } 5404 }
5399 lineStart->h = h; 5405 lineStart->h = h;
5400 lineStart->baseLine = h; 5406 lineStart->baseLine = h;
5401 tmpBaseLine = lineStart->baseLine; 5407 tmpBaseLine = lineStart->baseLine;
5402 lastBreak = -2; 5408 lastBreak = -2;
5403 x = 0xffffff; 5409 x = 0xffffff;
5404 minw = QMAX( minw, tminw ); 5410 minw = QMAX( minw, tminw );
5405 5411
5406 int tw = ci->minimumWidth() + ( doc ? doc->leftMargin() : 0 ); 5412 int tw = ci->minimumWidth() + ( doc ? doc->leftMargin() : 0 );
5407 if ( tw < QWIDGETSIZE_MAX ) 5413 if ( tw < QWIDGETSIZE_MAX )
5408 tminw = tw; 5414 tminw = tw;
5409 else 5415 else
5410 tminw = marg; 5416 tminw = marg;
5411 wused = QMAX( wused, ci->width ); 5417 wused = QMAX( wused, ci->width );
5412 continue; 5418 continue;
5413 } else if ( c->isCustom() && ci->placement() != QTextCustomItem::PlaceInline ) { 5419 } else if ( c->isCustom() && ci->placement() != QTextCustomItem::PlaceInline ) {
5414 int tw = ci->minimumWidth(); 5420 int tw = ci->minimumWidth();
5415 if ( tw < QWIDGETSIZE_MAX ) 5421 if ( tw < QWIDGETSIZE_MAX )
5416 minw = QMAX( minw, tw ); 5422 minw = QMAX( minw, tw );
5417 } 5423 }
5418 5424
5419 bool lastWasOwnLineCustomItem = lastBreak == -2; 5425 bool lastWasOwnLineCustomItem = lastBreak == -2;
5420 bool hadBreakableChar = lastBreak != -1; 5426 bool hadBreakableChar = lastBreak != -1;
5421 bool lastWasHardBreak = lastChr == QChar_linesep; 5427 bool lastWasHardBreak = lastChr == QChar_linesep;
5422 5428
5423 // we break if 5429 // we break if
5424 // 1. the last character was a hard break (QChar_linesep) or 5430 // 1. the last character was a hard break (QChar_linesep) or
5425 // 2. the last charater was a own-line custom item (eg. table or ruler) or 5431 // 2. the last charater was a own-line custom item (eg. table or ruler) or
5426 // 3. wrapping was enabled, it was not a space and following 5432 // 3. wrapping was enabled, it was not a space and following
5427 // condition is true: We either had a breakable character 5433 // condition is true: We either had a breakable character
5428 // previously or we ar allowed to break in words and - either 5434 // previously or we ar allowed to break in words and - either
5429 // we break at w pixels and the current char would exceed that 5435 // we break at w pixels and the current char would exceed that
5430 // or - we break at a column and the current character would 5436 // or - we break at a column and the current character would
5431 // exceed that. 5437 // exceed that.
5432 if ( lastWasHardBreak || lastWasOwnLineCustomItem || 5438 if ( lastWasHardBreak || lastWasOwnLineCustomItem ||
5433 ( wrapEnabled && 5439 ( wrapEnabled &&
5434 ( (!c->c.isSpace() && (hadBreakableChar || allowBreakInWords()) && 5440 ( (!c->c.isSpace() && (hadBreakableChar || allowBreakInWords()) &&
5435 ( (wrapAtColumn() == -1 && x + ww > w) || 5441 ( (wrapAtColumn() == -1 && x + ww > w) ||
5436 (wrapAtColumn() != -1 && col >= wrapAtColumn()) ) ) ) 5442 (wrapAtColumn() != -1 && col >= wrapAtColumn()) ) ) )
5437 ) 5443 )
5438 ) { 5444 ) {
5439 if ( wrapAtColumn() != -1 ) 5445 if ( wrapAtColumn() != -1 )
5440 minw = QMAX( minw, x + ww ); 5446 minw = QMAX( minw, x + ww );
5441 // if a break was forced (no breakable char, hard break or own line custom item), break immediately.... 5447 // if a break was forced (no breakable char, hard break or own line custom item), break immediately....
5442 if ( !hadBreakableChar || lastWasHardBreak || lastWasOwnLineCustomItem ) { 5448 if ( !hadBreakableChar || lastWasHardBreak || lastWasOwnLineCustomItem ) {
5443 if ( lineStart ) { 5449 if ( lineStart ) {
5444 lineStart->baseLine = QMAX( lineStart->baseLine, tmpBaseLine ); 5450 lineStart->baseLine = QMAX( lineStart->baseLine, tmpBaseLine );
5445 h = QMAX( h, tmph ); 5451 h = QMAX( h, tmph );
5446 lineStart->h = h; 5452 lineStart->h = h;
5447 DO_FLOW( lineStart ); 5453 DO_FLOW( lineStart );
5448 } 5454 }
5449 lineStart = formatLine( parag, string, lineStart, firstChar, c-1, align, SPACE(w - x) ); 5455 lineStart = formatLine( parag, string, lineStart, firstChar, c-1, align, SPACE(w - x) );
5450 x = doc ? doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left; 5456 x = doc ? doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left;
5451 w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 ); 5457 w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 );
5452 if ( !doc && c->c == '\t' ) { // qt_format_text tab handling 5458 if ( !doc && c->c == '\t' ) { // qt_format_text tab handling
5453 int nx = parag->nextTab( i, x - left ) + left; 5459 int nx = parag->nextTab( i, x - left ) + left;
5454 if ( nx < x ) 5460 if ( nx < x )
5455 ww = w - x; 5461 ww = w - x;
5456 else 5462 else
5457 ww = nx - x; 5463 ww = nx - x;
5458 } 5464 }
5459 curLeft = x; 5465 curLeft = x;
5460 y += QMAX( h, linespacing ); 5466 y += QMAX( h, linespacing );
5461 tmph = c->height(); 5467 tmph = c->height();
5462 h = 0; 5468 h = 0;
5463 lineStart->y = y; 5469 lineStart->y = y;
5464 insertLineStart( parag, i, lineStart ); 5470 insertLineStart( parag, i, lineStart );
5465 lineStart->baseLine = c->ascent(); 5471 lineStart->baseLine = c->ascent();
5466 lineStart->h = c->height(); 5472 lineStart->h = c->height();
5467 c->lineStart = 1; 5473 c->lineStart = 1;
5468 firstChar = c; 5474 firstChar = c;
5469 tmpBaseLine = lineStart->baseLine; 5475 tmpBaseLine = lineStart->baseLine;
5470 lastBreak = -1; 5476 lastBreak = -1;
5471 col = 0; 5477 col = 0;
5472 } else { // ... otherwise if we had a breakable char, break there 5478 } else { // ... otherwise if we had a breakable char, break there
5473 DO_FLOW( lineStart ); 5479 DO_FLOW( lineStart );
5474 i = lastBreak; 5480 i = lastBreak;
5475 lineStart = formatLine( parag, string, lineStart, firstChar, parag->at( lastBreak ),align, SPACE(w - string->at( i ).x) ); 5481 lineStart = formatLine( parag, string, lineStart, firstChar, parag->at( lastBreak ),align, SPACE(w - string->at( i ).x) );
5476 x = doc ? doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left; 5482 x = doc ? doc->flow()->adjustLMargin( y + parag->rect().y(), parag->rect().height(), left, 4 ) : left;
5477 w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 ); 5483 w = dw - ( doc ? doc->flow()->adjustRMargin( y + parag->rect().y(), parag->rect().height(), rm, 4 ) : 0 );
5478 if ( !doc && c->c == '\t' ) { // qt_format_text tab handling 5484 if ( !doc && c->c == '\t' ) { // qt_format_text tab handling
5479 int nx = parag->nextTab( i, x - left ) + left; 5485 int nx = parag->nextTab( i, x - left ) + left;
5480 if ( nx < x ) 5486 if ( nx < x )
5481 ww = w - x; 5487 ww = w - x;
5482 else 5488 else
5483 ww = nx - x; 5489 ww = nx - x;
5484 } 5490 }
5485 curLeft = x; 5491 curLeft = x;
5486 y += QMAX( h, linespacing ); 5492 y += QMAX( h, linespacing );
5487 tmph = c->height(); 5493 tmph = c->height();
5488 h = tmph; 5494 h = tmph;
5489 lineStart->y = y; 5495 lineStart->y = y;
5490 insertLineStart( parag, i + 1, lineStart ); 5496 insertLineStart( parag, i + 1, lineStart );
5491 lineStart->baseLine = c->ascent(); 5497 lineStart->baseLine = c->ascent();
5492 lineStart->h = c->height(); 5498 lineStart->h = c->height();
5493 c->lineStart = 1; 5499 c->lineStart = 1;
5494 firstChar = c; 5500 firstChar = c;
5495 tmpBaseLine = lineStart->baseLine; 5501 tmpBaseLine = lineStart->baseLine;
5496 lastBreak = -1; 5502 lastBreak = -1;
5497 col = 0; 5503 col = 0;
5498 tminw = marg; 5504 tminw = marg;
5499 continue; 5505 continue;
5500 } 5506 }
5501 } else if ( lineStart && isBreakable( string, i ) ) { 5507 } else if ( lineStart && isBreakable( string, i ) ) {
5502 if ( len <= 2 || i < len - 1 ) { 5508 if ( len <= 2 || i < len - 1 ) {
5503 tmpBaseLine = QMAX( tmpBaseLine, c->ascent() ); 5509 tmpBaseLine = QMAX( tmpBaseLine, c->ascent() );
5504 tmph = QMAX( tmph, c->height() ); 5510 tmph = QMAX( tmph, c->height() );
5505 } 5511 }
5506 minw = QMAX( minw, tminw ); 5512 minw = QMAX( minw, tminw );
5507 tminw = marg + ww; 5513 tminw = marg + ww;
5508 lineStart->baseLine = QMAX( lineStart->baseLine, tmpBaseLine ); 5514 lineStart->baseLine = QMAX( lineStart->baseLine, tmpBaseLine );
5509 h = QMAX( h, tmph ); 5515 h = QMAX( h, tmph );
5510 lineStart->h = h; 5516 lineStart->h = h;
5511 if ( i < len - 2 || c->c != ' ' ) 5517 if ( i < len - 2 || c->c != ' ' )
5512 lastBreak = i; 5518 lastBreak = i;
5513 } else { 5519 } else {
5514 tminw += ww; 5520 tminw += ww;
5515 int belowBaseLine = QMAX( tmph - tmpBaseLine, c->height()- c->ascent() ); 5521 int belowBaseLine = QMAX( tmph - tmpBaseLine, c->height()- c->ascent() );
5516 tmpBaseLine = QMAX( tmpBaseLine, c->ascent() ); 5522 tmpBaseLine = QMAX( tmpBaseLine, c->ascent() );
5517 tmph = tmpBaseLine + belowBaseLine; 5523 tmph = tmpBaseLine + belowBaseLine;
5518 } 5524 }
5519 5525
5520 c->x = x; 5526 c->x = x;
5521 x += ww; 5527 x += ww;
5522 wused = QMAX( wused, x ); 5528 wused = QMAX( wused, x );
5523 } 5529 }
5524 5530
5525 // ### hack. The last char in the paragraph is always invisible, 5531 // ### hack. The last char in the paragraph is always invisible,
5526 // ### and somehow sometimes has a wrong format. It changes 5532 // ### and somehow sometimes has a wrong format. It changes
5527 // ### between // layouting and printing. This corrects some 5533 // ### between // layouting and printing. This corrects some
5528 // ### layouting errors in BiDi mode due to this. 5534 // ### layouting errors in BiDi mode due to this.
5529 if ( len > 1 && !c->isAnchor() ) { 5535 if ( len > 1 && !c->isAnchor() ) {
5530 c->format()->removeRef(); 5536 c->format()->removeRef();
5531 c->setFormat( string->at( len - 2 ).format() ); 5537 c->setFormat( string->at( len - 2 ).format() );
5532 c->format()->addRef(); 5538 c->format()->addRef();
5533 } 5539 }
5534 5540
5535 if ( lineStart ) { 5541 if ( lineStart ) {
5536 lineStart->baseLine = QMAX( lineStart->baseLine, tmpBaseLine ); 5542 lineStart->baseLine = QMAX( lineStart->baseLine, tmpBaseLine );
5537 h = QMAX( h, tmph ); 5543 h = QMAX( h, tmph );
5538 lineStart->h = h; 5544 lineStart->h = h;
5539 // last line in a paragraph is not justified 5545 // last line in a paragraph is not justified
5540 if ( align == Qt3::AlignJustify || lastChr == QChar_linesep ) 5546 if ( align == Qt3::AlignJustify || lastChr == QChar_linesep )
5541 align = Qt3::AlignAuto; 5547 align = Qt3::AlignAuto;
5542 DO_FLOW( lineStart ); 5548 DO_FLOW( lineStart );
5543 lineStart = formatLine( parag, string, lineStart, firstChar, c, align, SPACE(w - x) ); 5549 lineStart = formatLine( parag, string, lineStart, firstChar, c, align, SPACE(w - x) );
5544 delete lineStart; 5550 delete lineStart;
5545 } 5551 }
5546 5552
5547 minw = QMAX( minw, tminw ); 5553 minw = QMAX( minw, tminw );
5548 if ( doc ) 5554 if ( doc )
5549 minw += doc->rightMargin(); 5555 minw += doc->rightMargin();
5550 5556
5551 int m = parag->bottomMargin(); 5557 int m = parag->bottomMargin();
5552 if ( !parag->next() ) 5558 if ( !parag->next() )
5553 m = 0; 5559 m = 0;
5554 else 5560 else
5555 m = QMAX(m, parag->next()->topMargin() ) / 2; 5561 m = QMAX(m, parag->next()->topMargin() ) / 2;
5556 parag->setFullWidth( fullWidth ); 5562 parag->setFullWidth( fullWidth );
5557 y += QMAX( h, linespacing ) + m; 5563 y += QMAX( h, linespacing ) + m;
5558 5564
5559 wused += rm; 5565 wused += rm;
5560 if ( !wrapEnabled || wrapAtColumn() != -1 ) 5566 if ( !wrapEnabled || wrapAtColumn() != -1 )
5561 minw = QMAX(minw, wused); 5567 minw = QMAX(minw, wused);
5562 5568
5563 // This is the case where we are breaking wherever we darn well please 5569 // This is the case where we are breaking wherever we darn well please
5564 // in cases like that, the minw should not be the length of the entire 5570 // in cases like that, the minw should not be the length of the entire
5565 // word, because we necessarily want to show the word on the whole line. 5571 // word, because we necessarily want to show the word on the whole line.
5566 // example: word wrap in iconview 5572 // example: word wrap in iconview
5567 if ( allowBreakInWords() && minw > wused ) 5573 if ( allowBreakInWords() && minw > wused )
5568 minw = wused; 5574 minw = wused;
5569 5575
5570 thisminw = minw; 5576 thisminw = minw;
5571 thiswused = wused; 5577 thiswused = wused;
5572 return y; 5578 return y;
5573} 5579}
5574 5580
5575// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5581// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5576 5582
5577QTextIndent::QTextIndent() 5583QTextIndent::QTextIndent()
5578{ 5584{
5579} 5585}
5580 5586
5581// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5587// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5582 5588
5583QTextFormatCollection::QTextFormatCollection() 5589QTextFormatCollection::QTextFormatCollection()
5584 : cKey( 307 ) 5590 : cKey( 307 )
5585{ 5591{
5586 defFormat = new QTextFormat( QApplication::font(), 5592 defFormat = new QTextFormat( QApplication::font(),
5587 QApplication::palette().color( QPalette::Active, QColorGroup::Text ) ); 5593 QApplication::palette().color( QPalette::Active, QColorGroup::Text ) );
5588 lastFormat = cres = 0; 5594 lastFormat = cres = 0;
5589 cflags = -1; 5595 cflags = -1;
5590 cKey.setAutoDelete( TRUE ); 5596 cKey.setAutoDelete( TRUE );
5591 cachedFormat = 0; 5597 cachedFormat = 0;
5592} 5598}
5593 5599
5594QTextFormatCollection::~QTextFormatCollection() 5600QTextFormatCollection::~QTextFormatCollection()
5595{ 5601{
5596 delete defFormat; 5602 delete defFormat;
5597} 5603}
5598 5604
5599QTextFormat *QTextFormatCollection::format( QTextFormat *f ) 5605QTextFormat *QTextFormatCollection::format( QTextFormat *f )
5600{ 5606{
5601 if ( f->parent() == this || f == defFormat ) { 5607 if ( f->parent() == this || f == defFormat ) {
5602 lastFormat = f; 5608 lastFormat = f;
5603 lastFormat->addRef(); 5609 lastFormat->addRef();
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
5797void QTextFormat::setVAlign( VerticalAlignment a ) 5803void QTextFormat::setVAlign( VerticalAlignment a )
5798{ 5804{
5799 if ( a == ha ) 5805 if ( a == ha )
5800 return; 5806 return;
5801 ha = a; 5807 ha = a;
5802 update(); 5808 update();
5803} 5809}
5804 5810
5805void QTextFormat::setItalic( bool b ) 5811void QTextFormat::setItalic( bool b )
5806{ 5812{
5807 if ( b == fn.italic() ) 5813 if ( b == fn.italic() )
5808 return; 5814 return;
5809 fn.setItalic( b ); 5815 fn.setItalic( b );
5810 update(); 5816 update();
5811} 5817}
5812 5818
5813void QTextFormat::setUnderline( bool b ) 5819void QTextFormat::setUnderline( bool b )
5814{ 5820{
5815 if ( b == fn.underline() ) 5821 if ( b == fn.underline() )
5816 return; 5822 return;
5817 fn.setUnderline( b ); 5823 fn.setUnderline( b );
5818 update(); 5824 update();
5819} 5825}
5820 5826
5821void QTextFormat::setStrikeOut( bool b ) 5827void QTextFormat::setStrikeOut( bool b )
5822{ 5828{
5823 if ( b == fn.strikeOut() ) 5829 if ( b == fn.strikeOut() )
5824 return; 5830 return;
5825 fn.setStrikeOut( b ); 5831 fn.setStrikeOut( b );
5826 update(); 5832 update();
5827} 5833}
5828 5834
5829void QTextFormat::setFamily( const QString &f ) 5835void QTextFormat::setFamily( const QString &f )
5830{ 5836{
5831 if ( f == fn.family() ) 5837 if ( f == fn.family() )
5832 return; 5838 return;
5833 fn.setFamily( f ); 5839 fn.setFamily( f );
5834 update(); 5840 update();
5835} 5841}
5836 5842
5837void QTextFormat::setPointSize( int s ) 5843void QTextFormat::setPointSize( int s )
5838{ 5844{
5839 if ( s == fn.pointSize() ) 5845 if ( s == fn.pointSize() )
5840 return; 5846 return;
5841 fn.setPointSize( s ); 5847 fn.setPointSize( s );
5842 usePixelSizes = FALSE; 5848 usePixelSizes = FALSE;
5843 update(); 5849 update();
5844} 5850}
5845 5851
5846void QTextFormat::setFont( const QFont &f ) 5852void QTextFormat::setFont( const QFont &f )
5847{ 5853{
5848 if ( f == fn && !k.isEmpty() ) 5854 if ( f == fn && !k.isEmpty() )
5849 return; 5855 return;
5850 fn = f; 5856 fn = f;
5851 update(); 5857 update();
5852} 5858}
5853 5859
5854void QTextFormat::setColor( const QColor &c ) 5860void QTextFormat::setColor( const QColor &c )
5855{ 5861{
5856 if ( c == col ) 5862 if ( c == col )
5857 return; 5863 return;
5858 col = c; 5864 col = c;
5859 update(); 5865 update();
5860} 5866}
5861 5867
5862QString QTextFormat::makeFormatChangeTags( QTextFormat* defaultFormat, QTextFormat *f, 5868QString QTextFormat::makeFormatChangeTags( QTextFormat* defaultFormat, QTextFormat *f,
5863 const QString& oldAnchorHref, const QString& anchorHref ) const 5869 const QString& oldAnchorHref, const QString& anchorHref ) const
5864{ 5870{
5865 QString tag; 5871 QString tag;
5866 if ( f ) 5872 if ( f )
5867 tag += f->makeFormatEndTags( defaultFormat, oldAnchorHref ); 5873 tag += f->makeFormatEndTags( defaultFormat, oldAnchorHref );
5868 5874
5869 if ( !anchorHref.isEmpty() ) 5875 if ( !anchorHref.isEmpty() )
5870 tag += "<a href=\"" + anchorHref + "\">"; 5876 tag += "<a href=\"" + anchorHref + "\">";
5871 5877
5872 if ( font() != defaultFormat->font() 5878 if ( font() != defaultFormat->font()
5873 || vAlign() != defaultFormat->vAlign() 5879 || vAlign() != defaultFormat->vAlign()
5874 || color().rgb() != defaultFormat->color().rgb() ) { 5880 || color().rgb() != defaultFormat->color().rgb() ) {
5875 QString s; 5881 QString s;
5876 if ( font().family() != defaultFormat->font().family() ) 5882 if ( font().family() != defaultFormat->font().family() )
5877 s += QString(!!s?";":"") + "font-family:" + fn.family(); 5883 s += QString(!!s?";":"") + "font-family:" + fn.family();
5878 if ( font().italic() && font().italic() != defaultFormat->font().italic() ) 5884 if ( font().italic() && font().italic() != defaultFormat->font().italic() )
5879 s += QString(!!s?";":"") + "font-style:" + (font().italic() ? "italic" : "normal"); 5885 s += QString(!!s?";":"") + "font-style:" + (font().italic() ? "italic" : "normal");
5880 if ( font().pointSize() != defaultFormat->font().pointSize() ) 5886 if ( font().pointSize() != defaultFormat->font().pointSize() )
5881 s += QString(!!s?";":"") + "font-size:" + QString::number( fn.pointSize() ) + "pt"; 5887 s += QString(!!s?";":"") + "font-size:" + QString::number( fn.pointSize() ) + "pt";
5882 if ( font().weight() != defaultFormat->font().weight() ) 5888 if ( font().weight() != defaultFormat->font().weight() )
5883 s += QString(!!s?";":"") + "font-weight:" + QString::number( fn.weight() * 8 ); 5889 s += QString(!!s?";":"") + "font-weight:" + QString::number( fn.weight() * 8 );
5884 if ( font().underline() != defaultFormat->font().underline() ) 5890 if ( font().underline() != defaultFormat->font().underline() )
5885 s += QString(!!s?";":"") + "text-decoration:" + ( font().underline() ? "underline" : "none"); 5891 s += QString(!!s?";":"") + "text-decoration:" + ( font().underline() ? "underline" : "none");
5886 if ( vAlign() != defaultFormat->vAlign() ) { 5892 if ( vAlign() != defaultFormat->vAlign() ) {
5887 s += QString(!!s?";":"") + "vertical-align:"; 5893 s += QString(!!s?";":"") + "vertical-align:";
5888 if ( vAlign() == QTextFormat::AlignSuperScript ) 5894 if ( vAlign() == QTextFormat::AlignSuperScript )
5889 s += "super"; 5895 s += "super";
5890 else if ( vAlign() == QTextFormat::AlignSubScript ) 5896 else if ( vAlign() == QTextFormat::AlignSubScript )
5891 s += "sub"; 5897 s += "sub";
5892 else 5898 else
5893 s += "normal"; 5899 s += "normal";
5894 } 5900 }
5895 if ( color().rgb() != defaultFormat->color().rgb() ) 5901 if ( color().rgb() != defaultFormat->color().rgb() )
5896 s += QString(!!s?";":"") + "color:" + col.name(); 5902 s += QString(!!s?";":"") + "color:" + col.name();
5897 if ( !s.isEmpty() ) 5903 if ( !s.isEmpty() )
5898 tag += "<span style=\"" + s + "\">"; 5904 tag += "<span style=\"" + s + "\">";
5899 } 5905 }
5900 5906
5901 return tag; 5907 return tag;
5902} 5908}
5903 5909
5904QString QTextFormat::makeFormatEndTags( QTextFormat* defaultFormat, const QString& anchorHref ) const 5910QString QTextFormat::makeFormatEndTags( QTextFormat* defaultFormat, const QString& anchorHref ) const
5905{ 5911{
5906 QString tag; 5912 QString tag;
5907 if ( font().family() != defaultFormat->font().family() 5913 if ( font().family() != defaultFormat->font().family()
5908 || font().pointSize() != defaultFormat->font().pointSize() 5914 || font().pointSize() != defaultFormat->font().pointSize()
5909 || font().weight() != defaultFormat->font().weight() 5915 || font().weight() != defaultFormat->font().weight()
5910 || font().italic() != defaultFormat->font().italic() 5916 || font().italic() != defaultFormat->font().italic()
5911 || font().underline() != defaultFormat->font().underline() 5917 || font().underline() != defaultFormat->font().underline()
5912 || font().strikeOut() != defaultFormat->font().strikeOut() 5918 || font().strikeOut() != defaultFormat->font().strikeOut()
5913 || vAlign() != defaultFormat->vAlign() 5919 || vAlign() != defaultFormat->vAlign()
5914 || color().rgb() != defaultFormat->color().rgb() ) 5920 || color().rgb() != defaultFormat->color().rgb() )
5915 tag += "</span>"; 5921 tag += "</span>";
5916 if ( !anchorHref.isEmpty() ) 5922 if ( !anchorHref.isEmpty() )
5917 tag += "</a>"; 5923 tag += "</a>";
5918 return tag; 5924 return tag;
5919} 5925}
5920 5926
5921QTextFormat QTextFormat::makeTextFormat( const QStyleSheetItem *style, const QMap<QString,QString>& attr, double scaleFontsFactor ) const 5927QTextFormat QTextFormat::makeTextFormat( const QStyleSheetItem *style, const QMap<QString,QString>& attr, double scaleFontsFactor ) const
5922{ 5928{
5923 QTextFormat format(*this); 5929 QTextFormat format(*this);
5924 if (!style ) 5930 if (!style )
5925 return format; 5931 return format;
5926 5932
5927 if ( !style->isAnchor() && style->color().isValid() ) { 5933 if ( !style->isAnchor() && style->color().isValid() ) {
5928 // the style is not an anchor and defines a color. 5934 // the style is not an anchor and defines a color.
5929 // It might be used inside an anchor and it should 5935 // It might be used inside an anchor and it should
5930 // override the link color. 5936 // override the link color.
5931 format.linkColor = FALSE; 5937 format.linkColor = FALSE;
5932 } 5938 }
5933 switch ( style->verticalAlignment() ) { 5939 switch ( style->verticalAlignment() ) {
5934 case QStyleSheetItem::VAlignBaseline: 5940 case QStyleSheetItem::VAlignBaseline:
5935 format.setVAlign( QTextFormat::AlignNormal ); 5941 format.setVAlign( QTextFormat::AlignNormal );
5936 break; 5942 break;
5937 case QStyleSheetItem::VAlignSuper: 5943 case QStyleSheetItem::VAlignSuper:
5938 format.setVAlign( QTextFormat::AlignSuperScript ); 5944 format.setVAlign( QTextFormat::AlignSuperScript );
5939 break; 5945 break;
5940 case QStyleSheetItem::VAlignSub: 5946 case QStyleSheetItem::VAlignSub:
5941 format.setVAlign( QTextFormat::AlignSubScript ); 5947 format.setVAlign( QTextFormat::AlignSubScript );
5942 break; 5948 break;
5943 } 5949 }
5944 5950
5945 if ( style->fontWeight() != QStyleSheetItem::Undefined ) 5951 if ( style->fontWeight() != QStyleSheetItem::Undefined )
5946 format.fn.setWeight( style->fontWeight() ); 5952 format.fn.setWeight( style->fontWeight() );
5947 if ( style->fontSize() != QStyleSheetItem::Undefined ) { 5953 if ( style->fontSize() != QStyleSheetItem::Undefined ) {
5948 format.fn.setPointSize( style->fontSize() ); 5954 format.fn.setPointSize( style->fontSize() );
5949 } else if ( style->logicalFontSize() != QStyleSheetItem::Undefined ) { 5955 } else if ( style->logicalFontSize() != QStyleSheetItem::Undefined ) {
5950 format.logicalFontSize = style->logicalFontSize(); 5956 format.logicalFontSize = style->logicalFontSize();
5951 if ( format.usePixelSizes ) 5957 if ( format.usePixelSizes )
5952 format.fn.setPixelSize( format.stdSize ); 5958 format.fn.setPixelSize( format.stdSize );
5953 else 5959 else
5954 format.fn.setPointSize( format.stdSize ); 5960 format.fn.setPointSize( format.stdSize );
5955 style->styleSheet()->scaleFont( format.fn, format.logicalFontSize ); 5961 style->styleSheet()->scaleFont( format.fn, format.logicalFontSize );
5956 } else if ( style->logicalFontSizeStep() ) { 5962 } else if ( style->logicalFontSizeStep() ) {
5957 format.logicalFontSize += style->logicalFontSizeStep(); 5963 format.logicalFontSize += style->logicalFontSizeStep();
5958 if ( format.usePixelSizes ) 5964 if ( format.usePixelSizes )
5959 format.fn.setPixelSize( format.stdSize ); 5965 format.fn.setPixelSize( format.stdSize );
5960 else 5966 else
5961 format.fn.setPointSize( format.stdSize ); 5967 format.fn.setPointSize( format.stdSize );
5962 style->styleSheet()->scaleFont( format.fn, format.logicalFontSize ); 5968 style->styleSheet()->scaleFont( format.fn, format.logicalFontSize );
5963 } 5969 }
5964 if ( !style->fontFamily().isEmpty() ) 5970 if ( !style->fontFamily().isEmpty() )
5965 format.fn.setFamily( style->fontFamily() ); 5971 format.fn.setFamily( style->fontFamily() );
5966 if ( style->color().isValid() ) 5972 if ( style->color().isValid() )
5967 format.col = style->color(); 5973 format.col = style->color();
5968 if ( style->definesFontItalic() ) 5974 if ( style->definesFontItalic() )
5969 format.fn.setItalic( style->fontItalic() ); 5975 format.fn.setItalic( style->fontItalic() );
5970 if ( style->definesFontUnderline() ) 5976 if ( style->definesFontUnderline() )
5971 format.fn.setUnderline( style->fontUnderline() ); 5977 format.fn.setUnderline( style->fontUnderline() );
5972 if ( style->definesFontStrikeOut() ) 5978 if ( style->definesFontStrikeOut() )
5973 format.fn.setStrikeOut( style->fontStrikeOut() ); 5979 format.fn.setStrikeOut( style->fontStrikeOut() );
5974 5980
5975 5981
5976 if ( style->name() == "font") { 5982 if ( style->name() == "font") {
5977 if ( attr.contains("color") ) { 5983 if ( attr.contains("color") ) {
5978 QString s = attr["color"]; 5984 QString s = attr["color"];
5979 if ( !s.isEmpty() ) { 5985 if ( !s.isEmpty() ) {
5980 format.col.setNamedColor( s ); 5986 format.col.setNamedColor( s );
5981 format.linkColor = FALSE; 5987 format.linkColor = FALSE;
5982 } 5988 }
5983 } 5989 }
5984 if ( attr.contains("face") ) { 5990 if ( attr.contains("face") ) {
5985 QString a = attr["face"]; 5991 QString a = attr["face"];
5986 QString family = QTextDocument::section( a, ",", 0, 0 ); 5992 QString family = QTextDocument::section( a, ",", 0, 0 );
5987 if ( !!family ) 5993 if ( !!family )
5988 format.fn.setFamily( family ); 5994 format.fn.setFamily( family );
5989 } 5995 }
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 );
6187 QBitmap m( 2, 2 ); 6193 QBitmap m( 2, 2 );
6188 m.fill( Qt::color1 ); 6194 m.fill( Qt::color1 );
6189 QPainter p( &m ); 6195 QPainter p( &m );
6190 p.setPen( Qt::color0 ); 6196 p.setPen( Qt::color0 );
6191 for ( int j = 0; j < 2; ++j ) { 6197 for ( int j = 0; j < 2; ++j ) {
6192 p.drawPoint( j % 2, j ); 6198 p.drawPoint( j % 2, j );
6193 } 6199 }
6194 p.end(); 6200 p.end();
6195 qrt_selection->setMask( m ); 6201 qrt_selection->setMask( m );
6196 qrt_selection->fill( cg.highlight() ); 6202 qrt_selection->fill( cg.highlight() );
6197} 6203}
6198#endif 6204#endif
6199 6205
6200void QTextImage::draw( QPainter* p, int x, int y, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool selected ) 6206void QTextImage::draw( QPainter* p, int x, int y, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool selected )
6201{ 6207{
6202 if ( placement() != PlaceInline ) { 6208 if ( placement() != PlaceInline ) {
6203 x = xpos; 6209 x = xpos;
6204 y = ypos; 6210 y = ypos;
6205 } 6211 }
6206 6212
6207 if ( pm.isNull() ) { 6213 if ( pm.isNull() ) {
6208 p->fillRect( x , y, width, height, cg.dark() ); 6214 p->fillRect( x , y, width, height, cg.dark() );
6209 return; 6215 return;
6210 } 6216 }
6211 6217
6212 if ( is_printer( p ) ) { 6218 if ( is_printer( p ) ) {
6213 p->drawPixmap( x, y, pm ); 6219 p->drawPixmap( x, y, pm );
6214 return; 6220 return;
6215 } 6221 }
6216 6222
6217 if ( placement() != PlaceInline && !QRect( xpos, ypos, width, height ).intersects( QRect( cx, cy, cw, ch ) ) ) 6223 if ( placement() != PlaceInline && !QRect( xpos, ypos, width, height ).intersects( QRect( cx, cy, cw, ch ) ) )
6218 return; 6224 return;
6219 6225
6220 if ( placement() == PlaceInline ) 6226 if ( placement() == PlaceInline )
6221 p->drawPixmap( x , y, pm ); 6227 p->drawPixmap( x , y, pm );
6222 else 6228 else
6223 p->drawPixmap( cx , cy, pm, cx - x, cy - y, cw, ch ); 6229 p->drawPixmap( cx , cy, pm, cx - x, cy - y, cw, ch );
6224 6230
6225 if ( selected && placement() == PlaceInline && is_printer( p ) ) { 6231 if ( selected && placement() == PlaceInline && is_printer( p ) ) {
6226#if defined(Q_WS_X11) 6232#if defined(Q_WS_X11)
6227 p->fillRect( QRect( QPoint( x, y ), pm.size() ), QBrush( cg.highlight(), QBrush::Dense4Pattern) ); 6233 p->fillRect( QRect( QPoint( x, y ), pm.size() ), QBrush( cg.highlight(), QBrush::Dense4Pattern) );
6228#else // in WIN32 Dense4Pattern doesn't work correctly (transparency problem), so work around it 6234#else // in WIN32 Dense4Pattern doesn't work correctly (transparency problem), so work around it
6229 if ( !qrt_selection ) 6235 if ( !qrt_selection )
6230 qrt_createSelectionPixmap( cg ); 6236 qrt_createSelectionPixmap( cg );
6231 p->drawTiledPixmap( x, y, pm.width(), pm.height(), *qrt_selection ); 6237 p->drawTiledPixmap( x, y, pm.width(), pm.height(), *qrt_selection );
6232#endif 6238#endif
6233 } 6239 }
6234} 6240}
6235 6241
6236void QTextHorizontalLine::adjustToPainter( QPainter* p ) 6242void QTextHorizontalLine::adjustToPainter( QPainter* p )
6237{ 6243{
6238 height = scale( tmpheight, p ); 6244 height = scale( tmpheight, p );
6239} 6245}
6240 6246
6241 6247
6242QTextHorizontalLine::QTextHorizontalLine( QTextDocument *p, const QMap<QString, QString> &attr, 6248QTextHorizontalLine::QTextHorizontalLine( QTextDocument *p, const QMap<QString, QString> &attr,
6243 const QString &, 6249 const QString &,
6244 QMimeSourceFactory & ) 6250 QMimeSourceFactory & )
6245 : QTextCustomItem( p ) 6251 : QTextCustomItem( p )
6246{ 6252{
6247 height = tmpheight = 8; 6253 height = tmpheight = 8;
6248 if ( attr.find( "color" ) != attr.end() ) 6254 if ( attr.find( "color" ) != attr.end() )
6249 color = QColor( *attr.find( "color" ) ); 6255 color = QColor( *attr.find( "color" ) );
6250} 6256}
6251 6257
6252QTextHorizontalLine::~QTextHorizontalLine() 6258QTextHorizontalLine::~QTextHorizontalLine()
6253{ 6259{
6254} 6260}
6255 6261
6256QString QTextHorizontalLine::richText() const 6262QString QTextHorizontalLine::richText() const
6257{ 6263{
6258 return "<hr>"; 6264 return "<hr>";
6259} 6265}
6260 6266
6261void QTextHorizontalLine::draw( QPainter* p, int x, int y, int , int , int , int , const QColorGroup& cg, bool selected ) 6267void QTextHorizontalLine::draw( QPainter* p, int x, int y, int , int , int , int , const QColorGroup& cg, bool selected )
6262{ 6268{
6263 QRect r( x, y, width, height); 6269 QRect r( x, y, width, height);
6264 if ( is_printer( p ) ) { 6270 if ( is_printer( p ) ) {
6265 QPen oldPen = p->pen(); 6271 QPen oldPen = p->pen();
6266 if ( !color.isValid() ) 6272 if ( !color.isValid() )
6267 p->setPen( QPen( cg.text(), height/8 ) ); 6273 p->setPen( QPen( cg.text(), height/8 ) );
6268 else 6274 else
6269 p->setPen( QPen( color, height/8 ) ); 6275 p->setPen( QPen( color, height/8 ) );
6270 p->drawLine( r.left()-1, y + height / 2, r.right() + 1, y + height / 2 ); 6276 p->drawLine( r.left()-1, y + height / 2, r.right() + 1, y + height / 2 );
6271 p->setPen( oldPen ); 6277 p->setPen( oldPen );
6272 } else { 6278 } else {
6273 QColorGroup g( cg ); 6279 QColorGroup g( cg );
6274 if ( color.isValid() ) 6280 if ( color.isValid() )
6275 g.setColor( QColorGroup::Dark, color ); 6281 g.setColor( QColorGroup::Dark, color );
6276 if ( selected ) 6282 if ( selected )
6277 p->fillRect( r.left(), y, r.right(), y + height, g.highlight() ); 6283 p->fillRect( r.left(), y, r.right(), y + height, g.highlight() );
6278 qDrawShadeLine( p, r.left() - 1, y + height / 2, r.right() + 1, y + height / 2, g, TRUE, height / 8 ); 6284 qDrawShadeLine( p, r.left() - 1, y + height / 2, r.right() + 1, y + height / 2, g, TRUE, height / 8 );
6279 } 6285 }
6280} 6286}
6281 6287
6282 6288
6283/*****************************************************************/ 6289/*****************************************************************/
6284// Small set of utility functions to make the parser a bit simpler 6290// Small set of utility functions to make the parser a bit simpler
6285// 6291//
6286 6292
6287bool QTextDocument::hasPrefix(const QChar* doc, int length, int pos, QChar c) 6293bool QTextDocument::hasPrefix(const QChar* doc, int length, int pos, QChar c)
6288{ 6294{
6289 if ( pos >= length ) 6295 if ( pos >= length )
6290 return FALSE; 6296 return FALSE;
6291 return doc[ pos ].lower() == c.lower(); 6297 return doc[ pos ].lower() == c.lower();
6292} 6298}
6293 6299
6294bool QTextDocument::hasPrefix( const QChar* doc, int length, int pos, const QString& s ) 6300bool QTextDocument::hasPrefix( const QChar* doc, int length, int pos, const QString& s )
6295{ 6301{
6296 if ( pos + (int) s.length() >= length ) 6302 if ( pos + (int) s.length() >= length )
6297 return FALSE; 6303 return FALSE;
6298 for ( int i = 0; i < (int)s.length(); i++ ) { 6304 for ( int i = 0; i < (int)s.length(); i++ ) {
6299 if ( doc[ pos + i ].lower() != s[ i ].lower() ) 6305 if ( doc[ pos + i ].lower() != s[ i ].lower() )
6300 return FALSE; 6306 return FALSE;
6301 } 6307 }
6302 return TRUE; 6308 return TRUE;
6303} 6309}
6304 6310
6305static bool qt_is_cell_in_use( QPtrList<QTextTableCell>& cells, int row, int col ) 6311static bool qt_is_cell_in_use( QPtrList<QTextTableCell>& cells, int row, int col )
6306{ 6312{
6307 for ( QTextTableCell* c = cells.first(); c; c = cells.next() ) { 6313 for ( QTextTableCell* c = cells.first(); c; c = cells.next() ) {
6308 if ( row >= c->row() && row < c->row() + c->rowspan() 6314 if ( row >= c->row() && row < c->row() + c->rowspan()
6309 && col >= c->column() && col < c->column() + c->colspan() ) 6315 && col >= c->column() && col < c->column() + c->colspan() )
6310 return TRUE; 6316 return TRUE;
6311 } 6317 }
6312 return FALSE; 6318 return FALSE;
6313} 6319}
6314 6320
6315QTextCustomItem* QTextDocument::parseTable( const QMap<QString, QString> &attr, const QTextFormat &fmt, 6321QTextCustomItem* QTextDocument::parseTable( const QMap<QString, QString> &attr, const QTextFormat &fmt,
6316 const QChar* doc, int length, int& pos, QTextParagraph *curpar ) 6322 const QChar* doc, int length, int& pos, QTextParagraph *curpar )
6317{ 6323{
6318 6324
6319 QTextTable* table = new QTextTable( this, attr ); 6325 QTextTable* table = new QTextTable( this, attr );
6320 int row = -1; 6326 int row = -1;
6321 int col = -1; 6327 int col = -1;
6322 6328
6323 QString rowbgcolor; 6329 QString rowbgcolor;
6324 QString rowalign; 6330 QString rowalign;
6325 QString tablebgcolor = attr["bgcolor"]; 6331 QString tablebgcolor = attr["bgcolor"];
6326 6332
6327 QPtrList<QTextTableCell> multicells; 6333 QPtrList<QTextTableCell> multicells;
6328 6334
6329 QString tagname; 6335 QString tagname;
6330 (void) eatSpace(doc, length, pos); 6336 (void) eatSpace(doc, length, pos);
6331 while ( pos < length) { 6337 while ( pos < length) {
6332 if (hasPrefix(doc, length, pos, QChar('<')) ){ 6338 if (hasPrefix(doc, length, pos, QChar('<')) ){
6333 if (hasPrefix(doc, length, pos+1, QChar('/'))) { 6339 if (hasPrefix(doc, length, pos+1, QChar('/'))) {
6334 tagname = parseCloseTag( doc, length, pos ); 6340 tagname = parseCloseTag( doc, length, pos );
6335 if ( tagname == "table" ) { 6341 if ( tagname == "table" ) {
6336 return table; 6342 return table;
6337 } 6343 }
6338 } else { 6344 } else {
6339 QMap<QString, QString> attr2; 6345 QMap<QString, QString> attr2;
6340 bool emptyTag = FALSE; 6346 bool emptyTag = FALSE;
6341 tagname = parseOpenTag( doc, length, pos, attr2, emptyTag ); 6347 tagname = parseOpenTag( doc, length, pos, attr2, emptyTag );
6342 if ( tagname == "tr" ) { 6348 if ( tagname == "tr" ) {
6343 rowbgcolor = attr2["bgcolor"]; 6349 rowbgcolor = attr2["bgcolor"];
6344 rowalign = attr2["align"]; 6350 rowalign = attr2["align"];
6345 row++; 6351 row++;
6346 col = -1; 6352 col = -1;
6347 } 6353 }
6348 else if ( tagname == "td" || tagname == "th" ) { 6354 else if ( tagname == "td" || tagname == "th" ) {
6349 col++; 6355 col++;
6350 while ( qt_is_cell_in_use( multicells, row, col ) ) { 6356 while ( qt_is_cell_in_use( multicells, row, col ) ) {
6351 col++; 6357 col++;
6352 } 6358 }
6353 6359
6354 if ( row >= 0 && col >= 0 ) { 6360 if ( row >= 0 && col >= 0 ) {
6355 const QStyleSheetItem* s = sheet_->item(tagname); 6361 const QStyleSheetItem* s = sheet_->item(tagname);
6356 if ( !attr2.contains("bgcolor") ) { 6362 if ( !attr2.contains("bgcolor") ) {
6357 if (!rowbgcolor.isEmpty() ) 6363 if (!rowbgcolor.isEmpty() )
6358 attr2["bgcolor"] = rowbgcolor; 6364 attr2["bgcolor"] = rowbgcolor;
6359 else if (!tablebgcolor.isEmpty() ) 6365 else if (!tablebgcolor.isEmpty() )
6360 attr2["bgcolor"] = tablebgcolor; 6366 attr2["bgcolor"] = tablebgcolor;
6361 } 6367 }
6362 if ( !attr2.contains("align") ) { 6368 if ( !attr2.contains("align") ) {
6363 if (!rowalign.isEmpty() ) 6369 if (!rowalign.isEmpty() )
6364 attr2["align"] = rowalign; 6370 attr2["align"] = rowalign;
6365 } 6371 }
6366 6372
6367 // extract the cell contents 6373 // extract the cell contents
6368 int end = pos; 6374 int end = pos;
6369 while ( end < length 6375 while ( end < length
6370 && !hasPrefix( doc, length, end, "</td") 6376 && !hasPrefix( doc, length, end, "</td")
6371 && !hasPrefix( doc, length, end, "<td") 6377 && !hasPrefix( doc, length, end, "<td")
6372 && !hasPrefix( doc, length, end, "</th") 6378 && !hasPrefix( doc, length, end, "</th")
6373 && !hasPrefix( doc, length, end, "<th") 6379 && !hasPrefix( doc, length, end, "<th")
6374 && !hasPrefix( doc, length, end, "<td") 6380 && !hasPrefix( doc, length, end, "<td")
6375 && !hasPrefix( doc, length, end, "</tr") 6381 && !hasPrefix( doc, length, end, "</tr")
6376 && !hasPrefix( doc, length, end, "<tr") 6382 && !hasPrefix( doc, length, end, "<tr")
6377 && !hasPrefix( doc, length, end, "</table") ) { 6383 && !hasPrefix( doc, length, end, "</table") ) {
6378 if ( hasPrefix( doc, length, end, "<table" ) ) { // nested table 6384 if ( hasPrefix( doc, length, end, "<table" ) ) { // nested table
6379 int nested = 1; 6385 int nested = 1;
6380 ++end; 6386 ++end;
6381 while ( end < length && nested != 0 ) { 6387 while ( end < length && nested != 0 ) {
6382 if ( hasPrefix( doc, length, end, "</table" ) ) 6388 if ( hasPrefix( doc, length, end, "</table" ) )
6383 nested--; 6389 nested--;
6384 if ( hasPrefix( doc, length, end, "<table" ) ) 6390 if ( hasPrefix( doc, length, end, "<table" ) )
6385 nested++; 6391 nested++;
6386 end++; 6392 end++;
6387 } 6393 }
6388 } 6394 }
6389 end++; 6395 end++;
6390 } 6396 }
6391 QTextTableCell* cell = new QTextTableCell( table, row, col, 6397 QTextTableCell* cell = new QTextTableCell( table, row, col,
6392 attr2, s, fmt.makeTextFormat( s, attr2, scaleFontsFactor ), 6398 attr2, s, fmt.makeTextFormat( s, attr2, scaleFontsFactor ),
6393 contxt, *factory_, sheet_, 6399 contxt, *factory_, sheet_,
6394 QString( doc, length).mid( pos, end - pos ) ); 6400 QString( doc, length).mid( pos, end - pos ) );
6395 cell->richText()->parentPar = curpar; 6401 cell->richText()->parentPar = curpar;
6396 if ( cell->colspan() > 1 || cell->rowspan() > 1 ) 6402 if ( cell->colspan() > 1 || cell->rowspan() > 1 )
6397 multicells.append( cell ); 6403 multicells.append( cell );
6398 col += cell->colspan()-1; 6404 col += cell->colspan()-1;
6399 pos = end; 6405 pos = end;
6400 } 6406 }
6401 } 6407 }
6402 } 6408 }
6403 6409
6404 } else { 6410 } else {
6405 ++pos; 6411 ++pos;
6406 } 6412 }
6407 } 6413 }
6408 return table; 6414 return table;
6409} 6415}
6410 6416
6411bool QTextDocument::eatSpace(const QChar* doc, int length, int& pos, bool includeNbsp ) 6417bool QTextDocument::eatSpace(const QChar* doc, int length, int& pos, bool includeNbsp )
6412{ 6418{
6413 int old_pos = pos; 6419 int old_pos = pos;
6414 while (pos < length && doc[pos].isSpace() && ( includeNbsp || (doc[pos] != QChar::nbsp ) ) ) 6420 while (pos < length && doc[pos].isSpace() && ( includeNbsp || (doc[pos] != QChar::nbsp ) ) )
6415 pos++; 6421 pos++;
6416 return old_pos < pos; 6422 return old_pos < pos;
6417} 6423}
6418 6424
6419bool QTextDocument::eat(const QChar* doc, int length, int& pos, QChar c) 6425bool QTextDocument::eat(const QChar* doc, int length, int& pos, QChar c)
6420{ 6426{
6421 bool ok = pos < length && doc[pos] == c; 6427 bool ok = pos < length && doc[pos] == c;
6422 if ( ok ) 6428 if ( ok )
6423 pos++; 6429 pos++;
6424 return ok; 6430 return ok;
6425} 6431}
6426/*****************************************************************/ 6432/*****************************************************************/
6427 6433
6428struct Entity { 6434struct Entity {
6429 const char * name; 6435 const char * name;
6430 Q_UINT16 code; 6436 Q_UINT16 code;
6431}; 6437};
6432 6438
6433static const Entity entitylist [] = { 6439static const Entity entitylist [] = {
6434 { "AElig", 0x00c6 }, 6440 { "AElig", 0x00c6 },
6435 { "Aacute", 0x00c1 }, 6441 { "Aacute", 0x00c1 },
6436 { "Acirc", 0x00c2 }, 6442 { "Acirc", 0x00c2 },
6437 { "Agrave", 0x00c0 }, 6443 { "Agrave", 0x00c0 },
6438 { "Alpha", 0x0391 }, 6444 { "Alpha", 0x0391 },
6439 { "AMP", 38 }, 6445 { "AMP", 38 },
6440 { "Aring", 0x00c5 }, 6446 { "Aring", 0x00c5 },
6441 { "Atilde", 0x00c3 }, 6447 { "Atilde", 0x00c3 },
6442 { "Auml", 0x00c4 }, 6448 { "Auml", 0x00c4 },
6443 { "Beta", 0x0392 }, 6449 { "Beta", 0x0392 },
6444 { "Ccedil", 0x00c7 }, 6450 { "Ccedil", 0x00c7 },
6445 { "Chi", 0x03a7 }, 6451 { "Chi", 0x03a7 },
6446 { "Dagger", 0x2021 }, 6452 { "Dagger", 0x2021 },
6447 { "Delta", 0x0394 }, 6453 { "Delta", 0x0394 },
6448 { "ETH", 0x00d0 }, 6454 { "ETH", 0x00d0 },
6449 { "Eacute", 0x00c9 }, 6455 { "Eacute", 0x00c9 },
6450 { "Ecirc", 0x00ca }, 6456 { "Ecirc", 0x00ca },
6451 { "Egrave", 0x00c8 }, 6457 { "Egrave", 0x00c8 },
6452 { "Epsilon", 0x0395 }, 6458 { "Epsilon", 0x0395 },
6453 { "Eta", 0x0397 }, 6459 { "Eta", 0x0397 },
6454 { "Euml", 0x00cb }, 6460 { "Euml", 0x00cb },
6455 { "Gamma", 0x0393 }, 6461 { "Gamma", 0x0393 },
6456 { "GT", 62 }, 6462 { "GT", 62 },
6457 { "Iacute", 0x00cd }, 6463 { "Iacute", 0x00cd },
6458 { "Icirc", 0x00ce }, 6464 { "Icirc", 0x00ce },
6459 { "Igrave", 0x00cc }, 6465 { "Igrave", 0x00cc },
6460 { "Iota", 0x0399 }, 6466 { "Iota", 0x0399 },
6461 { "Iuml", 0x00cf }, 6467 { "Iuml", 0x00cf },
6462 { "Kappa", 0x039a }, 6468 { "Kappa", 0x039a },
6463 { "Lambda", 0x039b }, 6469 { "Lambda", 0x039b },
6464 { "LT", 60 }, 6470 { "LT", 60 },
6465 { "Mu", 0x039c }, 6471 { "Mu", 0x039c },
6466 { "Ntilde", 0x00d1 }, 6472 { "Ntilde", 0x00d1 },
6467 { "Nu", 0x039d }, 6473 { "Nu", 0x039d },
6468 { "OElig", 0x0152 }, 6474 { "OElig", 0x0152 },
6469 { "Oacute", 0x00d3 }, 6475 { "Oacute", 0x00d3 },
6470 { "Ocirc", 0x00d4 }, 6476 { "Ocirc", 0x00d4 },
6471 { "Ograve", 0x00d2 }, 6477 { "Ograve", 0x00d2 },
6472 { "Omega", 0x03a9 }, 6478 { "Omega", 0x03a9 },
6473 { "Omicron", 0x039f }, 6479 { "Omicron", 0x039f },
6474 { "Oslash", 0x00d8 }, 6480 { "Oslash", 0x00d8 },
6475 { "Otilde", 0x00d5 }, 6481 { "Otilde", 0x00d5 },
6476 { "Ouml", 0x00d6 }, 6482 { "Ouml", 0x00d6 },
6477 { "Phi", 0x03a6 }, 6483 { "Phi", 0x03a6 },
6478 { "Pi", 0x03a0 }, 6484 { "Pi", 0x03a0 },
6479 { "Prime", 0x2033 }, 6485 { "Prime", 0x2033 },
6480 { "Psi", 0x03a8 }, 6486 { "Psi", 0x03a8 },
6481 { "QUOT", 34 }, 6487 { "QUOT", 34 },
6482 { "Rho", 0x03a1 }, 6488 { "Rho", 0x03a1 },
6483 { "Scaron", 0x0160 }, 6489 { "Scaron", 0x0160 },
6484 { "Sigma", 0x03a3 }, 6490 { "Sigma", 0x03a3 },
6485 { "THORN", 0x00de }, 6491 { "THORN", 0x00de },
6486 { "Tau", 0x03a4 }, 6492 { "Tau", 0x03a4 },
6487 { "Theta", 0x0398 }, 6493 { "Theta", 0x0398 },
6488 { "Uacute", 0x00da }, 6494 { "Uacute", 0x00da },
6489 { "Ucirc", 0x00db }, 6495 { "Ucirc", 0x00db },
6490 { "Ugrave", 0x00d9 }, 6496 { "Ugrave", 0x00d9 },
6491 { "Upsilon", 0x03a5 }, 6497 { "Upsilon", 0x03a5 },
6492 { "Uuml", 0x00dc }, 6498 { "Uuml", 0x00dc },
6493 { "Xi", 0x039e }, 6499 { "Xi", 0x039e },
6494 { "Yacute", 0x00dd }, 6500 { "Yacute", 0x00dd },
6495 { "Yuml", 0x0178 }, 6501 { "Yuml", 0x0178 },
6496 { "Zeta", 0x0396 }, 6502 { "Zeta", 0x0396 },
6497 { "aacute", 0x00e1 }, 6503 { "aacute", 0x00e1 },
6498 { "acirc", 0x00e2 }, 6504 { "acirc", 0x00e2 },
6499 { "acute", 0x00b4 }, 6505 { "acute", 0x00b4 },
6500 { "aelig", 0x00e6 }, 6506 { "aelig", 0x00e6 },
6501 { "agrave", 0x00e0 }, 6507 { "agrave", 0x00e0 },
6502 { "alefsym", 0x2135 }, 6508 { "alefsym", 0x2135 },
6503 { "alpha", 0x03b1 }, 6509 { "alpha", 0x03b1 },
6504 { "amp", 38 }, 6510 { "amp", 38 },
6505 { "and", 0x22a5 }, 6511 { "and", 0x22a5 },
6506 { "ang", 0x2220 }, 6512 { "ang", 0x2220 },
6507 { "apos", 0x0027 }, 6513 { "apos", 0x0027 },
6508 { "aring", 0x00e5 }, 6514 { "aring", 0x00e5 },
6509 { "asymp", 0x2248 }, 6515 { "asymp", 0x2248 },
6510 { "atilde", 0x00e3 }, 6516 { "atilde", 0x00e3 },
6511 { "auml", 0x00e4 }, 6517 { "auml", 0x00e4 },
6512 { "bdquo", 0x201e }, 6518 { "bdquo", 0x201e },
6513 { "beta", 0x03b2 }, 6519 { "beta", 0x03b2 },
6514 { "brvbar", 0x00a6 }, 6520 { "brvbar", 0x00a6 },
6515 { "bull", 0x2022 }, 6521 { "bull", 0x2022 },
6516 { "cap", 0x2229 }, 6522 { "cap", 0x2229 },
6517 { "ccedil", 0x00e7 }, 6523 { "ccedil", 0x00e7 },
6518 { "cedil", 0x00b8 }, 6524 { "cedil", 0x00b8 },
6519 { "cent", 0x00a2 }, 6525 { "cent", 0x00a2 },
6520 { "chi", 0x03c7 }, 6526 { "chi", 0x03c7 },
6521 { "circ", 0x02c6 }, 6527 { "circ", 0x02c6 },
6522 { "clubs", 0x2663 }, 6528 { "clubs", 0x2663 },
6523 { "cong", 0x2245 }, 6529 { "cong", 0x2245 },
6524 { "copy", 0x00a9 }, 6530 { "copy", 0x00a9 },
6525 { "crarr", 0x21b5 }, 6531 { "crarr", 0x21b5 },
6526 { "cup", 0x222a }, 6532 { "cup", 0x222a },
6527 { "curren", 0x00a4 }, 6533 { "curren", 0x00a4 },
6528 { "dArr", 0x21d3 }, 6534 { "dArr", 0x21d3 },
6529 { "dagger", 0x2020 }, 6535 { "dagger", 0x2020 },
6530 { "darr", 0x2193 }, 6536 { "darr", 0x2193 },
6531 { "deg", 0x00b0 }, 6537 { "deg", 0x00b0 },
6532 { "delta", 0x03b4 }, 6538 { "delta", 0x03b4 },
6533 { "diams", 0x2666 }, 6539 { "diams", 0x2666 },
6534 { "divide", 0x00f7 }, 6540 { "divide", 0x00f7 },
6535 { "eacute", 0x00e9 }, 6541 { "eacute", 0x00e9 },
6536 { "ecirc", 0x00ea }, 6542 { "ecirc", 0x00ea },
6537 { "egrave", 0x00e8 }, 6543 { "egrave", 0x00e8 },
6538 { "empty", 0x2205 }, 6544 { "empty", 0x2205 },
6539 { "emsp", 0x2003 }, 6545 { "emsp", 0x2003 },
6540 { "ensp", 0x2002 }, 6546 { "ensp", 0x2002 },
6541 { "epsilon", 0x03b5 }, 6547 { "epsilon", 0x03b5 },
6542 { "equiv", 0x2261 }, 6548 { "equiv", 0x2261 },
6543 { "eta", 0x03b7 }, 6549 { "eta", 0x03b7 },
6544 { "eth", 0x00f0 }, 6550 { "eth", 0x00f0 },
6545 { "euml", 0x00eb }, 6551 { "euml", 0x00eb },
6546 { "euro", 0x20ac }, 6552 { "euro", 0x20ac },
6547 { "exist", 0x2203 }, 6553 { "exist", 0x2203 },
6548 { "fnof", 0x0192 }, 6554 { "fnof", 0x0192 },
6549 { "forall", 0x2200 }, 6555 { "forall", 0x2200 },
6550 { "frac12", 0x00bd }, 6556 { "frac12", 0x00bd },
6551 { "frac14", 0x00bc }, 6557 { "frac14", 0x00bc },
6552 { "frac34", 0x00be }, 6558 { "frac34", 0x00be },
6553 { "frasl", 0x2044 }, 6559 { "frasl", 0x2044 },
6554 { "gamma", 0x03b3 }, 6560 { "gamma", 0x03b3 },
6555 { "ge", 0x2265 }, 6561 { "ge", 0x2265 },
6556 { "gt", 62 }, 6562 { "gt", 62 },
6557 { "hArr", 0x21d4 }, 6563 { "hArr", 0x21d4 },
6558 { "harr", 0x2194 }, 6564 { "harr", 0x2194 },
6559 { "hearts", 0x2665 }, 6565 { "hearts", 0x2665 },
6560 { "hellip", 0x2026 }, 6566 { "hellip", 0x2026 },
6561 { "iacute", 0x00ed }, 6567 { "iacute", 0x00ed },
6562 { "icirc", 0x00ee }, 6568 { "icirc", 0x00ee },
6563 { "iexcl", 0x00a1 }, 6569 { "iexcl", 0x00a1 },
6564 { "igrave", 0x00ec }, 6570 { "igrave", 0x00ec },
6565 { "image", 0x2111 }, 6571 { "image", 0x2111 },
6566 { "infin", 0x221e }, 6572 { "infin", 0x221e },
6567 { "int", 0x222b }, 6573 { "int", 0x222b },
6568 { "iota", 0x03b9 }, 6574 { "iota", 0x03b9 },
6569 { "iquest", 0x00bf }, 6575 { "iquest", 0x00bf },
6570 { "isin", 0x2208 }, 6576 { "isin", 0x2208 },
6571 { "iuml", 0x00ef }, 6577 { "iuml", 0x00ef },
6572 { "kappa", 0x03ba }, 6578 { "kappa", 0x03ba },
6573 { "lArr", 0x21d0 }, 6579 { "lArr", 0x21d0 },
6574 { "lambda", 0x03bb }, 6580 { "lambda", 0x03bb },
6575 { "lang", 0x2329 }, 6581 { "lang", 0x2329 },
6576 { "laquo", 0x00ab }, 6582 { "laquo", 0x00ab },
6577 { "larr", 0x2190 }, 6583 { "larr", 0x2190 },
6578 { "lceil", 0x2308 }, 6584 { "lceil", 0x2308 },
6579 { "ldquo", 0x201c }, 6585 { "ldquo", 0x201c },
6580 { "le", 0x2264 }, 6586 { "le", 0x2264 },
6581 { "lfloor", 0x230a }, 6587 { "lfloor", 0x230a },
6582 { "lowast", 0x2217 }, 6588 { "lowast", 0x2217 },
6583 { "loz", 0x25ca }, 6589 { "loz", 0x25ca },
6584 { "lrm", 0x200e }, 6590 { "lrm", 0x200e },
6585 { "lsaquo", 0x2039 }, 6591 { "lsaquo", 0x2039 },
6586 { "lsquo", 0x2018 }, 6592 { "lsquo", 0x2018 },
6587 { "lt", 60 }, 6593 { "lt", 60 },
6588 { "macr", 0x00af }, 6594 { "macr", 0x00af },
6589 { "mdash", 0x2014 }, 6595 { "mdash", 0x2014 },
6590 { "micro", 0x00b5 }, 6596 { "micro", 0x00b5 },
6591 { "middot", 0x00b7 }, 6597 { "middot", 0x00b7 },
6592 { "minus", 0x2212 }, 6598 { "minus", 0x2212 },
6593 { "mu", 0x03bc }, 6599 { "mu", 0x03bc },
6594 { "nabla", 0x2207 }, 6600 { "nabla", 0x2207 },
6595 { "nbsp", 0x00a0 }, 6601 { "nbsp", 0x00a0 },
6596 { "ndash", 0x2013 }, 6602 { "ndash", 0x2013 },
6597 { "ne", 0x2260 }, 6603 { "ne", 0x2260 },
6598 { "ni", 0x220b }, 6604 { "ni", 0x220b },
6599 { "not", 0x00ac }, 6605 { "not", 0x00ac },
6600 { "notin", 0x2209 }, 6606 { "notin", 0x2209 },
6601 { "nsub", 0x2284 }, 6607 { "nsub", 0x2284 },
6602 { "ntilde", 0x00f1 }, 6608 { "ntilde", 0x00f1 },
6603 { "nu", 0x03bd }, 6609 { "nu", 0x03bd },
6604 { "oacute", 0x00f3 }, 6610 { "oacute", 0x00f3 },
6605 { "ocirc", 0x00f4 }, 6611 { "ocirc", 0x00f4 },
6606 { "oelig", 0x0153 }, 6612 { "oelig", 0x0153 },
6607 { "ograve", 0x00f2 }, 6613 { "ograve", 0x00f2 },
6608 { "oline", 0x203e }, 6614 { "oline", 0x203e },
6609 { "omega", 0x03c9 }, 6615 { "omega", 0x03c9 },
6610 { "omicron", 0x03bf }, 6616 { "omicron", 0x03bf },
6611 { "oplus", 0x2295 }, 6617 { "oplus", 0x2295 },
6612 { "or", 0x22a6 }, 6618 { "or", 0x22a6 },
6613 { "ordf", 0x00aa }, 6619 { "ordf", 0x00aa },
6614 { "ordm", 0x00ba }, 6620 { "ordm", 0x00ba },
6615 { "oslash", 0x00f8 }, 6621 { "oslash", 0x00f8 },
6616 { "otilde", 0x00f5 }, 6622 { "otilde", 0x00f5 },
6617 { "otimes", 0x2297 }, 6623 { "otimes", 0x2297 },
6618 { "ouml", 0x00f6 }, 6624 { "ouml", 0x00f6 },
6619 { "para", 0x00b6 }, 6625 { "para", 0x00b6 },
6620 { "part", 0x2202 }, 6626 { "part", 0x2202 },
6621 { "percnt", 0x0025 }, 6627 { "percnt", 0x0025 },
6622 { "permil", 0x2030 }, 6628 { "permil", 0x2030 },
6623 { "perp", 0x22a5 }, 6629 { "perp", 0x22a5 },
6624 { "phi", 0x03c6 }, 6630 { "phi", 0x03c6 },
6625 { "pi", 0x03c0 }, 6631 { "pi", 0x03c0 },
6626 { "piv", 0x03d6 }, 6632 { "piv", 0x03d6 },
6627 { "plusmn", 0x00b1 }, 6633 { "plusmn", 0x00b1 },
6628 { "pound", 0x00a3 }, 6634 { "pound", 0x00a3 },
6629 { "prime", 0x2032 }, 6635 { "prime", 0x2032 },
6630 { "prod", 0x220f }, 6636 { "prod", 0x220f },
6631 { "prop", 0x221d }, 6637 { "prop", 0x221d },
6632 { "psi", 0x03c8 }, 6638 { "psi", 0x03c8 },
6633 { "quot", 34 }, 6639 { "quot", 34 },
6634 { "rArr", 0x21d2 }, 6640 { "rArr", 0x21d2 },
6635 { "radic", 0x221a }, 6641 { "radic", 0x221a },
6636 { "rang", 0x232a }, 6642 { "rang", 0x232a },
6637 { "raquo", 0x00bb }, 6643 { "raquo", 0x00bb },
6638 { "rarr", 0x2192 }, 6644 { "rarr", 0x2192 },
6639 { "rceil", 0x2309 }, 6645 { "rceil", 0x2309 },
6640 { "rdquo", 0x201d }, 6646 { "rdquo", 0x201d },
6641 { "real", 0x211c }, 6647 { "real", 0x211c },
6642 { "reg", 0x00ae }, 6648 { "reg", 0x00ae },
6643 { "rfloor", 0x230b }, 6649 { "rfloor", 0x230b },
6644 { "rho", 0x03c1 }, 6650 { "rho", 0x03c1 },
6645 { "rlm", 0x200f }, 6651 { "rlm", 0x200f },
6646 { "rsaquo", 0x203a }, 6652 { "rsaquo", 0x203a },
6647 { "rsquo", 0x2019 }, 6653 { "rsquo", 0x2019 },
6648 { "sbquo", 0x201a }, 6654 { "sbquo", 0x201a },
6649 { "scaron", 0x0161 }, 6655 { "scaron", 0x0161 },
6650 { "sdot", 0x22c5 }, 6656 { "sdot", 0x22c5 },
6651 { "sect", 0x00a7 }, 6657 { "sect", 0x00a7 },
6652 { "shy", 0x00ad }, 6658 { "shy", 0x00ad },
6653 { "sigma", 0x03c3 }, 6659 { "sigma", 0x03c3 },
6654 { "sigmaf", 0x03c2 }, 6660 { "sigmaf", 0x03c2 },
6655 { "sim", 0x223c }, 6661 { "sim", 0x223c },
6656 { "spades", 0x2660 }, 6662 { "spades", 0x2660 },
6657 { "sub", 0x2282 }, 6663 { "sub", 0x2282 },
6658 { "sube", 0x2286 }, 6664 { "sube", 0x2286 },
6659 { "sum", 0x2211 }, 6665 { "sum", 0x2211 },
6660 { "sup1", 0x00b9 }, 6666 { "sup1", 0x00b9 },
6661 { "sup2", 0x00b2 }, 6667 { "sup2", 0x00b2 },
6662 { "sup3", 0x00b3 }, 6668 { "sup3", 0x00b3 },
6663 { "sup", 0x2283 }, 6669 { "sup", 0x2283 },
6664 { "supe", 0x2287 }, 6670 { "supe", 0x2287 },
6665 { "szlig", 0x00df }, 6671 { "szlig", 0x00df },
6666 { "tau", 0x03c4 }, 6672 { "tau", 0x03c4 },
6667 { "there4", 0x2234 }, 6673 { "there4", 0x2234 },
6668 { "theta", 0x03b8 }, 6674 { "theta", 0x03b8 },
6669 { "thetasym", 0x03d1 }, 6675 { "thetasym", 0x03d1 },
6670 { "thinsp", 0x2009 }, 6676 { "thinsp", 0x2009 },
6671 { "thorn", 0x00fe }, 6677 { "thorn", 0x00fe },
6672 { "tilde", 0x02dc }, 6678 { "tilde", 0x02dc },
6673 { "times", 0x00d7 }, 6679 { "times", 0x00d7 },
6674 { "trade", 0x2122 }, 6680 { "trade", 0x2122 },
6675 { "uArr", 0x21d1 }, 6681 { "uArr", 0x21d1 },
6676 { "uacute", 0x00fa }, 6682 { "uacute", 0x00fa },
6677 { "uarr", 0x2191 }, 6683 { "uarr", 0x2191 },
6678 { "ucirc", 0x00fb }, 6684 { "ucirc", 0x00fb },
6679 { "ugrave", 0x00f9 }, 6685 { "ugrave", 0x00f9 },
6680 { "uml", 0x00a8 }, 6686 { "uml", 0x00a8 },
6681 { "upsih", 0x03d2 }, 6687 { "upsih", 0x03d2 },
6682 { "upsilon", 0x03c5 }, 6688 { "upsilon", 0x03c5 },
6683 { "uuml", 0x00fc }, 6689 { "uuml", 0x00fc },
6684 { "weierp", 0x2118 }, 6690 { "weierp", 0x2118 },
6685 { "xi", 0x03be }, 6691 { "xi", 0x03be },
6686 { "yacute", 0x00fd }, 6692 { "yacute", 0x00fd },
6687 { "yen", 0x00a5 }, 6693 { "yen", 0x00a5 },
6688 { "yuml", 0x00ff }, 6694 { "yuml", 0x00ff },
6689 { "zeta", 0x03b6 }, 6695 { "zeta", 0x03b6 },
6690 { "zwj", 0x200d }, 6696 { "zwj", 0x200d },
6691 { "zwnj", 0x200c }, 6697 { "zwnj", 0x200c },
6692 { "", 0x0000 } 6698 { "", 0x0000 }
6693}; 6699};
6694 6700
6695 6701
6696 6702
6697 6703
6698 6704
6699static QMap<QCString, QChar> *html_map = 0; 6705static QMap<QCString, QChar> *html_map = 0;
6700static void qt_cleanup_html_map() 6706static void qt_cleanup_html_map()
6701{ 6707{
6702 delete html_map; 6708 delete html_map;
6703 html_map = 0; 6709 html_map = 0;
6704} 6710}
6705 6711
6706static QMap<QCString, QChar> *htmlMap() 6712static QMap<QCString, QChar> *htmlMap()
6707{ 6713{
6708 if ( !html_map ) { 6714 if ( !html_map ) {
6709 html_map = new QMap<QCString, QChar>; 6715 html_map = new QMap<QCString, QChar>;
6710 qAddPostRoutine( qt_cleanup_html_map ); 6716 qAddPostRoutine( qt_cleanup_html_map );
6711 6717
6712 const Entity *ent = entitylist; 6718 const Entity *ent = entitylist;
6713 while( ent->code ) { 6719 while( ent->code ) {
6714 html_map->insert( ent->name, QChar(ent->code) ); 6720 html_map->insert( ent->name, QChar(ent->code) );
6715 ent++; 6721 ent++;
6716 } 6722 }
6717 } 6723 }
6718 return html_map; 6724 return html_map;
6719} 6725}
6720 6726
6721QChar QTextDocument::parseHTMLSpecialChar(const QChar* doc, int length, int& pos) 6727QChar QTextDocument::parseHTMLSpecialChar(const QChar* doc, int length, int& pos)
6722{ 6728{
6723 QCString s; 6729 QCString s;
6724 pos++; 6730 pos++;
6725 int recoverpos = pos; 6731 int recoverpos = pos;
6726 while ( pos < length && doc[pos] != ';' && !doc[pos].isSpace() && pos < recoverpos + 6) { 6732 while ( pos < length && doc[pos] != ';' && !doc[pos].isSpace() && pos < recoverpos + 6) {
6727 s += doc[pos]; 6733 s += doc[pos];
6728 pos++; 6734 pos++;
6729 } 6735 }
6730 if (doc[pos] != ';' && !doc[pos].isSpace() ) { 6736 if (doc[pos] != ';' && !doc[pos].isSpace() ) {
6731 pos = recoverpos; 6737 pos = recoverpos;
6732 return '&'; 6738 return '&';
6733 } 6739 }
6734 pos++; 6740 pos++;
6735 6741
6736 if ( s.length() > 1 && s[0] == '#') { 6742 if ( s.length() > 1 && s[0] == '#') {
6737 int num = s.mid(1).toInt(); 6743 int num = s.mid(1).toInt();
6738 if ( num == 151 ) // ### hack for designer manual 6744 if ( num == 151 ) // ### hack for designer manual
6739 return '-'; 6745 return '-';
6740 return num; 6746 return num;
6741 } 6747 }
6742 6748
6743 QMap<QCString, QChar>::Iterator it = htmlMap()->find(s); 6749 QMap<QCString, QChar>::Iterator it = htmlMap()->find(s);
6744 if ( it != htmlMap()->end() ) { 6750 if ( it != htmlMap()->end() ) {
6745 return *it; 6751 return *it;
6746 } 6752 }
6747 6753
6748 pos = recoverpos; 6754 pos = recoverpos;
6749 return '&'; 6755 return '&';
6750} 6756}
6751 6757
6752QString QTextDocument::parseWord(const QChar* doc, int length, int& pos, bool lower) 6758QString QTextDocument::parseWord(const QChar* doc, int length, int& pos, bool lower)
6753{ 6759{
6754 QString s; 6760 QString s;
6755 6761
6756 if (doc[pos] == '"') { 6762 if (doc[pos] == '"') {
6757 pos++; 6763 pos++;
6758 while ( pos < length && doc[pos] != '"' ) { 6764 while ( pos < length && doc[pos] != '"' ) {
6759 s += doc[pos]; 6765 s += doc[pos];
6760 pos++; 6766 pos++;
6761 } 6767 }
6762 eat(doc, length, pos, '"'); 6768 eat(doc, length, pos, '"');
6763 } else { 6769 } else {
6764 static QString term = QString::fromLatin1("/>"); 6770 static QString term = QString::fromLatin1("/>");
6765 while( pos < length && 6771 while( pos < length &&
6766 (doc[pos] != '>' && !hasPrefix( doc, length, pos, term)) 6772 (doc[pos] != '>' && !hasPrefix( doc, length, pos, term))
6767 && doc[pos] != '<' 6773 && doc[pos] != '<'
6768 && doc[pos] != '=' 6774 && doc[pos] != '='
6769 && !doc[pos].isSpace()) 6775 && !doc[pos].isSpace())
6770 { 6776 {
6771 if ( doc[pos] == '&') 6777 if ( doc[pos] == '&')
6772 s += parseHTMLSpecialChar( doc, length, pos ); 6778 s += parseHTMLSpecialChar( doc, length, pos );
6773 else { 6779 else {
6774 s += doc[pos]; 6780 s += doc[pos];
6775 pos++; 6781 pos++;
6776 } 6782 }
6777 } 6783 }
6778 if (lower) 6784 if (lower)
6779 s = s.lower(); 6785 s = s.lower();
6780 } 6786 }
6781 return s; 6787 return s;
6782} 6788}
6783 6789
6784QChar QTextDocument::parseChar(const QChar* doc, int length, int& pos, QStyleSheetItem::WhiteSpaceMode wsm ) 6790QChar QTextDocument::parseChar(const QChar* doc, int length, int& pos, QStyleSheetItem::WhiteSpaceMode wsm )
6785{ 6791{
6786 if ( pos >= length ) 6792 if ( pos >= length )
6787 return QChar::null; 6793 return QChar::null;
6788 6794
6789 QChar c = doc[pos++]; 6795 QChar c = doc[pos++];
6790 6796
6791 if (c == '<' ) 6797 if (c == '<' )
6792 return QChar::null; 6798 return QChar::null;
6793 6799
6794 if ( c.isSpace() && c != QChar::nbsp ) { 6800 if ( c.isSpace() && c != QChar::nbsp ) {
6795 if ( wsm == QStyleSheetItem::WhiteSpacePre ) { 6801 if ( wsm == QStyleSheetItem::WhiteSpacePre ) {
6796 if ( c == '\n' ) 6802 if ( c == '\n' )
6797 return QChar_linesep; 6803 return QChar_linesep;
6798 else 6804 else
6799 return c; 6805 return c;
6800 } else { // non-pre mode: collapse whitespace except nbsp 6806 } else { // non-pre mode: collapse whitespace except nbsp
6801 while ( pos< length && 6807 while ( pos< length &&
6802 doc[pos].isSpace() && doc[pos] != QChar::nbsp ) 6808 doc[pos].isSpace() && doc[pos] != QChar::nbsp )
6803 pos++; 6809 pos++;
6804 if ( wsm == QStyleSheetItem::WhiteSpaceNoWrap ) 6810 if ( wsm == QStyleSheetItem::WhiteSpaceNoWrap )
6805 return QChar::nbsp; 6811 return QChar::nbsp;
6806 else 6812 else
6807 return ' '; 6813 return ' ';
6808 } 6814 }
6809 } 6815 }
6810 else if ( c == '&' ) 6816 else if ( c == '&' )
6811 return parseHTMLSpecialChar( doc, length, --pos ); 6817 return parseHTMLSpecialChar( doc, length, --pos );
6812 else 6818 else
6813 return c; 6819 return c;
6814} 6820}
6815 6821
6816QString QTextDocument::parseOpenTag(const QChar* doc, int length, int& pos, 6822QString QTextDocument::parseOpenTag(const QChar* doc, int length, int& pos,
6817 QMap<QString, QString> &attr, bool& emptyTag) 6823 QMap<QString, QString> &attr, bool& emptyTag)
6818{ 6824{
6819 emptyTag = FALSE; 6825 emptyTag = FALSE;
6820 pos++; 6826 pos++;
6821 if ( hasPrefix(doc, length, pos, '!') ) { 6827 if ( hasPrefix(doc, length, pos, '!') ) {
6822 if ( hasPrefix( doc, length, pos+1, "--")) { 6828 if ( hasPrefix( doc, length, pos+1, "--")) {
6823 pos += 3; 6829 pos += 3;
6824 // eat comments 6830 // eat comments
6825 QString pref = QString::fromLatin1("-->"); 6831 QString pref = QString::fromLatin1("-->");
6826 while ( !hasPrefix(doc, length, pos, pref ) && pos < length ) 6832 while ( !hasPrefix(doc, length, pos, pref ) && pos < length )
6827 pos++; 6833 pos++;
6828 if ( hasPrefix(doc, length, pos, pref ) ) { 6834 if ( hasPrefix(doc, length, pos, pref ) ) {
6829 pos += 3; 6835 pos += 3;
6830 eatSpace(doc, length, pos, TRUE); 6836 eatSpace(doc, length, pos, TRUE);
6831 } 6837 }
6832 emptyTag = TRUE; 6838 emptyTag = TRUE;
6833 return QString::null; 6839 return QString::null;
6834 } 6840 }
6835 else { 6841 else {
6836 // eat strange internal tags 6842 // eat strange internal tags
6837 while ( !hasPrefix(doc, length, pos, '>') && pos < length ) 6843 while ( !hasPrefix(doc, length, pos, '>') && pos < length )
6838 pos++; 6844 pos++;
6839 if ( hasPrefix(doc, length, pos, '>') ) { 6845 if ( hasPrefix(doc, length, pos, '>') ) {
6840 pos++; 6846 pos++;
6841 eatSpace(doc, length, pos, TRUE); 6847 eatSpace(doc, length, pos, TRUE);
6842 } 6848 }
6843 return QString::null; 6849 return QString::null;
6844 } 6850 }
6845 } 6851 }
6846 6852
6847 QString tag = parseWord(doc, length, pos ); 6853 QString tag = parseWord(doc, length, pos );
6848 eatSpace(doc, length, pos, TRUE); 6854 eatSpace(doc, length, pos, TRUE);
6849 static QString term = QString::fromLatin1("/>"); 6855 static QString term = QString::fromLatin1("/>");
6850 static QString s_TRUE = QString::fromLatin1("TRUE"); 6856 static QString s_TRUE = QString::fromLatin1("TRUE");
6851 6857
6852 while (doc[pos] != '>' && ! (emptyTag = hasPrefix(doc, length, pos, term) )) { 6858 while (doc[pos] != '>' && ! (emptyTag = hasPrefix(doc, length, pos, term) )) {
6853 QString key = parseWord(doc, length, pos ); 6859 QString key = parseWord(doc, length, pos );
6854 eatSpace(doc, length, pos, TRUE); 6860 eatSpace(doc, length, pos, TRUE);
6855 if ( key.isEmpty()) { 6861 if ( key.isEmpty()) {
6856 // error recovery 6862 // error recovery
6857 while ( pos < length && doc[pos] != '>' ) 6863 while ( pos < length && doc[pos] != '>' )
6858 pos++; 6864 pos++;
6859 break; 6865 break;
6860 } 6866 }
6861 QString value; 6867 QString value;
6862 if (hasPrefix(doc, length, pos, '=') ){ 6868 if (hasPrefix(doc, length, pos, '=') ){
6863 pos++; 6869 pos++;
6864 eatSpace(doc, length, pos); 6870 eatSpace(doc, length, pos);
6865 value = parseWord(doc, length, pos, FALSE); 6871 value = parseWord(doc, length, pos, FALSE);
6866 } 6872 }
6867 else 6873 else
6868 value = s_TRUE; 6874 value = s_TRUE;
6869 attr.insert(key.lower(), value ); 6875 attr.insert(key.lower(), value );
6870 eatSpace(doc, length, pos, TRUE); 6876 eatSpace(doc, length, pos, TRUE);
6871 } 6877 }
6872 6878
6873 if (emptyTag) { 6879 if (emptyTag) {
6874 eat(doc, length, pos, '/'); 6880 eat(doc, length, pos, '/');
6875 eat(doc, length, pos, '>'); 6881 eat(doc, length, pos, '>');
6876 } 6882 }
6877 else 6883 else
6878 eat(doc, length, pos, '>'); 6884 eat(doc, length, pos, '>');
6879 6885
6880 return tag; 6886 return tag;
6881} 6887}
6882 6888
6883QString QTextDocument::parseCloseTag( const QChar* doc, int length, int& pos ) 6889QString QTextDocument::parseCloseTag( const QChar* doc, int length, int& pos )
6884{ 6890{
6885 pos++; 6891 pos++;
6886 pos++; 6892 pos++;
6887 QString tag = parseWord(doc, length, pos ); 6893 QString tag = parseWord(doc, length, pos );
6888 eatSpace(doc, length, pos, TRUE); 6894 eatSpace(doc, length, pos, TRUE);
6889 eat(doc, length, pos, '>'); 6895 eat(doc, length, pos, '>');
6890 return tag; 6896 return tag;
6891} 6897}
6892 6898
6893QTextFlow::QTextFlow() 6899QTextFlow::QTextFlow()
6894{ 6900{
6895 w = pagesize = 0; 6901 w = pagesize = 0;
6896 leftItems.setAutoDelete( FALSE ); 6902 leftItems.setAutoDelete( FALSE );
6897 rightItems.setAutoDelete( FALSE ); 6903 rightItems.setAutoDelete( FALSE );
6898} 6904}
6899 6905
6900QTextFlow::~QTextFlow() 6906QTextFlow::~QTextFlow()
6901{ 6907{
6902} 6908}
6903 6909
6904void QTextFlow::clear() 6910void QTextFlow::clear()
6905{ 6911{
6906 leftItems.clear(); 6912 leftItems.clear();
6907 rightItems.clear(); 6913 rightItems.clear();
6908} 6914}
6909 6915
6910void QTextFlow::setWidth( int width ) 6916void QTextFlow::setWidth( int width )
6911{ 6917{
6912 w = width; 6918 w = width;
6913} 6919}
6914 6920
6915int QTextFlow::adjustLMargin( int yp, int, int margin, int space ) 6921int QTextFlow::adjustLMargin( int yp, int, int margin, int space )
6916{ 6922{
6917 for ( QTextCustomItem* item = leftItems.first(); item; item = leftItems.next() ) { 6923 for ( QTextCustomItem* item = leftItems.first(); item; item = leftItems.next() ) {
6918 if ( item->ypos == -1 ) 6924 if ( item->ypos == -1 )
6919 continue; 6925 continue;
6920 if ( yp >= item->ypos && yp < item->ypos + item->height ) 6926 if ( yp >= item->ypos && yp < item->ypos + item->height )
6921 margin = QMAX( margin, item->xpos + item->width + space ); 6927 margin = QMAX( margin, item->xpos + item->width + space );
6922 } 6928 }
6923 return margin; 6929 return margin;
6924} 6930}
6925 6931
6926int QTextFlow::adjustRMargin( int yp, int, int margin, int space ) 6932int QTextFlow::adjustRMargin( int yp, int, int margin, int space )
6927{ 6933{
6928 for ( QTextCustomItem* item = rightItems.first(); item; item = rightItems.next() ) { 6934 for ( QTextCustomItem* item = rightItems.first(); item; item = rightItems.next() ) {
6929 if ( item->ypos == -1 ) 6935 if ( item->ypos == -1 )
6930 continue; 6936 continue;
6931 if ( yp >= item->ypos && yp < item->ypos + item->height ) 6937 if ( yp >= item->ypos && yp < item->ypos + item->height )
6932 margin = QMAX( margin, w - item->xpos - space ); 6938 margin = QMAX( margin, w - item->xpos - space );
6933 } 6939 }
6934 return margin; 6940 return margin;
6935} 6941}
6936 6942
6937 6943
6938int QTextFlow::adjustFlow( int y, int /*w*/, int h ) 6944int QTextFlow::adjustFlow( int y, int /*w*/, int h )
6939{ 6945{
6940 if ( pagesize > 0 ) { // check pages 6946 if ( pagesize > 0 ) { // check pages
6941 int yinpage = y % pagesize; 6947 int yinpage = y % pagesize;
6942 if ( yinpage <= border_tolerance ) 6948 if ( yinpage <= border_tolerance )
6943 return border_tolerance - yinpage; 6949 return border_tolerance - yinpage;
6944 else 6950 else
6945 if ( yinpage + h > pagesize - border_tolerance ) 6951 if ( yinpage + h > pagesize - border_tolerance )
6946 return ( pagesize - yinpage ) + border_tolerance; 6952 return ( pagesize - yinpage ) + border_tolerance;
6947 } 6953 }
6948 return 0; 6954 return 0;
6949} 6955}
6950 6956
6951void QTextFlow::unregisterFloatingItem( QTextCustomItem* item ) 6957void QTextFlow::unregisterFloatingItem( QTextCustomItem* item )
6952{ 6958{
6953 leftItems.removeRef( item ); 6959 leftItems.removeRef( item );
6954 rightItems.removeRef( item ); 6960 rightItems.removeRef( item );
6955} 6961}
6956 6962
6957void QTextFlow::registerFloatingItem( QTextCustomItem* item ) 6963void QTextFlow::registerFloatingItem( QTextCustomItem* item )
6958{ 6964{
6959 if ( item->placement() == QTextCustomItem::PlaceRight ) { 6965 if ( item->placement() == QTextCustomItem::PlaceRight ) {
6960 if ( !rightItems.contains( item ) ) 6966 if ( !rightItems.contains( item ) )
6961 rightItems.append( item ); 6967 rightItems.append( item );
6962 } else if ( item->placement() == QTextCustomItem::PlaceLeft && 6968 } else if ( item->placement() == QTextCustomItem::PlaceLeft &&
6963 !leftItems.contains( item ) ) { 6969 !leftItems.contains( item ) ) {
6964 leftItems.append( item ); 6970 leftItems.append( item );
6965 } 6971 }
6966} 6972}
6967 6973
6968QRect QTextFlow::boundingRect() const 6974QRect QTextFlow::boundingRect() const
6969{ 6975{
6970 QRect br; 6976 QRect br;
6971 QPtrListIterator<QTextCustomItem> l( leftItems ); 6977 QPtrListIterator<QTextCustomItem> l( leftItems );
6972 while( l.current() ) { 6978 while( l.current() ) {
6973 br = br.unite( l.current()->geometry() ); 6979 br = br.unite( l.current()->geometry() );
6974 ++l; 6980 ++l;
6975 } 6981 }
6976 QPtrListIterator<QTextCustomItem> r( rightItems ); 6982 QPtrListIterator<QTextCustomItem> r( rightItems );
6977 while( r.current() ) { 6983 while( r.current() ) {
6978 br = br.unite( r.current()->geometry() ); 6984 br = br.unite( r.current()->geometry() );
6979 ++r; 6985 ++r;
6980 } 6986 }
6981 return br; 6987 return br;
6982} 6988}
6983 6989
6984 6990
6985void QTextFlow::drawFloatingItems( QPainter* p, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool selected ) 6991void QTextFlow::drawFloatingItems( QPainter* p, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool selected )
6986{ 6992{
6987 QTextCustomItem *item; 6993 QTextCustomItem *item;
6988 for ( item = leftItems.first(); item; item = leftItems.next() ) { 6994 for ( item = leftItems.first(); item; item = leftItems.next() ) {
6989 if ( item->xpos == -1 || item->ypos == -1 ) 6995 if ( item->xpos == -1 || item->ypos == -1 )
6990 continue; 6996 continue;
6991 item->draw( p, item->xpos, item->ypos, cx, cy, cw, ch, cg, selected ); 6997 item->draw( p, item->xpos, item->ypos, cx, cy, cw, ch, cg, selected );
6992 } 6998 }
6993 6999
6994 for ( item = rightItems.first(); item; item = rightItems.next() ) { 7000 for ( item = rightItems.first(); item; item = rightItems.next() ) {
6995 if ( item->xpos == -1 || item->ypos == -1 ) 7001 if ( item->xpos == -1 || item->ypos == -1 )
6996 continue; 7002 continue;
6997 item->draw( p, item->xpos, item->ypos, cx, cy, cw, ch, cg, selected ); 7003 item->draw( p, item->xpos, item->ypos, cx, cy, cw, ch, cg, selected );
6998 } 7004 }
6999} 7005}
7000 7006
7001// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 7007// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7002 7008
7003void QTextCustomItem::pageBreak( int /*y*/ , QTextFlow* /*flow*/ ) 7009void QTextCustomItem::pageBreak( int /*y*/ , QTextFlow* /*flow*/ )
7004{ 7010{
7005} 7011}
7006 7012
7007QTextTable::QTextTable( QTextDocument *p, const QMap<QString, QString> & attr ) 7013QTextTable::QTextTable( QTextDocument *p, const QMap<QString, QString> & attr )
7008 : QTextCustomItem( p ) 7014 : QTextCustomItem( p )
7009{ 7015{
7010 cells.setAutoDelete( FALSE ); 7016 cells.setAutoDelete( FALSE );
7011 cellspacing = 2; 7017 cellspacing = 2;
7012 if ( attr.contains("cellspacing") ) 7018 if ( attr.contains("cellspacing") )
7013 cellspacing = attr["cellspacing"].toInt(); 7019 cellspacing = attr["cellspacing"].toInt();
7014 cellpadding = 1; 7020 cellpadding = 1;
7015 if ( attr.contains("cellpadding") ) 7021 if ( attr.contains("cellpadding") )
7016 cellpadding = attr["cellpadding"].toInt(); 7022 cellpadding = attr["cellpadding"].toInt();
7017 border = innerborder = 0; 7023 border = innerborder = 0;
7018 if ( attr.contains("border" ) ) { 7024 if ( attr.contains("border" ) ) {
7019 QString s( attr["border"] ); 7025 QString s( attr["border"] );
7020 if ( s == "TRUE" ) 7026 if ( s == "TRUE" )
7021 border = 1; 7027 border = 1;
7022 else 7028 else
7023 border = attr["border"].toInt(); 7029 border = attr["border"].toInt();
7024 } 7030 }
7025 us_b = border; 7031 us_b = border;
7026 7032
7027 innerborder = us_ib = border ? 1 : 0; 7033 innerborder = us_ib = border ? 1 : 0;
7028 7034
7029 if ( border ) 7035 if ( border )
7030 cellspacing += 2; 7036 cellspacing += 2;
7031 7037
7032 us_ib = innerborder; 7038 us_ib = innerborder;
7033 us_cs = cellspacing; 7039 us_cs = cellspacing;
7034 us_cp = cellpadding; 7040 us_cp = cellpadding;
7035 outerborder = cellspacing + border; 7041 outerborder = cellspacing + border;
7036 us_ob = outerborder; 7042 us_ob = outerborder;
7037 layout = new QGridLayout( 1, 1, cellspacing ); 7043 layout = new QGridLayout( 1, 1, cellspacing );
7038 7044
7039 fixwidth = 0; 7045 fixwidth = 0;
7040 stretch = 0; 7046 stretch = 0;
7041 if ( attr.contains("width") ) { 7047 if ( attr.contains("width") ) {
7042 bool b; 7048 bool b;
7043 QString s( attr["width"] ); 7049 QString s( attr["width"] );
7044 int w = s.toInt( &b ); 7050 int w = s.toInt( &b );
7045 if ( b ) { 7051 if ( b ) {
7046 fixwidth = w; 7052 fixwidth = w;
7047 } else { 7053 } else {
7048 s = s.stripWhiteSpace(); 7054 s = s.stripWhiteSpace();
7049 if ( s.length() > 1 && s[ (int)s.length()-1 ] == '%' ) 7055 if ( s.length() > 1 && s[ (int)s.length()-1 ] == '%' )
7050 stretch = s.left( s.length()-1).toInt(); 7056 stretch = s.left( s.length()-1).toInt();
7051 } 7057 }
7052 } 7058 }
7053 7059
7054 place = PlaceInline; 7060 place = PlaceInline;
7055 if ( attr["align"] == "left" ) 7061 if ( attr["align"] == "left" )
7056 place = PlaceLeft; 7062 place = PlaceLeft;
7057 else if ( attr["align"] == "right" ) 7063 else if ( attr["align"] == "right" )
7058 place = PlaceRight; 7064 place = PlaceRight;
7059 cachewidth = 0; 7065 cachewidth = 0;
7060 attributes = attr; 7066 attributes = attr;
7061 pageBreakFor = -1; 7067 pageBreakFor = -1;
7062} 7068}
7063 7069
7064QTextTable::~QTextTable() 7070QTextTable::~QTextTable()
7065{ 7071{
7066 delete layout; 7072 delete layout;
7067} 7073}
7068 7074
7069QString QTextTable::richText() const 7075QString QTextTable::richText() const
7070{ 7076{
7071 QString s; 7077 QString s;
7072 s = "<table "; 7078 s = "<table ";
7073 QMap<QString, QString>::ConstIterator it = attributes.begin(); 7079 QMap<QString, QString>::ConstIterator it = attributes.begin();
7074 for ( ; it != attributes.end(); ++it ) 7080 for ( ; it != attributes.end(); ++it )
7075 s += it.key() + "=" + *it + " "; 7081 s += it.key() + "=" + *it + " ";
7076 s += ">\n"; 7082 s += ">\n";
7077 7083
7078 int lastRow = -1; 7084 int lastRow = -1;
7079 bool needEnd = FALSE; 7085 bool needEnd = FALSE;
7080 QPtrListIterator<QTextTableCell> it2( cells ); 7086 QPtrListIterator<QTextTableCell> it2( cells );
7081 while ( it2.current() ) { 7087 while ( it2.current() ) {
7082 QTextTableCell *cell = it2.current(); 7088 QTextTableCell *cell = it2.current();
7083 ++it2; 7089 ++it2;
7084 if ( lastRow != cell->row() ) { 7090 if ( lastRow != cell->row() ) {
7085 if ( lastRow != -1 ) 7091 if ( lastRow != -1 )
7086 s += "</tr>\n"; 7092 s += "</tr>\n";
7087 s += "<tr>"; 7093 s += "<tr>";
7088 lastRow = cell->row(); 7094 lastRow = cell->row();
7089 needEnd = TRUE; 7095 needEnd = TRUE;
7090 } 7096 }
7091 s += "<td"; 7097 s += "<td";
7092 it = cell->attributes.begin(); 7098 it = cell->attributes.begin();
7093 for ( ; it != cell->attributes.end(); ++it ) 7099 for ( ; it != cell->attributes.end(); ++it )
7094 s += " " + it.key() + "=" + *it; 7100 s += " " + it.key() + "=" + *it;
7095 s += ">"; 7101 s += ">";
7096 s += cell->richText()->richText(); 7102 s += cell->richText()->richText();
7097 s += "</td>"; 7103 s += "</td>";
7098 } 7104 }
7099 if ( needEnd ) 7105 if ( needEnd )
7100 s += "</tr>\n"; 7106 s += "</tr>\n";
7101 s += "</table>\n"; 7107 s += "</table>\n";
7102 return s; 7108 return s;
7103} 7109}
7104 7110
7105void QTextTable::adjustToPainter( QPainter* p ) 7111void QTextTable::adjustToPainter( QPainter* p )
7106{ 7112{
7107 cellspacing = scale( us_cs, p ); 7113 cellspacing = scale( us_cs, p );
7108 cellpadding = scale( us_cp, p ); 7114 cellpadding = scale( us_cp, p );
7109 border = scale( us_b , p ); 7115 border = scale( us_b , p );
7110 innerborder = scale( us_ib, p ); 7116 innerborder = scale( us_ib, p );
7111 outerborder = scale( us_ob ,p ); 7117 outerborder = scale( us_ob ,p );
7112 width = 0; 7118 width = 0;
7113 cachewidth = 0; 7119 cachewidth = 0;
7114 for ( QTextTableCell* cell = cells.first(); cell; cell = cells.next() ) 7120 for ( QTextTableCell* cell = cells.first(); cell; cell = cells.next() )
7115 cell->adjustToPainter( p ); 7121 cell->adjustToPainter( p );
7116} 7122}
7117 7123
7118void QTextTable::adjustCells( int y , int shift ) 7124void QTextTable::adjustCells( int y , int shift )
7119{ 7125{
7120 QPtrListIterator<QTextTableCell> it( cells ); 7126 QPtrListIterator<QTextTableCell> it( cells );
7121 QTextTableCell* cell; 7127 QTextTableCell* cell;
7122 bool enlarge = FALSE; 7128 bool enlarge = FALSE;
7123 while ( ( cell = it.current() ) ) { 7129 while ( ( cell = it.current() ) ) {
7124 ++it; 7130 ++it;
7125 QRect r = cell->geometry(); 7131 QRect r = cell->geometry();
7126 if ( y <= r.top() ) { 7132 if ( y <= r.top() ) {
7127 r.moveBy(0, shift ); 7133 r.moveBy(0, shift );
7128 cell->setGeometry( r ); 7134 cell->setGeometry( r );
7129 enlarge = TRUE; 7135 enlarge = TRUE;
7130 } else if ( y <= r.bottom() ) { 7136 } else if ( y <= r.bottom() ) {
7131 r.rBottom() += shift; 7137 r.rBottom() += shift;
7132 cell->setGeometry( r ); 7138 cell->setGeometry( r );
7133 enlarge = TRUE; 7139 enlarge = TRUE;
7134 } 7140 }
7135 } 7141 }
7136 if ( enlarge ) 7142 if ( enlarge )
7137 height += shift; 7143 height += shift;
7138} 7144}
7139 7145
7140void QTextTable::pageBreak( int yt, QTextFlow* flow ) 7146void QTextTable::pageBreak( int yt, QTextFlow* flow )
7141{ 7147{
7142 if ( flow->pageSize() <= 0 ) 7148 if ( flow->pageSize() <= 0 )
7143 return; 7149 return;
7144 if ( layout && pageBreakFor > 0 && pageBreakFor != yt ) { 7150 if ( layout && pageBreakFor > 0 && pageBreakFor != yt ) {
7145 layout->invalidate(); 7151 layout->invalidate();
7146 int h = layout->heightForWidth( width-2*outerborder ); 7152 int h = layout->heightForWidth( width-2*outerborder );
7147 layout->setGeometry( QRect(0, 0, width-2*outerborder, h) ); 7153 layout->setGeometry( QRect(0, 0, width-2*outerborder, h) );
7148 height = layout->geometry().height()+2*outerborder; 7154 height = layout->geometry().height()+2*outerborder;
7149 } 7155 }
7150 pageBreakFor = yt; 7156 pageBreakFor = yt;
7151 QPtrListIterator<QTextTableCell> it( cells ); 7157 QPtrListIterator<QTextTableCell> it( cells );
7152 QTextTableCell* cell; 7158 QTextTableCell* cell;
7153 while ( ( cell = it.current() ) ) { 7159 while ( ( cell = it.current() ) ) {
7154 ++it; 7160 ++it;
7155 int y = yt + outerborder + cell->geometry().y(); 7161 int y = yt + outerborder + cell->geometry().y();
7156 int shift = flow->adjustFlow( y - cellspacing, width, cell->richText()->height() + 2*cellspacing ); 7162 int shift = flow->adjustFlow( y - cellspacing, width, cell->richText()->height() + 2*cellspacing );
7157 adjustCells( y - outerborder - yt, shift ); 7163 adjustCells( y - outerborder - yt, shift );
7158 } 7164 }
7159} 7165}
7160 7166
7161 7167
7162void QTextTable::draw(QPainter* p, int x, int y, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool selected ) 7168void QTextTable::draw(QPainter* p, int x, int y, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool selected )
7163{ 7169{
7164 if ( placement() != PlaceInline ) { 7170 if ( placement() != PlaceInline ) {
7165 x = xpos; 7171 x = xpos;
7166 y = ypos; 7172 y = ypos;
7167 } 7173 }
7168 7174
7169 for (QTextTableCell* cell = cells.first(); cell; cell = cells.next() ) { 7175 for (QTextTableCell* cell = cells.first(); cell; cell = cells.next() ) {
7170 if ( cx < 0 && cy < 0 || 7176 if ( cx < 0 && cy < 0 ||
7171 QRect( cx, cy, cw, ch ).intersects( QRect( x + outerborder + cell->geometry().x(), 7177 QRect( cx, cy, cw, ch ).intersects( QRect( x + outerborder + cell->geometry().x(),
7172 y + outerborder + cell->geometry().y(), 7178 y + outerborder + cell->geometry().y(),
7173 cell->geometry().width(), cell->geometry().height() ) ) ) { 7179 cell->geometry().width(), cell->geometry().height() ) ) ) {
7174 cell->draw( p, x+outerborder, y+outerborder, cx, cy, cw, ch, cg, selected ); 7180 cell->draw( p, x+outerborder, y+outerborder, cx, cy, cw, ch, cg, selected );
7175 if ( border ) { 7181 if ( border ) {
7176 QRect r( x+outerborder+cell->geometry().x() - innerborder, 7182 QRect r( x+outerborder+cell->geometry().x() - innerborder,
7177 y+outerborder+cell->geometry().y() - innerborder, 7183 y+outerborder+cell->geometry().y() - innerborder,
7178 cell->geometry().width() + 2 * innerborder, 7184 cell->geometry().width() + 2 * innerborder,
7179 cell->geometry().height() + 2 * innerborder ); 7185 cell->geometry().height() + 2 * innerborder );
7180 if ( is_printer( p ) ) { 7186 if ( is_printer( p ) ) {
7181 QPen oldPen = p->pen(); 7187 QPen oldPen = p->pen();
7182 QRect r2 = r; 7188 QRect r2 = r;
7183 r2.setLeft( r2.left() + innerborder/2 ); 7189 r2.setLeft( r2.left() + innerborder/2 );
7184 r2.setTop( r2.top() + innerborder/2 ); 7190 r2.setTop( r2.top() + innerborder/2 );
7185 r2.setRight( r2.right() - innerborder/2 ); 7191 r2.setRight( r2.right() - innerborder/2 );
7186 r2.setBottom( r2.bottom() - innerborder/2 ); 7192 r2.setBottom( r2.bottom() - innerborder/2 );
7187 p->setPen( QPen( cg.text(), innerborder ) ); 7193 p->setPen( QPen( cg.text(), innerborder ) );
7188 p->drawRect( r2 ); 7194 p->drawRect( r2 );
7189 p->setPen( oldPen ); 7195 p->setPen( oldPen );
7190 } else { 7196 } else {
7191 int s = QMAX( cellspacing-2*innerborder, 0); 7197 int s = QMAX( cellspacing-2*innerborder, 0);
7192 if ( s ) { 7198 if ( s ) {
7193 p->fillRect( r.left()-s, r.top(), s+1, r.height(), cg.button() ); 7199 p->fillRect( r.left()-s, r.top(), s+1, r.height(), cg.button() );
7194 p->fillRect( r.right(), r.top(), s+1, r.height(), cg.button() ); 7200 p->fillRect( r.right(), r.top(), s+1, r.height(), cg.button() );
7195 p->fillRect( r.left()-s, r.top()-s, r.width()+2*s, s, cg.button() ); 7201 p->fillRect( r.left()-s, r.top()-s, r.width()+2*s, s, cg.button() );
7196 p->fillRect( r.left()-s, r.bottom(), r.width()+2*s, s, cg.button() ); 7202 p->fillRect( r.left()-s, r.bottom(), r.width()+2*s, s, cg.button() );
7197 } 7203 }
7198 qDrawShadePanel( p, r, cg, TRUE, innerborder ); 7204 qDrawShadePanel( p, r, cg, TRUE, innerborder );
7199 } 7205 }
7200 } 7206 }
7201 } 7207 }
7202 } 7208 }
7203 if ( border ) { 7209 if ( border ) {
7204 QRect r ( x, y, width, height ); 7210 QRect r ( x, y, width, height );
7205 if ( is_printer( p ) ) { 7211 if ( is_printer( p ) ) {
7206 QRect r2 = r; 7212 QRect r2 = r;
7207 r2.setLeft( r2.left() + border/2 ); 7213 r2.setLeft( r2.left() + border/2 );
7208 r2.setTop( r2.top() + border/2 ); 7214 r2.setTop( r2.top() + border/2 );
7209 r2.setRight( r2.right() - border/2 ); 7215 r2.setRight( r2.right() - border/2 );
7210 r2.setBottom( r2.bottom() - border/2 ); 7216 r2.setBottom( r2.bottom() - border/2 );
7211 QPen oldPen = p->pen(); 7217 QPen oldPen = p->pen();
7212 p->setPen( QPen( cg.text(), border ) ); 7218 p->setPen( QPen( cg.text(), border ) );
7213 p->drawRect( r2 ); 7219 p->drawRect( r2 );
7214 p->setPen( oldPen ); 7220 p->setPen( oldPen );
7215 } else { 7221 } else {
7216 int s = border+QMAX( cellspacing-2*innerborder, 0); 7222 int s = border+QMAX( cellspacing-2*innerborder, 0);
7217 if ( s ) { 7223 if ( s ) {
7218 p->fillRect( r.left(), r.top(), s, r.height(), cg.button() ); 7224 p->fillRect( r.left(), r.top(), s, r.height(), cg.button() );
7219 p->fillRect( r.right()-s, r.top(), s, r.height(), cg.button() ); 7225 p->fillRect( r.right()-s, r.top(), s, r.height(), cg.button() );
7220 p->fillRect( r.left(), r.top(), r.width(), s, cg.button() ); 7226 p->fillRect( r.left(), r.top(), r.width(), s, cg.button() );
7221 p->fillRect( r.left(), r.bottom()-s, r.width(), s, cg.button() ); 7227 p->fillRect( r.left(), r.bottom()-s, r.width(), s, cg.button() );
7222 } 7228 }
7223 qDrawShadePanel( p, r, cg, FALSE, border ); 7229 qDrawShadePanel( p, r, cg, FALSE, border );
7224 } 7230 }
7225 } 7231 }
7226 7232
7227} 7233}
7228 7234
7229int QTextTable::minimumWidth() const 7235int QTextTable::minimumWidth() const
7230{ 7236{
7231 return (layout ? layout->minimumSize().width() : 0) + 2 * outerborder; 7237 return (layout ? layout->minimumSize().width() : 0) + 2 * outerborder;
7232} 7238}
7233 7239
7234void QTextTable::resize( int nwidth ) 7240void QTextTable::resize( int nwidth )
7235{ 7241{
7236 if ( fixwidth && cachewidth != 0 ) 7242 if ( fixwidth && cachewidth != 0 )
7237 return; 7243 return;
7238 if ( nwidth == cachewidth ) 7244 if ( nwidth == cachewidth )
7239 return; 7245 return;
7240 7246
7241 7247
7242 cachewidth = nwidth; 7248 cachewidth = nwidth;
7243 int w = nwidth; 7249 int w = nwidth;
7244 7250
7245 format( w ); 7251 format( w );
7246 7252
7247 if ( stretch ) 7253 if ( stretch )
7248 nwidth = nwidth * stretch / 100; 7254 nwidth = nwidth * stretch / 100;
7249 7255
7250 width = nwidth; 7256 width = nwidth;
7251 layout->invalidate(); 7257 layout->invalidate();
7252 int shw = layout->sizeHint().width() + 2*outerborder; 7258 int shw = layout->sizeHint().width() + 2*outerborder;
7253 int mw = layout->minimumSize().width() + 2*outerborder; 7259 int mw = layout->minimumSize().width() + 2*outerborder;
7254 if ( stretch ) 7260 if ( stretch )
7255 width = QMAX( mw, nwidth ); 7261 width = QMAX( mw, nwidth );
7256 else 7262 else
7257 width = QMAX( mw, QMIN( nwidth, shw ) ); 7263 width = QMAX( mw, QMIN( nwidth, shw ) );
7258 7264
7259 if ( fixwidth ) 7265 if ( fixwidth )
7260 width = fixwidth; 7266 width = fixwidth;
7261 7267
7262 layout->invalidate(); 7268 layout->invalidate();
7263 mw = layout->minimumSize().width() + 2*outerborder; 7269 mw = layout->minimumSize().width() + 2*outerborder;
7264 width = QMAX( width, mw ); 7270 width = QMAX( width, mw );
7265 7271
7266 int h = layout->heightForWidth( width-2*outerborder ); 7272 int h = layout->heightForWidth( width-2*outerborder );
7267 layout->setGeometry( QRect(0, 0, width-2*outerborder, h) ); 7273 layout->setGeometry( QRect(0, 0, width-2*outerborder, h) );
7268 height = layout->geometry().height()+2*outerborder; 7274 height = layout->geometry().height()+2*outerborder;
7269} 7275}
7270 7276
7271void QTextTable::format( int w ) 7277void QTextTable::format( int w )
7272{ 7278{
7273 for ( int i = 0; i < (int)cells.count(); ++i ) { 7279 for ( int i = 0; i < (int)cells.count(); ++i ) {
7274 QTextTableCell *cell = cells.at( i ); 7280 QTextTableCell *cell = cells.at( i );
7275 QRect r = cell->geometry(); 7281 QRect r = cell->geometry();
7276 r.setWidth( w - 2*outerborder ); 7282 r.setWidth( w - 2*outerborder );
7277 cell->setGeometry( r ); 7283 cell->setGeometry( r );
7278 } 7284 }
7279} 7285}
7280 7286
7281void QTextTable::addCell( QTextTableCell* cell ) 7287void QTextTable::addCell( QTextTableCell* cell )
7282{ 7288{
7283 cells.append( cell ); 7289 cells.append( cell );
7284 layout->addMultiCell( cell, cell->row(), cell->row() + cell->rowspan()-1, 7290 layout->addMultiCell( cell, cell->row(), cell->row() + cell->rowspan()-1,
7285 cell->column(), cell->column() + cell->colspan()-1 ); 7291 cell->column(), cell->column() + cell->colspan()-1 );
7286} 7292}
7287 7293
7288bool QTextTable::enter( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy, bool atEnd ) 7294bool QTextTable::enter( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy, bool atEnd )
7289{ 7295{
7290 currCell.remove( c ); 7296 currCell.remove( c );
7291 if ( !atEnd ) 7297 if ( !atEnd )
7292 return next( c, doc, parag, idx, ox, oy ); 7298 return next( c, doc, parag, idx, ox, oy );
7293 currCell.insert( c, cells.count() ); 7299 currCell.insert( c, cells.count() );
7294 return prev( c, doc, parag, idx, ox, oy ); 7300 return prev( c, doc, parag, idx, ox, oy );
7295} 7301}
7296 7302
7297bool QTextTable::enterAt( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy, const QPoint &pos ) 7303bool QTextTable::enterAt( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy, const QPoint &pos )
7298{ 7304{
7299 currCell.remove( c ); 7305 currCell.remove( c );
7300 int lastCell = -1; 7306 int lastCell = -1;
7301 int lastY = -1; 7307 int lastY = -1;
7302 int i; 7308 int i;
7303 for ( i = 0; i < (int)cells.count(); ++i ) { 7309 for ( i = 0; i < (int)cells.count(); ++i ) {
7304 QTextTableCell *cell = cells.at( i ); 7310 QTextTableCell *cell = cells.at( i );
7305 if ( !cell ) 7311 if ( !cell )
7306 continue; 7312 continue;
7307 QRect r( cell->geometry().x(), 7313 QRect r( cell->geometry().x(),
7308 cell->geometry().y(), 7314 cell->geometry().y(),
7309 cell->geometry().width() + 2 * innerborder + 2 * outerborder, 7315 cell->geometry().width() + 2 * innerborder + 2 * outerborder,
7310 cell->geometry().height() + 2 * innerborder + 2 * outerborder ); 7316 cell->geometry().height() + 2 * innerborder + 2 * outerborder );
7311 7317
7312 if ( r.left() <= pos.x() && r.right() >= pos.x() ) { 7318 if ( r.left() <= pos.x() && r.right() >= pos.x() ) {
7313 if ( cell->geometry().y() > lastY ) { 7319 if ( cell->geometry().y() > lastY ) {
7314 lastCell = i; 7320 lastCell = i;
7315 lastY = cell->geometry().y(); 7321 lastY = cell->geometry().y();
7316 } 7322 }
7317 if ( r.top() <= pos.y() && r.bottom() >= pos.y() ) { 7323 if ( r.top() <= pos.y() && r.bottom() >= pos.y() ) {
7318 currCell.insert( c, i ); 7324 currCell.insert( c, i );
7319 break; 7325 break;
7320 } 7326 }
7321 } 7327 }
7322 } 7328 }
7323 if ( i == (int) cells.count() ) 7329 if ( i == (int) cells.count() )
7324 return FALSE; // no cell found 7330 return FALSE; // no cell found
7325 7331
7326 if ( currCell.find( c ) == currCell.end() ) { 7332 if ( currCell.find( c ) == currCell.end() ) {
7327 if ( lastY != -1 ) 7333 if ( lastY != -1 )
7328 currCell.insert( c, lastCell ); 7334 currCell.insert( c, lastCell );
7329 else 7335 else
7330 return FALSE; 7336 return FALSE;
7331 } 7337 }
7332 7338
7333 QTextTableCell *cell = cells.at( *currCell.find( c ) ); 7339 QTextTableCell *cell = cells.at( *currCell.find( c ) );
7334 if ( !cell ) 7340 if ( !cell )
7335 return FALSE; 7341 return FALSE;
7336 doc = cell->richText(); 7342 doc = cell->richText();
7337 parag = doc->firstParagraph(); 7343 parag = doc->firstParagraph();
7338 idx = 0; 7344 idx = 0;
7339 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x(); 7345 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x();
7340 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder; 7346 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder;
7341 return TRUE; 7347 return TRUE;
7342} 7348}
7343 7349
7344bool QTextTable::next( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy ) 7350bool QTextTable::next( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy )
7345{ 7351{
7346 int cc = -1; 7352 int cc = -1;
7347 if ( currCell.find( c ) != currCell.end() ) 7353 if ( currCell.find( c ) != currCell.end() )
7348 cc = *currCell.find( c ); 7354 cc = *currCell.find( c );
7349 if ( cc > (int)cells.count() - 1 || cc < 0 ) 7355 if ( cc > (int)cells.count() - 1 || cc < 0 )
7350 cc = -1; 7356 cc = -1;
7351 currCell.remove( c ); 7357 currCell.remove( c );
7352 currCell.insert( c, ++cc ); 7358 currCell.insert( c, ++cc );
7353 if ( cc >= (int)cells.count() ) { 7359 if ( cc >= (int)cells.count() ) {
7354 currCell.insert( c, 0 ); 7360 currCell.insert( c, 0 );
7355 QTextCustomItem::next( c, doc, parag, idx, ox, oy ); 7361 QTextCustomItem::next( c, doc, parag, idx, ox, oy );
7356 QTextTableCell *cell = cells.first(); 7362 QTextTableCell *cell = cells.first();
7357 if ( !cell ) 7363 if ( !cell )
7358 return FALSE; 7364 return FALSE;
7359 doc = cell->richText(); 7365 doc = cell->richText();
7360 idx = -1; 7366 idx = -1;
7361 return TRUE; 7367 return TRUE;
7362 } 7368 }
7363 7369
7364 if ( currCell.find( c ) == currCell.end() ) 7370 if ( currCell.find( c ) == currCell.end() )
7365 return FALSE; 7371 return FALSE;
7366 QTextTableCell *cell = cells.at( *currCell.find( c ) ); 7372 QTextTableCell *cell = cells.at( *currCell.find( c ) );
7367 if ( !cell ) 7373 if ( !cell )
7368 return FALSE; 7374 return FALSE;
7369 doc = cell->richText(); 7375 doc = cell->richText();
7370 parag = doc->firstParagraph(); 7376 parag = doc->firstParagraph();
7371 idx = 0; 7377 idx = 0;
7372 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x(); 7378 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x();
7373 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder; 7379 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder;
7374 return TRUE; 7380 return TRUE;
7375} 7381}
7376 7382
7377bool QTextTable::prev( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy ) 7383bool QTextTable::prev( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy )
7378{ 7384{
7379 int cc = -1; 7385 int cc = -1;
7380 if ( currCell.find( c ) != currCell.end() ) 7386 if ( currCell.find( c ) != currCell.end() )
7381 cc = *currCell.find( c ); 7387 cc = *currCell.find( c );
7382 if ( cc > (int)cells.count() - 1 || cc < 0 ) 7388 if ( cc > (int)cells.count() - 1 || cc < 0 )
7383 cc = cells.count(); 7389 cc = cells.count();
7384 currCell.remove( c ); 7390 currCell.remove( c );
7385 currCell.insert( c, --cc ); 7391 currCell.insert( c, --cc );
7386 if ( cc < 0 ) { 7392 if ( cc < 0 ) {
7387 currCell.insert( c, 0 ); 7393 currCell.insert( c, 0 );
7388 QTextCustomItem::prev( c, doc, parag, idx, ox, oy ); 7394 QTextCustomItem::prev( c, doc, parag, idx, ox, oy );
7389 QTextTableCell *cell = cells.first(); 7395 QTextTableCell *cell = cells.first();
7390 if ( !cell ) 7396 if ( !cell )
7391 return FALSE; 7397 return FALSE;
7392 doc = cell->richText(); 7398 doc = cell->richText();
7393 idx = -1; 7399 idx = -1;
7394 return TRUE; 7400 return TRUE;
7395 } 7401 }
7396 7402
7397 if ( currCell.find( c ) == currCell.end() ) 7403 if ( currCell.find( c ) == currCell.end() )
7398 return FALSE; 7404 return FALSE;
7399 QTextTableCell *cell = cells.at( *currCell.find( c ) ); 7405 QTextTableCell *cell = cells.at( *currCell.find( c ) );
7400 if ( !cell ) 7406 if ( !cell )
7401 return FALSE; 7407 return FALSE;
7402 doc = cell->richText(); 7408 doc = cell->richText();
7403 parag = doc->lastParagraph(); 7409 parag = doc->lastParagraph();
7404 idx = parag->length() - 1; 7410 idx = parag->length() - 1;
7405 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x(); 7411 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x();
7406 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder; 7412 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder;
7407 return TRUE; 7413 return TRUE;
7408} 7414}
7409 7415
7410bool QTextTable::down( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy ) 7416bool QTextTable::down( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy )
7411{ 7417{
7412 if ( currCell.find( c ) == currCell.end() ) 7418 if ( currCell.find( c ) == currCell.end() )
7413 return FALSE; 7419 return FALSE;
7414 QTextTableCell *cell = cells.at( *currCell.find( c ) ); 7420 QTextTableCell *cell = cells.at( *currCell.find( c ) );
7415 if ( cell->row_ == layout->numRows() - 1 ) { 7421 if ( cell->row_ == layout->numRows() - 1 ) {
7416 currCell.insert( c, 0 ); 7422 currCell.insert( c, 0 );
7417 QTextCustomItem::down( c, doc, parag, idx, ox, oy ); 7423 QTextCustomItem::down( c, doc, parag, idx, ox, oy );
7418 QTextTableCell *cell = cells.first(); 7424 QTextTableCell *cell = cells.first();
7419 if ( !cell ) 7425 if ( !cell )
7420 return FALSE; 7426 return FALSE;
7421 doc = cell->richText(); 7427 doc = cell->richText();
7422 idx = -1; 7428 idx = -1;
7423 return TRUE; 7429 return TRUE;
7424 } 7430 }
7425 7431
7426 int oldRow = cell->row_; 7432 int oldRow = cell->row_;
7427 int oldCol = cell->col_; 7433 int oldCol = cell->col_;
7428 if ( currCell.find( c ) == currCell.end() ) 7434 if ( currCell.find( c ) == currCell.end() )
7429 return FALSE; 7435 return FALSE;
7430 int cc = *currCell.find( c ); 7436 int cc = *currCell.find( c );
7431 for ( int i = cc; i < (int)cells.count(); ++i ) { 7437 for ( int i = cc; i < (int)cells.count(); ++i ) {
7432 cell = cells.at( i ); 7438 cell = cells.at( i );
7433 if ( cell->row_ > oldRow && cell->col_ == oldCol ) { 7439 if ( cell->row_ > oldRow && cell->col_ == oldCol ) {
7434 currCell.insert( c, i ); 7440 currCell.insert( c, i );
7435 break; 7441 break;
7436 } 7442 }
7437 } 7443 }
7438 doc = cell->richText(); 7444 doc = cell->richText();
7439 if ( !cell ) 7445 if ( !cell )
7440 return FALSE; 7446 return FALSE;
7441 parag = doc->firstParagraph(); 7447 parag = doc->firstParagraph();
7442 idx = 0; 7448 idx = 0;
7443 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x(); 7449 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x();
7444 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder; 7450 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder;
7445 return TRUE; 7451 return TRUE;
7446} 7452}
7447 7453
7448bool QTextTable::up( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy ) 7454bool QTextTable::up( QTextCursor *c, QTextDocument *&doc, QTextParagraph *&parag, int &idx, int &ox, int &oy )
7449{ 7455{
7450 if ( currCell.find( c ) == currCell.end() ) 7456 if ( currCell.find( c ) == currCell.end() )
7451 return FALSE; 7457 return FALSE;
7452 QTextTableCell *cell = cells.at( *currCell.find( c ) ); 7458 QTextTableCell *cell = cells.at( *currCell.find( c ) );
7453 if ( cell->row_ == 0 ) { 7459 if ( cell->row_ == 0 ) {
7454 currCell.insert( c, 0 ); 7460 currCell.insert( c, 0 );
7455 QTextCustomItem::up( c, doc, parag, idx, ox, oy ); 7461 QTextCustomItem::up( c, doc, parag, idx, ox, oy );
7456 QTextTableCell *cell = cells.first(); 7462 QTextTableCell *cell = cells.first();
7457 if ( !cell ) 7463 if ( !cell )
7458 return FALSE; 7464 return FALSE;
7459 doc = cell->richText(); 7465 doc = cell->richText();
7460 idx = -1; 7466 idx = -1;
7461 return TRUE; 7467 return TRUE;
7462 } 7468 }
7463 7469
7464 int oldRow = cell->row_; 7470 int oldRow = cell->row_;
7465 int oldCol = cell->col_; 7471 int oldCol = cell->col_;
7466 if ( currCell.find( c ) == currCell.end() ) 7472 if ( currCell.find( c ) == currCell.end() )
7467 return FALSE; 7473 return FALSE;
7468 int cc = *currCell.find( c ); 7474 int cc = *currCell.find( c );
7469 for ( int i = cc; i >= 0; --i ) { 7475 for ( int i = cc; i >= 0; --i ) {
7470 cell = cells.at( i ); 7476 cell = cells.at( i );
7471 if ( cell->row_ < oldRow && cell->col_ == oldCol ) { 7477 if ( cell->row_ < oldRow && cell->col_ == oldCol ) {
7472 currCell.insert( c, i ); 7478 currCell.insert( c, i );
7473 break; 7479 break;
7474 } 7480 }
7475 } 7481 }
7476 doc = cell->richText(); 7482 doc = cell->richText();
7477 if ( !cell ) 7483 if ( !cell )
7478 return FALSE; 7484 return FALSE;
7479 parag = doc->lastParagraph(); 7485 parag = doc->lastParagraph();
7480 idx = parag->length() - 1; 7486 idx = parag->length() - 1;
7481 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x(); 7487 ox += cell->geometry().x() + cell->horizontalAlignmentOffset() + outerborder + parent->x();
7482 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder; 7488 oy += cell->geometry().y() + cell->verticalAlignmentOffset() + outerborder;
7483 return TRUE; 7489 return TRUE;
7484} 7490}
7485 7491
7486QTextTableCell::QTextTableCell( QTextTable* table, 7492QTextTableCell::QTextTableCell( QTextTable* table,
7487 int row, int column, 7493 int row, int column,
7488 const QMap<QString, QString> &attr, 7494 const QMap<QString, QString> &attr,
7489 const QStyleSheetItem* /*style*/, // ### use them 7495 const QStyleSheetItem* /*style*/, // ### use them
7490 const QTextFormat& /*fmt*/, const QString& context, 7496 const QTextFormat& /*fmt*/, const QString& context,
7491 QMimeSourceFactory &factory, QStyleSheet *sheet, 7497 QMimeSourceFactory &factory, QStyleSheet *sheet,
7492 const QString& doc) 7498 const QString& doc)
7493{ 7499{
7494 cached_width = -1; 7500 cached_width = -1;
7495 cached_sizehint = -1; 7501 cached_sizehint = -1;
7496 7502
7497 maxw = QWIDGETSIZE_MAX; 7503 maxw = QWIDGETSIZE_MAX;
7498 minw = 0; 7504 minw = 0;
7499 7505
7500 parent = table; 7506 parent = table;
7501 row_ = row; 7507 row_ = row;
7502 col_ = column; 7508 col_ = column;
7503 stretch_ = 0; 7509 stretch_ = 0;
7504 richtext = new QTextDocument( table->parent ); 7510 richtext = new QTextDocument( table->parent );
7505 richtext->setTableCell( this ); 7511 richtext->setTableCell( this );
7506 QString a = *attr.find( "align" ); 7512 QString a = *attr.find( "align" );
7507 if ( !a.isEmpty() ) { 7513 if ( !a.isEmpty() ) {
7508 a = a.lower(); 7514 a = a.lower();
7509 if ( a == "left" ) 7515 if ( a == "left" )
7510 richtext->setAlignment( Qt::AlignLeft ); 7516 richtext->setAlignment( Qt::AlignLeft );
7511 else if ( a == "center" ) 7517 else if ( a == "center" )
7512 richtext->setAlignment( Qt::AlignHCenter ); 7518 richtext->setAlignment( Qt::AlignHCenter );
7513 else if ( a == "right" ) 7519 else if ( a == "right" )
7514 richtext->setAlignment( Qt::AlignRight ); 7520 richtext->setAlignment( Qt::AlignRight );
7515 } 7521 }
7516 align = 0; 7522 align = 0;
7517 QString va = *attr.find( "valign" ); 7523 QString va = *attr.find( "valign" );
7518 if ( !va.isEmpty() ) { 7524 if ( !va.isEmpty() ) {
7519 va = va.lower(); 7525 va = va.lower();
7520 if ( va == "center" ) 7526 if ( va == "center" )
7521 align |= Qt::AlignVCenter; 7527 align |= Qt::AlignVCenter;
7522 else if ( va == "bottom" ) 7528 else if ( va == "bottom" )
7523 align |= Qt::AlignBottom; 7529 align |= Qt::AlignBottom;
7524 } 7530 }
7525 richtext->setFormatter( table->parent->formatter() ); 7531 richtext->setFormatter( table->parent->formatter() );
7526 richtext->setUseFormatCollection( table->parent->useFormatCollection() ); 7532 richtext->setUseFormatCollection( table->parent->useFormatCollection() );
7527 richtext->setMimeSourceFactory( &factory ); 7533 richtext->setMimeSourceFactory( &factory );
7528 richtext->setStyleSheet( sheet ); 7534 richtext->setStyleSheet( sheet );
7529 richtext->setDefaultFormat( table->parent->formatCollection()->defaultFormat()->font(), 7535 richtext->setDefaultFormat( table->parent->formatCollection()->defaultFormat()->font(),
7530 table->parent->formatCollection()->defaultFormat()->color() ); 7536 table->parent->formatCollection()->defaultFormat()->color() );
7531 richtext->setRichText( doc, context ); 7537 richtext->setRichText( doc, context );
7532 rowspan_ = 1; 7538 rowspan_ = 1;
7533 colspan_ = 1; 7539 colspan_ = 1;
7534 if ( attr.contains("colspan") ) 7540 if ( attr.contains("colspan") )
7535 colspan_ = attr["colspan"].toInt(); 7541 colspan_ = attr["colspan"].toInt();
7536 if ( attr.contains("rowspan") ) 7542 if ( attr.contains("rowspan") )
7537 rowspan_ = attr["rowspan"].toInt(); 7543 rowspan_ = attr["rowspan"].toInt();
7538 7544
7539 background = 0; 7545 background = 0;
7540 if ( attr.contains("bgcolor") ) { 7546 if ( attr.contains("bgcolor") ) {
7541 background = new QBrush(QColor( attr["bgcolor"] )); 7547 background = new QBrush(QColor( attr["bgcolor"] ));
7542 } 7548 }
7543 7549
7544 7550
7545 hasFixedWidth = FALSE; 7551 hasFixedWidth = FALSE;
7546 if ( attr.contains("width") ) { 7552 if ( attr.contains("width") ) {
7547 bool b; 7553 bool b;
7548 QString s( attr["width"] ); 7554 QString s( attr["width"] );
7549 int w = s.toInt( &b ); 7555 int w = s.toInt( &b );
7550 if ( b ) { 7556 if ( b ) {
7551 maxw = w; 7557 maxw = w;
7552 minw = maxw; 7558 minw = maxw;
7553 hasFixedWidth = TRUE; 7559 hasFixedWidth = TRUE;
7554 } else { 7560 } else {
7555 s = s.stripWhiteSpace(); 7561 s = s.stripWhiteSpace();
7556 if ( s.length() > 1 && s[ (int)s.length()-1 ] == '%' ) 7562 if ( s.length() > 1 && s[ (int)s.length()-1 ] == '%' )
7557 stretch_ = s.left( s.length()-1).toInt(); 7563 stretch_ = s.left( s.length()-1).toInt();
7558 } 7564 }
7559 } 7565 }
7560 7566
7561 attributes = attr; 7567 attributes = attr;
7562 7568
7563 parent->addCell( this ); 7569 parent->addCell( this );
7564} 7570}
7565 7571
7566QTextTableCell::~QTextTableCell() 7572QTextTableCell::~QTextTableCell()
7567{ 7573{
7568 delete background; 7574 delete background;
7569 background = 0; 7575 background = 0;
7570 delete richtext; 7576 delete richtext;
7571 richtext = 0; 7577 richtext = 0;
7572} 7578}
7573 7579
7574QSize QTextTableCell::sizeHint() const 7580QSize QTextTableCell::sizeHint() const
7575{ 7581{
7576 int extra = 2 * ( parent->innerborder + parent->cellpadding + border_tolerance); 7582 int extra = 2 * ( parent->innerborder + parent->cellpadding + border_tolerance);
7577 int used = richtext->widthUsed() + extra; 7583 int used = richtext->widthUsed() + extra;
7578 7584
7579 if (stretch_ ) { 7585 if (stretch_ ) {
7580 int w = parent->width * stretch_ / 100 - 2*parent->cellspacing - 2*parent->cellpadding; 7586 int w = parent->width * stretch_ / 100 - 2*parent->cellspacing - 2*parent->cellpadding;
7581 return QSize( QMIN( w, maxw ), 0 ).expandedTo( minimumSize() ); 7587 return QSize( QMIN( w, maxw ), 0 ).expandedTo( minimumSize() );
7582 } 7588 }
7583 7589
7584 return QSize( used, 0 ).expandedTo( minimumSize() ); 7590 return QSize( used, 0 ).expandedTo( minimumSize() );
7585} 7591}
7586 7592
7587QSize QTextTableCell::minimumSize() const 7593QSize QTextTableCell::minimumSize() const
7588{ 7594{
7589 int extra = 2 * ( parent->innerborder + parent->cellpadding + border_tolerance); 7595 int extra = 2 * ( parent->innerborder + parent->cellpadding + border_tolerance);
7590 return QSize( QMAX( richtext->minimumWidth() + extra, minw), 0 ); 7596 return QSize( QMAX( richtext->minimumWidth() + extra, minw), 0 );
7591} 7597}
7592 7598
7593QSize QTextTableCell::maximumSize() const 7599QSize QTextTableCell::maximumSize() const
7594{ 7600{
7595 return QSize( QWIDGETSIZE_MAX, QWIDGETSIZE_MAX ); 7601 return QSize( QWIDGETSIZE_MAX, QWIDGETSIZE_MAX );
7596} 7602}
7597 7603
7598QSizePolicy::ExpandData QTextTableCell::expanding() const 7604QSizePolicy::ExpandData QTextTableCell::expanding() const
7599{ 7605{
7600 return QSizePolicy::BothDirections; 7606 return QSizePolicy::BothDirections;
7601} 7607}
7602 7608
7603bool QTextTableCell::isEmpty() const 7609bool QTextTableCell::isEmpty() const
7604{ 7610{
7605 return FALSE; 7611 return FALSE;
7606} 7612}
7607void QTextTableCell::setGeometry( const QRect& r ) 7613void QTextTableCell::setGeometry( const QRect& r )
7608{ 7614{
7609 int extra = 2 * ( parent->innerborder + parent->cellpadding ); 7615 int extra = 2 * ( parent->innerborder + parent->cellpadding );
7610 if ( r.width() != cached_width ) 7616 if ( r.width() != cached_width )
7611 richtext->doLayout( QTextFormat::painter(), r.width() - extra ); 7617 richtext->doLayout( QTextFormat::painter(), r.width() - extra );
7612 cached_width = r.width(); 7618 cached_width = r.width();
7613 geom = r; 7619 geom = r;
7614} 7620}
7615 7621
7616QRect QTextTableCell::geometry() const 7622QRect QTextTableCell::geometry() const
7617{ 7623{
7618 return geom; 7624 return geom;
7619} 7625}
7620 7626
7621bool QTextTableCell::hasHeightForWidth() const 7627bool QTextTableCell::hasHeightForWidth() const
7622{ 7628{
7623 return TRUE; 7629 return TRUE;
7624} 7630}
7625 7631
7626int QTextTableCell::heightForWidth( int w ) const 7632int QTextTableCell::heightForWidth( int w ) const
7627{ 7633{
7628 int extra = 2 * ( parent->innerborder + parent->cellpadding ); 7634 int extra = 2 * ( parent->innerborder + parent->cellpadding );
7629 w = QMAX( minw, w ); 7635 w = QMAX( minw, w );
7630 7636
7631 if ( cached_width != w ) { 7637 if ( cached_width != w ) {
7632 QTextTableCell* that = (QTextTableCell*) this; 7638 QTextTableCell* that = (QTextTableCell*) this;
7633 that->richtext->doLayout( QTextFormat::painter(), w - extra ); 7639 that->richtext->doLayout( QTextFormat::painter(), w - extra );
7634 that->cached_width = w; 7640 that->cached_width = w;
7635 } 7641 }
7636 return richtext->height() + extra; 7642 return richtext->height() + extra;
7637} 7643}
7638 7644
7639void QTextTableCell::adjustToPainter( QPainter* p ) 7645void QTextTableCell::adjustToPainter( QPainter* p )
7640{ 7646{
7641 QTextParagraph *parag = richtext->firstParagraph(); 7647 QTextParagraph *parag = richtext->firstParagraph();
7642 while ( parag ) { 7648 while ( parag ) {
7643 parag->adjustToPainter( p ); 7649 parag->adjustToPainter( p );
7644 parag = parag->next(); 7650 parag = parag->next();
7645 } 7651 }
7646} 7652}
7647 7653
7648int QTextTableCell::horizontalAlignmentOffset() const 7654int QTextTableCell::horizontalAlignmentOffset() const
7649{ 7655{
7650 return parent->cellpadding; 7656 return parent->cellpadding;
7651} 7657}
7652 7658
7653int QTextTableCell::verticalAlignmentOffset() const 7659int QTextTableCell::verticalAlignmentOffset() const
7654{ 7660{
7655 if ( (align & Qt::AlignVCenter ) == Qt::AlignVCenter ) 7661 if ( (align & Qt::AlignVCenter ) == Qt::AlignVCenter )
7656 return ( geom.height() - richtext->height() ) / 2; 7662 return ( geom.height() - richtext->height() ) / 2;
7657 else if ( ( align & Qt::AlignBottom ) == Qt::AlignBottom ) 7663 else if ( ( align & Qt::AlignBottom ) == Qt::AlignBottom )
7658 return geom.height() - parent->cellpadding - richtext->height() ; 7664 return geom.height() - parent->cellpadding - richtext->height() ;
7659 return parent->cellpadding; 7665 return parent->cellpadding;
7660} 7666}
7661 7667
7662void QTextTableCell::draw( QPainter* p, int x, int y, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool ) 7668void QTextTableCell::draw( QPainter* p, int x, int y, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool )
7663{ 7669{
7664 if ( cached_width != geom.width() ) { 7670 if ( cached_width != geom.width() ) {
7665 int extra = 2 * ( parent->innerborder + parent->cellpadding ); 7671 int extra = 2 * ( parent->innerborder + parent->cellpadding );
7666 richtext->doLayout( p, geom.width() - extra ); 7672 richtext->doLayout( p, geom.width() - extra );
7667 cached_width = geom.width(); 7673 cached_width = geom.width();
7668 } 7674 }
7669 QColorGroup g( cg ); 7675 QColorGroup g( cg );
7670 if ( background ) 7676 if ( background )
7671 g.setBrush( QColorGroup::Base, *background ); 7677 g.setBrush( QColorGroup::Base, *background );
7672 else if ( richtext->paper() ) 7678 else if ( richtext->paper() )
7673 g.setBrush( QColorGroup::Base, *richtext->paper() ); 7679 g.setBrush( QColorGroup::Base, *richtext->paper() );
7674 7680
7675 p->save(); 7681 p->save();
7676 p->translate( x + geom.x(), y + geom.y() ); 7682 p->translate( x + geom.x(), y + geom.y() );
7677 if ( background ) 7683 if ( background )
7678 p->fillRect( 0, 0, geom.width(), geom.height(), *background ); 7684 p->fillRect( 0, 0, geom.width(), geom.height(), *background );
7679 else if ( richtext->paper() ) 7685 else if ( richtext->paper() )
7680 p->fillRect( 0, 0, geom.width(), geom.height(), *richtext->paper() ); 7686 p->fillRect( 0, 0, geom.width(), geom.height(), *richtext->paper() );
7681 7687
7682 p->translate( horizontalAlignmentOffset(), verticalAlignmentOffset() ); 7688 p->translate( horizontalAlignmentOffset(), verticalAlignmentOffset() );
7683 7689
7684 QRegion r; 7690 QRegion r;
7685 if ( cx >= 0 && cy >= 0 ) 7691 if ( cx >= 0 && cy >= 0 )
7686 richtext->draw( p, cx - ( x + horizontalAlignmentOffset() + geom.x() ), 7692 richtext->draw( p, cx - ( x + horizontalAlignmentOffset() + geom.x() ),
7687 cy - ( y + geom.y() + verticalAlignmentOffset() ), 7693 cy - ( y + geom.y() + verticalAlignmentOffset() ),
7688 cw, ch, g, FALSE, FALSE, 0 ); 7694 cw, ch, g, FALSE, FALSE, 0 );
7689 else 7695 else
7690 richtext->draw( p, -1, -1, -1, -1, g, FALSE, FALSE, 0 ); 7696 richtext->draw( p, -1, -1, -1, -1, g, FALSE, FALSE, 0 );
7691 7697
7692 p->restore(); 7698 p->restore();
7693} 7699}
7694 7700
7695QString QTextDocument::section( QString str, const QString &sep, int start, int end ) 7701QString QTextDocument::section( QString str, const QString &sep, int start, int end )
7696{ 7702{
7697 const QChar *uc = str.unicode(); 7703 const QChar *uc = str.unicode();
7698 if ( !uc ) 7704 if ( !uc )
7699 return QString(); 7705 return QString();
7700 QString _sep = sep; 7706 QString _sep = sep;
7701 const QChar *uc_sep = _sep.unicode(); 7707 const QChar *uc_sep = _sep.unicode();
7702 if(!uc_sep) 7708 if(!uc_sep)
7703 return QString(); 7709 return QString();
7704 bool match = FALSE, last_match = TRUE; 7710 bool match = FALSE, last_match = TRUE;
7705 7711
7706 //find start 7712 //find start
7707 int n = str.length(), sep_len = _sep.length(); 7713 int n = str.length(), sep_len = _sep.length();
7708 const QChar *begin = start < 0 ? uc + n : uc; 7714 const QChar *begin = start < 0 ? uc + n : uc;
7709 while(start) { 7715 while(start) {
7710 match = FALSE; 7716 match = FALSE;
7711 int c = 0; 7717 int c = 0;
7712 for(const QChar *tmp = start < 0 ? begin - sep_len : begin; 7718 for(const QChar *tmp = start < 0 ? begin - sep_len : begin;
7713 c < sep_len && tmp < uc + n && tmp >= uc; tmp++, c++) { 7719 c < sep_len && tmp < uc + n && tmp >= uc; tmp++, c++) {
7714 if( *tmp != *(uc_sep + c) ) 7720 if( *tmp != *(uc_sep + c) )
7715 break; 7721 break;
7716 if(c == sep_len - 1) { 7722 if(c == sep_len - 1) {
7717 match = TRUE; 7723 match = TRUE;
7718 break; 7724 break;
7719 } 7725 }
7720 } 7726 }
7721 last_match = match; 7727 last_match = match;
7722 7728
7723 if(start < 0) { 7729 if(start < 0) {
7724 if(match) { 7730 if(match) {
7725 begin -= sep_len; 7731 begin -= sep_len;
7726 if(!++start) 7732 if(!++start)
7727 break; 7733 break;
7728 } else { 7734 } else {
7729 if(start == -1 && begin == uc) 7735 if(start == -1 && begin == uc)
7730 break; 7736 break;
7731 begin--; 7737 begin--;
7732 } 7738 }
7733 } else { 7739 } else {
7734 if(match) { 7740 if(match) {
7735 if(!--start) 7741 if(!--start)
7736 break; 7742 break;
7737 begin += sep_len; 7743 begin += sep_len;
7738 } else { 7744 } else {
7739 if(start == 1 && begin == uc + n) 7745 if(start == 1 && begin == uc + n)
7740 break; 7746 break;
7741 begin++; 7747 begin++;
7742 } 7748 }
7743 } 7749 }
7744 if(begin > uc + n || begin < uc) 7750 if(begin > uc + n || begin < uc)
7745 return QString(); 7751 return QString();
7746 } 7752 }
7747 if(match) 7753 if(match)
7748 begin+=sep_len; 7754 begin+=sep_len;
7749 if(begin > uc + n || begin < uc) 7755 if(begin > uc + n || begin < uc)
7750 return QString(); 7756 return QString();
7751 7757
7752 //now find last 7758 //now find last
7753 match = FALSE; 7759 match = FALSE;
7754 const QChar *last = end < 0 ? uc + n : uc; 7760 const QChar *last = end < 0 ? uc + n : uc;
7755 if(end == -1) { 7761 if(end == -1) {
7756 int c = 0; 7762 int c = 0;
7757 for(const QChar *tmp = end < 0 ? last - sep_len : last; 7763 for(const QChar *tmp = end < 0 ? last - sep_len : last;
7758 c < sep_len && tmp < uc + n && tmp >= uc; tmp++, c++) { 7764 c < sep_len && tmp < uc + n && tmp >= uc; tmp++, c++) {
7759 if( *tmp != *(uc_sep + c) ) 7765 if( *tmp != *(uc_sep + c) )
7760 break; 7766 break;
7761 if(c == sep_len - 1) { 7767 if(c == sep_len - 1) {
7762 match = TRUE; 7768 match = TRUE;
7763 break; 7769 break;
7764 } 7770 }
7765 } 7771 }
7766 } else { 7772 } else {
7767 end++; 7773 end++;
7768 last_match = TRUE; 7774 last_match = TRUE;
7769 while(end) { 7775 while(end) {
7770 match = FALSE; 7776 match = FALSE;
7771 int c = 0; 7777 int c = 0;
7772 for(const QChar *tmp = end < 0 ? last - sep_len : last; 7778 for(const QChar *tmp = end < 0 ? last - sep_len : last;
7773 c < sep_len && tmp < uc + n && tmp >= uc; tmp++, c++) { 7779 c < sep_len && tmp < uc + n && tmp >= uc; tmp++, c++) {
7774 if( *tmp != *(uc_sep + c) ) 7780 if( *tmp != *(uc_sep + c) )
7775 break; 7781 break;
7776 if(c == sep_len - 1) { 7782 if(c == sep_len - 1) {
7777 match = TRUE; 7783 match = TRUE;
7778 break; 7784 break;
7779 } 7785 }
7780 } 7786 }
7781 last_match = match; 7787 last_match = match;
7782 7788
7783 if(end < 0) { 7789 if(end < 0) {
7784 if(match) { 7790 if(match) {
7785 if(!++end) 7791 if(!++end)
7786 break; 7792 break;
7787 last -= sep_len; 7793 last -= sep_len;
7788 } else { 7794 } else {
7789 last--; 7795 last--;
7790 } 7796 }
7791 } else { 7797 } else {
7792 if(match) { 7798 if(match) {
7793 last += sep_len; 7799 last += sep_len;
7794 if(!--end) 7800 if(!--end)
7795 break; 7801 break;
7796 } else { 7802 } else {
7797 last++; 7803 last++;
7798 } 7804 }
7799 } 7805 }
7800 if(last >= uc + n) { 7806 if(last >= uc + n) {
7801 last = uc + n; 7807 last = uc + n;
7802 break; 7808 break;
7803 } else if(last < uc) { 7809 } else if(last < uc) {
7804 return QString(); 7810 return QString();
7805 } 7811 }
7806 } 7812 }
7807 } 7813 }
7808 if(match) 7814 if(match)
7809 last -= sep_len; 7815 last -= sep_len;
7810 if(last < uc || last > uc + n || begin >= last) 7816 if(last < uc || last > uc + n || begin >= last)
7811 return QString(); 7817 return QString();
7812 7818
7813 //done 7819 //done
7814 return QString(begin, last - begin); 7820 return QString(begin, last - begin);
7815} 7821}
7816 7822
7817bool QTextDocument::endsWith( QString str, const QString &s) 7823bool QTextDocument::endsWith( QString str, const QString &s)
7818{ 7824{
7819 if ( str.isNull() ) 7825 if ( str.isNull() )
7820 return s.isNull(); 7826 return s.isNull();
7821 int pos = str.length() - s.length(); 7827 int pos = str.length() - s.length();
7822 if ( pos < 0 ) 7828 if ( pos < 0 )
7823 return FALSE; 7829 return FALSE;
7824 for ( uint i = 0; i < s.length(); i++ ) { 7830 for ( uint i = 0; i < s.length(); i++ ) {
7825 if ( str.unicode()[pos+i] != s[(int)i] ) 7831 if ( str.unicode()[pos+i] != s[(int)i] )
7826 return FALSE; 7832 return FALSE;
7827 } 7833 }
7828 return TRUE; 7834 return TRUE;
7829} 7835}
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,603 +1,606 @@
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;
237 usePixelSizes = FALSE; 240 usePixelSizes = FALSE;
238 if ( stdSize == -1 ) { 241 if ( stdSize == -1 ) {
239 stdSize = f.pixelSize(); 242 stdSize = f.pixelSize();
240 usePixelSizes = TRUE; 243 usePixelSizes = TRUE;
241 } 244 }
242 collection = parent; 245 collection = parent;
243 leftBearing = fm.minLeftBearing(); 246 leftBearing = fm.minLeftBearing();
244 rightBearing = fm.minRightBearing(); 247 rightBearing = fm.minRightBearing();
245 hei = fm.lineSpacing(); 248 hei = fm.lineSpacing();
246 asc = fm.ascent() + (fm.leading()+1)/2; 249 asc = fm.ascent() + (fm.leading()+1)/2;
247 dsc = fm.descent(); 250 dsc = fm.descent();
248 missp = FALSE; 251 missp = FALSE;
249 ha = AlignNormal; 252 ha = AlignNormal;
250 memset( widths, 0, 256 ); 253 memset( widths, 0, 256 );
251 generateKey(); 254 generateKey();
252 addRef(); 255 addRef();
253} 256}
254 257
255QTextFormat::QTextFormat( const QTextFormat &f ) 258QTextFormat::QTextFormat( const QTextFormat &f )
256 : fm( f.fm ) 259 : fm( f.fm )
257{ 260{
258 ref = 0; 261 ref = 0;
259 collection = 0; 262 collection = 0;
260 fn = f.fn; 263 fn = f.fn;
261 col = f.col; 264 col = f.col;
262 leftBearing = f.leftBearing; 265 leftBearing = f.leftBearing;
263 rightBearing = f.rightBearing; 266 rightBearing = f.rightBearing;
264 memset( widths, 0, 256 ); 267 memset( widths, 0, 256 );
265 hei = f.hei; 268 hei = f.hei;
266 asc = f.asc; 269 asc = f.asc;
267 dsc = f.dsc; 270 dsc = f.dsc;
268 stdSize = f.stdSize; 271 stdSize = f.stdSize;
269 usePixelSizes = f.usePixelSizes; 272 usePixelSizes = f.usePixelSizes;
270 logicalFontSize = f.logicalFontSize; 273 logicalFontSize = f.logicalFontSize;
271 missp = f.missp; 274 missp = f.missp;
272 ha = f.ha; 275 ha = f.ha;
273 k = f.k; 276 k = f.k;
274 linkColor = f.linkColor; 277 linkColor = f.linkColor;
275 addRef(); 278 addRef();
276} 279}
277 280
278QTextFormat& QTextFormat::operator=( const QTextFormat &f ) 281QTextFormat& QTextFormat::operator=( const QTextFormat &f )
279{ 282{
280 ref = 0; 283 ref = 0;
281 collection = f.collection; 284 collection = f.collection;
282 fn = f.fn; 285 fn = f.fn;
283 col = f.col; 286 col = f.col;
284 fm = f.fm; 287 fm = f.fm;
285 leftBearing = f.leftBearing; 288 leftBearing = f.leftBearing;
286 rightBearing = f.rightBearing; 289 rightBearing = f.rightBearing;
287 memset( widths, 0, 256 ); 290 memset( widths, 0, 256 );
288 hei = f.hei; 291 hei = f.hei;
289 asc = f.asc; 292 asc = f.asc;
290 dsc = f.dsc; 293 dsc = f.dsc;
291 stdSize = f.stdSize; 294 stdSize = f.stdSize;
292 usePixelSizes = f.usePixelSizes; 295 usePixelSizes = f.usePixelSizes;
293 logicalFontSize = f.logicalFontSize; 296 logicalFontSize = f.logicalFontSize;
294 missp = f.missp; 297 missp = f.missp;
295 ha = f.ha; 298 ha = f.ha;
296 k = f.k; 299 k = f.k;
297 linkColor = f.linkColor; 300 linkColor = f.linkColor;
298 addRef(); 301 addRef();
299 return *this; 302 return *this;
300} 303}
301 304
302void QTextFormat::update() 305void QTextFormat::update()
303{ 306{
304 fm = QFontMetrics( fn ); 307 fm = QFontMetrics( fn );
305 leftBearing = fm.minLeftBearing(); 308 leftBearing = fm.minLeftBearing();
306 rightBearing = fm.minRightBearing(); 309 rightBearing = fm.minRightBearing();
307 hei = fm.lineSpacing(); 310 hei = fm.lineSpacing();
308 asc = fm.ascent() + (fm.leading()+1)/2; 311 asc = fm.ascent() + (fm.leading()+1)/2;
309 dsc = fm.descent(); 312 dsc = fm.descent();
310 memset( widths, 0, 256 ); 313 memset( widths, 0, 256 );
311 generateKey(); 314 generateKey();
312} 315}
313 316
314 317
315QPainter* QTextFormat::pntr = 0; 318QPainter* QTextFormat::pntr = 0;
316 319
317void QTextFormat::setPainter( QPainter *p ) 320void QTextFormat::setPainter( QPainter *p )
318{ 321{
319 pntr = p; 322 pntr = p;
320} 323}
321 324
322QPainter* QTextFormat::painter() 325QPainter* QTextFormat::painter()
323{ 326{
324 return pntr; 327 return pntr;
325} 328}
326 329
327 330
328int QTextFormat::minLeftBearing() const 331int QTextFormat::minLeftBearing() const
329{ 332{
330 if ( !pntr || !pntr->isActive() ) 333 if ( !pntr || !pntr->isActive() )
331 return leftBearing; 334 return leftBearing;
332 pntr->setFont( fn ); 335 pntr->setFont( fn );
333 return pntr->fontMetrics().minLeftBearing(); 336 return pntr->fontMetrics().minLeftBearing();
334} 337}
335 338
336int QTextFormat::minRightBearing() const 339int QTextFormat::minRightBearing() const
337{ 340{
338 if ( !pntr || !pntr->isActive() ) 341 if ( !pntr || !pntr->isActive() )
339 return rightBearing; 342 return rightBearing;
340 pntr->setFont( fn ); 343 pntr->setFont( fn );
341 return pntr->fontMetrics().minRightBearing(); 344 return pntr->fontMetrics().minRightBearing();
342} 345}
343 346
344int QTextFormat::height() const 347int QTextFormat::height() const
345{ 348{
346 if ( !pntr || !pntr->isActive() ) 349 if ( !pntr || !pntr->isActive() )
347 return hei; 350 return hei;
348 pntr->setFont( fn ); 351 pntr->setFont( fn );
349 return pntr->fontMetrics().lineSpacing(); 352 return pntr->fontMetrics().lineSpacing();
350} 353}
351 354
352int QTextFormat::ascent() const 355int QTextFormat::ascent() const
353{ 356{
354 if ( !pntr || !pntr->isActive() ) 357 if ( !pntr || !pntr->isActive() )
355 return asc; 358 return asc;
356 pntr->setFont( fn ); 359 pntr->setFont( fn );
357 return pntr->fontMetrics().ascent() + (pntr->fontMetrics().leading()+1)/2; 360 return pntr->fontMetrics().ascent() + (pntr->fontMetrics().leading()+1)/2;
358} 361}
359 362
360int QTextFormat::descent() const 363int QTextFormat::descent() const
361{ 364{
362 if ( !pntr || !pntr->isActive() ) 365 if ( !pntr || !pntr->isActive() )
363 return dsc; 366 return dsc;
364 pntr->setFont( fn ); 367 pntr->setFont( fn );
365 return pntr->fontMetrics().descent(); 368 return pntr->fontMetrics().descent();
366} 369}
367 370
368int QTextFormat::leading() const 371int QTextFormat::leading() const
369{ 372{
370 if ( !pntr || !pntr->isActive() ) 373 if ( !pntr || !pntr->isActive() )
371 return fm.leading(); 374 return fm.leading();
372 pntr->setFont( fn ); 375 pntr->setFont( fn );
373 return pntr->fontMetrics().leading(); 376 return pntr->fontMetrics().leading();
374} 377}
375 378
376void QTextFormat::generateKey() 379void QTextFormat::generateKey()
377{ 380{
378 k = getKey( fn, col, isMisspelled(), vAlign() ); 381 k = getKey( fn, col, isMisspelled(), vAlign() );
379} 382}
380 383
381QString QTextFormat::getKey( const QFont &fn, const QColor &col, bool misspelled, VerticalAlignment a ) 384QString QTextFormat::getKey( const QFont &fn, const QColor &col, bool misspelled, VerticalAlignment a )
382{ 385{
383 QString k = fn.key(); 386 QString k = fn.key();
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,446 +1,451 @@
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 );
106 111
107 // enter today's date in the date box as default 112 // enter today's date in the date box as default
108 QDate today = QDate::currentDate (); 113 QDate today = QDate::currentDate ();
109 int defaultday = today.day(); 114 int defaultday = today.day();
110 int defaultmonth = today.month(); 115 int defaultmonth = today.month();
111 int defaultyear = today.year(); 116 int defaultyear = today.year();
112 newaccount->startdate->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) ); 117 newaccount->startdate->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) );
113 118
114 //add account information if user pushes OK button 119 //add account information if user pushes OK button
115 if ( newaccount->exec() == QDialog::Accepted ) 120 if ( newaccount->exec() == QDialog::Accepted )
116 { 121 {
117 if ( newaccount->childcheckbox->isChecked () == TRUE ) // set a parent id and type for a child account 122 if ( newaccount->childcheckbox->isChecked () == TRUE ) // set a parent id and type for a child account
118 { 123 {
119 // go through the parentlist we created and determine the parent accountid 124 // go through the parentlist we created and determine the parent accountid
120 // we can't use the name of the account because there may be two accounts 125 // we can't use the name of the account because there may be two accounts
121 // with the same name. This function does it all by accountid 126 // with the same name. This function does it all by accountid
122 int counter; 127 int counter;
123 for ( counter = 0; counter < listview->childCount() + 1; counter++ ) 128 for ( counter = 0; counter < listview->childCount() + 1; counter++ )
124 if ( ( parentlist [ counter ] [ 2 ].toInt() ) == newaccount->childbox->currentItem() ) 129 if ( ( parentlist [ counter ] [ 2 ].toInt() ) == newaccount->childbox->currentItem() )
125 { 130 {
126 parentid = parentlist [ counter ] [ 1 ].toInt(); 131 parentid = parentlist [ counter ] [ 1 ].toInt();
127 break; 132 break;
128 } 133 }
129 type = ( newaccount->accounttype->currentItem() ) + 6; // sets account ids for child accounts. See accountdisplay.h for types 134 type = ( newaccount->accounttype->currentItem() ) + 6; // sets account ids for child accounts. See accountdisplay.h for types
130 } 135 }
131 else 136 else
132 { 137 {
133 parentid = -1; 138 parentid = -1;
134 type = newaccount->accounttype->currentItem(); // sets account ids for parent accounts 139 type = newaccount->accounttype->currentItem(); // sets account ids for parent accounts
135 } 140 }
136 141
137 // add the new account 142 // add the new account
138 if ( newaccount->getDateEdited () == TRUE ) 143 if ( newaccount->getDateEdited () == TRUE )
139 account->addAccount ( newaccount->accountname->text(), parentid, newaccount->accountbalance->text().toFloat(), type, 144 account->addAccount ( newaccount->accountname->text(), parentid, newaccount->accountbalance->text().toFloat(), type,
140 newaccount->getDescription(), newaccount->creditlimit->text().toFloat(), newaccount->getYear(), 145 newaccount->getDescription(), newaccount->creditlimit->text().toFloat(), newaccount->getYear(),
141 newaccount->getMonth(), newaccount->getDay(), newaccount->accountbalance->text().toFloat(), newaccount->currencybox->currencybox->currentText() ); 146 newaccount->getMonth(), newaccount->getDay(), newaccount->accountbalance->text().toFloat(), newaccount->currencybox->currencybox->currentText() );
142 else 147 else
143 account->addAccount ( newaccount->accountname->text (), parentid, newaccount->accountbalance->text().toFloat(), type, 148 account->addAccount ( newaccount->accountname->text (), parentid, newaccount->accountbalance->text().toFloat(), type,
144 newaccount->getDescription(), newaccount->creditlimit->text().toFloat(), defaultyear, 149 newaccount->getDescription(), newaccount->creditlimit->text().toFloat(), defaultyear,
145 defaultmonth, defaultday, newaccount->accountbalance->text().toFloat(), newaccount->currencybox->currencybox->currentText() ); 150 defaultmonth, defaultday, newaccount->accountbalance->text().toFloat(), newaccount->currencybox->currencybox->currentText() );
146 151
147 if ( parentid != -1 ) 152 if ( parentid != -1 )
148 account->changeParentAccountBalance ( parentid ); 153 account->changeParentAccountBalance ( parentid );
149 154
150 // redisplay accounts 155 // redisplay accounts
151 // this function clears the account display first 156 // this function clears the account display first
152 account->displayAccounts ( listview ); 157 account->displayAccounts ( listview );
153 setToggleButton(); 158 setToggleButton();
154 } 159 }
155 maintabs->setTabEnabled ( tab2, FALSE ); 160 maintabs->setTabEnabled ( tab2, FALSE );
156 } 161 }
157 162
158void AccountDisplay::deleteAccount () 163void AccountDisplay::deleteAccount ()
159 { 164 {
160 if ( listview->selectedItem() == 0 ) 165 if ( listview->selectedItem() == 0 )
161 QMessageBox::warning ( this, "QashMoney", "Please select an account\nto delete."); 166 QMessageBox::warning ( this, "QashMoney", "Please select an account\nto delete.");
162 else if ( listview->selectedItem()->parent() == 0 && listview->selectedItem()->childCount() != 0 ) 167 else if ( listview->selectedItem()->parent() == 0 && listview->selectedItem()->childCount() != 0 )
163 QMessageBox::warning ( this, "QashMoney", "Can't delete parent accounts\nwith children"); 168 QMessageBox::warning ( this, "QashMoney", "Can't delete parent accounts\nwith children");
164 else 169 else
165 { 170 {
166 QMessageBox mb ( "Delete Account", "This will delete all transactions\nand transfers for this account.", QMessageBox::Information, QMessageBox::Ok, QMessageBox::Cancel, QMessageBox::NoButton ); 171 QMessageBox mb ( "Delete Account", "This will delete all transactions\nand transfers for this account.", QMessageBox::Information, QMessageBox::Ok, QMessageBox::Cancel, QMessageBox::NoButton );
167 if ( mb.exec() == QMessageBox::Ok ) 172 if ( mb.exec() == QMessageBox::Ok )
168 { 173 {
169 int accountid = listview->selectedItem()->text ( getIDColumn() ).toInt (); 174 int accountid = listview->selectedItem()->text ( getIDColumn() ).toInt ();
170 int parentid = account->getParentAccountID ( accountid ); 175 int parentid = account->getParentAccountID ( accountid );
171 176
172 // delete all the transactions and transfers for the account 177 // delete all the transactions and transfers for the account
173 transaction->deleteAllTransactions ( accountid ); 178 transaction->deleteAllTransactions ( accountid );
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 {
367 // set the accountid 372 // set the accountid
368 int accountid = listview->selectedItem()->text ( getIDColumn() ).toInt(); 373 int accountid = listview->selectedItem()->text ( getIDColumn() ).toInt();
369 374
370 //construct new dialog box 375 //construct new dialog box
371 QDialog *editaccountwindow = new QDialog ( this, 0, TRUE ); 376 QDialog *editaccountwindow = new QDialog ( this, 0, TRUE );
372 editaccountwindow->setCaption ( "Edit Account" ); 377 editaccountwindow->setCaption ( "Edit Account" );
373 378
374 // construct the items which will go in the dialog bix 379 // construct the items which will go in the dialog bix
375 QLabel *namelabel = new QLabel ( "Account Name", editaccountwindow ); 380 QLabel *namelabel = new QLabel ( "Account Name", editaccountwindow );
376 QLineEdit *accountname = new QLineEdit ( editaccountwindow ); 381 QLineEdit *accountname = new QLineEdit ( editaccountwindow );
377 QLabel *descriptionlabel = new QLabel ( "Account Description", editaccountwindow ); 382 QLabel *descriptionlabel = new QLabel ( "Account Description", editaccountwindow );
378 QLineEdit *accountdescription = new QLineEdit ( editaccountwindow ); 383 QLineEdit *accountdescription = new QLineEdit ( editaccountwindow );
379 Currency *currencybox = new Currency ( editaccountwindow ); 384 Currency *currencybox = new Currency ( editaccountwindow );
380 385
381 QVBoxLayout *layout = new QVBoxLayout ( editaccountwindow, 5, 2 ); 386 QVBoxLayout *layout = new QVBoxLayout ( editaccountwindow, 5, 2 );
382 layout->addWidget ( namelabel ); 387 layout->addWidget ( namelabel );
383 layout->addWidget ( accountname ); 388 layout->addWidget ( accountname );
384 layout->addWidget ( descriptionlabel ); 389 layout->addWidget ( descriptionlabel );
385 layout->addWidget ( accountdescription ); 390 layout->addWidget ( accountdescription );
386 layout->addWidget ( currencybox ); 391 layout->addWidget ( currencybox );
387 392
388 //set the account name 393 //set the account name
389 accountname->setText ( listview->selectedItem()->text ( 0 ) ); 394 accountname->setText ( listview->selectedItem()->text ( 0 ) );
390 395
391 //set the account description 396 //set the account description
392 accountdescription->setText ( account->getAccountDescription ( accountid ) ); 397 accountdescription->setText ( account->getAccountDescription ( accountid ) );
393 398
394 if ( preferences->getPreference ( 4 ) == 1 ) 399 if ( preferences->getPreference ( 4 ) == 1 )
395 { 400 {
396 // get currency code for this account then iterate through the currency box 401 // get currency code for this account then iterate through the currency box
397 // to find the one we want 402 // to find the one we want
398 int count = currencybox->currencybox->count(); 403 int count = currencybox->currencybox->count();
399 QString code = account->getCurrencyCode ( accountid ); 404 QString code = account->getCurrencyCode ( accountid );
400 for ( int counter = 0; count - 1; counter++ ) 405 for ( int counter = 0; count - 1; counter++ )
401 { 406 {
402 if ( QString::compare ( currencybox->currencybox->text ( counter ), code ) == 0 ) 407 if ( QString::compare ( currencybox->currencybox->text ( counter ), code ) == 0 )
403 { 408 {
404 currencybox->currencybox->setCurrentItem ( counter ); 409 currencybox->currencybox->setCurrentItem ( counter );
405 break; 410 break;
406 } 411 }
407 } 412 }
408 } 413 }
409 else 414 else
410 currencybox->setEnabled ( FALSE ); 415 currencybox->setEnabled ( FALSE );
411 416
412 //execute the dialog box 417 //execute the dialog box
413 int response = editaccountwindow->exec(); 418 int response = editaccountwindow->exec();
414 if ( response == 1 ) 419 if ( response == 1 )
415 { 420 {
416 account->updateAccount ( accountname->text(), accountdescription->text(), currencybox->currencybox->currentText(), accountid ); 421 account->updateAccount ( accountname->text(), accountdescription->text(), currencybox->currencybox->currentText(), accountid );
417 account->displayAccounts ( listview ); 422 account->displayAccounts ( listview );
418 423
419 // Try and select the same account that was just edited 424 // Try and select the same account that was just edited
420 QListViewItemIterator it ( listview ); 425 QListViewItemIterator it ( listview );
421 for ( ; it.current(); ++it ) 426 for ( ; it.current(); ++it )
422 { 427 {
423 if ( it.current()->text ( 0 ) == accountname->text() ) 428 if ( it.current()->text ( 0 ) == accountname->text() )
424 { 429 {
425 listview->setSelected ( it.current(), TRUE ); 430 listview->setSelected ( it.current(), TRUE );
426 return; 431 return;
427 } 432 }
428 } 433 }
429 maintabs->setTabEnabled ( tab2, FALSE ); 434 maintabs->setTabEnabled ( tab2, FALSE );
430 } 435 }
431 } 436 }
432 } 437 }
433 438
434void AccountDisplay::setAccountExpanded ( QListViewItem *item ) 439void AccountDisplay::setAccountExpanded ( QListViewItem *item )
435 { 440 {
436 int accountid = item->text ( getIDColumn() ).toInt(); 441 int accountid = item->text ( getIDColumn() ).toInt();
437 account->setAccountExpanded ( 1, accountid ); 442 account->setAccountExpanded ( 1, accountid );
438 } 443 }
439 444
440void AccountDisplay::setAccountCollapsed ( QListViewItem *item ) 445void AccountDisplay::setAccountCollapsed ( QListViewItem *item )
441 { 446 {
442 int accountid = item->text ( getIDColumn() ).toInt(); 447 int accountid = item->text ( getIDColumn() ).toInt();
443 account->setAccountExpanded ( 0, accountid ); 448 account->setAccountExpanded ( 0, accountid );
444 } 449 }
445 450
446 451
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,1470 +1,1478 @@
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{
125 clear(); 133 clear();
126} 134}
127 135
128void TVVariantPrivate::clear() 136void TVVariantPrivate::clear()
129{ 137{
130 switch( typ ) 138 switch( typ )
131 { 139 {
132 case TVVariant::String: 140 case TVVariant::String:
133 delete (QString *)value.ptr; 141 delete (QString *)value.ptr;
134 break; 142 break;
135 case TVVariant::Date: 143 case TVVariant::Date:
136 delete (QDate *)value.ptr; 144 delete (QDate *)value.ptr;
137 break; 145 break;
138 case TVVariant::Time: 146 case TVVariant::Time:
139 delete (QTime *)value.ptr; 147 delete (QTime *)value.ptr;
140 break; 148 break;
141 case TVVariant::Invalid: 149 case TVVariant::Invalid:
142 case TVVariant::Int: 150 case TVVariant::Int:
143 break; 151 break;
144 } 152 }
145 153
146 typ = TVVariant::Invalid; 154 typ = TVVariant::Invalid;
147} 155}
148 156
149/*! 157/*!
150 \class TVVariant 158 \class TVVariant
151 blah 159 blah
152*/ 160*/
153 161
154TVVariant::TVVariant() 162TVVariant::TVVariant()
155{ 163{
156 d = new TVVariantPrivate; 164 d = new TVVariantPrivate;
157} 165}
158 166
159TVVariant::~TVVariant() 167TVVariant::~TVVariant()
160{ 168{
161 if (d->deref()) 169 if (d->deref())
162 delete d; 170 delete d;
163} 171}
164 172
165TVVariant::TVVariant(const TVVariant& p) 173TVVariant::TVVariant(const TVVariant& p)
166{ 174{
167 d = new TVVariantPrivate; 175 d = new TVVariantPrivate;
168 *this = p; 176 *this = p;
169} 177}
170 178
171TVVariant::TVVariant(QDataStream& s) 179TVVariant::TVVariant(QDataStream& s)
172{ 180{
173 d = new TVVariantPrivate; 181 d = new TVVariantPrivate;
174 s >> *this; 182 s >> *this;
175} 183}
176 184
177TVVariant::TVVariant(const QString &val) 185TVVariant::TVVariant(const QString &val)
178{ 186{
179 d = new TVVariantPrivate; 187 d = new TVVariantPrivate;
180 d->typ = String; 188 d->typ = String;
181 d->value.ptr = new QString(val); 189 d->value.ptr = new QString(val);
182} 190}
183 191
184TVVariant::TVVariant(const QDate &val) 192TVVariant::TVVariant(const QDate &val)
185{ 193{
186 d = new TVVariantPrivate; 194 d = new TVVariantPrivate;
187 d->typ = Date; 195 d->typ = Date;
188 d->value.ptr = new QDate(val); 196 d->value.ptr = new QDate(val);
189} 197}
190 198
191TVVariant::TVVariant(const QTime &val) 199TVVariant::TVVariant(const QTime &val)
192{ 200{
193 d = new TVVariantPrivate; 201 d = new TVVariantPrivate;
194 d->typ = Time; 202 d->typ = Time;
195 d->value.ptr = new QTime(val); 203 d->value.ptr = new QTime(val);
196} 204}
197 205
198TVVariant::TVVariant( int val ) 206TVVariant::TVVariant( int val )
199{ 207{
200 d = new TVVariantPrivate; 208 d = new TVVariantPrivate;
201 d->typ = Int; 209 d->typ = Int;
202 d->value.i = val; 210 d->value.i = val;
203} 211}
204 212
205TVVariant& TVVariant::operator=(const TVVariant& variant ) 213TVVariant& TVVariant::operator=(const TVVariant& variant )
206{ 214{
207 TVVariant& other = (TVVariant&) variant; 215 TVVariant& other = (TVVariant&) variant;
208 216
209 other.d->ref(); 217 other.d->ref();
210 if ( d->deref() ) 218 if ( d->deref() )
211 delete d; 219 delete d;
212 220
213 d = other.d; 221 d = other.d;
214 222
215 return *this; 223 return *this;
216} 224}
217 225
218void TVVariant::detach() 226void 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
412 int day = parseNextNumber(&q); 420 int day = parseNextNumber(&q);
413 int month = parseNextNumber(&q); 421 int month = parseNextNumber(&q);
414 int year = parseNextNumber(&q); 422 int year = parseNextNumber(&q);
415 if (!QDate::isValid(year, month, day)) 423 if (!QDate::isValid(year, month, day))
416 return QDate(); 424 return QDate();
417 return QDate(year, month, day); 425 return QDate(year, month, day);
418 } 426 }
419 427
420 428
421 return QDate(); 429 return QDate();
422} 430}
423 431
424const QTime TVVariant::toTime() const 432const QTime TVVariant::toTime() const
425{ 433{
426 if(d->typ == Time) 434 if(d->typ == Time)
427 return *((QTime *)d->value.ptr); 435 return *((QTime *)d->value.ptr);
428 436
429 if(d->typ == String) { 437 if(d->typ == String) {
430 QString q = toString(); 438 QString q = toString();
431 int hour = parseNextNumber(&q); 439 int hour = parseNextNumber(&q);
432 int minute = parseNextNumber(&q); 440 int minute = parseNextNumber(&q);
433 int second = parseNextNumber(&q); 441 int second = parseNextNumber(&q);
434 int msecond = parseNextNumber(&q); 442 int msecond = parseNextNumber(&q);
435 if (!QTime::isValid(hour, minute, second, msecond)) 443 if (!QTime::isValid(hour, minute, second, msecond))
436 return QTime(); 444 return QTime();
437 return QTime(hour, minute, second, msecond); 445 return QTime(hour, minute, second, msecond);
438 } 446 }
439 447
440 return QTime(); 448 return QTime();
441} 449}
442 450
443#define TV_VARIANT_AS( f ) Q##f& TVVariant::as##f() { \ 451#define TV_VARIANT_AS( f ) Q##f& TVVariant::as##f() { \
444 if ( d->typ != f ) \ 452 if ( d->typ != f ) \
445 *this = TVVariant( to##f() ); \ 453 *this = TVVariant( to##f() ); \
446 else \ 454 else \
447 detach(); \ 455 detach(); \
448 return *((Q##f*)d->value.ptr); } 456 return *((Q##f*)d->value.ptr); }
449 457
450TV_VARIANT_AS(String) 458TV_VARIANT_AS(String)
451TV_VARIANT_AS(Date) 459TV_VARIANT_AS(Date)
452TV_VARIANT_AS(Time) 460TV_VARIANT_AS(Time)
453 461
454#undef TV_VARIANT_AS 462#undef TV_VARIANT_AS
455 463
456int& TVVariant::asInt() 464int& TVVariant::asInt()
457{ 465{
458 detach(); 466 detach();
459 if (d->typ != Int) { 467 if (d->typ != Int) {
460 d->value.i = toInt(); 468 d->value.i = toInt();
461 d->typ = Int; 469 d->typ = Int;
462 } 470 }
463 return d->value.i; 471 return d->value.i;
464} 472}
465 473
466/*! 474/*!
467 valid cast is 475 valid cast is
468 anything to String 476 anything to String
469 same to same 477 same to same
470*/ 478*/
471bool TVVariant::canCast(KeyType t) const 479bool TVVariant::canCast(KeyType t) const
472{ 480{
473 if(d->typ == t) 481 if(d->typ == t)
474 return TRUE; 482 return TRUE;
475 483
476 if(t == String) 484 if(t == String)
477 return TRUE; 485 return TRUE;
478 486
479 if(t == Int) { 487 if(t == Int) {
480 if (d->typ == Date) 488 if (d->typ == Date)
481 return TRUE; 489 return TRUE;
482 if (d->typ == Time) 490 if (d->typ == Time)
483 return TRUE; 491 return TRUE;
484 if (d->typ == String) 492 if (d->typ == String)
485 return TRUE; 493 return TRUE;
486 } 494 }
487 495
488 return FALSE; 496 return FALSE;
489} 497}
490 498
491bool TVVariant::operator==( const TVVariant &v ) const 499bool TVVariant::operator==( const TVVariant &v ) const
492{ 500{
493 switch(d->typ) { 501 switch(d->typ) {
494 case String: 502 case String:
495 return v.toString() == toString(); 503 return v.toString() == toString();
496 case Date: 504 case Date:
497 return v.toDate() == toDate(); 505 return v.toDate() == toDate();
498 case Time: 506 case Time:
499 return v.toTime() == toTime(); 507 return v.toTime() == toTime();
500 case Int: 508 case Int:
501 return v.toInt() == toInt(); 509 return v.toInt() == toInt();
502 case Invalid: 510 case Invalid:
503 break; 511 break;
504 } 512 }
505 513
506 return FALSE; 514 return FALSE;
507} 515}
508 516
509bool TVVariant::operator!=( const TVVariant &v ) const 517bool TVVariant::operator!=( const TVVariant &v ) const
510{ 518{
511 return !( v == *this); 519 return !( v == *this);
512} 520}
513 521
514bool TVVariant::operator<( const TVVariant &v ) const 522bool TVVariant::operator<( const TVVariant &v ) const
515{ 523{
516 switch(d->typ) { 524 switch(d->typ) {
517 case String: 525 case String:
518 return toString().lower() < v.toString().lower(); 526 return toString().lower() < v.toString().lower();
519 case Date: 527 case Date:
520 return toDate() < v.toDate(); 528 return toDate() < v.toDate();
521 case Time: 529 case Time:
522 return toTime() < v.toTime(); 530 return toTime() < v.toTime();
523 case Int: 531 case Int:
524 return toInt() < v.toInt(); 532 return toInt() < v.toInt();
525 case Invalid: 533 case Invalid:
526 default: 534 default:
527 break; 535 break;
528 } 536 }
529 return FALSE; 537 return FALSE;
530} 538}
531 539
532bool TVVariant::operator>( const TVVariant &v ) const 540bool TVVariant::operator>( const TVVariant &v ) const
533{ 541{
534 switch(d->typ) { 542 switch(d->typ) {
535 case String: 543 case String:
536 return toString().lower() > v.toString().lower(); 544 return toString().lower() > v.toString().lower();
537 case Date: 545 case Date:
538 return toDate() > v.toDate(); 546 return toDate() > v.toDate();
539 case Time: 547 case Time:
540 return toTime() > v.toTime(); 548 return toTime() > v.toTime();
541 case Int: 549 case Int:
542 return toInt() > v.toInt(); 550 return toInt() > v.toInt();
543 case Invalid: 551 case Invalid:
544 default: 552 default:
545 break; 553 break;
546 } 554 }
547 return FALSE; 555 return FALSE;
548} 556}
549 557
550/*! True if n is closer to this than o */ 558/*! True if n is closer to this than o */
551bool TVVariant::closer(TVVariant n, TVVariant o) 559bool TVVariant::closer(TVVariant n, TVVariant o)
552{ 560{
553 /* Nothing is close to an invalid, so nothing can be closer */ 561 /* Nothing is close to an invalid, so nothing can be closer */
554 if(d->typ == Invalid) 562 if(d->typ == Invalid)
555 return FALSE; 563 return FALSE;
556 564
557 /* can't be closer if of different type */ 565 /* can't be closer if of different type */
558 if(n.type() != type()) 566 if(n.type() != type())
559 return FALSE; 567 return FALSE;
560 568
561 /* if new shares type, and old doesn't, then new is closer */ 569 /* if new shares type, and old doesn't, then new is closer */
562 if(o.type() != type()) 570 if(o.type() != type())
563 return TRUE; 571 return TRUE;
564 572
565 switch(type()){ 573 switch(type()){
566 case String: { 574 case String: {
567 /* case for strings is close is a substring.. closer is 575 /* case for strings is close is a substring.. closer is
568 * earlier alphabetically */ 576 * earlier alphabetically */
569 QString qs1 = n.toString().lower(); 577 QString qs1 = n.toString().lower();
570 QString qs2 = o.toString().lower(); 578 QString qs2 = o.toString().lower();
571 QString qsv = toString().lower(); 579 QString qsv = toString().lower();
572 580
573 if (!qs1.startsWith(qsv)) 581 if (!qs1.startsWith(qsv))
574 return FALSE; 582 return FALSE;
575 583
576 /* contains sub-str, if later than is not closer */ 584 /* contains sub-str, if later than is not closer */
577 if(QString::compare(qs1, qs2) > 0) 585 if(QString::compare(qs1, qs2) > 0)
578 return FALSE; 586 return FALSE;
579 return TRUE; 587 return TRUE;
580 } 588 }
581 case Int: { 589 case Int: {
582 /* case for int is smallest absolute difference */ 590 /* case for int is smallest absolute difference */
583 int i1 = n.toInt(); 591 int i1 = n.toInt();
584 int i2 = o.toInt(); 592 int i2 = o.toInt();
585 int iv = toInt(); 593 int iv = toInt();
586 594
587 int diff1 = (i1 - iv); 595 int diff1 = (i1 - iv);
588 if (diff1 < 0) 596 if (diff1 < 0)
589 diff1 = -diff1; 597 diff1 = -diff1;
590 int diff2 = (i2 - iv); 598 int diff2 = (i2 - iv);
591 if (diff2 < 0) 599 if (diff2 < 0)
592 diff2 = -diff2; 600 diff2 = -diff2;
593 601
594 if (diff1 < diff2) 602 if (diff1 < diff2)
595 return TRUE; 603 return TRUE;
596 return FALSE; 604 return FALSE;
597 } 605 }
598 case Date: { 606 case Date: {
599 QDate i1 = n.toDate(); 607 QDate i1 = n.toDate();
600 QDate i2 = o.toDate(); 608 QDate i2 = o.toDate();
601 QDate iv = toDate(); 609 QDate iv = toDate();
602 610
603 /* definition of closer is the least difference in days */ 611 /* definition of closer is the least difference in days */
604 int diff1 = i1.daysTo(iv); 612 int diff1 = i1.daysTo(iv);
605 if (diff1 < 0) 613 if (diff1 < 0)
606 diff1 = -diff1; 614 diff1 = -diff1;
607 int diff2 = i2.daysTo(iv); 615 int diff2 = i2.daysTo(iv);
608 if (diff2 < 0) 616 if (diff2 < 0)
609 diff2 = -diff2; 617 diff2 = -diff2;
610 618
611 if (diff1 < diff2) 619 if (diff1 < diff2)
612 return TRUE; 620 return TRUE;
613 return FALSE; 621 return FALSE;
614 } 622 }
615 case Time: { 623 case Time: {
616 QTime i1 = n.toTime(); 624 QTime i1 = n.toTime();
617 QTime i2 = o.toTime(); 625 QTime i2 = o.toTime();
618 QTime iv = toTime(); 626 QTime iv = toTime();
619 627
620 /* definition of closer is the least difference in days */ 628 /* definition of closer is the least difference in days */
621 int diff1 = i1.msecsTo(iv); 629 int diff1 = i1.msecsTo(iv);
622 if (diff1 < 0) 630 if (diff1 < 0)
623 diff1 = -diff1; 631 diff1 = -diff1;
624 int diff2 = i2.msecsTo(iv); 632 int diff2 = i2.msecsTo(iv);
625 if (diff2 < 0) 633 if (diff2 < 0)
626 diff2 = -diff2; 634 diff2 = -diff2;
627 if (diff1 < diff2) 635 if (diff1 < diff2)
628 return TRUE; 636 return TRUE;
629 return FALSE; 637 return FALSE;
630 } 638 }
631 default: 639 default:
632 /* don't know how to do 'closer' on this type, hence never closer 640 /* don't know how to do 'closer' on this type, hence never closer
633 * or even close */ 641 * or even close */
634 break; 642 break;
635 } 643 }
636 return FALSE; 644 return FALSE;
637} 645}
638 646
639/*! True if n is close to this */ 647/*! True if n is close to this */
640bool TVVariant::close(TVVariant n) 648bool TVVariant::close(TVVariant n)
641{ 649{
642 /* Nothing is close to an invalid, so nothing can be closer */ 650 /* Nothing is close to an invalid, so nothing can be closer */
643 if(type() == Invalid) 651 if(type() == Invalid)
644 return FALSE; 652 return FALSE;
645 653
646 /* can't be close if of different type */ 654 /* can't be close if of different type */
647 if(n.type() != type()) 655 if(n.type() != type())
648 return FALSE; 656 return FALSE;
649 657
650 switch(type()){ 658 switch(type()){
651 case String: { 659 case String: {
652 /* case for strings is close is a substring.. closer is 660 /* case for strings is close is a substring.. closer is
653 * earlier alphabetically */ 661 * earlier alphabetically */
654 QString qs1 = n.toString().lower(); 662 QString qs1 = n.toString().lower();
655 QString qsv = toString().lower(); 663 QString qsv = toString().lower();
656 664
657 if (!qs1.startsWith(qsv)) 665 if (!qs1.startsWith(qsv))
658 return FALSE; 666 return FALSE;
659 return TRUE; 667 return TRUE;
660 } 668 }
661 case Int: 669 case Int:
662 case Date: 670 case Date:
663 case Time: 671 case Time:
664 return TRUE; 672 return TRUE;
665 default: 673 default:
666 /* don't know how to do 'closer' on this type, hence never closer 674 /* don't know how to do 'closer' on this type, hence never closer
667 * or even close */ 675 * or even close */
668 break; 676 break;
669 } 677 }
670 return FALSE; 678 return FALSE;
671} 679}
672 680
673/*! 681/*!
674 \class Key 682 \class Key
675 \brief document me! 683 \brief document me!
676 684
677 document me! 685 document me!
678*/ 686*/
679 687
680Key::Key() : kname(), kexample(), kflags(0) { } 688Key::Key() : kname(), kexample(), kflags(0) { }
681 689
682Key::Key(QString name, TVVariant example, int flags) : 690Key::Key(QString name, TVVariant example, int flags) :
683 kname(name), kexample(example), kflags(flags) { } 691 kname(name), kexample(example), kflags(flags) { }
684 692
685Key::Key(const Key &other) 693Key::Key(const Key &other)
686{ 694{
687 kname = other.kname; 695 kname = other.kname;
688 kexample = other.kexample; 696 kexample = other.kexample;
689 kflags = other.kflags; 697 kflags = other.kflags;
690} 698}
691 699
692Key& Key::operator=(const Key& key) 700Key& Key::operator=(const Key& key)
693{ 701{
694 kname = key.kname; 702 kname = key.kname;
695 kexample = key.kexample; 703 kexample = key.kexample;
696 kflags = key.kflags; 704 kflags = key.kflags;
697 return *this; 705 return *this;
698} 706}
699 707
700QString Key::name() const 708QString Key::name() const
701{ 709{
702 return QString(kname); 710 return QString(kname);
703} 711}
704 712
705TVVariant Key::example() const 713TVVariant Key::example() const
706{ 714{
707 return TVVariant(kexample); 715 return TVVariant(kexample);
708} 716}
709 717
710TVVariant::KeyType Key::type() const 718TVVariant::KeyType Key::type() const
711{ 719{
712 return kexample.type(); 720 return kexample.type();
713} 721}
714 722
715void Key::setName(const QString &name) 723void Key::setName(const QString &name)
716{ 724{
717 kname = QString(name); 725 kname = QString(name);
718} 726}
719 727
720void Key::setExample(const TVVariant &e) 728void Key::setExample(const TVVariant &e)
721{ 729{
722 kexample = TVVariant(e); 730 kexample = TVVariant(e);
723} 731}
724 732
725int Key::flags() const 733int Key::flags() const
726{ 734{
727 return kflags; 735 return kflags;
728} 736}
729 737
730void Key::setFlags(int fl) 738void Key::setFlags(int fl)
731{ 739{
732 kflags = fl; 740 kflags = fl;
733} 741}
734 742
735bool Key::delFlag() const 743bool Key::delFlag() const
736{ 744{
737 if(kflags & del_flag) 745 if(kflags & del_flag)
738 return TRUE; 746 return TRUE;
739 return FALSE; 747 return FALSE;
740} 748}
741 749
742bool Key::newFlag() const 750bool Key::newFlag() const
743{ 751{
744 if(kflags & new_flag) 752 if(kflags & new_flag)
745 return TRUE; 753 return TRUE;
746 return FALSE; 754 return FALSE;
747} 755}
748 756
749void Key::setDelFlag(bool v) 757void Key::setDelFlag(bool v)
750{ 758{
751 if(delFlag() != v) 759 if(delFlag() != v)
752 kflags = kflags ^ del_flag; 760 kflags = kflags ^ del_flag;
753} 761}
754 762
755void Key::setNewFlag(bool v) 763void Key::setNewFlag(bool v)
756{ 764{
757 if(newFlag() != v) 765 if(newFlag() != v)
758 kflags = kflags ^ new_flag; 766 kflags = kflags ^ new_flag;
759} 767}
760 768
761/*! 769/*!
762 \class KeyList 770 \class KeyList
763 \brief A represntation of keys used for a table. 771 \brief A represntation of keys used for a table.
764 772
765 The KeyList class is used to store the representation of keys used in table 773 The KeyList class is used to store the representation of keys used in table
766 headings by DBStore. It stores the names and types of the keys 774 headings by DBStore. It stores the names and types of the keys
767*/ 775*/
768 776
769/*! 777/*!
770 Constructs a KeyList 778 Constructs a KeyList
771*/ 779*/
772KeyList::KeyList() : QIntDict<Key>(20) 780KeyList::KeyList() : QIntDict<Key>(20)
773{ 781{
774 setAutoDelete(TRUE); 782 setAutoDelete(TRUE);
775} 783}
776 784
777/* Should be deep copy, but isn't */ 785/* Should be deep copy, but isn't */
778KeyList::KeyList(const KeyList &k) : QIntDict<Key>(k) 786KeyList::KeyList(const KeyList &k) : QIntDict<Key>(k)
779{ 787{
780 KeyListIterator it(k); 788 KeyListIterator it(k);
781 while(it.current()) { 789 while(it.current()) {
782 replace(it.currentKey(), new Key(*it.current())); 790 replace(it.currentKey(), new Key(*it.current()));
783 ++it; 791 ++it;
784 } 792 }
785 793
786 setAutoDelete(TRUE); 794 setAutoDelete(TRUE);
787} 795}
788 796
789/*! 797/*!
790 Destroys a KeyList 798 Destroys a KeyList
791*/ 799*/
792KeyList::~KeyList() { 800KeyList::~KeyList() {
793} 801}
794 802
795/* Do a comparision base on Keys */ 803/* Do a comparision base on Keys */
796bool KeyList::operator!=(const KeyList &other) 804bool KeyList::operator!=(const KeyList &other)
797{ 805{
798 KeyListIterator it(*this); 806 KeyListIterator it(*this);
799 807
800 if (other.getNumFields() != getNumFields()) 808 if (other.getNumFields() != getNumFields())
801 return TRUE; 809 return TRUE;
802 810
803 while(it.current()) { 811 while(it.current()) {
804 //it.currentKey(), it.current(); 812 //it.currentKey(), it.current();
805 if (other.getKeyName(it.currentKey()) != getKeyName(it.currentKey())) 813 if (other.getKeyName(it.currentKey()) != getKeyName(it.currentKey()))
806 return TRUE; 814 return TRUE;
807 if (other.getKeyType(it.currentKey()) != getKeyType(it.currentKey())) 815 if (other.getKeyType(it.currentKey()) != getKeyType(it.currentKey()))
808 return TRUE; 816 return TRUE;
809 ++it; 817 ++it;
810 } 818 }
811 return FALSE; 819 return FALSE;
812} 820}
813 821
814/*! 822/*!
815 Returns the number of keys stored in the KeyList 823 Returns the number of keys stored in the KeyList
816*/ 824*/
817int KeyList::getNumFields() const 825int KeyList::getNumFields() const
818{ 826{
819 return count(); 827 return count();
820} 828}
821 829
822/*! 830/*!
823 Adds a new key to the KeyList 831 Adds a new key to the KeyList
824 832
825 \param name the name of the new key 833 \param name the name of the new key
826 \param type the type of the new key 834 \param type the type of the new key
827*/ 835*/
828int KeyList::addKey(QString name, TVVariant example) 836int KeyList::addKey(QString name, TVVariant example)
829{ 837{
830 int i = count(); 838 int i = count();
831 while(find(i) && (i > -1)) 839 while(find(i) && (i > -1))
832 i--; 840 i--;
833 replace(i, new Key(name, example, 0)); 841 replace(i, new Key(name, example, 0));
834 return i; 842 return i;
835} 843}
836 844
837int KeyList::addKey(QString name, TVVariant::KeyType type) 845int KeyList::addKey(QString name, TVVariant::KeyType type)
838{ 846{
839 /* generate a valid type for the example? */ 847 /* generate a valid type for the example? */
840 TVVariant e = TVVariant("0"); 848 TVVariant e = TVVariant("0");
841 switch(type) { 849 switch(type) {
842 case TVVariant::String: 850 case TVVariant::String:
843 return addKey(name, TVVariant("<undefined>").asString()); 851 return addKey(name, TVVariant("<undefined>").asString());
844 break; 852 break;
845 case TVVariant::Date: 853 case TVVariant::Date:
846 return addKey(name, TVVariant(QDate::currentDate()).asDate()); 854 return addKey(name, TVVariant(QDate::currentDate()).asDate());
847 break; 855 break;
848 case TVVariant::Time: 856 case TVVariant::Time:
849 return addKey(name, TVVariant(QTime(0,0,0)).toTime()); 857 return addKey(name, TVVariant(QTime(0,0,0)).toTime());
850 break; 858 break;
851 case TVVariant::Int: 859 case TVVariant::Int:
852 return addKey(name, TVVariant(0).toInt()); 860 return addKey(name, TVVariant(0).toInt());
853 break; 861 break;
854 default: 862 default:
855 qWarning(QObject::tr("KeyList::addKey() Cannot make default " 863 qWarning(QObject::tr("KeyList::addKey() Cannot make default "
856 "value for type %1, Key not added.").arg(type)); 864 "value for type %1, Key not added.").arg(type));
857 break; 865 break;
858 } 866 }
859 return -1; 867 return -1;
860} 868}
861 869
862void KeyList::setKeyFlags(int i, int flag) 870void KeyList::setKeyFlags(int i, int flag)
863{ 871{
864 if(find(i)) 872 if(find(i))
865 find(i)->setFlags(flag); 873 find(i)->setFlags(flag);
866} 874}
867 875
868int KeyList::getKeyFlags(int i) const 876int KeyList::getKeyFlags(int i) const
869{ 877{
870 if(find(i)) 878 if(find(i))
871 return find(i)->flags(); 879 return find(i)->flags();
872 return 0; 880 return 0;
873} 881}
874 882
875bool KeyList::checkNewFlag(int i) const 883bool KeyList::checkNewFlag(int i) const
876{ 884{
877 if (find(i)) 885 if (find(i))
878 return find(i)->newFlag(); 886 return find(i)->newFlag();
879 return false; 887 return false;
880} 888}
881 889
882void KeyList::setNewFlag(int i, bool f) 890void KeyList::setNewFlag(int i, bool f)
883{ 891{
884 if(!find(i)) 892 if(!find(i))
885 return; 893 return;
886 find(i)->setNewFlag(f); 894 find(i)->setNewFlag(f);
887} 895}
888 896
889bool KeyList::checkDeleteFlag(int i) const 897bool KeyList::checkDeleteFlag(int i) const
890{ 898{
891 if (find(i)) 899 if (find(i))
892 return find(i)->delFlag(); 900 return find(i)->delFlag();
893 return false; 901 return false;
894} 902}
895 903
896void KeyList::setDeleteFlag(int i, bool f) 904void KeyList::setDeleteFlag(int i, bool f)
897{ 905{
898 if(!find(i)) 906 if(!find(i))
899 return; 907 return;
900 find(i)->setDelFlag(f); 908 find(i)->setDelFlag(f);
901} 909}
902 910
903/*! 911/*!
904 Returns the name of the key at index i 912 Returns the name of the key at index i
905*/ 913*/
906QString KeyList::getKeyName(int i) const 914QString KeyList::getKeyName(int i) const
907{ 915{
908 if (find (i)) 916 if (find (i))
909 return find(i)->name(); 917 return find(i)->name();
910 return QString(); 918 return QString();
911} 919}
912 920
913void KeyList::setKeyName(int i, const QString &n) 921void KeyList::setKeyName(int i, const QString &n)
914{ 922{
915 if(find(i)) 923 if(find(i))
916 find(i)->setName(n); 924 find(i)->setName(n);
917} 925}
918 926
919/*! 927/*!
920 Returns the type of the key at index i 928 Returns the type of the key at index i
921*/ 929*/
922TVVariant::KeyType KeyList::getKeyType(int i) const 930TVVariant::KeyType KeyList::getKeyType(int i) const
923{ 931{
924 if(find(i)) 932 if(find(i))
925 return find(i)->type(); 933 return find(i)->type();
926 return TVVariant::Invalid; 934 return TVVariant::Invalid;
927} 935}
928 936
929void KeyList::setKeyType(int i, TVVariant::KeyType t) 937void KeyList::setKeyType(int i, TVVariant::KeyType t)
930{ 938{
931 if(!find(i)) 939 if(!find(i))
932 return; 940 return;
933 switch(t) { 941 switch(t) {
934 case TVVariant::String: 942 case TVVariant::String:
935 find(i)->setExample(TVVariant(QString("default"))); 943 find(i)->setExample(TVVariant(QString("default")));
936 return; 944 return;
937 case TVVariant::Int: 945 case TVVariant::Int:
938 find(i)->setExample(TVVariant(int(0))); 946 find(i)->setExample(TVVariant(int(0)));
939 return; 947 return;
940 case TVVariant::Date: 948 case TVVariant::Date:
941 find(i)->setExample(TVVariant(QDate::currentDate())); 949 find(i)->setExample(TVVariant(QDate::currentDate()));
942 return; 950 return;
943 case TVVariant::Time: 951 case TVVariant::Time:
944 find(i)->setExample(TVVariant(QTime(0,0,0,0))); 952 find(i)->setExample(TVVariant(QTime(0,0,0,0)));
945 return; 953 return;
946 default: 954 default:
947 break; 955 break;
948 } 956 }
949 return; 957 return;
950} 958}
951 959
952TVVariant KeyList::getKeyExample(int i) const 960TVVariant KeyList::getKeyExample(int i) const
953{ 961{
954 if(find(i)) 962 if(find(i))
955 return find(i)->example(); 963 return find(i)->example();
956 return TVVariant(); 964 return TVVariant();
957} 965}
958 966
959void KeyList::setKeyExample(int i, TVVariant example) 967void KeyList::setKeyExample(int i, TVVariant example)
960{ 968{
961 if(find(i)) 969 if(find(i))
962 find(i)->setExample(example); 970 find(i)->setExample(example);
963} 971}
964 972
965/*! 973/*!
966 Returns the index of the key with name q 974 Returns the index of the key with name q
967*/ 975*/
968int KeyList::getKeyIndex(QString q) const 976int KeyList::getKeyIndex(QString q) const
969{ 977{
970 KeyListIterator it(*this); 978 KeyListIterator it(*this);
971 979
972 while(it.current()) { 980 while(it.current()) {
973 if(it.current()->name() == q) 981 if(it.current()->name() == q)
974 return it.currentKey(); 982 return it.currentKey();
975 ++it; 983 ++it;
976 } 984 }
977 return -1; 985 return -1;
978} 986}
979 987
980bool KeyList::validIndex(int i) const 988bool KeyList::validIndex(int i) const
981{ 989{
982 if(!find(i)) 990 if(!find(i))
983 return FALSE; 991 return FALSE;
984 if(find(i)->delFlag()) 992 if(find(i)->delFlag())
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);
1178 1186
1179 TVVariant t = TVVariant(q); 1187 TVVariant t = TVVariant(q);
1180 1188
1181 switch(kt) { 1189 switch(kt) {
1182 case TVVariant::Int: { 1190 case TVVariant::Int: {
1183 t.asInt(); 1191 t.asInt();
1184 setField(i, t); 1192 setField(i, t);
1185 return; 1193 return;
1186 } 1194 }
1187 case TVVariant::String: { 1195 case TVVariant::String: {
1188 t.asString(); 1196 t.asString();
1189 setField(i, t); 1197 setField(i, t);
1190 return; 1198 return;
1191 } 1199 }
1192 case TVVariant::Date: { 1200 case TVVariant::Date: {
1193 t.asDate(); 1201 t.asDate();
1194 setField(i, t); 1202 setField(i, t);
1195 return; 1203 return;
1196 } 1204 }
1197 case TVVariant::Time: { 1205 case TVVariant::Time: {
1198 t.asTime(); 1206 t.asTime();
1199 setField(i, t); 1207 setField(i, t);
1200 return; 1208 return;
1201 } 1209 }
1202 default: 1210 default:
1203 qWarning( 1211 qWarning(
1204 QObject::tr("DataElem::setField(%1, %2) No valid type found").arg(i).arg(q) 1212 QObject::tr("DataElem::setField(%1, %2) No valid type found").arg(i).arg(q)
1205 ); 1213 );
1206 } 1214 }
1207} 1215}
1208 1216
1209/*! 1217/*!
1210 Sets the value of the elements field index i to the value at the pointer 1218 Sets the value of the elements field index i to the value at the pointer
1211 value. 1219 value.
1212 1220
1213 \param i index of the field to set 1221 \param i index of the field to set
1214 \param value a pointer to the (already allocated) value to set 1222 \param value a pointer to the (already allocated) value to set
1215*/ 1223*/
1216void DataElem::setField(int i, TVVariant value) 1224void DataElem::setField(int i, TVVariant value)
1217{ 1225{
1218 if (value.isValid()) { 1226 if (value.isValid()) {
1219 values.remove(i); 1227 values.remove(i);
1220 values.replace(i, new TVVariant(value)); 1228 values.replace(i, new TVVariant(value));
1221 } 1229 }
1222} 1230}
1223 1231
1224/*! 1232/*!
1225 Sets the value of the elements field name qs to the value represented in 1233 Sets the value of the elements field name qs to the value represented in
1226 the QString q. 1234 the QString q.
1227 1235
1228 \param qs name of the field to set 1236 \param qs name of the field to set
1229 \param q a string that can be parsed to get the value to be set 1237 \param q a string that can be parsed to get the value to be set
1230*/ 1238*/
1231void DataElem::setField(QString qs, QString q) 1239void DataElem::setField(QString qs, QString q)
1232{ 1240{
1233 /* from the type of the field, parse q and store */ 1241 /* from the type of the field, parse q and store */
1234 int i = contained->getKeyIndex(qs); 1242 int i = contained->getKeyIndex(qs);
1235 setField(i, qs); 1243 setField(i, qs);
1236} 1244}
1237 1245
1238/*! 1246/*!
1239 Sets the value of the elements field name qs to the value at the pointer 1247 Sets the value of the elements field name qs to the value at the pointer
1240 value. 1248 value.
1241 1249
1242 \param qs name of the field to set 1250 \param qs name of the field to set
1243 \param value a pointer to the (already allocated) value to set 1251 \param value a pointer to the (already allocated) value to set
1244*/ 1252*/
1245void DataElem::setField(QString qs, TVVariant value) 1253void DataElem::setField(QString qs, TVVariant value)
1246{ 1254{
1247 int i = contained->getKeyIndex(qs); 1255 int i = contained->getKeyIndex(qs);
1248 setField(i, value); 1256 setField(i, value);
1249} 1257}
1250 1258
1251void DataElem::unsetField(int i) { 1259void DataElem::unsetField(int i) {
1252 values.remove(i); 1260 values.remove(i);
1253} 1261}
1254 1262
1255void DataElem::unsetField(QString qs) 1263void DataElem::unsetField(QString qs)
1256{ 1264{
1257 int i = contained->getKeyIndex(qs); 1265 int i = contained->getKeyIndex(qs);
1258 unsetField(i); 1266 unsetField(i);
1259} 1267}
1260 1268
1261/*! 1269/*!
1262 Converts the data element to a Rich Text QString 1270 Converts the data element to a Rich Text QString
1263*/ 1271*/
1264QString DataElem::toQString() const 1272QString DataElem::toQString() const
1265{ 1273{
1266 /* lets make an attempt at this function */ 1274 /* lets make an attempt at this function */
1267 int i; 1275 int i;
1268 QString scratch = ""; 1276 QString scratch = "";
1269 1277
1270 QIntDictIterator<TVVariant> it(values); 1278 QIntDictIterator<TVVariant> it(values);
1271 1279
1272 while (it.current()) { 1280 while (it.current()) {
1273 i = it.currentKey(); 1281 i = it.currentKey();
1274 if(hasValidValue(i)) { 1282 if(hasValidValue(i)) {
1275 scratch += "<B>" + contained->getKeyName(i) + ":</B> "; 1283 scratch += "<B>" + contained->getKeyName(i) + ":</B> ";
1276 scratch += getField(i).toString(); 1284 scratch += getField(i).toString();
1277 scratch += "<br>"; 1285 scratch += "<br>";
1278 } 1286 }
1279 ++it; 1287 ++it;
1280 } 1288 }
1281 return scratch; 1289 return scratch;
1282} 1290}
1283 1291
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,293 +1,301 @@
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()
250{ 258{
251 unsigned int new_current_elem = current_elem + 1; 259 unsigned int new_current_elem = current_elem + 1;
252 if (current_elem < number_elems) 260 if (current_elem < number_elems)
253 /* was valid before inc (it is possible but unlikely that inc current 261 /* was valid before inc (it is possible but unlikely that inc current
254 elem will change it from invalid to valid) */ 262 elem will change it from invalid to valid) */
255 if (new_current_elem < number_elems) { 263 if (new_current_elem < number_elems) {
256 /* is valid after inc */ 264 /* is valid after inc */
257 current_elem = new_current_elem; 265 current_elem = new_current_elem;
258 return true; 266 return true;
259 } 267 }
260 return false; 268 return false;
261} 269}
262 270
263/*! 271/*!
264 Sets the current element to the previous element of the database if 272 Sets the current element to the previous element of the database if
265 there exists an element before the current one. 273 there exists an element before the current one.
266*/ 274*/
267bool DBStore::previous() 275bool DBStore::previous()
268{ 276{
269 unsigned int new_current_elem = current_elem -1; 277 unsigned int new_current_elem = current_elem -1;
270 if (current_elem < number_elems) 278 if (current_elem < number_elems)
271 /* was valid */ 279 /* was valid */
272 if (new_current_elem < number_elems) { 280 if (new_current_elem < number_elems) {
273 /* still is (if was 0, then now -1, but as is unsigned will wrap 281 /* still is (if was 0, then now -1, but as is unsigned will wrap
274 and hence be invalid */ 282 and hence be invalid */
275 current_elem = new_current_elem; 283 current_elem = new_current_elem;
276 return true; 284 return true;
277 } 285 }
278 return false; 286 return false;
279} 287}
280 288
281/*! 289/*!
282 Returns the current data element in the database. Which element is current 290 Returns the current data element in the database. Which element is current
283 is affected by newly added items, findItem, next, previous, first and 291 is affected by newly added items, findItem, next, previous, first and
284 last functions 292 last functions
285 293
286 \return a pointer to the current data element 294 \return a pointer to the current data element
287*/ 295*/
288DataElem *DBStore::getCurrentData() 296DataElem *DBStore::getCurrentData()
289{ 297{
290 if (current_elem >= number_elems) 298 if (current_elem >= number_elems)
291 return NULL; 299 return NULL;
292 return master_table[current_elem]; 300 return master_table[current_elem];
293} 301}
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,480 +1,482 @@
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
388 390
389 391
390void TableViewerWindow::editItemSlot() 392void TableViewerWindow::editItemSlot()
391{ 393{
392 if(TVEditView::openEditItemDialog(&ts, ts.current_elem, this)) { 394 if(TVEditView::openEditItemDialog(&ts, ts.current_elem, this)) {
393 listView->rebuildData(); 395 listView->rebuildData();
394 browseView->rebuildData(); 396 browseView->rebuildData();
395 dirty = TRUE; 397 dirty = TRUE;
396 } 398 }
397} 399}
398 400
399void TableViewerWindow::newItemSlot() 401void TableViewerWindow::newItemSlot()
400{ 402{
401 DataElem *d = new DataElem(ds); 403 DataElem *d = new DataElem(ds);
402 if (TVEditView::openEditItemDialog(&ts, d, this)) { 404 if (TVEditView::openEditItemDialog(&ts, d, this)) {
403 405
404 ds->addItem(d); 406 ds->addItem(d);
405 ts.current_elem = d; 407 ts.current_elem = d;
406 applyFilter(); 408 applyFilter();
407 listView->rebuildData(); 409 listView->rebuildData();
408 browseView->rebuildData(); 410 browseView->rebuildData();
409 dirty = TRUE; 411 dirty = TRUE;
410 } 412 }
411} 413}
412 414
413void TableViewerWindow::deleteItemSlot() 415void TableViewerWindow::deleteItemSlot()
414{ 416{
415 /* delete the actual item, then do a 'filter' */ 417 /* delete the actual item, then do a 'filter' */
416 DataElem *to_remove = ts.current_elem; 418 DataElem *to_remove = ts.current_elem;
417 419
418 if(!to_remove) 420 if(!to_remove)
419 return; 421 return;
420 422
421 listView->removeItem(); 423 listView->removeItem();
422 ds->removeItem(to_remove); 424 ds->removeItem(to_remove);
423 425
424 applyFilter(); 426 applyFilter();
425 listView->rebuildData(); 427 listView->rebuildData();
426 browseView->rebuildData(); 428 browseView->rebuildData();
427 dirty = TRUE; 429 dirty = TRUE;
428} 430}
429 431
430void TableViewerWindow::editKeysSlot() 432void TableViewerWindow::editKeysSlot()
431{ 433{
432 DataElem *d; 434 DataElem *d;
433 KeyList *k = TVKeyEdit::openEditKeysDialog(&ts, this); 435 KeyList *k = TVKeyEdit::openEditKeysDialog(&ts, this);
434 436
435 if(k) { 437 if(k) {
436 /* set as new keys */ 438 /* set as new keys */
437 ds->setKeys(k); 439 ds->setKeys(k);
438 440
439 ts.current_column = 0; 441 ts.current_column = 0;
440 ts.kRep = k; 442 ts.kRep = k;
441 443
442 browseView->reset(); 444 browseView->reset();
443 listView->reset(); 445 listView->reset();
444 filterView->reset(); 446 filterView->reset();
445 447
446 browseView->rebuildKeys(); 448 browseView->rebuildKeys();
447 listView->rebuildKeys(); 449 listView->rebuildKeys();
448 filterView->rebuildKeys(); 450 filterView->rebuildKeys();
449 451
450 ds->first(); 452 ds->first();
451 /* set up the list view */ 453 /* set up the list view */
452 listView->clearItems(); 454 listView->clearItems();
453 do { 455 do {
454 d = ds->getCurrentData(); 456 d = ds->getCurrentData();
455 if(d) 457 if(d)
456 listView->addItem(d); 458 listView->addItem(d);
457 } while(ds->next()); 459 } while(ds->next());
458 460
459 /* Set up browse view, Will be based of structure of listView */ 461 /* Set up browse view, Will be based of structure of listView */
460 dirty = TRUE; 462 dirty = TRUE;
461 } 463 }
462} 464}
463 465
464/*! 466/*!
465 A Slot that allows for widgets above to indicate a search should be 467 A Slot that allows for widgets above to indicate a search should be
466 done on a specified key index for a specified value 468 done on a specified key index for a specified value
467*/ 469*/
468void TableViewerWindow::searchOnKey(int i, TVVariant v) 470void TableViewerWindow::searchOnKey(int i, TVVariant v)
469{ 471{
470 listView->findItem(i, v); 472 listView->findItem(i, v);
471 ts.current_elem = listView->getCurrentData(); 473 ts.current_elem = listView->getCurrentData();
472 browseView->rebuildData(); 474 browseView->rebuildData();
473} 475}
474 476
475void TableViewerWindow::setPrimaryKey(int i) 477void TableViewerWindow::setPrimaryKey(int i)
476{ 478{
477 ts.current_column = i; 479 ts.current_column = i;
478 listView->rebuildData(); 480 listView->rebuildData();
479 browseView->rebuildData(); 481 browseView->rebuildData();
480} 482}
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,315 +1,322 @@
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)
263 return; 270 return;
264 271
265 /* revers lookup the column */ 272 /* revers lookup the column */
266 i = -1; 273 i = -1;
267 for(kit = keyIds.begin(); kit != keyIds.end(); ++kit) { 274 for(kit = keyIds.begin(); kit != keyIds.end(); ++kit) {
268 if (kit.data() == ts->current_column) { 275 if (kit.data() == ts->current_column) {
269 i = kit.key(); 276 i = kit.key();
270 break; 277 break;
271 } 278 }
272 } 279 }
273 if (i == -1) 280 if (i == -1)
274 return; 281 return;
275 282
276 listViewDisplay->setSorting(i); 283 listViewDisplay->setSorting(i);
277 listViewDisplay->sort(); 284 listViewDisplay->sort();
278 285
279 /* reset current element */ 286 /* reset current element */
280 listViewDisplay->setCurrentItem(it->current()); 287 listViewDisplay->setCurrentItem(it->current());
281 listViewDisplay->setSelected(it->current(), true); 288 listViewDisplay->setSelected(it->current(), true);
282 listViewDisplay->ensureItemVisible(it->current()); 289 listViewDisplay->ensureItemVisible(it->current());
283} 290}
284 291
285void TVListView::reset() 292void TVListView::reset()
286{ 293{
287 int i; 294 int i;
288 listViewDisplay->clear(); 295 listViewDisplay->clear();
289 296
290 i = listViewDisplay->columns(); 297 i = listViewDisplay->columns();
291 while (i > 0) 298 while (i > 0)
292 listViewDisplay->removeColumn(--i); 299 listViewDisplay->removeColumn(--i);
293 300
294 keyIds.clear(); 301 keyIds.clear();
295} 302}
296 303
297void TVListView::setCurrent(QListViewItem *i) 304void TVListView::setCurrent(QListViewItem *i)
298{ 305{
299 /* cast */ 306 /* cast */
300 TVListViewItem *t = (TVListViewItem *)i; 307 TVListViewItem *t = (TVListViewItem *)i;
301 308
302 if(!t) { 309 if(!t) {
303 /* set current to null */ 310 /* set current to null */
304 ts->current_elem = 0; 311 ts->current_elem = 0;
305 return; 312 return;
306 } 313 }
307 314
308 ts->current_elem = t->getDataElem(); 315 ts->current_elem = t->getDataElem();
309 /* now also set up the iterator */ 316 /* now also set up the iterator */
310 317
311 delete it; 318 delete it;
312 it = new QListViewItemIterator(i); 319 it = new QListViewItemIterator(i);
313 320
314 //emit browseView(); 321 //emit browseView();
315} 322}
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,256 +1,253 @@
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);
107 ScQtFileDlgLayout = new QVBoxLayout( this ); 104 ScQtFileDlgLayout = new QVBoxLayout( this );
108 ScQtFileDlgLayout->setSpacing( 6 ); 105 ScQtFileDlgLayout->setSpacing( 6 );
109 ScQtFileDlgLayout->setMargin( 11 ); 106 ScQtFileDlgLayout->setMargin( 11 );
110 107
111 Layout5 = new QVBoxLayout; 108 Layout5 = new QVBoxLayout;
112 Layout5->setSpacing( 6 ); 109 Layout5->setSpacing( 6 );
113 Layout5->setMargin( 0 ); 110 Layout5->setMargin( 0 );
114 111
115 Layout4 = new QVBoxLayout; 112 Layout4 = new QVBoxLayout;
116 Layout4->setSpacing( 6 ); 113 Layout4->setSpacing( 6 );
117 Layout4->setMargin( 0 ); 114 Layout4->setMargin( 0 );
118 115
119 Layout3 = new QHBoxLayout; 116 Layout3 = new QHBoxLayout;
120 Layout3->setSpacing( 6 ); 117 Layout3->setSpacing( 6 );
121 Layout3->setMargin( 0 ); 118 Layout3->setMargin( 0 );
122 119
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,3732 +1,3729 @@
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[] = {
139"14 14 16 1", 138"14 14 16 1",
140". c None", 139". c None",
141"# c #000000", 140"# c #000000",
142"b c #0000de", 141"b c #0000de",
143"a c #0000e6", 142"a c #0000e6",
144"j c #41de83", 143"j c #41de83",
145"k c #4acecd", 144"k c #4acecd",
146"h c #4aced5", 145"h c #4aced5",
147"g c #5a40cd", 146"g c #5a40cd",
148"d c #5a44d5", 147"d c #5a44d5",
149"l c #9440d5", 148"l c #9440d5",
150"m c #b4ce4a", 149"m c #b4ce4a",
151"n c #cd4883", 150"n c #cd4883",
152"e c #d5ae10", 151"e c #d5ae10",
153"f c #de3ce6", 152"f c #de3ce6",
154"i c #e640e6", 153"i c #e640e6",
155"c c #ffffff", 154"c c #ffffff",
156"..............", 155"..............",
157".###########..", 156".###########..",
158".#ababababa#..", 157".#ababababa#..",
159".#babbbabbb#..", 158".#babbbabbb#..",
160".#ccccccccc#..", 159".#ccccccccc#..",
161".#cdcefcghc#..", 160".#cdcefcghc#..",
162".#ccccccccc#..", 161".#ccccccccc#..",
163".#cicjkclic#..", 162".#cicjkclic#..",
164".#ccccccccc#..", 163".#ccccccccc#..",
165".#cmchlcnec#..", 164".#cmchlcnec#..",
166".#ccccccccc#..", 165".#ccccccccc#..",
167".###########..", 166".###########..",
168"..............", 167"..............",
169".............."}; 168".............."};
170 169
171 170
172static const char* const passwords_data[] = { 171static const char* const passwords_data[] = {
173"16 16 20 1", 172"16 16 20 1",
174". c None", 173". c None",
175"# c #000000", 174"# c #000000",
176"r c #000083", 175"r c #000083",
177"p c #0000c5", 176"p c #0000c5",
178"q c #0000ff", 177"q c #0000ff",
179"n c #008100", 178"n c #008100",
180"l c #00c200", 179"l c #00c200",
181"m c #00ff00", 180"m c #00ff00",
182"j c #838100", 181"j c #838100",
183"a c #c55900", 182"a c #c55900",
184"h c #c5c200", 183"h c #c5c200",
185"o c #c5c2ff", 184"o c #c5c2ff",
186"k c #c5ffc5", 185"k c #c5ffc5",
187"f c #ff0000", 186"f c #ff0000",
188"d c #ff8100", 187"d c #ff8100",
189"b c #ffaa5a", 188"b c #ffaa5a",
190"e c #ffc2c5", 189"e c #ffc2c5",
191"c c #ffdeac", 190"c c #ffdeac",
192"i c #ffff00", 191"i c #ffff00",
193"g c #ffffc5", 192"g c #ffffc5",
194"............###.", 193"............###.",
195"...........#abb#", 194"...........#abb#",
196"..........#cbab#", 195"..........#cbab#",
197".........#cbdd#.", 196".........#cbdd#.",
198"######..#cbdd#..", 197"######..#cbdd#..",
199"#eeff#..#add#...", 198"#eeff#..#add#...",
200"#eeff#######....", 199"#eeff#######....",
201"#ccdbdd#........", 200"#ccdbdd#........",
202"#dddbdd###......", 201"#dddbdd###......",
203"#gghihhjj#......", 202"#gghihhjj#......",
204"#hhhihhjj###....", 203"#hhhihhjj###....",
205"#kklmllnnnn#....", 204"#kklmllnnnn#....",
206"#lllmllnnnn#....", 205"#lllmllnnnn#....",
207"#oopqpprprr#....", 206"#oopqpprprr#....",
208"#oopqpprprr#....", 207"#oopqpprprr#....",
209"############...."}; 208"############...."};
210 209
211static const char* const software_data[] = { 210static const char* const software_data[] = {
212"16 16 5 1", 211"16 16 5 1",
213". c None", 212". c None",
214"# c #000000", 213"# c #000000",
215"b c #838183", 214"b c #838183",
216"c c #c5ffff", 215"c c #c5ffff",
217"a c #ffffff", 216"a c #ffffff",
218"................", 217"................",
219".##############.", 218".##############.",
220"#aaaaaaaaaaaaaa#", 219"#aaaaaaaaaaaaaa#",
221"#abbbbbbbbbbbbb#", 220"#abbbbbbbbbbbbb#",
222"#ab##########ab#", 221"#ab##########ab#",
223"#ab#c########ab#", 222"#ab#c########ab#",
224"#ab#c#c######ab#", 223"#ab#c#c######ab#",
225"#ab##########ab#", 224"#ab##########ab#",
226"#ab##########ab#", 225"#ab##########ab#",
227"#ab##########ab#", 226"#ab##########ab#",
228"#ab##########ab#", 227"#ab##########ab#",
229"#ab##########ab#", 228"#ab##########ab#",
230"#aaaaaaaaaaaaab#", 229"#aaaaaaaaaaaaab#",
231"#bbbbbbbbbbbbbb#", 230"#bbbbbbbbbbbbbb#",
232".##############.", 231".##############.",
233"................"}; 232"................"};
234 233
235static const char* const general_data[] = { 234static const char* const general_data[] = {
236"14 14 98 2", 235"14 14 98 2",
237"Qt c None", 236"Qt c None",
238".k c #000000", 237".k c #000000",
239"#x c #080808", 238"#x c #080808",
240"#F c #101008", 239"#F c #101008",
241"#q c #101010", 240"#q c #101010",
242"#i c #101410", 241"#i c #101410",
243"## c #101810", 242"## c #101810",
244".m c #181818", 243".m c #181818",
245".3 c #181c18", 244".3 c #181c18",
246".I c #182018", 245".I c #182018",
247".T c #202420", 246".T c #202420",
248"#D c #202820", 247"#D c #202820",
249"#y c #292c29", 248"#y c #292c29",
250".c c #293029", 249".c c #293029",
251".d c #313031", 250".d c #313031",
252"#E c #313429", 251"#E c #313429",
253"#r c #313831", 252"#r c #313831",
254".j c #393c31", 253".j c #393c31",
255"#j c #394039", 254"#j c #394039",
256"#C c #414841", 255"#C c #414841",
257".w c #4a554a", 256".w c #4a554a",
258".a c #4a594a", 257".a c #4a594a",
259".# c #525052", 258".# c #525052",
260".l c #52594a", 259".l c #52594a",
261"#f c #525952", 260"#f c #525952",
262"#v c #525d52", 261"#v c #525d52",
263".O c #5a4c4a", 262".O c #5a4c4a",
264".9 c #5a595a", 263".9 c #5a595a",
265".A c #5a5d52", 264".A c #5a5d52",
266".B c #624c52", 265".B c #624c52",
267".0 c #625552", 266".0 c #625552",
268"#o c #626562", 267"#o c #626562",
269".R c #626962", 268".R c #626962",
270"#. c #626d5a", 269"#. c #626d5a",
271"#p c #626d62", 270"#p c #626d62",
272".2 c #627162", 271".2 c #627162",
273"#h c #6a6d62", 272"#h c #6a6d62",
274"#z c #6a7562", 273"#z c #6a7562",
275"#w c #6a756a", 274"#w c #6a756a",
276".C c #73656a", 275".C c #73656a",
277".P c #73696a", 276".P c #73696a",
278"#a c #737d6a", 277"#a c #737d6a",
279".U c #738573", 278".U c #738573",
280".E c #7b817b", 279".E c #7b817b",
281"#B c #7b857b", 280"#B c #7b857b",
282"#s c #7b897b", 281"#s c #7b897b",
283"#n c #7b917b", 282"#n c #7b917b",
284".b c #838d83", 283".b c #838d83",
285".7 c #839583", 284".7 c #839583",
286".n c #8b7d7b", 285".n c #8b7d7b",
287"#g c #8b8583", 286"#g c #8b8583",
288".g c #8b858b", 287".g c #8b858b",
289".r c #8b898b", 288".r c #8b898b",
290".s c #8b8d8b", 289".s c #8b8d8b",
291".i c #8b9183", 290".i c #8b9183",
292".8 c #8b918b", 291".8 c #8b918b",
293"#A c #8b9d8b", 292"#A c #8b9d8b",
294".S c #8ba183", 293".S c #8ba183",
295".Z c #94918b", 294".Z c #94918b",
296".N c #949994", 295".N c #949994",
297".F c #949d94", 296".F c #949d94",
298".x c #94a18b", 297".x c #94a18b",
299".v c #94a194", 298".v c #94a194",
300".Y c #94aa94", 299".Y c #94aa94",
301".h c #9c999c", 300".h c #9c999c",
302".Q c #9ca19c", 301".Q c #9ca19c",
303"#u c #9ca59c", 302"#u c #9ca59c",
304".H c #9caa9c", 303".H c #9caa9c",
305"#e c #9cb29c", 304"#e c #9cb29c",
306"#m c #a4b29c", 305"#m c #a4b29c",
307"#t c #a4b2a4", 306"#t c #a4b2a4",
308".M c #a4b69c", 307".M c #a4b69c",
309"#l c #a4b6a4", 308"#l c #a4b6a4",
310".z c #a4baa4", 309".z c #a4baa4",
311".f c #aca5ac", 310".f c #aca5ac",
312".q c #acaaac", 311".q c #acaaac",
313"#d c #acbeac", 312"#d c #acbeac",
314".6 c #acc2ac", 313".6 c #acc2ac",
315".o c #b4b2b4", 314".o c #b4b2b4",
316".t c #b4beb4", 315".t c #b4beb4",
317"#k c #b4c2ac", 316"#k c #b4c2ac",
318".5 c #b4cab4", 317".5 c #b4cab4",
319".D c #bdb6bd", 318".D c #bdb6bd",
320".G c #bdc6b4", 319".G c #bdc6b4",
321"#c c #bdceb4", 320"#c c #bdceb4",
322".X c #bdd2bd", 321".X c #bdd2bd",
323".4 c #bdd6bd", 322".4 c #bdd6bd",
324".1 c #c5bec5", 323".1 c #c5bec5",
325".e c #c5c2c5", 324".e c #c5c2c5",
326".u c #c5cac5", 325".u c #c5cac5",
327"#b c #c5d6c5", 326"#b c #c5d6c5",
328".J c #c5dec5", 327".J c #c5dec5",
329".p c #cdcacd", 328".p c #cdcacd",
330".W c #cddecd", 329".W c #cddecd",
331".L c #cde2cd", 330".L c #cde2cd",
332".K c #d5eacd", 331".K c #d5eacd",
333".V c #d5ead5", 332".V c #d5ead5",
334".y c #d5eed5", 333".y c #d5eed5",
335"QtQtQtQtQtQtQtQtQtQtQtQtQtQt", 334"QtQtQtQtQtQtQtQtQtQtQtQtQtQt",
336"QtQtQt.#.a.b.cQtQtQtQtQtQtQt", 335"QtQtQt.#.a.b.cQtQtQtQtQtQtQt",
337"QtQt.d.e.f.g.h.i.c.j.dQt.kQt", 336"QtQt.d.e.f.g.h.i.c.j.dQt.kQt",
338".a.l.m.n.o.p.q.r.s.t.u.v.wQt", 337".a.l.m.n.o.p.q.r.s.t.u.v.wQt",
339".x.y.z.A.B.C.D.p.q.E.F.G.H.I", 338".x.y.z.A.B.C.D.p.q.E.F.G.H.I",
340".I.J.K.L.M.N.O.P.o.p.Q.R.S.T", 339".I.J.K.L.M.N.O.P.o.p.Q.R.S.T",
341"Qt.U.V.L.W.X.Y.Z.0.P.1.s.2.3", 340"Qt.U.V.L.W.X.Y.Z.0.P.1.s.2.3",
342"Qt.3.X.W.4.X.5.6.7.8.9.s#.##", 341"Qt.3.X.W.4.X.5.6.7.8.9.s#.##",
343"QtQt#a.X#b#c.5.6#d#e#f#g#h#i", 342"QtQt#a.X#b#c.5.6#d#e#f#g#h#i",
344"QtQtQt#j.7#k.6#d#l#m#n#o#p#q", 343"QtQtQt#j.7#k.6#d#l#m#n#o#p#q",
345"QtQtQtQt.k#r#s#m#t.H#u#v#w#x", 344"QtQtQtQt.k#r#s#m#t.H#u#v#w#x",
346"QtQtQtQtQtQt.k#y#z.v#A#B#C#x", 345"QtQtQtQtQtQt.k#y#z.v#A#B#C#x",
347"QtQtQtQtQtQtQtQt.k#D.w#s#E.k", 346"QtQtQtQtQtQtQtQt.k#D.w#s#E.k",
348"QtQtQtQtQtQtQtQtQtQtQt#x#FQt"}; 347"QtQtQtQtQtQtQtQtQtQtQt#x#FQt"};
349 348
350// exit ZSafe and clear the clipboard for security reasons 349// exit ZSafe and clear the clipboard for security reasons
351 void ZSafe::exitZs (int ec) 350 void ZSafe::exitZs (int ec)
352 { 351 {
353 QClipboard *cb = QApplication::clipboard(); 352 QClipboard *cb = QApplication::clipboard();
354 cb->clear(); 353 cb->clear();
355 354
356 exit (ec); 355 exit (ec);
357 } 356 }
358 357
359 358
360// save the configuration into the file 359// save the configuration into the file
361 void ZSafe::saveConf () 360 void ZSafe::saveConf ()
362 { 361 {
363 if (conf) 362 if (conf)
364 { 363 {
365 delete conf; 364 delete conf;
366 365
367#ifdef DESKTOP 366#ifdef DESKTOP
368#ifndef WIN32 367#ifndef WIN32
369 conf = new QSettings (); 368 conf = new QSettings ();
370 conf->insertSearchPath (QSettings::Unix, QDir::homeDirPath()); 369 conf->insertSearchPath (QSettings::Unix, QDir::homeDirPath());
371#else 370#else
372 conf = new QSettings (cfgFile); 371 conf = new QSettings (cfgFile);
373 conf->insertSearchPath (QSettings::Unix, cfgFile); 372 conf->insertSearchPath (QSettings::Unix, cfgFile);
374#endif 373#endif
375#else 374#else
376 conf = new Config (cfgFile, Config::File); 375 conf = new Config (cfgFile, Config::File);
377 conf->setGroup ("zsafe"); 376 conf->setGroup ("zsafe");
378#endif 377#endif
379 } 378 }
380 } 379 }
381 380
382 381
383/* 382/*
384 * Constructs a ZSafe which is a child of 'parent', with the 383 * Constructs a ZSafe which is a child of 'parent', with the
385 * name 'name' and widget flags set to 'f' 384 * name 'name' and widget flags set to 'f'
386 * 385 *
387 * The dialog will by default be modeless, unless you set 'modal' to 386 * The dialog will by default be modeless, unless you set 'modal' to
388 * TRUE to construct a modal dialog. 387 * TRUE to construct a modal dialog.
389 */ 388 */
390ZSafe::ZSafe( QWidget* parent, const char* name, bool modal, WFlags fl ) 389ZSafe::ZSafe( QWidget* parent, const char* name, bool modal, WFlags fl )
391 : QDialog( parent, name, modal, fl ), 390 : QDialog( parent, name, modal, fl ),
392 Edit(0l), Delete(0l), Find(0l), New(0l), ListView(0l) 391 Edit(0l), Delete(0l), Find(0l), New(0l), ListView(0l)
393{ 392{
394 IsCut = false; 393 IsCut = false;
395 IsCopy = false; 394 IsCopy = false;
396 modified = false; 395 modified = false;
397 396
398 // set the config file 397 // set the config file
399 cfgFile=QDir::homeDirPath(); 398 cfgFile=QDir::homeDirPath();
400 cfgFile += "/.zsafe.cfg"; 399 cfgFile += "/.zsafe.cfg";
401 // set the icon path 400 // set the icon path
402#ifdef NO_OPIE 401#ifdef NO_OPIE
403 QString qpedir ((const char *)getenv("QPEDIR")); 402 QString qpedir ((const char *)getenv("QPEDIR"));
404#else 403#else
405 QString qpedir ((const char *)getenv("OPIEDIR")); 404 QString qpedir ((const char *)getenv("OPIEDIR"));
406#endif 405#endif
407 406
408#ifdef DESKTOP 407#ifdef DESKTOP
409 iconPath = QDir::homeDirPath() + "/pics/"; 408 iconPath = QDir::homeDirPath() + "/pics/";
410#else 409#else
411 if (qpedir.isEmpty()) 410 if (qpedir.isEmpty())
412 iconPath = "/home/QtPalmtop/pics/"; 411 iconPath = "/home/QtPalmtop/pics/";
413 else 412 else
414 iconPath = qpedir + "/pics/"; 413 iconPath = qpedir + "/pics/";
415#endif 414#endif
416 415
417 // create a zsafe configuration object 416 // create a zsafe configuration object
418#ifdef DESKTOP 417#ifdef DESKTOP
419#ifndef WIN32 418#ifndef WIN32
420 conf = new QSettings (); 419 conf = new QSettings ();
421 conf->insertSearchPath (QSettings::Unix, QDir::homeDirPath()); 420 conf->insertSearchPath (QSettings::Unix, QDir::homeDirPath());
422#else 421#else
423 conf = new QSettings (cfgFile); 422 conf = new QSettings (cfgFile);
424 conf->insertSearchPath (QSettings::Unix, cfgFile); 423 conf->insertSearchPath (QSettings::Unix, cfgFile);
425#endif 424#endif
426#else 425#else
427 conf = new Config (cfgFile, Config::File); 426 conf = new Config (cfgFile, Config::File);
428 conf->setGroup ("zsafePrefs"); 427 conf->setGroup ("zsafePrefs");
429#endif 428#endif
430#ifdef DESKTOP 429#ifdef DESKTOP
431// #ifndef WIN32 430// #ifndef WIN32
432 expandTree = conf->readBoolEntry(APP_KEY+"expandTree", false); 431 expandTree = conf->readBoolEntry(APP_KEY+"expandTree", false);
433// #endif 432// #endif
434#else 433#else
435 expandTree = conf->readNumEntry(APP_KEY+"expandTree", 0); 434 expandTree = conf->readNumEntry(APP_KEY+"expandTree", 0);
436#endif 435#endif
437#ifndef DESKTOP 436#ifndef DESKTOP
438 conf->setGroup ("zsafe"); 437 conf->setGroup ("zsafe");
439#endif 438#endif
440 439
441 QPixmap copy_img((const char**) copy_xpm); 440 QPixmap copy_img((const char**) copy_xpm);
442 QPixmap cut_img((const char**) cut_xpm); 441 QPixmap cut_img((const char**) cut_xpm);
443 QPixmap edit_img((const char**) edit_xpm); 442 QPixmap edit_img((const char**) edit_xpm);
444 QPixmap editdelete_img((const char**) editdelete_xpm); 443 QPixmap editdelete_img((const char**) editdelete_xpm);
445 QPixmap find_img((const char**) find_xpm); 444 QPixmap find_img((const char**) find_xpm);
446 QPixmap folder_open_img((const char**) folder_open_xpm); 445 QPixmap folder_open_img((const char**) folder_open_xpm);
447 QPixmap help_icon_img((const char**) help_icon_xpm); 446 QPixmap help_icon_img((const char**) help_icon_xpm);
448 QPixmap new_img((const char**) new_xpm); 447 QPixmap new_img((const char**) new_xpm);
449 QPixmap paste_img((const char**) paste_xpm); 448 QPixmap paste_img((const char**) paste_xpm);
450 QPixmap quit_icon_img((const char**) quit_icon_xpm); 449 QPixmap quit_icon_img((const char**) quit_icon_xpm);
451 QPixmap save_img((const char**) save_xpm); 450 QPixmap save_img((const char**) save_xpm);
452 QPixmap trash_img((const char**) trash_xpm); 451 QPixmap trash_img((const char**) trash_xpm);
453 QPixmap expand_img((const char**) expand_xpm); 452 QPixmap expand_img((const char**) expand_xpm);
454 QPixmap export_img((const char**) export_xpm); 453 QPixmap export_img((const char**) export_xpm);
455 QPixmap import_img((const char**) import_xpm); 454 QPixmap import_img((const char**) import_xpm);
456 455
457 QPixmap bank_cards( ( const char** ) bank_cards_data ); 456 QPixmap bank_cards( ( const char** ) bank_cards_data );
458 QPixmap passwords( ( const char** ) passwords_data ); 457 QPixmap passwords( ( const char** ) passwords_data );
459 QPixmap software( ( const char** ) software_data ); 458 QPixmap software( ( const char** ) software_data );
460 QPixmap general( ( const char** ) general_data ); 459 QPixmap general( ( const char** ) general_data );
461 if ( !name ) 460 if ( !name )
462 setName( "ZSafe" ); 461 setName( "ZSafe" );
463 462
464#ifdef DESKTOP 463#ifdef DESKTOP
465#ifdef WIN32 464#ifdef WIN32
466 setGeometry(100, 150, DeskW, DeskH-30 ); 465 setGeometry(100, 150, DeskW, DeskH-30 );
467#else 466#else
468 resize( DeskW, DeskH-30 ); 467 resize( DeskW, DeskH-30 );
469#endif 468#endif
470 469
471#else 470#else
472 471
473#ifdef JPATCH_HDE 472#ifdef JPATCH_HDE
474 int DeskS; 473 int DeskS;
475 if(DeskW > DeskH) 474 if(DeskW > DeskH)
476 { 475 {
477 DeskS = DeskW; 476 DeskS = DeskW;
478 } 477 }
479 else 478 else
480 { 479 {
481 DeskS = DeskH; 480 DeskS = DeskH;
482 } 481 }
483 resize( DeskW, DeskH ); 482 resize( DeskW, DeskH );
484 setMinimumSize( QSize( DeskS, DeskS ) ); 483 setMinimumSize( QSize( DeskS, DeskS ) );
485 setMaximumSize( QSize( DeskS, DeskS ) ); 484 setMaximumSize( QSize( DeskS, DeskS ) );
486#else 485#else
487 resize( DeskW, DeskH-30 ); 486 resize( DeskW, DeskH-30 );
488#endif 487#endif
489 488
490#endif 489#endif
491 // setCaption( tr( "ZSafe" ) ); 490 // setCaption( tr( "ZSafe" ) );
492 491
493 filename = conf->readEntry(APP_KEY+"document"); 492 filename = conf->readEntry(APP_KEY+"document");
494 if (filename.isEmpty() || filename.isNull()) 493 if (filename.isEmpty() || filename.isNull())
495 { 494 {
496 495
497 // check if the directory application exists, if not 496 // check if the directory application exists, if not
498 // create it 497 // create it
499// #ifndef WIN32 498// #ifndef WIN32
500 // QString d1("Documents/application"); 499 // QString d1("Documents/application");
501// #else 500// #else
502 QString d1(QDir::homeDirPath() + "/Documents/application"); 501 QString d1(QDir::homeDirPath() + "/Documents/application");
503// #endif 502// #endif
504 QDir pd1(d1); 503 QDir pd1(d1);
505 if (!pd1.exists()) 504 if (!pd1.exists())
506 { 505 {
507 QDir pd1("Documents"); 506 QDir pd1("Documents");
508 if (!pd1.mkdir("application", FALSE)) 507 if (!pd1.mkdir("application", FALSE))
509 { 508 {
510 QMessageBox::critical( 0, tr("ZSafe"), 509 QMessageBox::critical( 0, tr("ZSafe"),
511#ifdef JPATCH_HDE 510#ifdef JPATCH_HDE
512 tr("Can't create directory\n.../Documents/application\n\nZSafe will now exit.")); 511 tr("Can't create directory\n.../Documents/application\n\nZSafe will now exit."));
513#else 512#else
514 tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d1)); 513 tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d1));
515#endif 514#endif
516 exitZs (1); 515 exitZs (1);
517 } 516 }
518 } 517 }
519 QString d2(QDir::homeDirPath() + "/Documents/application/zsafe"); 518 QString d2(QDir::homeDirPath() + "/Documents/application/zsafe");
520 QDir pd2(d2); 519 QDir pd2(d2);
521 if (!pd2.exists()) 520 if (!pd2.exists())
522 { 521 {
523 QDir pd2(QDir::homeDirPath() + "Documents/application"); 522 QDir pd2(QDir::homeDirPath() + "Documents/application");
524 if (!pd2.mkdir("zsafe", FALSE)) 523 if (!pd2.mkdir("zsafe", FALSE))
525 { 524 {
526 QMessageBox::critical( 0, tr("ZSafe"), 525 QMessageBox::critical( 0, tr("ZSafe"),
527#ifdef JPATCH_HDE 526#ifdef JPATCH_HDE
528 tr("Can't create directory\n...//Documents/application/zsafe\n\nZSafe will now exit.")); 527 tr("Can't create directory\n...//Documents/application/zsafe\n\nZSafe will now exit."));
529#else 528#else
530 tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d2)); 529 tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d2));
531#endif 530#endif
532 exitZs (1); 531 exitZs (1);
533 } 532 }
534 } 533 }
535 534
536 535
537 // set the default filename 536 // set the default filename
538 filename=d2 + "/passwords.zsf"; 537 filename=d2 + "/passwords.zsf";
539 538
540 // save the current filename to the config file 539 // save the current filename to the config file
541 conf->writeEntry(APP_KEY+"document", filename); 540 conf->writeEntry(APP_KEY+"document", filename);
542 saveConf(); 541 saveConf();
543 } 542 }
544 543
545 //if (filename == "INVALIDPWD") 544 //if (filename == "INVALIDPWD")
546 //filename = ""; 545 //filename = "";
547 546
548 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 547 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
549#ifdef WIN32 548#ifdef WIN32
550 this->setCaption("Qt ZSafe: " + ti); 549 this->setCaption("Qt ZSafe: " + ti);
551#else 550#else
552 this->setCaption("ZSafe: " + ti); 551 this->setCaption("ZSafe: " + ti);
553#endif 552#endif
554 553
555 selectedItem = NULL; 554 selectedItem = NULL;
556 lastSearchedCategory = NULL; 555 lastSearchedCategory = NULL;
557 lastSearchedItem = NULL; 556 lastSearchedItem = NULL;
558 lastSearchedName = ""; 557 lastSearchedName = "";
559 lastSearchedUsername = ""; 558 lastSearchedUsername = "";
560 lastSearchedComment = ""; 559 lastSearchedComment = "";
561 560
562 infoForm = new InfoForm(); 561 infoForm = new InfoForm();
563 categoryDialog = NULL; 562 categoryDialog = NULL;
564 563
565 // add a menu bar 564 // add a menu bar
566 QMenuBar *menu = new QMenuBar( this ); 565 QMenuBar *menu = new QMenuBar( this );
567 566
568 // add file menu 567 // add file menu
569 // QPopupMenu *file = new QPopupMenu( this ); 568 // QPopupMenu *file = new QPopupMenu( this );
570 file = new QPopupMenu( this ); 569 file = new QPopupMenu( this );
571 570
572// #ifdef DESKTOP 571// #ifdef DESKTOP
573 file->insertItem( new_img, tr("&New document"), this, SLOT(newDocument()) ); 572 file->insertItem( new_img, tr("&New document"), this, SLOT(newDocument()) );
574 file->insertItem( folder_open_img, tr("&Open document"), this, SLOT(loadDocument()) ); 573 file->insertItem( folder_open_img, tr("&Open document"), this, SLOT(loadDocument()) );
575 file->insertItem( save_img, tr("&Save document as .."), this, SLOT(saveDocumentAs()) ); 574 file->insertItem( save_img, tr("&Save document as .."), this, SLOT(saveDocumentAs()) );
576 file->insertSeparator(); 575 file->insertSeparator();
577// #endif 576// #endif
578 577
579 file->insertItem( save_img, tr("&Save document"), this, SLOT(saveDocumentWithoutPwd()) ); 578 file->insertItem( save_img, tr("&Save document"), this, SLOT(saveDocumentWithoutPwd()) );
580 file->insertItem( save_img, tr("S&ave document with new Password"), this, 579 file->insertItem( save_img, tr("S&ave document with new Password"), this,
581 SLOT(saveDocumentWithPwd()) ); 580 SLOT(saveDocumentWithPwd()) );
582 file->insertSeparator(); 581 file->insertSeparator();
583 file->insertItem( export_img, tr("&Export text file"), this, SLOT(writeAllEntries()) ); 582 file->insertItem( export_img, tr("&Export text file"), this, SLOT(writeAllEntries()) );
584 file->insertItem( import_img, tr("&Import text file"), this, SLOT(readAllEntries()) ); 583 file->insertItem( import_img, tr("&Import text file"), this, SLOT(readAllEntries()) );
585 file->insertItem( trash_img, tr("&Remove text file"), this, SLOT(removeAsciiFile()) ); 584 file->insertItem( trash_img, tr("&Remove text file"), this, SLOT(removeAsciiFile()) );
586 file->insertSeparator(); 585 file->insertSeparator();
587 file->insertItem( expand_img, tr("&Open entries expanded"), this, 586 file->insertItem( expand_img, tr("&Open entries expanded"), this,
588 SLOT(setExpandFlag()), 0, 'o'); 587 SLOT(setExpandFlag()), 0, 'o');
589 file->setItemChecked('o', expandTree); 588 file->setItemChecked('o', expandTree);
590 file->insertSeparator(); 589 file->insertSeparator();
591 file->insertItem( quit_icon_img, tr("E&xit"), this, SLOT(quitMe()) ); 590 file->insertItem( quit_icon_img, tr("E&xit"), this, SLOT(quitMe()) );
592 menu->insertItem( tr("&File"), file ); 591 menu->insertItem( tr("&File"), file );
593 592
594 QPopupMenu *cat = new QPopupMenu( this ); 593 QPopupMenu *cat = new QPopupMenu( this );
595 cat->insertItem( new_img, tr("&New"), this, SLOT(addCategory()) ); 594 cat->insertItem( new_img, tr("&New"), this, SLOT(addCategory()) );
596 cat->insertItem( edit_img, tr("&Edit"), this, SLOT(editCategory()) ); 595 cat->insertItem( edit_img, tr("&Edit"), this, SLOT(editCategory()) );
597 cat->insertItem( trash_img, tr("&Delete"), this, SLOT(delCategory()) ); 596 cat->insertItem( trash_img, tr("&Delete"), this, SLOT(delCategory()) );
598 menu->insertItem( tr("&Category"), cat ); 597 menu->insertItem( tr("&Category"), cat );
599 598
600 QPopupMenu *it = new QPopupMenu( this ); 599 QPopupMenu *it = new QPopupMenu( this );
601 it->insertItem( cut_img, tr("&Cut"), this, SLOT(cutItem()) ); 600 it->insertItem( cut_img, tr("&Cut"), this, SLOT(cutItem()) );
602 it->insertItem( copy_img, tr("C&opy"), this, SLOT(copyItem()) ); 601 it->insertItem( copy_img, tr("C&opy"), this, SLOT(copyItem()) );
603 it->insertItem( paste_img, tr("&Paste"), this, SLOT(pasteItem()) ); 602 it->insertItem( paste_img, tr("&Paste"), this, SLOT(pasteItem()) );
604 it->insertSeparator(); 603 it->insertSeparator();
605 it->insertItem( new_img, tr("&New"), this, SLOT(newPwd()) ); 604 it->insertItem( new_img, tr("&New"), this, SLOT(newPwd()) );
606 it->insertItem( edit_img, tr("&Edit"), this, SLOT(editPwd()) ); 605 it->insertItem( edit_img, tr("&Edit"), this, SLOT(editPwd()) );
607 it->insertItem( trash_img, tr("&Delete"), this, SLOT(deletePwd()) ); 606 it->insertItem( trash_img, tr("&Delete"), this, SLOT(deletePwd()) );
608 it->insertItem( find_img, tr("&Search"), this, SLOT(findPwd()) ); 607 it->insertItem( find_img, tr("&Search"), this, SLOT(findPwd()) );
609 menu->insertItem( tr("&Entry"), it ); 608 menu->insertItem( tr("&Entry"), it );
610 609
611 QPopupMenu *help = new QPopupMenu( this ); 610 QPopupMenu *help = new QPopupMenu( this );
612 help->insertItem( help_icon_img, tr("&About"), this, SLOT(about()) ); 611 help->insertItem( help_icon_img, tr("&About"), this, SLOT(about()) );
613 menu->insertItem( tr("&Help"), help ); 612 menu->insertItem( tr("&Help"), help );
614 613
615 // toolbar icons 614 // toolbar icons
616 615
617 New = new QToolButton( menu, "New" ); 616 New = new QToolButton( menu, "New" );
618 New->setGeometry( QRect( DeskW-84, 2, 20, 20 ) ); 617 New->setGeometry( QRect( DeskW-84, 2, 20, 20 ) );
619 New->setMouseTracking( TRUE ); 618 New->setMouseTracking( TRUE );
620 New->setText( tr( "" ) ); 619 New->setText( tr( "" ) );
621 New->setPixmap( new_img ); 620 New->setPixmap( new_img );
622 QToolTip::add( New, tr( "New entry" ) ); 621 QToolTip::add( New, tr( "New entry" ) );
623 622
624 Edit = new QToolButton( menu, "Edit" ); 623 Edit = new QToolButton( menu, "Edit" );
625 Edit->setGeometry( QRect( DeskW-64, 2, 20, 20 ) ); 624 Edit->setGeometry( QRect( DeskW-64, 2, 20, 20 ) );
626 Edit->setText( tr( "" ) ); 625 Edit->setText( tr( "" ) );
627 Edit->setPixmap( edit_img ); 626 Edit->setPixmap( edit_img );
628 QToolTip::add( Edit, tr( "Edit category or entry" ) ); 627 QToolTip::add( Edit, tr( "Edit category or entry" ) );
629 628
630 Delete = new QToolButton( menu, "Delete" ); 629 Delete = new QToolButton( menu, "Delete" );
631 Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) ); 630 Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) );
632 Delete->setText( tr( "" ) ); 631 Delete->setText( tr( "" ) );
633 Delete->setPixmap( trash_img ); 632 Delete->setPixmap( trash_img );
634 QToolTip::add( Delete, tr( "Delete category or entry" ) ); 633 QToolTip::add( Delete, tr( "Delete category or entry" ) );
635 634
636 Find = new QToolButton( menu, "Find" ); 635 Find = new QToolButton( menu, "Find" );
637 Find->setGeometry( QRect( DeskW-24, 2, 20, 20 ) ); 636 Find->setGeometry( QRect( DeskW-24, 2, 20, 20 ) );
638 Find->setText( tr( "" ) ); 637 Find->setText( tr( "" ) );
639 Find->setPixmap( find_img ); 638 Find->setPixmap( find_img );
640 QToolTip::add( Find, tr( "Find entry" ) ); 639 QToolTip::add( Find, tr( "Find entry" ) );
641 640
642/* 641/*
643 QBoxLayout * h = new QHBoxLayout( this ); 642 QBoxLayout * h = new QHBoxLayout( this );
644 h->addWidget (menu); 643 h->addWidget (menu);
645 h->addWidget (New); 644 h->addWidget (New);
646 h->addWidget (Edit); 645 h->addWidget (Edit);
647 h->addWidget (Delete); 646 h->addWidget (Delete);
648 h->addWidget (Find); 647 h->addWidget (Find);
649*/ 648*/
650 649
651 ListView = new ZListView( this, "ListView" ); 650 ListView = new ZListView( this, "ListView" );
652 ListView->addColumn( tr( "Name" ) ); 651 ListView->addColumn( tr( "Name" ) );
653 ListView->addColumn( tr( "Field 2" ) ); 652 ListView->addColumn( tr( "Field 2" ) );
654 ListView->addColumn( tr( "Field 3" ) ); 653 ListView->addColumn( tr( "Field 3" ) );
655 ListView->addColumn( tr( "Comment" ) ); 654 ListView->addColumn( tr( "Comment" ) );
656 ListView->addColumn( tr( "Field 4" ) ); 655 ListView->addColumn( tr( "Field 4" ) );
657 ListView->addColumn( tr( "Field 5" ) ); 656 ListView->addColumn( tr( "Field 5" ) );
658 ListView->setAllColumnsShowFocus(TRUE); 657 ListView->setAllColumnsShowFocus(TRUE);
659 658
660#ifdef DESKTOP 659#ifdef DESKTOP
661 ListView->setResizePolicy(QScrollView::AutoOneFit); 660 ListView->setResizePolicy(QScrollView::AutoOneFit);
662 // ListView->setGeometry( QRect( 0, 22, this->width(), this->height() - 30 ) ); 661 // ListView->setGeometry( QRect( 0, 22, this->width(), this->height() - 30 ) );
663#else 662#else
664 ListView->setResizePolicy(QScrollView::AutoOneFit); 663 ListView->setResizePolicy(QScrollView::AutoOneFit);
665 // ListView->setGeometry( QRect( 0, 22, 664 // ListView->setGeometry( QRect( 0, 22,
666 // this->width(), this->height() - 30 ) ); 665 // this->width(), this->height() - 30 ) );
667 // ListView->setMaximumSize( QSize( 440, 290 ) ); 666 // ListView->setMaximumSize( QSize( 440, 290 ) );
668#endif 667#endif
669 ListView->setVScrollBarMode( QListView::Auto ); 668 ListView->setVScrollBarMode( QListView::Auto );
670 669
671 QBoxLayout * l = new QVBoxLayout( this ); 670 QBoxLayout * l = new QVBoxLayout( this );
672 l->addWidget (menu); 671 l->addWidget (menu);
673 l->addWidget (ListView); 672 l->addWidget (ListView);
674 673
675#ifndef DESKTOP 674#ifndef DESKTOP
676 // start a timer (100 ms) to load the default document 675 // start a timer (100 ms) to load the default document
677 docuTimer.start( 100, true ); 676 docuTimer.start( 100, true );
678 connect( &docuTimer, SIGNAL(timeout()), SLOT( slotLoadDocu() ) ); 677 connect( &docuTimer, SIGNAL(timeout()), SLOT( slotLoadDocu() ) );
679 raiseFlag = true; 678 raiseFlag = true;
680 connect( &raiseTimer, SIGNAL(timeout()), SLOT( slotRaiseTimer() ) ); 679 connect( &raiseTimer, SIGNAL(timeout()), SLOT( slotRaiseTimer() ) );
681#else 680#else
682 // open the default document 681 // open the default document
683 openDocument(filename); 682 openDocument(filename);
684#endif 683#endif
685 684
686 // signals and slots connections for QTollButton 685 // signals and slots connections for QTollButton
687 connect( New, SIGNAL( clicked() ), this, SLOT( newPwd() ) ); 686 connect( New, SIGNAL( clicked() ), this, SLOT( newPwd() ) );
688 connect( Edit, SIGNAL( clicked() ), this, SLOT( editPwd() ) ); 687 connect( Edit, SIGNAL( clicked() ), this, SLOT( editPwd() ) );
689 connect( Delete, SIGNAL( clicked() ), this, SLOT( deletePwd() ) ); 688 connect( Delete, SIGNAL( clicked() ), this, SLOT( deletePwd() ) );
690 connect( Find, SIGNAL( clicked() ), this, SLOT( findPwd() ) ); 689 connect( Find, SIGNAL( clicked() ), this, SLOT( findPwd() ) );
691 // signals and slots connections for QListView 690 // signals and slots connections for QListView
692 connect( ListView, SIGNAL( selectionChanged(QListViewItem*) ), 691 connect( ListView, SIGNAL( selectionChanged(QListViewItem*) ),
693 this, SLOT( listViewSelected(QListViewItem*) ) ); 692 this, SLOT( listViewSelected(QListViewItem*) ) );
694 connect( ListView, SIGNAL( doubleClicked(QListViewItem*) ), 693 connect( ListView, SIGNAL( doubleClicked(QListViewItem*) ),
695 this, SLOT( showInfo(QListViewItem*) ) ); 694 this, SLOT( showInfo(QListViewItem*) ) );
696 connect( ListView, SIGNAL( returnPressed(QListViewItem*) ), 695 connect( ListView, SIGNAL( returnPressed(QListViewItem*) ),
697 this, SLOT( showInfo(QListViewItem*) ) ); 696 this, SLOT( showInfo(QListViewItem*) ) );
698 697
699} 698}
700 699
701const QColor *ZSafe::evenRowColor = &Qt::white; 700const QColor *ZSafe::evenRowColor = &Qt::white;
702// const QColor *ZSafe::oddRowColor = &Qt::lightGray; 701// const QColor *ZSafe::oddRowColor = &Qt::lightGray;
703const QColor *ZSafe::oddRowColor = new QColor(216,240,255); 702const QColor *ZSafe::oddRowColor = new QColor(216,240,255);
704 703
705/* 704/*
706 * Destroys the object and frees any allocated resources 705 * Destroys the object and frees any allocated resources
707 */ 706 */
708ZSafe::~ZSafe() 707ZSafe::~ZSafe()
709{ 708{
710 // no need to delete child widgets, Qt does it all for us 709 // no need to delete child widgets, Qt does it all for us
711 quitMe(); 710 quitMe();
712} 711}
713 712
714// load the default document 713// load the default document
715void ZSafe::slotLoadDocu() 714void ZSafe::slotLoadDocu()
716{ 715{
717 openDocument (filename); 716 openDocument (filename);
718} 717}
719 718
720void ZSafe::deletePwd() 719void ZSafe::deletePwd()
721{ 720{
722 721
723 if (!selectedItem) 722 if (!selectedItem)
724 return; 723 return;
725 if (!isCategory(selectedItem)) 724 if (!isCategory(selectedItem))
726 { 725 {
727 switch( QMessageBox::information( this, tr("ZSafe"), 726 switch( QMessageBox::information( this, tr("ZSafe"),
728 tr("Do you want to delete?"), 727 tr("Do you want to delete?"),
729 tr("&Delete"), tr("D&on't Delete"), 728 tr("&Delete"), tr("D&on't Delete"),
730 0 // Enter == button 0 729 0 // Enter == button 0
731 ) ) { // Escape == button 2 730 ) ) { // Escape == button 2
732 case 0: // Delete clicked, Alt-S or Enter pressed. 731 case 0: // Delete clicked, Alt-S or Enter pressed.
733 // Delete 732 // Delete
734 modified = true; 733 modified = true;
735 selectedItem->parent()->takeItem(selectedItem); 734 selectedItem->parent()->takeItem(selectedItem);
736 selectedItem = NULL; 735 selectedItem = NULL;
737 break; 736 break;
738 case 1: // Don't delete 737 case 1: // Don't delete
739 break; 738 break;
740 } 739 }
741 } 740 }
742 else 741 else
743 { 742 {
744 delCategory(); 743 delCategory();
745 } 744 }
746} 745}
747 746
748void ZSafe::editPwd() 747void ZSafe::editPwd()
749{ 748{
750 if (!selectedItem) 749 if (!selectedItem)
751 return; 750 return;
752 if (!isCategory(selectedItem)) 751 if (!isCategory(selectedItem))
753 { 752 {
754 // open the 'New Entry' dialog 753 // open the 'New Entry' dialog
755 NewDialog *dialog = new NewDialog(this, tr("Edit Entry"), TRUE); 754 NewDialog *dialog = new NewDialog(this, tr("Edit Entry"), TRUE);
756#ifdef WIN32 755#ifdef WIN32
757 dialog->setCaption ("Qt " + tr("Edit Entry")); 756 dialog->setCaption ("Qt " + tr("Edit Entry"));
758 dialog->setGeometry(200, 250, 220, 310 ); 757 dialog->setGeometry(200, 250, 220, 310 );
759#endif 758#endif
760 759
761 // set the labels 760 // set the labels
762 dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name"))); 761 dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name")));
763 dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username"))); 762 dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username")));
764 dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password"))); 763 dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password")));
765 dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment"))); 764 dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment")));
766 dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4"))); 765 dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4")));
767 dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5"))); 766 dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5")));
768 767
769 // set the fields 768 // set the fields
770 dialog->NameField->setText(selectedItem->text (0)); 769 dialog->NameField->setText(selectedItem->text (0));
771 dialog->UsernameField->setText(selectedItem->text (1)); 770 dialog->UsernameField->setText(selectedItem->text (1));
772 dialog->PasswordField->setText(selectedItem->text (2)); 771 dialog->PasswordField->setText(selectedItem->text (2));
773 QString comment = selectedItem->text (3); 772 QString comment = selectedItem->text (3);
774 comment.replace (QRegExp("<br>"), "\n"); 773 comment.replace (QRegExp("<br>"), "\n");
775 dialog->Field5->setText(selectedItem->text (4)); 774 dialog->Field5->setText(selectedItem->text (4));
776 dialog->Field6->setText(selectedItem->text (5)); 775 dialog->Field6->setText(selectedItem->text (5));
777 dialog->CommentField->insertLine(comment); 776 dialog->CommentField->insertLine(comment);
778 dialog->CommentField->setCursorPosition(0,0); 777 dialog->CommentField->setCursorPosition(0,0);
779 778
780 DialogCode result = (DialogCode) QPEApplication::execDialog( dialog ); 779 DialogCode result = (DialogCode) QPEApplication::execDialog( dialog );
781 780
782#ifdef DESKTOP 781#ifdef DESKTOP
783 result = Accepted; 782 result = Accepted;
784#endif 783#endif
785 if (result == Accepted) 784 if (result == Accepted)
786 { 785 {
787 modified = true; 786 modified = true;
788 // edit the selected item 787 // edit the selected item
789 QString name = dialog->NameField->text(); 788 QString name = dialog->NameField->text();
790 selectedItem->setText (0, tr (name)); 789 selectedItem->setText (0, tr (name));
791 QString user = dialog->UsernameField->text(); 790 QString user = dialog->UsernameField->text();
792 selectedItem->setText (1, tr (user)); 791 selectedItem->setText (1, tr (user));
793 QString pwd = dialog->PasswordField->text(); 792 QString pwd = dialog->PasswordField->text();
794 selectedItem->setText (2, tr (pwd)); 793 selectedItem->setText (2, tr (pwd));
795 QString comment = dialog->CommentField->text(); 794 QString comment = dialog->CommentField->text();
796 comment.replace (QRegExp("\n"), "<br>"); 795 comment.replace (QRegExp("\n"), "<br>");
797 selectedItem->setText (3, tr (comment)); 796 selectedItem->setText (3, tr (comment));
798 QString f5 = dialog->Field5->text(); 797 QString f5 = dialog->Field5->text();
799 selectedItem->setText (4, tr (f5)); 798 selectedItem->setText (4, tr (f5));
800 QString f6 = dialog->Field6->text(); 799 QString f6 = dialog->Field6->text();
801 selectedItem->setText (5, tr (f6)); 800 selectedItem->setText (5, tr (f6));
802 } 801 }
803 802
804 delete dialog; 803 delete dialog;
805 } 804 }
806 else 805 else
807 { 806 {
808 editCategory(); 807 editCategory();
809 } 808 }
810} 809}
811 810
812void ZSafe::newPwd() 811void ZSafe::newPwd()
813{ 812{
814 if (!selectedItem) 813 if (!selectedItem)
815 return; 814 return;
816 815
817 if (!isCategory(selectedItem)) 816 if (!isCategory(selectedItem))
818 selectedItem = selectedItem->parent(); 817 selectedItem = selectedItem->parent();
819 818
820 if (isCategory(selectedItem)) 819 if (isCategory(selectedItem))
821 { 820 {
822 QString cat = selectedItem->text(0); 821 QString cat = selectedItem->text(0);
823 822
824 // open the 'New Entry' dialog 823 // open the 'New Entry' dialog
825 NewDialog *dialog = new NewDialog(this, tr("New Entry"), TRUE); 824 NewDialog *dialog = new NewDialog(this, tr("New Entry"), TRUE);
826#ifdef WIN32 825#ifdef WIN32
827 dialog->setCaption ("Qt " + tr("New Entry")); 826 dialog->setCaption ("Qt " + tr("New Entry"));
828 dialog->setGeometry(200, 250, 220, 310 ); 827 dialog->setGeometry(200, 250, 220, 310 );
829#endif 828#endif
830 // set the labels 829 // set the labels
831 dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name"))); 830 dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name")));
832 dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username"))); 831 dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username")));
833 dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password"))); 832 dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password")));
834 dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment"))); 833 dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment")));
835 dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4"))); 834 dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4")));
836 dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5"))); 835 dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5")));
837retype: 836retype:
838 837
839 DialogCode result = (DialogCode) QPEApplication::execDialog( dialog ); 838 DialogCode result = (DialogCode) QPEApplication::execDialog( dialog );
840#ifdef DESKTOP 839#ifdef DESKTOP
841 result = Accepted; 840 result = Accepted;
842#endif 841#endif
843 842
844 if (result == Accepted) 843 if (result == Accepted)
845 { 844 {
846 845
847 QString name = dialog->NameField->text(); 846 QString name = dialog->NameField->text();
848 if (cat == name) 847 if (cat == name)
849 { 848 {
850 QMessageBox::critical( 0, tr("ZSafe"), 849 QMessageBox::critical( 0, tr("ZSafe"),
851 tr("Entry name must be different\nfrom the category name.") ); 850 tr("Entry name must be different\nfrom the category name.") );
852 goto retype; // it's not a good programming style :-) 851 goto retype; // it's not a good programming style :-)
853 } 852 }
854 853
855 modified = true; 854 modified = true;
856 // add the new item 855 // add the new item
857 QListViewItem *i = new ShadedListItem (0, selectedItem); 856 QListViewItem *i = new ShadedListItem (0, selectedItem);
858 i->setOpen (TRUE); 857 i->setOpen (TRUE);
859 858
860 i->setText (0, tr (name)); 859 i->setText (0, tr (name));
861 QString user = dialog->UsernameField->text(); 860 QString user = dialog->UsernameField->text();
862 i->setText (1, tr (user)); 861 i->setText (1, tr (user));
863 QString pwd = dialog->PasswordField->text(); 862 QString pwd = dialog->PasswordField->text();
864 i->setText (2, tr (pwd)); 863 i->setText (2, tr (pwd));
865 QString comment = dialog->CommentField->text(); 864 QString comment = dialog->CommentField->text();
866 comment.replace (QRegExp("\n"), "<br>"); 865 comment.replace (QRegExp("\n"), "<br>");
867 i->setText (3, tr (comment)); 866 i->setText (3, tr (comment));
868 QString f5 = dialog->Field5->text(); 867 QString f5 = dialog->Field5->text();
869 i->setText (4, tr (f5)); 868 i->setText (4, tr (f5));
870 QString f6 = dialog->Field6->text(); 869 QString f6 = dialog->Field6->text();
871 i->setText (5, tr (f6)); 870 i->setText (5, tr (f6));
872 } 871 }
873 872
874 delete dialog; 873 delete dialog;
875 } 874 }
876} 875}
877 876
878void ZSafe::findPwd() 877void ZSafe::findPwd()
879{ 878{
880 879
881 // open the 'Search' dialog 880 // open the 'Search' dialog
882 SearchDialog *dialog = new SearchDialog(this, tr("Search"), TRUE); 881 SearchDialog *dialog = new SearchDialog(this, tr("Search"), TRUE);
883#ifdef WIN32 882#ifdef WIN32
884 dialog->setCaption ("Qt " + tr("Search")); 883 dialog->setCaption ("Qt " + tr("Search"));
885#endif 884#endif
886 885
887#ifdef DESKTOP 886#ifdef DESKTOP
888#endif 887#endif
889 if (lastSearchedName) 888 if (lastSearchedName)
890 dialog->NameField->setText(lastSearchedName); 889 dialog->NameField->setText(lastSearchedName);
891 else 890 else
892 dialog->NameField->setText(""); 891 dialog->NameField->setText("");
893 if (lastSearchedUsername) 892 if (lastSearchedUsername)
894 dialog->UsernameField->setText(lastSearchedUsername); 893 dialog->UsernameField->setText(lastSearchedUsername);
895 else 894 else
896 dialog->UsernameField->setText(""); 895 dialog->UsernameField->setText("");
897 if (lastSearchedComment) 896 if (lastSearchedComment)
898 dialog->CommentField->setText(lastSearchedComment); 897 dialog->CommentField->setText(lastSearchedComment);
899 else 898 else
900 dialog->CommentField->setText(""); 899 dialog->CommentField->setText("");
901 DialogCode result = (DialogCode) dialog->exec(); 900 DialogCode result = (DialogCode) dialog->exec();
902#ifdef DESKTOP 901#ifdef DESKTOP
903 result = Accepted; 902 result = Accepted;
904#endif 903#endif
905 904
906 QString name; 905 QString name;
907 QString username; 906 QString username;
908 QString comment; 907 QString comment;
909 if (result == Accepted) 908 if (result == Accepted)
910 { 909 {
911 name = dialog->NameField->text(); 910 name = dialog->NameField->text();
912 username = dialog->UsernameField->text(); 911 username = dialog->UsernameField->text();
913 comment = dialog->CommentField->text(); 912 comment = dialog->CommentField->text();
914 qWarning (name); 913 qWarning (name);
915 } 914 }
916 else 915 else
917 { 916 {
918 delete dialog; 917 delete dialog;
919 return; 918 return;
920 } 919 }
921 920
922 if (!name.isEmpty() && name != lastSearchedName || 921 if (!name.isEmpty() && name != lastSearchedName ||
923 lastSearchedName.isEmpty() && !name.isEmpty()) 922 lastSearchedName.isEmpty() && !name.isEmpty())
924 { 923 {
925 // set search at the beginning if a new name is given 924 // set search at the beginning if a new name is given
926 lastSearchedCategory = NULL; 925 lastSearchedCategory = NULL;
927 lastSearchedItem = NULL; 926 lastSearchedItem = NULL;
928 } 927 }
929 lastSearchedName = name; 928 lastSearchedName = name;
930 if (!username.isEmpty() && username != lastSearchedUsername || 929 if (!username.isEmpty() && username != lastSearchedUsername ||
931 lastSearchedUsername.isEmpty() && !username.isEmpty()) 930 lastSearchedUsername.isEmpty() && !username.isEmpty())
932 { 931 {
933 // set search at the beginning if a new name is given 932 // set search at the beginning if a new name is given
934 lastSearchedCategory = NULL; 933 lastSearchedCategory = NULL;
935 lastSearchedItem = NULL; 934 lastSearchedItem = NULL;
936 } 935 }
937 lastSearchedUsername = username; 936 lastSearchedUsername = username;
938 if (!comment.isEmpty() && comment != lastSearchedComment || 937 if (!comment.isEmpty() && comment != lastSearchedComment ||
939 lastSearchedComment.isEmpty() && !comment.isEmpty()) 938 lastSearchedComment.isEmpty() && !comment.isEmpty())
940 { 939 {
941 // set search at the beginning if a new name is given 940 // set search at the beginning if a new name is given
942 lastSearchedCategory = NULL; 941 lastSearchedCategory = NULL;
943 lastSearchedItem = NULL; 942 lastSearchedItem = NULL;
944 } 943 }
945 lastSearchedComment = comment; 944 lastSearchedComment = comment;
946 945
947 ListView->clearSelection(); 946 ListView->clearSelection();
948 947
949 bool found=FALSE; 948 bool found=FALSE;
950 // step through all categories 949 // step through all categories
951 QListViewItem *i; 950 QListViewItem *i;
952 if (lastSearchedCategory) 951 if (lastSearchedCategory)
953 i = lastSearchedCategory; 952 i = lastSearchedCategory;
954 else 953 else
955 i = ListView->firstChild(); 954 i = ListView->firstChild();
956 for (; 955 for (;
957 i != NULL; 956 i != NULL;
958 i = i->nextSibling()) 957 i = i->nextSibling())
959 { 958 {
960 qWarning (i->text(0)); 959 qWarning (i->text(0));
961 i->setSelected(FALSE); 960 i->setSelected(FALSE);
962 961
963 // step through all subitems 962 // step through all subitems
964 QListViewItem *si; 963 QListViewItem *si;
965 if (lastSearchedItem) 964 if (lastSearchedItem)
966 si = lastSearchedItem; 965 si = lastSearchedItem;
967 else 966 else
968 si = i->firstChild(); 967 si = i->firstChild();
969 // for (si = i->firstChild(); 968 // for (si = i->firstChild();
970 for (; 969 for (;
971 si != NULL; 970 si != NULL;
972 si = si->nextSibling()) 971 si = si->nextSibling())
973 { 972 {
974 qWarning (si->text(0)); 973 qWarning (si->text(0));
975 if (si->isSelected()) 974 if (si->isSelected())
976 si->setSelected(FALSE); 975 si->setSelected(FALSE);
977 // ListView->repaintItem(si); 976 // ListView->repaintItem(si);
978 977
979 bool n=TRUE; 978 bool n=TRUE;
980 bool u=TRUE; 979 bool u=TRUE;
981 bool c=TRUE; 980 bool c=TRUE;
982 if (!name.isEmpty()) 981 if (!name.isEmpty())
983 n = (si->text(0)).contains (name, FALSE); 982 n = (si->text(0)).contains (name, FALSE);
984 if (!username.isEmpty()) 983 if (!username.isEmpty())
985 u = (si->text(1)).contains (username, FALSE); 984 u = (si->text(1)).contains (username, FALSE);
986 if (!comment.isEmpty()) 985 if (!comment.isEmpty())
987 c = (si->text(3)).contains (comment, FALSE); 986 c = (si->text(3)).contains (comment, FALSE);
988 987
989 if ((n && u && c ) && !found) 988 if ((n && u && c ) && !found)
990 { 989 {
991 qWarning ("Found"); 990 qWarning ("Found");
992 selectedItem = si; 991 selectedItem = si;
993 si->setSelected(TRUE); 992 si->setSelected(TRUE);
994 ListView->setCurrentItem(si); 993 ListView->setCurrentItem(si);
995 ListView->ensureItemVisible(si); 994 ListView->ensureItemVisible(si);
996 ListView->triggerUpdate(); 995 ListView->triggerUpdate();
997 996
998 lastSearchedCategory = i; 997 lastSearchedCategory = i;
999 // set to the next item 998 // set to the next item
1000 lastSearchedItem = si->nextSibling(); 999 lastSearchedItem = si->nextSibling();
1001 if (!lastSearchedItem) 1000 if (!lastSearchedItem)
1002 { 1001 {
1003 // no next item within category -> set next category 1002 // no next item within category -> set next category
1004 lastSearchedCategory = i->nextSibling(); 1003 lastSearchedCategory = i->nextSibling();
1005 if (!lastSearchedCategory) 1004 if (!lastSearchedCategory)
1006 lastSearchedItem = NULL; // END 1005 lastSearchedItem = NULL; // END
1007 } 1006 }
1008 1007
1009 found = TRUE; 1008 found = TRUE;
1010 delete dialog; 1009 delete dialog;
1011 update(); 1010 update();
1012 return; 1011 return;
1013 } 1012 }
1014 } 1013 }
1015 lastSearchedCategory = i->nextSibling(); 1014 lastSearchedCategory = i->nextSibling();
1016 lastSearchedItem = NULL; 1015 lastSearchedItem = NULL;
1017 } 1016 }
1018 lastSearchedCategory = NULL; 1017 lastSearchedCategory = NULL;
1019 lastSearchedItem = NULL; 1018 lastSearchedItem = NULL;
1020 delete dialog; 1019 delete dialog;
1021 update(); 1020 update();
1022 QMessageBox::information( this, tr("ZSafe"), 1021 QMessageBox::information( this, tr("ZSafe"),
1023 tr("Entry not found"), tr("&OK"), 0); 1022 tr("Entry not found"), tr("&OK"), 0);
1024 1023
1025} 1024}
1026 1025
1027QString ZSafe::getFieldLabel (QListViewItem *_item, QString field, QString def) 1026QString ZSafe::getFieldLabel (QListViewItem *_item, QString field, QString def)
1028{ 1027{
1029 QString category; 1028 QString category;
1030 if (_item) 1029 if (_item)
1031 { 1030 {
1032 if (isCategory(_item)) 1031 if (isCategory(_item))
1033 { 1032 {
1034 category = _item->text(0); 1033 category = _item->text(0);
1035 } 1034 }
1036 else 1035 else
1037 { 1036 {
1038 QListViewItem *cat = _item->parent(); 1037 QListViewItem *cat = _item->parent();
1039 category = cat->text(0); 1038 category = cat->text(0);
1040 } 1039 }
1041 } 1040 }
1042 else 1041 else
1043 { 1042 {
1044 return def; 1043 return def;
1045 } 1044 }
1046 1045
1047 QString app_key = APP_KEY; 1046 QString app_key = APP_KEY;
1048#ifndef DESKTOP 1047#ifndef DESKTOP
1049#ifndef WIN32 1048#ifndef WIN32
1050 conf->setGroup ("fieldDefs"); 1049 conf->setGroup ("fieldDefs");
1051#endif 1050#endif
1052#else 1051#else
1053#ifndef WIN32 1052#ifndef WIN32
1054 app_key += "/fieldDefs/"; 1053 app_key += "/fieldDefs/";
1055#endif 1054#endif
1056#endif 1055#endif
1057// #ifndef WIN32 1056// #ifndef WIN32
1058 QString label = conf->readEntry(app_key+category+"-field"+field,def); 1057 QString label = conf->readEntry(app_key+category+"-field"+field,def);
1059// #else 1058// #else
1060// QString label(def); 1059// QString label(def);
1061// #endif 1060// #endif
1062 1061
1063#ifndef DESKTOP 1062#ifndef DESKTOP
1064 conf->setGroup ("zsafe"); 1063 conf->setGroup ("zsafe");
1065#endif 1064#endif
1066 return label; 1065 return label;
1067} 1066}
1068 1067
1069QString ZSafe::getFieldLabel (QString category, QString field, QString def) 1068QString ZSafe::getFieldLabel (QString category, QString field, QString def)
1070{ 1069{
1071 QString app_key = APP_KEY; 1070 QString app_key = APP_KEY;
1072#ifndef DESKTOP 1071#ifndef DESKTOP
1073 conf->setGroup ("fieldDefs"); 1072 conf->setGroup ("fieldDefs");
1074#else 1073#else
1075#ifndef WIN32 1074#ifndef WIN32
1076 app_key += "/fieldDefs/"; 1075 app_key += "/fieldDefs/";
1077#endif 1076#endif
1078#endif 1077#endif
1079// #ifndef WIN32 1078// #ifndef WIN32
1080 QString label = conf->readEntry(app_key+category+"-field"+field, 1079 QString label = conf->readEntry(app_key+category+"-field"+field,
1081 def); 1080 def);
1082// #else 1081// #else
1083 // QString label(def); 1082 // QString label(def);
1084// #endif 1083// #endif
1085#ifndef DESKTOP 1084#ifndef DESKTOP
1086 conf->setGroup ("zsafe"); 1085 conf->setGroup ("zsafe");
1087#endif 1086#endif
1088 return label; 1087 return label;
1089} 1088}
1090 1089
1091void ZSafe::showInfo( QListViewItem *_item) 1090void ZSafe::showInfo( QListViewItem *_item)
1092{ 1091{
1093 if (!_item) 1092 if (!_item)
1094 return; 1093 return;
1095 if (selectedItem != NULL) 1094 if (selectedItem != NULL)
1096 selectedItem->setSelected(FALSE); 1095 selectedItem->setSelected(FALSE);
1097 1096
1098 selectedItem = _item; 1097 selectedItem = _item;
1099 selectedItem->setSelected(TRUE); 1098 selectedItem->setSelected(TRUE);
1100 1099
1101 if (!isCategory(_item)) 1100 if (!isCategory(_item))
1102 { 1101 {
1103/* 1102/*
1104 QString label=selectedItem->text(0); 1103 QString label=selectedItem->text(0);
1105 label+="\n"; 1104 label+="\n";
1106 label+=selectedItem->text(1); 1105 label+=selectedItem->text(1);
1107 label+="\n"; 1106 label+="\n";
1108 label+=selectedItem->text(2); 1107 label+=selectedItem->text(2);
1109 label+="\n"; 1108 label+="\n";
1110 label+=selectedItem->text(3); 1109 label+=selectedItem->text(3);
1111*/ 1110*/
1112 1111
1113 QString text; 1112 QString text;
1114 QString entry; 1113 QString entry;
1115 1114
1116 text = "<html><body><div align=""center""><u><b>"; 1115 text = "<html><body><div align=""center""><u><b>";
1117 text += selectedItem->text(0); 1116 text += selectedItem->text(0);
1118 text += "</b></u><br></div><br>"; 1117 text += "</b></u><br></div><br>";
1119 1118
1120 entry = selectedItem->text(1); 1119 entry = selectedItem->text(1);
1121 if (!entry.isEmpty() && entry.compare(" ")) 1120 if (!entry.isEmpty() && entry.compare(" "))
1122 { 1121 {
1123 text += "<u><b>"; 1122 text += "<u><b>";
1124 text += getFieldLabel (selectedItem, "2", tr("Username")); 1123 text += getFieldLabel (selectedItem, "2", tr("Username"));
1125 text += ":<br></b></u><blockquote>"; 1124 text += ":<br></b></u><blockquote>";
1126 text += entry; 1125 text += entry;
1127 text += "</blockquote>"; 1126 text += "</blockquote>";
1128 // text += "<br>"; 1127 // text += "<br>";
1129 } 1128 }
1130 1129
1131 entry = selectedItem->text(2); 1130 entry = selectedItem->text(2);
1132 if (!entry.isEmpty() && entry.compare(" ")) 1131 if (!entry.isEmpty() && entry.compare(" "))
1133 { 1132 {
1134 text += "<u><b>"; 1133 text += "<u><b>";
1135 text += getFieldLabel (selectedItem, "3", tr("Password")); 1134 text += getFieldLabel (selectedItem, "3", tr("Password"));
1136 text += ":<br> </b></u><blockquote>"; 1135 text += ":<br> </b></u><blockquote>";
1137 text += entry; 1136 text += entry;
1138 text += "</blockquote>"; 1137 text += "</blockquote>";
1139 // text += "<br>"; 1138 // text += "<br>";
1140 } 1139 }
1141 1140
1142 entry = selectedItem->text(4); 1141 entry = selectedItem->text(4);
1143 if (!entry.isEmpty() && entry.compare(" ")) 1142 if (!entry.isEmpty() && entry.compare(" "))
1144 { 1143 {
1145 text += "<u><b>"; 1144 text += "<u><b>";
1146 text += getFieldLabel (selectedItem, "5", tr("Field 4")); 1145 text += getFieldLabel (selectedItem, "5", tr("Field 4"));
1147 text += ":<br> </b></u><blockquote>"; 1146 text += ":<br> </b></u><blockquote>";
1148 text += entry; 1147 text += entry;
1149 text += "</blockquote>"; 1148 text += "</blockquote>";
1150 // text += "<br>"; 1149 // text += "<br>";
1151 } 1150 }
1152 1151
1153 entry = selectedItem->text(5); 1152 entry = selectedItem->text(5);
1154 if (!entry.isEmpty() && entry.compare(" ")) 1153 if (!entry.isEmpty() && entry.compare(" "))
1155 { 1154 {
1156 text += "<u><b>"; 1155 text += "<u><b>";
1157 text += getFieldLabel (selectedItem, "6", tr("Field 5")); 1156 text += getFieldLabel (selectedItem, "6", tr("Field 5"));
1158 text += ":<br> </b></u><blockquote>"; 1157 text += ":<br> </b></u><blockquote>";
1159 text += entry; 1158 text += entry;
1160 text += "</blockquote>"; 1159 text += "</blockquote>";
1161 // text += "<br>"; 1160 // text += "<br>";
1162 } 1161 }
1163 1162
1164 entry = selectedItem->text(3); 1163 entry = selectedItem->text(3);
1165 if (!entry.isEmpty() && entry.compare(" ")) 1164 if (!entry.isEmpty() && entry.compare(" "))
1166 { 1165 {
1167 text += "<u><b>"; 1166 text += "<u><b>";
1168 text += getFieldLabel (selectedItem, "4", tr("Comment")); 1167 text += getFieldLabel (selectedItem, "4", tr("Comment"));
1169 text += ":<br> </b></u>"; 1168 text += ":<br> </b></u>";
1170 QString comment = selectedItem->text(3); 1169 QString comment = selectedItem->text(3);
1171 comment.replace (QRegExp("\n"), "<br>"); 1170 comment.replace (QRegExp("\n"), "<br>");
1172 text += comment; 1171 text += comment;
1173 // text += "<br>"; 1172 // text += "<br>";
1174 } 1173 }
1175 1174
1176 text += "</body></html>"; 1175 text += "</body></html>";
1177 1176
1178 infoForm->InfoText->setText(text); 1177 infoForm->InfoText->setText(text);
1179 infoForm->hide(); 1178 infoForm->hide();
1180 QPEApplication::showDialog( infoForm ); 1179 QPEApplication::showDialog( infoForm );
1181 } 1180 }
1182} 1181}
1183 1182
1184void ZSafe::listViewSelected( QListViewItem *_item) 1183void ZSafe::listViewSelected( QListViewItem *_item)
1185{ 1184{
1186 if (!_item) 1185 if (!_item)
1187 return; 1186 return;
1188 if (selectedItem != NULL) 1187 if (selectedItem != NULL)
1189 selectedItem->setSelected(FALSE); 1188 selectedItem->setSelected(FALSE);
1190 1189
1191 selectedItem = _item; 1190 selectedItem = _item;
1192 1191
1193#ifndef DESKTOP 1192#ifndef DESKTOP
1194 // set the column text dependent on the selected item 1193 // set the column text dependent on the selected item
1195 ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name"))); 1194 ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name")));
1196 ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2"))); 1195 ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2")));
1197 ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3"))); 1196 ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3")));
1198 ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment"))); 1197 ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment")));
1199 ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4"))); 1198 ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4")));
1200 ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5"))); 1199 ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5")));
1201#endif 1200#endif
1202#ifdef WIN32 1201#ifdef WIN32
1203 // set the column text dependent on the selected item 1202 // set the column text dependent on the selected item
1204 ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name"))); 1203 ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name")));
1205 ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2"))); 1204 ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2")));
1206 ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3"))); 1205 ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3")));
1207 ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment"))); 1206 ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment")));
1208 ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4"))); 1207 ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4")));
1209 ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5"))); 1208 ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5")));
1210#endif 1209#endif
1211 1210
1212} 1211}
1213 1212
1214bool ZSafe::isCategory(QListViewItem *_item) 1213bool ZSafe::isCategory(QListViewItem *_item)
1215{ 1214{
1216 if (_item == NULL) 1215 if (_item == NULL)
1217 return FALSE; 1216 return FALSE;
1218 1217
1219 QString categoryName = _item->text (0); 1218 QString categoryName = _item->text (0);
1220 if (categories.find (categoryName)) 1219 if (categories.find (categoryName))
1221 return TRUE; 1220 return TRUE;
1222 else 1221 else
1223 return FALSE; 1222 return FALSE;
1224} 1223}
1225 1224
1226void ZSafe::removeAsciiFile() 1225void ZSafe::removeAsciiFile()
1227{ 1226{
1228 // QString fn = filename + ".txt"; 1227 // QString fn = filename + ".txt";
1229 // open the file dialog 1228 // open the file dialog
1230#ifndef DESKTOP 1229#ifndef DESKTOP
1231#ifndef NO_OPIE 1230#ifndef NO_OPIE
1232 QMap<QString, QStringList> mimeTypes; 1231 QMap<QString, QStringList> mimeTypes;
1233 mimeTypes.insert(tr("All"), QStringList() ); 1232 mimeTypes.insert(tr("All"), QStringList() );
1234 mimeTypes.insert(tr("Text"), "text/*" ); 1233 mimeTypes.insert(tr("Text"), "text/*" );
1235 QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, 1234 QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL,
1236 QDir::homeDirPath() + "/Documents/application/zsafe", 1235 QDir::homeDirPath() + "/Documents/application/zsafe",
1237 QString::null, 1236 QString::null,
1238 mimeTypes, 1237 mimeTypes,
1239 this, 1238 this,
1240 tr ("Remove text file")); 1239 tr ("Remove text file"));
1241#else 1240#else
1242 QString fn = ScQtFileEdit::getOpenFileName(this, 1241 QString fn = ScQtFileEdit::getOpenFileName(this,
1243 tr ("Remove text file"), 1242 tr ("Remove text file"),
1244 QDir::homeDirPath() + "/Documents/application/zsafe", 1243 QDir::homeDirPath() + "/Documents/application/zsafe",
1245 "*.txt"); 1244 "*.txt");
1246#endif 1245#endif
1247#else 1246#else
1248 QString fn = QFileDialog::getOpenFileName( 1247 QString fn = QFileDialog::getOpenFileName(
1249 QDir::homeDirPath() + "/Documents/application/zsafe", 1248 QDir::homeDirPath() + "/Documents/application/zsafe",
1250 "ZSafe (*.txt)", 1249 "ZSafe (*.txt)",
1251 this, 1250 this,
1252 "ZSafe File Dialog" 1251 "ZSafe File Dialog"
1253 "Choose a text file" ); 1252 "Choose a text file" );
1254#endif 1253#endif
1255 1254
1256 if (fn && fn.length() > 0 ) 1255 if (fn && fn.length() > 0 )
1257 { 1256 {
1258 QFile f( fn ); 1257 QFile f( fn );
1259 if ( !f.remove() ) 1258 if ( !f.remove() )
1260 { 1259 {
1261 qWarning( QString("Could not remove file %1").arg(fn), 1260 qWarning( QString("Could not remove file %1").arg(fn),
1262 2000 ); 1261 2000 );
1263 QMessageBox::critical( 0, tr("ZSafe"), 1262 QMessageBox::critical( 0, tr("ZSafe"),
1264 tr("Could not remove text file.") ); 1263 tr("Could not remove text file.") );
1265 return; 1264 return;
1266 } 1265 }
1267 } 1266 }
1268} 1267}
1269 1268
1270void ZSafe::writeAllEntries() 1269void ZSafe::writeAllEntries()
1271{ 1270{
1272 if (filename.isEmpty()) 1271 if (filename.isEmpty())
1273 { 1272 {
1274 QMessageBox::critical( 0, tr("ZSafe"), 1273 QMessageBox::critical( 0, tr("ZSafe"),
1275 tr("No document defined.\nYou have to create a new document")); 1274 tr("No document defined.\nYou have to create a new document"));
1276 return; 1275 return;
1277 } 1276 }
1278 1277
1279 // open the file dialog 1278 // open the file dialog
1280#ifndef DESKTOP 1279#ifndef DESKTOP
1281#ifndef NO_OPIE 1280#ifndef NO_OPIE
1282 QMap<QString, QStringList> mimeTypes; 1281 QMap<QString, QStringList> mimeTypes;
1283 mimeTypes.insert(tr("All"), QStringList() ); 1282 mimeTypes.insert(tr("All"), QStringList() );
1284 mimeTypes.insert(tr("Text"), "text/*" ); 1283 mimeTypes.insert(tr("Text"), "text/*" );
1285 QString fn = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL, 1284 QString fn = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL,
1286 QDir::homeDirPath() + "/Documents/application/zsafe", 1285 QDir::homeDirPath() + "/Documents/application/zsafe",
1287 QString::null, 1286 QString::null,
1288 mimeTypes, 1287 mimeTypes,
1289 this, 1288 this,
1290 tr ("Export text file")); 1289 tr ("Export text file"));
1291#else 1290#else
1292 QString fn = ScQtFileEdit::getSaveAsFileName(this, 1291 QString fn = ScQtFileEdit::getSaveAsFileName(this,
1293 tr ("Export text file"), 1292 tr ("Export text file"),
1294 QDir::homeDirPath() + "/Documents/application/zsafe", 1293 QDir::homeDirPath() + "/Documents/application/zsafe",
1295 "*.txt"); 1294 "*.txt");
1296#endif 1295#endif
1297#else 1296#else
1298 QString fn = QFileDialog::getSaveFileName( 1297 QString fn = QFileDialog::getSaveFileName(
1299 QDir::homeDirPath() + "/Documents/application/zsafe", 1298 QDir::homeDirPath() + "/Documents/application/zsafe",
1300 "ZSafe (*.txt)", 1299 "ZSafe (*.txt)",
1301 this, 1300 this,
1302 "ZSafe File Dialog" 1301 "ZSafe File Dialog"
1303 "Choose a text file" ); 1302 "Choose a text file" );
1304#endif 1303#endif
1305 1304
1306 // open the new document 1305 // open the new document
1307 if (fn && fn.length() > 0 ) 1306 if (fn && fn.length() > 0 )
1308 { 1307 {
1309 QFile f( fn ); 1308 QFile f( fn );
1310 if ( !f.open( IO_WriteOnly ) ) { 1309 if ( !f.open( IO_WriteOnly ) ) {
1311 qWarning( QString("Could not write to file %1").arg(fn), 1310 qWarning( QString("Could not write to file %1").arg(fn),
1312 2000 ); 1311 2000 );
1313 QMessageBox::critical( 0, "ZSafe", 1312 QMessageBox::critical( 0, "ZSafe",
1314 QString("Could not export to text file.") ); 1313 QString("Could not export to text file.") );
1315 return; 1314 return;
1316 } 1315 }
1317 QTextStream t( &f ); 1316 QTextStream t( &f );
1318 1317
1319 QListViewItem *i; 1318 QListViewItem *i;
1320 // step through all categories 1319 // step through all categories
1321 for (i = ListView->firstChild(); 1320 for (i = ListView->firstChild();
1322 i != NULL; 1321 i != NULL;
1323 i = i->nextSibling()) 1322 i = i->nextSibling())
1324 { 1323 {
1325 // step through all subitems 1324 // step through all subitems
1326 QListViewItem *si; 1325 QListViewItem *si;
1327 for (si = i->firstChild(); 1326 for (si = i->firstChild();
1328 si != NULL; 1327 si != NULL;
1329 si = si->nextSibling()) 1328 si = si->nextSibling())
1330 { 1329 {
1331 QString oneEntry; 1330 QString oneEntry;
1332 oneEntry += "\""; 1331 oneEntry += "\"";
1333 oneEntry += i->text(0); 1332 oneEntry += i->text(0);
1334 oneEntry += "\";"; 1333 oneEntry += "\";";
1335 oneEntry += "\""; 1334 oneEntry += "\"";
1336 oneEntry += si->text(0); 1335 oneEntry += si->text(0);
1337 oneEntry += "\";"; 1336 oneEntry += "\";";
1338 oneEntry += "\""; 1337 oneEntry += "\"";
1339 oneEntry += si->text(1); 1338 oneEntry += si->text(1);
1340 oneEntry += "\";"; 1339 oneEntry += "\";";
1341 oneEntry += "\""; 1340 oneEntry += "\"";
1342 oneEntry += si->text(2); 1341 oneEntry += si->text(2);
1343 oneEntry += "\";"; 1342 oneEntry += "\";";
1344 oneEntry += "\""; 1343 oneEntry += "\"";
1345 QString comment = si->text(3); 1344 QString comment = si->text(3);
1346 comment.replace (QRegExp("\n"), "<br>"); 1345 comment.replace (QRegExp("\n"), "<br>");
1347 oneEntry += comment; 1346 oneEntry += comment;
1348 oneEntry += "\";"; 1347 oneEntry += "\";";
1349 oneEntry += "\""; 1348 oneEntry += "\"";
1350 oneEntry += si->text(4); 1349 oneEntry += si->text(4);
1351 oneEntry += "\";"; 1350 oneEntry += "\";";
1352 oneEntry += "\""; 1351 oneEntry += "\"";
1353 oneEntry += si->text(5); 1352 oneEntry += si->text(5);
1354 oneEntry += "\""; 1353 oneEntry += "\"";
1355 // qWarning (oneEntry); 1354 // qWarning (oneEntry);
1356 t << oneEntry << endl; 1355 t << oneEntry << endl;
1357 1356
1358 // qWarning (si->text(0)); 1357 // qWarning (si->text(0));
1359 } 1358 }
1360 } 1359 }
1361 f.close(); 1360 f.close();
1362 } 1361 }
1363} 1362}
1364 1363
1365void ZSafe::readAllEntries() 1364void ZSafe::readAllEntries()
1366{ 1365{
1367 if (filename.isEmpty()) 1366 if (filename.isEmpty())
1368 { 1367 {
1369 QMessageBox::critical( 0, tr("ZSafe"), 1368 QMessageBox::critical( 0, tr("ZSafe"),
1370 tr("No document defined.\nYou have to create a new document")); 1369 tr("No document defined.\nYou have to create a new document"));
1371 return; 1370 return;
1372 } 1371 }
1373 1372
1374 // open the file dialog 1373 // open the file dialog
1375#ifndef DESKTOP 1374#ifndef DESKTOP
1376#ifndef NO_OPIE 1375#ifndef NO_OPIE
1377 QMap<QString, QStringList> mimeTypes; 1376 QMap<QString, QStringList> mimeTypes;
1378 mimeTypes.insert(tr("All"), QStringList() ); 1377 mimeTypes.insert(tr("All"), QStringList() );
1379 mimeTypes.insert(tr("Text"), "text/*" ); 1378 mimeTypes.insert(tr("Text"), "text/*" );
1380 QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, 1379 QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL,
1381 QDir::homeDirPath() + "/Documents/application/zsafe", 1380 QDir::homeDirPath() + "/Documents/application/zsafe",
1382 QString::null, 1381 QString::null,
1383 mimeTypes, 1382 mimeTypes,
1384 this, 1383 this,
1385 tr ("Import text file")); 1384 tr ("Import text file"));
1386#else 1385#else
1387 QString fn = ScQtFileEdit::getOpenFileName(this, 1386 QString fn = ScQtFileEdit::getOpenFileName(this,
1388 tr ("Import text file"), 1387 tr ("Import text file"),
1389 QDir::homeDirPath() + "/Documents/application/zsafe", 1388 QDir::homeDirPath() + "/Documents/application/zsafe",
1390 "*.txt"); 1389 "*.txt");
1391#endif 1390#endif
1392#else 1391#else
1393 QString fn = QFileDialog::getOpenFileName( 1392 QString fn = QFileDialog::getOpenFileName(
1394 QDir::homeDirPath() + "/Documents/application/zsafe", 1393 QDir::homeDirPath() + "/Documents/application/zsafe",
1395 "ZSafe (*.txt)", 1394 "ZSafe (*.txt)",
1396 this, 1395 this,
1397 "ZSafe File Dialog" 1396 "ZSafe File Dialog"
1398 "Choose a text file" ); 1397 "Choose a text file" );
1399#endif 1398#endif
1400 1399
1401 if (fn && fn.length() > 0 ) 1400 if (fn && fn.length() > 0 )
1402 { 1401 {
1403 QFile f( fn ); 1402 QFile f( fn );
1404 if ( !f.open( IO_ReadOnly ) ) 1403 if ( !f.open( IO_ReadOnly ) )
1405 { 1404 {
1406 qWarning( QString("Could not read file %1").arg(fn), 1405 qWarning( QString("Could not read file %1").arg(fn),
1407 2000 ); 1406 2000 );
1408 QMessageBox::critical( 0, "ZSafe", 1407 QMessageBox::critical( 0, "ZSafe",
1409 QString("Could not import text file.") ); 1408 QString("Could not import text file.") );
1410 return; 1409 return;
1411 } 1410 }
1412 1411
1413 modified = true; 1412 modified = true;
1414 1413
1415 // clear the password list 1414 // clear the password list
1416 selectedItem = NULL; 1415 selectedItem = NULL;
1417 QListViewItem *i; 1416 QListViewItem *i;
1418 // step through all categories 1417 // step through all categories
1419 for (i = ListView->firstChild(); 1418 for (i = ListView->firstChild();
1420 i != NULL; 1419 i != NULL;
1421 i = i->nextSibling()) 1420 i = i->nextSibling())
1422 { 1421 {
1423 // step through all subitems 1422 // step through all subitems
1424 QListViewItem *si; 1423 QListViewItem *si;
1425 for (si = i->firstChild(); 1424 for (si = i->firstChild();
1426 si != NULL; ) 1425 si != NULL; )
1427 // si = si->nextSibling()) 1426 // si = si->nextSibling())
1428 { 1427 {
1429 QListViewItem *_si = si; 1428 QListViewItem *_si = si;
1430 si = si->nextSibling(); 1429 si = si->nextSibling();
1431 i->takeItem(_si); // remove from view list 1430 i->takeItem(_si); // remove from view list
1432 if (_si) delete _si; 1431 if (_si) delete _si;
1433 } 1432 }
1434 } 1433 }
1435 1434
1436 qWarning ("ReadAllEntries(): "); 1435 qWarning ("ReadAllEntries(): ");
1437 1436
1438 QTextStream t(&f); 1437 QTextStream t(&f);
1439 while ( !t.eof() ) 1438 while ( !t.eof() )
1440 { 1439 {
1441 QString s = t.readLine(); 1440 QString s = t.readLine();
1442 s.replace (QRegExp("\";\""), "\"|\""); 1441 s.replace (QRegExp("\";\""), "\"|\"");
1443 // char buffer[1024]; 1442 // char buffer[1024];
1444#ifndef WIN32 1443#ifndef WIN32
1445 char buffer[s.length()+1]; 1444 char buffer[s.length()+1];
1446#else 1445#else
1447 char buffer[4048]; 1446 char buffer[4048];
1448#endif 1447#endif
1449 1448
1450 1449
1451 /* modify QString -> QCString::utf8 */ 1450 /* modify QString -> QCString::utf8 */
1452 1451
1453 strcpy (buffer, s.utf8()); 1452 strcpy (buffer, s.utf8());
1454 1453
1455 QString name; 1454 QString name;
1456 QString user; 1455 QString user;
1457 QString password; 1456 QString password;
1458 QString comment; 1457 QString comment;
1459 QString field5=""; 1458 QString field5="";
1460 QString field6=""; 1459 QString field6="";
1461 1460
1462 // separete the entries 1461 // separete the entries
1463 char *i = strtok (buffer, "|"); 1462 char *i = strtok (buffer, "|");
1464 QString category(QString::fromUtf8(&i[1])); 1463 QString category(QString::fromUtf8(&i[1]));
1465 category.truncate(category.length() -1); 1464 category.truncate(category.length() -1);
1466 1465
1467 int idx=0; 1466 int idx=0;
1468 while ((i = strtok (NULL, "|")) != NULL) 1467 while ((i = strtok (NULL, "|")) != NULL)
1469 { 1468 {
1470 switch (idx) 1469 switch (idx)
1471 { 1470 {
1472 case 0: 1471 case 0:
1473 name = QString::fromUtf8(&i[1]); 1472 name = QString::fromUtf8(&i[1]);
1474 name.truncate(name.length() -1); 1473 name.truncate(name.length() -1);
1475 // name 1474 // name
1476 break; 1475 break;
1477 case 1: 1476 case 1:
1478 // user 1477 // user
1479 user = QString::fromUtf8(&i[1]); 1478 user = QString::fromUtf8(&i[1]);
1480 user.truncate(user.length() -1); 1479 user.truncate(user.length() -1);
1481 break; 1480 break;
1482 case 2: 1481 case 2:
1483 // password 1482 // password
1484 password = QString::fromUtf8(&i[1]); 1483 password = QString::fromUtf8(&i[1]);
1485 password.truncate(password.length() -1); 1484 password.truncate(password.length() -1);
1486 break; 1485 break;
1487 case 3: 1486 case 3:
1488 // comment 1487 // comment
1489 comment = QString::fromUtf8(&i[1]); 1488 comment = QString::fromUtf8(&i[1]);
1490 comment.truncate(comment.length() -1); 1489 comment.truncate(comment.length() -1);
1491 break; 1490 break;
1492 case 4: 1491 case 4:
1493 // field5 1492 // field5
1494 field5 = QString::fromUtf8(&i[1]); 1493 field5 = QString::fromUtf8(&i[1]);
1495 field5.truncate(field5.length() -1); 1494 field5.truncate(field5.length() -1);
1496 break; 1495 break;
1497 case 5: 1496 case 5:
1498 // field6 1497 // field6
1499 field6 = QString::fromUtf8(&i[1]); 1498 field6 = QString::fromUtf8(&i[1]);
1500 field6.truncate(field6.length() -1); 1499 field6.truncate(field6.length() -1);
1501 break; 1500 break;
1502 } 1501 }
1503 idx++; 1502 idx++;
1504 } 1503 }
1505 1504
1506 Category *cat= categories.find (category); 1505 Category *cat= categories.find (category);
1507 if (cat) 1506 if (cat)
1508 { 1507 {
1509 // use the existend item 1508 // use the existend item
1510 QListViewItem *catItem = cat->getListItem(); 1509 QListViewItem *catItem = cat->getListItem();
1511 if (catItem) 1510 if (catItem)
1512 { 1511 {
1513 QListViewItem * item = new ShadedListItem( 0, catItem ); 1512 QListViewItem * item = new ShadedListItem( 0, catItem );
1514 item->setText( 0, tr( name ) ); 1513 item->setText( 0, tr( name ) );
1515 item->setText( 1, tr( user ) ); 1514 item->setText( 1, tr( user ) );
1516 item->setText( 2, tr( password ) ); 1515 item->setText( 2, tr( password ) );
1517 item->setText( 3, tr( comment ) ); 1516 item->setText( 3, tr( comment ) );
1518 item->setText( 4, tr( field5 ) ); 1517 item->setText( 4, tr( field5 ) );
1519 item->setText( 5, tr( field6 ) ); 1518 item->setText( 5, tr( field6 ) );
1520 catItem->setOpen( TRUE ); 1519 catItem->setOpen( TRUE );
1521 } 1520 }
1522 } 1521 }
1523 else 1522 else
1524 { 1523 {
1525 QListViewItem *catI = new ShadedListItem( 1, ListView ); 1524 QListViewItem *catI = new ShadedListItem( 1, ListView );
1526 // create and insert a new item 1525 // create and insert a new item
1527 QListViewItem * item = new ShadedListItem( 0, catI ); 1526 QListViewItem * item = new ShadedListItem( 0, catI );
1528 item->setText( 0, tr( name ) ); 1527 item->setText( 0, tr( name ) );
1529 item->setText( 1, tr( user ) ); 1528 item->setText( 1, tr( user ) );
1530 item->setText( 2, tr( password ) ); 1529 item->setText( 2, tr( password ) );
1531 item->setText( 3, tr( comment ) ); 1530 item->setText( 3, tr( comment ) );
1532 item->setText( 4, tr( field5 ) ); 1531 item->setText( 4, tr( field5 ) );
1533 item->setText( 5, tr( field6 ) ); 1532 item->setText( 5, tr( field6 ) );
1534 1533
1535 catI->setOpen( TRUE ); 1534 catI->setOpen( TRUE );
1536 1535
1537 Category *c1 = new Category(); 1536 Category *c1 = new Category();
1538 c1->setCategoryName(category); 1537 c1->setCategoryName(category);
1539 1538
1540 QString icon; 1539 QString icon;
1541 QString fullIconPath; 1540 QString fullIconPath;
1542 QPixmap *pix; 1541 QPixmap *pix;
1543// #ifndef WIN32 1542// #ifndef WIN32
1544 icon = conf->readEntry(APP_KEY+category); 1543 icon = conf->readEntry(APP_KEY+category);
1545// #endif 1544// #endif
1546 bool isIconAv = false; 1545 bool isIconAv = false;
1547 if (!icon.isEmpty() && !icon.isNull()) 1546 if (!icon.isEmpty() && !icon.isNull())
1548 { 1547 {
1549 // build the full path 1548 // build the full path
1550 fullIconPath = iconPath + icon; 1549 fullIconPath = iconPath + icon;
1551 pix = new QPixmap (fullIconPath); 1550 pix = new QPixmap (fullIconPath);
1552 if (pix) 1551 if (pix)
1553 { 1552 {
1554 QImage img = pix->convertToImage(); 1553 QImage img = pix->convertToImage();
1555 pix->convertFromImage(img.smoothScale(14,14)); 1554 pix->convertFromImage(img.smoothScale(14,14));
1556 c1->setIconName (icon); 1555 c1->setIconName (icon);
1557 c1->setIcon (*pix); 1556 c1->setIcon (*pix);
1558 isIconAv = true; 1557 isIconAv = true;
1559 } 1558 }
1560 } 1559 }
1561 if (!isIconAv) 1560 if (!isIconAv)
1562 { 1561 {
1563 c1->setIcon (*getPredefinedIcon(category)); 1562 c1->setIcon (*getPredefinedIcon(category));
1564 } 1563 }
1565 c1->setListItem (catI); 1564 c1->setListItem (catI);
1566 c1->initListItem(); 1565 c1->initListItem();
1567 categories.insert (c1->getCategoryName(), c1); 1566 categories.insert (c1->getCategoryName(), c1);
1568 } 1567 }
1569 1568
1570 } 1569 }
1571 f.close(); 1570 f.close();
1572 1571
1573 } 1572 }
1574 else 1573 else
1575 { 1574 {
1576 } 1575 }
1577 1576
1578} 1577}
1579 1578
1580#ifdef UNUSED 1579#ifdef UNUSED
1581void ZSafe::writeAllEntries() 1580void ZSafe::writeAllEntries()
1582{ 1581{
1583 // open the file for writing 1582 // open the file for writing
1584 QString fn = filename + ".txt"; 1583 QString fn = filename + ".txt";
1585 QFile f( fn ); 1584 QFile f( fn );
1586 if ( !f.open( IO_WriteOnly ) ) { 1585 if ( !f.open( IO_WriteOnly ) ) {
1587 qWarning( QString("Could not write to file %1").arg(fn), 1586 qWarning( QString("Could not write to file %1").arg(fn),
1588 2000 ); 1587 2000 );
1589 QMessageBox::critical( 0, tr("ZSafe"), 1588 QMessageBox::critical( 0, tr("ZSafe"),
1590 tr("Could not export to text file.") ); 1589 tr("Could not export to text file.") );
1591 return; 1590 return;
1592 } 1591 }
1593 QTextStream t( &f ); 1592 QTextStream t( &f );
1594 1593
1595 QListViewItem *i; 1594 QListViewItem *i;
1596 // step through all categories 1595 // step through all categories
1597 for (i = ListView->firstChild(); 1596 for (i = ListView->firstChild();
1598 i != NULL; 1597 i != NULL;
1599 i = i->nextSibling()) 1598 i = i->nextSibling())
1600 { 1599 {
1601 // step through all subitems 1600 // step through all subitems
1602 QListViewItem *si; 1601 QListViewItem *si;
1603 for (si = i->firstChild(); 1602 for (si = i->firstChild();
1604 si != NULL; 1603 si != NULL;
1605 si = si->nextSibling()) 1604 si = si->nextSibling())
1606 { 1605 {
1607 QString oneEntry; 1606 QString oneEntry;
1608 oneEntry += "\""; 1607 oneEntry += "\"";
1609 oneEntry += i->text(0); 1608 oneEntry += i->text(0);
1610 oneEntry += "\";"; 1609 oneEntry += "\";";
1611 oneEntry += "\""; 1610 oneEntry += "\"";
1612 oneEntry += si->text(0); 1611 oneEntry += si->text(0);
1613 oneEntry += "\";"; 1612 oneEntry += "\";";
1614 oneEntry += "\""; 1613 oneEntry += "\"";
1615 oneEntry += si->text(1); 1614 oneEntry += si->text(1);
1616 oneEntry += "\";"; 1615 oneEntry += "\";";
1617 oneEntry += "\""; 1616 oneEntry += "\"";
1618 oneEntry += si->text(2); 1617 oneEntry += si->text(2);
1619 oneEntry += "\";"; 1618 oneEntry += "\";";
1620 oneEntry += "\""; 1619 oneEntry += "\"";
1621 // oneEntry += si->text(3); 1620 // oneEntry += si->text(3);
1622 QString comment = si->text(3); 1621 QString comment = si->text(3);
1623 comment.replace (QRegExp("\n"), "<br>"); 1622 comment.replace (QRegExp("\n"), "<br>");
1624 oneEntry += comment; 1623 oneEntry += comment;
1625 oneEntry += "\""; 1624 oneEntry += "\"";
1626 // qWarning (oneEntry); 1625 // qWarning (oneEntry);
1627 t << oneEntry << endl; 1626 t << oneEntry << endl;
1628 1627
1629 // qWarning (si->text(0)); 1628 // qWarning (si->text(0));
1630 } 1629 }
1631 } 1630 }
1632 f.close(); 1631 f.close();
1633} 1632}
1634 1633
1635void ZSafe::readAllEntries() 1634void ZSafe::readAllEntries()
1636{ 1635{
1637 QString fn = filename + ".txt"; 1636 QString fn = filename + ".txt";
1638 QFile f( fn ); 1637 QFile f( fn );
1639 if ( !f.open( IO_ReadOnly ) ) 1638 if ( !f.open( IO_ReadOnly ) )
1640 { 1639 {
1641 qWarning( QString("Could not read file %1").arg(fn), 1640 qWarning( QString("Could not read file %1").arg(fn),
1642 2000 ); 1641 2000 );
1643 QMessageBox::critical( 0, tr("ZSafe"), 1642 QMessageBox::critical( 0, tr("ZSafe"),
1644 tr("Could not import text file.") ); 1643 tr("Could not import text file.") );
1645 return; 1644 return;
1646 } 1645 }
1647 1646
1648 modified = true; 1647 modified = true;
1649 1648
1650 // clear the password list 1649 // clear the password list
1651 selectedItem = NULL; 1650 selectedItem = NULL;
1652 QListViewItem *i; 1651 QListViewItem *i;
1653 // step through all categories 1652 // step through all categories
1654 for (i = ListView->firstChild(); 1653 for (i = ListView->firstChild();
1655 i != NULL; 1654 i != NULL;
1656 i = i->nextSibling()) 1655 i = i->nextSibling())
1657 { 1656 {
1658 // step through all subitems 1657 // step through all subitems
1659 QListViewItem *si; 1658 QListViewItem *si;
1660 for (si = i->firstChild(); 1659 for (si = i->firstChild();
1661 si != NULL; ) 1660 si != NULL; )
1662 // si = si->nextSibling()) 1661 // si = si->nextSibling())
1663 { 1662 {
1664 QListViewItem *_si = si; 1663 QListViewItem *_si = si;
1665 si = si->nextSibling(); 1664 si = si->nextSibling();
1666 i->takeItem(_si); // remove from view list 1665 i->takeItem(_si); // remove from view list
1667 if (_si) delete _si; 1666 if (_si) delete _si;
1668 } 1667 }
1669 } 1668 }
1670 1669
1671 qWarning ("ReadAllEntries(): "); 1670 qWarning ("ReadAllEntries(): ");
1672 1671
1673 QTextStream t(&f); 1672 QTextStream t(&f);
1674 while ( !t.eof() ) 1673 while ( !t.eof() )
1675 { 1674 {
1676 QString s = t.readLine(); 1675 QString s = t.readLine();
1677 s.replace (QRegExp("\";\""), "\"|\""); 1676 s.replace (QRegExp("\";\""), "\"|\"");
1678 // char buffer[1024]; 1677 // char buffer[1024];
1679 int len=s.length()+1; 1678 int len=s.length()+1;
1680#ifdef WIN32 1679#ifdef WIN32
1681 char buffer[512]; 1680 char buffer[512];
1682#else 1681#else
1683 char buffer[len]; 1682 char buffer[len];
1684#endif 1683#endif
1685 strcpy (buffer, s); 1684 strcpy (buffer, s);
1686 1685
1687 QString name; 1686 QString name;
1688 QString user; 1687 QString user;
1689 QString password; 1688 QString password;
1690 QString comment; 1689 QString comment;
1691 1690
1692 // separete the entries 1691 // separete the entries
1693 char *i = strtok (buffer, "|"); 1692 char *i = strtok (buffer, "|");
1694 QString category(&i[1]); 1693 QString category(&i[1]);
1695 category.truncate(category.length() -1); 1694 category.truncate(category.length() -1);
1696 1695
1697 int idx=0; 1696 int idx=0;
1698 while (i = strtok (NULL, "|")) 1697 while (i = strtok (NULL, "|"))
1699 { 1698 {
1700 switch (idx) 1699 switch (idx)
1701 { 1700 {
1702 case 0: 1701 case 0:
1703 name = &i[1]; 1702 name = &i[1];
1704 name.truncate(name.length() -1); 1703 name.truncate(name.length() -1);
1705 // name 1704 // name
1706 break; 1705 break;
1707 case 1: 1706 case 1:
1708 // user 1707 // user
1709 user = &i[1]; 1708 user = &i[1];
1710 user.truncate(user.length() -1); 1709 user.truncate(user.length() -1);
1711 break; 1710 break;
1712 case 2: 1711 case 2:
1713 // password 1712 // password
1714 password = &i[1]; 1713 password = &i[1];
1715 password.truncate(password.length() -1); 1714 password.truncate(password.length() -1);
1716 break; 1715 break;
1717 case 3: 1716 case 3:
1718 // comment 1717 // comment
1719 comment = &i[1]; 1718 comment = &i[1];
1720 comment.truncate(comment.length() -1); 1719 comment.truncate(comment.length() -1);
1721 break; 1720 break;
1722 } 1721 }
1723 idx++; 1722 idx++;
1724 } 1723 }
1725 1724
1726 Category *cat= categories.find (category); 1725 Category *cat= categories.find (category);
1727 if (cat) 1726 if (cat)
1728 { 1727 {
1729 // use the existend item 1728 // use the existend item
1730 QListViewItem *catItem = cat->getListItem(); 1729 QListViewItem *catItem = cat->getListItem();
1731 if (catItem) 1730 if (catItem)
1732 { 1731 {
1733 QListViewItem * item = new ShadedListItem( 0, catItem ); 1732 QListViewItem * item = new ShadedListItem( 0, catItem );
1734 item->setText( 0, tr( name ) ); 1733 item->setText( 0, tr( name ) );
1735 item->setText( 1, tr( user ) ); 1734 item->setText( 1, tr( user ) );
1736 item->setText( 2, tr( password ) ); 1735 item->setText( 2, tr( password ) );
1737 item->setText( 3, tr( comment ) ); 1736 item->setText( 3, tr( comment ) );
1738 1737
1739 catItem->setOpen( TRUE ); 1738 catItem->setOpen( TRUE );
1740 } 1739 }
1741 } 1740 }
1742 else 1741 else
1743 { 1742 {
1744 QListViewItem *catI = new ShadedListItem( 1, ListView ); 1743 QListViewItem *catI = new ShadedListItem( 1, ListView );
1745 // create and insert a new item 1744 // create and insert a new item
1746 QListViewItem * item = new ShadedListItem( 0, catI ); 1745 QListViewItem * item = new ShadedListItem( 0, catI );
1747 item->setText( 0, tr( name ) ); 1746 item->setText( 0, tr( name ) );
1748 item->setText( 1, tr( user ) ); 1747 item->setText( 1, tr( user ) );
1749 item->setText( 2, tr( password ) ); 1748 item->setText( 2, tr( password ) );
1750 item->setText( 3, tr( comment ) ); 1749 item->setText( 3, tr( comment ) );
1751 1750
1752 catI->setOpen( TRUE ); 1751 catI->setOpen( TRUE );
1753 1752
1754 Category *c1 = new Category(); 1753 Category *c1 = new Category();
1755 c1->setCategoryName(category); 1754 c1->setCategoryName(category);
1756 1755
1757 QString icon; 1756 QString icon;
1758 QString fullIconPath; 1757 QString fullIconPath;
1759 QPixmap *pix; 1758 QPixmap *pix;
1760// #ifndef WIN32 1759// #ifndef WIN32
1761 icon = conf->readEntry(APP_KEY+category); 1760 icon = conf->readEntry(APP_KEY+category);
1762// #endif 1761// #endif
1763 bool isIconAv = false; 1762 bool isIconAv = false;
1764 if (!icon.isEmpty() && !icon.isNull()) 1763 if (!icon.isEmpty() && !icon.isNull())
1765 { 1764 {
1766 // build the full path 1765 // build the full path
1767 fullIconPath = iconPath + icon; 1766 fullIconPath = iconPath + icon;
1768 pix = new QPixmap (fullIconPath); 1767 pix = new QPixmap (fullIconPath);
1769 if (pix) 1768 if (pix)
1770 { 1769 {
1771 QImage img = pix->convertToImage(); 1770 QImage img = pix->convertToImage();
1772 pix->convertFromImage(img.smoothScale(14,14)); 1771 pix->convertFromImage(img.smoothScale(14,14));
1773 c1->setIconName (icon); 1772 c1->setIconName (icon);
1774 c1->setIcon (*pix); 1773 c1->setIcon (*pix);
1775 isIconAv = true; 1774 isIconAv = true;
1776 } 1775 }
1777 } 1776 }
1778 if (!isIconAv) 1777 if (!isIconAv)
1779 { 1778 {
1780 c1->setIcon (*getPredefinedIcon(category)); 1779 c1->setIcon (*getPredefinedIcon(category));
1781 } 1780 }
1782 c1->setListItem (catI); 1781 c1->setListItem (catI);
1783 c1->initListItem(); 1782 c1->initListItem();
1784 categories.insert (c1->getCategoryName(), c1); 1783 categories.insert (c1->getCategoryName(), c1);
1785 } 1784 }
1786 1785
1787 } 1786 }
1788 f.close(); 1787 f.close();
1789 1788
1790} 1789}
1791#endif // UNUSED 1790#endif // UNUSED
1792 1791
1793void ZSafe::resume(int) 1792void ZSafe::resume(int)
1794{ 1793{
1795 qWarning ("Resume"); 1794 qWarning ("Resume");
1796 // hide the main window 1795 // hide the main window
1797 1796
1798 infoForm->hide(); 1797 infoForm->hide();
1799 // open zsafe again 1798 // open zsafe again
1800 m_password = ""; 1799 m_password = "";
1801 selectedItem = NULL; 1800 selectedItem = NULL;
1802 1801
1803 // clear the password list 1802 // clear the password list
1804 QListViewItem *i; 1803 QListViewItem *i;
1805 // step through all categories 1804 // step through all categories
1806 for (i = ListView->firstChild(); 1805 for (i = ListView->firstChild();
1807 i != NULL; 1806 i != NULL;
1808 i = i->nextSibling()) 1807 i = i->nextSibling())
1809 { 1808 {
1810 // step through all subitems 1809 // step through all subitems
1811 QListViewItem *si; 1810 QListViewItem *si;
1812 for (si = i->firstChild(); 1811 for (si = i->firstChild();
1813 si != NULL; ) 1812 si != NULL; )
1814 { 1813 {
1815 QListViewItem *_si = si; 1814 QListViewItem *_si = si;
1816 si = si->nextSibling(); 1815 si = si->nextSibling();
1817 i->takeItem(_si); // remove from view list 1816 i->takeItem(_si); // remove from view list
1818 if (_si) delete _si; 1817 if (_si) delete _si;
1819 } 1818 }
1820 } 1819 }
1821 1820
1822 // ask for password and read again 1821 // ask for password and read again
1823 openDocument(filename); 1822 openDocument(filename);
1824} 1823}
1825 1824
1826//--------------------------------------------- 1825//---------------------------------------------
1827 1826
1828 1827
1829bool ZSafe::openDocument(const char* _filename, const char* ) 1828bool ZSafe::openDocument(const char* _filename, const char* )
1830{ 1829{
1831 int retval; 1830 int retval;
1832 char* entry[FIELD_SIZE]; 1831 char* entry[FIELD_SIZE];
1833// #ifndef WIN32 1832// #ifndef WIN32
1834 int validationFlag = conf->readNumEntry(APP_KEY+"valzsafe", 1); 1833 int validationFlag = conf->readNumEntry(APP_KEY+"valzsafe", 1);
1835// #else 1834// #else
1836 // int validationFlag = 1; 1835 // int validationFlag = 1;
1837// #endif 1836// #endif
1838 1837
1839 int pwdOk = 0; 1838 int pwdOk = 0;
1840 int numberOfTries = 3; 1839 int numberOfTries = 3;
1841 for (int i=0; i < numberOfTries; i++) 1840 for (int i=0; i < numberOfTries; i++)
1842 { 1841 {
1843 QFile f(_filename); 1842 QFile f(_filename);
1844 if (f.exists()) 1843 if (f.exists())
1845 { 1844 {
1846 // ask with a dialog for the password 1845 // ask with a dialog for the password
1847 if (m_password.isEmpty()) 1846 if (m_password.isEmpty())
1848 getDocPassword(tr("Enter Password")); 1847 getDocPassword(tr("Enter Password"));
1849 if (m_password.isEmpty() && validationFlag == 0) 1848 if (m_password.isEmpty() && validationFlag == 0)
1850 { 1849 {
1851 qWarning ("Wrong password"); 1850 qWarning ("Wrong password");
1852 QMessageBox::critical( 0, tr("ZSafe"), 1851 QMessageBox::critical( 0, tr("ZSafe"),
1853 tr("Wrong password.\n\nZSafe will now exit.") ); 1852 tr("Wrong password.\n\nZSafe will now exit.") );
1854 exitZs (1); 1853 exitZs (1);
1855 } 1854 }
1856 1855
1857 retval = loadInit(_filename, m_password); 1856 retval = loadInit(_filename, m_password);
1858 if (retval != PWERR_GOOD) 1857 if (retval != PWERR_GOOD)
1859 { 1858 {
1860 qWarning ("Error loading Document"); 1859 qWarning ("Error loading Document");
1861 return false; 1860 return false;
1862 } 1861 }
1863 } 1862 }
1864 else 1863 else
1865 { 1864 {
1866#ifdef WIN32 1865#ifdef WIN32
1867 this->setCaption("Qt ZSafe"); 1866 this->setCaption("Qt ZSafe");
1868#else 1867#else
1869 this->setCaption("ZSafe"); 1868 this->setCaption("ZSafe");
1870#endif 1869#endif
1871 filename = ""; 1870 filename = "";
1872 return false; 1871 return false;
1873 } 1872 }
1874 1873
1875 1874
1876 // load the validation entry 1875 // load the validation entry
1877 if (validationFlag == 0) 1876 if (validationFlag == 0)
1878 { 1877 {
1879 pwdOk = 1; 1878 pwdOk = 1;
1880 break; 1879 break;
1881 } 1880 }
1882 1881
1883 retval = loadEntry(entry); 1882 retval = loadEntry(entry);
1884 if (retval == 1 && 1883 if (retval == 1 &&
1885 !strcmp (entry[0], "ZSAFECATEGORY") && 1884 !strcmp (entry[0], "ZSAFECATEGORY") &&
1886 !strcmp (entry[1], "name") && 1885 !strcmp (entry[1], "name") &&
1887 !strcmp (entry[2], "username") && 1886 !strcmp (entry[2], "username") &&
1888 !strcmp (entry[3], "password") && 1887 !strcmp (entry[3], "password") &&
1889 !strcmp (entry[4], "comment") ) 1888 !strcmp (entry[4], "comment") )
1890 { 1889 {
1891 for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]); 1890 for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]);
1892 pwdOk = 1; 1891 pwdOk = 1;
1893 break; 1892 break;
1894 } 1893 }
1895 else 1894 else
1896 // for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]); 1895 // for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]);
1897 fclose (fd); 1896 fclose (fd);
1898 m_password = ""; 1897 m_password = "";
1899 1898
1900 if (i < numberOfTries - 1) 1899 if (i < numberOfTries - 1)
1901 { 1900 {
1902 switch( QMessageBox::warning( this, tr("ZSafe"), 1901 switch( QMessageBox::warning( this, tr("ZSafe"),
1903 tr("Wrong password.\nEnter again?"), 1902 tr("Wrong password.\nEnter again?"),
1904 tr("&Yes"), tr("&No."), 1903 tr("&Yes"), tr("&No."),
1905 0 1904 0
1906 ) ) 1905 ) )
1907 { 1906 {
1908 case 1: // No 1907 case 1: // No
1909 exitZs (1); 1908 exitZs (1);
1910 break; 1909 break;
1911 case 0: // Yes 1910 case 0: // Yes
1912 continue; 1911 continue;
1913 } 1912 }
1914 } 1913 }
1915 } 1914 }
1916 if (pwdOk == 0) 1915 if (pwdOk == 0)
1917 { 1916 {
1918 // unset the document entry 1917 // unset the document entry
1919 conf->writeEntry(APP_KEY+"document", "INVALIDPWD"); 1918 conf->writeEntry(APP_KEY+"document", "INVALIDPWD");
1920 if (conf) 1919 if (conf)
1921 delete conf; 1920 delete conf;
1922 1921
1923 exitZs (1); 1922 exitZs (1);
1924 } 1923 }
1925 1924
1926 1925
1927 retval = loadEntry(entry); 1926 retval = loadEntry(entry);
1928 1927
1929 int numberOfEntries=0; 1928 int numberOfEntries=0;
1930 while (retval == 1) { 1929 while (retval == 1) {
1931 1930
1932 QString category( QString::fromUtf8(entry[0]) ); 1931 QString category( QString::fromUtf8(entry[0]) );
1933 QString name( QString::fromUtf8(entry[1]) ); 1932 QString name( QString::fromUtf8(entry[1]) );
1934 QString user( QString::fromUtf8(entry[2]) ); 1933 QString user( QString::fromUtf8(entry[2]) );
1935 QString password( QString::fromUtf8(entry[3]) ); 1934 QString password( QString::fromUtf8(entry[3]) );
1936 QString comment( QString::fromUtf8(entry[4]) ); 1935 QString comment( QString::fromUtf8(entry[4]) );
1937 QString field5( QString::fromUtf8(entry[5]) ); 1936 QString field5( QString::fromUtf8(entry[5]) );
1938 QString field6( QString::fromUtf8(entry[6]) ); 1937 QString field6( QString::fromUtf8(entry[6]) );
1939 // add the subitems to the categories 1938 // add the subitems to the categories
1940 1939
1941 Category *cat= categories.find (category); 1940 Category *cat= categories.find (category);
1942 if (cat) 1941 if (cat)
1943 { 1942 {
1944 // use the existend item 1943 // use the existend item
1945 QListViewItem *catItem = cat->getListItem(); 1944 QListViewItem *catItem = cat->getListItem();
1946 if (catItem) 1945 if (catItem)
1947 { 1946 {
1948 QListViewItem * item = new ShadedListItem( 0, catItem ); 1947 QListViewItem * item = new ShadedListItem( 0, catItem );
1949 item->setText( 0, tr( name ) ); 1948 item->setText( 0, tr( name ) );
1950 item->setText( 1, tr( user ) ); 1949 item->setText( 1, tr( user ) );
1951 item->setText( 2, tr( password ) ); 1950 item->setText( 2, tr( password ) );
1952 item->setText( 3, tr( comment ) ); 1951 item->setText( 3, tr( comment ) );
1953 item->setText( 4, tr( field5 ) ); 1952 item->setText( 4, tr( field5 ) );
1954 item->setText( 5, tr( field6 ) ); 1953 item->setText( 5, tr( field6 ) );
1955 1954
1956 if (expandTree) 1955 if (expandTree)
1957 catItem->setOpen( TRUE ); 1956 catItem->setOpen( TRUE );
1958 numberOfEntries++; 1957 numberOfEntries++;
1959 } 1958 }
1960 } 1959 }
1961 else 1960 else
1962 { 1961 {
1963 QListViewItem *catI = new ShadedListItem( 1, ListView ); 1962 QListViewItem *catI = new ShadedListItem( 1, ListView );
1964 // create and insert a new item 1963 // create and insert a new item
1965 QListViewItem * item = new ShadedListItem( 0, catI ); 1964 QListViewItem * item = new ShadedListItem( 0, catI );
1966 1965
1967 item->setText( 0, tr( name ) ); 1966 item->setText( 0, tr( name ) );
1968 item->setText( 1, tr( user ) ); 1967 item->setText( 1, tr( user ) );
1969 item->setText( 2, tr( password ) ); 1968 item->setText( 2, tr( password ) );
1970 item->setText( 3, tr( comment ) ); 1969 item->setText( 3, tr( comment ) );
1971 item->setText( 4, tr( field5 ) ); 1970 item->setText( 4, tr( field5 ) );
1972 item->setText( 5, tr( field6 ) ); 1971 item->setText( 5, tr( field6 ) );
1973 1972
1974 if (expandTree) 1973 if (expandTree)
1975 catI->setOpen( TRUE ); 1974 catI->setOpen( TRUE );
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);
2412 2409
2413 /* First, we make the IV */ 2410 /* First, we make the IV */
2414 for (count2 = 0; count2 < 4; count2++) { 2411 for (count2 = 0; count2 < 4; count2++) {
2415 iv[count2] = rand (); 2412 iv[count2] = rand ();
2416 putc ((unsigned char) (iv[count2] >> 8), fd); 2413 putc ((unsigned char) (iv[count2] >> 8), fd);
2417 putc ((unsigned char) (iv[count2] & 0xff), fd); 2414 putc ((unsigned char) (iv[count2] & 0xff), fd);
2418 } 2415 }
2419 2416
2420 bufferIndex = 0; 2417 bufferIndex = 0;
2421 return PWERR_GOOD; 2418 return PWERR_GOOD;
2422} 2419}
2423 2420
2424 2421
2425int ZSafe::saveEntry(char *entry[FIELD_SIZE]) 2422int ZSafe::saveEntry(char *entry[FIELD_SIZE])
2426{ 2423{
2427 char *text1; 2424 char *text1;
2428 int count2, count3; 2425 int count2, count3;
2429 unsigned short ciphertext[4]; 2426 unsigned short ciphertext[4];
2430 Krc2* krc2 = new Krc2(); 2427 Krc2* krc2 = new Krc2();
2431 2428
2432 buffer = (char*)memset(buffer, '\0', save_buffer_length); 2429 buffer = (char*)memset(buffer, '\0', save_buffer_length);
2433 2430
2434 for (count2 = 0; count2 < FIELD_SIZE; count2++) { 2431 for (count2 = 0; count2 < FIELD_SIZE; count2++) {
2435 text1 = entry[count2]; 2432 text1 = entry[count2];
2436 if (strlen (text1) == 0) { 2433 if (strlen (text1) == 0) {
2437 strncat(buffer, " ", strlen(" ")); 2434 strncat(buffer, " ", strlen(" "));
2438 } else { 2435 } else {
2439 strncat(buffer, text1, strlen(text1)); 2436 strncat(buffer, text1, strlen(text1));
2440 } 2437 }
2441 /* Use 255 as the marker. \n is too tough to test for */ 2438 /* Use 255 as the marker. \n is too tough to test for */
2442 buffer[strlen (buffer)] = 255; 2439 buffer[strlen (buffer)] = 255;
2443 } /*for (count2 = 0; count2 < 5; count2++)*/ 2440 } /*for (count2 = 0; count2 < 5; count2++)*/
2444 count2 = 0; 2441 count2 = 0;
2445 /* I'm using CBC mode and encrypting the data straight from top down. 2442 /* I'm using CBC mode and encrypting the data straight from top down.
2446 * At the bottom, encrypted, I will append an MD5 hash of the file, eventually. 2443 * At the bottom, encrypted, I will append an MD5 hash of the file, eventually.
2447 * PKCS 5 padding (explained at the code section 2444 * PKCS 5 padding (explained at the code section
2448 */ 2445 */
2449 while (count2 < (int)strlen (buffer)) { 2446 while (count2 < (int)strlen (buffer)) {
2450#ifndef WORDS_BIGENDIAN 2447#ifndef WORDS_BIGENDIAN
2451 plaintext[bufferIndex] = buffer[count2 + 1] << 8; 2448 plaintext[bufferIndex] = buffer[count2 + 1] << 8;
2452 plaintext[bufferIndex] += buffer[count2] & 0xff; 2449 plaintext[bufferIndex] += buffer[count2] & 0xff;
2453#endif 2450#endif
2454#ifdef WORDS_BIGENDIAN 2451#ifdef WORDS_BIGENDIAN
2455 plaintext[bufferIndex] = buffer[count2] << 8; 2452 plaintext[bufferIndex] = buffer[count2] << 8;
2456 plaintext[bufferIndex] += buffer[count2 + 1] & 0xff; 2453 plaintext[bufferIndex] += buffer[count2 + 1] & 0xff;
2457#endif 2454#endif
2458 bufferIndex++; 2455 bufferIndex++;
2459 if (bufferIndex == 4) { 2456 if (bufferIndex == 4) {
2460 krc2->rc2_encrypt (plaintext); 2457 krc2->rc2_encrypt (plaintext);
2461 2458
2462 for (count3 = 0; count3 < 4; count3++) { 2459 for (count3 = 0; count3 < 4; count3++) {
2463 ciphertext[count3] = iv[count3] ^ plaintext[count3]; 2460 ciphertext[count3] = iv[count3] ^ plaintext[count3];
2464 2461
2465 /* Now store the ciphertext as the iv */ 2462 /* Now store the ciphertext as the iv */
2466 iv[count3] = plaintext[count3]; 2463 iv[count3] = plaintext[count3];
2467 2464
2468 /* reset the buffer index */ 2465 /* reset the buffer index */
2469 bufferIndex = 0; 2466 bufferIndex = 0;
2470 if (putc ((unsigned char) (ciphertext[count3] >> 8), fd) == EOF) return PWERR_DATA; 2467 if (putc ((unsigned char) (ciphertext[count3] >> 8), fd) == EOF) return PWERR_DATA;
2471 if (putc ((unsigned char) (ciphertext[count3] & 0xff), fd) == EOF) return PWERR_DATA; 2468 if (putc ((unsigned char) (ciphertext[count3] & 0xff), fd) == EOF) return PWERR_DATA;
2472 } /*for (count3 = 0; count3 < 5; count3++)*/ 2469 } /*for (count3 = 0; count3 < 5; count3++)*/
2473 } /*if (bufferIndex == 5)*/ 2470 } /*if (bufferIndex == 5)*/
2474 /* increment a short, not a byte */ 2471 /* increment a short, not a byte */
2475 count2 += 2; 2472 count2 += 2;
2476 } /*while (count2 < strlen (buffer))*/ 2473 } /*while (count2 < strlen (buffer))*/
2477 int ret = PWERR_GOOD; 2474 int ret = PWERR_GOOD;
2478 return ret; 2475 return ret;
2479} 2476}
2480 2477
2481int ZSafe::saveFinalize(void) 2478int ZSafe::saveFinalize(void)
2482{ 2479{
2483 int count1, retval = PWERR_GOOD; 2480 int count1, retval = PWERR_GOOD;
2484 unsigned short ciphertext[4]; 2481 unsigned short ciphertext[4];
2485 Krc2* krc2 = new Krc2(); 2482 Krc2* krc2 = new Krc2();
2486 2483
2487 /* Tack on the PKCS 5 padding 2484 /* Tack on the PKCS 5 padding
2488 * How it works is we fill up the last n bytes with the value n 2485 * How it works is we fill up the last n bytes with the value n
2489 * 2486 *
2490 * So, if we have, say, 13 bytes, 8 of which are used, we have 5 left 2487 * So, if we have, say, 13 bytes, 8 of which are used, we have 5 left
2491 * over, leaving us 3 short, so we fill it in with 3's. 2488 * over, leaving us 3 short, so we fill it in with 3's.
2492 * 2489 *
2493 * If we come out even, we fill it with 8 8s 2490 * If we come out even, we fill it with 8 8s
2494 * 2491 *
2495 * um, except that in this instance we are using 4 shorts instead of 8 bytes. 2492 * um, except that in this instance we are using 4 shorts instead of 8 bytes.
2496 * so, half everything 2493 * so, half everything
2497 */ 2494 */
2498 for (count1 = bufferIndex; count1 < 4; count1++) { 2495 for (count1 = bufferIndex; count1 < 4; count1++) {
2499 plaintext[count1] = (4 - bufferIndex); 2496 plaintext[count1] = (4 - bufferIndex);
2500 } 2497 }
2501 krc2->rc2_encrypt (plaintext); 2498 krc2->rc2_encrypt (plaintext);
2502 for (count1 = 0; count1 < 4; count1++) { 2499 for (count1 = 0; count1 < 4; count1++) {
2503 ciphertext[count1] = iv[count1] ^ plaintext[count1]; 2500 ciphertext[count1] = iv[count1] ^ plaintext[count1];
2504 if (putc ((unsigned char) (ciphertext[count1] >> 8), fd) == EOF) retval = PWERR_DATA; 2501 if (putc ((unsigned char) (ciphertext[count1] >> 8), fd) == EOF) retval = PWERR_DATA;
2505 if (putc ((unsigned char) (ciphertext[count1] & 0xff), fd) == EOF) retval = PWERR_DATA; 2502 if (putc ((unsigned char) (ciphertext[count1] & 0xff), fd) == EOF) retval = PWERR_DATA;
2506 } 2503 }
2507 2504
2508 fclose (fd); 2505 fclose (fd);
2509 free(buffer); 2506 free(buffer);
2510 return retval; 2507 return retval;
2511} 2508}
2512 2509
2513void ZSafe::quitMe () 2510void ZSafe::quitMe ()
2514{ 2511{
2515 qWarning ("QUIT..."); 2512 qWarning ("QUIT...");
2516 2513
2517 if (modified) 2514 if (modified)
2518 { 2515 {
2519 switch( QMessageBox::information( this, tr("ZSafe"), 2516 switch( QMessageBox::information( this, tr("ZSafe"),
2520 tr("Do you want to save\nbefore exiting?"), 2517 tr("Do you want to save\nbefore exiting?"),
2521 tr("&Save"), 2518 tr("&Save"),
2522 tr("S&ave with\nnew\npassword"), 2519 tr("S&ave with\nnew\npassword"),
2523 tr("&Don't Save"), 2520 tr("&Don't Save"),
2524 0 // Enter == button 0 2521 0 // Enter == button 0
2525 ) ) 2522 ) )
2526 { // Escape == button 2 2523 { // Escape == button 2
2527 case 0: // Save clicked, Alt-S or Enter pressed. 2524 case 0: // Save clicked, Alt-S or Enter pressed.
2528 // save 2525 // save
2529 modified = false; 2526 modified = false;
2530 saveDocument(filename, FALSE); 2527 saveDocument(filename, FALSE);
2531 exitZs (1); 2528 exitZs (1);
2532 break; 2529 break;
2533 case 1: // 2530 case 1: //
2534 // Save with new password 2531 // Save with new password
2535 modified = false; 2532 modified = false;
2536 saveDocument(filename, TRUE); 2533 saveDocument(filename, TRUE);
2537 exitZs (1); 2534 exitZs (1);
2538 break; 2535 break;
2539 case 2: // Don't Save clicked or Alt-D pressed 2536 case 2: // Don't Save clicked or Alt-D pressed
2540 // don't save but exitZs 2537 // don't save but exitZs
2541 exitZs (1); 2538 exitZs (1);
2542 break; 2539 break;
2543 } 2540 }
2544 } 2541 }
2545 exitZs (1); 2542 exitZs (1);
2546 2543
2547} 2544}
2548 2545
2549void ZSafe::categoryFieldActivated( const QString& category) 2546void ZSafe::categoryFieldActivated( const QString& category)
2550{ 2547{
2551 if (categoryDialog) 2548 if (categoryDialog)
2552 setCategoryDialogFields(categoryDialog, category); 2549 setCategoryDialogFields(categoryDialog, category);
2553} 2550}
2554 2551
2555void ZSafe::addCategory() 2552void ZSafe::addCategory()
2556{ 2553{
2557 if (filename.isEmpty()) 2554 if (filename.isEmpty())
2558 { 2555 {
2559 QMessageBox::critical( 0, tr("ZSafe"), 2556 QMessageBox::critical( 0, tr("ZSafe"),
2560 tr("No document defined.\nYou have to create a new document")); 2557 tr("No document defined.\nYou have to create a new document"));
2561 return; 2558 return;
2562 } 2559 }
2563 else 2560 else
2564 { 2561 {
2565 // open the 'Category' dialog 2562 // open the 'Category' dialog
2566 bool initIcons = false; 2563 bool initIcons = false;
2567 // open the 'Category' dialog 2564 // open the 'Category' dialog
2568 CategoryDialog *dialog; 2565 CategoryDialog *dialog;
2569 if (categoryDialog) 2566 if (categoryDialog)
2570 { 2567 {
2571 dialog = categoryDialog; 2568 dialog = categoryDialog;
2572 } 2569 }
2573 else 2570 else
2574 { 2571 {
2575 categoryDialog = new CategoryDialog(this, tr("Category"), TRUE); 2572 categoryDialog = new CategoryDialog(this, tr("Category"), TRUE);
2576#ifdef WIN32 2573#ifdef WIN32
2577 categoryDialog->setCaption ("Qt " + tr("Category")); 2574 categoryDialog->setCaption ("Qt " + tr("Category"));
2578#endif 2575#endif
2579 dialog = categoryDialog; 2576 dialog = categoryDialog;
2580 connect( dialog->CategoryField, 2577 connect( dialog->CategoryField,
2581 SIGNAL( activated(const QString&)), 2578 SIGNAL( activated(const QString&)),
2582 this, SLOT( categoryFieldActivated(const QString&) ) ); 2579 this, SLOT( categoryFieldActivated(const QString&) ) );
2583 initIcons = true; 2580 initIcons = true;
2584 } 2581 }
2585 2582
2586#ifdef DESKTOP 2583#ifdef DESKTOP
2587#ifndef WIN32 2584#ifndef WIN32
2588 QStringList list = conf->entryList( APP_KEY+"/fieldDefs" ); 2585 QStringList list = conf->entryList( APP_KEY+"/fieldDefs" );
2589#else 2586#else
2590 // read all categories from the config file and store 2587 // read all categories from the config file and store
2591 // into a list 2588 // into a list
2592 QFile f (cfgFile); 2589 QFile f (cfgFile);
2593 QStringList list; 2590 QStringList list;
2594 if ( f.open(IO_ReadOnly) ) { // file opened successfully 2591 if ( f.open(IO_ReadOnly) ) { // file opened successfully
2595 QTextStream t( &f ); // use a text stream 2592 QTextStream t( &f ); // use a text stream
2596 QString s; 2593 QString s;
2597 int n = 1; 2594 int n = 1;
2598 while ( !t.eof() ) { // until end of file... 2595 while ( !t.eof() ) { // until end of file...
2599 s = t.readLine(); // line of text excluding '\n' 2596 s = t.readLine(); // line of text excluding '\n'
2600 list.append(s); 2597 list.append(s);
2601 } 2598 }
2602 f.close(); 2599 f.close();
2603 } 2600 }
2604#endif 2601#endif
2605#else 2602#else
2606 // read all categories from the config file and store 2603 // read all categories from the config file and store
2607 // into a list 2604 // into a list
2608 QFile f (cfgFile); 2605 QFile f (cfgFile);
2609 QStringList list; 2606 QStringList list;
2610 if ( f.open(IO_ReadOnly) ) { // file opened successfully 2607 if ( f.open(IO_ReadOnly) ) { // file opened successfully
2611 QTextStream t( &f ); // use a text stream 2608 QTextStream t( &f ); // use a text stream
2612 QString s; 2609 QString s;
2613 while ( !t.eof() ) { // until end of file... 2610 while ( !t.eof() ) { // until end of file...
2614 s = t.readLine(); // line of text excluding '\n' 2611 s = t.readLine(); // line of text excluding '\n'
2615 list.append(s); 2612 list.append(s);
2616 } 2613 }
2617 f.close(); 2614 f.close();
2618 } 2615 }
2619#endif 2616#endif
2620 QStringList::Iterator it = list.begin(); 2617 QStringList::Iterator it = list.begin();
2621 QString categ; 2618 QString categ;
2622 QString firstCategory; 2619 QString firstCategory;
2623 dialog->CategoryField->clear(); // remove all items 2620 dialog->CategoryField->clear(); // remove all items
2624 while( it != list.end() ) 2621 while( it != list.end() )
2625 { 2622 {
2626 QString *cat = new QString (*it); 2623 QString *cat = new QString (*it);
2627 if (cat->contains("-field1", FALSE)) 2624 if (cat->contains("-field1", FALSE))
2628 { 2625 {
2629#ifdef DESKTOP 2626#ifdef DESKTOP
2630#ifndef WIN32 2627#ifndef WIN32
2631 categ = cat->section ("-field1", 0, 0); 2628 categ = cat->section ("-field1", 0, 0);
2632#else 2629#else
2633 int pos = cat->find ("-field1"); 2630 int pos = cat->find ("-field1");
2634 categ = cat->left (pos); 2631 categ = cat->left (pos);
2635#endif 2632#endif
2636#else 2633#else
2637 int pos = cat->find ("-field1"); 2634 int pos = cat->find ("-field1");
2638 cat->truncate(pos); 2635 cat->truncate(pos);
2639 categ = *cat; 2636 categ = *cat;
2640#endif 2637#endif
2641 if (!categ.isEmpty()) 2638 if (!categ.isEmpty())
2642 { 2639 {
2643 dialog->CategoryField->insertItem (categ, -1); 2640 dialog->CategoryField->insertItem (categ, -1);
2644 if (firstCategory.isEmpty()) 2641 if (firstCategory.isEmpty())
2645 firstCategory = categ; 2642 firstCategory = categ;
2646 } 2643 }
2647 } 2644 }
2648 ++it; 2645 ++it;
2649 } 2646 }
2650 2647
2651 2648
2652 if (firstCategory.isEmpty()) 2649 if (firstCategory.isEmpty())
2653 setCategoryDialogFields(dialog); 2650 setCategoryDialogFields(dialog);
2654 else 2651 else
2655 setCategoryDialogFields(dialog, firstCategory); 2652 setCategoryDialogFields(dialog, firstCategory);
2656 2653
2657 // CategoryDialog *dialog = new CategoryDialog(this, "Category", TRUE); 2654 // CategoryDialog *dialog = new CategoryDialog(this, "Category", TRUE);
2658 2655
2659 if (initIcons) 2656 if (initIcons)
2660 { 2657 {
2661 Wait waitDialog(this, tr("Wait dialog")); 2658 Wait waitDialog(this, tr("Wait dialog"));
2662 waitDialog.waitLabel->setText(tr("Gathering icons...")); 2659 waitDialog.waitLabel->setText(tr("Gathering icons..."));
2663 waitDialog.show(); 2660 waitDialog.show();
2664 qApp->processEvents(); 2661 qApp->processEvents();
2665 2662
2666#ifdef DESKTOP 2663#ifdef DESKTOP
2667 QDir d(iconPath); 2664 QDir d(iconPath);
2668#else 2665#else
2669 QDir d(QPEApplication::qpeDir() + "/pics/"); 2666 QDir d(QPEApplication::qpeDir() + "/pics/");
2670#endif 2667#endif
2671 d.setFilter( QDir::Files); 2668 d.setFilter( QDir::Files);
2672 2669
2673 const QFileInfoList *list = d.entryInfoList(); 2670 const QFileInfoList *list = d.entryInfoList();
2674 QFileInfoListIterator it( *list ); // create list iterator 2671 QFileInfoListIterator it( *list ); // create list iterator
2675 QFileInfo *fi; // pointer for traversing 2672 QFileInfo *fi; // pointer for traversing
2676 2673
2677 dialog->IconField->insertItem("predefined"); 2674 dialog->IconField->insertItem("predefined");
2678 while ( (fi=it.current()) ) { // for each file... 2675 while ( (fi=it.current()) ) { // for each file...
2679 QString fileName = fi->fileName(); 2676 QString fileName = fi->fileName();
2680 if(fileName.right(4) == ".png"){ 2677 if(fileName.right(4) == ".png"){
2681 fileName = fileName.mid(0,fileName.length()-4); 2678 fileName = fileName.mid(0,fileName.length()-4);
2682#ifdef DESKTOP 2679#ifdef DESKTOP
2683 QPixmap imageOfFile; 2680 QPixmap imageOfFile;
2684 imageOfFile.load(iconPath + fi->fileName()); 2681 imageOfFile.load(iconPath + fi->fileName());
2685#else 2682#else
2686 QPixmap imageOfFile(Resource::loadPixmap(fileName)); 2683 QPixmap imageOfFile(Resource::loadPixmap(fileName));
2687#endif 2684#endif
2688 QImage foo = imageOfFile.convertToImage(); 2685 QImage foo = imageOfFile.convertToImage();
2689 foo = foo.smoothScale(16,16); 2686 foo = foo.smoothScale(16,16);
2690 imageOfFile.convertFromImage(foo); 2687 imageOfFile.convertFromImage(foo);
2691 dialog->IconField->insertItem(imageOfFile,fileName); 2688 dialog->IconField->insertItem(imageOfFile,fileName);
2692 } 2689 }
2693 ++it; 2690 ++it;
2694 } 2691 }
2695 waitDialog.hide(); 2692 waitDialog.hide();
2696 } 2693 }
2697 2694
2698#ifndef WIN32 2695#ifndef WIN32
2699 dialog->show(); 2696 dialog->show();
2700#endif 2697#endif
2701#ifndef DESKTOP 2698#ifndef DESKTOP
2702 // dialog->move (20, 100); 2699 // dialog->move (20, 100);
2703#endif 2700#endif
2704 DialogCode result = (DialogCode) dialog->exec(); 2701 DialogCode result = (DialogCode) dialog->exec();
2705#ifdef DESKTOP 2702#ifdef DESKTOP
2706 result = Accepted; 2703 result = Accepted;
2707#endif 2704#endif
2708 2705
2709 QString category; 2706 QString category;
2710 QString icon; 2707 QString icon;
2711 QString fullIconPath; 2708 QString fullIconPath;
2712 QPixmap *pix; 2709 QPixmap *pix;
2713 if (result == Accepted) 2710 if (result == Accepted)
2714 { 2711 {
2715 modified = true; 2712 modified = true;
2716 category = dialog->CategoryField->currentText(); 2713 category = dialog->CategoryField->currentText();
2717 icon = dialog->IconField->currentText()+".png"; 2714 icon = dialog->IconField->currentText()+".png";
2718 2715
2719 qWarning (category); 2716 qWarning (category);
2720 2717
2721 QListViewItem *li = new ShadedListItem( 1, ListView ); 2718 QListViewItem *li = new ShadedListItem( 1, ListView );
2722 Category *c1 = new Category(); 2719 Category *c1 = new Category();
2723 c1->setCategoryName(category); 2720 c1->setCategoryName(category);
2724 2721
2725 // if (!icon.isEmpty() && !icon.isNull()) 2722 // if (!icon.isEmpty() && !icon.isNull())
2726 if (icon != "predefined.png") 2723 if (icon != "predefined.png")
2727 { 2724 {
2728 // build the full path 2725 // build the full path
2729 fullIconPath = iconPath + icon; 2726 fullIconPath = iconPath + icon;
2730 pix = new QPixmap (fullIconPath); 2727 pix = new QPixmap (fullIconPath);
2731 // pix->resize(14, 14); 2728 // pix->resize(14, 14);
2732 if (pix) 2729 if (pix)
2733 { 2730 {
2734 // save the full pixmap name into the config file 2731 // save the full pixmap name into the config file
2735// #ifndef WIN32 2732// #ifndef WIN32
2736 conf->writeEntry(APP_KEY+category, icon); 2733 conf->writeEntry(APP_KEY+category, icon);
2737// #endif 2734// #endif
2738 saveConf(); 2735 saveConf();
2739 QImage img = pix->convertToImage(); 2736 QImage img = pix->convertToImage();
2740 pix->convertFromImage(img.smoothScale(14,14)); 2737 pix->convertFromImage(img.smoothScale(14,14));
2741 c1->setIcon (*pix); 2738 c1->setIcon (*pix);
2742 c1->setIconName(icon); 2739 c1->setIconName(icon);
2743 } 2740 }
2744 else 2741 else
2745 { 2742 {
2746 QPixmap folder( ( const char** ) general_data ); 2743 QPixmap folder( ( const char** ) general_data );
2747 c1->setIcon (folder); 2744 c1->setIcon (folder);
2748 } 2745 }
2749 } 2746 }
2750 else 2747 else
2751 { 2748 {
2752 c1->setIcon (*getPredefinedIcon(category)); 2749 c1->setIcon (*getPredefinedIcon(category));
2753 } 2750 }
2754 2751
2755 c1->setListItem (li); 2752 c1->setListItem (li);
2756 c1->initListItem(); 2753 c1->initListItem();
2757 categories.insert (c1->getCategoryName(), c1); 2754 categories.insert (c1->getCategoryName(), c1);
2758 2755
2759 saveCategoryDialogFields(dialog); 2756 saveCategoryDialogFields(dialog);
2760 } 2757 }
2761 else 2758 else
2762 { 2759 {
2763 // delete dialog; 2760 // delete dialog;
2764 dialog->hide(); 2761 dialog->hide();
2765 return; 2762 return;
2766 } 2763 }
2767 2764
2768 } 2765 }
2769 2766
2770} 2767}
2771 2768
2772void ZSafe::delCategory() 2769void ZSafe::delCategory()
2773{ 2770{
2774 if (!selectedItem) 2771 if (!selectedItem)
2775 return; 2772 return;
2776 if (isCategory(selectedItem)) 2773 if (isCategory(selectedItem))
2777 { 2774 {
2778 switch( QMessageBox::information( this, tr("ZSafe"), 2775 switch( QMessageBox::information( this, tr("ZSafe"),
2779 tr("Do you want to delete?"), 2776 tr("Do you want to delete?"),
2780 tr("&Delete"), tr("D&on't Delete"), 2777 tr("&Delete"), tr("D&on't Delete"),
2781 0 // Enter == button 0 2778 0 // Enter == button 0
2782 ) ) { // Escape == button 2 2779 ) ) { // Escape == button 2
2783 case 0: // Delete clicked, Alt-S or Enter pressed. 2780 case 0: // Delete clicked, Alt-S or Enter pressed.
2784 // Delete from the category list 2781 // Delete from the category list
2785 modified = true; 2782 modified = true;
2786 categories.remove (selectedItem->text(0)); 2783 categories.remove (selectedItem->text(0));
2787// #ifndef WIN32 2784// #ifndef WIN32
2788 conf->removeEntry (selectedItem->text(0)); 2785 conf->removeEntry (selectedItem->text(0));
2789// #endif 2786// #endif
2790 saveConf(); 2787 saveConf();
2791 2788
2792 // Delete the selected item and all subitems 2789 // Delete the selected item and all subitems
2793 // step through all subitems 2790 // step through all subitems
2794 QListViewItem *si; 2791 QListViewItem *si;
2795 for (si = selectedItem->firstChild(); 2792 for (si = selectedItem->firstChild();
2796 si != NULL; ) 2793 si != NULL; )
2797 { 2794 {
2798 QListViewItem *_si = si; 2795 QListViewItem *_si = si;
2799 si = si->nextSibling(); 2796 si = si->nextSibling();
2800 selectedItem->takeItem(_si); // remove from view list 2797 selectedItem->takeItem(_si); // remove from view list
2801 if (_si) delete _si; 2798 if (_si) delete _si;
2802 } 2799 }
2803 ListView->takeItem(selectedItem); 2800 ListView->takeItem(selectedItem);
2804 delete selectedItem; 2801 delete selectedItem;
2805 2802
2806 selectedItem = NULL; 2803 selectedItem = NULL;
2807 break; 2804 break;
2808 case 1: // Don't delete 2805 case 1: // Don't delete
2809 break; 2806 break;
2810 } 2807 }
2811 2808
2812 } 2809 }
2813} 2810}
2814 2811
2815void ZSafe::setCategoryDialogFields(CategoryDialog *dialog) 2812void ZSafe::setCategoryDialogFields(CategoryDialog *dialog)
2816{ 2813{
2817 if (!dialog) 2814 if (!dialog)
2818 return; 2815 return;
2819 2816
2820 QString icon; 2817 QString icon;
2821 if (selectedItem) 2818 if (selectedItem)
2822 { 2819 {
2823 dialog->Field1->setText(getFieldLabel (selectedItem, "1", tr("Name"))); 2820 dialog->Field1->setText(getFieldLabel (selectedItem, "1", tr("Name")));
2824 dialog->Field2->setText(getFieldLabel (selectedItem, "2", tr("Username"))); 2821 dialog->Field2->setText(getFieldLabel (selectedItem, "2", tr("Username")));
2825 dialog->Field3->setText(getFieldLabel (selectedItem, "3", tr("Password"))); 2822 dialog->Field3->setText(getFieldLabel (selectedItem, "3", tr("Password")));
2826 dialog->Field4->setText(getFieldLabel (selectedItem, "4", tr("Comment"))); 2823 dialog->Field4->setText(getFieldLabel (selectedItem, "4", tr("Comment")));
2827 dialog->Field5->setText(getFieldLabel (selectedItem, "5", tr("Field 4"))); 2824 dialog->Field5->setText(getFieldLabel (selectedItem, "5", tr("Field 4")));
2828 dialog->Field6->setText(getFieldLabel (selectedItem, "6", tr("Field 5"))); 2825 dialog->Field6->setText(getFieldLabel (selectedItem, "6", tr("Field 5")));
2829 2826
2830 Category *cat= categories.find (selectedItem->text(0)); 2827 Category *cat= categories.find (selectedItem->text(0));
2831 if (cat) 2828 if (cat)
2832 { 2829 {
2833 icon = cat->getIconName(); 2830 icon = cat->getIconName();
2834 } 2831 }
2835 else 2832 else
2836 icon = conf->readEntry(APP_KEY+selectedItem->text(0)); 2833 icon = conf->readEntry(APP_KEY+selectedItem->text(0));
2837 } 2834 }
2838 else 2835 else
2839 { 2836 {
2840 dialog->Field1->setText(tr("Name")); 2837 dialog->Field1->setText(tr("Name"));
2841 dialog->Field2->setText(tr("Username")); 2838 dialog->Field2->setText(tr("Username"));
2842 dialog->Field3->setText(tr("Password")); 2839 dialog->Field3->setText(tr("Password"));
2843 dialog->Field4->setText(tr("Comment")); 2840 dialog->Field4->setText(tr("Comment"));
2844 dialog->Field5->setText(tr("Field 4")); 2841 dialog->Field5->setText(tr("Field 4"));
2845 dialog->Field6->setText(tr("Field 5")); 2842 dialog->Field6->setText(tr("Field 5"));
2846 } 2843 }
2847 2844
2848#ifdef DESKTOP 2845#ifdef DESKTOP
2849 QDir d(iconPath); 2846 QDir d(iconPath);
2850#else 2847#else
2851 QDir d(QPEApplication::qpeDir() + "/pics/"); 2848 QDir d(QPEApplication::qpeDir() + "/pics/");
2852#endif 2849#endif
2853 d.setFilter( QDir::Files); 2850 d.setFilter( QDir::Files);
2854 2851
2855 const QFileInfoList *list = d.entryInfoList(); 2852 const QFileInfoList *list = d.entryInfoList();
2856 int i=0; 2853 int i=0;
2857 QFileInfoListIterator it( *list ); // create list iterator 2854 QFileInfoListIterator it( *list ); // create list iterator
2858 QFileInfo *fi; // pointer for traversing 2855 QFileInfo *fi; // pointer for traversing
2859 if (icon.isEmpty() || icon.isNull()) 2856 if (icon.isEmpty() || icon.isNull())
2860 { 2857 {
2861 dialog->IconField->setCurrentItem(0); 2858 dialog->IconField->setCurrentItem(0);
2862 } 2859 }
2863 else 2860 else
2864 { 2861 {
2865 while ( (fi=it.current()) ) 2862 while ( (fi=it.current()) )
2866 { // for each file... 2863 { // for each file...
2867 QString fileName = fi->fileName(); 2864 QString fileName = fi->fileName();
2868 if(fileName.right(4) == ".png") 2865 if(fileName.right(4) == ".png")
2869 { 2866 {
2870 fileName = fileName.mid(0,fileName.length()-4); 2867 fileName = fileName.mid(0,fileName.length()-4);
2871 2868
2872 if(fileName+".png"==icon) 2869 if(fileName+".png"==icon)
2873 { 2870 {
2874 dialog->IconField->setCurrentItem(i+1); 2871 dialog->IconField->setCurrentItem(i+1);
2875 break; 2872 break;
2876 } 2873 }
2877 ++i; 2874 ++i;
2878 } 2875 }
2879 ++it; 2876 ++it;
2880 } 2877 }
2881 } 2878 }
2882} 2879}
2883 2880
2884void ZSafe::setCategoryDialogFields(CategoryDialog *dialog, QString category) 2881void ZSafe::setCategoryDialogFields(CategoryDialog *dialog, QString category)
2885{ 2882{
2886 if (!dialog) 2883 if (!dialog)
2887 return; 2884 return;
2888 2885
2889 dialog->Field1->setText(getFieldLabel (category, "1", tr("Name"))); 2886 dialog->Field1->setText(getFieldLabel (category, "1", tr("Name")));
2890 dialog->Field2->setText(getFieldLabel (category, "2", tr("Username"))); 2887 dialog->Field2->setText(getFieldLabel (category, "2", tr("Username")));
2891 dialog->Field3->setText(getFieldLabel (category, "3", tr("Password"))); 2888 dialog->Field3->setText(getFieldLabel (category, "3", tr("Password")));
2892 dialog->Field4->setText(getFieldLabel (category, "4", tr("Comment"))); 2889 dialog->Field4->setText(getFieldLabel (category, "4", tr("Comment")));
2893 dialog->Field5->setText(getFieldLabel (category, "5", tr("Field 4"))); 2890 dialog->Field5->setText(getFieldLabel (category, "5", tr("Field 4")));
2894 dialog->Field6->setText(getFieldLabel (category, "6", tr("Field 5"))); 2891 dialog->Field6->setText(getFieldLabel (category, "6", tr("Field 5")));
2895 2892
2896 QString icon; 2893 QString icon;
2897 Category *cat= categories.find (category); 2894 Category *cat= categories.find (category);
2898 if (cat) 2895 if (cat)
2899 { 2896 {
2900 icon = cat->getIconName(); 2897 icon = cat->getIconName();
2901 } 2898 }
2902 else 2899 else
2903 icon = conf->readEntry(APP_KEY+category); 2900 icon = conf->readEntry(APP_KEY+category);
2904 2901
2905#ifdef DESKTOP 2902#ifdef DESKTOP
2906 QDir d(iconPath); 2903 QDir d(iconPath);
2907#else 2904#else
2908 QDir d(QPEApplication::qpeDir() + "/pics/"); 2905 QDir d(QPEApplication::qpeDir() + "/pics/");
2909#endif 2906#endif
2910 d.setFilter( QDir::Files); 2907 d.setFilter( QDir::Files);
2911 2908
2912 const QFileInfoList *list = d.entryInfoList(); 2909 const QFileInfoList *list = d.entryInfoList();
2913 int i=0; 2910 int i=0;
2914 QFileInfoListIterator it( *list ); // create list iterator 2911 QFileInfoListIterator it( *list ); // create list iterator
2915 QFileInfo *fi; // pointer for traversing 2912 QFileInfo *fi; // pointer for traversing
2916 if (icon.isEmpty() || icon.isNull()) 2913 if (icon.isEmpty() || icon.isNull())
2917 { 2914 {
2918 dialog->IconField->setCurrentItem(0); 2915 dialog->IconField->setCurrentItem(0);
2919 } 2916 }
2920 else 2917 else
2921 { 2918 {
2922 while ( (fi=it.current()) ) 2919 while ( (fi=it.current()) )
2923 { // for each file... 2920 { // for each file...
2924 QString fileName = fi->fileName(); 2921 QString fileName = fi->fileName();
2925 if(fileName.right(4) == ".png") 2922 if(fileName.right(4) == ".png")
2926 { 2923 {
2927 fileName = fileName.mid(0,fileName.length()-4); 2924 fileName = fileName.mid(0,fileName.length()-4);
2928 2925
2929 if(fileName+".png"==icon) 2926 if(fileName+".png"==icon)
2930 { 2927 {
2931 dialog->IconField->setCurrentItem(i+1); 2928 dialog->IconField->setCurrentItem(i+1);
2932 break; 2929 break;
2933 } 2930 }
2934 ++i; 2931 ++i;
2935 } 2932 }
2936 ++it; 2933 ++it;
2937 } 2934 }
2938 } 2935 }
2939} 2936}
2940 2937
2941void ZSafe::saveCategoryDialogFields(CategoryDialog *dialog) 2938void ZSafe::saveCategoryDialogFields(CategoryDialog *dialog)
2942{ 2939{
2943 QString app_key = APP_KEY; 2940 QString app_key = APP_KEY;
2944#ifndef DESKTOP 2941#ifndef DESKTOP
2945 conf->setGroup ("fieldDefs"); 2942 conf->setGroup ("fieldDefs");
2946#else 2943#else
2947#ifndef WIN32 2944#ifndef WIN32
2948 app_key += "/fieldDefs/"; 2945 app_key += "/fieldDefs/";
2949#endif 2946#endif
2950#endif 2947#endif
2951 QString category = dialog->CategoryField->currentText(); 2948 QString category = dialog->CategoryField->currentText();
2952// #ifndef WIN32 2949// #ifndef WIN32
2953 conf->writeEntry(app_key+category+"-field1", dialog->Field1->text()); 2950 conf->writeEntry(app_key+category+"-field1", dialog->Field1->text());
2954 conf->writeEntry(app_key+category+"-field2", dialog->Field2->text()); 2951 conf->writeEntry(app_key+category+"-field2", dialog->Field2->text());
2955 conf->writeEntry(app_key+category+"-field3", dialog->Field3->text()); 2952 conf->writeEntry(app_key+category+"-field3", dialog->Field3->text());
2956 conf->writeEntry(app_key+category+"-field4", dialog->Field4->text()); 2953 conf->writeEntry(app_key+category+"-field4", dialog->Field4->text());
2957 conf->writeEntry(app_key+category+"-field5", dialog->Field5->text()); 2954 conf->writeEntry(app_key+category+"-field5", dialog->Field5->text());
2958 conf->writeEntry(app_key+category+"-field6", dialog->Field6->text()); 2955 conf->writeEntry(app_key+category+"-field6", dialog->Field6->text());
2959// #endif 2956// #endif
2960 saveConf(); 2957 saveConf();
2961#ifndef DESKTOP 2958#ifndef DESKTOP
2962 conf->setGroup ("zsafe"); 2959 conf->setGroup ("zsafe");
2963#endif 2960#endif
2964} 2961}
2965 2962
2966void ZSafe::editCategory() 2963void ZSafe::editCategory()
2967{ 2964{
2968 if (!selectedItem) 2965 if (!selectedItem)
2969 return; 2966 return;
2970 if (isCategory(selectedItem)) 2967 if (isCategory(selectedItem))
2971 { 2968 {
2972 QString category = selectedItem->text(0); 2969 QString category = selectedItem->text(0);
2973 bool initIcons = false; 2970 bool initIcons = false;
2974 // open the 'Category' dialog 2971 // open the 'Category' dialog
2975 CategoryDialog *dialog; 2972 CategoryDialog *dialog;
2976 if (categoryDialog) 2973 if (categoryDialog)
2977 { 2974 {
2978 dialog = categoryDialog; 2975 dialog = categoryDialog;
2979 } 2976 }
2980 else 2977 else
2981 { 2978 {
2982 categoryDialog = new CategoryDialog(this, tr("Category"), TRUE); 2979 categoryDialog = new CategoryDialog(this, tr("Category"), TRUE);
2983#ifdef WIN32 2980#ifdef WIN32
2984 categoryDialog->setCaption ("Qt " + tr("Category")); 2981 categoryDialog->setCaption ("Qt " + tr("Category"));
2985#endif 2982#endif
2986 dialog = categoryDialog; 2983 dialog = categoryDialog;
2987 connect( dialog->CategoryField, 2984 connect( dialog->CategoryField,
2988 SIGNAL( activated(const QString&)), 2985 SIGNAL( activated(const QString&)),
2989 this, SLOT( categoryFieldActivated(const QString&) ) ); 2986 this, SLOT( categoryFieldActivated(const QString&) ) );
2990 initIcons = true; 2987 initIcons = true;
2991 } 2988 }
2992 setCategoryDialogFields(dialog); 2989 setCategoryDialogFields(dialog);
2993 2990
2994#ifdef DESKTOP 2991#ifdef DESKTOP
2995#ifndef WIN32 2992#ifndef WIN32
2996 QStringList list = conf->entryList( APP_KEY+"/fieldDefs" ); 2993 QStringList list = conf->entryList( APP_KEY+"/fieldDefs" );
2997#else 2994#else
2998 // read all categories from the config file and store 2995 // read all categories from the config file and store
2999 // into a list 2996 // into a list
3000 QFile f (cfgFile); 2997 QFile f (cfgFile);
3001 QStringList list; 2998 QStringList list;
3002 if ( f.open(IO_ReadOnly) ) { // file opened successfully 2999 if ( f.open(IO_ReadOnly) ) { // file opened successfully
3003 QTextStream t( &f ); // use a text stream 3000 QTextStream t( &f ); // use a text stream
3004 QString s; 3001 QString s;
3005 int n = 1; 3002 int n = 1;
3006 while ( !t.eof() ) { // until end of file... 3003 while ( !t.eof() ) { // until end of file...
3007 s = t.readLine(); // line of text excluding '\n' 3004 s = t.readLine(); // line of text excluding '\n'
3008 list.append(s); 3005 list.append(s);
3009 } 3006 }
3010 f.close(); 3007 f.close();
3011 } 3008 }
3012#endif 3009#endif
3013#else 3010#else
3014 // read all categories from the config file and store 3011 // read all categories from the config file and store
3015 // into a list 3012 // into a list
3016 QFile f (cfgFile); 3013 QFile f (cfgFile);
3017 QStringList list; 3014 QStringList list;
3018 if ( f.open(IO_ReadOnly) ) { // file opened successfully 3015 if ( f.open(IO_ReadOnly) ) { // file opened successfully
3019 QTextStream t( &f ); // use a text stream 3016 QTextStream t( &f ); // use a text stream
3020 QString s; 3017 QString s;
3021 while ( !t.eof() ) { // until end of file... 3018 while ( !t.eof() ) { // until end of file...
3022 s = t.readLine(); // line of text excluding '\n' 3019 s = t.readLine(); // line of text excluding '\n'
3023 list.append(s); 3020 list.append(s);
3024 } 3021 }
3025 f.close(); 3022 f.close();
3026 } 3023 }
3027#endif 3024#endif
3028 QStringList::Iterator it = list.begin(); 3025 QStringList::Iterator it = list.begin();
3029 QString categ; 3026 QString categ;
3030 dialog->CategoryField->clear(); // remove all items 3027 dialog->CategoryField->clear(); // remove all items
3031 int i=0; 3028 int i=0;
3032 bool foundCategory = false; 3029 bool foundCategory = false;
3033 while( it != list.end() ) 3030 while( it != list.end() )
3034 { 3031 {
3035 QString *cat = new QString (*it); 3032 QString *cat = new QString (*it);
3036 if (cat->contains("-field1", FALSE)) 3033 if (cat->contains("-field1", FALSE))
3037 { 3034 {
3038#ifdef DESKTOP 3035#ifdef DESKTOP
3039#ifndef WIN32 3036#ifndef WIN32
3040 categ = cat->section ("-field1", 0, 0); 3037 categ = cat->section ("-field1", 0, 0);
3041#else 3038#else
3042 int pos = cat->find ("-field1"); 3039 int pos = cat->find ("-field1");
3043 categ = cat->left (pos); 3040 categ = cat->left (pos);
3044#endif 3041#endif
3045#else 3042#else
3046 int pos = cat->find ("-field1"); 3043 int pos = cat->find ("-field1");
3047 cat->truncate(pos); 3044 cat->truncate(pos);
3048 categ = *cat; 3045 categ = *cat;
3049#endif 3046#endif
3050 if (!categ.isEmpty()) 3047 if (!categ.isEmpty())
3051 { 3048 {
3052 dialog->CategoryField->insertItem (categ, i); 3049 dialog->CategoryField->insertItem (categ, i);
3053 if (category.compare(categ) == 0) 3050 if (category.compare(categ) == 0)
3054 { 3051 {
3055 dialog->CategoryField->setCurrentItem(i); 3052 dialog->CategoryField->setCurrentItem(i);
3056 foundCategory = true; 3053 foundCategory = true;
3057 } 3054 }
3058 i++; 3055 i++;
3059 } 3056 }
3060 } 3057 }
3061 ++it; 3058 ++it;
3062 } 3059 }
3063 if (!foundCategory) 3060 if (!foundCategory)
3064 { 3061 {
3065 dialog->CategoryField->insertItem (category, i); 3062 dialog->CategoryField->insertItem (category, i);
3066 dialog->CategoryField->setCurrentItem(i); 3063 dialog->CategoryField->setCurrentItem(i);
3067 } 3064 }
3068 3065
3069 QString icon; 3066 QString icon;
3070 Category *cat= categories.find (selectedItem->text(0)); 3067 Category *cat= categories.find (selectedItem->text(0));
3071 if (cat) 3068 if (cat)
3072 { 3069 {
3073 icon = cat->getIconName(); 3070 icon = cat->getIconName();
3074 } 3071 }
3075 3072
3076 if (initIcons) 3073 if (initIcons)
3077 { 3074 {
3078 3075
3079 Wait waitDialog(this, tr("Wait dialog")); 3076 Wait waitDialog(this, tr("Wait dialog"));
3080 waitDialog.waitLabel->setText(tr("Gathering icons...")); 3077 waitDialog.waitLabel->setText(tr("Gathering icons..."));
3081 waitDialog.show(); 3078 waitDialog.show();
3082 qApp->processEvents(); 3079 qApp->processEvents();
3083 3080
3084#ifdef DESKTOP 3081#ifdef DESKTOP
3085 QDir d(iconPath); 3082 QDir d(iconPath);
3086#else 3083#else
3087 QDir d(QPEApplication::qpeDir() + "/pics/"); 3084 QDir d(QPEApplication::qpeDir() + "/pics/");
3088#endif 3085#endif
3089 d.setFilter( QDir::Files); 3086 d.setFilter( QDir::Files);
3090 3087
3091 const QFileInfoList *list = d.entryInfoList(); 3088 const QFileInfoList *list = d.entryInfoList();
3092 int i=0; 3089 int i=0;
3093 QFileInfoListIterator it( *list ); // create list iterator 3090 QFileInfoListIterator it( *list ); // create list iterator
3094 QFileInfo *fi; // pointer for traversing 3091 QFileInfo *fi; // pointer for traversing
3095 if (icon.isEmpty() || icon.isNull()) 3092 if (icon.isEmpty() || icon.isNull())
3096 { 3093 {
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));
3290 selectedItem->setOpen( TRUE ); 3287 selectedItem->setOpen( TRUE );
3291 3288
3292 // remove the cutted item 3289 // remove the cutted item
3293 copiedItem->parent()->takeItem(copiedItem); 3290 copiedItem->parent()->takeItem(copiedItem);
3294 selectedItem = NULL; 3291 selectedItem = NULL;
3295 } 3292 }
3296 } 3293 }
3297 else if (IsCopy) 3294 else if (IsCopy)
3298 { 3295 {
3299 if (copiedItem) 3296 if (copiedItem)
3300 { 3297 {
3301 // add the new item 3298 // add the new item
3302 QListViewItem *i = new ShadedListItem (0, selectedItem); 3299 QListViewItem *i = new ShadedListItem (0, selectedItem);
3303 // i->setOpen (TRUE); 3300 // i->setOpen (TRUE);
3304 i->setText (0, copiedItem->text(0)); 3301 i->setText (0, copiedItem->text(0));
3305 i->setText (1, copiedItem->text(1)); 3302 i->setText (1, copiedItem->text(1));
3306 i->setText (2, copiedItem->text(2)); 3303 i->setText (2, copiedItem->text(2));
3307 i->setText (3, copiedItem->text(3)); 3304 i->setText (3, copiedItem->text(3));
3308 i->setText (4, copiedItem->text(4)); 3305 i->setText (4, copiedItem->text(4));
3309 i->setText (5, copiedItem->text(5)); 3306 i->setText (5, copiedItem->text(5));
3310 selectedItem->setOpen( TRUE ); 3307 selectedItem->setOpen( TRUE );
3311 } 3308 }
3312 } 3309 }
3313 } 3310 }
3314 IsCut = false; 3311 IsCut = false;
3315 IsCopy = false; 3312 IsCopy = false;
3316} 3313}
3317 3314
3318void ZSafe::newDocument() 3315void ZSafe::newDocument()
3319{ 3316{
3320 3317
3321 // open the file dialog 3318 // open the file dialog
3322#ifndef DESKTOP 3319#ifndef DESKTOP
3323#ifndef NO_OPIE 3320#ifndef NO_OPIE
3324 QMap<QString, QStringList> mimeTypes; 3321 QMap<QString, QStringList> mimeTypes;
3325 mimeTypes.insert(tr("All"), QStringList() ); 3322 mimeTypes.insert(tr("All"), QStringList() );
3326 mimeTypes.insert(tr("ZSafe"), "zsafe/*" ); 3323 mimeTypes.insert(tr("ZSafe"), "zsafe/*" );
3327 QString newFile = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL, 3324 QString newFile = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL,
3328 QDir::homeDirPath() + "/Documents/application/zsafe", 3325 QDir::homeDirPath() + "/Documents/application/zsafe",
3329 QString::null, 3326 QString::null,
3330 mimeTypes, 3327 mimeTypes,
3331 this, 3328 this,
3332 tr ("Create new ZSafe document")); 3329 tr ("Create new ZSafe document"));
3333#else 3330#else
3334 QString newFile = ScQtFileEdit::getSaveAsFileName(this, 3331 QString newFile = ScQtFileEdit::getSaveAsFileName(this,
3335 tr ("Create new ZSafe document"), 3332 tr ("Create new ZSafe document"),
3336 QDir::homeDirPath() + "/Documents/application/zsafe", 3333 QDir::homeDirPath() + "/Documents/application/zsafe",
3337 "*.zsf"); 3334 "*.zsf");
3338#endif 3335#endif
3339#else 3336#else
3340 QString newFile = QFileDialog::getSaveFileName( 3337 QString newFile = QFileDialog::getSaveFileName(
3341 QDir::homeDirPath() + "/Documents/application/zsafe", 3338 QDir::homeDirPath() + "/Documents/application/zsafe",
3342 "ZSafe (*.zsf)", 3339 "ZSafe (*.zsf)",
3343 this, 3340 this,
3344 "ZSafe File Dialog" 3341 "ZSafe File Dialog"
3345 "Choose a ZSafe file" ); 3342 "Choose a ZSafe file" );
3346#endif 3343#endif
3347 3344
3348 // open the new document 3345 // open the new document
3349 if (newFile && newFile.length() > 0 ) 3346 if (newFile && newFile.length() > 0 )
3350 { 3347 {
3351 // save the previous opened document 3348 // save the previous opened document
3352 if (!filename.isEmpty()) 3349 if (!filename.isEmpty())
3353 saveDocument(filename, FALSE); 3350 saveDocument(filename, FALSE);
3354 3351
3355 modified = true; 3352 modified = true;
3356 3353
3357 // clear the password list 3354 // clear the password list
3358 QListViewItem *i; 3355 QListViewItem *i;
3359 QListViewItem *c = NULL; 3356 QListViewItem *c = NULL;
3360 // step through all categories 3357 // step through all categories
3361 for (i = ListView->firstChild(); 3358 for (i = ListView->firstChild();
3362 i != NULL; 3359 i != NULL;
3363 i = i->nextSibling()) 3360 i = i->nextSibling())
3364 { 3361 {
3365 if (c) delete c; // delete the previous category 3362 if (c) delete c; // delete the previous category
3366 3363
3367 c = i; 3364 c = i;
3368 // step through all subitems 3365 // step through all subitems
3369 QListViewItem *si; 3366 QListViewItem *si;
3370 for (si = i->firstChild(); 3367 for (si = i->firstChild();
3371 si != NULL; ) 3368 si != NULL; )
3372 { 3369 {
3373 QListViewItem *_si = si; 3370 QListViewItem *_si = si;
3374 si = si->nextSibling(); 3371 si = si->nextSibling();
3375 i->takeItem(_si); // remove from view list 3372 i->takeItem(_si); // remove from view list
3376 if (_si) delete _si; 3373 if (_si) delete _si;
3377 } 3374 }
3378 } 3375 }
3379 if (c) delete c; // delete the previous category 3376 if (c) delete c; // delete the previous category
3380 categories.clear(); 3377 categories.clear();
3381 3378
3382 // m_password = ""; 3379 // m_password = "";
3383 selectedItem = NULL; 3380 selectedItem = NULL;
3384 3381
3385 filename = newFile; 3382 filename = newFile;
3386 3383
3387 // save the current filename to the config file 3384 // save the current filename to the config file
3388 conf->writeEntry(APP_KEY+"document", filename); 3385 conf->writeEntry(APP_KEY+"document", filename);
3389 saveConf(); 3386 saveConf();
3390 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 3387 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
3391#ifdef WIN32 3388#ifdef WIN32
3392 this->setCaption("Qt ZSafe: " + ti); 3389 this->setCaption("Qt ZSafe: " + ti);
3393#else 3390#else
3394 this->setCaption("ZSafe: " + ti); 3391 this->setCaption("ZSafe: " + ti);
3395#endif 3392#endif
3396 3393
3397 // openDocument(filename); 3394 // openDocument(filename);
3398 3395
3399 QMessageBox::information( this, tr("ZSafe"), 3396 QMessageBox::information( this, tr("ZSafe"),
3400 tr("Now you have to enter\na password twice for your\nnewly created document."), tr("&OK"), 0); 3397 tr("Now you have to enter\na password twice for your\nnewly created document."), tr("&OK"), 0);
3401 3398
3402 saveDocumentWithPwd(); 3399 saveDocumentWithPwd();
3403 } 3400 }
3404} 3401}
3405 3402
3406void ZSafe::loadDocument() 3403void ZSafe::loadDocument()
3407{ 3404{
3408 3405
3409 // open the file dialog 3406 // open the file dialog
3410#ifndef DESKTOP 3407#ifndef DESKTOP
3411#ifndef NO_OPIE 3408#ifndef NO_OPIE
3412 QMap<QString, QStringList> mimeTypes; 3409 QMap<QString, QStringList> mimeTypes;
3413 mimeTypes.insert(tr("All"), QStringList() ); 3410 mimeTypes.insert(tr("All"), QStringList() );
3414 mimeTypes.insert(tr("ZSafe"), "zsafe/*" ); 3411 mimeTypes.insert(tr("ZSafe"), "zsafe/*" );
3415 QString newFile = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, 3412 QString newFile = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL,
3416 QDir::homeDirPath() + "/Documents/application/zsafe", 3413 QDir::homeDirPath() + "/Documents/application/zsafe",
3417 QString::null, 3414 QString::null,
3418 mimeTypes, 3415 mimeTypes,
3419 this, 3416 this,
3420 tr ("Open ZSafe document")); 3417 tr ("Open ZSafe document"));
3421#else 3418#else
3422 QString newFile = ScQtFileEdit::getOpenFileName(this, 3419 QString newFile = ScQtFileEdit::getOpenFileName(this,
3423 tr ("Open ZSafe document"), 3420 tr ("Open ZSafe document"),
3424 QDir::homeDirPath() + "/Documents/application/zsafe", 3421 QDir::homeDirPath() + "/Documents/application/zsafe",
3425 "*.zsf"); 3422 "*.zsf");
3426#endif 3423#endif
3427#else 3424#else
3428 QString newFile = QFileDialog::getOpenFileName( 3425 QString newFile = QFileDialog::getOpenFileName(
3429 QDir::homeDirPath() + "/Documents/application/zsafe", 3426 QDir::homeDirPath() + "/Documents/application/zsafe",
3430 "ZSafe (*.zsf)", 3427 "ZSafe (*.zsf)",
3431 this, 3428 this,
3432 "ZSafe File Dialog" 3429 "ZSafe File Dialog"
3433 "Choose a ZSafe file" ); 3430 "Choose a ZSafe file" );
3434#endif 3431#endif
3435 3432
3436 // open the new document 3433 // open the new document
3437 if (newFile && newFile.length() > 0 ) 3434 if (newFile && newFile.length() > 0 )
3438 { 3435 {
3439 // save the previous opened document 3436 // save the previous opened document
3440 if (!filename.isEmpty()) 3437 if (!filename.isEmpty())
3441 saveDocument(filename, FALSE); 3438 saveDocument(filename, FALSE);
3442 3439
3443 // clear the password list 3440 // clear the password list
3444 QListViewItem *i; 3441 QListViewItem *i;
3445 QListViewItem *c = NULL; 3442 QListViewItem *c = NULL;
3446 // step through all categories 3443 // step through all categories
3447 for (i = ListView->firstChild(); 3444 for (i = ListView->firstChild();
3448 i != NULL; 3445 i != NULL;
3449 i = i->nextSibling()) 3446 i = i->nextSibling())
3450 { 3447 {
3451 if (c) delete c; // delete the previous category 3448 if (c) delete c; // delete the previous category
3452 3449
3453 c = i; 3450 c = i;
3454 // step through all subitems 3451 // step through all subitems
3455 QListViewItem *si; 3452 QListViewItem *si;
3456 for (si = i->firstChild(); 3453 for (si = i->firstChild();
3457 si != NULL; ) 3454 si != NULL; )
3458 { 3455 {
3459 QListViewItem *_si = si; 3456 QListViewItem *_si = si;
3460 si = si->nextSibling(); 3457 si = si->nextSibling();
3461 i->takeItem(_si); // remove from view list 3458 i->takeItem(_si); // remove from view list
3462 if (_si) delete _si; 3459 if (_si) delete _si;
3463 } 3460 }
3464 } 3461 }
3465 if (c) delete c; // delete the previous category 3462 if (c) delete c; // delete the previous category
3466 categories.clear(); 3463 categories.clear();
3467 m_password = ""; 3464 m_password = "";
3468 selectedItem = NULL; 3465 selectedItem = NULL;
3469 filename = newFile; 3466 filename = newFile;
3470 3467
3471 // save the current filename to the config file 3468 // save the current filename to the config file
3472 conf->writeEntry(APP_KEY+"document", filename); 3469 conf->writeEntry(APP_KEY+"document", filename);
3473 saveConf(); 3470 saveConf();
3474 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 3471 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
3475#ifdef WIN32 3472#ifdef WIN32
3476 this->setCaption("Qt ZSafe: " + ti); 3473 this->setCaption("Qt ZSafe: " + ti);
3477#else 3474#else
3478 this->setCaption("ZSafe: " + ti); 3475 this->setCaption("ZSafe: " + ti);
3479#endif 3476#endif
3480 3477
3481 openDocument(filename); 3478 openDocument(filename);
3482 } 3479 }
3483} 3480}
3484 3481
3485void ZSafe::saveDocumentAs() 3482void ZSafe::saveDocumentAs()
3486{ 3483{
3487 3484
3488#ifndef DESKTOP 3485#ifndef DESKTOP
3489#ifndef NO_OPIE 3486#ifndef NO_OPIE
3490 QMap<QString, QStringList> mimeTypes; 3487 QMap<QString, QStringList> mimeTypes;
3491 mimeTypes.insert(tr("All"), QStringList() ); 3488 mimeTypes.insert(tr("All"), QStringList() );
3492 mimeTypes.insert(tr("ZSafe"), "zsafe/*" ); 3489 mimeTypes.insert(tr("ZSafe"), "zsafe/*" );
3493 QString newFile = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL, 3490 QString newFile = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL,
3494 QDir::homeDirPath() + "/Documents/application/zsafe", 3491 QDir::homeDirPath() + "/Documents/application/zsafe",
3495 QString::null, 3492 QString::null,
3496 mimeTypes, 3493 mimeTypes,
3497 this, 3494 this,
3498 tr ("Save ZSafe document as..")); 3495 tr ("Save ZSafe document as.."));
3499#else 3496#else
3500 QString newFile = ScQtFileEdit::getSaveAsFileName(this, 3497 QString newFile = ScQtFileEdit::getSaveAsFileName(this,
3501 tr ("Save ZSafe document as.."), 3498 tr ("Save ZSafe document as.."),
3502 QDir::homeDirPath() + "/Documents/application/zsafe", 3499 QDir::homeDirPath() + "/Documents/application/zsafe",
3503 "*.zsf"); 3500 "*.zsf");
3504#endif 3501#endif
3505#else 3502#else
3506 // open the file dialog 3503 // open the file dialog
3507 QString newFile = QFileDialog::getSaveFileName( 3504 QString newFile = QFileDialog::getSaveFileName(
3508 QDir::homeDirPath() + "/Documents/application/zsafe", 3505 QDir::homeDirPath() + "/Documents/application/zsafe",
3509 "ZSafe (*.zsf)", 3506 "ZSafe (*.zsf)",
3510 this, 3507 this,
3511 "ZSafe File Dialog" 3508 "ZSafe File Dialog"
3512 "Choose a ZSafe file" ); 3509 "Choose a ZSafe file" );
3513#endif 3510#endif
3514 3511
3515 // open the new document 3512 // open the new document
3516 if (newFile && newFile.length() > 0 ) 3513 if (newFile && newFile.length() > 0 )
3517 { 3514 {
3518 // save the previous opened document 3515 // save the previous opened document
3519 if (!filename.isEmpty()) 3516 if (!filename.isEmpty())
3520 saveDocument(filename, FALSE); 3517 saveDocument(filename, FALSE);
3521 3518
3522 selectedItem = NULL; 3519 selectedItem = NULL;
3523 filename = newFile; 3520 filename = newFile;
3524 3521
3525 // save the current filename to the config file 3522 // save the current filename to the config file
3526 conf->writeEntry(APP_KEY+"document", filename); 3523 conf->writeEntry(APP_KEY+"document", filename);
3527 saveConf(); 3524 saveConf();
3528 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 3525 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
3529#ifdef WIN32 3526#ifdef WIN32
3530 this->setCaption("Qt ZSafe: " + ti); 3527 this->setCaption("Qt ZSafe: " + ti);
3531#else 3528#else
3532 this->setCaption("ZSafe: " + ti); 3529 this->setCaption("ZSafe: " + ti);
3533#endif 3530#endif
3534 3531
3535 QMessageBox::information( this, tr("ZSafe"), 3532 QMessageBox::information( this, tr("ZSafe"),
3536 tr("Now you have to enter\na password twice for your\nnewly created document."), tr("&OK"), 0); 3533 tr("Now you have to enter\na password twice for your\nnewly created document."), tr("&OK"), 0);
3537 3534
3538 saveDocumentWithPwd(); 3535 saveDocumentWithPwd();
3539 } 3536 }
3540} 3537}
3541 3538
3542void ZSafe::saveDocumentWithoutPwd() 3539void ZSafe::saveDocumentWithoutPwd()
3543{ 3540{
3544 saveDocument(filename, FALSE); 3541 saveDocument(filename, FALSE);
3545} 3542}
3546 3543
3547void ZSafe::saveDocumentWithPwd() 3544void ZSafe::saveDocumentWithPwd()
3548{ 3545{
3549 saveDocument(filename, TRUE); 3546 saveDocument(filename, TRUE);
3550} 3547}
3551 3548
3552void ZSafe::about() 3549void ZSafe::about()
3553{ 3550{
3554 QString info; 3551 QString info;
3555#ifdef JPATCH_HDE 3552#ifdef JPATCH_HDE
3556 info = "<html><body><div align=""center"">"; 3553 info = "<html><body><div align=""center"">";
3557 info += "<b>"; 3554 info += "<b>";
3558 info += tr("Zaurus Password Manager<br>"); 3555 info += tr("Zaurus Password Manager<br>");
3559 info += tr("ZSafe version 2.1.2-jv01b<br>"); 3556 info += tr("ZSafe version 2.1.2-jv01b<br>");
3560 info += "</b>"; 3557 info += "</b>";
3561 info += tr("by Carsten Schneider<br>"); 3558 info += tr("by Carsten Schneider<br>");
3562 info += "zcarsten@gmx.net<br>"; 3559 info += "zcarsten@gmx.net<br>";
3563 info += "http://z-soft.z-portal.info/zsafe"; 3560 info += "http://z-soft.z-portal.info/zsafe";
3564 info += "<br>"; 3561 info += "<br>";
3565 info += tr("Translations by Robert Ernst<br>"); 3562 info += tr("Translations by Robert Ernst<br>");
3566 info += "robert.ernst@linux-solutions.at<br>"; 3563 info += "robert.ernst@linux-solutions.at<br>";
3567 3564
3568 info += "<br><br>"; 3565 info += "<br><br>";
3569 info += QString::fromUtf8("æ~W¥æ~\\¬èª~^/VGA Zaurus対å¿~\\ã~C~Qã~C~Cã~C~Aä½~\\æ ~H~P<br>"); 3566 info += QString::fromUtf8("æ~W¥æ~\\¬èª~^/VGA Zaurus対å¿~\\ã~C~Qã~C~Cã~C~Aä½~\\æ ~H~P<br>");
3570 info += "HADECO R&D<br>"; 3567 info += "HADECO R&D<br>";
3571 info += "r&d@hadeco.co.jp<br>"; 3568 info += "r&d@hadeco.co.jp<br>";
3572 info += "http://www.hadeco.co.jp/r&d/<br>"; 3569 info += "http://www.hadeco.co.jp/r&d/<br>";
3573 info += "<br></div>"; 3570 info += "<br></div>";
3574 info += "</body></html>"; 3571 info += "</body></html>";
3575#else 3572#else
3576 info = "<html><body><div align=""center"">"; 3573 info = "<html><body><div align=""center"">";
3577 info += "<b>"; 3574 info += "<b>";
3578 info += tr("Zaurus Password Manager<br>"); 3575 info += tr("Zaurus Password Manager<br>");
3579 info += tr("ZSafe version 2.1.2<br>"); 3576 info += tr("ZSafe version 2.1.2<br>");
3580 info += "</b>"; 3577 info += "</b>";
3581 info += tr("by Carsten Schneider<br>"); 3578 info += tr("by Carsten Schneider<br>");
3582 info += "zcarsten@gmx.net<br>"; 3579 info += "zcarsten@gmx.net<br>";
3583 info += "http://z-soft.z-portal.info/zsafe"; 3580 info += "http://z-soft.z-portal.info/zsafe";
3584 info += "<br>"; 3581 info += "<br>";
3585 info += tr("Translations by Robert Ernst<br>"); 3582 info += tr("Translations by Robert Ernst<br>");
3586 info += "robert.ernst@linux-solutions.at<br>"; 3583 info += "robert.ernst@linux-solutions.at<br>";
3587 info += "<br></div>"; 3584 info += "<br></div>";
3588 info += "</body></html>"; 3585 info += "</body></html>";
3589#endif 3586#endif
3590 3587
3591 // QMessageBox::information( this, tr("ZSafe"), info, tr("&OK"), 0); 3588 // QMessageBox::information( this, tr("ZSafe"), info, tr("&OK"), 0);
3592 3589
3593 QMessageBox mb( this, tr("ZSafe")); 3590 QMessageBox mb( this, tr("ZSafe"));
3594 mb.setText (info); 3591 mb.setText (info);
3595 mb.setButtonText (QMessageBox::Ok, tr ("&OK")); 3592 mb.setButtonText (QMessageBox::Ok, tr ("&OK"));
3596 QPixmap zsafe_img((const char**) zsafe_xpm); 3593 QPixmap zsafe_img((const char**) zsafe_xpm);
3597 mb.setIconPixmap (zsafe_img); 3594 mb.setIconPixmap (zsafe_img);
3598 mb.exec(); 3595 mb.exec();
3599} 3596}
3600 3597
3601void ZSafe::setExpandFlag() 3598void ZSafe::setExpandFlag()
3602{ 3599{
3603 expandTree = !expandTree; 3600 expandTree = !expandTree;
3604 file->setItemChecked('o', expandTree); 3601 file->setItemChecked('o', expandTree);
3605#ifndef DESKTOP 3602#ifndef DESKTOP
3606 conf->setGroup ("zsafePrefs"); 3603 conf->setGroup ("zsafePrefs");
3607#endif 3604#endif
3608// #ifndef WIN32 3605// #ifndef WIN32
3609 conf->writeEntry (APP_KEY+"expandTree", expandTree); 3606 conf->writeEntry (APP_KEY+"expandTree", expandTree);
3610// #endif 3607// #endif
3611 saveConf(); 3608 saveConf();
3612 3609
3613} 3610}
3614 3611
3615void ZSafe::paintEvent( QPaintEvent * ) 3612void ZSafe::paintEvent( QPaintEvent * )
3616{ 3613{
3617 if (raiseFlag) 3614 if (raiseFlag)
3618 { 3615 {
3619 raiseFlag = false; 3616 raiseFlag = false;
3620 raiseTimer.start (1, true); 3617 raiseTimer.start (1, true);
3621 if (infoForm->isVisible()) 3618 if (infoForm->isVisible())
3622 infoForm->raise(); 3619 infoForm->raise();
3623 } 3620 }
3624} 3621}
3625 3622
3626void ZSafe::resizeEvent ( QResizeEvent * ) 3623void ZSafe::resizeEvent ( QResizeEvent * )
3627{ 3624{
3628 // qWarning ("resizeEvent"); 3625 // qWarning ("resizeEvent");
3629#ifndef DESKTOP 3626#ifndef DESKTOP
3630 DeskW = appl->desktop()->width(); 3627 DeskW = appl->desktop()->width();
3631 DeskH = appl->desktop()->height(); 3628 DeskH = appl->desktop()->height();
3632#else 3629#else
3633 DeskW = this->width(); 3630 DeskW = this->width();
3634 DeskH = this->height(); 3631 DeskH = this->height();
3635#endif 3632#endif
3636 3633
3637 if (New) 3634 if (New)
3638 New->setGeometry ( QRect( DeskW-84, 2, 20, 20 ) ); 3635 New->setGeometry ( QRect( DeskW-84, 2, 20, 20 ) );
3639 if (Edit) 3636 if (Edit)
3640 Edit->setGeometry ( QRect( DeskW-64, 2, 20, 20 ) ); 3637 Edit->setGeometry ( QRect( DeskW-64, 2, 20, 20 ) );
3641 if (Delete) 3638 if (Delete)
3642 Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) ); 3639 Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) );
3643 if (Find) 3640 if (Find)
3644 Find->setGeometry ( QRect( DeskW-24, 2, 20, 20 ) ); 3641 Find->setGeometry ( QRect( DeskW-24, 2, 20, 20 ) );
3645} 3642}
3646 3643
3647void ZSafe::slotRaiseTimer() 3644void ZSafe::slotRaiseTimer()
3648{ 3645{
3649 if (infoForm->isVisible()) 3646 if (infoForm->isVisible())
3650 infoForm->raise(); 3647 infoForm->raise();
3651 raiseFlag = true; 3648 raiseFlag = true;
3652} 3649}
3653 3650
3654QPixmap * ZSafe::getPredefinedIcon(QString category) 3651QPixmap * ZSafe::getPredefinedIcon(QString category)
3655{ 3652{
3656 QPixmap *pm; 3653 QPixmap *pm;
3657 if (category == "Bank cards") 3654 if (category == "Bank cards")
3658 pm = new QPixmap((const char**)bank_cards_data); 3655 pm = new QPixmap((const char**)bank_cards_data);
3659 else if (category == "Passwords") 3656 else if (category == "Passwords")
3660 pm = new QPixmap((const char**)passwords_data); 3657 pm = new QPixmap((const char**)passwords_data);
3661 else if (category == "Software") 3658 else if (category == "Software")
3662 pm = new QPixmap((const char**)software_data); 3659 pm = new QPixmap((const char**)software_data);
3663 else if (category == "General") 3660 else if (category == "General")
3664 pm = new QPixmap((const char**)general_data); 3661 pm = new QPixmap((const char**)general_data);
3665 else 3662 else
3666 pm = new QPixmap((const char**)general_data); 3663 pm = new QPixmap((const char**)general_data);
3667 return pm; 3664 return pm;
3668} 3665}
3669 3666
3670void ZSafe::setDocument(const QString& fileref) 3667void ZSafe::setDocument(const QString& fileref)
3671{ 3668{
3672#ifndef DESKTOP 3669#ifndef DESKTOP
3673 // stop the timer to prevent loading of the default document 3670 // stop the timer to prevent loading of the default document
3674 docuTimer.stop(); 3671 docuTimer.stop();
3675 3672
3676 DocLnk link(fileref); 3673 DocLnk link(fileref);
3677 if ( link.isValid() ) 3674 if ( link.isValid() )
3678 { 3675 {
3679 // if (filename != link.file()) 3676 // if (filename != link.file())
3680 // saveDocument(filename, FALSE); 3677 // saveDocument(filename, FALSE);
3681 filename = link.file(); 3678 filename = link.file();
3682 } 3679 }
3683 else 3680 else
3684 { 3681 {
3685 // if (filename != fileref) 3682 // if (filename != fileref)
3686 // saveDocument(filename, FALSE); 3683 // saveDocument(filename, FALSE);
3687 filename = fileref; 3684 filename = fileref;
3688 } 3685 }
3689 // save the current filename to the config file 3686 // save the current filename to the config file
3690 conf->writeEntry(APP_KEY+"document", filename); 3687 conf->writeEntry(APP_KEY+"document", filename);
3691 saveConf(); 3688 saveConf();
3692 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 3689 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
3693#ifdef WIN32 3690#ifdef WIN32
3694 this->setCaption("Qt ZSafe: " + ti); 3691 this->setCaption("Qt ZSafe: " + ti);
3695#else 3692#else
3696 this->setCaption("ZSafe: " + ti); 3693 this->setCaption("ZSafe: " + ti);
3697#endif 3694#endif
3698 3695
3699 // clear the password list 3696 // clear the password list
3700 QListViewItem *i; 3697 QListViewItem *i;
3701 QListViewItem *c = NULL; 3698 QListViewItem *c = NULL;
3702 // step through all categories 3699 // step through all categories
3703 for (i = ListView->firstChild(); 3700 for (i = ListView->firstChild();
3704 i != NULL; 3701 i != NULL;
3705 i = i->nextSibling()) 3702 i = i->nextSibling())
3706 { 3703 {
3707 if (c) delete c; // delete the previous category 3704 if (c) delete c; // delete the previous category
3708 3705
3709 c = i; 3706 c = i;
3710 // step through all subitems 3707 // step through all subitems
3711 QListViewItem *si; 3708 QListViewItem *si;
3712 for (si = i->firstChild(); 3709 for (si = i->firstChild();
3713 si != NULL; ) 3710 si != NULL; )
3714 { 3711 {
3715 QListViewItem *_si = si; 3712 QListViewItem *_si = si;
3716 si = si->nextSibling(); 3713 si = si->nextSibling();
3717 i->takeItem(_si); // remove from view list 3714 i->takeItem(_si); // remove from view list
3718 if (_si) delete _si; 3715 if (_si) delete _si;
3719 } 3716 }
3720 } 3717 }
3721 if (c) delete c; // delete the previous category 3718 if (c) delete c; // delete the previous category
3722 categories.clear(); 3719 categories.clear();
3723 3720
3724 m_password = ""; 3721 m_password = "";
3725 selectedItem = NULL; 3722 selectedItem = NULL;
3726 3723
3727 openDocument(filename); 3724 openDocument(filename);
3728#endif 3725#endif
3729} 3726}
3730 3727
3731 3728
3732 3729
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,202 +1,210 @@
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;
174 b = b >> decoder->format->blueShift; 182 b = b >> decoder->format->blueShift;
175 b = b & blueMax; 183 b = b & blueMax;
176 184
177 r = ( r * 255 ) / redMax; 185 r = ( r * 255 ) / redMax;
178 g = ( g * 255 ) / greenMax; 186 g = ( g * 255 ) / greenMax;
179 b = ( b * 255 ) / blueMax; 187 b = ( b * 255 ) / blueMax;
180 188
181 ulong *p = ( ulong * ) img.scanLine( j ) + i; 189 ulong *p = ( ulong * ) img.scanLine( j ) + i;
182 *p = qRgb( r,g,b ); 190 *p = qRgb( r,g,b );
183 } 191 }
184 } 192 }
185 } 193 }
186 else { 194 else {
187 p.setBrush( QBrush( Qt::black ) ); 195 p.setBrush( QBrush( Qt::black ) );
188 p.drawRect( x, y, w, h ); 196 p.drawRect( x, y, w, h );
189 } 197 }
190 198
191 if (scaleFactor > 1) { 199 if (scaleFactor > 1) {
192 /* FIXME: proper zero width/height handling */ 200 /* FIXME: proper zero width/height handling */
193 if (w/scaleFactor != 0) 201 if (w/scaleFactor != 0)
194 p.drawImage( x/scaleFactor, y/scaleFactor, img.smoothScale(w/scaleFactor,h/scaleFactor) ); 202 p.drawImage( x/scaleFactor, y/scaleFactor, img.smoothScale(w/scaleFactor,h/scaleFactor) );
195 emit updated( x/scaleFactor, y/scaleFactor, w/scaleFactor, h/scaleFactor ); 203 emit updated( x/scaleFactor, y/scaleFactor, w/scaleFactor, h/scaleFactor );
196 } 204 }
197 else { 205 else {
198 p.drawImage( x, y, img); 206 p.drawImage( x, y, img);
199 emit updated( x, y, w, h ); 207 emit updated( x, y, w, h );
200 } 208 }
201} 209}
202 210
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,200 +1,204 @@
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()
174{ 178{
175 if ( loggedIn_ ) { 179 if ( loggedIn_ ) {
176 connection_->sendCutText( qApp->clipboard()->text() ); 180 connection_->sendCutText( qApp->clipboard()->text() );
177 } 181 }
178} 182}
179void KRFBCanvas::sendCtlAltDel( void) 183void KRFBCanvas::sendCtlAltDel( void)
180{ 184{
181 185
182 if ( loggedIn_ ) { 186 if ( loggedIn_ ) {
183 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Control, 0,0)); 187 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Control, 0,0));
184 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Alt, 0,0)); 188 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Alt, 0,0));
185 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Delete, 0,0)); 189 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Delete, 0,0));
186 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Control, 0,0)); 190 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Control, 0,0));
187 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Alt, 0,0)); 191 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Alt, 0,0));
188 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Delete, 0,0)); 192 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Delete, 0,0));
189 } 193 }
190} 194}
191 195
192void KRFBCanvas::markDoubleClick( void) 196void KRFBCanvas::markDoubleClick( void)
193{ 197{
194 nextRightClick=1; 198 nextRightClick=1;
195} 199}
196 200
197void KRFBCanvas::markRightClick( void) 201void KRFBCanvas::markRightClick( void)
198{ 202{
199 nextRightClick=1; 203 nextRightClick=1;
200} 204}
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,971 +1,975 @@
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
178 182
179 for(a=0;a<15;a++) 183 for(a=0;a<15;a++)
180 { 184 {
181 p1[a]=new CanvasImageItem(piece_1_front,area); 185 p1[a]=new CanvasImageItem(piece_1_front,area);
182 p1[a]->setSize(15,15); 186 p1[a]->setSize(15,15);
183 p1_side[a]=new CanvasImageItem(piece_1_side,area); 187 p1_side[a]=new CanvasImageItem(piece_1_side,area);
184 p1_side[a]->setSize(15,5); 188 p1_side[a]->setSize(15,5);
185 189
186 p2[a]=new CanvasImageItem(piece_2_front,area); 190 p2[a]=new CanvasImageItem(piece_2_front,area);
187 p2[a]->setSize(15,15); 191 p2[a]->setSize(15,15);
188 p2_side[a]=new CanvasImageItem(piece_2_side,area); 192 p2_side[a]=new CanvasImageItem(piece_2_side,area);
189 p2_side[a]->setSize(15,5); 193 p2_side[a]->setSize(15,5);
190 } 194 }
191 draw(); 195 draw();
192 196
193 //the dice 197 //the dice
194 QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name)); 198 QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name));
195 diceA1=new CanvasImageItem*[7]; 199 diceA1=new CanvasImageItem*[7];
196 diceA2=new CanvasImageItem*[7]; 200 diceA2=new CanvasImageItem*[7];
197 QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name)); 201 QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name));
198 diceB1=new CanvasImageItem*[7]; 202 diceB1=new CanvasImageItem*[7];
199 diceB2=new CanvasImageItem*[7]; 203 diceB2=new CanvasImageItem*[7];
200 QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name)); 204 QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name));
201 //oddsDice=new CanvasImageItem*[6]; 205 //oddsDice=new CanvasImageItem*[6];
202 206
203 207
204 for(a=0;a<7;a++) 208 for(a=0;a<7;a++)
205 { 209 {
206 QImage dicebgA=dicebgA_all.copy(a*25,0,25,25); 210 QImage dicebgA=dicebgA_all.copy(a*25,0,25,25);
207 diceA1[a]=new CanvasImageItem(dicebgA,area); 211 diceA1[a]=new CanvasImageItem(dicebgA,area);
208 diceA1[a]->setX(5); 212 diceA1[a]->setX(5);
209 diceA1[a]->setY(205-2); 213 diceA1[a]->setY(205-2);
210 diceA1[a]->setZ(1); 214 diceA1[a]->setZ(1);
211 diceA1[a]->setSize(25,25); 215 diceA1[a]->setSize(25,25);
212 diceA2[a]=new CanvasImageItem(dicebgA,area); 216 diceA2[a]=new CanvasImageItem(dicebgA,area);
213 diceA2[a]->setX(35); 217 diceA2[a]->setX(35);
214 diceA2[a]->setY(205-2); 218 diceA2[a]->setY(205-2);
215 diceA2[a]->setZ(1); 219 diceA2[a]->setZ(1);
216 diceA2[a]->setSize(25,25); 220 diceA2[a]->setSize(25,25);
217 221
218 QImage dicebgB=dicebgB_all.copy(a*25,0,25,25); 222 QImage dicebgB=dicebgB_all.copy(a*25,0,25,25);
219 diceB1[a]=new CanvasImageItem(dicebgB,area); 223 diceB1[a]=new CanvasImageItem(dicebgB,area);
220 diceB1[a]->setX(175); 224 diceB1[a]->setX(175);
221 diceB1[a]->setY(205-2); 225 diceB1[a]->setY(205-2);
222 diceB1[a]->setZ(1); 226 diceB1[a]->setZ(1);
223 diceB1[a]->setSize(25,25); 227 diceB1[a]->setSize(25,25);
224 diceB2[a]=new CanvasImageItem(dicebgB,area); 228 diceB2[a]=new CanvasImageItem(dicebgB,area);
225 diceB2[a]->setX(205); 229 diceB2[a]->setX(205);
226 diceB2[a]->setY(205-2); 230 diceB2[a]->setY(205-2);
227 diceB2[a]->setZ(1); 231 diceB2[a]->setZ(1);
228 diceB2[a]->setSize(25,25); 232 diceB2[a]->setSize(25,25);
229 233
230 /* 234 /*
231 if(a<6) 235 if(a<6)
232 { 236 {
233 QImage oddsbg=oddsbg_all.copy(a*15,0,15,15); 237 QImage oddsbg=oddsbg_all.copy(a*15,0,15,15);
234 oddsDice[a]=new CanvasImageItem(oddsbg,area); 238 oddsDice[a]=new CanvasImageItem(oddsbg,area);
235 oddsDice[a]->setX(110); 239 oddsDice[a]->setX(110);
236 oddsDice[a]->setY(210-2); 240 oddsDice[a]->setY(210-2);
237 oddsDice[a]->setZ(1); 241 oddsDice[a]->setZ(1);
238 oddsDice[a]->setSize(15,15); 242 oddsDice[a]->setSize(15,15);
239 oddsDice[a]->hide(); 243 oddsDice[a]->hide();
240 } 244 }
241 */ 245 */
242 } 246 }
243 //oddsDice[0]->show(); 247 //oddsDice[0]->show();
244 248
245 //set the board 249 //set the board
246 QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name)); 250 QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name));
247 board=new CanvasImageItem(boardbg,area); 251 board=new CanvasImageItem(boardbg,area);
248 board->setX(0); 252 board->setX(0);
249 board->setY(0); 253 board->setY(0);
250 board->setZ(0); 254 board->setZ(0);
251 board->setSize(235-2,200-2); 255 board->setSize(235-2,200-2);
252 board->show(); 256 board->show();
253 257
254 //the table 258 //the table
255 QImage tablebg(Resource::loadImage("backgammon/table/"+table_name)); 259 QImage tablebg(Resource::loadImage("backgammon/table/"+table_name));
256 table=new CanvasImageItem(tablebg,area); 260 table=new CanvasImageItem(tablebg,area);
257 table->setX(0); 261 table->setX(0);
258 table->setY(200-2); 262 table->setY(200-2);
259 table->setZ(0); 263 table->setZ(0);
260 table->setSize(235-2,20); 264 table->setSize(235-2,20);
261 table->show(); 265 table->show();
262 266
263 //the no move marker 267 //the no move marker
264 QImage nomovebg(Resource::loadImage("backgammon/no_move")); 268 QImage nomovebg(Resource::loadImage("backgammon/no_move"));
265 nomove_marker=new CanvasImageItem(nomovebg,area); 269 nomove_marker=new CanvasImageItem(nomovebg,area);
266 nomove_marker->setX(0); 270 nomove_marker->setX(0);
267 nomove_marker->setY(200); 271 nomove_marker->setY(200);
268 nomove_marker->setZ(2); 272 nomove_marker->setZ(2);
269 nomove_marker->hide(); 273 nomove_marker->hide();
270 274
271 //default human against computer 275 //default human against computer
272 player1_auto=false; 276 player1_auto=false;
273 player2_auto=true; 277 player2_auto=true;
274 //start new game 278 //start new game
275 newgame(); 279 newgame();
276} 280}
277 281
278BackGammon::~BackGammon() 282BackGammon::~BackGammon()
279{ 283{
280 //DESTRUCTOR 284 //DESTRUCTOR
281} 285}
282 286
283void BackGammon::newgame() 287void BackGammon::newgame()
284{ 288{
285 gameFinished=false; 289 gameFinished=false;
286 QDateTime now=QDateTime::currentDateTime(); 290 QDateTime now=QDateTime::currentDateTime();
287 game_name=now.date().toString()+"_"+now.time().toString(); 291 game_name=now.date().toString()+"_"+now.time().toString();
288 move->reset(); 292 move->reset();
289 draw(); 293 draw();
290 diceA1_value=7; 294 diceA1_value=7;
291 diceA2_value=7; 295 diceA2_value=7;
292 diceA3_value=7; 296 diceA3_value=7;
293 diceA4_value=7; 297 diceA4_value=7;
294 diceB1_value=7; 298 diceB1_value=7;
295 diceB2_value=7; 299 diceB2_value=7;
296 diceB3_value=7; 300 diceB3_value=7;
297 diceB4_value=7; 301 diceB4_value=7;
298 showdice(); 302 showdice();
299 player=2; 303 player=2;
300 dice1_played=true; 304 dice1_played=true;
301 dice2_played=true; 305 dice2_played=true;
302 dice3_played=true; 306 dice3_played=true;
303 dice4_played=true; 307 dice4_played=true;
304 dice_rolled=false; 308 dice_rolled=false;
305 setplayer(); 309 setplayer();
306 area->update(); 310 area->update();
307} 311}
308 312
309void BackGammon::playerselect() 313void BackGammon::playerselect()
310{ 314{
311 PlayerDialog* playerdialog=new PlayerDialog(this); 315 PlayerDialog* playerdialog=new PlayerDialog(this);
312 playerdialog->setAuto1(player1_auto); 316 playerdialog->setAuto1(player1_auto);
313 playerdialog->setAuto2(player2_auto); 317 playerdialog->setAuto2(player2_auto);
314 if(!playerdialog->exec()) 318 if(!playerdialog->exec())
315 return; 319 return;
316 player1_auto=playerdialog->getAuto1(); 320 player1_auto=playerdialog->getAuto1();
317 player2_auto=playerdialog->getAuto2(); 321 player2_auto=playerdialog->getAuto2();
318} 322}
319 323
320void BackGammon::loadgame() 324void BackGammon::loadgame()
321{ 325{
322 FileDialog* file=new FileDialog(this,"Load Game",".game"); 326 FileDialog* file=new FileDialog(this,"Load Game",".game");
323 if(!file->exec()) 327 if(!file->exec())
324 return; 328 return;
325 329
326 game_name=file->filename(); 330 game_name=file->filename();
327 QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; 331 QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game";
328 332
329 Config game(game_file,Config::File); 333 Config game(game_file,Config::File);
330 game.setGroup("dice"); 334 game.setGroup("dice");
331 diceA1_value=game.readNumEntry("diceA1_value"); 335 diceA1_value=game.readNumEntry("diceA1_value");
332 diceA2_value=game.readNumEntry("diceA2_value"); 336 diceA2_value=game.readNumEntry("diceA2_value");
333 diceA3_value=game.readNumEntry("diceA3_value"); 337 diceA3_value=game.readNumEntry("diceA3_value");
334 diceA4_value=game.readNumEntry("diceA4_value"); 338 diceA4_value=game.readNumEntry("diceA4_value");
335 diceB1_value=game.readNumEntry("diceB1_value"); 339 diceB1_value=game.readNumEntry("diceB1_value");
336 diceB2_value=game.readNumEntry("diceB2_value"); 340 diceB2_value=game.readNumEntry("diceB2_value");
337 diceB3_value=game.readNumEntry("diceB3_value"); 341 diceB3_value=game.readNumEntry("diceB3_value");
338 diceB4_value=game.readNumEntry("diceB4_value"); 342 diceB4_value=game.readNumEntry("diceB4_value");
339 player=game.readNumEntry("player"); 343 player=game.readNumEntry("player");
340 dice1_played=game.readBoolEntry("dice1_played"); 344 dice1_played=game.readBoolEntry("dice1_played");
341 dice2_played=game.readBoolEntry("dice2_played"); 345 dice2_played=game.readBoolEntry("dice2_played");
342 dice3_played=game.readBoolEntry("dice3_played"); 346 dice3_played=game.readBoolEntry("dice3_played");
343 dice4_played=game.readBoolEntry("dice4_played"); 347 dice4_played=game.readBoolEntry("dice4_played");
344 dice_rolled=game.readBoolEntry("dice_rolled"); 348 dice_rolled=game.readBoolEntry("dice_rolled");
345 player1_auto=game.readBoolEntry("player1_auto"); 349 player1_auto=game.readBoolEntry("player1_auto");
346 player2_auto=game.readBoolEntry("player2_auto"); 350 player2_auto=game.readBoolEntry("player2_auto");
347 351
348 game.setGroup("pieces"); 352 game.setGroup("pieces");
349 QString label; 353 QString label;
350 LoadSave load; 354 LoadSave load;
351 for(int a=0;a<28;a++) 355 for(int a=0;a<28;a++)
352 { 356 {
353 label.setNum(a); 357 label.setNum(a);
354 load.pop[a].total = game.readNumEntry(label,0); 358 load.pop[a].total = game.readNumEntry(label,0);
355 } 359 }
356 360
357 move->loadGame(load); 361 move->loadGame(load);
358 setplayer(); 362 setplayer();
359 showdice(); 363 showdice();
360 draw(); 364 draw();
361 area->update(); 365 area->update();
362} 366}
363 367
364void BackGammon::savegame() 368void BackGammon::savegame()
365{ 369{
366 QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; 370 QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game";
367 371
368 Config game(game_file,Config::File); 372 Config game(game_file,Config::File);
369 game.setGroup("dice"); 373 game.setGroup("dice");
370 game.writeEntry("diceA1_value",diceA1_value); 374 game.writeEntry("diceA1_value",diceA1_value);
371 game.writeEntry("diceA2_value",diceA2_value); 375 game.writeEntry("diceA2_value",diceA2_value);
372 game.writeEntry("diceA3_value",diceA3_value); 376 game.writeEntry("diceA3_value",diceA3_value);
373 game.writeEntry("diceA4_value",diceA4_value); 377 game.writeEntry("diceA4_value",diceA4_value);
374 game.writeEntry("diceB1_value",diceB1_value); 378 game.writeEntry("diceB1_value",diceB1_value);
375 game.writeEntry("diceB2_value",diceB3_value); 379 game.writeEntry("diceB2_value",diceB3_value);
376 game.writeEntry("diceB3_value",diceB4_value); 380 game.writeEntry("diceB3_value",diceB4_value);
377 game.writeEntry("diceB4_value",diceB4_value); 381 game.writeEntry("diceB4_value",diceB4_value);
378 game.writeEntry("player",player); 382 game.writeEntry("player",player);
379 game.writeEntry("dice1_played",dice1_played); 383 game.writeEntry("dice1_played",dice1_played);
380 game.writeEntry("dice2_played",dice2_played); 384 game.writeEntry("dice2_played",dice2_played);
381 game.writeEntry("dice3_played",dice3_played); 385 game.writeEntry("dice3_played",dice3_played);
382 game.writeEntry("dice4_played",dice4_played); 386 game.writeEntry("dice4_played",dice4_played);
383 game.writeEntry("dice_rolled",dice_rolled); 387 game.writeEntry("dice_rolled",dice_rolled);
384 game.writeEntry("player1_auto",player1_auto); 388 game.writeEntry("player1_auto",player1_auto);
385 game.writeEntry("player2_auto",player2_auto); 389 game.writeEntry("player2_auto",player2_auto);
386 390
387 game.setGroup("pieces"); 391 game.setGroup("pieces");
388 QString label; 392 QString label;
389 LoadSave save=move->saveGame(); 393 LoadSave save=move->saveGame();
390 for(int a=0;a<28;a++) 394 for(int a=0;a<28;a++)
391 { 395 {
392 label.setNum(a); 396 label.setNum(a);
393 game.writeEntry(label,save.pop[a].total); 397 game.writeEntry(label,save.pop[a].total);
394 } 398 }
395 QMessageBox::information(this,"Backgammon","Game saved","OK"); 399 QMessageBox::information(this,"Backgammon","Game saved","OK");
396} 400}
397 401
398void BackGammon::deletegame() 402void BackGammon::deletegame()
399{ 403{
400 FileDialog* file=new FileDialog(this,"Delete Game",".game"); 404 FileDialog* file=new FileDialog(this,"Delete Game",".game");
401 if(!file->exec()) 405 if(!file->exec())
402 return; 406 return;
403 407
404 game_name=file->filename(); 408 game_name=file->filename();
405 QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; 409 QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game";
406 410
407 if(!QMessageBox::warning(this,"Backgammon","deleted game\n"+game_name+" ?","OK","Cancel")) 411 if(!QMessageBox::warning(this,"Backgammon","deleted game\n"+game_name+" ?","OK","Cancel"))
408 { 412 {
409 QFile(game_file).remove(); 413 QFile(game_file).remove();
410 } 414 }
411} 415}
412 416
413 417
414void BackGammon::newtheme() 418void BackGammon::newtheme()
415{ 419{
416 ThemeDialog* theme=new ThemeDialog(this); 420 ThemeDialog* theme=new ThemeDialog(this);
417 421
418 ImageNames names; 422 ImageNames names;
419 names.theme=theme_name; 423 names.theme=theme_name;
420 names.board=board_name; 424 names.board=board_name;
421 names.pieces1=piecesA_name; 425 names.pieces1=piecesA_name;
422 names.pieces2=piecesB_name; 426 names.pieces2=piecesB_name;
423 names.dice1=diceA_name; 427 names.dice1=diceA_name;
424 names.dice2=diceB_name; 428 names.dice2=diceB_name;
425 names.odds=odds_name; 429 names.odds=odds_name;
426 names.table=table_name; 430 names.table=table_name;
427 431
428 theme->setCurrent(names); 432 theme->setCurrent(names);
429 if(!theme->exec()) 433 if(!theme->exec())
430 return; 434 return;
431 435
432 names=theme->getNames(); 436 names=theme->getNames();
433 theme_name=names.theme; 437 theme_name=names.theme;
434 board_name=names.board; 438 board_name=names.board;
435 piecesA_name=names.pieces1; 439 piecesA_name=names.pieces1;
436 piecesB_name=names.pieces2; 440 piecesB_name=names.pieces2;
437 diceA_name=names.dice1; 441 diceA_name=names.dice1;
438 diceB_name=names.dice2; 442 diceB_name=names.dice2;
439 odds_name=names.odds; 443 odds_name=names.odds;
440 table_name=names.table; 444 table_name=names.table;
441 445
442 applytheme(); 446 applytheme();
443} 447}
444 448
445void BackGammon::loadtheme() 449void BackGammon::loadtheme()
446{ 450{
447 FileDialog* file=new FileDialog(this,"Load Theme",".theme"); 451 FileDialog* file=new FileDialog(this,"Load Theme",".theme");
448 if(!file->exec()) 452 if(!file->exec())
449 return; 453 return;
450 454
451 theme_name=file->filename(); 455 theme_name=file->filename();
452 QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; 456 QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme";
453 457
454 Config theme(theme_file,Config::File); 458 Config theme(theme_file,Config::File);
455 theme.setGroup("theme"); 459 theme.setGroup("theme");
456 board_name=theme.readEntry("board","board_1"); 460 board_name=theme.readEntry("board","board_1");
457 piecesA_name=theme.readEntry("pieces1","pieces_1"); 461 piecesA_name=theme.readEntry("pieces1","pieces_1");
458 piecesB_name=theme.readEntry("pieces2","pieces_2"); 462 piecesB_name=theme.readEntry("pieces2","pieces_2");
459 diceA_name=theme.readEntry("dice1","dice_1"); 463 diceA_name=theme.readEntry("dice1","dice_1");
460 diceB_name=theme.readEntry("dice2","dice_2"); 464 diceB_name=theme.readEntry("dice2","dice_2");
461 table_name=theme.readEntry("table","table_1"); 465 table_name=theme.readEntry("table","table_1");
462 odds_name=theme.readEntry("odds","odds_1"); 466 odds_name=theme.readEntry("odds","odds_1");
463 467
464 applytheme(); 468 applytheme();
465 469
466} 470}
467 471
468void BackGammon::savetheme() 472void BackGammon::savetheme()
469{ 473{
470 if(theme_name=="default") 474 if(theme_name=="default")
471 { 475 {
472 QMessageBox::information(this,"Backgammon","Sorry\nCannot overwrite default.theme","OK"); 476 QMessageBox::information(this,"Backgammon","Sorry\nCannot overwrite default.theme","OK");
473 return; 477 return;
474 } 478 }
475 QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; 479 QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme";
476 if(QMessageBox::information(this,"Backgammon","Save Theme\n"+theme_name,"Yes","No")) 480 if(QMessageBox::information(this,"Backgammon","Save Theme\n"+theme_name,"Yes","No"))
477 return; 481 return;
478 482
479 Config theme(theme_file,Config::File); 483 Config theme(theme_file,Config::File);
480 theme.setGroup("theme"); 484 theme.setGroup("theme");
481 theme.writeEntry("board",board_name); 485 theme.writeEntry("board",board_name);
482 theme.writeEntry("pieces1",piecesA_name); 486 theme.writeEntry("pieces1",piecesA_name);
483 theme.writeEntry("pieces2",piecesB_name); 487 theme.writeEntry("pieces2",piecesB_name);
484 theme.writeEntry("dice1",diceA_name); 488 theme.writeEntry("dice1",diceA_name);
485 theme.writeEntry("dice2",diceB_name); 489 theme.writeEntry("dice2",diceB_name);
486 theme.writeEntry("table",table_name); 490 theme.writeEntry("table",table_name);
487 theme.writeEntry("odds",odds_name); 491 theme.writeEntry("odds",odds_name);
488 492
489} 493}
490 494
491void BackGammon::themedefault() 495void BackGammon::themedefault()
492{ 496{
493 if(QMessageBox::information(this,"Backgammon","Make Theme\n"+theme_name+"\nthe default theme","Yes","No")) 497 if(QMessageBox::information(this,"Backgammon","Make Theme\n"+theme_name+"\nthe default theme","Yes","No"))
494 return; 498 return;
495 499
496 Config conf("backgammon"); 500 Config conf("backgammon");
497 conf.setGroup("general"); 501 conf.setGroup("general");
498 conf.writeEntry("theme",theme_name); 502 conf.writeEntry("theme",theme_name);
499} 503}
500 504
501void BackGammon::deletetheme() 505void BackGammon::deletetheme()
502{ 506{
503 FileDialog* file=new FileDialog(this,"Delete Theme",".theme"); 507 FileDialog* file=new FileDialog(this,"Delete Theme",".theme");
504 if(!file->exec()) 508 if(!file->exec())
505 return; 509 return;
506 510
507 theme_name=file->filename(); 511 theme_name=file->filename();
508 QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; 512 QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme";
509 513
510 if(!QMessageBox::warning(this,tr( "Backgammon" ),tr( "deleted theme %1?").arg(theme_name),tr( "OK" ),tr( "Cancel" ))) 514 if(!QMessageBox::warning(this,tr( "Backgammon" ),tr( "deleted theme %1?").arg(theme_name),tr( "OK" ),tr( "Cancel" )))
511 { 515 {
512 QFile(theme_file).remove(); 516 QFile(theme_file).remove();
513 } 517 }
514} 518}
515 519
516void BackGammon::modify_AI() 520void BackGammon::modify_AI()
517{ 521{
518 AI_Dialog* ai_mod=new AI_Dialog(this,tr( "Load Theme" ),".theme"); 522 AI_Dialog* ai_mod=new AI_Dialog(this,tr( "Load Theme" ),".theme");
519 ai_mod->setAISettings(move->getAISettings()); 523 ai_mod->setAISettings(move->getAISettings());
520 if(!ai_mod->exec()) 524 if(!ai_mod->exec())
521 return; 525 return;
522 526
523 //get the AI settings 527 //get the AI settings
524 AISettings ai=ai_mod->getAISettings(); 528 AISettings ai=ai_mod->getAISettings();
525 move->setAISettings(ai); 529 move->setAISettings(ai);
526 //write new settings to conf file 530 //write new settings to conf file
527 Config conf("backgammon"); 531 Config conf("backgammon");
528 conf.setGroup("ai"); 532 conf.setGroup("ai");
529 conf.writeEntry("rescue",ai.rescue); 533 conf.writeEntry("rescue",ai.rescue);
530 conf.writeEntry("eliminate",ai.eliminate); 534 conf.writeEntry("eliminate",ai.eliminate);
531 conf.writeEntry("expose",ai.expose); 535 conf.writeEntry("expose",ai.expose);
532 conf.writeEntry("protect",ai.protect); 536 conf.writeEntry("protect",ai.protect);
533 conf.writeEntry("safe",ai.safe); 537 conf.writeEntry("safe",ai.safe);
534 conf.writeEntry("empty",ai.empty); 538 conf.writeEntry("empty",ai.empty);
535} 539}
536 540
537void BackGammon::setrules() 541void BackGammon::setrules()
538{ 542{
539 RulesDialog* rulesdialog=new RulesDialog(this,tr( "Load Theme" ),".theme"); 543 RulesDialog* rulesdialog=new RulesDialog(this,tr( "Load Theme" ),".theme");
540 rulesdialog->setRules(rules); 544 rulesdialog->setRules(rules);
541 if(!rulesdialog->exec()) 545 if(!rulesdialog->exec())
542 return; 546 return;
543 rules=rulesdialog->getRules(); 547 rules=rulesdialog->getRules();
544 Config conf("backgammon"); 548 Config conf("backgammon");
545 conf.setGroup("rules"); 549 conf.setGroup("rules");
546 conf.writeEntry("move_with_pieces_out",rules.move_with_pieces_out); 550 conf.writeEntry("move_with_pieces_out",rules.move_with_pieces_out);
547 conf.writeEntry("nice_dice",rules.generous_dice); 551 conf.writeEntry("nice_dice",rules.generous_dice);
548 move->setRules(rules); 552 move->setRules(rules);
549} 553}
550 554
551 555
552void BackGammon::draw() 556void BackGammon::draw()
553{ 557{
554 Pieces pieces; 558 Pieces pieces;
555 move->position(pieces); 559 move->position(pieces);
556 for(int a=0;a<15;a++) 560 for(int a=0;a<15;a++)
557 { 561 {
558 if(!pieces.player1[a].side) 562 if(!pieces.player1[a].side)
559 { 563 {
560 p1[a]->setX(pieces.player1[a].x); 564 p1[a]->setX(pieces.player1[a].x);
561 p1[a]->setY(pieces.player1[a].y); 565 p1[a]->setY(pieces.player1[a].y);
562 p1[a]->setZ(pieces.player1[a].z); 566 p1[a]->setZ(pieces.player1[a].z);
563 p1[a]->show(); 567 p1[a]->show();
564 p1_side[a]->hide(); 568 p1_side[a]->hide();
565 } 569 }
566 else 570 else
567 { 571 {
568 p1_side[a]->setX(pieces.player1[a].x); 572 p1_side[a]->setX(pieces.player1[a].x);
569 p1_side[a]->setY(pieces.player1[a].y); 573 p1_side[a]->setY(pieces.player1[a].y);
570 p1_side[a]->setZ(pieces.player1[a].z); 574 p1_side[a]->setZ(pieces.player1[a].z);
571 p1_side[a]->show(); 575 p1_side[a]->show();
572 p1[a]->hide(); 576 p1[a]->hide();
573 } 577 }
574 578
575 if(!pieces.player2[a].side) 579 if(!pieces.player2[a].side)
576 { 580 {
577 p2[a]->setX(pieces.player2[a].x); 581 p2[a]->setX(pieces.player2[a].x);
578 p2[a]->setY(pieces.player2[a].y); 582 p2[a]->setY(pieces.player2[a].y);
579 p2[a]->setZ(pieces.player2[a].z); 583 p2[a]->setZ(pieces.player2[a].z);
580 p2[a]->show(); 584 p2[a]->show();
581 p2_side[a]->hide(); 585 p2_side[a]->hide();
582 } 586 }
583 else 587 else
584 { 588 {
585 p2_side[a]->setX(pieces.player2[a].x); 589 p2_side[a]->setX(pieces.player2[a].x);
586 p2_side[a]->setY(pieces.player2[a].y); 590 p2_side[a]->setY(pieces.player2[a].y);
587 p2_side[a]->setZ(pieces.player2[a].z); 591 p2_side[a]->setZ(pieces.player2[a].z);
588 p2_side[a]->show(); 592 p2_side[a]->show();
589 p2[a]->hide(); 593 p2[a]->hide();
590 } 594 }
591 } 595 }
592} 596}
593 597
594void BackGammon::mouse(int x,int y) 598void BackGammon::mouse(int x,int y)
595{ 599{
596 if(gameFinished) 600 if(gameFinished)
597 { 601 {
598 newgame(); 602 newgame();
599 return; 603 return;
600 } 604 }
601 if(y<=200) //move pieces 605 if(y<=200) //move pieces
602 { 606 {
603 if((player==1 && player1_auto) || (player==2 && player2_auto)) 607 if((player==1 && player1_auto) || (player==2 && player2_auto))
604 return; 608 return;
605 609
606 Marker marker; 610 Marker marker;
607 611
608 move->boardpressed(x,y,marker); 612 move->boardpressed(x,y,marker);
609 if(marker.visible_current) 613 if(marker.visible_current)
610 { 614 {
611 marker_current->setX(marker.x_current); 615 marker_current->setX(marker.x_current);
612 marker_current->setY(marker.y_current); 616 marker_current->setY(marker.y_current);
613 marker_current->show(); 617 marker_current->show();
614 } 618 }
615 else 619 else
616 { 620 {
617 marker_current->hide(); 621 marker_current->hide();
618 } 622 }
619 623
620 for(int a=0;a<4;a++) 624 for(int a=0;a<4;a++)
621 { 625 {
622 if(marker.visible_next[a]) 626 if(marker.visible_next[a])
623 { 627 {
624 marker_next[a]->setX(marker.x_next[a]); 628 marker_next[a]->setX(marker.x_next[a]);
625 marker_next[a]->setY(marker.y_next[a]); 629 marker_next[a]->setY(marker.y_next[a]);
626 marker_next[a]->show(); 630 marker_next[a]->show();
627 } 631 }
628 else 632 else
629 { 633 {
630 marker_next[a]->hide(); 634 marker_next[a]->hide();
631 } 635 }
632 } 636 }
633 area->update(); 637 area->update();
634 } 638 }
635 else //roll dice 639 else //roll dice
636 { 640 {
637 if(x>=10 && x<=65 && player==1 && !dice_rolled) 641 if(x>=10 && x<=65 && player==1 && !dice_rolled)
638 { 642 {
639 dice1_played=false; 643 dice1_played=false;
640 dice2_played=false; 644 dice2_played=false;
641 dice3_played=false; 645 dice3_played=false;
642 dice4_played=false; 646 dice4_played=false;
643 dice_rolled=true; 647 dice_rolled=true;
644 srand(QTime::currentTime().msec()); 648 srand(QTime::currentTime().msec());
645 diceA1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); 649 diceA1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0));
646 diceA2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); 650 diceA2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0));
647 if(diceA1_value==diceA2_value) 651 if(diceA1_value==diceA2_value)
648 { 652 {
649 diceA3_value=diceA1_value; 653 diceA3_value=diceA1_value;
650 diceA4_value=diceA1_value; 654 diceA4_value=diceA1_value;
651 } 655 }
652 else 656 else
653 { 657 {
654 diceA3_value=7; 658 diceA3_value=7;
655 dice3_played=true; 659 dice3_played=true;
656 diceA4_value=7; 660 diceA4_value=7;
657 dice4_played=true; 661 dice4_played=true;
658 } 662 }
659 showdice(); 663 showdice();
660 area->update(); 664 area->update();
661 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); 665 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
662 666
663 } 667 }
664 else if(x>=160 && x<=225 && player==2 && !dice_rolled) 668 else if(x>=160 && x<=225 && player==2 && !dice_rolled)
665 { 669 {
666 dice1_played=false; 670 dice1_played=false;
667 dice2_played=false; 671 dice2_played=false;
668 dice3_played=false; 672 dice3_played=false;
669 dice4_played=false; 673 dice4_played=false;
670 dice_rolled=true; 674 dice_rolled=true;
671 srand(QTime::currentTime().msec()); 675 srand(QTime::currentTime().msec());
672 diceB1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); 676 diceB1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0));
673 diceB2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); 677 diceB2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0));
674 if(diceB1_value==diceB2_value) 678 if(diceB1_value==diceB2_value)
675 { 679 {
676 diceB3_value=diceB1_value; 680 diceB3_value=diceB1_value;
677 diceB4_value=diceB1_value; 681 diceB4_value=diceB1_value;
678 } 682 }
679 else 683 else
680 { 684 {
681 diceB3_value=7; 685 diceB3_value=7;
682 dice3_played=true; 686 dice3_played=true;
683 diceB4_value=7; 687 diceB4_value=7;
684 dice4_played=true; 688 dice4_played=true;
685 } 689 }
686 showdice(); 690 showdice();
687 area->update(); 691 area->update();
688 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); 692 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
689 } 693 }
690 } 694 }
691} 695}
692 696
693void BackGammon::done_dice1() 697void BackGammon::done_dice1()
694{ 698{
695 dice1_played=true; 699 dice1_played=true;
696 if(player==1) 700 if(player==1)
697 diceA1_value=7; 701 diceA1_value=7;
698 else 702 else
699 diceB1_value=7; 703 diceB1_value=7;
700 setplayer(); 704 setplayer();
701 showdice(); 705 showdice();
702 draw(); 706 draw();
703 area->update(); 707 area->update();
704 if(!dice2_played || !dice3_played || !dice4_played) 708 if(!dice2_played || !dice3_played || !dice4_played)
705 { 709 {
706 if(player==1) 710 if(player==1)
707 { 711 {
708 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); 712 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
709 } 713 }
710 else 714 else
711 { 715 {
712 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); 716 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
713 } 717 }
714 } 718 }
715} 719}
716 720
717void BackGammon::done_dice2() 721void BackGammon::done_dice2()
718{ 722{
719 dice2_played=true; 723 dice2_played=true;
720 if(player==1) 724 if(player==1)
721 diceA2_value=7; 725 diceA2_value=7;
722 else 726 else
723 diceB2_value=7; 727 diceB2_value=7;
724 setplayer(); 728 setplayer();
725 showdice(); 729 showdice();
726 draw(); 730 draw();
727 area->update(); 731 area->update();
728 if(!dice1_played || !dice3_played || !dice4_played) 732 if(!dice1_played || !dice3_played || !dice4_played)
729 { 733 {
730 if(player==1) 734 if(player==1)
731 { 735 {
732 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); 736 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
733 } 737 }
734 else 738 else
735 { 739 {
736 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); 740 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
737 } 741 }
738 } 742 }
739} 743}
740 744
741 745
742void BackGammon::done_dice3() 746void BackGammon::done_dice3()
743{ 747{
744 dice3_played=true; 748 dice3_played=true;
745 if(player==1) 749 if(player==1)
746 diceA3_value=7; 750 diceA3_value=7;
747 else 751 else
748 diceB3_value=7; 752 diceB3_value=7;
749 setplayer(); 753 setplayer();
750 showdice(); 754 showdice();
751 draw(); 755 draw();
752 area->update(); 756 area->update();
753 if(!dice1_played || !dice2_played || !dice4_played) 757 if(!dice1_played || !dice2_played || !dice4_played)
754 { 758 {
755 if(player==1) 759 if(player==1)
756 { 760 {
757 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); 761 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
758 } 762 }
759 else 763 else
760 { 764 {
761 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); 765 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
762 } 766 }
763 } 767 }
764} 768}
765 769
766 770
767void BackGammon::done_dice4() 771void BackGammon::done_dice4()
768{ 772{
769 dice4_played=true; 773 dice4_played=true;
770 if(player==1) 774 if(player==1)
771 diceA4_value=7; 775 diceA4_value=7;
772 else 776 else
773 diceB4_value=7; 777 diceB4_value=7;
774 setplayer(); 778 setplayer();
775 showdice(); 779 showdice();
776 draw(); 780 draw();
777 area->update(); 781 area->update();
778 if(!dice1_played || !dice2_played || !dice3_played) 782 if(!dice1_played || !dice2_played || !dice3_played)
779 { 783 {
780 if(player==1) 784 if(player==1)
781 { 785 {
782 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); 786 move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
783 } 787 }
784 else 788 else
785 { 789 {
786 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); 790 move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
787 } 791 }
788 } 792 }
789} 793}
790 794
791 795
792void BackGammon::nomove() 796void BackGammon::nomove()
793{ 797{
794 if(player==1) 798 if(player==1)
795 nomove_marker->setX(0); 799 nomove_marker->setX(0);
796 else 800 else
797 nomove_marker->setX(170); 801 nomove_marker->setX(170);
798 nomove_marker->show(); 802 nomove_marker->show();
799 message->setText(tr( "<b>no move</b>" )); 803 message->setText(tr( "<b>no move</b>" ));
800 dice1_played=true; 804 dice1_played=true;
801 dice2_played=true; 805 dice2_played=true;
802 dice3_played=true; 806 dice3_played=true;
803 dice4_played=true; 807 dice4_played=true;
804 if(player==1) 808 if(player==1)
805 { 809 {
806 diceA1_value=7; 810 diceA1_value=7;
807 diceA2_value=7; 811 diceA2_value=7;
808 diceA3_value=7; 812 diceA3_value=7;
809 diceA4_value=7; 813 diceA4_value=7;
810 } 814 }
811 else 815 else
812 { 816 {
813 diceB1_value=7; 817 diceB1_value=7;
814 diceB2_value=7; 818 diceB2_value=7;
815 diceB3_value=7; 819 diceB3_value=7;
816 diceB4_value=7; 820 diceB4_value=7;
817 } 821 }
818 area->update(); 822 area->update();
819 QTimer::singleShot(2000,this,SLOT(nomove2())); 823 QTimer::singleShot(2000,this,SLOT(nomove2()));
820} 824}
821 825
822void BackGammon::nomove2() 826void BackGammon::nomove2()
823{ 827{
824 nomove_marker->hide(); 828 nomove_marker->hide();
825 setplayer(); 829 setplayer();
826 showdice(); 830 showdice();
827 draw(); 831 draw();
828 area->update(); 832 area->update();
829} 833}
830 834
831void BackGammon::finished(int theplayer) 835void BackGammon::finished(int theplayer)
832{ 836{
833 nomove_marker->hide(); 837 nomove_marker->hide();
834 if(theplayer==1) 838 if(theplayer==1)
835 message->setText(tr( "<b>Player 1 wins. Click on board for new game.</b>" )); 839 message->setText(tr( "<b>Player 1 wins. Click on board for new game.</b>" ));
836 else 840 else
837 message->setText(tr( "<b>Player 2 wins. Click on board for new game.</b>" )); 841 message->setText(tr( "<b>Player 2 wins. Click on board for new game.</b>" ));
838 diceA1_value=7; 842 diceA1_value=7;
839 diceA2_value=7; 843 diceA2_value=7;
840 diceB1_value=7; 844 diceB1_value=7;
841 diceB2_value=7; 845 diceB2_value=7;
842 player=0; 846 player=0;
843 showdice(); 847 showdice();
844 draw(); 848 draw();
845 area->update(); 849 area->update();
846 gameFinished=true; 850 gameFinished=true;
847} 851}
848 852
849void BackGammon::showdice() 853void BackGammon::showdice()
850{ 854{
851 int value_diceA1=diceA1_value-1; 855 int value_diceA1=diceA1_value-1;
852 if(diceA1_value==7 && diceA3_value!=7) 856 if(diceA1_value==7 && diceA3_value!=7)
853 value_diceA1=diceA3_value-1; 857 value_diceA1=diceA3_value-1;
854 858
855 int value_diceA2=diceA2_value-1; 859 int value_diceA2=diceA2_value-1;
856 if(diceA2_value==7 && diceA4_value!=7) 860 if(diceA2_value==7 && diceA4_value!=7)
857 value_diceA2=diceA4_value-1; 861 value_diceA2=diceA4_value-1;
858 862
859 int value_diceB1=diceB1_value-1; 863 int value_diceB1=diceB1_value-1;
860 if(diceB1_value==7 && diceB3_value!=7) 864 if(diceB1_value==7 && diceB3_value!=7)
861 value_diceB1=diceB3_value-1; 865 value_diceB1=diceB3_value-1;
862 866
863 int value_diceB2=diceB2_value-1; 867 int value_diceB2=diceB2_value-1;
864 if(diceB2_value==7 && diceB4_value!=7) 868 if(diceB2_value==7 && diceB4_value!=7)
865 value_diceB2=diceB4_value-1; 869 value_diceB2=diceB4_value-1;
866 870
867 for(int index=0;index<7;index++) 871 for(int index=0;index<7;index++)
868 { 872 {
869 if(value_diceA1==index) 873 if(value_diceA1==index)
870 diceA1[index]->show(); 874 diceA1[index]->show();
871 else 875 else
872 diceA1[index]->hide(); 876 diceA1[index]->hide();
873 877
874 if(value_diceA2==index) 878 if(value_diceA2==index)
875 diceA2[index]->show(); 879 diceA2[index]->show();
876 else 880 else
877 diceA2[index]->hide(); 881 diceA2[index]->hide();
878 882
879 if(value_diceB1==index) 883 if(value_diceB1==index)
880 diceB1[index]->show(); 884 diceB1[index]->show();
881 else 885 else
882 diceB1[index]->hide(); 886 diceB1[index]->hide();
883 887
884 if(value_diceB2==index) 888 if(value_diceB2==index)
885 diceB2[index]->show(); 889 diceB2[index]->show();
886 else 890 else
887 diceB2[index]->hide(); 891 diceB2[index]->hide();
888 } 892 }
889} 893}
890 894
891void BackGammon::setplayer() 895void BackGammon::setplayer()
892{ 896{
893 if(dice1_played && dice2_played && dice3_played && dice4_played && player==1) 897 if(dice1_played && dice2_played && dice3_played && dice4_played && player==1)
894 { 898 {
895 message->setText(tr( "<b>P2 turn</b>", "P means player" )); 899 message->setText(tr( "<b>P2 turn</b>", "P means player" ));
896 dice_rolled=false; 900 dice_rolled=false;
897 player=2; 901 player=2;
898 if(player2_auto) 902 if(player2_auto)
899 QTimer::singleShot(2000,this,SLOT(autoroll_dice2())); 903 QTimer::singleShot(2000,this,SLOT(autoroll_dice2()));
900 } 904 }
901 else if(dice1_played && dice2_played && dice3_played && dice4_played && player==2) 905 else if(dice1_played && dice2_played && dice3_played && dice4_played && player==2)
902 { 906 {
903 message->setText(tr( "<b>P1 turn</b>", "P means player" )); 907 message->setText(tr( "<b>P1 turn</b>", "P means player" ));
904 dice_rolled=false; 908 dice_rolled=false;
905 player=1; 909 player=1;
906 if(player1_auto) 910 if(player1_auto)
907 QTimer::singleShot(2000,this,SLOT(autoroll_dice1())); 911 QTimer::singleShot(2000,this,SLOT(autoroll_dice1()));
908 } 912 }
909} 913}
910 914
911void BackGammon::autoroll_dice1() 915void BackGammon::autoroll_dice1()
912{ 916{
913 mouse(20,210); 917 mouse(20,210);
914} 918}
915 919
916void BackGammon::autoroll_dice2() 920void BackGammon::autoroll_dice2()
917{ 921{
918 mouse(170,210); 922 mouse(170,210);
919} 923}
920 924
921void BackGammon::applytheme() 925void BackGammon::applytheme()
922{ 926{
923 QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name)); 927 QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name));
924 board->setImage(boardbg); 928 board->setImage(boardbg);
925 929
926 QImage tablebg(Resource::loadImage("backgammon/table/"+table_name)); 930 QImage tablebg(Resource::loadImage("backgammon/table/"+table_name));
927 table->setImage(tablebg); 931 table->setImage(tablebg);
928 932
929 QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name)); 933 QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name));
930 QImage piece_1_front=piece_1_all.copy(0,0,15,15); 934 QImage piece_1_front=piece_1_all.copy(0,0,15,15);
931 QImage piece_1_side=piece_1_all.copy(0,15,15,5); 935 QImage piece_1_side=piece_1_all.copy(0,15,15,5);
932 936
933 QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name)); 937 QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name));
934 QImage piece_2_front=piece_2_all.copy(0,0,15,15); 938 QImage piece_2_front=piece_2_all.copy(0,0,15,15);
935 QImage piece_2_side=piece_2_all.copy(0,15,15,5); 939 QImage piece_2_side=piece_2_all.copy(0,15,15,5);
936 940
937 int a=0; 941 int a=0;
938 for(a=0;a<15;a++) 942 for(a=0;a<15;a++)
939 { 943 {
940 p1[a]->setImage(piece_1_front); 944 p1[a]->setImage(piece_1_front);
941 p1_side[a]->setImage(piece_1_side); 945 p1_side[a]->setImage(piece_1_side);
942 946
943 p2[a]->setImage(piece_2_front); 947 p2[a]->setImage(piece_2_front);
944 p2_side[a]->setImage(piece_2_side); 948 p2_side[a]->setImage(piece_2_side);
945 } 949 }
946 draw(); 950 draw();
947 951
948 QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name)); 952 QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name));
949 QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name)); 953 QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name));
950 QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name)); 954 QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name));
951 955
952 for(a=0;a<7;a++) 956 for(a=0;a<7;a++)
953 { 957 {
954 QImage dicebgA=dicebgA_all.copy(a*25,0,25,25); 958 QImage dicebgA=dicebgA_all.copy(a*25,0,25,25);
955 diceA1[a]->setImage(dicebgA); 959 diceA1[a]->setImage(dicebgA);
956 diceA2[a]->setImage(dicebgA); 960 diceA2[a]->setImage(dicebgA);
957 961
958 QImage dicebgB=dicebgB_all.copy(a*25,0,25,25); 962 QImage dicebgB=dicebgB_all.copy(a*25,0,25,25);
959 diceB1[a]->setImage(dicebgB); 963 diceB1[a]->setImage(dicebgB);
960 diceB2[a]->setImage(dicebgB); 964 diceB2[a]->setImage(dicebgB);
961 /* 965 /*
962 if(a<6) 966 if(a<6)
963 { 967 {
964 QImage oddsbg=oddsbg_all.copy(a*15,0,15,15); 968 QImage oddsbg=oddsbg_all.copy(a*15,0,15,15);
965 oddsDice[a]->setImage(oddsbg); 969 oddsDice[a]->setImage(oddsbg);
966 } 970 }
967 */ 971 */
968 } 972 }
969} 973}
970 974
971 975
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
@@ -1,557 +1,557 @@
1#include "moveengine.h" 1#include "moveengine.h"
2 2
3#include <qtimer.h> 3#include <qtimer.h>
4#include <stdlib.h> 4#include <stdlib.h>
5 5
6MoveEngine::MoveEngine() 6MoveEngine::MoveEngine()
7 : QObject() 7 : QObject()
8{ 8{
9 int offset=7; 9 int offset=7;
10 int a=0; //counter variable 10 int a=0; //counter variable
11 int xfill[]={210,185,170,155,140,125,110,85,70,55,40,25,10,10,25,40,55,70,85,110,125,140,155,170,185,210}; 11 int xfill[]={210,185,170,155,140,125,110,85,70,55,40,25,10,10,25,40,55,70,85,110,125,140,155,170,185,210};
12 for(a=0;a<26;a++) 12 for(a=0;a<26;a++)
13 { 13 {
14 x_coord[a]=xfill[a]; 14 x_coord[a]=xfill[a];
15 } 15 }
16 16
17 int yfill[]={10,25,40,55,70,10+offset,25+offset,40+offset,55+offset,25,40,55, 25+offset,40+offset,40}; 17 int yfill[]={10,25,40,55,70,10+offset,25+offset,40+offset,55+offset,25,40,55, 25+offset,40+offset,40};
18 int zfill[]={1,1,1,1,1,2,2,2,2,3,3,3,4,4,5}; 18 int zfill[]={1,1,1,1,1,2,2,2,2,3,3,3,4,4,5};
19 for(a=0;a<15;a++) 19 for(a=0;a<15;a++)
20 { 20 {
21 yup_coord[a]=yfill[a]; 21 yup_coord[a]=yfill[a];
22 ylow_coord[a]=185-(yfill[a]); 22 ylow_coord[a]=185-(yfill[a]);
23 z_coord[a]=zfill[a]; 23 z_coord[a]=zfill[a];
24 } 24 }
25 for(a=0;a<5;a++) 25 for(a=0;a<5;a++)
26 { 26 {
27 if(a<3) 27 if(a<3)
28 { 28 {
29 x_fin1[a]=65+a*15; 29 x_fin1[a]=65+a*15;
30 x_fin2[a]=155-a*15; 30 x_fin2[a]=155-a*15;
31 } 31 }
32 y_fin[a]=225-a*5; 32 y_fin[a]=225-a*5;
33 } 33 }
34 z_fin=1; 34 z_fin=1;
35 35
36 reset(); 36 reset();
37} 37}
38 38
39MoveEngine::~MoveEngine() 39MoveEngine::~MoveEngine()
40{} 40{}
41 41
42void MoveEngine::position(Pieces& pieces,bool non_qte) 42void MoveEngine::position(Pieces& pieces,bool non_qte)
43{ 43{
44 int player1_counter=0; 44 int player1_counter=0;
45 int player2_counter=0; 45 int player2_counter=0;
46 46
47 //non qte styles are smaller !! 47 //non qte styles are smaller !!
48 int offset=(non_qte) ? 5 : 0; 48 int offset=(non_qte) ? 5 : 0;
49 49
50 for(int a=0;a<28;a++) 50 for(int a=0;a<28;a++)
51 { 51 {
52 for(int b=0;b<abs(population[a].total);b++) 52 for(int b=0;b<abs(population[a].total);b++)
53 { 53 {
54 if(population[a].total>0) //player 1 pieces 54 if(population[a].total>0) //player 1 pieces
55 { 55 {
56 pieces.player1[player1_counter].x=x_coord[a]-offset; 56 pieces.player1[player1_counter].x=x_coord[a]-offset;
57 if(a>=0 && a<13) 57 if(a>=0 && a<13)
58 { 58 {
59 pieces.player1[player1_counter].y=yup_coord[b]-offset; 59 pieces.player1[player1_counter].y=yup_coord[b]-offset;
60 pieces.player1[player1_counter].z=z_coord[b]; 60 pieces.player1[player1_counter].z=z_coord[b];
61 pieces.player1[player1_counter].side=false; 61 pieces.player1[player1_counter].side=false;
62 player1_counter++; 62 player1_counter++;
63 } 63 }
64 else if(a>12 && a<26) 64 else if(a>12 && a<26)
65 { 65 {
66 pieces.player1[player1_counter].y=ylow_coord[b]-offset; 66 pieces.player1[player1_counter].y=ylow_coord[b]-offset;
67 pieces.player1[player1_counter].z=z_coord[b]; 67 pieces.player1[player1_counter].z=z_coord[b];
68 pieces.player1[player1_counter].side=false; 68 pieces.player1[player1_counter].side=false;
69 player1_counter++; 69 player1_counter++;
70 } 70 }
71 else if(a==26) 71 else if(a==26)
72 { 72 {
73 if(b<5) 73 if(b<5)
74 { 74 {
75 pieces.player1[player1_counter].x=x_fin1[0]-offset; 75 pieces.player1[player1_counter].x=x_fin1[0]-offset;
76 pieces.player1[player1_counter].y=y_fin[b]-offset; 76 pieces.player1[player1_counter].y=y_fin[b]-offset;
77 pieces.player1[player1_counter].z=z_fin; 77 pieces.player1[player1_counter].z=z_fin;
78 } 78 }
79 else if(b>=5 && b<10) 79 else if(b>=5 && b<10)
80 { 80 {
81 pieces.player1[player1_counter].x=x_fin1[1]-offset; 81 pieces.player1[player1_counter].x=x_fin1[1]-offset;
82 pieces.player1[player1_counter].y=y_fin[b-5]-offset; 82 pieces.player1[player1_counter].y=y_fin[b-5]-offset;
83 pieces.player1[player1_counter].z=z_fin; 83 pieces.player1[player1_counter].z=z_fin;
84 } 84 }
85 else 85 else
86 { 86 {
87 pieces.player1[player1_counter].x=x_fin1[2]-offset; 87 pieces.player1[player1_counter].x=x_fin1[2]-offset;
88 pieces.player1[player1_counter].y=y_fin[b-10]-offset; 88 pieces.player1[player1_counter].y=y_fin[b-10]-offset;
89 pieces.player1[player1_counter].z=z_fin; 89 pieces.player1[player1_counter].z=z_fin;
90 } 90 }
91 pieces.player1[player1_counter].side=true; 91 pieces.player1[player1_counter].side=true;
92 player1_counter++; 92 player1_counter++;
93 93
94 } 94 }
95 } 95 }
96 96
97 else if(population[a].total<0) //player 2 pieces 97 else if(population[a].total<0) //player 2 pieces
98 { 98 {
99 pieces.player2[player2_counter].x=x_coord[a]-offset; 99 pieces.player2[player2_counter].x=x_coord[a]-offset;
100 if(a>=0 && a<13) 100 if(a>=0 && a<13)
101 { 101 {
102 pieces.player2[player2_counter].y=yup_coord[b]-offset; 102 pieces.player2[player2_counter].y=yup_coord[b]-offset;
103 pieces.player2[player2_counter].z=z_coord[b]; 103 pieces.player2[player2_counter].z=z_coord[b];
104 pieces.player2[player2_counter].side=false; 104 pieces.player2[player2_counter].side=false;
105 player2_counter++; 105 player2_counter++;
106 } 106 }
107 else if(a>12 && a<26) 107 else if(a>12 && a<26)
108 { 108 {
109 pieces.player2[player2_counter].y=ylow_coord[b]-offset; 109 pieces.player2[player2_counter].y=ylow_coord[b]-offset;
110 pieces.player2[player2_counter].z=z_coord[b]; 110 pieces.player2[player2_counter].z=z_coord[b];
111 pieces.player2[player2_counter].side=false; 111 pieces.player2[player2_counter].side=false;
112 player2_counter++; 112 player2_counter++;
113 } 113 }
114 else if(a==27) 114 else if(a==27)
115 { 115 {
116 if(b<5) 116 if(b<5)
117 { 117 {
118 pieces.player2[player2_counter].x=x_fin2[0]-offset; 118 pieces.player2[player2_counter].x=x_fin2[0]-offset;
119 pieces.player2[player2_counter].y=y_fin[b]-offset; 119 pieces.player2[player2_counter].y=y_fin[b]-offset;
120 pieces.player2[player2_counter].z=z_fin; 120 pieces.player2[player2_counter].z=z_fin;
121 } 121 }
122 else if(b>=5 && b<10) 122 else if(b>=5 && b<10)
123 { 123 {
124 pieces.player2[player2_counter].x=x_fin2[1]-offset; 124 pieces.player2[player2_counter].x=x_fin2[1]-offset;
125 pieces.player2[player2_counter].y=y_fin[b-5]-offset; 125 pieces.player2[player2_counter].y=y_fin[b-5]-offset;
126 pieces.player2[player2_counter].z=z_fin; 126 pieces.player2[player2_counter].z=z_fin;
127 } 127 }
128 else 128 else
129 { 129 {
130 pieces.player2[player2_counter].x=x_fin2[2]-offset; 130 pieces.player2[player2_counter].x=x_fin2[2]-offset;
131 pieces.player2[player2_counter].y=y_fin[b-10]-offset; 131 pieces.player2[player2_counter].y=y_fin[b-10]-offset;
132 pieces.player2[player2_counter].z=z_fin; 132 pieces.player2[player2_counter].z=z_fin;
133 } 133 }
134 pieces.player2[player2_counter].side=true; 134 pieces.player2[player2_counter].side=true;
135 player2_counter++; 135 player2_counter++;
136 136
137 } 137 }
138 } 138 }
139 } 139 }
140 } 140 }
141} 141}
142 142
143void MoveEngine::diceroll(const int& newplayer,const int& face1,const int& face2,const int& face3,const int& face4,bool computer) 143void MoveEngine::diceroll(const int& newplayer,const int& face1,const int& face2,const int& face3,const int& face4,bool computer)
144{ 144{
145 checkstate(); 145 checkstate();
146 player=newplayer; 146 player=newplayer;
147 otherplayer=(player==1) ? 2 : 1; 147 otherplayer=(player==1) ? 2 : 1;
148 dice[0]=face1; 148 dice[0]=face1;
149 dice[1]=face2; 149 dice[1]=face2;
150 dice[2]=face3; 150 dice[2]=face3;
151 dice[3]=face4; 151 dice[3]=face4;
152 marker_current=-1; 152 marker_current=-1;
153 if(getPossibleMoves()==0) 153 if(getPossibleMoves()==0)
154 { 154 {
155 emit nomove(); 155 emit nomove();
156 return; // player will be changed 156 return; // player will be changed
157 } 157 }
158 if(!computer) 158 if(!computer)
159 return; //human intervention required 159 return; //human intervention required
160 160
161 QTimer::singleShot(2000,this,SLOT(automove())); 161 QTimer::singleShot(2000,this,SLOT(automove()));
162} 162}
163 163
164 164
165void MoveEngine::automove() 165void MoveEngine::automove()
166{ 166{
167 //the maximimum possibility 167 //the maximimum possibility
168 int maxpos=0; 168 int maxpos=0;
169 //the position in the moves array 169 //the position in the moves array
170 int from=-1; 170 int from=-1;
171 int to=-1; 171 int to=-1;
172 //dice1 or dice 2 ?? 172 //dice1 or dice 2 ??
173 int index_dice=0; 173 int index_dice=0;
174 for(int counter=0;counter<26;counter++) 174 for(int counter=0;counter<26;counter++)
175 { 175 {
176 int a=(player==1) ? counter : 25-counter; 176 int a=(player==1) ? counter : 25-counter;
177 for(int b=0;b<4;b++) 177 for(int b=0;b<4;b++)
178 { 178 {
179 if(moves[a].weight[b]>maxpos) 179 if(moves[a].weight[b]>maxpos)
180 { 180 {
181 maxpos=moves[a].weight[b]; 181 maxpos=moves[a].weight[b];
182 from=a; 182 from=a;
183 to=moves[a].to[b]; 183 to=moves[a].to[b];
184 index_dice=b+1; 184 index_dice=b+1;
185 } 185 }
186 } 186 }
187 } 187 }
188 move(from,to,index_dice); 188 move(from,to,index_dice);
189} 189}
190 190
191 191
192void MoveEngine::boardpressed(const int& x,const int& y,Marker& marker,bool non_qte) 192void MoveEngine::boardpressed(const int& x,const int& y,Marker& marker,bool non_qte)
193{ 193{
194 //get the position of the mouse click 194 //get the position of the mouse click
195 bool upper=true; 195 bool upper=true;
196 bool found=false; 196 bool found=false;
197 197
198 int offset=(non_qte) ? 5 : 0; 198 int offset=(non_qte) ? 5 : 0;
199 199
200 if(y<=85) // board slots 0 to 12 200 if(y<=85) // board slots 0 to 12
201 marker.y_current=0; 201 marker.y_current=0;
202 else if(y>=105) //board slots 13 to 25 202 else if(y>=105) //board slots 13 to 25
203 { 203 {
204 marker.y_current=195-2*offset; 204 marker.y_current=195-2*offset;
205 upper=false; 205 upper=false;
206 } 206 }
207 207
208 int index=13; // the clicked board slot 208 int index=13; // the clicked board slot
209 209
210 while(index<25 && !found) 210 while(index<25 && !found)
211 { 211 {
212 if(x>=x_coord[index] && x<x_coord[index+1]) 212 if(x>=x_coord[index] && x<x_coord[index+1])
213 { 213 {
214 marker.x_current=x_coord[index]; 214 marker.x_current=x_coord[index];
215 found=true; 215 found=true;
216 ; 216 ;
217 } 217 }
218 else 218 else
219 { 219 {
220 index++; 220 index++;
221 } 221 }
222 } 222 }
223 if(!found) 223 if(!found)
224 { 224 {
225 marker.x_current=x_coord[25]; 225 marker.x_current=x_coord[25];
226 index=25; 226 index=25;
227 } 227 }
228 if(upper) 228 if(upper)
229 { 229 {
230 index=25-index; 230 index=25-index;
231 } 231 }
232 232
233 int a=0; 233 int a=0;
234 int usedice=-1; 234 int usedice=-1;
235 int dice_value=7; 235 int dice_value=7;
236 for(a=0;a<4;a++) 236 for(a=0;a<4;a++)
237 { 237 {
238 if(index==marker_next[a] && marker_next[a]!=-1 && dice_value>dice[a]) 238 if(index==marker_next[a] && marker_next[a]!=-1 && dice_value>dice[a])
239 { 239 {
240 usedice=a; 240 usedice=a;
241 dice_value=dice[0]; 241 dice_value=dice[0];
242 } 242 }
243 } 243 }
244 if(usedice!=-1) 244 if(usedice!=-1)
245 { 245 {
246 move(marker_current,marker_next[usedice],usedice+1); 246 move(marker_current,marker_next[usedice],usedice+1);
247 nomarker(marker); 247 nomarker(marker);
248 return; 248 return;
249 249
250 } 250 }
251 251
252 252
253 if(dice[0]==7 && dice[1]==7 && dice[2]==7 && dice[3]==7) //no dice rolled 253 if(dice[0]==7 && dice[1]==7 && dice[2]==7 && dice[3]==7) //no dice rolled
254 { 254 {
255 nomarker(marker); 255 nomarker(marker);
256 return; 256 return;
257 } 257 }
258 else if(fieldColor(index)==player) 258 else if(fieldColor(index)==player)
259 { 259 {
260 marker.visible_current=true; 260 marker.visible_current=true;
261 marker_current=index; 261 marker_current=index;
262 } 262 }
263 else 263 else
264 { 264 {
265 nomarker(marker); 265 nomarker(marker);
266 return; 266 return;
267 } 267 }
268 268
269 for(a=0;a<4;a++) 269 for(a=0;a<4;a++)
270 { 270 {
271 if(moves[index].weight[a]>0) 271 if(moves[index].weight[a]>0)
272 { 272 {
273 int nextfield=moves[index].to[a]; 273 int nextfield=moves[index].to[a];
274 marker.x_next[a]=x_coord[nextfield]; 274 marker.x_next[a]=x_coord[nextfield];
275 marker_next[a]=nextfield; 275 marker_next[a]=nextfield;
276 if(nextfield<13) //upper half 276 if(nextfield<13) //upper half
277 marker.y_next[a]=0; 277 marker.y_next[a]=0;
278 else //lower half 278 else //lower half
279 marker.y_next[a]=195-2*offset; 279 marker.y_next[a]=195-2*offset;
280 marker.visible_next[a]=true; 280 marker.visible_next[a]=true;
281 } 281 }
282 else 282 else
283 { 283 {
284 marker.x_next[a]=0; 284 marker.x_next[a]=0;
285 marker.y_next[a]=0; 285 marker.y_next[a]=0;
286 marker_next[a]=-1; 286 marker_next[a]=-1;
287 marker.visible_next[a]=false; 287 marker.visible_next[a]=false;
288 } 288 }
289 } 289 }
290 return; 290 return;
291} 291}
292 292
293void MoveEngine::reset() 293void MoveEngine::reset()
294{ 294{
295 int a=0; 295 int a=0;
296 for(a=0;a<28;a++) 296 for(a=0;a<28;a++)
297 { 297 {
298 population[a].total=0; 298 population[a].total=0;
299 } 299 }
300 300
301 int p1_index[]={1,1,12,12,12,12,12,17,17,17,19,19,19,19,19}; 301 int p1_index[]={1,1,12,12,12,12,12,17,17,17,19,19,19,19,19};
302 int p2_index[]={24,24,13,13,13,13,13,8,8,8,6,6,6,6,6}; 302 int p2_index[]={24,24,13,13,13,13,13,8,8,8,6,6,6,6,6};
303 //int p1_index[]={19,20,21,22,22,23,23,18,18,23,24,24,24,24,24}; 303 //int p1_index[]={19,20,21,22,22,23,23,18,18,23,24,24,24,24,24};
304 //int p2_index[]={6,5,4,3,3,2,2,2,2,2,1,7,7,1,1}; 304 //int p2_index[]={6,5,4,3,3,2,2,2,2,2,1,7,7,1,1};
305 for(a=0;a<15;a++) 305 for(a=0;a<15;a++)
306 { 306 {
307 population[p1_index[a]].total++; 307 population[p1_index[a]].total++;
308 population[p2_index[a]].total--; 308 population[p2_index[a]].total--;
309 } 309 }
310 310
311 player=0; 311 player=0;
312 dice[0]=7; 312 dice[0]=7;
313 dice[1]=7; 313 dice[1]=7;
314 dice[2]=7; 314 dice[2]=7;
315 dice[3]=7; 315 dice[3]=7;
316 316
317 marker_current=-1; 317 marker_current=-1;
318 marker_next[0]=-1; 318 marker_next[0]=-1;
319 marker_next[1]=-1; 319 marker_next[1]=-1;
320 marker_next[2]=-1; 320 marker_next[2]=-1;
321 marker_next[3]=-1; 321 marker_next[3]=-1;
322 //allclear[0]==false; 322 //allclear[0]==false;
323 allclear[1]=false; 323 allclear[1]=false;
324 allclear[2]=false; 324 allclear[2]=false;
325 last_piece[1]=0; 325 last_piece[1]=0;
326 last_piece[2]=25; 326 last_piece[2]=25;
327} 327}
328 328
329void MoveEngine::loadGame(const LoadSave& load) 329void MoveEngine::loadGame(const LoadSave& load)
330{ 330{
331 for(int a=0;a<28;a++) 331 for(int a=0;a<28;a++)
332 { 332 {
333 population[a].total=load.pop[a].total; 333 population[a].total=load.pop[a].total;
334 } 334 }
335 checkstate(); 335 checkstate();
336} 336}
337 337
338LoadSave MoveEngine::saveGame() 338LoadSave MoveEngine::saveGame()
339{ 339{
340 LoadSave save; 340 LoadSave save;
341 for(int a=0;a<28;a++) 341 for(int a=0;a<28;a++)
342 { 342 {
343 save.pop[a].total=population[a].total; 343 save.pop[a].total=population[a].total;
344 } 344 }
345 return save; 345 return save;
346} 346}
347 347
348AISettings MoveEngine::getAISettings() 348AISettings MoveEngine::getAISettings()
349{ 349{
350 return ai; 350 return ai;
351} 351}
352 352
353void MoveEngine::setAISettings(const AISettings& new_ai) 353void MoveEngine::setAISettings(const AISettings& new_ai)
354{ 354{
355 ai=new_ai; 355 ai=new_ai;
356} 356}
357 357
358void MoveEngine::setRules(Rules rules) 358void MoveEngine::setRules(Rules rules)
359{ 359{
360 move_with_pieces_out=rules.move_with_pieces_out; 360 move_with_pieces_out=rules.move_with_pieces_out;
361 nice_dice=rules.generous_dice; 361 nice_dice=rules.generous_dice;
362} 362}
363 363
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
557 557
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,605 +1,612 @@
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();
121 r.moveBy( dx, dy ); 128 r.moveBy( dx, dy );
122 JezzField* field = (JezzField *)canvas(); 129 JezzField* field = (JezzField *)canvas();
123 130
124 int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE ); 131 int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE );
125 int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE ); 132 int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE );
126 int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE ); 133 int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE );
127 int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE ); 134 int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE );
128 135
129 return ( ul!=TILE_FREE || ur!=TILE_FREE || bl!=TILE_FREE || br!=TILE_FREE ); 136 return ( ul!=TILE_FREE || ur!=TILE_FREE || bl!=TILE_FREE || br!=TILE_FREE );
130} 137}
131 138
132/*************************************************************************/ 139/*************************************************************************/
133 140
134Wall::Wall( JezzField *field, int x, int y, Direction dir, int tile, QObject *parent, const char *name ) 141Wall::Wall( JezzField *field, int x, int y, Direction dir, int tile, QObject *parent, const char *name )
135 : QObject( parent, name ), m_dir( dir ), m_field( field ), m_startX( x ), m_startY( y ), 142 : QObject( parent, name ), m_dir( dir ), m_field( field ), m_startX( x ), m_startY( y ),
136 m_tile( tile ), m_delay( MS2TICKS(WALL_DELAY)/2 ), m_active( true ) 143 m_tile( tile ), m_delay( MS2TICKS(WALL_DELAY)/2 ), m_active( true )
137{ 144{
138 // setup position and direction 145 // setup position and direction
139 m_dx = 0; 146 m_dx = 0;
140 m_dy = 0; 147 m_dy = 0;
141 switch ( m_dir ) 148 switch ( m_dir )
142 { 149 {
143 case Up: m_dy = -1; break; 150 case Up: m_dy = -1; break;
144 case Down: m_dy = 1; break; 151 case Down: m_dy = 1; break;
145 case Left: m_dx = -1; break; 152 case Left: m_dx = -1; break;
146 case Right: m_dx = 1; break; 153 case Right: m_dx = 1; break;
147 } 154 }
148 155
149 m_x = m_startX; 156 m_x = m_startX;
150 m_y = m_startY; 157 m_y = m_startY;
151 158
152 m_field->setTile( m_x, m_y, m_tile ); 159 m_field->setTile( m_x, m_y, m_tile );
153} 160}
154 161
155void Wall::finish() 162void Wall::finish()
156{ 163{
157 m_active = false; 164 m_active = false;
158} 165}
159 166
160bool Wall::isFree( int x, int y ) 167bool Wall::isFree( int x, int y )
161{ 168{
162 if ( m_field->tile(x, y)==TILE_FREE ) 169 if ( m_field->tile(x, y)==TILE_FREE )
163 { 170 {
164 // check whether there is a ball at the moment 171 // check whether there is a ball at the moment
165 QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE, 172 QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE,
166 TILE_SIZE, TILE_SIZE) ); 173 TILE_SIZE, TILE_SIZE) );
167 if ( cols.count()==0 ) 174 if ( cols.count()==0 )
168 return true; 175 return true;
169 } 176 }
170 177
171 return false; 178 return false;
172} 179}
173 180
174void Wall::update() 181void Wall::update()
175{ 182{
176} 183}
177 184
178void Wall::advance() 185void Wall::advance()
179{ 186{
180 update(); 187 update();
181 188
182 // move wall 189 // move wall
183 if ( m_active ) 190 if ( m_active )
184 { 191 {
185 m_delay--; 192 m_delay--;
186 if ( m_delay<=0 ) 193 if ( m_delay<=0 )
187 { 194 {
188 m_delay = MS2TICKS(WALL_DELAY); 195 m_delay = MS2TICKS(WALL_DELAY);
189 196
190 // set previous tile 197 // set previous tile
191 m_field->setTile( m_x, m_y, m_tile ); 198 m_field->setTile( m_x, m_y, m_tile );
192 199
193 // check whether next place is still free 200 // check whether next place is still free
194 if ( isFree(m_x+m_dx, m_y+m_dy) ) 201 if ( isFree(m_x+m_dx, m_y+m_dy) )
195 { 202 {
196 // move ball 203 // move ball
197 m_x += m_dx; 204 m_x += m_dx;
198 m_y += m_dy; 205 m_y += m_dy;
199 206
200 // set tile 207 // set tile
201 m_field->setTile( m_x, m_y, TILE_WALLEND ); 208 m_field->setTile( m_x, m_y, TILE_WALLEND );
202 } else 209 } else
203 { 210 {
204 finish(); 211 finish();
205 emit finished( this, m_field->tile( m_x+m_dx, m_y+m_dy ) ); 212 emit finished( this, m_field->tile( m_x+m_dx, m_y+m_dy ) );
206 } 213 }
207 } 214 }
208 } 215 }
209} 216}
210 217
211void Wall::fill( bool black ) 218void Wall::fill( bool black )
212{ 219{
213 if ( m_dx ) 220 if ( m_dx )
214 { 221 {
215 for ( int x=m_startX ; x!=m_x; x+=m_dx ) 222 for ( int x=m_startX ; x!=m_x; x+=m_dx )
216 if ( m_field->tile(x, m_startY)==m_tile ) 223 if ( m_field->tile(x, m_startY)==m_tile )
217 m_field->setGameTile( x, m_startY, black ); 224 m_field->setGameTile( x, m_startY, black );
218 225
219 m_field->setGameTile( m_x, m_startY, black ); 226 m_field->setGameTile( m_x, m_startY, black );
220 } else 227 } else
221 { 228 {
222 for ( int y=m_startY ; y!=m_y; y+=m_dy ) 229 for ( int y=m_startY ; y!=m_y; y+=m_dy )
223 if ( m_field->tile(m_startX, y)==m_tile ) 230 if ( m_field->tile(m_startX, y)==m_tile )
224 m_field->setGameTile( m_startX, y, black ); 231 m_field->setGameTile( m_startX, y, black );
225 232
226 m_field->setGameTile( m_startX, m_y, black ); 233 m_field->setGameTile( m_startX, m_y, black );
227 } 234 }
228} 235}
229 236
230/*************************************************************************/ 237/*************************************************************************/
231 238
232JezzField::JezzField( QPixmap tiles, QObject* parent, const char* name ) 239JezzField::JezzField( QPixmap tiles, QObject* parent, const char* name )
233 : QCanvas( parent, name ), m_tiles( tiles ) 240 : QCanvas( parent, name ), m_tiles( tiles )
234{ 241{
235 setPixmaps( tiles ); 242 setPixmaps( tiles );
236} 243}
237 244
238void JezzField::setGameTile( int x, int y, bool black ) 245void JezzField::setGameTile( int x, int y, bool black )
239{ 246{
240 setTile( x, y, black ? TILE_BORDER : TILE_FREE ); 247 setTile( x, y, black ? TILE_BORDER : TILE_FREE );
241} 248}
242 249
243void JezzField::setPixmaps( QPixmap tiles ) 250void JezzField::setPixmaps( QPixmap tiles )
244{ 251{
245 // create new tiles 252 // create new tiles
246 QPixmap allTiles( TILE_SIZE*(FIELD_WIDTH-2), TILE_SIZE*(FIELD_HEIGHT-1) ); 253 QPixmap allTiles( TILE_SIZE*(FIELD_WIDTH-2), TILE_SIZE*(FIELD_HEIGHT-1) );
247 254
248 // handle default tiles 255 // handle default tiles
249 bitBlt( &allTiles, 0, TILE_SIZE*(FIELD_HEIGHT-2), 256 bitBlt( &allTiles, 0, TILE_SIZE*(FIELD_HEIGHT-2),
250 &tiles, 0, 0, tiles.width(), tiles.height() ); 257 &tiles, 0, 0, tiles.width(), tiles.height() );
251 258
252 // load tiles into canvas 259 // load tiles into canvas
253 setTiles( allTiles, FIELD_WIDTH, FIELD_HEIGHT, TILE_SIZE, TILE_SIZE ); 260 setTiles( allTiles, FIELD_WIDTH, FIELD_HEIGHT, TILE_SIZE, TILE_SIZE );
254} 261}
255 262
256/*************************************************************************/ 263/*************************************************************************/
257 264
258JezzView::JezzView(QCanvas* viewing, QWidget* parent, const char* name, WFlags f) 265JezzView::JezzView(QCanvas* viewing, QWidget* parent, const char* name, WFlags f)
259 : QCanvasView( viewing, parent, name, f ), m_vertical( false ) 266 : QCanvasView( viewing, parent, name, f ), m_vertical( false )
260{ 267{
261 setResizePolicy( AutoOne ); 268 setResizePolicy( AutoOne );
262 setHScrollBarMode( AlwaysOff ); 269 setHScrollBarMode( AlwaysOff );
263 setVScrollBarMode( AlwaysOff ); 270 setVScrollBarMode( AlwaysOff );
264 271
265 setCursor( sizeHorCursor ); 272 setCursor( sizeHorCursor );
266} 273}
267 274
268void JezzView::viewportMouseReleaseEvent( QMouseEvent *ev ) 275void JezzView::viewportMouseReleaseEvent( QMouseEvent *ev )
269{ 276{
270 if ( ev->button() & LeftButton ) 277 if ( ev->button() & LeftButton )
271 { 278 {
272 emit buildWall( ev->x()/TILE_SIZE, ev->y()/TILE_SIZE, m_vertical ); 279 emit buildWall( ev->x()/TILE_SIZE, ev->y()/TILE_SIZE, m_vertical );
273 } 280 }
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
467 // fill above 474 // fill above
468 for ( _x=x+1; _x<stopx; _x++ ) 475 for ( _x=x+1; _x<stopx; _x++ )
469 if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 ); 476 if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 );
470 477
471 // fill below; 478 // fill below;
472 for ( _x=x+1; _x<stopx; _x++ ) 479 for ( _x=x+1; _x<stopx; _x++ )
473 if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 ); 480 if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 );
474} 481}
475 482
476void JezzGame::ballCollision( Ball*, int, int, int tile ) 483void JezzGame::ballCollision( Ball*, int, int, int tile )
477{ 484{
478 if ( tile!=TILE_BORDER && tile>TILE_FREE && tile!=TILE_WALLEND ) 485 if ( tile!=TILE_BORDER && tile>TILE_FREE && tile!=TILE_WALLEND )
479 { 486 {
480 // stop walls 487 // stop walls
481 if ( (tile==TILE_WALLUP || tile==TILE_WALLLEFT) && m_wall1 ) 488 if ( (tile==TILE_WALLUP || tile==TILE_WALLLEFT) && m_wall1 )
482 { 489 {
483 m_wall1->finish(); 490 m_wall1->finish();
484 m_wall1->fill( false ); 491 m_wall1->fill( false );
485 delete m_wall1; 492 delete m_wall1;
486 m_wall1 = 0; 493 m_wall1 = 0;
487 } 494 }
488 495
489 if ( (tile==TILE_WALLDOWN || tile==TILE_WALLRIGHT) && m_wall2 ) 496 if ( (tile==TILE_WALLDOWN || tile==TILE_WALLRIGHT) && m_wall2 )
490 { 497 {
491 m_wall2->finish(); 498 m_wall2->finish();
492 m_wall2->fill( false ); 499 m_wall2->fill( false );
493 delete m_wall2; 500 delete m_wall2;
494 m_wall2 = 0; 501 m_wall2 = 0;
495 } 502 }
496 503
497 // update view 504 // update view
498 m_field->update(); 505 m_field->update();
499 m_view->repaint(); 506 m_view->repaint();
500 507
501 // send death msg 508 // send death msg
502 emit died(); 509 emit died();
503 } 510 }
504} 511}
505 512
506void JezzGame::buildWall( int x, int y, bool vertical ) 513void JezzGame::buildWall( int x, int y, bool vertical )
507{ 514{
508 if ( !m_running ) return; 515 if ( !m_running ) return;
509 516
510 if ( m_field->tile(x, y)==TILE_FREE ) 517 if ( m_field->tile(x, y)==TILE_FREE )
511 { 518 {
512 // check whether there is a ball at the moment 519 // check whether there is a ball at the moment
513 QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE) ); 520 QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE) );
514 if ( cols.count()>0 ) 521 if ( cols.count()>0 )
515 { 522 {
516 //kdDebug() << "Direct collision" << endl; 523 //kdDebug() << "Direct collision" << endl;
517 emit ballCollision( (Ball*)cols.first(), x, y, TILE_WALLUP ); 524 emit ballCollision( (Ball*)cols.first(), x, y, TILE_WALLUP );
518 return; 525 return;
519 } 526 }
520 527
521 // start walls 528 // start walls
522 if ( !m_wall1 ) 529 if ( !m_wall1 )
523 { 530 {
524 m_wall1 = new Wall( m_field, x, y, 531 m_wall1 = new Wall( m_field, x, y,
525 vertical? Wall::Up : Wall::Left, 532 vertical? Wall::Up : Wall::Left,
526 vertical? TILE_WALLUP : TILE_WALLLEFT, 533 vertical? TILE_WALLUP : TILE_WALLLEFT,
527 this, "m_wall1" ); 534 this, "m_wall1" );
528 connect( m_wall1, SIGNAL(finished(Wall*,int)), 535 connect( m_wall1, SIGNAL(finished(Wall*,int)),
529 this, SLOT(wallFinished(Wall*,int)) ); } 536 this, SLOT(wallFinished(Wall*,int)) ); }
530 537
531 if ( !m_wall2 ) 538 if ( !m_wall2 )
532 { 539 {
533 m_wall2 = new Wall( m_field, x, y, 540 m_wall2 = new Wall( m_field, x, y,
534 vertical? Wall::Down: Wall::Right, 541 vertical? Wall::Down: Wall::Right,
535 vertical? TILE_WALLDOWN : TILE_WALLRIGHT, 542 vertical? TILE_WALLDOWN : TILE_WALLRIGHT,
536 this, "m_wall2" ); 543 this, "m_wall2" );
537 connect( m_wall2, SIGNAL(finished(Wall*,int)), 544 connect( m_wall2, SIGNAL(finished(Wall*,int)),
538 this, SLOT(wallFinished(Wall*,int)) ); 545 this, SLOT(wallFinished(Wall*,int)) );
539 } 546 }
540 } 547 }
541} 548}
542 549
543void JezzGame::wallFinished( Wall *wall, int tile ) 550void JezzGame::wallFinished( Wall *wall, int tile )
544{ 551{
545 if ( tile==TILE_WALLEND ) 552 if ( tile==TILE_WALLEND )
546 { 553 {
547 if ( m_wall1 ) 554 if ( m_wall1 )
548 { 555 {
549 m_wall1->fill( false ); 556 m_wall1->fill( false );
550 delete m_wall1; 557 delete m_wall1;
551 m_wall1 = 0; 558 m_wall1 = 0;
552 } 559 }
553 560
554 if ( m_wall2 ) 561 if ( m_wall2 )
555 { 562 {
556 m_wall2->fill( false ); 563 m_wall2->fill( false );
557 delete m_wall2; 564 delete m_wall2;
558 m_wall2 = 0; 565 m_wall2 = 0;
559 } 566 }
560 } else 567 } else
561 { 568 {
562 if ( m_wall1==wall && m_wall1 ) 569 if ( m_wall1==wall && m_wall1 )
563 { 570 {
564 m_wall1->fill( true ); 571 m_wall1->fill( true );
565 delete m_wall1; 572 delete m_wall1;
566 m_wall1 = 0; 573 m_wall1 = 0;
567 } 574 }
568 575
569 if ( m_wall2==wall && m_wall2 ) 576 if ( m_wall2==wall && m_wall2 )
570 { 577 {
571 m_wall2->fill( true ); 578 m_wall2->fill( true );
572 delete m_wall2; 579 delete m_wall2;
573 m_wall2 = 0; 580 m_wall2 = 0;
574 } 581 }
575 } 582 }
576 583
577 m_field->update(); 584 m_field->update();
578 m_view->repaint(); 585 m_view->repaint();
579 586
580 makeBlack(); 587 makeBlack();
581} 588}
582 589
583void JezzGame::tick() 590void JezzGame::tick()
584{ 591{
585 if ( m_running ) 592 if ( m_running )
586 { 593 {
587 if ( m_field ) m_field->advance(); 594 if ( m_field ) m_field->advance();
588 if ( m_wall1 ) m_wall1->advance(); 595 if ( m_wall1 ) m_wall1->advance();
589 if ( m_wall2 ) m_wall2->advance(); 596 if ( m_wall2 ) m_wall2->advance();
590 } else 597 } else
591 { 598 {
592 for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() ) 599 for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() )
593 ball->update(); 600 ball->update();
594 601
595 if ( m_field ) m_field->update(); 602 if ( m_field ) m_field->update();
596 if ( m_wall1 ) m_wall1->update(); 603 if ( m_wall1 ) m_wall1->update();
597 if ( m_wall2 ) m_wall2->update(); 604 if ( m_wall2 ) m_wall2->update();
598 } 605 }
599} 606}
600 607
601void JezzGame::changeCursor() 608void JezzGame::changeCursor()
602{ 609{
603 arrow->changeDirection(); 610 arrow->changeDirection();
604 m_view->changeCursor(); 611 m_view->changeCursor();
605} 612}
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,460 +1,461 @@
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");
132 newBlackStone = new QImage( fn ); 133 newBlackStone = new QImage( fn );
133 fn = Resource::findPixmap("Go-white"); 134 fn = Resource::findPixmap("Go-white");
134 whiteStone = new QImage( fn ); 135 whiteStone = new QImage( fn );
135 */ 136 */
136 blackStone = new QPixmap(Resource::loadPixmap( "Go-black" )); 137 blackStone = new QPixmap(Resource::loadPixmap( "Go-black" ));
137 whiteStone = new QPixmap(Resource::loadPixmap( "Go-white" )); 138 whiteStone = new QPixmap(Resource::loadPixmap( "Go-white" ));
138 newBlackStone = new QPixmap(Resource::loadPixmap( "Go-black-highlight" )); 139 newBlackStone = new QPixmap(Resource::loadPixmap( "Go-black-highlight" ));
139 140
140 init(); 141 init();
141} 142}
142 143
143GoWidget::~GoWidget() 144GoWidget::~GoWidget()
144{ 145{
145 writeConfig(); 146 writeConfig();
146} 147}
147 148
148void GoWidget::writeConfig() 149void GoWidget::writeConfig()
149{ 150{
150 Config cfg("Go"); 151 Config cfg("Go");
151 cfg.setGroup("Game"); 152 cfg.setGroup("Game");
152 cfg.writeEntry("TwoPlayer", twoplayer); 153 cfg.writeEntry("TwoPlayer", twoplayer);
153 cfg.writeEntry("CurrentPlayer", currentPlayer); 154 cfg.writeEntry("CurrentPlayer", currentPlayer);
154 cfg.writeEntry("NPassed", nPassed); 155 cfg.writeEntry("NPassed", nPassed);
155 QString b; 156 QString b;
156 for (int i=0; i<19; i++) 157 for (int i=0; i<19; i++)
157 for (int j=0; j<19; j++) 158 for (int j=0; j<19; j++)
158 b += board[i][j] == BLACK ? 'B' : board[i][j] == WHITE ? 'W' : '.'; 159 b += board[i][j] == BLACK ? 'B' : board[i][j] == WHITE ? 'W' : '.';
159 cfg.writeEntry("Board", b); 160 cfg.writeEntry("Board", b);
160 cfg.writeEntry("LastX", lastX); 161 cfg.writeEntry("LastX", lastX);
161 cfg.writeEntry("LastY", lastY); 162 cfg.writeEntry("LastY", lastY);
162 extern int blackPrisoners, whitePrisoners; 163 extern int blackPrisoners, whitePrisoners;
163 cfg.writeEntry("BlackPrisoners", blackPrisoners); 164 cfg.writeEntry("BlackPrisoners", blackPrisoners);
164 cfg.writeEntry("WhitePrisoners", whitePrisoners); 165 cfg.writeEntry("WhitePrisoners", whitePrisoners);
165} 166}
166 167
167void GoWidget::readConfig() 168void GoWidget::readConfig()
168{ 169{
169 init(); 170 init();
170 Config cfg("Go"); 171 Config cfg("Go");
171 cfg.setGroup("Game"); 172 cfg.setGroup("Game");
172 twoplayer = cfg.readBoolEntry("TwoPlayer"); 173 twoplayer = cfg.readBoolEntry("TwoPlayer");
173 currentPlayer = (bVal)cfg.readNumEntry("CurrentPlayer",1); 174 currentPlayer = (bVal)cfg.readNumEntry("CurrentPlayer",1);
174 nPassed = cfg.readNumEntry("NPassed",0); 175 nPassed = cfg.readNumEntry("NPassed",0);
175 QString b = cfg.readEntry("Board"); 176 QString b = cfg.readEntry("Board");
176 if ( b.length() == 19*19 ) 177 if ( b.length() == 19*19 )
177 for (int i=0; i<19; i++) 178 for (int i=0; i<19; i++)
178 for (int j=0; j<19; j++) { 179 for (int j=0; j<19; j++) {
179 QChar ch = b[j+19*i]; 180 QChar ch = b[j+19*i];
180 if ( ch != '.' ) 181 if ( ch != '.' )
181 GoPlaceStone( ch == 'B' ? BLACK : WHITE, i, j ); 182 GoPlaceStone( ch == 'B' ? BLACK : WHITE, i, j );
182 } 183 }
183 lastX = cfg.readNumEntry("LastX"); 184 lastX = cfg.readNumEntry("LastX");
184 lastY = cfg.readNumEntry("LastY"); 185 lastY = cfg.readNumEntry("LastY");
185 extern int blackPrisoners, whitePrisoners; 186 extern int blackPrisoners, whitePrisoners;
186 blackPrisoners = cfg.readNumEntry("BlackPrisoners",0); 187 blackPrisoners = cfg.readNumEntry("BlackPrisoners",0);
187 whitePrisoners = cfg.readNumEntry("WhitePrisoners",0); 188 whitePrisoners = cfg.readNumEntry("WhitePrisoners",0);
188 reportPrisoners(blackPrisoners,whitePrisoners); 189 reportPrisoners(blackPrisoners,whitePrisoners);
189 emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone ); 190 emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone );
190} 191}
191 192
192void GoWidget::resizeEvent( QResizeEvent * ) 193void GoWidget::resizeEvent( QResizeEvent * )
193{ 194{
194 d = QMIN(width(),height())/19; 195 d = QMIN(width(),height())/19;
195 // int r = (d/2-1); 196 // int r = (d/2-1);
196 bx = (width() - 18*d)/2 ; 197 bx = (width() - 18*d)/2 ;
197 by = (height() - 18*d)/2 ; 198 by = (height() - 18*d)/2 ;
198 199
199 if ( d < 10 && !smallStones ) { 200 if ( d < 10 && !smallStones ) {
200 blackStone->convertFromImage( blackStone->convertToImage().smoothScale(8,8) ); 201 blackStone->convertFromImage( blackStone->convertToImage().smoothScale(8,8) );
201 whiteStone->convertFromImage( whiteStone->convertToImage().smoothScale(8,8) ); 202 whiteStone->convertFromImage( whiteStone->convertToImage().smoothScale(8,8) );
202 newBlackStone->convertFromImage( newBlackStone->convertToImage().smoothScale(8,8) ); 203 newBlackStone->convertFromImage( newBlackStone->convertToImage().smoothScale(8,8) );
203 204
204 smallStones = TRUE; 205 smallStones = TRUE;
205 } else if ( d >= 10 && smallStones ) { 206 } else if ( d >= 10 && smallStones ) {
206 blackStone = new QPixmap(Resource::loadPixmap( "Go-black" )); 207 blackStone = new QPixmap(Resource::loadPixmap( "Go-black" ));
207 whiteStone = new QPixmap(Resource::loadPixmap( "Go-white" )); 208 whiteStone = new QPixmap(Resource::loadPixmap( "Go-white" ));
208 newBlackStone = new QPixmap(Resource::loadPixmap( "Go-black-highlight" )); 209 newBlackStone = new QPixmap(Resource::loadPixmap( "Go-black-highlight" ));
209 smallStones = FALSE; 210 smallStones = FALSE;
210 } 211 }
211} 212}
212 213
213void GoWidget::init() 214void GoWidget::init()
214{ 215{
215 lastX = lastY = newX = newY = -1; 216 lastX = lastY = newX = newY = -1;
216 nPassed = 0; 217 nPassed = 0;
217 for ( int i = 0; i < 19; i++ ) 218 for ( int i = 0; i < 19; i++ )
218 for ( int j = 0; j < 19; j++ ) 219 for ( int j = 0; j < 19; j++ )
219 board[i][j]=-1; 220 board[i][j]=-1;
220 gameActive = TRUE; 221 gameActive = TRUE;
221 goRestart(current_handicap); 222 goRestart(current_handicap);
222 223
223 if ( twoplayer ) { 224 if ( twoplayer ) {
224 currentPlayer = BLACK; 225 currentPlayer = BLACK;
225 } else { 226 } else {
226 doComputerMove(); 227 doComputerMove();
227 currentPlayer = WHITE; 228 currentPlayer = WHITE;
228 } 229 }
229 emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone ); 230 emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone );
230} 231}
231 232
232void GoWidget::paintEvent( QPaintEvent *e ) 233void GoWidget::paintEvent( QPaintEvent *e )
233{ 234{
234 int i,j; 235 int i,j;
235 236
236 int r = whiteStone->width()/2; 237 int r = whiteStone->width()/2;
237 238
238 QPainter p(this); 239 QPainter p(this);
239 p.fillRect( bx - d/2, by - d/2, 19*d, 19*d, *goBrush ); 240 p.fillRect( bx - d/2, by - d/2, 19*d, 19*d, *goBrush );
240 241
241 int xMin = QMAX( x2board(e->rect().left()), 0 ); 242 int xMin = QMAX( x2board(e->rect().left()), 0 );
242 int xMax = QMIN( x2board(e->rect().right()), 18 ); 243 int xMax = QMIN( x2board(e->rect().right()), 18 );
243 int yMin = QMAX( y2board(e->rect().top()), 0 ); 244 int yMin = QMAX( y2board(e->rect().top()), 0 );
244 int yMax = QMIN( y2board(e->rect().bottom()), 18 ); 245 int yMax = QMIN( y2board(e->rect().bottom()), 18 );
245 246
246 QColor pine( 255, 186, 89 ); 247 QColor pine( 255, 186, 89 );
247 p.setPen( pine.dark() ); 248 p.setPen( pine.dark() );
248 249
249 for ( i = xMin; i < xMax+1 ; i ++ ) { 250 for ( i = xMin; i < xMax+1 ; i ++ ) {
250 p.drawLine( bx+i*d, by, bx+i*d, by+18*d ); 251 p.drawLine( bx+i*d, by, bx+i*d, by+18*d );
251 } 252 }
252 for ( j = yMin; j < yMax+1 ; j ++ ) { 253 for ( j = yMin; j < yMax+1 ; j ++ ) {
253 p.drawLine( bx, by+j*d, bx+18*d, by+j*d); 254 p.drawLine( bx, by+j*d, bx+18*d, by+j*d);
254 } 255 }
255 256
256 // dots are at (3,3), (3,9), (3,15) and so on 257 // dots are at (3,3), (3,9), (3,15) and so on
257 p.setBrush( black ); 258 p.setBrush( black );
258 for ( i = 3; i < xMax+1; i+=6 ) 259 for ( i = 3; i < xMax+1; i+=6 )
259 for ( j = 3; j < yMax+1; j+=6 ) 260 for ( j = 3; j < yMax+1; j+=6 )
260 p.drawEllipse( bx+i*d-2, by+j*d-2, 5, 5 ); 261 p.drawEllipse( bx+i*d-2, by+j*d-2, 5, 5 );
261 262
262 263
263 for ( i = xMin; i < xMax+1; i++ ) 264 for ( i = xMin; i < xMax+1; i++ )
264 for ( j = yMin; j < yMax+1; j++ ) { 265 for ( j = yMin; j < yMax+1; j++ ) {
265 if ( board[i][j] == WHITE || 266 if ( board[i][j] == WHITE ||
266 currentPlayer==WHITE && newX == i && newY == j ) 267 currentPlayer==WHITE && newX == i && newY == j )
267 p.drawPixmap( bx+i*d - r, by+j*d - r, *whiteStone ); 268 p.drawPixmap( bx+i*d - r, by+j*d - r, *whiteStone );
268 else if ( i == lastX && j == lastY ) 269 else if ( i == lastX && j == lastY )
269 p.drawPixmap( bx+i*d - r, by+j*d - r, *newBlackStone ); 270 p.drawPixmap( bx+i*d - r, by+j*d - r, *newBlackStone );
270 else if ( board[i][j] == BLACK || 271 else if ( board[i][j] == BLACK ||
271 currentPlayer==BLACK && newX == i && newY == j) 272 currentPlayer==BLACK && newX == i && newY == j)
272 p.drawPixmap( bx+i*d - r, by+j*d - r, *blackStone ); 273 p.drawPixmap( bx+i*d - r, by+j*d - r, *blackStone );
273 } 274 }
274} 275}
275 276
276void GoWidget::doMove( int x, int y ) 277void GoWidget::doMove( int x, int y )
277{ 278{
278 279
279 if ( !GoPlaceStone( currentPlayer, x, y ) ) { 280 if ( !GoPlaceStone( currentPlayer, x, y ) ) {
280 //printf( "Illegal move (%d,%d)\n", x, y ); 281 //printf( "Illegal move (%d,%d)\n", x, y );
281 return; 282 return;
282 } 283 }
283 //printf( "you do (%d,%d)\n", x, y ); 284 //printf( "you do (%d,%d)\n", x, y );
284 nPassed = 0; 285 nPassed = 0;
285 if ( twoplayer ) 286 if ( twoplayer )
286 currentPlayer = (currentPlayer==WHITE) ? BLACK : WHITE; 287 currentPlayer = (currentPlayer==WHITE) ? BLACK : WHITE;
287 else 288 else
288 doComputerMove(); 289 doComputerMove();
289 290
290 emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone ); 291 emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone );
291 292
292} 293}
293 294
294void GoWidget::pass() 295void GoWidget::pass()
295{ 296{
296 if ( !gameActive ) 297 if ( !gameActive )
297 return; 298 return;
298 nPassed++; 299 nPassed++;
299 if ( nPassed >= 2 ) 300 if ( nPassed >= 2 )
300 endGame(); 301 endGame();
301 else if ( !twoplayer ) 302 else if ( !twoplayer )
302 doComputerMove(); 303 doComputerMove();
303} 304}
304 305
305void GoWidget::resign() 306void GoWidget::resign()
306{ 307{
307 if ( gameActive ) 308 if ( gameActive )
308 endGame(); 309 endGame();
309} 310}
310 311
311 312
312void GoWidget::newGame() 313void GoWidget::newGame()
313{ 314{
314 init(); 315 init();
315 update(); 316 update();
316} 317}
317 318
318 319
319void GoWidget::endGame() 320void GoWidget::endGame()
320{ 321{
321 gameActive = FALSE; 322 gameActive = FALSE;
322 323
323 int w,b; 324 int w,b;
324 CountUp( &w, &b); 325 CountUp( &w, &b);
325 QString s = tr("White %1, Black %2. ").arg(w).arg(b); 326 QString s = tr("White %1, Black %2. ").arg(w).arg(b);
326 if ( w > b ) 327 if ( w > b )
327 s += tr("White wins."); 328 s += tr("White wins.");
328 else if ( w < b ) 329 else if ( w < b )
329 s += tr("Black wins."); 330 s += tr("Black wins.");
330 else 331 else
331 s += tr("A draw."); 332 s += tr("A draw.");
332 emit showScore( s ); 333 emit showScore( s );
333} 334}
334 335
335void GoWidget::doComputerMove() 336void GoWidget::doComputerMove()
336{ 337{
337 int ox = lastX; 338 int ox = lastX;
338 int oy = lastY; 339 int oy = lastY;
339 lastX = lastY = -1; 340 lastX = lastY = -1;
340 emit showTurn( *blackStone ); 341 emit showTurn( *blackStone );
341 refresh( ox, oy); 342 refresh( ox, oy);
342 qApp->processEvents(); 343 qApp->processEvents();
343 short int x,y; 344 short int x,y;
344 if ( genMove( computer_color, &x, &y ) ) { 345 if ( genMove( computer_color, &x, &y ) ) {
345 lastX = x; 346 lastX = x;
346 lastY = y; 347 lastY = y;
347 //printf( "I do (%d,%d)\n", x, y ); 348 //printf( "I do (%d,%d)\n", x, y );
348 GoPlaceStone(computer_color,x,y); 349 GoPlaceStone(computer_color,x,y);
349 nPassed = 0; 350 nPassed = 0;
350 } else { 351 } else {
351 emit showScore( tr("I pass") ); 352 emit showScore( tr("I pass") );
352 nPassed++; 353 nPassed++;
353 if ( nPassed >= 2 ) 354 if ( nPassed >= 2 )
354 endGame(); 355 endGame();
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,366 +1,369 @@
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) ||
120 ((opos = s.find(QRegExp("\\\\[0-7]+"), opos)) != -1)) { 123 ((opos = s.find(QRegExp("\\\\[0-7]+"), opos)) != -1)) {
121 if (xpos != -1) { 124 if (xpos != -1) {
122 valids = "0123456789abcdef"; 125 valids = "0123456789abcdef";
123 leadin = 2; 126 leadin = 2;
124 pos = xpos; 127 pos = xpos;
125 } else { 128 } else {
126 valids = "01234567"; 129 valids = "01234567";
127 leadin = 1; 130 leadin = 1;
128 pos = opos; 131 pos = opos;
129 } 132 }
130 133
131 c = '\0'; 134 c = '\0';
132 len = 0; 135 len = 0;
133 value = s.mid(pos+leadin, 3); 136 value = s.mid(pos+leadin, 3);
134 ptr = (const char *) value; 137 ptr = (const char *) value;
135 138
136 while (*ptr != '\0' && (v = valids.find(*ptr++, 0, FALSE)) != -1) { 139 while (*ptr != '\0' && (v = valids.find(*ptr++, 0, FALSE)) != -1) {
137 c = (c * valids.length()) + v; 140 c = (c * valids.length()) + v;
138 len++; 141 len++;
139 } 142 }
140 143
141 value.fill(c, 1); 144 value.fill(c, 1);
142 s.replace(pos, len+leadin, value); 145 s.replace(pos, len+leadin, value);
143 } 146 }
144 147
145 return s; 148 return s;
146} 149}
147 150
148void Status::fillArray(QArray<int> &array, QString values, int max) 151void Status::fillArray(QArray<int> &array, QString values, int max)
149{ 152{
150 array.resize(max); 153 array.resize(max);
151 int last = 0; 154 int last = 0;
152 bool ok; 155 bool ok;
153 QString value; 156 QString value;
154 157
155 for (uint i = 0; i < array.size(); i++) { 158 for (uint i = 0; i < array.size(); i++) {
156 if (values.find(',') < 0 && values.length() > 0) { 159 if (values.find(',') < 0 && values.length() > 0) {
157 value = values; 160 value = values;
158 values = ""; 161 values = "";
159 } 162 }
160 if (values.find(',') >= 0) { 163 if (values.find(',') >= 0) {
161 value = values.left(values.find(',')); 164 value = values.left(values.find(','));
162 values.remove(0,values.find(',')+1); 165 values.remove(0,values.find(',')+1);
163 } 166 }
164 array[i] = value.toInt(&ok); 167 array[i] = value.toInt(&ok);
165 if (ok) 168 if (ok)
166 last = array[i]; 169 last = array[i];
167 else 170 else
168 array[i] = last; 171 array[i] = last;
169 } 172 }
170} 173}
171 174
172void Status::fillStrList(QStrList &list, QString values, int max) 175void Status::fillStrList(QStrList &list, QString values, int max)
173{ 176{
174 if (!list.isEmpty()) 177 if (!list.isEmpty())
175 list.clear(); 178 list.clear();
176 179
177 QString last = ""; 180 QString last = "";
178 QString value; 181 QString value;
179 182
180 for (uint i = 0; i < (uint) max; i++) { 183 for (uint i = 0; i < (uint) max; i++) {
181 if (values.find(',') < 0 && values.length() > 0) { 184 if (values.find(',') < 0 && values.length() > 0) {
182 value = values; 185 value = values;
183 values = ""; 186 values = "";
184 } 187 }
185 if (values.find(',') >= 0) { 188 if (values.find(',') >= 0) {
186 value = values.left(values.find(',')); 189 value = values.left(values.find(','));
187 values.remove(0,values.find(',')+1); 190 values.remove(0,values.find(',')+1);
188 } 191 }
189 if (!value.isEmpty()) 192 if (!value.isEmpty())
190 last = decodeHexOctString(value); 193 last = decodeHexOctString(value);
191 list.append(last); 194 list.append(last);
192 } 195 }
193} 196}
194 197
195void Status::fillPixmapName(QStrList &pixmapName) 198void Status::fillPixmapName(QStrList &pixmapName)
196{ 199{
197 QStrList list = pixmapName; 200 QStrList list = pixmapName;
198 201
199 if (!pixmapName.isEmpty()) 202 if (!pixmapName.isEmpty())
200 pixmapName.clear(); 203 pixmapName.clear();
201 204
202 QString pixmap; 205 QString pixmap;
203 206
204 QFileInfo fileInfo; 207 QFileInfo fileInfo;
205 208
206 for (uint i = 0; i < list.count(); i++) { 209 for (uint i = 0; i < list.count(); i++) {
207 pixmap = list.at(i); 210 pixmap = list.at(i);
208 211
209 if (pixmap.left(1) != "/" && pixmap.left(1) != "~") 212 if (pixmap.left(1) != "/" && pixmap.left(1) != "~")
210 pixmap = FIND_APP_DATA( pixmapDirectory+pixmap ); 213 pixmap = FIND_APP_DATA( pixmapDirectory+pixmap );
211 214
212 fileInfo.setFile(pixmap); 215 fileInfo.setFile(pixmap);
213 if (!fileInfo.isReadable() || !fileInfo.isFile()) 216 if (!fileInfo.isReadable() || !fileInfo.isFile())
214 pixmap = ""; 217 pixmap = "";
215 218
216 pixmapName.append(pixmap); 219 pixmapName.append(pixmap);
217 } 220 }
218} 221}
219 222
220void Status::confLevels(bool defGroup) 223void Status::confLevels(bool defGroup)
221{ 224{
222 APP_CONFIG_BEGIN( cfg ); 225 APP_CONFIG_BEGIN( cfg );
223 if (defGroup || cfg->hasKey("Levels")) 226 if (defGroup || cfg->hasKey("Levels"))
224 maxLevel = cfg->readNumEntry("Levels", 13); 227 maxLevel = cfg->readNumEntry("Levels", 13);
225 APP_CONFIG_END( cfg ); 228 APP_CONFIG_END( cfg );
226} 229}
227 230
228void Status::confMisc(bool defGroup) 231void Status::confMisc(bool defGroup)
229{ 232{
230 APP_CONFIG_BEGIN( cfg ); 233 APP_CONFIG_BEGIN( cfg );
231 if (defGroup || cfg->hasKey("LevelPosition")) 234 if (defGroup || cfg->hasKey("LevelPosition"))
232 fillArray(levelPos, cfg->readEntry("LevelPosition", "0,1,2,3,,4,,5,,6,,7"), maxLevel); 235 fillArray(levelPos, cfg->readEntry("LevelPosition", "0,1,2,3,,4,,5,,6,,7"), maxLevel);
233 236
234 if (defGroup || cfg->hasKey("PixmapDirectory")) { 237 if (defGroup || cfg->hasKey("PixmapDirectory")) {
235 pixmapDirectory = cfg->readEntry("PixmapDirectory"); 238 pixmapDirectory = cfg->readEntry("PixmapDirectory");
236 239
237 if (pixmapDirectory.left(1) != "/" && pixmapDirectory.left(1) != "~") 240 if (pixmapDirectory.left(1) != "/" && pixmapDirectory.left(1) != "~")
238 pixmapDirectory.insert(0, "pics/"); 241 pixmapDirectory.insert(0, "pics/");
239 if (pixmapDirectory.right(1) != "/") 242 if (pixmapDirectory.right(1) != "/")
240 pixmapDirectory.append("/"); 243 pixmapDirectory.append("/");
241 } 244 }
242 245
243 if (defGroup || cfg->hasKey("LifesPixmapName")) 246 if (defGroup || cfg->hasKey("LifesPixmapName"))
244 fillStrList(lifesPixmapName, 247 fillStrList(lifesPixmapName,
245 cfg->readEntry("LifesPixmapName", "lifes.xpm"), maxLevel+1); 248 cfg->readEntry("LifesPixmapName", "lifes.xpm"), maxLevel+1);
246 if (defGroup || cfg->hasKey("LevelPixmapName")) 249 if (defGroup || cfg->hasKey("LevelPixmapName"))
247 fillStrList(levelPixmapName, 250 fillStrList(levelPixmapName,
248 cfg->readEntry("LevelPixmapName", "fruit.xpm"), maxLevel+1); 251 cfg->readEntry("LevelPixmapName", "fruit.xpm"), maxLevel+1);
249 APP_CONFIG_END( cfg ); 252 APP_CONFIG_END( cfg );
250} 253}
251 254
252void Status::confScheme() 255void Status::confScheme()
253{ 256{
254 APP_CONFIG_BEGIN( cfg ); 257 APP_CONFIG_BEGIN( cfg );
255 SAVE_CONFIG_GROUP( cfg, oldgroup ); 258 SAVE_CONFIG_GROUP( cfg, oldgroup );
256 QString newgroup; 259 QString newgroup;
257 260
258 // if not set, read mode and scheme from the configfile 261 // if not set, read mode and scheme from the configfile
259 if (mode == -1 && scheme == -1) { 262 if (mode == -1 && scheme == -1) {
260 scheme = cfg->readNumEntry("Scheme", -1); 263 scheme = cfg->readNumEntry("Scheme", -1);
261 mode = cfg->readNumEntry("Mode", -1); 264 mode = cfg->readNumEntry("Mode", -1);
262 265
263 // if mode is not set in the defGroup-group, lookup the scheme group 266 // if mode is not set in the defGroup-group, lookup the scheme group
264 if (scheme != -1 || mode == -1) { 267 if (scheme != -1 || mode == -1) {
265 newgroup.sprintf("Scheme %d", scheme); 268 newgroup.sprintf("Scheme %d", scheme);
266 cfg->setGroup(newgroup); 269 cfg->setGroup(newgroup);
267 270
268 mode = cfg->readNumEntry("Mode", -1); 271 mode = cfg->readNumEntry("Mode", -1);
269 RESTORE_CONFIG_GROUP( cfg, oldgroup ); 272 RESTORE_CONFIG_GROUP( cfg, oldgroup );
270 } 273 }
271 } 274 }
272 275
273 confLevels(); 276 confLevels();
274 277
275 if (mode != -1) { 278 if (mode != -1) {
276 newgroup.sprintf("Mode %d", mode); 279 newgroup.sprintf("Mode %d", mode);
277 cfg->setGroup(newgroup); 280 cfg->setGroup(newgroup);
278 281
279 confLevels(FALSE); 282 confLevels(FALSE);
280 } 283 }
281 284
282 if (scheme != -1) { 285 if (scheme != -1) {
283 newgroup.sprintf("Scheme %d", scheme); 286 newgroup.sprintf("Scheme %d", scheme);
284 cfg->setGroup(newgroup); 287 cfg->setGroup(newgroup);
285 288
286 confLevels(FALSE); 289 confLevels(FALSE);
287 } 290 }
288 291
289 RESTORE_CONFIG_GROUP( cfg, oldgroup ); 292 RESTORE_CONFIG_GROUP( cfg, oldgroup );
290 293
291 confMisc(); 294 confMisc();
292 295
293 if (mode != -1) { 296 if (mode != -1) {
294 newgroup.sprintf("Mode %d", mode); 297 newgroup.sprintf("Mode %d", mode);
295 cfg->setGroup(newgroup); 298 cfg->setGroup(newgroup);
296 299
297 confMisc(FALSE); 300 confMisc(FALSE);
298 } 301 }
299 302
300 if (scheme != -1) { 303 if (scheme != -1) {
301 newgroup.sprintf("Scheme %d", scheme); 304 newgroup.sprintf("Scheme %d", scheme);
302 cfg->setGroup(newgroup); 305 cfg->setGroup(newgroup);
303 306
304 confMisc(FALSE); 307 confMisc(FALSE);
305 } 308 }
306 309
307 fillPixmapName(lifesPixmapName); 310 fillPixmapName(lifesPixmapName);
308 fillPixmapName(levelPixmapName); 311 fillPixmapName(levelPixmapName);
309 312
310 initPixmaps(); 313 initPixmaps();
311 314
312 setFixedHeight(minHeight()); 315 setFixedHeight(minHeight());
313 316
314 RESTORE_CONFIG_GROUP( cfg, oldgroup ); 317 RESTORE_CONFIG_GROUP( cfg, oldgroup );
315 APP_CONFIG_END( cfg ); 318 APP_CONFIG_END( cfg );
316} 319}
317 320
318void Status::setScheme(int Scheme, int Mode) 321void Status::setScheme(int Scheme, int Mode)
319{ 322{
320 mode = Mode; 323 mode = Mode;
321 scheme = Scheme; 324 scheme = Scheme;
322 325
323 confScheme(); 326 confScheme();
324 327
325 repaint(); 328 repaint();
326} 329}
327 330
328int Status::minHeight() 331int Status::minHeight()
329{ 332{
330 if (lifesPix->isEmpty() && levelPix->isEmpty()) 333 if (lifesPix->isEmpty() && levelPix->isEmpty())
331 return 0; 334 return 0;
332 if (levelPix->isEmpty()) 335 if (levelPix->isEmpty())
333 return lifesPix->at(0)->height(); 336 return lifesPix->at(0)->height();
334 if (lifesPix->isEmpty()) 337 if (lifesPix->isEmpty())
335 return levelPix->at(0)->height(); 338 return levelPix->at(0)->height();
336 return (lifesPix->at(0)->height() > levelPix->at(0)->height()) ? 339 return (lifesPix->at(0)->height() > levelPix->at(0)->height()) ?
337 lifesPix->at(0)->height() : levelPix->at(0)->height(); 340 lifesPix->at(0)->height() : levelPix->at(0)->height();
338} 341}
339 342
340int Status::minWidth() 343int Status::minWidth()
341{ 344{
342 if (lifesPix->isEmpty() && levelPix->isEmpty()) 345 if (lifesPix->isEmpty() && levelPix->isEmpty())
343 return 0; 346 return 0;
344 if (levelPix->isEmpty()) 347 if (levelPix->isEmpty())
345 return lifesPix->at(0)->width(); 348 return lifesPix->at(0)->width();
346 if (lifesPix->isEmpty()) 349 if (lifesPix->isEmpty())
347 return levelPix->at(0)->width(); 350 return levelPix->at(0)->width();
348 return (lifesPix->at(0)->width() > levelPix->at(0)->width()) ? 351 return (lifesPix->at(0)->width() > levelPix->at(0)->width()) ?
349 lifesPix->at(0)->width() : levelPix->at(0)->width(); 352 lifesPix->at(0)->width() : levelPix->at(0)->width();
350} 353}
351 354
352void Status::setLifes(int lifes) 355void Status::setLifes(int lifes)
353{ 356{
354 actualLifes = lifes; 357 actualLifes = lifes;
355 repaint(); 358 repaint();
356} 359}
357 360
358void Status::setLevel(int Level) 361void Status::setLevel(int Level)
359{ 362{
360 level = Level; 363 level = Level;
361 364
362 initPixmaps(); 365 initPixmaps();
363 366
364 actualLevel = (level > (int) levelPix->count()) ? (int) levelPix->count() : level; 367 actualLevel = (level > (int) levelPix->count()) ? (int) levelPix->count() : level;
365 repaint(); 368 repaint();
366} 369}
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,953 +1,953 @@
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) {
190 return *specialPegs[t]; 190 return *specialPegs[t];
191 } else { 191 } else {
192 return *normalPegs[rand() % 6]; 192 return *normalPegs[rand() % 6];
193 } 193 }
194 } 194 }
195 return *normalPegs[t]; 195 return *normalPegs[t];
196} 196}
197 197
198Peg::Peg(QCanvas *canvas , int t, int g, int p) 198Peg::Peg(QCanvas *canvas , int t, int g, int p)
199 : QCanvasRectangle(canvas) 199 : QCanvasRectangle(canvas)
200{ 200{
201 setSize(normalPegs[t]->width(), normalPegs[t]->height() ); 201 setSize(normalPegs[t]->width(), normalPegs[t]->height() );
202 pegtype = t; 202 pegtype = t;
203 isplaced = FALSE; 203 isplaced = FALSE;
204 peg_pos = p; 204 peg_pos = p;
205 peg_go = g; 205 peg_go = g;
206 aniStep = rand() % 6; 206 aniStep = rand() % 6;
207 setAnimated(TRUE); 207 setAnimated(TRUE);
208} 208}
209 209
210void Peg::advance(int phase) { 210void Peg::advance(int phase) {
211 if (phase == 0) 211 if (phase == 0)
212 aniStep = (++aniStep) % 6; 212 aniStep = (++aniStep) % 6;
213 else { 213 else {
214 hide(); 214 hide();
215 show(); 215 show();
216 } 216 }
217} 217}
218 218
219void Peg::drawShape(QPainter &p ) 219void Peg::drawShape(QPainter &p )
220{ 220{
221 if ((pegtype == 5) && eggLevel > 5) { 221 if ((pegtype == 5) && eggLevel > 5) {
222 p.drawImage(int(x()), int(y()), *normalPegs[aniStep]); 222 p.drawImage(int(x()), int(y()), *normalPegs[aniStep]);
223 } else 223 } else
224 p.drawImage(int(x()), int(y()), imageForType(pegtype)); 224 p.drawImage(int(x()), int(y()), imageForType(pegtype));
225} 225}
226 226
227bool Peg::hit( const QPoint &p ) const 227bool Peg::hit( const QPoint &p ) const
228{ 228{
229 int ix = p.x() - int(x()); 229 int ix = p.x() - int(x());
230 int iy = p.y() - int(y()); 230 int iy = p.y() - int(y());
231 if (!normalPegs[pegtype]->valid(ix, iy)) 231 if (!normalPegs[pegtype]->valid(ix, iy))
232 return FALSE; 232 return FALSE;
233 QRgb pixel = normalPegs[pegtype]->pixel(ix, iy); 233 QRgb pixel = normalPegs[pegtype]->pixel(ix, iy);
234 return (qAlpha(pixel ) != 0); 234 return (qAlpha(pixel ) != 0);
235} 235}
236 236
237inline bool Peg::placed() const 237inline bool Peg::placed() const
238{ 238{
239 return isplaced; 239 return isplaced;
240} 240}
241 241
242inline int Peg::pegGo() const 242inline int Peg::pegGo() const
243{ 243{
244 return peg_go; 244 return peg_go;
245} 245}
246 246
247inline int Peg::pegPos() const 247inline int Peg::pegPos() const
248{ 248{
249 return peg_pos; 249 return peg_pos;
250} 250}
251 251
252inline void Peg::setPegPos(int p) 252inline void Peg::setPegPos(int p)
253{ 253{
254 peg_pos = p; 254 peg_pos = p;
255} 255}
256 256
257inline void Peg::setPlaced(bool p) 257inline void Peg::setPlaced(bool p)
258{ 258{
259 isplaced = p; 259 isplaced = p;
260} 260}
261 261
262inline int Peg::type() const 262inline int Peg::type() const
263{ 263{
264 return pegtype; 264 return pegtype;
265} 265}
266 266
267/* Load the main image, copy from it the pegs, the board, and the answer image 267/* Load the main image, copy from it the pegs, the board, and the answer image
268 * and use these to create the tray, answer and board 268 * and use these to create the tray, answer and board
269 */ 269 */
270MindBreaker::MindBreaker( QWidget *parent, const char *name, int wFlags ) 270MindBreaker::MindBreaker( QWidget *parent, const char *name, int wFlags )
271 : QMainWindow(parent, name, wFlags) 271 : QMainWindow(parent, name, wFlags)
272{ 272{
273 setCaption( tr("Mind Breaker")); 273 setCaption( tr("Mind Breaker"));
274 QPEApplication::setInputMethodHint( this, QPEApplication::AlwaysOff ); 274 QPEApplication::setInputMethodHint( this, QPEApplication::AlwaysOff );
275 setMinimumSize(160,210); 275 setMinimumSize(160,210);
276 276
277 QWidget *w = new QWidget( this ); 277 QWidget *w = new QWidget( this );
278 w->setBackgroundColor( black ); 278 w->setBackgroundColor( black );
279 QHBoxLayout *hb = new QHBoxLayout( w ); 279 QHBoxLayout *hb = new QHBoxLayout( w );
280 hb->addStretch(); 280 hb->addStretch();
281 board = new MindBreakerBoard(w); 281 board = new MindBreakerBoard(w);
282 hb->addWidget( board, 100 ); 282 hb->addWidget( board, 100 );
283 hb->addStretch(); 283 hb->addStretch();
284 284
285 setCentralWidget(w); 285 setCentralWidget(w);
286 286
287 setToolBarsMovable( FALSE ); 287 setToolBarsMovable( FALSE );
288 288
289 QToolBar *tb = new QToolBar(this); 289 QToolBar *tb = new QToolBar(this);
290 tb->setHorizontalStretchable( TRUE ); 290 tb->setHorizontalStretchable( TRUE );
291 291
292 QIconSet newicon = Resource::loadIconSet("new"); 292 QIconSet newicon = Resource::loadIconSet("new");
293 new QToolButton(newicon, tr("New Game"), 0, 293 new QToolButton(newicon, tr("New Game"), 0,
294 board, SLOT(clear()), tb, "NewGame"); 294 board, SLOT(clear()), tb, "NewGame");
295 295
296 score = new QToolButton(tb); 296 score = new QToolButton(tb);
297 score->setText(""); 297 score->setText("");
298 score->setMaximumHeight(20); 298 score->setMaximumHeight(20);
299 score->setUsesTextLabel(TRUE); 299 score->setUsesTextLabel(TRUE);
300 tb->setStretchableWidget(score); 300 tb->setStretchableWidget(score);
301 301
302 connect(board, SIGNAL(scoreChanged(int,int)), this, SLOT(setScore(int,int))); 302 connect(board, SIGNAL(scoreChanged(int,int)), this, SLOT(setScore(int,int)));
303 connect(score, SIGNAL(clicked()), board, SLOT(resetScore())); 303 connect(score, SIGNAL(clicked()), board, SLOT(resetScore()));
304 304
305 int a, b; 305 int a, b;
306 board->getScore(&a, &b); 306 board->getScore(&a, &b);
307 setScore(a,b); 307 setScore(a,b);
308 308
309 layout()->setResizeMode(QLayout::FreeResize); 309 layout()->setResizeMode(QLayout::FreeResize);
310} 310}
311 311
312void MindBreaker::setScore(int turns, int games) 312void MindBreaker::setScore(int turns, int games)
313{ 313{
314 double average; 314 double average;
315 double total_turns = turns; 315 double total_turns = turns;
316 double total_games = games; 316 double total_games = games;
317 317
318 if(total_games > 0) 318 if(total_games > 0)
319 average = total_turns / total_games; 319 average = total_turns / total_games;
320 else 320 else
321 average = 0.0; 321 average = 0.0;
322 322
323 score->setText(tr("win avg: %1 turns (%2 games)").arg(average).arg(games)); 323 score->setText(tr("win avg: %1 turns (%2 games)").arg(average).arg(games));
324} 324}
325 325
326void MindBreaker::resizeEvent( QResizeEvent *e ) 326void MindBreaker::resizeEvent( QResizeEvent *e )
327{ 327{
328 board->fixSize(); 328 board->fixSize();
329 QMainWindow::resizeEvent( e ); 329 QMainWindow::resizeEvent( e );
330} 330}
331 331
332 332
333MindBreakerBoard::MindBreakerBoard( QWidget *parent, 333MindBreakerBoard::MindBreakerBoard( QWidget *parent,
334 const char *name, int wFlags ) 334 const char *name, int wFlags )
335 : QCanvasView(0, parent, name, wFlags), 335 : QCanvasView(0, parent, name, wFlags),
336 moving(0), game_over(FALSE), total_turns(0), total_games(0) 336 moving(0), game_over(FALSE), total_turns(0), total_games(0)
337{ 337{
338 setFrameStyle( NoFrame ); 338 setFrameStyle( NoFrame );
339 setupBoardSize(qApp->desktop()->width(),qApp->desktop()->height()); 339 setupBoardSize(qApp->desktop()->width(),qApp->desktop()->height());
340 cnv.resize(100,100); 340 cnv.resize(100,100);
341 setCanvas(&cnv); 341 setCanvas(&cnv);
342 setBackgroundColor( black ); 342 setBackgroundColor( black );
343 343
344 struct timeval tv; 344 struct timeval tv;
345 345
346 current_go = 0; 346 current_go = 0;
347 gettimeofday(&tv, 0); 347 gettimeofday(&tv, 0);
348 srand(tv.tv_usec); 348 srand(tv.tv_usec);
349 349
350 canvas()->setAdvancePeriod(500); 350 canvas()->setAdvancePeriod(500);
351 current_highlight = 0; 351 current_highlight = 0;
352 352
353 widthTimer = new QTimer( this ); 353 widthTimer = new QTimer( this );
354 connect(widthTimer, SIGNAL(timeout()), this, SLOT(doFixSize()) ); 354 connect(widthTimer, SIGNAL(timeout()), this, SLOT(doFixSize()) );
355 355
356 setMaximumWidth( QMIN(qApp->desktop()->height(),qApp->desktop()->width()) ); 356 setMaximumWidth( QMIN(qApp->desktop()->height(),qApp->desktop()->width()) );
357 //doFixSize(); // build images... needs to be done before reading config. 357 //doFixSize(); // build images... needs to be done before reading config.
358 //readConfig(); // first read... to ensure initial labels and side look right. 358 //readConfig(); // first read... to ensure initial labels and side look right.
359} 359}
360 360
361void MindBreakerBoard::readConfig() 361void MindBreakerBoard::readConfig()
362{ 362{
363 Config c("MindBreaker", Config::User); 363 Config c("MindBreaker", Config::User);
364 c.setGroup("Board"); 364 c.setGroup("Board");
365 game_over = FALSE; 365 game_over = FALSE;
366 int i; 366 int i;
367 if (c.readNumEntry("Answer0") < 0) { 367 if (c.readNumEntry("Answer0") < 0) {
368 for (i = 0; i < 4; i++) { 368 for (i = 0; i < 4; i++) {
369 answer[i] = rand() % 6; 369 answer[i] = rand() % 6;
370 current_guess[i] = 6; 370 current_guess[i] = 6;
371 } 371 }
372 total_turns = 0; 372 total_turns = 0;
373 total_games = 0; 373 total_games = 0;
374 } else { 374 } else {
375 int j; 375 int j;
376 c.setGroup("Score"); 376 c.setGroup("Score");
377 total_turns = c.readNumEntry("Turns"); 377 total_turns = c.readNumEntry("Turns");
378 total_games = c.readNumEntry("Games"); 378 total_games = c.readNumEntry("Games");
379 if(total_turns < 0) 379 if(total_turns < 0)
380 total_turns = 0; 380 total_turns = 0;
381 if(total_games < 0) 381 if(total_games < 0)
382 total_games = 0; 382 total_games = 0;
383 383
384 384
385 checkScores(); 385 checkScores();
386 c.setGroup("Board"); 386 c.setGroup("Board");
387 for(i = 0; i < 4; i++) 387 for(i = 0; i < 4; i++)
388 answer[i] = c.readNumEntry(QString("Answer%1").arg(i)); 388 answer[i] = c.readNumEntry(QString("Answer%1").arg(i));
389 /* read, and parse past guesses */ 389 /* read, and parse past guesses */
390 current_go = 0; 390 current_go = 0;
391 for(j=0; j < 9; j++) { 391 for(j=0; j < 9; j++) {
392 current_guess[0] = c.readNumEntry(QString("Go%1p0").arg(j)); 392 current_guess[0] = c.readNumEntry(QString("Go%1p0").arg(j));
393 if (current_guess[0] < 0) 393 if (current_guess[0] < 0)
394 break; 394 break;
395 placeGuessPeg(0, current_guess[0]); 395 placeGuessPeg(0, current_guess[0]);
396 current_guess[1] = c.readNumEntry(QString("Go%1p1").arg(j)); 396 current_guess[1] = c.readNumEntry(QString("Go%1p1").arg(j));
397 placeGuessPeg(1, current_guess[1]); 397 placeGuessPeg(1, current_guess[1]);
398 current_guess[2] = c.readNumEntry(QString("Go%1p2").arg(j)); 398 current_guess[2] = c.readNumEntry(QString("Go%1p2").arg(j));
399 placeGuessPeg(2, current_guess[2]); 399 placeGuessPeg(2, current_guess[2]);
400 current_guess[3] = c.readNumEntry(QString("Go%1p3").arg(j)); 400 current_guess[3] = c.readNumEntry(QString("Go%1p3").arg(j));
401 placeGuessPeg(3, current_guess[3]); 401 placeGuessPeg(3, current_guess[3]);
402 checkGuess(); 402 checkGuess();
403 } 403 }
404 for(i = 0; i < 4; i++) { 404 for(i = 0; i < 4; i++) {
405 current_guess[i] = c.readNumEntry(QString("CurrentGo%1").arg(i)); 405 current_guess[i] = c.readNumEntry(QString("CurrentGo%1").arg(i));
406 if (current_guess[i] != 6) 406 if (current_guess[i] != 6)
407 placeGuessPeg(i, current_guess[i]); 407 placeGuessPeg(i, current_guess[i]);
408 } 408 }
409 } 409 }
410} 410}
411 411
412MindBreakerBoard::~MindBreakerBoard() 412MindBreakerBoard::~MindBreakerBoard()
413{ 413{
414 int i; 414 int i;
415 if (game_over) { 415 if (game_over) {
416 current_go = 0; 416 current_go = 0;
417 /* clear the answer, clear the guess */ 417 /* clear the answer, clear the guess */
418 for (i = 0; i < 4; i++) { 418 for (i = 0; i < 4; i++) {
419 answer[i] = rand() % 6; 419 answer[i] = rand() % 6;
420 current_guess[i] = 6; 420 current_guess[i] = 6;
421 } 421 }
422 } 422 }
423 writeConfig(); 423 writeConfig();
424} 424}
425 425
426void MindBreakerBoard::writeConfig() 426void MindBreakerBoard::writeConfig()
427{ 427{
428 Config c("MindBreaker", Config::User); 428 Config c("MindBreaker", Config::User);
429 c.setGroup("Board"); 429 c.setGroup("Board");
430 c.clearGroup(); 430 c.clearGroup();
431 /* write the board */ 431 /* write the board */
432 int i,j; 432 int i,j;
433 for (i = 0; i < current_go; i++) { 433 for (i = 0; i < current_go; i++) {
434 for(j = 0; j < 4; j++) 434 for(j = 0; j < 4; j++)
435 c.writeEntry(QString("Go%1p%2").arg(i).arg(j), past_guesses[4*i+j]); 435 c.writeEntry(QString("Go%1p%2").arg(i).arg(j), past_guesses[4*i+j]);
436 } 436 }
437 for(j = 0; j < 4; j++) 437 for(j = 0; j < 4; j++)
438 c.writeEntry(QString("CurrentGo%1").arg(j), current_guess[j]); 438 c.writeEntry(QString("CurrentGo%1").arg(j), current_guess[j]);
439 for(j = 0; j < 4; j++) 439 for(j = 0; j < 4; j++)
440 c.writeEntry(QString("Answer%1").arg(j), answer[j]); 440 c.writeEntry(QString("Answer%1").arg(j), answer[j]);
441 441
442 c.setGroup("Score"); 442 c.setGroup("Score");
443 /* write the score */ 443 /* write the score */
444 444
445 c.writeEntry("Turns", total_turns); 445 c.writeEntry("Turns", total_turns);
446 c.writeEntry("Games", total_games); 446 c.writeEntry("Games", total_games);
447} 447}
448 448
449void MindBreakerBoard::getScore(int *a, int *b) 449void MindBreakerBoard::getScore(int *a, int *b)
450{ 450{
451 *a = total_turns; 451 *a = total_turns;
452 *b = total_games; 452 *b = total_games;
453 return; 453 return;
454} 454}
455 455
456void MindBreakerBoard::fixSize() 456void MindBreakerBoard::fixSize()
457{ 457{
458 hide(); 458 hide();
459 setMaximumWidth( parentWidget()->height() ); 459 setMaximumWidth( parentWidget()->height() );
460 widthTimer->start( 20, TRUE ); 460 widthTimer->start( 20, TRUE );
461} 461}
462 462
463void MindBreakerBoard::doFixSize() 463void MindBreakerBoard::doFixSize()
464{ 464{
465 QSize s = size(); 465 QSize s = size();
466 int fw = frameWidth(); 466 int fw = frameWidth();
467 s.setWidth(s.width() - fw); 467 s.setWidth(s.width() - fw);
468 s.setHeight(s.height() - fw); 468 s.setHeight(s.height() - fw);
469 469
470 /* min size is 200 x 260 */ 470 /* min size is 200 x 260 */
471/* 471/*
472 if (s.width() < adjusted_board_width) 472 if (s.width() < adjusted_board_width)
473 s.setWidth(adjusted_board_width); 473 s.setWidth(adjusted_board_width);
474 474
475 if (s.height() < adjusted_board_height) 475 if (s.height() < adjusted_board_height)
476 s.setHeight(adjusted_board_height); 476 s.setHeight(adjusted_board_height);
477*/ 477*/
478 478
479 if ( current_highlight ) // non-first resize 479 if ( current_highlight ) // non-first resize
480 writeConfig(); 480 writeConfig();
481 481
482 setupBoardSize(s.width() - fw, s.height() - fw); 482 setupBoardSize(s.width() - fw, s.height() - fw);
483 canvas()->resize(s.width() - fw, s.height() - fw); 483 canvas()->resize(s.width() - fw, s.height() - fw);
484 Peg::buildImages(); // must be done BEFORE any pegs are made 484 Peg::buildImages(); // must be done BEFORE any pegs are made
485 485
486 QImage image = Resource::loadImage("mindbreaker/mindbreaker"); 486 QImage image = Resource::loadImage("mindbreaker/mindbreaker");
487 487
488 /* copy from master image to functional images */ 488 /* copy from master image to functional images */
489 int x = 0; 489 int x = 0;
490 int y = 0; 490 int y = 0;
491 panelImage = image.copy(x, y, panel_width, panel_height). 491 panelImage = image.copy(x, y, panel_width, panel_height).
492 smoothScale( adjusted_panel_width, adjusted_panel_height); 492 smoothScale( adjusted_panel_width, adjusted_panel_height);
493 493
494 y += panel_height; 494 y += panel_height;
495 y += panel_height; 495 y += panel_height;
496 496
497 titleImage = image.copy(x, y, title_width, title_height). 497 titleImage = image.copy(x, y, title_width, title_height).
498 smoothScale( adjusted_title_width, adjusted_title_height); 498 smoothScale( adjusted_title_width, adjusted_title_height);
499 show(); 499 show();
500 500
501 delete current_highlight; 501 delete current_highlight;
502 current_highlight = new Peg(canvas(), 8); 502 current_highlight = new Peg(canvas(), 8);
503 current_highlight->setPlaced(TRUE); 503 current_highlight->setPlaced(TRUE);
504 current_highlight->setX(0); 504 current_highlight->setX(0);
505 current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height)); 505 current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height));
506 current_highlight->setZ(0); 506 current_highlight->setZ(0);
507 current_highlight->show(); 507 current_highlight->show();
508 508
509 /* set up the game */ 509 /* set up the game */
510 //readConfig(); 510 //readConfig();
511 511
512 /* draw initial screen */ 512 /* draw initial screen */
513 //drawBackground(); 513 //drawBackground();
514 //canvas()->update(); 514 //canvas()->update();
515 clear(); 515 clear();
516 516
517 readConfig(); 517 readConfig();
518} 518}
519 519
520void MindBreakerBoard::placeGuessPeg(int pos, int pegId) 520void MindBreakerBoard::placeGuessPeg(int pos, int pegId)
521{ 521{
522 int x = adjusted_first_peg_x_diff + (pos * adjusted_peg_spacing); 522 int x = adjusted_first_peg_x_diff + (pos * adjusted_peg_spacing);
523 int y = adjusted_board_height - ((current_go + 1) * adjusted_panel_height) 523 int y = adjusted_board_height - ((current_go + 1) * adjusted_panel_height)
524 + adjusted_first_peg_y_diff; 524 + adjusted_first_peg_y_diff;
525 525
526 Peg *peg = new Peg(canvas(), pegId, current_go, pos); 526 Peg *peg = new Peg(canvas(), pegId, current_go, pos);
527 peg->setPegPos(pos); 527 peg->setPegPos(pos);
528 peg->setPlaced(TRUE); 528 peg->setPlaced(TRUE);
529 peg->setX(x); 529 peg->setX(x);
530 peg->setY(y); 530 peg->setY(y);
531 peg->setZ(2); 531 peg->setZ(2);
532 peg->show(); 532 peg->show();
533} 533}
534 534
535void MindBreakerBoard::drawBackground() 535void MindBreakerBoard::drawBackground()
536{ 536{
537 int i, j, x, y, x_gap, y_gap; 537 int i, j, x, y, x_gap, y_gap;
538 QPixmap background = QPixmap(canvas()->width(), canvas()->height()); 538 QPixmap background = QPixmap(canvas()->width(), canvas()->height());
539 539
540 QPainter painter(&background); 540 QPainter painter(&background);
541 541
542 painter.fillRect(0, 0, canvas()->width(), canvas()->height(), QColor(0,0,0)); 542 painter.fillRect(0, 0, canvas()->width(), canvas()->height(), QColor(0,0,0));
543 /* very first thing is to draw the bins, as everything else needs 543 /* very first thing is to draw the bins, as everything else needs
544 * to be drawn over them */ 544 * to be drawn over them */
545 545
546 QPen pen(QColor(85, 45, 27), 4); 546 QPen pen(QColor(85, 45, 27), 4);
547 painter.setPen(pen); 547 painter.setPen(pen);
548 x_gap = canvas()->width() - (adjusted_panel_width + (2 * adjusted_bin_margin)); 548 x_gap = canvas()->width() - (adjusted_panel_width + (2 * adjusted_bin_margin));
549 //x_gap += peg_size >> 1; 549 //x_gap += peg_size >> 1;
550 if (x_gap < 1) 550 if (x_gap < 1)
551 x_gap = 1; 551 x_gap = 1;
552 552
553 y_gap = adjusted_board_height / 6; 553 y_gap = adjusted_board_height / 6;
554 y_gap -= (2 * adjusted_bin_margin); 554 y_gap -= (2 * adjusted_bin_margin);
555 //y_gap += peg_size >> 1; 555 //y_gap += peg_size >> 1;
556 if (y_gap < 1) 556 if (y_gap < 1)
557 y_gap = 1; 557 y_gap = 1;
558 x = adjusted_panel_width + adjusted_bin_margin - (adjusted_peg_size >> 1); 558 x = adjusted_panel_width + adjusted_bin_margin - (adjusted_peg_size >> 1);
559 y = adjusted_bin_margin - (adjusted_peg_size >> 1) + 2; 559 y = adjusted_bin_margin - (adjusted_peg_size >> 1) + 2;
560 560
561 for (i = 0; i < 6; i++) { 561 for (i = 0; i < 6; i++) {
562 for (j = 0; j < 10; j++) { 562 for (j = 0; j < 10; j++) {
563 int rx = x + (rand() % x_gap); 563 int rx = x + (rand() % x_gap);
564 int ry = y + (rand() % y_gap); 564 int ry = y + (rand() % y_gap);
565 painter.drawImage(rx,ry, Peg::imageForType(i)); 565 painter.drawImage(rx,ry, Peg::imageForType(i));
566 } 566 }
567 y += adjusted_board_height / 6; 567 y += adjusted_board_height / 6;
568 } 568 }
569 /* now draw the surrounding boxes */ 569 /* now draw the surrounding boxes */
570 x_gap = canvas()->width() - adjusted_panel_width; 570 x_gap = canvas()->width() - adjusted_panel_width;
571 if (x_gap < 1) x_gap = 1; 571 if (x_gap < 1) x_gap = 1;
572 y_gap = adjusted_board_height / 6; 572 y_gap = adjusted_board_height / 6;
573 x = adjusted_panel_width; 573 x = adjusted_panel_width;
574 y = 1; 574 y = 1;
575 575
576 for (i = 0; i < 6; i++) { 576 for (i = 0; i < 6; i++) {
577 painter.drawRect(x, y, x_gap, y_gap); 577 painter.drawRect(x, y, x_gap, y_gap);
578 y += y_gap; 578 y += y_gap;
579 } 579 }
580 580
581 x = 0; 581 x = 0;
582 y = 0; 582 y = 0;
583 583
584 painter.drawImage(x,y, titleImage); 584 painter.drawImage(x,y, titleImage);
585 y = adjusted_title_height; 585 y = adjusted_title_height;
586 /* now nine gues panels */ 586 /* now nine gues panels */
587 for (i = 0; i < 9; i ++) { 587 for (i = 0; i < 9; i ++) {
588 painter.drawImage(x, y, panelImage); 588 painter.drawImage(x, y, panelImage);
589 y += adjusted_panel_height; 589 y += adjusted_panel_height;
590 } 590 }
591 591
592 painter.flush(); 592 painter.flush();
593 canvas()->setBackgroundPixmap(background); 593 canvas()->setBackgroundPixmap(background);
594} 594}
595 595
596void MindBreakerBoard::checkGuess() 596void MindBreakerBoard::checkGuess()
597{ 597{
598 int i,j; 598 int i,j;
599 int num_white = 0; 599 int num_white = 0;
600 int num_black = 0; 600 int num_black = 0;
601 int copy_answer[4]; 601 int copy_answer[4];
602 int copy_guess[4]; 602 int copy_guess[4];
603 603
604 for(i = 0; i < 4; i++) { 604 for(i = 0; i < 4; i++) {
605 copy_answer[i] = answer[i]; 605 copy_answer[i] = answer[i];
606 copy_guess[i] = current_guess[i]; 606 copy_guess[i] = current_guess[i];
607 if (current_guess[i] == 6) 607 if (current_guess[i] == 6)
608 return; 608 return;
609 if (answer[i] == current_guess[i]) { 609 if (answer[i] == current_guess[i]) {
610 num_black++; 610 num_black++;
611 copy_answer[i] = 6; 611 copy_answer[i] = 6;
612 copy_guess[i] = 7; 612 copy_guess[i] = 7;
613 } 613 }
614 } 614 }
615 615
616 /* now sure that user has completed a 'guess' */ 616 /* now sure that user has completed a 'guess' */
617 for (i = 0; i < 4; i++) { 617 for (i = 0; i < 4; i++) {
618 if (copy_guess[i] == 7) 618 if (copy_guess[i] == 7)
619 continue; // already marked for a black 619 continue; // already marked for a black
620 for (j = 0; j < 4; j++) { 620 for (j = 0; j < 4; j++) {
621 if(copy_guess[i] == copy_answer[j]) { 621 if(copy_guess[i] == copy_answer[j]) {
622 copy_answer[j] = 6; 622 copy_answer[j] = 6;
623 num_white++; 623 num_white++;
624 break; 624 break;
625 } 625 }
626 } 626 }
627 } 627 }
628 628
629 int x = adjusted_answerpegx; 629 int x = adjusted_answerpegx;
630 int y = (adjusted_board_height - ((current_go + 1) * adjusted_panel_height)) + adjusted_answerpegy; 630 int y = (adjusted_board_height - ((current_go + 1) * adjusted_panel_height)) + adjusted_answerpegy;
631 631
632 if (num_black == 4) 632 if (num_black == 4)
633 game_over = TRUE; 633 game_over = TRUE;
634 634
635 while(num_black > 0) { 635 while(num_black > 0) {
636 Peg *p = new Peg(canvas(), 7); 636 Peg *p = new Peg(canvas(), 7);
637 p->setPlaced(TRUE); 637 p->setPlaced(TRUE);
638 p->setX(x); 638 p->setX(x);
639 p->setY(y); 639 p->setY(y);
640 p->setZ(1); 640 p->setZ(1);
641 p->show(); 641 p->show();
642 num_black--; 642 num_black--;
643 643
644 if (x == adjusted_answerpegx) 644 if (x == adjusted_answerpegx)
645 x = adjusted_answerpegx + adjusted_answerpeg_xdiff; 645 x = adjusted_answerpegx + adjusted_answerpeg_xdiff;
646 else { 646 else {
647 x = adjusted_answerpegx; 647 x = adjusted_answerpegx;
648 y += adjusted_answerpeg_ydiff; 648 y += adjusted_answerpeg_ydiff;
649 } 649 }
650 } 650 }
651 while(num_white > 0){ 651 while(num_white > 0){
652 Peg *p = new Peg(canvas(), 6); 652 Peg *p = new Peg(canvas(), 6);
653 p->setPlaced(TRUE); 653 p->setPlaced(TRUE);
654 p->setX(x); 654 p->setX(x);
655 p->setY(y); 655 p->setY(y);
656 p->setZ(1); 656 p->setZ(1);
657 p->show(); 657 p->show();
658 num_white--; 658 num_white--;
659 659
660 if (x == adjusted_answerpegx) 660 if (x == adjusted_answerpegx)
661 x = adjusted_answerpegx + adjusted_answerpeg_xdiff; 661 x = adjusted_answerpegx + adjusted_answerpeg_xdiff;
662 else { 662 else {
663 x = adjusted_answerpegx; 663 x = adjusted_answerpegx;
664 y += adjusted_answerpeg_ydiff; 664 y += adjusted_answerpeg_ydiff;
665 } 665 }
666 } 666 }
667 /* move to next go */ 667 /* move to next go */
668 for(i = 0; i < 4; i++) { 668 for(i = 0; i < 4; i++) {
669 past_guesses[4*current_go+i] = current_guess[i]; 669 past_guesses[4*current_go+i] = current_guess[i];
670 current_guess[i] = 6; 670 current_guess[i] = 6;
671 } 671 }
672 672
673 current_go++; 673 current_go++;
674 if((current_go > 8) || game_over) { 674 if((current_go > 8) || game_over) {
675 total_games++; 675 total_games++;
676 if(!game_over) 676 if(!game_over)
677 total_turns += 10; 677 total_turns += 10;
678 else 678 else
679 total_turns += current_go; 679 total_turns += current_go;
680 680
681 emit scoreChanged(total_turns, total_games); 681 emit scoreChanged(total_turns, total_games);
682 Peg *p = new Peg(canvas(), 9); 682 Peg *p = new Peg(canvas(), 9);
683 game_over = TRUE; 683 game_over = TRUE;
684 p->setPlaced(TRUE); 684 p->setPlaced(TRUE);
685 p->setX(0); 685 p->setX(0);
686 p->setY(0); 686 p->setY(0);
687 p->setZ(0); 687 p->setZ(0);
688 p->show(); 688 p->show();
689 689
690 for (i = 0; i < 4; i++) { 690 for (i = 0; i < 4; i++) {
691 p = new Peg(canvas(), answer[i], -1); 691 p = new Peg(canvas(), answer[i], -1);
692 p->setX(adjusted_first_peg_x_diff + (i * adjusted_peg_spacing)); 692 p->setX(adjusted_first_peg_x_diff + (i * adjusted_peg_spacing));
693 p->setY(adjusted_first_peg_y_diff); 693 p->setY(adjusted_first_peg_y_diff);
694 p->setZ(3); 694 p->setZ(3);
695 p->show(); 695 p->show();
696 } 696 }
697 } else { 697 } else {
698 current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height)); 698 current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height));
699 } 699 }
700 canvas()->update(); 700 canvas()->update();
701} 701}
702 702
703void MindBreakerBoard::clear() 703void MindBreakerBoard::clear()
704{ 704{
705 if(!game_over) { 705 if(!game_over) {
706 total_games++; 706 total_games++;
707 total_turns += 10; 707 total_turns += 10;
708 emit scoreChanged(total_turns, total_games); 708 emit scoreChanged(total_turns, total_games);
709 } 709 }
710 int i; 710 int i;
711 /* reset the game board */ 711 /* reset the game board */
712 game_over = FALSE; 712 game_over = FALSE;
713 /* clear the answer, clear the guess */ 713 /* clear the answer, clear the guess */
714 for (i = 0; i < 4; i++) { 714 for (i = 0; i < 4; i++) {
715 answer[i] = rand() % 6; 715 answer[i] = rand() % 6;
716 current_guess[i] = 6; 716 current_guess[i] = 6;
717 } 717 }
718 current_go = 0; 718 current_go = 0;
719 719
720 QCanvasItemList list = canvas()->allItems(); 720 QCanvasItemList list = canvas()->allItems();
721 QCanvasItemList::Iterator it = list.begin(); 721 QCanvasItemList::Iterator it = list.begin();
722 for (; it != list.end(); ++it) { 722 for (; it != list.end(); ++it) {
723 if (*it == current_highlight) 723 if (*it == current_highlight)
724 continue; 724 continue;
725 if (*it) 725 if (*it)
726 delete *it; 726 delete *it;
727 } 727 }
728 728
729 current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height)); 729 current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height));
730 checkScores(); 730 checkScores();
731 drawBackground(); 731 drawBackground();
732 canvas()->update(); 732 canvas()->update();
733} 733}
734 734
735void MindBreakerBoard::resetScore() 735void MindBreakerBoard::resetScore()
736{ 736{
737 /* are u sure */ 737 /* are u sure */
738 738
739 if (QMessageBox::information(this, tr( "Reset Statistics" ), 739 if (QMessageBox::information(this, tr( "Reset Statistics" ),
740 tr( "Reset the win ratio?" ), 740 tr( "Reset the win ratio?" ),
741 tr( "OK" ), tr( "Cancel" ) ) == 0) { 741 tr( "OK" ), tr( "Cancel" ) ) == 0) {
742 total_turns = 0; 742 total_turns = 0;
743 total_games = 0; 743 total_games = 0;
744 Peg::eggLevel = 0; 744 Peg::eggLevel = 0;
745 drawBackground(); 745 drawBackground();
746 canvas()->update(); 746 canvas()->update();
747 emit scoreChanged(total_turns, total_games); 747 emit scoreChanged(total_turns, total_games);
748 } 748 }
749} 749}
750 750
751/* EVENTS */ 751/* EVENTS */
752 752
753void MindBreakerBoard::contentsMousePressEvent(QMouseEvent *e) 753void MindBreakerBoard::contentsMousePressEvent(QMouseEvent *e)
754{ 754{
755 if (game_over) { 755 if (game_over) {
756 null_press = TRUE; 756 null_press = TRUE;
757 null_point = e->pos(); 757 null_point = e->pos();
758 moving = 0; 758 moving = 0;
759 return; 759 return;
760 } 760 }
761 761
762 copy_press = FALSE; 762 copy_press = FALSE;
763 null_press = FALSE; 763 null_press = FALSE;
764 /* ok, first work out if it is one of the bins that 764 /* ok, first work out if it is one of the bins that
765 got clicked */ 765 got clicked */
766 if (e->x() > adjusted_panel_width) { 766 if (e->x() > adjusted_panel_width) {
767 /* its a bin, but which bin */ 767 /* its a bin, but which bin */
768 int bin = (e->y() + 2) / (adjusted_board_height / 6); 768 int bin = (e->y() + 2) / (adjusted_board_height / 6);
769 if (bin > 5) 769 if (bin > 5)
770 return; // missed everything 770 return; // missed everything
771 771
772 /* make new peg... set it moving */ 772 /* make new peg... set it moving */
773 moving_pos = e->pos(); 773 moving_pos = e->pos();
774 moving = new Peg(canvas(), bin, current_go); 774 moving = new Peg(canvas(), bin, current_go);
775 moving->setX(e->x() - (adjusted_peg_size >> 1)); 775 moving->setX(e->x() - (adjusted_peg_size >> 1));
776 moving->setY(e->y() - (adjusted_peg_size >> 1)); 776 moving->setY(e->y() - (adjusted_peg_size >> 1));
777 moving->setZ(5); 777 moving->setZ(5);
778 moving->show(); 778 moving->show();
779 canvas()->update(); 779 canvas()->update();
780 return; 780 return;
781 } 781 }
782 782
783 QCanvasItemList l = canvas()->collisions(e->pos()); 783 QCanvasItemList l = canvas()->collisions(e->pos());
784 for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) { 784 for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) {
785 if ( (*it)->rtti() == pegRTTI ) { 785 if ( (*it)->rtti() == pegRTTI ) {
786 Peg *item = (Peg *)(*it); 786 Peg *item = (Peg *)(*it);
787 if (!item->hit(e->pos())) 787 if (!item->hit(e->pos()))
788 continue; 788 continue;
789 if (item->type() > 5) { 789 if (item->type() > 5) {
790 null_press = TRUE; 790 null_press = TRUE;
791 null_point = e->pos(); 791 null_point = e->pos();
792 continue; /* not a color peg */ 792 continue; /* not a color peg */
793 } 793 }
794 if (item->placed()) { 794 if (item->placed()) {
795 /* copy */ 795 /* copy */
796 if(item->pegGo() == -1) 796 if(item->pegGo() == -1)
797 return; 797 return;
798 if(item->pegGo() == current_go) { 798 if(item->pegGo() == current_go) {
799 copy_press = TRUE; 799 copy_press = TRUE;
800 copy_peg = item; 800 copy_peg = item;
801 } 801 }
802 moving = new Peg(canvas(), 802 moving = new Peg(canvas(),
803 item->type(), current_go); 803 item->type(), current_go);
804 moving->setX(e->x() - (adjusted_peg_size >> 1)); 804 moving->setX(e->x() - (adjusted_peg_size >> 1));
805 moving->setY(e->y() - (adjusted_peg_size >> 1)); 805 moving->setY(e->y() - (adjusted_peg_size >> 1));
806 moving->setZ(5); 806 moving->setZ(5);
807 moving->show(); 807 moving->show();
808 moving_pos = QPoint(e->x(), e->y()); 808 moving_pos = QPoint(e->x(), e->y());
809 canvas()->update(); 809 canvas()->update();
810 return; 810 return;
811 } 811 }
812 moving = (Peg *)*it; 812 moving = (Peg *)*it;
813 moving_pos = e->pos(); 813 moving_pos = e->pos();
814 canvas()->update(); 814 canvas()->update();
815 return; 815 return;
816 } 816 }
817 } 817 }
818 null_press = TRUE; 818 null_press = TRUE;
819 null_point = e->pos(); 819 null_point = e->pos();
820 moving = 0; 820 moving = 0;
821} 821}
822 822
823void MindBreakerBoard::contentsMouseMoveEvent(QMouseEvent* e) 823void MindBreakerBoard::contentsMouseMoveEvent(QMouseEvent* e)
824{ 824{
825 if (moving ) { 825 if (moving ) {
826 moving->moveBy(e->pos().x() - moving_pos.x(), 826 moving->moveBy(e->pos().x() - moving_pos.x(),
827 e->pos().y() - moving_pos.y()); 827 e->pos().y() - moving_pos.y());
828 moving_pos = e->pos(); 828 moving_pos = e->pos();
829 canvas()->update(); 829 canvas()->update();
830 return; 830 return;
831 } 831 }
832} 832}
833 833
834void MindBreakerBoard::contentsMouseReleaseEvent(QMouseEvent* e) 834void MindBreakerBoard::contentsMouseReleaseEvent(QMouseEvent* e)
835{ 835{
836 /* time to put down the peg */ 836 /* time to put down the peg */
837 if(moving) { 837 if(moving) {
838 if(copy_press) { 838 if(copy_press) {
839 /* check if collided with original. if so, delete both */ 839 /* check if collided with original. if so, delete both */
840 copy_press = FALSE; 840 copy_press = FALSE;
841 QCanvasItemList l = canvas()->collisions(e->pos()); 841 QCanvasItemList l = canvas()->collisions(e->pos());
842 for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) { 842 for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) {
843 if (*it == copy_peg) 843 if (*it == copy_peg)
844 copy_press = TRUE; 844 copy_press = TRUE;
845 } 845 }
846 if (copy_press) { 846 if (copy_press) {
847 current_guess[copy_peg->pegPos()] = 6; 847 current_guess[copy_peg->pegPos()] = 6;
848 delete copy_peg; 848 delete copy_peg;
849 delete moving; 849 delete moving;
850 copy_press = FALSE; 850 copy_press = FALSE;
851 moving = 0; 851 moving = 0;
852 copy_peg = 0; 852 copy_peg = 0;
853 canvas()->update(); 853 canvas()->update();
854 return; 854 return;
855 } 855 }
856 } 856 }
857 857
858 /* first work out if in y */ 858 /* first work out if in y */
859 if (e->y() > (adjusted_board_height - (current_go * adjusted_panel_height))) { 859 if (e->y() > (adjusted_board_height - (current_go * adjusted_panel_height))) {
860 delete moving; 860 delete moving;
861 moving = 0; 861 moving = 0;
862 canvas()->update(); 862 canvas()->update();
863 return; 863 return;
864 } 864 }
865 if (e->y() < (adjusted_board_height - ((current_go + 1) * adjusted_panel_height))) { 865 if (e->y() < (adjusted_board_height - ((current_go + 1) * adjusted_panel_height))) {
866 delete moving; 866 delete moving;
867 moving = 0; 867 moving = 0;
868 canvas()->update(); 868 canvas()->update();
869 return; 869 return;
870 } 870 }
871 /* ok, a valid go, but which peg */ 871 /* ok, a valid go, but which peg */
872 int x_bar = adjusted_first_peg_x_diff - (adjusted_peg_size >> 1); 872 int x_bar = adjusted_first_peg_x_diff - (adjusted_peg_size >> 1);
873 x_bar += adjusted_peg_spacing; 873 x_bar += adjusted_peg_spacing;
874 int pos = 0; 874 int pos = 0;
875 if (e->x() > x_bar) 875 if (e->x() > x_bar)
876 pos = 1; 876 pos = 1;
877 x_bar += adjusted_peg_spacing; 877 x_bar += adjusted_peg_spacing;
878 if (e->x() > x_bar) 878 if (e->x() > x_bar)
879 pos = 2; 879 pos = 2;
880 x_bar += adjusted_peg_spacing; 880 x_bar += adjusted_peg_spacing;
881 if (e->x() > x_bar) 881 if (e->x() > x_bar)
882 pos = 3; 882 pos = 3;
883 x_bar += adjusted_peg_spacing; 883 x_bar += adjusted_peg_spacing;
884 884
885 if (e->x() > x_bar) { 885 if (e->x() > x_bar) {
886 /* invalid x */ 886 /* invalid x */
887 delete moving; 887 delete moving;
888 moving = 0; 888 moving = 0;
889 canvas()->update(); 889 canvas()->update();
890 return; 890 return;
891 } 891 }
892 892
893 int x = adjusted_first_peg_x_diff + (pos * adjusted_peg_spacing); 893 int x = adjusted_first_peg_x_diff + (pos * adjusted_peg_spacing);
894 int y = adjusted_board_height - ((current_go + 1) * adjusted_panel_height) 894 int y = adjusted_board_height - ((current_go + 1) * adjusted_panel_height)
895 + adjusted_first_peg_y_diff; 895 + adjusted_first_peg_y_diff;
896 moving->setPegPos(pos); 896 moving->setPegPos(pos);
897 moving->setX(x); 897 moving->setX(x);
898 moving->setY(y); 898 moving->setY(y);
899 moving->setZ(2); 899 moving->setZ(2);
900 900
901 /* remove all other pegs from this position */ 901 /* remove all other pegs from this position */
902 QCanvasItemList l = canvas()->collisions(QPoint(x,y)); 902 QCanvasItemList l = canvas()->collisions(QPoint(x,y));
903 for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) { 903 for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) {
904 if ( (*it)->rtti() == pegRTTI ) { 904 if ( (*it)->rtti() == pegRTTI ) {
905 Peg *item = (Peg *)(*it); 905 Peg *item = (Peg *)(*it);
906 if ((item != moving) && (item != current_highlight)) 906 if ((item != moving) && (item != current_highlight))
907 delete item; 907 delete item;
908 } 908 }
909 } 909 }
910 current_guess[pos] = ((Peg *)moving)->type(); 910 current_guess[pos] = ((Peg *)moving)->type();
911 911
912 ((Peg *)moving)->setPlaced(true); 912 ((Peg *)moving)->setPlaced(true);
913 canvas()->update(); 913 canvas()->update();
914 return; 914 return;
915 } 915 }
916 moving = 0; 916 moving = 0;
917 null_point -= e->pos(); 917 null_point -= e->pos();
918 if(null_point.manhattanLength() < 6) { 918 if(null_point.manhattanLength() < 6) {
919 if (game_over) 919 if (game_over)
920 clear(); 920 clear();
921 else 921 else
922 checkGuess(); 922 checkGuess();
923 } 923 }
924} 924}
925 925
926void MindBreakerBoard::resizeEvent(QResizeEvent *e) 926void MindBreakerBoard::resizeEvent(QResizeEvent *e)
927{ 927{
928 QCanvasView::resizeEvent(e); 928 QCanvasView::resizeEvent(e);
929 fixSize(); 929 fixSize();
930} 930}
931 931
932 932
933/* Easter egg function... beat the clock */ 933/* Easter egg function... beat the clock */
934void MindBreakerBoard::checkScores() 934void MindBreakerBoard::checkScores()
935{ 935{
936 double games = total_games; 936 double games = total_games;
937 double turns = total_turns; 937 double turns = total_turns;
938 double g = games / 10.0; 938 double g = games / 10.0;
939 Peg::eggLevel = 0; 939 Peg::eggLevel = 0;
940 940
941 double break_even = 5.0; 941 double break_even = 5.0;
942 if (g < 1.0) 942 if (g < 1.0)
943 return; 943 return;
944 double avg = turns / games; 944 double avg = turns / games;
945 g--; 945 g--;
946 while (break_even >= 0.0) { 946 while (break_even >= 0.0) {
947 if (avg >= (break_even + g)) 947 if (avg >= (break_even + g))
948 return; 948 return;
949 // score a peg. 949 // score a peg.
950 break_even -= 1.0; 950 break_even -= 1.0;
951 Peg::eggLevel = int(5.0 - break_even); 951 Peg::eggLevel = int(5.0 - break_even);
952 } 952 }
953} 953}
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,687 +1,693 @@
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;
491 case 4: 497 case 4:
492 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 498 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
493 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 499 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
494 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 500 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
495 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 501 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
496 break; 502 break;
497 case 5: 503 case 5:
498 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 504 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
499 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 505 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
500 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 506 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
501 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 507 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
502 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 508 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
503 break; 509 break;
504 case 6: 510 case 6:
505 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 511 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
506 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 512 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
507 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 513 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
508 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 514 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
509 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 515 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
510 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 516 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
511 break; 517 break;
512 } 518 }
513} 519}
514 520
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
@@ -1,1510 +1,1510 @@
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#include "wordgame.h" 22#include "wordgame.h"
23 23
24#include <qpe/global.h> 24#include <qpe/global.h>
25#include <qpe/resource.h> 25#include <qpe/resource.h>
26#include <qpe/config.h> 26#include <qpe/config.h>
27 27
28#include <qapplication.h> 28#include <qapplication.h>
29#include <qmessagebox.h> 29#include <qmessagebox.h>
30#include <qcombobox.h> 30#include <qcombobox.h>
31#include <qdir.h> 31#include <qdir.h>
32#include <qlineedit.h> 32#include <qlineedit.h>
33#include <qpushbutton.h> 33#include <qpushbutton.h>
34#include <qtextstream.h> 34#include <qtextstream.h>
35#include <qtimer.h> 35#include <qtimer.h>
36#include <qtoolbar.h> 36#include <qtoolbar.h>
37#include <qtoolbutton.h> 37#include <qtoolbutton.h>
38#include <qvbox.h> 38#include <qvbox.h>
39#include <qwidgetstack.h> 39#include <qwidgetstack.h>
40#include <qlayout.h> 40#include <qlayout.h>
41 41
42#include <stdlib.h> 42#include <stdlib.h>
43#include <unistd.h> 43#include <unistd.h>
44#include <pwd.h> 44#include <pwd.h>
45#include <sys/types.h> 45#include <sys/types.h>
46 46
47enum RuleEffects { 47enum RuleEffects {
48 Multiplier=15, 48 Multiplier=15,
49 MultiplyAll=64, 49 MultiplyAll=64,
50 Start=128 50 Start=128
51}; 51};
52 52
53static int tile_smallw = 16; 53static int tile_smallw = 16;
54static int tile_smallh = 16; 54static int tile_smallh = 16;
55static int tile_bigw = 22; 55static int tile_bigw = 22;
56static int tile_bigh = 22; 56static int tile_bigh = 22;
57static int tile_stweak = -2; 57static int tile_stweak = -2;
58static int tile_btweak = -1; 58static int tile_btweak = -1;
59 59
60static const int rack_tiles=7; 60static const int rack_tiles=7;
61 61
62const char* sampleWGR= 62const char* sampleWGR=
63 "wordgame_shapes\n" 63 "wordgame_shapes\n"
64 "15 15\n" 64 "15 15\n"
65 "400001040100004\n" 65 "400001040100004\n"
66 "030000000000030\n" 66 "030000000000030\n"
67 "002002000200200\n" 67 "002002000200200\n"
68 "000300020003000\n" 68 "000300020003000\n"
69 "000020000020000\n" 69 "000020000020000\n"
70 "102001000100201\n" 70 "102001000100201\n"
71 "000000202000000\n" 71 "000000202000000\n"
72 "400200050002004\n" 72 "400200050002004\n"
73 "000000202000000\n" 73 "000000202000000\n"
74 "102001000100201\n" 74 "102001000100201\n"
75 "000020000020000\n" 75 "000020000020000\n"
76 "000300020003000\n" 76 "000300020003000\n"
77 "002002000200200\n" 77 "002002000200200\n"
78 "030000000000030\n" 78 "030000000000030\n"
79 "400001040100004\n" 79 "400001040100004\n"
80 "1 2 3 66 67 194 100 0\n" 80 "1 2 3 66 67 194 100 0\n"
81 "1 j 8\n" 81 "1 j 8\n"
82 "1 q 7\n" 82 "1 q 7\n"
83 "1 x 6\n" 83 "1 x 6\n"
84 "1 z 6\n" 84 "1 z 6\n"
85 "1 w 4\n" 85 "1 w 4\n"
86 "1 k 4\n" 86 "1 k 4\n"
87 "1 v 3\n" 87 "1 v 3\n"
88 "1 f 3\n" 88 "1 f 3\n"
89 "2 y 3\n" 89 "2 y 3\n"
90 "2 h 2\n" 90 "2 h 2\n"
91 "2 b 2\n" 91 "2 b 2\n"
92 "2 m 2\n" 92 "2 m 2\n"
93 "3 p 2\n" 93 "3 p 2\n"
94 "3 g 2\n" 94 "3 g 2\n"
95 "3 u 2\n" 95 "3 u 2\n"
96 "4 d 2\n" 96 "4 d 2\n"
97 "4 c 2\n" 97 "4 c 2\n"
98 "5 l 1\n" 98 "5 l 1\n"
99 "5 o 1\n" 99 "5 o 1\n"
100 "7 t 1\n" 100 "7 t 1\n"
101 "7 n 1\n" 101 "7 n 1\n"
102 "7 a 1\n" 102 "7 a 1\n"
103 "7 r 1\n" 103 "7 r 1\n"
104 "8 s 1\n" 104 "8 s 1\n"
105 "8 i 1\n" 105 "8 i 1\n"
106 "11 e 1\n" 106 "11 e 1\n"
107 "0\n"; 107 "0\n";
108 108
109WordGame::WordGame( QWidget* parent, const char* name, WFlags fl ) : 109WordGame::WordGame( QWidget* parent, const char* name, WFlags fl ) :
110 QMainWindow(parent, name, fl) 110 QMainWindow(parent, name, fl)
111{ 111{
112 if ( qApp->desktop()->width() < 240 ) { 112 if ( qApp->desktop()->width() < 240 ) {
113 tile_smallw = 10; 113 tile_smallw = 10;
114 tile_smallh = 10; 114 tile_smallh = 10;
115 tile_bigw = 16; 115 tile_bigw = 16;
116 tile_bigh = 16; 116 tile_bigh = 16;
117 tile_stweak = 0; 117 tile_stweak = 0;
118 tile_btweak = 0; 118 tile_btweak = 0;
119 } 119 }
120 120
121 setIcon( Resource::loadPixmap( "wordgame/WordGame.png" ) ); 121 setIcon( Resource::loadPixmap( "wordgame/WordGame.png" ) );
122 setCaption( tr("Word Game") ); 122 setCaption( tr("Word Game") );
123 123
124 setToolBarsMovable( FALSE ); 124 setToolBarsMovable( FALSE );
125 vbox = new QVBox(this); 125 vbox = new QVBox(this);
126 126
127 setCentralWidget(vbox); 127 setCentralWidget(vbox);
128 toolbar = new QToolBar(this); 128 toolbar = new QToolBar(this);
129 addToolBar(toolbar, Bottom); 129 addToolBar(toolbar, Bottom);
130 reset = new QToolButton(Resource::loadPixmap("back"), tr("Back"), "", this, SLOT(resetTurn()), toolbar); 130 reset = new QToolButton(Resource::loadPixmap("back"), tr("Back"), "", this, SLOT(resetTurn()), toolbar);
131 done = new QToolButton(Resource::loadPixmap("done"), tr("Done"), "", this, SLOT(endTurn()), toolbar); 131 done = new QToolButton(Resource::loadPixmap("done"), tr("Done"), "", this, SLOT(endTurn()), toolbar);
132 scoreinfo = new ScoreInfo(toolbar); 132 scoreinfo = new ScoreInfo(toolbar);
133 scoreinfo->setFont(QFont("Helvetica",10)); 133 scoreinfo->setFont(QFont("Helvetica",10));
134 new QToolButton(Resource::loadPixmap("finish"), tr("Close"), "", this, SLOT(endGame()), toolbar); 134 new QToolButton(Resource::loadPixmap("finish"), tr("Close"), "", this, SLOT(endGame()), toolbar);
135 toolbar->setStretchableWidget(scoreinfo); 135 toolbar->setStretchableWidget(scoreinfo);
136 136
137 cpu = 0; 137 cpu = 0;
138 board = 0; 138 board = 0;
139 bag = 0; 139 bag = 0;
140 racks = 0; 140 racks = 0;
141 141
142 aiheart = new QTimer(this); 142 aiheart = new QTimer(this);
143 connect(aiheart, SIGNAL(timeout()), this, SLOT(think())); 143 connect(aiheart, SIGNAL(timeout()), this, SLOT(think()));
144 144
145 readConfig(); 145 readConfig();
146} 146}
147 147
148WordGame::~WordGame() 148WordGame::~WordGame()
149{ 149{
150 writeConfig(); 150 writeConfig();
151} 151}
152 152
153void WordGame::writeConfig() 153void WordGame::writeConfig()
154{ 154{
155 Config cfg("WordGame"); 155 Config cfg("WordGame");
156 cfg.setGroup("Game"); 156 cfg.setGroup("Game");
157 cfg.writeEntry("NameList",namelist,';'); 157 cfg.writeEntry("NameList",namelist,';');
158 cfg.writeEntry("CurrentPlayer",gameover ? 0 : player+1); 158 cfg.writeEntry("CurrentPlayer",gameover ? 0 : player+1);
159 if ( !gameover ) { 159 if ( !gameover ) {
160 cfg.writeEntry("Rules",rules); 160 cfg.writeEntry("Rules",rules);
161 bag->writeConfig(cfg); 161 bag->writeConfig(cfg);
162 board->writeConfig(cfg); 162 board->writeConfig(cfg);
163 scoreinfo->writeConfig(cfg); 163 scoreinfo->writeConfig(cfg);
164 } 164 }
165 for (int p=0; p<nplayers; p++) { 165 for (int p=0; p<nplayers; p++) {
166 cfg.setGroup("Player"+QString::number(p+1)); 166 cfg.setGroup("Player"+QString::number(p+1));
167 if ( gameover ) cfg.clearGroup(); else rack(p)->writeConfig(cfg); 167 if ( gameover ) cfg.clearGroup(); else rack(p)->writeConfig(cfg);
168 } 168 }
169} 169}
170 170
171void WordGame::readConfig() 171void WordGame::readConfig()
172{ 172{
173 Config cfg("WordGame"); 173 Config cfg("WordGame");
174 cfg.setGroup("Game"); 174 cfg.setGroup("Game");
175 int currentplayer = cfg.readNumEntry("CurrentPlayer",0); 175 int currentplayer = cfg.readNumEntry("CurrentPlayer",0);
176 QStringList pnames = cfg.readListEntry("NameList",';'); 176 QStringList pnames = cfg.readListEntry("NameList",';');
177 if ( currentplayer ) { 177 if ( currentplayer ) {
178 gameover = FALSE; 178 gameover = FALSE;
179 rules = cfg.readEntry("Rules"); 179 rules = cfg.readEntry("Rules");
180 if ( rules.find("x-wordgamerules") >= 0 ) { 180 if ( rules.find("x-wordgamerules") >= 0 ) {
181 // rules files moved 181 // rules files moved
182 rules = "Sample.rules"; 182 rules = "Sample.rules";
183 } 183 }
184 if ( loadRules(rules) ) { 184 if ( loadRules(rules) ) {
185 startGame(pnames); 185 startGame(pnames);
186 bag->readConfig(cfg); 186 bag->readConfig(cfg);
187 board->readConfig(cfg); 187 board->readConfig(cfg);
188 scoreinfo->readConfig(cfg); 188 scoreinfo->readConfig(cfg);
189 for (int p=0; p<nplayers; p++) { 189 for (int p=0; p<nplayers; p++) {
190 cfg.setGroup("Player"+QString::number(p+1)); 190 cfg.setGroup("Player"+QString::number(p+1));
191 rack(p)->readConfig(cfg); 191 rack(p)->readConfig(cfg);
192 } 192 }
193 player=currentplayer-1; 193 player=currentplayer-1;
194 readyRack(player); 194 readyRack(player);
195 return; 195 return;
196 } 196 }
197 } 197 }
198 // fall-back 198 // fall-back
199 openGameSelector(pnames); 199 openGameSelector(pnames);
200} 200}
201 201
202void WordGame::openGameSelector(const QStringList& initnames) 202void WordGame::openGameSelector(const QStringList& initnames)
203{ 203{
204 toolbar->hide(); 204 toolbar->hide();
205 gameover = FALSE; 205 gameover = FALSE;
206 206
207 delete board; 207 delete board;
208 board = 0; 208 board = 0;
209 delete racks; 209 delete racks;
210 racks = 0; 210 racks = 0;
211 211
212 delete cpu; 212 delete cpu;
213 cpu = 0; 213 cpu = 0;
214 214
215 newgame = new NewGame(vbox); 215 newgame = new NewGame(vbox);
216 216
217 //Rules rules(this); 217 //Rules rules(this);
218 //connect(game.editrules, SIGNAL(clicked()), &rules, SLOT(editRules())); 218 //connect(game.editrules, SIGNAL(clicked()), &rules, SLOT(editRules()));
219 //connect(&rules, SIGNAL(rulesChanged()), &game, SLOT(updateRuleSets())); 219 //connect(&rules, SIGNAL(rulesChanged()), &game, SLOT(updateRuleSets()));
220 struct passwd* n = getpwuid(getuid()); 220 struct passwd* n = getpwuid(getuid());
221 QString playername = n ? n->pw_name : ""; 221 QString playername = n ? n->pw_name : "";
222 if ( playername.isEmpty() ) { 222 if ( playername.isEmpty() ) {
223 playername = "Player"; 223 playername = "Player";
224 } 224 }
225 newgame->player0->changeItem(playername,0); 225 newgame->player0->changeItem(playername,0);
226 newgame->player1->setCurrentItem(1); 226 newgame->player1->setCurrentItem(1);
227 newgame->updateRuleSets(); 227 newgame->updateRuleSets();
228 newgame->show(); 228 newgame->show();
229 229
230 connect(newgame->buttonOk, SIGNAL(clicked()), this, SLOT(startGame())); 230 connect(newgame->buttonOk, SIGNAL(clicked()), this, SLOT(startGame()));
231} 231}
232 232
233void WordGame::startGame() 233void WordGame::startGame()
234{ 234{
235 rules = newgame->ruleslist[newgame->rules->currentItem()]; 235 rules = newgame->ruleslist[newgame->rules->currentItem()];
236 if ( loadRules(rules) ) { 236 if ( loadRules(rules) ) {
237 QStringList names; 237 QStringList names;
238 names.append(newgame->player0->currentText()); 238 names.append(newgame->player0->currentText());
239 names.append(newgame->player1->currentText()); 239 names.append(newgame->player1->currentText());
240 names.append(newgame->player2->currentText()); 240 names.append(newgame->player2->currentText());
241 names.append(newgame->player3->currentText()); 241 names.append(newgame->player3->currentText());
242 names.append(newgame->player4->currentText()); 242 names.append(newgame->player4->currentText());
243 names.append(newgame->player5->currentText()); 243 names.append(newgame->player5->currentText());
244 delete newgame; 244 delete newgame;
245 startGame(names); 245 startGame(names);
246 } else { 246 } else {
247 // error... 247 // error...
248 delete newgame; 248 delete newgame;
249 close(); 249 close();
250 } 250 }
251} 251}
252 252
253void WordGame::startGame(const QStringList& playerlist) 253void WordGame::startGame(const QStringList& playerlist)
254{ 254{
255 toolbar->show(); 255 toolbar->show();
256 racks = new QWidgetStack(vbox); 256 racks = new QWidgetStack(vbox);
257 racks->setFixedHeight(TileItem::bigHeight()+2); 257 racks->setFixedHeight(TileItem::bigHeight()+2);
258 namelist.clear(); 258 namelist.clear();
259 nplayers=0; 259 nplayers=0;
260 for (QStringList::ConstIterator it=playerlist.begin(); it!=playerlist.end(); ++it) 260 for (QStringList::ConstIterator it=playerlist.begin(); it!=playerlist.end(); ++it)
261 addPlayer(*it); 261 addPlayer(*it);
262 scoreinfo->init(namelist); 262 scoreinfo->init(namelist);
263 263
264 if ( nplayers ) { 264 if ( nplayers ) {
265 player=0; 265 player=0;
266 readyRack(player); 266 readyRack(player);
267 } 267 }
268 268
269 board->show(); 269 board->show();
270 racks->show(); 270 racks->show();
271} 271}
272 272
273bool WordGame::loadRules(const QString &name) 273bool WordGame::loadRules(const QString &name)
274{ 274{
275 QString filename = Global::applicationFileName( "wordgame", name ); 275 QString filename = Global::applicationFileName( "wordgame", name );
276 QFile file( filename ); 276 QFile file( filename );
277 if ( !file.open( IO_ReadOnly ) ) 277 if ( !file.open( IO_ReadOnly ) )
278 return FALSE; 278 return FALSE;
279 279
280 QTextStream ts( &file ); 280 QTextStream ts( &file );
281 281
282 QString title = name; 282 QString title = name;
283 title.truncate( title.length() - 6 ); 283 title.truncate( title.length() - 6 );
284 //setCaption( title ); 284 //setCaption( title );
285 285
286 QString shapepixmap; 286 QString shapepixmap;
287 ts >> shapepixmap; 287 ts >> shapepixmap;
288 int htiles,vtiles; 288 int htiles,vtiles;
289 ts >> htiles >> vtiles; 289 ts >> htiles >> vtiles;
290 290
291 if ( htiles < 3 || vtiles < 3 ) 291 if ( htiles < 3 || vtiles < 3 )
292 return FALSE; 292 return FALSE;
293 293
294 QString rule_shapes; 294 QString rule_shapes;
295 for (int i=0; i<vtiles; i++) { 295 for (int i=0; i<vtiles; i++) {
296 QString line; 296 QString line;
297 ts >> line; 297 ts >> line;
298 rule_shapes += line; 298 rule_shapes += line;
299 } 299 }
300 static int rule_effects[12]; 300 static int rule_effects[12];
301 int re=0,e; 301 int re=0,e;
302 ts >> e; 302 ts >> e;
303 while ( e && re < 10 ) { 303 while ( e && re < 10 ) {
304 rule_effects[re] = e; 304 rule_effects[re] = e;
305 if ( re++ < 10 ) ts >> e; 305 if ( re++ < 10 ) ts >> e;
306 } 306 }
307 307
308 QImage shim = Resource::loadImage("wordgame/wordgame_shapes"); 308 QImage shim = Resource::loadImage("wordgame/wordgame_shapes");
309 shim = shim.smoothScale((re-1)*TileItem::smallWidth(),TileItem::smallHeight()); 309 shim = shim.smoothScale((re-1)*TileItem::smallWidth(),TileItem::smallHeight());
310 QPixmap bgshapes; 310 QPixmap bgshapes;
311 bgshapes.convertFromImage(shim); 311 bgshapes.convertFromImage(shim);
312 312
313 rule_effects[re++] = 100; // default bonus 313 rule_effects[re++] = 100; // default bonus
314 board = new Board(bgshapes, htiles, vtiles, vbox); 314 board = new Board(bgshapes, htiles, vtiles, vbox);
315 board->setRules(rule_shapes, rule_effects); 315 board->setRules(rule_shapes, rule_effects);
316 connect(board, SIGNAL(temporaryScore(int)), scoreinfo, SLOT(showTemporaryScore(int))); 316 connect(board, SIGNAL(temporaryScore(int)), scoreinfo, SLOT(showTemporaryScore(int)));
317 317
318 bag = new Bag; 318 bag = new Bag;
319 319
320 int count; 320 int count;
321 ts >> count; 321 ts >> count;
322 while ( count ) { 322 while ( count ) {
323 QString text; 323 QString text;
324 int value; 324 int value;
325 ts >> text >> value; 325 ts >> text >> value;
326 if ( text == "_" ) 326 if ( text == "_" )
327 text = ""; 327 text = "";
328 328
329 Tile t(text, value); 329 Tile t(text, value);
330 for (int n=count; n--; ) 330 for (int n=count; n--; )
331 bag->add(t); 331 bag->add(t);
332 332
333 ts >> count; 333 ts >> count;
334 } 334 }
335 335
336 return TRUE; 336 return TRUE;
337} 337}
338 338
339 339
340NewGame::NewGame(QWidget* parent) : 340NewGame::NewGame(QWidget* parent) :
341 NewGameBase(parent) 341 NewGameBase(parent)
342{ 342{
343} 343}
344 344
345void NewGame::updateRuleSets() 345void NewGame::updateRuleSets()
346{ 346{
347 rules->clear(); 347 rules->clear();
348 348
349 QString rulesDir = Global::applicationFileName( "wordgame", "" ); 349 QString rulesDir = Global::applicationFileName( "wordgame", "" );
350 QDir dir( rulesDir, "*.rules" ); 350 QDir dir( rulesDir, "*.rules" );
351 ruleslist = dir.entryList(); 351 ruleslist = dir.entryList();
352 if ( ruleslist.isEmpty() ) { 352 if ( ruleslist.isEmpty() ) {
353 // Provide a sample 353 // Provide a sample
354 QFile file( rulesDir + "Sample.rules" ); 354 QFile file( rulesDir + "Sample.rules" );
355 if ( file.open( IO_WriteOnly ) ) { 355 if ( file.open( IO_WriteOnly ) ) {
356 file.writeBlock( sampleWGR, strlen(sampleWGR) ); 356 file.writeBlock( sampleWGR, strlen(sampleWGR) );
357 file.close(); 357 file.close();
358 updateRuleSets(); 358 updateRuleSets();
359 } 359 }
360 return; 360 return;
361 } 361 }
362 int newest=0; 362 int newest=0;
363 int newest_age=INT_MAX; 363 int newest_age=INT_MAX;
364 QDateTime now = QDateTime::currentDateTime(); 364 QDateTime now = QDateTime::currentDateTime();
365 QStringList::Iterator it; 365 QStringList::Iterator it;
366 for ( it = ruleslist.begin(); it != ruleslist.end(); ++it ) { 366 for ( it = ruleslist.begin(); it != ruleslist.end(); ++it ) {
367 QFileInfo fi((*it)); 367 QFileInfo fi((*it));
368 int age = fi.lastModified().secsTo(now); 368 int age = fi.lastModified().secsTo(now);
369 QString name = *it; 369 QString name = *it;
370 name.truncate( name.length()-6 ); // remove extension 370 name.truncate( name.length()-6 ); // remove extension
371 rules->insertItem( name ); 371 rules->insertItem( name );
372 if ( age < newest_age ) { 372 if ( age < newest_age ) {
373 newest_age = age; 373 newest_age = age;
374 newest = rules->count()-1; 374 newest = rules->count()-1;
375 } 375 }
376 } 376 }
377 rules->setCurrentItem(newest); 377 rules->setCurrentItem(newest);
378} 378}
379 379
380Rules::Rules(QWidget* parent) : 380Rules::Rules(QWidget* parent) :
381 RulesBase(parent,0,TRUE) 381 RulesBase(parent,0,TRUE)
382{ 382{
383} 383}
384 384
385void Rules::editRules() 385void Rules::editRules()
386{ 386{
387 if ( exec() ) { 387 if ( exec() ) {
388 // ### create a new set of rules 388 // ### create a new set of rules
389 emit rulesChanged(); 389 emit rulesChanged();
390 } 390 }
391} 391}
392 392
393void Rules::deleteRuleSet() 393void Rules::deleteRuleSet()
394{ 394{
395 // ### delete existing rule set 395 // ### delete existing rule set
396 emit rulesChanged(); 396 emit rulesChanged();
397} 397}
398 398
399void WordGame::addPlayer(const QString& name) 399void WordGame::addPlayer(const QString& name)
400{ 400{
401 if ( !name.isEmpty() ) { 401 if ( !name.isEmpty() ) {
402 int colon = name.find(':'); 402 int colon = name.find(':');
403 int cpu = (colon >=0 && name.left(2) == "AI") ? name.mid(2,1).toInt() : 0; 403 int cpu = (colon >=0 && name.left(2) == "AI") ? name.mid(2,1).toInt() : 0;
404 addPlayer(name,cpu); 404 addPlayer(name,cpu);
405 } 405 }
406} 406}
407 407
408void WordGame::addPlayer(const QString& name, int cpu) 408void WordGame::addPlayer(const QString& name, int cpu)
409{ 409{
410 Rack* r = new Rack(rack_tiles,racks); 410 Rack* r = new Rack(rack_tiles,racks);
411 r->setPlayerName(name); 411 r->setPlayerName(name);
412 r->setComputerization(cpu); 412 r->setComputerization(cpu);
413 racks->addWidget(r, nplayers); 413 racks->addWidget(r, nplayers);
414 refillRack(nplayers); 414 refillRack(nplayers);
415 namelist.append(name); 415 namelist.append(name);
416 416
417 ++nplayers; 417 ++nplayers;
418} 418}
419 419
420void WordGame::nextPlayer() 420void WordGame::nextPlayer()
421{ 421{
422 if ( !refillRack(player) ) { 422 if ( !refillRack(player) ) {
423 endGame(); 423 endGame();
424 } else { 424 } else {
425 player = (player+1)%nplayers; 425 player = (player+1)%nplayers;
426 scoreinfo->setBoldOne(player); 426 scoreinfo->setBoldOne(player);
427 readyRack(player); 427 readyRack(player);
428 } 428 }
429} 429}
430 430
431bool WordGame::mayEndGame() 431bool WordGame::mayEndGame()
432{ 432{
433 int out=-1; 433 int out=-1;
434 int i; 434 int i;
435 for (i=0; i<nplayers; i++) 435 for (i=0; i<nplayers; i++)
436 if ( !rack(i)->count() ) 436 if ( !rack(i)->count() )
437 out = i; 437 out = i;
438 if ( out<0 ) { 438 if ( out<0 ) {
439 if ( QMessageBox::warning(this,tr("End game"), 439 if ( QMessageBox::warning(this,tr("End game"),
440 tr("Do you want to end the game early?"), 440 tr("Do you want to end the game early?"),
441 tr("Yes"), tr("No") )!=0 ) 441 tr("Yes"), tr("No") )!=0 )
442 { 442 {
443 return FALSE; 443 return FALSE;
444 } 444 }
445 } 445 }
446 return TRUE; 446 return TRUE;
447} 447}
448 448
449void WordGame::endGame() 449void WordGame::endGame()
450{ 450{
451 if ( gameover ) { 451 if ( gameover ) {
452 close(); 452 close();
453 return; 453 return;
454 } 454 }
455 455
456 if ( !mayEndGame() ) 456 if ( !mayEndGame() )
457 return; 457 return;
458 int out=-1; 458 int out=-1;
459 int totalleft=0; 459 int totalleft=0;
460 int i; 460 int i;
461 for (i=0; i<nplayers; i++) { 461 for (i=0; i<nplayers; i++) {
462 Rack* r = rack(i); 462 Rack* r = rack(i);
463 int c = r->count(); 463 int c = r->count();
464 if ( c ) { 464 if ( c ) {
465 int lose=0; 465 int lose=0;
466 for ( int j=0; j<c; j++ ) 466 for ( int j=0; j<c; j++ )
467 lose += r->tileRef(j)->value(); 467 lose += r->tileRef(j)->value();
468 totalleft += lose; 468 totalleft += lose;
469 scoreinfo->addScore(i,-lose); 469 scoreinfo->addScore(i,-lose);
470 } else { 470 } else {
471 out = i; 471 out = i;
472 } 472 }
473 } 473 }
474 int highest=0; 474 int highest=0;
475 int winner=0; 475 int winner=0;
476 for (i=0; i<nplayers; i++) { 476 for (i=0; i<nplayers; i++) {
477 int s = scoreinfo->playerScore(i); 477 int s = scoreinfo->playerScore(i);
478 if ( s > highest ) { 478 if ( s > highest ) {
479 highest = s; 479 highest = s;
480 winner = i; 480 winner = i;
481 } 481 }
482 } 482 }
483 if ( out >= 0 ) 483 if ( out >= 0 )
484 scoreinfo->addScore(out,totalleft); 484 scoreinfo->addScore(out,totalleft);
485 scoreinfo->setBoldOne(winner); 485 scoreinfo->setBoldOne(winner);
486 gameover = TRUE; 486 gameover = TRUE;
487 done->setEnabled(TRUE); 487 done->setEnabled(TRUE);
488 reset->setEnabled(FALSE); 488 reset->setEnabled(FALSE);
489} 489}
490 490
491void WordGame::endTurn() 491void WordGame::endTurn()
492{ 492{
493 if ( gameover ) { 493 if ( gameover ) {
494 openGameSelector(namelist); 494 openGameSelector(namelist);
495 } else { 495 } else {
496 if ( board->checkTurn() ) { 496 if ( board->checkTurn() ) {
497 if ( board->turnScore() >= 0 ) { 497 if ( board->turnScore() >= 0 ) {
498 scoreinfo->addScore(player,board->turnScore()); 498 scoreinfo->addScore(player,board->turnScore());
499 board->finalizeTurn(); 499 board->finalizeTurn();
500 } else { 500 } else {
501 QApplication::beep(); 501 QApplication::beep();
502 } 502 }
503 nextPlayer(); 503 nextPlayer();
504 } 504 }
505 } 505 }
506} 506}
507 507
508void WordGame::resetTurn() 508void WordGame::resetTurn()
509{ 509{
510 board->resetRack(); 510 board->resetRack();
511} 511}
512 512
513void WordGame::passTurn() 513void WordGame::passTurn()
514{ 514{
515 // ######## trade? 515 // ######## trade?
516 nextPlayer(); 516 nextPlayer();
517} 517}
518 518
519bool WordGame::refillRack(int i) 519bool WordGame::refillRack(int i)
520{ 520{
521 Rack* r = rack(i); 521 Rack* r = rack(i);
522 while ( !bag->isEmpty() && !r->isFull() ) { 522 while ( !bag->isEmpty() && !r->isFull() ) {
523 r->addTile(bag->takeRandom()); 523 r->addTile(bag->takeRandom());
524 } 524 }
525 return r->count() != 0; 525 return r->count() != 0;
526} 526}
527 527
528void WordGame::readyRack(int i) 528void WordGame::readyRack(int i)
529{ 529{
530 Rack* r = rack(i); 530 Rack* r = rack(i);
531 racks->raiseWidget(i); 531 racks->raiseWidget(i);
532 board->setCurrentRack(r); 532 board->setCurrentRack(r);
533 533
534 done->setEnabled( !r->computerized() ); 534 done->setEnabled( !r->computerized() );
535 reset->setEnabled( !r->computerized() ); 535 reset->setEnabled( !r->computerized() );
536 536
537 if ( r->computerized() ) { 537 if ( r->computerized() ) {
538 cpu = new ComputerPlayer(board, r); 538 cpu = new ComputerPlayer(board, r);
539 aiheart->start(0); 539 aiheart->start(0);
540 } 540 }
541} 541}
542 542
543Rack* WordGame::rack(int i) const 543Rack* WordGame::rack(int i) const
544{ 544{
545 return (Rack*)racks->widget(i); 545 return (Rack*)racks->widget(i);
546} 546}
547 547
548void WordGame::think() 548void WordGame::think()
549{ 549{
550 if ( !cpu->step() ) { 550 if ( !cpu->step() ) {
551 delete cpu; 551 delete cpu;
552 cpu = 0; 552 cpu = 0;
553 aiheart->stop(); 553 aiheart->stop();
554 if ( board->turnScore() < 0 ) 554 if ( board->turnScore() < 0 )
555 passTurn(); 555 passTurn();
556 else 556 else
557 endTurn(); 557 endTurn();
558 } 558 }
559} 559}
560 560
561ComputerPlayer::ComputerPlayer(Board* b, Rack* r) : 561ComputerPlayer::ComputerPlayer(Board* b, Rack* r) :
562 board(b), rack(r), best(new const Tile*[rack_tiles]), 562 board(b), rack(r), best(new const Tile*[rack_tiles]),
563 best_blankvalues(new Tile[rack_tiles]) 563 best_blankvalues(new Tile[rack_tiles])
564{ 564{
565 best_score = -1; 565 best_score = -1;
566 across=FALSE; 566 across=FALSE;
567 dict=0; 567 dict=0;
568} 568}
569 569
570ComputerPlayer::~ComputerPlayer() 570ComputerPlayer::~ComputerPlayer()
571{ 571{
572 delete [] best; 572 delete [] best;
573 delete [] best_blankvalues; 573 delete [] best_blankvalues;
574} 574}
575 575
576bool ComputerPlayer::step() 576bool ComputerPlayer::step()
577{ 577{
578 const QDawg::Node* root = dict ? Global::dawg("WordGame").root() 578 const QDawg::Node* root = dict ? Global::dawg("WordGame").root()
579 : Global::fixedDawg().root(); 579 : Global::fixedDawg().root();
580 QPoint d = across ? QPoint(1,0) : QPoint(0,1); 580 QPoint d = across ? QPoint(1,0) : QPoint(0,1);
581 const Tile* tiles[99]; // ### max board size 581 const Tile* tiles[99]; // ### max board size
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)
775{ 775{
776 setFixedSize(w*TileItem::smallWidth(),h*TileItem::smallHeight()); 776 setFixedSize(w*TileItem::smallWidth(),h*TileItem::smallHeight());
777 grid = new TileItem*[w*h]; 777 grid = new TileItem*[w*h];
778 memset(grid,0,w*h*sizeof(TileItem*)); 778 memset(grid,0,w*h*sizeof(TileItem*));
779 setFrameStyle(0); 779 setFrameStyle(0);
780 setHScrollBarMode(AlwaysOff); 780 setHScrollBarMode(AlwaysOff);
781 setVScrollBarMode(AlwaysOff); 781 setVScrollBarMode(AlwaysOff);
782 current_rack = 0; 782 current_rack = 0;
783 shown_n = 0; 783 shown_n = 0;
784} 784}
785 785
786Board::~Board() 786Board::~Board()
787{ 787{
788 delete canvas(); 788 delete canvas();
789} 789}
790 790
791QSize Board::sizeHint() const 791QSize Board::sizeHint() const
792{ 792{
793 return QSize(canvas()->width(),canvas()->height()); 793 return QSize(canvas()->width(),canvas()->height());
794} 794}
795 795
796void Board::writeConfig(Config& cfg) 796void Board::writeConfig(Config& cfg)
797{ 797{
798 QStringList t; 798 QStringList t;
799 int n=canvas()->tilesHorizontally()*canvas()->tilesVertically(); 799 int n=canvas()->tilesHorizontally()*canvas()->tilesVertically();
800 for (int i=0; i<n; i++) 800 for (int i=0; i<n; i++)
801 t.append( grid[i] ? grid[i]->tile().key() : QString(".") ); 801 t.append( grid[i] ? grid[i]->tile().key() : QString(".") );
802 cfg.writeEntry("Board",t,';'); 802 cfg.writeEntry("Board",t,';');
803} 803}
804 804
805void Board::readConfig(Config& cfg) 805void Board::readConfig(Config& cfg)
806{ 806{
807 clear(); 807 clear();
808 QStringList t = cfg.readListEntry("Board",';'); 808 QStringList t = cfg.readListEntry("Board",';');
809 int i=0; 809 int i=0;
810 int h=canvas()->tilesHorizontally(); 810 int h=canvas()->tilesHorizontally();
811 for (QStringList::ConstIterator it=t.begin(); it!=t.end(); ++it) { 811 for (QStringList::ConstIterator it=t.begin(); it!=t.end(); ++it) {
812 if ( *it != "." ) { 812 if ( *it != "." ) {
813 QPoint p(i%h,i/h); 813 QPoint p(i%h,i/h);
814 setTile(p,Tile(*it)); 814 setTile(p,Tile(*it));
815 } 815 }
816 i++; 816 i++;
817 } 817 }
818 canvas()->update(); 818 canvas()->update();
819} 819}
820 820
821void Board::clear() 821void Board::clear()
822{ 822{
823 int n=canvas()->tilesHorizontally()*canvas()->tilesVertically(); 823 int n=canvas()->tilesHorizontally()*canvas()->tilesVertically();
824 for (int i=0; i<n; i++) { 824 for (int i=0; i<n; i++) {
825 delete grid[i]; 825 delete grid[i];
826 grid[i]=0; 826 grid[i]=0;
827 } 827 }
828} 828}
829 829
830 830
831void Board::setCurrentRack(Rack* r) 831void Board::setCurrentRack(Rack* r)
832{ 832{
833 turn_score = -1; 833 turn_score = -1;
834 current_rack = r; 834 current_rack = r;
835} 835}
836 836
837void Board::resetRack() 837void Board::resetRack()
838{ 838{
839 unshowTurn(); 839 unshowTurn();
840 canvas()->update(); 840 canvas()->update();
841} 841}
842 842
843void Board::contentsMousePressEvent(QMouseEvent* e) 843void Board::contentsMousePressEvent(QMouseEvent* e)
844{ 844{
845 dragstart = e->pos(); 845 dragstart = e->pos();
846} 846}
847 847
848void Board::contentsMouseMoveEvent(QMouseEvent* e) 848void Board::contentsMouseMoveEvent(QMouseEvent* e)
849{ 849{
850 if ( current_rack && !current_rack->computerized() ) { 850 if ( current_rack && !current_rack->computerized() ) {
851 QPoint d = e->pos() - dragstart; 851 QPoint d = e->pos() - dragstart;
852 if ( d.x() <= 0 && d.y() <= 0 ) { 852 if ( d.x() <= 0 && d.y() <= 0 ) {
853 // None 853 // None
854 resetRack(); 854 resetRack();
855 } else { 855 } else {
856 int n; 856 int n;
857 QPoint start=boardPos(dragstart); 857 QPoint start=boardPos(dragstart);
858 QPoint end=boardPos(e->pos()); 858 QPoint end=boardPos(e->pos());
859 QPoint diff=end-start; 859 QPoint diff=end-start;
860 QPoint dir; 860 QPoint dir;
861 if ( d.x() > d.y() ) { 861 if ( d.x() > d.y() ) {
862 n = diff.x()+1; 862 n = diff.x()+1;
863 dir = QPoint(1,0); 863 dir = QPoint(1,0);
864 } else { 864 } else {
865 n = diff.y()+1; 865 n = diff.y()+1;
866 dir = QPoint(0,1); 866 dir = QPoint(0,1);
867 } 867 }
868 868
869 unshowTurn(); 869 unshowTurn();
870 870
871 // Subtract existing tiles from n 871 // Subtract existing tiles from n
872 QPoint t = start; 872 QPoint t = start;
873 for ( int i=n; i--; ) { 873 for ( int i=n; i--; ) {
874 if ( contains(t) && tile(t) ) 874 if ( contains(t) && tile(t) )
875 n--; 875 n--;
876 t += dir; 876 t += dir;
877 } 877 }
878 878
879 // Move start back to real start 879 // Move start back to real start
880 while (contains(start-dir) && tile(start-dir)) 880 while (contains(start-dir) && tile(start-dir))
881 start -= dir; 881 start -= dir;
882 882
883 scoreTurn(start, n, dir); 883 scoreTurn(start, n, dir);
884 showTurn(); 884 showTurn();
885 } 885 }
886 } 886 }
887} 887}
888 888
889void Board::finalizeTurn() 889void Board::finalizeTurn()
890{ 890{
891 int i=0; 891 int i=0;
892 QPoint at = shown_at; 892 QPoint at = shown_at;
893 while ( i<shown_n && contains(at) ) { 893 while ( i<shown_n && contains(at) ) {
894 if ( item(at) && item(at)->state() == TileItem::Floating ) { 894 if ( item(at) && item(at)->state() == TileItem::Floating ) {
895 current_rack->remove(item(at)->tile()); 895 current_rack->remove(item(at)->tile());
896 setTileState(at,TileItem::Firm); 896 setTileState(at,TileItem::Firm);
897 i++; 897 i++;
898 } 898 }
899 at += shown_step; 899 at += shown_step;
900 } 900 }
901 canvas()->update(); 901 canvas()->update();
902} 902}
903 903
904void Board::unshowTurn() 904void Board::unshowTurn()
905{ 905{
906 int i=0; 906 int i=0;
907 QPoint at = shown_at; 907 QPoint at = shown_at;
908 while ( i<shown_n && i<current_rack->count() && contains(at) ) { 908 while ( i<shown_n && i<current_rack->count() && contains(at) ) {
909 if ( item(at) && item(at)->state() == TileItem::Floating ) { 909 if ( item(at) && item(at)->state() == TileItem::Floating ) {
910 unsetTile(at); 910 unsetTile(at);
911 i++; 911 i++;
912 } 912 }
913 at += shown_step; 913 at += shown_step;
914 } 914 }
915} 915}
916 916
917void Board::showTurn() 917void Board::showTurn()
918{ 918{
919 unshowTurn(); 919 unshowTurn();
920 QPoint at = shown_at; 920 QPoint at = shown_at;
921 int i=0; 921 int i=0;
922 while ( i<shown_n && i<current_rack->count() && contains(at) ) { 922 while ( i<shown_n && i<current_rack->count() && contains(at) ) {
923 if ( !tile(at) ) { 923 if ( !tile(at) ) {
924 Tile t = current_rack->tile(i); 924 Tile t = current_rack->tile(i);
925 setTile(at,t); 925 setTile(at,t);
926 setTileState(at,TileItem::Floating); 926 setTileState(at,TileItem::Floating);
927 i++; 927 i++;
928 } 928 }
929 at += shown_step; 929 at += shown_step;
930 } 930 }
931 canvas()->update(); 931 canvas()->update();
932} 932}
933 933
934int Board::bonussedValue(const QPoint& at, int base, int& all_mult) const 934int Board::bonussedValue(const QPoint& at, int base, int& all_mult) const
935{ 935{
936 int rule = rule_shape[idx(at)]-'0'; 936 int rule = rule_shape[idx(at)]-'0';
937 int effect = rule_effect[rule]; 937 int effect = rule_effect[rule];
938 int mult = effect&Multiplier; 938 int mult = effect&Multiplier;
939 if ( effect & MultiplyAll ) { 939 if ( effect & MultiplyAll ) {
940 all_mult *= mult; 940 all_mult *= mult;
941 return base; 941 return base;
942 } else { 942 } else {
943 return base * mult; 943 return base * mult;
944 } 944 }
945} 945}
946 946
947bool Board::isStart(const QPoint& at) const 947bool Board::isStart(const QPoint& at) const
948{ 948{
949 int rule = rule_shape[idx(at)]-'0'; 949 int rule = rule_shape[idx(at)]-'0';
950 int effect = rule_effect[rule]; 950 int effect = rule_effect[rule];
951 return effect&Start; 951 return effect&Start;
952} 952}
953 953
954bool Board::checkTurn() 954bool Board::checkTurn()
955{ 955{
956 if ( current_rack->computerized() ) 956 if ( current_rack->computerized() )
957 return TRUE; // computer doesn't cheat, and has already set blanks. 957 return TRUE; // computer doesn't cheat, and has already set blanks.
958 958
959 QPoint at = shown_at; 959 QPoint at = shown_at;
960 int n = shown_n; 960 int n = shown_n;
961 QPoint d = shown_step; 961 QPoint d = shown_step;
962 const Tile* tiles[99]; 962 const Tile* tiles[99];
963 Tile blankvalues[99]; 963 Tile blankvalues[99];
964 if ( n > current_rack->count() ) 964 if ( n > current_rack->count() )
965 n = current_rack->count(); 965 n = current_rack->count();
966 966
967 QDialog check(this,0,TRUE); 967 QDialog check(this,0,TRUE);
968 (new QVBoxLayout(&check))->setAutoAdd(TRUE); 968 (new QVBoxLayout(&check))->setAutoAdd(TRUE);
969 969
970 QHBox mw(&check); 970 QHBox mw(&check);
971 new QLabel(tr("Blanks: "),&mw); 971 new QLabel(tr("Blanks: "),&mw);
972 972
973 int bl=0; 973 int bl=0;
974 QLineEdit* le[99]; 974 QLineEdit* le[99];
975 for (int i=0; i<n; i++) { 975 for (int i=0; i<n; i++) {
976 tiles[i] = current_rack->tileRef(i); 976 tiles[i] = current_rack->tileRef(i);
977 if ( tiles[i]->isBlank() ) { 977 if ( tiles[i]->isBlank() ) {
978 QLineEdit *l = new QLineEdit(&mw); 978 QLineEdit *l = new QLineEdit(&mw);
979 le[bl++] = l; 979 le[bl++] = l;
980 l->setMaxLength(1); 980 l->setMaxLength(1);
981 l->setFixedSize(l->minimumSizeHint()); 981 l->setFixedSize(l->minimumSizeHint());
982 } 982 }
983 } 983 }
984 984
985 QHBox btns(&check); 985 QHBox btns(&check);
986 connect(new QPushButton(tr("OK"),&btns), SIGNAL(clicked()), &check, SLOT(accept())); 986 connect(new QPushButton(tr("OK"),&btns), SIGNAL(clicked()), &check, SLOT(accept()));
987 connect(new QPushButton(tr("Cancel"),&btns), SIGNAL(clicked()), &check, SLOT(reject())); 987 connect(new QPushButton(tr("Cancel"),&btns), SIGNAL(clicked()), &check, SLOT(reject()));
988 988
989 if ( bl ) { 989 if ( bl ) {
990retry: 990retry:
991 if ( !check.exec() ) { 991 if ( !check.exec() ) {
992 unshowTurn(); 992 unshowTurn();
993 canvas()->update(); 993 canvas()->update();
994 return FALSE; 994 return FALSE;
995 } 995 }
996 996
997 for (int b=0; b<bl; b++) { 997 for (int b=0; b<bl; b++) {
998 QString v = le[b]->text(); 998 QString v = le[b]->text();
999 blankvalues[b]=Tile(v,0); 999 blankvalues[b]=Tile(v,0);
1000 if ( v.length() != 1 ) 1000 if ( v.length() != 1 )
1001 goto retry; 1001 goto retry;
1002 } 1002 }
1003 } 1003 }
1004 1004
1005 QStringList words; 1005 QStringList words;
1006 unshowTurn(); 1006 unshowTurn();
1007 turn_score = score(at,tiles,n,blankvalues,d,FALSE,&words); 1007 turn_score = score(at,tiles,n,blankvalues,d,FALSE,&words);
1008 showTurn(); 1008 showTurn();
1009 QStringList to_add; 1009 QStringList to_add;
1010 for (QStringList::Iterator it=words.begin(); it!=words.end(); ++it) { 1010 for (QStringList::Iterator it=words.begin(); it!=words.end(); ++it) {
1011 if ( !Global::fixedDawg().contains(*it) 1011 if ( !Global::fixedDawg().contains(*it)
1012 && !Global::dawg("WordGame").contains(*it) ) { 1012 && !Global::dawg("WordGame").contains(*it) ) {
1013 switch (QMessageBox::warning(this, tr("Unknown word"), 1013 switch (QMessageBox::warning(this, tr("Unknown word"),
1014 tr("<p>The word \"%1\" is not in the dictionary.").arg(*it), 1014 tr("<p>The word \"%1\" is not in the dictionary.").arg(*it),
1015 tr("Add"), tr("Ignore"), tr("Cancel"))) 1015 tr("Add"), tr("Ignore"), tr("Cancel")))
1016 { 1016 {
1017 case 0: 1017 case 0:
1018 // ####### add to wordgame dictionary 1018 // ####### add to wordgame dictionary
1019 to_add.append(*it); 1019 to_add.append(*it);
1020 break; 1020 break;
1021 case 1: 1021 case 1:
1022 break; 1022 break;
1023 case 2: 1023 case 2:
1024 unshowTurn(); 1024 unshowTurn();
1025 canvas()->update(); 1025 canvas()->update();
1026 return FALSE; 1026 return FALSE;
1027 } 1027 }
1028 } 1028 }
1029 } 1029 }
1030 if ( to_add.count() ) 1030 if ( to_add.count() )
1031 Global::addWords("WordGame",to_add); 1031 Global::addWords("WordGame",to_add);
1032 return TRUE; 1032 return TRUE;
1033} 1033}
1034 1034
1035void Board::scoreTurn(const QPoint& at, int n, const QPoint& d) 1035void Board::scoreTurn(const QPoint& at, int n, const QPoint& d)
1036{ 1036{
1037 unshowTurn(); 1037 unshowTurn();
1038 shown_at = at; 1038 shown_at = at;
1039 shown_n = n; 1039 shown_n = n;
1040 shown_step = d; 1040 shown_step = d;
1041 const Tile* tiles[99]; 1041 const Tile* tiles[99];
1042 if ( n > current_rack->count() ) 1042 if ( n > current_rack->count() )
1043 n = current_rack->count(); 1043 n = current_rack->count();
1044 for (int i=0; i<n; i++) 1044 for (int i=0; i<n; i++)
1045 tiles[i] = current_rack->tileRef(i); 1045 tiles[i] = current_rack->tileRef(i);
1046 turn_score = score(at,tiles,n,0,d,FALSE,0); 1046 turn_score = score(at,tiles,n,0,d,FALSE,0);
1047 emit temporaryScore(turn_score); 1047 emit temporaryScore(turn_score);
1048} 1048}
1049 1049
1050int Board::score(QPoint at, const Tile** tiles, int n, const Tile* blankvalue, const QPoint& d, bool checkdict, QStringList* words) const 1050int Board::score(QPoint at, const Tile** tiles, int n, const Tile* blankvalue, const QPoint& d, bool checkdict, QStringList* words) const
1051{ 1051{
1052 int total=0; 1052 int total=0;
1053 int totalsidetotal=0; 1053 int totalsidetotal=0;
1054 1054
1055 // words gets filled with words made 1055 // words gets filled with words made
1056 1056
1057 // mainword==0 -> 1057 // mainword==0 ->
1058 // Checks side words, but not main word 1058 // Checks side words, but not main word
1059 1059
1060 // -1 means words not in dict, or illegally positioned (eg. not connected) 1060 // -1 means words not in dict, or illegally positioned (eg. not connected)
1061 1061
1062 // text is assumed to fit on board. 1062 // text is assumed to fit on board.
1063 1063
1064 if ( words ) *words=QStringList(); 1064 if ( words ) *words=QStringList();
1065 1065
1066 QPoint otherd(d.y(), d.x()); 1066 QPoint otherd(d.y(), d.x());
1067 1067
1068 int all_mult = 1; 1068 int all_mult = 1;
1069 int bl=0; 1069 int bl=0;
1070 1070
1071 bool connected = FALSE; 1071 bool connected = FALSE;
1072 1072
1073 QString mainword=""; 1073 QString mainword="";
1074 1074
1075 if ( contains(at-d) && tile(at-d) ) { 1075 if ( contains(at-d) && tile(at-d) ) {
1076 return -1; // preceeding tiles 1076 return -1; // preceeding tiles
1077 } 1077 }
1078 1078
1079 const Tile* t; 1079 const Tile* t;
1080 for (int i=0; contains(at) && ((t=tile(at)) || i<n); ) { 1080 for (int i=0; contains(at) && ((t=tile(at)) || i<n); ) {
1081 if ( t ) { 1081 if ( t ) {
1082 if ( checkdict || words ) mainword += t->text(); 1082 if ( checkdict || words ) mainword += t->text();
1083 total += t->value(); 1083 total += t->value();
1084 connected = TRUE; 1084 connected = TRUE;
1085 } else { 1085 } else {
1086 QString sideword; 1086 QString sideword;
1087 QString tt; 1087 QString tt;
1088 if ( tiles[i]->isBlank() ) { 1088 if ( tiles[i]->isBlank() ) {
1089 if ( blankvalue ) 1089 if ( blankvalue )
1090 tt = blankvalue[bl++].text(); 1090 tt = blankvalue[bl++].text();
1091 } else { 1091 } else {
1092 tt = tiles[i]->text(); 1092 tt = tiles[i]->text();
1093 } 1093 }
1094 sideword=tt; 1094 sideword=tt;
1095 if ( checkdict || words ) mainword += tt; 1095 if ( checkdict || words ) mainword += tt;
1096 int side_mult = 1; 1096 int side_mult = 1;
1097 int tilevalue = bonussedValue(at,tiles[i]->value(),side_mult); 1097 int tilevalue = bonussedValue(at,tiles[i]->value(),side_mult);
1098 all_mult *= side_mult; 1098 all_mult *= side_mult;
1099 if ( !connected && isStart(at) ) 1099 if ( !connected && isStart(at) )
1100 connected = TRUE; 1100 connected = TRUE;
1101 total += tilevalue; 1101 total += tilevalue;
1102 int sidetotal = tilevalue; 1102 int sidetotal = tilevalue;
1103 { 1103 {
1104 QPoint side = at-otherd; 1104 QPoint side = at-otherd;
1105 1105
1106 while ( contains(side) && (t=tile(side)) ) { 1106 while ( contains(side) && (t=tile(side)) ) {
1107 sidetotal += t->value(); 1107 sidetotal += t->value();
1108 sideword.prepend(t->text()); 1108 sideword.prepend(t->text());
1109 side -= otherd; 1109 side -= otherd;
1110 } 1110 }
1111 } 1111 }
1112 { 1112 {
1113 QPoint side = at+otherd; 1113 QPoint side = at+otherd;
1114 while ( contains(side) && (t=tile(side)) ) { 1114 while ( contains(side) && (t=tile(side)) ) {
1115 sidetotal += t->value(); 1115 sidetotal += t->value();
1116 sideword.append(t->text()); 1116 sideword.append(t->text());
1117 side += otherd; 1117 side += otherd;
1118 } 1118 }
1119 } 1119 }
1120 if ( sideword.length() > 1 ) { 1120 if ( sideword.length() > 1 ) {
1121 if ( words ) 1121 if ( words )
1122 words->append(sideword); 1122 words->append(sideword);
1123 if ( checkdict && !Global::fixedDawg().contains(sideword) 1123 if ( checkdict && !Global::fixedDawg().contains(sideword)
1124 && !Global::dawg("WordGame").contains(sideword) ) 1124 && !Global::dawg("WordGame").contains(sideword) )
1125 return -1; 1125 return -1;
1126 totalsidetotal += sidetotal * side_mult; 1126 totalsidetotal += sidetotal * side_mult;
1127 connected = TRUE; 1127 connected = TRUE;
1128 } 1128 }
1129 i++; 1129 i++;
1130 } 1130 }
1131 at += d; 1131 at += d;
1132 } 1132 }
1133 1133
1134 if ( words ) 1134 if ( words )
1135 words->append(mainword); 1135 words->append(mainword);
1136 if ( checkdict && !Global::fixedDawg().contains(mainword) 1136 if ( checkdict && !Global::fixedDawg().contains(mainword)
1137 && !Global::dawg("WordGame").contains(mainword) ) 1137 && !Global::dawg("WordGame").contains(mainword) )
1138 return -1; 1138 return -1;
1139 1139
1140 if ( n == rack_tiles ) 1140 if ( n == rack_tiles )
1141 totalsidetotal += rack_tiles_bonus; 1141 totalsidetotal += rack_tiles_bonus;
1142 1142
1143 return connected ? totalsidetotal + total * all_mult : -1; 1143 return connected ? totalsidetotal + total * all_mult : -1;
1144} 1144}
1145 1145
1146QPoint Board::boardPos(const QPoint& p) const 1146QPoint Board::boardPos(const QPoint& p) const
1147{ 1147{
1148 return QPoint(p.x()/canvas()->tileWidth(), p.y()/canvas()->tileHeight()); 1148 return QPoint(p.x()/canvas()->tileWidth(), p.y()/canvas()->tileHeight());
1149} 1149}
1150 1150
1151void Board::contentsMouseReleaseEvent(QMouseEvent*) 1151void Board::contentsMouseReleaseEvent(QMouseEvent*)
1152{ 1152{
1153 if ( current_rack ) { 1153 if ( current_rack ) {
1154 } 1154 }
1155} 1155}
1156 1156
1157 1157
1158void Board::setRules(const QString& shapes, const int* effects) 1158void Board::setRules(const QString& shapes, const int* effects)
1159{ 1159{
1160 rule_shape=shapes; rule_effect=effects; 1160 rule_shape=shapes; rule_effect=effects;
1161 int i=0; 1161 int i=0;
1162 int maxre=0; 1162 int maxre=0;
1163 for (int y=0; y<yTiles(); y++) { 1163 for (int y=0; y<yTiles(); y++) {
1164 for (int x=0; x<xTiles(); x++) { 1164 for (int x=0; x<xTiles(); x++) {
1165 int re = shapes[i++]-'0'; 1165 int re = shapes[i++]-'0';
1166 if ( re > maxre ) maxre = re; 1166 if ( re > maxre ) maxre = re;
1167 canvas()->setTile(x,y,re); 1167 canvas()->setTile(x,y,re);
1168 } 1168 }
1169 } 1169 }
1170 rack_tiles_bonus=effects[maxre+1]; 1170 rack_tiles_bonus=effects[maxre+1];
1171} 1171}
1172 1172
1173void Board::unsetTile(const QPoint& p) 1173void Board::unsetTile(const QPoint& p)
1174{ 1174{
1175 delete item(p); 1175 delete item(p);
1176 grid[idx(p)] = 0; 1176 grid[idx(p)] = 0;
1177} 1177}
1178 1178
1179void Board::setTile(const QPoint& p, const Tile& t) 1179void Board::setTile(const QPoint& p, const Tile& t)
1180{ 1180{
1181 TileItem* it=item(p); 1181 TileItem* it=item(p);
1182 if ( !it ) { 1182 if ( !it ) {
1183 it = grid[idx(p)] = new TileItem(t,FALSE,canvas()); 1183 it = grid[idx(p)] = new TileItem(t,FALSE,canvas());
1184 it->move(p.x()*canvas()->tileWidth(), p.y()*canvas()->tileHeight()); 1184 it->move(p.x()*canvas()->tileWidth(), p.y()*canvas()->tileHeight());
1185 it->show(); 1185 it->show();
1186 } else { 1186 } else {
1187 it->setTile(t); 1187 it->setTile(t);
1188 } 1188 }
1189} 1189}
1190 1190
1191Rack::Rack(int ntiles, QWidget* parent) : QCanvasView( 1191Rack::Rack(int ntiles, QWidget* parent) : QCanvasView(
1192 new QCanvas(ntiles*TileItem::bigWidth(),TileItem::bigHeight()), 1192 new QCanvas(ntiles*TileItem::bigWidth(),TileItem::bigHeight()),
1193 parent), 1193 parent),
1194 item(ntiles) 1194 item(ntiles)
1195{ 1195{
1196 setLineWidth(1); 1196 setLineWidth(1);
1197 setFixedHeight(sizeHint().height()); 1197 setFixedHeight(sizeHint().height());
1198 n = 0; 1198 n = 0;
1199 for (int i=0; i<ntiles; i++) 1199 for (int i=0; i<ntiles; i++)
1200 item[i]=0; 1200 item[i]=0;
1201 setHScrollBarMode(AlwaysOff); 1201 setHScrollBarMode(AlwaysOff);
1202 setVScrollBarMode(AlwaysOff); 1202 setVScrollBarMode(AlwaysOff);
1203 canvas()->setBackgroundColor(gray); 1203 canvas()->setBackgroundColor(gray);
1204 dragging = 0; 1204 dragging = 0;
1205} 1205}
1206 1206
1207Rack::~Rack() 1207Rack::~Rack()
1208{ 1208{
1209 clear(); 1209 clear();
1210 delete canvas(); 1210 delete canvas();
1211} 1211}
1212 1212
1213QSize Rack::sizeHint() const 1213QSize Rack::sizeHint() const
1214{ 1214{
1215 return QSize(-1,TileItem::bigHeight()+2); 1215 return QSize(-1,TileItem::bigHeight()+2);
1216} 1216}
1217 1217
1218void Rack::clear() 1218void Rack::clear()
1219{ 1219{
1220 for (int i=0; i<n; i++) 1220 for (int i=0; i<n; i++)
1221 delete item[i]; 1221 delete item[i];
1222 n=0; 1222 n=0;
1223} 1223}
1224 1224
1225void Rack::writeConfig(Config& cfg) 1225void Rack::writeConfig(Config& cfg)
1226{ 1226{
1227 QStringList l; 1227 QStringList l;
1228 for (int i=0; i<n; i++) 1228 for (int i=0; i<n; i++)
1229 l.append(tile(i).key()); 1229 l.append(tile(i).key());
1230 cfg.writeEntry("Tiles",l,';'); 1230 cfg.writeEntry("Tiles",l,';');
1231} 1231}
1232 1232
1233void Rack::readConfig(Config& cfg) 1233void Rack::readConfig(Config& cfg)
1234{ 1234{
1235 clear(); 1235 clear();
1236 int x=0; 1236 int x=0;
1237 QStringList l = cfg.readListEntry("Tiles",';'); 1237 QStringList l = cfg.readListEntry("Tiles",';');
1238 for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) { 1238 for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) {
1239 TileItem *i = new TileItem(Tile(*it),TRUE,canvas()); 1239 TileItem *i = new TileItem(Tile(*it),TRUE,canvas());
1240 i->move(x++,0); 1240 i->move(x++,0);
1241 i->show(); 1241 i->show();
1242 item[n++] = i; 1242 item[n++] = i;
1243 } 1243 }
1244 layoutTiles(); 1244 layoutTiles();
1245} 1245}
1246 1246
1247static int cmp_tileitem(const void *a, const void *b) 1247static int cmp_tileitem(const void *a, const void *b)
1248{ 1248{
1249 const TileItem* ia = *(TileItem**)a; 1249 const TileItem* ia = *(TileItem**)a;
1250 const TileItem* ib = *(TileItem**)b; 1250 const TileItem* ib = *(TileItem**)b;
1251 return int(ia->x() - ib->x()); 1251 return int(ia->x() - ib->x());
1252} 1252}
1253 1253
1254void Rack::layoutTiles() 1254void Rack::layoutTiles()
1255{ 1255{
1256 int w = TileItem::bigWidth()+2; 1256 int w = TileItem::bigWidth()+2;
1257 1257
1258 if ( dragging ) dragging->moveBy(dragging_adj,0); 1258 if ( dragging ) dragging->moveBy(dragging_adj,0);
1259 qsort(item.data(), n, sizeof(TileItem*), cmp_tileitem); 1259 qsort(item.data(), n, sizeof(TileItem*), cmp_tileitem);
1260 if ( dragging ) dragging->moveBy(-dragging_adj,0); 1260 if ( dragging ) dragging->moveBy(-dragging_adj,0);
1261 1261
1262 for (int i=0; i<n ;i++) 1262 for (int i=0; i<n ;i++)
1263 if ( item[i] == dragging ) { 1263 if ( item[i] == dragging ) {
1264 item[i]->setZ(1); 1264 item[i]->setZ(1);
1265 } else { 1265 } else {
1266 item[i]->move(i*w, 0); 1266 item[i]->move(i*w, 0);
1267 item[i]->setZ(0); 1267 item[i]->setZ(0);
1268 } 1268 }
1269 canvas()->update(); 1269 canvas()->update();
1270} 1270}
1271 1271
1272void Rack::setBlanks(const Tile* bv) 1272void Rack::setBlanks(const Tile* bv)
1273{ 1273{
1274 for (int j=0; j<n; j++) { 1274 for (int j=0; j<n; j++) {
1275 Tile tt = item[j]->tile(); 1275 Tile tt = item[j]->tile();
1276 if ( tt.isBlank() ) { 1276 if ( tt.isBlank() ) {
1277 tt.setText(bv->text()); 1277 tt.setText(bv->text());
1278 item[j]->setTile(tt); 1278 item[j]->setTile(tt);
1279 bv++; 1279 bv++;
1280 } 1280 }
1281 } 1281 }
1282} 1282}
1283 1283
1284bool Rack::arrangeTiles(const Tile** s, int sn) 1284bool Rack::arrangeTiles(const Tile** s, int sn)
1285{ 1285{
1286 bool could = TRUE; 1286 bool could = TRUE;
1287 for (int j=0; j<n; j++) { 1287 for (int j=0; j<n; j++) {
1288 Tile tt = item[j]->tile(); 1288 Tile tt = item[j]->tile();
1289 int f=-1; 1289 int f=-1;
1290 for (int i=0; i<sn && f<0; i++) { 1290 for (int i=0; i<sn && f<0; i++) {
1291 if (s[i] && *s[i] == tt ) { 1291 if (s[i] && *s[i] == tt ) {
1292 s[i]=0; 1292 s[i]=0;
1293 f=i; 1293 f=i;
1294 } 1294 }
1295 } 1295 }
1296 if ( f >= 0 ) { 1296 if ( f >= 0 ) {
1297 item[j]->move(f-999,0); 1297 item[j]->move(f-999,0);
1298 } else { 1298 } else {
1299 could = FALSE; 1299 could = FALSE;
1300 } 1300 }
1301 } 1301 }
1302 layoutTiles(); 1302 layoutTiles();
1303 return could; 1303 return could;
1304} 1304}
1305 1305
1306void Rack::addTile(const Tile& t) 1306void Rack::addTile(const Tile& t)
1307{ 1307{
1308 TileItem *i = new TileItem(t,TRUE,canvas()); 1308 TileItem *i = new TileItem(t,TRUE,canvas());
1309 i->show(); 1309 i->show();
1310 item[n++] = i; 1310 item[n++] = i;
1311 layoutTiles(); 1311 layoutTiles();
1312} 1312}
1313 1313
1314void Rack::remove(Tile t) 1314void Rack::remove(Tile t)
1315{ 1315{
1316 for (int i=0; i<n ;i++) 1316 for (int i=0; i<n ;i++)
1317 if ( item[i]->tile() == t ) { 1317 if ( item[i]->tile() == t ) {
1318 remove(i); 1318 remove(i);
1319 return; 1319 return;
1320 } 1320 }
1321} 1321}
1322 1322
1323void Rack::remove(int i) 1323void Rack::remove(int i)
1324{ 1324{
1325 delete item[i]; 1325 delete item[i];
1326 n--; 1326 n--;
1327 for (;i<n;i++) 1327 for (;i<n;i++)
1328 item[i]=item[i+1]; 1328 item[i]=item[i+1];
1329 layoutTiles(); 1329 layoutTiles();
1330} 1330}
1331 1331
1332void Rack::resizeEvent(QResizeEvent* e) 1332void Rack::resizeEvent(QResizeEvent* e)
1333{ 1333{
1334 canvas()->resize(width()-frameWidth()*2,height()-frameWidth()*2); 1334 canvas()->resize(width()-frameWidth()*2,height()-frameWidth()*2);
1335 QCanvasView::resizeEvent(e); 1335 QCanvasView::resizeEvent(e);
1336} 1336}
1337 1337
1338void Rack::contentsMousePressEvent(QMouseEvent* e) 1338void Rack::contentsMousePressEvent(QMouseEvent* e)
1339{ 1339{
1340 if ( computerized() ) 1340 if ( computerized() )
1341 return; 1341 return;
1342 QCanvasItemList list = canvas()->collisions(e->pos()); 1342 QCanvasItemList list = canvas()->collisions(e->pos());
1343 if (list.count()) { 1343 if (list.count()) {
1344 dragging = list.first(); 1344 dragging = list.first();
1345 dragstart = e->pos()-QPoint(int(dragging->x()),int(dragging->y())); 1345 dragstart = e->pos()-QPoint(int(dragging->x()),int(dragging->y()));
1346 } else { 1346 } else {
1347 dragging = 0; 1347 dragging = 0;
1348 } 1348 }
1349} 1349}
1350 1350
1351void Rack::contentsMouseMoveEvent(QMouseEvent* e) 1351void Rack::contentsMouseMoveEvent(QMouseEvent* e)
1352{ 1352{
1353 if ( computerized() ) 1353 if ( computerized() )
1354 return; 1354 return;
1355 //int w = TileItem::bigWidth()+2; 1355 //int w = TileItem::bigWidth()+2;
1356 if ( dragging ) { 1356 if ( dragging ) {
1357 dragging_adj = TileItem::bigWidth()/2; 1357 dragging_adj = TileItem::bigWidth()/2;
1358 if ( dragging->x() > e->x()-dragstart.x() ) 1358 if ( dragging->x() > e->x()-dragstart.x() )
1359 dragging_adj = -dragging_adj; 1359 dragging_adj = -dragging_adj;
1360 dragging->move(e->x()-dragstart.x(),0); 1360 dragging->move(e->x()-dragstart.x(),0);
1361 layoutTiles(); 1361 layoutTiles();
1362 } 1362 }
1363} 1363}
1364 1364
1365void Rack::contentsMouseReleaseEvent(QMouseEvent* e) 1365void Rack::contentsMouseReleaseEvent(QMouseEvent* e)
1366{ 1366{
1367 if ( computerized() ) 1367 if ( computerized() )
1368 return; 1368 return;
1369 if ( dragging ) { 1369 if ( dragging ) {
1370 dragging=0; 1370 dragging=0;
1371 layoutTiles(); 1371 layoutTiles();
1372 } 1372 }
1373} 1373}
1374 1374
1375Tile::Tile(const QString& key) 1375Tile::Tile(const QString& key)
1376{ 1376{
1377 int a=key.find('@'); 1377 int a=key.find('@');
1378 txt = key.left(a); 1378 txt = key.left(a);
1379 val = key.mid(a+1).toInt(); 1379 val = key.mid(a+1).toInt();
1380 blank = txt.isEmpty(); 1380 blank = txt.isEmpty();
1381} 1381}
1382 1382
1383QString Tile::key() const 1383QString Tile::key() const
1384{ 1384{
1385 return txt+"@"+QString::number(val); 1385 return txt+"@"+QString::number(val);
1386} 1386}
1387 1387
1388Bag::Bag() 1388Bag::Bag()
1389{ 1389{
1390 tiles.setAutoDelete(TRUE); 1390 tiles.setAutoDelete(TRUE);
1391} 1391}
1392 1392
1393void Bag::writeConfig(Config& cfg) 1393void Bag::writeConfig(Config& cfg)
1394{ 1394{
1395 QStringList t; 1395 QStringList t;
1396 for (QListIterator<Tile> it(tiles); it; ++it) 1396 for (QListIterator<Tile> it(tiles); it; ++it)
1397 t.append((*it)->key()); 1397 t.append((*it)->key());
1398 cfg.writeEntry("Tiles",t,';'); 1398 cfg.writeEntry("Tiles",t,';');
1399} 1399}
1400 1400
1401void Bag::readConfig(Config& cfg) 1401void Bag::readConfig(Config& cfg)
1402{ 1402{
1403 tiles.clear(); 1403 tiles.clear();
1404 QStringList t = cfg.readListEntry("Tiles",';'); 1404 QStringList t = cfg.readListEntry("Tiles",';');
1405 for (QStringList::ConstIterator it=t.begin(); it!=t.end(); ++it ) 1405 for (QStringList::ConstIterator it=t.begin(); it!=t.end(); ++it )
1406 add(Tile(*it)); 1406 add(Tile(*it));
1407} 1407}
1408 1408
1409void Bag::add(const Tile& t) 1409void Bag::add(const Tile& t)
1410{ 1410{
1411 tiles.append(new Tile(t)); 1411 tiles.append(new Tile(t));
1412} 1412}
1413 1413
1414Tile Bag::takeRandom() 1414Tile Bag::takeRandom()
1415{ 1415{
1416 Tile* rp = tiles.take(random()%tiles.count()); 1416 Tile* rp = tiles.take(random()%tiles.count());
1417 Tile r=*rp; 1417 Tile r=*rp;
1418 return r; 1418 return r;
1419} 1419}
1420 1420
1421ScoreInfo::ScoreInfo( QWidget* parent, const char* name, WFlags fl ) : 1421ScoreInfo::ScoreInfo( QWidget* parent, const char* name, WFlags fl ) :
1422 QLabel("<P>",parent,name,fl) 1422 QLabel("<P>",parent,name,fl)
1423{ 1423{
1424 score=0; 1424 score=0;
1425 msgtimer = new QTimer(this); 1425 msgtimer = new QTimer(this);
1426 connect(msgtimer, SIGNAL(timeout()), this, SLOT(showScores())); 1426 connect(msgtimer, SIGNAL(timeout()), this, SLOT(showScores()));
1427 setBackgroundMode( PaletteButton ); 1427 setBackgroundMode( PaletteButton );
1428} 1428}
1429 1429
1430ScoreInfo::~ScoreInfo() 1430ScoreInfo::~ScoreInfo()
1431{ 1431{
1432 if ( score ) delete [] score; 1432 if ( score ) delete [] score;
1433} 1433}
1434 1434
1435void ScoreInfo::writeConfig(Config& cfg) 1435void ScoreInfo::writeConfig(Config& cfg)
1436{ 1436{
1437 QStringList l; 1437 QStringList l;
1438 for (int i=0; i<(int)names.count(); i++) 1438 for (int i=0; i<(int)names.count(); i++)
1439 l.append(QString::number(score[i])); 1439 l.append(QString::number(score[i]));
1440 cfg.writeEntry("Scores",l,';'); 1440 cfg.writeEntry("Scores",l,';');
1441} 1441}
1442 1442
1443void ScoreInfo::readConfig(Config& cfg) 1443void ScoreInfo::readConfig(Config& cfg)
1444{ 1444{
1445 QStringList l = cfg.readListEntry("Scores",';'); 1445 QStringList l = cfg.readListEntry("Scores",';');
1446 int i=0; 1446 int i=0;
1447 for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it ) 1447 for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it )
1448 score[i++]=(*it).toInt(); 1448 score[i++]=(*it).toInt();
1449 showScores(); 1449 showScores();
1450} 1450}
1451 1451
1452 1452
1453QSize ScoreInfo::sizeHint() const 1453QSize ScoreInfo::sizeHint() const
1454{ 1454{
1455 return QSize(QLabel::sizeHint().width(),fontMetrics().height()); 1455 return QSize(QLabel::sizeHint().width(),fontMetrics().height());
1456} 1456}
1457 1457
1458void ScoreInfo::init(const QStringList& namelist) 1458void ScoreInfo::init(const QStringList& namelist)
1459{ 1459{
1460 names = namelist; 1460 names = namelist;
1461 if ( score ) delete [] score; 1461 if ( score ) delete [] score;
1462 score = new int[names.count()]; 1462 score = new int[names.count()];
1463 memset(score,0,sizeof(int)*names.count()); 1463 memset(score,0,sizeof(int)*names.count());
1464 boldone = -1; 1464 boldone = -1;
1465 showScores(); 1465 showScores();
1466} 1466}
1467 1467
1468void ScoreInfo::addScore(int player, int change) 1468void ScoreInfo::addScore(int player, int change)
1469{ 1469{
1470 score[player] += change; 1470 score[player] += change;
1471 showScores(); 1471 showScores();
1472} 1472}
1473 1473
1474void ScoreInfo::setBoldOne(int b) 1474void ScoreInfo::setBoldOne(int b)
1475{ 1475{
1476 boldone=b; 1476 boldone=b;
1477 showScores(); 1477 showScores();
1478} 1478}
1479 1479
1480void ScoreInfo::showScores() 1480void ScoreInfo::showScores()
1481{ 1481{
1482 QString r="<p>"; 1482 QString r="<p>";
1483 int i=0; 1483 int i=0;
1484 //int spl=(names.count()+1)/2; // 2 lines 1484 //int spl=(names.count()+1)/2; // 2 lines
1485 for (QStringList::ConstIterator it=names.begin(); it!=names.end(); ) { 1485 for (QStringList::ConstIterator it=names.begin(); it!=names.end(); ) {
1486 if ( i==boldone ) r += "<b>"; 1486 if ( i==boldone ) r += "<b>";
1487 QString n = *it; 1487 QString n = *it;
1488 n.replace(QRegExp(":.*"),""); 1488 n.replace(QRegExp(":.*"),"");
1489 r += n; 1489 r += n;
1490 r += ":"; 1490 r += ":";
1491 r += QString::number(score[i]); 1491 r += QString::number(score[i]);
1492 if ( i==boldone ) r += "</b>"; 1492 if ( i==boldone ) r += "</b>";
1493 1493
1494 ++i; 1494 ++i;
1495 ++it; 1495 ++it;
1496 if ( it != names.end() ) 1496 if ( it != names.end() )
1497 r += " "; 1497 r += " ";
1498 } 1498 }
1499 setText(r); 1499 setText(r);
1500} 1500}
1501 1501
1502void ScoreInfo::showTemporaryScore(int amount) 1502void ScoreInfo::showTemporaryScore(int amount)
1503{ 1503{
1504 if ( amount < 0 ) 1504 if ( amount < 0 )
1505 setText(tr("<P>Invalid move")); 1505 setText(tr("<P>Invalid move"));
1506 else 1506 else
1507 setText(tr("<P>Score: ")+QString::number(amount)); 1507 setText(tr("<P>Score: ")+QString::number(amount));
1508 msgtimer->start(3000,TRUE); 1508 msgtimer->start(3000,TRUE);
1509} 1509}
1510 1510
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,1425 +1,1429 @@
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
427//-------------------------------------------------------------------------- 431//--------------------------------------------------------------------------
428// Evaluate number, be it int, rational, or float from directory. 432// Evaluate number, be it int, rational, or float from directory.
429//-------------------------------------------------------------------------- 433//--------------------------------------------------------------------------
430double ExifData::ConvertAnyFormat(void * ValuePtr, int Format) 434double ExifData::ConvertAnyFormat(void * ValuePtr, int Format)
431{ 435{
432 double Value; 436 double Value;
433 Value = 0; 437 Value = 0;
434 438
435 switch(Format){ 439 switch(Format){
436 case FMT_SBYTE: Value = *(signed char *)ValuePtr; break; 440 case FMT_SBYTE: Value = *(signed char *)ValuePtr; break;
437 case FMT_BYTE: Value = *(uchar *)ValuePtr; break; 441 case FMT_BYTE: Value = *(uchar *)ValuePtr; break;
438 442
439 case FMT_USHORT: Value = Get16u(ValuePtr); break; 443 case FMT_USHORT: Value = Get16u(ValuePtr); break;
440 444
441 case FMT_ULONG: Value = Get32u(ValuePtr); break; 445 case FMT_ULONG: Value = Get32u(ValuePtr); break;
442 446
443 case FMT_URATIONAL: 447 case FMT_URATIONAL:
444 case FMT_SRATIONAL: 448 case FMT_SRATIONAL:
445 { 449 {
446 int Num,Den; 450 int Num,Den;
447 Num = Get32s(ValuePtr); 451 Num = Get32s(ValuePtr);
448 Den = Get32s(4+(char *)ValuePtr); 452 Den = Get32s(4+(char *)ValuePtr);
449 if (Den == 0){ 453 if (Den == 0){
450 Value = 0; 454 Value = 0;
451 }else{ 455 }else{
452 Value = (double)Num/Den; 456 Value = (double)Num/Den;
453 } 457 }
454 break; 458 break;
455 } 459 }
456 460
457 case FMT_SSHORT: Value = (signed short)Get16u(ValuePtr); break; 461 case FMT_SSHORT: Value = (signed short)Get16u(ValuePtr); break;
458 case FMT_SLONG: Value = Get32s(ValuePtr); break; 462 case FMT_SLONG: Value = Get32s(ValuePtr); break;
459 463
460 // Not sure if this is correct (never seen float used in Exif format) 464 // Not sure if this is correct (never seen float used in Exif format)
461 case FMT_SINGLE: Value = (double)*(float *)ValuePtr; break; 465 case FMT_SINGLE: Value = (double)*(float *)ValuePtr; break;
462 case FMT_DOUBLE: Value = *(double *)ValuePtr; break; 466 case FMT_DOUBLE: Value = *(double *)ValuePtr; break;
463 } 467 }
464 return Value; 468 return Value;
465} 469}
466 470
467//-------------------------------------------------------------------------- 471//--------------------------------------------------------------------------
468// Process one of the nested EXIF directories. 472// Process one of the nested EXIF directories.
469//-------------------------------------------------------------------------- 473//--------------------------------------------------------------------------
470void ExifData::ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength) 474void ExifData::ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength)
471{ 475{
472 int de; 476 int de;
473 int a; 477 int a;
474 int NumDirEntries; 478 int NumDirEntries;
475 unsigned ThumbnailOffset = 0; 479 unsigned ThumbnailOffset = 0;
476 unsigned ThumbnailSize = 0; 480 unsigned ThumbnailSize = 0;
477 481
478 NumDirEntries = Get16u(DirStart); 482 NumDirEntries = Get16u(DirStart);
479 #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry)) 483 #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry))
480 484
481 { 485 {
482 unsigned char * DirEnd; 486 unsigned char * DirEnd;
483 DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries); 487 DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries);
484 if (DirEnd+4 > (OffsetBase+ExifLength)){ 488 if (DirEnd+4 > (OffsetBase+ExifLength)){
485 if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){ 489 if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){
486 // Version 1.3 of jhead would truncate a bit too much. 490 // Version 1.3 of jhead would truncate a bit too much.
487 // This also caught later on as well. 491 // This also caught later on as well.
488 }else{ 492 }else{
489 // Note: Files that had thumbnails trimmed with jhead 1.3 or earlier 493 // Note: Files that had thumbnails trimmed with jhead 1.3 or earlier
490 // might trigger this. 494 // might trigger this.
491 return; 495 return;
492 } 496 }
493 } 497 }
494 if (DirEnd < LastExifRefd) LastExifRefd = DirEnd; 498 if (DirEnd < LastExifRefd) LastExifRefd = DirEnd;
495 } 499 }
496 500
497 for (de=0;de<NumDirEntries;de++){ 501 for (de=0;de<NumDirEntries;de++){
498 int Tag, Format, Components; 502 int Tag, Format, Components;
499 unsigned char * ValuePtr; 503 unsigned char * ValuePtr;
500 int ByteCount; 504 int ByteCount;
501 char * DirEntry; 505 char * DirEntry;
502 DirEntry = (char *)DIR_ENTRY_ADDR(DirStart, de); 506 DirEntry = (char *)DIR_ENTRY_ADDR(DirStart, de);
503 507
504 Tag = Get16u(DirEntry); 508 Tag = Get16u(DirEntry);
505 Format = Get16u(DirEntry+2); 509 Format = Get16u(DirEntry+2);
506 Components = Get32u(DirEntry+4); 510 Components = Get32u(DirEntry+4);
507 511
508 if ((Format-1) >= NUM_FORMATS) { 512 if ((Format-1) >= NUM_FORMATS) {
509 // (-1) catches illegal zero case as unsigned underflows to positive large. 513 // (-1) catches illegal zero case as unsigned underflows to positive large.
510 return; 514 return;
511 } 515 }
512 516
513 ByteCount = Components * BytesPerFormat[Format]; 517 ByteCount = Components * BytesPerFormat[Format];
514 518
515 if (ByteCount > 4){ 519 if (ByteCount > 4){
516 unsigned OffsetVal; 520 unsigned OffsetVal;
517 OffsetVal = Get32u(DirEntry+8); 521 OffsetVal = Get32u(DirEntry+8);
518 // If its bigger than 4 bytes, the dir entry contains an offset. 522 // If its bigger than 4 bytes, the dir entry contains an offset.
519 if (OffsetVal+ByteCount > ExifLength){ 523 if (OffsetVal+ByteCount > ExifLength){
520 // Bogus pointer offset and / or bytecount value 524 // Bogus pointer offset and / or bytecount value
521 //printf("Offset %d bytes %d ExifLen %d\n",OffsetVal, ByteCount, ExifLength); 525 //printf("Offset %d bytes %d ExifLen %d\n",OffsetVal, ByteCount, ExifLength);
522 526
523 return; 527 return;
524 } 528 }
525 ValuePtr = OffsetBase+OffsetVal; 529 ValuePtr = OffsetBase+OffsetVal;
526 }else{ 530 }else{
527 // 4 bytes or less and value is in the dir entry itself 531 // 4 bytes or less and value is in the dir entry itself
528 ValuePtr = (unsigned char *)DirEntry+8; 532 ValuePtr = (unsigned char *)DirEntry+8;
529 } 533 }
530 534
531 if (LastExifRefd < ValuePtr+ByteCount){ 535 if (LastExifRefd < ValuePtr+ByteCount){
532 // Keep track of last byte in the exif header that was actually referenced. 536 // Keep track of last byte in the exif header that was actually referenced.
533 // That way, we know where the discardable thumbnail data begins. 537 // That way, we know where the discardable thumbnail data begins.
534 LastExifRefd = ValuePtr+ByteCount; 538 LastExifRefd = ValuePtr+ByteCount;
535 } 539 }
536 540
537 // Extract useful components of tag 541 // Extract useful components of tag
538 switch(Tag){ 542 switch(Tag){
539 543
540 case TAG_MAKE: 544 case TAG_MAKE:
541 ExifData::CameraMake = QString((char*)ValuePtr); 545 ExifData::CameraMake = QString((char*)ValuePtr);
542 break; 546 break;
543 547
544 case TAG_MODEL: 548 case TAG_MODEL:
545 ExifData::CameraModel = QString((char*)ValuePtr); 549 ExifData::CameraModel = QString((char*)ValuePtr);
546 break; 550 break;
547 551
548 case TAG_ORIENTATION: 552 case TAG_ORIENTATION:
549 Orientation = (int)ConvertAnyFormat(ValuePtr, Format); 553 Orientation = (int)ConvertAnyFormat(ValuePtr, Format);
550 break; 554 break;
551 555
552 case TAG_DATETIME_ORIGINAL: 556 case TAG_DATETIME_ORIGINAL:
553 DateTime = QString((char*)ValuePtr); 557 DateTime = QString((char*)ValuePtr);
554 break; 558 break;
555 559
556 case TAG_USERCOMMENT: 560 case TAG_USERCOMMENT:
557 // Olympus has this padded with trailing spaces. Remove these first. 561 // Olympus has this padded with trailing spaces. Remove these first.
558 for (a=ByteCount;;){ 562 for (a=ByteCount;;){
559 a--; 563 a--;
560 if ((ValuePtr)[a] == ' '){ 564 if ((ValuePtr)[a] == ' '){
561 (ValuePtr)[a] = '\0'; 565 (ValuePtr)[a] = '\0';
562 }else{ 566 }else{
563 break; 567 break;
564 } 568 }
565 if (a == 0) break; 569 if (a == 0) break;
566 } 570 }
567 571
568 // Copy the comment 572 // Copy the comment
569 if (memcmp(ValuePtr, "ASCII",5) == 0){ 573 if (memcmp(ValuePtr, "ASCII",5) == 0){
570 for (a=5;a<10;a++){ 574 for (a=5;a<10;a++){
571 int c; 575 int c;
572 c = (ValuePtr)[a]; 576 c = (ValuePtr)[a];
573 if (c != '\0' && c != ' '){ 577 if (c != '\0' && c != ' '){
574 //strncpy(ImageInfo.Comments, (const char*)(a+ValuePtr), 199); 578 //strncpy(ImageInfo.Comments, (const char*)(a+ValuePtr), 199);
575 UserComment.sprintf("%s", (const char*)(a+ValuePtr)); 579 UserComment.sprintf("%s", (const char*)(a+ValuePtr));
576 break; 580 break;
577 } 581 }
578 } 582 }
579 }else{ 583 }else{
580 //strncpy(ImageInfo.Comments, (const char*)ValuePtr, 199); 584 //strncpy(ImageInfo.Comments, (const char*)ValuePtr, 199);
581 UserComment.sprintf("%s", (const char*)ValuePtr); 585 UserComment.sprintf("%s", (const char*)ValuePtr);
582 } 586 }
583 break; 587 break;
584 588
585 case TAG_FNUMBER: 589 case TAG_FNUMBER:
586 // Simplest way of expressing aperture, so I trust it the most. 590 // Simplest way of expressing aperture, so I trust it the most.
587 // (overwrite previously computd value if there is one) 591 // (overwrite previously computd value if there is one)
588 ExifData::ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format); 592 ExifData::ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format);
589 break; 593 break;
590 594
591 case TAG_APERTURE: 595 case TAG_APERTURE:
592 case TAG_MAXAPERTURE: 596 case TAG_MAXAPERTURE:
593 // More relevant info always comes earlier, so only use this field if we don't 597 // More relevant info always comes earlier, so only use this field if we don't
594 // have appropriate aperture information yet. 598 // have appropriate aperture information yet.
595 if (ExifData::ApertureFNumber == 0){ 599 if (ExifData::ApertureFNumber == 0){
596 ExifData::ApertureFNumber 600 ExifData::ApertureFNumber
597 = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5); 601 = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5);
598 } 602 }
599 break; 603 break;
600 604
601 case TAG_FOCALLENGTH: 605 case TAG_FOCALLENGTH:
602 // Nice digital cameras actually save the focal length as a function 606 // Nice digital cameras actually save the focal length as a function
603 // of how farthey are zoomed in. 607 // of how farthey are zoomed in.
604 ExifData::FocalLength = (float)ConvertAnyFormat(ValuePtr, Format); 608 ExifData::FocalLength = (float)ConvertAnyFormat(ValuePtr, Format);
605 break; 609 break;
606 610
607 case TAG_SUBJECT_DISTANCE: 611 case TAG_SUBJECT_DISTANCE:
608 // Inidcates the distacne the autofocus camera is focused to. 612 // Inidcates the distacne the autofocus camera is focused to.
609 // Tends to be less accurate as distance increases. 613 // Tends to be less accurate as distance increases.
610 ExifData::Distance = (float)ConvertAnyFormat(ValuePtr, Format); 614 ExifData::Distance = (float)ConvertAnyFormat(ValuePtr, Format);
611 break; 615 break;
612 616
613 case TAG_EXPOSURETIME: 617 case TAG_EXPOSURETIME:
614 // Simplest way of expressing exposure time, so I trust it most. 618 // Simplest way of expressing exposure time, so I trust it most.
615 // (overwrite previously computd value if there is one) 619 // (overwrite previously computd value if there is one)
616 ExifData::ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format); 620 ExifData::ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format);
617 break; 621 break;
618 622
619 case TAG_SHUTTERSPEED: 623 case TAG_SHUTTERSPEED:
620 // More complicated way of expressing exposure time, so only use 624 // More complicated way of expressing exposure time, so only use
621 // this value if we don't already have it from somewhere else. 625 // this value if we don't already have it from somewhere else.
622 if (ExifData::ExposureTime == 0){ 626 if (ExifData::ExposureTime == 0){
623 ExifData::ExposureTime 627 ExifData::ExposureTime
624 = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2))); 628 = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2)));
625 } 629 }
626 break; 630 break;
627 631
628 case TAG_FLASH: 632 case TAG_FLASH:
629 if (ConvertAnyFormat(ValuePtr, Format)){ 633 if (ConvertAnyFormat(ValuePtr, Format)){
630 ExifData::FlashUsed = 1; 634 ExifData::FlashUsed = 1;
631 } 635 }
632 break; 636 break;
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 }
1013 return dest; 1017 return dest;
1014} 1018}
1015 1019
1016static QImage rotate_90_all( const QImage& img ) { 1020static QImage rotate_90_all( const QImage& img ) {
1017 dest.create(img.height(), img.width(), img.depth()); 1021 dest.create(img.height(), img.width(), img.depth());
1018 for ( y=0; y < img.height(); ++y ) { 1022 for ( y=0; y < img.height(); ++y ) {
1019 srcData = (unsigned int *)img.scanLine(y); 1023 srcData = (unsigned int *)img.scanLine(y);
1020 for ( x=0; x < img.width(); ++x ) { 1024 for ( x=0; x < img.width(); ++x ) {
1021 destData = (unsigned int *)dest.scanLine(x); 1025 destData = (unsigned int *)dest.scanLine(x);
1022 destData[img.height()-y-1] = srcData[x]; 1026 destData[img.height()-y-1] = srcData[x];
1023 } 1027 }
1024 } 1028 }
1025 1029
1026 return dest; 1030 return dest;
1027} 1031}
1028 1032
1029 1033
1030static QImage rotate_90( const QImage & img ) { 1034static QImage rotate_90( const QImage & img ) {
1031 if ( img.depth() > 8) 1035 if ( img.depth() > 8)
1032 return rotate_90_all( img ); 1036 return rotate_90_all( img );
1033 else 1037 else
1034 return rotate_90_8( img ); 1038 return rotate_90_8( img );
1035} 1039}
1036 1040
1037static QImage rotate_180_all( const QImage& img ) { 1041static QImage rotate_180_all( const QImage& img ) {
1038 dest.create(img.width(), img.height(), img.depth()); 1042 dest.create(img.width(), img.height(), img.depth());
1039 for ( y=0; y < img.height(); ++y ){ 1043 for ( y=0; y < img.height(); ++y ){
1040 srcData = (unsigned int *)img.scanLine(y); 1044 srcData = (unsigned int *)img.scanLine(y);
1041 destData = (unsigned int *)dest.scanLine(img.height()-y-1); 1045 destData = (unsigned int *)dest.scanLine(img.height()-y-1);
1042 for ( x=0; x < img.width(); ++x ) 1046 for ( x=0; x < img.width(); ++x )
1043 destData[img.width()-x-1] = srcData[x]; 1047 destData[img.width()-x-1] = srcData[x];
1044 } 1048 }
1045 return dest; 1049 return dest;
1046} 1050}
1047 1051
1048static QImage rotate_180_8( const QImage& img ) { 1052static QImage rotate_180_8( const QImage& img ) {
1049 dest.create(img.width(), img.height(), img.depth()); 1053 dest.create(img.width(), img.height(), img.depth());
1050 dest.setNumColors(img.numColors()); 1054 dest.setNumColors(img.numColors());
1051 srcTable = (unsigned int *)img.colorTable(); 1055 srcTable = (unsigned int *)img.colorTable();
1052 destTable = (unsigned int *)dest.colorTable(); 1056 destTable = (unsigned int *)dest.colorTable();
1053 for ( x=0; x < img.numColors(); ++x ) 1057 for ( x=0; x < img.numColors(); ++x )
1054 destTable[x] = srcTable[x]; 1058 destTable[x] = srcTable[x];
1055 for ( y=0; y < img.height(); ++y ){ 1059 for ( y=0; y < img.height(); ++y ){
1056 srcData8 = (unsigned char *)img.scanLine(y); 1060 srcData8 = (unsigned char *)img.scanLine(y);
1057 destData8 = (unsigned char *)dest.scanLine(img.height()-y-1); 1061 destData8 = (unsigned char *)dest.scanLine(img.height()-y-1);
1058 for ( x=0; x < img.width(); ++x ) 1062 for ( x=0; x < img.width(); ++x )
1059 destData8[img.width()-x-1] = srcData8[x]; 1063 destData8[img.width()-x-1] = srcData8[x];
1060 } 1064 }
1061 return dest; 1065 return dest;
1062} 1066}
1063 1067
1064static QImage rotate_180( const QImage& img ) { 1068static QImage rotate_180( const QImage& img ) {
1065 if ( img.depth() > 8 ) 1069 if ( img.depth() > 8 )
1066 return rotate_180_all( img ); 1070 return rotate_180_all( img );
1067 else 1071 else
1068 return rotate_180_8( img ); 1072 return rotate_180_8( img );
1069} 1073}
1070 1074
1071 1075
1072static QImage rotate_270_8( const QImage& img ) { 1076static QImage rotate_270_8( const QImage& img ) {
1073 dest.create(img.height(), img.width(), img.depth()); 1077 dest.create(img.height(), img.width(), img.depth());
1074 dest.setNumColors(img.numColors()); 1078 dest.setNumColors(img.numColors());
1075 srcTable = (unsigned int *)img.colorTable(); 1079 srcTable = (unsigned int *)img.colorTable();
1076 destTable = (unsigned int *)dest.colorTable(); 1080 destTable = (unsigned int *)dest.colorTable();
1077 for ( x=0; x < img.numColors(); ++x ) 1081 for ( x=0; x < img.numColors(); ++x )
1078 destTable[x] = srcTable[x]; 1082 destTable[x] = srcTable[x];
1079 for ( y=0; y < img.height(); ++y ){ 1083 for ( y=0; y < img.height(); ++y ){
1080 srcData8 = (unsigned char *)img.scanLine(y); 1084 srcData8 = (unsigned char *)img.scanLine(y);
1081 for ( x=0; x < img.width(); ++x ){ 1085 for ( x=0; x < img.width(); ++x ){
1082 destData8 = (unsigned char *)dest.scanLine(img.width()-x-1); 1086 destData8 = (unsigned char *)dest.scanLine(img.width()-x-1);
1083 destData8[y] = srcData8[x]; 1087 destData8[y] = srcData8[x];
1084 } 1088 }
1085 } 1089 }
1086 1090
1087 return dest; 1091 return dest;
1088} 1092}
1089 1093
1090static QImage rotate_270_all( const QImage& img ) { 1094static QImage rotate_270_all( const QImage& img ) {
1091 dest.create(img.height(), img.width(), img.depth()); 1095 dest.create(img.height(), img.width(), img.depth());
1092 for ( y=0; y < img.height(); ++y ){ 1096 for ( y=0; y < img.height(); ++y ){
1093 srcData = (unsigned int *)img.scanLine(y); 1097 srcData = (unsigned int *)img.scanLine(y);
1094 for ( x=0; x < img.width(); ++x ){ 1098 for ( x=0; x < img.width(); ++x ){
1095 destData = (unsigned int *)dest.scanLine(img.width()-x-1); 1099 destData = (unsigned int *)dest.scanLine(img.width()-x-1);
1096 destData[y] = srcData[x]; 1100 destData[y] = srcData[x];
1097 } 1101 }
1098 } 1102 }
1099 return dest; 1103 return dest;
1100} 1104}
1101 1105
1102static QImage rotate_270( const QImage& img ) { 1106static QImage rotate_270( const QImage& img ) {
1103 if ( img.depth() > 8 ) 1107 if ( img.depth() > 8 )
1104 return rotate_270_all( img ); 1108 return rotate_270_all( img );
1105 else 1109 else
1106 return rotate_270_8( img ); 1110 return rotate_270_8( img );
1107} 1111}
1108 1112
1109 1113
1110static QString color_mode_to_string( bool b ) { 1114static QString color_mode_to_string( bool b ) {
1111 return b ? QObject::tr( "Colormode: Color\n" ) : QObject::tr( "Colormode: Black and white\n" ); 1115 return b ? QObject::tr( "Colormode: Color\n" ) : QObject::tr( "Colormode: Black and white\n" );
1112} 1116}
1113 1117
1114static QString compression_to_string( int level ) { 1118static QString compression_to_string( int level ) {
1115 QString str; 1119 QString str;
1116 switch( level ) { 1120 switch( level ) {
1117 case 1: 1121 case 1:
1118 str = QObject::tr( "Basic" ); 1122 str = QObject::tr( "Basic" );
1119 break; 1123 break;
1120 case 2: 1124 case 2:
1121 str = QObject::tr( "Normal" ); 1125 str = QObject::tr( "Normal" );
1122 break; 1126 break;
1123 case 4: 1127 case 4:
1124 str = QObject::tr( "Fine" ); 1128 str = QObject::tr( "Fine" );
1125 break; 1129 break;
1126 default: 1130 default:
1127 str = QObject::tr( "Unknown" ); 1131 str = QObject::tr( "Unknown" );
1128 1132
1129 } 1133 }
1130 return QObject::tr("Quality: %1\n").arg(str); 1134 return QObject::tr("Quality: %1\n").arg(str);
1131} 1135}
1132 1136
1133 1137
1134static QDateTime parseDateTime( const QString& string ) 1138static QDateTime parseDateTime( const QString& string )
1135{ 1139{
1136 QDateTime dt; 1140 QDateTime dt;
1137 if ( string.length() != 19 ) 1141 if ( string.length() != 19 )
1138 return dt; 1142 return dt;
1139 1143
1140 QString year = string.left( 4 ); 1144 QString year = string.left( 4 );
1141 QString month = string.mid( 5, 2 ); 1145 QString month = string.mid( 5, 2 );
1142 QString day = string.mid( 8, 2 ); 1146 QString day = string.mid( 8, 2 );
1143 QString hour = string.mid( 11, 2 ); 1147 QString hour = string.mid( 11, 2 );
1144 QString minute = string.mid( 14, 2 ); 1148 QString minute = string.mid( 14, 2 );
1145 QString seconds = string.mid( 18, 2 ); 1149 QString seconds = string.mid( 18, 2 );
1146 1150
1147 bool ok; 1151 bool ok;
1148 bool allOk = true; 1152 bool allOk = true;
1149 int y = year.toInt( &ok ); 1153 int y = year.toInt( &ok );
1150 allOk &= ok; 1154 allOk &= ok;
1151 1155
1152 int mo = month.toInt( &ok ); 1156 int mo = month.toInt( &ok );
1153 allOk &= ok; 1157 allOk &= ok;
1154 1158
1155 int d = day.toInt( &ok ); 1159 int d = day.toInt( &ok );
1156 allOk &= ok; 1160 allOk &= ok;
1157 1161
1158 int h = hour.toInt( &ok ); 1162 int h = hour.toInt( &ok );
1159 allOk &= ok; 1163 allOk &= ok;
1160 1164
1161 int mi = minute.toInt( &ok ); 1165 int mi = minute.toInt( &ok );
1162 allOk &= ok; 1166 allOk &= ok;
1163 1167
1164 int s = seconds.toInt( &ok ); 1168 int s = seconds.toInt( &ok );
1165 allOk &= ok; 1169 allOk &= ok;
1166 1170
1167 if ( allOk ) { 1171 if ( allOk ) {
1168 dt.setDate( QDate( y, mo, d ) ); 1172 dt.setDate( QDate( y, mo, d ) );
1169 dt.setTime( QTime( h, mi, s ) ); 1173 dt.setTime( QTime( h, mi, s ) );
1170 } 1174 }
1171 1175
1172 return dt; 1176 return dt;
1173} 1177}
1174 1178
1175static QString white_balance_string( int i ) { 1179static QString white_balance_string( int i ) {
1176 QString balance; 1180 QString balance;
1177 switch ( i ) { 1181 switch ( i ) {
1178 case 0: 1182 case 0:
1179 balance = QObject::tr( "Unknown" ); 1183 balance = QObject::tr( "Unknown" );
1180 break; 1184 break;
1181 case 1: 1185 case 1:
1182 balance = QObject::tr( "Daylight" ); 1186 balance = QObject::tr( "Daylight" );
1183 break; 1187 break;
1184 case 2: 1188 case 2:
1185 balance = QObject::tr( "Fluorescent" ); 1189 balance = QObject::tr( "Fluorescent" );
1186 break; 1190 break;
1187 case 3: 1191 case 3:
1188 balance = QObject::tr( "Tungsten" ); 1192 balance = QObject::tr( "Tungsten" );
1189 break; 1193 break;
1190 case 17: 1194 case 17:
1191 balance = QObject::tr( "Standard light A" ); 1195 balance = QObject::tr( "Standard light A" );
1192 break; 1196 break;
1193 case 18: 1197 case 18:
1194 balance = QObject::tr( "Standard light B" ); 1198 balance = QObject::tr( "Standard light B" );
1195 break; 1199 break;
1196 case 19: 1200 case 19:
1197 balance = QObject::tr( "Standard light C" ); 1201 balance = QObject::tr( "Standard light C" );
1198 break; 1202 break;
1199 case 20: 1203 case 20:
1200 balance = QObject::tr( "D55" ); 1204 balance = QObject::tr( "D55" );
1201 break; 1205 break;
1202 case 21: 1206 case 21:
1203 balance = QObject::tr( "D65" ); 1207 balance = QObject::tr( "D65" );
1204 break; 1208 break;
1205 case 22: 1209 case 22:
1206 balance = QObject::tr( "D75" ); 1210 balance = QObject::tr( "D75" );
1207 break; 1211 break;
1208 case 255: 1212 case 255:
1209 balance = QObject::tr( "Other" ); 1213 balance = QObject::tr( "Other" );
1210 break; 1214 break;
1211 default: 1215 default:
1212 balance = QObject::tr( "Unknown" ); 1216 balance = QObject::tr( "Unknown" );
1213 } 1217 }
1214 return QObject::tr( "White Balance: %1\n" ).arg( balance ); 1218 return QObject::tr( "White Balance: %1\n" ).arg( balance );
1215 1219
1216} 1220}
1217 1221
1218 1222
1219static QString metering_mode( int i) { 1223static QString metering_mode( int i) {
1220 QString meter; 1224 QString meter;
1221 switch( i ) { 1225 switch( i ) {
1222 case 0: 1226 case 0:
1223 meter = QObject::tr( "Unknown" ); 1227 meter = QObject::tr( "Unknown" );
1224 break; 1228 break;
1225 case 1: 1229 case 1:
1226 meter = QObject::tr( "Average" ); 1230 meter = QObject::tr( "Average" );
1227 break; 1231 break;
1228 case 2: 1232 case 2:
1229 meter = QObject::tr( "Center weighted average" ); 1233 meter = QObject::tr( "Center weighted average" );
1230 break; 1234 break;
1231 case 3: 1235 case 3:
1232 meter = QObject::tr( "Spot" ); 1236 meter = QObject::tr( "Spot" );
1233 break; 1237 break;
1234 case 4: 1238 case 4:
1235 meter = QObject::tr( "MultiSpot" ); 1239 meter = QObject::tr( "MultiSpot" );
1236 break; 1240 break;
1237 case 5: 1241 case 5:
1238 meter = QObject::tr( "Pattern" ); 1242 meter = QObject::tr( "Pattern" );
1239 break; 1243 break;
1240 case 6: 1244 case 6:
1241 meter = QObject::tr( "Partial" ); 1245 meter = QObject::tr( "Partial" );
1242 break; 1246 break;
1243 case 255: 1247 case 255:
1244 meter = QObject::tr( "Other" ); 1248 meter = QObject::tr( "Other" );
1245 break; 1249 break;
1246 default: 1250 default:
1247 meter = QObject::tr( "Unknown" ); 1251 meter = QObject::tr( "Unknown" );
1248 } 1252 }
1249 1253
1250 return QObject::tr( "Metering Mode: %1\n" ).arg( meter ); 1254 return QObject::tr( "Metering Mode: %1\n" ).arg( meter );
1251} 1255}
1252 1256
1253 1257
1254static QString exposure_program( int i ) { 1258static QString exposure_program( int i ) {
1255 QString exp; 1259 QString exp;
1256 switch( i ) { 1260 switch( i ) {
1257 case 0: 1261 case 0:
1258 exp = QObject::tr( "Not defined" ); 1262 exp = QObject::tr( "Not defined" );
1259 break; 1263 break;
1260 case 1: 1264 case 1:
1261 exp = QObject::tr( "Manual" ); 1265 exp = QObject::tr( "Manual" );
1262 break; 1266 break;
1263 case 2: 1267 case 2:
1264 exp = QObject::tr( "Normal progam" ); 1268 exp = QObject::tr( "Normal progam" );
1265 break; 1269 break;
1266 case 3: 1270 case 3:
1267 exp = QObject::tr( "Aperture priority" ); 1271 exp = QObject::tr( "Aperture priority" );
1268 break; 1272 break;
1269 case 4: 1273 case 4:
1270 exp = QObject::tr( "Shutter priority" ); 1274 exp = QObject::tr( "Shutter priority" );
1271 break; 1275 break;
1272 case 5: 1276 case 5:
1273 exp = QObject::tr( "Creative progam\n(biased toward fast shutter speed" ); 1277 exp = QObject::tr( "Creative progam\n(biased toward fast shutter speed" );
1274 break; 1278 break;
1275 case 6: 1279 case 6:
1276 exp = QObject::tr( "Action progam\n(biased toward fast shutter speed)" ); 1280 exp = QObject::tr( "Action progam\n(biased toward fast shutter speed)" );
1277 break; 1281 break;
1278 case 7: 1282 case 7:
1279 exp = QObject::tr( "Portrait mode\n(for closeup photos with the background out of focus)" ); 1283 exp = QObject::tr( "Portrait mode\n(for closeup photos with the background out of focus)" );
1280 break; 1284 break;
1281 case 8: 1285 case 8:
1282 exp = QObject::tr( "Landscape mode\n(for landscape photos with the background in focus)" ); 1286 exp = QObject::tr( "Landscape mode\n(for landscape photos with the background in focus)" );
1283 break; 1287 break;
1284 default: 1288 default:
1285 exp = QObject::tr( "Unknown" ); 1289 exp = QObject::tr( "Unknown" );
1286 } 1290 }
1287 1291
1288 return QObject::tr( "Exposure Program: %1\n" ).arg( exp ); 1292 return QObject::tr( "Exposure Program: %1\n" ).arg( exp );
1289} 1293}
1290 1294
1291JpegSlave::JpegSlave() 1295JpegSlave::JpegSlave()
1292 : SlaveInterface( QStringList::split( " ", "jpeg jpg" ) ) 1296 : SlaveInterface( QStringList::split( " ", "jpeg jpg" ) )
1293{} 1297{}
1294 1298
1295JpegSlave::~JpegSlave() {} 1299JpegSlave::~JpegSlave() {}
1296 1300
1297QString JpegSlave::iconViewName( const QString& path) { 1301QString JpegSlave::iconViewName( const QString& path) {
1298 ExifData ImageInfo; 1302 ExifData ImageInfo;
1299 if ( !ImageInfo.scan( path ) ) 1303 if ( !ImageInfo.scan( path ) )
1300 return QString::null; 1304 return QString::null;
1301 1305
1302 QString tag; 1306 QString tag;
1303 tag = QObject::tr( "Comment: %1\n" ).arg( ImageInfo.getComment() ); 1307 tag = QObject::tr( "Comment: %1\n" ).arg( ImageInfo.getComment() );
1304 { 1308 {
1305// ODP fixme 1309// ODP fixme
1306 QString timestring = TimeString::dateString( parseDateTime( ImageInfo.getDateTime() ), FALSE ); 1310 QString timestring = TimeString::dateString( parseDateTime( ImageInfo.getDateTime() ), FALSE );
1307 tag += QObject::tr( "Date/Time: %1\n" ).arg( timestring ); 1311 tag += QObject::tr( "Date/Time: %1\n" ).arg( timestring );
1308 } 1312 }
1309 tag += QObject::tr( "Dimensions: %1x%2\n" ).arg(ImageInfo.getWidth()) 1313 tag += QObject::tr( "Dimensions: %1x%2\n" ).arg(ImageInfo.getWidth())
1310 .arg(ImageInfo.getHeight() ); 1314 .arg(ImageInfo.getHeight() );
1311 1315
1312 tag += color_mode_to_string( ImageInfo.getIsColor() ); 1316 tag += color_mode_to_string( ImageInfo.getIsColor() );
1313 1317
1314 tag += compression_to_string( ImageInfo.getCompressionLevel() ); 1318 tag += compression_to_string( ImageInfo.getCompressionLevel() );
1315 1319
1316 return tag; 1320 return tag;
1317} 1321}
1318 1322
1319 1323
1320/* 1324/*
1321 * messy messy string creation 1325 * messy messy string creation
1322 */ 1326 */
1323QString JpegSlave::fullImageInfo( const QString& path) { 1327QString JpegSlave::fullImageInfo( const QString& path) {
1324 ExifData ImageInfo; 1328 ExifData ImageInfo;
1325 if ( !ImageInfo.scan( path ) ) 1329 if ( !ImageInfo.scan( path ) )
1326 return QString::null; 1330 return QString::null;
1327 1331
1328 QString tag, tmp; 1332 QString tag, tmp;
1329 tag = QObject::tr( "<qt>Comment: %1\n" ).arg( ImageInfo.getComment() ); 1333 tag = QObject::tr( "<qt>Comment: %1\n" ).arg( ImageInfo.getComment() );
1330 1334
1331 tmp = ImageInfo.getCameraMake(); 1335 tmp = ImageInfo.getCameraMake();
1332 if ( tmp.length() ) 1336 if ( tmp.length() )
1333 tag += QObject::tr( "Manufacturer: %1\n" ).arg( tmp ); 1337 tag += QObject::tr( "Manufacturer: %1\n" ).arg( tmp );
1334 tmp = ImageInfo.getCameraModel(); 1338 tmp = ImageInfo.getCameraModel();
1335 if ( tmp.length() ) 1339 if ( tmp.length() )
1336 tag += QObject::tr( "Model: %1\n" ).arg( tmp ); 1340 tag += QObject::tr( "Model: %1\n" ).arg( tmp );
1337 { 1341 {
1338// ODP fixme 1342// ODP fixme
1339 tmp = TimeString::dateString( parseDateTime( ImageInfo.getDateTime() ), FALSE ); 1343 tmp = TimeString::dateString( parseDateTime( ImageInfo.getDateTime() ), FALSE );
1340 tag += QObject::tr( "Date/Time: %1\n" ).arg( tmp ); 1344 tag += QObject::tr( "Date/Time: %1\n" ).arg( tmp );
1341 } 1345 }
1342 tag += QObject::tr( "Dimensions: %1x%2\n" ).arg(ImageInfo.getWidth()) 1346 tag += QObject::tr( "Dimensions: %1x%2\n" ).arg(ImageInfo.getWidth())
1343 .arg(ImageInfo.getHeight() ); 1347 .arg(ImageInfo.getHeight() );
1344 1348
1345 tag += color_mode_to_string( ImageInfo.getIsColor() ); 1349 tag += color_mode_to_string( ImageInfo.getIsColor() );
1346 1350
1347 tag += compression_to_string( ImageInfo.getCompressionLevel() ); 1351 tag += compression_to_string( ImageInfo.getCompressionLevel() );
1348 if ( ImageInfo.getOrientation() ) 1352 if ( ImageInfo.getOrientation() )
1349 tag += QObject::tr( "Orientation: %1\n" ).arg(ImageInfo.getOrientation() ); 1353 tag += QObject::tr( "Orientation: %1\n" ).arg(ImageInfo.getOrientation() );
1350 1354
1351 1355
1352 { 1356 {
1353 int flash_used = ImageInfo.getFlashUsed(); 1357 int flash_used = ImageInfo.getFlashUsed();
1354 if ( flash_used >= 0 ) 1358 if ( flash_used >= 0 )
1355 tag += QObject::tr( "Flash used\n" ); 1359 tag += QObject::tr( "Flash used\n" );
1356 } 1360 }
1357 1361
1358 if ( ImageInfo.getFocalLength() ) { 1362 if ( ImageInfo.getFocalLength() ) {
1359 tag += QObject::tr( "Focal length: %1\n" ).arg( QString().sprintf( "%4.1f", ImageInfo.getFocalLength() ) ); 1363 tag += QObject::tr( "Focal length: %1\n" ).arg( QString().sprintf( "%4.1f", ImageInfo.getFocalLength() ) );
1360 if ( ImageInfo.getCCDWidth() ) 1364 if ( ImageInfo.getCCDWidth() )
1361 tag += QObject::tr( "35mm equivalent: %1\n" ).arg( (int)(ImageInfo.getFocalLength()/ImageInfo.getCCDWidth()*35 + 0.5) ); 1365 tag += QObject::tr( "35mm equivalent: %1\n" ).arg( (int)(ImageInfo.getFocalLength()/ImageInfo.getCCDWidth()*35 + 0.5) );
1362 1366
1363 } 1367 }
1364 1368
1365 if ( ImageInfo.getCCDWidth() ) 1369 if ( ImageInfo.getCCDWidth() )
1366 tag += QObject::tr( "CCD width: %1" ).arg( ImageInfo.getCCDWidth() ); 1370 tag += QObject::tr( "CCD width: %1" ).arg( ImageInfo.getCCDWidth() );
1367 if ( ImageInfo.getExposureTime() ) { 1371 if ( ImageInfo.getExposureTime() ) {
1368 tmp = QString().sprintf("%4.2f", ImageInfo.getExposureTime() ); 1372 tmp = QString().sprintf("%4.2f", ImageInfo.getExposureTime() );
1369 float exposureTime = ImageInfo.getExposureTime(); 1373 float exposureTime = ImageInfo.getExposureTime();
1370 if ( exposureTime > 0 && exposureTime <= 0.5 ) 1374 if ( exposureTime > 0 && exposureTime <= 0.5 )
1371 tmp += QString().sprintf(" (1/%d)", (int)(0.5 +1/exposureTime) ); 1375 tmp += QString().sprintf(" (1/%d)", (int)(0.5 +1/exposureTime) );
1372 tag += QObject::tr( "Exposure time: %1\n" ).arg( tmp ); 1376 tag += QObject::tr( "Exposure time: %1\n" ).arg( tmp );
1373 } 1377 }
1374 1378
1375 if ( ImageInfo.getApertureFNumber() ) 1379 if ( ImageInfo.getApertureFNumber() )
1376 tag += QObject::tr( "Aperture: %1\n" ).arg( QString().sprintf("f/%3.1f", (double)ImageInfo.getApertureFNumber() ) ); 1380 tag += QObject::tr( "Aperture: %1\n" ).arg( QString().sprintf("f/%3.1f", (double)ImageInfo.getApertureFNumber() ) );
1377 1381
1378 if ( ImageInfo.getDistance() ) { 1382 if ( ImageInfo.getDistance() ) {
1379 if ( ImageInfo.getDistance() < 0 ) 1383 if ( ImageInfo.getDistance() < 0 )
1380 tag += QObject::tr( "Distance: %1\n" ).arg( QObject::tr( "Infinite" ) ); 1384 tag += QObject::tr( "Distance: %1\n" ).arg( QObject::tr( "Infinite" ) );
1381 else 1385 else
1382 tag += QObject::tr( "Distance: %1\n" ).arg( QString().sprintf( "%5.2fm", (double)ImageInfo.getDistance() ) ); 1386 tag += QObject::tr( "Distance: %1\n" ).arg( QString().sprintf( "%5.2fm", (double)ImageInfo.getDistance() ) );
1383 } 1387 }
1384 1388
1385 if ( ImageInfo.getExposureBias() ) { 1389 if ( ImageInfo.getExposureBias() ) {
1386 tag += QObject::tr( "Exposure bias: %1\n", QString().sprintf("%4.2f", (double)ImageInfo.getExposureBias() ) ); 1390 tag += QObject::tr( "Exposure bias: %1\n", QString().sprintf("%4.2f", (double)ImageInfo.getExposureBias() ) );
1387 } 1391 }
1388 1392
1389 if ( ImageInfo.getWhitebalance() != -1 ) 1393 if ( ImageInfo.getWhitebalance() != -1 )
1390 tag += white_balance_string( ImageInfo.getWhitebalance() ); 1394 tag += white_balance_string( ImageInfo.getWhitebalance() );
1391 1395
1392 1396
1393 if( ImageInfo.getMeteringMode() != -1 ) 1397 if( ImageInfo.getMeteringMode() != -1 )
1394 tag += metering_mode( ImageInfo.getMeteringMode() ); 1398 tag += metering_mode( ImageInfo.getMeteringMode() );
1395 1399
1396 if ( ImageInfo.getExposureProgram() ) 1400 if ( ImageInfo.getExposureProgram() )
1397 tag += exposure_program( ImageInfo.getExposureProgram() ); 1401 tag += exposure_program( ImageInfo.getExposureProgram() );
1398 if ( ImageInfo.getISOequivalent() ) 1402 if ( ImageInfo.getISOequivalent() )
1399 tag += QObject::tr( "ISO equivalent: %1\n" ).arg( QString().sprintf("%2d", ImageInfo.getISOequivalent() ) ); 1403 tag += QObject::tr( "ISO equivalent: %1\n" ).arg( QString().sprintf("%2d", ImageInfo.getISOequivalent() ) );
1400 1404
1401 tmp = ImageInfo.getUserComment(); 1405 tmp = ImageInfo.getUserComment();
1402 if ( tmp.length() ) 1406 if ( tmp.length() )
1403 tag += QObject::tr( "EXIF comment: %1" ).arg( tmp ); 1407 tag += QObject::tr( "EXIF comment: %1" ).arg( tmp );
1404 1408
1405 tag += QObject::tr( "</qt>" ); 1409 tag += QObject::tr( "</qt>" );
1406 1410
1407 1411
1408 1412
1409 return tag; 1413 return tag;
1410} 1414}
1411 1415
1412QPixmap JpegSlave::pixmap( const QString& path, int wid, int hei) { 1416QPixmap JpegSlave::pixmap( const QString& path, int wid, int hei) {
1413 ExifData ImageInfo; 1417 ExifData ImageInfo;
1414 if ( !ImageInfo.scan( path ) || ImageInfo.isNullThumbnail() ) { 1418 if ( !ImageInfo.scan( path ) || ImageInfo.isNullThumbnail() ) {
1415 QImage img; 1419 QImage img;
1416 QImageIO iio( path, 0l ); 1420 QImageIO iio( path, 0l );
1417 QString str = QString( "Fast Shrink( 4 ) Scale( %1, %2, ScaleFree)" ).arg( wid ).arg( hei ); 1421 QString str = QString( "Fast Shrink( 4 ) Scale( %1, %2, ScaleFree)" ).arg( wid ).arg( hei );
1418 iio.setParameters( str.latin1() );// will be strdupped anyway 1422 iio.setParameters( str.latin1() );// will be strdupped anyway
1419 img = iio.read() ? iio.image() : QImage(); 1423 img = iio.read() ? iio.image() : QImage();
1420 return ThumbNailTool::scaleImage( img, wid,hei ); 1424 return ThumbNailTool::scaleImage( img, wid,hei );
1421 }else{ 1425 }else{
1422 QImage img = ImageInfo.getThumbnail(); 1426 QImage img = ImageInfo.getThumbnail();
1423 return ThumbNailTool::scaleImage( img, wid,hei ); 1427 return ThumbNailTool::scaleImage( img, wid,hei );
1424 } 1428 }
1425} 1429}
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
@@ -1,325 +1,325 @@
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..}^=.=       =       ; 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 "audiowidget.h" 35#include "audiowidget.h"
36 36
37#include <qpe/qpeapplication.h> 37#include <qpe/qpeapplication.h>
38 38
39using namespace Opie::Ui; 39using 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
@@ -1,432 +1,432 @@
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 LJP <> 5 Copyright (c) 2002 LJP <>
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..}^=.=       =       ; 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
@@ -1,401 +1,401 @@
1#include <qpe/qpeapplication.h> 1#include <qpe/qpeapplication.h>
2#include <qpe/config.h> 2#include <qpe/config.h>
3#include <qfileinfo.h> 3#include <qfileinfo.h>
4 4
5#include "mediaplayer.h" 5#include "mediaplayer.h"
6#include "audiowidget.h" 6#include "audiowidget.h"
7#include "videowidget.h" 7#include "videowidget.h"
8#include "volumecontrol.h" 8#include "volumecontrol.h"
9 9
10 10
11 // for setBacklight() 11 // for setBacklight()
12#include <linux/fb.h> 12#include <linux/fb.h>
13#include <sys/file.h> 13#include <sys/file.h>
14#include <sys/ioctl.h> 14#include <sys/ioctl.h>
15 15
16 16
17#define FBIOBLANK 0x4611 17#define FBIOBLANK 0x4611
18 18
19MediaPlayer::MediaPlayer( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QObject *parent, const char *name ) 19MediaPlayer::MediaPlayer( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QObject *parent, const char *name )
20 : QObject( parent, name ), volumeDirection( 0 ), mediaPlayerState( _mediaPlayerState ), playList( _playList ) { 20 : QObject( parent, name ), volumeDirection( 0 ), mediaPlayerState( _mediaPlayerState ), playList( _playList ) {
21 21
22 m_audioUI = 0; 22 m_audioUI = 0;
23 m_videoUI = 0; 23 m_videoUI = 0;
24 m_xineControl = 0; 24 m_xineControl = 0;
25 xine = new XINE::Lib( XINE::Lib::InitializeInThread ); 25 xine = new XINE::Lib( XINE::Lib::InitializeInThread );
26 26
27 fd=-1;fl=-1; 27 fd=-1;fl=-1;
28 playList.setCaption( tr( "OpiePlayer: Initializating" ) ); 28 playList.setCaption( tr( "OpiePlayer: Initializating" ) );
29 29
30 qApp->processEvents(); 30 qApp->processEvents();
31 // QPEApplication::grabKeyboard(); // EVIL 31 // QPEApplication::grabKeyboard(); // EVIL
32 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 32 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
33 33
34 connect( &mediaPlayerState, SIGNAL( playingToggled(bool) ), this, SLOT( setPlaying(bool) ) ); 34 connect( &mediaPlayerState, SIGNAL( playingToggled(bool) ), this, SLOT( setPlaying(bool) ) );
35 35
36// What is pauseCheck good for? (Simon) 36// What is pauseCheck good for? (Simon)
37// connect( &mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( pauseCheck(bool) ) ); 37// connect( &mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( pauseCheck(bool) ) );
38 38
39 connect( &mediaPlayerState, SIGNAL( next() ), this, SLOT( next() ) ); 39 connect( &mediaPlayerState, SIGNAL( next() ), this, SLOT( next() ) );
40 connect( &mediaPlayerState, SIGNAL( prev() ), this, SLOT( prev() ) ); 40 connect( &mediaPlayerState, SIGNAL( prev() ), this, SLOT( prev() ) );
41 connect( &mediaPlayerState, SIGNAL( blankToggled(bool) ), this, SLOT ( blank(bool) ) ); 41 connect( &mediaPlayerState, SIGNAL( blankToggled(bool) ), this, SLOT ( blank(bool) ) );
42 42
43 volControl = new VolumeControl; 43 volControl = new VolumeControl;
44 Config cfg( "OpiePlayer" ); 44 Config cfg( "OpiePlayer" );
45 cfg.setGroup("PlayList"); 45 cfg.setGroup("PlayList");
46 QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default"); 46 QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default");
47 playList.setCaption( tr( "OpiePlayer: " ) + QFileInfo(currentPlaylist).baseName() ); 47 playList.setCaption( tr( "OpiePlayer: " ) + QFileInfo(currentPlaylist).baseName() );
48 48
49 m_skinLoader = new SkinLoader; 49 m_skinLoader = new SkinLoader;
50 m_skinLoader->schedule( AudioWidget::guiInfo() ); 50 m_skinLoader->schedule( AudioWidget::guiInfo() );
51 m_skinLoader->schedule( VideoWidget::guiInfo() ); 51 m_skinLoader->schedule( VideoWidget::guiInfo() );
52 m_skinLoader->start(); 52 m_skinLoader->start();
53} 53}
54 54
55MediaPlayer::~MediaPlayer() { 55MediaPlayer::~MediaPlayer() {
56 // this shold never happen, but one never knows... 56 // this shold never happen, but one never knows...
57 if ( xine ) { 57 if ( xine ) {
58 xine->ensureInitialized(); 58 xine->ensureInitialized();
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
@@ -1,1043 +1,1043 @@
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,2003 Max Reiss <harlekin@handhelds.org> 4              Copyright (c) 2002,2003 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#include <qtoolbar.h> 34#include <qtoolbar.h>
35 35
36#include <opie2/ofiledialog.h> 36#include <opie2/ofiledialog.h>
37 37
38#include <qmessagebox.h> 38#include <qmessagebox.h>
39 39
40#include "playlistselection.h" 40#include "playlistselection.h"
41#include "playlistwidget.h" 41#include "playlistwidget.h"
42#include "mediaplayer.h" 42#include "mediaplayer.h"
43#include "inputDialog.h" 43#include "inputDialog.h"
44#include "om3u.h" 44#include "om3u.h"
45#include "playlistfileview.h" 45#include "playlistfileview.h"
46 46
47//only needed for the random play 47//only needed for the random play
48#include <assert.h> 48#include <assert.h>
49 49
50using namespace Opie::Ui; 50using namespace Opie::Ui;
51PlayListWidget::PlayListWidget(QWidget* parent, const char* name, WFlags fl ) 51PlayListWidget::PlayListWidget(QWidget* parent, const char* name, WFlags fl )
52 : PlayListWidgetGui( parent, "playList" ) , currentFileListView( 0 ) 52 : PlayListWidgetGui( parent, "playList" ) , currentFileListView( 0 )
53{ 53{
54 mediaPlayerState = new MediaPlayerState(0, "mediaPlayerState" ); 54 mediaPlayerState = new MediaPlayerState(0, "mediaPlayerState" );
55 m_mp = new MediaPlayer(*this, *mediaPlayerState, 0, "mediaPlayer"); 55 m_mp = new MediaPlayer(*this, *mediaPlayerState, 0, "mediaPlayer");
56 56
57 57
58 58
59 d->tbAddToList = new ToolButton( bar, tr( "Add to Playlist" ), 59 d->tbAddToList = new ToolButton( bar, tr( "Add to Playlist" ),
60 "opieplayer2/add_to_playlist", 60 "opieplayer2/add_to_playlist",
61 this , SLOT(addSelected() ) ); 61 this , SLOT(addSelected() ) );
62 d->tbRemoveFromList = new ToolButton( bar, tr( "Remove from Playlist" ), 62 d->tbRemoveFromList = new ToolButton( bar, tr( "Remove from Playlist" ),
63 "opieplayer2/remove_from_playlist", 63 "opieplayer2/remove_from_playlist",
64 this , SLOT(removeSelected() ) ); 64 this , SLOT(removeSelected() ) );
65 d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer2/play", 65 d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer2/play",
66 this , SLOT( btnPlay(bool) ), TRUE ); 66 this , SLOT( btnPlay(bool) ), TRUE );
67 d->tbShuffle = new ToolButton( bar, tr( "Randomize" ),"opieplayer2/shuffle", 67 d->tbShuffle = new ToolButton( bar, tr( "Randomize" ),"opieplayer2/shuffle",
68 mediaPlayerState, SLOT( setShuffled(bool) ), TRUE ); 68 mediaPlayerState, SLOT( setShuffled(bool) ), TRUE );
69 d->tbLoop = new ToolButton( bar, tr( "Loop" ), "opieplayer2/loop", 69 d->tbLoop = new ToolButton( bar, tr( "Loop" ), "opieplayer2/loop",
70 mediaPlayerState, SLOT( setLooping(bool) ), TRUE ); 70 mediaPlayerState, SLOT( setLooping(bool) ), TRUE );
71 71
72 (void)new MenuItem( pmPlayList, tr( "Clear List" ), this, SLOT( clearList() ) ); 72 (void)new MenuItem( pmPlayList, tr( "Clear List" ), this, SLOT( clearList() ) );
73 (void)new MenuItem( pmPlayList, tr( "Add all audio files" ), 73 (void)new MenuItem( pmPlayList, tr( "Add all audio files" ),
74 this, SLOT( addAllMusicToList() ) ); 74 this, SLOT( addAllMusicToList() ) );
75 (void)new MenuItem( pmPlayList, tr( "Add all video files" ), 75 (void)new MenuItem( pmPlayList, tr( "Add all video files" ),
76 this, SLOT( addAllVideoToList() ) ); 76 this, SLOT( addAllVideoToList() ) );
77 (void)new MenuItem( pmPlayList, tr( "Add all files" ), 77 (void)new MenuItem( pmPlayList, tr( "Add all files" ),
78 this, SLOT( addAllToList() ) ); 78 this, SLOT( addAllToList() ) );
79 pmPlayList->insertSeparator(-1); 79 pmPlayList->insertSeparator(-1);
80 (void)new MenuItem( pmPlayList, tr( "Add File" ), 80 (void)new MenuItem( pmPlayList, tr( "Add File" ),
81 this,SLOT( openFile() ) ); 81 this,SLOT( openFile() ) );
82 (void)new MenuItem( pmPlayList, tr("Add URL"), 82 (void)new MenuItem( pmPlayList, tr("Add URL"),
83 this,SLOT( openURL() ) ); 83 this,SLOT( openURL() ) );
84 pmPlayList->insertSeparator(-1); 84 pmPlayList->insertSeparator(-1);
85 (void)new MenuItem( pmPlayList, tr( "Save Playlist" ), 85 (void)new MenuItem( pmPlayList, tr( "Save Playlist" ),
86 this, SLOT(writem3u() ) ); 86 this, SLOT(writem3u() ) );
87 pmPlayList->insertSeparator(-1); 87 pmPlayList->insertSeparator(-1);
88 (void)new MenuItem( pmPlayList, tr( "Rescan for Audio Files" ), 88 (void)new MenuItem( pmPlayList, tr( "Rescan for Audio Files" ),
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
501 501
502void PlayListWidget::tabChanged(QWidget *) { 502void PlayListWidget::tabChanged(QWidget *) {
503 503
504 d->tbPlay->setEnabled( true ); 504 d->tbPlay->setEnabled( true );
505 505
506 disconnect( audioView, SIGNAL( itemsSelected(bool) ), 506 disconnect( audioView, SIGNAL( itemsSelected(bool) ),
507 d->tbPlay, SLOT( setEnabled(bool) ) ); 507 d->tbPlay, SLOT( setEnabled(bool) ) );
508 disconnect( videoView, SIGNAL( itemsSelected(bool) ), 508 disconnect( videoView, SIGNAL( itemsSelected(bool) ),
509 d->tbPlay, SLOT( setEnabled(bool) ) ); 509 d->tbPlay, SLOT( setEnabled(bool) ) );
510 510
511 currentFileListView = 0; 511 currentFileListView = 0;
512 512
513 switch ( currentTab() ) { 513 switch ( currentTab() ) {
514 case CurrentPlayList: 514 case CurrentPlayList:
515 { 515 {
516 if( !tbDeletePlaylist->isHidden() ) { 516 if( !tbDeletePlaylist->isHidden() ) {
517 tbDeletePlaylist->hide(); 517 tbDeletePlaylist->hide();
518 } 518 }
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
@@ -1,193 +1,193 @@
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 <qtoolbar.h> 35#include <qtoolbar.h>
36#include <qpe/qpeapplication.h> 36#include <qpe/qpeapplication.h>
37 37
38#include <qlayout.h> 38#include <qlayout.h>
39#include <qmenubar.h> 39#include <qmenubar.h>
40 40
41#include "playlistselection.h" 41#include "playlistselection.h"
42#include "playlistwidget.h" 42#include "playlistwidget.h"
43#include "mediaplayerstate.h" 43#include "mediaplayerstate.h"
44#include "inputDialog.h" 44#include "inputDialog.h"
45#include "playlistfileview.h" 45#include "playlistfileview.h"
46 46
47 47
48PlayListWidgetGui::PlayListWidgetGui(QWidget* parent, const char* name ) 48PlayListWidgetGui::PlayListWidgetGui(QWidget* parent, const char* name )
49 : QMainWindow( parent, name ) { 49 : QMainWindow( parent, name ) {
50 50
51 d = new PlayListWidgetPrivate; 51 d = new PlayListWidgetPrivate;
52 d->setDocumentUsed = FALSE; 52 d->setDocumentUsed = FALSE;
53 53
54 setBackgroundMode( PaletteButton ); 54 setBackgroundMode( PaletteButton );
55 setToolBarsMovable( FALSE ); 55 setToolBarsMovable( FALSE );
56 56
57 // Create Toolbar 57 // Create Toolbar
58 QToolBar *toolbar = new QToolBar( this ); 58 QToolBar *toolbar = new QToolBar( this );
59 toolbar->setHorizontalStretchable( TRUE ); 59 toolbar->setHorizontalStretchable( TRUE );
60 60
61 // Create Menubar 61 // Create Menubar
62 QMenuBar *menu = new QMenuBar( toolbar ); 62 QMenuBar *menu = new QMenuBar( toolbar );
63 menu->setMargin( 0 ); 63 menu->setMargin( 0 );
64 64
65 bar = new QToolBar( this ); 65 bar = new QToolBar( this );
66 bar->setLabel( tr( "Play Operations" ) ); 66 bar->setLabel( tr( "Play Operations" ) );
67 67
68 tbDeletePlaylist = new QPushButton( Resource::loadIconSet( "trash" ), "", bar, "close" ); 68 tbDeletePlaylist = new QPushButton( Resource::loadIconSet( "trash" ), "", bar, "close" );
69 tbDeletePlaylist->setFlat( TRUE ); 69 tbDeletePlaylist->setFlat( TRUE );
70 tbDeletePlaylist->setFixedSize( 20, 20 ); 70 tbDeletePlaylist->setFixedSize( 20, 20 );
71 71
72 tbDeletePlaylist->hide(); 72 tbDeletePlaylist->hide();
73 73
74 pmPlayList = new QPopupMenu( this ); 74 pmPlayList = new QPopupMenu( this );
75 menu->insertItem( tr( "File" ), pmPlayList ); 75 menu->insertItem( tr( "File" ), pmPlayList );
76 76
77 pmView = new QPopupMenu( this ); 77 pmView = new QPopupMenu( this );
78 menu->insertItem( tr( "View" ), pmView ); 78 menu->insertItem( tr( "View" ), pmView );
79 pmView->isCheckable(); 79 pmView->isCheckable();
80 80
81 skinsMenu = new QPopupMenu( this ); 81 skinsMenu = new QPopupMenu( this );
82 pmView->insertItem( tr( "Skins" ), skinsMenu ); 82 pmView->insertItem( tr( "Skins" ), skinsMenu );
83 skinsMenu->isCheckable(); 83 skinsMenu->isCheckable();
84 84
85 gammaMenu = new QPopupMenu( this ); 85 gammaMenu = new QPopupMenu( this );
86 pmView->insertItem( tr( "Gamma (Video)" ), gammaMenu ); 86 pmView->insertItem( tr( "Gamma (Video)" ), gammaMenu );
87 87
88 gammaSlider = new QSlider( QSlider::Vertical, gammaMenu ); 88 gammaSlider = new QSlider( QSlider::Vertical, gammaMenu );
89 gammaSlider->setRange( -40, 40 ); 89 gammaSlider->setRange( -40, 40 );
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
@@ -1,322 +1,322 @@
1/* 1/*
2 Copyright (C) 2002 Simon Hausmann <simon@lst.de> 2 Copyright (C) 2002 Simon Hausmann <simon@lst.de>
3 (C) 2002 Max Reiss <harlekin@handhelds.org> 3 (C) 2002 Max Reiss <harlekin@handhelds.org>
4 (C) 2002 L. Potter <ljp@llornkcor.com> 4 (C) 2002 L. Potter <ljp@llornkcor.com>
5 (C) 2002 Holger Freyther <zecke@handhelds.org> 5 (C) 2002 Holger Freyther <zecke@handhelds.org>
6 6
7 This program is free software; you can redistribute it and/or 7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public 8 modify it under the terms of the GNU General Public
9 License as published by the Free Software Foundation; either 9 License as published by the Free Software Foundation; either
10 version 2 of the License, or (at your option) any later version. 10 version 2 of the License, or (at your option) any later version.
11 11
12 This program is distributed in the hope that it will be useful, 12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details. 15 General Public License for more details.
16 16
17 You should have received a copy of the GNU General Public License 17 You should have received a copy of the GNU General Public License
18 along with this program; see the file COPYING. If not, write to 18 along with this program; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. 20 Boston, MA 02111-1307, USA.
21*/ 21*/
22 22
23#include "skin.h" 23#include "skin.h"
24#include "singleton.h" 24#include "singleton.h"
25 25
26#include <qcache.h> 26#include <qcache.h>
27#include <qtimer.h> 27#include <qtimer.h>
28 28
29#include <qpe/config.h> 29#include <qpe/config.h>
30 30
31#include <assert.h> 31#include <assert.h>
32 32
33struct SkinData 33struct SkinData
34{ 34{
35 typedef QMap<QString, QImage> ButtonMaskImageMap; 35 typedef QMap<QString, QImage> ButtonMaskImageMap;
36 36
37 QPixmap backgroundPixmap; 37 QPixmap backgroundPixmap;
38 QImage buttonUpImage; 38 QImage buttonUpImage;
39 QImage buttonDownImage; 39 QImage buttonDownImage;
40 QImage buttonMask; 40 QImage buttonMask;
41 ButtonMaskImageMap buttonMasks; 41 ButtonMaskImageMap buttonMasks;
42}; 42};
43 43
44class SkinCache : public Singleton<SkinCache> 44class SkinCache : public Singleton<SkinCache>
45{ 45{
46public: 46public:
47 SkinCache(); 47 SkinCache();
48 48
49 SkinData *lookupAndTake( const QString &skinPath, const QString &fileNameInfix ); 49 SkinData *lookupAndTake( const QString &skinPath, const QString &fileNameInfix );
50 50
51 void store( const QString &skinPath, const QString &fileNameInfix, SkinData *data ); 51 void store( const QString &skinPath, const QString &fileNameInfix, SkinData *data );
52 52
53private: 53private:
54 typedef QCache<SkinData> DataCache; 54 typedef QCache<SkinData> DataCache;
55 typedef QCache<QPixmap> BackgroundPixmapCache; 55 typedef QCache<QPixmap> BackgroundPixmapCache;
56 56
57 template <class CacheType> 57 template <class CacheType>
58 void store( const QCache<CacheType> &cache, const QString &key, CacheType *data ); 58 void store( const QCache<CacheType> &cache, const QString &key, CacheType *data );
59 59
60 DataCache m_cache; 60 DataCache m_cache;
61 BackgroundPixmapCache m_backgroundPixmapCache; 61 BackgroundPixmapCache m_backgroundPixmapCache;
62}; 62};
63 63
64Skin::Skin( const QString &name, const QString &fileNameInfix ) 64Skin::Skin( const QString &name, const QString &fileNameInfix )
65 : m_fileNameInfix( fileNameInfix ) 65 : m_fileNameInfix( fileNameInfix )
66{ 66{
67 init( name ); 67 init( name );
68} 68}
69 69
70Skin::Skin( const QString &fileNameInfix ) 70Skin::Skin( const QString &fileNameInfix )
71 : m_fileNameInfix( fileNameInfix ) 71 : m_fileNameInfix( fileNameInfix )
72{ 72{
73 init( defaultSkinName() ); 73 init( defaultSkinName() );
74} 74}
75 75
76Skin::~Skin() 76Skin::~Skin()
77{ 77{
78 if ( m_isCachable ) 78 if ( m_isCachable )
79 SkinCache::self().store( m_skinPath, m_fileNameInfix, d ); 79 SkinCache::self().store( m_skinPath, m_fileNameInfix, d );
80 else 80 else
81 delete d; 81 delete d;
82} 82}
83 83
84void Skin::init( const QString &name ) 84void 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
@@ -1,394 +1,394 @@
1/* This file is part of the KDE project 1/* This file is part of the KDE project
2 Copyright (C) 2002 Simon Hausmann <hausmann@kde.org> 2 Copyright (C) 2002 Simon Hausmann <hausmann@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 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 library is distributed in the hope that it will be useful, 9 This library 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 License 14 You should have received a copy of the GNU Library General Public License
15 along with this library; see the file COPYING.LIB. If not, write to 15 along with this library; see the file COPYING.LIB. If not, write to
16 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 16 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA. 17 Boston, MA 02111-1307, USA.
18*/ 18*/
19 19
20#include "threadutil.h" 20#include "threadutil.h"
21 21
22#include <qsocketnotifier.h> 22#include <qsocketnotifier.h>
23 23
24#include <pthread.h> 24#include <pthread.h>
25#include <assert.h> 25#include <assert.h>
26#include <unistd.h> 26#include <unistd.h>
27#include <errno.h> 27#include <errno.h>
28 28
29using namespace ThreadUtil; 29using namespace ThreadUtil;
30 30
31struct Mutex::Data 31struct Mutex::Data
32{ 32{
33 Data() 33 Data()
34 { 34 {
35 pthread_mutex_init( &mutex, 0 ); 35 pthread_mutex_init( &mutex, 0 );
36 } 36 }
37 ~Data() 37 ~Data()
38 { 38 {
39 pthread_mutex_destroy( &mutex ); 39 pthread_mutex_destroy( &mutex );
40 } 40 }
41 41
42 pthread_mutex_t mutex; 42 pthread_mutex_t mutex;
43}; 43};
44 44
45Mutex::Mutex() 45Mutex::Mutex()
46 : d( new Data ) 46 : d( new Data )
47{ 47{
48} 48}
49 49
50Mutex::~Mutex() 50Mutex::~Mutex()
51{ 51{
52 delete d; 52 delete d;
53} 53}
54 54
55void Mutex::lock() 55void Mutex::lock()
56{ 56{
57 pthread_mutex_lock( &d->mutex ); 57 pthread_mutex_lock( &d->mutex );
58} 58}
59 59
60void Mutex::unlock() 60void Mutex::unlock()
61{ 61{
62 pthread_mutex_unlock( &d->mutex ); 62 pthread_mutex_unlock( &d->mutex );
63} 63}
64 64
65bool Mutex::tryLock() 65bool Mutex::tryLock()
66{ 66{
67 return pthread_mutex_trylock( &d->mutex ) == 0; 67 return pthread_mutex_trylock( &d->mutex ) == 0;
68} 68}
69 69
70bool Mutex::isLocked() 70bool Mutex::isLocked()
71{ 71{
72 if ( !tryLock() ) 72 if ( !tryLock() )
73 return true; 73 return true;
74 74
75 unlock(); 75 unlock();
76 return false; 76 return false;
77} 77}
78 78
79struct WaitCondition::Data 79struct WaitCondition::Data
80{ 80{
81 Data() 81 Data()
82 { 82 {
83 int result = pthread_cond_init( &waitCondition, 0 ); 83 int result = pthread_cond_init( &waitCondition, 0 );
84 assert( result == 0 ); 84 assert( result == 0 );
85 } 85 }
86 ~Data() 86 ~Data()
87 { 87 {
88 pthread_cond_destroy( &waitCondition ); 88 pthread_cond_destroy( &waitCondition );
89 } 89 }
90 90
91 pthread_cond_t waitCondition; 91 pthread_cond_t waitCondition;
92}; 92};
93 93
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 )
384 { 384 {
385 msg->m_condition.wakeOne(); 385 msg->m_condition.wakeOne();
386 // this is a bit tricky. we unlock only when we reply. 386 // this is a bit tricky. we unlock only when we reply.
387 // reply() does an unlock as well. 387 // reply() does an unlock as well.
388 msg->m_guard.unlock(); 388 msg->m_guard.unlock();
389 } 389 }
390 } 390 }
391} 391}
392 392
393/* vim: et sw=4 ts=4 393/* vim: et sw=4 ts=4
394 */ 394 */
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,196 +1,201 @@
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()
125{ 130{
126#ifndef QT_NO_FILEDIALOG 131#ifndef QT_NO_FILEDIALOG
127#endif 132#endif
128} 133}
129 134
130void HelpWindow::newWindow() 135void HelpWindow::newWindow()
131{ 136{
132 ( new HelpWindow(browser->source(), "qbrowser") )->show(); 137 ( new HelpWindow(browser->source(), "qbrowser") )->show();
133} 138}
134 139
135void HelpWindow::print() 140void HelpWindow::print()
136{ 141{
137#ifndef QT_NO_PRINTER 142#ifndef QT_NO_PRINTER
138#endif 143#endif
139} 144}
140 145
141void HelpWindow::pathSelected( const QString &_path ) 146void HelpWindow::pathSelected( const QString &_path )
142{ 147{
143 browser->setSource( _path ); 148 browser->setSource( _path );
144 QMap<int, QString>::Iterator it = mHistory.begin(); 149 QMap<int, QString>::Iterator it = mHistory.begin();
145 bool exists = FALSE; 150 bool exists = FALSE;
146 for ( ; it != mHistory.end(); ++it ) { 151 for ( ; it != mHistory.end(); ++it ) {
147 if ( *it == _path ) { 152 if ( *it == _path ) {
148 exists = TRUE; 153 exists = TRUE;
149 break; 154 break;
150 } 155 }
151 } 156 }
152 if ( !exists ) 157 if ( !exists )
153 mHistory[ hist->insertItem( _path ) ] = _path; 158 mHistory[ hist->insertItem( _path ) ] = _path;
154} 159}
155 160
156void HelpWindow::readHistory() 161void HelpWindow::readHistory()
157{ 162{
158 if ( QFile::exists( QDir::currentDirPath() + "/.history" ) ) { 163 if ( QFile::exists( QDir::currentDirPath() + "/.history" ) ) {
159 QFile f( QDir::currentDirPath() + "/.history" ); 164 QFile f( QDir::currentDirPath() + "/.history" );
160 f.open( IO_ReadOnly ); 165 f.open( IO_ReadOnly );
161 QDataStream s( &f ); 166 QDataStream s( &f );
162 s >> history; 167 s >> history;
163 f.close(); 168 f.close();
164 while ( history.count() > 20 ) 169 while ( history.count() > 20 )
165 history.remove( history.begin() ); 170 history.remove( history.begin() );
166 } 171 }
167} 172}
168 173
169void HelpWindow::readBookmarks() 174void HelpWindow::readBookmarks()
170{ 175{
171 if ( QFile::exists( QDir::currentDirPath() + "/.bookmarks" ) ) { 176 if ( QFile::exists( QDir::currentDirPath() + "/.bookmarks" ) ) {
172 QFile f( QDir::currentDirPath() + "/.bookmarks" ); 177 QFile f( QDir::currentDirPath() + "/.bookmarks" );
173 f.open( IO_ReadOnly ); 178 f.open( IO_ReadOnly );
174 QDataStream s( &f ); 179 QDataStream s( &f );
175 s >> bookmarks; 180 s >> bookmarks;
176 f.close(); 181 f.close();
177 } 182 }
178} 183}
179 184
180void HelpWindow::histChosen( int i ) 185void HelpWindow::histChosen( int i )
181{ 186{
182 if ( mHistory.contains( i ) ) 187 if ( mHistory.contains( i ) )
183 browser->setSource( mHistory[ i ] ); 188 browser->setSource( mHistory[ i ] );
184} 189}
185 190
186void HelpWindow::bookmChosen( int i ) 191void HelpWindow::bookmChosen( int i )
187{ 192{
188 if ( mBookmarks.contains( i ) ) 193 if ( mBookmarks.contains( i ) )
189 browser->setSource( mBookmarks[ i ] ); 194 browser->setSource( mBookmarks[ i ] );
190} 195}
191 196
192void HelpWindow::addBookmark() 197void HelpWindow::addBookmark()
193{ 198{
194 mBookmarks[ bookm->insertItem( caption() ) ] = caption(); 199 mBookmarks[ bookm->insertItem( caption() ) ] = caption();
195} 200}
196 201
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,2132 +1,2131 @@
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();
473 } 472 }
474 473
475 ListView1->clear(); 474 ListView1->clear();
476 475
477 if( autoMute) 476 if( autoMute)
478 doMute(false); 477 doMute(false);
479 478
480 if( wavFile) delete wavFile; 479 if( wavFile) delete wavFile;
481// if(soundDevice) delete soundDevice; 480// if(soundDevice) delete soundDevice;
482} 481}
483 482
484void QtRec::init() { 483void QtRec::init() {
485 484
486 needsStereoOut = false; 485 needsStereoOut = false;
487 QPixmap image3( ( const char** ) image3_data ); 486 QPixmap image3( ( const char** ) image3_data );
488 QPixmap image4( ( const char** ) image4_data ); 487 QPixmap image4( ( const char** ) image4_data );
489 QPixmap image6( ( const char** ) image6_data ); 488 QPixmap image6( ( const char** ) image6_data );
490 489
491 stopped = true; 490 stopped = true;
492 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); 491 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) );
493 QGridLayout *layout = new QGridLayout( this ); 492 QGridLayout *layout = new QGridLayout( this );
494 layout->setSpacing( 2); 493 layout->setSpacing( 2);
495 layout->setMargin( 2); 494 layout->setMargin( 2);
496 495
497 TabWidget = new QTabWidget( this, "TabWidget" ); 496 TabWidget = new QTabWidget( this, "TabWidget" );
498 layout->addMultiCellWidget(TabWidget, 0, 7, 0, 7); 497 layout->addMultiCellWidget(TabWidget, 0, 7, 0, 7);
499// TabWidget->setTabShape(QTabWidget::Triangular); 498// TabWidget->setTabShape(QTabWidget::Triangular);
500 499
501 ///**********<<<<<<<<<<<<>>>>>>>>>>>>*************** 500 ///**********<<<<<<<<<<<<>>>>>>>>>>>>***************
502 tab = new QWidget( TabWidget, "tab" ); 501 tab = new QWidget( TabWidget, "tab" );
503 502
504 QGridLayout *layout1 = new QGridLayout( tab); 503 QGridLayout *layout1 = new QGridLayout( tab);
505 layout1->setSpacing( 2); 504 layout1->setSpacing( 2);
506 layout1->setMargin( 2); 505 layout1->setMargin( 2);
507 506
508 timeSlider = new QSlider( 0,100,10,0, QSlider::Horizontal, tab, (const char *) "timeSlider" ); 507 timeSlider = new QSlider( 0,100,10,0, QSlider::Horizontal, tab, (const char *) "timeSlider" );
509 layout1->addMultiCellWidget( timeSlider, 1, 1, 0, 3); 508 layout1->addMultiCellWidget( timeSlider, 1, 1, 0, 3);
510 509
511 timeLabel = new QLabel( tab, "TimeLabel" ); 510 timeLabel = new QLabel( tab, "TimeLabel" );
512 layout1->addMultiCellWidget( timeLabel, 0, 0, 0, 3); 511 layout1->addMultiCellWidget( timeLabel, 0, 0, 0, 3);
513 512
514 playLabel2 = new QLabel(tab, "PlayLabel2" ); 513 playLabel2 = new QLabel(tab, "PlayLabel2" );
515 playLabel2->setText(tr("Play") ); 514 playLabel2->setText(tr("Play") );
516 playLabel2->setFixedHeight( 18); 515 playLabel2->setFixedHeight( 18);
517 layout1->addMultiCellWidget( playLabel2, 0, 0, 4, 4); 516 layout1->addMultiCellWidget( playLabel2, 0, 0, 4, 4);
518 517
519 Stop_PushButton = new QPushButton( tab, "Stop_PushButton" ); 518 Stop_PushButton = new QPushButton( tab, "Stop_PushButton" );
520 layout1->addMultiCellWidget( Stop_PushButton, 1, 1, 4, 4); 519 layout1->addMultiCellWidget( Stop_PushButton, 1, 1, 4, 4);
521 Stop_PushButton->setFixedSize( 22, 22); 520 Stop_PushButton->setFixedSize( 22, 22);
522 Stop_PushButton->setPixmap( image4 ); 521 Stop_PushButton->setPixmap( image4 );
523 522
524 toBeginningButton = new QPushButton( tab, "Beginning_PushButton" ); 523 toBeginningButton = new QPushButton( tab, "Beginning_PushButton" );
525 layout1->addMultiCellWidget(toBeginningButton, 1, 1, 5, 5); 524 layout1->addMultiCellWidget(toBeginningButton, 1, 1, 5, 5);
526 toBeginningButton->setFixedSize( 22, 22); 525 toBeginningButton->setFixedSize( 22, 22);
527 toBeginningButton->setPixmap( Resource::loadPixmap("fastback") ); 526 toBeginningButton->setPixmap( Resource::loadPixmap("fastback") );
528 527
529 toEndButton = new QPushButton( tab, "End_PushButton" ); 528 toEndButton = new QPushButton( tab, "End_PushButton" );
530 layout1->addMultiCellWidget( toEndButton, 1, 1, 6, 6); 529 layout1->addMultiCellWidget( toEndButton, 1, 1, 6, 6);
531 toEndButton->setFixedSize( 22, 22); 530 toEndButton->setFixedSize( 22, 22);
532 toEndButton->setPixmap( Resource::loadPixmap( "fastforward" ) ); 531 toEndButton->setPixmap( Resource::loadPixmap( "fastforward" ) );
533 532
534 QLabel *recLabel2; 533 QLabel *recLabel2;
535 recLabel2 = new QLabel( tab, "recLabel2" ); 534 recLabel2 = new QLabel( tab, "recLabel2" );
536 recLabel2->setText(tr("Rec")); 535 recLabel2->setText(tr("Rec"));
537 recLabel2->setFixedHeight( 18); 536 recLabel2->setFixedHeight( 18);
538 layout1->addMultiCellWidget( recLabel2, 0, 0, 7, 7); 537 layout1->addMultiCellWidget( recLabel2, 0, 0, 7, 7);
539 538
540 Rec_PushButton = new QPushButton( tab, "Rec_PushButton" ); 539 Rec_PushButton = new QPushButton( tab, "Rec_PushButton" );
541 layout1->addMultiCellWidget( Rec_PushButton, 1, 1, 7, 7); 540 layout1->addMultiCellWidget( Rec_PushButton, 1, 1, 7, 7);
542 Rec_PushButton->setFixedSize( 22, 22); 541 Rec_PushButton->setFixedSize( 22, 22);
543 Rec_PushButton->setPixmap( image6 ); 542 Rec_PushButton->setPixmap( image6 );
544 543
545 t = new QTimer( this ); 544 t = new QTimer( this );
546 connect( t, SIGNAL( timeout() ), SLOT( timerBreak() ) ); 545 connect( t, SIGNAL( timeout() ), SLOT( timerBreak() ) );
547 546
548 rewindTimer = new QTimer( this ); 547 rewindTimer = new QTimer( this );
549 connect( rewindTimer, SIGNAL( timeout() ), 548 connect( rewindTimer, SIGNAL( timeout() ),
550 this, SLOT( rewindTimerTimeout() ) ); 549 this, SLOT( rewindTimerTimeout() ) );
551 550
552 forwardTimer = new QTimer( this ); 551 forwardTimer = new QTimer( this );
553 connect( forwardTimer, SIGNAL( timeout() ), 552 connect( forwardTimer, SIGNAL( timeout() ),
554 this, SLOT( forwardTimerTimeout() ) ); 553 this, SLOT( forwardTimerTimeout() ) );
555 554
556 deleteSoundButton = new QPushButton( tab, "deleteSoundButton" ); 555 deleteSoundButton = new QPushButton( tab, "deleteSoundButton" );
557 layout1->addMultiCellWidget( deleteSoundButton, 1, 1, 8, 8); 556 layout1->addMultiCellWidget( deleteSoundButton, 1, 1, 8, 8);
558 deleteSoundButton->setText( tr( "Delete" ) ); 557 deleteSoundButton->setText( tr( "Delete" ) );
559 558
560 ListView1 = new QListView( tab, "IconView1" ); 559 ListView1 = new QListView( tab, "IconView1" );
561 layout1->addMultiCellWidget( ListView1, 2, 2, 0, 8); 560 layout1->addMultiCellWidget( ListView1, 2, 2, 0, 8);
562 561
563 ListView1->addColumn( tr( "Name" ) ); 562 ListView1->addColumn( tr( "Name" ) );
564 ListView1->setColumnWidth( 0, 140); 563 ListView1->setColumnWidth( 0, 140);
565 ListView1->setSorting( 1, false); 564 ListView1->setSorting( 1, false);
566 ListView1->addColumn( tr( "Time" ) ); //in seconds 565 ListView1->addColumn( tr( "Time" ) ); //in seconds
567 ListView1->setColumnWidth( 1, 50); 566 ListView1->setColumnWidth( 1, 50);
568 ListView1->addColumn( tr("Location") ); 567 ListView1->addColumn( tr("Location") );
569 ListView1->setColumnWidth( 2, 50); 568 ListView1->setColumnWidth( 2, 50);
570 ListView1->addColumn( tr("Date") ); 569 ListView1->addColumn( tr("Date") );
571 ListView1->setColumnWidth( 3, 63); 570 ListView1->setColumnWidth( 3, 63);
572 571
573 ListView1->setColumnWidthMode( 0, QListView::Manual); 572 ListView1->setColumnWidthMode( 0, QListView::Manual);
574 ListView1->setColumnAlignment( 1, QListView::AlignCenter); 573 ListView1->setColumnAlignment( 1, QListView::AlignCenter);
575 ListView1->setColumnAlignment( 2, QListView::AlignRight); 574 ListView1->setColumnAlignment( 2, QListView::AlignRight);
576 ListView1->setColumnAlignment( 3, QListView::AlignLeft); 575 ListView1->setColumnAlignment( 3, QListView::AlignLeft);
577 ListView1->setAllColumnsShowFocus( true ); 576 ListView1->setAllColumnsShowFocus( true );
578 QPEApplication::setStylusOperation( ListView1->viewport(), QPEApplication::RightOnHold); 577 QPEApplication::setStylusOperation( ListView1->viewport(), QPEApplication::RightOnHold);
579 578
580 TabWidget->insertTab( tab, tr( "Files" ) ); 579 TabWidget->insertTab( tab, tr( "Files" ) );
581 580
582 ///**********<<<<<<<<<<<<>>>>>>>>>>>>*************** 581 ///**********<<<<<<<<<<<<>>>>>>>>>>>>***************
583 tab_3 = new QWidget( TabWidget, "tab_3" ); 582 tab_3 = new QWidget( TabWidget, "tab_3" );
584 QGridLayout *glayout3 = new QGridLayout( tab_3 ); 583 QGridLayout *glayout3 = new QGridLayout( tab_3 );
585 glayout3->setSpacing( 2); 584 glayout3->setSpacing( 2);
586 glayout3->setMargin( 2); 585 glayout3->setMargin( 2);
587 //////////////////////////////////// 586 ////////////////////////////////////
588 sampleGroup = new QGroupBox( tab_3, "samplegroup" ); 587 sampleGroup = new QGroupBox( tab_3, "samplegroup" );
589 sampleGroup->setTitle( tr( "Sample Rate" ) ); 588 sampleGroup->setTitle( tr( "Sample Rate" ) );
590 sampleGroup->setFixedSize( 95,50); 589 sampleGroup->setFixedSize( 95,50);
591 590
592 sampleRateComboBox = new QComboBox( false, sampleGroup, "SampleRateComboBox" ); 591 sampleRateComboBox = new QComboBox( false, sampleGroup, "SampleRateComboBox" );
593 sampleRateComboBox->setGeometry( QRect( 10, 20, 80, 25 ) ); 592 sampleRateComboBox->setGeometry( QRect( 10, 20, 80, 25 ) );
594//#ifndef QT_QWS_EBX 593//#ifndef QT_QWS_EBX
595 QString s; 594 QString s;
596 int z = 0; 595 int z = 0;
597 while( deviceSampleRates[z] != -1) { 596 while( deviceSampleRates[z] != -1) {
598 sampleRateComboBox->insertItem( s.setNum( deviceSampleRates[z], 10)); 597 sampleRateComboBox->insertItem( s.setNum( deviceSampleRates[z], 10));
599 z++; 598 z++;
600 } 599 }
601 600
602 601
603 glayout3->addMultiCellWidget( sampleGroup, 0, 0, 0, 0); 602 glayout3->addMultiCellWidget( sampleGroup, 0, 0, 0, 0);
604 603
605 sizeGroup= new QGroupBox( tab_3, "sizeGroup" ); 604 sizeGroup= new QGroupBox( tab_3, "sizeGroup" );
606 sizeGroup->setTitle( tr( "Limit Size" ) ); 605 sizeGroup->setTitle( tr( "Limit Size" ) );
607 sizeGroup->setFixedSize( 80, 50); 606 sizeGroup->setFixedSize( 80, 50);
608 607
609 sizeLimitCombo = new QComboBox( false, sizeGroup, "sizeLimitCombo" ); 608 sizeLimitCombo = new QComboBox( false, sizeGroup, "sizeLimitCombo" );
610 sizeLimitCombo ->setGeometry( QRect( 5, 20, 70, 25 ) ); 609 sizeLimitCombo ->setGeometry( QRect( 5, 20, 70, 25 ) );
611 sizeLimitCombo->insertItem(tr("Unlimited")); 610 sizeLimitCombo->insertItem(tr("Unlimited"));
612 611
613 for(int i=1;i<13; i++) { 612 for(int i=1;i<13; i++) {
614 sizeLimitCombo->insertItem( QString::number( i * 5)); 613 sizeLimitCombo->insertItem( QString::number( i * 5));
615 } 614 }
616 615
617 616
618 glayout3->addMultiCellWidget( sizeGroup, 0, 0, 1, 1); 617 glayout3->addMultiCellWidget( sizeGroup, 0, 0, 1, 1);
619 dirGroup = new QGroupBox( tab_3, "dirGroup" ); 618 dirGroup = new QGroupBox( tab_3, "dirGroup" );
620 dirGroup->setTitle( tr( "File Directory" ) ); 619 dirGroup->setTitle( tr( "File Directory" ) );
621 dirGroup->setFixedSize( 130, 50); 620 dirGroup->setFixedSize( 130, 50);
622 621
623 directoryComboBox = new QComboBox( false, dirGroup, "dirGroup" ); 622 directoryComboBox = new QComboBox( false, dirGroup, "dirGroup" );
624 directoryComboBox->setGeometry( QRect( 10, 15, 115, 25 ) ); 623 directoryComboBox->setGeometry( QRect( 10, 15, 115, 25 ) );
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 )
2102// input = -input; // Absolute value. 2101// input = -input; // Absolute value.
2103// if ( input >= output ) { 2102// if ( input >= output ) {
2104// // When we hit a peak, ride the peak to the top. 2103// // When we hit a peak, ride the peak to the top.
2105// output = input; 2104// output = input;
2106// } else { 2105// } else {
2107// // Exponential decay of output when signal is low. 2106// // Exponential decay of output when signal is low.
2108// output = output * scalar; 2107// output = output * scalar;
2109// // 2108// //
2110// // When current gets close to 0.0, set current to 0.0 to prevent FP underflow 2109// // When current gets close to 0.0, set current to 0.0 to prevent FP underflow
2111// // which can cause a severe performance degradation due to a flood 2110// // which can cause a severe performance degradation due to a flood
2112// // of interrupts. 2111// // of interrupts.
2113// // 2112// //
2114// if( output < vsf ) output = 0.0; 2113// if( output < vsf ) output = 0.0;
2115// } 2114// }
2116 2115
2117// return (long) output; 2116// return (long) output;
2118// } 2117// }
2119 2118
2120void QtRec::changeStereoCheck(bool b) { 2119void QtRec::changeStereoCheck(bool b) {
2121 Config cfg("OpieRec"); 2120 Config cfg("OpieRec");
2122 cfg.setGroup("Settings"); 2121 cfg.setGroup("Settings");
2123 int ch = 0; 2122 int ch = 0;
2124 if ( !b) { ch = 1;} 2123 if ( !b) { ch = 1;}
2125 else { ch = 2;} 2124 else { ch = 2;}
2126 cfg.writeEntry("stereo", b); 2125 cfg.writeEntry("stereo", b);
2127 filePara.channels = ch; 2126 filePara.channels = ch;
2128 2127
2129 cfg.write(); 2128 cfg.write();
2130} 2129}
2131 2130
2132 2131
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,585 +1,589 @@
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
119 chordnote = new QComboBox( FALSE, tab, "chordnote" ); 123 chordnote = new QComboBox( FALSE, tab, "chordnote" );
120 chordnote->insertItem( tr( "C" ) ); 124 chordnote->insertItem( tr( "C" ) );
121 chordnote->insertItem( tr( "C#" ) ); 125 chordnote->insertItem( tr( "C#" ) );
122 chordnote->insertItem( tr( "D" ) ); 126 chordnote->insertItem( tr( "D" ) );
123 chordnote->insertItem( tr( "Eb" ) ); 127 chordnote->insertItem( tr( "Eb" ) );
124 chordnote->insertItem( tr( "E" ) ); 128 chordnote->insertItem( tr( "E" ) );
125 chordnote->insertItem( tr( "F" ) ); 129 chordnote->insertItem( tr( "F" ) );
126 chordnote->insertItem( tr( "F#" ) ); 130 chordnote->insertItem( tr( "F#" ) );
127 chordnote->insertItem( tr( "G" ) ); 131 chordnote->insertItem( tr( "G" ) );
128 chordnote->insertItem( tr( "G#" ) ); 132 chordnote->insertItem( tr( "G#" ) );
129 chordnote->insertItem( tr( "A" ) ); 133 chordnote->insertItem( tr( "A" ) );
130 chordnote->insertItem( tr( "Bb" ) ); 134 chordnote->insertItem( tr( "Bb" ) );
131 chordnote->insertItem( tr( "B" ) ); 135 chordnote->insertItem( tr( "B" ) );
132 chordnote->setGeometry( QRect( 0, 0, 40, 21 ) ); 136 chordnote->setGeometry( QRect( 0, 0, 40, 21 ) );
133 chordnote->setCurrentItem( 9 ); 137 chordnote->setCurrentItem( 9 );
134 138
135 QWidget* privateLayoutWidget = new QWidget( tab, "Layout1" ); 139 QWidget* privateLayoutWidget = new QWidget( tab, "Layout1" );
136 privateLayoutWidget->setGeometry( QRect( 5, 232, 160, 20 ) ); 140 privateLayoutWidget->setGeometry( QRect( 5, 232, 160, 20 ) );
137 Layout1 = new QHBoxLayout( privateLayoutWidget ); 141 Layout1 = new QHBoxLayout( privateLayoutWidget );
138 Layout1->setSpacing( 6 ); 142 Layout1->setSpacing( 6 );
139 Layout1->setMargin( 0 ); 143 Layout1->setMargin( 0 );
140 144
141 s1_1 = new QLabel( privateLayoutWidget, "s1_1" ); 145 s1_1 = new QLabel( privateLayoutWidget, "s1_1" );
142 s1_1->setText( tr( "E" ) ); 146 s1_1->setText( tr( "E" ) );
143 s1_1->setAlignment( int( QLabel::AlignCenter ) ); 147 s1_1->setAlignment( int( QLabel::AlignCenter ) );
144 Layout1->addWidget( s1_1 ); 148 Layout1->addWidget( s1_1 );
145 149
146 s1_2 = new QLabel( privateLayoutWidget, "s1_2" ); 150 s1_2 = new QLabel( privateLayoutWidget, "s1_2" );
147 s1_2->setText( tr( "A" ) ); 151 s1_2->setText( tr( "A" ) );
148 s1_2->setAlignment( int( QLabel::AlignCenter ) ); 152 s1_2->setAlignment( int( QLabel::AlignCenter ) );
149 Layout1->addWidget( s1_2 ); 153 Layout1->addWidget( s1_2 );
150 154
151 s1_3 = new QLabel( privateLayoutWidget, "s1_3" ); 155 s1_3 = new QLabel( privateLayoutWidget, "s1_3" );
152 s1_3->setText( tr( "E" ) ); 156 s1_3->setText( tr( "E" ) );
153 s1_3->setAlignment( int( QLabel::AlignCenter ) ); 157 s1_3->setAlignment( int( QLabel::AlignCenter ) );
154 Layout1->addWidget( s1_3 ); 158 Layout1->addWidget( s1_3 );
155 159
156 s1_4 = new QLabel( privateLayoutWidget, "s1_4" ); 160 s1_4 = new QLabel( privateLayoutWidget, "s1_4" );
157 s1_4->setText( tr( "A" ) ); 161 s1_4->setText( tr( "A" ) );
158 s1_4->setAlignment( int( QLabel::AlignCenter ) ); 162 s1_4->setAlignment( int( QLabel::AlignCenter ) );
159 Layout1->addWidget( s1_4 ); 163 Layout1->addWidget( s1_4 );
160 164
161 s1_5 = new QLabel( privateLayoutWidget, "s1_5" ); 165 s1_5 = new QLabel( privateLayoutWidget, "s1_5" );
162 s1_5->setText( tr( "C#" ) ); 166 s1_5->setText( tr( "C#" ) );
163 s1_5->setAlignment( int( QLabel::AlignCenter ) ); 167 s1_5->setAlignment( int( QLabel::AlignCenter ) );
164 Layout1->addWidget( s1_5 ); 168 Layout1->addWidget( s1_5 );
165 169
166 s1_6 = new QLabel( privateLayoutWidget, "s1_6" ); 170 s1_6 = new QLabel( privateLayoutWidget, "s1_6" );
167 s1_6->setText( tr( "E" ) ); 171 s1_6->setText( tr( "E" ) );
168 s1_6->setAlignment( int( QLabel::AlignCenter ) ); 172 s1_6->setAlignment( int( QLabel::AlignCenter ) );
169 Layout1->addWidget( s1_6 ); 173 Layout1->addWidget( s1_6 );
170 174
171 // sound_label = new QLabel( tab, "sound_label" ); 175 // sound_label = new QLabel( tab, "sound_label" );
172 // sound_label->setGeometry( QRect( 185, 160, 32, 17 ) ); 176 // sound_label->setGeometry( QRect( 185, 160, 32, 17 ) );
173 // sound_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, sound_label->sizePolicy().hasHeightForWidth() ) ); 177 // sound_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, sound_label->sizePolicy().hasHeightForWidth() ) );
174 // sound_label->setPixmap( image0 ); 178 // sound_label->setPixmap( image0 );
175 // sound_label->pixmap()->setMask(*image0.mask()); 179 // sound_label->pixmap()->setMask(*image0.mask());
176 // sound_label->setScaledContents( TRUE ); 180 // sound_label->setScaledContents( TRUE );
177 // sound_label->setBackgroundMode( QWidget::PaletteButton ); 181 // sound_label->setBackgroundMode( QWidget::PaletteButton );
178 // sound_label->setBackgroundColor(this->backgroundColor()); 182 // sound_label->setBackgroundColor(this->backgroundColor());
179 // sound_label->setPalette( QPalette( QColor( 232, 227, 215) ) ); 183 // sound_label->setPalette( QPalette( QColor( 232, 227, 215) ) );
180 184
181 185
182 Frame6 = new QFrame( tab, "Frame6" ); 186 Frame6 = new QFrame( tab, "Frame6" );
183 Frame6->setGeometry( QRect( 170, 145, 66, 10 ) ); 187 Frame6->setGeometry( QRect( 170, 145, 66, 10 ) );
184 Frame6->setFrameShape( QFrame::HLine ); 188 Frame6->setFrameShape( QFrame::HLine );
185 Frame6->setFrameShadow( QFrame::Raised ); 189 Frame6->setFrameShadow( QFrame::Raised );
186 190
187 chordshow_label = new QLabel( tab, "chordshow_label" ); 191 chordshow_label = new QLabel( tab, "chordshow_label" );
188 chordshow_label->setGeometry( QRect( 185, 60, 32, 17 ) ); 192 chordshow_label->setGeometry( QRect( 185, 60, 32, 17 ) );
189 // chordshow_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, chordshow_label->sizePolicy().hasHeightForWidth() ) ); 193 // chordshow_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, chordshow_label->sizePolicy().hasHeightForWidth() ) );
190 chordshow_label->setFrameShape( QLabel::NoFrame ); 194 chordshow_label->setFrameShape( QLabel::NoFrame );
191 chordshow_label->setPixmap( image1 ); 195 chordshow_label->setPixmap( image1 );
192 chordshow_label->setScaledContents( TRUE ); 196 chordshow_label->setScaledContents( TRUE );
193 // chordshow_label->setBackgroundMode( QWidget::PaletteButton ); 197 // chordshow_label->setBackgroundMode( QWidget::PaletteButton );
194 198
195 transport_rec = new QPushButton( tab, "transport_rec" ); 199 transport_rec = new QPushButton( tab, "transport_rec" );
196 transport_rec->setGeometry( QRect( 170, 80, 30, 30 ) ); 200 transport_rec->setGeometry( QRect( 170, 80, 30, 30 ) );
197 transport_rec->setText( tr( "" ) ); 201 transport_rec->setText( tr( "" ) );
198 transport_rec->setPixmap( image2 ); 202 transport_rec->setPixmap( image2 );
199 203
200 play_sound = new QPushButton( tab, "play_sound" ); 204 play_sound = new QPushButton( tab, "play_sound" );
201 play_sound->setGeometry( QRect( 170, 180, 60, 55 ) ); 205 play_sound->setGeometry( QRect( 170, 180, 60, 55 ) );
202 play_sound->setText( tr( "" ) ); 206 play_sound->setText( tr( "" ) );
203 play_sound->setPixmap( image3 ); 207 play_sound->setPixmap( image3 );
204 208
205 Frame6_2 = new QFrame( tab, "Frame6_2" ); 209 Frame6_2 = new QFrame( tab, "Frame6_2" );
206 Frame6_2->setGeometry( QRect( 170, 45, 66, 10 ) ); 210 Frame6_2->setGeometry( QRect( 170, 45, 66, 10 ) );
207 Frame6_2->setFrameShape( QFrame::HLine ); 211 Frame6_2->setFrameShape( QFrame::HLine );
208 Frame6_2->setFrameShadow( QFrame::Raised ); 212 Frame6_2->setFrameShadow( QFrame::Raised );
209 213
210 transport_play = new QPushButton( tab, "transport_play" ); 214 transport_play = new QPushButton( tab, "transport_play" );
211 transport_play->setEnabled( FALSE ); 215 transport_play->setEnabled( FALSE );
212 transport_play->setGeometry( QRect( 200, 80, 30, 30 ) ); 216 transport_play->setGeometry( QRect( 200, 80, 30, 30 ) );
213 transport_play->setText( tr( "" ) ); 217 transport_play->setText( tr( "" ) );
214 transport_play->setPixmap( image3 ); 218 transport_play->setPixmap( image3 );
215 219
216 transport_rew = new QPushButton( tab, "transport_rew" ); 220 transport_rew = new QPushButton( tab, "transport_rew" );
217 transport_rew->setEnabled( FALSE ); 221 transport_rew->setEnabled( FALSE );
218 transport_rew->setGeometry( QRect( 170, 110, 30, 30 ) ); 222 transport_rew->setGeometry( QRect( 170, 110, 30, 30 ) );
219 transport_rew->setText( tr( "" ) ); 223 transport_rew->setText( tr( "" ) );
220 transport_rew->setPixmap( image4 ); 224 transport_rew->setPixmap( image4 );
221 225
222 transport_fwd = new QPushButton( tab, "transport_fwd" ); 226 transport_fwd = new QPushButton( tab, "transport_fwd" );
223 transport_fwd->setEnabled( FALSE ); 227 transport_fwd->setEnabled( FALSE );
224 transport_fwd->setGeometry( QRect( 200, 110, 30, 30 ) ); 228 transport_fwd->setGeometry( QRect( 200, 110, 30, 30 ) );
225 transport_fwd->setText( tr( "" ) ); 229 transport_fwd->setText( tr( "" ) );
226 transport_fwd->setPixmap( image5 ); 230 transport_fwd->setPixmap( image5 );
227 231
228 chordname = new QLabel( tab, "chordname" ); 232 chordname = new QLabel( tab, "chordname" );
229 chordname->setGeometry( QRect( 146, 0, 90, 20 ) ); //cxm moved l 5 233 chordname->setGeometry( QRect( 146, 0, 90, 20 ) ); //cxm moved l 5
230 chordname->setText( tr( "A" ) ); 234 chordname->setText( tr( "A" ) );
231 chordname->setAlignment( int( QLabel::AlignCenter ) ); 235 chordname->setAlignment( int( QLabel::AlignCenter ) );
232 QToolTip::add( chordname, tr( "" ) ); 236 QToolTip::add( chordname, tr( "" ) );
233 237
234 synth = new gs(); 238 synth = new gs();
235 tuner = new gt(); 239 tuner = new gt();
236 frets = new FretBoard( tab, "frets" ); 240 frets = new FretBoard( tab, "frets" );
237 frets->setGeometry( QRect( 0, 20, 168, 210 ) ); 241 frets->setGeometry( QRect( 0, 20, 168, 210 ) );
238 tabs->insertTab( tab, tr( "Guitar" ) ); 242 tabs->insertTab( tab, tr( "Guitar" ) );
239 243
240 tab_2 = new QWidget( tabs, "tab_2" ); 244 tab_2 = new QWidget( tabs, "tab_2" );
241 245
242 optlab2 = new QLabel( tab_2, "optlab2" ); 246 optlab2 = new QLabel( tab_2, "optlab2" );
243 optlab2->setGeometry( QRect( 9, 58, 120, 41 ) ); 247 optlab2->setGeometry( QRect( 9, 58, 120, 41 ) );
244 optlab2->setText( tr( "Alternative tunings are possible" ) ); 248 optlab2->setText( tr( "Alternative tunings are possible" ) );
245 optlab2->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignLeft ) ); 249 optlab2->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignLeft ) );
246 250
247 span = new QComboBox( FALSE, tab_2, "span" ); 251 span = new QComboBox( FALSE, tab_2, "span" );
248 span->insertItem( tr( "2" ) ); 252 span->insertItem( tr( "2" ) );
249 span->insertItem( tr( "3" ) ); 253 span->insertItem( tr( "3" ) );
250 span->insertItem( tr( "4" ) ); 254 span->insertItem( tr( "4" ) );
251 span->insertItem( tr( "5" ) ); 255 span->insertItem( tr( "5" ) );
252 span->insertItem( tr( "6" ) ); 256 span->insertItem( tr( "6" ) );
253 span->setGeometry( QRect( 180, 20, 50, 21 ) ); 257 span->setGeometry( QRect( 180, 20, 50, 21 ) );
254 span->setCurrentItem( 1 ); 258 span->setCurrentItem( 1 );
255 259
256 TextLabel1 = new QLabel( tab_2, "TextLabel1" ); 260 TextLabel1 = new QLabel( tab_2, "TextLabel1" );
257 TextLabel1->setGeometry( QRect( 3, 109, 226, 140 ) ); 261 TextLabel1->setGeometry( QRect( 3, 109, 226, 140 ) );
258 TextLabel1->setText( tr( QString::fromUtf8( "©2002 Camilo Mesias\n" 262 TextLabel1->setText( tr( QString::fromUtf8( "©2002 Camilo Mesias\n"
259"camilo@mesias.co.uk\n" 263"camilo@mesias.co.uk\n"
260"Version 0.0.7 beta" ) ) ); 264"Version 0.0.7 beta" ) ) );
261 TextLabel1->setAlignment( int( QLabel::AlignBottom | QLabel::AlignLeft ) ); 265 TextLabel1->setAlignment( int( QLabel::AlignBottom | QLabel::AlignLeft ) );
262 266
263 tuning = new QComboBox( FALSE, tab_2, "tuning" ); 267 tuning = new QComboBox( FALSE, tab_2, "tuning" );
264 tuning->insertItem( tr( "EADGBE" ) ); 268 tuning->insertItem( tr( "EADGBE" ) );
265 tuning->insertItem( tr( "EBEG#BE" ) ); 269 tuning->insertItem( tr( "EBEG#BE" ) );
266 tuning->insertItem( tr( "EAEAC#E" ) ); 270 tuning->insertItem( tr( "EAEAC#E" ) );
267 tuning->insertItem( tr( "EADF#BE" ) ); 271 tuning->insertItem( tr( "EADF#BE" ) );
268 tuning->insertItem( tr( "EADGCF" ) ); 272 tuning->insertItem( tr( "EADGCF" ) );
269 tuning->insertItem( tr( "DADGAD" ) ); 273 tuning->insertItem( tr( "DADGAD" ) );
270 tuning->insertItem( tr( "DGCGCD" ) ); 274 tuning->insertItem( tr( "DGCGCD" ) );
271 tuning->insertItem( tr( "DADF#AD" ) ); 275 tuning->insertItem( tr( "DADF#AD" ) );
272 tuning->insertItem( tr( "DADGBE" ) ); 276 tuning->insertItem( tr( "DADGBE" ) );
273 tuning->insertItem( tr( "DGDGBD" ) ); 277 tuning->insertItem( tr( "DGDGBD" ) );
274 tuning->insertItem( tr( "DADACD" ) ); 278 tuning->insertItem( tr( "DADACD" ) );
275 tuning->insertItem( tr( "CGCGAE" ) ); 279 tuning->insertItem( tr( "CGCGAE" ) );
276 tuning->insertItem( tr( "FADGBE" ) ); 280 tuning->insertItem( tr( "FADGBE" ) );
277 tuning->insertItem( tr( "G minor" ) ); 281 tuning->insertItem( tr( "G minor" ) );
278 tuning->setGeometry( QRect( 140, 70, 91, 21 ) ); 282 tuning->setGeometry( QRect( 140, 70, 91, 21 ) );
279 283
280 optlab1 = new QLabel( tab_2, "optlab1" ); 284 optlab1 = new QLabel( tab_2, "optlab1" );
281 optlab1->setGeometry( QRect( 8, 8, 160, 40 ) ); 285 optlab1->setGeometry( QRect( 8, 8, 160, 40 ) );
282 optlab1->setText( tr( "Span: the greatest number of frets over which you want chords to be generated" ) ); 286 optlab1->setText( tr( "Span: the greatest number of frets over which you want chords to be generated" ) );
283 optlab1->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignLeft ) ); 287 optlab1->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignLeft ) );
284 tabs->insertTab( tab_2, tr( "Options" ) ); 288 tabs->insertTab( tab_2, tr( "Options" ) );
285 289
286 Tuner = new QWidget( tabs, "Tuner" ); 290 Tuner = new QWidget( tabs, "Tuner" );
287 291
288 Frame4 = new QFrame( Tuner, "Frame4" ); 292 Frame4 = new QFrame( Tuner, "Frame4" );
289 Frame4->setGeometry( QRect( 0, 0, 230, 126 ) ); 293 Frame4->setGeometry( QRect( 0, 0, 230, 126 ) );
290 Frame4->setFrameShape( QFrame::Box ); 294 Frame4->setFrameShape( QFrame::Box );
291 Frame4->setFrameShadow( QFrame::Raised ); 295 Frame4->setFrameShadow( QFrame::Raised );
292 296
293 vu = new VUMeter( Frame4, "vu" ); 297 vu = new VUMeter( Frame4, "vu" );
294 vu->setGeometry( QRect( 5, 5, 220, 115 ) ); 298 vu->setGeometry( QRect( 5, 5, 220, 115 ) );
295 299
296 tuner_note = new QComboBox( FALSE, Tuner, "tuner_note" ); 300 tuner_note = new QComboBox( FALSE, Tuner, "tuner_note" );
297 tuner_note->insertItem( tr( "auto" ) ); 301 tuner_note->insertItem( tr( "auto" ) );
298 tuner_note->insertItem( tr( "E" ) ); 302 tuner_note->insertItem( tr( "E" ) );
299 tuner_note->insertItem( tr( "D" ) ); 303 tuner_note->insertItem( tr( "D" ) );
300 tuner_note->insertItem( tr( "G" ) ); 304 tuner_note->insertItem( tr( "G" ) );
301 tuner_note->insertItem( tr( "A" ) ); 305 tuner_note->insertItem( tr( "A" ) );
302 tuner_note->insertItem( tr( "B" ) ); 306 tuner_note->insertItem( tr( "B" ) );
303 tuner_note->insertItem( tr( "C" ) ); 307 tuner_note->insertItem( tr( "C" ) );
304 tuner_note->insertItem( tr( "F" ) ); 308 tuner_note->insertItem( tr( "F" ) );
305 tuner_note->setGeometry( QRect( 5, 160, 90, 20 ) ); 309 tuner_note->setGeometry( QRect( 5, 160, 90, 20 ) );
306 310
307 Frame8 = new QFrame( Tuner, "Frame8" ); 311 Frame8 = new QFrame( Tuner, "Frame8" );
308 Frame8->setGeometry( QRect( -2, 188, 231, 10 ) ); 312 Frame8->setGeometry( QRect( -2, 188, 231, 10 ) );
309 Frame8->setFrameShape( QFrame::HLine ); 313 Frame8->setFrameShape( QFrame::HLine );
310 Frame8->setFrameShadow( QFrame::Raised ); 314 Frame8->setFrameShadow( QFrame::Raised );
311 315
312 tuner_start = new QPushButton( Tuner, "tuner_start" ); 316 tuner_start = new QPushButton( Tuner, "tuner_start" );
313 tuner_start->setGeometry( QRect( 100, 155, 91, 30 ) ); 317 tuner_start->setGeometry( QRect( 100, 155, 91, 30 ) );
314 tuner_start->setText( tr( "Start" ) ); 318 tuner_start->setText( tr( "Start" ) );
315 319
316 tuner_lab1 = new QLabel( Tuner, "tuner_lab1" ); 320 tuner_lab1 = new QLabel( Tuner, "tuner_lab1" );
317 tuner_lab1->setGeometry( QRect( 10, 130, 100, 21 ) ); 321 tuner_lab1->setGeometry( QRect( 10, 130, 100, 21 ) );
318 tuner_lab1->setText( tr( "Tuner operation" ) ); 322 tuner_lab1->setText( tr( "Tuner operation" ) );
319 323
320 tuner_lab2 = new QLabel( Tuner, "tuner_lab2" ); 324 tuner_lab2 = new QLabel( Tuner, "tuner_lab2" );
321 tuner_lab2->setGeometry( QRect( 10, 200, 100, 16 ) ); 325 tuner_lab2->setGeometry( QRect( 10, 200, 100, 16 ) );
322 tuner_lab2->setText( tr( "Pitch calibration" ) ); 326 tuner_lab2->setText( tr( "Pitch calibration" ) );
323 327
324 tuner_calib_note = new QComboBox( FALSE, Tuner, "tuner_calib_note" ); 328 tuner_calib_note = new QComboBox( FALSE, Tuner, "tuner_calib_note" );
325 tuner_calib_note->insertItem( tr( "A" ) ); 329 tuner_calib_note->insertItem( tr( "A" ) );
326 tuner_calib_note->insertItem( tr( "C" ) ); 330 tuner_calib_note->insertItem( tr( "C" ) );
327 tuner_calib_note->setGeometry( QRect( 5, 225, 90, 21 ) ); 331 tuner_calib_note->setGeometry( QRect( 5, 225, 90, 21 ) );
328 332
329 tuner_calib_freq = new QSpinBox( Tuner, "tuner_calib_freq" ); 333 tuner_calib_freq = new QSpinBox( Tuner, "tuner_calib_freq" );
330 tuner_calib_freq->setGeometry( QRect( 105, 225, 71, 21 ) ); 334 tuner_calib_freq->setGeometry( QRect( 105, 225, 71, 21 ) );
331 tuner_calib_freq->setSuffix( tr( "Hz" ) ); 335 tuner_calib_freq->setSuffix( tr( "Hz" ) );
332 tuner_calib_freq->setWrapping( TRUE ); 336 tuner_calib_freq->setWrapping( TRUE );
333 tuner_calib_freq->setMaxValue( 500 ); 337 tuner_calib_freq->setMaxValue( 500 );
334 tuner_calib_freq->setMinValue( 300 ); 338 tuner_calib_freq->setMinValue( 300 );
335 tuner_calib_freq->setValue( 440 ); 339 tuner_calib_freq->setValue( 440 );
336 340
337 tuner_lab3 = new QLabel( Tuner, "tuner_lab3" ); 341 tuner_lab3 = new QLabel( Tuner, "tuner_lab3" );
338 tuner_lab3->setGeometry( QRect( 185, 225, 40, 21 ) ); 342 tuner_lab3->setGeometry( QRect( 185, 225, 40, 21 ) );
339 tuner_lab3->setText( tr( "Pitch" ) ); 343 tuner_lab3->setText( tr( "Pitch" ) );
340 344
341 tuner_pic1 = new QLabel( Tuner, "tuner_pic1" ); 345 tuner_pic1 = new QLabel( Tuner, "tuner_pic1" );
342 tuner_pic1->setGeometry( QRect( 195, 155, 31, 31 ) ); 346 tuner_pic1->setGeometry( QRect( 195, 155, 31, 31 ) );
343 tuner_pic1->setFrameShape( QLabel::NoFrame ); 347 tuner_pic1->setFrameShape( QLabel::NoFrame );
344 tuner_pic1->setPixmap( image6 ); 348 tuner_pic1->setPixmap( image6 );
345 tuner_pic1->setScaledContents( TRUE ); 349 tuner_pic1->setScaledContents( TRUE );
346 tabs->insertTab( Tuner, tr( "Tuner" ) ); 350 tabs->insertTab( Tuner, tr( "Tuner" ) );
347 351
348 tab_3 = new QWidget( tabs, "tab_3" ); 352 tab_3 = new QWidget( tabs, "tab_3" );
349 353
350 chordlistlab1 = new QLabel( tab_3, "chordlistlab1" ); 354 chordlistlab1 = new QLabel( tab_3, "chordlistlab1" );
351 chordlistlab1->setGeometry( QRect( 5, 5, 216, 16 ) ); 355 chordlistlab1->setGeometry( QRect( 5, 5, 216, 16 ) );
352 chordlistlab1->setText( tr( "Chord list" ) ); 356 chordlistlab1->setText( tr( "Chord list" ) );
353 357
354 chordlist = new QListBox( tab_3, "chordlist" ); 358 chordlist = new QListBox( tab_3, "chordlist" );
355 chordlist->setGeometry( QRect( 5, 25, 220, 200 ) ); 359 chordlist->setGeometry( QRect( 5, 25, 220, 200 ) );
356 360
357 list_remove_btn = new QPushButton( tab_3, "list_remove_btn" ); 361 list_remove_btn = new QPushButton( tab_3, "list_remove_btn" );
358 list_remove_btn->setGeometry( QRect( 150, 230, 71, 25 ) ); 362 list_remove_btn->setGeometry( QRect( 150, 230, 71, 25 ) );
359 list_remove_btn->setText( tr( "Remove" ) ); 363 list_remove_btn->setText( tr( "Remove" ) );
360 tabs->insertTab( tab_3, tr( "Chords" ) ); 364 tabs->insertTab( tab_3, tr( "Chords" ) );
361 365
362 // hope this does what it's supposed to!! 366 // hope this does what it's supposed to!!
363 // setPalette( QPalette( QColor( 232, 227, 215) ) ); 367 // setPalette( QPalette( QColor( 232, 227, 215) ) );
364 368
365 // signals and slots connections 369 // signals and slots connections
366 370
367 //cxm 371 //cxm
368 connect( tuning, SIGNAL( activated(int) ), frets, SLOT( Tune(int) ) ); 372 connect( tuning, SIGNAL( activated(int) ), frets, SLOT( Tune(int) ) );
369 connect( span, SIGNAL( activated(int) ), frets, SLOT( Span(int) ) ); 373 connect( span, SIGNAL( activated(int) ), frets, SLOT( Span(int) ) );
370 connect( transport_rec, SIGNAL( clicked() ), this, SLOT( transport_rec_cb() )); 374 connect( transport_rec, SIGNAL( clicked() ), this, SLOT( transport_rec_cb() ));
371 connect( play_sound, SIGNAL( clicked() ), this, SLOT( play_chord_cb() )); 375 connect( play_sound, SIGNAL( clicked() ), this, SLOT( play_chord_cb() ));
372 connect( tuner_start, SIGNAL( clicked() ), this, SLOT( tuner_start_cb() )); 376 connect( tuner_start, SIGNAL( clicked() ), this, SLOT( tuner_start_cb() ));
373 connect( tuner_note, SIGNAL( textChanged(const QString&) ), vu, SLOT( AnnotL(const QString&) )); 377 connect( tuner_note, SIGNAL( textChanged(const QString&) ), vu, SLOT( AnnotL(const QString&) ));
374 connect( this, SIGNAL( frequency_change(int) ), vu, SLOT( Value(int) )); 378 connect( this, SIGNAL( frequency_change(int) ), vu, SLOT( Value(int) ));
375 379
376 connect( chordnote, SIGNAL( activated(int) ), frets, SLOT( Base(int) ) ); 380 connect( chordnote, SIGNAL( activated(int) ), frets, SLOT( Base(int) ) );
377 connect( chordkey, SIGNAL( activated(int) ), frets, SLOT( Chord(int) ) ); 381 connect( chordkey, SIGNAL( activated(int) ), frets, SLOT( Chord(int) ) );
378 connect( chordfret, SIGNAL( activated(int) ), frets, SLOT( Fret(int) ) ); 382 connect( chordfret, SIGNAL( activated(int) ), frets, SLOT( Fret(int) ) );
379 connect( list_remove_btn, SIGNAL( clicked() ), this, SLOT( list_remove_cb() ) ); 383 connect( list_remove_btn, SIGNAL( clicked() ), this, SLOT( list_remove_cb() ) );
380 connect( frets, SIGNAL( s1nameChanged(const QString&) ), s1_1, SLOT( setText(const QString&) ) ); 384 connect( frets, SIGNAL( s1nameChanged(const QString&) ), s1_1, SLOT( setText(const QString&) ) );
381 connect( frets, SIGNAL( s2nameChanged(const QString&) ), s1_2, SLOT( setText(const QString&) ) ); 385 connect( frets, SIGNAL( s2nameChanged(const QString&) ), s1_2, SLOT( setText(const QString&) ) );
382 connect( frets, SIGNAL( s3nameChanged(const QString&) ), s1_3, SLOT( setText(const QString&) ) ); 386 connect( frets, SIGNAL( s3nameChanged(const QString&) ), s1_3, SLOT( setText(const QString&) ) );
383 connect( frets, SIGNAL( s4nameChanged(const QString&) ), s1_4, SLOT( setText(const QString&) ) ); 387 connect( frets, SIGNAL( s4nameChanged(const QString&) ), s1_4, SLOT( setText(const QString&) ) );
384 connect( frets, SIGNAL( s5nameChanged(const QString&) ), s1_5, SLOT( setText(const QString&) ) ); 388 connect( frets, SIGNAL( s5nameChanged(const QString&) ), s1_5, SLOT( setText(const QString&) ) );
385 connect( frets, SIGNAL( s6nameChanged(const QString&) ), s1_6, SLOT( setText(const QString&) ) ); 389 connect( frets, SIGNAL( s6nameChanged(const QString&) ), s1_6, SLOT( setText(const QString&) ) );
386 connect( frets, SIGNAL( nameChanged(const QString&) ), chordname, SLOT( setText(const QString&) ) ); 390 connect( frets, SIGNAL( nameChanged(const QString&) ), chordname, SLOT( setText(const QString&) ) );
387} 391}
388 392
389 393
390static int known=0; 394static int known=0;
391#include <qmessagebox.h> 395#include <qmessagebox.h>
392void PowerchordBase::transport_rec_cb(){ 396void PowerchordBase::transport_rec_cb(){
393 chordlist->insertItem(chordname->text(),-1); 397 chordlist->insertItem(chordname->text(),-1);
394 if (!known){ 398 if (!known){
395 QMessageBox::information(this, "Powerchord", "This chord has been saved\ninto the list of chords,\nfor later playback."); 399 QMessageBox::information(this, "Powerchord", "This chord has been saved\ninto the list of chords,\nfor later playback.");
396 known = 1; 400 known = 1;
397 } 401 }
398} 402}
399void PowerchordBase::list_remove_cb(){ 403void PowerchordBase::list_remove_cb(){
400 if (chordlist->count() > 0){ 404 if (chordlist->count() > 0){
401 chordlist->removeItem(0); 405 chordlist->removeItem(0);
402 } 406 }
403} 407}
404void PowerchordBase::play_chord_cb(){ 408void PowerchordBase::play_chord_cb(){
405 // QMessageBox::information(this, "Coming soon!", "This button plays\nthe chord by synthesizing\nthe sound of the notes."); 409 // QMessageBox::information(this, "Coming soon!", "This button plays\nthe chord by synthesizing\nthe sound of the notes.");
406 410
407 411
408 if (audio_timer){ 412 if (audio_timer){
409 audio_timer->stop(); 413 audio_timer->stop();
410 // set pixmap? 414 // set pixmap?
411 synth->Stop(); 415 synth->Stop();
412 delete(audio_timer); 416 delete(audio_timer);
413 audio_timer = 0; 417 audio_timer = 0;
414 }else{ 418 }else{
415 // get notes from chord engine 419 // get notes from chord engine
416 420
417 int note; 421 int note;
418 int base; 422 int base;
419 int octave; 423 int octave;
420 note = frets->ce.noteindex(0); 424 note = frets->ce.noteindex(0);
421 if (note >= 0){ 425 if (note >= 0){
422 //fprintf(stderr, "Note was %d\n", note); 426 //fprintf(stderr, "Note was %d\n", note);
423 base = note % 12; 427 base = note % 12;
424 octave = note / 12; 428 octave = note / 12;
425 synth->note_start(0, base, octave); 429 synth->note_start(0, base, octave);
426 }else{ 430 }else{
427 // subtle bug here - replay second note if 1st one muted 431 // subtle bug here - replay second note if 1st one muted
428 note = frets->ce.noteindex(1); 432 note = frets->ce.noteindex(1);
429 base = note % 12; 433 base = note % 12;
430 octave = note / 12; 434 octave = note / 12;
431 synth->note_start(1, base, octave); 435 synth->note_start(1, base, octave);
432 436
433 } 437 }
434 438
435 // init synth 439 // init synth
436 if (synth->Play()){ 440 if (synth->Play()){
437 // error 441 // error
438 QMessageBox::information(this, "Powerchord", "Unable to open device for sound playback - check that no other application is using it."); 442 QMessageBox::information(this, "Powerchord", "Unable to open device for sound playback - check that no other application is using it.");
439 return; 443 return;
440 } 444 }
441 synth->fill_buffer(); 445 synth->fill_buffer();
442 446
443 // start timer 447 // start timer
444 audio_timer = new QTimer(); 448 audio_timer = new QTimer();
445 connect(audio_timer, SIGNAL( timeout() ), this, SLOT( audio_cb() )); 449 connect(audio_timer, SIGNAL( timeout() ), this, SLOT( audio_cb() ));
446 // set pixmap on player? 450 // set pixmap on player?
447 audio_timer->start(19); // 19 msec (fudge factor!!) 451 audio_timer->start(19); // 19 msec (fudge factor!!)
448 } 452 }
449} 453}
450 454
451 455
452 456
453void PowerchordBase::audio_cb(){ 457void PowerchordBase::audio_cb(){
454 // play the next bit of audio until quiet 458 // play the next bit of audio until quiet
455 459
456 // strum timing 460 // strum timing
457#define INTERVAL 2 461#define INTERVAL 2
458 462
459 if ((synth->Frames() % INTERVAL) == 0){ 463 if ((synth->Frames() % INTERVAL) == 0){
460 int string = synth->Frames() / INTERVAL; 464 int string = synth->Frames() / INTERVAL;
461 if (string <= 5){ 465 if (string <= 5){
462 int note; 466 int note;
463 int base; 467 int base;
464 int octave; 468 int octave;
465 note = frets->ce.noteindex(string); 469 note = frets->ce.noteindex(string);
466 // check not muted... 470 // check not muted...
467 if (note > 0){ 471 if (note > 0){
468 base = note % 12; 472 base = note % 12;
469 octave = note / 12; 473 octave = note / 12;
470 synth->note_start(string, base, octave); 474 synth->note_start(string, base, octave);
471 } 475 }
472 } 476 }
473 } 477 }
474 478
475 if (synth->Playing()){ 479 if (synth->Playing()){
476 synth->write_buffer(); 480 synth->write_buffer();
477 synth->fill_buffer(); 481 synth->fill_buffer();
478 }else{ 482 }else{
479 audio_timer->stop(); 483 audio_timer->stop();
480 // set pixmap? 484 // set pixmap?
481 synth->Stop(); 485 synth->Stop();
482 delete(audio_timer); 486 delete(audio_timer);
483 audio_timer = 0; 487 audio_timer = 0;
484 } 488 }
485} 489}
486 490
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,1240 +1,1242 @@
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
142void InfoDialog::displayInfo(const QString &caption, const QStringList text, QWidget *parent) 144void InfoDialog::displayInfo(const QString &caption, const QStringList text, QWidget *parent)
143{ 145{
144 InfoDialog *dlg=new InfoDialog(caption,text,parent); 146 InfoDialog *dlg=new InfoDialog(caption,text,parent);
145 dlg->exec(); 147 dlg->exec();
146 delete dlg; 148 delete dlg;
147} 149}
148 150
149//=========================================================================== 151//===========================================================================
150 152
151 153
152ImagePane::ImagePane( QWidget *parent ) : QWidget( parent ) 154ImagePane::ImagePane( QWidget *parent ) : QWidget( parent )
153{ 155{
154 vb = new QVBoxLayout( this ); 156 vb = new QVBoxLayout( this );
155 157
156 image = new QScrollView(this,0,WResizeNoErase|WNorthWestGravity); 158 image = new QScrollView(this,0,WResizeNoErase|WNorthWestGravity);
157 pic=new ImageWidget(image); 159 pic=new ImageWidget(image);
158 image->addChild(pic); 160 image->addChild(pic);
159 161
160 connect(pic, SIGNAL( clicked() ), this, SLOT( imageClicked() )); 162 connect(pic, SIGNAL( clicked() ), this, SLOT( imageClicked() ));
161 163
162 vb->addWidget( image ); 164 vb->addWidget( image );
163 165
164} 166}
165 167
166void ImagePane::setPixmap( const QPixmap &pm ) 168void ImagePane::setPixmap( const QPixmap &pm )
167{ 169{
168 pic->setPixmap( pm ); 170 pic->setPixmap( pm );
169 pic->resize(pm.width(),pm.height()); 171 pic->resize(pm.width(),pm.height());
170 image->updateScrollBars (); 172 image->updateScrollBars ();
171 pic->repaint(false); 173 pic->repaint(false);
172} 174}
173 175
174void ImagePane::imageClicked() 176void ImagePane::imageClicked()
175{ 177{
176 emit clicked(); 178 emit clicked();
177} 179}
178//=========================================================================== 180//===========================================================================
179/* 181/*
180 Draws the portion of the scaled pixmap that needs to be updated 182 Draws the portion of the scaled pixmap that needs to be updated
181*/ 183*/
182 184
183void ImageWidget::paintEvent( QPaintEvent *e ) 185void ImageWidget::paintEvent( QPaintEvent *e )
184{ 186{
185 QPainter painter(this); 187 QPainter painter(this);
186 188
187 painter.setClipRect(e->rect()); 189 painter.setClipRect(e->rect());
188 painter.fillRect(0,0,width(),height(),QColor(0,0,0)); 190 painter.fillRect(0,0,width(),height(),QColor(0,0,0));
189 191
190 if ( pixmap.size() != QSize( 0, 0 ) ) 192 if ( pixmap.size() != QSize( 0, 0 ) )
191 { // is an image loaded? 193 { // is an image loaded?
192 painter.drawPixmap((width() - pixmap.width()) / 2, (height() - pixmap.height()) / 2, pixmap); 194 painter.drawPixmap((width() - pixmap.width()) / 2, (height() - pixmap.height()) / 2, pixmap);
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 }
635 637
636 return ok; 638 return ok;
637} 639}
638 640
639bool ImageViewer::reconvertImage() 641bool ImageViewer::reconvertImage()
640{ 642{
641 bool success = FALSE; 643 bool success = FALSE;
642 644
643 if ( image.isNull() ) return FALSE; 645 if ( image.isNull() ) return FALSE;
644 646
645 QApplication::setOverrideCursor( waitCursor ); // this might take time 647 QApplication::setOverrideCursor( waitCursor ); // this might take time
646 if ( pm.convertFromImage(image /*, conversion_flags */ ) ) 648 if ( pm.convertFromImage(image /*, conversion_flags */ ) )
647 { 649 {
648 pmScaled = QPixmap(); 650 pmScaled = QPixmap();
649 scale(); 651 scale();
650 success = TRUE; // load successful 652 success = TRUE; // load successful
651 } 653 }
652 else 654 else
653 { 655 {
654 pm.resize(0,0); // couldn't load image 656 pm.resize(0,0); // couldn't load image
655 } 657 }
656 QApplication::restoreOverrideCursor(); // restore original cursor 658 QApplication::restoreOverrideCursor(); // restore original cursor
657 659
658 return success; // TRUE if loaded OK 660 return success; // TRUE if loaded OK
659} 661}
660 662
661 663
662int ImageViewer::calcHeight() 664int ImageViewer::calcHeight()
663{ 665{
664 if ( !isFullScreen ) 666 if ( !isFullScreen )
665 return imagePanel->paneHeight(); 667 return imagePanel->paneHeight();
666 else 668 else
667 return qApp->desktop()->height(); 669 return qApp->desktop()->height();
668} 670}
669/* 671/*
670 This functions scales the pixmap in the member variable "pm" to fit the 672 This functions scales the pixmap in the member variable "pm" to fit the
671 widget size and puts the resulting pixmap in the member variable "pmScaled". 673 widget size and puts the resulting pixmap in the member variable "pmScaled".
672*/ 674*/
673void ImageViewer::scale() 675void ImageViewer::scale()
674{ 676{
675 int h = calcHeight(); 677 int h = calcHeight();
676 if ( image.isNull() ) return; 678 if ( image.isNull() ) return;
677 679
678 QApplication::setOverrideCursor( waitCursor ); // this might take time 680 QApplication::setOverrideCursor( waitCursor ); // this might take time
679 if ( imagePanel->paneWidth() == pm.width() && h == pm.height() ) 681 if ( imagePanel->paneWidth() == pm.width() && h == pm.height() )
680 { // no need to scale if widget 682 { // no need to scale if widget
681 pmScaled = pm; // size equals pixmap size 683 pmScaled = pm; // size equals pixmap size
682 } 684 }
683 else 685 else
684 { 686 {
685 double hs = (double)h / (double)image.height(); 687 double hs = (double)h / (double)image.height();
686 double ws = (double)imagePanel->paneWidth() / (double)image.width(); 688 double ws = (double)imagePanel->paneWidth() / (double)image.width();
687 double scaleFactor = (hs > ws) ? ws : hs; 689 double scaleFactor = (hs > ws) ? ws : hs;
688 int smoothW = (int)(scaleFactor * image.width()); 690 int smoothW = (int)(scaleFactor * image.width());
689 int smoothH = (int)(scaleFactor * image.height()); 691 int smoothH = (int)(scaleFactor * image.height());
690 692
691 pmScaled.convertFromImage( image.smoothScale( smoothW, smoothH ) /*, conversion_flags */ ); 693 pmScaled.convertFromImage( image.smoothScale( smoothW, smoothH ) /*, conversion_flags */ );
692 } 694 }
693 QApplication::restoreOverrideCursor(); // restore original cursor 695 QApplication::restoreOverrideCursor(); // restore original cursor
694} 696}
695 697
696/* 698/*
697 The resize event handler, if a valid pixmap was loaded it will call 699 The resize event handler, if a valid pixmap was loaded it will call
698 scale() to fit the pixmap to the new widget size. 700 scale() to fit the pixmap to the new widget size.
699*/ 701*/
700 702
701void ImageViewer::resizeEvent( QResizeEvent * ) 703void ImageViewer::resizeEvent( QResizeEvent * )
702{ 704{
703 705
704 if ( pm.size() == QSize( 0, 0 ) ) // we couldn't load the image 706 if ( pm.size() == QSize( 0, 0 ) ) // we couldn't load the image
705 return; 707 return;
706 708
707 int h = calcHeight(); 709 int h = calcHeight();
708 710
709 if ( imagePanel->paneWidth() != pmScaled.width() || h != pmScaled.height() ) 711 if ( imagePanel->paneWidth() != pmScaled.width() || h != pmScaled.height() )
710 { // if new size, 712 { // if new size,
711 scale(); // scale pmScaled to window 713 scale(); // scale pmScaled to window
712 } 714 }
713 if ( image.hasAlphaBuffer() ) 715 if ( image.hasAlphaBuffer() )
714 erase(); 716 erase();
715} 717}
716 718
717 719
718void ImageViewer::hFlip() 720void ImageViewer::hFlip()
719{ 721{
720// matrix.scale( -1.0, 1.0 ); 722// matrix.scale( -1.0, 1.0 );
721 723
722 setImage(image.mirror(TRUE,FALSE)); 724 setImage(image.mirror(TRUE,FALSE));
723} 725}
724 726
725void ImageViewer::vFlip() 727void ImageViewer::vFlip()
726{ 728{
727// matrix.scale( 1.0, -1.0 ); 729// matrix.scale( 1.0, -1.0 );
728 setImage(image.mirror(FALSE,TRUE)); 730 setImage(image.mirror(FALSE,TRUE));
729} 731}
730 732
731void ImageViewer::rot180() 733void ImageViewer::rot180()
732{ 734{
733// matrix.rotate( 180.0 ); 735// matrix.rotate( 180.0 );
734 setImage(image.mirror(TRUE,TRUE)); 736 setImage(image.mirror(TRUE,TRUE));
735} 737}
736 738
737void ImageViewer::rot90() 739void ImageViewer::rot90()
738{ 740{
739 QImage oldimage; 741 QImage oldimage;
740 oldimage = image.convertDepth(32); 742 oldimage = image.convertDepth(32);
741// matrix.rotate( -90.0 ); 743// matrix.rotate( -90.0 );
742 setImage(rotate(oldimage,Rotate90)); 744 setImage(rotate(oldimage,Rotate90));
743 745
744} 746}
745void ImageViewer::rot270() 747void ImageViewer::rot270()
746{ 748{
747 749
748 QImage oldimage; 750 QImage oldimage;
749 oldimage = image.convertDepth(32); 751 oldimage = image.convertDepth(32);
750// matrix.rotate(90.0); 752// matrix.rotate(90.0);
751 setImage(rotate(oldimage,Rotate270)); 753 setImage(rotate(oldimage,Rotate270));
752 754
753} 755}
754 756
755void ImageViewer::blackAndWhite() 757void ImageViewer::blackAndWhite()
756{ 758{
757 759
758 viewMenuView->setItemEnabled(BLACKANDWHITE,false); 760 viewMenuView->setItemEnabled(BLACKANDWHITE,false);
759 setImage(toGray(image,false)); 761 setImage(toGray(image,false));
760} 762}
761 763
762void ImageViewer::displayControlsDialog() 764void ImageViewer::displayControlsDialog()
763{ 765{
764 int w=80; 766 int w=80;
765 int h=w; 767 int h=w;
766 QImage small; 768 QImage small;
767 769
768 if ( image.width()<w ||image.height()<h ) 770 if ( image.width()<w ||image.height()<h )
769 small=image.smoothScale(w,h); 771 small=image.smoothScale(w,h);
770 else 772 else
771 small=image.copy(0,0,w,h); 773 small=image.copy(0,0,w,h);
772 774
773 int newB=0; 775 int newB=0;
774 ControlsDialog *dlg=new ControlsDialog("Image Viewer",small,&newB,this); 776 ControlsDialog *dlg=new ControlsDialog("Image Viewer",small,&newB,this);
775 dlg->exec(); 777 dlg->exec();
776 if ( newB ) { 778 if ( newB ) {
777 intensity(image,(float)newB/100); 779 intensity(image,(float)newB/100);
778 setImage(image); 780 setImage(image);
779 } 781 }
780 782
781} 783}
782 784
783 785
784void ImageViewer::displayInfoDialog() 786void ImageViewer::displayInfoDialog()
785{ 787{
786 788
787 QStringList ls; 789 QStringList ls;
788 790
789 for ( int i=0;i<LAST;i++ ) 791 for ( int i=0;i<LAST;i++ )
790 ls.append(imageInfo[i]); 792 ls.append(imageInfo[i]);
791 793
792 InfoDialog::displayInfo("Image Viewer",ls,this); 794 InfoDialog::displayInfo("Image Viewer",ls,this);
793} 795}
794void ImageViewer::normalView() 796void ImageViewer::normalView()
795{ 797{
796 if ( !imagePanel->parentWidget() ) 798 if ( !imagePanel->parentWidget() )
797 { 799 {
798 800
799 isFullScreen = FALSE; 801 isFullScreen = FALSE;
800 stack->addWidget( imagePanel, 1 ); 802 stack->addWidget( imagePanel, 1 );
801 switchToImageView(); 803 switchToImageView();
802 if ( isSized ) 804 if ( isSized )
803 scale(); 805 scale();
804 806
805 updateImage(); 807 updateImage();
806 808
807 } 809 }
808} 810}
809 811
810void ImageViewer::stopSlideShow() { 812void ImageViewer::stopSlideShow() {
811 if (slideTimer->isActive()) 813 if (slideTimer->isActive())
812 slideTimer->stop(); 814 slideTimer->stop();
813} 815}
814 816
815void ImageViewer::fullScreen() 817void ImageViewer::fullScreen()
816{ 818{
817 // Full-screen option 819 // Full-screen option
818 // contributed by Robert Wittams <robert@wittams.com> 820 // contributed by Robert Wittams <robert@wittams.com>
819 if ( imagePanel->parentWidget() && loadSelected() ) 821 if ( imagePanel->parentWidget() && loadSelected() )
820 { 822 {
821 isFullScreen = TRUE; 823 isFullScreen = TRUE;
822 imagePanel->reparent(0,QPoint(0,0)); 824 imagePanel->reparent(0,QPoint(0,0));
823 imagePanel->resize(qApp->desktop()->width(), qApp->desktop()->height()); 825 imagePanel->resize(qApp->desktop()->width(), qApp->desktop()->height());
824 826
825 if ( isSized ) 827 if ( isSized )
826 scale(); 828 scale();
827 updateImage(); 829 updateImage();
828 imagePanel->showFullScreen(); 830 imagePanel->showFullScreen();
829 } 831 }
830} 832}
831 833
832void ImageViewer::setImage(const QImage& newimage) 834void ImageViewer::setImage(const QImage& newimage)
833{ 835{
834 image = newimage; 836 image = newimage;
835 reconvertImage(); 837 reconvertImage();
836 updateImage(); 838 updateImage();
837} 839}
838 840
839void ImageViewer::updateImageInfo(QString &filePath) 841void ImageViewer::updateImageInfo(QString &filePath)
840{ 842{
841 843
842 for ( int i=0;i<LAST;i++ ) 844 for ( int i=0;i<LAST;i++ )
843 { 845 {
844 imageInfo[i]=""; 846 imageInfo[i]="";
845 } 847 }
846 848
847 imageInfo[FORMAT]=QImage::imageFormat (filePath ); 849 imageInfo[FORMAT]=QImage::imageFormat (filePath );
848 QFileInfo fi(filePath); 850 QFileInfo fi(filePath);
849 imageInfo[PATH]=fi.fileName(); 851 imageInfo[PATH]=fi.fileName();
850 imageInfo[FILE_SIZE]=QString::number(fi.size())+" (bytes)"; 852 imageInfo[FILE_SIZE]=QString::number(fi.size())+" (bytes)";
851 QString message("%1x%2"); 853 QString message("%1x%2");
852 imageInfo[SIZE]=QString("%1x%2"); 854 imageInfo[SIZE]=QString("%1x%2");
853 imageInfo[SIZE]=imageInfo[SIZE].arg(image.width()).arg(image.height()); 855 imageInfo[SIZE]=imageInfo[SIZE].arg(image.width()).arg(image.height());
854 if ( image.numColors() > 0 ) 856 if ( image.numColors() > 0 )
855 { 857 {
856 imageInfo[COLORS]=tr("%1 colors").arg(image.numColors()); 858 imageInfo[COLORS]=tr("%1 colors").arg(image.numColors());
857 } 859 }
858 else if ( image.depth() >= 16 ) 860 else if ( image.depth() >= 16 )
859 { 861 {
860 imageInfo[COLORS]=tr(" True color"); 862 imageInfo[COLORS]=tr(" True color");
861 } 863 }
862 if ( image.hasAlphaBuffer() ) 864 if ( image.hasAlphaBuffer() )
863 { 865 {
864 if ( image.depth() == 8 ) 866 if ( image.depth() == 8 )
865 { 867 {
866 int i; 868 int i;
867 bool alpha[256]; 869 bool alpha[256];
868 int nalpha=0; 870 int nalpha=0;
869 871
870 for ( i=0; i<256; i++ ) 872 for ( i=0; i<256; i++ )
871 alpha[i] = FALSE; 873 alpha[i] = FALSE;
872 874
873 for ( i=0; i<image.numColors(); i++ ) 875 for ( i=0; i<image.numColors(); i++ )
874 { 876 {
875 int alevel = image.color(i) >> 24; 877 int alevel = image.color(i) >> 24;
876 if ( !alpha[alevel] ) 878 if ( !alpha[alevel] )
877 { 879 {
878 alpha[alevel] = TRUE; 880 alpha[alevel] = TRUE;
879 nalpha++; 881 nalpha++;
880 } 882 }
881 } 883 }
882 imageInfo[ALPHA]=tr("%1 alpha levels").arg(nalpha); 884 imageInfo[ALPHA]=tr("%1 alpha levels").arg(nalpha);
883 } 885 }
884 else 886 else
885 { 887 {
886 imageInfo[ALPHA]=tr("8-bit alpha channel"); 888 imageInfo[ALPHA]=tr("8-bit alpha channel");
887 } 889 }
888 } 890 }
889 891
890} 892}
891 893
892void ImageViewer::closeEvent( QCloseEvent *e ) 894void ImageViewer::closeEvent( QCloseEvent *e )
893{ 895{
894 if ( stack->visibleWidget() == imagePanel && !bFromDocView ) 896 if ( stack->visibleWidget() == imagePanel && !bFromDocView )
895 { 897 {
896 e->ignore(); 898 e->ignore();
897 open(); 899 open();
898 } 900 }
899 else 901 else
900 { 902 {
901 bFromDocView = FALSE; 903 bFromDocView = FALSE;
902 e->accept(); 904 e->accept();
903 } 905 }
904} 906}
905 907
906// Intensity,toGray and rotate code courtesy of KDE project. 908// Intensity,toGray and rotate code courtesy of KDE project.
907 909
908 910
909QImage& ImageViewer::intensity(QImage &image, float percent) 911QImage& ImageViewer::intensity(QImage &image, float percent)
910{ 912{
911 913
912 int segColors = image.depth() > 8 ? 256 : image.numColors(); 914 int segColors = image.depth() > 8 ? 256 : image.numColors();
913 unsigned char *segTbl = new unsigned char[segColors]; 915 unsigned char *segTbl = new unsigned char[segColors];
914 int pixels = image.depth() > 8 ? image.width()*image.height() : 916 int pixels = image.depth() > 8 ? image.width()*image.height() :
915 image.numColors(); 917 image.numColors();
916 unsigned int *data = image.depth() > 8 ? (unsigned int *)image.bits() : 918 unsigned int *data = image.depth() > 8 ? (unsigned int *)image.bits() :
917 (unsigned int *)image.colorTable(); 919 (unsigned int *)image.colorTable();
918 920
919 bool brighten = (percent >= 0); 921 bool brighten = (percent >= 0);
920 if ( percent < 0 ) 922 if ( percent < 0 )
921 percent = -percent; 923 percent = -percent;
922 924
923 if ( brighten ) 925 if ( brighten )
924 { // keep overflow check out of loops 926 { // keep overflow check out of loops
925 for ( int i=0; i < segColors; ++i ) 927 for ( int i=0; i < segColors; ++i )
926 { 928 {
927 int tmp = (int)(i*percent); 929 int tmp = (int)(i*percent);
928 if ( tmp > 255 ) 930 if ( tmp > 255 )
929 tmp = 255; 931 tmp = 255;
930 segTbl[i] = tmp; 932 segTbl[i] = tmp;
931 } 933 }
932 } 934 }
933 else 935 else
934 { 936 {
935 for ( int i=0; i < segColors; ++i ) 937 for ( int i=0; i < segColors; ++i )
936 { 938 {
937 int tmp = (int)(i*percent); 939 int tmp = (int)(i*percent);
938 if ( tmp < 0 ) 940 if ( tmp < 0 )
939 tmp = 0; 941 tmp = 0;
940 segTbl[i] = tmp; 942 segTbl[i] = tmp;
941 } 943 }
942 } 944 }
943 945
944 if ( brighten ) 946 if ( brighten )
945 { // same here 947 { // same here
946 for ( int i=0; i < pixels; ++i ) 948 for ( int i=0; i < pixels; ++i )
947 { 949 {
948 int r = qRed(data[i]); 950 int r = qRed(data[i]);
949 int g = qGreen(data[i]); 951 int g = qGreen(data[i]);
950 int b = qBlue(data[i]); 952 int b = qBlue(data[i]);
951 int a = qAlpha(data[i]); 953 int a = qAlpha(data[i]);
952 r = r + segTbl[r] > 255 ? 255 : r + segTbl[r]; 954 r = r + segTbl[r] > 255 ? 255 : r + segTbl[r];
953 g = g + segTbl[g] > 255 ? 255 : g + segTbl[g]; 955 g = g + segTbl[g] > 255 ? 255 : g + segTbl[g];
954 b = b + segTbl[b] > 255 ? 255 : b + segTbl[b]; 956 b = b + segTbl[b] > 255 ? 255 : b + segTbl[b];
955 data[i] = qRgba(r, g, b,a); 957 data[i] = qRgba(r, g, b,a);
956 } 958 }
957 } 959 }
958 else 960 else
959 { 961 {
960 for ( int i=0; i < pixels; ++i ) 962 for ( int i=0; i < pixels; ++i )
961 { 963 {
962 int r = qRed(data[i]); 964 int r = qRed(data[i]);
963 int g = qGreen(data[i]); 965 int g = qGreen(data[i]);
964 int b = qBlue(data[i]); 966 int b = qBlue(data[i]);
965 int a = qAlpha(data[i]); 967 int a = qAlpha(data[i]);
966 r = r - segTbl[r] < 0 ? 0 : r - segTbl[r]; 968 r = r - segTbl[r] < 0 ? 0 : r - segTbl[r];
967 g = g - segTbl[g] < 0 ? 0 : g - segTbl[g]; 969 g = g - segTbl[g] < 0 ? 0 : g - segTbl[g];
968 b = b - segTbl[b] < 0 ? 0 : b - segTbl[b]; 970 b = b - segTbl[b] < 0 ? 0 : b - segTbl[b];
969 data[i] = qRgba(r, g, b, a); 971 data[i] = qRgba(r, g, b, a);
970 } 972 }
971 } 973 }
972 delete [] segTbl; 974 delete [] segTbl;
973 975
974 return image; 976 return image;
975} 977}
976 978
977QImage& ImageViewer::toGray(QImage &img, bool fast) 979QImage& ImageViewer::toGray(QImage &img, bool fast)
978{ 980{
979 if ( img.width() == 0 || img.height() == 0 ) 981 if ( img.width() == 0 || img.height() == 0 )
980 return img; 982 return img;
981 983
982 if ( fast ) 984 if ( fast )
983 { 985 {
984 if ( img.depth() == 32 ) 986 if ( img.depth() == 32 )
985 { 987 {
986 register uchar * r(img.bits()); 988 register uchar * r(img.bits());
987 register uchar * g(img.bits() + 1); 989 register uchar * g(img.bits() + 1);
988 register uchar * b(img.bits() + 2); 990 register uchar * b(img.bits() + 2);
989 991
990 uchar * end(img.bits() + img.numBytes()); 992 uchar * end(img.bits() + img.numBytes());
991 993
992 while ( r != end ) 994 while ( r != end )
993 { 995 {
994 996
995 *r = *g = *b = (((*r + *g) >> 1) + *b) >> 1; // (r + b + g) / 3 997 *r = *g = *b = (((*r + *g) >> 1) + *b) >> 1; // (r + b + g) / 3
996 998
997 r += 4; 999 r += 4;
998 g += 4; 1000 g += 4;
999 b += 4; 1001 b += 4;
1000 } 1002 }
1001 } 1003 }
1002 else 1004 else
1003 { 1005 {
1004 for ( int i = 0; i < img.numColors(); i++ ) 1006 for ( int i = 0; i < img.numColors(); i++ )
1005 { 1007 {
1006 register uint r = qRed(img.color(i)); 1008 register uint r = qRed(img.color(i));
1007 register uint g = qGreen(img.color(i)); 1009 register uint g = qGreen(img.color(i));
1008 register uint b = qBlue(img.color(i)); 1010 register uint b = qBlue(img.color(i));
1009 1011
1010 register uint gray = (((r + g) >> 1) + b) >> 1; 1012 register uint gray = (((r + g) >> 1) + b) >> 1;
1011 img.setColor(i, qRgba(gray, gray, gray, qAlpha(img.color(i)))); 1013 img.setColor(i, qRgba(gray, gray, gray, qAlpha(img.color(i))));
1012 } 1014 }
1013 } 1015 }
1014 } 1016 }
1015 else 1017 else
1016 { 1018 {
1017 int pixels = img.depth() > 8 ? img.width()*img.height() : 1019 int pixels = img.depth() > 8 ? img.width()*img.height() :
1018 img.numColors(); 1020 img.numColors();
1019 unsigned int *data = img.depth() > 8 ? (unsigned int *)img.bits() : 1021 unsigned int *data = img.depth() > 8 ? (unsigned int *)img.bits() :
1020 (unsigned int *)img.colorTable(); 1022 (unsigned int *)img.colorTable();
1021 int val, i; 1023 int val, i;
1022 for ( i=0; i < pixels; ++i ) 1024 for ( i=0; i < pixels; ++i )
1023 { 1025 {
1024 val = qGray(data[i]); 1026 val = qGray(data[i]);
1025 data[i] = qRgba(val, val, val, qAlpha(data[i])); 1027 data[i] = qRgba(val, val, val, qAlpha(data[i]));
1026 } 1028 }
1027 } 1029 }
1028 return img; 1030 return img;
1029} 1031}
1030 1032
1031 1033
1032QImage ImageViewer::rotate(QImage &img, RotateDirection r) 1034QImage ImageViewer::rotate(QImage &img, RotateDirection r)
1033{ 1035{
1034 QImage dest; 1036 QImage dest;
1035 int x, y; 1037 int x, y;
1036 if ( img.depth() > 8 ) 1038 if ( img.depth() > 8 )
1037 { 1039 {
1038 unsigned int *srcData, *destData; 1040 unsigned int *srcData, *destData;
1039 switch ( r ) 1041 switch ( r )
1040 { 1042 {
1041 case Rotate90: 1043 case Rotate90:
1042 dest.create(img.height(), img.width(), img.depth()); 1044 dest.create(img.height(), img.width(), img.depth());
1043 for ( y=0; y < img.height(); ++y ) 1045 for ( y=0; y < img.height(); ++y )
1044 { 1046 {
1045 srcData = (unsigned int *)img.scanLine(y); 1047 srcData = (unsigned int *)img.scanLine(y);
1046 for ( x=0; x < img.width(); ++x ) 1048 for ( x=0; x < img.width(); ++x )
1047 { 1049 {
1048 destData = (unsigned int *)dest.scanLine(x); 1050 destData = (unsigned int *)dest.scanLine(x);
1049 destData[img.height()-y-1] = srcData[x]; 1051 destData[img.height()-y-1] = srcData[x];
1050 } 1052 }
1051 } 1053 }
1052 break; 1054 break;
1053 case Rotate180: 1055 case Rotate180:
1054 dest.create(img.width(), img.height(), img.depth()); 1056 dest.create(img.width(), img.height(), img.depth());
1055 for ( y=0; y < img.height(); ++y ) 1057 for ( y=0; y < img.height(); ++y )
1056 { 1058 {
1057 srcData = (unsigned int *)img.scanLine(y); 1059 srcData = (unsigned int *)img.scanLine(y);
1058 destData = (unsigned int *)dest.scanLine(img.height()-y-1); 1060 destData = (unsigned int *)dest.scanLine(img.height()-y-1);
1059 for ( x=0; x < img.width(); ++x ) 1061 for ( x=0; x < img.width(); ++x )
1060 destData[img.width()-x-1] = srcData[x]; 1062 destData[img.width()-x-1] = srcData[x];
1061 } 1063 }
1062 break; 1064 break;
1063 case Rotate270: 1065 case Rotate270:
1064 dest.create(img.height(), img.width(), img.depth()); 1066 dest.create(img.height(), img.width(), img.depth());
1065 for ( y=0; y < img.height(); ++y ) 1067 for ( y=0; y < img.height(); ++y )
1066 { 1068 {
1067 srcData = (unsigned int *)img.scanLine(y); 1069 srcData = (unsigned int *)img.scanLine(y);
1068 for ( x=0; x < img.width(); ++x ) 1070 for ( x=0; x < img.width(); ++x )
1069 { 1071 {
1070 destData = (unsigned int *)dest.scanLine(img.width()-x-1); 1072 destData = (unsigned int *)dest.scanLine(img.width()-x-1);
1071 destData[y] = srcData[x]; 1073 destData[y] = srcData[x];
1072 } 1074 }
1073 } 1075 }
1074 break; 1076 break;
1075 default: 1077 default:
1076 dest = img; 1078 dest = img;
1077 break; 1079 break;
1078 } 1080 }
1079 } 1081 }
1080 else 1082 else
1081 { 1083 {
1082 unsigned char *srcData, *destData; 1084 unsigned char *srcData, *destData;
1083 unsigned int *srcTable, *destTable; 1085 unsigned int *srcTable, *destTable;
1084 switch ( r ) 1086 switch ( r )
1085 { 1087 {
1086 case Rotate90: 1088 case Rotate90:
1087 dest.create(img.height(), img.width(), img.depth()); 1089 dest.create(img.height(), img.width(), img.depth());
1088 dest.setNumColors(img.numColors()); 1090 dest.setNumColors(img.numColors());
1089 srcTable = (unsigned int *)img.colorTable(); 1091 srcTable = (unsigned int *)img.colorTable();
1090 destTable = (unsigned int *)dest.colorTable(); 1092 destTable = (unsigned int *)dest.colorTable();
1091 for ( x=0; x < img.numColors(); ++x ) 1093 for ( x=0; x < img.numColors(); ++x )
1092 destTable[x] = srcTable[x]; 1094 destTable[x] = srcTable[x];
1093 for ( y=0; y < img.height(); ++y ) 1095 for ( y=0; y < img.height(); ++y )
1094 { 1096 {
1095 srcData = (unsigned char *)img.scanLine(y); 1097 srcData = (unsigned char *)img.scanLine(y);
1096 for ( x=0; x < img.width(); ++x ) 1098 for ( x=0; x < img.width(); ++x )
1097 { 1099 {
1098 destData = (unsigned char *)dest.scanLine(x); 1100 destData = (unsigned char *)dest.scanLine(x);
1099 destData[img.height()-y-1] = srcData[x]; 1101 destData[img.height()-y-1] = srcData[x];
1100 } 1102 }
1101 } 1103 }
1102 break; 1104 break;
1103 case Rotate180: 1105 case Rotate180:
1104 dest.create(img.width(), img.height(), img.depth()); 1106 dest.create(img.width(), img.height(), img.depth());
1105 dest.setNumColors(img.numColors()); 1107 dest.setNumColors(img.numColors());
1106 srcTable = (unsigned int *)img.colorTable(); 1108 srcTable = (unsigned int *)img.colorTable();
1107 destTable = (unsigned int *)dest.colorTable(); 1109 destTable = (unsigned int *)dest.colorTable();
1108 for ( x=0; x < img.numColors(); ++x ) 1110 for ( x=0; x < img.numColors(); ++x )
1109 destTable[x] = srcTable[x]; 1111 destTable[x] = srcTable[x];
1110 for ( y=0; y < img.height(); ++y ) 1112 for ( y=0; y < img.height(); ++y )
1111 { 1113 {
1112 srcData = (unsigned char *)img.scanLine(y); 1114 srcData = (unsigned char *)img.scanLine(y);
1113 destData = (unsigned char *)dest.scanLine(img.height()-y-1); 1115 destData = (unsigned char *)dest.scanLine(img.height()-y-1);
1114 for ( x=0; x < img.width(); ++x ) 1116 for ( x=0; x < img.width(); ++x )
1115 destData[img.width()-x-1] = srcData[x]; 1117 destData[img.width()-x-1] = srcData[x];
1116 } 1118 }
1117 break; 1119 break;
1118 case Rotate270: 1120 case Rotate270:
1119 dest.create(img.height(), img.width(), img.depth()); 1121 dest.create(img.height(), img.width(), img.depth());
1120 dest.setNumColors(img.numColors()); 1122 dest.setNumColors(img.numColors());
1121 srcTable = (unsigned int *)img.colorTable(); 1123 srcTable = (unsigned int *)img.colorTable();
1122 destTable = (unsigned int *)dest.colorTable(); 1124 destTable = (unsigned int *)dest.colorTable();
1123 for ( x=0; x < img.numColors(); ++x ) 1125 for ( x=0; x < img.numColors(); ++x )
1124 destTable[x] = srcTable[x]; 1126 destTable[x] = srcTable[x];
1125 for ( y=0; y < img.height(); ++y ) 1127 for ( y=0; y < img.height(); ++y )
1126 { 1128 {
1127 srcData = (unsigned char *)img.scanLine(y); 1129 srcData = (unsigned char *)img.scanLine(y);
1128 for ( x=0; x < img.width(); ++x ) 1130 for ( x=0; x < img.width(); ++x )
1129 { 1131 {
1130 destData = (unsigned char *)dest.scanLine(img.width()-x-1); 1132 destData = (unsigned char *)dest.scanLine(img.width()-x-1);
1131 destData[y] = srcData[x]; 1133 destData[y] = srcData[x];
1132 } 1134 }
1133 } 1135 }
1134 break; 1136 break;
1135 default: 1137 default:
1136 dest = img; 1138 dest = img;
1137 break; 1139 break;
1138 } 1140 }
1139 1141
1140 } 1142 }
1141 return (dest); 1143 return (dest);
1142} 1144}
1143 1145
1144void ImageViewer::slideShow( bool on ) 1146void ImageViewer::slideShow( bool on )
1145{ 1147{
1146 if (on) { 1148 if (on) {
1147 if (!imageList.isEmpty()) { 1149 if (!imageList.isEmpty()) {
1148 slideTimer->start(slideDelay * 1000, FALSE); 1150 slideTimer->start(slideDelay * 1000, FALSE);
1149 filename = ""; // force restart 1151 filename = ""; // force restart
1150 slideReverse ? prevImage() : nextImage(); 1152 slideReverse ? prevImage() : nextImage();
1151 } 1153 }
1152 } else { 1154 } else {
1153 slideTimer->stop(); 1155 slideTimer->stop();
1154 slideAction->setOn( false); 1156 slideAction->setOn( false);
1155 } 1157 }
1156} 1158}
1157 1159
1158void ImageViewer::slideUpdate() 1160void ImageViewer::slideUpdate()
1159{ 1161{
1160 bool final_image = slideReverse ? prevImage() : nextImage(); 1162 bool final_image = slideReverse ? prevImage() : nextImage();
1161 1163
1162 if (final_image && !slideRepeat) { 1164 if (final_image && !slideRepeat) {
1163 slideTimer->stop(); 1165 slideTimer->stop();
1164 slideAction->setOn(FALSE); 1166 slideAction->setOn(FALSE);
1165 } 1167 }
1166} 1168}
1167 1169
1168// 1170//
1169// Display the image after the current one in the image list. 1171// Display the image after the current one in the image list.
1170// Return TRUE if the next call to nextImage() will wrap around to the 1172// Return TRUE if the next call to nextImage() will wrap around to the
1171// first image in the list (ie. we're now viewing the last image in the list). 1173// first image in the list (ie. we're now viewing the last image in the list).
1172// 1174//
1173bool ImageViewer::nextImage(void) 1175bool ImageViewer::nextImage(void)
1174{ 1176{
1175 int idx = 0; 1177 int idx = 0;
1176 1178
1177 if (imageList.count() > 0) { 1179 if (imageList.count() > 0) {
1178 idx = imageIndex(); 1180 idx = imageIndex();
1179 if (idx != -1) { 1181 if (idx != -1) {
1180 if (idx == int(imageList.count() - 1)) { 1182 if (idx == int(imageList.count() - 1)) {
1181 idx = 0; 1183 idx = 0;
1182 } else { 1184 } else {
1183 idx++; 1185 idx++;
1184 } 1186 }
1185 } else { 1187 } else {
1186 idx = 0; 1188 idx = 0;
1187 } 1189 }
1188 openFile(imageList[idx]); 1190 openFile(imageList[idx]);
1189 } 1191 }
1190 1192
1191 return idx == int(imageList.count() - 1) ? TRUE : FALSE; 1193 return idx == int(imageList.count() - 1) ? TRUE : FALSE;
1192} 1194}
1193 1195
1194// 1196//
1195// Display the image preceeding the current one in the image list. 1197// Display the image preceeding the current one in the image list.
1196// Return TRUE if the next call to prevImage() will wrap around to the last 1198// Return TRUE if the next call to prevImage() will wrap around to the last
1197// image in the list (ie. we're now viewing the first image in the list). 1199// image in the list (ie. we're now viewing the first image in the list).
1198// 1200//
1199bool ImageViewer::prevImage(void) 1201bool ImageViewer::prevImage(void)
1200{ 1202{
1201 int idx = -1; 1203 int idx = -1;
1202 1204
1203 if (imageList.count() > 0) { 1205 if (imageList.count() > 0) {
1204 idx = imageIndex(); 1206 idx = imageIndex();
1205 if (idx != -1) { 1207 if (idx != -1) {
1206 if (idx == 0) { 1208 if (idx == 0) {
1207 idx = imageList.count() - 1; 1209 idx = imageList.count() - 1;
1208 } else { 1210 } else {
1209 idx--; 1211 idx--;
1210 } 1212 }
1211 } else { 1213 } else {
1212 idx = imageList.count() - 1; 1214 idx = imageList.count() - 1;
1213 } 1215 }
1214 openFile(imageList[idx]); 1216 openFile(imageList[idx]);
1215 } 1217 }
1216 1218
1217 return idx == 0 ? TRUE : FALSE; 1219 return idx == 0 ? TRUE : FALSE;
1218} 1220}
1219 1221
1220// 1222//
1221// Return the index into the imageList of the currently viewed 1223// Return the index into the imageList of the currently viewed
1222// image (ie. ImageViewer::filename in ImageViewer::imageList). 1224// image (ie. ImageViewer::filename in ImageViewer::imageList).
1223// 1225//
1224int ImageViewer::imageIndex(void) 1226int ImageViewer::imageIndex(void)
1225{ 1227{
1226 QValueListConstIterator<DocLnk> i; 1228 QValueListConstIterator<DocLnk> i;
1227 int index; 1229 int index;
1228 1230
1229 if (imageList.count() == 0) { 1231 if (imageList.count() == 0) {
1230 return -1; 1232 return -1;
1231 } 1233 }
1232 1234
1233 for (index = 0, i = imageList.begin(); i != imageList.end(); ++i, index++) { 1235 for (index = 0, i = imageList.begin(); i != imageList.end(); ++i, index++) {
1234 if ((*i).file() == filename) { 1236 if ((*i).file() == filename) {
1235 return index; 1237 return index;
1236 } 1238 }
1237 } 1239 }
1238 1240
1239 return -1; 1241 return -1;
1240} 1242}
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
@@ -1,302 +1,302 @@
1#include <qt.h> 1#include <qt.h>
2 2
3#include <opie2/ofiledialog.h> 3#include <opie2/ofiledialog.h>
4#include <qpe/resource.h> 4#include <qpe/resource.h>
5#include <qpe/config.h> 5#include <qpe/config.h>
6#include <qpe/global.h> 6#include <qpe/global.h>
7#include <qpe/contact.h> 7#include <qpe/contact.h>
8 8
9#include "composemail.h" 9#include "composemail.h"
10 10
11#include <libmailwrapper/smtpwrapper.h> 11#include <libmailwrapper/smtpwrapper.h>
12#include <libmailwrapper/storemail.h> 12#include <libmailwrapper/storemail.h>
13#include <libmailwrapper/abstractmail.h> 13#include <libmailwrapper/abstractmail.h>
14#include <libmailwrapper/mailtypes.h> 14#include <libmailwrapper/mailtypes.h>
15 15
16using namespace Opie::Core; 16using namespace Opie::Core;
17using namespace Opie::Ui; 17using namespace Opie::Ui;
18ComposeMail::ComposeMail( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags ) 18ComposeMail::ComposeMail( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags )
19 : ComposeMailUI( parent, name, modal, flags ) 19 : ComposeMailUI( parent, name, modal, flags )
20{ 20{
21 settings = s; 21 settings = s;
22 m_replyid = ""; 22 m_replyid = "";
23 23
24 QString vfilename = Global::applicationFileName("addressbook", 24 QString vfilename = Global::applicationFileName("addressbook",
25 "businesscard.vcf"); 25 "businesscard.vcf");
26 Contact c; 26 Contact c;
27 if (QFile::exists(vfilename)) { 27 if (QFile::exists(vfilename)) {
28 c = Contact::readVCard( vfilename )[0]; 28 c = Contact::readVCard( vfilename )[0];
29 } 29 }
30 30
31 QStringList mails = c.emailList(); 31 QStringList mails = c.emailList();
32 QString defmail = c.defaultEmail(); 32 QString defmail = c.defaultEmail();
33 33
34 if (defmail.length()!=0) { 34 if (defmail.length()!=0) {
35 fromBox->insertItem(defmail); 35 fromBox->insertItem(defmail);
36 } 36 }
37 QStringList::ConstIterator sit = mails.begin(); 37 QStringList::ConstIterator sit = mails.begin();
38 for (;sit!=mails.end();++sit) { 38 for (;sit!=mails.end();++sit) {
39 if ( (*sit)==defmail) 39 if ( (*sit)==defmail)
40 continue; 40 continue;
41 fromBox->insertItem((*sit)); 41 fromBox->insertItem((*sit));
42 } 42 }
43 senderNameEdit->setText(c.firstName()+" "+c.lastName()); 43 senderNameEdit->setText(c.firstName()+" "+c.lastName());
44 Config cfg( "mail" ); 44 Config cfg( "mail" );
45 cfg.setGroup( "Compose" ); 45 cfg.setGroup( "Compose" );
46 checkBoxLater->setChecked( cfg.readBoolEntry( "sendLater", false ) ); 46 checkBoxLater->setChecked( cfg.readBoolEntry( "sendLater", false ) );
47 47
48 attList->addColumn( tr( "Name" ) ); 48 attList->addColumn( tr( "Name" ) );
49 attList->addColumn( tr( "Size" ) ); 49 attList->addColumn( tr( "Size" ) );
50 50
51 QList<Account> accounts = settings->getAccounts(); 51 QList<Account> accounts = settings->getAccounts();
52 52
53 Account *it; 53 Account *it;
54 for ( it = accounts.first(); it; it = accounts.next() ) { 54 for ( it = accounts.first(); it; it = accounts.next() ) {
55 if ( it->getType()==MAILLIB::A_SMTP ) { 55 if ( it->getType()==MAILLIB::A_SMTP ) {
56 SMTPaccount *smtp = static_cast<SMTPaccount *>(it); 56 SMTPaccount *smtp = static_cast<SMTPaccount *>(it);
57 smtpAccountBox->insertItem( smtp->getAccountName() ); 57 smtpAccountBox->insertItem( smtp->getAccountName() );
58 smtpAccounts.append( smtp ); 58 smtpAccounts.append( smtp );
59 } 59 }
60 } 60 }
61 61
62 if ( smtpAccounts.count() > 0 ) { 62 if ( smtpAccounts.count() > 0 ) {
63 fillValues( smtpAccountBox->currentItem() ); 63 fillValues( smtpAccountBox->currentItem() );
64 } else { 64 } else {
65 QMessageBox::information( this, tr( "Problem" ), 65 QMessageBox::information( this, tr( "Problem" ),
66 tr( "<p>Please create an SMTP account first.</p>" ), 66 tr( "<p>Please create an SMTP account first.</p>" ),
67 tr( "Ok" ) ); 67 tr( "Ok" ) );
68 return; 68 return;
69 } 69 }
70 70
71 connect( smtpAccountBox, SIGNAL( activated(int) ), SLOT( fillValues(int) ) ); 71 connect( smtpAccountBox, SIGNAL( activated(int) ), SLOT( fillValues(int) ) );
72 connect( toButton, SIGNAL( clicked() ), SLOT( pickAddressTo() ) ); 72 connect( toButton, SIGNAL( clicked() ), SLOT( pickAddressTo() ) );
73 connect( ccButton, SIGNAL( clicked() ), SLOT( pickAddressCC() ) ); 73 connect( ccButton, SIGNAL( clicked() ), SLOT( pickAddressCC() ) );
74 connect( bccButton, SIGNAL( clicked() ), SLOT( pickAddressBCC() ) ); 74 connect( bccButton, SIGNAL( clicked() ), SLOT( pickAddressBCC() ) );
75 connect( replyButton, SIGNAL( clicked() ), SLOT( pickAddressReply() ) ); 75 connect( replyButton, SIGNAL( clicked() ), SLOT( pickAddressReply() ) );
76 connect( addButton, SIGNAL( clicked() ), SLOT( addAttachment() ) ); 76 connect( addButton, SIGNAL( clicked() ), SLOT( addAttachment() ) );
77 connect( deleteButton, SIGNAL( clicked() ), SLOT( removeAttachment() ) ); 77 connect( deleteButton, SIGNAL( clicked() ), SLOT( removeAttachment() ) );
78} 78}
79 79
80void ComposeMail::pickAddress( QLineEdit *line ) 80void ComposeMail::pickAddress( QLineEdit *line )
81{ 81{
82 QString names = AddressPicker::getNames(); 82 QString names = AddressPicker::getNames();
83 if ( line->text().isEmpty() ) { 83 if ( line->text().isEmpty() ) {
84 line->setText( names ); 84 line->setText( names );
85 } else if ( !names.isEmpty() ) { 85 } else if ( !names.isEmpty() ) {
86 line->setText( line->text() + ", " + names ); 86 line->setText( line->text() + ", " + names );
87 } 87 }
88} 88}
89 89
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,594 +1,594 @@
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());
362} 362}
363 363
364void IMAPconfig::accept() 364void IMAPconfig::accept()
365{ 365{
366 data->setAccountName( accountLine->text() ); 366 data->setAccountName( accountLine->text() );
367 data->setServer( serverLine->text() ); 367 data->setServer( serverLine->text() );
368 data->setPort( portLine->text() ); 368 data->setPort( portLine->text() );
369 data->setConnectionType( ComboBox1->currentItem() ); 369 data->setConnectionType( ComboBox1->currentItem() );
370 data->setUser( userLine->text() ); 370 data->setUser( userLine->text() );
371 data->setPassword( passLine->text() ); 371 data->setPassword( passLine->text() );
372 data->setPrefix(prefixLine->text()); 372 data->setPrefix(prefixLine->text());
373 373
374 QDialog::accept(); 374 QDialog::accept();
375} 375}
376 376
377/** 377/**
378 * POP3config 378 * POP3config
379 */ 379 */
380 380
381POP3config::POP3config( POP3account *account, QWidget *parent, const char *name, bool modal, WFlags flags ) 381POP3config::POP3config( POP3account *account, QWidget *parent, const char *name, bool modal, WFlags flags )
382 : POP3configUI( parent, name, modal, flags ) 382 : POP3configUI( parent, name, modal, flags )
383{ 383{
384 data = account; 384 data = account;
385 fillValues(); 385 fillValues();
386 386
387 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) ); 387 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) );
388 ComboBox1->insertItem( "Only if available", 0 ); 388 ComboBox1->insertItem( "Only if available", 0 );
389 ComboBox1->insertItem( "Always, Negotiated", 1 ); 389 ComboBox1->insertItem( "Always, Negotiated", 1 );
390 ComboBox1->insertItem( "Connect on secure port", 2 ); 390 ComboBox1->insertItem( "Connect on secure port", 2 );
391 ComboBox1->insertItem( "Run command instead", 3 ); 391 ComboBox1->insertItem( "Run command instead", 3 );
392 CommandEdit->hide(); 392 CommandEdit->hide();
393 ComboBox1->setCurrentItem( data->ConnectionType() ); 393 ComboBox1->setCurrentItem( data->ConnectionType() );
394} 394}
395 395
396void POP3config::slotConnectionToggle( int index ) 396void POP3config::slotConnectionToggle( int index )
397{ 397{
398 // 2 is ssl connection 398 // 2 is ssl connection
399 if ( index == 2 ) 399 if ( index == 2 )
400 { 400 {
401 portLine->setText( POP3_SSL_PORT ); 401 portLine->setText( POP3_SSL_PORT );
402 } 402 }
403 else if ( index == 3 ) 403 else if ( index == 3 )
404 { 404 {
405 portLine->setText( POP3_PORT ); 405 portLine->setText( POP3_PORT );
406 CommandEdit->show(); 406 CommandEdit->show();
407 } 407 }
408 else 408 else
409 { 409 {
410 portLine->setText( POP3_PORT ); 410 portLine->setText( POP3_PORT );
411 } 411 }
412} 412}
413 413
414void POP3config::fillValues() 414void POP3config::fillValues()
415{ 415{
416 accountLine->setText( data->getAccountName() ); 416 accountLine->setText( data->getAccountName() );
417 serverLine->setText( data->getServer() ); 417 serverLine->setText( data->getServer() );
418 portLine->setText( data->getPort() ); 418 portLine->setText( data->getPort() );
419 ComboBox1->setCurrentItem( data->ConnectionType() ); 419 ComboBox1->setCurrentItem( data->ConnectionType() );
420 userLine->setText( data->getUser() ); 420 userLine->setText( data->getUser() );
421 passLine->setText( data->getPassword() ); 421 passLine->setText( data->getPassword() );
422} 422}
423 423
424void POP3config::accept() 424void POP3config::accept()
425{ 425{
426 data->setAccountName( accountLine->text() ); 426 data->setAccountName( accountLine->text() );
427 data->setServer( serverLine->text() ); 427 data->setServer( serverLine->text() );
428 data->setPort( portLine->text() ); 428 data->setPort( portLine->text() );
429 data->setConnectionType( ComboBox1->currentItem() ); 429 data->setConnectionType( ComboBox1->currentItem() );
430 data->setUser( userLine->text() ); 430 data->setUser( userLine->text() );
431 data->setPassword( passLine->text() ); 431 data->setPassword( passLine->text() );
432 432
433 QDialog::accept(); 433 QDialog::accept();
434} 434}
435 435
436/** 436/**
437 * SMTPconfig 437 * SMTPconfig
438 */ 438 */
439 439
440SMTPconfig::SMTPconfig( SMTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags ) 440SMTPconfig::SMTPconfig( SMTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags )
441 : SMTPconfigUI( parent, name, modal, flags ) 441 : SMTPconfigUI( parent, name, modal, flags )
442{ 442{
443 data = account; 443 data = account;
444 444
445 connect( loginBox, SIGNAL( toggled(bool) ), userLine, SLOT( setEnabled(bool) ) ); 445 connect( loginBox, SIGNAL( toggled(bool) ), userLine, SLOT( setEnabled(bool) ) );
446 connect( loginBox, SIGNAL( toggled(bool) ), passLine, SLOT( setEnabled(bool) ) ); 446 connect( loginBox, SIGNAL( toggled(bool) ), passLine, SLOT( setEnabled(bool) ) );
447 447
448 fillValues(); 448 fillValues();
449 449
450 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) ); 450 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) );
451 ComboBox1->insertItem( "Only if available", 0 ); 451 ComboBox1->insertItem( "Only if available", 0 );
452 ComboBox1->insertItem( "Always, Negotiated", 1 ); 452 ComboBox1->insertItem( "Always, Negotiated", 1 );
453 ComboBox1->insertItem( "Connect on secure port", 2 ); 453 ComboBox1->insertItem( "Connect on secure port", 2 );
454 ComboBox1->insertItem( "Run command instead", 3 ); 454 ComboBox1->insertItem( "Run command instead", 3 );
455 CommandEdit->hide(); 455 CommandEdit->hide();
456 ComboBox1->setCurrentItem( data->ConnectionType() ); 456 ComboBox1->setCurrentItem( data->ConnectionType() );
457} 457}
458 458
459void SMTPconfig::slotConnectionToggle( int index ) 459void SMTPconfig::slotConnectionToggle( int index )
460{ 460{
461 // 2 is ssl connection 461 // 2 is ssl connection
462 if ( index == 2 ) 462 if ( index == 2 )
463 { 463 {
464 portLine->setText( SMTP_SSL_PORT ); 464 portLine->setText( SMTP_SSL_PORT );
465 } 465 }
466 else if ( index == 3 ) 466 else if ( index == 3 )
467 { 467 {
468 portLine->setText( SMTP_PORT ); 468 portLine->setText( SMTP_PORT );
469 CommandEdit->show(); 469 CommandEdit->show();
470 } 470 }
471 else 471 else
472 { 472 {
473 portLine->setText( SMTP_PORT ); 473 portLine->setText( SMTP_PORT );
474 } 474 }
475} 475}
476 476
477void SMTPconfig::fillValues() 477void SMTPconfig::fillValues()
478{ 478{
479 accountLine->setText( data->getAccountName() ); 479 accountLine->setText( data->getAccountName() );
480 serverLine->setText( data->getServer() ); 480 serverLine->setText( data->getServer() );
481 portLine->setText( data->getPort() ); 481 portLine->setText( data->getPort() );
482 ComboBox1->setCurrentItem( data->ConnectionType() ); 482 ComboBox1->setCurrentItem( data->ConnectionType() );
483 loginBox->setChecked( data->getLogin() ); 483 loginBox->setChecked( data->getLogin() );
484 userLine->setText( data->getUser() ); 484 userLine->setText( data->getUser() );
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
@@ -1,468 +1,468 @@
1#include "generatemail.h" 1#include "generatemail.h"
2#include "mailwrapper.h" 2#include "mailwrapper.h"
3 3
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
@@ -1,476 +1,476 @@
1#include "genericwrapper.h" 1#include "genericwrapper.h"
2#include <libetpan/libetpan.h> 2#include <libetpan/libetpan.h>
3#include "mailtypes.h" 3#include "mailtypes.h"
4 4
5using namespace Opie::Core; 5using namespace Opie::Core;
6Genericwrapper::Genericwrapper() 6Genericwrapper::Genericwrapper()
7 : AbstractMail() 7 : AbstractMail()
8{ 8{
9 bodyCache.clear(); 9 bodyCache.clear();
10 m_storage = 0; 10 m_storage = 0;
11 m_folder = 0; 11 m_folder = 0;
12} 12}
13 13
14Genericwrapper::~Genericwrapper() 14Genericwrapper::~Genericwrapper()
15{ 15{
16 if (m_folder) { 16 if (m_folder) {
17 mailfolder_free(m_folder); 17 mailfolder_free(m_folder);
18 } 18 }
19 if (m_storage) { 19 if (m_storage) {
20 mailstorage_free(m_storage); 20 mailstorage_free(m_storage);
21 } 21 }
22 cleanMimeCache(); 22 cleanMimeCache();
23} 23}
24 24
25void Genericwrapper::fillSingleBody(RecPartP&target,mailmessage*,mailmime*mime) 25void Genericwrapper::fillSingleBody(RecPartP&target,mailmessage*,mailmime*mime)
26{ 26{
27 if (!mime) { 27 if (!mime) {
28 return; 28 return;
29 } 29 }
30 mailmime_field*field = 0; 30 mailmime_field*field = 0;
31 mailmime_single_fields fields; 31 mailmime_single_fields fields;
32 memset(&fields, 0, sizeof(struct mailmime_single_fields)); 32 memset(&fields, 0, sizeof(struct mailmime_single_fields));
33 if (mime->mm_mime_fields != NULL) { 33 if (mime->mm_mime_fields != NULL) {
34 mailmime_single_fields_init(&fields, mime->mm_mime_fields, 34 mailmime_single_fields_init(&fields, mime->mm_mime_fields,
35 mime->mm_content_type); 35 mime->mm_content_type);
36 } 36 }
37 37
38 mailmime_content*type = fields.fld_content; 38 mailmime_content*type = fields.fld_content;
39 clistcell*current; 39 clistcell*current;
40 if (!type) { 40 if (!type) {
41 target->setType("text"); 41 target->setType("text");
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,179 +1,179 @@
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] == '-')
151 ++srcPtr; 151 ++srcPtr;
152 } 152 }
153 } 153 }
154 154
155 return QString::fromUtf8( dst.data() ); 155 return QString::fromUtf8( dst.data() );
156} 156}
157 157
158Mail::Mail() 158Mail::Mail()
159 :Opie::Core::ORefCount(),name(""), mail(""), to(""), cc(""), bcc(""), reply(""), subject(""), message("") 159 :Opie::Core::ORefCount(),name(""), mail(""), to(""), cc(""), bcc(""), reply(""), subject(""), message("")
160{ 160{
161} 161}
162 162
163MHFolder::MHFolder(const QString&disp_name,const QString&mbox) 163MHFolder::MHFolder(const QString&disp_name,const QString&mbox)
164 : Folder( disp_name,"/" ) 164 : Folder( disp_name,"/" )
165{ 165{
166 separator = "/"; 166 separator = "/";
167 name = mbox; 167 name = mbox;
168 if (!disp_name.startsWith("/") && disp_name.length()>0) 168 if (!disp_name.startsWith("/") && disp_name.length()>0)
169 name+="/"; 169 name+="/";
170 name+=disp_name; 170 name+=disp_name;
171 if (disp_name.length()==0) { 171 if (disp_name.length()==0) {
172 nameDisplay = separator; 172 nameDisplay = separator;
173 } 173 }
174 prefix = mbox; 174 prefix = mbox;
175} 175}
176 176
177MHFolder::~MHFolder() 177MHFolder::~MHFolder()
178{ 178{
179} 179}
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,288 +1,288 @@
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) {
271 res = new encodedString(target,length); 271 res = new encodedString(target,length);
272 } 272 }
273 return res; 273 return res;
274} 274}
275 275
276MAILLIB::ATYPE NNTPwrapper::getType()const { 276MAILLIB::ATYPE NNTPwrapper::getType()const {
277 return account->getType(); 277 return account->getType();
278} 278}
279 279
280const QString&NNTPwrapper::getName()const{ 280const QString&NNTPwrapper::getName()const{
281 return account->getAccountName(); 281 return account->getAccountName();
282} 282}
283 283
284void NNTPwrapper::deleteMail(const RecMailP&) { 284void NNTPwrapper::deleteMail(const RecMailP&) {
285} 285}
286 286
287int NNTPwrapper::deleteAllMail(const FolderP&) { 287int NNTPwrapper::deleteAllMail(const FolderP&) {
288} 288}
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
@@ -1,455 +1,455 @@
1#include "smtpwrapper.h" 1#include "smtpwrapper.h"
2#include "mailwrapper.h" 2#include "mailwrapper.h"
3#include "abstractmail.h" 3#include "abstractmail.h"
4#include "logindialog.h" 4#include "logindialog.h"
5#include "mailtypes.h" 5#include "mailtypes.h"
6#include "sendmailprogress.h" 6#include "sendmailprogress.h"
7 7
8#include <qt.h> 8#include <qt.h>
9 9
10#include <qpe/config.h> 10#include <qpe/config.h>
11#include <qpe/qcopenvelope_qws.h> 11#include <qpe/qcopenvelope_qws.h>
12 12
13#include <libetpan/libetpan.h> 13#include <libetpan/libetpan.h>
14 14
15 15
16using namespace Opie::Core; 16using namespace Opie::Core;
17progressMailSend*SMTPwrapper::sendProgress = 0; 17progressMailSend*SMTPwrapper::sendProgress = 0;
18 18
19SMTPwrapper::SMTPwrapper(SMTPaccount * aSmtp ) 19SMTPwrapper::SMTPwrapper(SMTPaccount * aSmtp )
20 : Generatemail() 20 : Generatemail()
21{ 21{
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
@@ -1,216 +1,216 @@
1#include <qlabel.h> 1#include <qlabel.h>
2#include <qvbox.h> 2#include <qvbox.h>
3#include <qheader.h> 3#include <qheader.h>
4#include <qtimer.h> 4#include <qtimer.h>
5#include <qlayout.h> 5#include <qlayout.h>
6 6
7#include <qpe/qpeapplication.h> 7#include <qpe/qpeapplication.h>
8 8
9#include "defines.h" 9#include "defines.h"
10#include "mainwindow.h" 10#include "mainwindow.h"
11 11
12 12
13MainWindow::MainWindow( QWidget *parent, const char *name, WFlags flags ) 13MainWindow::MainWindow( QWidget *parent, const char *name, WFlags flags )
14 : QMainWindow( parent, name, flags ) 14 : QMainWindow( parent, name, flags )
15{ 15{
16 16
17 setCaption( tr( "Mail" ) ); 17 setCaption( tr( "Mail" ) );
18 setToolBarsMovable( false ); 18 setToolBarsMovable( false );
19 19
20 toolBar = new QToolBar( this ); 20 toolBar = new QToolBar( this );
21 menuBar = new QMenuBar( toolBar ); 21 menuBar = new QMenuBar( toolBar );
22 mailMenu = new QPopupMenu( menuBar ); 22 mailMenu = new QPopupMenu( menuBar );
23 menuBar->insertItem( tr( "Mail" ), mailMenu ); 23 menuBar->insertItem( tr( "Mail" ), mailMenu );
24 settingsMenu = new QPopupMenu( menuBar ); 24 settingsMenu = new QPopupMenu( menuBar );
25 menuBar->insertItem( tr( "Settings" ), settingsMenu ); 25 menuBar->insertItem( tr( "Settings" ), settingsMenu );
26 26
27 addToolBar( toolBar ); 27 addToolBar( toolBar );
28 toolBar->setHorizontalStretchable( true ); 28 toolBar->setHorizontalStretchable( true );
29 29
30 QLabel *spacer = new QLabel( toolBar ); 30 QLabel *spacer = new QLabel( toolBar );
31 spacer->setBackgroundMode( QWidget::PaletteButton ); 31 spacer->setBackgroundMode( QWidget::PaletteButton );
32 toolBar->setStretchableWidget( spacer ); 32 toolBar->setStretchableWidget( spacer );
33 33
34 composeMail = new QAction( tr( "Compose new mail" ), ICON_COMPOSEMAIL, 34 composeMail = new QAction( tr( "Compose new mail" ), ICON_COMPOSEMAIL,
35 0, 0, this ); 35 0, 0, this );
36 composeMail->addTo( toolBar ); 36 composeMail->addTo( toolBar );
37 composeMail->addTo( mailMenu ); 37 composeMail->addTo( mailMenu );
38 38
39 sendQueued = new QAction( tr( "Send queued mails" ), ICON_SENDQUEUED, 39 sendQueued = new QAction( tr( "Send queued mails" ), ICON_SENDQUEUED,
40 0, 0, this ); 40 0, 0, this );
41 sendQueued->addTo( toolBar ); 41 sendQueued->addTo( toolBar );
42 sendQueued->addTo( mailMenu ); 42 sendQueued->addTo( mailMenu );
43 43
44 /* 44 /*
45 syncFolders = new QAction( tr( "Sync mailfolders" ), ICON_SYNC, 45 syncFolders = new QAction( tr( "Sync mailfolders" ), ICON_SYNC,
46 0, 0, this ); 46 0, 0, this );
47 syncFolders->addTo( toolBar ); 47 syncFolders->addTo( toolBar );
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
@@ -1,145 +1,145 @@
1#include <qpainter.h> 1#include <qpainter.h>
2#include <qtimer.h> 2#include <qtimer.h>
3 3
4#include <qpe/qcopenvelope_qws.h> 4#include <qpe/qcopenvelope_qws.h>
5#include <qpe/resource.h> 5#include <qpe/resource.h>
6#include <qpe/config.h> 6#include <qpe/config.h>
7#include <qpe/applnk.h> 7#include <qpe/applnk.h>
8 8
9#include <opie2/odevice.h> 9#include <opie2/odevice.h>
10 10
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
@@ -1,477 +1,477 @@
1#include "composemail.h" 1#include "composemail.h"
2#include "viewmail.h" 2#include "viewmail.h"
3 3
4/* OPIE */ 4/* OPIE */
5#include <libmailwrapper/settings.h> 5#include <libmailwrapper/settings.h>
6#include <libmailwrapper/abstractmail.h> 6#include <libmailwrapper/abstractmail.h>
7#include <libmailwrapper/mailtypes.h> 7#include <libmailwrapper/mailtypes.h>
8 8
9#include <opie2/ofiledialog.h> 9#include <opie2/ofiledialog.h>
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#include <qtextbrowser.h> 14#include <qtextbrowser.h>
15#include <qmessagebox.h> 15#include <qmessagebox.h>
16#include <qtextstream.h> 16#include <qtextstream.h>
17#include <qaction.h> 17#include <qaction.h>
18#include <qpopupmenu.h> 18#include <qpopupmenu.h>
19#include <qfile.h> 19#include <qfile.h>
20 20
21using namespace Opie::Ui; 21using namespace Opie::Ui;
22AttachItem::AttachItem(QListView * parent,QListViewItem *after, const QString&mime,const QString&desc,const QString&file, 22AttachItem::AttachItem(QListView * parent,QListViewItem *after, const QString&mime,const QString&desc,const QString&file,
23 const QString&fsize,int num,const QValueList<int>&path) 23 const QString&fsize,int num,const QValueList<int>&path)
24 : QListViewItem(parent,after),_partNum(num) 24 : QListViewItem(parent,after),_partNum(num)
25{ 25{
26 _path=path; 26 _path=path;
27 setText(0, mime); 27 setText(0, mime);
28 setText(1, desc); 28 setText(1, desc);
29 setText(2, file); 29 setText(2, file);
30 setText(3, fsize); 30 setText(3, fsize);
31} 31}
32 32
33AttachItem::AttachItem(QListViewItem * parent,QListViewItem *after, const QString&mime,const QString&desc,const QString&file, 33AttachItem::AttachItem(QListViewItem * parent,QListViewItem *after, const QString&mime,const QString&desc,const QString&file,
34 const QString&fsize,int num,const QValueList<int>&path) 34 const QString&fsize,int num,const QValueList<int>&path)
35 : QListViewItem(parent,after),_partNum(num) 35 : QListViewItem(parent,after),_partNum(num)
36{ 36{
37 _path=path; 37 _path=path;
38 setText(0, mime); 38 setText(0, mime);
39 setText(1, desc); 39 setText(1, desc);
40 setText(2, file); 40 setText(2, file);
41 setText(3, fsize); 41 setText(3, fsize);
42} 42}
43 43
44bool AttachItem::isParentof(const QValueList<int>&path) 44bool AttachItem::isParentof(const QValueList<int>&path)
45{ 45{
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 }
239 } 239 }
240 break ; 240 break ;
241 241
242 case 1: 242 case 1:
243 if ( ( ( AttachItem* )item )->Partnumber() == -1 ) 243 if ( ( ( AttachItem* )item )->Partnumber() == -1 )
244 { 244 {
245 setText(); 245 setText();
246 } 246 }
247 else 247 else
248 { 248 {
249 if ( m_recMail->Wrapper() != 0l ) 249 if ( m_recMail->Wrapper() != 0l )
250 { // make sure that there is a wrapper , even after delete or simular actions 250 { // make sure that there is a wrapper , even after delete or simular actions
251 browser->setText( m_recMail->Wrapper()->fetchTextPart( m_recMail, m_body->Parts()[ ( ( AttachItem* )item )->Partnumber() ] ) ); 251 browser->setText( m_recMail->Wrapper()->fetchTextPart( m_recMail, m_body->Parts()[ ( ( AttachItem* )item )->Partnumber() ] ) );
252 } 252 }
253 } 253 }
254 break; 254 break;
255 } 255 }
256 delete menu; 256 delete menu;
257} 257}
258 258
259 259
260void ViewMail::setMail(const RecMailP&mail ) 260void ViewMail::setMail(const RecMailP&mail )
261{ 261{
262 262
263 m_recMail = mail; 263 m_recMail = mail;
264 264
265 m_mail[0] = mail->getFrom(); 265 m_mail[0] = mail->getFrom();
266 m_mail[1] = mail->getSubject(); 266 m_mail[1] = mail->getSubject();
267 m_mail[3] = mail->getDate(); 267 m_mail[3] = mail->getDate();
268 m_mail[4] = mail->Msgid(); 268 m_mail[4] = mail->Msgid();
269 269
270 m_mail2[0] = mail->To(); 270 m_mail2[0] = mail->To();
271 m_mail2[1] = mail->CC(); 271 m_mail2[1] = mail->CC();
272 m_mail2[2] = mail->Bcc(); 272 m_mail2[2] = mail->Bcc();
273 273
274 setText(); 274 setText();
275} 275}
276 276
277 277
278 278
279ViewMail::ViewMail( QWidget *parent, const char *name, WFlags fl) 279ViewMail::ViewMail( QWidget *parent, const char *name, WFlags fl)
280 : ViewMailBase(parent, name, fl), _inLoop(false) 280 : ViewMailBase(parent, name, fl), _inLoop(false)
281{ 281{
282 m_gotBody = false; 282 m_gotBody = false;
283 deleted = false; 283 deleted = false;
284 284
285 connect( reply, SIGNAL(activated()), SLOT(slotReply())); 285 connect( reply, SIGNAL(activated()), SLOT(slotReply()));
286 connect( forward, SIGNAL(activated()), SLOT(slotForward())); 286 connect( forward, SIGNAL(activated()), SLOT(slotForward()));
287 connect( deleteMail, SIGNAL( activated() ), SLOT( slotDeleteMail() ) ); 287 connect( deleteMail, SIGNAL( activated() ), SLOT( slotDeleteMail() ) );
288 connect( showHtml, SIGNAL( toggled(bool) ), SLOT( slotShowHtml(bool) ) ); 288 connect( showHtml, SIGNAL( toggled(bool) ), SLOT( slotShowHtml(bool) ) );
289 289
290 attachments->setEnabled(m_gotBody); 290 attachments->setEnabled(m_gotBody);
291 connect( attachments, SIGNAL( clicked(QListViewItem*,const QPoint&, int) ), SLOT( slotItemClicked(QListViewItem*,const QPoint&, int) ) ); 291 connect( attachments, SIGNAL( clicked(QListViewItem*,const QPoint&, int) ), SLOT( slotItemClicked(QListViewItem*,const QPoint&, int) ) );
292 292
293 readConfig(); 293 readConfig();
294 attachments->setSorting(-1); 294 attachments->setSorting(-1);
295} 295}
296 296
297void ViewMail::readConfig() 297void ViewMail::readConfig()
298{ 298{
299 Config cfg( "mail" ); 299 Config cfg( "mail" );
300 cfg.setGroup( "Settings" ); 300 cfg.setGroup( "Settings" );
301 m_showHtml = cfg.readBoolEntry( "showHtml", false ); 301 m_showHtml = cfg.readBoolEntry( "showHtml", false );
302 showHtml->setOn( m_showHtml ); 302 showHtml->setOn( m_showHtml );
303} 303}
304 304
305void ViewMail::setText() 305void ViewMail::setText()
306{ 306{
307 307
308 QString toString; 308 QString toString;
309 QString ccString; 309 QString ccString;
310 QString bccString; 310 QString bccString;
311 311
312 for ( QStringList::Iterator it = ( m_mail2[0] ).begin(); it != ( m_mail2[0] ).end(); ++it ) 312 for ( QStringList::Iterator it = ( m_mail2[0] ).begin(); it != ( m_mail2[0] ).end(); ++it )
313 { 313 {
314 toString += (*it); 314 toString += (*it);
315 } 315 }
316 for ( QStringList::Iterator it = ( m_mail2[1] ).begin(); it != ( m_mail2[1] ).end(); ++it ) 316 for ( QStringList::Iterator it = ( m_mail2[1] ).begin(); it != ( m_mail2[1] ).end(); ++it )
317 { 317 {
318 ccString += (*it); 318 ccString += (*it);
319 } 319 }
320 for ( QStringList::Iterator it = ( m_mail2[2] ).begin(); it != ( m_mail2[2] ).end(); ++it ) 320 for ( QStringList::Iterator it = ( m_mail2[2] ).begin(); it != ( m_mail2[2] ).end(); ++it )
321 { 321 {
322 bccString += (*it); 322 bccString += (*it);
323 } 323 }
324 324
325 setCaption( caption().arg( m_mail[0] ) ); 325 setCaption( caption().arg( m_mail[0] ) );
326 326
327 m_mailHtml = "<html><body>" 327 m_mailHtml = "<html><body>"
328 "<table width=\"100%\" border=\"0\"><tr bgcolor=\"#FFDD76\"><td>" 328 "<table width=\"100%\" border=\"0\"><tr bgcolor=\"#FFDD76\"><td>"
329 "<div align=left><b>" + deHtml( m_mail[1] ) + "</b></div>" 329 "<div align=left><b>" + deHtml( m_mail[1] ) + "</b></div>"
330 "</td></tr><tr bgcolor=\"#EEEEE6\"><td>" 330 "</td></tr><tr bgcolor=\"#EEEEE6\"><td>"
331 "<b>" + tr( "From" ) + ": </b><font color=#6C86C0>" + deHtml( m_mail[0] ) + "</font><br>" 331 "<b>" + tr( "From" ) + ": </b><font color=#6C86C0>" + deHtml( m_mail[0] ) + "</font><br>"
332 "<b>" + tr( "To" ) + ": </b><font color=#6C86C0>" + deHtml( toString ) + "</font><br><b>" + 332 "<b>" + tr( "To" ) + ": </b><font color=#6C86C0>" + deHtml( toString ) + "</font><br><b>" +
333 tr( "Cc" ) + ": </b>" + deHtml( ccString ) + "<br>" 333 tr( "Cc" ) + ": </b>" + deHtml( ccString ) + "<br>"
334 "<b>" + tr( "Date" ) + ": </b> " + m_mail[3] + 334 "<b>" + tr( "Date" ) + ": </b> " + m_mail[3] +
335 "</td></tr></table><font face=fixed>"; 335 "</td></tr></table><font face=fixed>";
336 336
337 if ( !m_showHtml ) 337 if ( !m_showHtml )
338 { 338 {
339 browser->setText( QString( m_mailHtml) + deHtml( m_mail[2] ) + "</font></html>" ); 339 browser->setText( QString( m_mailHtml) + deHtml( m_mail[2] ) + "</font></html>" );
340 } 340 }
341 else 341 else
342 { 342 {
343 browser->setText( QString( m_mailHtml) + m_mail[2] + "</font></html>" ); 343 browser->setText( QString( m_mailHtml) + m_mail[2] + "</font></html>" );
344 } 344 }
345 // remove later in favor of a real handling 345 // remove later in favor of a real handling
346 m_gotBody = true; 346 m_gotBody = true;
347} 347}
348 348
349 349
350ViewMail::~ViewMail() 350ViewMail::~ViewMail()
351{ 351{
352 m_recMail->Wrapper()->cleanMimeCache(); 352 m_recMail->Wrapper()->cleanMimeCache();
353 hide(); 353 hide();
354} 354}
355 355
356void ViewMail::hide() 356void ViewMail::hide()
357{ 357{
358 QWidget::hide(); 358 QWidget::hide();
359 359
360 if (_inLoop) 360 if (_inLoop)
361 { 361 {
362 _inLoop = false; 362 _inLoop = false;
363 qApp->exit_loop(); 363 qApp->exit_loop();
364 364
365 } 365 }
366 366
367} 367}
368 368
369void ViewMail::exec() 369void ViewMail::exec()
370{ 370{
371 show(); 371 show();
372 372
373 if (!_inLoop) 373 if (!_inLoop)
374 { 374 {
375 _inLoop = true; 375 _inLoop = true;
376 qApp->enter_loop(); 376 qApp->enter_loop();
377 } 377 }
378 378
379} 379}
380 380
381QString ViewMail::deHtml(const QString &string) 381QString ViewMail::deHtml(const QString &string)
382{ 382{
383 QString string_ = string; 383 QString string_ = string;
384 string_.replace(QRegExp("&"), "&amp;"); 384 string_.replace(QRegExp("&"), "&amp;");
385 string_.replace(QRegExp("<"), "&lt;"); 385 string_.replace(QRegExp("<"), "&lt;");
386 string_.replace(QRegExp(">"), "&gt;"); 386 string_.replace(QRegExp(">"), "&gt;");
387 string_.replace(QRegExp("\\n"), "<br>"); 387 string_.replace(QRegExp("\\n"), "<br>");
388 return string_; 388 return string_;
389} 389}
390 390
391void ViewMail::slotReply() 391void ViewMail::slotReply()
392{ 392{
393 if (!m_gotBody) 393 if (!m_gotBody)
394 { 394 {
395 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot reply yet."), tr("Ok")); 395 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot reply yet."), tr("Ok"));
396 return; 396 return;
397 } 397 }
398 398
399 QString rtext; 399 QString rtext;
400 rtext += QString("* %1 wrote on %2:\n") // no i18n on purpose 400 rtext += QString("* %1 wrote on %2:\n") // no i18n on purpose
401 .arg( m_mail[0] ) 401 .arg( m_mail[0] )
402 .arg( m_mail[3] ); 402 .arg( m_mail[3] );
403 403
404 QString text = m_mail[2]; 404 QString text = m_mail[2];
405 QStringList lines = QStringList::split(QRegExp("\\n"), text); 405 QStringList lines = QStringList::split(QRegExp("\\n"), text);
406 QStringList::Iterator it; 406 QStringList::Iterator it;
407 for (it = lines.begin(); it != lines.end(); it++) 407 for (it = lines.begin(); it != lines.end(); it++)
408 { 408 {
409 rtext += "> " + *it + "\n"; 409 rtext += "> " + *it + "\n";
410 } 410 }
411 rtext += "\n"; 411 rtext += "\n";
412 412
413 QString prefix; 413 QString prefix;
414 if ( m_mail[1].find(QRegExp("^Re: .*$")) != -1) prefix = ""; 414 if ( m_mail[1].find(QRegExp("^Re: .*$")) != -1) prefix = "";
415 else prefix = "Re: "; // no i18n on purpose 415 else prefix = "Re: "; // no i18n on purpose
416 416
417 Settings *settings = new Settings(); 417 Settings *settings = new Settings();
418 ComposeMail composer( settings ,this, 0, true); 418 ComposeMail composer( settings ,this, 0, true);
419 if (m_recMail->Replyto().isEmpty()) { 419 if (m_recMail->Replyto().isEmpty()) {
420 composer.setTo( m_recMail->getFrom()); 420 composer.setTo( m_recMail->getFrom());
421 } else { 421 } else {
422 composer.setTo( m_recMail->Replyto()); 422 composer.setTo( m_recMail->Replyto());
423 } 423 }
424 composer.setSubject( prefix + m_mail[1] ); 424 composer.setSubject( prefix + m_mail[1] );
425 composer.setMessage( rtext ); 425 composer.setMessage( rtext );
426 composer.setInReplyTo(m_recMail->Msgid()); 426 composer.setInReplyTo(m_recMail->Msgid());
427 427
428 if ( QDialog::Accepted == QPEApplication::execDialog( &composer ) ) 428 if ( QDialog::Accepted == QPEApplication::execDialog( &composer ) )
429 { 429 {
430 m_recMail->Wrapper()->answeredMail(m_recMail); 430 m_recMail->Wrapper()->answeredMail(m_recMail);
431 } 431 }
432} 432}
433 433
434void ViewMail::slotForward() 434void ViewMail::slotForward()
435{ 435{
436 if (!m_gotBody) 436 if (!m_gotBody)
437 { 437 {
438 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot forward yet."), tr("Ok")); 438 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot forward yet."), tr("Ok"));
439 return; 439 return;
440 } 440 }
441 441
442 QString ftext; 442 QString ftext;
443 ftext += QString("\n----- Forwarded message from %1 -----\n\n") 443 ftext += QString("\n----- Forwarded message from %1 -----\n\n")
444 .arg( m_mail[0] ); 444 .arg( m_mail[0] );
445 if (!m_mail[3].isNull()) 445 if (!m_mail[3].isNull())
446 ftext += QString("Date: %1\n") 446 ftext += QString("Date: %1\n")
447 .arg( m_mail[3] ); 447 .arg( m_mail[3] );
448 if (!m_mail[0].isNull()) 448 if (!m_mail[0].isNull())
449 ftext += QString("From: %1\n") 449 ftext += QString("From: %1\n")
450 .arg( m_mail[0] ); 450 .arg( m_mail[0] );
451 if (!m_mail[1].isNull()) 451 if (!m_mail[1].isNull())
452 ftext += QString("Subject: %1\n") 452 ftext += QString("Subject: %1\n")
453 .arg( m_mail[1] ); 453 .arg( m_mail[1] );
454 454
455 ftext += QString("\n%1\n") 455 ftext += QString("\n%1\n")
456 .arg( m_mail[2]); 456 .arg( m_mail[2]);
457 457
458 ftext += QString("----- End forwarded message -----\n"); 458 ftext += QString("----- End forwarded message -----\n");
459 459
460 Settings *settings = new Settings(); 460 Settings *settings = new Settings();
461 ComposeMail composer( settings ,this, 0, true); 461 ComposeMail composer( settings ,this, 0, true);
462 composer.setSubject( "Fwd: " + m_mail[1] ); 462 composer.setSubject( "Fwd: " + m_mail[1] );
463 composer.setMessage( ftext ); 463 composer.setMessage( ftext );
464 if ( QDialog::Accepted == QPEApplication::execDialog( &composer )) 464 if ( QDialog::Accepted == QPEApplication::execDialog( &composer ))
465 { 465 {
466 } 466 }
467} 467}
468 468
469void ViewMail::slotDeleteMail( ) 469void ViewMail::slotDeleteMail( )
470{ 470{
471 if ( QMessageBox::warning(this, tr("Delete Mail"), QString( tr("<p>Do you really want to delete this mail? <br><br>" ) + m_mail[0] + " - " + m_mail[1] ) , QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes ) 471 if ( QMessageBox::warning(this, tr("Delete Mail"), QString( tr("<p>Do you really want to delete this mail? <br><br>" ) + m_mail[0] + " - " + m_mail[1] ) , QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes )
472 { 472 {
473 m_recMail->Wrapper()->deleteMail( m_recMail ); 473 m_recMail->Wrapper()->deleteMail( m_recMail );
474 hide(); 474 hide();
475 deleted = true; 475 deleted = true;
476 } 476 }
477} 477}
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,272 +1,272 @@
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;
132 QFileInfo fi(file); 132 QFileInfo fi(file);
133 133
134 LineEdit1->setText( file); 134 LineEdit1->setText( file);
135 OwnerLineEdit->setText( fi.owner()); 135 OwnerLineEdit->setText( fi.owner());
136 GroupLineEdit->setText( fi.group()); 136 GroupLineEdit->setText( fi.group());
137 137
138 if( fi.permission( QFileInfo::ReadUser)) { CheckBox1->setChecked(true); } 138 if( fi.permission( QFileInfo::ReadUser)) { CheckBox1->setChecked(true); }
139 if( fi.permission( QFileInfo::WriteUser)) { CheckBox1_2->setChecked(true); } 139 if( fi.permission( QFileInfo::WriteUser)) { CheckBox1_2->setChecked(true); }
140 if( fi.permission( QFileInfo::ExeUser)) { CheckBox1_3->setChecked(true); } 140 if( fi.permission( QFileInfo::ExeUser)) { CheckBox1_3->setChecked(true); }
141 141
142 if( fi.permission( QFileInfo::ReadGroup)) { CheckBox1_4->setChecked(true); } 142 if( fi.permission( QFileInfo::ReadGroup)) { CheckBox1_4->setChecked(true); }
143 if( fi.permission( QFileInfo::WriteGroup)) { CheckBox1_5->setChecked(true); } 143 if( fi.permission( QFileInfo::WriteGroup)) { CheckBox1_5->setChecked(true); }
144 if( fi.permission( QFileInfo::ExeGroup)) { CheckBox1_6->setChecked(true); } 144 if( fi.permission( QFileInfo::ExeGroup)) { CheckBox1_6->setChecked(true); }
145 145
146 if( fi.permission( QFileInfo::ReadOther)) { CheckBox1_7->setChecked(true); } 146 if( fi.permission( QFileInfo::ReadOther)) { CheckBox1_7->setChecked(true); }
147 if( fi.permission( QFileInfo::WriteOther)) { CheckBox1_8->setChecked(true); } 147 if( fi.permission( QFileInfo::WriteOther)) { CheckBox1_8->setChecked(true); }
148 if( fi.permission( QFileInfo::ExeOther)) { CheckBox1_8_2->setChecked(true); } 148 if( fi.permission( QFileInfo::ExeOther)) { CheckBox1_8_2->setChecked(true); }
149 149
150 stat(file.latin1(), &buf); 150 stat(file.latin1(), &buf);
151 mode = buf.st_mode; 151 mode = buf.st_mode;
152 modeStr.sprintf("%#o", buf.st_mode & ~(S_IFMT) ); 152 modeStr.sprintf("%#o", buf.st_mode & ~(S_IFMT) );
153 ModeLine->setText(modeStr); 153 ModeLine->setText(modeStr);
154 bool ok; 154 bool ok;
155 i_mode = modeStr.toInt(&ok,10); 155 i_mode = modeStr.toInt(&ok,10);
156 156
157} 157}
158 158
159/* 159/*
160 * Destroys the object and frees any allocated resources 160 * Destroys the object and frees any allocated resources
161 */ 161 */
162filePermissions::~filePermissions() 162filePermissions::~filePermissions()
163{ 163{
164} 164}
165 165
166 166
167// might this be better as a callback routine??? 167// might this be better as a callback routine???
168void filePermissions::ownReadCheck() { 168void filePermissions::ownReadCheck() {
169 if(CheckBox1->isChecked()) { i_mode +=400; } 169 if(CheckBox1->isChecked()) { i_mode +=400; }
170 else i_mode -=400; 170 else i_mode -=400;
171 modeStr.sprintf("0%d",i_mode); 171 modeStr.sprintf("0%d",i_mode);
172 ModeLine->setText( modeStr); 172 ModeLine->setText( modeStr);
173// 0400 173// 0400
174} 174}
175 175
176void filePermissions::ownWriteCheck() { 176void filePermissions::ownWriteCheck() {
177 if(CheckBox1_2->isChecked()) { i_mode +=200; } 177 if(CheckBox1_2->isChecked()) { i_mode +=200; }
178 else i_mode -=200; 178 else i_mode -=200;
179 modeStr.sprintf("0%d",i_mode); 179 modeStr.sprintf("0%d",i_mode);
180 ModeLine->setText(modeStr); 180 ModeLine->setText(modeStr);
181// 0200 181// 0200
182} 182}
183 183
184void filePermissions::ownExeCheck() { 184void filePermissions::ownExeCheck() {
185 if(CheckBox1_3->isChecked()) { i_mode +=100; } 185 if(CheckBox1_3->isChecked()) { i_mode +=100; }
186 else i_mode -=100; 186 else i_mode -=100;
187 modeStr.sprintf("0%d",i_mode); 187 modeStr.sprintf("0%d",i_mode);
188 ModeLine->setText(modeStr); 188 ModeLine->setText(modeStr);
189// 0100 189// 0100
190} 190}
191 191
192void filePermissions::grpReadCheck() { 192void filePermissions::grpReadCheck() {
193 if(CheckBox1_4->isChecked()) { i_mode +=40; } 193 if(CheckBox1_4->isChecked()) { i_mode +=40; }
194 else i_mode -=40; 194 else i_mode -=40;
195 modeStr.sprintf("0%d",i_mode); 195 modeStr.sprintf("0%d",i_mode);
196 ModeLine->setText(modeStr); 196 ModeLine->setText(modeStr);
197// 0040 197// 0040
198} 198}
199 199
200void filePermissions::grpWriteCheck() { 200void filePermissions::grpWriteCheck() {
201 if(CheckBox1_5->isChecked()) { i_mode +=20; } 201 if(CheckBox1_5->isChecked()) { i_mode +=20; }
202 else i_mode -=20; 202 else i_mode -=20;
203 modeStr.sprintf("0%d",i_mode); 203 modeStr.sprintf("0%d",i_mode);
204 ModeLine->setText(modeStr); 204 ModeLine->setText(modeStr);
205// 0020 205// 0020
206} 206}
207 207
208void filePermissions::grpExeCheck() { 208void filePermissions::grpExeCheck() {
209 if(CheckBox1_6->isChecked()) { i_mode +=10; } 209 if(CheckBox1_6->isChecked()) { i_mode +=10; }
210 else i_mode -=10; 210 else i_mode -=10;
211 modeStr.sprintf("0%d",i_mode); 211 modeStr.sprintf("0%d",i_mode);
212 ModeLine->setText(modeStr); 212 ModeLine->setText(modeStr);
213// 0010 213// 0010
214} 214}
215 215
216void filePermissions::wrldReadCheck() { 216void filePermissions::wrldReadCheck() {
217 if(CheckBox1_7->isChecked()) { i_mode +=4; } 217 if(CheckBox1_7->isChecked()) { i_mode +=4; }
218 else i_mode -=4; 218 else i_mode -=4;
219 modeStr.sprintf("0%d",i_mode); 219 modeStr.sprintf("0%d",i_mode);
220 ModeLine->setText(modeStr); 220 ModeLine->setText(modeStr);
221// 0004 221// 0004
222} 222}
223 223
224void filePermissions::wrldWriteCheck() { 224void filePermissions::wrldWriteCheck() {
225 if(CheckBox1_8->isChecked()) { i_mode +=2; } 225 if(CheckBox1_8->isChecked()) { i_mode +=2; }
226 else i_mode -=2; 226 else i_mode -=2;
227 modeStr.sprintf("0%d",i_mode); 227 modeStr.sprintf("0%d",i_mode);
228 ModeLine->setText(modeStr); 228 ModeLine->setText(modeStr);
229// 0002 229// 0002
230} 230}
231 231
232void filePermissions::wrldExeCheck() { 232void filePermissions::wrldExeCheck() {
233 if(CheckBox1_8_2->isChecked()) { i_mode +=1; } 233 if(CheckBox1_8_2->isChecked()) { i_mode +=1; }
234 else i_mode -=1; 234 else i_mode -=1;
235 modeStr.sprintf("0%d",i_mode); 235 modeStr.sprintf("0%d",i_mode);
236 ModeLine->setText(modeStr); 236 ModeLine->setText(modeStr);
237// 0001 237// 0001
238} 238}
239 239
240void filePermissions::accept() { 240void filePermissions::accept() {
241 QFileInfo fi(file); 241 QFileInfo fi(file);
242 struct passwd *pwd=0; 242 struct passwd *pwd=0;
243 struct group *grp=0; 243 struct group *grp=0;
244 pwd = getpwnam(OwnerLineEdit->text().latin1() ); 244 pwd = getpwnam(OwnerLineEdit->text().latin1() );
245 if(pwd == NULL) { 245 if(pwd == NULL) {
246 perror("getpwnam"); 246 perror("getpwnam");
247 QMessageBox::warning(this,tr("Warning"),tr("Error- no user")); 247 QMessageBox::warning(this,tr("Warning"),tr("Error- no user"));
248 return; 248 return;
249 } else { 249 } else {
250 grp = getgrnam(GroupLineEdit->text().latin1()); 250 grp = getgrnam(GroupLineEdit->text().latin1());
251 if(grp==NULL) { 251 if(grp==NULL) {
252 perror("getgrnam"); 252 perror("getgrnam");
253 QMessageBox::warning(this,tr("Warning"),tr("Error- no group")); 253 QMessageBox::warning(this,tr("Warning"),tr("Error- no group"));
254 return; 254 return;
255 } 255 }
256 if( chown( file.latin1(), pwd->pw_uid, grp->gr_gid) <0) { 256 if( chown( file.latin1(), pwd->pw_uid, grp->gr_gid) <0) {
257 perror("chown"); 257 perror("chown");
258 QMessageBox::warning(this,tr("Warning"),tr("Error setting ownership or group")); 258 QMessageBox::warning(this,tr("Warning"),tr("Error setting ownership or group"));
259 return; 259 return;
260 } 260 }
261 bool ok; 261 bool ok;
262 moder = modeStr.toUInt(&ok,8); 262 moder = modeStr.toUInt(&ok,8);
263 if (!isRemote) { 263 if (!isRemote) {
264 if( chmod( file.latin1(), moder) < 0) { 264 if( chmod( file.latin1(), moder) < 0) {
265 perror("chmod"); 265 perror("chmod");
266 QMessageBox::warning(this,tr("Warning"),tr("Error setting mode")); 266 QMessageBox::warning(this,tr("Warning"),tr("Error setting mode"));
267 return; 267 return;
268 } 268 }
269 } 269 }
270} 270}
271 close(); 271 close();
272} 272}
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,1529 +1,1532 @@
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);
161 164
162 Local_View = new QListView( tab, "Local_View" ); 165 Local_View = new QListView( tab, "Local_View" );
163// Local_View->setResizePolicy( QListView::AutoOneFit ); 166// Local_View->setResizePolicy( QListView::AutoOneFit );
164 Local_View->addColumn( tr("File"),150); 167 Local_View->addColumn( tr("File"),150);
165 Local_View->addColumn( tr("Date"),-1); 168 Local_View->addColumn( tr("Date"),-1);
166 Local_View->setColumnAlignment(1,QListView::AlignRight); 169 Local_View->setColumnAlignment(1,QListView::AlignRight);
167 Local_View->addColumn( tr("Size"),-1); 170 Local_View->addColumn( tr("Size"),-1);
168 Local_View->setColumnAlignment(2,QListView::AlignRight); 171 Local_View->setColumnAlignment(2,QListView::AlignRight);
169 Local_View->setAllColumnsShowFocus(TRUE); 172 Local_View->setAllColumnsShowFocus(TRUE);
170 173
171 Local_View->setMultiSelection( TRUE); 174 Local_View->setMultiSelection( TRUE);
172 Local_View->setSelectionMode(QListView::Extended); 175 Local_View->setSelectionMode(QListView::Extended);
173 Local_View->setFocusPolicy(QWidget::ClickFocus); 176 Local_View->setFocusPolicy(QWidget::ClickFocus);
174 177
175 QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold); 178 QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold);
176 179
177 tabLayout->addWidget( Local_View, 0, 0 ); 180 tabLayout->addWidget( Local_View, 0, 0 );
178 181
179 connect( Local_View, SIGNAL( clicked(QListViewItem*)), 182 connect( Local_View, SIGNAL( clicked(QListViewItem*)),
180 this,SLOT( localListClicked(QListViewItem*)) ); 183 this,SLOT( localListClicked(QListViewItem*)) );
181// connect( Local_View, SIGNAL( doubleClicked(QListViewItem*)), 184// connect( Local_View, SIGNAL( doubleClicked(QListViewItem*)),
182// this,SLOT( localListClicked(QListViewItem*)) ); 185// this,SLOT( localListClicked(QListViewItem*)) );
183 connect( Local_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), 186 connect( Local_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
184 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) ); 187 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) );
185 188
186 TabWidget->insertTab( tab, tr( "Local" ) ); 189 TabWidget->insertTab( tab, tr( "Local" ) );
187 190
188 tab_2 = new QWidget( TabWidget, "tab_2" ); 191 tab_2 = new QWidget( TabWidget, "tab_2" );
189 tabLayout_2 = new QGridLayout( tab_2 ); 192 tabLayout_2 = new QGridLayout( tab_2 );
190 tabLayout_2->setSpacing( 2); 193 tabLayout_2->setSpacing( 2);
191 tabLayout_2->setMargin( 2); 194 tabLayout_2->setMargin( 2);
192 195
193 Remote_View = new QListView( tab_2, "Remote_View" ); 196 Remote_View = new QListView( tab_2, "Remote_View" );
194 Remote_View->addColumn( tr("File"),150); 197 Remote_View->addColumn( tr("File"),150);
195 Remote_View->addColumn( tr("Date"),-1); 198 Remote_View->addColumn( tr("Date"),-1);
196// Remote_View->setColumnAlignment(1,QListView::AlignRight); 199// Remote_View->setColumnAlignment(1,QListView::AlignRight);
197 Remote_View->addColumn( tr("Size"),-1); 200 Remote_View->addColumn( tr("Size"),-1);
198 Remote_View->setColumnAlignment(2,QListView::AlignRight); 201 Remote_View->setColumnAlignment(2,QListView::AlignRight);
199 Remote_View->setColumnAlignment(3,QListView::AlignCenter); 202 Remote_View->setColumnAlignment(3,QListView::AlignCenter);
200 Remote_View->addColumn( tr("Dir"),-1); 203 Remote_View->addColumn( tr("Dir"),-1);
201 Remote_View->setColumnAlignment(4,QListView::AlignRight); 204 Remote_View->setColumnAlignment(4,QListView::AlignRight);
202 Remote_View->setAllColumnsShowFocus(TRUE); 205 Remote_View->setAllColumnsShowFocus(TRUE);
203 206
204 Remote_View->setMultiSelection( FALSE); 207 Remote_View->setMultiSelection( FALSE);
205 Remote_View->setSelectionMode(QListView::Extended); 208 Remote_View->setSelectionMode(QListView::Extended);
206 Remote_View->setFocusPolicy(QWidget::ClickFocus); 209 Remote_View->setFocusPolicy(QWidget::ClickFocus);
207 210
208 QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold); 211 QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold);
209 212
210 connect( Remote_View, SIGNAL( clicked(QListViewItem*)), 213 connect( Remote_View, SIGNAL( clicked(QListViewItem*)),
211 this,SLOT( remoteListClicked(QListViewItem*)) ); 214 this,SLOT( remoteListClicked(QListViewItem*)) );
212 connect( Remote_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), 215 connect( Remote_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
213 this,SLOT( RemoteListPressed(int,QListViewItem*,const QPoint&,int)) ); 216 this,SLOT( RemoteListPressed(int,QListViewItem*,const QPoint&,int)) );
214 217
215 tabLayout_2->addWidget( Remote_View, 0, 0 ); 218 tabLayout_2->addWidget( Remote_View, 0, 0 );
216 219
217 TabWidget->insertTab( tab_2, tr( "Remote" ) ); 220 TabWidget->insertTab( tab_2, tr( "Remote" ) );
218 221
219 tab_3 = new QWidget( TabWidget, "tab_3" ); 222 tab_3 = new QWidget( TabWidget, "tab_3" );
220 tabLayout_3 = new QGridLayout( tab_3 ); 223 tabLayout_3 = new QGridLayout( tab_3 );
221 tabLayout_3->setSpacing( 2); 224 tabLayout_3->setSpacing( 2);
222 tabLayout_3->setMargin( 2); 225 tabLayout_3->setMargin( 2);
223 226
224 TextLabel1 = new QLabel( tab_3, "TextLabel1" ); 227 TextLabel1 = new QLabel( tab_3, "TextLabel1" );
225 TextLabel1->setText( tr( "Username" ) ); 228 TextLabel1->setText( tr( "Username" ) );
226 tabLayout_3->addMultiCellWidget( TextLabel1, 0, 0, 0, 1 ); 229 tabLayout_3->addMultiCellWidget( TextLabel1, 0, 0, 0, 1 );
227 230
228 UsernameComboBox = new QComboBox( FALSE, tab_3, "UsernameComboBox" ); 231 UsernameComboBox = new QComboBox( FALSE, tab_3, "UsernameComboBox" );
229 UsernameComboBox->setEditable(TRUE); 232 UsernameComboBox->setEditable(TRUE);
230 tabLayout_3->addMultiCellWidget( UsernameComboBox, 1, 1, 0, 1 ); 233 tabLayout_3->addMultiCellWidget( UsernameComboBox, 1, 1, 0, 1 );
231 234
232 connect( UsernameComboBox,SIGNAL(textChanged(const QString&)),this, 235 connect( UsernameComboBox,SIGNAL(textChanged(const QString&)),this,
233 SLOT( UsernameComboBoxEdited(const QString&) )); 236 SLOT( UsernameComboBoxEdited(const QString&) ));
234 237
235 TextLabel2 = new QLabel( tab_3, "TextLabel2" ); 238 TextLabel2 = new QLabel( tab_3, "TextLabel2" );
236 TextLabel2->setText( tr( "Password" ) ); 239 TextLabel2->setText( tr( "Password" ) );
237 tabLayout_3->addMultiCellWidget( TextLabel2, 0, 0, 2, 3 ); 240 tabLayout_3->addMultiCellWidget( TextLabel2, 0, 0, 2, 3 );
238 241
239 PasswordEdit = new QLineEdit( "", tab_3, "PasswordComboBox" ); 242 PasswordEdit = new QLineEdit( "", tab_3, "PasswordComboBox" );
240 PasswordEdit->setEchoMode(QLineEdit::Password); 243 PasswordEdit->setEchoMode(QLineEdit::Password);
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() );
966 delete m; 969 delete m;
967} 970}
968 971
969void OpieFtp::localMakDir() 972void OpieFtp::localMakDir()
970{ 973{
971 InputDialog *fileDlg; 974 InputDialog *fileDlg;
972 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); 975 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0);
973 fileDlg->exec(); 976 fileDlg->exec();
974 if( fileDlg->result() == 1 ) { 977 if( fileDlg->result() == 1 ) {
975 QString filename = fileDlg->LineEdit1->text(); 978 QString filename = fileDlg->LineEdit1->text();
976 currentDir.mkdir( currentDir.canonicalPath()+"/"+filename); 979 currentDir.mkdir( currentDir.canonicalPath()+"/"+filename);
977 } 980 }
978 populateLocalView(); 981 populateLocalView();
979} 982}
980 983
981void OpieFtp::localDelete() 984void OpieFtp::localDelete()
982{ 985{
983 QList<QListViewItem> * getSelectedItems( QListView * Local_View ); 986 QList<QListViewItem> * getSelectedItems( QListView * Local_View );
984 QListViewItemIterator it( Local_View ); 987 QListViewItemIterator it( Local_View );
985 for ( ; it.current(); ++it ) { 988 for ( ; it.current(); ++it ) {
986 if ( it.current()->isSelected() ) { 989 if ( it.current()->isSelected() ) {
987 QString f = it.current()->text(0); 990 QString f = it.current()->text(0);
988 it.current()->setSelected(FALSE); 991 it.current()->setSelected(FALSE);
989 992
990// QString f = Local_View->currentItem()->text(0); 993// QString f = Local_View->currentItem()->text(0);
991 if(QDir(f).exists() ) { 994 if(QDir(f).exists() ) {
992 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+ 995 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+
993 tr(" ?\nIt must be empty"),tr("Yes"),tr("No"),0,0,1) ) { 996 tr(" ?\nIt must be empty"),tr("Yes"),tr("No"),0,0,1) ) {
994 case 0: { 997 case 0: {
995 f=currentDir.canonicalPath()+"/"+f; 998 f=currentDir.canonicalPath()+"/"+f;
996 QString cmd="rmdir "+f; 999 QString cmd="rmdir "+f;
997 system( cmd.latin1()); 1000 system( cmd.latin1());
998 } 1001 }
999 break; 1002 break;
1000 case 1: 1003 case 1:
1001 // exit 1004 // exit
1002 break; 1005 break;
1003 }; 1006 };
1004 1007
1005 } else { 1008 } else {
1006 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f 1009 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f
1007 +" ?",tr("Yes"),tr("No"),0,0,1) ) { 1010 +" ?",tr("Yes"),tr("No"),0,0,1) ) {
1008 case 0: { 1011 case 0: {
1009 f=currentDir.canonicalPath()+"/"+f; 1012 f=currentDir.canonicalPath()+"/"+f;
1010 QString cmd="rm "+f; 1013 QString cmd="rm "+f;
1011 system( cmd.latin1()); 1014 system( cmd.latin1());
1012 } 1015 }
1013 break; 1016 break;
1014 case 1: 1017 case 1:
1015 // exit 1018 // exit
1016 break; 1019 break;
1017 }; 1020 };
1018 } 1021 }
1019 } 1022 }
1020 } 1023 }
1021 populateLocalView(); 1024 populateLocalView();
1022 1025
1023} 1026}
1024 1027
1025void OpieFtp::remoteMakDir() 1028void OpieFtp::remoteMakDir()
1026{ 1029{
1027 InputDialog *fileDlg; 1030 InputDialog *fileDlg;
1028 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); 1031 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0);
1029 fileDlg->exec(); 1032 fileDlg->exec();
1030 if( fileDlg->result() == 1 ) { 1033 if( fileDlg->result() == 1 ) {
1031 QString filename = fileDlg->LineEdit1->text();//+".playlist"; 1034 QString filename = fileDlg->LineEdit1->text();//+".playlist";
1032 QString tmp=currentRemoteDir+filename; 1035 QString tmp=currentRemoteDir+filename;
1033// QCopEnvelope ( "QPE/System", "busy()" ); 1036// QCopEnvelope ( "QPE/System", "busy()" );
1034 if(FtpMkdir( tmp.latin1(), conn) == 0) { 1037 if(FtpMkdir( tmp.latin1(), conn) == 0) {
1035 QString msg; 1038 QString msg;
1036 msg.sprintf(tr("Unable to make directory\n")+"%s",FtpLastResponse(conn)); 1039 msg.sprintf(tr("Unable to make directory\n")+"%s",FtpLastResponse(conn));
1037 msg.replace(QRegExp(":"),"\n"); 1040 msg.replace(QRegExp(":"),"\n");
1038 QMessageBox::message(tr("Note"),msg); 1041 QMessageBox::message(tr("Note"),msg);
1039 } 1042 }
1040// QCopEnvelope ( "QPE/System", "notBusy()" ); 1043// QCopEnvelope ( "QPE/System", "notBusy()" );
1041 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1044 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1042 } 1045 }
1043} 1046}
1044 1047
1045void OpieFtp::remoteDelete() 1048void OpieFtp::remoteDelete()
1046{ 1049{
1047 QList<QListViewItem> * getSelectedItems( QListView * Remote_View ); 1050 QList<QListViewItem> * getSelectedItems( QListView * Remote_View );
1048 QListViewItemIterator it( Remote_View ); 1051 QListViewItemIterator it( Remote_View );
1049 for ( ; it.current(); ++it ) { 1052 for ( ; it.current(); ++it ) {
1050 if ( it.current()->isSelected() ) { 1053 if ( it.current()->isSelected() ) {
1051 QString f = it.current()->text(0); 1054 QString f = it.current()->text(0);
1052// QString f = Remote_View->currentItem()->text(0); 1055// QString f = Remote_View->currentItem()->text(0);
1053// QCopEnvelope ( "QPE/System", "busy()" ); 1056// QCopEnvelope ( "QPE/System", "busy()" );
1054 if( f.right(1) =="/") { 1057 if( f.right(1) =="/") {
1055 QString path= currentRemoteDir+f; 1058 QString path= currentRemoteDir+f;
1056 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?" 1059 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?"
1057 ,tr("Yes"),tr("No"),0,0,1) ) { 1060 ,tr("Yes"),tr("No"),0,0,1) ) {
1058 case 0: { 1061 case 0: {
1059 f=currentDir.canonicalPath()+"/"+f; 1062 f=currentDir.canonicalPath()+"/"+f;
1060 if(FtpRmdir( path.latin1(), conn) ==0) { 1063 if(FtpRmdir( path.latin1(), conn) ==0) {
1061 QString msg; 1064 QString msg;
1062 msg.sprintf(tr("Unable to remove directory\n")+"%s",FtpLastResponse(conn)); 1065 msg.sprintf(tr("Unable to remove directory\n")+"%s",FtpLastResponse(conn));
1063 msg.replace(QRegExp(":"),"\n"); 1066 msg.replace(QRegExp(":"),"\n");
1064 QMessageBox::message(tr("Note"),msg); 1067 QMessageBox::message(tr("Note"),msg);
1065 } 1068 }
1066 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1069 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1067 } 1070 }
1068 break; 1071 break;
1069 }; 1072 };
1070 } else { 1073 } else {
1071 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?" 1074 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?"
1072 ,tr("Yes"),tr("No"),0,0,1) ) { 1075 ,tr("Yes"),tr("No"),0,0,1) ) {
1073 case 0: { 1076 case 0: {
1074 QString path= currentRemoteDir+f; 1077 QString path= currentRemoteDir+f;
1075 if(FtpDelete( path.latin1(), conn)==0) { 1078 if(FtpDelete( path.latin1(), conn)==0) {
1076 QString msg; 1079 QString msg;
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
@@ -1,221 +1,221 @@
1/* 1/*
2               =. This file is part of the OPIE Project 2               =. This file is part of the OPIE Project
3             .=l. Copyright (c) 2002 Maximilian Reiss <max.reiss@gmx.de> 3             .=l. Copyright (c) 2002 Maximilian Reiss <max.reiss@gmx.de>
4           .>+-= 4           .>+-=
5 _;:,     .>    :=|. This library is free software; you can 5 _;:,     .>    :=|. This library is free software; you can
6.> <,   >  .   <= redistribute it and/or modify it under 6.> <,   >  .   <= redistribute it and/or modify it under
7:=1 )Y*s>-.--   : the terms of the GNU Library General Public 7:=1 )Y*s>-.--   : the terms of the GNU Library General Public
8.="- .-=="i,     .._ License as published by the Free Software 8.="- .-=="i,     .._ License as published by the Free Software
9 - .   .-<_>     .<> Foundation; either version 2 of the License, 9 - .   .-<_>     .<> Foundation; either version 2 of the License,
10     ._= =}       : or (at your option) any later version. 10     ._= =}       : or (at your option) any later version.
11    .%+i>       _;_. 11    .%+i>       _;_.
12    .i_,=:_.      -<s. This library is distributed in the hope that 12    .i_,=:_.      -<s. This library is distributed in the hope that
13     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 13     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
14    : ..    .:,     . . . without even the implied warranty of 14    : ..    .:,     . . . without even the implied warranty of
15    =_        +     =;=| MERCHANTABILITY or FITNESS FOR A 15    =_        +     =;=| MERCHANTABILITY or FITNESS FOR A
16  _.=:.       :    :=>: PARTICULAR PURPOSE. See the GNU 16  _.=:.       :    :=>: PARTICULAR PURPOSE. See the GNU
17..}^=.=       =       ; Library General Public License for more 17..}^=.=       =       ; Library General Public License for more
18++=   -.     .     .: details. 18++=   -.     .     .: details.
19 :     =  ...= . :.=- 19 :     =  ...= . :.=-
20 -.   .:....=;==+<; You should have received a copy of the GNU 20 -.   .:....=;==+<; You should have received a copy of the GNU
21  -_. . .   )=.  = Library General Public License along with 21  -_. . .   )=.  = Library General Public License along with
22    --        :-= this library; see the file COPYING.LIB. 22    --        :-= this library; see the file COPYING.LIB.
23 If not, write to the Free Software Foundation, 23 If not, write to the Free Software Foundation,
24 Inc., 59 Temple Place - Suite 330, 24 Inc., 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29 29
30#include "bluezapplet.h" 30#include "bluezapplet.h"
31#include <qapplication.h> 31#include <qapplication.h>
32 32
33#include <qpe/qcopenvelope_qws.h> 33#include <qpe/qcopenvelope_qws.h>
34#include <qpe/config.h> 34#include <qpe/config.h>
35#include <qpe/resource.h> 35#include <qpe/resource.h>
36 36
37#include <opie2/odevice.h> 37#include <opie2/odevice.h>
38 38
39#include <qpoint.h> 39#include <qpoint.h>
40#include <qpainter.h> 40#include <qpainter.h>
41#include <qlayout.h> 41#include <qlayout.h>
42#include <qframe.h> 42#include <qframe.h>
43#include <qpixmap.h> 43#include <qpixmap.h>
44#include <qstring.h> 44#include <qstring.h>
45#include <qtimer.h> 45#include <qtimer.h>
46#include <qpopupmenu.h> 46#include <qpopupmenu.h>
47 47
48#include <device.h> 48#include <device.h>
49 49
50using namespace Opie::Core; 50using namespace Opie::Core;
51 51
52namespace OpieTooth { 52namespace OpieTooth {
53 53
54 BluezApplet::BluezApplet( QWidget *parent, const char *name ) : QWidget( parent, name ) { 54 BluezApplet::BluezApplet( QWidget *parent, const char *name ) : QWidget( parent, name ) {
55 setFixedHeight( 18 ); 55 setFixedHeight( 18 );
56 setFixedWidth( 14 ); 56 setFixedWidth( 14 );
57 bluezOnPixmap = Resource::loadPixmap( "bluetoothapplet/bluezon" ); 57 bluezOnPixmap = Resource::loadPixmap( "bluetoothapplet/bluezon" );
58 bluezOffPixmap = Resource::loadPixmap( "bluetoothapplet/bluezoff" ); 58 bluezOffPixmap = Resource::loadPixmap( "bluetoothapplet/bluezoff" );
59 // bluezDiscoveryOnPixmap = Resource::loadPixmap( "bluetoothapplet/magglass" ); 59 // bluezDiscoveryOnPixmap = Resource::loadPixmap( "bluetoothapplet/magglass" );
60 startTimer(4000); 60 startTimer(4000);
61 btDevice = 0; 61 btDevice = 0;
62 bluezactive = false; 62 bluezactive = false;
63 bluezDiscoveryActive = false; 63 bluezDiscoveryActive = false;
64 64
65 } 65 }
66 66
67 BluezApplet::~BluezApplet() { 67 BluezApplet::~BluezApplet() {
68 if ( btDevice ) { 68 if ( btDevice ) {
69 delete btDevice; 69 delete btDevice;
70 } 70 }
71 } 71 }
72 72
73 bool BluezApplet::checkBluezStatus() { 73 bool BluezApplet::checkBluezStatus() {
74 if (btDevice) { 74 if (btDevice) {
75 if (btDevice->isLoaded() ) { 75 if (btDevice->isLoaded() ) {
76 return true; 76 return true;
77 } else { 77 } else {
78 return false; 78 return false;
79 } 79 }
80 } else { 80 } else {
81 return false; 81 return false;
82 } 82 }
83 } 83 }
84 84
85 int BluezApplet::setBluezStatus(int c) { 85 int BluezApplet::setBluezStatus(int c) {
86 86
87 if ( c == 1 ) { 87 if ( c == 1 ) {
88 switch ( ODevice::inst()->model() ) { 88 switch ( ODevice::inst()->model() ) {
89 case Model_iPAQ_H39xx: 89 case Model_iPAQ_H39xx:
90 btDevice = new Device( "/dev/tts/1", "bcsp", "921600" ); 90 btDevice = new Device( "/dev/tts/1", "bcsp", "921600" );
91 break; 91 break;
92 92
93 case Model_iPAQ_H5xxx: 93 case Model_iPAQ_H5xxx:
94 btDevice = new Device( "/dev/tts/1", "any", "921600" ); 94 btDevice = new Device( "/dev/tts/1", "any", "921600" );
95 break; 95 break;
96 96
97 default: 97 default:
98 btDevice = new Device( "/dev/ttySB0", "bcsp", "230400" ); 98 btDevice = new Device( "/dev/ttySB0", "bcsp", "230400" );
99 break; 99 break;
100 } 100 }
101 } else { 101 } else {
102 if ( btDevice ) { 102 if ( btDevice ) {
103 delete btDevice; 103 delete btDevice;
104 btDevice = 0; 104 btDevice = 0;
105 } 105 }
106 } 106 }
107 return 0; 107 return 0;
108 } 108 }
109 109
110 int BluezApplet::checkBluezDiscoveryStatus() { 110 int BluezApplet::checkBluezDiscoveryStatus() {
111 } 111 }
112 112
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
@@ -1,688 +1,688 @@
1/* 1/*
2 * bluebase.cpp * 2 * bluebase.cpp *
3 * --------------------- 3 * ---------------------
4 * 4 *
5 * copyright : (c) 2002 by Maximilian Reiß 5 * copyright : (c) 2002 by Maximilian Reiß
6 * email : max.reiss@gmx.de 6 * email : max.reiss@gmx.de
7 * 7 *
8 */ 8 */
9/*************************************************************************** 9/***************************************************************************
10 * * 10 * *
11 * This program is free software; you can redistribute it and/or modify * 11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by * 12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or * 13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. * 14 * (at your option) any later version. *
15 * * 15 * *
16 ***************************************************************************/ 16 ***************************************************************************/
17 17
18#include "bluebase.h" 18#include "bluebase.h"
19#include "scandialog.h" 19#include "scandialog.h"
20#include "hciconfwrapper.h" 20#include "hciconfwrapper.h"
21#include "devicehandler.h" 21#include "devicehandler.h"
22#include "btconnectionitem.h" 22#include "btconnectionitem.h"
23#include "rfcommassigndialogimpl.h" 23#include "rfcommassigndialogimpl.h"
24 24
25/* OPIE */ 25/* OPIE */
26#include <qpe/qpeapplication.h> 26#include <qpe/qpeapplication.h>
27#include <qpe/resource.h> 27#include <qpe/resource.h>
28#include <qpe/config.h> 28#include <qpe/config.h>
29 29
30/* QT */ 30/* QT */
31#include <qframe.h> 31#include <qframe.h>
32#include <qlabel.h> 32#include <qlabel.h>
33#include <qpushbutton.h> 33#include <qpushbutton.h>
34#include <qlayout.h> 34#include <qlayout.h>
35#include <qvariant.h> 35#include <qvariant.h>
36#include <qimage.h> 36#include <qimage.h>
37#include <qpixmap.h> 37#include <qpixmap.h>
38#include <qtabwidget.h> 38#include <qtabwidget.h>
39#include <qscrollview.h> 39#include <qscrollview.h>
40#include <qvbox.h> 40#include <qvbox.h>
41#include <qmessagebox.h> 41#include <qmessagebox.h>
42#include <qcheckbox.h> 42#include <qcheckbox.h>
43#include <qlineedit.h> 43#include <qlineedit.h>
44#include <qlistview.h> 44#include <qlistview.h>
45#include <qdir.h> 45#include <qdir.h>
46#include <qpopupmenu.h> 46#include <qpopupmenu.h>
47#include <qtimer.h> 47#include <qtimer.h>
48#include <qlist.h> 48#include <qlist.h>
49 49
50/* STD */ 50/* STD */
51#include <remotedevice.h> 51#include <remotedevice.h>
52#include <services.h> 52#include <services.h>
53#include <stdlib.h> 53#include <stdlib.h>
54 54
55using namespace OpieTooth; 55using namespace OpieTooth;
56 56
57BlueBase::BlueBase( QWidget* parent, const char* name, WFlags fl ) 57BlueBase::BlueBase( QWidget* parent, const char* name, WFlags fl )
58 : BluetoothBase( parent, name, fl ) 58 : BluetoothBase( parent, name, fl )
59{ 59{
60 60
61 m_localDevice = new Manager( "hci0" ); 61 m_localDevice = new Manager( "hci0" );
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();
255 255
256 writeConfig(); 256 writeConfig();
257 257
258 QMessageBox::information( this, tr("Test") , tr("Changes were applied.") ); 258 QMessageBox::information( this, tr("Test") , tr("Changes were applied.") );
259} 259}
260 260
261/** 261/**
262 * Launch Rfcomm Bind dialog 262 * Launch Rfcomm Bind dialog
263 * 263 *
264 */ 264 */
265void BlueBase::rfcommDialog() 265void BlueBase::rfcommDialog()
266{ 266{
267 RfcommAssignDialog rfcommAssign ( this, "RfcommAssignDialog", true, WStyle_ContextHelp ); 267 RfcommAssignDialog rfcommAssign ( this, "RfcommAssignDialog", true, WStyle_ContextHelp );
268 268
269 if ( QPEApplication::execDialog( &rfcommAssign ) == QDialog::Accepted ) 269 if ( QPEApplication::execDialog( &rfcommAssign ) == QDialog::Accepted )
270 { 270 {
271 rfcommAssign.saveConfig(); 271 rfcommAssign.saveConfig();
272 } 272 }
273} 273}
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
@@ -1,161 +1,161 @@
1/* main.cpp 1/* main.cpp
2 * 2 *
3 * --------------------- 3 * ---------------------
4 * 4 *
5 * copyright : (c) 2002 by Maximilian Reiß 5 * copyright : (c) 2002 by Maximilian Reiß
6 * email : max.reiss@gmx.de 6 * email : max.reiss@gmx.de
7 * 7 *
8 */ 8 */
9/*************************************************************************** 9/***************************************************************************
10 * * 10 * *
11 * This program is free software; you can redistribute it and/or modify * 11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by * 12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or * 13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. * 14 * (at your option) any later version. *
15 * * 15 * *
16 ***************************************************************************/ 16 ***************************************************************************/
17 17
18 18
19#include "scandialog.h" 19#include "scandialog.h"
20 20
21#include <qheader.h> 21#include <qheader.h>
22#include <qlistview.h> 22#include <qlistview.h>
23#include <qpushbutton.h> 23#include <qpushbutton.h>
24#include <qlayout.h> 24#include <qlayout.h>
25#include <qvariant.h> 25#include <qvariant.h>
26#include <qtooltip.h> 26#include <qtooltip.h>
27#include <qwhatsthis.h> 27#include <qwhatsthis.h>
28#include <qprogressbar.h> 28#include <qprogressbar.h>
29#include <qlist.h> 29#include <qlist.h>
30 30
31#include <manager.h> 31#include <manager.h>
32#include <device.h> 32#include <device.h>
33 33
34 34
35namespace OpieTooth { 35namespace OpieTooth {
36 36
37#include <remotedevice.h> 37#include <remotedevice.h>
38 38
39/** 39/**
40 */ 40 */
41 ScanDialog::ScanDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) 41 ScanDialog::ScanDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
42 : QDialog( parent, name, modal, fl ) { 42 : QDialog( parent, name, modal, fl ) {
43 43
44 setCaption( tr( "Scan for devices" ) ); 44 setCaption( tr( "Scan for devices" ) );
45 45
46 Layout11 = new QVBoxLayout( this ); 46 Layout11 = new QVBoxLayout( this );
47 Layout11->setSpacing( 6 ); 47 Layout11->setSpacing( 6 );
48 Layout11->setMargin( 0 ); 48 Layout11->setMargin( 0 );
49 49
50 progress = new QProgressBar( this, "progbar"); 50 progress = new QProgressBar( this, "progbar");
51 progress->setTotalSteps(20); 51 progress->setTotalSteps(20);
52 52
53 StartStopButton = new QPushButton( this, "StartButton" ); 53 StartStopButton = new QPushButton( this, "StartButton" );
54 StartStopButton->setText( tr( "Start scan" ) ); 54 StartStopButton->setText( tr( "Start scan" ) );
55 55
56 ListView1 = new QListView( this, "ListView1" ); 56 ListView1 = new QListView( this, "ListView1" );
57 57
58 //ListView1->addColumn( tr( "Add" ) ); 58 //ListView1->addColumn( tr( "Add" ) );
59 ListView1->addColumn( tr( "Add Device" ) ); 59 ListView1->addColumn( tr( "Add Device" ) );
60 //ListView1->addColumn( tr( "Type" ) ); 60 //ListView1->addColumn( tr( "Type" ) );
61 61
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,581 +1,582 @@
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
542 // write variable content 543 // write variable content
543 544
544 char ch; 545 char ch;
545 while ( !f.atEnd() ) 546 while ( !f.atEnd() )
546 { 547 {
547 f.readBlock( &ch, 1 ); 548 f.readBlock( &ch, 1 );
548 ::write ( sock, &ch, 1 ); 549 ::write ( sock, &ch, 1 );
549 } 550 }
550 551
551 // write preambel 552 // write preambel
552 553
553 ascii = preambel.latin1(); 554 ascii = preambel.latin1();
554 ascii_len = ::strlen( ascii ); 555 ascii_len = ::strlen( ascii );
555 ::write ( sock, ascii, ascii_len ); 556 ::write ( sock, ascii, ascii_len );
556 557
557 // done! 558 // done!
558 559
559 ok = true; 560 ok = true;
560 } 561 }
561 } 562 }
562 ::close ( sock ); 563 ::close ( sock );
563 } 564 }
564 if ( ok ) 565 if ( ok )
565 QMessageBox::information( 0, tr( "Success" ), 566 QMessageBox::information( 0, tr( "Success" ),
566 QString ( "<p>%1</p>" ).arg( tr( "Capture Dump was uploaded to %1" ) ).arg( CAP_hostname ) ); 567 QString ( "<p>%1</p>" ).arg( tr( "Capture Dump was uploaded to %1" ) ).arg( CAP_hostname ) );
567 else 568 else
568 QMessageBox::warning( 0, tr( "Error" ), 569 QMessageBox::warning( 0, tr( "Error" ),
569 QString ( "<p>%1</p>" ).arg ( tr( "Connection to %1 failed" ) ).arg( CAP_hostname ) ); 570 QString ( "<p>%1</p>" ).arg ( tr( "Connection to %1 failed" ) ).arg( CAP_hostname ) );
570} 571}
571 572
572 573
573void WellenreiterMainWindow::viewExpandAll() 574void WellenreiterMainWindow::viewExpandAll()
574{ 575{
575 mw->netView()->expand(); 576 mw->netView()->expand();
576} 577}
577 578
578void WellenreiterMainWindow::viewCollapseAll() 579void WellenreiterMainWindow::viewCollapseAll()
579{ 580{
580 mw->netView()->collapse(); 581 mw->netView()->collapse();
581} 582}
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
@@ -1,159 +1,159 @@
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 OPIE team <opie@handhelds.org?> 4             .=l. Copyright (c) 2002 OPIE team <opie@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 "settingstabwidget.h" 29#include "settingstabwidget.h"
30 30
31#include <qpe/config.h> 31#include <qpe/config.h>
32#include <qpe/qpeapplication.h> 32#include <qpe/qpeapplication.h>
33 33
34#include <qcheckbox.h> 34#include <qcheckbox.h>
35#include <qcombobox.h> 35#include <qcombobox.h>
36#include <qlabel.h> 36#include <qlabel.h>
37#include <qlayout.h> 37#include <qlayout.h>
38#include <qscrollview.h> 38#include <qscrollview.h>
39#include <qspinbox.h> 39#include <qspinbox.h>
40 40
41SettingsTabWidget::SettingsTabWidget( QWidget *parent ) 41SettingsTabWidget::SettingsTabWidget( QWidget *parent )
42 : QWidget( parent, 0x0, 0 ) 42 : QWidget( parent, 0x0, 0 )
43{ 43{
44 QVBoxLayout *tmpvb = new QVBoxLayout( this ); 44 QVBoxLayout *tmpvb = new QVBoxLayout( this );
45 QScrollView *sv = new QScrollView( this ); 45 QScrollView *sv = new QScrollView( this );
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
@@ -1,302 +1,302 @@
1/** 1/**
2 * $Author$ 2 * $Author$
3 * $Date$ 3 * $Date$
4 */ 4 */
5 5
6#include "interface.h" 6#include "interface.h"
7#include <qdatetime.h> 7#include <qdatetime.h>
8#include <qfile.h> 8#include <qfile.h>
9#include <qdir.h> 9#include <qdir.h>
10#include <qfileinfo.h> 10#include <qfileinfo.h>
11#include <qtextstream.h> 11#include <qtextstream.h>
12 12
13#define IFCONFIG "/sbin/ifconfig" 13#define IFCONFIG "/sbin/ifconfig"
14#define DHCP_INFO_DIR "/etc/dhcpc" 14#define DHCP_INFO_DIR "/etc/dhcpc"
15 15
16#include <stdio.h> 16#include <stdio.h>
17#include <stdlib.h> 17#include <stdlib.h>
18 18
19Interface::Interface(QObject * parent, const char * name, bool newSatus): QObject(parent, name), hardwareName("Unknown"), moduleOwner(NULL), status(newSatus), attached(false), dhcp(false), macAddress(""), ip("0.0.0.0"), broadcast(""), subnetMask("0.0.0.0"){ 19Interface::Interface(QObject * parent, const char * name, bool newSatus): QObject(parent, name), hardwareName("Unknown"), moduleOwner(NULL), status(newSatus), attached(false), dhcp(false), macAddress(""), ip("0.0.0.0"), broadcast(""), subnetMask("0.0.0.0"){
20 refresh(); 20 refresh();
21} 21}
22 22
23/** 23/**
24 * Set status 24 * Set status
25 * @param newStatus - the new status 25 * @param newStatus - the new status
26 * emit updateInterface 26 * emit updateInterface
27 */ 27 */
28void Interface::setStatus(bool newStatus){ 28void Interface::setStatus(bool newStatus){
29 if(status != newStatus){ 29 if(status != newStatus){
30 status = newStatus; 30 status = newStatus;
31 refresh(); 31 refresh();
32 } 32 }
33}; 33};
34 34
35/** 35/**
36 * Set if attached or not (802.11 card pulled out for example) 36 * Set if attached or not (802.11 card pulled out for example)
37 * @param isAttached - if attached 37 * @param isAttached - if attached
38 * emit updateInterface 38 * emit updateInterface
39 */ 39 */
40void Interface::setAttached(bool isAttached){ 40void Interface::setAttached(bool isAttached){
41 attached = isAttached; 41 attached = isAttached;
42 emit(updateInterface(this)); 42 emit(updateInterface(this));
43}; 43};
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
@@ -1,349 +1,349 @@
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 "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"));
218 tabWindow->addTab( ip_w, tr("IP") ); 218 tabWindow->addTab( ip_w, tr("IP") );
219 219
220 // // GATEWAY WIDGET 220 // // GATEWAY WIDGET
221 gateway_w = new GatewayWidget( _pppdata, tabWindow, isnewaccount, tr("Gateway Setup")); 221 gateway_w = new GatewayWidget( _pppdata, tabWindow, isnewaccount, tr("Gateway Setup"));
222 tabWindow->addTab( gateway_w, tr("Gateway") ); 222 tabWindow->addTab( gateway_w, tr("Gateway") );
223 223
224 // // DNS WIDGET 224 // // DNS WIDGET
225 dns_w = new DNSWidget( _pppdata, tabWindow, isnewaccount, tr("DNS Servers") ); 225 dns_w = new DNSWidget( _pppdata, tabWindow, isnewaccount, tr("DNS Servers") );
226 tabWindow->addTab( dns_w, tr("DNS") ); 226 tabWindow->addTab( dns_w, tr("DNS") );
227 227
228 // // EXECUTE WIDGET 228 // // EXECUTE WIDGET
229 ExecWidget *exec_w = new ExecWidget( _pppdata, tabWindow, isnewaccount, tr("Execute Programs")); 229 ExecWidget *exec_w = new ExecWidget( _pppdata, tabWindow, isnewaccount, tr("Execute Programs"));
230 tabWindow->addTab( exec_w, tr("Execute") ); 230 tabWindow->addTab( exec_w, tr("Execute") );
231 231
232 int result = 0; 232 int result = 0;
233 bool ok = false; 233 bool ok = false;
234 234
235 while (!ok) 235 while (!ok)
236 { 236 {
237 result = QPEApplication::execDialog( dlg ); 237 result = QPEApplication::execDialog( dlg );
238 ok = true; 238 ok = true;
239 239
240 if(result == QDialog::Accepted) 240 if(result == QDialog::Accepted)
241 { 241 {
242 if (!auth_w->check()) 242 if (!auth_w->check())
243 { 243 {
244 ok = false; 244 ok = false;
245 } 245 }
246 else if(!dial_w->save()) 246 else if(!dial_w->save())
247 { 247 {
248 QMessageBox::critical(this, "error", tr( "You must enter a unique account name")); 248 QMessageBox::critical(this, "error", tr( "You must enter a unique account name"));
249 ok = false; 249 ok = false;
250 } 250 }
251 else 251 else
252 { 252 {
253 ip_w->save(); 253 ip_w->save();
254 dns_w->save(); 254 dns_w->save();
255 gateway_w->save(); 255 gateway_w->save();
256 auth_w->save(); 256 auth_w->save();
257 exec_w->save(); 257 exec_w->save();
258 } 258 }
259 } 259 }
260 } 260 }
261 261
262 delete dlg; 262 delete dlg;
263 263
264 return result; 264 return result;
265} 265}
266 266
267 267
268// QString AccountWidget::prettyPrintVolume(unsigned int n) { 268// QString AccountWidget::prettyPrintVolume(unsigned int n) {
269// int idx = 0; 269// int idx = 0;
270// const QString quant[] = {tr("Byte"), tr("KB"), 270// const QString quant[] = {tr("Byte"), tr("KB"),
271 // tr("MB"), tr("GB"), QString::null}; 271 // tr("MB"), tr("GB"), QString::null};
272 272
273// float n1 = n; 273// float n1 = n;
274// while(n >= 1024 && quant[idx] != QString::null) { 274// while(n >= 1024 && quant[idx] != QString::null) {
275// idx++; 275// idx++;
276// n /= 1024; 276// n /= 1024;
277// } 277// }
278 278
279// int i = idx; 279// int i = idx;
280// while(i--) 280// while(i--)
281// n1 = n1 / 1024.0; 281// n1 = n1 / 1024.0;
282 282
283// QString s = QString::number( n1, 'f', idx==0 ? 0 : 1 ); 283// QString s = QString::number( n1, 'f', idx==0 ? 0 : 1 );
284// s += " " + quant[idx]; 284// s += " " + quant[idx];
285// return s; 285// return s;
286// } 286// }
287 287
288 288
289///////////////////////////////////////////////////////////////////////////// 289/////////////////////////////////////////////////////////////////////////////
290// 290//
291// Queries the user what to reset: costs, volume or both 291// Queries the user what to reset: costs, volume or both
292// 292//
293///////////////////////////////////////////////////////////////////////////// 293/////////////////////////////////////////////////////////////////////////////
294// QueryReset::QueryReset(QWidget *parent) : QDialog(parent, 0, true) { 294// QueryReset::QueryReset(QWidget *parent) : QDialog(parent, 0, true) {
295// // KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon()); 295// // KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());
296// setCaption(tr("Reset Accounting")); 296// setCaption(tr("Reset Accounting"));
297 297
298// QVBoxLayout *tl = new QVBoxLayout(this, 10, 10); 298// QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
299// QVGroupBox *f = new QVGroupBox(tr("What to Reset"), this); 299// QVGroupBox *f = new QVGroupBox(tr("What to Reset"), this);
300 300
301// QVBoxLayout *l1 = new QVBoxLayout(this, 10, 10); 301// QVBoxLayout *l1 = new QVBoxLayout(this, 10, 10);
302// // costs = new QCheckBox(tr("Reset the accumulated phone costs"), f); 302// // costs = new QCheckBox(tr("Reset the accumulated phone costs"), f);
303// // costs->setChecked(true); 303// // costs->setChecked(true);
304// // l1->addWidget(costs); 304// // l1->addWidget(costs);
305// // QWhatsThis::add(costs, tr("Check this to set the phone costs\n" 305// // QWhatsThis::add(costs, tr("Check this to set the phone costs\n"
306 // // "to zero. Typically you'll want to\n" 306 // // "to zero. Typically you'll want to\n"
307 // // "do this once a month.")); 307 // // "do this once a month."));
308 308
309// // volume = new QCheckBox(tr("Reset volume accounting"), f); 309// // volume = new QCheckBox(tr("Reset volume accounting"), f);
310// // volume->setChecked(true); 310// // volume->setChecked(true);
311// // l1->addWidget(volume); 311// // l1->addWidget(volume);
312// // QWhatsThis::add(volume, tr("Check this to set the volume accounting\n" 312// // QWhatsThis::add(volume, tr("Check this to set the volume accounting\n"
313 // // "to zero. Typically you'll want to do this\n" 313 // // "to zero. Typically you'll want to do this\n"
314 // // "once a month.")); 314 // // "once a month."));
315 315
316// l1->activate(); 316// l1->activate();
317 317
318// // this activates the f-layout and sets minimumSize() 318// // this activates the f-layout and sets minimumSize()
319// f->show(); 319// f->show();
320 320
321// tl->addWidget(f); 321// tl->addWidget(f);
322 322
323// QButtonGroup *bbox = new QButtonGroup(this); 323// QButtonGroup *bbox = new QButtonGroup(this);
324// // bbox->addStretch(1); 324// // bbox->addStretch(1);
325// QPushButton *ok = new QPushButton( bbox, tr("OK") ); 325// QPushButton *ok = new QPushButton( bbox, tr("OK") );
326// bbox->insert(ok); 326// bbox->insert(ok);
327// ok->setDefault(true); 327// ok->setDefault(true);
328// QPushButton *cancel = new QPushButton( bbox, tr("Cancel") ); 328// QPushButton *cancel = new QPushButton( bbox, tr("Cancel") );
329// bbox->insert(cancel); 329// bbox->insert(cancel);
330 330
331// connect(ok, SIGNAL(clicked()), 331// connect(ok, SIGNAL(clicked()),
332 // this, SLOT(accepted())); 332 // this, SLOT(accepted()));
333// connect(cancel, SIGNAL(clicked()), 333// connect(cancel, SIGNAL(clicked()),
334 // this, SLOT(reject())); 334 // this, SLOT(reject()));
335 335
336// bbox->layout(); 336// bbox->layout();
337// tl->addWidget(bbox); 337// tl->addWidget(bbox);
338 338
339// } 339// }
340 340
341 341
342// void QueryReset::accepted() { 342// void QueryReset::accepted() {
343// int result = costs->isChecked() ? COSTS : 0; 343// int result = costs->isChecked() ? COSTS : 0;
344// result += volume->isChecked() ? VOLUME : 0; 344// result += volume->isChecked() ? VOLUME : 0;
345 345
346// done(result); 346// done(result);
347// } 347// }
348 348
349 349
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
@@ -1,197 +1,197 @@
1 1
2#include <qlayout.h> 2#include <qlayout.h>
3#include <qmessagebox.h> 3#include <qmessagebox.h>
4#include <qtoolbutton.h> 4#include <qtoolbutton.h>
5#include <qwhatsthis.h> 5#include <qwhatsthis.h>
6 6
7#include "auth.h" 7#include "auth.h"
8#include "authwidget.h" 8#include "authwidget.h"
9#include "edit.h" 9#include "edit.h"
10#include "pppdata.h" 10#include "pppdata.h"
11 11
12 12
13static const char* const image0_data[] = { 13static const char* const image0_data[] = {
14"16 16 2 1", 14"16 16 2 1",
15". c None", 15". c None",
16"# c #000000", 16"# c #000000",
17"................", 17"................",
18"...#...###...##.", 18"...#...###...##.",
19"..#.#..#..#.##..", 19"..#.#..#..#.##..",
20"..###..###.##...", 20"..###..###.##...",
21".#...#.#..##....", 21".#...#.#..##....",
22".#...#.#.##.....", 22".#...#.#.##.....",
23"........##.#..#.", 23"........##.#..#.",
24"..##...##...##..", 24"..##...##...##..",
25".#..#.###...##..", 25".#..#.###...##..",
26".#...##..#.#..#.", 26".#...##..#.#..#.",
27".#..##..........", 27".#..##..........",
28".#.##.#..#.#..#.", 28".#.##.#..#.#..#.",
29"..##...##...##..", 29"..##...##...##..",
30".##....##...##..", 30".##....##...##..",
31".#....#..#.#..#.", 31".#....#..#.#..#.",
32"................"}; 32"................"};
33 33
34 34
35AuthWidget::AuthWidget(PPPData *pd, QWidget *parent, bool isnewaccount, const char *name ) 35AuthWidget::AuthWidget(PPPData *pd, QWidget *parent, bool isnewaccount, const char *name )
36 : QWidget( parent, name), 36 : QWidget( parent, name),
37 scriptWidget(0), 37 scriptWidget(0),
38 _pppdata(pd), 38 _pppdata(pd),
39 isNewAccount(isnewaccount) 39 isNewAccount(isnewaccount)
40{ 40{
41 layout = new QGridLayout(this); 41 layout = new QGridLayout(this);
42 42
43 auth_l = new QLabel(tr("Authentication: "), this); 43 auth_l = new QLabel(tr("Authentication: "), this);
44 layout->addWidget(auth_l, 0, 0); 44 layout->addWidget(auth_l, 0, 0);
45 45
46 auth = new QComboBox(this); 46 auth = new QComboBox(this);
47 auth->insertItem(tr("Script-based")); 47 auth->insertItem(tr("Script-based"));
48 auth->insertItem(tr("PAP")); 48 auth->insertItem(tr("PAP"));
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
@@ -1,1466 +1,1466 @@
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 * 4 *
5 * Copyright (C) 1997 Bernd Johannes Wuebben 5 * Copyright (C) 1997 Bernd Johannes Wuebben
6 * wuebben@math.cornell.edu 6 * wuebben@math.cornell.edu
7 * Copyright (C) 1998-2001 Harri Porten <porten@kde.org> 7 * Copyright (C) 1998-2001 Harri Porten <porten@kde.org>
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 <config.h> 27//#include <config.h>
28 28
29#include <qlayout.h> 29#include <qlayout.h>
30#include <qregexp.h> 30#include <qregexp.h>
31 31
32#include <qapplication.h> 32#include <qapplication.h>
33//#include <kdebug.h> 33//#include <kdebug.h>
34//#include <klocale.h> 34//#include <klocale.h>
35#include <qmessagebox.h> 35#include <qmessagebox.h>
36#include <qpushbutton.h> 36#include <qpushbutton.h>
37 37
38#include <unistd.h> 38#include <unistd.h>
39#include <stdlib.h> 39#include <stdlib.h>
40#include <string.h> 40#include <string.h>
41#include <fcntl.h> 41#include <fcntl.h>
42#include <netdb.h> 42#include <netdb.h>
43#include <sys/types.h> 43#include <sys/types.h>
44#include <sys/socket.h> 44#include <sys/socket.h>
45#include <arpa/inet.h> 45#include <arpa/inet.h>
46#include <netinet/in.h> 46#include <netinet/in.h>
47#include <sys/ioctl.h> 47#include <sys/ioctl.h>
48#include <assert.h> 48#include <assert.h>
49 49
50#ifdef _XPG4_2 50#ifdef _XPG4_2
51 #define __xnet_connectconnect 51 #define __xnet_connectconnect
52#endif 52#endif
53 53
54#include <errno.h> 54#include <errno.h>
55 55
56#ifdef HAVE_SYS_PARAM_H 56#ifdef HAVE_SYS_PARAM_H
57#include <sys/param.h> 57#include <sys/param.h>
58#endif 58#endif
59 59
60#ifdef __linux__ 60#ifdef __linux__
61#include "runtests.h" 61#include "runtests.h"
62#endif 62#endif
63 63
64#include "auth.h" 64#include "auth.h"
65#include "connect.h" 65#include "connect.h"
66//#include "docking.h" 66//#include "docking.h"
67#include "interfaceppp.h" 67#include "interfaceppp.h"
68#include "modem.h" 68#include "modem.h"
69#include "kpppconfig.h" 69#include "kpppconfig.h"
70#include "pppdata.h" 70#include "pppdata.h"
71#include "kpppwidget.h" 71#include "kpppwidget.h"
72//#include "requester.h" 72//#include "requester.h"
73//#include "utils.h" 73//#include "utils.h"
74#define execute_command system 74#define execute_command system
75 75
76QString old_hostname; 76QString old_hostname;
77bool modified_hostname; 77bool modified_hostname;
78 78
79 79
80ConnectWidget::ConnectWidget(InterfacePPP *ifp, QWidget *parent, const char *name) 80ConnectWidget::ConnectWidget(InterfacePPP *ifp, QWidget *parent, const char *name)
81 : QWidget(parent, name), 81 : QWidget(parent, name),
82 myreadbuffer(""), 82 myreadbuffer(""),
83 main_timer_ID(0), 83 main_timer_ID(0),
84 vmain(0), 84 vmain(0),
85 substate(-1), 85 substate(-1),
86 scriptindex(0), 86 scriptindex(0),
87 loopnest(0), 87 loopnest(0),
88 loopend(false), 88 loopend(false),
89 semaphore(false), 89 semaphore(false),
90 expecting(false), 90 expecting(false),
91 readbuffer(""), 91 readbuffer(""),
92 scanvar(""), 92 scanvar(""),
93 scanning(false), 93 scanning(false),
94 pausing(false), 94 pausing(false),
95 dialnumber(0), 95 dialnumber(0),
96 _ifaceppp(ifp) 96 _ifaceppp(ifp)
97{ 97{
98 modified_hostname = false; 98 modified_hostname = false;
99 99
100 QVBoxLayout *tl = new QVBoxLayout(this, 8, 10); 100 QVBoxLayout *tl = new QVBoxLayout(this, 8, 10);
101 QString tit = QObject::tr("Connecting to: "); 101 QString tit = QObject::tr("Connecting to: ");
102 setCaption(tit); 102 setCaption(tit);
103 103
104 QHBoxLayout *l0 = new QHBoxLayout(10); 104 QHBoxLayout *l0 = new QHBoxLayout(10);
105 tl->addLayout(l0); 105 tl->addLayout(l0);
106 l0->addSpacing(10); 106 l0->addSpacing(10);
107 messg = new QLabel(this, "messg"); 107 messg = new QLabel(this, "messg");
108 messg->setFrameStyle(QFrame::Panel|QFrame::Sunken); 108 messg->setFrameStyle(QFrame::Panel|QFrame::Sunken);
109 messg->setAlignment(AlignCenter); 109 messg->setAlignment(AlignCenter);
110 messg->setText(QObject::tr("Unable to create modem lock file.")); 110 messg->setText(QObject::tr("Unable to create modem lock file."));
111 messg->setMinimumHeight(messg->sizeHint().height() + 5); 111 messg->setMinimumHeight(messg->sizeHint().height() + 5);
112// int messw = (messg->sizeHint().width() * 12) / 10; 112// int messw = (messg->sizeHint().width() * 12) / 10;
113// messw = QMAX(messw,280); 113// messw = QMAX(messw,280);
114// messg->setMinimumWidth(messw); 114// messg->setMinimumWidth(messw);
115 if (_ifaceppp->getStatus()) 115 if (_ifaceppp->getStatus())
116 messg->setText(QObject::tr("Online")); 116 messg->setText(QObject::tr("Online"));
117 else 117 else
118 messg->setText(QObject::tr("Offline")); 118 messg->setText(QObject::tr("Offline"));
119 l0->addSpacing(10); 119 l0->addSpacing(10);
120 l0->addWidget(messg); 120 l0->addWidget(messg);
121 l0->addSpacing(10); 121 l0->addSpacing(10);
122 122
123 QHBoxLayout *l1 = new QHBoxLayout(10); 123 QHBoxLayout *l1 = new QHBoxLayout(10);
124 tl->addLayout(l1); 124 tl->addLayout(l1);
125 l1->addStretch(1); 125 l1->addStretch(1);
126 126
127 debug = new QPushButton(QObject::tr("Log"), this); 127 debug = new QPushButton(QObject::tr("Log"), this);
128 debug->setToggleButton(true); 128 debug->setToggleButton(true);
129 debug->setEnabled( false ); // FIXME: disable the log button 129 debug->setEnabled( false ); // FIXME: disable the log button
130 connect(debug, SIGNAL(clicked()), SIGNAL(toggleDebugWindow())); 130 connect(debug, SIGNAL(clicked()), SIGNAL(toggleDebugWindow()));
131 131
132 cancel = new QPushButton(QObject::tr("Cancel"), this); 132 cancel = new QPushButton(QObject::tr("Cancel"), this);
133 cancel->setFocus(); 133 cancel->setFocus();
134 connect(cancel, SIGNAL(clicked()), SLOT(cancelbutton())); 134 connect(cancel, SIGNAL(clicked()), SLOT(cancelbutton()));
135 135
136// int maxw = QMAX(cancel->sizeHint().width(), 136// int maxw = QMAX(cancel->sizeHint().width(),
137 // debug->sizeHint().width()); 137 // debug->sizeHint().width());
138// maxw = QMAX(maxw,65); 138// maxw = QMAX(maxw,65);
139// debug->setFixedWidth(maxw); 139// debug->setFixedWidth(maxw);
140// cancel->setFixedWidth(maxw); 140// cancel->setFixedWidth(maxw);
141 l1->addWidget(debug); 141 l1->addWidget(debug);
142 l1->addWidget(cancel); 142 l1->addWidget(cancel);
143 143
144// setFixedSize(sizeHint()); 144// setFixedSize(sizeHint());
145 145
146 pausetimer = new QTimer(this); 146 pausetimer = new QTimer(this);
147 connect(pausetimer, SIGNAL(timeout()), SLOT(pause())); 147 connect(pausetimer, SIGNAL(timeout()), SLOT(pause()));
148 148
149 qApp->processEvents(); 149 qApp->processEvents();
150 150
151 timeout_timer = new QTimer(this); 151 timeout_timer = new QTimer(this);
152 connect(timeout_timer, SIGNAL(timeout()), SLOT(script_timed_out())); 152 connect(timeout_timer, SIGNAL(timeout()), SLOT(script_timed_out()));
153 153
154 inittimer = new QTimer(this); 154 inittimer = new QTimer(this);
155 connect(inittimer, SIGNAL(timeout()), SLOT(init())); 155 connect(inittimer, SIGNAL(timeout()), SLOT(init()));
156 156
157 if_timeout_timer = new QTimer(this); 157 if_timeout_timer = new QTimer(this);
158 connect(if_timeout_timer, SIGNAL(timeout()), SLOT(if_waiting_timed_out())); 158 connect(if_timeout_timer, SIGNAL(timeout()), SLOT(if_waiting_timed_out()));
159 159
160 connect(this,SIGNAL(if_waiting_signal()),this,SLOT(if_waiting_slot())); 160 connect(this,SIGNAL(if_waiting_signal()),this,SLOT(if_waiting_slot()));
161 161
162 prompt = new PWEntry( this, "pw" ); 162 prompt = new PWEntry( this, "pw" );
163 if_timer = new QTimer(this); 163 if_timer = new QTimer(this);
164 connect(if_timer,SIGNAL(timeout()), SLOT(if_waiting_slot())); 164 connect(if_timer,SIGNAL(timeout()), SLOT(if_waiting_slot()));
165} 165}
166 166
167 167
168ConnectWidget::~ConnectWidget() { 168ConnectWidget::~ConnectWidget() {
169} 169}
170 170
171 171
172void ConnectWidget::preinit() { 172void ConnectWidget::preinit() {
173 // this is all just to keep the GUI nice and snappy .... 173 // this is all just to keep the GUI nice and snappy ....
174 // you have to see to believe ... 174 // you have to see to believe ...
175 messg->setText(QObject::tr("Looking for modem...")); 175 messg->setText(QObject::tr("Looking for modem..."));
176 inittimer->start(100); 176 inittimer->start(100);
177} 177}
178 178
179 179
180void ConnectWidget::init() { 180void ConnectWidget::init() {
181 _ifaceppp->data()->setpppdError(0); 181 _ifaceppp->data()->setpppdError(0);
182 inittimer->stop(); 182 inittimer->stop();
183 vmain = 0; 183 vmain = 0;
184 substate = -1; 184 substate = -1;
185 expecting = false; 185 expecting = false;
186 pausing = false; 186 pausing = false;
187 scriptindex = 0; 187 scriptindex = 0;
188 myreadbuffer = ""; 188 myreadbuffer = "";
189 scanning = false; 189 scanning = false;
190 scanvar = ""; 190 scanvar = "";
191 firstrunID = true; 191 firstrunID = true;
192 firstrunPW = true; 192 firstrunPW = true;
193// stats->totalbytes = 0; 193// stats->totalbytes = 0;
194 dialnumber = 0; 194 dialnumber = 0;
195 195
196// p_kppp->con_speed = ""; 196// p_kppp->con_speed = "";
197 197
198// p_kppp->setQuitOnDisconnect (p_kppp->quitOnDisconnect() || _ifaceppp->data()->quit_on_disconnect()); 198// p_kppp->setQuitOnDisconnect (p_kppp->quitOnDisconnect() || _ifaceppp->data()->quit_on_disconnect());
199 199
200 comlist = &_ifaceppp->data()->scriptType(); 200 comlist = &_ifaceppp->data()->scriptType();
201 arglist = &_ifaceppp->data()->script(); 201 arglist = &_ifaceppp->data()->script();
202 202
203 QString tit = QObject::tr("Connecting to: %1").arg(_ifaceppp->data()->accname()); 203 QString tit = QObject::tr("Connecting to: %1").arg(_ifaceppp->data()->accname());
204 setCaption(tit); 204 setCaption(tit);
205 205
206 qApp->processEvents(); 206 qApp->processEvents();
207 207
208 // run the "before-connect" command 208 // run the "before-connect" command
209 if (!_ifaceppp->data()->command_before_connect().isEmpty()) { 209 if (!_ifaceppp->data()->command_before_connect().isEmpty()) {
210 messg->setText(QObject::tr("Running pre-startup command...")); 210 messg->setText(QObject::tr("Running pre-startup command..."));
211 emit debugMessage(QObject::tr("Running pre-startup command...")); 211 emit debugMessage(QObject::tr("Running pre-startup command..."));
212 212
213 qApp->processEvents(); 213 qApp->processEvents();
214 QApplication::flushX(); 214 QApplication::flushX();
215 pid_t id = execute_command(_ifaceppp->data()->command_before_connect()); 215 pid_t id = execute_command(_ifaceppp->data()->command_before_connect());
216// int i, status; 216// int i, status;
217 217
218// do { 218// do {
219// qApp->processEvents(); 219// qApp->processEvents();
220// i = waitpid(id, &status, WNOHANG); 220// i = waitpid(id, &status, WNOHANG);
221// usleep(100000); 221// usleep(100000);
222// } while (i == 0 && errno == 0); 222// } while (i == 0 && errno == 0);
223 } 223 }
224 224
225 int lock = _ifaceppp->modem()->lockdevice(); 225 int lock = _ifaceppp->modem()->lockdevice();
226 226
227 if (lock == 1) { 227 if (lock == 1) {
228 messg->setText(QObject::tr("Modem device is locked.")); 228 messg->setText(QObject::tr("Modem device is locked."));
229 vmain = 20; // wait until cancel is pressed 229 vmain = 20; // wait until cancel is pressed
230 return; 230 return;
231 } 231 }
232 232
233 if (lock == -1) { 233 if (lock == -1) {
234 messg->setText(QObject::tr("Unable to create modem lock file.")); 234 messg->setText(QObject::tr("Unable to create modem lock file."));
235 vmain = 20; // wait until cancel is pressed 235 vmain = 20; // wait until cancel is pressed
236 return; 236 return;
237 } 237 }
238 238
239 if(_ifaceppp->modem()->opentty()) { 239 if(_ifaceppp->modem()->opentty()) {
240 messg->setText(_ifaceppp->modem()->modemMessage()); 240 messg->setText(_ifaceppp->modem()->modemMessage());
241 qApp->processEvents(); 241 qApp->processEvents();
242 if(_ifaceppp->modem()->hangup()) { 242 if(_ifaceppp->modem()->hangup()) {
243 243
244 qApp->processEvents(); 244 qApp->processEvents();
245 245
246 semaphore = false; 246 semaphore = false;
247 247
248 _ifaceppp->modem()->stop(); 248 _ifaceppp->modem()->stop();
249 _ifaceppp->modem()->notify(this, SLOT(readChar(unsigned char))); 249 _ifaceppp->modem()->notify(this, SLOT(readChar(unsigned char)));
250 250
251 // if we are stuck anywhere we will time out 251 // if we are stuck anywhere we will time out
252 timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000); 252 timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000);
253 253
254 // this timer will run the script etc. 254 // this timer will run the script etc.
255 main_timer_ID = startTimer(10); 255 main_timer_ID = startTimer(10);
256 256
257 return; 257 return;
258 } 258 }
259 } 259 }
260 260
261 // initialization failed 261 // initialization failed
262 messg->setText(_ifaceppp->modem()->modemMessage()); 262 messg->setText(_ifaceppp->modem()->modemMessage());
263 vmain = 20; // wait until cancel is pressed 263 vmain = 20; // wait until cancel is pressed
264 _ifaceppp->modem()->unlockdevice(); 264 _ifaceppp->modem()->unlockdevice();
265} 265}
266 266
267 267
268void ConnectWidget::timerEvent(QTimerEvent *) { 268void ConnectWidget::timerEvent(QTimerEvent *) {
269 if (semaphore || pausing) 269 if (semaphore || pausing)
270 return; 270 return;
271 271
272 if(vmain == 0) { 272 if(vmain == 0) {
273#ifdef DEBUG_WO_DIALING 273#ifdef DEBUG_WO_DIALING
274 vmain = 10; 274 vmain = 10;
275 return; 275 return;
276#endif 276#endif
277 277
278 assert(PPPData::NumInitStrings > 0); 278 assert(PPPData::NumInitStrings > 0);
279 // first init string ? 279 // first init string ?
280 if(substate == -1) { 280 if(substate == -1) {
281 messg->setText(QObject::tr("Initializing modem...")); 281 messg->setText(QObject::tr("Initializing modem..."));
282 emit debugMessage(QObject::tr("Initializing modem...")); 282 emit debugMessage(QObject::tr("Initializing modem..."));
283 substate = 0; 283 substate = 0;
284 } 284 }
285 285
286 QString initStr = _ifaceppp->data()->modemInitStr(substate); 286 QString initStr = _ifaceppp->data()->modemInitStr(substate);
287 if (!initStr.isEmpty()) { 287 if (!initStr.isEmpty()) {
288 // send a carriage return and then wait a bit so that the modem will 288 // send a carriage return and then wait a bit so that the modem will
289 // let us issue commands. 289 // let us issue commands.
290 if(_ifaceppp->data()->modemPreInitDelay() > 0) { 290 if(_ifaceppp->data()->modemPreInitDelay() > 0) {
291 usleep(_ifaceppp->data()->modemPreInitDelay() * 5000); 291 usleep(_ifaceppp->data()->modemPreInitDelay() * 5000);
292 writeline(""); 292 writeline("");
293 usleep(_ifaceppp->data()->modemPreInitDelay() * 5000); 293 usleep(_ifaceppp->data()->modemPreInitDelay() * 5000);
294 } 294 }
295 setExpect(_ifaceppp->data()->modemInitResp()); 295 setExpect(_ifaceppp->data()->modemInitResp());
296 writeline(initStr); 296 writeline(initStr);
297 usleep(_ifaceppp->data()->modemInitDelay() * 10000); // 0.01 - 3.0 sec 297 usleep(_ifaceppp->data()->modemInitDelay() * 10000); // 0.01 - 3.0 sec
298 } 298 }
299 299
300 substate++; 300 substate++;
301 301
302 /* 302 /*
303 * FIXME after 3.0: Make it possible to disable ATS11 since it 303 * FIXME after 3.0: Make it possible to disable ATS11 since it
304 * seems to be incompatible with some ISDN adapters (e.g. DataBox 304 * seems to be incompatible with some ISDN adapters (e.g. DataBox
305 * Speed Dragon). Even better would be to detect this when doing 305 * Speed Dragon). Even better would be to detect this when doing
306 * a "Modem Query" 306 * a "Modem Query"
307 */ 307 */
308 if (MODEM_TONEDURATION != _ifaceppp->data()->modemToneDuration()) 308 if (MODEM_TONEDURATION != _ifaceppp->data()->modemToneDuration())
309 vmain = 5; 309 vmain = 5;
310 else 310 else
311 vmain = 3; 311 vmain = 3;
312 312
313 return; 313 return;
314 } 314 }
315 315
316 if (vmain == 5) { 316 if (vmain == 5) {
317 if(!expecting) { 317 if(!expecting) {
318 QString sToneDuration = "ATS11=" + QString::number(_ifaceppp->data()->modemToneDuration()); 318 QString sToneDuration = "ATS11=" + QString::number(_ifaceppp->data()->modemToneDuration());
319 QString msg = QObject::tr("Setting ") + sToneDuration; 319 QString msg = QObject::tr("Setting ") + sToneDuration;
320 messg->setText(msg); 320 messg->setText(msg);
321 emit debugMessage(msg); 321 emit debugMessage(msg);
322 setExpect(_ifaceppp->data()->modemInitResp()); 322 setExpect(_ifaceppp->data()->modemInitResp());
323 writeline(sToneDuration); 323 writeline(sToneDuration);
324 } 324 }
325 vmain = 3; 325 vmain = 3;
326 return; 326 return;
327 } 327 }
328 328
329 if(vmain == 3) { 329 if(vmain == 3) {
330 if(!expecting) { 330 if(!expecting) {
331 // done with all init strings ? 331 // done with all init strings ?
332 if(substate < PPPData::NumInitStrings) { 332 if(substate < PPPData::NumInitStrings) {
333 vmain = 0; 333 vmain = 0;
334 return; 334 return;
335 } 335 }
336 substate = -1; 336 substate = -1;
337 // skip setting the volume if command is empty 337 // skip setting the volume if command is empty
338 if(_ifaceppp->data()->volumeInitString().isEmpty()) { 338 if(_ifaceppp->data()->volumeInitString().isEmpty()) {
339 vmain = 4; 339 vmain = 4;
340 return; 340 return;
341 } 341 }
342 messg->setText(QObject::tr("Setting speaker volume...")); 342 messg->setText(QObject::tr("Setting speaker volume..."));
343 emit debugMessage(QObject::tr("Setting speaker volume...")); 343 emit debugMessage(QObject::tr("Setting speaker volume..."));
344 344
345 setExpect(_ifaceppp->data()->modemInitResp()); 345 setExpect(_ifaceppp->data()->modemInitResp());
346 QString vol("AT"); 346 QString vol("AT");
347 vol += _ifaceppp->data()->volumeInitString(); 347 vol += _ifaceppp->data()->volumeInitString();
348 writeline(vol); 348 writeline(vol);
349 usleep(_ifaceppp->data()->modemInitDelay() * 10000); // 0.01 - 3.0 sec 349 usleep(_ifaceppp->data()->modemInitDelay() * 10000); // 0.01 - 3.0 sec
350 vmain = 4; 350 vmain = 4;
351 return; 351 return;
352 } 352 }
353 } 353 }
354 354
355 if(vmain == 4) { 355 if(vmain == 4) {
356 if(!expecting) { 356 if(!expecting) {
357 if(!_ifaceppp->data()->waitForDialTone()) { 357 if(!_ifaceppp->data()->waitForDialTone()) {
358 QString msg = QObject::tr("Turning off dial tone waiting..."); 358 QString msg = QObject::tr("Turning off dial tone waiting...");
359 messg->setText(msg); 359 messg->setText(msg);
360 emit debugMessage(msg); 360 emit debugMessage(msg);
361 setExpect(_ifaceppp->data()->modemInitResp()); 361 setExpect(_ifaceppp->data()->modemInitResp());
362 writeline(_ifaceppp->data()->modemNoDialToneDetectionStr()); 362 writeline(_ifaceppp->data()->modemNoDialToneDetectionStr());
363 } 363 }
364 vmain = 1; 364 vmain = 1;
365 return; 365 return;
366 } 366 }
367 } 367 }
368 368
369 // dial the number and wait to connect 369 // dial the number and wait to connect
370 if(vmain == 1) { 370 if(vmain == 1) {
371 if(!expecting) { 371 if(!expecting) {
372 372
373 timeout_timer->stop(); 373 timeout_timer->stop();
374 timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000); 374 timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000);
375 375
376 QStringList &plist = _ifaceppp->data()->phonenumbers(); 376 QStringList &plist = _ifaceppp->data()->phonenumbers();
377 QString bmarg= _ifaceppp->data()->dialPrefix(); 377 QString bmarg= _ifaceppp->data()->dialPrefix();
378 bmarg += *plist.at(dialnumber); 378 bmarg += *plist.at(dialnumber);
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
572 scriptindex++; 572 scriptindex++;
573 return; 573 return;
574 } 574 }
575 575
576 if (scriptCommand == "Hangup") { 576 if (scriptCommand == "Hangup") {
577 messg->setText(QObject::tr("Hangup")); 577 messg->setText(QObject::tr("Hangup"));
578 emit debugMessage(QObject::tr("Hangup")); 578 emit debugMessage(QObject::tr("Hangup"));
579 579
580 writeline(_ifaceppp->data()->modemHangupStr()); 580 writeline(_ifaceppp->data()->modemHangupStr());
581 setExpect(_ifaceppp->data()->modemHangupResp()); 581 setExpect(_ifaceppp->data()->modemHangupResp());
582 582
583 scriptindex++; 583 scriptindex++;
584 return; 584 return;
585 } 585 }
586 586
587 if (scriptCommand == "Answer") { 587 if (scriptCommand == "Answer") {
588 588
589 timeout_timer->stop(); 589 timeout_timer->stop();
590 590
591 messg->setText(QObject::tr("Answer")); 591 messg->setText(QObject::tr("Answer"));
592 emit debugMessage(QObject::tr("Answer")); 592 emit debugMessage(QObject::tr("Answer"));
593 593
594 setExpect(_ifaceppp->data()->modemRingResp()); 594 setExpect(_ifaceppp->data()->modemRingResp());
595 vmain = 150; 595 vmain = 150;
596 return; 596 return;
597 } 597 }
598 598
599 if (scriptCommand == "ID") { 599 if (scriptCommand == "ID") {
600 QString bm = QObject::tr("ID %1").arg(scriptArgument); 600 QString bm = QObject::tr("ID %1").arg(scriptArgument);
601 messg->setText(bm); 601 messg->setText(bm);
602 emit debugMessage(bm); 602 emit debugMessage(bm);
603 603
604 QString idstring = _ifaceppp->data()->password(); 604 QString idstring = _ifaceppp->data()->password();
605 605
606 if(!idstring.isEmpty() && firstrunID) { 606 if(!idstring.isEmpty() && firstrunID) {
607 // the user entered an Id on the main kppp dialog 607 // the user entered an Id on the main kppp dialog
608 writeline(idstring); 608 writeline(idstring);
609 firstrunID = false; 609 firstrunID = false;
610 scriptindex++; 610 scriptindex++;
611 } 611 }
612 else { 612 else {
613 // the user didn't enter and Id on the main kppp dialog 613 // the user didn't enter and Id on the main kppp dialog
614 // let's query for an ID 614 // let's query for an ID
615 /* if not around yet, then post window... */ 615 /* if not around yet, then post window... */
616 if (prompt->Consumed()) { 616 if (prompt->Consumed()) {
617 if (!(prompt->isVisible())) { 617 if (!(prompt->isVisible())) {
618 prompt->setPrompt(scriptArgument); 618 prompt->setPrompt(scriptArgument);
619 prompt->setEchoModeNormal(); 619 prompt->setEchoModeNormal();
620 prompt->show(); 620 prompt->show();
621 } 621 }
622 } else { 622 } else {
623 /* if prompt withdrawn ... then, */ 623 /* if prompt withdrawn ... then, */
624 if(!(prompt->isVisible())) { 624 if(!(prompt->isVisible())) {
625 writeline(prompt->text()); 625 writeline(prompt->text());
626 prompt->setConsumed(); 626 prompt->setConsumed();
627 scriptindex++; 627 scriptindex++;
628 return; 628 return;
629 } 629 }
630 /* replace timeout value */ 630 /* replace timeout value */
631 } 631 }
632 } 632 }
633 } 633 }
634 634
635 if (scriptCommand == "Password") { 635 if (scriptCommand == "Password") {
636 QString bm = QObject::tr("Password %1").arg(scriptArgument); 636 QString bm = QObject::tr("Password %1").arg(scriptArgument);
637 messg->setText(bm); 637 messg->setText(bm);
638 emit debugMessage(bm); 638 emit debugMessage(bm);
639 639
640 QString pwstring = _ifaceppp->data()->password(); 640 QString pwstring = _ifaceppp->data()->password();
641 641
642 if(!pwstring.isEmpty() && firstrunPW) { 642 if(!pwstring.isEmpty() && firstrunPW) {
643 // the user entered a password on the main kppp dialog 643 // the user entered a password on the main kppp dialog
644 writeline(pwstring); 644 writeline(pwstring);
645 firstrunPW = false; 645 firstrunPW = false;
646 scriptindex++; 646 scriptindex++;
647 } 647 }
648 else { 648 else {
649 // the user didn't enter a password on the main kppp dialog 649 // the user didn't enter a password on the main kppp dialog
650 // let's query for a password 650 // let's query for a password
651 /* if not around yet, then post window... */ 651 /* if not around yet, then post window... */
652 if (prompt->Consumed()) { 652 if (prompt->Consumed()) {
653 if (!(prompt->isVisible())) { 653 if (!(prompt->isVisible())) {
654 prompt->setPrompt(scriptArgument); 654 prompt->setPrompt(scriptArgument);
655 prompt->setEchoModePassword(); 655 prompt->setEchoModePassword();
656 prompt->show(); 656 prompt->show();
657 } 657 }
658 } else { 658 } else {
659 /* if prompt withdrawn ... then, */ 659 /* if prompt withdrawn ... then, */
660 if(!(prompt->isVisible())) { 660 if(!(prompt->isVisible())) {
661 // p_kppp->setPW_Edit(prompt->text()); 661 // p_kppp->setPW_Edit(prompt->text());
662 writeline(prompt->text()); 662 writeline(prompt->text());
663 prompt->setConsumed(); 663 prompt->setConsumed();
664 scriptindex++; 664 scriptindex++;
665 return; 665 return;
666 } 666 }
667 /* replace timeout value */ 667 /* replace timeout value */
668 } 668 }
669 } 669 }
670 } 670 }
671 671
672 if (scriptCommand == "Prompt") { 672 if (scriptCommand == "Prompt") {
673 QString bm = QObject::tr("Prompting %1"); 673 QString bm = QObject::tr("Prompting %1");
674 674
675 // if the scriptindex (aka the prompt text) includes a ## marker 675 // if the scriptindex (aka the prompt text) includes a ## marker
676 // this marker should get substituted with the contents of our stored 676 // this marker should get substituted with the contents of our stored
677 // variable (from the subsequent scan). 677 // variable (from the subsequent scan).
678 678
679 QString ts = scriptArgument; 679 QString ts = scriptArgument;
680 int vstart = ts.find( "##" ); 680 int vstart = ts.find( "##" );
681 if( vstart != -1 ) { 681 if( vstart != -1 ) {
682 ts.remove( vstart, 2 ); 682 ts.remove( vstart, 2 );
683 ts.insert( vstart, scanvar ); 683 ts.insert( vstart, scanvar );
684 } 684 }
685 685
686 bm = bm.arg(ts); 686 bm = bm.arg(ts);
687 messg->setText(bm); 687 messg->setText(bm);
688 emit debugMessage(bm); 688 emit debugMessage(bm);
689 689
690 /* if not around yet, then post window... */ 690 /* if not around yet, then post window... */
691 if (prompt->Consumed()) { 691 if (prompt->Consumed()) {
692 if (!(prompt->isVisible())) { 692 if (!(prompt->isVisible())) {
693 prompt->setPrompt( ts ); 693 prompt->setPrompt( ts );
694 prompt->setEchoModeNormal(); 694 prompt->setEchoModeNormal();
695 prompt->show(); 695 prompt->show();
696 } 696 }
697 } else { 697 } else {
698 /* if prompt withdrawn ... then, */ 698 /* if prompt withdrawn ... then, */
699 if (!(prompt->isVisible())) { 699 if (!(prompt->isVisible())) {
700 writeline(prompt->text()); 700 writeline(prompt->text());
701 prompt->setConsumed(); 701 prompt->setConsumed();
702 scriptindex++; 702 scriptindex++;
703 return; 703 return;
704 } 704 }
705 /* replace timeout value */ 705 /* replace timeout value */
706 } 706 }
707 } 707 }
708 708
709 if (scriptCommand == "PWPrompt") { 709 if (scriptCommand == "PWPrompt") {
710 QString bm = QObject::tr("PW Prompt %1").arg(scriptArgument); 710 QString bm = QObject::tr("PW Prompt %1").arg(scriptArgument);
711 messg->setText(bm); 711 messg->setText(bm);
712 emit debugMessage(bm); 712 emit debugMessage(bm);
713 713
714 /* if not around yet, then post window... */ 714 /* if not around yet, then post window... */
715 if (prompt->Consumed()) { 715 if (prompt->Consumed()) {
716 if (!(prompt->isVisible())) { 716 if (!(prompt->isVisible())) {
717 prompt->setPrompt(scriptArgument); 717 prompt->setPrompt(scriptArgument);
718 prompt->setEchoModePassword(); 718 prompt->setEchoModePassword();
719 prompt->show(); 719 prompt->show();
720 } 720 }
721 } else { 721 } else {
722 /* if prompt withdrawn ... then, */ 722 /* if prompt withdrawn ... then, */
723 if (!(prompt->isVisible())) { 723 if (!(prompt->isVisible())) {
724 writeline(prompt->text()); 724 writeline(prompt->text());
725 prompt->setConsumed(); 725 prompt->setConsumed();
726 scriptindex++; 726 scriptindex++;
727 return; 727 return;
728 } 728 }
729 /* replace timeout value */ 729 /* replace timeout value */
730 } 730 }
731 } 731 }
732 732
733 if (scriptCommand == "LoopStart") { 733 if (scriptCommand == "LoopStart") {
734 734
735 QString bm = QObject::tr("Loop Start %1").arg(scriptArgument); 735 QString bm = QObject::tr("Loop Start %1").arg(scriptArgument);
736 736
737 // The incrementing of the scriptindex MUST be before the 737 // The incrementing of the scriptindex MUST be before the
738 // call to setExpect otherwise the expect will miss a string that is 738 // call to setExpect otherwise the expect will miss a string that is
739 // already in the buffer. 739 // already in the buffer.
740 scriptindex++; 740 scriptindex++;
741 741
742 if ( loopnest > (MAXLOOPNEST-2) ) { 742 if ( loopnest > (MAXLOOPNEST-2) ) {
743 bm += QObject::tr("ERROR: Nested too deep, ignored."); 743 bm += QObject::tr("ERROR: Nested too deep, ignored.");
744 vmain=20; 744 vmain=20;
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 }
948 } 948 }
949 949
950 if (loopend && readbuffer.contains(loopstr[loopnest])) { 950 if (loopend && readbuffer.contains(loopstr[loopnest])) {
951 expecting = false; 951 expecting = false;
952 readbuffer = ""; 952 readbuffer = "";
953 QString ts = QObject::tr("Looping: %1").arg(loopstr[loopnest]); 953 QString ts = QObject::tr("Looping: %1").arg(loopstr[loopnest]);
954 emit debugMessage(ts); 954 emit debugMessage(ts);
955 scriptindex = loopstartindex[loopnest]; 955 scriptindex = loopstartindex[loopnest];
956 loopend = false; 956 loopend = false;
957 loopnest++; 957 loopnest++;
958 } 958 }
959 // notify event loop if expected string was found 959 // notify event loop if expected string was found
960 if(!expecting) 960 if(!expecting)
961 timerEvent((QTimerEvent *) 0); 961 timerEvent((QTimerEvent *) 0);
962 } 962 }
963} 963}
964 964
965 965
966 966
967void ConnectWidget::pause() { 967void ConnectWidget::pause() {
968 pausing = false; 968 pausing = false;
969 pausetimer->stop(); 969 pausetimer->stop();
970} 970}
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()) {
1164// // p_kppp->con_win->showMinimized(); 1164// // p_kppp->con_win->showMinimized();
1165// } 1165// }
1166// } 1166// }
1167 1167
1168 _ifaceppp->modem()->closetty(); 1168 _ifaceppp->modem()->closetty();
1169} 1169}
1170 1170
1171void ConnectWidget::refresh() { 1171void ConnectWidget::refresh() {
1172 _ifaceppp->refresh(); 1172 _ifaceppp->refresh();
1173 if ( _ifaceppp->getStatus() ) { 1173 if ( _ifaceppp->getStatus() ) {
1174 messg->setText(QObject::tr("Online")); 1174 messg->setText(QObject::tr("Online"));
1175 } else { 1175 } else {
1176 messg->setText(QObject::tr("Offline")); 1176 messg->setText(QObject::tr("Offline"));
1177 } 1177 }
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";
1371 write(fd, tmp, tmp.length()); 1371 write(fd, tmp, tmp.length());
1372 } 1372 }
1373 } 1373 }
1374 } 1374 }
1375 close(fd); 1375 close(fd);
1376 } 1376 }
1377} 1377}
1378 1378
1379 1379
1380// adds the DNS entries in the /etc/resolv.conf file 1380// adds the DNS entries in the /etc/resolv.conf file
1381void adddns( InterfacePPP *_ifaceppp) 1381void adddns( InterfacePPP *_ifaceppp)
1382{ 1382{
1383 int fd; 1383 int fd;
1384 1384
1385 if ((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_APPEND)) >= 0) { 1385 if ((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_APPEND)) >= 0) {
1386 QStringList &dnslist = _ifaceppp->data()->dns(); 1386 QStringList &dnslist = _ifaceppp->data()->dns();
1387 for ( QStringList::Iterator it = dnslist.begin(); 1387 for ( QStringList::Iterator it = dnslist.begin();
1388 it != dnslist.end(); 1388 it != dnslist.end();
1389 ++it ) 1389 ++it )
1390 { 1390 {
1391 QCString dns = "nameserver " + (*it).local8Bit() + 1391 QCString dns = "nameserver " + (*it).local8Bit() +
1392 " \t#kppp temp entry\n"; 1392 " \t#kppp temp entry\n";
1393 write(fd, dns.data(), dns.length()); 1393 write(fd, dns.data(), dns.length());
1394 } 1394 }
1395 close(fd); 1395 close(fd);
1396 } 1396 }
1397 add_domain(_ifaceppp->data()->domain(), _ifaceppp); 1397 add_domain(_ifaceppp->data()->domain(), _ifaceppp);
1398} 1398}
1399 1399
1400void addpeerdns(InterfacePPP *_ifaceppp) { 1400void addpeerdns(InterfacePPP *_ifaceppp) {
1401 int fd, fd2; 1401 int fd, fd2;
1402 1402
1403 if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_APPEND)) >= 0) { 1403 if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_APPEND)) >= 0) {
1404 if((fd2 = open("/etc/ppp/resolv.conf", O_RDONLY)) >= 0) { 1404 if((fd2 = open("/etc/ppp/resolv.conf", O_RDONLY)) >= 0) {
1405 char c; 1405 char c;
1406 int i = 0; 1406 int i = 0;
1407 while(i++ < 100 && read(fd2, &c, 1) == 1) { 1407 while(i++ < 100 && read(fd2, &c, 1) == 1) {
1408 if(c == '\n') 1408 if(c == '\n')
1409 write(fd, "\t#kppp temp entry\n", 18); 1409 write(fd, "\t#kppp temp entry\n", 18);
1410 else 1410 else
1411 write(fd, &c, 1); 1411 write(fd, &c, 1);
1412 } 1412 }
1413 close(fd2); 1413 close(fd2);
1414 } else 1414 } else
1415 fprintf(stderr, "failed to read from /etc/ppp/resolv.conf\n"); 1415 fprintf(stderr, "failed to read from /etc/ppp/resolv.conf\n");
1416 close(fd); 1416 close(fd);
1417 } 1417 }
1418 add_domain(_ifaceppp->data()->domain(), _ifaceppp); 1418 add_domain(_ifaceppp->data()->domain(), _ifaceppp);
1419} 1419}
1420 1420
1421// remove the dns entries from the /etc/resolv.conf file 1421// remove the dns entries from the /etc/resolv.conf file
1422void removedns(InterfacePPP *_ifaceppp) { 1422void removedns(InterfacePPP *_ifaceppp) {
1423 1423
1424 int fd; 1424 int fd;
1425 char c; 1425 char c;
1426 QString resolv[MAX_RESOLVCONF_LINES]; 1426 QString resolv[MAX_RESOLVCONF_LINES];
1427 1427
1428 if((fd = _ifaceppp->modem()->openResolv(O_RDONLY)) >= 0) { 1428 if((fd = _ifaceppp->modem()->openResolv(O_RDONLY)) >= 0) {
1429 1429
1430 int i=0; 1430 int i=0;
1431 while(read(fd, &c, 1) == 1 && i < MAX_RESOLVCONF_LINES) { 1431 while(read(fd, &c, 1) == 1 && i < MAX_RESOLVCONF_LINES) {
1432 if(c == '\n') { 1432 if(c == '\n') {
1433 i++; 1433 i++;
1434 } 1434 }
1435 else { 1435 else {
1436 resolv[i] += c; 1436 resolv[i] += c;
1437 } 1437 }
1438 } 1438 }
1439 close(fd); 1439 close(fd);
1440 1440
1441 if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_TRUNC)) >= 0) { 1441 if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_TRUNC)) >= 0) {
1442 for(int j=0; j < i; j++) { 1442 for(int j=0; j < i; j++) {
1443 if(resolv[j].contains("#kppp temp entry")) continue; 1443 if(resolv[j].contains("#kppp temp entry")) continue;
1444 if(resolv[j].contains("#entry disabled by kppp")) { 1444 if(resolv[j].contains("#entry disabled by kppp")) {
1445 QCString tmp = resolv[j].local8Bit(); 1445 QCString tmp = resolv[j].local8Bit();
1446 write(fd, tmp.data()+2, tmp.length() - 27); 1446 write(fd, tmp.data()+2, tmp.length() - 27);
1447 write(fd, "\n", 1); 1447 write(fd, "\n", 1);
1448 } 1448 }
1449 else { 1449 else {
1450 QCString tmp = resolv[j].local8Bit() + "\n"; 1450 QCString tmp = resolv[j].local8Bit() + "\n";
1451 write(fd, tmp, tmp.length()); 1451 write(fd, tmp, tmp.length());
1452 } 1452 }
1453 } 1453 }
1454 } 1454 }
1455 close(fd); 1455 close(fd);
1456 1456
1457 } 1457 }
1458 1458
1459 if ( modified_hostname ) { 1459 if ( modified_hostname ) {
1460 _ifaceppp->modem()->setHostname(old_hostname); 1460 _ifaceppp->modem()->setHostname(old_hostname);
1461 modified_hostname = FALSE; 1461 modified_hostname = FALSE;
1462 } 1462 }
1463 1463
1464} 1464}
1465 1465
1466 1466
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,217 +1,217 @@
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
176 QTabWidget *tabWindow = new QTabWidget( dlg, "tabWindow" ); 176 QTabWidget *tabWindow = new QTabWidget( dlg, "tabWindow" );
177 layout->addWidget( tabWindow ); 177 layout->addWidget( tabWindow );
178 178
179 bool isnew; 179 bool isnew;
180 180
181 if(_pppdata->devname().isEmpty()) { 181 if(_pppdata->devname().isEmpty()) {
182 dlg->setCaption(tr("New Device")); 182 dlg->setCaption(tr("New Device"));
183 isnew = true; 183 isnew = true;
184 } else { 184 } else {
185 QString tit = tr("Edit Device: "); 185 QString tit = tr("Edit Device: ");
186 tit += _pppdata->devname(); 186 tit += _pppdata->devname();
187 dlg->setCaption(tit); 187 dlg->setCaption(tit);
188 isnew = false; 188 isnew = false;
189 } 189 }
190 190
191 modem1 = new ModemWidget( _pppdata, tabWindow, "modem1" ); 191 modem1 = new ModemWidget( _pppdata, tabWindow, "modem1" );
192 tabWindow->addTab( modem1, tr("&Device") ); 192 tabWindow->addTab( modem1, tr("&Device") );
193 modem2 = new ModemWidget2( _pppdata, _ifaceppp, tabWindow, "modem2" ); 193 modem2 = new ModemWidget2( _pppdata, _ifaceppp, tabWindow, "modem2" );
194 tabWindow->addTab( modem2, tr("&Modem") ); 194 tabWindow->addTab( modem2, tr("&Modem") );
195 195
196 int result = 0; 196 int result = 0;
197 bool ok = false; 197 bool ok = false;
198 198
199 while (!ok){ 199 while (!ok){
200 result = QPEApplication::execDialog( dlg ); 200 result = QPEApplication::execDialog( dlg );
201 ok = true; 201 ok = true;
202 202
203 if(result == QDialog::Accepted) { 203 if(result == QDialog::Accepted) {
204 if (!modem1->save()){ 204 if (!modem1->save()){
205 QMessageBox::critical(this, "error", tr( "You must enter a unique device name")); 205 QMessageBox::critical(this, "error", tr( "You must enter a unique device name"));
206 ok = false; 206 ok = false;
207 }else{ 207 }else{
208 modem2->save(); 208 modem2->save();
209 } 209 }
210 } 210 }
211 } 211 }
212 212
213 delete dlg; 213 delete dlg;
214 214
215 return result; 215 return result;
216} 216}
217 217
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
@@ -1,526 +1,526 @@
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 "general.h" 27#include "general.h"
28#include "interfaceppp.h" 28#include "interfaceppp.h"
29#include "modeminfo.h" 29#include "modeminfo.h"
30#include "modemcmds.h" 30#include "modemcmds.h"
31#include "pppdata.h" 31#include "pppdata.h"
32 32
33/* OPIE */ 33/* OPIE */
34#include <qpe/config.h> 34#include <qpe/config.h>
35#include <qpe/qpeapplication.h> 35#include <qpe/qpeapplication.h>
36 36
37/* QT */ 37/* QT */
38#include <qcheckbox.h> 38#include <qcheckbox.h>
39#include <qcombobox.h> 39#include <qcombobox.h>
40#include <qlabel.h> 40#include <qlabel.h>
41#include <qlayout.h> 41#include <qlayout.h>
42#include <qpushbutton.h> 42#include <qpushbutton.h>
43#include <qslider.h> 43#include <qslider.h>
44#include <qspinbox.h> 44#include <qspinbox.h>
45#include <qwhatsthis.h> 45#include <qwhatsthis.h>
46 46
47/* STD */ 47/* STD */
48#include <termios.h> 48#include <termios.h>
49#include <string.h> 49#include <string.h>
50 50
51 51
52ModemWidget::ModemWidget( PPPData *pd, QWidget *parent, const char *name ) 52ModemWidget::ModemWidget( PPPData *pd, QWidget *parent, const char *name )
53 : QWidget(parent, name), _pppdata(pd) 53 : QWidget(parent, name), _pppdata(pd)
54{ 54{
55 int k; 55 int k;
56 56
57 QGridLayout *tl = new QGridLayout(this, 8, 2, 0 );//, KDialog::spacingHint()); 57 QGridLayout *tl = new QGridLayout(this, 8, 2, 0 );//, KDialog::spacingHint());
58 58
59 QLabel *label1; 59 QLabel *label1;
60 60
61 label1 = new QLabel(tr("Modem &name:"), this); 61 label1 = new QLabel(tr("Modem &name:"), this);
62 tl->addWidget(label1, 0, 0); 62 tl->addWidget(label1, 0, 0);
63 63
64 modemname = new QLineEdit(this, "modemName"); 64 modemname = new QLineEdit(this, "modemName");
65 modemname->setText( _pppdata->devname() ); 65 modemname->setText( _pppdata->devname() );
66 label1->setBuddy(modemname); 66 label1->setBuddy(modemname);
67 tl->addWidget(modemname, 0, 1); 67 tl->addWidget(modemname, 0, 1);
68 68
69 label1 = new QLabel(tr("Modem de&vice:"), this); 69 label1 = new QLabel(tr("Modem de&vice:"), this);
70 tl->addWidget(label1, 1, 0); 70 tl->addWidget(label1, 1, 0);
71 71
72 modemdevice = new QComboBox(false, this); 72 modemdevice = new QComboBox(false, this);
73 modemdevice->setEditable( true ); 73 modemdevice->setEditable( true );
74 modemdevice->setDuplicatesEnabled ( false ); 74 modemdevice->setDuplicatesEnabled ( false );
75 modemdevice->setInsertionPolicy( QComboBox::AtTop ); 75 modemdevice->setInsertionPolicy( QComboBox::AtTop );
76 label1->setBuddy(modemdevice); 76 label1->setBuddy(modemdevice);
77 77
78 Config cfg("NetworkSetupPPP"); 78 Config cfg("NetworkSetupPPP");
79 cfg.setGroup("Devices_General"); 79 cfg.setGroup("Devices_General");
80 QStringList devs = cfg.readListEntry("devices",','); 80 QStringList devs = cfg.readListEntry("devices",',');
81 if (devs.isEmpty()) devs << "/dev/modem" << "/dev/ircomm0" << "/dev/ttyS0"; 81 if (devs.isEmpty()) devs << "/dev/modem" << "/dev/ircomm0" << "/dev/ttyS0";
82 modemdevice->insertStringList( devs ); 82 modemdevice->insertStringList( devs );
83 tl->addWidget(modemdevice, 1, 1); 83 tl->addWidget(modemdevice, 1, 1);
84 84
85 // connect(modemdevice, SIGNAL(activated(int)), 85 // connect(modemdevice, SIGNAL(activated(int)),
86 // SLOT(setmodemdc(int))); 86 // SLOT(setmodemdc(int)));
87 // connect(modemdevice, SIGNAL(textChanged(const QString&) ), 87 // connect(modemdevice, SIGNAL(textChanged(const QString&) ),
88 // SLOT( setmodemdc(const QString&) ) ); 88 // SLOT( setmodemdc(const QString&) ) );
89 89
90 QString tmp = tr("This specifies the serial port your modem is attached \n" 90 QString tmp = tr("This specifies the serial port your modem is attached \n"
91 "to. On Linux/x86, typically this is either /dev/ttyS0 \n" 91 "to. On Linux/x86, typically this is either /dev/ttyS0 \n"
92 "(COM1 under DOS) or /dev/ttyS1 (COM2 under DOS).\n" 92 "(COM1 under DOS) or /dev/ttyS1 (COM2 under DOS).\n"
93 "\n" 93 "\n"
94 "If you have an internal ISDN card with AT command\n" 94 "If you have an internal ISDN card with AT command\n"
95 "emulation (most cards under Linux support this), you\n" 95 "emulation (most cards under Linux support this), you\n"
96 "should select one of the /dev/ttyIx devices."); 96 "should select one of the /dev/ttyIx devices.");
97 97
98 QWhatsThis::add(label1,tmp); 98 QWhatsThis::add(label1,tmp);
99 QWhatsThis::add(modemdevice,tmp); 99 QWhatsThis::add(modemdevice,tmp);
100 100
101 101
102 label1 = new QLabel(tr("&Flow control:"), this); 102 label1 = new QLabel(tr("&Flow control:"), this);
103 tl->addWidget(label1, 2, 0); 103 tl->addWidget(label1, 2, 0);
104 104
105 flowcontrol = new QComboBox(false, this); 105 flowcontrol = new QComboBox(false, this);
106 label1->setBuddy(flowcontrol); 106 label1->setBuddy(flowcontrol);
107 flowcontrol->insertItem(tr("Hardware [CRTSCTS]")); 107 flowcontrol->insertItem(tr("Hardware [CRTSCTS]"));
108 flowcontrol->insertItem(tr("Software [XON/XOFF]")); 108 flowcontrol->insertItem(tr("Software [XON/XOFF]"));
109 flowcontrol->insertItem(tr("None")); 109 flowcontrol->insertItem(tr("None"));
110 tl->addWidget(flowcontrol, 2, 1); 110 tl->addWidget(flowcontrol, 2, 1);
111 // connect(flowcontrol, SIGNAL(activated(int)), 111 // connect(flowcontrol, SIGNAL(activated(int)),
112 // SLOT(setflowcontrol(int))); 112 // SLOT(setflowcontrol(int)));
113 113
114 tmp = tr("<p>Specifies how the serial port and modem\n" 114 tmp = tr("<p>Specifies how the serial port and modem\n"
115 "communicate. You should not change this unless\n" 115 "communicate. You should not change this unless\n"
116 "you know what you are doing.\n" 116 "you know what you are doing.\n"
117 "\n" 117 "\n"
118 "<b>Default</b>: CRTSCTS"); 118 "<b>Default</b>: CRTSCTS");
119 119
120 QWhatsThis::add(label1,tmp); 120 QWhatsThis::add(label1,tmp);
121 QWhatsThis::add(flowcontrol,tmp); 121 QWhatsThis::add(flowcontrol,tmp);
122 122
123 QLabel *labelenter = new QLabel(tr("&Line termination:"), this); 123 QLabel *labelenter = new QLabel(tr("&Line termination:"), this);
124 tl->addWidget(labelenter, 3, 0); 124 tl->addWidget(labelenter, 3, 0);
125 125
126 enter = new QComboBox(false, this); 126 enter = new QComboBox(false, this);
127 labelenter->setBuddy(enter); 127 labelenter->setBuddy(enter);
128 enter->insertItem("CR"); 128 enter->insertItem("CR");
129 enter->insertItem("LF"); 129 enter->insertItem("LF");
130 enter->insertItem("CR/LF"); 130 enter->insertItem("CR/LF");
131 tl->addWidget(enter, 3, 1); 131 tl->addWidget(enter, 3, 1);
132 // connect(enter, SIGNAL(activated(int)), SLOT(setenter(int))); 132 // connect(enter, SIGNAL(activated(int)), SLOT(setenter(int)));
133 tmp = tr("<p>Specifies how AT commands are sent to your\n" 133 tmp = tr("<p>Specifies how AT commands are sent to your\n"
134 "modem. Most modems will work fine with the\n" 134 "modem. Most modems will work fine with the\n"
135 "default <i>CR/LF</i>. If your modem does not react\n" 135 "default <i>CR/LF</i>. If your modem does not react\n"
136 "to the init string, you should try different\n" 136 "to the init string, you should try different\n"
137 "settings here\n" 137 "settings here\n"
138 "\n" 138 "\n"
139 "<b>Default</b>: CR/LF"); 139 "<b>Default</b>: CR/LF");
140 140
141 QWhatsThis::add(labelenter,tmp); 141 QWhatsThis::add(labelenter,tmp);
142 QWhatsThis::add(enter, tmp); 142 QWhatsThis::add(enter, tmp);
143 143
144 QLabel *baud_label = new QLabel(tr("Co&nnection speed:"), this); 144 QLabel *baud_label = new QLabel(tr("Co&nnection speed:"), this);
145 tl->addWidget(baud_label, 4, 0); 145 tl->addWidget(baud_label, 4, 0);
146 baud_c = new QComboBox(this); 146 baud_c = new QComboBox(this);
147 baud_label->setBuddy(baud_c); 147 baud_label->setBuddy(baud_c);
148 148
149 static const char *baudrates[] = 149 static const char *baudrates[] =
150 { 150 {
151 151
152#ifdef B460800 152#ifdef B460800
153 "460800", 153 "460800",
154#endif 154#endif
155 155
156#ifdef B230400 156#ifdef B230400
157 "230400", 157 "230400",
158#endif 158#endif
159 159
160#ifdef B115200 160#ifdef B115200
161 "115200", 161 "115200",
162#endif 162#endif
163 163
164#ifdef B57600 164#ifdef B57600
165 "57600", 165 "57600",
166#endif 166#endif
167 167
168 "38400", 168 "38400",
169 "19200", 169 "19200",
170 "9600", 170 "9600",
171 "2400", 171 "2400",
172 0 172 0
173 }; 173 };
174 174
175 for(k = 0; baudrates[k]; k++) 175 for(k = 0; baudrates[k]; k++)
176 baud_c->insertItem(baudrates[k]); 176 baud_c->insertItem(baudrates[k]);
177 177
178 baud_c->setCurrentItem(3); 178 baud_c->setCurrentItem(3);
179 // connect(baud_c, SIGNAL(activated(int)), 179 // connect(baud_c, SIGNAL(activated(int)),
180 // this, SLOT(speed_selection(int))); 180 // this, SLOT(speed_selection(int)));
181 tl->addWidget(baud_c, 4, 1); 181 tl->addWidget(baud_c, 4, 1);
182 182
183 tmp = tr("Specifies the speed your modem and the serial\n" 183 tmp = tr("Specifies the speed your modem and the serial\n"
184 "port talk to each other. You should begin with\n" 184 "port talk to each other. You should begin with\n"
185 "the default of 38400 bits/sec. If everything\n" 185 "the default of 38400 bits/sec. If everything\n"
186 "works you can try to increase this value, but to\n" 186 "works you can try to increase this value, but to\n"
187 "no more than 115200 bits/sec (unless you know\n" 187 "no more than 115200 bits/sec (unless you know\n"
188 "that your serial port supports higher speeds)."); 188 "that your serial port supports higher speeds).");
189 189
190 QWhatsThis::add(baud_label,tmp); 190 QWhatsThis::add(baud_label,tmp);
191 QWhatsThis::add(baud_c,tmp); 191 QWhatsThis::add(baud_c,tmp);
192 192
193 for(int i=0; i <= enter->count()-1; i++) 193 for(int i=0; i <= enter->count()-1; i++)
194 { 194 {
195 if(_pppdata->enter() == enter->text(i)) 195 if(_pppdata->enter() == enter->text(i))
196 enter->setCurrentItem(i); 196 enter->setCurrentItem(i);
197 } 197 }
198 198
199 tl->addRowSpacing(5, 10); 199 tl->addRowSpacing(5, 10);
200 200
201 //Modem Lock File 201 //Modem Lock File
202 modemlockfile = new QCheckBox(tr("&Use lock file"), this); 202 modemlockfile = new QCheckBox(tr("&Use lock file"), this);
203 203
204 modemlockfile->setChecked(_pppdata->modemLockFile()); 204 modemlockfile->setChecked(_pppdata->modemLockFile());
205 // connect(modemlockfile, SIGNAL(toggled(bool)), 205 // connect(modemlockfile, SIGNAL(toggled(bool)),
206 // SLOT(modemlockfilechanged(bool))); 206 // SLOT(modemlockfilechanged(bool)));
207 tl->addMultiCellWidget(modemlockfile, 6, 6, 0, 1); 207 tl->addMultiCellWidget(modemlockfile, 6, 6, 0, 1);
208 // l12->addStretch(1); 208 // l12->addStretch(1);
209 QWhatsThis::add(modemlockfile, 209 QWhatsThis::add(modemlockfile,
210 tr("<p>To prevent other programs from accessing the\n" 210 tr("<p>To prevent other programs from accessing the\n"
211 "modem while a connection is established, a\n" 211 "modem while a connection is established, a\n"
212 "file can be created to indicate that the modem\n" 212 "file can be created to indicate that the modem\n"
213 "is in use. On Linux an example file would be\n" 213 "is in use. On Linux an example file would be\n"
214 "<tt>/var/lock/LCK..ttyS1</tt>\n" 214 "<tt>/var/lock/LCK..ttyS1</tt>\n"
215 "Here you can select whether this locking will\n" 215 "Here you can select whether this locking will\n"
216 "be done.\n" 216 "be done.\n"
217 "\n" 217 "\n"
218 "<b>Default</b>: On")); 218 "<b>Default</b>: On"));
219 219
220 // Modem Timeout Line Edit Box 220 // Modem Timeout Line Edit Box
221 QHBoxLayout *timeoutLayout = new QHBoxLayout( this ); 221 QHBoxLayout *timeoutLayout = new QHBoxLayout( this );
222 QLabel *timeoutlabel = new QLabel( tr("Modem timeout:") ,this, "timeout" ); 222 QLabel *timeoutlabel = new QLabel( tr("Modem timeout:") ,this, "timeout" );
223 modemtimeout = new QSpinBox( 1, 120, 1, this, "modemTimeout" ); 223 modemtimeout = new QSpinBox( 1, 120, 1, this, "modemTimeout" );
224 // modemtimeout = new KIntNumInput(_pppdata->modemTimeout(), this); 224 // modemtimeout = new KIntNumInput(_pppdata->modemTimeout(), this);
225 // modemtimeout->setLabel(tr("Modem &timeout:")); 225 // modemtimeout->setLabel(tr("Modem &timeout:"));
226 // modemtimeout->setRange(1, 120, 1); 226 // modemtimeout->setRange(1, 120, 1);
227 modemtimeout->setSuffix(tr(" sec")); 227 modemtimeout->setSuffix(tr(" sec"));
228 modemtimeout->setValue( _pppdata->modemTimeout() ); 228 modemtimeout->setValue( _pppdata->modemTimeout() );
229 // connect(modemtimeout, SIGNAL(valueChanged(int)), 229 // connect(modemtimeout, SIGNAL(valueChanged(int)),
230 // SLOT(modemtimeoutchanged(int))); 230 // SLOT(modemtimeoutchanged(int)));
231 timeoutLayout->addWidget(timeoutlabel); 231 timeoutLayout->addWidget(timeoutlabel);
232 timeoutLayout->addWidget(modemtimeout); 232 timeoutLayout->addWidget(modemtimeout);
233 tl->addMultiCellLayout(timeoutLayout, 7, 7, 0, 1); 233 tl->addMultiCellLayout(timeoutLayout, 7, 7, 0, 1);
234 234
235 QWhatsThis::add(modemtimeout, 235 QWhatsThis::add(modemtimeout,
236 tr("This specifies how long <i>kppp</i> waits for a\n" 236 tr("This specifies how long <i>kppp</i> waits for a\n"
237 "<i>CONNECT</i> response from your modem. The\n" 237 "<i>CONNECT</i> response from your modem. The\n"
238 "recommended value is 30 seconds.")); 238 "recommended value is 30 seconds."));
239 239
240 //set stuff from gpppdata 240 //set stuff from gpppdata
241 for(int i=0; i <= enter->count()-1; i++) 241 for(int i=0; i <= enter->count()-1; i++)
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"));
435#endif 435#endif
436 436
437 modemcmds = new QPushButton(tr("Mod&em Commands..."), this); 437 modemcmds = new QPushButton(tr("Mod&em Commands..."), this);
438 QWhatsThis::add(modemcmds, 438 QWhatsThis::add(modemcmds,
439 tr("Allows you to change the AT command for\n" 439 tr("Allows you to change the AT command for\n"
440 "your modem.")); 440 "your modem."));
441 441
442 modeminfo_button = new QPushButton(tr("&Query Modem..."), this); 442 modeminfo_button = new QPushButton(tr("&Query Modem..."), this);
443 QWhatsThis::add(modeminfo_button, 443 QWhatsThis::add(modeminfo_button,
444 tr("Most modems support the ATI command set to\n" 444 tr("Most modems support the ATI command set to\n"
445 "find out vendor and revision of your modem.\n" 445 "find out vendor and revision of your modem.\n"
446 "\n" 446 "\n"
447 "Press this button to query your modem for\n" 447 "Press this button to query your modem for\n"
448 "this information. It can be useful to help\n" 448 "this information. It can be useful to help\n"
449 "you setup the modem")); 449 "you setup the modem"));
450 450
451 // terminal_button = new QPushButton(tr("&Terminal..."), this); 451 // terminal_button = new QPushButton(tr("&Terminal..."), this);
452 // QWhatsThis::add(terminal_button, 452 // QWhatsThis::add(terminal_button,
453 // tr("Opens the built-in terminal program. You\n" 453 // tr("Opens the built-in terminal program. You\n"
454 // "can use this if you want to play around\n" 454 // "can use this if you want to play around\n"
455 // "with your modem's AT command set")); 455 // "with your modem's AT command set"));
456 456
457 QHBoxLayout *hbox = new QHBoxLayout(); 457 QHBoxLayout *hbox = new QHBoxLayout();
458 l1->addLayout(hbox); 458 l1->addLayout(hbox);
459 hbox->addStretch(1); 459 hbox->addStretch(1);
460 QVBoxLayout *vbox = new QVBoxLayout(); 460 QVBoxLayout *vbox = new QVBoxLayout();
461 hbox->addLayout(vbox); 461 hbox->addLayout(vbox);
462 462
463 vbox->addWidget(modemcmds); 463 vbox->addWidget(modemcmds);
464 vbox->addWidget(modeminfo_button); 464 vbox->addWidget(modeminfo_button);
465 // vbox->addWidget(terminal_button); 465 // vbox->addWidget(terminal_button);
466 466
467 hbox->addStretch(1); 467 hbox->addStretch(1);
468 l1->addStretch(1); 468 l1->addStretch(1);
469 469
470 connect(modemcmds, SIGNAL(clicked()), 470 connect(modemcmds, SIGNAL(clicked()),
471 SLOT(modemcmdsbutton())); 471 SLOT(modemcmdsbutton()));
472 connect(modeminfo_button, SIGNAL(clicked()), 472 connect(modeminfo_button, SIGNAL(clicked()),
473 SLOT(query_modem())); 473 SLOT(query_modem()));
474 // connect(terminal_button, SIGNAL(clicked()), 474 // connect(terminal_button, SIGNAL(clicked()),
475 // SLOT(terminal())); 475 // SLOT(terminal()));
476} 476}
477 477
478 478
479void ModemWidget2::modemcmdsbutton() 479void ModemWidget2::modemcmdsbutton()
480{ 480{
481 ModemCommands mc(_ifaceppp->data(), this, "commands" , true, Qt::WStyle_ContextHelp); 481 ModemCommands mc(_ifaceppp->data(), this, "commands" , true, Qt::WStyle_ContextHelp);
482 482
483 QPEApplication::execDialog( &mc ); 483 QPEApplication::execDialog( &mc );
484} 484}
485 485
486 486
487void ModemWidget2::query_modem() 487void ModemWidget2::query_modem()
488{ 488{
489 ModemTransfer mt(_ifaceppp->modem(), this); 489 ModemTransfer mt(_ifaceppp->modem(), this);
490 mt.exec(); 490 mt.exec();
491} 491}
492 492
493 493
494// void ModemWidget2::terminal() { 494// void ModemWidget2::terminal() {
495// MiniTerm terminal(NULL,NULL); 495// MiniTerm terminal(NULL,NULL);
496// terminal.exec(); 496// terminal.exec();
497// } 497// }
498 498
499 499
500// #if 0 500// #if 0
501// void ModemWidget2::use_cdline_toggled(bool on) { 501// void ModemWidget2::use_cdline_toggled(bool on) {
502// _pppdata->setUseCDLine(on); 502// _pppdata->setUseCDLine(on);
503// } 503// }
504// #endif 504// #endif
505 505
506// void ModemWidget2::waitfordtchanged(bool b) { 506// void ModemWidget2::waitfordtchanged(bool b) {
507// _pppdata->setWaitForDialTone((int)b); 507// _pppdata->setWaitForDialTone((int)b);
508// } 508// }
509 509
510// void ModemWidget2::busywaitchanged(int n) { 510// void ModemWidget2::busywaitchanged(int n) {
511// _pppdata->setbusyWait(n); 511// _pppdata->setbusyWait(n);
512// } 512// }
513 513
514 514
515// void ModemWidget2::volumeChanged(int v) { 515// void ModemWidget2::volumeChanged(int v) {
516// _pppdata->setVolume(v); 516// _pppdata->setVolume(v);
517// } 517// }
518 518
519bool ModemWidget2::save() 519bool ModemWidget2::save()
520{ 520{
521 _pppdata->setWaitForDialTone(waitfordt->isChecked()); 521 _pppdata->setWaitForDialTone(waitfordt->isChecked());
522 _pppdata->setbusyWait(busywait->value()); 522 _pppdata->setbusyWait(busywait->value());
523 _pppdata->setVolume(volume->value()); 523 _pppdata->setVolume(volume->value());
524 return true; 524 return true;
525} 525}
526 526
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,877 +1,877 @@
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" ) );
180 connect( quit_b, SIGNAL(clicked()), SLOT(quitbutton())); 180 connect( quit_b, SIGNAL(clicked()), SLOT(quitbutton()));
181 if(quit_b->sizeHint().width() > minw) 181 if(quit_b->sizeHint().width() > minw)
182 minw = quit_b->sizeHint().width(); 182 minw = quit_b->sizeHint().width();
183 183
184 setup_b = new QPushButton(QObject::tr("&Setup..."), this); 184 setup_b = new QPushButton(QObject::tr("&Setup..."), this);
185// setup_b->setGuiItem (KGuiItem(QObject::tr("&Setup...")) ); 185// setup_b->setGuiItem (KGuiItem(QObject::tr("&Setup...")) );
186 connect( setup_b, SIGNAL(clicked()), SLOT(expandbutton())); 186 connect( setup_b, SIGNAL(clicked()), SLOT(expandbutton()));
187 if(setup_b->sizeHint().width() > minw) 187 if(setup_b->sizeHint().width() > minw)
188 minw = setup_b->sizeHint().width(); 188 minw = setup_b->sizeHint().width();
189 189
190 190
191 191
192// if(_pppdata->access() != KConfig::ReadWrite) 192// if(_pppdata->access() != KConfig::ReadWrite)
193 // setup_b->setEnabled(false); 193 // setup_b->setEnabled(false);
194 194
195// help_b = new QPushButton(QObject::tr("&Help"), this); 195// help_b = new QPushButton(QObject::tr("&Help"), this);
196// connect( help_b, SIGNAL(clicked()), SLOT(helpbutton())); 196// connect( help_b, SIGNAL(clicked()), SLOT(helpbutton()));
197 197
198// KHelpMenu *helpMenu = new KHelpMenu(this, KGlobal::instance()->aboutData(), true); 198// KHelpMenu *helpMenu = new KHelpMenu(this, KGlobal::instance()->aboutData(), true);
199// help_b->setPopup((QPopupMenu*)helpMenu->menu()); 199// help_b->setPopup((QPopupMenu*)helpMenu->menu());
200// help_b->setGuiItem (KGuiItem(QObject::tr("&Help"), "help" ) ); 200// help_b->setGuiItem (KGuiItem(QObject::tr("&Help"), "help" ) );
201 201
202// if(help_b->sizeHint().width() > minw) 202// if(help_b->sizeHint().width() > minw)
203// minw = help_b->sizeHint().width(); 203// minw = help_b->sizeHint().width();
204 204
205 connect_b = new QPushButton(QObject::tr("&Connect"), this); 205 connect_b = new QPushButton(QObject::tr("&Connect"), this);
206 connect_b->setDefault(true); 206 connect_b->setDefault(true);
207 connect_b->setFocus(); 207 connect_b->setFocus();
208 connect(connect_b, SIGNAL(clicked()), SLOT(beginConnect())); 208 connect(connect_b, SIGNAL(clicked()), SLOT(beginConnect()));
209 if(connect_b->sizeHint().width() > minw) 209 if(connect_b->sizeHint().width() > minw)
210 minw = connect_b->sizeHint().width(); 210 minw = connect_b->sizeHint().width();
211 211
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 }
611 611
612 this->hide(); 612 this->hide();
613 613
614 QString tit = QObject::tr("Connecting to: %1").arg(_pppdata->accname()); 614 QString tit = QObject::tr("Connecting to: %1").arg(_pppdata->accname());
615// con->setCaption(tit); 615// con->setCaption(tit);
616 616
617// con->show(); 617// con->show();
618 618
619 619
620 emit begin_connect(); 620 emit begin_connect();
621} 621}
622 622
623 623
624void KPPPWidget::disconnect() { 624void KPPPWidget::disconnect() {
625 if (!_pppdata->command_before_disconnect().isEmpty()) { 625 if (!_pppdata->command_before_disconnect().isEmpty()) {
626 con_win->hide(); 626 con_win->hide();
627 con->show(); 627 con->show();
628 con->setCaption(QObject::tr("Disconnecting...")); 628 con->setCaption(QObject::tr("Disconnecting..."));
629 con->setMsg(QObject::tr("Executing command before disconnection.")); 629 con->setMsg(QObject::tr("Executing command before disconnection."));
630 630
631 qApp->processEvents(); 631 qApp->processEvents();
632 QApplication::flushX(); 632 QApplication::flushX();
633// pid_t id = 633// pid_t id =
634 execute_command(_pppdata->command_before_disconnect()); 634 execute_command(_pppdata->command_before_disconnect());
635// int i, status; 635// int i, status;
636 636
637// do { 637// do {
638// kapp->processEvents(); 638// kapp->processEvents();
639// i = waitpid(id, &status, WNOHANG); 639// i = waitpid(id, &status, WNOHANG);
640// usleep(500000); 640// usleep(500000);
641// } while (i == 0 && errno == 0); 641// } while (i == 0 && errno == 0);
642 642
643 con->hide(); 643 con->hide();
644 } 644 }
645 645
646 qApp->processEvents(); 646 qApp->processEvents();
647 647
648// statdlg->stop_stats(); 648// statdlg->stop_stats();
649 Modem::modem->killPPPDaemon(); 649 Modem::modem->killPPPDaemon();
650 650
651 QApplication::flushX(); 651 QApplication::flushX();
652 execute_command(_pppdata->command_on_disconnect()); 652 execute_command(_pppdata->command_on_disconnect());
653 653
654 Modem::modem->removeSecret(AUTH_PAP); 654 Modem::modem->removeSecret(AUTH_PAP);
655 Modem::modem->removeSecret(AUTH_CHAP); 655 Modem::modem->removeSecret(AUTH_CHAP);
656 656
657 removedns(); 657 removedns();
658 Modem::modem->unlockdevice(); 658 Modem::modem->unlockdevice();
659 659
660 con_win->stopClock(); 660 con_win->stopClock();
661// p_kppp->stopAccounting(); 661// p_kppp->stopAccounting();
662 con_win->hide(); 662 con_win->hide();
663 663
664// DockWidget::dock_widget->stop_stats(); 664// DockWidget::dock_widget->stop_stats();
665// DockWidget::dock_widget->hide(); 665// DockWidget::dock_widget->hide();
666 666
667// if(m_bQuitOnDisconnect) 667// if(m_bQuitOnDisconnect)
668// kapp->exit(0); 668// kapp->exit(0);
669// else { 669// else {
670 this->quit_b->setFocus(); 670 this->quit_b->setFocus();
671 this->show(); 671 this->show();
672// } 672// }
673} 673}
674 674
675 675
676// void KPPPWidget::helpbutton() { 676// void KPPPWidget::helpbutton() {
677// kapp->invokeHelp(); 677// kapp->invokeHelp();
678// } 678// }
679 679
680 680
681void KPPPWidget::quitbutton() { 681void KPPPWidget::quitbutton() {
682 if(_pppdata->pppdRunning()) { 682 if(_pppdata->pppdRunning()) {
683 int ok = QMessageBox::warning(this, 683 int ok = QMessageBox::warning(this,
684 QObject::tr("Exiting kPPP will close your PPP Session."), 684 QObject::tr("Exiting kPPP will close your PPP Session."),
685 QObject::tr("Quit kPPP?")); 685 QObject::tr("Quit kPPP?"));
686 if(ok == QMessageBox::Yes) { 686 if(ok == QMessageBox::Yes) {
687 Modem::modem->killPPPDaemon(); 687 Modem::modem->killPPPDaemon();
688 QApplication::flushX(); 688 QApplication::flushX();
689 execute_command(_pppdata->command_on_disconnect()); 689 execute_command(_pppdata->command_on_disconnect());
690 removedns(); 690 removedns();
691 Modem::modem->unlockdevice(); 691 Modem::modem->unlockdevice();
692 } 692 }
693 } else { 693 } else {
694 if (!_pppdata->accname().isEmpty() && !_pppdata->storePassword()) 694 if (!_pppdata->accname().isEmpty() && !_pppdata->storePassword())
695 _pppdata->setStoredPassword(""); 695 _pppdata->setStoredPassword("");
696 } 696 }
697 _pppdata->save(); 697 _pppdata->save();
698 qApp->quit(); 698 qApp->quit();
699} 699}
700 700
701 701
702// void KPPPWidget::rulesetLoadError() { 702// void KPPPWidget::rulesetLoadError() {
703// QMessageBox::warning(this,"error", ruleset_load_errmsg); 703// QMessageBox::warning(this,"error", ruleset_load_errmsg);
704// } 704// }
705 705
706 706
707// void KPPPWidget::startAccounting() { 707// void KPPPWidget::startAccounting() {
708// // volume accounting 708// // volume accounting
709// stats->totalbytes = 0; 709// stats->totalbytes = 0;
710 710
711// kdDebug() << "AcctEnabled: " << _pppdata->AcctEnabled() << endl; 711// kdDebug() << "AcctEnabled: " << _pppdata->AcctEnabled() << endl;
712 712
713// // load the ruleset 713// // load the ruleset
714// if(!_pppdata->AcctEnabled()) 714// if(!_pppdata->AcctEnabled())
715// return; 715// return;
716 716
717// QString d = AccountingBase::getAccountingFile(_pppdata->accountingFile()); 717// QString d = AccountingBase::getAccountingFile(_pppdata->accountingFile());
718// // if(::access(d.data(), X_OK) != 0) 718// // if(::access(d.data(), X_OK) != 0)
719// acct = new Accounting(this, stats); 719// acct = new Accounting(this, stats);
720// // else 720// // else
721// // acct = new ExecutableAccounting(this); 721// // acct = new ExecutableAccounting(this);
722 722
723// // connect to the accounting object 723// // connect to the accounting object
724// connect(acct, SIGNAL(changed(QString,QString)), 724// connect(acct, SIGNAL(changed(QString,QString)),
725 // con_win, SLOT(slotAccounting(QString,QString))); 725 // con_win, SLOT(slotAccounting(QString,QString)));
726 726
727// // if(!acct->loadRuleSet(_pppdata->accountingFile())) { 727// // if(!acct->loadRuleSet(_pppdata->accountingFile())) {
728// // QString s= QObject::tr("Can not load the accounting " 728// // QString s= QObject::tr("Can not load the accounting "
729 // // "ruleset \"%1\"!").arg(_pppdata->accountingFile()); 729 // // "ruleset \"%1\"!").arg(_pppdata->accountingFile());
730 730
731// // starting the messagebox with a timer will prevent us 731// // starting the messagebox with a timer will prevent us
732// // from blocking the calling function ConnectWidget::timerEvent 732// // from blocking the calling function ConnectWidget::timerEvent
733// ruleset_load_errmsg = s; 733// ruleset_load_errmsg = s;
734// QTimer::singleShot(0, this, SLOT(rulesetLoadError())); 734// QTimer::singleShot(0, this, SLOT(rulesetLoadError()));
735// return; 735// return;
736// } 736// }
737// //else 737// //else
738// // acct->slotStart(); 738// // acct->slotStart();
739// } 739// }
740 740
741// void KPPPWidget::stopAccounting() { 741// void KPPPWidget::stopAccounting() {
742// // store volume accounting 742// // store volume accounting
743// // if(stats->totalbytes != 0) 743// // if(stats->totalbytes != 0)
744// // _pppdata->setTotalBytes(stats->totalbytes); 744// // _pppdata->setTotalBytes(stats->totalbytes);
745 745
746// if(!_pppdata->AcctEnabled()) 746// if(!_pppdata->AcctEnabled())
747// return; 747// return;
748 748
749// // if(acct != 0) { 749// // if(acct != 0) {
750// // acct->slotStop(); 750// // acct->slotStop();
751// // delete acct; 751// // delete acct;
752// // acct = 0; 752// // acct = 0;
753// // } 753// // }
754// } 754// }
755 755
756 756
757// void KPPPWidget::showStats() { 757// void KPPPWidget::showStats() {
758// if(statdlg) { 758// if(statdlg) {
759// statdlg->show(); 759// statdlg->show();
760// statdlg->raise(); 760// statdlg->raise();
761// } 761// }
762// } 762// }
763 763
764 764
765void KPPPWidget::usernameChanged(const QString &) { 765void KPPPWidget::usernameChanged(const QString &) {
766 // store username for later use 766 // store username for later use
767 _pppdata->setStoredUsername(ID_Edit->text()); 767 _pppdata->setStoredUsername(ID_Edit->text());
768} 768}
769 769
770 770
771void KPPPWidget::passwordChanged(const QString &) { 771void KPPPWidget::passwordChanged(const QString &) {
772 // store the password if so requested 772 // store the password if so requested
773 if(_pppdata->storePassword()) 773 if(_pppdata->storePassword())
774 _pppdata->setStoredPassword(PW_Edit->text()); 774 _pppdata->setStoredPassword(PW_Edit->text());
775 else 775 else
776 _pppdata->setStoredPassword(""); 776 _pppdata->setStoredPassword("");
777} 777}
778 778
779 779
780void KPPPWidget::setPW_Edit(const QString &pw) { 780void KPPPWidget::setPW_Edit(const QString &pw) {
781 PW_Edit->setText(pw); 781 PW_Edit->setText(pw);
782} 782}
783 783
784 784
785// void KPPPWidget::resetCosts(const QString &s) { 785// void KPPPWidget::resetCosts(const QString &s) {
786// AccountingBase::resetCosts(s); 786// AccountingBase::resetCosts(s);
787// } 787// }
788 788
789 789
790// void KPPPWidget::resetVolume(const QString &s) { 790// void KPPPWidget::resetVolume(const QString &s) {
791// AccountingBase::resetVolume(s); 791// AccountingBase::resetVolume(s);
792// } 792// }
793 793
794/** 794/**
795 * pppd's getword() function knows about escape characters. 795 * pppd's getword() function knows about escape characters.
796 * If we write the username and password to the secrets file 796 * If we write the username and password to the secrets file
797 * we'll therefore have to escape back slashes. 797 * we'll therefore have to escape back slashes.
798 */ 798 */
799QString KPPPWidget::encodeWord(const QString &s) { 799QString KPPPWidget::encodeWord(const QString &s) {
800 QString r = s; 800 QString r = s;
801 r.replace(QRegExp("\\"), "\\\\"); 801 r.replace(QRegExp("\\"), "\\\\");
802 return r; 802 return r;
803} 803}
804 804
805// void KPPPWidget::setQuitOnDisconnect (bool b) 805// void KPPPWidget::setQuitOnDisconnect (bool b)
806// { 806// {
807// m_bQuitOnDisconnect = b; 807// m_bQuitOnDisconnect = b;
808// } 808// }
809 809
810void KPPPWidget::showNews() { 810void KPPPWidget::showNews() {
811#ifdef KPPP_SHOW_NEWS 811#ifdef KPPP_SHOW_NEWS
812 /* 812 /*
813 * Introduce the QuickHelp feature to new users of this version 813 * Introduce the QuickHelp feature to new users of this version
814 */ 814 */
815 #define QUICKHELP_HINT "Hint_QuickHelp" 815 #define QUICKHELP_HINT "Hint_QuickHelp"
816 if(_pppdata->readNumConfig(GENERAL_GRP, QUICKHELP_HINT, 0) == 0) { 816 if(_pppdata->readNumConfig(GENERAL_GRP, QUICKHELP_HINT, 0) == 0) {
817 QDialog dlg(0, 0, true); 817 QDialog dlg(0, 0, true);
818 dlg.setCaption(QObject::tr("Recent Changes in KPPP")); 818 dlg.setCaption(QObject::tr("Recent Changes in KPPP"));
819 819
820 QVBoxLayout *tl = new QVBoxLayout(&dlg, 10, 10); 820 QVBoxLayout *tl = new QVBoxLayout(&dlg, 10, 10);
821 QHBoxLayout *l1 = new QHBoxLayout(10); 821 QHBoxLayout *l1 = new QHBoxLayout(10);
822 QVBoxLayout *l2 = new QVBoxLayout(10); 822 QVBoxLayout *l2 = new QVBoxLayout(10);
823 tl->addLayout(l1); 823 tl->addLayout(l1);
824 824
825 QLabel *icon = new QLabel(&dlg); 825 QLabel *icon = new QLabel(&dlg);
826 icon->setPixmap(BarIcon("exclamation")); 826 icon->setPixmap(BarIcon("exclamation"));
827 icon->setFixedSize(icon->sizeHint()); 827 icon->setFixedSize(icon->sizeHint());
828 l1->addWidget(icon); 828 l1->addWidget(icon);
829 l1->addLayout(l2); 829 l1->addLayout(l2);
830 830
831 QLabel *l = new QLabel(QObject::tr("From version 1.4.8 on, kppp has a new feature\n" 831 QLabel *l = new QLabel(QObject::tr("From version 1.4.8 on, kppp has a new feature\n"
832 "called \"Quickhelp\". It's similar to a tooltip,\n" 832 "called \"Quickhelp\". It's similar to a tooltip,\n"
833 "but you can activate it whenever you want.\n" 833 "but you can activate it whenever you want.\n"
834 "\n" 834 "\n"
835 "To activate it, simply click on a control like\n" 835 "To activate it, simply click on a control like\n"
836 "a button or a label with the right mouse button.\n" 836 "a button or a label with the right mouse button.\n"
837 "If the item supports Quickhelp, a popup menu\n" 837 "If the item supports Quickhelp, a popup menu\n"
838 "will appear leading to Quickhelp.\n" 838 "will appear leading to Quickhelp.\n"
839 "\n" 839 "\n"
840 "To test it, right-click somewhere in this text."), 840 "To test it, right-click somewhere in this text."),
841 &dlg); 841 &dlg);
842 842
843 QCheckBox *cb = new QCheckBox(QObject::tr("Don't show this hint again"), &dlg); 843 QCheckBox *cb = new QCheckBox(QObject::tr("Don't show this hint again"), &dlg);
844 cb->setFixedSize(cb->sizeHint()); 844 cb->setFixedSize(cb->sizeHint());
845 845
846 KButtonBox *bbox = new KButtonBox(&dlg); 846 KButtonBox *bbox = new KButtonBox(&dlg);
847 bbox->addStretch(1); 847 bbox->addStretch(1);
848 QPushButton *ok = bbox->addButton(QObject::tr("OK")); 848 QPushButton *ok = bbox->addButton(QObject::tr("OK"));
849 ok->setDefault(true); 849 ok->setDefault(true);
850 dlg.connect(ok, SIGNAL(clicked()), 850 dlg.connect(ok, SIGNAL(clicked()),
851 &dlg, SLOT(accept())); 851 &dlg, SLOT(accept()));
852 bbox->addStretch(1); 852 bbox->addStretch(1);
853 bbox->layout(); 853 bbox->layout();
854 854
855 l2->addWidget(l); 855 l2->addWidget(l);
856 l2->addWidget(cb); 856 l2->addWidget(cb);
857 tl->addWidget(bbox); 857 tl->addWidget(bbox);
858 858
859 QString tmp = QObject::tr("This is an example of <b>QuickHelp</b>.\n" 859 QString tmp = QObject::tr("This is an example of <b>QuickHelp</b>.\n"
860 "This window will stay open until you\n" 860 "This window will stay open until you\n"
861 "click a mouse button or a press a key.\n"); 861 "click a mouse button or a press a key.\n");
862 862
863 QWhatsThis::add(cb,tmp); 863 QWhatsThis::add(cb,tmp);
864 QWhatsThis::add(l, tmp); 864 QWhatsThis::add(l, tmp);
865 865
866 dlg.exec(); 866 dlg.exec();
867 if(cb->isChecked()) { 867 if(cb->isChecked()) {
868 _pppdata->writeConfig(GENERAL_GRP, QUICKHELP_HINT, 1); 868 _pppdata->writeConfig(GENERAL_GRP, QUICKHELP_HINT, 1);
869 _pppdata->save(); 869 _pppdata->save();
870 } 870 }
871 } 871 }
872#endif 872#endif
873} 873}
874 874
875 875
876//#include "kpppwidget.moc" 876//#include "kpppwidget.moc"
877 877
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,1080 +1,1080 @@
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
766 return true; 766 return true;
767} 767}
768 768
769 769
770bool Modem::removeAuthFile(Auth method) { 770bool Modem::removeAuthFile(Auth method) {
771 const char *authfile, *oldName; 771 const char *authfile, *oldName;
772 772
773 if(!(authfile = authFile(method))) 773 if(!(authfile = authFile(method)))
774 return false; 774 return false;
775 if(!(oldName = authFile(method, Old))) 775 if(!(oldName = authFile(method, Old)))
776 return false; 776 return false;
777 777
778 if(access(oldName, F_OK) == 0) { 778 if(access(oldName, F_OK) == 0) {
779 unlink(authfile); 779 unlink(authfile);
780 return (rename(oldName, authfile) == 0); 780 return (rename(oldName, authfile) == 0);
781 } else 781 } else
782 return false; 782 return false;
783} 783}
784 784
785 785
786bool Modem::setSecret(int method, const char* name, const char* password) 786bool Modem::setSecret(int method, const char* name, const char* password)
787{ 787{
788 788
789 Auth auth; 789 Auth auth;
790 if(method == AUTH_PAPCHAP) 790 if(method == AUTH_PAPCHAP)
791 return setSecret(AUTH_PAP, name, password) && 791 return setSecret(AUTH_PAP, name, password) &&
792 setSecret(AUTH_CHAP, name, password); 792 setSecret(AUTH_CHAP, name, password);
793 793
794 switch(method) { 794 switch(method) {
795 case AUTH_PAP: 795 case AUTH_PAP:
796 auth = Modem::PAP; 796 auth = Modem::PAP;
797 break; 797 break;
798 case AUTH_CHAP: 798 case AUTH_CHAP:
799 auth = Modem::CHAP; 799 auth = Modem::CHAP;
800 break; 800 break;
801 default: 801 default:
802 return false; 802 return false;
803 } 803 }
804 804
805 return createAuthFile(auth, name, password); 805 return createAuthFile(auth, name, password);
806 806
807} 807}
808 808
809bool Modem::removeSecret(int method) 809bool Modem::removeSecret(int method)
810{ 810{
811 Auth auth; 811 Auth auth;
812 812
813 switch(method) { 813 switch(method) {
814 case AUTH_PAP: 814 case AUTH_PAP:
815 auth = Modem::PAP; 815 auth = Modem::PAP;
816 break; 816 break;
817 case AUTH_CHAP: 817 case AUTH_CHAP:
818 auth = Modem::CHAP; 818 auth = Modem::CHAP;
819 break; 819 break;
820 default: 820 default:
821 return false; 821 return false;
822 } 822 }
823 return removeAuthFile( auth ); 823 return removeAuthFile( auth );
824} 824}
825 825
826int checkForInterface() 826int checkForInterface()
827{ 827{
828// I don't know if Linux needs more initialization to get the ioctl to 828// I don't know if Linux needs more initialization to get the ioctl to
829// work, pppd seems to hint it does. But BSD doesn't, and the following 829// work, pppd seems to hint it does. But BSD doesn't, and the following
830// code should compile. 830// code should compile.
831#if (defined(HAVE_NET_IF_PPP_H) || defined(HAVE_LINUX_IF_PPP_H)) && !defined(__svr4__) 831#if (defined(HAVE_NET_IF_PPP_H) || defined(HAVE_LINUX_IF_PPP_H)) && !defined(__svr4__)
832 int s, ok; 832 int s, ok;
833 struct ifreq ifr; 833 struct ifreq ifr;
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,1495 +1,1495 @@
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
242 242
243const QString PPPData::defaultAccount() { 243const QString PPPData::defaultAccount() {
244 return readConfig(GENERAL_GRP, DEFAULTACCOUNT_KEY); 244 return readConfig(GENERAL_GRP, DEFAULTACCOUNT_KEY);
245} 245}
246 246
247 247
248void PPPData::setDefaultAccount(const QString &n) { 248void PPPData::setDefaultAccount(const QString &n) {
249 writeConfig(GENERAL_GRP, DEFAULTACCOUNT_KEY, n); 249 writeConfig(GENERAL_GRP, DEFAULTACCOUNT_KEY, n);
250 250
251 //now set the current account index to the default account 251 //now set the current account index to the default account
252 setAccount(defaultAccount()); 252 setAccount(defaultAccount());
253} 253}
254 254
255 255
256bool PPPData::get_show_clock_on_caption() { 256bool PPPData::get_show_clock_on_caption() {
257 return (bool) readNumConfig(GENERAL_GRP, SHOWCLOCK_KEY, true); 257 return (bool) readNumConfig(GENERAL_GRP, SHOWCLOCK_KEY, true);
258} 258}
259 259
260 260
261void PPPData::set_show_clock_on_caption(bool set) { 261void PPPData::set_show_clock_on_caption(bool set) {
262 writeConfig(GENERAL_GRP, SHOWCLOCK_KEY, (int) set); 262 writeConfig(GENERAL_GRP, SHOWCLOCK_KEY, (int) set);
263} 263}
264 264
265 265
266bool PPPData::get_xserver_exit_disconnect() { 266bool PPPData::get_xserver_exit_disconnect() {
267 return (bool) readNumConfig(GENERAL_GRP, DISCONNECT_KEY, true); 267 return (bool) readNumConfig(GENERAL_GRP, DISCONNECT_KEY, true);
268} 268}
269 269
270 270
271void PPPData::setPPPDebug(bool set) { 271void 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
479 479
480void PPPData::setModemToneDuration(int n) { 480void PPPData::setModemToneDuration(int n) {
481 writeConfig(modemGroup(), TONEDURATION_KEY, n); 481 writeConfig(modemGroup(), TONEDURATION_KEY, n);
482} 482}
483 483
484 484
485int PPPData::busyWait() { 485int PPPData::busyWait() {
486 return readNumConfig(modemGroup(), BUSYWAIT_KEY, BUSY_WAIT); 486 return readNumConfig(modemGroup(), BUSYWAIT_KEY, BUSY_WAIT);
487} 487}
488 488
489 489
490void PPPData::setbusyWait(int n) { 490void PPPData::setbusyWait(int n) {
491 writeConfig(modemGroup(), BUSYWAIT_KEY, n); 491 writeConfig(modemGroup(), BUSYWAIT_KEY, n);
492} 492}
493 493
494 494
495// 495//
496//Advanced "Modem" dialog 496//Advanced "Modem" dialog
497// 497//
498// defaults: InitString=ATZ, InitString1="" etc. 498// defaults: InitString=ATZ, InitString1="" etc.
499const QString PPPData::modemInitStr(int i) { 499const QString PPPData::modemInitStr(int i) {
500 assert(i >= 0 && i < NumInitStrings); 500 assert(i >= 0 && i < NumInitStrings);
501 if(i == 0) 501 if(i == 0)
502 return readConfig(modemGroup(), INITSTR_KEY, "ATZ"); 502 return readConfig(modemGroup(), INITSTR_KEY, "ATZ");
503 else 503 else
504 return readConfig(modemGroup(), INITSTR_KEY + QString::number(i), ""); 504 return readConfig(modemGroup(), INITSTR_KEY + QString::number(i), "");
505} 505}
506 506
507 507
508void PPPData::setModemInitStr(int i, const QString &n) { 508void PPPData::setModemInitStr(int i, const QString &n) {
509 assert(i >= 0 && i < NumInitStrings); 509 assert(i >= 0 && i < NumInitStrings);
510 QString k = INITSTR_KEY + (i > 0 ? QString::number(i) : QString("")); 510 QString k = INITSTR_KEY + (i > 0 ? QString::number(i) : QString(""));
511 writeConfig(modemGroup(), k, n); 511 writeConfig(modemGroup(), k, n);
512} 512}
513 513
514 514
515const QString PPPData::modemInitResp() { 515const QString PPPData::modemInitResp() {
516 return readConfig(modemGroup(), INITRESP_KEY, "OK"); 516 return readConfig(modemGroup(), INITRESP_KEY, "OK");
517} 517}
518 518
519 519
520void PPPData::setModemInitResp(const QString &n) { 520void PPPData::setModemInitResp(const QString &n) {
521 writeConfig(modemGroup(), INITRESP_KEY, n); 521 writeConfig(modemGroup(), INITRESP_KEY, n);
522} 522}
523 523
524 524
525int PPPData::modemPreInitDelay() { 525int PPPData::modemPreInitDelay() {
526 return readNumConfig(modemGroup(), PREINITDELAY_KEY, 50); 526 return readNumConfig(modemGroup(), PREINITDELAY_KEY, 50);
527} 527}
528 528
529 529
530void PPPData::setModemPreInitDelay(int n) { 530void PPPData::setModemPreInitDelay(int n) {
531 writeConfig(modemGroup(), PREINITDELAY_KEY, n); 531 writeConfig(modemGroup(), PREINITDELAY_KEY, n);
532} 532}
533 533
534 534
535int PPPData::modemInitDelay() { 535int PPPData::modemInitDelay() {
536 return readNumConfig(modemGroup(), INITDELAY_KEY, 50); 536 return readNumConfig(modemGroup(), INITDELAY_KEY, 50);
537} 537}
538 538
539 539
540void PPPData::setModemInitDelay(int n) { 540void PPPData::setModemInitDelay(int n) {
541 writeConfig(modemGroup(), INITDELAY_KEY, n); 541 writeConfig(modemGroup(), INITDELAY_KEY, n);
542} 542}
543 543
544QString PPPData::modemNoDialToneDetectionStr() { 544QString PPPData::modemNoDialToneDetectionStr() {
545 return readConfig(modemGroup(), NODTDETECT_KEY, "ATX3"); 545 return readConfig(modemGroup(), NODTDETECT_KEY, "ATX3");
546} 546}
547 547
548void PPPData::setModemNoDialToneDetectionStr(const QString &n) { 548void PPPData::setModemNoDialToneDetectionStr(const QString &n) {
549 writeConfig(modemGroup(), NODTDETECT_KEY, n); 549 writeConfig(modemGroup(), NODTDETECT_KEY, n);
550} 550}
551 551
552const QString PPPData::modemDialStr() { 552const QString PPPData::modemDialStr() {
553 return readConfig(modemGroup(), DIALSTR_KEY, "ATDT"); 553 return readConfig(modemGroup(), DIALSTR_KEY, "ATDT");
554} 554}
555 555
556 556
557void PPPData::setModemDialStr(const QString &n) { 557void PPPData::setModemDialStr(const QString &n) {
558 writeConfig(modemGroup(), DIALSTR_KEY, n); 558 writeConfig(modemGroup(), DIALSTR_KEY, n);
559} 559}
560 560
561 561
562const QString PPPData::modemConnectResp() { 562const QString PPPData::modemConnectResp() {
563 return readConfig(modemGroup(), CONNECTRESP_KEY, "CONNECT"); 563 return readConfig(modemGroup(), CONNECTRESP_KEY, "CONNECT");
564} 564}
565 565
566 566
567void PPPData::setModemConnectResp(const QString &n) { 567void PPPData::setModemConnectResp(const QString &n) {
568 writeConfig(modemGroup(), CONNECTRESP_KEY, n); 568 writeConfig(modemGroup(), CONNECTRESP_KEY, n);
569} 569}
570 570
571 571
572const QString PPPData::modemBusyResp() { 572const QString PPPData::modemBusyResp() {
573 return readConfig(modemGroup(), BUSYRESP_KEY, "BUSY"); 573 return readConfig(modemGroup(), BUSYRESP_KEY, "BUSY");
574} 574}
575 575
576 576
577void PPPData::setModemBusyResp(const QString &n) { 577void PPPData::setModemBusyResp(const QString &n) {
578 writeConfig(modemGroup(), BUSYRESP_KEY, n); 578 writeConfig(modemGroup(), BUSYRESP_KEY, n);
579} 579}
580 580
581 581
582const QString PPPData::modemNoCarrierResp() { 582const QString PPPData::modemNoCarrierResp() {
583 return readConfig(modemGroup(), NOCARRIERRESP_KEY, "NO CARRIER"); 583 return readConfig(modemGroup(), NOCARRIERRESP_KEY, "NO CARRIER");
584} 584}
585 585
586 586
587void PPPData::setModemNoCarrierResp(const QString &n) { 587void PPPData::setModemNoCarrierResp(const QString &n) {
588 writeConfig(modemGroup(), NOCARRIERRESP_KEY, n); 588 writeConfig(modemGroup(), NOCARRIERRESP_KEY, n);
589} 589}
590 590
591 591
592const QString PPPData::modemNoDialtoneResp() { 592const QString PPPData::modemNoDialtoneResp() {
593 return readConfig(modemGroup(), NODIALTONERESP_KEY, "NO DIALTONE"); 593 return readConfig(modemGroup(), NODIALTONERESP_KEY, "NO DIALTONE");
594} 594}
595 595
596 596
597void PPPData::setModemNoDialtoneResp(const QString &n) { 597void PPPData::setModemNoDialtoneResp(const QString &n) {
598 writeConfig(modemGroup(), NODIALTONERESP_KEY, n); 598 writeConfig(modemGroup(), NODIALTONERESP_KEY, n);
599} 599}
600 600
601 601
602const QString PPPData::modemHangupStr() { 602const QString PPPData::modemHangupStr() {
603 return readConfig(modemGroup(), HANGUPSTR_KEY, "+++ATH"); 603 return readConfig(modemGroup(), HANGUPSTR_KEY, "+++ATH");
604} 604}
605 605
606void PPPData::setModemHangupStr(const QString &n) { 606void PPPData::setModemHangupStr(const QString &n) {
607 writeConfig(modemGroup(), HANGUPSTR_KEY, n); 607 writeConfig(modemGroup(), HANGUPSTR_KEY, n);
608} 608}
609 609
610 610
611const QString PPPData::modemHangupResp() { 611const QString PPPData::modemHangupResp() {
612 return readConfig(modemGroup(), HANGUPRESP_KEY, "OK"); 612 return readConfig(modemGroup(), HANGUPRESP_KEY, "OK");
613} 613}
614 614
615void PPPData::setModemHangupResp(const QString &n) { 615void PPPData::setModemHangupResp(const QString &n) {
616 writeConfig(modemGroup(), HANGUPRESP_KEY, n); 616 writeConfig(modemGroup(), HANGUPRESP_KEY, n);
617} 617}
618 618
619 619
620const QString PPPData::modemAnswerStr() { 620const QString PPPData::modemAnswerStr() {
621 return readConfig(modemGroup(), ANSWERSTR_KEY, "ATA"); 621 return readConfig(modemGroup(), ANSWERSTR_KEY, "ATA");
622} 622}
623 623
624 624
625QString PPPData::volumeOff() { 625QString PPPData::volumeOff() {
626 return readConfig(modemGroup(), VOLUME_OFF, "M0L0"); 626 return readConfig(modemGroup(), VOLUME_OFF, "M0L0");
627} 627}
628 628
629 629
630void PPPData::setVolumeOff(const QString &s) { 630void PPPData::setVolumeOff(const QString &s) {
631 writeConfig(modemGroup(), VOLUME_OFF, s); 631 writeConfig(modemGroup(), VOLUME_OFF, s);
632} 632}
633 633
634 634
635QString PPPData::volumeMedium() { 635QString PPPData::volumeMedium() {
636 return readConfig(modemGroup(), VOLUME_MEDIUM, "M1L1"); 636 return readConfig(modemGroup(), VOLUME_MEDIUM, "M1L1");
637} 637}
638 638
639 639
640void PPPData::setVolumeMedium(const QString &s) { 640void PPPData::setVolumeMedium(const QString &s) {
641 writeConfig(modemGroup(), VOLUME_MEDIUM, s); 641 writeConfig(modemGroup(), VOLUME_MEDIUM, s);
642} 642}
643 643
644 644
645QString PPPData::volumeHigh() { 645QString 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);
1067} 1067}
1068 1068
1069 1069
1070// int PPPData::VolAcctEnabled() { 1070// int PPPData::VolAcctEnabled() {
1071// return readNumConfig(cgroup, VOLACCTENABLED_KEY, 0); 1071// return readNumConfig(cgroup, VOLACCTENABLED_KEY, 0);
1072// } 1072// }
1073 1073
1074 1074
1075// void PPPData::setVolAcctEnabled(int set) { 1075// void PPPData::setVolAcctEnabled(int set) {
1076// writeConfig(cgroup, VOLACCTENABLED_KEY, set); 1076// writeConfig(cgroup, VOLACCTENABLED_KEY, set);
1077// } 1077// }
1078 1078
1079 1079
1080const QString PPPData::gateway() { 1080const QString PPPData::gateway() {
1081 return readConfig(cgroup, GATEWAY_KEY); 1081 return readConfig(cgroup, GATEWAY_KEY);
1082} 1082}
1083 1083
1084 1084
1085void PPPData::setGateway(const QString &n ) { 1085void PPPData::setGateway(const QString &n ) {
1086 writeConfig(cgroup, GATEWAY_KEY, n); 1086 writeConfig(cgroup, GATEWAY_KEY, n);
1087} 1087}
1088 1088
1089 1089
1090bool PPPData::defaultroute() { 1090bool PPPData::defaultroute() {
1091 // default route is by default 'on'. 1091 // default route is by default 'on'.
1092 return (bool) readNumConfig(cgroup, DEFAULTROUTE_KEY, true); 1092 return (bool) readNumConfig(cgroup, DEFAULTROUTE_KEY, true);
1093} 1093}
1094 1094
1095 1095
1096void PPPData::setDefaultroute(bool set) { 1096void PPPData::setDefaultroute(bool set) {
1097 writeConfig(cgroup, DEFAULTROUTE_KEY, (int) set); 1097 writeConfig(cgroup, DEFAULTROUTE_KEY, (int) set);
1098} 1098}
1099 1099
1100 1100
1101bool PPPData::autoDNS() { 1101bool PPPData::autoDNS() {
1102 bool set = (bool) readNumConfig(cgroup, AUTODNS_KEY, true); 1102 bool set = (bool) readNumConfig(cgroup, AUTODNS_KEY, true);
1103 return (set && pppdVersionMin(2, 3, 7)); 1103 return (set && pppdVersionMin(2, 3, 7));
1104} 1104}
1105 1105
1106 1106
1107void PPPData::setAutoDNS(bool set) { 1107void PPPData::setAutoDNS(bool set) {
1108 writeConfig(cgroup, AUTODNS_KEY, (int) set); 1108 writeConfig(cgroup, AUTODNS_KEY, (int) set);
1109} 1109}
1110 1110
1111 1111
1112void PPPData::setExDNSDisabled(bool set) { 1112void PPPData::setExDNSDisabled(bool set) {
1113 writeConfig(cgroup, EXDNSDISABLED_KEY, (int) set); 1113 writeConfig(cgroup, EXDNSDISABLED_KEY, (int) set);
1114} 1114}
1115 1115
1116 1116
1117bool PPPData::exDNSDisabled() { 1117bool PPPData::exDNSDisabled() {
1118 return (bool) readNumConfig(cgroup, EXDNSDISABLED_KEY,0); 1118 return (bool) readNumConfig(cgroup, EXDNSDISABLED_KEY,0);
1119} 1119}
1120 1120
1121 1121
1122QStringList &PPPData::dns() { 1122QStringList &PPPData::dns() {
1123 static QStringList dnslist; 1123 static QStringList dnslist;
1124 1124
1125 readListConfig(cgroup, DNS_KEY, dnslist); 1125 readListConfig(cgroup, DNS_KEY, dnslist);
1126 while(dnslist.count() > MAX_DNS_ENTRIES) 1126 while(dnslist.count() > MAX_DNS_ENTRIES)
1127 dnslist.remove(dnslist.last()); 1127 dnslist.remove(dnslist.last());
1128 1128
1129 return dnslist; 1129 return dnslist;
1130} 1130}
1131 1131
1132 1132
1133void PPPData::setDns(QStringList &list) { 1133void PPPData::setDns(QStringList &list) {
1134 writeListConfig(cgroup, DNS_KEY, list); 1134 writeListConfig(cgroup, DNS_KEY, list);
1135} 1135}
1136 1136
1137 1137
1138const QString PPPData::domain() { 1138const QString PPPData::domain() {
1139 return readConfig(cgroup, DOMAIN_KEY); 1139 return readConfig(cgroup, DOMAIN_KEY);
1140} 1140}
1141 1141
1142 1142
1143void PPPData::setDomain(const QString &n ) { 1143void PPPData::setDomain(const QString &n ) {
1144 writeConfig(cgroup, DOMAIN_KEY, n); 1144 writeConfig(cgroup, DOMAIN_KEY, n);
1145} 1145}
1146 1146
1147 1147
1148QStringList &PPPData::scriptType() { 1148QStringList &PPPData::scriptType() {
1149 static QStringList typelist; 1149 static QStringList typelist;
1150 1150
1151 readListConfig(cgroup, SCRIPTCOM_KEY, typelist); 1151 readListConfig(cgroup, SCRIPTCOM_KEY, typelist);
1152 while(typelist.count() > MAX_SCRIPT_ENTRIES) 1152 while(typelist.count() > MAX_SCRIPT_ENTRIES)
1153 typelist.remove(typelist.last()); 1153 typelist.remove(typelist.last());
1154 1154
1155 return typelist; 1155 return typelist;
1156} 1156}
1157 1157
1158 1158
1159void PPPData::setScriptType(QStringList &list) { 1159void PPPData::setScriptType(QStringList &list) {
1160 writeListConfig(cgroup, SCRIPTCOM_KEY, list); 1160 writeListConfig(cgroup, SCRIPTCOM_KEY, list);
1161} 1161}
1162 1162
1163 1163
1164QStringList &PPPData::script() { 1164QStringList &PPPData::script() {
1165 static QStringList scriptlist; 1165 static QStringList scriptlist;
1166 1166
1167 readListConfig(cgroup, SCRIPTARG_KEY, scriptlist); 1167 readListConfig(cgroup, SCRIPTARG_KEY, scriptlist);
1168 while(scriptlist.count() > MAX_SCRIPT_ENTRIES) 1168 while(scriptlist.count() > MAX_SCRIPT_ENTRIES)
1169 scriptlist.remove(scriptlist.last()); 1169 scriptlist.remove(scriptlist.last());
1170 1170
1171 return scriptlist; 1171 return scriptlist;
1172} 1172}
1173 1173
1174 1174
1175void PPPData::setScript(QStringList &list) { 1175void PPPData::setScript(QStringList &list) {
1176 writeListConfig(cgroup, SCRIPTARG_KEY, list); 1176 writeListConfig(cgroup, SCRIPTARG_KEY, list);
1177} 1177}
1178 1178
1179 1179
1180// const QString PPPData::accountingFile() { 1180// const QString PPPData::accountingFile() {
1181// return readConfig(cgroup, ACCTFILE_KEY); 1181// return readConfig(cgroup, ACCTFILE_KEY);
1182// } 1182// }
1183 1183
1184 1184
1185// void PPPData::setAccountingFile(const QString &n) { 1185// void PPPData::setAccountingFile(const QString &n) {
1186// writeConfig(cgroup, ACCTFILE_KEY, n); 1186// writeConfig(cgroup, ACCTFILE_KEY, n);
1187// } 1187// }
1188 1188
1189 1189
1190// const QString PPPData::totalCosts() { 1190// const QString PPPData::totalCosts() {
1191// return readConfig(cgroup, TOTALCOSTS_KEY); 1191// return readConfig(cgroup, TOTALCOSTS_KEY);
1192// } 1192// }
1193 1193
1194 1194
1195// void PPPData::setTotalCosts(const QString &n) { 1195// void PPPData::setTotalCosts(const QString &n) {
1196// writeConfig(cgroup, TOTALCOSTS_KEY, n); 1196// writeConfig(cgroup, TOTALCOSTS_KEY, n);
1197// } 1197// }
1198 1198
1199 1199
1200// int PPPData::totalBytes() { 1200// int PPPData::totalBytes() {
1201// return readNumConfig(cgroup, TOTALBYTES_KEY, 0); 1201// return readNumConfig(cgroup, TOTALBYTES_KEY, 0);
1202// } 1202// }
1203 1203
1204// void PPPData::setTotalBytes(int n) { 1204// void PPPData::setTotalBytes(int n) {
1205// writeConfig(cgroup, TOTALBYTES_KEY, n); 1205// writeConfig(cgroup, TOTALBYTES_KEY, n);
1206// } 1206// }
1207 1207
1208 1208
1209QStringList &PPPData::pppdArgument() { 1209QStringList &PPPData::pppdArgument() {
1210 static QStringList arglist; 1210 static QStringList arglist;
1211 1211
1212 while(arglist.count() > MAX_PPPD_ARGUMENTS) 1212 while(arglist.count() > MAX_PPPD_ARGUMENTS)
1213 arglist.remove(arglist.last()); 1213 arglist.remove(arglist.last());
1214 readListConfig(cgroup, PPPDARG_KEY, arglist); 1214 readListConfig(cgroup, PPPDARG_KEY, arglist);
1215 1215
1216 return arglist; 1216 return arglist;
1217} 1217}
1218 1218
1219 1219
1220void PPPData::setpppdArgument(QStringList &args) { 1220void PPPData::setpppdArgument(QStringList &args) {
1221 writeListConfig(cgroup, PPPDARG_KEY, args); 1221 writeListConfig(cgroup, PPPDARG_KEY, args);
1222} 1222}
1223 1223
1224 1224
1225void PPPData::setpppdArgumentDefaults() { 1225void PPPData::setpppdArgumentDefaults() {
1226 QStringList arg; 1226 QStringList arg;
1227 arg << "lcp-echo-failure 0"; 1227 arg << "lcp-echo-failure 0";
1228 setpppdArgument(arg); 1228 setpppdArgument(arg);
1229} 1229}
1230 1230
1231 1231
1232// // graphing widget 1232// // graphing widget
1233// void PPPData::setGraphingOptions(bool enable, 1233// void PPPData::setGraphingOptions(bool enable,
1234 // QColor bg, 1234 // QColor bg,
1235 // QColor text, 1235 // QColor text,
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
@@ -1,200 +1,200 @@
1#include "wextensions.h" 1#include "wextensions.h"
2 2
3#include <qfile.h> 3#include <qfile.h>
4#include <qtextstream.h> 4#include <qtextstream.h>
5 5
6#include <arpa/inet.h> 6#include <arpa/inet.h>
7#include <sys/socket.h> 7#include <sys/socket.h>
8#include <sys/ioctl.h> 8#include <sys/ioctl.h>
9 9
10#include <math.h> 10#include <math.h>
11 11
12#define PROCNETWIRELESS "/proc/net/wireless" 12#define PROCNETWIRELESS "/proc/net/wireless"
13#define IW_LOWER 0 13#define IW_LOWER 0
14#define IW_UPPER 256 14#define IW_UPPER 256
15 15
16/** 16/**
17 * Constructor. Sets hasWirelessExtensions 17 * Constructor. Sets hasWirelessExtensions
18 */ 18 */
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
@@ -1,255 +1,255 @@
1 1
2#include "wlanmodule.h" 2#include "wlanmodule.h"
3#include "wlanimp2.h" 3#include "wlanimp2.h"
4#include "infoimp.h" 4#include "infoimp.h"
5#include "wextensions.h" 5#include "wextensions.h"
6#include "interfaceinformationimp.h" 6#include "interfaceinformationimp.h"
7 7
8/* OPIE */ 8/* OPIE */
9#include <qpe/qpeapplication.h> 9#include <qpe/qpeapplication.h>
10 10
11/* QT */ 11/* QT */
12#include <qcheckbox.h> 12#include <qcheckbox.h>
13#include <qcombobox.h> 13#include <qcombobox.h>
14#include <qlabel.h> 14#include <qlabel.h>
15#include <qlineedit.h> 15#include <qlineedit.h>
16#include <qprogressbar.h> 16#include <qprogressbar.h>
17#include <qspinbox.h> 17#include <qspinbox.h>
18#include <qtabwidget.h> 18#include <qtabwidget.h>
19 19
20 20
21/** 21/**
22 * Constructor, find all of the possible interfaces 22 * Constructor, find all of the possible interfaces
23 */ 23 */
24WLANModule::WLANModule() 24WLANModule::WLANModule()
25 : Module(), 25 : Module(),
26 wlanconfigWiget(0) 26 wlanconfigWiget(0)
27{ 27{
28} 28}
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,480 +1,480 @@
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() );
273 ++loops; 273 ++loops;
274 } 274 }
275 275
276 return loops * text.length(); 276 return loops * text.length();
277} 277}
278 278
279int BenchmarkInfo::gfxRendering( int seconds ) 279int BenchmarkInfo::gfxRendering( int seconds )
280{ 280{
281 int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 }; 281 int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 };
282 int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 }; 282 int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 };
283 int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 }; 283 int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 };
284 284
285 int w = QApplication::desktop()->width(); 285 int w = QApplication::desktop()->width();
286 int h = QApplication::desktop()->height(); 286 int h = QApplication::desktop()->height();
287 287
288 srand( time( NULL ) ); 288 srand( time( NULL ) );
289 289
290 BenchmarkPaintWidget bpw; 290 BenchmarkPaintWidget bpw;
291 291
292 QTime t; 292 QTime t;
293 t.start(); 293 t.start();
294 int stop = t.elapsed() + seconds*1000; 294 int stop = t.elapsed() + seconds*1000;
295 int loops = 0; 295 int loops = 0;
296 296
297 while ( t.elapsed() < stop ) 297 while ( t.elapsed() < stop )
298 { 298 {
299 int k = rand() % 9; 299 int k = rand() % 9;
300 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) ); 300 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
301 bpw.p.drawLine( rand()%w, rand()%h, rand()%w, rand()%h ); 301 bpw.p.drawLine( rand()%w, rand()%h, rand()%w, rand()%h );
302 ++loops; 302 ++loops;
303 } 303 }
304 304
305 t.restart(); 305 t.restart();
306 stop = t.elapsed() + seconds*1000; 306 stop = t.elapsed() + seconds*1000;
307 307
308 while ( t.elapsed() < stop ) 308 while ( t.elapsed() < stop )
309 { 309 {
310 int k = rand() % 9; 310 int k = rand() % 9;
311 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) ); 311 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
312 bpw.p.drawArc( rand()%w, rand()%h, rand()%w, rand()%h, 360 * 16, 360 * 16 ); 312 bpw.p.drawArc( rand()%w, rand()%h, rand()%w, rand()%h, 360 * 16, 360 * 16 );
313 ++loops; 313 ++loops;
314 } 314 }
315 315
316 QBrush br1; 316 QBrush br1;
317 br1.setStyle( SolidPattern ); 317 br1.setStyle( SolidPattern );
318 t.restart(); 318 t.restart();
319 stop = t.elapsed() + seconds*1000; 319 stop = t.elapsed() + seconds*1000;
320 320
321 while ( t.elapsed() < stop ) 321 while ( t.elapsed() < stop )
322 { 322 {
323 int k = rand() % 9; 323 int k = rand() % 9;
324 br1.setColor( QColor( rr[ k ], gg[ k ], bb[ k ] ) ); 324 br1.setColor( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
325 bpw.p.fillRect( rand()%w, rand()%h, rand()%w, rand()%h, br1 ); 325 bpw.p.fillRect( rand()%w, rand()%h, rand()%w, rand()%h, br1 );
326 ++loops; 326 ++loops;
327 } 327 }
328 328
329 QPixmap p = Resource::loadPixmap( "sysinfo/pattern" ); 329 QPixmap p = Resource::loadPixmap( "sysinfo/pattern" );
330 t.restart(); 330 t.restart();
331 stop = t.elapsed() + seconds*1000; 331 stop = t.elapsed() + seconds*1000;
332 332
333 while ( t.elapsed() < stop ) 333 while ( t.elapsed() < stop )
334 { 334 {
335 bpw.p.drawPixmap( rand()%w, rand()%h, p ); 335 bpw.p.drawPixmap( rand()%w, rand()%h, p );
336 ++loops; 336 ++loops;
337 } 337 }
338 338
339 return loops; 339 return loops;
340 340
341} 341}
342 342
343void BenchmarkInfo::performFileTest( const QString& fname, OCheckListItem* item ) 343void BenchmarkInfo::performFileTest( const QString& fname, OCheckListItem* item )
344{ 344{
345 QTime time; 345 QTime time;
346 time.start(); 346 time.start();
347 if ( writeFile( fname ) && 347 if ( writeFile( fname ) &&
348 readFile( fname ) ) 348 readFile( fname ) )
349 { 349 {
350 QFile::remove( fname ); 350 QFile::remove( fname );
351 item->setText( 1, QString( "%1 kb/sec" ).arg( QString::number( 1024.0 / ( time.elapsed() / 1000.0 ) ) ) ); 351 item->setText( 1, QString( "%1 kb/sec" ).arg( QString::number( 1024.0 / ( time.elapsed() / 1000.0 ) ) ) );
352 item->setOn( false ); 352 item->setOn( false );
353 } 353 }
354 else 354 else
355 { 355 {
356 item->setText( 1, tr( "error" ) ); 356 item->setText( 1, tr( "error" ) );
357 } 357 }
358} 358}
359 359
360char FileBuf[ BUFF_SIZE + 1 ]; 360char FileBuf[ BUFF_SIZE + 1 ];
361 361
362bool BenchmarkInfo::writeFile( const QString& w_path ) 362bool BenchmarkInfo::writeFile( const QString& w_path )
363{ 363{
364 int i; 364 int i;
365 int k; 365 int k;
366 int n; 366 int n;
367 int pos; 367 int pos;
368 int len; 368 int len;
369 char *data = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 62 369 char *data = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 62
370 370
371 371
372 // /*------------------------------------ 372 // /*------------------------------------
373 int w_len; 373 int w_len;
374 374
375 QFile writeFile( w_path ); 375 QFile writeFile( w_path );
376 srand( time( NULL ) ); 376 srand( time( NULL ) );
377 377
378 for ( n = 0 ; n < 20 ; n++ ) 378 for ( n = 0 ; n < 20 ; n++ )
379 { 379 {
380 if ( ! writeFile.open( IO_WriteOnly ) ) 380 if ( ! writeFile.open( IO_WriteOnly ) )
381 { 381 {
382 writeFile.close(); 382 writeFile.close();
383 writeFile.remove(); 383 writeFile.remove();
384 return ( false ); 384 return ( false );
385 } 385 }
386 // ------------------------------------------ sequential write 386 // ------------------------------------------ sequential write
387 for ( k = 0 ; k < 256 ; k++ ) 387 for ( k = 0 ; k < 256 ; k++ )
388 { 388 {
389 n = rand() % 30; 389 n = rand() % 30;
390 memcpy( &FileBuf[ k * 32 ], &data[ n ], 32 ); 390 memcpy( &FileBuf[ k * 32 ], &data[ n ], 32 );
391 } 391 }
392 392
393 for ( i = 0 ; i < FILE_SIZE / BUFF_SIZE ; i++ ) 393 for ( i = 0 ; i < FILE_SIZE / BUFF_SIZE ; i++ )
394 { 394 {
395 w_len = writeFile.writeBlock( FileBuf, BUFF_SIZE ); 395 w_len = writeFile.writeBlock( FileBuf, BUFF_SIZE );
396 if ( w_len != BUFF_SIZE ) 396 if ( w_len != BUFF_SIZE )
397 { 397 {
398 writeFile.close(); 398 writeFile.close();
399 writeFile.remove(); 399 writeFile.remove();
400 return ( false ); 400 return ( false );
401 } 401 }
402 writeFile.flush(); 402 writeFile.flush();
403 } 403 }
404 // ------------------------------------------ random write 404 // ------------------------------------------ random write
405 for ( i = 0 ; i < 400 ; i++ ) 405 for ( i = 0 ; i < 400 ; i++ )
406 { 406 {
407 len = rand() % 90 + 4000; 407 len = rand() % 90 + 4000;
408 for ( k = 0 ; k < 128 ; k++ ) 408 for ( k = 0 ; k < 128 ; k++ )
409 { 409 {
410 n = rand() % 30; 410 n = rand() % 30;
411 memcpy( &FileBuf[ k * 8 ], &data[ n ], 32 ); 411 memcpy( &FileBuf[ k * 8 ], &data[ n ], 32 );
412 } 412 }
413 pos = rand() % ( FILE_SIZE - BUFF_SIZE ); 413 pos = rand() % ( FILE_SIZE - BUFF_SIZE );
414 414
415 writeFile.at( pos ); 415 writeFile.at( pos );
416 w_len = writeFile.writeBlock( FileBuf, len ); 416 w_len = writeFile.writeBlock( FileBuf, len );
417 if ( w_len != len ) 417 if ( w_len != len )
418 { 418 {
419 writeFile.close(); 419 writeFile.close();
420 writeFile.remove(); 420 writeFile.remove();
421 return ( false ); 421 return ( false );
422 } 422 }
423 writeFile.flush(); 423 writeFile.flush();
424 } 424 }
425 writeFile.close(); 425 writeFile.close();
426 } 426 }
427 return ( true ); 427 return ( true );
428 428
429} 429}
430 430
431 431
432bool BenchmarkInfo::readFile( const QString& r_path ) 432bool BenchmarkInfo::readFile( const QString& r_path )
433{ 433{
434 int i; 434 int i;
435 int k; 435 int k;
436 int len; 436 int len;
437 int pos; 437 int pos;
438 int r_len; 438 int r_len;
439 439
440 QFile readFile( r_path ); 440 QFile readFile( r_path );
441 srand( time( NULL ) ); 441 srand( time( NULL ) );
442 442
443 for ( k = 0 ; k < 200 ; k++ ) 443 for ( k = 0 ; k < 200 ; k++ )
444 { 444 {
445 if ( ! readFile.open( IO_ReadOnly ) ) 445 if ( ! readFile.open( IO_ReadOnly ) )
446 { 446 {
447 readFile.remove(); 447 readFile.remove();
448 return ( false ); 448 return ( false );
449 } 449 }
450 // ------------------------------------------ sequential read 450 // ------------------------------------------ sequential read
451 readFile.at( 0 ); 451 readFile.at( 0 );
452 for ( i = 0 ; i < FILE_SIZE / BUFF_SIZE ; i++ ) 452 for ( i = 0 ; i < FILE_SIZE / BUFF_SIZE ; i++ )
453 { 453 {
454 readFile.at( i * BUFF_SIZE ); 454 readFile.at( i * BUFF_SIZE );
455 r_len = readFile.readBlock( FileBuf, BUFF_SIZE ); 455 r_len = readFile.readBlock( FileBuf, BUFF_SIZE );
456 if ( r_len != BUFF_SIZE ) 456 if ( r_len != BUFF_SIZE )
457 { 457 {
458 readFile.close(); 458 readFile.close();
459 readFile.remove(); 459 readFile.remove();
460 return ( false ); 460 return ( false );
461 } 461 }
462 } 462 }
463 // ------------------------------------------ random read 463 // ------------------------------------------ random read
464 for ( i = 0 ; i < 1000 ; i++ ) 464 for ( i = 0 ; i < 1000 ; i++ )
465 { 465 {
466 len = rand() % 120 + 8; 466 len = rand() % 120 + 8;
467 pos = rand() % ( FILE_SIZE / BUFF_SIZE - BUFF_SIZE ); 467 pos = rand() % ( FILE_SIZE / BUFF_SIZE - BUFF_SIZE );
468 readFile.at( pos ); 468 readFile.at( pos );
469 r_len = readFile.readBlock( FileBuf, len ); 469 r_len = readFile.readBlock( FileBuf, len );
470 if ( r_len != len ) 470 if ( r_len != len )
471 { 471 {
472 readFile.close(); 472 readFile.close();
473 readFile.remove(); 473 readFile.remove();
474 return ( false ); 474 return ( false );
475 } 475 }
476 } 476 }
477 readFile.close(); 477 readFile.close();
478 } 478 }
479 return ( true ); 479 return ( true );
480} 480}
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,490 +1,488 @@
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);
134 layout->addSpacing(5); 132 layout->addSpacing(5);
135 layout->addLayout(hlayout); 133 layout->addLayout(hlayout);
136 QVBoxLayout *vlayout1=new QVBoxLayout(-1,"vlayout1"); 134 QVBoxLayout *vlayout1=new QVBoxLayout(-1,"vlayout1");
137 QVBoxLayout *vlayout2=new QVBoxLayout(-1,"vlayout2"); 135 QVBoxLayout *vlayout2=new QVBoxLayout(-1,"vlayout2");
138 // First column, labels 136 // First column, labels
139 vlayout1->addWidget(loginLabel); 137 vlayout1->addWidget(loginLabel);
140 vlayout1->addSpacing(5); 138 vlayout1->addSpacing(5);
141 vlayout1->addWidget(uidLabel); 139 vlayout1->addWidget(uidLabel);
142 vlayout1->addSpacing(5); 140 vlayout1->addSpacing(5);
143 vlayout1->addWidget(gecosLabel); 141 vlayout1->addWidget(gecosLabel);
144 vlayout1->addSpacing(5); 142 vlayout1->addSpacing(5);
145 vlayout1->addWidget(passwordLabel); 143 vlayout1->addWidget(passwordLabel);
146 vlayout1->addSpacing(5); 144 vlayout1->addSpacing(5);
147 vlayout1->addWidget(shellLabel); 145 vlayout1->addWidget(shellLabel);
148 vlayout1->addSpacing(5); 146 vlayout1->addSpacing(5);
149 vlayout1->addWidget(groupLabel); 147 vlayout1->addWidget(groupLabel);
150 if(vm==VIEWMODE_NEW) 148 if(vm==VIEWMODE_NEW)
151 { 149 {
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 }
489 } 487 }
490} 488}
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,257 +1,260 @@
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");
114} 117}
115void UserConfig::getUsers() { 118void UserConfig::getUsers() {
116 QString mytext; 119 QString mytext;
117 QPixmap mypixmap; 120 QPixmap mypixmap;
118 QListViewItem *listviewitem; 121 QListViewItem *listviewitem;
119 122
120 // Empty the iconview & the listview. 123 // Empty the iconview & the listview.
121 usersIconView->clear(); 124 usersIconView->clear();
122 usersListView->clear(); 125 usersListView->clear();
123 126
124 // availableUID is used as a deposite for the next available UID on the system, this should start at an ID over 500. 127 // availableUID is used as a deposite for the next available UID on the system, this should start at an ID over 500.
125 availableUID=500; 128 availableUID=500;
126 for(QStringList::Iterator it=accounts->passwdStringList.begin(); it!=accounts->passwdStringList.end(); ++it) { 129 for(QStringList::Iterator it=accounts->passwdStringList.begin(); it!=accounts->passwdStringList.end(); ++it) {
127 accounts->splitPasswdEntry(*it); // Split the string into it's components and store in variables in the accounts object. ("pr_name" and so on.) 130 accounts->splitPasswdEntry(*it); // Split the string into it's components and store in variables in the accounts object. ("pr_name" and so on.)
128 if(accounts->pw_name.find(QRegExp("^#"),0)) {// Skip commented lines. 131 if(accounts->pw_name.find(QRegExp("^#"),0)) {// Skip commented lines.
129 new QListViewItem(usersListView,QString::number(accounts->pw_uid),accounts->pw_name,accounts->pw_gecos); 132 new QListViewItem(usersListView,QString::number(accounts->pw_uid),accounts->pw_name,accounts->pw_gecos);
130 if((accounts->pw_uid>=500) && (accounts->pw_uid<65000)) {// Is this user a "normal" user ? 133 if((accounts->pw_uid>=500) && (accounts->pw_uid<65000)) {// Is this user a "normal" user ?
131 mytext=QString(accounts->pw_name)+" - ("+QString(accounts->pw_gecos)+")"; // The string displayed next to the icon. 134 mytext=QString(accounts->pw_name)+" - ("+QString(accounts->pw_gecos)+")"; // The string displayed next to the icon.
132 if(!(mypixmap.load("/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png"))) { // Is there an icon for this user? Resource::loadPixmap is caching, doesn't work. 135 if(!(mypixmap.load("/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png"))) { // Is there an icon for this user? Resource::loadPixmap is caching, doesn't work.
133 mypixmap=Resource::loadPixmap(QString("usermanager/usericon"));// If this user has no icon, load the default icon. 136 mypixmap=Resource::loadPixmap(QString("usermanager/usericon"));// If this user has no icon, load the default icon.
134 } 137 }
135 listviewitem=new QListViewItem(usersIconView,"",mytext);// Add the icon+text to the qiconview. 138 listviewitem=new QListViewItem(usersIconView,"",mytext);// Add the icon+text to the qiconview.
136 listviewitem->setPixmap(0,mypixmap); 139 listviewitem->setPixmap(0,mypixmap);
137 } 140 }
138 if((accounts->pw_uid>=availableUID) && (accounts->pw_uid<65000)) availableUID=accounts->pw_uid+1; // Increase 1 to the latest know UID to get a free uid. 141 if((accounts->pw_uid>=availableUID) && (accounts->pw_uid<65000)) availableUID=accounts->pw_uid+1; // Increase 1 to the latest know UID to get a free uid.
139 } 142 }
140 } 143 }
141 usersIconView->sort(); 144 usersIconView->sort();
142} 145}
143 146
144void UserConfig::addUser() { 147void UserConfig::addUser() {
145 if(UserDialog::addUser(availableUID,availableGID)) {// Add the user to the system, also send next available UID and GID. 148 if(UserDialog::addUser(availableUID,availableGID)) {// Add the user to the system, also send next available UID and GID.
146 getUsers(); // Update users views. 149 getUsers(); // Update users views.
147 getGroups(); // Update groups view. 150 getGroups(); // Update groups view.
148 } 151 }
149} 152}
150 153
151void UserConfig::editUser() { 154void UserConfig::editUser() {
152 QString username; 155 QString username;
153 if(myTabWidget->currentPageIndex()==0) {// Users 156 if(myTabWidget->currentPageIndex()==0) {// Users
154 if(usersIconView->currentItem()) {// Any icon selected? 157 if(usersIconView->currentItem()) {// Any icon selected?
155 username=usersIconView->currentItem()->text(1);// Get the text associated with the icon. 158 username=usersIconView->currentItem()->text(1);// Get the text associated with the icon.
156 username=username.left(username.find(" - (",0,true));// Strip out the username. 159 username=username.left(username.find(" - (",0,true));// Strip out the username.
157 if(UserDialog::editUser(username)) {// Bring up the userinfo dialog. 160 if(UserDialog::editUser(username)) {// Bring up the userinfo dialog.
158 // If there were any changed also update the views. 161 // If there were any changed also update the views.
159 getUsers(); 162 getUsers();
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,2608 +1,2613 @@
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
249 p->drawLine(x+2, y2, x2-2, y2); // b 254 p->drawLine(x+2, y2, x2-2, y2); // b
250 p->drawPoint(x+1, y+1); // tl 255 p->drawPoint(x+1, y+1); // tl
251 p->drawPoint(x2-1, y+1); // tr 256 p->drawPoint(x2-1, y+1); // tr
252 p->drawPoint(x+1, y2-1); // bl 257 p->drawPoint(x+1, y2-1); // bl
253 p->drawPoint(x2-1, y2-1); // br 258 p->drawPoint(x2-1, y2-1); // br
254 259
255 // inner top light lines 260 // inner top light lines
256 p->setPen(c.light(105)); 261 p->setPen(c.light(105));
257 p->drawLine(x+2, y+1, x2-2, y+1); 262 p->drawLine(x+2, y+1, x2-2, y+1);
258 p->drawLine(x+1, y+2, x2-1, y+2); 263 p->drawLine(x+1, y+2, x2-1, y+2);
259 p->drawLine(x+1, y+3, x+2, y+3); 264 p->drawLine(x+1, y+3, x+2, y+3);
260 p->drawLine(x2-2, y+3, x2-1, y+3); 265 p->drawLine(x2-2, y+3, x2-1, y+3);
261 p->drawPoint(x+1, y+4); 266 p->drawPoint(x+1, y+4);
262 p->drawPoint(x2-1, y+4); 267 p->drawPoint(x2-1, y+4);
263 268
264 // inner bottom light lines 269 // inner bottom light lines
265 p->setPen(c.light(110)); 270 p->setPen(c.light(110));
266 p->drawLine(x+2, y2-1, x2-2, y2-1); 271 p->drawLine(x+2, y2-1, x2-2, y2-1);
267 p->drawLine(x+1, y2-2, x2-1, y2-2); 272 p->drawLine(x+1, y2-2, x2-1, y2-2);
268 p->drawLine(x+1, y2-3, x+2, y2-3); 273 p->drawLine(x+1, y2-3, x+2, y2-3);
269 p->drawLine(x2-2, y2-3, x2-1, y2-3); 274 p->drawLine(x2-2, y2-3, x2-1, y2-3);
270 p->drawPoint(x+1, y2-4); 275 p->drawPoint(x+1, y2-4);
271 p->drawPoint(x2-1, y2-4); 276 p->drawPoint(x2-1, y2-4);
272 277
273 // inner left mid lines 278 // inner left mid lines
274 //p->setPen(c.light(105)); 279 //p->setPen(c.light(105));
275 p->setPen(c); 280 p->setPen(c);
276 p->drawLine(x+1, y+5, x+1, y2-5); 281 p->drawLine(x+1, y+5, x+1, y2-5);
277 p->drawLine(x+2, y+4, x+2, y2-4); 282 p->drawLine(x+2, y+4, x+2, y2-4);
278 283
279 // inner right mid lines 284 // inner right mid lines
280 p->drawLine(x2-1, y+5, x2-1, y2-5); 285 p->drawLine(x2-1, y+5, x2-1, y2-5);
281 p->drawLine(x2-2, y+4, x2-2, y2-4); 286 p->drawLine(x2-2, y+4, x2-2, y2-4);
282 287
283 // fill 288 // fill
284 QPixmap *pix; 289 QPixmap *pix;
285 if(h >= 32){ 290 if(h >= 32){
286 pix = bevelFillDict.find(c.rgb()); 291 pix = bevelFillDict.find(c.rgb());
287 if(!pix){ 292 if(!pix){
288 int h, s, v; 293 int h, s, v;
289 c.hsv(&h, &s, &v); 294 c.hsv(&h, &s, &v);
290 pix = new QPixmap(*bevelFillPix); 295 pix = new QPixmap(*bevelFillPix);
291 adjustHSV(*pix, h, s, v); 296 adjustHSV(*pix, h, s, v);
292 bevelFillDict.insert(c.rgb(), pix); 297 bevelFillDict.insert(c.rgb(), pix);
293 } 298 }
294 } 299 }
295 else{ 300 else{
296 pix = smallBevelFillDict.find(c.rgb()); 301 pix = smallBevelFillDict.find(c.rgb());
297 if(!pix){ 302 if(!pix){
298 int h, s, v; 303 int h, s, v;
299 c.hsv(&h, &s, &v); 304 c.hsv(&h, &s, &v);
300 pix = new QPixmap(*smallBevelFillPix); 305 pix = new QPixmap(*smallBevelFillPix);
301 adjustHSV(*pix, h, s, v); 306 adjustHSV(*pix, h, s, v);
302 smallBevelFillDict.insert(c.rgb(), pix); 307 smallBevelFillDict.insert(c.rgb(), pix);
303 } 308 }
304 } 309 }
305 p->drawTiledPixmap(x+3, y+3, w-6, h-6, *pix); 310 p->drawTiledPixmap(x+3, y+3, w-6, h-6, *pix);
306 // blend 311 // blend
307 int red, green, blue; 312 int red, green, blue;
308 QColor btnColor(c.dark(130)); 313 QColor btnColor(c.dark(130));
309 red = (btnColor.red() >> 1) + (bg.red() >> 1); 314 red = (btnColor.red() >> 1) + (bg.red() >> 1);
310 green = (btnColor.green() >> 1) + (bg.green() >> 1); 315 green = (btnColor.green() >> 1) + (bg.green() >> 1);
311 blue = (btnColor.blue() >> 1) + (bg.blue() >> 1); 316 blue = (btnColor.blue() >> 1) + (bg.blue() >> 1);
312 btnColor.setRgb(red, green, blue); 317 btnColor.setRgb(red, green, blue);
313 318
314 p->setPen(btnColor); 319 p->setPen(btnColor);
315 p->drawPoint(x+1, y); 320 p->drawPoint(x+1, y);
316 p->drawPoint(x, y+1); 321 p->drawPoint(x, y+1);
317 p->drawPoint(x+1, y2); 322 p->drawPoint(x+1, y2);
318 p->drawPoint(x, y2-1); 323 p->drawPoint(x, y2-1);
319 324
320 p->drawPoint(x2-1, y); 325 p->drawPoint(x2-1, y);
321 p->drawPoint(x2, y+1); 326 p->drawPoint(x2, y+1);
322 p->drawPoint(x2-1, y2); 327 p->drawPoint(x2-1, y2);
323 p->drawPoint(x2, y2-1); 328 p->drawPoint(x2, y2-1);
324 329
325 p->setPen(oldPen); 330 p->setPen(oldPen);
326 331
327} 332}
328 333
329void LiquidStyle::drawRoundButton(QPainter *painter, const QColor &c, 334void LiquidStyle::drawRoundButton(QPainter *painter, const QColor &c,
330 const QColor &back, int x, int y, int w, int h, 335 const QColor &back, int x, int y, int w, int h,
331 bool supportPushDown, bool pushedDown, 336 bool supportPushDown, bool pushedDown,
332 bool autoDefault, bool isMasked) 337 bool autoDefault, bool isMasked)
333{ 338{
334 if(w < 21 || h < 21){ 339 if(w < 21 || h < 21){
335 drawClearBevel(painter, x, y, w, h, c, back); 340 drawClearBevel(painter, x, y, w, h, c, back);
336 return; 341 return;
337 } 342 }
338 if(supportPushDown){ 343 if(supportPushDown){
339 --w, --h; 344 --w, --h;
340 } 345 }
341 /* We don't make the round buttons smaller, since they don't look as good 346 /* We don't make the round buttons smaller, since they don't look as good
342 if(autoDefault){ 347 if(autoDefault){
343 w = w-buttonDefaultIndicatorWidth()*2; 348 w = w-buttonDefaultIndicatorWidth()*2;
344 h = h-buttonDefaultIndicatorWidth()*2; 349 h = h-buttonDefaultIndicatorWidth()*2;
345 }*/ 350 }*/
346 351
347 352
348 QPixmap *pix = btnDict.find(c.rgb()); 353 QPixmap *pix = btnDict.find(c.rgb());
349 if(!pix){ 354 if(!pix){
350 int h, s, v; 355 int h, s, v;
351 c.hsv(&h, &s, &v); 356 c.hsv(&h, &s, &v);
352 pix = new QPixmap(*btnBorderPix); 357 pix = new QPixmap(*btnBorderPix);
353 adjustHSV(*pix, h, s, v); 358 adjustHSV(*pix, h, s, v);
354 btnDict.insert(c.rgb(), pix); 359 btnDict.insert(c.rgb(), pix);
355 } 360 }
356 int x2 = x+w-1; 361 int x2 = x+w-1;
357 int y2 = y+h-1; 362 int y2 = y+h-1;
358 int bx2 = pix->width()-1; 363 int bx2 = pix->width()-1;
359 int by2 = pix->height()-1; 364 int by2 = pix->height()-1;
360 365
361 QPixmap tmpPix(w, h); 366 QPixmap tmpPix(w, h);
362 QPixmap tilePix; 367 QPixmap tilePix;
363 QPainter p; 368 QPainter p;
364 p.begin(&tmpPix); 369 p.begin(&tmpPix);
365 370
366 // do the fill 371 // do the fill
367 p.drawPixmap(0, 0, *pix, 0, 0, 10, 10); // tl 372 p.drawPixmap(0, 0, *pix, 0, 0, 10, 10); // tl
368 p.drawPixmap(x2-9, 0, *pix, bx2-9, 0, 10, 10); // tr 373 p.drawPixmap(x2-9, 0, *pix, bx2-9, 0, 10, 10); // tr
369 p.drawPixmap(0, y2-9, *pix, 0, by2-9, 10, 10); // bl 374 p.drawPixmap(0, y2-9, *pix, 0, by2-9, 10, 10); // bl
370 p.drawPixmap(x2-9, y2-9, *pix, bx2-9, by2-9, 10, 10); // br 375 p.drawPixmap(x2-9, y2-9, *pix, bx2-9, by2-9, 10, 10); // br
371 376
372 // edges 377 // edges
373 tilePix.resize(pix->width()-20, 10); 378 tilePix.resize(pix->width()-20, 10);
374 // top 379 // top
375 bitBlt(&tilePix, 0, 0, pix, 10, 0, pix->width()-20, 10); 380 bitBlt(&tilePix, 0, 0, pix, 10, 0, pix->width()-20, 10);
376 p.drawTiledPixmap(10, 0, w-20, 10, tilePix); 381 p.drawTiledPixmap(10, 0, w-20, 10, tilePix);
377 // bottom 382 // bottom
378 bitBlt(&tilePix, 0, 0, pix, 10, by2-9, pix->width()-20, 20); 383 bitBlt(&tilePix, 0, 0, pix, 10, by2-9, pix->width()-20, 20);
379 p.drawTiledPixmap(10, y2-9, w-20, 10, tilePix); 384 p.drawTiledPixmap(10, y2-9, w-20, 10, tilePix);
380 // left 385 // left
381 tilePix.resize(10, pix->height()-20); 386 tilePix.resize(10, pix->height()-20);
382 bitBlt(&tilePix, 0, 0, pix, 0, 10, 10, pix->height()-20); 387 bitBlt(&tilePix, 0, 0, pix, 0, 10, 10, pix->height()-20);
383 p.drawTiledPixmap(0, 10, 10, h-20, tilePix); 388 p.drawTiledPixmap(0, 10, 10, h-20, tilePix);
384 // right 389 // right
385 bitBlt(&tilePix, 0, 0, pix, bx2-9, 10, 10, pix->height()-20); 390 bitBlt(&tilePix, 0, 0, pix, bx2-9, 10, 10, pix->height()-20);
386 p.drawTiledPixmap(x2-9, 10, 10, h-20, tilePix); 391 p.drawTiledPixmap(x2-9, 10, 10, h-20, tilePix);
387 392
388 // middle 393 // middle
389 tilePix.resize(pix->width()-20, pix->height()-20); 394 tilePix.resize(pix->width()-20, pix->height()-20);
390 bitBlt(&tilePix, 0, 0, pix, 10, 10, pix->width()-20, pix->height()-20); 395 bitBlt(&tilePix, 0, 0, pix, 10, 10, pix->width()-20, pix->height()-20);
391 p.drawTiledPixmap(10, 10, w-20, h-20, tilePix); 396 p.drawTiledPixmap(10, 10, w-20, h-20, tilePix);
392 397
393 398
394 // do the blend 399 // do the blend
395 QBitmap blendMask; 400 QBitmap blendMask;
396 if(!isMasked){ 401 if(!isMasked){
397 //QRgb bgRgb = back.rgb(); 402 //QRgb bgRgb = back.rgb();
398 //QRgb fgRgb = c.rgb(); 403 //QRgb fgRgb = c.rgb();
399 //int r, g, b; 404 //int r, g, b;
400 405
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*/);
594 break; 599 break;
595 case TabDown: 600 case TabDown:
596 pixmaps[TabDown] = processEmbedded("tab", btnH, btnS, btnV /*, true*/); 601 pixmaps[TabDown] = processEmbedded("tab", btnH, btnS, btnV /*, true*/);
597 break; 602 break;
598 case TabFocus: 603 case TabFocus:
599 pixmaps[TabFocus] = processEmbedded("tab", btnHoverH, btnHoverS, btnHoverV /*, true*/); 604 pixmaps[TabFocus] = processEmbedded("tab", btnHoverH, btnHoverS, btnHoverV /*, true*/);
600 break; 605 break;
601 606
602 case CB: 607 case CB:
603 pixmaps[CB] = processEmbedded("checkbox", bH, bS, bV /*, true*/); 608 pixmaps[CB] = processEmbedded("checkbox", bH, bS, bV /*, true*/);
604 break; 609 break;
605 case CBHover: 610 case CBHover:
606 pixmaps[CBHover] = processEmbedded("checkbox", btnHoverH, btnHoverS, btnHoverV /*, true*/); 611 pixmaps[CBHover] = processEmbedded("checkbox", btnHoverH, btnHoverS, btnHoverV /*, true*/);
607 break; 612 break;
608 case CBDown: 613 case CBDown:
609 pixmaps[CBDown] = processEmbedded("checkboxdown", btnH, btnS, btnV /*, true*/); 614 pixmaps[CBDown] = processEmbedded("checkboxdown", btnH, btnS, btnV /*, true*/);
610 break; 615 break;
611 case CBDownHover: 616 case CBDownHover:
612 pixmaps[CBDownHover] = processEmbedded("checkboxdown", btnHoverH, btnHoverS, btnHoverV /*, true*/); 617 pixmaps[CBDownHover] = processEmbedded("checkboxdown", btnHoverH, btnHoverS, btnHoverV /*, true*/);
613 break; 618 break;
614 619
615 case VSlider: 620 case VSlider:
616 pixmaps[VSlider] = processEmbedded("sliderarrow", btnH, btnS, btnV, true ); 621 pixmaps[VSlider] = processEmbedded("sliderarrow", btnH, btnS, btnV, true );
617 *pixmaps[VSlider] = pixmaps[VSlider]->xForm(rMatrix); 622 *pixmaps[VSlider] = pixmaps[VSlider]->xForm(rMatrix);
618 break; 623 break;
619 case VSBSliderTop: 624 case VSBSliderTop:
620 case VSBSliderTopHover: 625 case VSBSliderTopHover:
621 pixmaps[item] = processEmbedded("sbslider_top", btnH, btnS, btnV /*, true*/); 626 pixmaps[item] = processEmbedded("sbslider_top", btnH, btnS, btnV /*, true*/);
622 break; 627 break;
623 case VSBSliderBtm: 628 case VSBSliderBtm:
624 case VSBSliderBtmHover: 629 case VSBSliderBtmHover:
625 pixmaps[item] = processEmbedded("sbslider_btm", btnH, btnS, btnV /*, true*/); 630 pixmaps[item] = processEmbedded("sbslider_btm", btnH, btnS, btnV /*, true*/);
626 break; 631 break;
627 case VSBSliderMid: 632 case VSBSliderMid:
628 case VSBSliderMidHover: 633 case VSBSliderMidHover:
629 pixmaps[item] = processEmbedded("sbslider_mid", btnH, btnS, btnV); 634 pixmaps[item] = processEmbedded("sbslider_mid", btnH, btnS, btnV);
630 break; 635 break;
631 case VSBSliderTopBg: 636 case VSBSliderTopBg:
632 pixmaps[VSBSliderTopBg] = processEmbedded("sbslider_top", bH, bS, bV /*, true*/); 637 pixmaps[VSBSliderTopBg] = processEmbedded("sbslider_top", bH, bS, bV /*, true*/);
633 break; 638 break;
634 case VSBSliderBtmBg: 639 case VSBSliderBtmBg:
635 pixmaps[VSBSliderBtmBg] = processEmbedded("sbslider_btm", bH, bS, bV /*, true*/); 640 pixmaps[VSBSliderBtmBg] = processEmbedded("sbslider_btm", bH, bS, bV /*, true*/);
636 break; 641 break;
637 case VSBSliderMidBg: 642 case VSBSliderMidBg:
638 pixmaps[VSBSliderMidBg] = processEmbedded("sbslider_mid", bH, bS, bV); 643 pixmaps[VSBSliderMidBg] = processEmbedded("sbslider_mid", bH, bS, bV);
639 break; 644 break;
640 645
641 case HSlider: 646 case HSlider:
642 pixmaps[HSlider] = processEmbedded("sliderarrow", btnH, btnS, btnV /*, true*/); 647 pixmaps[HSlider] = processEmbedded("sliderarrow", btnH, btnS, btnV /*, true*/);
643 break; 648 break;
644 case HSBSliderTop: 649 case HSBSliderTop:
645 case HSBSliderTopHover: 650 case HSBSliderTopHover:
646 pixmaps[item] = processEmbedded("sbslider_top", btnH, btnS, btnV, true ); 651 pixmaps[item] = processEmbedded("sbslider_top", btnH, btnS, btnV, true );
647 *pixmaps[item] = pixmaps[item]->xForm(rMatrix); 652 *pixmaps[item] = pixmaps[item]->xForm(rMatrix);
648 break; 653 break;
649 case HSBSliderBtm: 654 case HSBSliderBtm:
650 case HSBSliderBtmHover: 655 case HSBSliderBtmHover:
651 pixmaps[item] = processEmbedded("sbslider_btm", btnH, btnS, btnV, true ); 656 pixmaps[item] = processEmbedded("sbslider_btm", btnH, btnS, btnV, true );
652 *pixmaps[item] = pixmaps[item]->xForm(rMatrix); 657 *pixmaps[item] = pixmaps[item]->xForm(rMatrix);
653 break; 658 break;
654 case HSBSliderMid: 659 case HSBSliderMid:
655 case HSBSliderMidHover: 660 case HSBSliderMidHover:
656 pixmaps[item] = processEmbedded("sbslider_mid", btnH, btnS, btnV); 661 pixmaps[item] = processEmbedded("sbslider_mid", btnH, btnS, btnV);
657 *pixmaps[item] = pixmaps[item]->xForm(rMatrix); 662 *pixmaps[item] = pixmaps[item]->xForm(rMatrix);
658 break; 663 break;
659 case HSBSliderTopBg: 664 case HSBSliderTopBg:
660 pixmaps[HSBSliderTopBg] = processEmbedded("sbslider_top", bH, bS, bV, true ); 665 pixmaps[HSBSliderTopBg] = processEmbedded("sbslider_top", bH, bS, bV, true );
661 *pixmaps[HSBSliderTopBg] = pixmaps[HSBSliderTopBg]->xForm(rMatrix); 666 *pixmaps[HSBSliderTopBg] = pixmaps[HSBSliderTopBg]->xForm(rMatrix);
662 break; 667 break;
663 case HSBSliderBtmBg: 668 case HSBSliderBtmBg:
664 pixmaps[HSBSliderBtmBg] = processEmbedded("sbslider_btm", bH, bS, bV, true ); 669 pixmaps[HSBSliderBtmBg] = processEmbedded("sbslider_btm", bH, bS, bV, true );
665 *pixmaps[HSBSliderBtmBg] = pixmaps[HSBSliderBtmBg]->xForm(rMatrix); 670 *pixmaps[HSBSliderBtmBg] = pixmaps[HSBSliderBtmBg]->xForm(rMatrix);
666 break; 671 break;
667 case HSBSliderMidBg: 672 case HSBSliderMidBg:
668 pixmaps[HSBSliderMidBg] = processEmbedded("sbslider_mid", bH, bS, bV); 673 pixmaps[HSBSliderMidBg] = processEmbedded("sbslider_mid", bH, bS, bV);
669 *pixmaps[HSBSliderMidBg] = pixmaps[HSBSliderMidBg]->xForm(rMatrix); 674 *pixmaps[HSBSliderMidBg] = pixmaps[HSBSliderMidBg]->xForm(rMatrix);
670 break; 675 break;
671 default: 676 default:
672 break; 677 break;
673 } 678 }
674 return(pixmaps[item]); 679 return(pixmaps[item]);
675} 680}
676 681
677void LiquidStyle::polish(QPalette &appPal) 682void LiquidStyle::polish(QPalette &appPal)
678{ 683{
679 int i; 684 int i;
680 for(i=0; i < BITMAP_ITEMS; ++i){ 685 for(i=0; i < BITMAP_ITEMS; ++i){
681 if(pixmaps[i]){ 686 if(pixmaps[i]){
682 delete pixmaps[i]; 687 delete pixmaps[i];
683 pixmaps[i] = NULL; 688 pixmaps[i] = NULL;
684 } 689 }
685 } 690 }
686 lowLightVal = 100 + (2* /*KGlobalSettings::contrast()*/ 3 +4)*10; 691 lowLightVal = 100 + (2* /*KGlobalSettings::contrast()*/ 3 +4)*10;
687 btnDict.clear(); 692 btnDict.clear();
688 btnBorderDict.clear(); 693 btnBorderDict.clear();
689 bevelFillDict.clear(); 694 bevelFillDict.clear();
690 smallBevelFillDict.clear(); 695 smallBevelFillDict.clear();
691 696
692 Config config ( "qpe" ); 697 Config config ( "qpe" );
693 config. setGroup ( "Liquid-Style" ); 698 config. setGroup ( "Liquid-Style" );
694 int contrast = config. readNumEntry ( "StippleContrast", 5 ); 699 int contrast = config. readNumEntry ( "StippleContrast", 5 );
695 if ( contrast < 0 ) 700 if ( contrast < 0 )
696 contrast = 0; 701 contrast = 0;
697 else if ( contrast > 10 ) 702 else if ( contrast > 10 )
698 contrast = 10; 703 contrast = 10;
699 704
700// QPalette pal = QApplication::palette(); 705// QPalette pal = QApplication::palette();
701 706
702 // button color stuff 707 // button color stuff
703 config. setGroup ( "Appearance" ); 708 config. setGroup ( "Appearance" );
704 QColor c = appPal. color ( QPalette::Active, QColorGroup::Button ); 709 QColor c = appPal. color ( QPalette::Active, QColorGroup::Button );
705 if ( c == appPal. color ( QPalette::Active, QColorGroup::Background )) { 710 if ( c == appPal. color ( QPalette::Active, QColorGroup::Background )) {
706 // force button color to be different from background 711 // force button color to be different from background
707 QBrush btnBrush(QColor(200, 202, 228)); 712 QBrush btnBrush(QColor(200, 202, 228));
708 appPal.setBrush(QColorGroup::Button, btnBrush); 713 appPal.setBrush(QColorGroup::Button, btnBrush);
709 } 714 }
710 c.hsv(&btnH, &btnS, &btnV); 715 c.hsv(&btnH, &btnS, &btnV);
711 c.light(120).hsv(&btnHoverH, &btnHoverS, &btnHoverV); 716 c.light(120).hsv(&btnHoverH, &btnHoverS, &btnHoverV);
712 717
713 // menu pixmap 718 // menu pixmap
714 if(!menuPix){ 719 if(!menuPix){
715 menuPix = new QPixmap; 720 menuPix = new QPixmap;
716 menuPix->resize(64, 64); 721 menuPix->resize(64, 64);
717 } 722 }
718 QPainter painter; 723 QPainter painter;
719 menuPix->fill(c.rgb()); 724 menuPix->fill(c.rgb());
720 painter.begin(menuPix); 725 painter.begin(menuPix);
721 painter.setPen(c.dark(105)); 726 painter.setPen(c.dark(105));
722 for(i=0; i < 63; i+=4){ 727 for(i=0; i < 63; i+=4){
723 painter.drawLine(0, i, 63, i); 728 painter.drawLine(0, i, 63, i);
724 painter.drawLine(0, i+1, 63, i+1); 729 painter.drawLine(0, i+1, 63, i+1);
725 }; 730 };
726 painter.end(); 731 painter.end();
727 menuBrush.setColor(c); 732 menuBrush.setColor(c);
728 menuBrush.setPixmap(*menuPix); 733 menuBrush.setPixmap(*menuPix);
729 734
730 // pager brush 735 // pager brush
731 c = c.dark(120); 736 c = c.dark(120);
732 QPixmap *pix = smallBevelFillDict.find(c.rgb()); // better be NULL ;-) 737 QPixmap *pix = smallBevelFillDict.find(c.rgb()); // better be NULL ;-)
733 if(!pix){ 738 if(!pix){
734 int h, s, v; 739 int h, s, v;
735 c.hsv(&h, &s, &v); 740 c.hsv(&h, &s, &v);
736 pix = new QPixmap(*smallBevelFillPix); 741 pix = new QPixmap(*smallBevelFillPix);
737 adjustHSV(*pix, h, s, v); 742 adjustHSV(*pix, h, s, v);
738 smallBevelFillDict.insert(c.rgb(), pix); 743 smallBevelFillDict.insert(c.rgb(), pix);
739 } 744 }
740// pagerHoverBrush.setColor(c); 745// pagerHoverBrush.setColor(c);
741// pagerHoverBrush.setPixmap(*pix); 746// pagerHoverBrush.setPixmap(*pix);
742 747
743 c = c.dark(120); 748 c = c.dark(120);
744 pix = smallBevelFillDict.find(c.rgb()); // better be NULL ;-) 749 pix = smallBevelFillDict.find(c.rgb()); // better be NULL ;-)
745 if(!pix){ 750 if(!pix){
746 int h, s, v; 751 int h, s, v;
747 c.hsv(&h, &s, &v); 752 c.hsv(&h, &s, &v);
748 pix = new QPixmap(*smallBevelFillPix); 753 pix = new QPixmap(*smallBevelFillPix);
749 adjustHSV(*pix, h, s, v); 754 adjustHSV(*pix, h, s, v);
750 smallBevelFillDict.insert(c.rgb(), pix); 755 smallBevelFillDict.insert(c.rgb(), pix);
751 } 756 }
752// pagerBrush.setColor(c); 757// pagerBrush.setColor(c);
753// pagerBrush.setPixmap(*pix); 758// pagerBrush.setPixmap(*pix);
754 759
755 // background color stuff 760 // background color stuff
756 c = appPal. color ( QPalette::Active, QColorGroup::Background ); 761 c = appPal. color ( QPalette::Active, QColorGroup::Background );
757 762
758 c.hsv(&bH, &bS, &bV); 763 c.hsv(&bH, &bS, &bV);
759 c.light(120).hsv(&bHoverH, &bHoverS, &bHoverV); 764 c.light(120).hsv(&bHoverH, &bHoverS, &bHoverV);
760 765
761 // FIXME? 766 // FIXME?
762 if(vsbSliderFillPix) 767 if(vsbSliderFillPix)
763 delete vsbSliderFillPix; 768 delete vsbSliderFillPix;
764 vsbSliderFillPix = new QPixmap(bevelFillPix->xForm(rMatrix)); 769 vsbSliderFillPix = new QPixmap(bevelFillPix->xForm(rMatrix));
765 adjustHSV(*vsbSliderFillPix, bH, bS, bV); 770 adjustHSV(*vsbSliderFillPix, bH, bS, bV);
766 771
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
960 Config config ( "qpe" ); 965 Config config ( "qpe" );
961 config. setGroup ( "Liquid-Style" ); 966 config. setGroup ( "Liquid-Style" );
962 967
963 // if ( config. readBoolEntry ( "WinDecoration", true )) 968 // if ( config. readBoolEntry ( "WinDecoration", true ))
964 // QApplication::qwsSetDecoration ( new LiquidDecoration ( )); 969 // QApplication::qwsSetDecoration ( new LiquidDecoration ( ));
965 970
966 flatTBButtons = config. readBoolEntry ( "FlatToolButtons", false ); 971 flatTBButtons = config. readBoolEntry ( "FlatToolButtons", false );
967} 972}
968 973
969void LiquidStyle::unPolish(QApplication *app) 974void LiquidStyle::unPolish(QApplication *app)
970{ 975{
971 QWindowsStyle::unPolish(app); 976 QWindowsStyle::unPolish(app);
972 app->setEffectEnabled(UI_AnimateMenu, menuAni); 977 app->setEffectEnabled(UI_AnimateMenu, menuAni);
973 app->setEffectEnabled(UI_FadeMenu, menuFade); 978 app->setEffectEnabled(UI_FadeMenu, menuFade);
974 979
975 qt_set_draw_menu_bar_impl ( 0 ); 980 qt_set_draw_menu_bar_impl ( 0 );
976 981
977// QApplication::qwsSetDecoration ( new QPEDecoration ( )); 982// QApplication::qwsSetDecoration ( new QPEDecoration ( ));
978} 983}
979 984
980 985
981/* !! HACK !! Beware 986/* !! HACK !! Beware
982 * 987 *
983 * TT forgot to make the QProgressBar widget styleable in Qt 2.x 988 * TT forgot to make the QProgressBar widget styleable in Qt 2.x
984 * So the only way to customize the drawing, is to intercept the 989 * So the only way to customize the drawing, is to intercept the
985 * paint event - since we have to use protected functions, we need 990 * paint event - since we have to use protected functions, we need
986 * to derive a "hack" class from QProgressBar and do the painting 991 * to derive a "hack" class from QProgressBar and do the painting
987 * in there. 992 * in there.
988 * 993 *
989 * - sandman 994 * - sandman
990 */ 995 */
991 996
992class HackProgressBar : public QProgressBar { 997class HackProgressBar : public QProgressBar {
993public: 998public:
994 HackProgressBar ( ); 999 HackProgressBar ( );
995 1000
996 void paint ( QPaintEvent *event, const QColorGroup &g, QPixmap *pix ) 1001 void paint ( QPaintEvent *event, const QColorGroup &g, QPixmap *pix )
997 { 1002 {
998 QPainter p( this ); 1003 QPainter p( this );
999 1004
1000 if ( !contentsRect().contains( event->rect() ) ) { 1005 if ( !contentsRect().contains( event->rect() ) ) {
1001 p.save(); 1006 p.save();
1002 p.setClipRegion( event->region().intersect(frameRect()) ); 1007 p.setClipRegion( event->region().intersect(frameRect()) );
1003 drawFrame( &p); 1008 drawFrame( &p);
1004 p.restore(); 1009 p.restore();
1005 } 1010 }
1006 if ( event->rect().intersects( contentsRect() )) { 1011 if ( event->rect().intersects( contentsRect() )) {
1007 p.setClipRegion( event->region().intersect( contentsRect() ) ); 1012 p.setClipRegion( event->region().intersect( contentsRect() ) );
1008 1013
1009 int x, y, w, h; 1014 int x, y, w, h;
1010 contentsRect ( ). rect ( &x, &y, &w, &h ); 1015 contentsRect ( ). rect ( &x, &y, &w, &h );
1011 1016
1012 int prog = progress ( ); 1017 int prog = progress ( );
1013 int total = totalSteps ( ); 1018 int total = totalSteps ( );
1014 if ( prog < 0 ) 1019 if ( prog < 0 )
1015 prog = 0; 1020 prog = 0;
1016 if ( total <= 0 ) 1021 if ( total <= 0 )
1017 total = 1; 1022 total = 1;
1018 int bw = w * prog / total; 1023 int bw = w * prog / total;
1019 if ( bw > w ) 1024 if ( bw > w )
1020 bw = w; 1025 bw = w;
1021 1026
1022 p.setPen(g.button().dark(130)); 1027 p.setPen(g.button().dark(130));
1023 p.drawRect(x, y, bw, h); 1028 p.drawRect(x, y, bw, h);
1024 p.setPen(g.button().light(120)); 1029 p.setPen(g.button().light(120));
1025 p.drawRect(x+1, y+1, bw-2, h-2); 1030 p.drawRect(x+1, y+1, bw-2, h-2);
1026 1031
1027 if(bw >= 4 && h >= 4 && pix) 1032 if(bw >= 4 && h >= 4 && pix)
1028 p.drawTiledPixmap(x+2, y+2, bw-4, h-4, *pix); 1033 p.drawTiledPixmap(x+2, y+2, bw-4, h-4, *pix);
1029 1034
1030 if ( progress ( )>= 0 && totalSteps ( ) > 0 ) { 1035 if ( progress ( )>= 0 && totalSteps ( ) > 0 ) {
1031 QString pstr; 1036 QString pstr;
1032 pstr. sprintf ( "%d%%", 100 * progress()/totalSteps ()); 1037 pstr. sprintf ( "%d%%", 100 * progress()/totalSteps ());
1033 p. setPen ( g.text());//g.highlightedText ( )); 1038 p. setPen ( g.text());//g.highlightedText ( ));
1034 p. drawText (x,y,w-1,h-1,AlignCenter,pstr); 1039 p. drawText (x,y,w-1,h-1,AlignCenter,pstr);
1035 } 1040 }
1036 } 1041 }
1037 } 1042 }
1038}; 1043};
1039 1044
1040 1045
1041/* 1046/*
1042 * The same for QToolButton: 1047 * The same for QToolButton:
1043 * TT hardcoded the drawing of the focus rect ... 1048 * TT hardcoded the drawing of the focus rect ...
1044 * 1049 *
1045 * - sandman 1050 * - sandman
1046 */ 1051 */
1047 1052
1048 1053
1049class HackToolButton : public QToolButton { 1054class HackToolButton : public QToolButton {
1050public: 1055public:
1051 HackToolButton ( ); 1056 HackToolButton ( );
1052 1057
1053 void paint ( QPaintEvent *ev ) 1058 void paint ( QPaintEvent *ev )
1054 { 1059 {
1055 erase ( ev-> region ( )); 1060 erase ( ev-> region ( ));
1056 QPainter p ( this ); 1061 QPainter p ( this );
1057 style ( ). drawToolButton ( this, &p ); 1062 style ( ). drawToolButton ( this, &p );
1058 drawButtonLabel ( &p ); 1063 drawButtonLabel ( &p );
1059 } 1064 }
1060}; 1065};
1061 1066
1062/* 1067/*
1063 * This is a fun method ;-) Here's an overview. KToolBar grabs resize to 1068 * This is a fun method ;-) Here's an overview. KToolBar grabs resize to
1064 * force everything to erase and repaint on resize. This is going away, I'm 1069 * force everything to erase and repaint on resize. This is going away, I'm
1065 * trying to get shaped widgets to work right without masking. QPushButton, 1070 * trying to get shaped widgets to work right without masking. QPushButton,
1066 * QComboBox, and Panel applet handles capture mouse enter and leaves in order 1071 * QComboBox, and Panel applet handles capture mouse enter and leaves in order
1067 * to set the highlightwidget and repaint for mouse hovers. CheckBoxes and 1072 * to set the highlightwidget and repaint for mouse hovers. CheckBoxes and
1068 * RadioButtons need to do this differently. Qt buffers these in pixmaps and 1073 * RadioButtons need to do this differently. Qt buffers these in pixmaps and
1069 * caches them in QPixmapCache, which is bad for doing things like hover 1074 * caches them in QPixmapCache, which is bad for doing things like hover
1070 * because the style methods aren't called in paintEvents if everything 1075 * because the style methods aren't called in paintEvents if everything
1071 * is cached. We use our own Paint event handler instead. Taskbuttons and 1076 * is cached. We use our own Paint event handler instead. Taskbuttons and
1072 * pager buttons draw into a pixmap buffer, so we handle those with palette 1077 * pager buttons draw into a pixmap buffer, so we handle those with palette
1073 * modifications. For QHeader, different header items are actually one widget 1078 * modifications. For QHeader, different header items are actually one widget
1074 * that draws multiple items, so we need to check which ID is hightlighted 1079 * that draws multiple items, so we need to check which ID is hightlighted
1075 * and draw it. Finally, we also check enter and leave events for QLineEdit, 1080 * and draw it. Finally, we also check enter and leave events for QLineEdit,
1076 * since if it's inside a combobox we want to highlight the combobox during 1081 * since if it's inside a combobox we want to highlight the combobox during
1077 * hovering in the edit. 1082 * hovering in the edit.
1078 */ 1083 */
1079bool LiquidStyle::eventFilter(QObject *obj, QEvent *ev) 1084bool LiquidStyle::eventFilter(QObject *obj, QEvent *ev)
1080{ 1085{
1081 if(obj->inherits("QToolBar")){ 1086 if(obj->inherits("QToolBar")){
1082 if(ev->type() == QEvent::Resize){ 1087 if(ev->type() == QEvent::Resize){
1083 const QObjectList *tbChildList = obj->children(); 1088 const QObjectList *tbChildList = obj->children();
1084 QObjectListIt it(*tbChildList); 1089 QObjectListIt it(*tbChildList);
1085 QObject *child; 1090 QObject *child;
1086 while((child = it.current()) != NULL){ 1091 while((child = it.current()) != NULL){
1087 ++it; 1092 ++it;
1088 if(child->isWidgetType()) 1093 if(child->isWidgetType())
1089 ((QWidget *)child)->repaint(true); 1094 ((QWidget *)child)->repaint(true);
1090 } 1095 }
1091 1096
1092 } 1097 }
1093 } 1098 }
1094 else if(obj->inherits("QToolButton")){ 1099 else if(obj->inherits("QToolButton")){
1095 QToolButton *btn = (QToolButton *)obj; 1100 QToolButton *btn = (QToolButton *)obj;
1096 if(ev->type() == QEvent::FocusIn ){ // && !btn-> autoRaise () 1101 if(ev->type() == QEvent::FocusIn ){ // && !btn-> autoRaise ()
1097 if(btn->isEnabled()){ 1102 if(btn->isEnabled()){
1098 highlightWidget = btn; 1103 highlightWidget = btn;
1099 btn->repaint(false); 1104 btn->repaint(false);
1100 } 1105 }
1101 } 1106 }
1102 else if(ev->type() == QEvent::FocusOut ){ 1107 else if(ev->type() == QEvent::FocusOut ){
1103 if(btn == highlightWidget){ 1108 if(btn == highlightWidget){
1104 highlightWidget = NULL; 1109 highlightWidget = NULL;
1105 btn->repaint(false); 1110 btn->repaint(false);
1106 } 1111 }
1107 } 1112 }
1108 else if(ev->type() == QEvent::Paint) { 1113 else if(ev->type() == QEvent::Paint) {
1109 (( HackToolButton *) btn )-> paint ((QPaintEvent *) ev ); 1114 (( HackToolButton *) btn )-> paint ((QPaintEvent *) ev );
1110 return true; 1115 return true;
1111 } 1116 }
1112 } 1117 }
1113 else if(obj->inherits("QRadioButton") || obj->inherits("QCheckBox")){ 1118 else if(obj->inherits("QRadioButton") || obj->inherits("QCheckBox")){
1114 QButton *btn = (QButton *)obj; 1119 QButton *btn = (QButton *)obj;
1115 bool isRadio = obj->inherits("QRadioButton"); 1120 bool isRadio = obj->inherits("QRadioButton");
1116 if(ev->type() == QEvent::Paint){ 1121 if(ev->type() == QEvent::Paint){
1117 //if(btn->autoMask()) 1122 //if(btn->autoMask())
1118 btn->erase(); 1123 btn->erase();
1119 QPainter p; 1124 QPainter p;
1120 p.begin(btn); 1125 p.begin(btn);
1121 QFontMetrics fm = btn->fontMetrics(); 1126 QFontMetrics fm = btn->fontMetrics();
1122 QSize lsz = fm.size(ShowPrefix, btn->text()); 1127 QSize lsz = fm.size(ShowPrefix, btn->text());
1123 QSize sz = isRadio ? exclusiveIndicatorSize() 1128 QSize sz = isRadio ? exclusiveIndicatorSize()
1124 : indicatorSize(); 1129 : indicatorSize();
1125 1130
1126/* 1131/*
1127 if(btn->hasFocus()){ 1132 if(btn->hasFocus()){
1128 QRect r = QRect(0, 0, btn->width(), btn->height()); 1133 QRect r = QRect(0, 0, btn->width(), btn->height());
1129 p.setPen(btn->colorGroup().button().dark(140)); 1134 p.setPen(btn->colorGroup().button().dark(140));
1130 p.drawLine(r.x()+1, r.y(), r.right()-1, r.y()); 1135 p.drawLine(r.x()+1, r.y(), r.right()-1, r.y());
1131 p.drawLine(r.x(), r.y()+1, r.x(), r.bottom()-1); 1136 p.drawLine(r.x(), r.y()+1, r.x(), r.bottom()-1);
1132 p.drawLine(r.right(), r.y()+1, r.right(), r.bottom()-1); 1137 p.drawLine(r.right(), r.y()+1, r.right(), r.bottom()-1);
1133 p.drawLine(r.x()+1, r.bottom(), r.right()-1, r.bottom()); 1138 p.drawLine(r.x()+1, r.bottom(), r.right()-1, r.bottom());
1134 } 1139 }
1135*/ 1140*/
1136 int x = 0; 1141 int x = 0;
1137 int y = (btn->height()-lsz.height()+fm.height()-sz.height())/2; 1142 int y = (btn->height()-lsz.height()+fm.height()-sz.height())/2;
1138 if(isRadio) 1143 if(isRadio)
1139 drawExclusiveIndicator(&p, x, y, sz.width(), sz.height(), 1144 drawExclusiveIndicator(&p, x, y, sz.width(), sz.height(),
1140 btn->colorGroup(), btn->isOn(), 1145 btn->colorGroup(), btn->isOn(),
1141 btn->isDown(), btn->isEnabled()); 1146 btn->isDown(), btn->isEnabled());
1142 else 1147 else
1143 drawIndicator(&p, x, y, sz.width(), sz.height(), 1148 drawIndicator(&p, x, y, sz.width(), sz.height(),
1144 btn->colorGroup(), btn->state(), btn->isDown(), 1149 btn->colorGroup(), btn->state(), btn->isDown(),
1145 btn->isEnabled()); 1150 btn->isEnabled());
1146 x = sz.width() + 6; 1151 x = sz.width() + 6;
1147 y = 0; 1152 y = 0;
1148 drawItem(&p, sz.width()+6+1, 0, btn->width()-(sz.width()+6+1), 1153 drawItem(&p, sz.width()+6+1, 0, btn->width()-(sz.width()+6+1),
1149 btn->height(), AlignLeft|AlignVCenter|ShowPrefix, 1154 btn->height(), AlignLeft|AlignVCenter|ShowPrefix,
1150 btn->colorGroup(), btn->isEnabled(), 1155 btn->colorGroup(), btn->isEnabled(),
1151 btn->pixmap(), btn->text()); 1156 btn->pixmap(), btn->text());
1152 p.end(); 1157 p.end();
1153 return(true); 1158 return(true);
1154 } 1159 }
1155 } 1160 }
1156 else if(obj->inherits("QHeader")){ 1161 else if(obj->inherits("QHeader")){
1157 QHeader *hw = (QHeader *)obj; 1162 QHeader *hw = (QHeader *)obj;
1158 if(ev->type() == QEvent::Enter){ 1163 if(ev->type() == QEvent::Enter){
1159 currentHeader = hw; 1164 currentHeader = hw;
1160 headerHoverID = -1; 1165 headerHoverID = -1;
1161 } 1166 }
1162 else if(ev->type() == QEvent::Leave){ 1167 else if(ev->type() == QEvent::Leave){
1163 currentHeader = NULL; 1168 currentHeader = NULL;
1164 if(headerHoverID != -1){ 1169 if(headerHoverID != -1){
1165 hw->repaint(hw->sectionPos(headerHoverID), 0, 1170 hw->repaint(hw->sectionPos(headerHoverID), 0,
1166 hw->sectionSize(headerHoverID), hw->height()); 1171 hw->sectionSize(headerHoverID), hw->height());
1167 } 1172 }
1168 headerHoverID = -1; 1173 headerHoverID = -1;
1169 } 1174 }
1170 else if(ev->type() == QEvent::MouseMove){ 1175 else if(ev->type() == QEvent::MouseMove){
1171 QMouseEvent *me = (QMouseEvent *)ev; 1176 QMouseEvent *me = (QMouseEvent *)ev;
1172 int oldHeader = headerHoverID; 1177 int oldHeader = headerHoverID;
1173 headerHoverID = hw->sectionAt(me->x()); 1178 headerHoverID = hw->sectionAt(me->x());
1174 if(oldHeader != headerHoverID){ 1179 if(oldHeader != headerHoverID){
1175 // reset old header 1180 // reset old header
1176 if(oldHeader != -1){ 1181 if(oldHeader != -1){
1177 hw->repaint(hw->sectionPos(oldHeader), 0, 1182 hw->repaint(hw->sectionPos(oldHeader), 0,
1178 hw->sectionSize(oldHeader), hw->height()); 1183 hw->sectionSize(oldHeader), hw->height());
1179 } 1184 }
1180 if(headerHoverID != -1){ 1185 if(headerHoverID != -1){
1181 hw->repaint(hw->sectionPos(headerHoverID), 0, 1186 hw->repaint(hw->sectionPos(headerHoverID), 0,
1182 hw->sectionSize(headerHoverID), hw->height()); 1187 hw->sectionSize(headerHoverID), hw->height());
1183 } 1188 }
1184 } 1189 }
1185 } 1190 }
1186 } 1191 }
1187 else if (obj-> inherits( "QProgressBar" )) { 1192 else if (obj-> inherits( "QProgressBar" )) {
1188 if ( ev->type() == QEvent::Paint ) { 1193 if ( ev->type() == QEvent::Paint ) {
1189 HackProgressBar *p = (HackProgressBar *) obj; 1194 HackProgressBar *p = (HackProgressBar *) obj;
1190 const QColorGroup &g = p-> colorGroup ( ); 1195 const QColorGroup &g = p-> colorGroup ( );
1191 1196
1192 QPixmap *pix = bevelFillDict.find(g.button().dark(120).rgb()); 1197 QPixmap *pix = bevelFillDict.find(g.button().dark(120).rgb());
1193 if(!pix){ 1198 if(!pix){
1194 int h, s, v; 1199 int h, s, v;
1195 g.button().dark(120).hsv(&h, &s, &v); 1200 g.button().dark(120).hsv(&h, &s, &v);
1196 pix = new QPixmap(*bevelFillPix); 1201 pix = new QPixmap(*bevelFillPix);
1197 adjustHSV(*pix, h, s, v); 1202 adjustHSV(*pix, h, s, v);
1198 bevelFillDict.insert(g.button().dark(120).rgb(), pix); 1203 bevelFillDict.insert(g.button().dark(120).rgb(), pix);
1199 } 1204 }
1200 p-> paint ((QPaintEvent *) ev, g, pix ); 1205 p-> paint ((QPaintEvent *) ev, g, pix );
1201 return true; 1206 return true;
1202 } 1207 }
1203 } 1208 }
1204 return false ; 1209 return false ;
1205} 1210}
1206 1211
1207void LiquidStyle::drawButton(QPainter *p, int x, int y, int w, int h, 1212void LiquidStyle::drawButton(QPainter *p, int x, int y, int w, int h,
1208 const QColorGroup &g, bool sunken, 1213 const QColorGroup &g, bool sunken,
1209 const QBrush *) 1214 const QBrush *)
1210{ 1215{
1211 drawRoundButton(p, sunken ? g.background() : g.button(), g.background(), 1216 drawRoundButton(p, sunken ? g.background() : g.button(), g.background(),
1212 x, y, w, h); 1217 x, y, w, h);
1213} 1218}
1214 1219
1215void LiquidStyle::drawToolButton(QPainter *p, int x, int y, int w, int h, 1220void LiquidStyle::drawToolButton(QPainter *p, int x, int y, int w, int h,
1216 const QColorGroup &g, bool sunken, 1221 const QColorGroup &g, bool sunken,
1217 const QBrush *) 1222 const QBrush *)
1218{ 1223{
1219 if(p->device()->devType() != QInternal::Widget){ 1224 if(p->device()->devType() != QInternal::Widget){
1220 // drawing into a temp pixmap, don't use mask 1225 // drawing into a temp pixmap, don't use mask
1221 QColor c = sunken ? g.button() : g.background(); 1226 QColor c = sunken ? g.button() : g.background();
1222 p->setPen(c.dark(130)); 1227 p->setPen(c.dark(130));
1223 p->drawRect(x, y, w, h); 1228 p->drawRect(x, y, w, h);
1224 p->setPen(c.light(105)); 1229 p->setPen(c.light(105));
1225 p->drawRect(x+1, y+1, w-2, h-2); 1230 p->drawRect(x+1, y+1, w-2, h-2);
1226 1231
1227 1232
1228 // fill 1233 // fill
1229 QPixmap *pix = bevelFillDict.find(c.rgb()); 1234 QPixmap *pix = bevelFillDict.find(c.rgb());
1230 if(!pix){ 1235 if(!pix){
1231 int h, s, v; 1236 int h, s, v;
1232 c.hsv(&h, &s, &v); 1237 c.hsv(&h, &s, &v);
1233 pix = new QPixmap(*bevelFillPix); 1238 pix = new QPixmap(*bevelFillPix);
1234 adjustHSV(*pix, h, s, v); 1239 adjustHSV(*pix, h, s, v);
1235 bevelFillDict.insert(c.rgb(), pix); 1240 bevelFillDict.insert(c.rgb(), pix);
1236 } 1241 }
1237 1242
1238 p->drawTiledPixmap(x+2, y+2, w-4, h-4, *pix); 1243 p->drawTiledPixmap(x+2, y+2, w-4, h-4, *pix);
1239 } 1244 }
1240 else{ 1245 else{
1241 drawClearBevel(p, x, y, w, h, sunken ? g.button() : 1246 drawClearBevel(p, x, y, w, h, sunken ? g.button() :
1242 highlightWidget == p->device() ? g.button().light(110) : 1247 highlightWidget == p->device() ? g.button().light(110) :
1243 g.background(), g.background()); 1248 g.background(), g.background());
1244 } 1249 }
1245} 1250}
1246 1251
1247void LiquidStyle::drawPushButton(QPushButton *btn, QPainter *p) 1252void LiquidStyle::drawPushButton(QPushButton *btn, QPainter *p)
1248{ 1253{
1249 QRect r = btn->rect(); 1254 QRect r = btn->rect();
1250 bool sunken = btn->isOn() || btn->isDown(); 1255 bool sunken = btn->isOn() || btn->isDown();
1251 QColorGroup g = btn->colorGroup(); 1256 QColorGroup g = btn->colorGroup();
1252 1257
1253 1258
1254 //int dw = buttonDefaultIndicatorWidth(); 1259 //int dw = buttonDefaultIndicatorWidth();
1255 if(btn->hasFocus() || btn->isDefault()){ 1260 if(btn->hasFocus() || btn->isDefault()){
1256 QColor c = btn->hasFocus() ? g.button().light(110) : g.background(); 1261 QColor c = btn->hasFocus() ? g.button().light(110) : g.background();
1257 QPixmap *pix = bevelFillDict.find(c.rgb()); 1262 QPixmap *pix = bevelFillDict.find(c.rgb());
1258 if(!pix){ 1263 if(!pix){
1259 int h, s, v; 1264 int h, s, v;
1260 c.hsv(&h, &s, &v); 1265 c.hsv(&h, &s, &v);
1261 pix = new QPixmap(*bevelFillPix); 1266 pix = new QPixmap(*bevelFillPix);
1262 adjustHSV(*pix, h, s, v); 1267 adjustHSV(*pix, h, s, v);
1263 bevelFillDict.insert(c.rgb(), pix); 1268 bevelFillDict.insert(c.rgb(), pix);
1264 } 1269 }
1265 p->setPen(c.dark(150)); 1270 p->setPen(c.dark(150));
1266 p->drawLine(r.x()+1, r.y(), r.right()-1, r.y()); 1271 p->drawLine(r.x()+1, r.y(), r.right()-1, r.y());
1267 p->drawLine(r.x(), r.y()+1, r.x(), r.bottom()-1); 1272 p->drawLine(r.x(), r.y()+1, r.x(), r.bottom()-1);
1268 p->drawLine(r.right(), r.y()+1, r.right(), r.bottom()-1); 1273 p->drawLine(r.right(), r.y()+1, r.right(), r.bottom()-1);
1269 p->drawLine(r.x()+1, r.bottom(), r.right()-1, r.bottom()); 1274 p->drawLine(r.x()+1, r.bottom(), r.right()-1, r.bottom());
1270 p->drawTiledPixmap(r.x()+1, r.y()+1, r.width()-2, r.height()-2, *pix); 1275 p->drawTiledPixmap(r.x()+1, r.y()+1, r.width()-2, r.height()-2, *pix);
1271 } 1276 }
1272 1277
1273 QColor newColor = btn == highlightWidget || sunken ? 1278 QColor newColor = btn == highlightWidget || sunken ?
1274 g.button().light(120) : g.button(); 1279 g.button().light(120) : g.button();
1275 1280
1276 drawRoundButton(p, newColor, g.background(), 1281 drawRoundButton(p, newColor, g.background(),
1277 r.x(), r.y(), r.width(), r.height(), !btn->autoMask(), 1282 r.x(), r.y(), r.width(), r.height(), !btn->autoMask(),
1278 sunken, btn->isDefault() || btn->autoDefault() || btn->hasFocus(), 1283 sunken, btn->isDefault() || btn->autoDefault() || btn->hasFocus(),
1279 btn->autoMask()); 1284 btn->autoMask());
1280} 1285}
1281 1286
1282void LiquidStyle::drawPushButtonLabel(QPushButton *btn, QPainter *p) 1287void LiquidStyle::drawPushButtonLabel(QPushButton *btn, QPainter *p)
1283{ 1288{
1284 int x1, y1, x2, y2, w, h; 1289 int x1, y1, x2, y2, w, h;
1285 btn->rect().coords(&x1, &y1, &x2, &y2); 1290 btn->rect().coords(&x1, &y1, &x2, &y2);
1286 w = btn->width(); 1291 w = btn->width();
1287 h = btn->height(); 1292 h = btn->height();
1288 1293
1289 bool act = btn->isOn() || btn->isDown(); 1294 bool act = btn->isOn() || btn->isDown();
1290 if(act){ 1295 if(act){
1291 ++x1, ++y1; 1296 ++x1, ++y1;
1292 } 1297 }
1293 1298
1294 // Draw iconset first, if any 1299 // Draw iconset first, if any
1295 if ( btn->iconSet() && !btn->iconSet()->isNull() ) 1300 if ( btn->iconSet() && !btn->iconSet()->isNull() )
1296 { 1301 {
1297 QIconSet::Mode mode = btn->isEnabled() 1302 QIconSet::Mode mode = btn->isEnabled()
1298 ? QIconSet::Normal : QIconSet::Disabled; 1303 ? QIconSet::Normal : QIconSet::Disabled;
1299 if ( mode == QIconSet::Normal && btn->hasFocus() ) 1304 if ( mode == QIconSet::Normal && btn->hasFocus() )
1300 mode = QIconSet::Active; 1305 mode = QIconSet::Active;
1301 QPixmap pixmap = btn->iconSet()->pixmap( QIconSet::Small, mode ); 1306 QPixmap pixmap = btn->iconSet()->pixmap( QIconSet::Small, mode );
1302 int pixw = pixmap.width(); 1307 int pixw = pixmap.width();
1303 int pixh = pixmap.height(); 1308 int pixh = pixmap.height();
1304 1309
1305 p->drawPixmap( x1+6, y1+h/2-pixh/2, pixmap ); 1310 p->drawPixmap( x1+6, y1+h/2-pixh/2, pixmap );
1306 x1 += pixw + 8; 1311 x1 += pixw + 8;
1307 w -= pixw + 8; 1312 w -= pixw + 8;
1308 } 1313 }
1309 1314
1310 if(act){ 1315 if(act){
1311 QFont font = btn->font(); 1316 QFont font = btn->font();
1312 font.setBold(true); 1317 font.setBold(true);
1313 p->setFont(font); 1318 p->setFont(font);
1314 QColor shadow(btn->colorGroup().button().dark(130)); 1319 QColor shadow(btn->colorGroup().button().dark(130));
1315 drawItem( p, x1+1, y1+1, w, h, 1320 drawItem( p, x1+1, y1+1, w, h,
1316 AlignCenter | ShowPrefix, btn->colorGroup(), btn->isEnabled(), 1321 AlignCenter | ShowPrefix, btn->colorGroup(), btn->isEnabled(),
1317 btn->pixmap(), btn->text(), -1, 1322 btn->pixmap(), btn->text(), -1,
1318 &shadow); 1323 &shadow);
1319 1324
1320 drawItem( p, x1, y1, w, h, 1325 drawItem( p, x1, y1, w, h,
1321 AlignCenter | ShowPrefix, btn->colorGroup(), btn->isEnabled(), 1326 AlignCenter | ShowPrefix, btn->colorGroup(), btn->isEnabled(),
1322 btn->pixmap(), btn->text(), -1, &btn->colorGroup().light()); 1327 btn->pixmap(), btn->text(), -1, &btn->colorGroup().light());
1323 } 1328 }
1324 else{ 1329 else{
1325 /* Too blurry 1330 /* Too blurry
1326 drawItem( p, x1+1, y1+1, w, h, 1331 drawItem( p, x1+1, y1+1, w, h,
1327 AlignCenter | ShowPrefix, btn->colorGroup(), btn->isEnabled(), 1332 AlignCenter | ShowPrefix, btn->colorGroup(), btn->isEnabled(),
1328 btn->pixmap(), btn->text(), -1, 1333 btn->pixmap(), btn->text(), -1,
1329 &btn->colorGroup().button().dark(115)); 1334 &btn->colorGroup().button().dark(115));
1330 */ 1335 */
1331 drawItem( p, x1, y1, w, h, 1336 drawItem( p, x1, y1, w, h,
1332 AlignCenter | ShowPrefix, 1337 AlignCenter | ShowPrefix,
1333 btn->colorGroup(), btn->isEnabled(), 1338 btn->colorGroup(), btn->isEnabled(),
1334 btn->pixmap(), btn->text(), -1, 1339 btn->pixmap(), btn->text(), -1,
1335 &btn->colorGroup().buttonText()); 1340 &btn->colorGroup().buttonText());
1336 } 1341 }
1337} 1342}
1338 1343
1339void LiquidStyle::drawButtonMask(QPainter *p, int x, int y, int w, int h) 1344void LiquidStyle::drawButtonMask(QPainter *p, int x, int y, int w, int h)
1340{ 1345{
1341 int x2 = x+w-1; 1346 int x2 = x+w-1;
1342 int y2 = y+h-1; 1347 int y2 = y+h-1;
1343 1348
1344 p->setPen(Qt::color1); 1349 p->setPen(Qt::color1);
1345 p->fillRect(x, y, w, h, Qt::color0); 1350 p->fillRect(x, y, w, h, Qt::color0);
1346 if(w < 21 || h < 21){ 1351 if(w < 21 || h < 21){
1347 // outer rect 1352 // outer rect
1348 p->drawLine(x, y+2, x, y2-2); // l 1353 p->drawLine(x, y+2, x, y2-2); // l
1349 p->drawLine(x2, y+2, x2, y2-2); // r 1354 p->drawLine(x2, y+2, x2, y2-2); // r
1350 p->drawLine(x+2, y, x2-2, y); // t 1355 p->drawLine(x+2, y, x2-2, y); // t
1351 p->drawLine(x+2, y2, x2-2, y2); // b 1356 p->drawLine(x+2, y2, x2-2, y2); // b
1352 p->drawLine(x+1, y+1, x2-1, y+1); // top second line 1357 p->drawLine(x+1, y+1, x2-1, y+1); // top second line
1353 p->drawLine(x+1, y2-1, x2-1, y2-1); // bottom second line 1358 p->drawLine(x+1, y2-1, x2-1, y2-1); // bottom second line
1354 p->fillRect(x+1, y+2, w-2, h-4, Qt::color1); 1359 p->fillRect(x+1, y+2, w-2, h-4, Qt::color1);
1355 } 1360 }
1356 else{ 1361 else{
1357 int x2 = x+w-1; 1362 int x2 = x+w-1;
1358 int y2 = y+h-1; 1363 int y2 = y+h-1;
1359 int bx2 = htmlBtnMaskBmp.width()-1; 1364 int bx2 = htmlBtnMaskBmp.width()-1;
1360 int by2 = htmlBtnMaskBmp.height()-1; 1365 int by2 = htmlBtnMaskBmp.height()-1;
1361 p->drawPixmap(0, 0, htmlBtnMaskBmp, 0, 0, 10, 10); // tl 1366 p->drawPixmap(0, 0, htmlBtnMaskBmp, 0, 0, 10, 10); // tl
1362 p->drawPixmap(x2-9, 0, htmlBtnMaskBmp, bx2-9, 0, 10, 10); // tr 1367 p->drawPixmap(x2-9, 0, htmlBtnMaskBmp, bx2-9, 0, 10, 10); // tr
1363 p->drawPixmap(0, y2-9, htmlBtnMaskBmp, 0, by2-9, 10, 10); // bl 1368 p->drawPixmap(0, y2-9, htmlBtnMaskBmp, 0, by2-9, 10, 10); // bl
1364 p->drawPixmap(x2-9, y2-9, htmlBtnMaskBmp, bx2-9, by2-9, 10, 10); // br 1369 p->drawPixmap(x2-9, y2-9, htmlBtnMaskBmp, bx2-9, by2-9, 10, 10); // br
1365 // fills 1370 // fills
1366 p->fillRect(10, 0, w-20, 10, Qt::color1); // top 1371 p->fillRect(10, 0, w-20, 10, Qt::color1); // top
1367 p->fillRect(10, y2-9, w-20, 10, Qt::color1); // bottom 1372 p->fillRect(10, y2-9, w-20, 10, Qt::color1); // bottom
1368 p->fillRect(0, 10, w, h-20, Qt::color1); // middle 1373 p->fillRect(0, 10, w, h-20, Qt::color1); // middle
1369 } 1374 }
1370} 1375}
1371 1376
1372void LiquidStyle::drawBevelButton(QPainter *p, int x, int y, int w, int h, 1377void LiquidStyle::drawBevelButton(QPainter *p, int x, int y, int w, int h,
1373 const QColorGroup &g, bool sunken, 1378 const QColorGroup &g, bool sunken,
1374 const QBrush */*fill*/) 1379 const QBrush */*fill*/)
1375{ 1380{
1376 if(currentHeader && p->device() == currentHeader){ 1381 if(currentHeader && p->device() == currentHeader){
1377 int id = currentHeader->sectionAt(x); 1382 int id = currentHeader->sectionAt(x);
1378 bool isHeaderHover = id != -1 && id == headerHoverID; 1383 bool isHeaderHover = id != -1 && id == headerHoverID;
1379 drawClearBevel(p, x, y, w, h, sunken ? 1384 drawClearBevel(p, x, y, w, h, sunken ?
1380 g.button() : isHeaderHover ? g.button().light(110) : 1385 g.button() : isHeaderHover ? g.button().light(110) :
1381 g.background(), g.background()); 1386 g.background(), g.background());
1382 } 1387 }
1383 else 1388 else
1384 drawClearBevel(p, x, y, w, h, sunken ? g.button() : g.background(), 1389 drawClearBevel(p, x, y, w, h, sunken ? g.button() : g.background(),
1385 g.background()); 1390 g.background());
1386} 1391}
1387 1392
1388QRect LiquidStyle::buttonRect(int x, int y, int w, int h) 1393QRect LiquidStyle::buttonRect(int x, int y, int w, int h)
1389{ 1394{
1390 return(QRect(x+5, y+5, w-10, h-10)); 1395 return(QRect(x+5, y+5, w-10, h-10));
1391} 1396}
1392 1397
1393void LiquidStyle::drawComboButton(QPainter *painter, int x, int y, int w, int h, 1398void LiquidStyle::drawComboButton(QPainter *painter, int x, int y, int w, int h,
1394 const QColorGroup &g, bool sunken, 1399 const QColorGroup &g, bool sunken,
1395 bool edit, bool, const QBrush *) 1400 bool edit, bool, const QBrush *)
1396{ 1401{
1397 bool isActive = false; 1402 bool isActive = false;
1398 if (( painter->device()->devType() == QInternal::Widget ) && 1403 if (( painter->device()->devType() == QInternal::Widget ) &&
1399 ( 1404 (
1400 ( qApp-> focusWidget ( ) == painter-> device ( )) || 1405 ( qApp-> focusWidget ( ) == painter-> device ( )) ||
1401 ( 1406 (
1402 edit && 1407 edit &&
1403 ((QWidget *) painter-> device ( ))-> inherits ( "QComboBox" ) && 1408 ((QWidget *) painter-> device ( ))-> inherits ( "QComboBox" ) &&
1404 ( qApp-> focusWidget ( ) == ((QComboBox *) painter->device())->lineEdit ( ) || 1409 ( qApp-> focusWidget ( ) == ((QComboBox *) painter->device())->lineEdit ( ) ||
1405 qApp-> focusWidget ( ) == ((QComboBox *) painter->device())->listBox ( )) 1410 qApp-> focusWidget ( ) == ((QComboBox *) painter->device())->listBox ( ))
1406 ) 1411 )
1407 ) 1412 )
1408 ) { 1413 ) {
1409 isActive = true; 1414 isActive = true;
1410 } 1415 }
1411 1416
1412 bool isMasked = false; 1417 bool isMasked = false;
1413 if(painter->device()->devType() == QInternal::Widget) 1418 if(painter->device()->devType() == QInternal::Widget)
1414 isMasked = ((QWidget*)painter->device())->autoMask(); 1419 isMasked = ((QWidget*)painter->device())->autoMask();
1415 // TODO: Do custom code, don't just call drawRoundButton into a pixmap 1420 // TODO: Do custom code, don't just call drawRoundButton into a pixmap
1416 QPixmap tmpPix(w, h); 1421 QPixmap tmpPix(w, h);
1417 QPainter p(&tmpPix); 1422 QPainter p(&tmpPix);
1418 1423
1419 drawRoundButton(&p, g.button(), g.background(), 0, 0, w, h, false, 1424 drawRoundButton(&p, g.button(), g.background(), 0, 0, w, h, false,
1420 sunken, false, isMasked); 1425 sunken, false, isMasked);
1421 if(!isActive){ 1426 if(!isActive){
1422 p.setClipRect(0, 0, w-17, h); 1427 p.setClipRect(0, 0, w-17, h);
1423 drawRoundButton(&p, g.background(), g.background(), 0, 0, w, h, false, 1428 drawRoundButton(&p, g.background(), g.background(), 0, 0, w, h, false,
1424 sunken, false, isMasked); 1429 sunken, false, isMasked);
1425 } 1430 }
1426 p.end(); 1431 p.end();
1427 int x2 = x+w-1; 1432 int x2 = x+w-1;
1428 int y2 = y+h-1; 1433 int y2 = y+h-1;
1429 int bx2 = btnMaskBmp.width()-1; 1434 int bx2 = btnMaskBmp.width()-1;
1430 int by2 = btnMaskBmp.height()-1; 1435 int by2 = btnMaskBmp.height()-1;
1431 QBitmap btnMask(w, h); 1436 QBitmap btnMask(w, h);
1432 QBitmap *mask = isMasked ? &htmlBtnMaskBmp : &btnMaskBmp; 1437 QBitmap *mask = isMasked ? &htmlBtnMaskBmp : &btnMaskBmp;
1433 p.begin(&btnMask); 1438 p.begin(&btnMask);
1434 p.fillRect(0, 0, w, h, Qt::color0); 1439 p.fillRect(0, 0, w, h, Qt::color0);
1435 p.drawPixmap(0, 0, *mask, 0, 0, 10, 10); // tl 1440 p.drawPixmap(0, 0, *mask, 0, 0, 10, 10); // tl
1436 p.drawPixmap(x2-9, 0, *mask, bx2-9, 0, 10, 10); // tr 1441 p.drawPixmap(x2-9, 0, *mask, bx2-9, 0, 10, 10); // tr
1437 p.drawPixmap(0, y2-9, *mask, 0, by2-9, 10, 10); // bl 1442 p.drawPixmap(0, y2-9, *mask, 0, by2-9, 10, 10); // bl
1438 p.drawPixmap(x2-9, y2-9, *mask, bx2-9, by2-9, 10, 10); // br 1443 p.drawPixmap(x2-9, y2-9, *mask, bx2-9, by2-9, 10, 10); // br
1439 // fills 1444 // fills
1440 p.fillRect(10, 0, w-20, 10, Qt::color1); // top 1445 p.fillRect(10, 0, w-20, 10, Qt::color1); // top
1441 p.fillRect(10, y2-9, w-20, 10, Qt::color1); // bottom 1446 p.fillRect(10, y2-9, w-20, 10, Qt::color1); // bottom
1442 p.fillRect(0, 10, w, h-20, Qt::color1); // middle 1447 p.fillRect(0, 10, w, h-20, Qt::color1); // middle
1443 p.end(); 1448 p.end();
1444 tmpPix.setMask(btnMask); 1449 tmpPix.setMask(btnMask);
1445 1450
1446 painter->drawPixmap(x, y, tmpPix); 1451 painter->drawPixmap(x, y, tmpPix);
1447 1452
1448 painter->setPen(g.button().dark(120)); 1453 painter->setPen(g.button().dark(120));
1449 painter->drawLine(x2-16, y+1, x2-16, y2-1); 1454 painter->drawLine(x2-16, y+1, x2-16, y2-1);
1450 1455
1451 if(edit){ 1456 if(edit){
1452 painter->setPen(g.mid()); 1457 painter->setPen(g.mid());
1453 painter->drawRect(x+8, y+2, w-25, h-4); 1458 painter->drawRect(x+8, y+2, w-25, h-4);
1454 } 1459 }
1455 int arrow_h = h / 3; 1460 int arrow_h = h / 3;
1456 int arrow_w = arrow_h; 1461 int arrow_w = arrow_h;
1457 int arrow_x = w - arrow_w - 6; 1462 int arrow_x = w - arrow_w - 6;
1458 int arrow_y = (h - arrow_h) / 2; 1463 int arrow_y = (h - arrow_h) / 2;
1459 drawArrow(painter, DownArrow, false, arrow_x, arrow_y, arrow_w, arrow_h, g, true); 1464 drawArrow(painter, DownArrow, false, arrow_x, arrow_y, arrow_w, arrow_h, g, true);
1460} 1465}
1461 1466
1462void LiquidStyle::drawComboButtonMask(QPainter *p, int x, int y, int w, int h) 1467void LiquidStyle::drawComboButtonMask(QPainter *p, int x, int y, int w, int h)
1463{ 1468{
1464 drawButtonMask(p, x, y, w, h); 1469 drawButtonMask(p, x, y, w, h);
1465} 1470}
1466 1471
1467QRect LiquidStyle::comboButtonRect(int x, int y, int w, int h) 1472QRect LiquidStyle::comboButtonRect(int x, int y, int w, int h)
1468{ 1473{
1469 //return(QRect(x+3, y+3, w - (h / 3) - 13, h-6)); 1474 //return(QRect(x+3, y+3, w - (h / 3) - 13, h-6));
1470 return(QRect(x+9, y+3, w - (h / 3) - 20, h-6)); 1475 return(QRect(x+9, y+3, w - (h / 3) - 20, h-6));
1471} 1476}
1472 1477
1473QRect LiquidStyle::comboButtonFocusRect(int /*x*/, int /*y*/, int /*w*/, int /*h*/) 1478QRect LiquidStyle::comboButtonFocusRect(int /*x*/, int /*y*/, int /*w*/, int /*h*/)
1474{ 1479{
1475 return QRect ( ); 1480 return QRect ( );
1476 1481
1477// return(QRect(x+5, y+3, w-(h/3)-13, h-5)); 1482// return(QRect(x+5, y+3, w-(h/3)-13, h-5));
1478} 1483}
1479 1484
1480void LiquidStyle::drawScrollBarControls(QPainter *p, const QScrollBar *sb, 1485void LiquidStyle::drawScrollBarControls(QPainter *p, const QScrollBar *sb,
1481 int sliderStart, uint controls, 1486 int sliderStart, uint controls,
1482 uint activeControl) 1487 uint activeControl)
1483{ 1488{
1484 int sliderMin, sliderMax, sliderLength, buttonDim; 1489 int sliderMin, sliderMax, sliderLength, buttonDim;
1485 scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim ); 1490 scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim );
1486 1491
1487 if (sliderStart > sliderMax) 1492 if (sliderStart > sliderMax)
1488 sliderStart = sliderMax; 1493 sliderStart = sliderMax;
1489 1494
1490 bool horiz = sb->orientation() == QScrollBar::Horizontal; 1495 bool horiz = sb->orientation() == QScrollBar::Horizontal;
1491 QColorGroup g = sb->colorGroup(); 1496 QColorGroup g = sb->colorGroup();
1492 QRect addB, subHC, subB; 1497 QRect addB, subHC, subB;
1493 QRect addPageR, subPageR, sliderR; 1498 QRect addPageR, subPageR, sliderR;
1494 int addX, addY, subX, subY; 1499 int addX, addY, subX, subY;
1495 int len = horiz ? sb->width() : sb->height(); 1500 int len = horiz ? sb->width() : sb->height();
1496 int extent = horiz ? sb->height() : sb->width(); 1501 int extent = horiz ? sb->height() : sb->width();
1497 1502
1498 // a few apps (ie: KSpread), are broken and use a hardcoded scrollbar 1503 // a few apps (ie: KSpread), are broken and use a hardcoded scrollbar
1499 // extent of 16. Luckily, most apps (ie: Kate), seem fixed by now. 1504 // extent of 16. Luckily, most apps (ie: Kate), seem fixed by now.
1500 bool brokenApp; 1505 bool brokenApp;
1501 if(extent == 16) 1506 if(extent == 16)
1502 brokenApp = true; 1507 brokenApp = true;
1503 else 1508 else
1504 brokenApp = false; 1509 brokenApp = false;
1505 1510
1506 if (horiz) { 1511 if (horiz) {
1507 subY = addY = ( extent - buttonDim ) / 2; 1512 subY = addY = ( extent - buttonDim ) / 2;
1508 subX = 0; 1513 subX = 0;
1509 addX = len - buttonDim; 1514 addX = len - buttonDim;
1510 if(sbBuffer.size() != sb->size()) 1515 if(sbBuffer.size() != sb->size())
1511 sbBuffer.resize(sb->size()); 1516 sbBuffer.resize(sb->size());
1512 } 1517 }
1513 else { 1518 else {
1514 subX = addX = ( extent - buttonDim ) / 2; 1519 subX = addX = ( extent - buttonDim ) / 2;
1515 subY = 0; 1520 subY = 0;
1516 addY = len - buttonDim; 1521 addY = len - buttonDim;
1517 if(sbBuffer.size() != sb->size()) 1522 if(sbBuffer.size() != sb->size())
1518 sbBuffer.resize(sb->size()); 1523 sbBuffer.resize(sb->size());
1519 } 1524 }
1520 subB.setRect( subX,subY,0,0); // buttonDim,buttonDim ); 1525 subB.setRect( subX,subY,0,0); // buttonDim,buttonDim );
1521 addB.setRect( addX,addY,buttonDim,buttonDim ); 1526 addB.setRect( addX,addY,buttonDim,buttonDim );
1522 if(horiz) 1527 if(horiz)
1523 subHC.setRect(addX-buttonDim,addY,buttonDim,buttonDim ); 1528 subHC.setRect(addX-buttonDim,addY,buttonDim,buttonDim );
1524 else 1529 else
1525 subHC.setRect(addX,addY-buttonDim,buttonDim,buttonDim ); 1530 subHC.setRect(addX,addY-buttonDim,buttonDim,buttonDim );
1526 1531
1527 int sliderEnd = sliderStart + sliderLength; 1532 int sliderEnd = sliderStart + sliderLength;
1528 int sliderW = extent; 1533 int sliderW = extent;
1529 1534
1530 if (horiz) { 1535 if (horiz) {
1531 subPageR.setRect( subB.right() + 1, 0, 1536 subPageR.setRect( subB.right() + 1, 0,
1532 sliderStart - subB.right() - 1 , sliderW ); 1537 sliderStart - subB.right() - 1 , sliderW );
1533 addPageR.setRect( sliderEnd, 0, addX - sliderEnd - buttonDim, sliderW ); 1538 addPageR.setRect( sliderEnd, 0, addX - sliderEnd - buttonDim, sliderW );
1534 sliderR .setRect( sliderStart, 0, sliderLength, sliderW ); 1539 sliderR .setRect( sliderStart, 0, sliderLength, sliderW );
1535 } 1540 }
1536 else { 1541 else {
1537 subPageR.setRect( 0, subB.bottom() + 1, sliderW, 1542 subPageR.setRect( 0, subB.bottom() + 1, sliderW,
1538 sliderStart - subB.bottom() - 1 ); 1543 sliderStart - subB.bottom() - 1 );
1539 addPageR.setRect( 0, sliderEnd, sliderW, addY - buttonDim - sliderEnd); 1544 addPageR.setRect( 0, sliderEnd, sliderW, addY - buttonDim - sliderEnd);
1540 sliderR .setRect( 0, sliderStart, sliderW, sliderLength ); 1545 sliderR .setRect( 0, sliderStart, sliderW, sliderLength );
1541 } 1546 }
1542 1547
1543 bool maxed = sb->maxValue() == sb->minValue(); 1548 bool maxed = sb->maxValue() == sb->minValue();
1544 1549
1545 QPainter painter; 1550 QPainter painter;
1546 if(!horiz){ 1551 if(!horiz){
1547 painter.begin(&sbBuffer); 1552 painter.begin(&sbBuffer);
1548 QRect bgR(0, subB.bottom()+1, sb->width(), (len-(buttonDim*2))+1); 1553 QRect bgR(0, subB.bottom()+1, sb->width(), (len-(buttonDim*2))+1);
1549 if(sliderR.height() >= 8){ 1554 if(sliderR.height() >= 8){
1550 painter.drawPixmap(bgR.x()+1, bgR.y(), *vsbSliderFillPix, 0, 0, 1555 painter.drawPixmap(bgR.x()+1, bgR.y(), *vsbSliderFillPix, 0, 0,
1551 13, 8); 1556 13, 8);
1552 painter.drawPixmap(bgR.x()+1, bgR.y(), *getPixmap(VSBSliderTopBg)); 1557 painter.drawPixmap(bgR.x()+1, bgR.y(), *getPixmap(VSBSliderTopBg));
1553 painter.drawTiledPixmap(bgR.x()+1, bgR.y()+8, 13, 1558 painter.drawTiledPixmap(bgR.x()+1, bgR.y()+8, 13,
1554 bgR.height()-16, *getPixmap(VSBSliderMidBg)); 1559 bgR.height()-16, *getPixmap(VSBSliderMidBg));
1555 painter.drawPixmap(bgR.x()+1, bgR.bottom()-8, *vsbSliderFillPix, 1560 painter.drawPixmap(bgR.x()+1, bgR.bottom()-8, *vsbSliderFillPix,
1556 0, 0, 13, 8); 1561 0, 0, 13, 8);
1557 painter.drawPixmap(bgR.x()+1, bgR.bottom()-8, *getPixmap(VSBSliderBtmBg)); 1562 painter.drawPixmap(bgR.x()+1, bgR.bottom()-8, *getPixmap(VSBSliderBtmBg));
1558 } 1563 }
1559 else{ 1564 else{
1560 painter.drawTiledPixmap(bgR.x()+1, bgR.y(), 13, bgR.height(), 1565 painter.drawTiledPixmap(bgR.x()+1, bgR.y(), 13, bgR.height(),
1561 *getPixmap(VSBSliderMidBg)); 1566 *getPixmap(VSBSliderMidBg));
1562 painter.setPen(g.background().dark(210)); 1567 painter.setPen(g.background().dark(210));
1563 painter.drawRect(bgR.x()+1, bgR.y(), 13, bgR.height()-1); 1568 painter.drawRect(bgR.x()+1, bgR.y(), 13, bgR.height()-1);
1564 painter.setPen(g.mid()); 1569 painter.setPen(g.mid());
1565 painter.drawPoint(bgR.x()+1, bgR.y()); 1570 painter.drawPoint(bgR.x()+1, bgR.y());
1566 painter.drawPoint(bgR.x()+13, bgR.y()); 1571 painter.drawPoint(bgR.x()+13, bgR.y());
1567 painter.drawPoint(bgR.x()+1, bgR.bottom()-1); 1572 painter.drawPoint(bgR.x()+1, bgR.bottom()-1);
1568 painter.drawPoint(bgR.x()+13, bgR.bottom()-1); 1573 painter.drawPoint(bgR.x()+13, bgR.bottom()-1);
1569 } 1574 }
1570 if(controls & Slider){ 1575 if(controls & Slider){
1571 if(sliderR.height() >= 16){ 1576 if(sliderR.height() >= 16){
1572 painter.drawPixmap(sliderR.x()+1, sliderR.y(), *getPixmap(VSBSliderTop)); 1577 painter.drawPixmap(sliderR.x()+1, sliderR.y(), *getPixmap(VSBSliderTop));
1573 painter.drawTiledPixmap(sliderR.x()+1, sliderR.y()+8, 13, 1578 painter.drawTiledPixmap(sliderR.x()+1, sliderR.y()+8, 13,
1574 sliderR.height()-16, *getPixmap(VSBSliderMid)); 1579 sliderR.height()-16, *getPixmap(VSBSliderMid));
1575 painter.drawPixmap(sliderR.x()+1, sliderR.bottom()-8, *getPixmap(VSBSliderBtm)); 1580 painter.drawPixmap(sliderR.x()+1, sliderR.bottom()-8, *getPixmap(VSBSliderBtm));
1576 } 1581 }
1577 else if(sliderR.height() >= 8){ 1582 else if(sliderR.height() >= 8){
1578 int m = sliderR.height()/2; 1583 int m = sliderR.height()/2;
1579 painter.drawPixmap(sliderR.x()+1, sliderR.y(), *getPixmap(VSBSliderTop), 0, 0, 13, m); 1584 painter.drawPixmap(sliderR.x()+1, sliderR.y(), *getPixmap(VSBSliderTop), 0, 0, 13, m);
1580 painter.drawPixmap(sliderR.x()+1, sliderR.y()+m, *getPixmap(VSBSliderBtm), 0, 8-m, 13, m); 1585 painter.drawPixmap(sliderR.x()+1, sliderR.y()+m, *getPixmap(VSBSliderBtm), 0, 8-m, 13, m);
1581 } 1586 }
1582 else{ 1587 else{
1583 painter.setPen(g.button().dark(210)); 1588 painter.setPen(g.button().dark(210));
1584 drawRoundRect(&painter, sliderR.x()+1, sliderR.y(), 1589 drawRoundRect(&painter, sliderR.x()+1, sliderR.y(),
1585 13, sliderR.height()); 1590 13, sliderR.height());
1586 painter.drawTiledPixmap(sliderR.x()+2, sliderR.y()+1, 1591 painter.drawTiledPixmap(sliderR.x()+2, sliderR.y()+1,
1587 11, sliderR.height()-2, 1592 11, sliderR.height()-2,
1588 *getPixmap(VSBSliderMid), 1, 0); 1593 *getPixmap(VSBSliderMid), 1, 0);
1589 } 1594 }
1590 } 1595 }
1591 painter.setPen(g.mid()); 1596 painter.setPen(g.mid());
1592 painter.drawLine(bgR.x(), bgR.y(), bgR.x(), bgR.bottom()); 1597 painter.drawLine(bgR.x(), bgR.y(), bgR.x(), bgR.bottom());
1593 painter.drawLine(bgR.right(), bgR.y(), bgR.right(), bgR.bottom()); 1598 painter.drawLine(bgR.right(), bgR.y(), bgR.right(), bgR.bottom());
1594 if(brokenApp && (controls & Slider)){ 1599 if(brokenApp && (controls & Slider)){
1595 painter.setPen(g.background()); 1600 painter.setPen(g.background());
1596 painter.drawLine(bgR.right()-1, bgR.y(), bgR.right()-1, 1601 painter.drawLine(bgR.right()-1, bgR.y(), bgR.right()-1,
1597 bgR.bottom()); 1602 bgR.bottom());
1598 } 1603 }
1599 painter.end(); 1604 painter.end();
1600 } 1605 }
1601 else{ 1606 else{
1602 painter.begin(&sbBuffer); 1607 painter.begin(&sbBuffer);
1603 QRect bgR(subB.right()+1, 0, (len-(buttonDim*2))+1, sb->height()); 1608 QRect bgR(subB.right()+1, 0, (len-(buttonDim*2))+1, sb->height());
1604 if(sliderR.width() >= 8){ 1609 if(sliderR.width() >= 8){
1605 painter.drawPixmap(bgR.x(), bgR.y()+1, *vsbSliderFillPix, 0, 0, 1610 painter.drawPixmap(bgR.x(), bgR.y()+1, *vsbSliderFillPix, 0, 0,
1606 8, 13); 1611 8, 13);
1607 painter.drawPixmap(bgR.x(), bgR.y()+1, *getPixmap(HSBSliderTopBg)); 1612 painter.drawPixmap(bgR.x(), bgR.y()+1, *getPixmap(HSBSliderTopBg));
1608 painter.drawTiledPixmap(bgR.x()+8, bgR.y()+1, bgR.width()-16, 1613 painter.drawTiledPixmap(bgR.x()+8, bgR.y()+1, bgR.width()-16,
1609 13, *getPixmap(HSBSliderMidBg)); 1614 13, *getPixmap(HSBSliderMidBg));
1610 painter.drawPixmap(bgR.right()-8, bgR.y()+1, *vsbSliderFillPix, 1615 painter.drawPixmap(bgR.right()-8, bgR.y()+1, *vsbSliderFillPix,
1611 0, 0, 8, 13); 1616 0, 0, 8, 13);
1612 painter.drawPixmap(bgR.right()-8, bgR.y()+1, *getPixmap(HSBSliderBtmBg)); 1617 painter.drawPixmap(bgR.right()-8, bgR.y()+1, *getPixmap(HSBSliderBtmBg));
1613 } 1618 }
1614 else{ 1619 else{
1615 painter.drawTiledPixmap(bgR.x(), bgR.y()+1, bgR.width(), 13, 1620 painter.drawTiledPixmap(bgR.x(), bgR.y()+1, bgR.width(), 13,
1616 *getPixmap(HSBSliderMidBg)); 1621 *getPixmap(HSBSliderMidBg));
1617 painter.setPen(g.background().dark(210)); 1622 painter.setPen(g.background().dark(210));
1618 painter.drawRect(bgR.x(), bgR.y()+1, bgR.width()-1, 13); 1623 painter.drawRect(bgR.x(), bgR.y()+1, bgR.width()-1, 13);
1619 painter.setPen(g.mid()); 1624 painter.setPen(g.mid());
1620 painter.drawPoint(bgR.x(), bgR.y()+1); 1625 painter.drawPoint(bgR.x(), bgR.y()+1);
1621 painter.drawPoint(bgR.x(), bgR.bottom()-1); 1626 painter.drawPoint(bgR.x(), bgR.bottom()-1);
1622 painter.drawPoint(bgR.right()-1, bgR.y()+1); 1627 painter.drawPoint(bgR.right()-1, bgR.y()+1);
1623 painter.drawPoint(bgR.right()-1, bgR.bottom()-1); 1628 painter.drawPoint(bgR.right()-1, bgR.bottom()-1);
1624 } 1629 }
1625 if(controls & Slider){ 1630 if(controls & Slider){
1626 if(sliderR.width() >= 16){ 1631 if(sliderR.width() >= 16){
1627 painter.drawPixmap(sliderR.x(), sliderR.y()+1, 1632 painter.drawPixmap(sliderR.x(), sliderR.y()+1,
1628 *getPixmap(HSBSliderTop)); 1633 *getPixmap(HSBSliderTop));
1629 painter.drawTiledPixmap(sliderR.x()+8, sliderR.y()+1, sliderR.width()-16, 1634 painter.drawTiledPixmap(sliderR.x()+8, sliderR.y()+1, sliderR.width()-16,
1630 13, *getPixmap(HSBSliderMid)); 1635 13, *getPixmap(HSBSliderMid));
1631 painter.drawPixmap(sliderR.right()-8, sliderR.y()+1, 1636 painter.drawPixmap(sliderR.right()-8, sliderR.y()+1,
1632 *getPixmap(HSBSliderBtm)); 1637 *getPixmap(HSBSliderBtm));
1633 } 1638 }
1634 else if(sliderR.width() >= 8){ 1639 else if(sliderR.width() >= 8){
1635 int m = sliderR.width()/2; 1640 int m = sliderR.width()/2;
1636 painter.drawPixmap(sliderR.x(), sliderR.y()+1, 1641 painter.drawPixmap(sliderR.x(), sliderR.y()+1,
1637 *getPixmap(HSBSliderTop), 0, 0, m, 13); 1642 *getPixmap(HSBSliderTop), 0, 0, m, 13);
1638 painter.drawPixmap(sliderR.right()-8, sliderR.y()+1, 1643 painter.drawPixmap(sliderR.right()-8, sliderR.y()+1,
1639 *getPixmap(HSBSliderBtm), 8-m, 0, m, 13); 1644 *getPixmap(HSBSliderBtm), 8-m, 0, m, 13);
1640 } 1645 }
1641 else{ 1646 else{
1642 painter.setPen(g.button().dark(210)); 1647 painter.setPen(g.button().dark(210));
1643 drawRoundRect(&painter, sliderR.x(), sliderR.y()+1, 1648 drawRoundRect(&painter, sliderR.x(), sliderR.y()+1,
1644 sliderR.width(), 13); 1649 sliderR.width(), 13);
1645 painter.drawTiledPixmap(sliderR.x()+1, sliderR.y()+2, 1650 painter.drawTiledPixmap(sliderR.x()+1, sliderR.y()+2,
1646 sliderR.width()-2, 11, 1651 sliderR.width()-2, 11,
1647 *getPixmap(HSBSliderMid), 0, 1); 1652 *getPixmap(HSBSliderMid), 0, 1);
1648 } 1653 }
1649 } 1654 }
1650 painter.setPen(g.mid()); 1655 painter.setPen(g.mid());
1651 painter.drawLine(bgR.x(), bgR.y(), bgR.right(), bgR.y()); 1656 painter.drawLine(bgR.x(), bgR.y(), bgR.right(), bgR.y());
1652 painter.drawLine(bgR.x(), bgR.bottom(), bgR.right(), bgR.bottom()); 1657 painter.drawLine(bgR.x(), bgR.bottom(), bgR.right(), bgR.bottom());
1653 if(brokenApp && (controls & Slider)){ 1658 if(brokenApp && (controls & Slider)){
1654 painter.setPen(g.background()); 1659 painter.setPen(g.background());
1655 painter.drawLine(bgR.x(), bgR.bottom()-1, bgR.right(), 1660 painter.drawLine(bgR.x(), bgR.bottom()-1, bgR.right(),
1656 bgR.bottom()-1); 1661 bgR.bottom()-1);
1657 } 1662 }
1658 painter.end(); 1663 painter.end();
1659 } 1664 }
1660 1665
1661 if ( controls & AddLine ) { 1666 if ( controls & AddLine ) {
1662 drawSBButton(p, addB, g, activeControl == AddLine); 1667 drawSBButton(p, addB, g, activeControl == AddLine);
1663 drawArrow( p, horiz ? RightArrow : DownArrow, 1668 drawArrow( p, horiz ? RightArrow : DownArrow,
1664 false, addB.x()+4, addB.y()+4, 1669 false, addB.x()+4, addB.y()+4,
1665 addB.width()-8, addB.height()-8, g, !maxed); 1670 addB.width()-8, addB.height()-8, g, !maxed);
1666 } 1671 }
1667 if ( controls & SubLine ) { 1672 if ( controls & SubLine ) {
1668 // drawSBButton(p, subB, g, activeControl == SubLine); 1673 // drawSBButton(p, subB, g, activeControl == SubLine);
1669 // drawArrow( p, horiz ? LeftArrow : UpArrow, 1674 // drawArrow( p, horiz ? LeftArrow : UpArrow,
1670 // false, subB.x()+4, subB.y()+4, 1675 // false, subB.x()+4, subB.y()+4,
1671 // subB.width()-8, subB.height()-8, g, !maxed); 1676 // subB.width()-8, subB.height()-8, g, !maxed);
1672 drawSBButton(p, subHC, g, activeControl == SubLine); 1677 drawSBButton(p, subHC, g, activeControl == SubLine);
1673 drawArrow( p, horiz ? LeftArrow : UpArrow, 1678 drawArrow( p, horiz ? LeftArrow : UpArrow,
1674 false, subHC.x()+4, subHC.y()+4, 1679 false, subHC.x()+4, subHC.y()+4,
1675 subHC.width()-8, subHC.height()-8, g, !maxed); 1680 subHC.width()-8, subHC.height()-8, g, !maxed);
1676 } 1681 }
1677 1682
1678 if(controls & AddPage){ 1683 if(controls & AddPage){
1679 if(addPageR.width()){ 1684 if(addPageR.width()){
1680 p->drawPixmap(addPageR.x(), addPageR.y(), sbBuffer, 1685 p->drawPixmap(addPageR.x(), addPageR.y(), sbBuffer,
1681 addPageR.x(), addPageR.y(), addPageR.width(), 1686 addPageR.x(), addPageR.y(), addPageR.width(),
1682 addPageR.height()); 1687 addPageR.height());
1683 } 1688 }
1684 } 1689 }
1685 if(controls & SubPage){ 1690 if(controls & SubPage){
1686 if(subPageR.height()){ 1691 if(subPageR.height()){
1687 p->drawPixmap(subPageR.x(), subPageR.y(), sbBuffer, 1692 p->drawPixmap(subPageR.x(), subPageR.y(), sbBuffer,
1688 subPageR.x(), subPageR.y(), subPageR.width(), 1693 subPageR.x(), subPageR.y(), subPageR.width(),
1689 subPageR.height()); 1694 subPageR.height());
1690 } 1695 }
1691 } 1696 }
1692 if ( controls & Slider ) { 1697 if ( controls & Slider ) {
1693 p->drawPixmap(sliderR.x(), sliderR.y(), sbBuffer, 1698 p->drawPixmap(sliderR.x(), sliderR.y(), sbBuffer,
1694 sliderR.x(), sliderR.y(), sliderR.width(), 1699 sliderR.x(), sliderR.y(), sliderR.width(),
1695 sliderR.height()); 1700 sliderR.height());
1696 } 1701 }
1697} 1702}
1698 1703
1699void LiquidStyle::drawSBButton(QPainter *p, const QRect &r, const QColorGroup &g, 1704void LiquidStyle::drawSBButton(QPainter *p, const QRect &r, const QColorGroup &g,
1700 bool down, bool /*fast*/) 1705 bool down, bool /*fast*/)
1701{ 1706{
1702 p->setPen(g.mid()); 1707 p->setPen(g.mid());
1703 p->drawRect(r); 1708 p->drawRect(r);
1704 QColor c(down ? g.button() : g.background()); 1709 QColor c(down ? g.button() : g.background());
1705 QPixmap *pix = bevelFillDict.find(c.rgb()); 1710 QPixmap *pix = bevelFillDict.find(c.rgb());
1706 if(!pix){ 1711 if(!pix){
1707 int h, s, v; 1712 int h, s, v;
1708 c.hsv(&h, &s, &v); 1713 c.hsv(&h, &s, &v);
1709 pix = new QPixmap(*bevelFillPix); 1714 pix = new QPixmap(*bevelFillPix);
1710 adjustHSV(*pix, h, s, v); 1715 adjustHSV(*pix, h, s, v);
1711 bevelFillDict.insert(c.rgb(), pix); 1716 bevelFillDict.insert(c.rgb(), pix);
1712 } 1717 }
1713 p->drawTiledPixmap(r.x()+1, r.y()+1, r.width()-2, r.height()-2, *pix); 1718 p->drawTiledPixmap(r.x()+1, r.y()+1, r.width()-2, r.height()-2, *pix);
1714 1719
1715} 1720}
1716 1721
1717void LiquidStyle::drawSBDeco(QPainter *p, const QRect &r, const QColorGroup &g, 1722void LiquidStyle::drawSBDeco(QPainter *p, const QRect &r, const QColorGroup &g,
1718 bool horiz) 1723 bool horiz)
1719{ 1724{
1720 if(horiz){ 1725 if(horiz){
1721 if(r.width() >= 15){ 1726 if(r.width() >= 15){
1722 int y = r.y()+3; 1727 int y = r.y()+3;
1723 int x = r.x() + (r.width()-7)/2; 1728 int x = r.x() + (r.width()-7)/2;
1724 int y2 = r.bottom()-3; 1729 int y2 = r.bottom()-3;
1725 p->setPen(g.light()); 1730 p->setPen(g.light());
1726 p->drawLine(x, y, x, y2); 1731 p->drawLine(x, y, x, y2);
1727 p->drawLine(x+3, y, x+3, y2); 1732 p->drawLine(x+3, y, x+3, y2);
1728 p->drawLine(x+6, y, x+6, y2); 1733 p->drawLine(x+6, y, x+6, y2);
1729 1734
1730 p->setPen(g.mid()); 1735 p->setPen(g.mid());
1731 p->drawLine(x+1, y, x+1, y2); 1736 p->drawLine(x+1, y, x+1, y2);
1732 p->drawLine(x+4, y, x+4, y2); 1737 p->drawLine(x+4, y, x+4, y2);
1733 p->drawLine(x+7, y, x+7, y2); 1738 p->drawLine(x+7, y, x+7, y2);
1734 } 1739 }
1735 } 1740 }
1736 else{ 1741 else{
1737 if(r.height() >= 15){ 1742 if(r.height() >= 15){
1738 int x = r.x()+3; 1743 int x = r.x()+3;
1739 int y = r.y() + (r.height()-7)/2; 1744 int y = r.y() + (r.height()-7)/2;
1740 int x2 = r.right()-3; 1745 int x2 = r.right()-3;
1741 p->setPen(g.light()); 1746 p->setPen(g.light());
1742 p->drawLine(x, y, x2, y); 1747 p->drawLine(x, y, x2, y);
1743 p->drawLine(x, y+3, x2, y+3); 1748 p->drawLine(x, y+3, x2, y+3);
1744 p->drawLine(x, y+6, x2, y+6); 1749 p->drawLine(x, y+6, x2, y+6);
1745 1750
1746 p->setPen(g.mid()); 1751 p->setPen(g.mid());
1747 p->drawLine(x, y+1, x2, y+1); 1752 p->drawLine(x, y+1, x2, y+1);
1748 p->drawLine(x, y+4, x2, y+4); 1753 p->drawLine(x, y+4, x2, y+4);
1749 p->drawLine(x, y+7, x2, y+7); 1754 p->drawLine(x, y+7, x2, y+7);
1750 } 1755 }
1751 } 1756 }
1752 1757
1753} 1758}
1754 1759
1755 1760
1756void LiquidStyle::scrollBarMetrics(const QScrollBar *sb, int &sliderMin, 1761void LiquidStyle::scrollBarMetrics(const QScrollBar *sb, int &sliderMin,
1757 int &sliderMax, int &sliderLength, 1762 int &sliderMax, int &sliderLength,
1758 int &buttonDim) 1763 int &buttonDim)
1759{ 1764{
1760 1765
1761 int maxLength; 1766 int maxLength;
1762 int b = 0; 1767 int b = 0;
1763 bool horiz = sb->orientation() == QScrollBar::Horizontal; 1768 bool horiz = sb->orientation() == QScrollBar::Horizontal;
1764 int length = horiz ? sb->width() : sb->height(); 1769 int length = horiz ? sb->width() : sb->height();
1765 int extent = horiz ? sb->height() : sb->width(); 1770 int extent = horiz ? sb->height() : sb->width();
1766 1771
1767 if ( length > ( extent - b*2 - 1 )*2 + b*2 ) 1772 if ( length > ( extent - b*2 - 1 )*2 + b*2 )
1768 buttonDim = extent - b*2; 1773 buttonDim = extent - b*2;
1769 else 1774 else
1770 buttonDim = ( length - b*2 )/2 - 1; 1775 buttonDim = ( length - b*2 )/2 - 1;
1771 1776
1772 sliderMin = b + 0; // buttonDim; 1777 sliderMin = b + 0; // buttonDim;
1773 maxLength = length - b*2 - buttonDim*2; // 3; 1778 maxLength = length - b*2 - buttonDim*2; // 3;
1774 1779
1775 if ( sb->maxValue() == sb->minValue() ) { 1780 if ( sb->maxValue() == sb->minValue() ) {
1776 sliderLength = maxLength; 1781 sliderLength = maxLength;
1777 } else { 1782 } else {
1778 sliderLength = (sb->pageStep()*maxLength)/ 1783 sliderLength = (sb->pageStep()*maxLength)/
1779 (sb->maxValue()-sb->minValue()+sb->pageStep()); 1784 (sb->maxValue()-sb->minValue()+sb->pageStep());
1780 uint range = sb->maxValue()-sb->minValue(); 1785 uint range = sb->maxValue()-sb->minValue();
1781 if ( sliderLength < 9 || range > INT_MAX/2 ) 1786 if ( sliderLength < 9 || range > INT_MAX/2 )
1782 sliderLength = 9; 1787 sliderLength = 9;
1783 if ( sliderLength > maxLength ) 1788 if ( sliderLength > maxLength )
1784 sliderLength = maxLength; 1789 sliderLength = maxLength;
1785 } 1790 }
1786 sliderMax = sliderMin + maxLength - sliderLength; 1791 sliderMax = sliderMin + maxLength - sliderLength;
1787 1792
1788} 1793}
1789 1794
1790QStyle::ScrollControl LiquidStyle::scrollBarPointOver(const QScrollBar *sb, 1795QStyle::ScrollControl LiquidStyle::scrollBarPointOver(const QScrollBar *sb,
1791 int sliderStart, 1796 int sliderStart,
1792 const QPoint &p) 1797 const QPoint &p)
1793{ 1798{
1794 if ( !sb->rect().contains( p ) ) 1799 if ( !sb->rect().contains( p ) )
1795 return NoScroll; 1800 return NoScroll;
1796 int sliderMin, sliderMax, sliderLength, buttonDim, pos; 1801 int sliderMin, sliderMax, sliderLength, buttonDim, pos;
1797 scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim ); 1802 scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim );
1798 pos = (sb->orientation() == QScrollBar::Horizontal)? p.x() : p.y(); 1803 pos = (sb->orientation() == QScrollBar::Horizontal)? p.x() : p.y();
1799 if ( pos < sliderMin ) 1804 if ( pos < sliderMin )
1800 return SubLine; 1805 return SubLine;
1801 if ( pos < sliderStart ) 1806 if ( pos < sliderStart )
1802 return SubPage; 1807 return SubPage;
1803 if ( pos < sliderStart + sliderLength ) 1808 if ( pos < sliderStart + sliderLength )
1804 return Slider; 1809 return Slider;
1805 if ( pos < sliderMax + sliderLength) 1810 if ( pos < sliderMax + sliderLength)
1806 return AddPage; 1811 return AddPage;
1807 if(pos > sliderMax + sliderLength + 16) 1812 if(pos > sliderMax + sliderLength + 16)
1808 return AddLine; 1813 return AddLine;
1809 1814
1810 return SubLine; 1815 return SubLine;
1811} 1816}
1812 1817
1813#define QCOORDARRLEN(x) sizeof(x)/(sizeof(QCOORD)*2) 1818#define QCOORDARRLEN(x) sizeof(x)/(sizeof(QCOORD)*2)
1814 1819
1815 1820
1816QSize LiquidStyle::exclusiveIndicatorSize() const 1821QSize LiquidStyle::exclusiveIndicatorSize() const
1817{ 1822{
1818 return(QSize(16, 16)); 1823 return(QSize(16, 16));
1819} 1824}
1820 1825
1821void LiquidStyle::drawExclusiveIndicator(QPainter *p, int x, int y, int /*w*/, 1826void LiquidStyle::drawExclusiveIndicator(QPainter *p, int x, int y, int /*w*/,
1822 int /*h*/, const QColorGroup &/*g*/, bool on, 1827 int /*h*/, const QColorGroup &/*g*/, bool on,
1823 bool down, bool) 1828 bool down, bool)
1824{ 1829{
1825 bool isActive = ( p->device()->devType() == QInternal::Widget ) && ( qApp-> focusWidget ( ) == p-> device ( )); 1830 bool isActive = ( p->device()->devType() == QInternal::Widget ) && ( qApp-> focusWidget ( ) == p-> device ( ));
1826 bool isMasked = p->device() && p->device()->devType() == QInternal::Widget 1831 bool isMasked = p->device() && p->device()->devType() == QInternal::Widget
1827 && ((QWidget*)p->device())->autoMask(); 1832 && ((QWidget*)p->device())->autoMask();
1828 1833
1829 if(isMasked){ 1834 if(isMasked){
1830 if(on || down){ 1835 if(on || down){
1831 p->drawPixmap(x, y, isActive ? *getPixmap(HTMLRadioDownHover) : 1836 p->drawPixmap(x, y, isActive ? *getPixmap(HTMLRadioDownHover) :
1832 *getPixmap(HTMLRadioDown)); 1837 *getPixmap(HTMLRadioDown));
1833 } 1838 }
1834 else 1839 else
1835 p->drawPixmap(x, y, isActive ? *getPixmap(HTMLRadioHover) : 1840 p->drawPixmap(x, y, isActive ? *getPixmap(HTMLRadioHover) :
1836 *getPixmap(HTMLRadio)); 1841 *getPixmap(HTMLRadio));
1837 1842
1838 } 1843 }
1839 else{ 1844 else{
1840 if(on || down){ 1845 if(on || down){
1841 p->drawPixmap(x, y, isActive ? *getPixmap(RadioOnHover) : 1846 p->drawPixmap(x, y, isActive ? *getPixmap(RadioOnHover) :
1842 *getPixmap(RadioOn)); 1847 *getPixmap(RadioOn));
1843 } 1848 }
1844 else 1849 else
1845 p->drawPixmap(x, y, isActive ? *getPixmap(RadioOffHover) : 1850 p->drawPixmap(x, y, isActive ? *getPixmap(RadioOffHover) :
1846 *getPixmap(RadioOff)); 1851 *getPixmap(RadioOff));
1847 } 1852 }
1848} 1853}
1849 1854
1850void LiquidStyle::drawExclusiveIndicatorMask(QPainter *p, int x, int y, int w, 1855void LiquidStyle::drawExclusiveIndicatorMask(QPainter *p, int x, int y, int w,
1851 int h, bool) 1856 int h, bool)
1852{ 1857{
1853 p->fillRect(x, y, w, h, Qt::color0); 1858 p->fillRect(x, y, w, h, Qt::color0);
1854 p->setPen(Qt::color1); 1859 p->setPen(Qt::color1);
1855 p->drawPixmap(x, y, *getPixmap(RadioOn)->mask()); 1860 p->drawPixmap(x, y, *getPixmap(RadioOn)->mask());
1856} 1861}
1857 1862
1858 1863
1859QSize LiquidStyle::indicatorSize() const 1864QSize LiquidStyle::indicatorSize() const
1860{ 1865{
1861 return(QSize(20, 22)); 1866 return(QSize(20, 22));
1862} 1867}
1863 1868
1864void LiquidStyle::drawIndicator(QPainter *p, int x, int y, int /*w*/, int /*h*/, 1869void LiquidStyle::drawIndicator(QPainter *p, int x, int y, int /*w*/, int /*h*/,
1865 const QColorGroup &/*g*/, int state, bool /*down*/, bool) 1870 const QColorGroup &/*g*/, int state, bool /*down*/, bool)
1866{ 1871{
1867 bool isActive = ( p->device()->devType() == QInternal::Widget ) && ( qApp-> focusWidget ( ) == p-> device ( )); 1872 bool isActive = ( p->device()->devType() == QInternal::Widget ) && ( qApp-> focusWidget ( ) == p-> device ( ));
1868 bool isMasked = p->device() && p->device()->devType() == QInternal::Widget 1873 bool isMasked = p->device() && p->device()->devType() == QInternal::Widget
1869 && ((QWidget*)p->device())->autoMask(); 1874 && ((QWidget*)p->device())->autoMask();
1870 if(isMasked){ 1875 if(isMasked){
1871 if(state != QButton::Off){ 1876 if(state != QButton::Off){
1872 p->drawPixmap(x, y, isActive ? *getPixmap(HTMLCBDownHover) : 1877 p->drawPixmap(x, y, isActive ? *getPixmap(HTMLCBDownHover) :
1873 *getPixmap(HTMLCBDown)); 1878 *getPixmap(HTMLCBDown));
1874 } 1879 }
1875 else 1880 else
1876 p->drawPixmap(x, y, isActive ? *getPixmap(HTMLCBHover) : 1881 p->drawPixmap(x, y, isActive ? *getPixmap(HTMLCBHover) :
1877 *getPixmap(HTMLCB)); 1882 *getPixmap(HTMLCB));
1878 1883
1879 } 1884 }
1880 else{ 1885 else{
1881 if(state != QButton::Off){ 1886 if(state != QButton::Off){
1882 p->drawPixmap(x, y, isActive ? *getPixmap(CBDownHover) : 1887 p->drawPixmap(x, y, isActive ? *getPixmap(CBDownHover) :
1883 *getPixmap(CBDown)); 1888 *getPixmap(CBDown));
1884 /* Todo - tristate 1889 /* Todo - tristate
1885 if(state == QButton::On){ 1890 if(state == QButton::On){
1886 p->setPen(Qt::black); 1891 p->setPen(Qt::black);
1887 p->drawPixmap(3, 3, xBmp); 1892 p->drawPixmap(3, 3, xBmp);
1888 } 1893 }
1889 else{ 1894 else{
1890 p->setPen(g.dark()); 1895 p->setPen(g.dark());
1891 p->drawRect(x+2, y+2, w-4, h-4); 1896 p->drawRect(x+2, y+2, w-4, h-4);
1892 p->setPen(Qt::black); 1897 p->setPen(Qt::black);
1893 p->drawLine(x+3, (y+h)/2-2, x+w-4, (y+h)/2-2); 1898 p->drawLine(x+3, (y+h)/2-2, x+w-4, (y+h)/2-2);
1894 p->drawLine(x+3, (y+h)/2, x+w-4, (y+h)/2); 1899 p->drawLine(x+3, (y+h)/2, x+w-4, (y+h)/2);
1895 p->drawLine(x+3, (y+h)/2+2, x+w-4, (y+h)/2+2); 1900 p->drawLine(x+3, (y+h)/2+2, x+w-4, (y+h)/2+2);
1896 }*/ 1901 }*/
1897 } 1902 }
1898 else 1903 else
1899 p->drawPixmap(x, y, isActive ? *getPixmap(CBHover) : *getPixmap(CB)); 1904 p->drawPixmap(x, y, isActive ? *getPixmap(CBHover) : *getPixmap(CB));
1900 } 1905 }
1901} 1906}
1902 1907
1903void LiquidStyle::drawIndicatorMask(QPainter *p, int x, int y, int /*w*/, int /*h*/, 1908void LiquidStyle::drawIndicatorMask(QPainter *p, int x, int y, int /*w*/, int /*h*/,
1904 int /*state*/) 1909 int /*state*/)
1905{ 1910{
1906 // needed for some reason by KHtml, even tho it's all filled ;P 1911 // needed for some reason by KHtml, even tho it's all filled ;P
1907 p->drawPixmap(x, y, *getPixmap(HTMLCB)->mask()); 1912 p->drawPixmap(x, y, *getPixmap(HTMLCB)->mask());
1908 1913
1909} 1914}
1910 1915
1911void LiquidStyle::drawSlider(QPainter *p, int x, int y, int w, int h, 1916void LiquidStyle::drawSlider(QPainter *p, int x, int y, int w, int h,
1912 const QColorGroup &/*g*/, Orientation orient, 1917 const QColorGroup &/*g*/, Orientation orient,
1913 bool, bool) 1918 bool, bool)
1914{ 1919{
1915 QWidget *parent = (QWidget *)p->device(); 1920 QWidget *parent = (QWidget *)p->device();
1916 p->setBrushOrigin(parent->pos()); 1921 p->setBrushOrigin(parent->pos());
1917 parent->erase(x, y, w, h); 1922 parent->erase(x, y, w, h);
1918 p->drawPixmap(x, y, orient == Qt::Horizontal ? *getPixmap(HSlider) : 1923 p->drawPixmap(x, y, orient == Qt::Horizontal ? *getPixmap(HSlider) :
1919 *getPixmap(VSlider)); 1924 *getPixmap(VSlider));
1920} 1925}
1921 1926
1922void LiquidStyle::drawSliderMask(QPainter *p, int x, int y, int /*w*/, int /*h*/, 1927void LiquidStyle::drawSliderMask(QPainter *p, int x, int y, int /*w*/, int /*h*/,
1923 Orientation orient, bool, bool) 1928 Orientation orient, bool, bool)
1924{ 1929{
1925 p->drawPixmap(x, y, orient == Qt::Horizontal ? *getPixmap(HSlider)->mask() : 1930 p->drawPixmap(x, y, orient == Qt::Horizontal ? *getPixmap(HSlider)->mask() :
1926 *getPixmap(VSlider)->mask()); 1931 *getPixmap(VSlider)->mask());
1927} 1932}
1928 1933
1929int LiquidStyle::sliderLength() const 1934int LiquidStyle::sliderLength() const
1930{ 1935{
1931 return(10); 1936 return(10);
1932} 1937}
1933 1938
1934#define QCOORDARRLEN(x) sizeof(x)/(sizeof(QCOORD)*2) 1939#define QCOORDARRLEN(x) sizeof(x)/(sizeof(QCOORD)*2)
1935 1940
1936void LiquidStyle::drawArrow(QPainter *p, Qt::ArrowType type, bool on, int x, 1941void LiquidStyle::drawArrow(QPainter *p, Qt::ArrowType type, bool on, int x,
1937 int y, int w, int h, const QColorGroup &g, 1942 int y, int w, int h, const QColorGroup &g,
1938 bool enabled, const QBrush *) 1943 bool enabled, const QBrush *)
1939{ 1944{
1940 static const QCOORD u_arrow[]={3,1, 4,1, 2,2, 5,2, 1,3, 6,3, 0,4, 7,4, 0,5, 7,5}; 1945 static const QCOORD u_arrow[]={3,1, 4,1, 2,2, 5,2, 1,3, 6,3, 0,4, 7,4, 0,5, 7,5};
1941 static const QCOORD d_arrow[]={0,2, 7,2, 0,3, 7,3, 1,4, 6,4, 2,5, 5,5, 3,6, 4,6}; 1946 static const QCOORD d_arrow[]={0,2, 7,2, 0,3, 7,3, 1,4, 6,4, 2,5, 5,5, 3,6, 4,6};
1942 static const QCOORD l_arrow[]={1,3, 1,4, 2,2, 2,5, 3,1, 3,6, 4,0, 4,7, 5,0, 5,7}; 1947 static const QCOORD l_arrow[]={1,3, 1,4, 2,2, 2,5, 3,1, 3,6, 4,0, 4,7, 5,0, 5,7};
1943 static const QCOORD r_arrow[]={2,0, 2,7, 3,0, 3,7, 4,1, 4,6, 5,2, 5,5, 6,3, 6,4}; 1948 static const QCOORD r_arrow[]={2,0, 2,7, 3,0, 3,7, 4,1, 4,6, 5,2, 5,5, 6,3, 6,4};
1944 1949
1945 p->setPen(enabled ? on ? g.light() : g.buttonText() : g.mid()); 1950 p->setPen(enabled ? on ? g.light() : g.buttonText() : g.mid());
1946 if(w > 8){ 1951 if(w > 8){
1947 x = x + (w-8)/2; 1952 x = x + (w-8)/2;
1948 y = y + (h-8)/2; 1953 y = y + (h-8)/2;
1949 } 1954 }
1950 1955
1951 QPointArray a; 1956 QPointArray a;
1952 switch(type){ 1957 switch(type){
1953 case Qt::UpArrow: 1958 case Qt::UpArrow:
1954 a.setPoints(QCOORDARRLEN(u_arrow), u_arrow); 1959 a.setPoints(QCOORDARRLEN(u_arrow), u_arrow);
1955 break; 1960 break;
1956 case Qt::DownArrow: 1961 case Qt::DownArrow:
1957 a.setPoints(QCOORDARRLEN(d_arrow), d_arrow); 1962 a.setPoints(QCOORDARRLEN(d_arrow), d_arrow);
1958 break; 1963 break;
1959 case Qt::LeftArrow: 1964 case Qt::LeftArrow:
1960 a.setPoints(QCOORDARRLEN(l_arrow), l_arrow); 1965 a.setPoints(QCOORDARRLEN(l_arrow), l_arrow);
1961 break; 1966 break;
1962 default: 1967 default:
1963 a.setPoints(QCOORDARRLEN(r_arrow), r_arrow); 1968 a.setPoints(QCOORDARRLEN(r_arrow), r_arrow);
1964 break; 1969 break;
1965 } 1970 }
1966 1971
1967 a.translate(x, y); 1972 a.translate(x, y);
1968 p->drawLineSegments(a); 1973 p->drawLineSegments(a);
1969} 1974}
1970 1975
1971 1976
1972void LiquidStyle::drawMenuBarItem(QPainter *p, int x, int y, int w, int h, 1977void LiquidStyle::drawMenuBarItem(QPainter *p, int x, int y, int w, int h,
1973 QMenuItem *mi, QColorGroup &g, bool /*enabled*/, bool active ) 1978 QMenuItem *mi, QColorGroup &g, bool /*enabled*/, bool active )
1974 { 1979 {
1975 if(active){ 1980 if(active){
1976 x -= 2; // Bug in Qt/E 1981 x -= 2; // Bug in Qt/E
1977 y -= 2; 1982 y -= 2;
1978 w += 2; 1983 w += 2;
1979 h += 2; 1984 h += 2;
1980 } 1985 }
1981 1986
1982 QWidget *parent = (QWidget *)p->device(); 1987 QWidget *parent = (QWidget *)p->device();
1983 p->setBrushOrigin(parent->pos()); 1988 p->setBrushOrigin(parent->pos());
1984 parent->erase(x, y, w, h); 1989 parent->erase(x, y, w, h);
1985 1990
1986 if(menuHandler->useShadowText()){ 1991 if(menuHandler->useShadowText()){
1987 QColor shadow; 1992 QColor shadow;
1988 if(p->device() && p->device()->devType() == QInternal::Widget && 1993 if(p->device() && p->device()->devType() == QInternal::Widget &&
1989 ((QWidget *)p->device())->inherits("QMenuBar")){ 1994 ((QWidget *)p->device())->inherits("QMenuBar")){
1990 shadow = ((QMenuBar*)p->device())->isTopLevel() ? g.button().dark(130) : 1995 shadow = ((QMenuBar*)p->device())->isTopLevel() ? g.button().dark(130) :
1991 g.background().dark(130); 1996 g.background().dark(130);
1992 } 1997 }
1993 else 1998 else
1994 shadow = g.background().dark(130); 1999 shadow = g.background().dark(130);
1995 2000
1996 QPixmap *dummy = 0; 2001 QPixmap *dummy = 0;
1997 2002
1998 if ( mi-> pixmap ( ) && !mi-> pixmap ( )-> isNull ( )) { 2003 if ( mi-> pixmap ( ) && !mi-> pixmap ( )-> isNull ( )) {
1999 dummy = new QPixmap ( mi-> pixmap ( )-> size ( )); 2004 dummy = new QPixmap ( mi-> pixmap ( )-> size ( ));
2000 QBitmap dummy_mask ( dummy-> size ( )); 2005 QBitmap dummy_mask ( dummy-> size ( ));
2001 dummy_mask. fill ( color1 ); 2006 dummy_mask. fill ( color1 );
2002 dummy-> setMask ( dummy_mask ); 2007 dummy-> setMask ( dummy_mask );
2003 } 2008 }
2004 2009
2005 if(active){ 2010 if(active){
2006 drawClearBevel(p, x+1, y+1, w-1, h-1, g.button(), g.background()); 2011 drawClearBevel(p, x+1, y+1, w-1, h-1, g.button(), g.background());
2007 QApplication::style().drawItem(p, x+1, y+1, w, h, 2012 QApplication::style().drawItem(p, x+1, y+1, w, h,
2008 AlignCenter|ShowPrefix|DontClip|SingleLine, 2013 AlignCenter|ShowPrefix|DontClip|SingleLine,
2009 g, mi->isEnabled(), dummy, mi->text(), 2014 g, mi->isEnabled(), dummy, mi->text(),
2010 -1, &shadow); 2015 -1, &shadow);
2011 QApplication::style().drawItem(p, x, y, w, h, 2016 QApplication::style().drawItem(p, x, y, w, h,
2012 AlignCenter|ShowPrefix|DontClip|SingleLine, 2017 AlignCenter|ShowPrefix|DontClip|SingleLine,
2013 g, mi->isEnabled(), mi-> pixmap ( ), mi->text(), 2018 g, mi->isEnabled(), mi-> pixmap ( ), mi->text(),
2014 -1, &g.text()); 2019 -1, &g.text());
2015 } 2020 }
2016 else{ 2021 else{
2017 QApplication::style().drawItem(p, x+1, y+1, w, h, 2022 QApplication::style().drawItem(p, x+1, y+1, w, h,
2018 AlignCenter|ShowPrefix|DontClip|SingleLine, 2023 AlignCenter|ShowPrefix|DontClip|SingleLine,
2019 g, mi->isEnabled(), dummy, mi->text(), 2024 g, mi->isEnabled(), dummy, mi->text(),
2020 -1, &shadow); 2025 -1, &shadow);
2021 QApplication::style().drawItem(p, x, y, w, h, 2026 QApplication::style().drawItem(p, x, y, w, h,
2022 AlignCenter|ShowPrefix|DontClip|SingleLine, 2027 AlignCenter|ShowPrefix|DontClip|SingleLine,
2023 g, mi->isEnabled(), mi-> pixmap ( ), mi->text(), 2028 g, mi->isEnabled(), mi-> pixmap ( ), mi->text(),
2024 -1, &g.text()); 2029 -1, &g.text());
2025 } 2030 }
2026 delete dummy; 2031 delete dummy;
2027 } 2032 }
2028 else{ 2033 else{
2029 if(active) 2034 if(active)
2030 drawClearBevel(p, x+1, y+1, w-1, h-1, g.button(), g.background()); 2035 drawClearBevel(p, x+1, y+1, w-1, h-1, g.button(), g.background());
2031 QApplication::style().drawItem(p, x, y, w, h, 2036 QApplication::style().drawItem(p, x, y, w, h,
2032 AlignCenter|ShowPrefix|DontClip|SingleLine, 2037 AlignCenter|ShowPrefix|DontClip|SingleLine,
2033 g, mi->isEnabled(), mi-> pixmap ( ), mi->text(), 2038 g, mi->isEnabled(), mi-> pixmap ( ), mi->text(),
2034 -1, &g.text()); 2039 -1, &g.text());
2035 } 2040 }
2036} 2041}
2037 2042
2038void LiquidStyle::drawPopupPanel(QPainter *p, int x, int y, int w, int h, 2043void LiquidStyle::drawPopupPanel(QPainter *p, int x, int y, int w, int h,
2039 const QColorGroup &g, int /*lineWidth*/, 2044 const QColorGroup &g, int /*lineWidth*/,
2040 const QBrush * /*fill*/) 2045 const QBrush * /*fill*/)
2041{ 2046{
2042 QColor c; 2047 QColor c;
2043 switch(menuHandler->transType()){ 2048 switch(menuHandler->transType()){
2044 case None: 2049 case None:
2045 case StippledBg: 2050 case StippledBg:
2046 case TransStippleBg: 2051 case TransStippleBg:
2047 c = g.background(); 2052 c = g.background();
2048 break; 2053 break;
2049 case StippledBtn: 2054 case StippledBtn:
2050 case TransStippleBtn: 2055 case TransStippleBtn:
2051 c = g.button(); 2056 c = g.button();
2052 break; 2057 break;
2053 default: 2058 default:
2054 c = menuHandler->bgColor(); 2059 c = menuHandler->bgColor();
2055 } 2060 }
2056 p->setPen(c.dark(140)); 2061 p->setPen(c.dark(140));
2057 p->drawRect(x, y, w, h); 2062 p->drawRect(x, y, w, h);
2058 p->setPen(c.light(120)); 2063 p->setPen(c.light(120));
2059 p->drawRect(x+1, y+1, w-2, h-2); 2064 p->drawRect(x+1, y+1, w-2, h-2);
2060} 2065}
2061 2066
2062void LiquidStyle::drawPopupMenuItem( QPainter* p, bool checkable, int maxpmw, 2067void LiquidStyle::drawPopupMenuItem( QPainter* p, bool checkable, int maxpmw,
2063 int tab, QMenuItem* mi, 2068 int tab, QMenuItem* mi,
2064 const QPalette& pal, bool act, 2069 const QPalette& pal, bool act,
2065 bool enabled, int x, int y, int w, int h) 2070 bool enabled, int x, int y, int w, int h)
2066{ 2071{
2067static const int motifItemFrame = 2; 2072static const int motifItemFrame = 2;
2068static const int motifItemHMargin = 3; 2073static const int motifItemHMargin = 3;
2069static const int motifItemVMargin = 2; 2074static const int motifItemVMargin = 2;
2070static const int motifArrowHMargin = 6; 2075static const int motifArrowHMargin = 6;
2071static const int windowsRightBorder = 12; 2076static const int windowsRightBorder = 12;
2072 2077
2073 maxpmw = QMAX( maxpmw, 20 ); 2078 maxpmw = QMAX( maxpmw, 20 );
2074 2079
2075 2080
2076 bool dis = !enabled; 2081 bool dis = !enabled;
2077 QColorGroup itemg = dis ? pal.disabled() : pal.active(); 2082 QColorGroup itemg = dis ? pal.disabled() : pal.active();
2078 2083
2079 int checkcol = maxpmw; 2084 int checkcol = maxpmw;
2080 if(act){ 2085 if(act){
2081 2086
2082 // FIXME 2087 // FIXME
2083 drawClearBevel(p, x, y, w, h, itemg.button(), itemg.background()); 2088 drawClearBevel(p, x, y, w, h, itemg.button(), itemg.background());
2084 } 2089 }
2085 //else if(((QWidget*)p->device())->backgroundPixmap()){ 2090 //else if(((QWidget*)p->device())->backgroundPixmap()){
2086 // p->drawPixmap(x, y, *((QWidget*)p->device())->backgroundPixmap(), 2091 // p->drawPixmap(x, y, *((QWidget*)p->device())->backgroundPixmap(),
2087 // x, y, w, h); 2092 // x, y, w, h);
2088 //} 2093 //}
2089 else{ 2094 else{
2090 if(menuHandler->transType() == None){ 2095 if(menuHandler->transType() == None){
2091 p->fillRect(x, y, w, h, pal.active().background()); 2096 p->fillRect(x, y, w, h, pal.active().background());
2092 } 2097 }
2093 else if(menuHandler->transType() == StippledBg){ 2098 else if(menuHandler->transType() == StippledBg){
2094 p->fillRect(x, y, w, h, bgBrush); 2099 p->fillRect(x, y, w, h, bgBrush);
2095 } 2100 }
2096 else if(menuHandler->transType() == StippledBtn){ 2101 else if(menuHandler->transType() == StippledBtn){
2097 p->fillRect(x, y, w, h, menuBrush); 2102 p->fillRect(x, y, w, h, menuBrush);
2098 } 2103 }
2099 else{ 2104 else{
2100 QPixmap *pix = menuHandler->pixmap(((QWidget*)p->device())->winId()); 2105 QPixmap *pix = menuHandler->pixmap(((QWidget*)p->device())->winId());
2101 if(pix) 2106 if(pix)
2102 p->drawPixmap(x, y, *pix, x, y, w, h); 2107 p->drawPixmap(x, y, *pix, x, y, w, h);
2103 } 2108 }
2104 } 2109 }
2105 2110
2106 if(!mi) 2111 if(!mi)
2107 return; 2112 return;
2108 2113
2109 QColor discol; 2114 QColor discol;
2110 if (dis) { 2115 if (dis) {
2111 discol = itemg.mid(); 2116 discol = itemg.mid();
2112 p->setPen(discol); 2117 p->setPen(discol);
2113 } 2118 }
2114 2119
2115 QColorGroup cg2(itemg); 2120 QColorGroup cg2(itemg);
2116 2121
2117 if(menuHandler->transType() == Custom){ 2122 if(menuHandler->transType() == Custom){
2118 cg2.setColor(QColorGroup::Foreground, menuHandler->textColor()); 2123 cg2.setColor(QColorGroup::Foreground, menuHandler->textColor());
2119 cg2.setColor(QColorGroup::Text, menuHandler->textColor()); 2124 cg2.setColor(QColorGroup::Text, menuHandler->textColor());
2120 cg2.setColor(QColorGroup::Light, menuHandler->textColor().light(120)); 2125 cg2.setColor(QColorGroup::Light, menuHandler->textColor().light(120));
2121 cg2.setColor(QColorGroup::Mid, menuHandler->textColor().dark(120)); 2126 cg2.setColor(QColorGroup::Mid, menuHandler->textColor().dark(120));
2122 } 2127 }
2123 else{ 2128 else{
2124 cg2 = QColorGroup(discol, itemg.highlight(), black, black, 2129 cg2 = QColorGroup(discol, itemg.highlight(), black, black,
2125 dis ? discol : black, discol, black); 2130 dis ? discol : black, discol, black);
2126 } 2131 }
2127 2132
2128 if(mi->isSeparator()){ 2133 if(mi->isSeparator()){
2129 QColor c; 2134 QColor c;
2130 switch(menuHandler->transType()){ 2135 switch(menuHandler->transType()){
2131 case None: 2136 case None:
2132 case StippledBg: 2137 case StippledBg:
2133 case TransStippleBg: 2138 case TransStippleBg:
2134 c = QApplication::palette().active().background(); 2139 c = QApplication::palette().active().background();
2135 break; 2140 break;
2136 case StippledBtn: 2141 case StippledBtn:
2137 case TransStippleBtn: 2142 case TransStippleBtn:
2138 c = QApplication::palette().active().button(); 2143 c = QApplication::palette().active().button();
2139 break; 2144 break;
2140 default: 2145 default:
2141 c = menuHandler->bgColor(); 2146 c = menuHandler->bgColor();
2142 } 2147 }
2143 p->setPen(c.dark(140)); 2148 p->setPen(c.dark(140));
2144 p->drawLine(x, y, x+w, y ); 2149 p->drawLine(x, y, x+w, y );
2145 p->setPen(c.light(115)); 2150 p->setPen(c.light(115));
2146 p->drawLine(x, y+1, x+w, y+1 ); 2151 p->drawLine(x, y+1, x+w, y+1 );
2147 return; 2152 return;
2148 } 2153 }
2149 if(mi->iconSet()) { 2154 if(mi->iconSet()) {
2150 QIconSet::Mode mode = dis? QIconSet::Disabled : QIconSet::Normal; 2155 QIconSet::Mode mode = dis? QIconSet::Disabled : QIconSet::Normal;
2151 if (!dis) 2156 if (!dis)
2152 mode = QIconSet::Active; 2157 mode = QIconSet::Active;
2153 QPixmap pixmap = mi->iconSet()->pixmap(QIconSet::Small, mode); 2158 QPixmap pixmap = mi->iconSet()->pixmap(QIconSet::Small, mode);
2154 int pixw = pixmap.width(); 2159 int pixw = pixmap.width();
2155 int pixh = pixmap.height(); 2160 int pixh = pixmap.height();
2156 QRect cr(x, y, checkcol, h); 2161 QRect cr(x, y, checkcol, h);
2157 QRect pmr(0, 0, pixw, pixh); 2162 QRect pmr(0, 0, pixw, pixh);
2158 pmr.moveCenter( cr.center() ); 2163 pmr.moveCenter( cr.center() );
2159 p->setPen(itemg.highlightedText()); 2164 p->setPen(itemg.highlightedText());
2160 p->drawPixmap(pmr.topLeft(), pixmap ); 2165 p->drawPixmap(pmr.topLeft(), pixmap );
2161 2166
2162 } 2167 }
2163 else if(checkable) { 2168 else if(checkable) {
2164 int mw = checkcol + motifItemFrame; 2169 int mw = checkcol + motifItemFrame;
2165 int mh = h - 2*motifItemFrame; 2170 int mh = h - 2*motifItemFrame;
2166 if (mi->isChecked()){ 2171 if (mi->isChecked()){
2167 drawCheckMark( p, x + motifItemFrame, 2172 drawCheckMark( p, x + motifItemFrame,
2168 y+motifItemFrame, mw, mh, cg2, act, dis ); 2173 y+motifItemFrame, mw, mh, cg2, act, dis );
2169 } 2174 }
2170 } 2175 }
2171 if(menuHandler->transType() == Custom) 2176 if(menuHandler->transType() == Custom)
2172 p->setPen(menuHandler->textColor()); 2177 p->setPen(menuHandler->textColor());
2173 else 2178 else
2174 p->setPen(itemg.text()); 2179 p->setPen(itemg.text());
2175 2180
2176 2181
2177 int xm = motifItemFrame + checkcol + motifItemHMargin; 2182 int xm = motifItemFrame + checkcol + motifItemHMargin;
2178 QString s = mi->text(); 2183 QString s = mi->text();
2179 if (!s.isNull()) { 2184 if (!s.isNull()) {
2180 int t = s.find( '\t' ); 2185 int t = s.find( '\t' );
2181 int m = motifItemVMargin; 2186 int m = motifItemVMargin;
2182 const int text_flags = AlignVCenter|ShowPrefix | DontClip | SingleLine; 2187 const int text_flags = AlignVCenter|ShowPrefix | DontClip | SingleLine;
2183 QPen oldPen = p->pen(); 2188 QPen oldPen = p->pen();
2184 if(menuHandler->useShadowText()){ 2189 if(menuHandler->useShadowText()){
2185 if(menuHandler->transType() == Custom) 2190 if(menuHandler->transType() == Custom)
2186 p->setPen(menuHandler->bgColor().dark(130)); 2191 p->setPen(menuHandler->bgColor().dark(130));
2187 else if(menuHandler->transType() == StippledBtn || 2192 else if(menuHandler->transType() == StippledBtn ||
2188 menuHandler->transType() == TransStippleBtn) 2193 menuHandler->transType() == TransStippleBtn)
2189 p->setPen(itemg.button().dark(130)); 2194 p->setPen(itemg.button().dark(130));
2190 else 2195 else
2191 p->setPen(bgBrush.color().dark(130)); 2196 p->setPen(bgBrush.color().dark(130));
2192 2197
2193 if (t >= 0) { 2198 if (t >= 0) {
2194 p->drawText(x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame+2, 2199 p->drawText(x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame+2,
2195 y+m+2, tab-1, h-2*m-1, text_flags, s.mid( t+1 )); 2200 y+m+2, tab-1, h-2*m-1, text_flags, s.mid( t+1 ));
2196 } 2201 }
2197 p->drawText(x+xm+1, y+m+1, w-xm-tab, h-2*m-1, text_flags, s, t); 2202 p->drawText(x+xm+1, y+m+1, w-xm-tab, h-2*m-1, text_flags, s, t);
2198 } 2203 }
2199 p->setPen(oldPen); 2204 p->setPen(oldPen);
2200 if (t >= 0) { 2205 if (t >= 0) {
2201 p->drawText(x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame+1, 2206 p->drawText(x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame+1,
2202 y+m+1, tab, h-2*m, text_flags, s.mid( t+1 )); 2207 y+m+1, tab, h-2*m, text_flags, s.mid( t+1 ));
2203 } 2208 }
2204 p->drawText(x+xm, y+m, w-xm-tab+1, h-2*m, text_flags, s, t); 2209 p->drawText(x+xm, y+m, w-xm-tab+1, h-2*m, text_flags, s, t);
2205 2210
2206 } 2211 }
2207 else if (mi->pixmap()) { 2212 else if (mi->pixmap()) {
2208 QPixmap *pixmap = mi->pixmap(); 2213 QPixmap *pixmap = mi->pixmap();
2209 if (pixmap->depth() == 1) 2214 if (pixmap->depth() == 1)
2210 p->setBackgroundMode(OpaqueMode); 2215 p->setBackgroundMode(OpaqueMode);
2211 p->drawPixmap( x+xm, y+motifItemFrame, *pixmap); 2216 p->drawPixmap( x+xm, y+motifItemFrame, *pixmap);
2212 if (pixmap->depth() == 1) 2217 if (pixmap->depth() == 1)
2213 p->setBackgroundMode(TransparentMode); 2218 p->setBackgroundMode(TransparentMode);
2214 } 2219 }
2215 if (mi->popup()) { 2220 if (mi->popup()) {
2216 int dim = (h-2*motifItemFrame) / 2; 2221 int dim = (h-2*motifItemFrame) / 2;
2217 drawArrow(p, RightArrow, true, 2222 drawArrow(p, RightArrow, true,
2218 x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2, 2223 x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2,
2219 dim, dim, cg2, TRUE); 2224 dim, dim, cg2, TRUE);
2220 } 2225 }
2221} 2226}
2222 2227
2223int LiquidStyle::popupMenuItemHeight(bool /*checkable*/, QMenuItem *mi, 2228int LiquidStyle::popupMenuItemHeight(bool /*checkable*/, QMenuItem *mi,
2224 const QFontMetrics &fm) 2229 const QFontMetrics &fm)
2225{ 2230{
2226 if (mi->isSeparator()) 2231 if (mi->isSeparator())
2227 return 2; 2232 return 2;
2228 2233
2229 int h = 0; 2234 int h = 0;
2230 if (mi->pixmap()) 2235 if (mi->pixmap())
2231 h = mi->pixmap()->height(); 2236 h = mi->pixmap()->height();
2232 2237
2233 if (mi->iconSet()) 2238 if (mi->iconSet())
2234 h = QMAX(mi->iconSet()-> 2239 h = QMAX(mi->iconSet()->
2235 pixmap(QIconSet::Small, QIconSet::Normal).height(), h); 2240 pixmap(QIconSet::Small, QIconSet::Normal).height(), h);
2236 2241
2237 h = QMAX(fm.height() + 4, h); 2242 h = QMAX(fm.height() + 4, h);
2238 2243
2239 // we want a minimum size of 18 2244 // we want a minimum size of 18
2240 h = QMAX(h, 18); 2245 h = QMAX(h, 18);
2241 2246
2242 return h; 2247 return h;
2243} 2248}
2244 2249
2245 2250
2246void LiquidStyle::drawFocusRect(QPainter *p, const QRect &r, 2251void LiquidStyle::drawFocusRect(QPainter *p, const QRect &r,
2247 const QColorGroup &g, const QColor *c, 2252 const QColorGroup &g, const QColor *c,
2248 bool atBorder) 2253 bool atBorder)
2249{ 2254{
2250 // are we painting a widget? 2255 // are we painting a widget?
2251 if(p->device()->devType() == QInternal::Widget){ 2256 if(p->device()->devType() == QInternal::Widget){
2252 // if so does it use a special focus rectangle? 2257 // if so does it use a special focus rectangle?
2253 QWidget *w = (QWidget *)p->device(); 2258 QWidget *w = (QWidget *)p->device();
2254 if(w->inherits("QPushButton") || w->inherits("QSlider") || w->inherits("QComboBox") || w->inherits("QToolButton" )){ 2259 if(w->inherits("QPushButton") || w->inherits("QSlider") || w->inherits("QComboBox") || w->inherits("QToolButton" )){
2255 return; 2260 return;
2256 } 2261 }
2257 else{ 2262 else{
2258 QWindowsStyle::drawFocusRect(p, r, g, c, atBorder); 2263 QWindowsStyle::drawFocusRect(p, r, g, c, atBorder);
2259 } 2264 }
2260 } 2265 }
2261 else 2266 else
2262 QWindowsStyle::drawFocusRect(p, r, g, c, atBorder); 2267 QWindowsStyle::drawFocusRect(p, r, g, c, atBorder);
2263 2268
2264} 2269}
2265 2270
2266void LiquidStyle::polishPopupMenu(QPopupMenu *mnu) 2271void LiquidStyle::polishPopupMenu(QPopupMenu *mnu)
2267{ 2272{
2268 mnu->installEventFilter(menuHandler); 2273 mnu->installEventFilter(menuHandler);
2269 QWindowsStyle::polishPopupMenu(mnu); 2274 QWindowsStyle::polishPopupMenu(mnu);
2270} 2275}
2271 2276
2272void LiquidStyle::drawTab(QPainter *p, const QTabBar *tabBar, QTab *tab, 2277void LiquidStyle::drawTab(QPainter *p, const QTabBar *tabBar, QTab *tab,
2273 bool selected) 2278 bool selected)
2274{ 2279{
2275 if(tabBar->shape() != QTabBar::RoundedAbove){ 2280 if(tabBar->shape() != QTabBar::RoundedAbove){
2276 QWindowsStyle::drawTab(p, tabBar, tab, selected); 2281 QWindowsStyle::drawTab(p, tabBar, tab, selected);
2277 return; 2282 return;
2278 } 2283 }
2279 QPixmap tilePix; 2284 QPixmap tilePix;
2280 QRect r = tab->rect(); 2285 QRect r = tab->rect();
2281 //QPixmap *pix = selected ? tabBar->hasFocus() ? pixmaps[TabFocus] : 2286 //QPixmap *pix = selected ? tabBar->hasFocus() ? pixmaps[TabFocus] :
2282 // pixmaps[TabDown] : pixmaps[Tab]; 2287 // pixmaps[TabDown] : pixmaps[Tab];
2283 2288
2284 QPixmap *pix = selected ? getPixmap(TabDown) : getPixmap(Tab); 2289 QPixmap *pix = selected ? getPixmap(TabDown) : getPixmap(Tab);
2285 p->drawPixmap(r.x(), r.y(), *pix, 0, 0, 9, r.height()); 2290 p->drawPixmap(r.x(), r.y(), *pix, 0, 0, 9, r.height());
2286 p->drawPixmap(r.right()-9, r.y(), *pix, pix->width()-9, 0, 9, r.height()); 2291 p->drawPixmap(r.right()-9, r.y(), *pix, pix->width()-9, 0, 9, r.height());
2287 tilePix.resize(pix->width()-18, r.height()); 2292 tilePix.resize(pix->width()-18, r.height());
2288 bitBlt(&tilePix, 0, 0, pix, 9, 0, pix->width()-18, r.height()); 2293 bitBlt(&tilePix, 0, 0, pix, 9, 0, pix->width()-18, r.height());
2289 p->drawTiledPixmap(r.x()+9, r.y(), r.width()-18, r.height(), tilePix); 2294 p->drawTiledPixmap(r.x()+9, r.y(), r.width()-18, r.height(), tilePix);
2290 QColor c = tabBar->colorGroup().button(); 2295 QColor c = tabBar->colorGroup().button();
2291 if(!selected){ 2296 if(!selected){
2292 p->setPen(c.dark(130)); 2297 p->setPen(c.dark(130));
2293 p->drawLine(r.x(), r.bottom(), r.right(), r.bottom()); 2298 p->drawLine(r.x(), r.bottom(), r.right(), r.bottom());
2294 } 2299 }
2295 2300
2296 /* 2301 /*
2297 p->setPen(c.light(110)); 2302 p->setPen(c.light(110));
2298 p->drawLine(r.x(), r.bottom()+1, r.right(), r.bottom()+1); 2303 p->drawLine(r.x(), r.bottom()+1, r.right(), r.bottom()+1);
2299 p->setPen(c); 2304 p->setPen(c);
2300 p->drawLine(r.x(), r.bottom()+2, r.right(), r.bottom()+2); 2305 p->drawLine(r.x(), r.bottom()+2, r.right(), r.bottom()+2);
2301 p->setPen(c.light(110)); 2306 p->setPen(c.light(110));
2302 p->drawLine(r.x(), r.bottom()+3, r.right(), r.bottom()+3); 2307 p->drawLine(r.x(), r.bottom()+3, r.right(), r.bottom()+3);
2303 p->setPen(c.light(120)); 2308 p->setPen(c.light(120));
2304 p->drawLine(r.x(), r.bottom()+4, r.right(), r.bottom()+4); 2309 p->drawLine(r.x(), r.bottom()+4, r.right(), r.bottom()+4);
2305 */ 2310 */
2306 2311
2307 /* 2312 /*
2308 QColor c = tabBar->colorGroup().button(); 2313 QColor c = tabBar->colorGroup().button();
2309 pix = bevelFillDict.find(c.rgb()); 2314 pix = bevelFillDict.find(c.rgb());
2310 if(!pix){ 2315 if(!pix){
2311 int h, s, v; 2316 int h, s, v;
2312 c.hsv(&h, &s, &v); 2317 c.hsv(&h, &s, &v);
2313 pix = new QPixmap(*bevelFillPix); 2318 pix = new QPixmap(*bevelFillPix);
2314 adjustHSV(*pix, h, s); 2319 adjustHSV(*pix, h, s);
2315 bevelFillDict.insert(c.rgb(), pix); 2320 bevelFillDict.insert(c.rgb(), pix);
2316 }*/ 2321 }*/
2317 2322
2318 /* 2323 /*
2319 QRect r = tab->rect(); 2324 QRect r = tab->rect();
2320 QColorGroup g = tabBar->colorGroup(); 2325 QColorGroup g = tabBar->colorGroup();
2321 if(!selected){ 2326 if(!selected){
2322 r.setY(r.y()+1); 2327 r.setY(r.y()+1);
2323 p->setPen(g.dark()); 2328 p->setPen(g.dark());
2324 p->drawLine(r.x(), r.y()+4, r.x(), r.bottom()-2); 2329 p->drawLine(r.x(), r.y()+4, r.x(), r.bottom()-2);
2325 p->drawLine(r.x(), r.y()+4, r.x()+4, r.y()); 2330 p->drawLine(r.x(), r.y()+4, r.x()+4, r.y());
2326 p->drawLine(r.x()+4, r.y(), r.right()-1, r.y()); 2331 p->drawLine(r.x()+4, r.y(), r.right()-1, r.y());
2327 p->drawLine(r.right(), r.y()+1, r.right(), r.bottom()-2); 2332 p->drawLine(r.right(), r.y()+1, r.right(), r.bottom()-2);
2328 2333
2329 p->setPen(g.midlight()); 2334 p->setPen(g.midlight());
2330 p->drawLine(r.x()+1, r.y()+4, r.x()+1, r.bottom()); 2335 p->drawLine(r.x()+1, r.y()+4, r.x()+1, r.bottom());
2331 p->drawLine(r.x()+1, r.y()+4, r.x()+4, r.y()+1); 2336 p->drawLine(r.x()+1, r.y()+4, r.x()+4, r.y()+1);
2332 p->drawLine(r.x()+5, r.y()+1, r.right()-2, r.y()+1); 2337 p->drawLine(r.x()+5, r.y()+1, r.right()-2, r.y()+1);
2333 p->drawLine(r.x(), r.bottom(), r.right(), r.bottom()); 2338 p->drawLine(r.x(), r.bottom(), r.right(), r.bottom());
2334 2339
2335 p->setPen(g.mid()); 2340 p->setPen(g.mid());
2336 p->drawPoint(r.right()-1, r.y()+1); 2341 p->drawPoint(r.right()-1, r.y()+1);
2337 p->drawLine(r.x()+4, r.y()+2, r.right()-1, r.y()+2); 2342 p->drawLine(r.x()+4, r.y()+2, r.right()-1, r.y()+2);
2338 p->drawLine(r.x()+3, r.y()+3, r.right()-1, r.y()+3); 2343 p->drawLine(r.x()+3, r.y()+3, r.right()-1, r.y()+3);
2339 2344
2340 p->fillRect(r.x()+2, r.y()+4, r.width()-3, r.height()-6, 2345 p->fillRect(r.x()+2, r.y()+4, r.width()-3, r.height()-6,
2341 g.brush(QColorGroup::Mid)); 2346 g.brush(QColorGroup::Mid));
2342 2347
2343 p->setPen(g.light()); 2348 p->setPen(g.light());
2344 p->drawLine(r.x(), r.bottom()-1, r.right(), r.bottom()-1); 2349 p->drawLine(r.x(), r.bottom()-1, r.right(), r.bottom()-1);
2345 2350
2346 } 2351 }
2347 else{ 2352 else{
2348 p->setPen(g.light()); 2353 p->setPen(g.light());
2349 p->drawLine(r.x(), r.y()+4, r.x(), r.bottom()); 2354 p->drawLine(r.x(), r.y()+4, r.x(), r.bottom());
2350 p->drawLine(r.x(), r.y()+4, r.x()+4, r.y()); 2355 p->drawLine(r.x(), r.y()+4, r.x()+4, r.y());
2351 p->drawLine(r.x()+4, r.y(), r.right()-1, r.y()); 2356 p->drawLine(r.x()+4, r.y(), r.right()-1, r.y());
2352 p->setPen(g.dark()); 2357 p->setPen(g.dark());
2353 p->drawLine(r.right(), r.y()+1, r.right(), r.bottom()); 2358 p->drawLine(r.right(), r.y()+1, r.right(), r.bottom());
2354 2359
2355 p->setPen(g.midlight()); 2360 p->setPen(g.midlight());
2356 p->drawLine(r.x()+1, r.y()+4, r.x()+1, r.bottom()); 2361 p->drawLine(r.x()+1, r.y()+4, r.x()+1, r.bottom());
2357 p->drawLine(r.x()+1, r.y()+4, r.x()+4, r.y()+1); 2362 p->drawLine(r.x()+1, r.y()+4, r.x()+4, r.y()+1);
2358 p->drawLine(r.x()+5, r.y()+1, r.right() - 2, r.y()+1); 2363 p->drawLine(r.x()+5, r.y()+1, r.right() - 2, r.y()+1);
2359 p->setPen(g.mid()); 2364 p->setPen(g.mid());
2360 p->drawLine(r.right()-1, r.y()+1, r.right()-1, r.bottom()); 2365 p->drawLine(r.right()-1, r.y()+1, r.right()-1, r.bottom());
2361 }*/ 2366 }*/
2362 2367
2363} 2368}
2364 2369
2365 2370
2366 2371
2367void LiquidStyle::drawTabMask(QPainter *p, const QTabBar*, QTab *tab, 2372void LiquidStyle::drawTabMask(QPainter *p, const QTabBar*, QTab *tab,
2368 bool selected) 2373 bool selected)
2369 2374
2370 2375
2371{ 2376{
2372 //p->fillRect(tab->rect(), Qt::color1); 2377 //p->fillRect(tab->rect(), Qt::color1);
2373 QRect r = tab->rect(); 2378 QRect r = tab->rect();
2374 QPixmap *pix = selected ? getPixmap(TabDown) : getPixmap(Tab); 2379 QPixmap *pix = selected ? getPixmap(TabDown) : getPixmap(Tab);
2375 p->drawPixmap(r.x(), r.y(), *pix->mask(), 0, 0, 9, r.height()); 2380 p->drawPixmap(r.x(), r.y(), *pix->mask(), 0, 0, 9, r.height());
2376 p->drawPixmap(r.right()-9, r.y(), *pix->mask(), pix->width()-9, 0, 9, r.height()); 2381 p->drawPixmap(r.right()-9, r.y(), *pix->mask(), pix->width()-9, 0, 9, r.height());
2377 p->fillRect(r.x()+9, r.y(), r.width()-18, r.height(), Qt::color1); 2382 p->fillRect(r.x()+9, r.y(), r.width()-18, r.height(), Qt::color1);
2378} 2383}
2379 2384
2380void LiquidStyle::tabbarMetrics(const QTabBar *t, int &hFrame, int &vFrame, 2385void LiquidStyle::tabbarMetrics(const QTabBar *t, int &hFrame, int &vFrame,
2381 int &overlap) 2386 int &overlap)
2382{ 2387{
2383 if(t->shape() == QTabBar::RoundedAbove){ 2388 if(t->shape() == QTabBar::RoundedAbove){
2384 overlap = 1; 2389 overlap = 1;
2385 hFrame = 18; // was 24 2390 hFrame = 18; // was 24
2386 vFrame = 8; // was 10 2391 vFrame = 8; // was 10
2387 } 2392 }
2388 else 2393 else
2389 QWindowsStyle::tabbarMetrics(t, hFrame, vFrame, overlap); 2394 QWindowsStyle::tabbarMetrics(t, hFrame, vFrame, overlap);
2390} 2395}
2391 2396
2392 2397
2393 2398
2394void LiquidStyle::drawSplitter(QPainter *p, int x, int y, int w, int h, 2399void LiquidStyle::drawSplitter(QPainter *p, int x, int y, int w, int h,
2395 const QColorGroup &g, Orientation) 2400 const QColorGroup &g, Orientation)
2396{ 2401{
2397 drawClearBevel(p, x, y, w, h, highlightWidget == p->device() ? 2402 drawClearBevel(p, x, y, w, h, highlightWidget == p->device() ?
2398 g.button().light(120) : g.button(), g.background()); 2403 g.button().light(120) : g.button(), g.background());
2399} 2404}
2400 2405
2401 2406
2402void LiquidStyle::drawPanel(QPainter *p, int x, int y, int w, int h, 2407void LiquidStyle::drawPanel(QPainter *p, int x, int y, int w, int h,
2403 const QColorGroup &g, bool sunken, 2408 const QColorGroup &g, bool sunken,
2404 int lineWidth, const QBrush *fill) 2409 int lineWidth, const QBrush *fill)
2405{ 2410{
2406 if(p->device()->devType() == QInternal::Widget && 2411 if(p->device()->devType() == QInternal::Widget &&
2407 ((QWidget *)p->device())->inherits("QLineEdit")){ 2412 ((QWidget *)p->device())->inherits("QLineEdit")){
2408 int x2 = x+w-1; 2413 int x2 = x+w-1;
2409 int y2 = y+h-1; 2414 int y2 = y+h-1;
2410 p->setPen(g.dark()); 2415 p->setPen(g.dark());
2411 p->drawRect(x, y, w, h); 2416 p->drawRect(x, y, w, h);
2412 p->setPen(g.mid()); 2417 p->setPen(g.mid());
2413 p->drawLine(x+1, y+1, x2-2, y+1); 2418 p->drawLine(x+1, y+1, x2-2, y+1);
2414 p->drawLine(x+1, y+1, x+1, y2-1); 2419 p->drawLine(x+1, y+1, x+1, y2-1);
2415 } 2420 }
2416 else if(lineWidth != 2 || !sunken) 2421 else if(lineWidth != 2 || !sunken)
2417 QWindowsStyle::drawPanel(p, x, y, w, h, g, sunken, lineWidth, fill); 2422 QWindowsStyle::drawPanel(p, x, y, w, h, g, sunken, lineWidth, fill);
2418 else{ 2423 else{
2419 QPen oldPen = p->pen(); 2424 QPen oldPen = p->pen();
2420 int x2 = x+w-1; 2425 int x2 = x+w-1;
2421 int y2 = y+h-1; 2426 int y2 = y+h-1;
2422 p->setPen(g.light()); 2427 p->setPen(g.light());
2423 p->drawLine(x, y2, x2, y2); 2428 p->drawLine(x, y2, x2, y2);
2424 p->drawLine(x2, y, x2, y2); 2429 p->drawLine(x2, y, x2, y2);
2425 p->setPen(g.mid()); 2430 p->setPen(g.mid());
2426 p->drawLine(x, y, x2, y); 2431 p->drawLine(x, y, x2, y);
2427 p->drawLine(x, y, x, y2); 2432 p->drawLine(x, y, x, y2);
2428 2433
2429 p->setPen(g.midlight()); 2434 p->setPen(g.midlight());
2430 p->drawLine(x+1, y2-1, x2-1, y2-1); 2435 p->drawLine(x+1, y2-1, x2-1, y2-1);
2431 p->drawLine(x2-1, y+1, x2-1, y2-1); 2436 p->drawLine(x2-1, y+1, x2-1, y2-1);
2432 p->setPen(g.dark()); 2437 p->setPen(g.dark());
2433 p->drawLine(x+1, y+1, x2-1, y+1); 2438 p->drawLine(x+1, y+1, x2-1, y+1);
2434 p->drawLine(x+1, y+1, x+1, y2-1); 2439 p->drawLine(x+1, y+1, x+1, y2-1);
2435 p->setPen(oldPen); 2440 p->setPen(oldPen);
2436 if(fill){ 2441 if(fill){
2437 // I believe here we are only supposed to fill if there is a 2442 // I believe here we are only supposed to fill if there is a
2438 // specified fill brush... 2443 // specified fill brush...
2439 p->fillRect(x+2, y+2, w-4, h-4, *fill); 2444 p->fillRect(x+2, y+2, w-4, h-4, *fill);
2440 } 2445 }
2441 } 2446 }
2442} 2447}
2443 2448
2444 2449
2445void LiquidStyle::adjustHSV(QPixmap &pix, int h, int s, int v) 2450void LiquidStyle::adjustHSV(QPixmap &pix, int h, int s, int v)
2446{ 2451{
2447 QBitmap *maskBmp = NULL; 2452 QBitmap *maskBmp = NULL;
2448 if(pix.mask()) 2453 if(pix.mask())
2449 maskBmp = new QBitmap(*pix.mask()); 2454 maskBmp = new QBitmap(*pix.mask());
2450 QImage img = pix.convertToImage(); 2455 QImage img = pix.convertToImage();
2451 if(img.depth() != 32) 2456 if(img.depth() != 32)
2452 img = img.convertDepth(32); 2457 img = img.convertDepth(32);
2453 unsigned int *data = (unsigned int *)img.bits(); 2458 unsigned int *data = (unsigned int *)img.bits();
2454 int total = img.width()*img.height(); 2459 int total = img.width()*img.height();
2455 int current; 2460 int current;
2456 QColor c; 2461 QColor c;
2457 int oldH, oldS, oldV; 2462 int oldH, oldS, oldV;
2458 if(v < 235) 2463 if(v < 235)
2459 v += 20; 2464 v += 20;
2460 else 2465 else
2461 v = 255; 2466 v = 255;
2462 float intensity = v/255.0; 2467 float intensity = v/255.0;
2463 2468
2464 for(current=0; current<total; ++current){ 2469 for(current=0; current<total; ++current){
2465 c.setRgb(data[current]); 2470 c.setRgb(data[current]);
2466 c.hsv(&oldH, &oldS, &oldV); 2471 c.hsv(&oldH, &oldS, &oldV);
2467 oldV = (int)(oldV*intensity); 2472 oldV = (int)(oldV*intensity);
2468 c.setHsv(h, s, oldV); 2473 c.setHsv(h, s, oldV);
2469 data[current] = c.rgb(); 2474 data[current] = c.rgb();
2470 } 2475 }
2471 pix.convertFromImage(img); 2476 pix.convertFromImage(img);
2472 if(maskBmp) 2477 if(maskBmp)
2473 pix.setMask(*maskBmp); 2478 pix.setMask(*maskBmp);
2474} 2479}
2475 2480
2476void LiquidStyle::intensity(QPixmap &pix, float percent) 2481void LiquidStyle::intensity(QPixmap &pix, float percent)
2477{ 2482{
2478 QImage image = pix.convertToImage(); 2483 QImage image = pix.convertToImage();
2479 int i, tmp, r, g, b; 2484 int i, tmp, r, g, b;
2480 int segColors = image.depth() > 8 ? 256 : image.numColors(); 2485 int segColors = image.depth() > 8 ? 256 : image.numColors();
2481 unsigned char *segTbl = new unsigned char[segColors]; 2486 unsigned char *segTbl = new unsigned char[segColors];
2482 int pixels = image.depth() > 8 ? image.width()*image.height() : 2487 int pixels = image.depth() > 8 ? image.width()*image.height() :
2483 image.numColors(); 2488 image.numColors();
2484 unsigned int *data = image.depth() > 8 ? (unsigned int *)image.bits() : 2489 unsigned int *data = image.depth() > 8 ? (unsigned int *)image.bits() :
2485 (unsigned int *)image.colorTable(); 2490 (unsigned int *)image.colorTable();
2486 2491
2487 bool brighten = (percent >= 0); 2492 bool brighten = (percent >= 0);
2488 if(percent < 0) 2493 if(percent < 0)
2489 percent = -percent; 2494 percent = -percent;
2490 2495
2491 if(brighten){ // keep overflow check out of loops 2496 if(brighten){ // keep overflow check out of loops
2492 for(i=0; i < segColors; ++i){ 2497 for(i=0; i < segColors; ++i){
2493 tmp = (int)(i*percent); 2498 tmp = (int)(i*percent);
2494 if(tmp > 255) 2499 if(tmp > 255)
2495 tmp = 255; 2500 tmp = 255;
2496 segTbl[i] = tmp; 2501 segTbl[i] = tmp;
2497 } 2502 }
2498 } 2503 }
2499 else{ 2504 else{
2500 for(i=0; i < segColors; ++i){ 2505 for(i=0; i < segColors; ++i){
2501 tmp = (int)(i*percent); 2506 tmp = (int)(i*percent);
2502 if(tmp < 0) 2507 if(tmp < 0)
2503 tmp = 0; 2508 tmp = 0;
2504 segTbl[i] = tmp; 2509 segTbl[i] = tmp;
2505 } 2510 }
2506 } 2511 }
2507 2512
2508 if(brighten){ // same here 2513 if(brighten){ // same here
2509 for(i=0; i < pixels; ++i){ 2514 for(i=0; i < pixels; ++i){
2510 r = qRed(data[i]); 2515 r = qRed(data[i]);
2511 g = qGreen(data[i]); 2516 g = qGreen(data[i]);
2512 b = qBlue(data[i]); 2517 b = qBlue(data[i]);
2513 r = r + segTbl[r] > 255 ? 255 : r + segTbl[r]; 2518 r = r + segTbl[r] > 255 ? 255 : r + segTbl[r];
2514 g = g + segTbl[g] > 255 ? 255 : g + segTbl[g]; 2519 g = g + segTbl[g] > 255 ? 255 : g + segTbl[g];
2515 b = b + segTbl[b] > 255 ? 255 : b + segTbl[b]; 2520 b = b + segTbl[b] > 255 ? 255 : b + segTbl[b];
2516 data[i] = qRgb(r, g, b); 2521 data[i] = qRgb(r, g, b);
2517 } 2522 }
2518 } 2523 }
2519 else{ 2524 else{
2520 for(i=0; i < pixels; ++i){ 2525 for(i=0; i < pixels; ++i){
2521 r = qRed(data[i]); 2526 r = qRed(data[i]);
2522 g = qGreen(data[i]); 2527 g = qGreen(data[i]);
2523 b = qBlue(data[i]); 2528 b = qBlue(data[i]);
2524 r = r - segTbl[r] < 0 ? 0 : r - segTbl[r]; 2529 r = r - segTbl[r] < 0 ? 0 : r - segTbl[r];
2525 g = g - segTbl[g] < 0 ? 0 : g - segTbl[g]; 2530 g = g - segTbl[g] < 0 ? 0 : g - segTbl[g];
2526 b = b - segTbl[b] < 0 ? 0 : b - segTbl[b]; 2531 b = b - segTbl[b] < 0 ? 0 : b - segTbl[b];
2527 data[i] = qRgb(r, g, b); 2532 data[i] = qRgb(r, g, b);
2528 } 2533 }
2529 } 2534 }
2530 delete [] segTbl; 2535 delete [] segTbl;
2531 pix.convertFromImage(image); 2536 pix.convertFromImage(image);
2532} 2537}
2533 2538
2534void LiquidStyle::drawRoundRect(QPainter *p, int x, int y, int w, int h) 2539void LiquidStyle::drawRoundRect(QPainter *p, int x, int y, int w, int h)
2535{ 2540{
2536 int x2 = x+w-1; 2541 int x2 = x+w-1;
2537 int y2 = y+h-1; 2542 int y2 = y+h-1;
2538 p->drawLine(x+1, y, x2-1, y); 2543 p->drawLine(x+1, y, x2-1, y);
2539 p->drawLine(x, y+1, x, y2-1); 2544 p->drawLine(x, y+1, x, y2-1);
2540 p->drawLine(x+1, y2, x2-1, y2); 2545 p->drawLine(x+1, y2, x2-1, y2);
2541 p->drawLine(x2, y+1, x2, y2-1); 2546 p->drawLine(x2, y+1, x2, y2-1);
2542} 2547}
2543 2548
2544void LiquidStyle::drawSliderGroove (QPainter * p, int x, int y, int w, int h, 2549void LiquidStyle::drawSliderGroove (QPainter * p, int x, int y, int w, int h,
2545 const QColorGroup &g, QCOORD, 2550 const QColorGroup &g, QCOORD,
2546 Orientation orient) 2551 Orientation orient)
2547{ 2552{
2548 bool isFocus = ((QWidget *)p->device())->hasFocus(); 2553 bool isFocus = ((QWidget *)p->device())->hasFocus();
2549 QColor c = isFocus ? g.background().dark(120) : g.background(); 2554 QColor c = isFocus ? g.background().dark(120) : g.background();
2550 if(orient == Qt::Horizontal){ 2555 if(orient == Qt::Horizontal){
2551 int x2 = x+w-1; 2556 int x2 = x+w-1;
2552 y+=2; 2557 y+=2;
2553 p->setPen(c.dark(130)); 2558 p->setPen(c.dark(130));
2554 p->drawLine(x+1, y, x2-1, y); 2559 p->drawLine(x+1, y, x2-1, y);
2555 p->setPen(c.dark(150)); 2560 p->setPen(c.dark(150));
2556 p->drawLine(x, y+1, x2, y+1); 2561 p->drawLine(x, y+1, x2, y+1);
2557 p->setPen(c.dark(125)); 2562 p->setPen(c.dark(125));
2558 p->drawLine(x, y+2, x2, y+2); 2563 p->drawLine(x, y+2, x2, y+2);
2559 p->setPen(c.dark(130)); 2564 p->setPen(c.dark(130));
2560 p->drawLine(x, y+3, x2, y+3); 2565 p->drawLine(x, y+3, x2, y+3);
2561 p->setPen(c.dark(120)); 2566 p->setPen(c.dark(120));
2562 p->drawLine(x, y+4, x2, y+4); 2567 p->drawLine(x, y+4, x2, y+4);
2563 p->setPen(c.light(110)); 2568 p->setPen(c.light(110));
2564 p->drawLine(x+1, y+5, x2-1, y+5); 2569 p->drawLine(x+1, y+5, x2-1, y+5);
2565 } 2570 }
2566 else{ 2571 else{
2567 int y2 = y+h-1; 2572 int y2 = y+h-1;
2568 x+=2; 2573 x+=2;
2569 p->setPen(c.dark(130)); 2574 p->setPen(c.dark(130));
2570 p->drawLine(x, y+1, x, y2-1); 2575 p->drawLine(x, y+1, x, y2-1);
2571 p->setPen(c.dark(150)); 2576 p->setPen(c.dark(150));
2572 p->drawLine(x+1, y, x+1, y2); 2577 p->drawLine(x+1, y, x+1, y2);
2573 p->setPen(c.dark(125)); 2578 p->setPen(c.dark(125));
2574 p->drawLine(x+2, y, x+2, y2); 2579 p->drawLine(x+2, y, x+2, y2);
2575 p->setPen(c.dark(130)); 2580 p->setPen(c.dark(130));
2576 p->drawLine(x+3, y, x+3, y2); 2581 p->drawLine(x+3, y, x+3, y2);
2577 p->setPen(c.dark(120)); 2582 p->setPen(c.dark(120));
2578 p->drawLine(x+4, y, x+4, y2); 2583 p->drawLine(x+4, y, x+4, y2);
2579 p->setPen(c.light(110)); 2584 p->setPen(c.light(110));
2580 p->drawLine(x+5, y+1, x+5, y2-1); 2585 p->drawLine(x+5, y+1, x+5, y2-1);
2581 } 2586 }
2582 //QWindowsStyle::drawSliderGroove(p, x, y, w, h, g, c, orient); 2587 //QWindowsStyle::drawSliderGroove(p, x, y, w, h, g, c, orient);
2583 2588
2584} 2589}
2585 2590
2586void LiquidStyle::drawSliderGrooveMask (QPainter * p, int x, int y, int w, 2591void LiquidStyle::drawSliderGrooveMask (QPainter * p, int x, int y, int w,
2587 int h, QCOORD, Orientation orient) 2592 int h, QCOORD, Orientation orient)
2588{ 2593{
2589 p->fillRect(x, y, w, h, Qt::color0); 2594 p->fillRect(x, y, w, h, Qt::color0);
2590 p->setPen(Qt::color1); 2595 p->setPen(Qt::color1);
2591 if(orient == Qt::Horizontal){ 2596 if(orient == Qt::Horizontal){
2592 int x2 = x+w-1; 2597 int x2 = x+w-1;
2593 y+=2; 2598 y+=2;
2594 p->drawLine(x+1, y, x2-1, y); 2599 p->drawLine(x+1, y, x2-1, y);
2595 p->fillRect(x, y+1, w, 4, Qt::color1); 2600 p->fillRect(x, y+1, w, 4, Qt::color1);
2596 p->drawLine(x+1, y+5, x2-1, y+5); 2601 p->drawLine(x+1, y+5, x2-1, y+5);
2597 } 2602 }
2598 else{ 2603 else{
2599 int y2 = y+h-1; 2604 int y2 = y+h-1;
2600 x+=2; 2605 x+=2;
2601 p->drawLine(x, y+1, x, y2-1); 2606 p->drawLine(x, y+1, x, y2-1);
2602 p->fillRect(x+1, y, 4, h, Qt::color1); 2607 p->fillRect(x+1, y, 4, h, Qt::color1);
2603 p->drawLine(x+5, y+1, x+5, y2-1); 2608 p->drawLine(x+5, y+1, x+5, y2-1);
2604 } 2609 }
2605} 2610}
2606 2611
2607 2612
2608/* vim: set noet sw=8 ts=8: */ 2613/* vim: set noet sw=8 ts=8: */
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,1205 +1,1200 @@
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
132 tmp.resize( pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ] ); 134 tmp.resize( pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ] );
133 destMask.resize( pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ] ); 135 destMask.resize( pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ] );
134 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbWidth[ i ], 0, 136 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbWidth[ i ], 0,
135 pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ], Qt::CopyROP, false ); 137 pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ], Qt::CopyROP, false );
136 if ( srcMask ) { 138 if ( srcMask ) {
137 bitBlt( &destMask, 0, 0, srcMask, pbWidth[ i ], 0, 139 bitBlt( &destMask, 0, 0, srcMask, pbWidth[ i ], 0,
138 pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ], 140 pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ],
139 Qt::CopyROP, false ); 141 Qt::CopyROP, false );
140 tmp.setMask( destMask ); 142 tmp.setMask( destMask );
141 } 143 }
142 pbPixmaps[ i ] ->setBorder( OThemePixmap::Top, tmp ); 144 pbPixmaps[ i ] ->setBorder( OThemePixmap::Top, tmp );
143 145
144 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbWidth[ i ], 146 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbWidth[ i ],
145 pbPixmaps[ i ] ->height() - pbWidth[ i ], 147 pbPixmaps[ i ] ->height() - pbWidth[ i ],
146 pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ], Qt::CopyROP, false ); 148 pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ], Qt::CopyROP, false );
147 if ( srcMask ) { 149 if ( srcMask ) {
148 bitBlt( &destMask, 0, 0, srcMask, pbWidth[ i ], 150 bitBlt( &destMask, 0, 0, srcMask, pbWidth[ i ],
149 pbPixmaps[ i ] ->height() - pbWidth[ i ], 151 pbPixmaps[ i ] ->height() - pbWidth[ i ],
150 pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ], Qt::CopyROP, false ); 152 pbPixmaps[ i ] ->width() - pbWidth[ i ] * 2, pbWidth[ i ], Qt::CopyROP, false );
151 tmp.setMask( destMask ); 153 tmp.setMask( destMask );
152 } 154 }
153 pbPixmaps[ i ] ->setBorder( OThemePixmap::Bottom, tmp ); 155 pbPixmaps[ i ] ->setBorder( OThemePixmap::Bottom, tmp );
154 156
155 tmp.resize( pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2 ); 157 tmp.resize( pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2 );
156 destMask.resize( pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2 ); 158 destMask.resize( pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2 );
157 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], 0, pbWidth[ i ], pbWidth[ i ], 159 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], 0, pbWidth[ i ], pbWidth[ i ],
158 pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2, Qt::CopyROP, false ); 160 pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2, Qt::CopyROP, false );
159 if ( srcMask ) { 161 if ( srcMask ) {
160 bitBlt( &destMask, 0, 0, srcMask, 0, pbWidth[ i ], pbWidth[ i ], 162 bitBlt( &destMask, 0, 0, srcMask, 0, pbWidth[ i ], pbWidth[ i ],
161 pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2, Qt::CopyROP, false ); 163 pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2, Qt::CopyROP, false );
162 tmp.setMask( destMask ); 164 tmp.setMask( destMask );
163 } 165 }
164 166
165 pbPixmaps[ i ] ->setBorder( OThemePixmap::Left, tmp ); 167 pbPixmaps[ i ] ->setBorder( OThemePixmap::Left, tmp );
166 168
167 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbPixmaps[ i ] ->width() - pbWidth[ i ], 169 bitBlt( &tmp, 0, 0, pbPixmaps[ i ], pbPixmaps[ i ] ->width() - pbWidth[ i ],
168 pbWidth[ i ], pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2, 170 pbWidth[ i ], pbWidth[ i ], pbPixmaps[ i ] ->height() - pbWidth[ i ] * 2,
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 );
507 mask.fill( color0 ); 502 mask.fill( color0 );
508 QPainter mPainter; 503 QPainter mPainter;
509 mPainter.begin( &mask ); 504 mPainter.begin( &mask );
510 505
511 QPixmap *tmp = borderPixmap( widget ) ->border( OThemePixmap::TopLeft ); 506 QPixmap *tmp = borderPixmap( widget ) ->border( OThemePixmap::TopLeft );
512 const QBitmap *srcMask = tmp->mask(); 507 const QBitmap *srcMask = tmp->mask();
513 int bdWidth = tmp->width(); 508 int bdWidth = tmp->width();
514 509
515 bitBlt( pixmap, 0, 0, tmp, 0, 0, bdWidth, bdWidth, 510 bitBlt( pixmap, 0, 0, tmp, 0, 0, bdWidth, bdWidth,
516 Qt::CopyROP, false ); 511 Qt::CopyROP, false );
517 if ( srcMask ) 512 if ( srcMask )
518 bitBlt( &mask, 0, 0, srcMask, 0, 0, bdWidth, bdWidth, 513 bitBlt( &mask, 0, 0, srcMask, 0, 0, bdWidth, bdWidth,
519 Qt::CopyROP, false ); 514 Qt::CopyROP, false );
520 else 515 else
521 mPainter.fillRect( 0, 0, bdWidth, bdWidth, color1 ); 516 mPainter.fillRect( 0, 0, bdWidth, bdWidth, color1 );
522 517
523 518
524 tmp = borderPixmap( widget ) ->border( OThemePixmap::TopRight ); 519 tmp = borderPixmap( widget ) ->border( OThemePixmap::TopRight );
525 srcMask = tmp->mask(); 520 srcMask = tmp->mask();
526 bitBlt( pixmap, w - bdWidth, 0, tmp, 0, 0, bdWidth, 521 bitBlt( pixmap, w - bdWidth, 0, tmp, 0, 0, bdWidth,
527 bdWidth, Qt::CopyROP, false ); 522 bdWidth, Qt::CopyROP, false );
528 if ( srcMask ) 523 if ( srcMask )
529 bitBlt( &mask, w - bdWidth, 0, srcMask, 0, 0, bdWidth, 524 bitBlt( &mask, w - bdWidth, 0, srcMask, 0, 0, bdWidth,
530 bdWidth, Qt::CopyROP, false ); 525 bdWidth, Qt::CopyROP, false );
531 else 526 else
532 mPainter.fillRect( w - bdWidth, 0, bdWidth, bdWidth, color1 ); 527 mPainter.fillRect( w - bdWidth, 0, bdWidth, bdWidth, color1 );
533 528
534 tmp = borderPixmap( widget ) ->border( OThemePixmap::BottomLeft ); 529 tmp = borderPixmap( widget ) ->border( OThemePixmap::BottomLeft );
535 srcMask = tmp->mask(); 530 srcMask = tmp->mask();
536 bitBlt( pixmap, 0, h - bdWidth, tmp, 0, 0, bdWidth, 531 bitBlt( pixmap, 0, h - bdWidth, tmp, 0, 0, bdWidth,
537 bdWidth, Qt::CopyROP, false ); 532 bdWidth, Qt::CopyROP, false );
538 if ( srcMask ) 533 if ( srcMask )
539 bitBlt( &mask, 0, h - bdWidth, srcMask, 0, 0, bdWidth, 534 bitBlt( &mask, 0, h - bdWidth, srcMask, 0, 0, bdWidth,
540 bdWidth, Qt::CopyROP, false ); 535 bdWidth, Qt::CopyROP, false );
541 else 536 else
542 mPainter.fillRect( 0, h - bdWidth, bdWidth, bdWidth, color1 ); 537 mPainter.fillRect( 0, h - bdWidth, bdWidth, bdWidth, color1 );
543 538
544 tmp = borderPixmap( widget ) ->border( OThemePixmap::BottomRight ); 539 tmp = borderPixmap( widget ) ->border( OThemePixmap::BottomRight );
545 srcMask = tmp->mask(); 540 srcMask = tmp->mask();
546 bitBlt( pixmap, w - bdWidth, h - bdWidth, tmp, 0, 0, 541 bitBlt( pixmap, w - bdWidth, h - bdWidth, tmp, 0, 0,
547 bdWidth, bdWidth, Qt::CopyROP, false ); 542 bdWidth, bdWidth, Qt::CopyROP, false );
548 if ( srcMask ) 543 if ( srcMask )
549 bitBlt( &mask, w - bdWidth, h - bdWidth, srcMask, 0, 0, 544 bitBlt( &mask, w - bdWidth, h - bdWidth, srcMask, 0, 0,
550 bdWidth, bdWidth, Qt::CopyROP, false ); 545 bdWidth, bdWidth, Qt::CopyROP, false );
551 else 546 else
552 mPainter.fillRect( w - bdWidth, h - bdWidth, bdWidth, bdWidth, color1 ); 547 mPainter.fillRect( w - bdWidth, h - bdWidth, bdWidth, bdWidth, color1 );
553 548
554 QPainter p; 549 QPainter p;
555 p.begin( pixmap ); 550 p.begin( pixmap );
556 if ( w - bdWidth * 2 > 0 ) { 551 if ( w - bdWidth * 2 > 0 ) {
557 tmp = borderPixmap( widget ) ->border( OThemePixmap::Top ); 552 tmp = borderPixmap( widget ) ->border( OThemePixmap::Top );
558 srcMask = tmp->mask(); 553 srcMask = tmp->mask();
559 p.drawTiledPixmap( bdWidth, 0, w - bdWidth * 2, bdWidth, *tmp ); 554 p.drawTiledPixmap( bdWidth, 0, w - bdWidth * 2, bdWidth, *tmp );
560 if ( srcMask ) 555 if ( srcMask )
561 mPainter.drawTiledPixmap( bdWidth, 0, w - bdWidth * 2, bdWidth, *srcMask ); 556 mPainter.drawTiledPixmap( bdWidth, 0, w - bdWidth * 2, bdWidth, *srcMask );
562 else 557 else
563 mPainter.fillRect( bdWidth, 0, w - bdWidth * 2, bdWidth, color1 ); 558 mPainter.fillRect( bdWidth, 0, w - bdWidth * 2, bdWidth, color1 );
564 559
565 tmp = borderPixmap( widget ) ->border( OThemePixmap::Bottom ); 560 tmp = borderPixmap( widget ) ->border( OThemePixmap::Bottom );
566 srcMask = tmp->mask(); 561 srcMask = tmp->mask();
567 p.drawTiledPixmap( bdWidth, h - bdWidth, w - bdWidth * 2, bdWidth, 562 p.drawTiledPixmap( bdWidth, h - bdWidth, w - bdWidth * 2, bdWidth,
568 *tmp ); 563 *tmp );
569 if ( srcMask ) 564 if ( srcMask )
570 mPainter.drawTiledPixmap( bdWidth, h - bdWidth, w - bdWidth * 2, bdWidth, *srcMask ); 565 mPainter.drawTiledPixmap( bdWidth, h - bdWidth, w - bdWidth * 2, bdWidth, *srcMask );
571 else 566 else
572 mPainter.fillRect( bdWidth, h - bdWidth, w - bdWidth * 2, bdWidth, 567 mPainter.fillRect( bdWidth, h - bdWidth, w - bdWidth * 2, bdWidth,
573 color1 ); 568 color1 );
574 } 569 }
575 if ( h - bdWidth * 2 > 0 ) { 570 if ( h - bdWidth * 2 > 0 ) {
576 tmp = borderPixmap( widget ) ->border( OThemePixmap::Left ); 571 tmp = borderPixmap( widget ) ->border( OThemePixmap::Left );
577 srcMask = tmp->mask(); 572 srcMask = tmp->mask();
578 p.drawTiledPixmap( 0, bdWidth, bdWidth, h - bdWidth * 2, *tmp ); 573 p.drawTiledPixmap( 0, bdWidth, bdWidth, h - bdWidth * 2, *tmp );
579 if ( srcMask ) 574 if ( srcMask )
580 mPainter.drawTiledPixmap( 0, bdWidth, bdWidth, h - bdWidth * 2, *srcMask ); 575 mPainter.drawTiledPixmap( 0, bdWidth, bdWidth, h - bdWidth * 2, *srcMask );
581 else 576 else
582 mPainter.fillRect( 0, bdWidth, bdWidth, h - bdWidth * 2, color1 ); 577 mPainter.fillRect( 0, bdWidth, bdWidth, h - bdWidth * 2, color1 );
583 578
584 tmp = borderPixmap( widget ) ->border( OThemePixmap::Right ); 579 tmp = borderPixmap( widget ) ->border( OThemePixmap::Right );
585 srcMask = tmp->mask(); 580 srcMask = tmp->mask();
586 p.drawTiledPixmap( w - bdWidth, bdWidth, bdWidth, h - bdWidth * 2, 581 p.drawTiledPixmap( w - bdWidth, bdWidth, bdWidth, h - bdWidth * 2,
587 *tmp ); 582 *tmp );
588 if ( srcMask ) 583 if ( srcMask )
589 mPainter.drawTiledPixmap( w - bdWidth, bdWidth, bdWidth, h - bdWidth * 2, *srcMask ); 584 mPainter.drawTiledPixmap( w - bdWidth, bdWidth, bdWidth, h - bdWidth * 2, *srcMask );
590 else 585 else
591 mPainter.fillRect( w - bdWidth, bdWidth, bdWidth, h - bdWidth * 2, color1 ); 586 mPainter.fillRect( w - bdWidth, bdWidth, bdWidth, h - bdWidth * 2, color1 );
592 } 587 }
593 p.end(); 588 p.end();
594 mPainter.end(); 589 mPainter.end();
595 pixmap->setMask( mask ); 590 pixmap->setMask( mask );
596 cache->insert( pixmap, OThemeCache::FullScale, widget, true ); 591 cache->insert( pixmap, OThemeCache::FullScale, widget, true );
597 if ( !pixmap->mask() ) 592 if ( !pixmap->mask() )
598 qDebug ( "No mask for border pixmap!\n" ); 593 qDebug ( "No mask for border pixmap!\n" );
599 } 594 }
600 return ( pixmap ); 595 return ( pixmap );
601} 596}
602 597
603 598
604OThemePixmap* OThemeBase::blend( WidgetType widget ) 599OThemePixmap* OThemeBase::blend( WidgetType widget )
605{ 600{
606 OGfxEffect::GradientType g; 601 OGfxEffect::GradientType g;
607 switch ( gradients[ widget ] ) { 602 switch ( gradients[ widget ] ) {
608 case GrHorizontal: 603 case GrHorizontal:
609 g = OGfxEffect::HorizontalGradient; 604 g = OGfxEffect::HorizontalGradient;
610 break; 605 break;
611 case GrVertical: 606 case GrVertical:
612 g = OGfxEffect::VerticalGradient; 607 g = OGfxEffect::VerticalGradient;
613 break; 608 break;
614 case GrPyramid: 609 case GrPyramid:
615 g = OGfxEffect::PyramidGradient; 610 g = OGfxEffect::PyramidGradient;
616 break; 611 break;
617 case GrRectangle: 612 case GrRectangle:
618 g = OGfxEffect::RectangleGradient; 613 g = OGfxEffect::RectangleGradient;
619 break; 614 break;
620 case GrElliptic: 615 case GrElliptic:
621 g = OGfxEffect::EllipticGradient; 616 g = OGfxEffect::EllipticGradient;
622 break; 617 break;
623 default: 618 default:
624 g = OGfxEffect::DiagonalGradient; 619 g = OGfxEffect::DiagonalGradient;
625 break; 620 break;
626 } 621 }
627 OGfxEffect::blend( *pixmaps[ widget ], blends[ widget ], *grLowColors[ widget ], 622 OGfxEffect::blend( *pixmaps[ widget ], blends[ widget ], *grLowColors[ widget ],
628 g, false ); 623 g, false );
629 return ( pixmaps[ widget ] ); 624 return ( pixmaps[ widget ] );
630} 625}
631 626
632OThemePixmap* OThemeBase::gradient( int w, int h, WidgetType widget ) 627OThemePixmap* OThemeBase::gradient( int w, int h, WidgetType widget )
633{ 628{
634 if ( gradients[ widget ] == GrVertical ) { 629 if ( gradients[ widget ] == GrVertical ) {
635 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->height() != h ) { 630 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->height() != h ) {
636 OThemePixmap * cachePix = cache->verticalPixmap( h, widget ); 631 OThemePixmap * cachePix = cache->verticalPixmap( h, widget );
637 if ( cachePix ) { 632 if ( cachePix ) {
638 cachePix = new OThemePixmap( *cachePix ); 633 cachePix = new OThemePixmap( *cachePix );
639 if ( pixmaps[ widget ] ) 634 if ( pixmaps[ widget ] )
640 cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale, 635 cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale,
641 widget ); 636 widget );
642 pixmaps[ widget ] = cachePix; 637 pixmaps[ widget ] = cachePix;
643 } 638 }
644 else { 639 else {
645 if ( pixmaps[ widget ] ) 640 if ( pixmaps[ widget ] )
646 cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale, 641 cache->insert( pixmaps[ widget ], OThemeCache::VerticalScale,
647 widget ); 642 widget );
648 pixmaps[ widget ] = new OThemePixmap; 643 pixmaps[ widget ] = new OThemePixmap;
649 pixmaps[ widget ] ->resize( w, h ); 644 pixmaps[ widget ] ->resize( w, h );
650 OGfxEffect::gradient( *pixmaps[ widget ], *grHighColors[ widget ], 645 OGfxEffect::gradient( *pixmaps[ widget ], *grHighColors[ widget ],
651 *grLowColors[ widget ], 646 *grLowColors[ widget ],
652 OGfxEffect::VerticalGradient ); 647 OGfxEffect::VerticalGradient );
653 } 648 }
654 } 649 }
655 } 650 }
656 else if ( gradients[ widget ] == GrHorizontal ) { 651 else if ( gradients[ widget ] == GrHorizontal ) {
657 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w ) { 652 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w ) {
658 OThemePixmap * cachePix = cache->horizontalPixmap( w, widget ); 653 OThemePixmap * cachePix = cache->horizontalPixmap( w, widget );
659 if ( cachePix ) { 654 if ( cachePix ) {
660 cachePix = new OThemePixmap( *cachePix ); 655 cachePix = new OThemePixmap( *cachePix );
661 if ( pixmaps[ widget ] ) 656 if ( pixmaps[ widget ] )
662 cache->insert( pixmaps[ widget ], 657 cache->insert( pixmaps[ widget ],
663 OThemeCache::HorizontalScale, widget ); 658 OThemeCache::HorizontalScale, widget );
664 pixmaps[ widget ] = cachePix; 659 pixmaps[ widget ] = cachePix;
665 } 660 }
666 else { 661 else {
667 if ( pixmaps[ widget ] ) 662 if ( pixmaps[ widget ] )
668 cache->insert( pixmaps[ widget ], 663 cache->insert( pixmaps[ widget ],
669 OThemeCache::HorizontalScale, widget ); 664 OThemeCache::HorizontalScale, widget );
670 pixmaps[ widget ] = new OThemePixmap; 665 pixmaps[ widget ] = new OThemePixmap;
671 pixmaps[ widget ] ->resize( w, h ); 666 pixmaps[ widget ] ->resize( w, h );
672 OGfxEffect::gradient( *pixmaps[ widget ], *grHighColors[ widget ], 667 OGfxEffect::gradient( *pixmaps[ widget ], *grHighColors[ widget ],
673 *grLowColors[ widget ], 668 *grLowColors[ widget ],
674 OGfxEffect::HorizontalGradient ); 669 OGfxEffect::HorizontalGradient );
675 } 670 }
676 } 671 }
677 } 672 }
678 else if ( gradients[ widget ] == GrReverseBevel ) { 673 else if ( gradients[ widget ] == GrReverseBevel ) {
679 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w || 674 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w ||
680 pixmaps[ widget ] ->height() != h ) { 675 pixmaps[ widget ] ->height() != h ) {
681 OThemePixmap * cachePix = cache->pixmap( w, h, widget ); 676 OThemePixmap * cachePix = cache->pixmap( w, h, widget );
682 if ( cachePix ) { 677 if ( cachePix ) {
683 cachePix = new OThemePixmap( *cachePix ); 678 cachePix = new OThemePixmap( *cachePix );
684 if ( pixmaps[ widget ] ) 679 if ( pixmaps[ widget ] )
685 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, 680 cache->insert( pixmaps[ widget ], OThemeCache::FullScale,
686 widget ); 681 widget );
687 pixmaps[ widget ] = cachePix; 682 pixmaps[ widget ] = cachePix;
688 } 683 }
689 else { 684 else {
690 if ( pixmaps[ widget ] ) 685 if ( pixmaps[ widget ] )
691 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, 686 cache->insert( pixmaps[ widget ], OThemeCache::FullScale,
692 widget ); 687 widget );
693 pixmaps[ widget ] = new OThemePixmap; 688 pixmaps[ widget ] = new OThemePixmap;
694 pixmaps[ widget ] ->resize( w, h ); 689 pixmaps[ widget ] ->resize( w, h );
695 690
696 QPixmap s; 691 QPixmap s;
697 int offset = decoWidth( widget ); 692 int offset = decoWidth( widget );
698 s.resize( w - offset * 2, h - offset * 2 ); 693 s.resize( w - offset * 2, h - offset * 2 );
699 QColor lc( *grLowColors[ widget ] ); 694 QColor lc( *grLowColors[ widget ] );
700 QColor hc( *grHighColors[ widget ] ); 695 QColor hc( *grHighColors[ widget ] );
701 if ( bevelContrast( widget ) ) { 696 if ( bevelContrast( widget ) ) {
702 int bc = bevelContrast( widget ); 697 int bc = bevelContrast( widget );
703 // want single increments, not factors like light()/dark() 698 // want single increments, not factors like light()/dark()
704 lc.setRgb( lc.red() - bc, lc.green() - bc, lc.blue() - bc ); 699 lc.setRgb( lc.red() - bc, lc.green() - bc, lc.blue() - bc );
705 hc.setRgb( hc.red() + bc, hc.green() + bc, hc.blue() + bc ); 700 hc.setRgb( hc.red() + bc, hc.green() + bc, hc.blue() + bc );
706 } 701 }
707 OGfxEffect::gradient( *pixmaps[ widget ], 702 OGfxEffect::gradient( *pixmaps[ widget ],
708 lc, hc, 703 lc, hc,
709 OGfxEffect::DiagonalGradient ); 704 OGfxEffect::DiagonalGradient );
710 OGfxEffect::gradient( s, *grHighColors[ widget ], 705 OGfxEffect::gradient( s, *grHighColors[ widget ],
711 *grLowColors[ widget ], 706 *grLowColors[ widget ],
712 OGfxEffect::DiagonalGradient ); 707 OGfxEffect::DiagonalGradient );
713 bitBlt( pixmaps[ widget ], offset, offset, &s, 0, 0, w - offset * 2, 708 bitBlt( pixmaps[ widget ], offset, offset, &s, 0, 0, w - offset * 2,
714 h - offset * 2, Qt::CopyROP ); 709 h - offset * 2, Qt::CopyROP );
715 } 710 }
716 } 711 }
717 } 712 }
718 else { 713 else {
719 OGfxEffect::GradientType g; 714 OGfxEffect::GradientType g;
720 switch ( gradients[ widget ] ) { 715 switch ( gradients[ widget ] ) {
721 case GrPyramid: 716 case GrPyramid:
722 g = OGfxEffect::PyramidGradient; 717 g = OGfxEffect::PyramidGradient;
723 break; 718 break;
724 case GrRectangle: 719 case GrRectangle:
725 g = OGfxEffect::RectangleGradient; 720 g = OGfxEffect::RectangleGradient;
726 break; 721 break;
727 case GrElliptic: 722 case GrElliptic:
728 g = OGfxEffect::EllipticGradient; 723 g = OGfxEffect::EllipticGradient;
729 break; 724 break;
730 default: 725 default:
731 g = OGfxEffect::DiagonalGradient; 726 g = OGfxEffect::DiagonalGradient;
732 break; 727 break;
733 } 728 }
734 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w || 729 if ( !pixmaps[ widget ] || pixmaps[ widget ] ->width() != w ||
735 pixmaps[ widget ] ->height() != h ) { 730 pixmaps[ widget ] ->height() != h ) {
736 OThemePixmap * cachePix = cache->pixmap( w, h, widget ); 731 OThemePixmap * cachePix = cache->pixmap( w, h, widget );
737 if ( cachePix ) { 732 if ( cachePix ) {
738 cachePix = new OThemePixmap( *cachePix ); 733 cachePix = new OThemePixmap( *cachePix );
739 if ( pixmaps[ widget ] ) 734 if ( pixmaps[ widget ] )
740 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, 735 cache->insert( pixmaps[ widget ], OThemeCache::FullScale,
741 widget ); 736 widget );
742 pixmaps[ widget ] = cachePix; 737 pixmaps[ widget ] = cachePix;
743 } 738 }
744 else { 739 else {
745 if ( pixmaps[ widget ] ) 740 if ( pixmaps[ widget ] )
746 cache->insert( pixmaps[ widget ], OThemeCache::FullScale, 741 cache->insert( pixmaps[ widget ], OThemeCache::FullScale,
747 widget ); 742 widget );
748 pixmaps[ widget ] = new OThemePixmap; 743 pixmaps[ widget ] = new OThemePixmap;
749 pixmaps[ widget ] ->resize( w, h ); 744 pixmaps[ widget ] ->resize( w, h );
750 OGfxEffect::gradient( *pixmaps[ widget ], *grHighColors[ widget ], 745 OGfxEffect::gradient( *pixmaps[ widget ], *grHighColors[ widget ],
751 *grLowColors[ widget ], g ); 746 *grLowColors[ widget ], g );
752 } 747 }
753 } 748 }
754 } 749 }
755 return ( pixmaps[ widget ] ); 750 return ( pixmaps[ widget ] );
756} 751}
757 752
758OThemePixmap* OThemeBase::scalePixmap( int w, int h, WidgetType widget ) 753OThemePixmap* OThemeBase::scalePixmap( int w, int h, WidgetType widget )
759{ 754{
760 755
761 if ( gradients[ widget ] && blends[ widget ] == 0.0 ) 756 if ( gradients[ widget ] && blends[ widget ] == 0.0 )
762 return ( gradient( w, h, widget ) ); 757 return ( gradient( w, h, widget ) );
763 758
764 return ( scale( w, h, widget ) ); 759 return ( scale( w, h, widget ) );
765} 760}
766 761
767QColorGroup* OThemeBase::makeColorGroup( QColor &fg, QColor &bg, 762QColorGroup* OThemeBase::makeColorGroup( QColor &fg, QColor &bg,
768 Qt::GUIStyle ) 763 Qt::GUIStyle )
769{ 764{
770 if ( shading == Motif ) { 765 if ( shading == Motif ) {
771 int highlightVal, lowlightVal; 766 int highlightVal, lowlightVal;
772 highlightVal = 100 + ( 2* /*KGlobalSettings::contrast()*/ 3 + 4 ) * 16 / 10; 767 highlightVal = 100 + ( 2* /*KGlobalSettings::contrast()*/ 3 + 4 ) * 16 / 10;
773 lowlightVal = 100 + ( ( 2* /*KGlobalSettings::contrast()*/ 3 + 4 ) * 10 ); 768 lowlightVal = 100 + ( ( 2* /*KGlobalSettings::contrast()*/ 3 + 4 ) * 10 );
774 return ( new QColorGroup( fg, bg, bg.light( highlightVal ), 769 return ( new QColorGroup( fg, bg, bg.light( highlightVal ),
775 bg.dark( lowlightVal ), bg.dark( 120 ), 770 bg.dark( lowlightVal ), bg.dark( 120 ),
776 fg, qApp->palette().normal().base() ) ); 771 fg, qApp->palette().normal().base() ) );
777 } 772 }
778 else 773 else
779 return ( new QColorGroup( fg, bg, bg.light( 150 ), bg.dark(), 774 return ( new QColorGroup( fg, bg, bg.light( 150 ), bg.dark(),
780 bg.dark( 120 ), fg, 775 bg.dark( 120 ), fg,
781 qApp->palette().normal().base() ) ); 776 qApp->palette().normal().base() ) );
782} 777}
783 778
784static QColor strToColor ( const QString &str ) 779static QColor strToColor ( const QString &str )
785{ 780{
786 QString str2 = str. stripWhiteSpace ( ); 781 QString str2 = str. stripWhiteSpace ( );
787 782
788 if ( str2 [0] == '#' ) 783 if ( str2 [0] == '#' )
789 return QColor ( str2 ); 784 return QColor ( str2 );
790 else { 785 else {
791 QStringList sl = QStringList::split ( ',', str2 ); 786 QStringList sl = QStringList::split ( ',', str2 );
792 787
793 if ( sl. count ( ) >= 3 ) 788 if ( sl. count ( ) >= 3 )
794 return QColor ( sl [0]. toInt ( ), sl [1]. toInt ( ), sl [2]. toInt ( )); 789 return QColor ( sl [0]. toInt ( ), sl [1]. toInt ( ), sl [2]. toInt ( ));
795 } 790 }
796 return QColor ( 0, 0, 0 ); 791 return QColor ( 0, 0, 0 );
797} 792}
798 793
799 794
800 795
801void OThemeBase::applyMiscResourceGroup( Config *config ) 796void OThemeBase::applyMiscResourceGroup( Config *config )
802{ 797{
803 config-> setGroup ( "Misc" ); 798 config-> setGroup ( "Misc" );
804 QString tmpStr; 799 QString tmpStr;
805 800
806 tmpStr = config->readEntry( "SButtonPosition" ); 801 tmpStr = config->readEntry( "SButtonPosition" );
807 if ( tmpStr == "BottomLeft" ) 802 if ( tmpStr == "BottomLeft" )
808 sbPlacement = SBBottomLeft; 803 sbPlacement = SBBottomLeft;
809 else if ( tmpStr == "BottomRight" ) 804 else if ( tmpStr == "BottomRight" )
810 sbPlacement = SBBottomRight; 805 sbPlacement = SBBottomRight;
811 else { 806 else {
812 if ( tmpStr != "Opposite" && !tmpStr.isEmpty() ) 807 if ( tmpStr != "Opposite" && !tmpStr.isEmpty() )
813 qDebug ( "OThemeBase: Unrecognized sb button option %s, using Opposite.\n", tmpStr.ascii() ); 808 qDebug ( "OThemeBase: Unrecognized sb button option %s, using Opposite.\n", tmpStr.ascii() );
814 sbPlacement = SBOpposite; 809 sbPlacement = SBOpposite;
815 } 810 }
816 tmpStr = config->readEntry( "ArrowType" ); 811 tmpStr = config->readEntry( "ArrowType" );
817 if ( tmpStr == "Small" ) 812 if ( tmpStr == "Small" )
818 arrowStyle = SmallArrow; 813 arrowStyle = SmallArrow;
819 else if ( tmpStr == "3D" ) 814 else if ( tmpStr == "3D" )
820 arrowStyle = MotifArrow; 815 arrowStyle = MotifArrow;
821 else { 816 else {
822 if ( tmpStr != "Normal" && !tmpStr.isEmpty() ) 817 if ( tmpStr != "Normal" && !tmpStr.isEmpty() )
823 qDebug ( "OThemeBase: Unrecognized arrow option %s, using Normal.\n", tmpStr.ascii() ); 818 qDebug ( "OThemeBase: Unrecognized arrow option %s, using Normal.\n", tmpStr.ascii() );
824 arrowStyle = LargeArrow; 819 arrowStyle = LargeArrow;
825 } 820 }
826 tmpStr = config->readEntry( "ShadeStyle" ); 821 tmpStr = config->readEntry( "ShadeStyle" );
827 if ( tmpStr == "Motif" ) 822 if ( tmpStr == "Motif" )
828 shading = Motif; 823 shading = Motif;
829 else if ( tmpStr == "Next" ) 824 else if ( tmpStr == "Next" )
830 shading = Next; 825 shading = Next;
831 else if ( tmpStr == "KDE" ) 826 else if ( tmpStr == "KDE" )
832 shading = KDE; 827 shading = KDE;
833 else 828 else
834 shading = Windows; 829 shading = Windows;
835 830
836 defaultFrame = config->readNumEntry( "FrameWidth", 2 ); 831 defaultFrame = config->readNumEntry( "FrameWidth", 2 );
837 cacheSize = config->readNumEntry( "Cache", 1024 ); 832 cacheSize = config->readNumEntry( "Cache", 1024 );
838 sbExtent = config->readNumEntry( "ScrollBarExtent", 16 ); 833 sbExtent = config->readNumEntry( "ScrollBarExtent", 16 );
839 834
840 config-> setGroup ( "General" ); 835 config-> setGroup ( "General" );
841 836
842 if ( config-> hasKey ( "foreground" )) fgcolor = strToColor ( config-> readEntry ( "foreground" )); 837 if ( config-> hasKey ( "foreground" )) fgcolor = strToColor ( config-> readEntry ( "foreground" ));
843 if ( config-> hasKey ( "background" )) bgcolor = strToColor ( config-> readEntry ( "background" )); 838 if ( config-> hasKey ( "background" )) bgcolor = strToColor ( config-> readEntry ( "background" ));
844 if ( config-> hasKey ( "selectForeground" )) selfgcolor = strToColor ( config-> readEntry ( "selectForeground" )); 839 if ( config-> hasKey ( "selectForeground" )) selfgcolor = strToColor ( config-> readEntry ( "selectForeground" ));
845 if ( config-> hasKey ( "selectBackground" )) selbgcolor = strToColor ( config-> readEntry ( "selectBackground" )); 840 if ( config-> hasKey ( "selectBackground" )) selbgcolor = strToColor ( config-> readEntry ( "selectBackground" ));
846 if ( config-> hasKey ( "windowForeground" )) winfgcolor = strToColor ( config-> readEntry ( "windowForeground" )); 841 if ( config-> hasKey ( "windowForeground" )) winfgcolor = strToColor ( config-> readEntry ( "windowForeground" ));
847 if ( config-> hasKey ( "windowBackground" )) winbgcolor = strToColor ( config-> readEntry ( "windowBackground" )); 842 if ( config-> hasKey ( "windowBackground" )) winbgcolor = strToColor ( config-> readEntry ( "windowBackground" ));
848} 843}
849 844
850void OThemeBase::readMiscResourceGroup() 845void OThemeBase::readMiscResourceGroup()
851{} 846{}
852 847
853void OThemeBase::applyResourceGroup( Config *config, int i, QString *copyfrom, QString *pixnames, QString *brdnames ) 848void OThemeBase::applyResourceGroup( Config *config, int i, QString *copyfrom, QString *pixnames, QString *brdnames )
854{ 849{
855 QString tmpStr; 850 QString tmpStr;
856 851
857 config-> setGroup ( widgetEntries [ i ] ); 852 config-> setGroup ( widgetEntries [ i ] );
858 853
859 tmpStr = config->readEntry( "CopyWidget", "" ); 854 tmpStr = config->readEntry( "CopyWidget", "" );
860 copyfrom [ i ] = tmpStr; 855 copyfrom [ i ] = tmpStr;
861 if ( !tmpStr.isEmpty() ) 856 if ( !tmpStr.isEmpty() )
862 return ; 857 return ;
863 858
864 // Scale hint 859 // Scale hint
865 tmpStr = config->readEntry( "Scale" ); 860 tmpStr = config->readEntry( "Scale" );
866 if ( tmpStr == "Full" ) 861 if ( tmpStr == "Full" )
867 scaleHints [ i ] = FullScale; 862 scaleHints [ i ] = FullScale;
868 else if ( tmpStr == "Horizontal" ) 863 else if ( tmpStr == "Horizontal" )
869 scaleHints [ i ] = HorizontalScale; 864 scaleHints [ i ] = HorizontalScale;
870 else if ( tmpStr == "Vertical" ) 865 else if ( tmpStr == "Vertical" )
871 scaleHints [ i ] = VerticalScale; 866 scaleHints [ i ] = VerticalScale;
872 else { 867 else {
873 if ( tmpStr != "Tile" && !tmpStr.isEmpty() ) 868 if ( tmpStr != "Tile" && !tmpStr.isEmpty() )
874 qDebug ( "OThemeBase: Unrecognized scale option %s, using Tile.\n", tmpStr.ascii() ); 869 qDebug ( "OThemeBase: Unrecognized scale option %s, using Tile.\n", tmpStr.ascii() );
875 scaleHints [ i ] = TileScale; 870 scaleHints [ i ] = TileScale;
876 } 871 }
877 872
878 873
879 // Gradient type 874 // Gradient type
880 tmpStr = config->readEntry( "Gradient" ); 875 tmpStr = config->readEntry( "Gradient" );
881 if ( tmpStr == "Diagonal" ) 876 if ( tmpStr == "Diagonal" )
882 gradients [ i ] = GrDiagonal; 877 gradients [ i ] = GrDiagonal;
883 else if ( tmpStr == "Horizontal" ) 878 else if ( tmpStr == "Horizontal" )
884 gradients [ i ] = GrHorizontal; 879 gradients [ i ] = GrHorizontal;
885 else if ( tmpStr == "Vertical" ) 880 else if ( tmpStr == "Vertical" )
886 gradients [ i ] = GrVertical; 881 gradients [ i ] = GrVertical;
887 else if ( tmpStr == "Pyramid" ) 882 else if ( tmpStr == "Pyramid" )
888 gradients [ i ] = GrPyramid; 883 gradients [ i ] = GrPyramid;
889 else if ( tmpStr == "Rectangle" ) 884 else if ( tmpStr == "Rectangle" )
890 gradients [ i ] = GrRectangle; 885 gradients [ i ] = GrRectangle;
891 else if ( tmpStr == "Elliptic" ) 886 else if ( tmpStr == "Elliptic" )
892 gradients [ i ] = GrElliptic; 887 gradients [ i ] = GrElliptic;
893 else if ( tmpStr == "ReverseBevel" ) 888 else if ( tmpStr == "ReverseBevel" )
894 gradients [ i ] = GrReverseBevel; 889 gradients [ i ] = GrReverseBevel;
895 else { 890 else {
896 if ( tmpStr != "None" && !tmpStr.isEmpty() ) 891 if ( tmpStr != "None" && !tmpStr.isEmpty() )
897 qDebug ( "OThemeBase: Unrecognized gradient option %s, using None.\n", tmpStr.ascii() ); 892 qDebug ( "OThemeBase: Unrecognized gradient option %s, using None.\n", tmpStr.ascii() );
898 gradients [ i ] = GrNone; 893 gradients [ i ] = GrNone;
899 } 894 }
900 895
901 // Blend intensity 896 // Blend intensity
902 blends[ i ] = config->readEntry( "BlendIntensity", "0.0" ).toDouble(); 897 blends[ i ] = config->readEntry( "BlendIntensity", "0.0" ).toDouble();
903 898
904 // Bevel contrast 899 // Bevel contrast
905 bContrasts[ i ] = config->readNumEntry( "BevelContrast", 0 ); 900 bContrasts[ i ] = config->readNumEntry( "BevelContrast", 0 );
906 901
907 // Border width 902 // Border width
908 borders [ i ] = config->readNumEntry( "Border", 1 ); 903 borders [ i ] = config->readNumEntry( "Border", 1 );
909 904
910 // Highlight width 905 // Highlight width
911 highlights [ i ] = config->readNumEntry( "Highlight", 1 ); 906 highlights [ i ] = config->readNumEntry( "Highlight", 1 );
912 907
913 // Gradient low color or blend background 908 // Gradient low color or blend background
914 if ( config->hasKey( "GradientLow" ) && ( gradients[ i ] != GrNone || blends[ i ] != 0.0 )) 909 if ( config->hasKey( "GradientLow" ) && ( gradients[ i ] != GrNone || blends[ i ] != 0.0 ))
915 grLowColors[ i ] = new QColor( strToColor ( config->readEntry( "GradientLow", qApp->palette().normal().background().name() ))); 910 grLowColors[ i ] = new QColor( strToColor ( config->readEntry( "GradientLow", qApp->palette().normal().background().name() )));
916 else 911 else
917 grLowColors[ i ] = NULL; 912 grLowColors[ i ] = NULL;
918 913
919 914
920 // Gradient high color 915 // Gradient high color
921 if ( config->hasKey( "GradientHigh" ) && ( gradients[ i ] != GrNone )) 916 if ( config->hasKey( "GradientHigh" ) && ( gradients[ i ] != GrNone ))
922 grHighColors[ i ] = new QColor( strToColor ( config->readEntry( "GradientHigh", qApp->palette().normal().background().name() ))); 917 grHighColors[ i ] = new QColor( strToColor ( config->readEntry( "GradientHigh", qApp->palette().normal().background().name() )));
923 else 918 else
924 grHighColors[ i ] = NULL; 919 grHighColors[ i ] = NULL;
925 920
926 // Extended color attributes 921 // Extended color attributes
927 if ( config->hasKey( "Foreground" ) || config->hasKey( "Background" ) ) { 922 if ( config->hasKey( "Foreground" ) || config->hasKey( "Background" ) ) {
928 QColor bg = strToColor( config->readEntry( "Background", qApp->palette().normal().background().name() )); 923 QColor bg = strToColor( config->readEntry( "Background", qApp->palette().normal().background().name() ));
929 QColor fg = strToColor( config->readEntry( "Foreground", qApp->palette().normal().foreground().name() )); 924 QColor fg = strToColor( config->readEntry( "Foreground", qApp->palette().normal().foreground().name() ));
930 925
931 colors[ i ] = makeColorGroup( fg, bg, Qt::WindowsStyle ); 926 colors[ i ] = makeColorGroup( fg, bg, Qt::WindowsStyle );
932 } 927 }
933 else 928 else
934 colors[ i ] = NULL; 929 colors[ i ] = NULL;
935 930
936 // Pixmap 931 // Pixmap
937 tmpStr = config->readEntry( "Pixmap", "" ); 932 tmpStr = config->readEntry( "Pixmap", "" );
938 pixnames[ i ] = tmpStr; 933 pixnames[ i ] = tmpStr;
939 duplicate[ i ] = false; 934 duplicate[ i ] = false;
940 pixmaps[ i ] = NULL; 935 pixmaps[ i ] = NULL;
941 images[ i ] = NULL; 936 images[ i ] = NULL;
942 937
943 938
944 // Pixmap border 939 // Pixmap border
945 tmpStr = config->readEntry( "PixmapBorder", "" ); 940 tmpStr = config->readEntry( "PixmapBorder", "" );
946 brdnames[ i ] = tmpStr; 941 brdnames[ i ] = tmpStr;
947 pbDuplicate[ i ] = false; 942 pbDuplicate[ i ] = false;
948 pbPixmaps[ i ] = NULL; 943 pbPixmaps[ i ] = NULL;
949 pbWidth[ i ] = 0; 944 pbWidth[ i ] = 0;
950 if ( !tmpStr.isEmpty() ) { 945 if ( !tmpStr.isEmpty() ) {
951 pbWidth[ i ] = config->readNumEntry( "PixmapBWidth", 0 ); 946 pbWidth[ i ] = config->readNumEntry( "PixmapBWidth", 0 );
952 if ( pbWidth[ i ] == 0 ) { 947 if ( pbWidth[ i ] == 0 ) {
953 qDebug ( "OThemeBase: No border width specified for pixmapped border widget %s\n", widgetEntries[ i ] ); 948 qDebug ( "OThemeBase: No border width specified for pixmapped border widget %s\n", widgetEntries[ i ] );
954 qDebug ( "OThemeBase: Using default of 2.\n" ); 949 qDebug ( "OThemeBase: Using default of 2.\n" );
955 pbWidth[ i ] = 2; 950 pbWidth[ i ] = 2;
956 } 951 }
957 } 952 }
958 953
959 954
960 // Various widget specific settings. This was more efficent when bunched 955 // Various widget specific settings. This was more efficent when bunched
961 // together in the misc group, but this makes an easier to read config. 956 // together in the misc group, but this makes an easier to read config.
962 if ( i == SliderGroove ) 957 if ( i == SliderGroove )
963 roundedSlider = config->readBoolEntry( "SmallGroove", false ); 958 roundedSlider = config->readBoolEntry( "SmallGroove", false );
964 else if ( i == ActiveTab ) { 959 else if ( i == ActiveTab ) {
965 aTabLine = config->readBoolEntry( "BottomLine", true ); 960 aTabLine = config->readBoolEntry( "BottomLine", true );
966 } 961 }
967 else if ( i == InactiveTab ) { 962 else if ( i == InactiveTab ) {
968 iTabLine = config->readBoolEntry( "BottomLine", true ); 963 iTabLine = config->readBoolEntry( "BottomLine", true );
969 } 964 }
970 else if ( i == Splitter ) 965 else if ( i == Splitter )
971 splitterWidth = config->readNumEntry( "Width", 10 ); 966 splitterWidth = config->readNumEntry( "Width", 10 );
972 else if ( i == ComboBox || i == ComboBoxDown ) { 967 else if ( i == ComboBox || i == ComboBoxDown ) {
973 roundedCombo = config->readBoolEntry( "Round", false ); 968 roundedCombo = config->readBoolEntry( "Round", false );
974 } 969 }
975 else if ( i == PushButton || i == PushButtonDown ) { 970 else if ( i == PushButton || i == PushButtonDown ) {
976 btnXShift = config->readNumEntry( "XShift", 0 ); 971 btnXShift = config->readNumEntry( "XShift", 0 );
977 btnYShift = config->readNumEntry( "YShift", 0 ); 972 btnYShift = config->readNumEntry( "YShift", 0 );
978 focus3D = config->readBoolEntry( "3DFocusRect", false ); 973 focus3D = config->readBoolEntry( "3DFocusRect", false );
979 focus3DOffset = config->readBoolEntry( "3DFocusOffset", 0 ); 974 focus3DOffset = config->readBoolEntry( "3DFocusOffset", 0 );
980 roundedButton = config->readBoolEntry( "Round", false ); 975 roundedButton = config->readBoolEntry( "Round", false );
981 } 976 }
982} 977}
983 978
984 979
985void OThemeBase::readResourceGroup( int i, QString *copyfrom, QString *pixnames, QString *brdnames, 980void OThemeBase::readResourceGroup( int i, QString *copyfrom, QString *pixnames, QString *brdnames,
986 bool *loadArray ) 981 bool *loadArray )
987{ 982{
988 if ( loadArray[ i ] == true ) { 983 if ( loadArray[ i ] == true ) {
989 return ; // already been preloaded. 984 return ; // already been preloaded.
990 } 985 }
991 986
992 int tmpVal; 987 int tmpVal;
993 QString tmpStr; 988 QString tmpStr;
994 989
995 tmpStr = copyfrom [ i ]; 990 tmpStr = copyfrom [ i ];
996 if ( !tmpStr.isEmpty() ) { // Duplicate another widget's config 991 if ( !tmpStr.isEmpty() ) { // Duplicate another widget's config
997 int sIndex; 992 int sIndex;
998 loadArray[ i ] = true; 993 loadArray[ i ] = true;
999 for ( sIndex = 0; sIndex < WIDGETS; ++sIndex ) { 994 for ( sIndex = 0; sIndex < WIDGETS; ++sIndex ) {
1000 if ( tmpStr == widgetEntries[ sIndex ] ) { 995 if ( tmpStr == widgetEntries[ sIndex ] ) {
1001 if ( !loadArray[ sIndex ] ) // hasn't been loaded yet 996 if ( !loadArray[ sIndex ] ) // hasn't been loaded yet
1002 readResourceGroup( sIndex, copyfrom, pixnames, brdnames, 997 readResourceGroup( sIndex, copyfrom, pixnames, brdnames,
1003 loadArray ); 998 loadArray );
1004 break; 999 break;
1005 } 1000 }
1006 } 1001 }
1007 if ( loadArray[ sIndex ] ) { 1002 if ( loadArray[ sIndex ] ) {
1008 copyWidgetConfig( sIndex, i, pixnames, brdnames ); 1003 copyWidgetConfig( sIndex, i, pixnames, brdnames );
1009 } 1004 }
1010 else 1005 else
1011 qDebug ( "OThemeBase: Unable to identify source widget for %s\n", widgetEntries[ i ] ); 1006 qDebug ( "OThemeBase: Unable to identify source widget for %s\n", widgetEntries[ i ] );
1012 return ; 1007 return ;
1013 } 1008 }
1014 // special inheritance for disabled arrows (these are tri-state unlike 1009 // special inheritance for disabled arrows (these are tri-state unlike
1015 // the rest of what we handle). 1010 // the rest of what we handle).
1016 for ( tmpVal = DisArrowUp; tmpVal <= DisArrowRight; ++tmpVal ) { 1011 for ( tmpVal = DisArrowUp; tmpVal <= DisArrowRight; ++tmpVal ) {
1017 if ( tmpVal == i ) { 1012 if ( tmpVal == i ) {
1018 tmpStr = pixnames [ i ]; 1013 tmpStr = pixnames [ i ];
1019 if ( tmpStr.isEmpty() ) { 1014 if ( tmpStr.isEmpty() ) {
1020 copyWidgetConfig( ArrowUp + ( tmpVal - DisArrowUp ), i, pixnames, 1015 copyWidgetConfig( ArrowUp + ( tmpVal - DisArrowUp ), i, pixnames,
1021 brdnames ); 1016 brdnames );
1022 return ; 1017 return ;
1023 } 1018 }
1024 } 1019 }
1025 } 1020 }
1026 1021
1027 // Pixmap 1022 // Pixmap
1028 int existing; 1023 int existing;
1029 // Scan for duplicate pixmaps(two identical pixmaps, tile scale, no blend, 1024 // Scan for duplicate pixmaps(two identical pixmaps, tile scale, no blend,
1030 // no pixmapped border) 1025 // no pixmapped border)
1031 if ( !pixnames [ i ].isEmpty() ) { 1026 if ( !pixnames [ i ].isEmpty() ) {
1032 for ( existing = 0; existing < i; ++existing ) { 1027 for ( existing = 0; existing < i; ++existing ) {
1033 if ( pixnames[ i ] == pixnames[ existing ] && scaleHints[ i ] == TileScale && 1028 if ( pixnames[ i ] == pixnames[ existing ] && scaleHints[ i ] == TileScale &&
1034 scaleHints[ existing ] == TileScale && blends[ existing ] == 0.0 && 1029 scaleHints[ existing ] == TileScale && blends[ existing ] == 0.0 &&
1035 blends[ i ] == 0.0 ) { 1030 blends[ i ] == 0.0 ) {
1036 pixmaps[ i ] = pixmaps[ existing ]; 1031 pixmaps[ i ] = pixmaps[ existing ];
1037 duplicate[ i ] = true; 1032 duplicate[ i ] = true;
1038 break; 1033 break;
1039 } 1034 }
1040 } 1035 }
1041 } 1036 }
1042 // load 1037 // load
1043 if ( !duplicate[ i ] && !pixnames[ i ].isEmpty() ) { 1038 if ( !duplicate[ i ] && !pixnames[ i ].isEmpty() ) {
1044 pixmaps[ i ] = loadPixmap( pixnames[ i ] ); 1039 pixmaps[ i ] = loadPixmap( pixnames[ i ] );
1045 // load and save images for scaled/blended widgets for speed. 1040 // load and save images for scaled/blended widgets for speed.
1046 if ( scaleHints[ i ] == TileScale && blends[ i ] == 0.0 ) 1041 if ( scaleHints[ i ] == TileScale && blends[ i ] == 0.0 )
1047 images[ i ] = NULL; 1042 images[ i ] = NULL;
1048 else 1043 else
1049 images[ i ] = loadImage( pixnames[ i ] ); 1044 images[ i ] = loadImage( pixnames[ i ] );
1050 } 1045 }
1051 1046
1052 // Pixmap border 1047 // Pixmap border
1053 if ( !brdnames [ i ]. isEmpty () ) { 1048 if ( !brdnames [ i ]. isEmpty () ) {
1054 // duplicate check 1049 // duplicate check
1055 for ( existing = 0; existing < i; ++existing ) { 1050 for ( existing = 0; existing < i; ++existing ) {
1056 if ( brdnames [i] == brdnames[ existing ] ) { 1051 if ( brdnames [i] == brdnames[ existing ] ) {
1057 pbPixmaps[ i ] = pbPixmaps[ existing ]; 1052 pbPixmaps[ i ] = pbPixmaps[ existing ];
1058 pbDuplicate[ i ] = true; 1053 pbDuplicate[ i ] = true;
1059 break; 1054 break;
1060 } 1055 }
1061 } 1056 }
1062 } 1057 }
1063 // load 1058 // load
1064 if ( !pbDuplicate[ i ] && !brdnames[ i ].isEmpty() ) 1059 if ( !pbDuplicate[ i ] && !brdnames[ i ].isEmpty() )
1065 pbPixmaps[ i ] = loadPixmap( brdnames[ i ] ); 1060 pbPixmaps[ i ] = loadPixmap( brdnames[ i ] );
1066 1061
1067 if ( pbPixmaps[ i ] && !pbDuplicate[ i ] ) 1062 if ( pbPixmaps[ i ] && !pbDuplicate[ i ] )
1068 generateBorderPix( i ); 1063 generateBorderPix( i );
1069 1064
1070 loadArray[ i ] = true; 1065 loadArray[ i ] = true;
1071} 1066}
1072 1067
1073 1068
1074OThemePixmap::OThemePixmap( bool timer ) 1069OThemePixmap::OThemePixmap( bool timer )
1075 : QPixmap() 1070 : QPixmap()
1076{ 1071{
1077 if(timer){ 1072 if(timer){
1078 t = new QTime; 1073 t = new QTime;
1079 t->start(); 1074 t->start();
1080 } 1075 }
1081 else 1076 else
1082 t = NULL; 1077 t = NULL;
1083 int i; 1078 int i;
1084 for ( i = 0; i < 8; ++i ) 1079 for ( i = 0; i < 8; ++i )
1085 b[ i ] = NULL; 1080 b[ i ] = NULL;
1086} 1081}
1087 1082
1088OThemePixmap::OThemePixmap( const OThemePixmap &p ) 1083OThemePixmap::OThemePixmap( const OThemePixmap &p )
1089 : QPixmap( p ) 1084 : QPixmap( p )
1090{ 1085{
1091 if(p.t){ 1086 if(p.t){
1092 t = new QTime; 1087 t = new QTime;
1093 t->start(); 1088 t->start();
1094 } 1089 }
1095 else 1090 else
1096 t = NULL; 1091 t = NULL;
1097 int i; 1092 int i;
1098 for ( i = 0; i < 8; ++i ) 1093 for ( i = 0; i < 8; ++i )
1099 if ( p.b[ i ] ) 1094 if ( p.b[ i ] )
1100 b[ i ] = new QPixmap( *p.b[ i ] ); 1095 b[ i ] = new QPixmap( *p.b[ i ] );
1101 else 1096 else
1102 b[ i ] = NULL; 1097 b[ i ] = NULL;
1103} 1098}
1104 1099
1105 1100
1106 1101
1107OThemePixmap::~OThemePixmap() 1102OThemePixmap::~OThemePixmap()
1108{ 1103{
1109 if(t) 1104 if(t)
1110 delete t; 1105 delete t;
1111 int i; 1106 int i;
1112 for ( i = 0; i < 8; ++i ) 1107 for ( i = 0; i < 8; ++i )
1113 if ( b[ i ] ) 1108 if ( b[ i ] )
1114 delete b[ i ]; 1109 delete b[ i ];
1115} 1110}
1116 1111
1117OThemeCache::OThemeCache( int maxSize, QObject *parent, const char *name ) 1112OThemeCache::OThemeCache( int maxSize, QObject *parent, const char *name )
1118 : QObject( parent, name ) 1113 : QObject( parent, name )
1119{ 1114{
1120 cache.setMaxCost( maxSize * 1024 ); 1115 cache.setMaxCost( maxSize * 1024 );
1121 cache.setAutoDelete( true ); 1116 cache.setAutoDelete( true );
1122 flushTimer.start(300000); // 5 minutes 1117 flushTimer.start(300000); // 5 minutes
1123 connect(&flushTimer, SIGNAL(timeout()), SLOT(flushTimeout())); 1118 connect(&flushTimer, SIGNAL(timeout()), SLOT(flushTimeout()));
1124} 1119}
1125 1120
1126void OThemeCache::flushTimeout() 1121void OThemeCache::flushTimeout()
1127{ 1122{
1128 QIntCacheIterator<OThemePixmap> it( cache ); 1123 QIntCacheIterator<OThemePixmap> it( cache );
1129 while ( it.current() ) { 1124 while ( it.current() ) {
1130 if ( it.current() ->isOld() ) 1125 if ( it.current() ->isOld() )
1131 cache.remove( it.currentKey() ); 1126 cache.remove( it.currentKey() );
1132 else 1127 else
1133 ++it; 1128 ++it;
1134 } 1129 }
1135} 1130}
1136 1131
1137OThemePixmap* OThemeCache::pixmap( int w, int h, int widgetID, bool border, 1132OThemePixmap* OThemeCache::pixmap( int w, int h, int widgetID, bool border,
1138 bool mask ) 1133 bool mask )
1139{ 1134{
1140 1135
1141 kthemeKey key; 1136 kthemeKey key;
1142 key.cacheKey = 0; // shut up, gcc 1137 key.cacheKey = 0; // shut up, gcc
1143 key.data.id = widgetID; 1138 key.data.id = widgetID;
1144 key.data.width = w; 1139 key.data.width = w;
1145 key.data.height = h; 1140 key.data.height = h;
1146 key.data.border = border; 1141 key.data.border = border;
1147 key.data.mask = mask; 1142 key.data.mask = mask;
1148 1143
1149 OThemePixmap *pix = cache.find( ( unsigned long ) key.cacheKey ); 1144 OThemePixmap *pix = cache.find( ( unsigned long ) key.cacheKey );
1150 if ( pix ) 1145 if ( pix )
1151 pix->updateAccessed(); 1146 pix->updateAccessed();
1152 return ( pix ); 1147 return ( pix );
1153} 1148}
1154 1149
1155OThemePixmap* OThemeCache::horizontalPixmap( int w, int widgetID ) 1150OThemePixmap* OThemeCache::horizontalPixmap( int w, int widgetID )
1156{ 1151{
1157 kthemeKey key; 1152 kthemeKey key;
1158 key.cacheKey = 0; // shut up, gcc 1153 key.cacheKey = 0; // shut up, gcc
1159 key.data.id = widgetID; 1154 key.data.id = widgetID;
1160 key.data.width = w; 1155 key.data.width = w;
1161 key.data.height = 0; 1156 key.data.height = 0;
1162 key.data.border = false; 1157 key.data.border = false;
1163 key.data.mask = false; 1158 key.data.mask = false;
1164 OThemePixmap *pix = cache.find( ( unsigned long ) key.cacheKey ); 1159 OThemePixmap *pix = cache.find( ( unsigned long ) key.cacheKey );
1165 if ( pix ) 1160 if ( pix )
1166 pix->updateAccessed(); 1161 pix->updateAccessed();
1167 return ( pix ); 1162 return ( pix );
1168} 1163}
1169 1164
1170OThemePixmap* OThemeCache::verticalPixmap( int h, int widgetID ) 1165OThemePixmap* OThemeCache::verticalPixmap( int h, int widgetID )
1171{ 1166{
1172 kthemeKey key; 1167 kthemeKey key;
1173 key.cacheKey = 0; // shut up, gcc 1168 key.cacheKey = 0; // shut up, gcc
1174 key.data.id = widgetID; 1169 key.data.id = widgetID;
1175 key.data.width = 0; 1170 key.data.width = 0;
1176 key.data.height = h; 1171 key.data.height = h;
1177 key.data.border = false; 1172 key.data.border = false;
1178 key.data.mask = false; 1173 key.data.mask = false;
1179 OThemePixmap *pix = cache.find( ( unsigned long ) key.cacheKey ); 1174 OThemePixmap *pix = cache.find( ( unsigned long ) key.cacheKey );
1180 if ( pix ) 1175 if ( pix )
1181 pix->updateAccessed(); 1176 pix->updateAccessed();
1182 return ( pix ); 1177 return ( pix );
1183} 1178}
1184 1179
1185bool OThemeCache::insert( OThemePixmap *pixmap, ScaleHint scale, int widgetID, 1180bool OThemeCache::insert( OThemePixmap *pixmap, ScaleHint scale, int widgetID,
1186 bool border, bool mask ) 1181 bool border, bool mask )
1187{ 1182{
1188 kthemeKey key; 1183 kthemeKey key;
1189 key.cacheKey = 0; // shut up, gcc 1184 key.cacheKey = 0; // shut up, gcc
1190 key.data.id = widgetID; 1185 key.data.id = widgetID;
1191 key.data.width = ( scale == FullScale || scale == HorizontalScale ) ? 1186 key.data.width = ( scale == FullScale || scale == HorizontalScale ) ?
1192 pixmap->width() : 0; 1187 pixmap->width() : 0;
1193 key.data.height = ( scale == FullScale || scale == VerticalScale ) ? 1188 key.data.height = ( scale == FullScale || scale == VerticalScale ) ?
1194 pixmap->height() : 0; 1189 pixmap->height() : 0;
1195 key.data.border = border; 1190 key.data.border = border;
1196 key.data.mask = mask; 1191 key.data.mask = mask;
1197 1192
1198 if ( cache.find( ( unsigned long ) key.cacheKey, true ) != NULL ) { 1193 if ( cache.find( ( unsigned long ) key.cacheKey, true ) != NULL ) {
1199 return ( true ); // a pixmap of this scale is already in there 1194 return ( true ); // a pixmap of this scale is already in there
1200 } 1195 }
1201 return ( cache.insert( ( unsigned long ) key.cacheKey, pixmap, 1196 return ( cache.insert( ( unsigned long ) key.cacheKey, pixmap,
1202 pixmap->width() * pixmap->height() * pixmap->depth() / 8 ) ); 1197 pixmap->width() * pixmap->height() * pixmap->depth() / 8 ) );
1203} 1198}
1204 1199
1205//#include "kthemebase.moc" 1200//#include "kthemebase.moc"
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,329 +1,329 @@
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)
145 output +=tempString; 145 output +=tempString;
146 } 146 }
147 else { 147 else {
148 // printf("| Symbol | %-20s |\n",stocks_tmp->Symbol); 148 // printf("| Symbol | %-20s |\n",stocks_tmp->Symbol);
149 tempString.sprintf("| Symbol %s ",stocks_tmp->Symbol); 149 tempString.sprintf("| Symbol %s ",stocks_tmp->Symbol);
150 if(dosymbolCheck) 150 if(dosymbolCheck)
151 output +=tempString; 151 output +=tempString;
152 } 152 }
153 153
154 if (stocks_tmp->Name) { 154 if (stocks_tmp->Name) {
155 if ( strlen(stocks_tmp->Name) > 20 ) { 155 if ( strlen(stocks_tmp->Name) > 20 ) {
156 // printf("| Name %.20s |\n",stocks_tmp->Name); 156 // printf("| Name %.20s |\n",stocks_tmp->Name);
157 tempString.sprintf("| Name %s ",stocks_tmp->Name); 157 tempString.sprintf("| Name %s ",stocks_tmp->Name);
158 tempString.stripWhiteSpace(); 158 tempString.stripWhiteSpace();
159 if(donameCheck) 159 if(donameCheck)
160 output +=tempString; 160 output +=tempString;
161 } else { 161 } else {
162 // printf("| Name | %-20s |\n",stocks_tmp->Name); 162 // printf("| Name | %-20s |\n",stocks_tmp->Name);
163 tempString.sprintf("| Name %s ",stocks_tmp->Name); 163 tempString.sprintf("| Name %s ",stocks_tmp->Name);
164 tempString.stripWhiteSpace(); 164 tempString.stripWhiteSpace();
165 if(donameCheck) 165 if(donameCheck)
166 output +=tempString; 166 output +=tempString;
167 } 167 }
168 } 168 }
169 else { 169 else {
170 // printf("| Name | |\n"); 170 // printf("| Name | |\n");
171 tempString.sprintf("| Name | |"); 171 tempString.sprintf("| Name | |");
172 if(donameCheck) 172 if(donameCheck)
173 output +=tempString; 173 output +=tempString;
174 } 174 }
175 175
176 // printf("| Price | %-7.2f |\n", stocks_tmp->CurrentPrice); 176 // printf("| Price | %-7.2f |\n", stocks_tmp->CurrentPrice);
177 tempString.sprintf("| Price %-7.2f ", stocks_tmp->CurrentPrice); 177 tempString.sprintf("| Price %-7.2f ", stocks_tmp->CurrentPrice);
178 if(docurrentPriceCheck) 178 if(docurrentPriceCheck)
179 output +=tempString; 179 output +=tempString;
180 180
181 // printf("| Yesterday | %-7.2f |\n",stocks_tmp->LastPrice); 181 // printf("| Yesterday | %-7.2f |\n",stocks_tmp->LastPrice);
182 tempString.sprintf("| Yesterday %-7.2f ",stocks_tmp->LastPrice); 182 tempString.sprintf("| Yesterday %-7.2f ",stocks_tmp->LastPrice);
183 if(dolastPriceCheck) 183 if(dolastPriceCheck)
184 output +=tempString; 184 output +=tempString;
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
@@ -1,214 +1,214 @@
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 "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,728 +1,735 @@
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");
139 QObject::tr("gal (US)"); 146 QObject::tr("gal (US)");
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 }
333 } 340 }
334 } 341 }
335 return Calculator::eventFilter( o, e ); 342 return Calculator::eventFilter( o, e );
336} 343}
337 344
338void CalculatorImpl::do_convert(int button) { 345void CalculatorImpl::do_convert(int button) {
339 if ( state == sError ) 346 if ( state == sError )
340 return; 347 return;
341 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) && 348 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) &&
342 button < changeable_func_button_count ) { 349 button < changeable_func_button_count ) {
343 if ( last_conversion > -1 ) { 350 if ( last_conversion > -1 ) {
344 if( state == sNewNumber ){ 351 if( state == sNewNumber ){
345 acc = (num+ preoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion]) 352 acc = (num+ preoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion])
346 / (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion]) 353 / (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion])
347 * (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + button]) 354 * (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + button])
348 +postoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + button]; 355 +postoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + button];
349 num = acc; 356 num = acc;
350 LCD->display( acc ); 357 LCD->display( acc );
351 } else { 358 } else {
352 state = sNewNumber; 359 state = sNewNumber;
353 num = (num+ preoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion]) 360 num = (num+ preoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion])
354 / (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion]) 361 / (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion])
355 * (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + button]) 362 * (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + button])
356 + postoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + button];; 363 + postoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + button];;
357 LCD->display( num ); 364 LCD->display( num );
358 acc = num; 365 acc = num;
359 } 366 }
360 } 367 }
361 last_conversion = button; 368 last_conversion = button;
362 } 369 }
363} 370}
364 371
365 372
366void CalculatorImpl::function_button(int mode){ 373void CalculatorImpl::function_button(int mode){
367 if ( state == sError ) 374 if ( state == sError )
368 clear(); 375 clear();
369 // dont need the next line when using a popup menu 376 // dont need the next line when using a popup menu
370 current_mode = mode; 377 current_mode = mode;
371 378
372 // reset the last conv 379 // reset the last conv
373 last_conversion = -1; 380 last_conversion = -1;
374 381
375 // set the caption 382 // set the caption
376 this->setCaption( captions[current_mode] ); 383 this->setCaption( captions[current_mode] );
377 384
378 reset_conv(); 385 reset_conv();
379 386
380 for ( int x = 0 ; x < changeable_func_button_count ; x++ ) { 387 for ( int x = 0 ; x < changeable_func_button_count ; x++ ) {
381 QPushButton* tmpbutton = func_buttons[x]; 388 QPushButton* tmpbutton = func_buttons[x];
382 389
383 // if its a conversion , make it a toggle button 390 // if its a conversion , make it a toggle button
384 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) ) { 391 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) ) {
385 tmpbutton->setToggleButton(TRUE); 392 tmpbutton->setToggleButton(TRUE);
386 } else { 393 } else {
387 tmpbutton->setToggleButton(FALSE); 394 tmpbutton->setToggleButton(FALSE);
388 } 395 }
389 tmpbutton->setText( faces[current_mode * func_button_count + x] ); 396 tmpbutton->setText( faces[current_mode * func_button_count + x] );
390 } 397 }
391 398
392 if ( current_mode == 0 ) display_pixmap_faces(); 399 if ( current_mode == 0 ) display_pixmap_faces();
393 400
394 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) ) { 401 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) ) {
395 bgr_function.setExclusive(TRUE); 402 bgr_function.setExclusive(TRUE);
396 } else { 403 } else {
397 bgr_function.setExclusive(FALSE); 404 bgr_function.setExclusive(FALSE);
398 } 405 }
399} 406}
400 407
401void CalculatorImpl::display_pixmap_faces() { 408void CalculatorImpl::display_pixmap_faces() {
402 QPixmap image0( ( const char** ) xtopowerofy_xpm); 409 QPixmap image0( ( const char** ) xtopowerofy_xpm);
403 QPushButton* tmpbutton = func_buttons[5]; 410 QPushButton* tmpbutton = func_buttons[5];
404 tmpbutton->setPixmap(image0); 411 tmpbutton->setPixmap(image0);
405 412
406 QPixmap image1( ( const char** ) ythrootofx_xpm); 413 QPixmap image1( ( const char** ) ythrootofx_xpm);
407 tmpbutton = func_buttons[6]; 414 tmpbutton = func_buttons[6];
408 tmpbutton->setPixmap(image1); 415 tmpbutton->setPixmap(image1);
409 416
410 QPixmap image2( ( const char** ) oneoverx_xpm); 417 QPixmap image2( ( const char** ) oneoverx_xpm);
411 tmpbutton = func_buttons[3]; 418 tmpbutton = func_buttons[3];
412 tmpbutton->setPixmap(image2); 419 tmpbutton->setPixmap(image2);
413} 420}
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:
607 sum = log10(num); 614 sum = log10(num);
608 break; 615 break;
609 case oLn: 616 case oLn:
610 sum = log(num); 617 sum = log(num);
611 break; 618 break;
612 case oTan: sum = qTan(num);break; 619 case oTan: sum = qTan(num);break;
613 case oSin: sum = qSin(num);break; 620 case oSin: sum = qSin(num);break;
614 case oCos: sum = qCos(num);break; 621 case oCos: sum = qCos(num);break;
615 default: sum = num; break; 622 default: sum = num; break;
616 } 623 }
617 624
618 if ( isinf( sum ) || isnan( sum ) ) 625 if ( isinf( sum ) || isnan( sum ) )
619 state = sError; 626 state = sError;
620 return sum; 627 return sum;
621} 628}
622 629
623 630
624void CalculatorImpl::enterNumber( int n ) 631void CalculatorImpl::enterNumber( int n )
625{ 632{
626 if ( state == sError ) 633 if ( state == sError )
627 return; 634 return;
628 if( state == sStart ){ 635 if( state == sStart ){
629 if( LCD->value() > 0 ){ 636 if( LCD->value() > 0 ){
630 QString s = QString::number( LCD->value(), 'g', LCD->numDigits()); 637 QString s = QString::number( LCD->value(), 'g', LCD->numDigits());
631 if( s.length() > (uint)(LCD->numDigits() - 2)) return; 638 if( s.length() > (uint)(LCD->numDigits() - 2)) return;
632 639
633 } else if( (int)fake.length() >= LCD->numDigits() || numDecimals >=12 ){ 640 } else if( (int)fake.length() >= LCD->numDigits() || numDecimals >=12 ){
634 return; 641 return;
635 } 642 }
636 } 643 }
637 644
638 if( state == sNewNumber ){ 645 if( state == sNewNumber ){
639 state = sStart; 646 state = sStart;
640 acc = 0; 647 acc = 0;
641 if( flPoint ){ 648 if( flPoint ){
642 numDecimals = 1; 649 numDecimals = 1;
643 num = n / pow(10, numDecimals); 650 num = n / pow(10, numDecimals);
644 } else 651 } else
645 num = n; 652 num = n;
646 } else if( flPoint ){ 653 } else if( flPoint ){
647 numDecimals++; 654 numDecimals++;
648 if( num < 0 ){ 655 if( num < 0 ){
649 num -= n / pow(10, numDecimals); 656 num -= n / pow(10, numDecimals);
650 } else { 657 } else {
651 num += n / pow(10, numDecimals); 658 num += n / pow(10, numDecimals);
652 } 659 }
653 } else { 660 } else {
654 num *= 10; 661 num *= 10;
655 if( num < 0 ) 662 if( num < 0 )
656 num -= n; 663 num -= n;
657 else 664 else
658 num += n; 665 num += n;
659 } 666 }
660 667
661 // We need feedback in the calc display while entering fl.point zeros. 668 // We need feedback in the calc display while entering fl.point zeros.
662 // This is a small hack to display sequences like: 0.000 and 1.100 669 // This is a small hack to display sequences like: 0.000 and 1.100
663 double integer, fraction; 670 double integer, fraction;
664 fraction = modf( num, &integer ); 671 fraction = modf( num, &integer );
665 if( flPoint ){ 672 if( flPoint ){
666 QString is, fs, zeros; 673 QString is, fs, zeros;
667 674
668 is = QString::number( integer, 'g', 13 ); 675 is = QString::number( integer, 'g', 13 );
669 fs = QString::number( fraction, 'g', numDecimals ); 676 fs = QString::number( fraction, 'g', numDecimals );
670 if( fs.contains('e') ){ 677 if( fs.contains('e') ){
671 fs = QString::number( fraction, 'f', LCD->numDigits() ); 678 fs = QString::number( fraction, 'f', LCD->numDigits() );
672 } 679 }
673 fs = fs.mid( 2, numDecimals ); 680 fs = fs.mid( 2, numDecimals );
674 681
675 if( (integer == 0) && (fraction == 0) ) 682 if( (integer == 0) && (fraction == 0) )
676 fake = "0."; 683 fake = "0.";
677 else if( (integer != 0) && (fraction == 0) ) 684 else if( (integer != 0) && (fraction == 0) )
678 fake = is + "."; 685 fake = is + ".";
679 else 686 else
680 fake = is + "." + fs; 687 fake = is + "." + fs;
681 688
682 zeros.fill( '0', (numDecimals - fs.length()) ); 689 zeros.fill( '0', (numDecimals - fs.length()) );
683 fake += zeros; 690 fake += zeros;
684 // ### This code sets LCD->value() to zero since it sets a text 691 // ### This code sets LCD->value() to zero since it sets a text
685 // ### Avoid getting the current value from LCD->value() for 692 // ### Avoid getting the current value from LCD->value() for
686 // ### calculations. 693 // ### calculations.
687 LCD->display( fake ); 694 LCD->display( fake );
688 } else 695 } else
689 LCD->display( num ); 696 LCD->display( num );
690} 697}
691 698
692void CalculatorImpl::command_buttons(int i) { 699void CalculatorImpl::command_buttons(int i) {
693 if ( state == sError && i != 3 ) 700 if ( state == sError && i != 3 )
694 return; 701 return;
695 switch (i) { 702 switch (i) {
696 case 0: // M+ 703 case 0: // M+
697 mem += num; 704 mem += num;
698 if( mem != 0 ){ 705 if( mem != 0 ){
699 memMark->show(); 706 memMark->show();
700 PushButtonMR->setEnabled( TRUE ); }; 707 PushButtonMR->setEnabled( TRUE ); };
701 state = sNewNumber; 708 state = sNewNumber;
702 break; 709 break;
703 case 1: // MR 710 case 1: // MR
704 acc = num = mem; 711 acc = num = mem;
705 state = sNewNumber; 712 state = sNewNumber;
706 LCD->display( mem ); 713 LCD->display( mem );
707 break; 714 break;
708 case 2: // MC 715 case 2: // MC
709 mem = 0; 716 mem = 0;
710 memMark->hide(); 717 memMark->hide();
711 PushButtonMR->setEnabled( FALSE ); 718 PushButtonMR->setEnabled( FALSE );
712 break; 719 break;
713 case 3: // CE 720 case 3: // CE
714 if ( state == sStart ) { 721 if ( state == sStart ) {
715 // clear the entered number on the first press 722 // clear the entered number on the first press
716 state = sNewNumber; 723 state = sNewNumber;
717 num = acc = 0; 724 num = acc = 0;
718 flPoint = FALSE; 725 flPoint = FALSE;
719 LCD->display( 0 ); 726 LCD->display( 0 );
720 fake = QString::null; 727 fake = QString::null;
721 numDecimals = 0; 728 numDecimals = 0;
722 } else { 729 } else {
723 clear(); 730 clear();
724 } 731 }
725 break; 732 break;
726 }; 733 };
727 734
728} 735}
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,632 +1,634 @@
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
134 tabLayout_2->addMultiCellWidget( editPushButton, 7, 7, 0, 0 ); 136 tabLayout_2->addMultiCellWidget( editPushButton, 7, 7, 0, 0 );
135 137
136 fsckButton = new QPushButton( tab_2, "fsckPushButton" ); 138 fsckButton = new QPushButton( tab_2, "fsckPushButton" );
137 fsckButton->setText( tr( "Check Disk" ) ); 139 fsckButton->setText( tr( "Check Disk" ) );
138 fsckButton->setMaximumWidth(100); 140 fsckButton->setMaximumWidth(100);
139 141
140 tabLayout_2->addMultiCellWidget( fsckButton, 7, 7, 1, 1); 142 tabLayout_2->addMultiCellWidget( fsckButton, 7, 7, 1, 1);
141 143
142 TextLabel3 = new QLabel( tab_2, "TextLabel3" ); 144 TextLabel3 = new QLabel( tab_2, "TextLabel3" );
143 TextLabel3->setText( tr( "Device" ) ); 145 TextLabel3->setText( tr( "Device" ) );
144 146
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 )