summaryrefslogtreecommitdiff
Unidiff
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--noncore/apps/opie-gutenbrowser/LibraryDialog.cpp88
-rw-r--r--noncore/apps/opie-gutenbrowser/openetext.cpp174
-rw-r--r--noncore/multimedia/opieplayer2/lib.cpp30
-rw-r--r--noncore/multimedia/opieplayer2/om3u.cpp141
-rw-r--r--noncore/multimedia/opieplayer2/threadutil.cpp17
-rw-r--r--noncore/net/opiestumbler/opiestumbler.cpp3
-rw-r--r--noncore/settings/networksettings/mainwindow/mainwindowimp.cpp11
-rw-r--r--noncore/settings/networksettings/ppp/modem.cpp6
8 files changed, 235 insertions, 235 deletions
diff --git a/noncore/apps/opie-gutenbrowser/LibraryDialog.cpp b/noncore/apps/opie-gutenbrowser/LibraryDialog.cpp
index 6c246e97..7f21ab3 100644
--- a/noncore/apps/opie-gutenbrowser/LibraryDialog.cpp
+++ b/noncore/apps/opie-gutenbrowser/LibraryDialog.cpp
@@ -1,1053 +1,1055 @@
1/*************************************************************************** 1/***************************************************************************
2// LibraryDialog.cpp - description 2// LibraryDialog.cpp - description
3// ------------------- 3// -------------------
4// begin : Sat Aug 19 2000 4// begin : Sat Aug 19 2000
5// copyright : (C) 2000 - 2004 by llornkcor 5// copyright : (C) 2000 - 2004 by llornkcor
6// email : ljp@llornkcor.com 6// email : ljp@llornkcor.com
7// ***************************************************/ 7// ***************************************************/
8// /*************************************************************************** 8// /***************************************************************************
9// * This program is free software; you can redistribute it and/or modify * 9// * This program is free software; you can redistribute it and/or modify *
10// * it under the terms of the GNU General Public License as published by * 10// * it under the terms of the GNU General Public License as published by *
11// * the Free Software Foundation; either version 2 of the License, or * 11// * the Free Software Foundation; either version 2 of the License, or *
12// * (at your option) any later version. * 12// * (at your option) any later version. *
13// ***************************************************************************/ 13// ***************************************************************************/
14//ftp://ibiblio.org/pub/docs/books/gutenberg/GUTINDEX.ALL 14//ftp://ibiblio.org/pub/docs/books/gutenberg/GUTINDEX.ALL
15 15
16#include "LibraryDialog.h" 16#include "LibraryDialog.h"
17#include "output.h" 17#include "output.h"
18 18
19/* OPIE */ 19/* OPIE */
20#include <qpe/applnk.h> 20#include <qpe/applnk.h>
21#include <qpe/qpeapplication.h> 21#include <qpe/qpeapplication.h>
22#include <qpe/qpedialog.h> 22#include <qpe/qpedialog.h>
23//#include <opie2///odebug.h> 23#include <opie2/odebug.h>
24 24
25/* QT */ 25/* QT */
26#include <qpushbutton.h> 26#include <qpushbutton.h>
27#include <qmultilineedit.h> 27#include <qmultilineedit.h>
28//#include <qlayout.h> 28//#include <qlayout.h>
29 29
30/* STD */ 30/* STD */
31#include <unistd.h> 31#include <unistd.h>
32#include <stdio.h> 32#include <stdio.h>
33#include <stdlib.h> 33#include <stdlib.h>
34 34
35/* 35/*
36 * The dialog will by default be modeless, unless you set 'modal' to 36 * The dialog will by default be modeless, unless you set 'modal' to
37 * true to construct a modal dialog. */ 37 * true to construct a modal dialog. */
38LibraryDialog::LibraryDialog( QWidget* parent, const char* name , bool /*modal*/, WFlags fl ) 38LibraryDialog::LibraryDialog( QWidget* parent, const char* name , bool /*modal*/, WFlags fl )
39 : QDialog( parent, name, true/* modal*/, fl ) 39 : QDialog( parent, name, true/* modal*/, fl )
40{ 40{
41 if ( !name ) 41 if ( !name )
42 setName( "LibraryDialog" ); 42 setName( "LibraryDialog" );
43 indexLoaded=false; 43 indexLoaded=false;
44 initDialog(); 44 initDialog();
45 45
46 // this->setMaximumWidth(240); 46 // this->setMaximumWidth(240);
47 47
48 index = "GUTINDEX.ALL"; 48 index = "GUTINDEX.ALL";
49 local_library = (QDir::homeDirPath ()) +"/Applications/gutenbrowser/"; 49 local_library = (QDir::homeDirPath ()) +"/Applications/gutenbrowser/";
50 local_index = local_library + index; 50 local_index = local_library + index;
51 51
52 QString iniFile ; 52 QString iniFile ;
53 iniFile = local_library + "/gutenbrowserrc"; 53 iniFile = local_library + "/gutenbrowserrc";
54 new_index = local_library + "/PGWHOLE.TXT"; 54 new_index = local_library + "/PGWHOLE.TXT";
55 old_index = local_index; 55 old_index = local_index;
56 // iniFile = local_library+"gutenbrowserrc"; 56 // iniFile = local_library+"gutenbrowserrc";
57 // new_index = local_library + "PGWHOLE.TXT"; 57 // new_index = local_library + "PGWHOLE.TXT";
58 // old_index = local_library + "GUTINDEX.ALL"; 58 // old_index = local_library + "GUTINDEX.ALL";
59 59
60 Config config("Gutenbrowser"); 60 Config config("Gutenbrowser");
61 61
62 config.setGroup( "HttpServer" ); 62 config.setGroup( "HttpServer" );
63 proxy_http = config.readEntry("Preferred", "http://sailor.gutenbook.org"); 63 proxy_http = config.readEntry("Preferred", "http://sailor.gutenbook.org");
64 64
65 config.setGroup( "FTPsite" ); 65 config.setGroup( "FTPsite" );
66 ftp_host = config.readEntry("SiteName", "sailor.gutenberg.org"); 66 ftp_host = config.readEntry("SiteName", "sailor.gutenberg.org");
67 //odebug << "Library Dialog: ftp_host is "+ftp_host << oendl; 67 //odebug << "Library Dialog: ftp_host is "+ftp_host << oendl;
68 // ftp_host=ftp_host.right(ftp_host.length()-(ftp_host.find(") ",0,true)+1) ); 68 // ftp_host=ftp_host.right(ftp_host.length()-(ftp_host.find(") ",0,true)+1) );
69 // ftp_host=ftp_host.stripWhiteSpace(); 69 // ftp_host=ftp_host.stripWhiteSpace();
70 ftp_base_dir= config.readEntry("base", "/pub/gutenberg"); 70 ftp_base_dir= config.readEntry("base", "/pub/gutenberg");
71 71
72 i_binary = 0; 72 i_binary = 0;
73 73
74 config.setGroup("SortAuth"); 74 config.setGroup("SortAuth");
75 if( config.readEntry("authSort", "false") == "true") 75 if( config.readEntry("authSort", "false") == "true")
76 authBox->setChecked(true); 76 authBox->setChecked(true);
77 77
78 config.setGroup("General"); 78 config.setGroup("General");
79 downDir = config.readEntry( "DownloadDirectory",local_library); 79 downDir = config.readEntry( "DownloadDirectory",local_library);
80 //odebug << "downDir is "+downDir << oendl; 80 //odebug << "downDir is "+downDir << oendl;
81 newindexLib.setName( old_index); 81 newindexLib.setName( old_index);
82 indexLib.setName( old_index); 82 indexLib.setName( old_index);
83 83
84 new QPEDialogListener(this); 84 new QPEDialogListener(this);
85 QTimer::singleShot( 1000, this, SLOT( FindLibrary()) ); 85 QTimer::singleShot( 1000, this, SLOT( FindLibrary()) );
86 86
87} 87}
88 88
89LibraryDialog::~LibraryDialog() 89LibraryDialog::~LibraryDialog()
90{ 90{
91} 91}
92 92
93void LibraryDialog::clearItems() { 93void LibraryDialog::clearItems() {
94 ListView1->clear(); 94 ListView1->clear();
95 ListView2->clear(); 95 ListView2->clear();
96 ListView3->clear(); 96 ListView3->clear();
97 ListView4->clear(); 97 ListView4->clear();
98 ListView5->clear(); 98 ListView5->clear();
99} 99}
100 100
101/*This groks using PGWHOLE.TXT */ 101/*This groks using PGWHOLE.TXT */
102void LibraryDialog::Newlibrary() 102void LibraryDialog::Newlibrary()
103{ 103{
104 clearItems(); 104 clearItems();
105#ifndef Q_WS_QWS //sorry embedded gutenbrowser cant use zip files 105#ifndef Q_WS_QWS //sorry embedded gutenbrowser cant use zip files
106 ////odebug << "Opening new library index " << newindexLib << "" << oendl; 106 ////odebug << "Opening new library index " << newindexLib << "" << oendl;
107 if ( newindexLib.open( IO_ReadOnly) ) { 107 if ( newindexLib.open( IO_ReadOnly) ) {
108 setCaption( tr( "Library Index - using master pg index." ) );// file opened successfully 108 setCaption( tr( "Library Index - using master pg index." ) );// file opened successfully
109 QTextStream indexStream( &newindexLib ); 109 QTextStream indexStream( &newindexLib );
110 QString indexLine; 110 QString indexLine;
111 while ( !indexStream.atEnd() ) { // until end of file.. 111 while ( !indexStream.atEnd() ) { // until end of file..
112 indexLine = indexStream.readLine(); 112 indexLine = indexStream.readLine();
113 if ( ( indexLine.mid(4,4)).toInt() && !( indexLine.left(3)).toInt()) { 113 if ( ( indexLine.mid(4,4)).toInt() && !( indexLine.left(3)).toInt()) {
114 year = indexLine.mid(4,4); 114 year = indexLine.mid(4,4);
115 file = indexLine.mid( indexLine.find( "[", 0, true )+1, 12 ); 115 file = indexLine.mid( indexLine.find( "[", 0, true )+1, 12 );
116 number = indexLine.mid( indexLine.find( "]", 0, true ) +1, indexLine.find( " ", 0, true )+1 ); 116 number = indexLine.mid( indexLine.find( "]", 0, true ) +1, indexLine.find( " ", 0, true )+1 );
117 if( year.toInt() < 1984) 117 if( year.toInt() < 1984)
118 number = number.left( number.length() -1 ); 118 number = number.left( number.length() -1 );
119 title = indexLine.mid( indexLine.find(" ", 26, true), indexLine.length() ); 119 title = indexLine.mid( indexLine.find(" ", 26, true), indexLine.length() );
120 120
121 addItems(); 121 addItems();
122 122
123 }// end if 123 }// end if
124 }// end while 124 }// end while
125 newindexLib.close(); 125 newindexLib.close();
126 } 126 }
127#ifndef Q_WS_QWS 127#ifndef Q_WS_QWS
128 setCursor( arrowCursor); 128 setCursor( arrowCursor);
129#endif 129#endif
130#endif 130#endif
131} // end Newlibrary() 131} // end Newlibrary()
132 132
133 133
134void LibraryDialog::Library() { 134void LibraryDialog::Library() {
135 clearItems(); 135 clearItems();
136 136
137 // qDebug( "opening GUTINDEX.ALL file"); 137 // qDebug( "opening GUTINDEX.ALL file");
138 IDontKnowWhy = ""; 138 IDontKnowWhy = "";
139 system("date"); 139 system("date");
140 if ( indexLib.open( IO_ReadOnly) ) { 140 if ( indexLib.open( IO_ReadOnly) ) {
141// file opened successfully 141// file opened successfully
142 QTextStream indexStream( &indexLib ); 142 QTextStream indexStream( &indexLib );
143 QString indexLine; 143 QString indexLine;
144 qApp->processEvents(); 144 qApp->processEvents();
145 145
146 bool okToRead = false; 146 bool okToRead = false;
147 while ( !indexStream.eof() ) { 147 while ( !indexStream.eof() ) {
148 indexLine = indexStream.readLine(); 148 indexLine = indexStream.readLine();
149 if(indexLine == "<==Start GUTINDEX.ALL listings==>") 149 if(indexLine == "<==Start GUTINDEX.ALL listings==>")
150 okToRead = true; 150 okToRead = true;
151 if(indexLine == "<==End of GUTINDEX.ALL==>") { 151 if(indexLine == "<==End of GUTINDEX.ALL==>") {
152 okToRead = false; 152 okToRead = false;
153 indexLib.at(indexLib.size()); 153 indexLib.at(indexLib.size());
154 } 154 }
155 155
156 if(okToRead) { 156 if(okToRead) {
157 QStringList token = QStringList::split(' ', indexLine); 157 QStringList token = QStringList::split(' ', indexLine);
158 int textNumber; 158 int textNumber;
159 if(( textNumber = token.last().toInt() )) 159 if(( textNumber = token.last().toInt() ))
160 if(textNumber > 10001) { 160 if(textNumber > 10001) {
161// qWarning("Last "+token.last()); 161// qWarning("Last "+token.last());
162// newer files with numbers > 100000 have new dir structure and need to be parsed differently.. 162// newer files with numbers > 100000 have new dir structure and need to be parsed differently..
163 if(textNumber < 10626) 163 if(textNumber < 10626)
164 year = "2003"; 164 year = "2003";
165 else if(textNumber >= 10626 && textNumber < 14600) 165 else if(textNumber >= 10626 && textNumber < 14600)
166 year = "2004"; 166 year = "2004";
167 else if(textNumber >= 14600) 167 else if(textNumber >= 14600)
168 year = "2005"; 168 year = "2005";
169 169
170 file = token.last(); 170 file = token.last();
171 title = indexLine.mid(0,72); 171 title = indexLine.mid(0,72);
172 172
173 addItems(); //author and qlistview 173 addItems(); //author and qlistview
174 //qDebug("file number is " + number + " title is " + title ); 174 //qDebug("file number is " + number + " title is " + title );
175 175
176 } else { //end new etexts 176 } else { //end new etexts
177 177
178 if(token[1].toInt() && token[1].toInt() > 1969) { 178 if(token[1].toInt() && token[1].toInt() > 1969) {
179 year = token[1]; 179 year = token[1];
180 file = indexLine.mid(60,12); 180 file = indexLine.mid(60,12);
181 181
182 if(file.left(1).find("[",0,TRUE) != -1) { 182 if(file.left(1).find("[",0,TRUE) != -1) {
183 file.remove(1,1); 183 file.remove(1,1);
184 if( file.find("]",0,TRUE) != -1) 184 if( file.find("]",0,TRUE) != -1)
185 file = file.left( file.find("]",0,TRUE)); 185 file = file.left( file.find("]",0,TRUE));
186 186
187 if(file.find("?", 0, false) != -1 ) { 187 if(file.find("?", 0, false) != -1 ) {
188 QString tmpfile = file.replace(QRegExp("[?]"), "8"); 188 QString tmpfile = file.replace(QRegExp("[?]"), "8");
189 file = tmpfile; 189 file = tmpfile;
190 } 190 }
191 title = indexLine.mid( 9, 50); 191 title = indexLine.mid( 9, 50);
192 192
193 addItems(); 193 addItems();
194 } 194 }
195 } else { // then try new format texts 195 } else { // then try new format texts
196 file = token.last(); 196 file = token.last();
197 title = indexLine.mid(0,72); 197 title = indexLine.mid(0,72);
198 year = "1980"; 198 year = "1980";
199 199
200 addItems(); //author and qlistview 200 addItems(); //author and qlistview
201 } 201 }
202 } //end old etexts 202 } //end old etexts
203 203
204 } //end okToTRead 204 } //end okToTRead
205 } 205 }
206 indexLib.close(); 206 indexLib.close();
207 } else { 207 } else {
208 QString sMsg; 208 QString sMsg;
209 209
210 sMsg = ( tr("<p>Error opening library index file. Please download a new one.</P> ")); 210 sMsg = ( tr("<p>Error opening library index file. Please download a new one.</P> "));
211 QMessageBox::message( "Error",sMsg); 211 QMessageBox::message( "Error",sMsg);
212 } 212 }
213 system("date"); 213 system("date");
214 sortLists(0); 214 sortLists(0);
215 215
216} //end Library() 216} //end Library()
217 217
218 218
219/* 219/*
220 Groks the author out of the title */ 220 Groks the author out of the title */
221bool LibraryDialog::getAuthor() 221bool LibraryDialog::getAuthor()
222{ 222{
223 if( title.contains( ", by", true)) { 223 if( title.contains( ", by", true)) {
224 int auth; 224 int auth;
225 auth = title.find(", by", 0, true); 225 auth = title.find(", by", 0, true);
226 author = title.right(title.length() - (auth + 4) ); 226 author = title.right(title.length() - (auth + 4) );
227 if( int finder = author.find("[", 0, true)) { 227 if( int finder = author.find("[", 0, true)) {
228 author = author.left(finder); 228 author = author.left(finder);
229 } 229 }
230 } 230 }
231 else if ( title.contains( "by, ", true) ) { 231 else if ( title.contains( "by, ", true) ) {
232 int auth; 232 int auth;
233 auth = title.find("by, ", 0, true); 233 auth = title.find("by, ", 0, true);
234 author = title.right(title.length() - (auth + 4) ); 234 author = title.right(title.length() - (auth + 4) );
235 if( int finder = author.find("[", 0, true)) { 235 if( int finder = author.find("[", 0, true)) {
236 author = author.left( finder); 236 author = author.left( finder);
237 } 237 }
238 } 238 }
239 else if ( title.contains( " by", true) ) { 239 else if ( title.contains( " by", true) ) {
240 int auth; 240 int auth;
241 auth = title.find(" by", 0, true); 241 auth = title.find(" by", 0, true);
242 author = title.right(title.length() - (auth + 3) ); 242 author = title.right(title.length() - (auth + 3) );
243 if( int finder = author.find("[", 0, true)) { 243 if( int finder = author.find("[", 0, true)) {
244 author = author.left( finder); 244 author = author.left( finder);
245 } 245 }
246 } 246 }
247 else if ( title.contains( "by ", true) ) { 247 else if ( title.contains( "by ", true) ) {
248 int auth; 248 int auth;
249 auth = title.find("by ", 0, true); 249 auth = title.find("by ", 0, true);
250 author = title.right(title.length() - (auth + 3) ); 250 author = title.right(title.length() - (auth + 3) );
251 if( int finder = author.find("[", 0, true)) { 251 if( int finder = author.find("[", 0, true)) {
252 author = author.left( finder); 252 author = author.left( finder);
253 } 253 }
254 } 254 }
255 else if ( title.contains( ",", true) ) { 255 else if ( title.contains( ",", true) ) {
256 int auth; 256 int auth;
257 auth = title.find(",", 0, true); 257 auth = title.find(",", 0, true);
258 author = title.right( title.length() - (auth + 1) ); 258 author = title.right( title.length() - (auth + 1) );
259 if ( author.contains( ",", true) ) { 259 if ( author.contains( ",", true) ) {
260 int auth; 260 int auth;
261 auth = author.find(",", 0, true); 261 auth = author.find(",", 0, true);
262 author = author.right( author.length() - (auth + 1) ); 262 author = author.right( author.length() - (auth + 1) );
263 } 263 }
264 if( int finder = author.find("[", 0, true)) { 264 if( int finder = author.find("[", 0, true)) {
265 author = author.left( finder); 265 author = author.left( finder);
266 } 266 }
267 } 267 }
268 else if ( title.contains( "/", true) ) { 268 else if ( title.contains( "/", true) ) {
269 int auth; 269 int auth;
270 auth = title.find("/", 0, true); 270 auth = title.find("/", 0, true);
271 author = title.right(title.length() - (auth + 1) ); 271 author = title.right(title.length() - (auth + 1) );
272 if( int finder = author.find("[", 0, true)) { 272 if( int finder = author.find("[", 0, true)) {
273 author = author.left( finder); 273 author = author.left( finder);
274 } 274 }
275 } 275 }
276 else if ( title.contains( "of", true) ) { 276 else if ( title.contains( "of", true) ) {
277 int auth; 277 int auth;
278 auth = title.find("of", 0, true); 278 auth = title.find("of", 0, true);
279 author = title.right(title.length() - (auth + 2) ); 279 author = title.right(title.length() - (auth + 2) );
280 if( int finder = author.find("[", 0, true)) 280 if( int finder = author.find("[", 0, true))
281 { 281 {
282 author = author.left( finder); 282 author = author.left( finder);
283 } 283 }
284 } else { 284 } else {
285 author = ""; 285 author = "";
286 } 286 }
287 if ( author.contains("et. al")) { 287 if ( author.contains("et. al")) {
288 int auth; 288 int auth;
289 auth = author.find("et. al", 0, true); 289 auth = author.find("et. al", 0, true);
290 author = author.left( auth ); 290 author = author.left( auth );
291 } 291 }
292 if ( author.contains("#")) { 292 if ( author.contains("#")) {
293 int auth; 293 int auth;
294 auth = author.find("#", 0, true); 294 auth = author.find("#", 0, true);
295 author = author.left( auth); 295 author = author.left( auth);
296 } 296 }
297 if ( author.contains("(")) { 297 if ( author.contains("(")) {
298 int auth; 298 int auth;
299 auth = author.find("(", 0, true); 299 auth = author.find("(", 0, true);
300 author = author.left( auth); 300 author = author.left( auth);
301 } 301 }
302 if ( author.contains("et al")) { 302 if ( author.contains("et al")) {
303 int auth; 303 int auth;
304 auth = author.find("et al", 0, true); 304 auth = author.find("et al", 0, true);
305 author = author.left( auth ); 305 author = author.left( auth );
306 } 306 }
307 QRegExp r = QRegExp("[0-9]", true, false); 307 QRegExp r = QRegExp("[0-9]", true, false);
308 if ( author.left(2).find( r) != -1 ) { 308 if ( author.left(2).find( r) != -1 ) {
309 author = ""; 309 author = "";
310 } 310 }
311 311
312 author = author.stripWhiteSpace(); 312 author = author.stripWhiteSpace();
313 if (authBox->isChecked() == TRUE) { // this reverses the first name and last name of the author 313 if (authBox->isChecked() == TRUE) { // this reverses the first name and last name of the author
314 QString lastName, firstName=""; 314 QString lastName, firstName="";
315 int finder = author.findRev( ' ', -1, TRUE); 315 int finder = author.findRev( ' ', -1, TRUE);
316 lastName = author.right( author.length()-finder); 316 lastName = author.right( author.length()-finder);
317 firstName = author.left(finder); 317 firstName = author.left(finder);
318 lastName = lastName.stripWhiteSpace(); 318 lastName = lastName.stripWhiteSpace();
319 firstName = firstName.stripWhiteSpace(); 319 firstName = firstName.stripWhiteSpace();
320 320
321 if( lastName.find( firstName, 0, true) == -1) // this avoids dup names 321 if( lastName.find( firstName, 0, true) == -1) // this avoids dup names
322 author = lastName+", "+firstName; 322 author = lastName+", "+firstName;
323 } 323 }
324 return true; 324 return true;
325}////// end getAuthor() 325}////// end getAuthor()
326 326
327void LibraryDialog::addItems() 327void LibraryDialog::addItems()
328{ 328{
329 cleanStrings(); 329 cleanStrings();
330 getAuthor(); // grok author 330 getAuthor(); // grok author
331 331
332 etext etextStruct; 332 etext etextStruct;
333 if( /*!number.isEmpty() 333 if( /*!number.isEmpty()
334 && */ 334 && */
335 (title.find( "reserved",0, FALSE) == -1) 335 (title.find( "reserved",0, FALSE) == -1)
336 && (file.find( "]",0, true) == -1) 336 && (file.find( "]",0, true) == -1)
337 &&(title.find( "Audio",0, FALSE) == -1)) { 337 &&(title.find( "Audio",0, FALSE) == -1)) {
338 // qDebug("new item "+title); 338 // qDebug("new item "+title);
339 // fill string list or something to be able to sort by Author 339 // fill string list or something to be able to sort by Author
340 etextStruct.title = title; 340 etextStruct.title = title;
341 etextStruct.author = author; 341 etextStruct.author = author;
342 etextStruct.year = year; 342 etextStruct.year = year;
343 etextStruct.file = file; 343 etextStruct.file = file;
344 344
345 etextLibrary.append( etextStruct); 345 etextLibrary.append( etextStruct);
346 346
347 if( author.isEmpty() ) 347 if( author.isEmpty() )
348 QList_Item5 = new QListViewItem( ListView5, /*number, */author, title, year, file ); 348 QList_Item5 = new QListViewItem( ListView5, /*number, */author, title, year, file );
349 else { 349 else {
350 if( author.find(QRegExp("[^a-fA-F]")) ) 350 if( author.find(QRegExp("[^a-fA-F]")) )
351 QList_Item1 = new QListViewItem( ListView1, /* number,*/author, title, year, file ); 351 QList_Item1 = new QListViewItem( ListView1, /* number,*/author, title, year, file );
352 352
353 else if(author.find(QRegExp("[^g-mG-M]")) ) 353 else if(author.find(QRegExp("[^g-mG-M]")) )
354 QList_Item2 = new QListViewItem( ListView2, /* number,*/ author, title,year, file ); 354 QList_Item2 = new QListViewItem( ListView2, /* number,*/ author, title,year, file );
355 355
356 else if(author.find(QRegExp("[^n-rN-R]")) ) 356 else if(author.find(QRegExp("[^n-rN-R]")) )
357 QList_Item3 = new QListViewItem( ListView3, /* number,*/ author, title, year, file ); 357 QList_Item3 = new QListViewItem( ListView3, /* number,*/ author, title, year, file );
358 358
359 else if(author.find(QRegExp("[^s-zS-Z]")) ) 359 else if(author.find(QRegExp("[^s-zS-Z]")) )
360 QList_Item4 = new QListViewItem( ListView4, /* number,*/ author, title, year, file ); 360 QList_Item4 = new QListViewItem( ListView4, /* number,*/ author, title, year, file );
361 } 361 }
362 } 362 }
363} 363}
364 364
365/* 365/*
366 selected one etext*/ 366 selected one etext*/
367void LibraryDialog::select_title( QListViewItem * item) 367void LibraryDialog::select_title( QListViewItem * item)
368{ 368{
369 if(item != NULL) { 369 if(item != NULL) {
370 i++; 370 i++;
371 int index = tabWidget->currentPageIndex(); 371 int index = tabWidget->currentPageIndex();
372 DlglistItemTitle = item->text(0); 372 DlglistItemTitle = item->text(0);
373 DlglistItemYear = item->text(2); 373 DlglistItemYear = item->text(2);
374 DlglistItemFile = item->text(3); 374 DlglistItemFile = item->text(3);
375 375
376 switch (index) { 376 switch (index) {
377 case 0: { 377 case 0: {
378 ListView1->clearSelection(); 378 ListView1->clearSelection();
379 } 379 }
380 break; 380 break;
381 case 1: { 381 case 1: {
382 ListView2->clearSelection(); 382 ListView2->clearSelection();
383 } 383 }
384 break; 384 break;
385 case 2: { 385 case 2: {
386 ListView3->clearSelection(); 386 ListView3->clearSelection();
387 } 387 }
388 break; 388 break;
389 case 3: { 389 case 3: {
390 ListView4->clearSelection(); 390 ListView4->clearSelection();
391 } 391 }
392 break; 392 break;
393 case 4: { 393 case 4: {
394 ListView5->clearSelection(); 394 ListView5->clearSelection();
395 } 395 }
396 break; 396 break;
397 }; 397 };
398 } 398 }
399 399
400 if(DlglistItemTitle.length() > 2) { 400 if(DlglistItemTitle.length() > 2) {
401 item = 0; 401 item = 0;
402 // todo check for connection here 402 // todo check for connection here
403 403
404 bool ok = false; 404 bool ok = false;
405 qDebug(DlglistItemFile); 405 qDebug(DlglistItemFile);
406 406
407 if(DlglistItemFile.toInt() > 10000 ) { 407 if(DlglistItemFile.toInt() > 10000 ) {
408 // new directory sturcture 408 // new directory sturcture
409 if( download_newEtext()) 409 if( download_newEtext())
410 ok = true; 410 ok = true;
411 } else { 411 } else {
412 if(download_Etext()) 412 if(download_Etext())
413 ok = true; 413 ok = true;
414 } 414 }
415 if(ok) { 415 if(ok) {
416 if(checkBox->isChecked () ) 416 if(checkBox->isChecked () )
417 accept(); 417 accept();
418 } 418 }
419 } 419 }
420} 420}
421 421
422bool LibraryDialog::download_newEtext() 422bool LibraryDialog::download_newEtext()
423{ // ftp method 423{ // ftp method
424 QString fileName = DlglistItemFile; 424 QString fileName = DlglistItemFile;
425 425
426 QString directory; 426 QString directory;
427 int stringlength = DlglistItemFile.length(); 427 int stringlength = DlglistItemFile.length();
428 for(i = 0; i < stringlength - 1; i++ ) { 428 for(i = 0; i < stringlength - 1; i++ ) {
429 directory += "/"+ DlglistItemFile[i]; 429 directory += "/"+ DlglistItemFile[i];
430 } 430 }
431 431
432 directory += "/" + DlglistItemFile; 432 directory += "/" + DlglistItemFile;
433 433
434// qWarning(directory); 434// qWarning(directory);
435 435
436 Config cfg("Gutenbrowser"); 436 Config cfg("Gutenbrowser");
437 cfg.setGroup("FTPsite"); 437 cfg.setGroup("FTPsite");
438 ftp_host = cfg.readEntry("SiteName", "sailor.gutenberg.org"); 438 ftp_host = cfg.readEntry("SiteName", "sailor.gutenberg.org");
439 ftp_base_dir = cfg.readEntry("base", "/pub/gutenberg"); 439 ftp_base_dir = cfg.readEntry("base", "/pub/gutenberg");
440 440
441 if( ftp_base_dir.find("=",0,true) ) 441 if( ftp_base_dir.find("=",0,true) )
442 ftp_base_dir.remove( ftp_base_dir.find("=",0,true),1); 442 ftp_base_dir.remove( ftp_base_dir.find("=",0,true),1);
443 443
444 QString dir = ftp_base_dir + directory; 444 QString dir = ftp_base_dir + directory;
445 QString outputFile = local_library + ".guten_temp"; 445 QString outputFile = local_library + ".guten_temp";
446 QString file = fileName + ".txt"; 446 QString file = fileName + ".txt";
447 447
448 QStringList networkList; 448 QStringList networkList;
449 networkList.append((const char *)ftp_host); //host 449 networkList.append((const char *)ftp_host); //host
450 networkList.append((const char *)dir); //ftp base directory 450 networkList.append((const char *)dir); //ftp base directory
451 networkList.append((const char *)outputFile); //output filepath 451 networkList.append((const char *)outputFile); //output filepath
452 networkList.append((const char *)file); //filename 452 networkList.append((const char *)file); //filename
453 453
454 getEtext( networkList); 454 getEtext( networkList);
455 455
456 return true; 456 return true;
457} 457}
458 458
459bool LibraryDialog::getEtext(const QStringList &networkList) 459bool LibraryDialog::getEtext(const QStringList &networkList)
460{ 460{
461 NetworkDialog *NetworkDlg; 461 NetworkDialog *NetworkDlg;
462 NetworkDlg = new NetworkDialog( this,"Network Protocol Dialog", true, 0, networkList); 462 NetworkDlg = new NetworkDialog( this,"Network Protocol Dialog", true, 0, networkList);
463 463
464// use new, improved, *INSTANT* network-dialog-file-getterer 464 // use new, improved, *INSTANT* network-dialog-file-getterer
465 if( NetworkDlg->exec() != 0 ) { 465 if( NetworkDlg->exec() != 0 ) {
466 File_Name = NetworkDlg->localFileName; 466 File_Name = NetworkDlg->localFileName;
467 467
468 qDebug("Just downloaded " + NetworkDlg->localFileName); 468 qDebug("Just downloaded " + NetworkDlg->localFileName);
469 469
470 if(NetworkDlg->successDownload) { 470 if(NetworkDlg->successDownload) {
471 //odebug << "Filename is "+File_Name << oendl; 471 //odebug << "Filename is "+File_Name << oendl;
472 if(File_Name.right(4) == ".txt") { 472 if(File_Name.right(4) == ".txt") {
473 QString s_fileName = File_Name; 473 QString s_fileName = File_Name;
474 s_fileName.replace( s_fileName.length() - 3, 3, "gtn"); 474 s_fileName.replace( s_fileName.length() - 3, 3, "gtn");
475 // s_fileName.replace( s_fileName.length()-3,3,"etx"); 475 if (rename( File_Name.latin1(), s_fileName.latin1()) == 1) {
476 rename( File_Name.latin1(), s_fileName.latin1()); 476 owarn << "Failed to rename " << File_Name.latin1() << " to "
477 File_Name = s_fileName; 477 << s_fileName.latin1() << oendl;
478 return false;
479 }
478 480
479 //odebug << "Filename is now "+File_Name << oendl; 481 File_Name = s_fileName;
480 482
481 } 483 //odebug << "Filename is now "+File_Name << oendl;
482 if(File_Name.length() > 5 ) {
483 setTitle();
484 QFileInfo fi(File_Name);
485 QString name_file = fi.fileName();
486 name_file = name_file.left( name_file.length() - 4);
487
488 //odebug << "Setting doclink" << oendl;
489 DocLnk lnk;
490 //odebug << "name is "+name_file << oendl;
491 lnk.setName(name_file); //sets file name
492 //odebug << "Title is "+DlglistItemTitle << oendl;
493 lnk.setComment(DlglistItemTitle);
494 484
495 //odebug << "Filename is "+File_Name << oendl;
496 lnk.setFile(File_Name); //sets File property
497 lnk.setType("guten/plain");// hey is this a REGISTERED mime type?!?!? ;D
498 lnk.setExec(File_Name);
499 lnk.setIcon("gutenbrowser/Gutenbrowser");
500 if(!lnk.writeLink()) {
501 //odebug << "Writing doclink did not work" << oendl;
502 } else {
503 } 485 }
504 } else 486 if(File_Name.length() > 5 ) {
505 QMessageBox::message("Note","<p>There was an error with the file</p>"); 487 setTitle();
506 } 488 QFileInfo fi(File_Name);
507 } 489 QString name_file = fi.fileName();
490 name_file = name_file.left( name_file.length() - 4);
491
492 //odebug << "Setting doclink" << oendl;
493 DocLnk lnk;
494 //odebug << "name is "+name_file << oendl;
495 lnk.setName(name_file); //sets file name
496 //odebug << "Title is "+DlglistItemTitle << oendl;
497 lnk.setComment(DlglistItemTitle);
498
499 //odebug << "Filename is "+File_Name << oendl;
500 lnk.setFile(File_Name); //sets File property
501 lnk.setType("guten/plain");// hey is this a REGISTERED mime type?!?!? ;D
502 lnk.setExec(File_Name);
503 lnk.setIcon("gutenbrowser/Gutenbrowser");
504 if(!lnk.writeLink()) {
505 //odebug << "Writing doclink did not work" << oendl;
506 }
507 } else
508 QMessageBox::message("Note","<p>There was an error with the file</p>");
509 }
510 }
508 511
509 return true; 512 return true;
510} 513}
511 514
512bool LibraryDialog::download_Etext() 515bool LibraryDialog::download_Etext()
513{ // ftp method 516{ // ftp method
514 // might have to use old gpl'd ftp for embedded!! 517 // might have to use old gpl'd ftp for embedded!!
515 518
516 Config cfg("Gutenbrowser"); 519 Config cfg("Gutenbrowser");
517 cfg.setGroup("FTPsite"); 520 cfg.setGroup("FTPsite");
518 ftp_host = cfg.readEntry("SiteName", "sailor.gutenberg.org"); 521 ftp_host = cfg.readEntry("SiteName", "sailor.gutenberg.org");
519 ftp_base_dir = cfg.readEntry("base", "/pub/gutenberg"); 522 ftp_base_dir = cfg.readEntry("base", "/pub/gutenberg");
520 523
521 qDebug( "about to network dialog"); 524 qDebug( "about to network dialog");
522 525
523 QString NewlistItemNumber, NewlistItemYear, ls_result, result_line, s, dir, /*networkUrl, */outputFile; 526 QString NewlistItemNumber, NewlistItemYear, ls_result, result_line, s, dir, /*networkUrl, */outputFile;
524 527
525 //////////////////// FIXME- if 'x' is part of real name.... 528 //////////////////// FIXME- if 'x' is part of real name....
526 NewlistItemFile = DlglistItemFile.left(DlglistItemFile.find(".xxx", 1, false)).left(DlglistItemFile.left(DlglistItemFile.find(".xxx", 1, false)).find("x", 1, false)); 529 NewlistItemFile = DlglistItemFile.left(DlglistItemFile.find(".xxx", 1, false)).left(DlglistItemFile.left(DlglistItemFile.find(".xxx", 1, false)).find("x", 1, false));
527 530
528 if( NewlistItemFile.find( DlglistItemFile.left(4) ,0,true) ==-1 ) { 531 if( NewlistItemFile.find( DlglistItemFile.left(4) ,0,true) ==-1 ) {
529 NewlistItemFile.replace( 0,4, DlglistItemFile.left(4)); 532 NewlistItemFile.replace( 0,4, DlglistItemFile.left(4));
530 qDebug("NewlistItemFile is now " + NewlistItemFile); 533 qDebug("NewlistItemFile is now " + NewlistItemFile);
531 } 534 }
532 535
533 NewlistItemYear = DlglistItemYear.right(2); 536 NewlistItemYear = DlglistItemYear.right(2);
534 int NewlistItemYear_Int = NewlistItemYear.toInt(0, 10); 537 int NewlistItemYear_Int = NewlistItemYear.toInt(0, 10);
535 //odebug << NewlistItemYear << oendl; 538 //odebug << NewlistItemYear << oendl;
536 if (NewlistItemYear_Int < 91 && NewlistItemYear_Int > 70) { 539 if (NewlistItemYear_Int < 91 && NewlistItemYear_Int > 70) {
537 NewlistItemYear = "90"; 540 NewlistItemYear = "90";
538 } 541 }
539 542
540 Edir ="etext" +NewlistItemYear; 543 Edir ="etext" +NewlistItemYear;
541 544
542 dir = ftp_base_dir + "/etext" + NewlistItemYear + "/"; 545 dir = ftp_base_dir + "/etext" + NewlistItemYear + "/";
543 546
544 if( ftp_base_dir.find("=",0,true) ) 547 if( ftp_base_dir.find("=",0,true) )
545 ftp_base_dir.remove( ftp_base_dir.find("=",0,true),1); 548 ftp_base_dir.remove( ftp_base_dir.find("=",0,true),1);
546 549
547// networkUrl = "ftp://"+ftp_host+dir; 550// networkUrl = "ftp://"+ftp_host+dir;
548 551
549 outputFile = local_library+".guten_temp"; 552 outputFile = local_library+".guten_temp";
550 553
551 qDebug( "Download file: " +NewlistItemFile); 554 qDebug( "Download file: " +NewlistItemFile);
552 qDebug("Checking: " + ftp_host + " " + dir + " " + outputFile+" " + NewlistItemFile); 555 qDebug("Checking: " + ftp_host + " " + dir + " " + outputFile+" " + NewlistItemFile);
553 556
554 557
555 QStringList networkList; 558 QStringList networkList;
556 networkList.append((const char *)ftp_host); //host 559 networkList.append((const char *)ftp_host); //host
557 networkList.append((const char *)dir); //ftp base directory 560 networkList.append((const char *)dir); //ftp base directory
558 networkList.append((const char *)outputFile); //output filepath 561 networkList.append((const char *)outputFile); //output filepath
559 networkList.append((const char *)NewlistItemFile); //filename 562 networkList.append((const char *)NewlistItemFile); //filename
560//<< (char *)ftp_host << (char *)dir << (char *)outputFile << (char *)NewlistItemFile; 563//<< (char *)ftp_host << (char *)dir << (char *)outputFile << (char *)NewlistItemFile;
561 getEtext( networkList); 564 getEtext( networkList);
562 565
563 return true; 566 return true;
564} 567}
565 568
566bool LibraryDialog::httpDownload() 569bool LibraryDialog::httpDownload()
567{// httpDownload 570{// httpDownload
568#ifndef Q_WS_QWS 571#ifndef Q_WS_QWS
569 Config config("Gutenbrowser"); 572 Config config("Gutenbrowser");
570 config.setGroup( "Browser" ); 573 config.setGroup( "Browser" );
571 QString brow = config.readEntry("Preferred", ""); 574 QString brow = config.readEntry("Preferred", "");
572 QString file_name = "./.guten_temp"; 575 QString file_name = "./.guten_temp";
573 // config.setGroup( "HttpServer" ); 576 // config.setGroup( "HttpServer" );
574 // QString s_http = config.readEntry("Preferred", "http://sailor.gutenbook.org"); 577 // QString s_http = config.readEntry("Preferred", "http://sailor.gutenbook.org");
575 QString httpName = proxy_http + "/"+Edir; 578 QString httpName = proxy_http + "/"+Edir;
576 // progressBar->setProgress( i); 579 // progressBar->setProgress( i);
577 i++; 580 i++;
578 if ( brow != "Konq") { /////////// use lynx 581 if ( brow != "Konq") { /////////// use lynx
579 // QString cmd = "lynx -source " + httpName +" | cat >> " + file_name; 582 // QString cmd = "lynx -source " + httpName +" | cat >> " + file_name;
580 // system(cmd); 583 // system(cmd);
581 } else { //////////// use KFM 584 } else { //////////// use KFM
582 // KFM::download( httpName, file_name); 585 // KFM::download( httpName, file_name);
583 } 586 }
584 i++; 587 i++;
585 QFile tmp( file_name); 588 QFile tmp( file_name);
586 QString str; 589 QString str;
587 if (tmp.open(IO_ReadOnly)) { 590 if (tmp.open(IO_ReadOnly)) {
588 QTextStream t( &tmp ); // use a text stream 591 QTextStream t( &tmp ); // use a text stream
589 while ( !t.eof()) { 592 while ( !t.eof()) {
590 QString s = t.readLine(); 593 QString s = t.readLine();
591 if (s.contains( NewlistItemFile, false) && (s.contains(".txt")) ) { 594 if (s.contains( NewlistItemFile, false) && (s.contains(".txt")) ) {
592 str = s.mid( s.find( ".txt\">"+NewlistItemFile, 0, true)+6, (s.find( ".txt</A>", 0, true) + 4) - ( s.find( ".txt\">"+NewlistItemFile, 0, true)+6 ) ); 595 str = s.mid( s.find( ".txt\">"+NewlistItemFile, 0, true)+6, (s.find( ".txt</A>", 0, true) + 4) - ( s.find( ".txt\">"+NewlistItemFile, 0, true)+6 ) );
593 httpName += "/" + str; 596 httpName += "/" + str;
594 } 597 }
595 } //end of while loop 598 } //end of while loop
596 } 599 }
597 tmp.close(); 600 tmp.close();
598 m_getFilePath = local_library + str; 601 m_getFilePath = local_library + str;
599 i++; 602 i++;
600 if ( brow != "KFM"){ ///////// use lynx 603 if ( brow != "KFM"){ ///////// use lynx
601 QString cmd = "lynx -source " + httpName +" | cat >> " + m_getFilePath; 604 QString cmd = "lynx -source " + httpName +" | cat >> " + m_getFilePath;
602 // QMessageBox::message("Error", cmd); 605 // QMessageBox::message("Error", cmd);
603 system(cmd); 606 system(cmd);
604 } else { ////////// use KFM 607 } else { ////////// use KFM
605 // KFM::download( httpName, m_getFilePath); 608 // KFM::download( httpName, m_getFilePath);
606 } 609 }
607 i++; 610 i++;
608#endif 611#endif
609 return false; 612 return false;
610} 613}
611 614
612void LibraryDialog::cancelIt() 615void LibraryDialog::cancelIt()
613{ 616{
614 saveConfig(); 617 saveConfig();
615 618
616 DlglistItemNumber = ""; 619 DlglistItemNumber = "";
617 this->reject(); 620 this->reject();
618} 621}
619 622
620bool LibraryDialog::setTitle() 623bool LibraryDialog::setTitle()
621{ 624{
622 Config config("Gutenbrowser"); 625 Config config("Gutenbrowser");
623 //odebug << "setting title" << oendl; 626 //odebug << "setting title" << oendl;
624 //odebug << DlglistItemTitle << oendl; 627 //odebug << DlglistItemTitle << oendl;
625 628
626 if( DlglistItemTitle.find("[",0,true) != -1) 629 if( DlglistItemTitle.find("[",0,true) != -1)
627 DlglistItemTitle.replace(DlglistItemTitle.find("[",0,true),1, "(" ); 630 DlglistItemTitle.replace(DlglistItemTitle.find("[",0,true),1, "(" );
628 if( DlglistItemTitle.find("]",0,true) !=-1) 631 if( DlglistItemTitle.find("]",0,true) !=-1)
629 DlglistItemTitle.replace(DlglistItemTitle.find("]",0,true),1, ")" ); 632 DlglistItemTitle.replace(DlglistItemTitle.find("]",0,true),1, ")" );
630 //odebug << "Title being set is "+DlglistItemTitle << oendl; 633 //odebug << "Title being set is "+DlglistItemTitle << oendl;
631 int test = 0; 634 int test = 0;
632 QString ramble, temp; 635 QString ramble, temp;
633 config.setGroup("Files"); 636 config.setGroup("Files");
634 QString s_numofFiles = config.readEntry("NumberOfFiles", "0" ); 637 QString s_numofFiles = config.readEntry("NumberOfFiles", "0" );
635 int i_numofFiles = s_numofFiles.toInt(); 638 int i_numofFiles = s_numofFiles.toInt();
636 for ( int i = 0; i <= i_numofFiles; i++){ 639 for ( int i = 0; i <= i_numofFiles; i++){
637 temp.setNum( i); 640 temp.setNum( i);
638 ramble = config.readEntry( temp, "" ); 641 ramble = config.readEntry( temp, "" );
639 if( strcmp( ramble, File_Name) == 0){ 642 if( strcmp( ramble, File_Name) == 0){
640 test = 1; 643 test = 1;
641 } 644 }
642 } 645 }
643 646
644 if(test == 0 ) { 647 if(test == 0 ) {
645 648
646 config.setGroup("Files"); 649 config.setGroup("Files");
647 config.writeEntry( "NumberOfFiles", i_numofFiles +1 ); 650 config.writeEntry( "NumberOfFiles", i_numofFiles +1 );
648 QString interger; 651 QString interger;
649 interger.setNum( i_numofFiles +1); 652 interger.setNum( i_numofFiles +1);
650 config.writeEntry( interger, File_Name); 653 config.writeEntry( interger, File_Name);
651 config.setGroup( "Titles" ); 654 config.setGroup( "Titles" );
652 config.writeEntry( File_Name, DlglistItemTitle); 655 config.writeEntry( File_Name, DlglistItemTitle);
653 } 656 }
654 test = 0; 657 test = 0;
655 return true; 658 return true;
656} 659}
657 660
658 661
659void LibraryDialog::saveConfig() 662void LibraryDialog::saveConfig()
660{ 663{
661 Config config("Gutenbrowser"); 664 Config config("Gutenbrowser");
662 if( httpBox->isChecked() == true) { 665 if( httpBox->isChecked() == true) {
663 checked = 1; 666 checked = 1;
664 config.setGroup( "Proxy" ); 667 config.setGroup( "Proxy" );
665 config.writeEntry("IsChecked", "true"); 668 config.writeEntry("IsChecked", "true");
666 } else { 669 } else {
667 checked = 0; 670 checked = 0;
668 config.setGroup( "Proxy" ); 671 config.setGroup( "Proxy" );
669 config.writeEntry("IsChecked", "false"); 672 config.writeEntry("IsChecked", "false");
670 } 673 }
671 if (authBox->isChecked() == true) { 674 if (authBox->isChecked() == true) {
672 config.setGroup("SortAuth"); 675 config.setGroup("SortAuth");
673 config.writeEntry("authSort", "true"); 676 config.writeEntry("authSort", "true");
674 } else { 677 } else {
675 config.setGroup("SortAuth"); 678 config.setGroup("SortAuth");
676 config.writeEntry("authSort", "false"); 679 config.writeEntry("authSort", "false");
677 } 680 }
678 // config.write(); 681 // config.write();
679} 682}
680 683
681/* 684/*
682 searches library index for user word*/ 685 searches library index for user word*/
683void LibraryDialog::onButtonSearch() 686void LibraryDialog::onButtonSearch()
684{ 687{
685 ListView1->clearSelection(); 688 ListView1->clearSelection();
686 ListView2->clearSelection(); 689 ListView2->clearSelection();
687 ListView3->clearSelection(); 690 ListView3->clearSelection();
688 ListView4->clearSelection(); 691 ListView4->clearSelection();
689 ListView5->clearSelection(); 692 ListView5->clearSelection();
690 693
691 int curTab = tabWidget->currentPageIndex(); 694 int curTab = tabWidget->currentPageIndex();
692 SearchDialog* searchDlg; 695 SearchDialog* searchDlg;
693 696
694 // if( resultsList) 697 // if( resultsList)
695 searchDlg = new SearchDialog( this, "Library Search", true); 698 searchDlg = new SearchDialog( this, "Library Search", true);
696 searchDlg->setCaption( tr( "Library Search" ) ); 699 searchDlg->setCaption( tr( "Library Search" ) );
697 searchDlg->setLabel( "- author or title"); 700 searchDlg->setLabel( "- author or title");
698 701
699 QString resultString; 702 QString resultString;
700 703
701 int i_berger = 0; 704 int i_berger = 0;
702 if( searchDlg->exec() != 0 ) { 705 if( searchDlg->exec() != 0 ) {
703 QString searcherStr = searchDlg->get_text(); 706 QString searcherStr = searchDlg->get_text();
704 int fluff = 0;
705 707
706 bool cS; 708 bool cS;
707 if( searchDlg->caseSensitiveCheckBox->isChecked()) 709 if( searchDlg->caseSensitiveCheckBox->isChecked())
708 cS = true; //case sensitive 710 cS = true; //case sensitive
709 else 711 else
710 cS = false; 712 cS = false;
711 713
712 etext etextStruct; 714 etext etextStruct;
713 QValueList<etext>::Iterator it; 715 QValueList<etext>::Iterator it;
714 716
715 for( it = etextLibrary.begin(); it != etextLibrary.end(); ++it ) { 717 for( it = etextLibrary.begin(); it != etextLibrary.end(); ++it ) {
716 QString tempTitle = (*it).title; 718 QString tempTitle = (*it).title;
717 QString tempAuthor = (*it).author; 719 QString tempAuthor = (*it).author;
718 QString tempFile = (*it).file; 720 QString tempFile = (*it).file;
719 QString tempYear = (*it).year; 721 QString tempYear = (*it).year;
720 if(tempTitle.find( searcherStr, 0, cS) != -1 722 if(tempTitle.find( searcherStr, 0, cS) != -1
721 || tempAuthor.find( searcherStr, 0, cS) != -1) { 723 || tempAuthor.find( searcherStr, 0, cS) != -1) {
722 qWarning(tempTitle); 724 qWarning(tempTitle);
723 Searchlist.append( tempTitle + " : " + tempYear + " : " + tempFile); 725 Searchlist.append( tempTitle + " : " + tempYear + " : " + tempFile);
724 } 726 }
725 } 727 }
726 728
727 729
728 tabWidget->setCurrentPage( curTab); 730 tabWidget->setCurrentPage( curTab);
729 731
730 Searchlist.sort(); 732 Searchlist.sort();
731 SearchResultsDlg* SearchResultsDialog; 733 SearchResultsDlg* SearchResultsDialog;
732 SearchResultsDialog = new SearchResultsDlg( searchDlg, "Results Dialog", true, 0 , Searchlist); 734 SearchResultsDialog = new SearchResultsDlg( searchDlg, "Results Dialog", true, 0 , Searchlist);
733 735
734 SearchResultsDialog->showMaximized(); 736 SearchResultsDialog->showMaximized();
735 if( SearchResultsDialog->exec() != 0) { 737 if( SearchResultsDialog->exec() != 0) {
736 texter = SearchResultsDialog->selText; 738 texter = SearchResultsDialog->selText;
737 // //odebug << texter << oendl; 739 // //odebug << texter << oendl;
738 resultLs = SearchResultsDialog->resultsList; 740 resultLs = SearchResultsDialog->resultsList;
739 i_berger = 1; 741 i_berger = 1;
740 } else { 742 } else {
741 resultLs.clear(); 743 resultLs.clear();
742 } 744 }
743 Searchlist.clear(); 745 Searchlist.clear();
744 746
745 QString tester; 747 QString tester;
746 for ( QStringList::Iterator it = resultLs.begin(); it != resultLs.end(); ++it ) { 748 for ( QStringList::Iterator it = resultLs.begin(); it != resultLs.end(); ++it ) {
747 texter.sprintf("%s \n",(*it).latin1()); 749 texter.sprintf("%s \n",(*it).latin1());
748 // //odebug << texter << oendl; 750 // //odebug << texter << oendl;
749 if( tester!=texter) 751 if( tester!=texter)
750 parseSearchResults( texter); 752 parseSearchResults( texter);
751 tester = texter; 753 tester = texter;
752 } 754 }
753 if(searchDlg) 755 if(searchDlg)
754 delete searchDlg; 756 delete searchDlg;
755 } 757 }
756 if(checkBox->isChecked() ) { 758 if(checkBox->isChecked() ) {
757 accept(); 759 accept();
758 } else { 760 } else {
759 setActiveWindow(); 761 setActiveWindow();
760 } 762 }
761} 763}
762 764
763/* 765/*
764 splits the result string and calls download for the current search result*/ 766 splits the result string and calls download for the current search result*/
765void LibraryDialog::parseSearchResults( QString resultStr) 767void LibraryDialog::parseSearchResults( QString resultStr)
766{ 768{
767 int stringLeng = resultStr.length(); 769 int stringLeng = resultStr.length();
768 770
769 QString my; 771 QString my;
770 my.setNum( stringLeng, 10); 772 my.setNum( stringLeng, 10);
771 773
772 if( resultStr.length() > 2 && resultStr.length() < 130) { 774 if( resultStr.length() > 2 && resultStr.length() < 130) {
773 QStringList token = QStringList::split(" : ", resultStr); 775 QStringList token = QStringList::split(" : ", resultStr);
774 776
775 DlglistItemTitle = token[0]; 777 DlglistItemTitle = token[0];
776 DlglistItemTitle = DlglistItemTitle.stripWhiteSpace(); 778 DlglistItemTitle = DlglistItemTitle.stripWhiteSpace();
777 779
778 DlglistItemYear = token[1]; 780 DlglistItemYear = token[1];
779 DlglistItemYear = DlglistItemYear.stripWhiteSpace(); 781 DlglistItemYear = DlglistItemYear.stripWhiteSpace();
780 782
781 DlglistItemFile = token[2]; 783 DlglistItemFile = token[2];
782 784
783 DlglistItemFile = DlglistItemFile.stripWhiteSpace(); 785 DlglistItemFile = DlglistItemFile.stripWhiteSpace();
784 786
785// qWarning(DlglistItemYear); 787// qWarning(DlglistItemYear);
786 788
787 789
788 if(DlglistItemFile.left(1) == "/") 790 if(DlglistItemFile.left(1) == "/")
789 DlglistItemFile = DlglistItemFile.right( DlglistItemFile.length() - 1); 791 DlglistItemFile = DlglistItemFile.right( DlglistItemFile.length() - 1);
790 792
791 if(DlglistItemFile.toInt() > 10000 || DlglistItemYear == "1980" ) { 793 if(DlglistItemFile.toInt() > 10000 || DlglistItemYear == "1980" ) {
792 // new directory sturcture 794 // new directory sturcture
793 download_newEtext(); //) 795 download_newEtext(); //)
794 } else { 796 } else {
795 download_Etext(); //) 797 download_Etext(); //)
796 } 798 }
797 } 799 }
798} 800}
799 801
800void LibraryDialog::sortLists(int index) 802void LibraryDialog::sortLists(int index)
801{ 803{
802 804
803 ListView1->setSorting(index); 805 ListView1->setSorting(index);
804 ListView2->setSorting(index); 806 ListView2->setSorting(index);
805 ListView3->setSorting(index); 807 ListView3->setSorting(index);
806 ListView4->setSorting(index); 808 ListView4->setSorting(index);
807 ListView5->setSorting(index); 809 ListView5->setSorting(index);
808 ListView1->sort(); 810 ListView1->sort();
809 ListView2->sort(); 811 ListView2->sort();
810 ListView3->sort(); 812 ListView3->sort();
811 ListView4->sort(); 813 ListView4->sort();
812 ListView5->sort(); 814 ListView5->sort();
813} 815}
814 816
815/* 817/*
816 Downloads the current selected listitem*/ 818 Downloads the current selected listitem*/
817bool LibraryDialog::getItem(QListViewItem *it) 819bool LibraryDialog::getItem(QListViewItem *it)
818{ 820{
819 // //odebug << "selected getItem" << oendl; 821 // //odebug << "selected getItem" << oendl;
820 822
821 // DlglistItemNumber = it->text(0); 823 // DlglistItemNumber = it->text(0);
822 DlglistItemTitle = it->text(0); 824 DlglistItemTitle = it->text(0);
823 DlglistItemYear = it->text(2); 825 DlglistItemYear = it->text(2);
824 DlglistItemFile = it->text(3); 826 DlglistItemFile = it->text(3);
825 827
826 if(download_Etext()) { 828 if(download_Etext()) {
827 if(i_binary == 1) { 829 if(i_binary == 1) {
828 } 830 }
829 } 831 }
830 return true; 832 return true;
831} 833}
832 834
833/* 835/*
834 download button is pushed so we get the current items to download*/ 836 download button is pushed so we get the current items to download*/
835bool LibraryDialog::onButtonDownload() 837bool LibraryDialog::onButtonDownload()
836{ 838{
837 // //odebug << "selected onButtonDownloadz" << oendl; 839 // //odebug << "selected onButtonDownloadz" << oendl;
838 840
839 QListViewItemIterator it1( ListView1 ); 841 QListViewItemIterator it1( ListView1 );
840 QListViewItemIterator it2( ListView2 ); 842 QListViewItemIterator it2( ListView2 );
841 QListViewItemIterator it3( ListView3 ); 843 QListViewItemIterator it3( ListView3 );
842 QListViewItemIterator it4( ListView4 ); 844 QListViewItemIterator it4( ListView4 );
843 QListViewItemIterator it5( ListView5 ); 845 QListViewItemIterator it5( ListView5 );
844 846
845 // iterate through all items of the listview 847 // iterate through all items of the listview
846 for ( ; it1.current(); ++it1 ) { 848 for ( ; it1.current(); ++it1 ) {
847 if ( it1.current()->isSelected() ) 849 if ( it1.current()->isSelected() )
848 getItem(it1.current()); 850 getItem(it1.current());
849 it1.current()->setSelected(false); 851 it1.current()->setSelected(false);
850 } 852 }
851 for ( ; it2.current(); ++it2 ) { 853 for ( ; it2.current(); ++it2 ) {
852 if ( it2.current()->isSelected() ) 854 if ( it2.current()->isSelected() )
853 getItem(it2.current()); 855 getItem(it2.current());
854 it2.current()->setSelected(false); 856 it2.current()->setSelected(false);
855 } 857 }
856 for ( ; it3.current(); ++it3 ) { 858 for ( ; it3.current(); ++it3 ) {
857 if ( it3.current()->isSelected() ) 859 if ( it3.current()->isSelected() )
858 getItem(it3.current()); 860 getItem(it3.current());
859 it3.current()->setSelected(false); 861 it3.current()->setSelected(false);
860 } 862 }
861 for ( ; it4.current(); ++it4 ) { 863 for ( ; it4.current(); ++it4 ) {
862 if ( it4.current()->isSelected() ) 864 if ( it4.current()->isSelected() )
863 getItem(it4.current()); 865 getItem(it4.current());
864 it4.current()->setSelected(false); 866 it4.current()->setSelected(false);
865 } 867 }
866 for ( ; it5.current(); ++it5 ) { 868 for ( ; it5.current(); ++it5 ) {
867 if ( it5.current()->isSelected() ) 869 if ( it5.current()->isSelected() )
868 getItem(it5.current()); 870 getItem(it5.current());
869 it5.current()->setSelected(false); 871 it5.current()->setSelected(false);
870 } 872 }
871 return true; 873 return true;
872} 874}
873 875
874 876
875/* 877/*
876 handles the sorting combo box */ 878 handles the sorting combo box */
877void LibraryDialog::comboSelect(int index) 879void LibraryDialog::comboSelect(int index)
878{ 880{
879 // //odebug << "we are sorting" << oendl; 881 // //odebug << "we are sorting" << oendl;
880 ListView1->setSorting( index, true); 882 ListView1->setSorting( index, true);
881 ListView2->setSorting( index, true); 883 ListView2->setSorting( index, true);
882 ListView3->setSorting( index, true); 884 ListView3->setSorting( index, true);
883 ListView4->setSorting( index, true); 885 ListView4->setSorting( index, true);
884 ListView5->setSorting( index, true); 886 ListView5->setSorting( index, true);
885 887
886 ListView1->sort(); 888 ListView1->sort();
887 ListView2->sort(); 889 ListView2->sort();
888 ListView3->sort(); 890 ListView3->sort();
889 ListView4->sort(); 891 ListView4->sort();
890 ListView5->sort(); 892 ListView5->sort();
891 893
892 // ListView1->triggerUpdate(); 894 // ListView1->triggerUpdate();
893 // ListView2->triggerUpdate(); 895 // ListView2->triggerUpdate();
894 // ListView3->triggerUpdate(); 896 // ListView3->triggerUpdate();
895 // ListView4->triggerUpdate(); 897 // ListView4->triggerUpdate();
896 // ListView5->triggerUpdate(); 898 // ListView5->triggerUpdate();
897} 899}
898 900
899void LibraryDialog::newList() 901void LibraryDialog::newList()
900{ 902{
901 if(indexLoaded) { 903 if(indexLoaded) {
902 onButtonDownload(); 904 onButtonDownload();
903 } else { 905 } else {
904 Output *outDlg; 906 Output *outDlg;
905 buttonNewList->setDown(true); 907 buttonNewList->setDown(true);
906 //odebug << "changing dir "+QPEApplication::qpeDir()+"etc/gutenbrowser" << oendl; 908 //odebug << "changing dir "+QPEApplication::qpeDir()+"etc/gutenbrowser" << oendl;
907 QString gutenindex1 = local_library + "/GUTINDEX.ALL"; 909 QString gutenindex1 = local_library + "/GUTINDEX.ALL";
908 910
909 QString cmd="wget -O " + gutenindex1 + " http://www.gutenberg.org/dirs/GUTINDEX.ALL 2>&1"; 911 QString cmd="wget -O " + gutenindex1 + " http://www.gutenberg.org/dirs/GUTINDEX.ALL 2>&1";
910 912
911 int result = QMessageBox::warning( this,"Download" 913 int result = QMessageBox::warning( this,"Download"
912 ,"<p>Ok to use /'wget/' to download a new library list?</P>" 914 ,"<p>Ok to use /'wget/' to download a new library list?</P>"
913 ,"Yes","No",0,0,1); 915 ,"Yes","No",0,0,1);
914 qApp->processEvents(); 916 qApp->processEvents();
915 if(result == 0) { 917 if(result == 0) {
916 outDlg = new Output( 0, tr("Downloading Gutenberg Index...."),true); 918 outDlg = new Output( 0, tr("Downloading Gutenberg Index...."),true);
917 outDlg->showMaximized(); 919 outDlg->showMaximized();
918 outDlg->show(); 920 outDlg->show();
919 qApp->processEvents(); 921 qApp->processEvents();
920 FILE *fp; 922 FILE *fp;
921 char line[130]; 923 char line[130];
922 outDlg->OutputEdit->append( tr("Running wget") ); 924 outDlg->OutputEdit->append( tr("Running wget") );
923 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false); 925 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false);
924 sleep(1); 926 sleep(1);
925 fp = popen( (const char *) cmd, "r"); 927 fp = popen( (const char *) cmd, "r");
926 if ( !fp ) { 928 if ( !fp ) {
927 } else { 929 } else {
928 //odebug << "Issuing the command\n"+cmd << oendl; 930 //odebug << "Issuing the command\n"+cmd << oendl;
929 // system(cmd); 931 // system(cmd);
930 while ( fgets( line, sizeof line, fp)) { 932 while ( fgets( line, sizeof line, fp)) {
931 outDlg->OutputEdit->append(line); 933 outDlg->OutputEdit->append(line);
932 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false); 934 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false);
933 } 935 }
934 pclose(fp); 936 pclose(fp);
935 outDlg->OutputEdit->append("Finished downloading\n"); 937 outDlg->OutputEdit->append("Finished downloading\n");
936 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false); 938 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,false);
937 qApp->processEvents(); 939 qApp->processEvents();
938 940
939 // if( QFile(gutenindex1).exists() ) { 941 // if( QFile(gutenindex1).exists() ) {
940 // QString gutenindex=QPEApplication::qpeDir()+"etc/gutenbrowser/GUTINDEX.ALL"; 942 // QString gutenindex=QPEApplication::qpeDir()+"etc/gutenbrowser/GUTINDEX.ALL";
941 // if( rename(gutenindex1.latin1(),gutenindex.latin1()) !=0) 943 // if( rename(gutenindex1.latin1(),gutenindex.latin1()) !=0)
942 // //odebug << "renaming error" << oendl; 944 // //odebug << "renaming error" << oendl;
943 // } 945 // }
944 946
945 } 947 }
946 // outDlg->close(); 948 // outDlg->close();
947 FindLibrary(); 949 FindLibrary();
948 if(outDlg) delete outDlg; 950 if(outDlg) delete outDlg;
949 } 951 }
950 buttonNewList->setDown(false); 952 buttonNewList->setDown(false);
951 953
952 // if(outDlg) 954 // if(outDlg)
953 // delete outDlg; 955 // delete outDlg;
954 } 956 }
955} 957}
956 958
957bool LibraryDialog::moreInfo() 959bool LibraryDialog::moreInfo()
958{ 960{
959 961
960 QListViewItem * item; 962 QListViewItem * item;
961 item = 0; 963 item = 0;
962 QString titleString; 964 QString titleString;
963 item = ListView1->currentItem(); 965 item = ListView1->currentItem();
964 if( item != 0) { 966 if( item != 0) {
965 titleString = item->text(0); 967 titleString = item->text(0);
966 ListView1->clearSelection(); 968 ListView1->clearSelection();
967 item = 0; 969 item = 0;
968 } 970 }
969 if( item == 0) 971 if( item == 0)
970 item = ListView2->currentItem(); 972 item = ListView2->currentItem();
971 if( item != 0) { 973 if( item != 0) {
972 titleString = item->text(0); 974 titleString = item->text(0);
973 ListView2->clearSelection(); 975 ListView2->clearSelection();
974 item = 0; 976 item = 0;
975 } 977 }
976 if( item == 0) 978 if( item == 0)
977 item = ListView3->currentItem(); 979 item = ListView3->currentItem();
978 if( item != 0) { 980 if( item != 0) {
979 titleString = item->text(0); 981 titleString = item->text(0);
980 ListView3->clearSelection(); 982 ListView3->clearSelection();
981 item = 0; 983 item = 0;
982 } 984 }
983 if( item == 0) 985 if( item == 0)
984 item = ListView4->currentItem(); 986 item = ListView4->currentItem();
985 if( item != 0) { 987 if( item != 0) {
986 titleString = item->text(0); 988 titleString = item->text(0);
987 ListView4->clearSelection(); 989 ListView4->clearSelection();
988 item = 0; 990 item = 0;
989 } 991 }
990 if( item == 0) 992 if( item == 0)
991 item = ListView5->currentItem(); 993 item = ListView5->currentItem();
992 if( item != 0) { 994 if( item != 0) {
993 titleString = item->text(0); 995 titleString = item->text(0);
994 ListView5->clearSelection(); 996 ListView5->clearSelection();
995 item = 0; 997 item = 0;
996 } 998 }
997 item=0; 999 item=0;
998 if(titleString.length()>2) { 1000 if(titleString.length()>2) {
999 //odebug << "Title is "+titleString << oendl; 1001 //odebug << "Title is "+titleString << oendl;
1000 titleString.replace( QRegExp("\\s"), "%20"); 1002 titleString.replace( QRegExp("\\s"), "%20");
1001 titleString.replace( QRegExp("'"), "%20"); 1003 titleString.replace( QRegExp("'"), "%20");
1002 titleString.replace( QRegExp("\""), "%20"); 1004 titleString.replace( QRegExp("\""), "%20");
1003 titleString.replace( QRegExp("&"), "%20"); 1005 titleString.replace( QRegExp("&"), "%20");
1004 QString cmd= "http://google.com/search?q="+titleString+"&num=30&sa=Google+Search"; 1006 QString cmd= "http://google.com/search?q="+titleString+"&num=30&sa=Google+Search";
1005 cmd="opera "+cmd; 1007 cmd="opera "+cmd;
1006 system(cmd); 1008 system(cmd);
1007 } else 1009 } else
1008 QMessageBox::message( "Note","<p>If you select a title, this will search google.com for that title.</p>"); 1010 QMessageBox::message( "Note","<p>If you select a title, this will search google.com for that title.</p>");
1009 return true; 1011 return true;
1010 1012
1011} 1013}
1012 1014
1013/* 1015/*
1014 This loads the library Index*/ 1016 This loads the library Index*/
1015void LibraryDialog::FindLibrary() 1017void LibraryDialog::FindLibrary()
1016{ 1018{
1017 buttonLibrary->setDown(true); 1019 buttonLibrary->setDown(true);
1018 1020
1019 qApp->processEvents(); 1021 qApp->processEvents();
1020 if( QFile( new_index).exists() /* && this->isHidden() */) { 1022 if( QFile( new_index).exists() /* && this->isHidden() */) {
1021 newindexLib.setName( new_index); 1023 newindexLib.setName( new_index);
1022 indexLib.setName( new_index); 1024 indexLib.setName( new_index);
1023 //odebug << "index file is "+ new_index << oendl; 1025 //odebug << "index file is "+ new_index << oendl;
1024 Newlibrary(); 1026 Newlibrary();
1025 } else { 1027 } else {
1026 newindexLib.setName( old_index); 1028 newindexLib.setName( old_index);
1027 indexLib.setName( old_index); 1029 indexLib.setName( old_index);
1028 //odebug << "new index nameis "+ old_index << oendl; 1030 //odebug << "new index nameis "+ old_index << oendl;
1029 Library(); 1031 Library();
1030 } 1032 }
1031 indexLoaded =true; 1033 indexLoaded =true;
1032 buttonSearch->setEnabled(true); 1034 buttonSearch->setEnabled(true);
1033 moreInfoButton->setEnabled(true); 1035 moreInfoButton->setEnabled(true);
1034 1036
1035 buttonLibrary->setDown(false); 1037 buttonLibrary->setDown(false);
1036 buttonNewList->setText("Download"); 1038 buttonNewList->setText("Download");
1037 qApp->processEvents(); 1039 qApp->processEvents();
1038 1040
1039} 1041}
1040 1042
1041void LibraryDialog::cleanStrings() { 1043void LibraryDialog::cleanStrings() {
1042 year = year.stripWhiteSpace(); 1044 year = year.stripWhiteSpace();
1043 file = file.stripWhiteSpace(); 1045 file = file.stripWhiteSpace();
1044 title = title.stripWhiteSpace(); 1046 title = title.stripWhiteSpace();
1045 number = number.stripWhiteSpace(); 1047 number = number.stripWhiteSpace();
1046 1048
1047} 1049}
1048 1050
1049void LibraryDialog::authBoxClicked() 1051void LibraryDialog::authBoxClicked()
1050{ 1052{
1051 qApp->processEvents(); 1053 qApp->processEvents();
1052 FindLibrary(); 1054 FindLibrary();
1053} 1055}
diff --git a/noncore/apps/opie-gutenbrowser/openetext.cpp b/noncore/apps/opie-gutenbrowser/openetext.cpp
index 0267416..a5d855d 100644
--- a/noncore/apps/opie-gutenbrowser/openetext.cpp
+++ b/noncore/apps/opie-gutenbrowser/openetext.cpp
@@ -1,521 +1,513 @@
1/*************************************************************************** 1/***************************************************************************
2 openetext.cpp - description 2 openetext.cpp - description
3 begin : Sat Dec 4 1999 3 begin : Sat Dec 4 1999
4 begin : Tue Jul 25 2000 4 begin : Tue Jul 25 2000
5 copyright : (C) 2000 -2004 by llornkcor 5 copyright : (C) 2000 -2004 by llornkcor
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 ***************************************************************************/ 7 ***************************************************************************/
8/*************************************************************************** 8/***************************************************************************
9 * This program is free software; you can redistribute it and/or modify * 9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by * 10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or * 11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. * 12 * (at your option) any later version. *
13 ***************************************************************************/ 13 ***************************************************************************/
14 14
15#include "gutenbrowser.h" 15#include "gutenbrowser.h"
16#include "openetext.h" 16#include "openetext.h"
17#include "editTitle.h" 17#include "editTitle.h"
18 18
19/* OPIE */ 19/* OPIE */
20#include <opie2/ofiledialog.h> 20#include <opie2/ofiledialog.h>
21#include <opie2/odebug.h> 21#include <opie2/odebug.h>
22#include <qpe/applnk.h> 22#include <qpe/applnk.h>
23#include <qpe/config.h> 23#include <qpe/config.h>
24#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
25using namespace Opie::Ui; 25using namespace Opie::Ui;
26 26
27/* QT */ 27/* QT */
28#include <qtextstream.h> 28#include <qtextstream.h>
29#include <qfileinfo.h> 29#include <qfileinfo.h>
30 30
31/* STD */ 31/* STD */
32#if defined(_WS_WIN_) 32#if defined(_WS_WIN_)
33#include <windows.h> 33#include <windows.h>
34#else 34#else
35#include <unistd.h> 35#include <unistd.h>
36#include <stdlib.h> 36#include <stdlib.h>
37#include <sys/stat.h> 37#include <sys/stat.h>
38#endif 38#endif
39 39
40OpenEtext::OpenEtext(QWidget *parent, QString name) : QDialog(parent,name,true) 40OpenEtext::OpenEtext(QWidget *parent, QString name) : QDialog(parent,name,true)
41{ 41{
42 local_library = (QDir::homeDirPath ()) +"/Applications/gutenbrowser/"; 42 local_library = (QDir::homeDirPath ()) +"/Applications/gutenbrowser/";
43 local_index=local_library+"GUTINDEX.ALL"; 43 local_index=local_library+"GUTINDEX.ALL";
44 initDialog(); 44 initDialog();
45 connect( QListBox_1, SIGNAL(selected ( int)),this, SLOT(select_title(int)) ); 45 connect( QListBox_1, SIGNAL(selected ( int)),this, SLOT(select_title(int)) );
46 46
47 getTitles(); 47 getTitles();
48} 48}
49 49
50OpenEtext::~OpenEtext() 50OpenEtext::~OpenEtext()
51{ 51{
52} 52}
53 53
54void OpenEtext::getTitles() 54void OpenEtext::getTitles()
55{ 55{
56 QListBox_1->clear(); 56 QListBox_1->clear();
57 Config config("Gutenbrowser"); 57 Config config("Gutenbrowser");
58 config.setGroup( "Files" ); 58 config.setGroup( "Files" );
59 s_numofFiles = config.readEntry("NumberOfFiles", "0"); 59 s_numofFiles = config.readEntry("NumberOfFiles", "0");
60 QLabel_1->setText( tr( 60 QLabel_1->setText( tr( s_numofFiles+" etexts in your library." ) );
61 s_numofFiles+" etexts in your library."));
62 int i_numofFiles = s_numofFiles.toInt(); 61 int i_numofFiles = s_numofFiles.toInt();
63 for (int i = 1; i <= i_numofFiles+1; i++) { 62 for (int i = 1; i <= i_numofFiles+1; i++) {
64 QString temp; 63 QString temp;
65 temp.setNum(i); 64 temp.setNum(i);
66 config.setGroup( "Files" ); 65 config.setGroup( "Files" );
67 QString ramble = config.readEntry(temp, "" ); 66 QString ramble = config.readEntry(temp, "" );
68 config.setGroup( "Titles" ); 67 config.setGroup( "Titles" );
69 title = config.readEntry(ramble, ""); 68 title = config.readEntry(ramble, "");
70 if( !title.isEmpty()) { 69 if( !title.isEmpty()) {
71 QListBox_1->insertItem ( QPixmap( QPEApplication::qpeDir()+"pics/gutenbrowser/gutenbrowser_sm.png"), title, -1); 70 QListBox_1->insertItem ( QPixmap(
71 QPEApplication::qpeDir() +
72 "pics/gutenbrowser/gutenbrowser_sm.png"
73 ),
74 title,
75 -1);
72 } 76 }
73 } 77 }
74} 78}
75 79
76/* 80/*
77 opens selected title */ 81 opens selected title */
78void OpenEtext::OpenTitle() 82void OpenEtext::OpenTitle()
79{ 83{
80 if( QListBox_1->currentItem() != -1) 84 if( QListBox_1->currentItem() != -1)
81 select_title( QListBox_1->currentItem() ); 85 select_title( QListBox_1->currentItem() );
82 else { 86 else {
83 QString sMsg; 87 QString sMsg;
84 sMsg = "You must select an Etext to open"; 88 sMsg = "You must select an Etext to open";
85 QMessageBox::message( "Error",sMsg); 89 QMessageBox::message( "Error",sMsg);
86 } 90 }
87} 91}
88 92
89void OpenEtext::select_title(int index ) 93void OpenEtext::select_title(int index )
90{ 94{
91 OpenButton->setDown(TRUE); 95 OpenButton->setDown(TRUE);
92 QString temp; 96 QString temp;
93 temp.setNum( index + 1); 97 temp.setNum( index + 1);
94 const char * title; 98 const char * title;
95 title = QListBox_1->text( index ); 99 title = QListBox_1->text( index );
96 openFileTitle = title; 100 openFileTitle = title;
97 Config config("Gutenbrowser"); 101 Config config("Gutenbrowser");
98 config.setGroup( "Files" ); 102 config.setGroup( "Files" );
99 file = config.readEntry(temp, ""); 103 file = config.readEntry(temp, "");
100 OpenEtext::accept(); 104 OpenEtext::accept();
101} 105}
102 106
103/* 107/*!
104 This function imports already existing etexts into the local library list*/ 108 * This function imports already existing etexts into the local library list
109 */
105void OpenEtext::open() 110void OpenEtext::open()
106{ 111{
107OpenFileButton->setDown(TRUE); 112OpenFileButton->setDown(TRUE);
108 title = ""; 113 title = "";
109 QString currDir=""; 114 QString currDir="";
110 QString filer; 115 QString filer;
111 QString name_file; 116 QString name_file;
112 QString local ; 117 QString local ;
113 local = (QDir::homeDirPath () +"Applications/gutenbrowser"); 118 local = (QDir::homeDirPath () +"Applications/gutenbrowser");
114 QDir library( local); 119 QDir library( local);
115 120
116// fileBrowser *browseForFiles;
117// browseForFiles=new fileBrowser(this,"Browse for File", TRUE, 0, "guten/plain;text/plain");
118// // browseForFiles=new fileBrowser(this,"fileBrowser",TRUE,0, "*");
119// browseForFiles->setFileView( 0);
120// browseForFiles->showMaximized();
121// browseForFiles->exec();
122// QString selFile= browseForFiles->selectedFileName;
123// fileList=browseForFiles->fileList;
124 Config cfg("Gutenbrowser"); 121 Config cfg("Gutenbrowser");
125 cfg. setGroup ( "View" ); 122 cfg. setGroup ( "View" );
126 QString dir = cfg.readEntry("LastOpenDirectory", QPEApplication::documentDir()); 123 QString dir = cfg.readEntry("LastOpenDirectory", QPEApplication::documentDir());
127 QMap<QString, QStringList> map; 124 QMap<QString, QStringList> map;
128 map.insert(tr("All"), QStringList() ); 125 map.insert(tr("All"), QStringList() );
129 QStringList text; 126 QStringList text;
130 text << "text/*"; 127 text << "text/*";
131 map.insert(tr("Text"), text ); 128 map.insert(tr("Text"), text );
132 text << "*"; 129 text << "*";
133 map.insert(tr("All"), text ); 130 map.insert(tr("All"), text );
134 131
135 QString str = OFileDialog::getOpenFileName( 2, dir , QString::null, map); 132 QString str = OFileDialog::getOpenFileName( 2, dir , QString::null, map);
136 133
137 if( !str.isEmpty() && QFile(str).exists() && !QFileInfo(str).isDir() ) { 134 if( !str.isEmpty() && QFile(str).exists() && !QFileInfo(str).isDir() ) {
138 filer = str; 135 filer = str;
139 136
140 odebug << "Open file: "+str << oendl; 137 odebug << "Open file: "+str << oendl;
141 138
142 // QStringList::ConstIterator f; 139 if( filer.right(4) == ".txt" ||
143// QString fileTemp; 140 filer.right(4) == ".TXT" ||
144// for ( f = fileList.begin(); f != fileList.end(); f++ ) { 141 filer.right(4) == ".etx" ||
145// fileTemp = *f; 142 filer.right(4) == ".ETX" ||
146// fileTemp.right( fileTemp.length()-5); 143 filer.right(4) == ".etx" ||
147// fileName = fileTemp; 144 filer.right(4) == ".ETX" ||
148// if( !fileName.isEmpty() ){ 145 filer.right(4) == ".zip" ||
149// filer = fileName; 146 filer.right(4) == ".ZIP" )
150// } else { //filename is empty 147 {
151// // QString sMsg;
152// // sMsg = "Error opening library filelist "+fileName;
153// }
154
155 if( filer.right(4) == ".txt"
156 || filer.right(4) == ".TXT"
157 || filer.right(4) == ".etx"
158 || filer.right(4) == ".ETX"
159 || filer.right(4) == ".etx"
160 || filer.right(4) == ".ETX"
161 || filer.right(4) == ".zip"
162 || filer.right(4) == ".ZIP" ) {
163 QFileInfo zipFile( filer); 148 QFileInfo zipFile( filer);
164 QString s_fileName = zipFile.fileName(); 149 QString s_fileName = zipFile.fileName();
165 QString cmd; 150 QString cmd;
166 151
167 if( s_fileName.right(4) == ".zip") { // unzip that sucker.... 152 if( s_fileName.right(4) == ".zip") { // unzip the file
168 s_fileName = s_fileName.left( s_fileName.length() - 4); 153 s_fileName = s_fileName.left( s_fileName.length() - 4);
169 if( chdir((const char*)local_library.latin1())!=0) 154 if( chdir((const char*)local_library.latin1())!=0)
170 odebug << "chdir failed." << oendl; // QString cmd = "gunzip -d " + filer + " -d " + local_library; 155 odebug << "chdir failed." << oendl;
171 cmd = "gunzip -S .zip " + filer; 156 cmd = "gunzip -S .zip " + filer;
172 fileName = local_library + s_fileName + ".txt"; 157 fileName = local_library + s_fileName + ".txt";
173 system( cmd); 158 system( cmd);
174 } 159 } else { // else rename .txt to .etx
175// this renames the .txt to .etx!! 160 // odebug << "Filename is "+fileName << oendl;
176 else /*if( s_fileName.right(4) == ".txt" || if( s_fileName.right(4) == ".TXT"))*/ {
177// odebug << "Filename is "+fileName << oendl;
178 s_fileName = fileName; 161 s_fileName = fileName;
179 s_fileName.replace( s_fileName.length()-3,3,"gtn");// s_fileName.replace( s_fileName.length()-3,3,"etx"); 162 s_fileName.replace( s_fileName.length()-3,3,"gtn");
180 rename(fileName.latin1(),s_fileName.latin1()); 163 if (rename(fileName.latin1(),s_fileName.latin1()) == -1)
164 owarn << "Rename of " << fileName.latin1() << " to "
165 << s_fileName.latin1() << " failed" << oendl;
181 fileName = s_fileName; 166 fileName = s_fileName;
182// odebug << "Filename is now "+fileName << oendl; 167 // odebug << "Filename is now "+fileName << oendl;
183 } 168 }
184 } else 169 } else
185 fileName = str; 170 fileName = str;
186 171
187 FindTitle(fileName); 172 FindTitle(fileName);
188 173
189 QFileInfo fi( fileName); 174 QFileInfo fi( fileName);
190 name_file = fi.fileName(); 175 name_file = fi.fileName();
191 name_file = name_file.left(name_file.length() - 4); 176 name_file = name_file.left(name_file.length() - 4);
192 177
193 odebug << "Setting doclink" << oendl; 178 odebug << "Setting doclink" << oendl;
194 DocLnk lnk; 179 DocLnk lnk;
195 odebug << "name is " + name_file << oendl; 180 odebug << "name is " + name_file << oendl;
196 lnk.setName(name_file); //sets file name 181 lnk.setName(name_file); //sets file name
197 odebug << "Title is "+title << oendl; 182 odebug << "Title is "+title << oendl;
198 lnk.setComment(title); 183 lnk.setComment(title);
199 184
200 QListBox_1->clear(); 185 QListBox_1->clear();
201 getTitles(); 186 getTitles();
202 odebug << "Filename is "+fileName << oendl; 187 odebug << "Filename is "+fileName << oendl;
203 lnk.setFile(fileName); //sets File property 188 lnk.setFile(fileName); //sets File property
204 lnk.setType("guten/plain");// hey is this a REGISTERED mime type?!?!? ;D 189 // @bug This is probably not a registered MIME type. Perhaps we should
190 // set a valid MIME type here instead. Or maybe register .etx as a
191 // Gutenberge etext?
192 lnk.setType("guten/plain");
205 lnk.setExec(fileName); 193 lnk.setExec(fileName);
206 lnk.setIcon("gutenbrowser/Gutenbrowser"); 194 lnk.setIcon("gutenbrowser/Gutenbrowser");
207 if(!lnk.writeLink()) 195 if(!lnk.writeLink())
208 odebug << "Writing doclink did not work" << oendl; 196 odebug << "Writing doclink did not work" << oendl;
209 197
210 } // end of for each file name.... 198 } // end of for each file name....
211 OpenFileButton->setDown(FALSE); 199 OpenFileButton->setDown(FALSE);
212} 200}
213 201
214/* 202/*
215find the title in the config file */ 203find the title in the config file */
216bool OpenEtext::FindTitle( QString filename) 204bool OpenEtext::FindTitle( QString filename)
217{ 205{
218 Config config("Gutenbrowser"); 206 Config config("Gutenbrowser");
219 config.setGroup( "Files" ); 207 config.setGroup( "Files" );
220 QString s_numofFiles = config.readEntry("NumberOfFiles", "0"); 208 QString s_numofFiles = config.readEntry("NumberOfFiles", "0");
221 int i_numofFiles = s_numofFiles.toInt(); 209 int i_numofFiles = s_numofFiles.toInt();
222 210
223 QFileInfo fi(filename); 211 QFileInfo fi(filename);
224 name = fi.fileName(); 212 name = fi.fileName();
225 odebug << "filename to open is " + name << oendl; 213 odebug << "filename to open is " + name << oendl;
226 QFile indexLib( filename); 214 QFile indexLib( filename);
227 bool findCheck = FALSE; 215 bool findCheck = FALSE;
228 // int Titlenumber=0;
229 216
230 if ( indexLib.open( IO_ReadOnly) ) { 217 if ( indexLib.open( IO_ReadOnly) ) {
231 odebug << "file opened successfully" << oendl; 218 odebug << "file opened successfully" << oendl;
232 QTextStream indexStream( &indexLib ); 219 QTextStream indexStream( &indexLib );
233 QString target = "Project Gutenberg Etext of"; 220 QString target = "Project Gutenberg Etext of";
234 QString target2 = "Project Gutenberg Etext"; 221 QString target2 = "Project Gutenberg Etext";
235 QString target3 = "Project Gutenberg's Etext of"; 222 QString target3 = "Project Gutenberg's Etext of";
236 QString target4 = "Project Gutenberg's Etext"; 223 QString target4 = "Project Gutenberg's Etext";
237 QString indexLine; 224 QString indexLine;
238 while ( !indexStream.eof() ) { 225 while ( !indexStream.eof() ) {
239 // until end of file.. 226 // until end of file..
240 indexLine = indexStream.readLine(); 227 indexLine = indexStream.readLine();
241 if( indexLine.find(target, 0, TRUE) > -1 && !findCheck) {findCheck = TRUE; 228 if( indexLine.find(target, 0, TRUE) > -1 && !findCheck) {findCheck = TRUE;
242 title = indexLine.mid( indexLine.find(target, 0, TRUE) + (target.length()) , indexLine.find("\r", 0, TRUE)); 229 title = indexLine.mid( indexLine.find(target, 0, TRUE) + (target.length()) , indexLine.find("\r", 0, TRUE));
243 title = title.left( title.find( "*",0, TRUE)); 230 title = title.left( title.find( "*",0, TRUE));
244 title = title.stripWhiteSpace (); 231 title = title.stripWhiteSpace ();
245// odebug << "Found the title 1 and it is " << title << "" << oendl; 232// odebug << "Found the title 1 and it is " << title << "" << oendl;
246// QListBox_1->insertItem ( title); 233// QListBox_1->insertItem ( title);
247 } 234 }
248 if( indexLine.find( target2, 0, TRUE) > -1 && !findCheck) { 235 if( indexLine.find( target2, 0, TRUE) > -1 && !findCheck) {
249 findCheck = TRUE; 236 findCheck = TRUE;
250 title = indexLine.mid( indexLine.find( target2, 0, TRUE ) + ( target2.length()) , indexLine.find("\r", 0, TRUE) ); 237 title = indexLine.mid( indexLine.find( target2, 0, TRUE ) + ( target2.length()) , indexLine.find("\r", 0, TRUE) );
251 title = title.left( title.find( "*",0, TRUE)); 238 title = title.left( title.find( "*",0, TRUE));
252 title = title.stripWhiteSpace (); 239 title = title.stripWhiteSpace ();
253// odebug << "Found the title 2 and it is " << title << "" << oendl; 240// odebug << "Found the title 2 and it is " << title << "" << oendl;
254// QListBox_1->insertItem ( title); 241// QListBox_1->insertItem ( title);
255 } 242 }
256 if( indexLine.find( target3, 0, TRUE) > -1 && !findCheck) { 243 if( indexLine.find( target3, 0, TRUE) > -1 && !findCheck) {
257 findCheck = TRUE; 244 findCheck = TRUE;
258 title = indexLine.mid( indexLine.find( target3, 0, TRUE) + ( target3.length()) , indexLine.find("\r", 0, TRUE)); 245 title = indexLine.mid( indexLine.find( target3, 0, TRUE) + ( target3.length()) , indexLine.find("\r", 0, TRUE));
259 title = title.left( title.find( "*",0, TRUE)); 246 title = title.left( title.find( "*",0, TRUE));
260 title = title.stripWhiteSpace (); 247 title = title.stripWhiteSpace ();
261// odebug << "Found the title 3 and it is " << title << "" << oendl; 248// odebug << "Found the title 3 and it is " << title << "" << oendl;
262 } 249 }
263 if( indexLine.find( target4, 0, TRUE) > -1 && !findCheck) { 250 if( indexLine.find( target4, 0, TRUE) > -1 && !findCheck) {
264 findCheck = TRUE; 251 findCheck = TRUE;
265 title = indexLine.mid( indexLine.find( target4, 0, TRUE) + ( target4.length()) , indexLine.find("\r", 0, TRUE)); 252 title = indexLine.mid( indexLine.find( target4, 0, TRUE) + ( target4.length()) , indexLine.find("\r", 0, TRUE));
266 title = title.left( title.find( "*",0, TRUE)); 253 title = title.left( title.find( "*",0, TRUE));
267 title = title.stripWhiteSpace (); 254 title = title.stripWhiteSpace ();
268// odebug << "Found the title 4 and it is " << title << "" << oendl; 255// odebug << "Found the title 4 and it is " << title << "" << oendl;
269 } 256 }
270 } //endof file 257 } //endof file
271 indexLib.close(); 258 indexLib.close();
272 259
273 if( !findCheck || title.length() < 2) { 260 if( !findCheck || title.length() < 2) {
274 odebug << "Trying hard to find title from GUTINDEX.ALL" << oendl; 261 odebug << "Trying hard to find title from GUTINDEX.ALL" << oendl;
275 title = titleFromLibrary( filename); 262 title = titleFromLibrary( filename);
276 findCheck = TRUE; 263 findCheck = TRUE;
277 } 264 }
278 265
279 if ( checkConf() == false && findCheck == TRUE) { 266 if ( checkConf() == false && findCheck == TRUE) {
280
281 config.setGroup( "Files"); 267 config.setGroup( "Files");
282 config.writeEntry("NumberOfFiles",i_numofFiles + 1 ); 268 config.writeEntry("NumberOfFiles",i_numofFiles + 1 );
283 QString interger; 269 QString interger;
284 interger.setNum( i_numofFiles +1); 270 interger.setNum( i_numofFiles +1);
285 config.writeEntry(interger, filename); 271 config.writeEntry(interger, filename);
286 config.setGroup( "Titles" ); 272 config.setGroup( "Titles" );
287 for (int i = 1; i <= i_numofFiles; i++) { //find dup titles in config file 273 for (int i = 1; i <= i_numofFiles; i++) { //find dup titles in config file
288 QString temp; 274 QString temp;
289 temp.setNum(i); 275 temp.setNum(i);
290 config.setGroup( "Files" ); 276 config.setGroup( "Files" );
291 QString ramble = config.readEntry(temp, "" ); 277 QString ramble = config.readEntry(temp, "" );
292 config.setGroup( "Titles" ); 278 config.setGroup( "Titles" );
293 QString title1 = config.readEntry(ramble, ""); 279 QString title1 = config.readEntry(ramble, "");
294 if(title1==title) 280 if(title1==title)
295 title+="1"; 281 title+="1";
296 i= i_numofFiles+1; 282 i= i_numofFiles+1;
297 } 283 }
298 if(title.length()<3) { 284 if(title.length()<3) {
299// odebug << "title is empty" << oendl; 285// odebug << "title is empty" << oendl;
300 title="Unknown"; 286 title="Unknown";
301 } 287 }
302 config.writeEntry( filename,title); 288 config.writeEntry( filename,title);
303 } 289 }
304 } else { 290 } else {
305 QString sMsg; 291 QString sMsg;
306 sMsg = "Error opening library file: "+filename; 292 sMsg = "Error opening library file: "+filename;
307 printf( sMsg+"\n"); 293 printf( sMsg+"\n");
308 } 294 }
309 return true; 295 return true;
310} 296}
311 297
312QString OpenEtext::titleFromLibrary( QString fileName) 298QString OpenEtext::titleFromLibrary( QString fileName)
313{ 299{
314 QFile indexLib( local_index); 300 QFile indexLib( local_index);
315 QString target; 301 QString target;
316 int find1 = fileName.findRev("/",-1,TRUE) + 1; 302 int find1 = fileName.findRev("/",-1,TRUE) + 1;
317 int find2 = fileName.findRev(".gtn",-1,TRUE) - find1; 303 int find2 = fileName.findRev(".gtn",-1,TRUE) - find1;
318 if(find2==-1-find1) 304 if(find2== (-1-find1))
319 int find2 = fileName.findRev(".etx",-1,TRUE) - find1; 305 find2 = fileName.findRev(".etx",-1,TRUE) - find1;
320 else if(find2==-1-find1) 306 else if(find2==(-1-find1))
321 int find2 = fileName.findRev(".txt",-1,TRUE) - find1; 307 find2 = fileName.findRev(".txt",-1,TRUE) - find1;
322 308
323 target = fileName.mid( find1, find2 ); 309 target = fileName.mid( find1, find2 );
324 QString checker = target.right(1); 310 QString checker = target.right(1);
325 bool ok; 311 bool ok;
326 checker.toInt( &ok,10); 312 checker.toInt( &ok,10);
327 if( ok) { 313 if( ok) {
328 target = target.left( target.length()-1); 314 target = target.left( target.length()-1);
329 checker = target.right(1); 315 checker = target.right(1);
330 ok = FALSE; 316 ok = FALSE;
331 checker.toInt( &ok,10); 317 checker.toInt( &ok,10);
332 if( ok) { 318 if( ok) {
333 target = target.left( target.length()-1); 319 target = target.left( target.length()-1);
334 } 320 }
335 } 321 }
336 if ( indexLib.open( IO_ReadOnly) ) { 322 if ( indexLib.open( IO_ReadOnly) ) {
337 // file opened successfully 323 // file opened successfully
338 QTextStream indexStream( &indexLib ); 324 QTextStream indexStream( &indexLib );
339 QString indexLine; 325 QString indexLine;
340 bool findCheck = FALSE; 326 bool findCheck = FALSE;
341 while ( !indexStream.atEnd() ) { // until end of file.. 327 while ( !indexStream.atEnd() ) { // until end of file..
342 indexLine = indexStream.readLine(); 328 indexLine = indexStream.readLine();
343 329
344 if( indexLine.find( target,0,FALSE) > 0 ) { 330 if( indexLine.find( target,0,FALSE) > 0 ) {
345 findCheck = TRUE; 331 findCheck = TRUE;
346 title = indexLine.mid( 9, 50); 332 title = indexLine.mid( 9, 50);
347// title = indexLine.mid( 26, indexLine.length() );
348 title = title.stripWhiteSpace (); 333 title = title.stripWhiteSpace ();
349// odebug << "Finally Found the title and it is\n " << title << "" << oendl; 334// odebug << "Finally Found the title and it is\n " << title << "" << oendl;
350// QListBox_1->insertItem ( title); 335// QListBox_1->insertItem ( title);
351 } 336 }
352 } //end while loop 337 } //end while loop
353 } 338 }
354 else 339 else
355 odebug << "Error opening library index "+ local_index << oendl; 340 odebug << "Error opening library index "+ local_index << oendl;
356 return title; 341 return title;
357} 342}
358 343
359bool OpenEtext::checkConf() 344bool OpenEtext::checkConf()
360{ 345{
361 QString file = fileName; 346 QString file = fileName;
362 Config config("Gutenbrowser"); 347 Config config("Gutenbrowser");
363 config.setGroup( "Files" ); 348 config.setGroup( "Files" );
364 QString s_numofFiles = config.readEntry("NumberOfFiles", "0" ); 349 QString s_numofFiles = config.readEntry("NumberOfFiles", "0" );
365 int i_numofFiles = s_numofFiles.toInt(); 350 int i_numofFiles = s_numofFiles.toInt();
366 351
367 for (int i = 1; i <= i_numofFiles; i++) { 352 for (int i = 1; i <= i_numofFiles; i++) {
368 QString temp; 353 QString temp;
369 temp.setNum(i); 354 temp.setNum(i);
370 config.setGroup( "Files"); 355 config.setGroup( "Files");
371 QString ramble = config.readEntry(temp, "" ); 356 QString ramble = config.readEntry(temp, "" );
372 357
373 if(ramble == file ) { 358 if(ramble == file ) {
374 return true; 359 return true;
375 } 360 }
376 } 361 }
377 return false; 362 return false;
378} 363}
379 364
380void OpenEtext::remove() 365void OpenEtext::remove()
381{ 366{
382 title_text = QListBox_1->text( QListBox_1->currentItem() ); 367 title_text = QListBox_1->text( QListBox_1->currentItem() );
383 title_text=title_text.stripWhiteSpace(); 368 title_text=title_text.stripWhiteSpace();
384 QString msg ="<p>Do you really want to REMOVE\n" +title_text +"?\nThis will not delete the file.</P>"; 369 QString msg ="<p>Do you really want to REMOVE\n" + title_text +
385 switch( QMessageBox::information( this, (tr("Remove Etext")), 370 "?\nThis will not delete the file.</P>";
386 (tr(msg)), 371 switch( QMessageBox::information( this, tr("Remove Etext"),
387 (tr("&Yes")), (tr("&Cancel")), 0 )){ 372 tr(msg),
373 tr("&Yes"), tr("&Cancel"), 0 ) )
374 {
388 case 0: // Yes clicked, 375 case 0: // Yes clicked,
389 removeSelection(); 376 removeSelection();
390 QListBox_1->clear(); 377 QListBox_1->clear();
391 getTitles(); 378 getTitles();
392 break; 379 break;
393 case 1: // Cancel 380 case 1:
394 break; 381 default:
395 }; 382 }
396} 383}
397 384
398/* 385/*!
399 this removes selected title entry*/ 386 * This removes selected title entry
387 */
400void OpenEtext::removeSelection() 388void OpenEtext::removeSelection()
401{ 389{
402 Config config("Gutenbrowser"); 390 Config config("Gutenbrowser");
403 config.setGroup( "Files" ); 391 config.setGroup( "Files" );
404 s_numofFiles = config.readEntry("NumberOfFiles", "0"); 392 s_numofFiles = config.readEntry("NumberOfFiles", "0");
405 int rem=0; 393 int rem=0;
406 int i_numofFiles = s_numofFiles.toInt(); 394 int i_numofFiles = s_numofFiles.toInt();
407 QString fileNum2; 395 QString fileNum2;
408 QString fileNum; 396 QString fileNum;
409 397
410 for (int i = 1; i <= i_numofFiles; i++) { 398 for (int i = 1; i <= i_numofFiles; i++) {
411 fileNum.setNum(i); 399 fileNum.setNum(i);
412 config.setGroup( "Files" ); 400 config.setGroup( "Files" );
413 401
414 QString s_filename = config.readEntry(fileNum, "" ); 402 QString s_filename = config.readEntry(fileNum, "" );
415 config.setGroup( "Titles" ); 403 config.setGroup( "Titles" );
416 404
417 QString file_title = config.readEntry( s_filename, ""); 405 QString file_title = config.readEntry( s_filename, "");
418 if(title_text == file_title) { 406 if(title_text == file_title) {
419 rem=i; 407 rem=i;
420//odebug << "file title to remove is "+file_title << oendl; 408 //odebug << "file title to remove is "+file_title << oendl;
421 selFile = s_filename; 409 selFile = s_filename;
422 config.removeEntry( s_filename); //removes file=title 410 config.removeEntry( s_filename); //removes file=title
423 } 411 }
424 } 412 }
425 config.setGroup( "Files" ); 413 config.setGroup( "Files" );
426 414
427 for(int fg = rem; fg < i_numofFiles ; fg++ ) { //this rewrites Files number entry 415 for(int fg = rem; fg < i_numofFiles ; fg++ ) { //this rewrites Files number entry
428 fileNum.setNum(fg); 416 fileNum.setNum(fg);
429 fileNum2.setNum( fg + 1); 417 fileNum2.setNum( fg + 1);
430 418
431 QString s_filename2 = config.readEntry(fileNum2, "" ); 419 QString s_filename2 = config.readEntry(fileNum2, "" );
432 420
433 if (!s_filename2.isEmpty()) { 421 if (!s_filename2.isEmpty()) {
434 config.writeEntry(fileNum, s_filename2 ); 422 config.writeEntry(fileNum, s_filename2 );
435 } 423 }
436 } 424 }
437 config.writeEntry("NumberOfFiles", i_numofFiles - 1 ); 425 config.writeEntry("NumberOfFiles", i_numofFiles - 1 );
438 config.removeEntry(fileNum2); 426 config.removeEntry(fileNum2);
439// remFile();
440} 427}
441 428
442/* 429/*!
443 removes file title name from list and config file*/ 430 * Removes file title name from list and config file
431 */
444void OpenEtext::remFile() 432void OpenEtext::remFile()
445{ 433{
446 Config config("Gutenbrowser"); 434 Config config("Gutenbrowser");
447 config.setGroup( "Files" ); 435 config.setGroup( "Files" );
448 QString remFile; 436 QString remFile;
449 s_numofFiles = config.readEntry("NumberOfFiles", "0"); 437 s_numofFiles = config.readEntry("NumberOfFiles", "0");
450 int i_numofFiles = s_numofFiles.toInt(); 438 int i_numofFiles = s_numofFiles.toInt();
451 for (int i = 1; i <= i_numofFiles; i++) { 439 for (int i = 1; i <= i_numofFiles; i++) {
452 QString fileNum; 440 QString fileNum;
453 fileNum.setNum(i); 441 fileNum.setNum(i);
454 QString s_filename = config.readEntry(fileNum, "" ); 442 QString s_filename = config.readEntry(fileNum, "" );
455 443
456 if( s_filename == selFile) { 444 if( s_filename == selFile) {
457 config.removeEntry(selFile); 445 config.removeEntry(selFile);
458 446
459 for(int fg = i_numofFiles - i; fg < i_numofFiles ; fg++ ) { //this rewrites Files number entry 447 for(int fg = i_numofFiles - i; fg < i_numofFiles ; fg++ ) { //this rewrites Files number entry
460 QString fileNum2; 448 QString fileNum2;
461 fileNum2.setNum( fg + 1); 449 fileNum2.setNum( fg + 1);
462 QString s_filename2 = config.readEntry(fileNum2, "" ); 450 QString s_filename2 = config.readEntry(fileNum2, "" );
463 451
464 if (!s_filename2.isEmpty()) { 452 if (!s_filename2.isEmpty())
465 config.writeEntry(fileNum, s_filename2 ); 453 config.writeEntry(fileNum, s_filename2 );
466 }
467 } 454 }
468 } 455 }
469 } 456 }
470 config.writeEntry("NumberOfFiles", i_numofFiles - 1 ); 457 config.writeEntry("NumberOfFiles", i_numofFiles - 1 );
471 config.removeEntry(s_numofFiles); 458 config.removeEntry(s_numofFiles);
472 459
473 QListBox_1->triggerUpdate(true); 460 QListBox_1->triggerUpdate(true);
474} 461}
475 462
476/* 463/*!
477sorts the list*/ 464 * Sorts the list
465 */
478void OpenEtext::scan() { 466void OpenEtext::scan() {
479 467
480 QListBox_1->sort(TRUE); 468 QListBox_1->sort(TRUE);
481 QListBox_1->triggerUpdate(true); 469 QListBox_1->triggerUpdate(true);
482} 470}
483 471
484void OpenEtext::editTitle() { 472void OpenEtext::editTitle() {
485 473
486 int currentItem=QListBox_1->currentItem(); 474 int currentItem=QListBox_1->currentItem();
487 QString title_text = QListBox_1->text( currentItem); 475 QString title_text = QListBox_1->text( currentItem);
488//odebug << "Selected "+title_text << oendl; 476 //odebug << "Selected "+title_text << oendl;
489 477
490 Config config("Gutenbrowser"); 478 Config config("Gutenbrowser");
491 config.setGroup( "Files" ); 479 config.setGroup( "Files" );
492 s_numofFiles = config.readEntry("NumberOfFiles", "0"); 480 s_numofFiles = config.readEntry("NumberOfFiles", "0");
493 int i_numofFiles = s_numofFiles.toInt(); 481 int i_numofFiles = s_numofFiles.toInt();
494 QString fileNum; 482 QString fileNum;
495 for (int i = 1; i <= i_numofFiles+1; i++) { 483 for (int i = 1; i <= i_numofFiles+1; i++) {
496 484
497 fileNum.setNum(i); 485 fileNum.setNum(i);
498 config.setGroup( "Files" ); 486 config.setGroup( "Files" );
499 QString s_filename = config.readEntry(fileNum, "" ); 487 QString s_filename = config.readEntry(fileNum, "" );
500 config.setGroup( "Titles" ); 488 config.setGroup( "Titles" );
501 QString file_title = config.readEntry( s_filename, ""); 489 QString file_title = config.readEntry( s_filename, "");
502//odebug << "file_title is "+file_title << oendl; 490 //odebug << "file_title is "+file_title << oendl;
503 if(title_text == file_title ) { 491 if(title_text == file_title ) {
504 selFile = s_filename; 492 selFile = s_filename;
505//odebug << "Edit: "+ file_title << oendl; 493 //odebug << "Edit: "+ file_title << oendl;
506 i=i_numofFiles+1; 494 i=i_numofFiles+1;
507 Edit_Title *titleEdit; 495 Edit_Title *titleEdit;
508 titleEdit = new Edit_Title(this,file_title ,TRUE); 496 titleEdit = new Edit_Title(this,file_title ,TRUE);
509 if(titleEdit->exec() !=0) { 497 if(titleEdit->exec() !=0) {
510//odebug << titleEdit->newTitle << oendl; 498 //odebug << titleEdit->newTitle << oendl;
511 config.writeEntry( s_filename, titleEdit->newTitle); 499 config.writeEntry( s_filename, titleEdit->newTitle);
512 QListBox_1->removeItem(currentItem); 500 QListBox_1->removeItem(currentItem);
513 QListBox_1->insertItem ( QPixmap( QPEApplication::qpeDir()+"pics/gutenbrowser/gutenbrowser_sm.png"), titleEdit->newTitle, currentItem); 501 QListBox_1->insertItem (
502 QPixmap( QPEApplication::qpeDir()+
503 "pics/gutenbrowser/gutenbrowser_sm.png"),
504 titleEdit->newTitle, currentItem
505 );
514 } 506 }
515 } 507 }
516 } 508 }
517 509
518// getTitles(); 510 //getTitles();
519 QListBox_1->triggerUpdate(true); 511 QListBox_1->triggerUpdate(true);
520} 512}
521 513
diff --git a/noncore/multimedia/opieplayer2/lib.cpp b/noncore/multimedia/opieplayer2/lib.cpp
index 84d28ce..5f281b7 100644
--- a/noncore/multimedia/opieplayer2/lib.cpp
+++ b/noncore/multimedia/opieplayer2/lib.cpp
@@ -1,491 +1,493 @@
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#include "xinevideowidget.h" 34#include "xinevideowidget.h"
35#include "lib.h" 35#include "lib.h"
36 36
37/* OPIE */ 37/* OPIE */
38#include <opie2/odebug.h> 38#include <opie2/odebug.h>
39#include <qpe/global.h> 39#include <qpe/global.h>
40 40
41/* QT */ 41/* QT */
42#include <qtextstream.h> 42#include <qtextstream.h>
43#include <qdir.h> 43#include <qdir.h>
44#include <qgfx_qws.h> 44#include <qgfx_qws.h>
45 45
46/* STD */ 46/* STD */
47#include <assert.h> 47#include <assert.h>
48#include <unistd.h> 48#include <unistd.h>
49 49
50typedef void (*display_xine_frame_t) (void *user_data, uint8_t* frame, 50typedef void (*display_xine_frame_t) (void *user_data, uint8_t* frame,
51 int width, int height,int bytes ); 51 int width, int height,int bytes );
52typedef void (*vo_scale_cb) (void*, int, int, double, 52typedef void (*vo_scale_cb) (void*, int, int, double,
53 int*, int*, int*, int*, double*, int*, int* ); 53 int*, int*, int*, int*, double*, int*, int* );
54typedef void (*dest_size_cb) (void*, int, int, double, int*, int*, double*); 54typedef void (*dest_size_cb) (void*, int, int, double, int*, int*, double*);
55 55
56 56
57extern "C" { 57extern "C" {
58 xine_vo_driver_t* init_video_out_plugin( xine_t *xine, void* video, display_xine_frame_t, void *, vo_scale_cb, dest_size_cb ); 58 xine_vo_driver_t* init_video_out_plugin( xine_t *xine, void* video, display_xine_frame_t, void *, vo_scale_cb, dest_size_cb );
59 int null_is_showing_video( const xine_vo_driver_t* self ); 59 int null_is_showing_video( const xine_vo_driver_t* self );
60 void null_set_show_video( const xine_vo_driver_t* self, int show ); 60 void null_set_show_video( const xine_vo_driver_t* self, int show );
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_display_handler( const xine_vo_driver_t* self, display_xine_frame_t t, void* user_data ); 62 void null_display_handler( const xine_vo_driver_t* self, display_xine_frame_t t, void* user_data );
63} 63}
64 64
65using namespace XINE; 65using namespace XINE;
66 66
67Lib::Lib( InitializationMode initMode, XineVideoWidget* widget ) 67Lib::Lib( InitializationMode initMode, XineVideoWidget* widget )
68{ 68{
69 m_initialized = false; 69 m_initialized = false;
70 m_duringInitialization = false; 70 m_duringInitialization = false;
71 m_video = false; 71 m_video = false;
72 m_wid = widget; 72 m_wid = widget;
73 printf("Lib"); 73 printf("Lib");
74 QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf"; 74 QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf";
75 // get the configuration 75 // get the configuration
76 76
77 // not really OO, should be an extra class, later 77 // not really OO, should be an extra class, later
78 if ( !QFile::exists(configPath) ) { 78 if ( !QFile::exists(configPath) ) {
79 QFile f(configPath); 79 QFile f(configPath);
80 f.open(IO_WriteOnly); 80 if (f.open(IO_WriteOnly)) {
81 QTextStream ts( &f ); 81 QTextStream ts( &f );
82 ts << "misc.memcpy_method:glibc\n"; 82 ts << "misc.memcpy_method:glibc\n";
83 ts << "# uncomment if you experience double speed audio \n #audio.oss_sync_method:softsync\n"; 83 ts << "# uncomment if you experience double speed audio \n #audio.oss_sync_method:softsync\n";
84 ts << "codec.ffmpeg_pp_quality:3\n"; 84 ts << "codec.ffmpeg_pp_quality:3\n";
85 ts << "audio.num_buffers:50\n"; 85 ts << "audio.num_buffers:50\n";
86 ts << "audio.size_buffers:4096\n"; 86 ts << "audio.size_buffers:4096\n";
87 ts << "video.num_buffers:20\n"; 87 ts << "video.num_buffers:20\n";
88 ts << "video.size_buffers:4096\n"; 88 ts << "video.size_buffers:4096\n";
89 ts << "audio.out_num_audio_buf:16\n"; 89 ts << "audio.out_num_audio_buf:16\n";
90 ts << "audio.out_size_audio_buf:8096\n"; 90 ts << "audio.out_size_audio_buf:8096\n";
91 ts << "audio.out_size_zero_buf:1024\n"; 91 ts << "audio.out_size_zero_buf:1024\n";
92 ts << "audio.passthrough_offset:0\n"; 92 ts << "audio.passthrough_offset:0\n";
93 f.close(); 93 f.close();
94 } else
95 owarn << "Failed to open " f.name() << oendl;
94 } 96 }
95 97
96 if ( initMode == InitializeImmediately ) { 98 if ( initMode == InitializeImmediately ) {
97 initialize(); 99 initialize();
98 m_initialized = true; 100 m_initialized = true;
99 } 101 }
100 else 102 else
101 start(); 103 start();
102} 104}
103 105
104void Lib::run() 106void Lib::run()
105{ 107{
106 odebug << "Lib::run() started" << oendl; 108 odebug << "Lib::run() started" << oendl;
107 initialize(); 109 initialize();
108 m_initialized = true; 110 m_initialized = true;
109 odebug << "Lib::run() finished" << oendl; 111 odebug << "Lib::run() finished" << oendl;
110} 112}
111 113
112void Lib::initialize() 114void Lib::initialize()
113{ 115{
114 m_duringInitialization = true; 116 m_duringInitialization = true;
115 m_xine = xine_new( ); 117 m_xine = xine_new( );
116 118
117 QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf"; 119 QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf";
118 xine_config_load( m_xine, QFile::encodeName( configPath ) ); 120 xine_config_load( m_xine, QFile::encodeName( configPath ) );
119 121
120 xine_init( m_xine ); 122 xine_init( m_xine );
121 123
122 // allocate oss for sound 124 // allocate oss for sound
123 // and fb for framebuffer 125 // and fb for framebuffer
124 m_audioOutput = xine_open_audio_driver( m_xine, "oss", NULL ); 126 m_audioOutput = xine_open_audio_driver( m_xine, "oss", NULL );
125 m_videoOutput = ::init_video_out_plugin( m_xine, NULL, 127 m_videoOutput = ::init_video_out_plugin( m_xine, NULL,
126 xine_display_frame, this, 128 xine_display_frame, this,
127 xine_vo_scale_cb, 129 xine_vo_scale_cb,
128 xine_dest_cb ); 130 xine_dest_cb );
129 131
130 m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput ); 132 m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput );
131 xine_set_param( m_stream, XINE_PARAM_AUDIO_CLOSE_DEVICE, 1); 133 xine_set_param( m_stream, XINE_PARAM_AUDIO_CLOSE_DEVICE, 1);
132 134
133 if (m_wid != 0 ) 135 if (m_wid != 0 )
134 setWidget( m_wid ); 136 setWidget( m_wid );
135 137
136 138
137 m_queue = xine_event_new_queue (m_stream); 139 m_queue = xine_event_new_queue (m_stream);
138 xine_event_create_listener_thread (m_queue, xine_event_handler, this); 140 xine_event_create_listener_thread (m_queue, xine_event_handler, this);
139 141
140 m_duringInitialization = false; 142 m_duringInitialization = false;
141} 143}
142 144
143Lib::~Lib() { 145Lib::~Lib() {
144 assert( isRunning() == false ); 146 assert( isRunning() == false );
145 assert( m_initialized ); 147 assert( m_initialized );
146 148
147// free( m_config ); 149// free( m_config );
148 150
149 xine_close( m_stream ); 151 xine_close( m_stream );
150 xine_event_dispose_queue( m_queue ); 152 xine_event_dispose_queue( m_queue );
151 xine_dispose( m_stream ); 153 xine_dispose( m_stream );
152 xine_close_audio_driver(m_xine,m_audioOutput); 154 xine_close_audio_driver(m_xine,m_audioOutput);
153 xine_close_video_driver(m_xine,m_videoOutput); 155 xine_close_video_driver(m_xine,m_videoOutput);
154 xine_exit( m_xine ); 156 xine_exit( m_xine );
155 157
156 /* FIXME either free or delete but valgrind bitches against both */ 158 /* FIXME either free or delete but valgrind bitches against both */
157 //free( m_videoOutput ); 159 //free( m_videoOutput );
158 //delete m_audioOutput; 160 //delete m_audioOutput;
159} 161}
160 162
161void Lib::resize ( const QSize &s ) { 163void Lib::resize ( const QSize &s ) {
162 assert( m_initialized || m_duringInitialization ); 164 assert( m_initialized || m_duringInitialization );
163 165
164 if ( s. width ( ) && s. height ( ) ) 166 if ( s. width ( ) && s. height ( ) )
165 m_videoSize = s; 167 m_videoSize = s;
166} 168}
167 169
168int Lib::majorVersion() { 170int Lib::majorVersion() {
169 int major, minor, sub; 171 int major, minor, sub;
170 xine_get_version ( &major, &minor, &sub ); 172 xine_get_version ( &major, &minor, &sub );
171 return major; 173 return major;
172} 174}
173 175
174int Lib::minorVersion() { 176int Lib::minorVersion() {
175 int major, minor, sub; 177 int major, minor, sub;
176 xine_get_version ( &major, &minor, &sub ); 178 xine_get_version ( &major, &minor, &sub );
177 return minor; 179 return minor;
178} 180}
179 181
180int Lib::subVersion() { 182int Lib::subVersion() {
181 int major, minor, sub; 183 int major, minor, sub;
182 xine_get_version ( &major, &minor, &sub ); 184 xine_get_version ( &major, &minor, &sub );
183 return sub; 185 return sub;
184} 186}
185 187
186int Lib::setfile(const QString& fileName) 188int Lib::setfile(const QString& fileName)
187{ 189{
188 QString str = fileName.stripWhiteSpace(); 190 QString str = fileName.stripWhiteSpace();
189 191
190 192
191 if ( !xine_open( m_stream, str.utf8().data() ) ) { 193 if ( !xine_open( m_stream, str.utf8().data() ) ) {
192 return 0; 194 return 0;
193 } 195 }
194 return 1; 196 return 1;
195} 197}
196 198
197int Lib::play( const QString& fileName, int startPos, int start_time ) { 199int Lib::play( const QString& fileName, int startPos, int start_time ) {
198 assert( m_initialized ); 200 assert( m_initialized );
199 201
200 QString str = fileName.stripWhiteSpace(); 202 QString str = fileName.stripWhiteSpace();
201 203
202 204
203 if ( !xine_open( m_stream, str.utf8().data() ) ) { 205 if ( !xine_open( m_stream, str.utf8().data() ) ) {
204 return 0; 206 return 0;
205 } 207 }
206 return xine_play( m_stream, startPos, start_time); 208 return xine_play( m_stream, startPos, start_time);
207} 209}
208 210
209void Lib::stop() { 211void Lib::stop() {
210 assert( m_initialized ); 212 assert( m_initialized );
211 xine_stop( m_stream ); 213 xine_stop( m_stream );
212 xine_set_param( m_stream, XINE_PARAM_AUDIO_CLOSE_DEVICE, 1); 214 xine_set_param( m_stream, XINE_PARAM_AUDIO_CLOSE_DEVICE, 1);
213} 215}
214 216
215void Lib::pause( bool toggle ) { 217void Lib::pause( bool toggle ) {
216 assert( m_initialized ); 218 assert( m_initialized );
217 219
218 if ( toggle ) { 220 if ( toggle ) {
219 xine_set_param( m_stream, XINE_PARAM_SPEED, XINE_SPEED_PAUSE ); 221 xine_set_param( m_stream, XINE_PARAM_SPEED, XINE_SPEED_PAUSE );
220 xine_set_param( m_stream, XINE_PARAM_AUDIO_CLOSE_DEVICE, 1); 222 xine_set_param( m_stream, XINE_PARAM_AUDIO_CLOSE_DEVICE, 1);
221 } 223 }
222 224
223 else { 225 else {
224 xine_set_param( m_stream, XINE_PARAM_SPEED, XINE_SPEED_NORMAL ); 226 xine_set_param( m_stream, XINE_PARAM_SPEED, XINE_SPEED_NORMAL );
225 } 227 }
226} 228}
227 229
228int Lib::speed() const { 230int Lib::speed() const {
229 assert( m_initialized ); 231 assert( m_initialized );
230 232
231 return xine_get_param ( m_stream, XINE_PARAM_SPEED ); 233 return xine_get_param ( m_stream, XINE_PARAM_SPEED );
232} 234}
233 235
234void Lib::setSpeed( int speed ) { 236void Lib::setSpeed( int speed ) {
235 assert( m_initialized ); 237 assert( m_initialized );
236 238
237 xine_set_param ( m_stream, XINE_PARAM_SPEED, speed ); 239 xine_set_param ( m_stream, XINE_PARAM_SPEED, speed );
238} 240}
239 241
240int Lib::status() const { 242int Lib::status() const {
241 assert( m_initialized ); 243 assert( m_initialized );
242 244
243 return xine_get_status( m_stream ); 245 return xine_get_status( m_stream );
244} 246}
245 247
246int Lib::currentPosition() const { 248int Lib::currentPosition() const {
247 assert( m_initialized ); 249 assert( m_initialized );
248 250
249 int pos, time, length; 251 int pos, time, length;
250 xine_get_pos_length( m_stream, &pos, &time, &length ); 252 xine_get_pos_length( m_stream, &pos, &time, &length );
251 return pos; 253 return pos;
252} 254}
253 255
254int Lib::currentTime() const { 256int Lib::currentTime() const {
255 assert( m_initialized ); 257 assert( m_initialized );
256 258
257 int pos, time, length; 259 int pos, time, length;
258 pos = time = length = 0; 260 pos = time = length = 0;
259 261
260 if ( xine_get_pos_length( m_stream, &pos, &time, &length ) ) 262 if ( xine_get_pos_length( m_stream, &pos, &time, &length ) )
261 return time/1000; 263 return time/1000;
262 else 264 else
263 return 0; 265 return 0;
264} 266}
265 267
266int Lib::length() const { 268int Lib::length() const {
267 assert( m_initialized ); 269 assert( m_initialized );
268 270
269 int pos, time, length; 271 int pos, time, length;
270/* dilb: patch to solve the wrong stream length reported to the GUI*/ 272/* dilb: patch to solve the wrong stream length reported to the GUI*/
271 int iRetVal=0, iTestLoop=0; 273 int iRetVal=0, iTestLoop=0;
272 274
273 do 275 do
274 { 276 {
275 iRetVal = xine_get_pos_length( m_stream, &pos, &time, &length ); 277 iRetVal = xine_get_pos_length( m_stream, &pos, &time, &length );
276 if (iRetVal) 278 if (iRetVal)
277 {/* if the function didn't return 0, then pos, time and length are valid.*/ 279 {/* if the function didn't return 0, then pos, time and length are valid.*/
278 return length/1000; 280 return length/1000;
279 } 281 }
280 /*don't poll too much*/ 282 /*don't poll too much*/
281 usleep(100000); 283 usleep(100000);
282 iTestLoop++; 284 iTestLoop++;
283 } 285 }
284 while ( iTestLoop < 10 ); /* if after 1s, we still don't have any 286 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 287valid stream, then return -1 (this value could be used to make the stream
286unseekable, but it should never occur!! Mr. Murphy ? :) ) */ 288unseekable, but it should never occur!! Mr. Murphy ? :) ) */
287 289
288 return -1; 290 return -1;
289} 291}
290 292
291/* info about current stream */ 293/* info about current stream */
292QSize Lib::videoSize()const 294QSize Lib::videoSize()const
293{ 295{
294 if (!m_initialized||!hasVideo()) return QSize(0,0); 296 if (!m_initialized||!hasVideo()) return QSize(0,0);
295 int width = xine_get_stream_info(m_stream,XINE_STREAM_INFO_VIDEO_WIDTH); 297 int width = xine_get_stream_info(m_stream,XINE_STREAM_INFO_VIDEO_WIDTH);
296 int height = xine_get_stream_info(m_stream,XINE_STREAM_INFO_VIDEO_HEIGHT); 298 int height = xine_get_stream_info(m_stream,XINE_STREAM_INFO_VIDEO_HEIGHT);
297 return QSize(width,height); 299 return QSize(width,height);
298} 300}
299 301
300 302
301bool Lib::isSeekable() const { 303bool Lib::isSeekable() const {
302 assert( m_initialized ); 304 assert( m_initialized );
303 305
304 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_SEEKABLE ); 306 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_SEEKABLE );
305} 307}
306 308
307bool Lib::hasVideo() const { 309bool Lib::hasVideo() const {
308 assert( m_initialized ); 310 assert( m_initialized );
309 311
310 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_HAS_VIDEO); 312 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_HAS_VIDEO);
311} 313}
312 314
313int Lib::audioBitrate()const 315int Lib::audioBitrate()const
314{ 316{
315 if (!m_initialized) return 0; 317 if (!m_initialized) return 0;
316 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_AUDIO_BITRATE); 318 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_AUDIO_BITRATE);
317} 319}
318int Lib::videoBitrate()const 320int Lib::videoBitrate()const
319{ 321{
320 if (!m_initialized||!hasVideo()) return 0; 322 if (!m_initialized||!hasVideo()) return 0;
321 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_VIDEO_BITRATE); 323 return xine_get_stream_info( m_stream, XINE_STREAM_INFO_VIDEO_BITRATE);
322} 324}
323/* end info block */ 325/* end info block */
324 326
325void Lib::seekTo( int time ) { 327void Lib::seekTo( int time ) {
326 assert( m_initialized ); 328 assert( m_initialized );
327 329
328 odebug << "Seeking to second " << time << oendl; 330 odebug << "Seeking to second " << time << oendl;
329 //Keep it paused if it was in that state 331 //Keep it paused if it was in that state
330 if ( xine_get_param( m_stream, XINE_PARAM_SPEED ) ) { 332 if ( xine_get_param( m_stream, XINE_PARAM_SPEED ) ) {
331 xine_play( m_stream, 0, time*1000 ); 333 xine_play( m_stream, 0, time*1000 );
332 } 334 }
333 335
334 else { 336 else {
335 xine_play( m_stream, 0, time*1000 ); 337 xine_play( m_stream, 0, time*1000 );
336 xine_set_param( m_stream, XINE_PARAM_SPEED, XINE_SPEED_PAUSE ); 338 xine_set_param( m_stream, XINE_PARAM_SPEED, XINE_SPEED_PAUSE );
337 } 339 }
338 340
339} 341}
340 342
341 343
342QString Lib::metaInfo( int number) const { 344QString Lib::metaInfo( int number) const {
343 assert( m_initialized ); 345 assert( m_initialized );
344 346
345 return xine_get_meta_info( m_stream, number ); 347 return xine_get_meta_info( m_stream, number );
346} 348}
347 349
348int Lib::error() const { 350int Lib::error() const {
349 assert( m_initialized ); 351 assert( m_initialized );
350 352
351 return xine_get_error( m_stream ); 353 return xine_get_error( m_stream );
352}; 354};
353 355
354void Lib::ensureInitialized() 356void Lib::ensureInitialized()
355{ 357{
356 if ( m_initialized ) 358 if ( m_initialized )
357 return; 359 return;
358 360
359 odebug << "waiting for initialization thread to finish" << oendl; 361 odebug << "waiting for initialization thread to finish" << oendl;
360 wait(); 362 wait();
361 odebug << "initialization thread finished!" << oendl; 363 odebug << "initialization thread finished!" << oendl;
362} 364}
363 365
364void Lib::setWidget( XineVideoWidget *widget ) 366void Lib::setWidget( XineVideoWidget *widget )
365{ 367{
366 m_wid = widget; 368 m_wid = widget;
367 if (m_wid) { 369 if (m_wid) {
368 resize ( m_wid-> size ( ) ); 370 resize ( m_wid-> size ( ) );
369 ::null_set_mode( m_videoOutput, qt_screen->depth(), qt_screen->pixelType() ); 371 ::null_set_mode( m_videoOutput, qt_screen->depth(), qt_screen->pixelType() );
370 } 372 }
371} 373}
372 374
373void Lib::receiveMessage( ThreadUtil::ChannelMessage *msg, SendType sendType ) 375void Lib::receiveMessage( ThreadUtil::ChannelMessage *msg, SendType sendType )
374{ 376{
375 assert( sendType == ThreadUtil::Channel::OneWay ); 377 assert( sendType == ThreadUtil::Channel::OneWay );
376 handleXineEvent( msg->type(), msg->data(), msg->msg() ); 378 handleXineEvent( msg->type(), msg->data(), msg->msg() );
377 delete msg; 379 delete msg;
378} 380}
379 381
380void Lib::handleXineEvent( const xine_event_t* t ) { 382void Lib::handleXineEvent( const xine_event_t* t ) {
381 int prog = -1; const char* name = 0; 383 int prog = -1; const char* name = 0;
382 if ( t->type == XINE_EVENT_PROGRESS ) { 384 if ( t->type == XINE_EVENT_PROGRESS ) {
383 xine_progress_data_t *pt = static_cast<xine_progress_data_t*>( t->data ); 385 xine_progress_data_t *pt = static_cast<xine_progress_data_t*>( t->data );
384 prog = pt->percent; 386 prog = pt->percent;
385 name = pt->description; 387 name = pt->description;
386 } 388 }
387 389
388 send( new ThreadUtil::ChannelMessage( t->type, prog, name ), OneWay ); 390 send( new ThreadUtil::ChannelMessage( t->type, prog, name ), OneWay );
389} 391}
390 392
391void Lib::handleXineEvent( int type, int data, const char* name ) { 393void Lib::handleXineEvent( int type, int data, const char* name ) {
392 assert( m_initialized ); 394 assert( m_initialized );
393 395
394 if ( type == XINE_EVENT_UI_PLAYBACK_FINISHED ) { 396 if ( type == XINE_EVENT_UI_PLAYBACK_FINISHED ) {
395 emit stopped(); 397 emit stopped();
396 }else if ( type == XINE_EVENT_PROGRESS ) { 398 }else if ( type == XINE_EVENT_PROGRESS ) {
397 QString str = name == 0 ? QString::null : QString::fromUtf8( name ); 399 QString str = name == 0 ? QString::null : QString::fromUtf8( name );
398 Global::statusMessage( tr( "Progress: %1 %2" ).arg( name, data ) );; 400 Global::statusMessage( tr( "Progress: %1 %2" ).arg( name, data ) );;
399 } 401 }
400} 402}
401 403
402 404
403void Lib::setShowVideo( bool video ) { 405void Lib::setShowVideo( bool video ) {
404 assert( m_initialized ); 406 assert( m_initialized );
405 407
406 m_video = video; 408 m_video = video;
407 ::null_set_show_video( m_videoOutput, video ); 409 ::null_set_show_video( m_videoOutput, video );
408} 410}
409 411
410bool Lib::isShowingVideo() const { 412bool Lib::isShowingVideo() const {
411 assert( m_initialized ); 413 assert( m_initialized );
412 414
413 return ::null_is_showing_video( m_videoOutput ); 415 return ::null_is_showing_video( m_videoOutput );
414} 416}
415 417
416void Lib::showVideoFullScreen( bool fullScreen ) { 418void Lib::showVideoFullScreen( bool fullScreen ) {
417 assert( m_initialized ); 419 assert( m_initialized );
418 420
419 #warning use xine 421 #warning use xine
420} 422}
421 423
422bool Lib::isVideoFullScreen() const { 424bool Lib::isVideoFullScreen() const {
423 assert( m_initialized ); 425 assert( m_initialized );
424 426
425 #warning use xine 427 #warning use xine
426 return false; 428 return false;
427} 429}
428 430
429void Lib::setScaling( bool scale ) { 431void Lib::setScaling( bool scale ) {
430 assert( m_initialized ); 432 assert( m_initialized );
431 433
432 xine_set_param( m_stream, XINE_PARAM_VO_ASPECT_RATIO, 434 xine_set_param( m_stream, XINE_PARAM_VO_ASPECT_RATIO,
433 scale ? XINE_VO_ASPECT_AUTO : XINE_VO_ASPECT_SQUARE ); 435 scale ? XINE_VO_ASPECT_AUTO : XINE_VO_ASPECT_SQUARE );
434} 436}
435 437
436void Lib::setGamma( int value ) { 438void Lib::setGamma( int value ) {
437 assert( m_initialized ); 439 assert( m_initialized );
438 xine_set_param( m_stream, XINE_PARAM_VO_BRIGHTNESS, value ); 440 xine_set_param( m_stream, XINE_PARAM_VO_BRIGHTNESS, value );
439} 441}
440 442
441bool Lib::isScaling() const { 443bool Lib::isScaling() const {
442 assert( m_initialized ); 444 assert( m_initialized );
443 445
444 int aratio = xine_get_param( m_stream, XINE_PARAM_VO_ASPECT_RATIO ); 446 int aratio = xine_get_param( m_stream, XINE_PARAM_VO_ASPECT_RATIO );
445 return aratio == XINE_VO_ASPECT_AUTO; 447 return aratio == XINE_VO_ASPECT_AUTO;
446} 448}
447 449
448void Lib::xine_event_handler( void* user_data, const xine_event_t* t ) { 450void Lib::xine_event_handler( void* user_data, const xine_event_t* t ) {
449 ( (Lib*)user_data)->handleXineEvent( t ); 451 ( (Lib*)user_data)->handleXineEvent( t );
450} 452}
451 453
452void Lib::xine_display_frame( void* user_data, uint8_t *frame, 454void Lib::xine_display_frame( void* user_data, uint8_t *frame,
453 int width, int height, int bytes ) { 455 int width, int height, int bytes ) {
454 ( (Lib*)user_data)->drawFrame( frame, width, height, bytes ); 456 ( (Lib*)user_data)->drawFrame( frame, width, height, bytes );
455} 457}
456 458
457void Lib::xine_vo_scale_cb( void *user_data, int video_with, int video_height, 459void Lib::xine_vo_scale_cb( void *user_data, int video_with, int video_height,
458 double video_pixel_aspect, 460 double video_pixel_aspect,
459 int *dest_x, int *dest_y, int *dest_width, 461 int *dest_x, int *dest_y, int *dest_width,
460 int *dest_height, double *dest_pixel_aspect, 462 int *dest_height, double *dest_pixel_aspect,
461 int *win_x, int *win_y ) { 463 int *win_x, int *win_y ) {
462 QSize size = ((Lib*)user_data)->m_videoSize; 464 QSize size = ((Lib*)user_data)->m_videoSize;
463 if (!size.isValid()) 465 if (!size.isValid())
464 return; 466 return;
465 467
466 *dest_x = 0; 468 *dest_x = 0;
467 *dest_y = 0; 469 *dest_y = 0;
468 *dest_width = size.width(); 470 *dest_width = size.width();
469 *dest_height = size.height(); 471 *dest_height = size.height();
470 *win_x = 0; 472 *win_x = 0;
471 *win_y = 0; 473 *win_y = 0;
472} 474}
473 475
474void Lib::xine_dest_cb( void* user_data, int, int, double, 476void Lib::xine_dest_cb( void* user_data, int, int, double,
475 int *dest_width, int* dest_height, double* ) { 477 int *dest_width, int* dest_height, double* ) {
476 QSize size = ((Lib*)user_data)->m_videoSize; 478 QSize size = ((Lib*)user_data)->m_videoSize;
477 if ( !size.isValid() ) 479 if ( !size.isValid() )
478 return; 480 return;
479 481
480 *dest_width = size.width(); 482 *dest_width = size.width();
481 *dest_height = size.height(); 483 *dest_height = size.height();
482} 484}
483 485
484void Lib::drawFrame( uint8_t* frame, int width, int height, int bytes ) { 486void Lib::drawFrame( uint8_t* frame, int width, int height, int bytes ) {
485 assert( m_initialized ); 487 assert( m_initialized );
486 488
487 if ( !m_video ) 489 if ( !m_video )
488 return; 490 return;
489 491
490 if (m_wid) m_wid-> setVideoFrame ( frame, width, height, bytes ); 492 if (m_wid) m_wid-> setVideoFrame ( frame, width, height, bytes );
491} 493}
diff --git a/noncore/multimedia/opieplayer2/om3u.cpp b/noncore/multimedia/opieplayer2/om3u.cpp
index 790fa09..f2a01d3 100644
--- a/noncore/multimedia/opieplayer2/om3u.cpp
+++ b/noncore/multimedia/opieplayer2/om3u.cpp
@@ -1,152 +1,145 @@
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/* OPIE */ 34/* OPIE */
35#include <opie2/odebug.h> 35#include <opie2/odebug.h>
36using namespace Opie::Core; 36using namespace Opie::Core;
37 37
38//extern PlayListWidget *playList; 38//extern PlayListWidget *playList;
39 39
40Om3u::Om3u( const QString &filePath, int mode) 40Om3u::Om3u( const QString &filePath, int mode)
41 : QStringList (){ 41 : QStringList ()
42odebug << "<<<<<<<new m3u "+filePath << oendl; 42{
43 f.setName(filePath); 43 odebug << "<<<<<<<new m3u "+filePath << oendl;
44 f.open(mode); 44 f.setName(filePath);
45 if (!f.open(mode)) {
46 owarn << "Unable to open file " << f.name() << oendl;
47 }
45} 48}
46 49
47Om3u::~Om3u(){} 50Om3u::~Om3u(){}
48 51
49void Om3u::readM3u() { 52void Om3u::readM3u() {
50// odebug << "<<<<<<reading m3u "+f.name() << oendl; 53// odebug << "<<<<<<reading m3u "+f.name() << oendl;
51 QTextStream t(&f); 54 QTextStream t(&f);
52 t.setEncoding(QTextStream::UnicodeUTF8); 55 t.setEncoding(QTextStream::UnicodeUTF8);
53 QString s; 56 QString s;
54 while ( !t.atEnd() ) { 57 while ( !t.atEnd() ) {
55 s=t.readLine(); 58 s=t.readLine();
56// odebug << s << oendl; 59 // odebug << s << oendl;
57 if( s.find( "#", 0, TRUE) == -1 ) { 60 if( s.find( "#", 0, TRUE) == -1 ) {
58 if( s.left(2) == "E:" || s.left(2) == "P:" ) { 61 if( s.left(2) == "E:" || s.left(2) == "P:" ) {
59 s = s.right( s.length() -2 ); 62 s = s.right( s.length() -2 );
60 QFileInfo f( s ); 63 QFileInfo f( s );
61 QString name = f.baseName(); 64 QString name = f.baseName();
62 name = name.right( name.length() - name.findRev( "\\", -1, TRUE ) -1 ); 65 name = name.right( name.length() - name.findRev( "\\", -1, TRUE ) -1 );
63 s=s.replace( QRegExp( "\\" ), "/" ); 66 s=s.replace( QRegExp( "\\" ), "/" );
64 append(s); 67 append(s);
65// odebug << s << oendl; 68// odebug << s << oendl;
66 } else { // is url 69 } else { // is url
67 QString name; 70 QString name;
68 name = s; 71 name = s;
69 append(name); 72 append(name);
70 } 73 }
71 } 74 }
72 } 75 }
73} 76}
74 77
75void Om3u::readPls() { //it's a pls file 78void Om3u::readPls() { //it's a pls file
76 QTextStream t( &f ); 79 QTextStream t( &f );
77 t.setEncoding(QTextStream::UnicodeUTF8); 80 t.setEncoding(QTextStream::UnicodeUTF8);
78 QString s; 81 QString s;
79 while ( !t.atEnd() ) { 82 while ( !t.atEnd() ) {
80 s = t.readLine(); 83 s = t.readLine();
81 if( s.left(4) == "File" ) { 84 if( s.left(4) == "File" ) {
82 s = s.right( s.length() - s.find("=",0,true)-1 ); 85 s = s.right( s.length() - s.find("=",0,true)-1 );
83 s = s.stripWhiteSpace(); 86 s = s.stripWhiteSpace();
84 s.replace( QRegExp( "%20" )," "); 87 s.replace( QRegExp( "%20" )," ");
85// odebug << "adding " + s + " to playlist" << oendl; 88 // odebug << "adding " + s + " to playlist" << oendl;
86 // numberofentries=2 89 s = s.replace( QRegExp( "\\" ), "/" );
87 // File1=http 90 QFileInfo f( s );
88 // Title 91 QString name = f.baseName();
89 // Length 92 if( name.left( 4 ) == "http" ) {
90 // Version 93 name = s.right( s.length() - 7);
91 // File2=http 94 } else {
92 s = s.replace( QRegExp( "\\" ), "/" ); 95 name = s;
93 QFileInfo f( s ); 96 }
94 QString name = f.baseName(); 97 name = name.right( name.length() - name.findRev( "\\", -1, TRUE) - 1 );
95 if( name.left( 4 ) == "http" ) { 98 if( s.at( s.length() - 4) == '.') // if this is probably a file
96 name = s.right( s.length() - 7); 99 append(s);
97 } else { 100 else { //if its a url
98 name = s;
99 }
100 name = name.right( name.length() - name.findRev( "\\", -1, TRUE) - 1 );
101 if( s.at( s.length() - 4) == '.') // if this is probably a file
102 append(s); 101 append(s);
103 else { //if its a url
104// if( name.right( 1 ).find( '/' ) == -1) {
105// s += "/";
106// }
107 append(s);
108 }
109 } 102 }
110 } 103 }
104 }
111} 105}
112 106
113void Om3u::write() { //writes list to m3u file 107void Om3u::write() { //writes list to m3u file
114 QString list; 108 QString list;
115 QTextStream t(&f); 109 QTextStream t(&f);
116 t.setEncoding(QTextStream::UnicodeUTF8); 110 t.setEncoding(QTextStream::UnicodeUTF8);
117 if(count()>0) { 111 if(count()>0) {
118 for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) { 112 for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) {
119// odebug << *it << oendl; 113 // odebug << *it << oendl;
120 t << *it << "\n"; 114 t << *it << "\n";
115 }
121 } 116 }
122 }
123// f.close();
124} 117}
125 118
126void Om3u::add(const QString &filePath) { //adds to m3u file 119void Om3u::add(const QString &filePath) { //adds to m3u file
127 append(filePath); 120 append(filePath);
128} 121}
129 122
130void Om3u::remove(const QString &filePath) { //removes from m3u list 123void Om3u::remove(const QString &filePath) { //removes from m3u list
131 QString list, currentFile; 124 QString list, currentFile;
132 if(count()>0) { 125 if(count()>0) {
133 for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) { 126 for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) {
134 currentFile=*it; 127 currentFile=*it;
135 // odebug << *it << oendl; 128 // odebug << *it << oendl;
136 129
137 if( filePath != currentFile) 130 if( filePath != currentFile)
138 list += currentFile+"\n"; 131 list += currentFile+"\n";
132 }
133 f.writeBlock( list, list.length() );
139 } 134 }
140 f.writeBlock( list, list.length() );
141 }
142} 135}
143 136
144void Om3u::deleteFile(const QString &/*filePath*/) {//deletes m3u file 137void Om3u::deleteFile(const QString &/*filePath*/) {//deletes m3u file
145 f.close(); 138 f.close();
146 f.remove(); 139 f.remove();
147 140
148} 141}
149 142
150void Om3u::close() { //closes m3u file 143void Om3u::close() { //closes m3u file
151 f.close(); 144 f.close();
152} 145}
diff --git a/noncore/multimedia/opieplayer2/threadutil.cpp b/noncore/multimedia/opieplayer2/threadutil.cpp
index b5cac61..5fc8a0b 100644
--- a/noncore/multimedia/opieplayer2/threadutil.cpp
+++ b/noncore/multimedia/opieplayer2/threadutil.cpp
@@ -1,394 +1,399 @@
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 <opie2/odebug.h> 22#include <opie2/odebug.h>
23#include <qsocketnotifier.h> 23#include <qsocketnotifier.h>
24 24
25#include <pthread.h> 25#include <pthread.h>
26#include <assert.h> 26#include <assert.h>
27#include <unistd.h> 27#include <unistd.h>
28#include <errno.h> 28#include <errno.h>
29 29
30using namespace ThreadUtil; 30using namespace ThreadUtil;
31 31
32struct Mutex::Data 32struct Mutex::Data
33{ 33{
34 Data() 34 Data()
35 { 35 {
36 pthread_mutex_init( &mutex, 0 ); 36 pthread_mutex_init( &mutex, 0 );
37 } 37 }
38 ~Data() 38 ~Data()
39 { 39 {
40 pthread_mutex_destroy( &mutex ); 40 pthread_mutex_destroy( &mutex );
41 } 41 }
42 42
43 pthread_mutex_t mutex; 43 pthread_mutex_t mutex;
44}; 44};
45 45
46Mutex::Mutex() 46Mutex::Mutex()
47 : d( new Data ) 47 : d( new Data )
48{ 48{
49} 49}
50 50
51Mutex::~Mutex() 51Mutex::~Mutex()
52{ 52{
53 delete d; 53 delete d;
54} 54}
55 55
56void Mutex::lock() 56void Mutex::lock()
57{ 57{
58 pthread_mutex_lock( &d->mutex ); 58 pthread_mutex_lock( &d->mutex );
59} 59}
60 60
61void Mutex::unlock() 61void Mutex::unlock()
62{ 62{
63 pthread_mutex_unlock( &d->mutex ); 63 pthread_mutex_unlock( &d->mutex );
64} 64}
65 65
66bool Mutex::tryLock() 66bool Mutex::tryLock()
67{ 67{
68 return pthread_mutex_trylock( &d->mutex ) == 0; 68 return pthread_mutex_trylock( &d->mutex ) == 0;
69} 69}
70 70
71bool Mutex::isLocked() 71bool Mutex::isLocked()
72{ 72{
73 if ( !tryLock() ) 73 if ( !tryLock() )
74 return true; 74 return true;
75 75
76 unlock(); 76 unlock();
77 return false; 77 return false;
78} 78}
79 79
80struct WaitCondition::Data 80struct WaitCondition::Data
81{ 81{
82 Data() 82 Data()
83 { 83 {
84 int result = pthread_cond_init( &waitCondition, 0 ); 84 int result = pthread_cond_init( &waitCondition, 0 );
85 assert( result == 0 ); 85 assert( result == 0 );
86 } 86 }
87 ~Data() 87 ~Data()
88 { 88 {
89 pthread_cond_destroy( &waitCondition ); 89 pthread_cond_destroy( &waitCondition );
90 } 90 }
91 91
92 pthread_cond_t waitCondition; 92 pthread_cond_t waitCondition;
93}; 93};
94 94
95WaitCondition::WaitCondition() 95WaitCondition::WaitCondition()
96 : d( new Data ) 96 : d( new Data )
97{ 97{
98} 98}
99 99
100WaitCondition::~WaitCondition() 100WaitCondition::~WaitCondition()
101{ 101{
102 delete d; 102 delete d;
103} 103}
104 104
105bool WaitCondition::wait() 105bool WaitCondition::wait()
106{ 106{
107 Mutex m; 107 Mutex m;
108 m.lock(); 108 m.lock();
109 return wait( m ); 109 return wait( m );
110} 110}
111 111
112bool WaitCondition::wait( Mutex &mutex ) 112bool WaitCondition::wait( Mutex &mutex )
113{ 113{
114 return pthread_cond_wait( &d->waitCondition, &mutex.d->mutex ); 114 return pthread_cond_wait( &d->waitCondition, &mutex.d->mutex );
115} 115}
116 116
117void WaitCondition::wakeOne() 117void WaitCondition::wakeOne()
118{ 118{
119 pthread_cond_signal( &d->waitCondition ); 119 pthread_cond_signal( &d->waitCondition );
120} 120}
121 121
122void WaitCondition::wakeAll() 122void WaitCondition::wakeAll()
123{ 123{
124 pthread_cond_broadcast( &d->waitCondition ); 124 pthread_cond_broadcast( &d->waitCondition );
125} 125}
126 126
127struct Thread::Data 127struct Thread::Data
128{ 128{
129 Data() : isRunning( false ) 129 Data() : isRunning( false )
130 {} 130 {}
131 131
132 pthread_t self; 132 pthread_t self;
133 Mutex guard; 133 Mutex guard;
134 bool isRunning; 134 bool isRunning;
135 135
136 WaitCondition finishCondition; 136 WaitCondition finishCondition;
137 137
138 Thread *thr; 138 Thread *thr;
139 139
140 void run() { thr->run(); } 140 void run() { thr->run(); }
141}; 141};
142 142
143extern "C" 143extern "C"
144{ 144{
145 145
146static void terminate_thread( void *arg ) 146static void terminate_thread( void *arg )
147{ 147{
148 Thread::Data *data = ( Thread::Data* )arg; 148 Thread::Data *data = ( Thread::Data* )arg;
149 149
150 assert( data ); 150 assert( data );
151 151
152 AutoLock locker( data->guard ); 152 AutoLock locker( data->guard );
153 data->isRunning = false; 153 data->isRunning = false;
154 data->finishCondition.wakeAll(); 154 data->finishCondition.wakeAll();
155} 155}
156 156
157static void *start_thread( void *arg ) 157static void *start_thread( void *arg )
158{ 158{
159 Thread::Data *data = ( Thread::Data* )arg; 159 Thread::Data *data = ( Thread::Data* )arg;
160 160
161 pthread_cleanup_push( terminate_thread, data ); 161 pthread_cleanup_push( terminate_thread, data );
162 162
163 data->isRunning = true; 163 data->isRunning = true;
164 data->run(); 164 data->run();
165 165
166 pthread_cleanup_pop( true ); 166 pthread_cleanup_pop( true );
167 167
168 Thread::exit(); 168 Thread::exit();
169 return 0; // never reached 169 return 0; // never reached
170} 170}
171 171
172} 172}
173 173
174Thread::Thread() 174Thread::Thread()
175 : d( new Data ) 175 : d( new Data )
176{ 176{
177 d->thr = this; 177 d->thr = this;
178} 178}
179 179
180Thread::~Thread() 180Thread::~Thread()
181{ 181{
182 assert( d->isRunning == false ); 182 assert( d->isRunning == false );
183 delete d; 183 delete d;
184} 184}
185 185
186void Thread::start() 186void Thread::start()
187{ 187{
188 AutoLock lock( d->guard ); 188 AutoLock lock( d->guard );
189 189
190 if ( d->isRunning ) { 190 if ( d->isRunning ) {
191 odebug << "ThreadUtil::Thread::start() called for running thread." << oendl; 191 odebug << "ThreadUtil::Thread::start() called for running thread." << oendl;
192 return; 192 return;
193 } 193 }
194 194
195 pthread_attr_t attributes; 195 pthread_attr_t attributes;
196 pthread_attr_init( &attributes ); 196 pthread_attr_init( &attributes );
197 pthread_attr_setscope( &attributes, PTHREAD_SCOPE_SYSTEM ); 197 pthread_attr_setscope( &attributes, PTHREAD_SCOPE_SYSTEM );
198 int err = pthread_create( &d->self, &attributes, start_thread, ( void* )d ); 198 int err = pthread_create( &d->self, &attributes, start_thread, ( void* )d );
199 if ( err != 0 ) { 199 if ( err != 0 ) {
200 odebug << "ThreadUtil::Thread::start() : can't create thread: " << strerror( err ) << "" << oendl; 200 odebug << "ThreadUtil::Thread::start() : can't create thread: " << strerror( err ) << "" << oendl;
201 pthread_attr_destroy( &attributes ); 201 pthread_attr_destroy( &attributes );
202 return; 202 return;
203 } 203 }
204 pthread_attr_destroy( &attributes ); 204 pthread_attr_destroy( &attributes );
205} 205}
206 206
207void Thread::terminate() 207void Thread::terminate()
208{ 208{
209 AutoLock lock( d->guard ); 209 AutoLock lock( d->guard );
210 if ( !d->isRunning ) 210 if ( !d->isRunning )
211 return; 211 return;
212 212
213 pthread_cancel( d->self ); 213 pthread_cancel( d->self );
214} 214}
215 215
216bool Thread::wait() 216bool Thread::wait()
217{ 217{
218 AutoLock lock( d->guard ); 218 AutoLock lock( d->guard );
219 if ( !d->isRunning ) 219 if ( !d->isRunning )
220 return true; 220 return true;
221 221
222 return d->finishCondition.wait( d->guard ); 222 return d->finishCondition.wait( d->guard );
223} 223}
224 224
225bool Thread::isRunning() const 225bool Thread::isRunning() const
226{ 226{
227 AutoLock lock( d->guard ); 227 AutoLock lock( d->guard );
228 return d->isRunning; 228 return d->isRunning;
229} 229}
230 230
231void Thread::exit() 231void Thread::exit()
232{ 232{
233 pthread_exit( 0 ); 233 pthread_exit( 0 );
234} 234}
235 235
236OnewayNotifier::OnewayNotifier() 236OnewayNotifier::OnewayNotifier() :
237{ 237 m_readFd(-1),
238 int fds[ 2 ]; 238 m_writeFd(-1)
239 pipe( fds ); 239{
240 m_readFd = fds[ 0 ]; 240 int fds[ 2 ] = { -1, -1 };
241 m_writeFd = fds[ 1 ]; 241 if (pipe( fds ) == 0) {
242 m_readFd = fds[ 0 ];
243 m_writeFd = fds[ 1 ];
244 } else {
245 owarn << "Call to pipe() failed" << oendl;
246 }
242 247
243 m_notifier = new QSocketNotifier( m_readFd, QSocketNotifier::Read ); 248 m_notifier = new QSocketNotifier( m_readFd, QSocketNotifier::Read );
244 connect( m_notifier, SIGNAL( activated(int) ), 249 connect( m_notifier, SIGNAL( activated(int) ),
245 this, SLOT( wakeUp() ) ); 250 this, SLOT( wakeUp() ) );
246} 251}
247 252
248OnewayNotifier::~OnewayNotifier() 253OnewayNotifier::~OnewayNotifier()
249{ 254{
250 delete m_notifier; 255 delete m_notifier;
251 256
252 ::close( m_readFd ); 257 ::close( m_readFd );
253 ::close( m_writeFd ); 258 ::close( m_writeFd );
254} 259}
255 260
256void OnewayNotifier::notify() 261void OnewayNotifier::notify()
257{ 262{
258 const char c = 42; 263 const char c = 42;
259 ::write( m_writeFd, &c, 1 ); 264 ::write( m_writeFd, &c, 1 );
260} 265}
261 266
262void OnewayNotifier::wakeUp() 267void OnewayNotifier::wakeUp()
263{ 268{
264 char c = 0; 269 char c = 0;
265 270
266 if ( ::read( m_readFd, &c, 1 ) != 1 ) 271 if ( ::read( m_readFd, &c, 1 ) != 1 )
267 return; 272 return;
268 273
269 emit awake(); 274 emit awake();
270} 275}
271 276
272ChannelMessage::ChannelMessage( int type, int data, const char* msg ) 277ChannelMessage::ChannelMessage( int type, int data, const char* msg )
273 : m_type( type ), m_data( data ), m_msg( msg ), 278 : m_type( type ), m_data( data ), m_msg( msg ),
274 m_isCall( false ), m_replied( false ), m_inEventHandler( false ) 279 m_isCall( false ), m_replied( false ), m_inEventHandler( false )
275{} 280{}
276 281
277ChannelMessage::~ChannelMessage() 282ChannelMessage::~ChannelMessage()
278{ 283{
279 if ( m_guard.isLocked() ) 284 if ( m_guard.isLocked() )
280 m_guard.unlock(); 285 m_guard.unlock();
281} 286}
282 287
283void ChannelMessage::reply() 288void ChannelMessage::reply()
284{ 289{
285 if ( !m_isCall ) 290 if ( !m_isCall )
286 { 291 {
287 odebug << "ChannelMessage::reply() - can't reply oneway message!" << oendl; 292 odebug << "ChannelMessage::reply() - can't reply oneway message!" << oendl;
288 return; 293 return;
289 } 294 }
290 295
291 if ( m_inEventHandler ) 296 if ( m_inEventHandler )
292 { 297 {
293 m_replied = true; 298 m_replied = true;
294 return; 299 return;
295 } 300 }
296 301
297 m_condition.wakeOne(); 302 m_condition.wakeOne();
298 m_guard.unlock(); 303 m_guard.unlock();
299} 304}
300 305
301struct Channel::Private 306struct Channel::Private
302{ 307{
303 Private() 308 Private()
304 { 309 {
305 ownerThread = pthread_self(); 310 ownerThread = pthread_self();
306 } 311 }
307 312
308 pthread_t ownerThread; 313 pthread_t ownerThread;
309}; 314};
310 315
311Channel::Channel( QObject *parent, const char *name ) 316Channel::Channel( QObject *parent, const char *name )
312 : QObject( parent, name ), d( new Private ) 317 : QObject( parent, name ), d( new Private )
313{ 318{
314 connect( &m_notifier, SIGNAL( awake() ), 319 connect( &m_notifier, SIGNAL( awake() ),
315 this, SLOT( deliver() ) ); 320 this, SLOT( deliver() ) );
316} 321}
317 322
318Channel::~Channel() 323Channel::~Channel()
319{ 324{
320 delete d; 325 delete d;
321} 326}
322 327
323void Channel::send( ChannelMessage *message, SendType type ) 328void Channel::send( ChannelMessage *message, SendType type )
324{ 329{
325 if ( type == WaitForReply ) 330 if ( type == WaitForReply )
326 { 331 {
327 message->m_guard.lock(); 332 message->m_guard.lock();
328 message->m_isCall = true; 333 message->m_isCall = true;
329 } 334 }
330 335
331 m_pendingMessagesGuard.lock(); 336 m_pendingMessagesGuard.lock();
332 m_pendingMessages << MsgEnvelope( type, message ); 337 m_pendingMessages << MsgEnvelope( type, message );
333 m_pendingMessagesGuard.unlock(); 338 m_pendingMessagesGuard.unlock();
334 339
335 if ( d->ownerThread == pthread_self() ) { 340 if ( d->ownerThread == pthread_self() ) {
336 assert( type != WaitForReply ); 341 assert( type != WaitForReply );
337 342
338 deliver(); 343 deliver();
339 } 344 }
340 else 345 else
341 m_notifier.notify(); 346 m_notifier.notify();
342 //QThread::postEvent( this, new QCustomEvent( QEvent::User, envelope ) ); 347 //QThread::postEvent( this, new QCustomEvent( QEvent::User, envelope ) );
343 348
344 if ( type == WaitForReply ) 349 if ( type == WaitForReply )
345 { 350 {
346 message->m_condition.wait( message->m_guard ); 351 message->m_condition.wait( message->m_guard );
347 message->m_guard.unlock(); 352 message->m_guard.unlock();
348 } 353 }
349} 354}
350 355
351void Channel::deliver() 356void Channel::deliver()
352{ 357{
353 AutoLock lock( m_pendingMessagesGuard ); 358 AutoLock lock( m_pendingMessagesGuard );
354 359
355 while ( !m_pendingMessages.isEmpty() ) { 360 while ( !m_pendingMessages.isEmpty() ) {
356 MsgEnvelope envelope = m_pendingMessages.first(); 361 MsgEnvelope envelope = m_pendingMessages.first();
357 362
358 m_pendingMessages.remove( m_pendingMessages.begin() ); 363 m_pendingMessages.remove( m_pendingMessages.begin() );
359 364
360 m_pendingMessagesGuard.unlock(); 365 m_pendingMessagesGuard.unlock();
361 deliverOne( envelope ); 366 deliverOne( envelope );
362 m_pendingMessagesGuard.lock(); 367 m_pendingMessagesGuard.lock();
363 } 368 }
364} 369}
365 370
366void Channel::deliverOne( const MsgEnvelope &envelope ) 371void Channel::deliverOne( const MsgEnvelope &envelope )
367{ 372{
368 ChannelMessage *msg = envelope.msg; 373 ChannelMessage *msg = envelope.msg;
369 374
370 assert( msg ); 375 assert( msg );
371 376
372 if ( envelope.type == WaitForReply ) 377 if ( envelope.type == WaitForReply )
373 { 378 {
374 msg->m_guard.lock(); 379 msg->m_guard.lock();
375 msg->m_inEventHandler = true; 380 msg->m_inEventHandler = true;
376 } 381 }
377 382
378 receiveMessage( msg, envelope.type ); 383 receiveMessage( msg, envelope.type );
379 384
380 if ( envelope.type == WaitForReply ) 385 if ( envelope.type == WaitForReply )
381 { 386 {
382 msg->m_inEventHandler = false; 387 msg->m_inEventHandler = false;
383 if ( msg->m_replied ) 388 if ( msg->m_replied )
384 { 389 {
385 msg->m_condition.wakeOne(); 390 msg->m_condition.wakeOne();
386 // this is a bit tricky. we unlock only when we reply. 391 // this is a bit tricky. we unlock only when we reply.
387 // reply() does an unlock as well. 392 // reply() does an unlock as well.
388 msg->m_guard.unlock(); 393 msg->m_guard.unlock();
389 } 394 }
390 } 395 }
391} 396}
392 397
393/* vim: et sw=4 ts=4 398/* vim: et sw=4 ts=4
394 */ 399 */
diff --git a/noncore/net/opiestumbler/opiestumbler.cpp b/noncore/net/opiestumbler/opiestumbler.cpp
index 9b0d099..ab0b8d8 100644
--- a/noncore/net/opiestumbler/opiestumbler.cpp
+++ b/noncore/net/opiestumbler/opiestumbler.cpp
@@ -1,384 +1,385 @@
1#include <cstdlib> 1#include <cstdlib>
2 2
3#include <qmenubar.h> 3#include <qmenubar.h>
4#include <qaction.h> 4#include <qaction.h>
5#include <qlistview.h> 5#include <qlistview.h>
6#include <qstring.h> 6#include <qstring.h>
7//#include <qapplication.h> 7//#include <qapplication.h>
8#include <qdatetime.h> 8#include <qdatetime.h>
9#include <qpopupmenu.h> 9#include <qpopupmenu.h>
10#include <qstatusbar.h> 10#include <qstatusbar.h>
11#include <qlayout.h> 11#include <qlayout.h>
12#include <qwhatsthis.h> 12#include <qwhatsthis.h>
13#include <qtimer.h> 13#include <qtimer.h>
14#include <qprogressbar.h> 14#include <qprogressbar.h>
15 15
16#include <qpe/config.h> 16#include <qpe/config.h>
17//#include <qpe/global.h> 17//#include <qpe/global.h>
18#include <qpe/qcopenvelope_qws.h> 18#include <qpe/qcopenvelope_qws.h>
19#include <qpe/qpeapplication.h> 19#include <qpe/qpeapplication.h>
20 20
21#include <opie2/odebug.h> 21#include <opie2/odebug.h>
22#include <opie2/ostation.h> 22#include <opie2/ostation.h>
23#include <opie2/omanufacturerdb.h> 23#include <opie2/omanufacturerdb.h>
24#include <opie2/onetwork.h> 24#include <opie2/onetwork.h>
25#include <opie2/oprocess.h> 25#include <opie2/oprocess.h>
26 26
27#include "stumbler.h" 27#include "stumbler.h"
28#include "opiestumbler.h" 28#include "opiestumbler.h"
29#include "stumblersettings.h" 29#include "stumblersettings.h"
30#include "stationviewitem.h" 30#include "stationviewitem.h"
31#include "stumblerstation.h" 31#include "stumblerstation.h"
32#include "stationinfo.h" 32#include "stationinfo.h"
33 33
34 34
35using Opie::Net::OWirelessNetworkInterface; 35using Opie::Net::OWirelessNetworkInterface;
36using Opie::Net::ONetwork; 36using Opie::Net::ONetwork;
37 37
38 38
39QString OpieStumbler::appCaption() { 39QString OpieStumbler::appCaption() {
40 return QObject::tr("OpieStumbler"); 40 return QObject::tr("OpieStumbler");
41} 41}
42 42
43OpieStumbler::OpieStumbler(QWidget *parent, const char *name, WFlags) 43OpieStumbler::OpieStumbler(QWidget *parent, const char *name, WFlags)
44 :QMainWindow(parent, name, WStyle_ContextHelp), 44 :QMainWindow(parent, name, WStyle_ContextHelp),
45 m_listCurrent(new QListView(this)), m_listHistory(new QListView(this)), 45 m_listCurrent(new QListView(this)), m_listHistory(new QListView(this)),
46 m_stationsCurrent(new QList<Opie::Net::OStation>), 46 m_stationsCurrent(new QList<Opie::Net::OStation>),
47 m_popupCurrent(new QPopupMenu(this)), 47 m_popupCurrent(new QPopupMenu(this)),
48 m_popupHistory(new QPopupMenu(this)), 48 m_popupHistory(new QPopupMenu(this)),
49 m_db(NULL), m_proc(NULL) 49 m_db(NULL), m_proc(NULL)
50{ 50{
51 51
52 if ( QCopChannel::isRegistered("QPE/OpieStumbler") ) { 52 if ( QCopChannel::isRegistered("QPE/OpieStumbler") ) {
53 QCopEnvelope e("QPE/OpieStumbler", "show()"); 53 QCopEnvelope e("QPE/OpieStumbler", "show()");
54 exit(EXIT_SUCCESS); 54 exit(EXIT_SUCCESS);
55 } 55 }
56 56
57 QGridLayout *grid = new QGridLayout( this, 1, 1, 3, 0, "grid"); 57 QGridLayout *grid = new QGridLayout( this, 1, 1, 3, 0, "grid");
58 QVBoxLayout *lay = new QVBoxLayout( NULL, 0, 5, "lay" ); 58 QVBoxLayout *lay = new QVBoxLayout( NULL, 0, 5, "lay" );
59 QSpacerItem *spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Fixed ); 59 QSpacerItem *spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Fixed );
60 lay->addItem(spacer); 60 lay->addItem(spacer);
61 lay->addWidget(m_listCurrent); 61 lay->addWidget(m_listCurrent);
62 lay->addWidget(m_listHistory); 62 lay->addWidget(m_listHistory);
63 grid->addLayout(lay, 0, 0); 63 grid->addLayout(lay, 0, 0);
64 64
65 m_stationsCurrent->setAutoDelete(true); 65 m_stationsCurrent->setAutoDelete(true);
66 66
67 m_channel = new QCopChannel( "QPE/OpieStumbler", this ); 67 m_channel = new QCopChannel( "QPE/OpieStumbler", this );
68 connect(m_channel, SIGNAL(received(const QCString &, const QByteArray &)), 68 connect(m_channel, SIGNAL(received(const QCString &, const QByteArray &)),
69 this, SLOT(slotMessageReceived( const QCString &, const QByteArray &)) ); 69 this, SLOT(slotMessageReceived( const QCString &, const QByteArray &)) );
70 70
71 //setCaption(appCaption()); 71 //setCaption(appCaption());
72 //setCentralWidget(grid); 72 //setCentralWidget(grid);
73 setToolBarsMovable(false); 73 setToolBarsMovable(false);
74 74
75 75
76 QPopupMenu *fileMenu = new QPopupMenu(this); 76 QPopupMenu *fileMenu = new QPopupMenu(this);
77 QPopupMenu *configMenu = new QPopupMenu(this); 77 QPopupMenu *configMenu = new QPopupMenu(this);
78 QPopupMenu *scanMenu = new QPopupMenu(this); 78 QPopupMenu *scanMenu = new QPopupMenu(this);
79 79
80 fileMenu->insertItem( tr("Exit"), this, SLOT(close()) ); 80 fileMenu->insertItem( tr("Exit"), this, SLOT(close()) );
81 configMenu->insertItem( tr("Configure"), this, SLOT(slotConfigure()) ); 81 configMenu->insertItem( tr("Configure"), this, SLOT(slotConfigure()) );
82 scanMenu->insertItem( tr("Start"), this, SLOT(slotStartScanning()) ); 82 scanMenu->insertItem( tr("Start"), this, SLOT(slotStartScanning()) );
83 scanMenu->insertItem( tr("Stop"), this, SLOT(slotStopScanning()) ); 83 scanMenu->insertItem( tr("Stop"), this, SLOT(slotStopScanning()) );
84 84
85 m_popupCurrent->insertItem( tr("Show details"), this, SLOT(slotShowDetails()) ); 85 m_popupCurrent->insertItem( tr("Show details"), this, SLOT(slotShowDetails()) );
86 m_popupCurrent->insertItem( tr("Join Network"), this, SLOT(slotJoinNetwork()) ); 86 m_popupCurrent->insertItem( tr("Join Network"), this, SLOT(slotJoinNetwork()) );
87 87
88 menuBar()->insertItem(tr("File"), fileMenu); 88 menuBar()->insertItem(tr("File"), fileMenu);
89 menuBar()->insertItem(tr("Settings"), configMenu); 89 menuBar()->insertItem(tr("Settings"), configMenu);
90 menuBar()->insertItem(tr("Scanning"), scanMenu); 90 menuBar()->insertItem(tr("Scanning"), scanMenu);
91 91
92 QPEApplication::setStylusOperation(m_listCurrent->viewport(), QPEApplication::RightOnHold); 92 QPEApplication::setStylusOperation(m_listCurrent->viewport(), QPEApplication::RightOnHold);
93 QPEApplication::setStylusOperation(m_listHistory->viewport(), QPEApplication::RightOnHold); 93 QPEApplication::setStylusOperation(m_listHistory->viewport(), QPEApplication::RightOnHold);
94 94
95 m_listCurrent->addColumn(tr("SSID")); 95 m_listCurrent->addColumn(tr("SSID"));
96 m_listCurrent->addColumn(tr("Chan")); 96 m_listCurrent->addColumn(tr("Chan"));
97 m_listCurrent->addColumn(tr("Signal")); 97 m_listCurrent->addColumn(tr("Signal"));
98 m_listCurrent->addColumn(tr("Enc")); 98 m_listCurrent->addColumn(tr("Enc"));
99 m_listCurrent->setSelectionMode( QListView::Extended ); 99 m_listCurrent->setSelectionMode( QListView::Extended );
100 100
101 m_listHistory->addColumn(tr("SSID")); 101 m_listHistory->addColumn(tr("SSID"));
102 m_listHistory->addColumn(tr("Chan")); 102 m_listHistory->addColumn(tr("Chan"));
103 m_listHistory->addColumn(tr("Max Sig")); 103 m_listHistory->addColumn(tr("Max Sig"));
104 m_listHistory->addColumn(tr("Enc")); 104 m_listHistory->addColumn(tr("Enc"));
105 m_listHistory->addColumn(tr("Vendor")); 105 m_listHistory->addColumn(tr("Vendor"));
106 106
107 connect(m_listCurrent, SIGNAL(mouseButtonPressed (int, QListViewItem*, const QPoint&, int)), 107 connect(m_listCurrent, SIGNAL(mouseButtonPressed (int, QListViewItem*, const QPoint&, int)),
108 this, SLOT(slotCurrentMousePressed (int, QListViewItem*, const QPoint&, int))); 108 this, SLOT(slotCurrentMousePressed (int, QListViewItem*, const QPoint&, int)));
109 109
110 connect(m_listHistory, SIGNAL(mouseButtonPressed (int, QListViewItem*, const QPoint&, int)), 110 connect(m_listHistory, SIGNAL(mouseButtonPressed (int, QListViewItem*, const QPoint&, int)),
111 this, SLOT(slotHistoryMousePressed (int, QListViewItem*, const QPoint&, int))); 111 this, SLOT(slotHistoryMousePressed (int, QListViewItem*, const QPoint&, int)));
112 112
113 for(int i = CURCHAN; i <= CURENC; ++i) { 113 for(int i = CURCHAN; i <= CURENC; ++i) {
114 m_listCurrent->setColumnAlignment( i, Qt::AlignHCenter ); 114 m_listCurrent->setColumnAlignment( i, Qt::AlignHCenter );
115 m_listHistory->setColumnAlignment( i, Qt::AlignHCenter ); 115 m_listHistory->setColumnAlignment( i, Qt::AlignHCenter );
116 } 116 }
117 117
118 loadConfig(); 118 loadConfig();
119 m_stumbler = new Stumbler(m_interface, this); 119 m_stumbler = new Stumbler(m_interface, this);
120 connect(m_stumbler, SIGNAL(newdata()), this, SLOT(slotUpdateStations())); 120 connect(m_stumbler, SIGNAL(newdata()), this, SLOT(slotUpdateStations()));
121 121
122 QTimer::singleShot(1000, this, SLOT(slotLoadManufacturers()) ); 122 QTimer::singleShot(1000, this, SLOT(slotLoadManufacturers()) );
123 123
124 slotStartScanning(); 124 slotStartScanning();
125} 125}
126 126
127void OpieStumbler::slotConfigure() 127void OpieStumbler::slotConfigure()
128{ 128{
129 StumblerSettings settings(this, "Settings", true); 129 StumblerSettings settings(this, "Settings", true);
130 if (settings.exec() == QDialog::Accepted) 130 if (settings.exec() == QDialog::Accepted)
131 loadConfig(); 131 loadConfig();
132} 132}
133 133
134void OpieStumbler::loadConfig() 134void OpieStumbler::loadConfig()
135{ 135{
136 Config cfg("OpieStumbler", Config::User); 136 Config cfg("OpieStumbler", Config::User);
137 cfg.setGroup("General"); 137 cfg.setGroup("General");
138 m_interface = cfg.readEntry("interface", "wlan0"); 138 m_interface = cfg.readEntry("interface", "wlan0");
139} 139}
140 140
141void OpieStumbler::slotStartScanning() 141void OpieStumbler::slotStartScanning()
142{ 142{
143 setCaption(appCaption() + " (" + tr("Scanning") + ")"); 143 setCaption(appCaption() + " (" + tr("Scanning") + ")");
144 m_stumbler->start(); 144 m_stumbler->start();
145} 145}
146 146
147void OpieStumbler::slotStopScanning() 147void OpieStumbler::slotStopScanning()
148{ 148{
149 setCaption(appCaption()); 149 setCaption(appCaption());
150 m_stumbler->stop(); 150 m_stumbler->stop();
151} 151}
152 152
153void OpieStumbler::slotUpdateStations() 153void OpieStumbler::slotUpdateStations()
154{ 154{
155 m_stationsCurrent->clear(); 155 m_stationsCurrent->clear();
156 156
157 m_stationsCurrent = m_stumbler->stations(); 157 m_stationsCurrent = m_stumbler->stations();
158 if (m_stationsCurrent) { 158 if (m_stationsCurrent) {
159 QListIterator<Opie::Net::OStation> it(*m_stationsCurrent); 159 QListIterator<Opie::Net::OStation> it(*m_stationsCurrent);
160 for(; it.current(); ++it) { 160 for(; it.current(); ++it) {
161 Opie::Net::OStation *station = it.current(); 161 Opie::Net::OStation *station = it.current();
162 QListIterator<StumblerStation> itr(m_stationsHistory); 162 QListIterator<StumblerStation> itr(m_stationsHistory);
163 for( ; itr.current(); ++itr) { 163 for( ; itr.current(); ++itr) {
164 if (itr.current()->st->macAddress.toString() == station->macAddress.toString()) { 164 if (itr.current()->st->macAddress.toString() == station->macAddress.toString()) {
165 break; 165 break;
166 } 166 }
167 } 167 }
168 if (!itr.current()) { 168 if (!itr.current()) {
169 //We need to copy the date because m_statiosCurrent has autodelete enabled 169 //We need to copy the date because m_statiosCurrent has autodelete enabled
170 m_stationsHistory.append(new StumblerStation(new Opie::Net::OStation, QDateTime::currentDateTime())); 170 m_stationsHistory.append(new StumblerStation(new Opie::Net::OStation, QDateTime::currentDateTime()));
171 *(m_stationsHistory.last()->st) = (*station); 171 *(m_stationsHistory.last()->st) = (*station);
172 } 172 }
173 else { 173 else {
174 if ( itr.current()->st->level < station->level ) 174 if ( itr.current()->st->level < station->level )
175 itr.current()->st->level = station->level; 175 itr.current()->st->level = station->level;
176 176
177 itr.current()->lastTimeSeen = QDateTime::currentDateTime(); 177 itr.current()->lastTimeSeen = QDateTime::currentDateTime();
178 } 178 }
179 } 179 }
180 } 180 }
181 displayStations(); 181 displayStations();
182} 182}
183 183
184void OpieStumbler::displayStations() 184void OpieStumbler::displayStations()
185{ 185{
186 m_listCurrent->clear(); 186 m_listCurrent->clear();
187 for(QListIterator<Opie::Net::OStation> it(*m_stationsCurrent); it.current(); ++it) 187 for(QListIterator<Opie::Net::OStation> it(*m_stationsCurrent); it.current(); ++it)
188 new StationViewItem( m_listCurrent, it.current()->ssid, QString::number(it.current()->channel), 188 new StationViewItem( m_listCurrent, it.current()->ssid, QString::number(it.current()->channel),
189 QString::number(it.current()->level), it.current()->encrypted ? "Y": "N", it.current()->macAddress.toString() ); 189 QString::number(it.current()->level), it.current()->encrypted ? "Y": "N", it.current()->macAddress.toString() );
190 190
191 m_listHistory->clear(); 191 m_listHistory->clear();
192 for(QListIterator<StumblerStation> it(m_stationsHistory); it.current(); ++it) 192 for(QListIterator<StumblerStation> it(m_stationsHistory); it.current(); ++it)
193 new StationViewItem( m_listHistory, it.current()->st->ssid, QString::number(it.current()->st->channel), 193 new StationViewItem( m_listHistory, it.current()->st->ssid, QString::number(it.current()->st->channel),
194 QString::number(it.current()->st->level), it.current()->st->encrypted ? "Y": "N", 194 QString::number(it.current()->st->level), it.current()->st->encrypted ? "Y": "N",
195 manufacturer(it.current()->st->macAddress.toString()), it.current()->st->macAddress.toString() ); 195 manufacturer(it.current()->st->macAddress.toString()), it.current()->st->macAddress.toString() );
196} 196}
197 197
198void OpieStumbler::slotMessageReceived( const QCString &message, const QByteArray &parameters) 198void OpieStumbler::slotMessageReceived( const QCString &message, const QByteArray &parameters)
199{ 199{
200 Q_UNUSED(const_cast<QByteArray &>(parameters)) 200 Q_UNUSED(const_cast<QByteArray &>(parameters))
201 201
202 if ( message == "show()" ) 202 if ( message == "show()" )
203 show(); 203 show();
204} 204}
205 205
206void OpieStumbler::slotCurrentMousePressed(int button, QListViewItem * item, const QPoint &point, int c) 206void OpieStumbler::slotCurrentMousePressed(int button, QListViewItem * item, const QPoint &point, int c)
207{ 207{
208 Q_UNUSED(c) 208 Q_UNUSED(c)
209 209
210 if ( 2 == button ) { 210 if ( 2 == button ) {
211 m_mac = item->text(CURENC + 1); 211 m_mac = item->text(CURENC + 1);
212 m_popupCurrent->popup(point); 212 m_popupCurrent->popup(point);
213 } 213 }
214} 214}
215 215
216 216
217void OpieStumbler::slotHistoryMousePressed(int button, QListViewItem * item, const QPoint &point, int c) 217void OpieStumbler::slotHistoryMousePressed(int button, QListViewItem * item, const QPoint &point, int c)
218{ 218{
219 Q_UNUSED(c) 219 Q_UNUSED(c)
220 220
221 if ( 2 == button ) { 221 if ( 2 == button ) {
222 m_mac = item->text(HISVENDOR + 1); 222 m_mac = item->text(HISVENDOR + 1);
223 m_popupHistory->popup(point); 223 m_popupHistory->popup(point);
224 } 224 }
225} 225}
226 226
227void OpieStumbler::slotShowDetails() 227void OpieStumbler::slotShowDetails()
228{ 228{
229 QListIterator<StumblerStation> it(m_stationsHistory); 229 QListIterator<StumblerStation> it(m_stationsHistory);
230 for(; it.current() && it.current()->st->macAddress.toString() != m_mac; ++it ); 230 for(; it.current() && it.current()->st->macAddress.toString() != m_mac; ++it );
231 231
232 if( it.current() ) { 232 if( it.current() ) {
233 StationInfo info(it.current()->st->ssid, it.current()->st->type, QString::number(it.current()->st->channel), 233 StationInfo info(it.current()->st->ssid, it.current()->st->type, QString::number(it.current()->st->channel),
234 QString::number(it.current()->st->rates.last()/1000000), QString::number(it.current()->st->level), 234 QString::number(it.current()->st->rates.last()/1000000), QString::number(it.current()->st->level),
235 it.current()->st->encrypted ? "WEP": "No", 235 it.current()->st->encrypted ? "WEP": "No",
236 it.current()->st->macAddress.toString(), manufacturer(it.current()->st->macAddress.toString(), true), 236 it.current()->st->macAddress.toString(), manufacturer(it.current()->st->macAddress.toString(), true),
237 it.current()->lastTimeSeen.toString() ,this, "", true); 237 it.current()->lastTimeSeen.toString() ,this, "", true);
238 info.exec(); 238 info.exec();
239 } 239 }
240 240
241} 241}
242 242
243void OpieStumbler::slotLoadManufacturers() 243void OpieStumbler::slotLoadManufacturers()
244{ 244{
245 m_db = Opie::Net::OManufacturerDB::instance(); 245 m_db = Opie::Net::OManufacturerDB::instance();
246} 246}
247 247
248QString OpieStumbler::manufacturer( const QString &mac, bool extended ) 248QString OpieStumbler::manufacturer( const QString &mac, bool extended )
249{ 249{
250 QString retval; 250 QString retval;
251 if ( m_db ) 251 if ( m_db )
252 if ( extended ) 252 if ( extended )
253 retval = m_db->lookupExt(mac); 253 retval = m_db->lookupExt(mac);
254 else 254 else
255 retval = m_db->lookup(mac); 255 retval = m_db->lookup(mac);
256 256
257 if ( retval.isEmpty() ) 257 if ( retval.isEmpty() )
258 retval = tr("Unknown"); 258 retval = tr("Unknown");
259 259
260 return retval; 260 return retval;
261} 261}
262 262
263void OpieStumbler::slotJoinNetwork() 263void OpieStumbler::slotJoinNetwork()
264{ 264{
265 slotStopScanning(); 265 slotStopScanning();
266 266
267 OWirelessNetworkInterface *wiface = static_cast<OWirelessNetworkInterface*>(ONetwork::instance()->interface(m_interface)); 267 OWirelessNetworkInterface *wiface = static_cast<OWirelessNetworkInterface*>(ONetwork::instance()->interface(m_interface));
268 268
269 if( !wiface ) 269 if( !wiface )
270 return; 270 return;
271 271
272 QListIterator<StumblerStation> it(m_stationsHistory); 272 QListIterator<StumblerStation> it(m_stationsHistory);
273 273
274 for(; it.current() && it.current()->st->macAddress.toString() != m_mac; ++it ); 274 for(; it.current() && it.current()->st->macAddress.toString() != m_mac; ++it );
275 275
276 if( !it.current() ) 276 if( !it.current() )
277 return; 277 return;
278 278
279 m_ssid = it.current()->st->ssid.left(it.current()->st->ssid.length()-1); 279 m_ssid = it.current()->st->ssid.left(it.current()->st->ssid.length()-1);
280 m_splash = new QFrame( this, "splash", false, WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_Customize ); 280 m_splash = new QFrame( this, "splash", false, WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_Customize );
281 m_splash->setFrameStyle( QFrame::Panel | QFrame::Raised ); 281 m_splash->setFrameStyle( QFrame::Panel | QFrame::Raised );
282 m_splashBox = new QVBoxLayout( m_splash, 4, 4 ); 282 m_splashBox = new QVBoxLayout( m_splash, 4, 4 );
283 m_infoLabel = new QLabel( QString("<center><b>%1 %2</b></center>").arg(tr("Joining Network")).arg(m_ssid), m_splash ); 283 m_infoLabel = new QLabel( QString("<center><b>%1 %2</b></center>").arg(tr("Joining Network")).arg(m_ssid), m_splash );
284 m_pbar = new QProgressBar( 3, m_splash ); 284 m_pbar = new QProgressBar( 3, m_splash );
285 m_pbar->setCenterIndicator(true); 285 m_pbar->setCenterIndicator(true);
286 m_splashBox->addWidget( m_infoLabel ); 286 m_splashBox->addWidget( m_infoLabel );
287 m_splashBox->addWidget( m_pbar ); 287 m_splashBox->addWidget( m_pbar );
288 int sw = m_splashBox->sizeHint().width() * 2; 288 int sw = m_splashBox->sizeHint().width() * 2;
289 int sh = m_splashBox->sizeHint().height(); 289 int sh = m_splashBox->sizeHint().height();
290 m_splash->setGeometry((qApp->desktop()->width() - sw)/2, (qApp->desktop()->height() - sh)/2, sw, sh); 290 m_splash->setGeometry((qApp->desktop()->width() - sw)/2, (qApp->desktop()->height() - sh)/2, sw, sh);
291 m_splash->show(); 291 m_splash->show();
292 m_splash->raise(); 292 m_splash->raise();
293 293
294 Opie::Net::OStation *station = it.current()->st; 294 Opie::Net::OStation *station = it.current()->st;
295 295
296 odebug << "Bringing interface down" << oendl; 296 odebug << "Bringing interface down" << oendl;
297 wiface->setUp(false); 297 wiface->setUp(false);
298 298
299 odebug << "Setting mode to " << (station->type == "adhoc" ? "adhoc" : "managed") << oendl; 299 odebug << "Setting mode to " << (station->type == "adhoc" ? "adhoc" : "managed") << oendl;
300 wiface->setMode(station->type == "adhoc" ? "adhoc" : "managed" ); 300 wiface->setMode(station->type == "adhoc" ? "adhoc" : "managed" );
301 301
302 odebug << "Setting channel to " << station->channel << oendl; 302 odebug << "Setting channel to " << station->channel << oendl;
303 wiface->setChannel(station->channel); 303 wiface->setChannel(station->channel);
304 304
305 odebug << "Setting SSID to " << station->ssid << oendl; 305 odebug << "Setting SSID to " << station->ssid << oendl;
306 wiface->setSSID(station->ssid); 306 wiface->setSSID(station->ssid);
307 307
308 wiface->commit(); 308 wiface->commit();
309 309
310 odebug << "Bringing interface up" << oendl; 310 odebug << "Bringing interface up" << oendl;
311 wiface->setUp(true); 311 wiface->setUp(true);
312 m_pbar->setProgress(1); 312 m_pbar->setProgress(1);
313 //Wait 5 sec for association 313 //Wait 5 sec for association
314 QTimer::singleShot(5000, this, SLOT(slotAssociated())); 314 QTimer::singleShot(5000, this, SLOT(slotAssociated()));
315} 315}
316 316
317void OpieStumbler::slotAssociated() 317void OpieStumbler::slotAssociated()
318{ 318{
319 OWirelessNetworkInterface *wiface = static_cast<OWirelessNetworkInterface*>(ONetwork::instance()->interface(m_interface)); 319 OWirelessNetworkInterface *wiface = static_cast<OWirelessNetworkInterface*>(ONetwork::instance()->interface(m_interface));
320 320
321 if( !wiface ) { 321 if( !wiface ) {
322 slotCleanSplash(); 322 slotCleanSplash();
323 return; 323 return;
324 } 324 }
325 325
326 if (!wiface->isAssociated()) { 326 if (!wiface->isAssociated()) {
327 Global::statusMessage(tr("Could not Join")); 327 Global::statusMessage(tr("Could not Join"));
328 m_infoLabel->setText(tr("Could not Join")); 328 m_infoLabel->setText(tr("Could not Join"));
329 QTimer::singleShot(5000, this, SLOT(slotCleanSplash())); 329 QTimer::singleShot(5000, this, SLOT(slotCleanSplash()));
330 return; 330 return;
331 } 331 }
332 332
333 Global::statusMessage(tr("Joined")); 333 Global::statusMessage(tr("Joined"));
334 m_pbar->setProgress(2); 334 m_pbar->setProgress(2);
335 m_infoLabel->setText(QString("<center><b>%1 %2</b></center>").arg(tr("Joined Network")).arg(m_ssid)); 335 m_infoLabel->setText(QString("<center><b>%1 %2</b></center>").arg(tr("Joined Network")).arg(m_ssid));
336 336
337 if(m_proc) { 337 if(m_proc) {
338 m_proc->kill(); 338 m_proc->kill();
339 delete m_proc; 339 delete m_proc;
340 } 340 }
341 341
342 m_proc = new Opie::Core::OProcess(this); 342 m_proc = new Opie::Core::OProcess(this);
343 343
344 *m_proc << "udhcpc" << "-f" << "-n" << "-i" << m_interface; 344 *m_proc << "udhcpc" << "-f" << "-n" << "-i" << m_interface;
345 m_proc->start(Opie::Core::OProcess::DontCare); 345 if (!m_proc->start(Opie::Core::OProcess::DontCare))
346 owarn << "Execution of udhcpc returned false. Are paths correct?" << oendl;
346 QTimer::singleShot(5000, this, SLOT(slotCheckDHCP())); 347 QTimer::singleShot(5000, this, SLOT(slotCheckDHCP()));
347} 348}
348 349
349void OpieStumbler::slotCheckDHCP() 350void OpieStumbler::slotCheckDHCP()
350{ 351{
351 if(!m_proc->isRunning()) { 352 if(!m_proc->isRunning()) {
352 Global::statusMessage(tr("Could not Obtain an Address")); 353 Global::statusMessage(tr("Could not Obtain an Address"));
353 m_infoLabel->setText(QString("<center><b>%1</b></center>").arg(tr("Could not Obtain an Address"))); 354 m_infoLabel->setText(QString("<center><b>%1</b></center>").arg(tr("Could not Obtain an Address")));
354 delete m_proc; 355 delete m_proc;
355 m_proc = NULL; 356 m_proc = NULL;
356 QTimer::singleShot(5000, this, SLOT(slotCleanSplash())); 357 QTimer::singleShot(5000, this, SLOT(slotCleanSplash()));
357 return; 358 return;
358 } 359 }
359 m_listCurrent->show(); 360 m_listCurrent->show();
360 m_pbar->setProgress(3); 361 m_pbar->setProgress(3);
361 362
362 OWirelessNetworkInterface *wiface = static_cast<OWirelessNetworkInterface*>(ONetwork::instance()->interface(m_interface)); 363 OWirelessNetworkInterface *wiface = static_cast<OWirelessNetworkInterface*>(ONetwork::instance()->interface(m_interface));
363 QString ipv4 = wiface->ipV4Address().toString(); 364 QString ipv4 = wiface->ipV4Address().toString();
364 m_infoLabel->setText(QString("<center><b>%1 %2</b></center>").arg(tr("Obtained IP")).arg(ipv4)); 365 m_infoLabel->setText(QString("<center><b>%1 %2</b></center>").arg(tr("Obtained IP")).arg(ipv4));
365 Global::statusMessage(tr("Obtained IP") + " " + ipv4); 366 Global::statusMessage(tr("Obtained IP") + " " + ipv4);
366 QTimer::singleShot(5000, this, SLOT(slotCleanSplash())); 367 QTimer::singleShot(5000, this, SLOT(slotCleanSplash()));
367 368
368} 369}
369 370
370void OpieStumbler::slotCleanSplash() 371void OpieStumbler::slotCleanSplash()
371{ 372{
372 delete m_pbar; 373 delete m_pbar;
373 m_pbar = 0; 374 m_pbar = 0;
374 375
375 delete m_infoLabel; 376 delete m_infoLabel;
376 m_infoLabel = 0; 377 m_infoLabel = 0;
377 378
378 delete m_splashBox; 379 delete m_splashBox;
379 m_splashBox = 0; 380 m_splashBox = 0;
380 381
381 delete m_splash; 382 delete m_splash;
382 m_splash = 0; 383 m_splash = 0;
383} 384}
384 385
diff --git a/noncore/settings/networksettings/mainwindow/mainwindowimp.cpp b/noncore/settings/networksettings/mainwindow/mainwindowimp.cpp
index 650e634..e81f603 100644
--- a/noncore/settings/networksettings/mainwindow/mainwindowimp.cpp
+++ b/noncore/settings/networksettings/mainwindow/mainwindowimp.cpp
@@ -1,785 +1,788 @@
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 <opie2/odebug.h> 10#include <opie2/odebug.h>
11#include <opie2/oprocess.h> 11#include <opie2/oprocess.h>
12#include <opie2/oresource.h> 12#include <opie2/oresource.h>
13 13
14#include <qpe/applnk.h> 14#include <qpe/applnk.h>
15#include <qpe/qcopenvelope_qws.h> 15#include <qpe/qcopenvelope_qws.h>
16#include <qpe/qpeapplication.h> 16#include <qpe/qpeapplication.h>
17#include <qpe/config.h> 17#include <qpe/config.h>
18#include <qpe/qlibrary.h> 18#include <qpe/qlibrary.h>
19 19
20/* QT */ 20/* QT */
21#include <qpushbutton.h> 21#include <qpushbutton.h>
22#include <qlistbox.h> 22#include <qlistbox.h>
23#include <qlineedit.h> 23#include <qlineedit.h>
24#include <qlistview.h> 24#include <qlistview.h>
25#include <qheader.h> 25#include <qheader.h>
26#include <qlabel.h> 26#include <qlabel.h>
27#include <qtabwidget.h> // in order to disable the profiles tab 27#include <qtabwidget.h> // in order to disable the profiles tab
28#include <qmessagebox.h> 28#include <qmessagebox.h>
29#include <qtextstream.h> 29#include <qtextstream.h>
30#include <qregexp.h> 30#include <qregexp.h>
31 31
32 32
33#if QT_VERSION < 0x030000 33#if QT_VERSION < 0x030000
34#include <qlist.h> 34#include <qlist.h>
35#else 35#else
36#include <qptrlist.h> 36#include <qptrlist.h>
37#endif 37#endif
38#include <qdir.h> 38#include <qdir.h>
39#include <qfile.h> 39#include <qfile.h>
40#include <qtextstream.h> 40#include <qtextstream.h>
41#include <qregexp.h> 41#include <qregexp.h>
42 42
43/* STD */ 43/* STD */
44#include <net/if.h> 44#include <net/if.h>
45#include <sys/ioctl.h> 45#include <sys/ioctl.h>
46#include <sys/socket.h> 46#include <sys/socket.h>
47 47
48#define DEFAULT_SCHEME "/var/lib/pcmcia/scheme" 48#define DEFAULT_SCHEME "/var/lib/pcmcia/scheme"
49#define _PROCNETDEV "/proc/net/dev" 49#define _PROCNETDEV "/proc/net/dev"
50 50
51// is this always right? 51// is this always right?
52#define _HOSTFILE "/etc/hostname" 52#define _HOSTFILE "/etc/hostname"
53#define _IRDANAME "/proc/sys/net/irda/devname" 53#define _IRDANAME "/proc/sys/net/irda/devname"
54 54
55using namespace Opie::Core; 55using namespace Opie::Core;
56 56
57MainWindowImp::MainWindowImp(QWidget *parent, const char *name, WFlags) : MainWindow(parent, name, Qt::WStyle_ContextHelp), advancedUserMode(true), scheme(DEFAULT_SCHEME) 57MainWindowImp::MainWindowImp(QWidget *parent, const char *name, WFlags) : MainWindow(parent, name, Qt::WStyle_ContextHelp), advancedUserMode(true), scheme(DEFAULT_SCHEME)
58{ 58{
59 connect(addConnectionButton, SIGNAL(clicked()), this, SLOT(addClicked())); 59 connect(addConnectionButton, SIGNAL(clicked()), this, SLOT(addClicked()));
60 connect(removeConnectionButton, SIGNAL(clicked()), this, SLOT(removeClicked())); 60 connect(removeConnectionButton, SIGNAL(clicked()), this, SLOT(removeClicked()));
61 connect(informationConnectionButton, SIGNAL(clicked()), this, SLOT(informationClicked())); 61 connect(informationConnectionButton, SIGNAL(clicked()), this, SLOT(informationClicked()));
62 connect(configureConnectionButton, SIGNAL(clicked()), this, SLOT(configureClicked())); 62 connect(configureConnectionButton, SIGNAL(clicked()), this, SLOT(configureClicked()));
63 63
64 //remove tab with no function 64 //remove tab with no function
65 tabWidget->removePage( tab ); 65 tabWidget->removePage( tab );
66 66
67 // Load connections. 67 // Load connections.
68 // /usr/local/kde/lib/libinterfaces.la 68 // /usr/local/kde/lib/libinterfaces.la
69 loadModules(QPEApplication::qpeDir() + "plugins/networksettings"); 69 loadModules(QPEApplication::qpeDir() + "plugins/networksettings");
70 getAllInterfaces(); 70 getAllInterfaces();
71 71
72 Interfaces i; 72 Interfaces i;
73 QStringList list = i.getInterfaceList(); 73 QStringList list = i.getInterfaceList();
74 QMap<QString, Interface*>::Iterator it; 74 QMap<QString, Interface*>::Iterator it;
75 for ( QStringList::Iterator ni = list.begin(); ni != list.end(); ++ni ) 75 for ( QStringList::Iterator ni = list.begin(); ni != list.end(); ++ni )
76 { 76 {
77 /* 77 /*
78 * we skipped it in getAllInterfaces now 78 * we skipped it in getAllInterfaces now
79 * we need to ignore it as well 79 * we need to ignore it as well
80 */ 80 */
81 if (m_handledIfaces.contains( *ni) ) 81 if (m_handledIfaces.contains( *ni) )
82 { 82 {
83 odebug << "Not up iface handled by module" << oendl; 83 odebug << "Not up iface handled by module" << oendl;
84 continue; 84 continue;
85 } 85 }
86 bool found = false; 86 bool found = false;
87 for( it = interfaceNames.begin(); it != interfaceNames.end(); ++it ) 87 for( it = interfaceNames.begin(); it != interfaceNames.end(); ++it )
88 { 88 {
89 if(it.key() == (*ni)) 89 if(it.key() == (*ni))
90 found = true; 90 found = true;
91 } 91 }
92 if(!found) 92 if(!found)
93 { 93 {
94 if(!(*ni).contains("_")) 94 if(!(*ni).contains("_"))
95 { 95 {
96 Interface *i = new Interface(this, *ni, false); 96 Interface *i = new Interface(this, *ni, false);
97 i->setAttached(false); 97 i->setAttached(false);
98 i->setHardwareName(tr("Disconnected")); 98 i->setHardwareName(tr("Disconnected"));
99 interfaceNames.insert(i->getInterfaceName(), i); 99 interfaceNames.insert(i->getInterfaceName(), i);
100 updateInterface(i); 100 updateInterface(i);
101 connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*))); 101 connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*)));
102 } 102 }
103 } 103 }
104 } 104 }
105 105
106 //getInterfaceList(); 106 //getInterfaceList();
107 connectionList->header()->hide(); 107 connectionList->header()->hide();
108 108
109 Config cfg("NetworkSetup"); 109 Config cfg("NetworkSetup");
110 profiles = QStringList::split(" ", cfg.readEntry("Profiles", "All")); 110 profiles = QStringList::split(" ", cfg.readEntry("Profiles", "All"));
111 for ( QStringList::Iterator it = profiles.begin(); 111 for ( QStringList::Iterator it = profiles.begin();
112 it != profiles.end(); ++it) 112 it != profiles.end(); ++it)
113 profilesList->insertItem((*it)); 113 profilesList->insertItem((*it));
114 currentProfileLabel->setText(cfg.readEntry("CurrentProfile", "All")); 114 currentProfileLabel->setText(cfg.readEntry("CurrentProfile", "All"));
115 advancedUserMode = cfg.readBoolEntry("AdvancedUserMode", false); 115 advancedUserMode = cfg.readBoolEntry("AdvancedUserMode", false);
116 scheme = cfg.readEntry("SchemeFile", DEFAULT_SCHEME); 116 scheme = cfg.readEntry("SchemeFile", DEFAULT_SCHEME);
117 117
118 QFile file(scheme); 118 QFile file(scheme);
119 if ( file.open(IO_ReadOnly) ) 119 if ( file.open(IO_ReadOnly) )
120 { // file opened successfully 120 { // file opened successfully
121 QTextStream stream( &file ); // use a text stream 121 QTextStream stream( &file ); // use a text stream
122 while ( !stream.eof() ) 122 while ( !stream.eof() )
123 { // until end of file... 123 { // until end of file...
124 QString line = stream.readLine(); // line of text excluding '\n' 124 QString line = stream.readLine(); // line of text excluding '\n'
125 if(line.contains("SCHEME")) 125 if(line.contains("SCHEME"))
126 { 126 {
127 line = line.mid(7, line.length()); 127 line = line.mid(7, line.length());
128 currentProfileLabel->setText(line); 128 currentProfileLabel->setText(line);
129 break; 129 break;
130 } 130 }
131 } 131 }
132 file.close(); 132 file.close();
133 } 133 }
134 makeChannel(); 134 makeChannel();
135 initHostname(); 135 initHostname();
136} 136}
137 137
138/** 138/**
139 * Deconstructor. Save profiles. Delete loaded libraries. 139 * Deconstructor. Save profiles. Delete loaded libraries.
140 */ 140 */
141MainWindowImp::~MainWindowImp() 141MainWindowImp::~MainWindowImp()
142{ 142{
143 // Save profiles. 143 // Save profiles.
144 Config cfg("NetworkSetup"); 144 Config cfg("NetworkSetup");
145 cfg.setGroup("General"); 145 cfg.setGroup("General");
146 cfg.writeEntry("Profiles", profiles.join(" ")); 146 cfg.writeEntry("Profiles", profiles.join(" "));
147 147
148 // Delete all interfaces that don't have owners. 148 // Delete all interfaces that don't have owners.
149 QMap<Interface*, QListViewItem*>::Iterator iIt; 149 QMap<Interface*, QListViewItem*>::Iterator iIt;
150 for( iIt = items.begin(); iIt != items.end(); ++iIt ) 150 for( iIt = items.begin(); iIt != items.end(); ++iIt )
151 { 151 {
152 if(iIt.key()->getModuleOwner() == NULL) 152 if(iIt.key()->getModuleOwner() == NULL)
153 delete iIt.key(); 153 delete iIt.key();
154 } 154 }
155 155
156 // Delete Modules and Libraries 156 // Delete Modules and Libraries
157 QMap<Module*, QLibrary*>::Iterator it; 157 QMap<Module*, QLibrary*>::Iterator it;
158 for( it = libraries.begin(); it != libraries.end(); ++it ) 158 for( it = libraries.begin(); it != libraries.end(); ++it )
159 { 159 {
160 delete it.key(); 160 delete it.key();
161 // I wonder why I can't delete the libraries 161 // I wonder why I can't delete the libraries
162 // What fucking shit this is. 162 // What fucking shit this is.
163 //delete it.data(); 163 //delete it.data();
164 } 164 }
165} 165}
166 166
167/** 167/**
168 * Query the kernel for all of the interfaces. 168 * Query the kernel for all of the interfaces.
169 */ 169 */
170void MainWindowImp::getAllInterfaces() 170void MainWindowImp::getAllInterfaces()
171{ 171{
172 int sockfd = socket(PF_INET, SOCK_DGRAM, 0); 172 int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
173 if(sockfd == -1) 173 if(sockfd == -1)
174 return; 174 return;
175 175
176 struct ifreq ifr; 176 struct ifreq ifr;
177 QStringList ifaces; 177 QStringList ifaces;
178 QFile procFile(QString(_PROCNETDEV)); 178 QFile procFile(QString(_PROCNETDEV));
179 int result; 179 int result;
180 Interface *i; 180 Interface *i;
181 181
182 if (! procFile.exists()) 182 if (! procFile.exists())
183 { 183 {
184 struct ifreq ifrs[100]; 184 struct ifreq ifrs[100];
185 struct ifconf ifc; 185 struct ifconf ifc;
186 ifc.ifc_len = sizeof(ifrs); 186 ifc.ifc_len = sizeof(ifrs);
187 ifc.ifc_req = ifrs; 187 ifc.ifc_req = ifrs;
188 result = ioctl(sockfd, SIOCGIFCONF, &ifc); 188 result = ioctl(sockfd, SIOCGIFCONF, &ifc);
189 189
190 for (unsigned int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++) 190 for (unsigned int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++)
191 { 191 {
192 struct ifreq *pifr = &ifrs[i]; 192 struct ifreq *pifr = &ifrs[i];
193 if ( !QString( pifr->ifr_name ).startsWith( "wifi" ) ) ifaces += pifr->ifr_name; 193 if ( !QString( pifr->ifr_name ).startsWith( "wifi" ) ) ifaces += pifr->ifr_name;
194 else odebug << "ignoring hostap control interface " << pifr->ifr_name << oendl; 194 else odebug << "ignoring hostap control interface " << pifr->ifr_name << oendl;
195 } 195 }
196 } 196 }
197 else 197 else
198 { 198 {
199 procFile.open(IO_ReadOnly); 199 if (!procFile.open(IO_ReadOnly))
200 owarn << "Failed to open proc file " << procFile.name() << oendl;
200 QString line; 201 QString line;
201 QTextStream procTs(&procFile); 202 QTextStream procTs(&procFile);
202 int loc = -1; 203 int loc = -1;
203 204
204 procTs.readLine(); // eat a line 205 procTs.readLine(); // eat a line
205 procTs.readLine(); // eat a line 206 procTs.readLine(); // eat a line
206 while((line = procTs.readLine().simplifyWhiteSpace()) != QString::null) 207 while((line = procTs.readLine().simplifyWhiteSpace()) != QString::null)
207 { 208 {
208 if((loc = line.find(":")) != -1) 209 if((loc = line.find(":")) != -1)
209 { 210 {
210 // ignore wifi* (hostap control interfaces) 211 // ignore wifi* (hostap control interfaces)
211 if ( !line.left(loc).startsWith( "wifi" ) ) ifaces += line.left(loc); 212 if ( !line.left(loc).startsWith( "wifi" ) ) ifaces += line.left(loc);
212 else odebug << "ignoring hostap control interface " << line.left(loc) << oendl; 213 else odebug << "ignoring hostap control interface " << line.left(loc) << oendl;
213 } 214 }
214 } 215 }
215 } 216 }
216 217
217 for (QStringList::Iterator it = ifaces.begin(); it != ifaces.end(); ++it) 218 for (QStringList::Iterator it = ifaces.begin(); it != ifaces.end(); ++it)
218 { 219 {
219 int flags = 0; 220 int flags = 0;
220 if ( m_handledIfaces.contains( (*it) ) ) 221 if ( m_handledIfaces.contains( (*it) ) )
221 { 222 {
222 odebug << " " << (*it).latin1() << " is handled by a module" << oendl; 223 odebug << " " << (*it).latin1() << " is handled by a module" << oendl;
223 continue; 224 continue;
224 } 225 }
225 // int family; 226 // int family;
226 i = NULL; 227 i = NULL;
227 228
228 strcpy(ifr.ifr_name, (*it).latin1()); 229 strcpy(ifr.ifr_name, (*it).latin1());
229 230
230 struct ifreq ifcopy; 231 struct ifreq ifcopy;
231 ifcopy = ifr; 232 ifcopy = ifr;
232 result = ioctl(sockfd, SIOCGIFFLAGS, &ifcopy); 233 result = ioctl(sockfd, SIOCGIFFLAGS, &ifcopy);
233 flags = ifcopy.ifr_flags; 234 flags = ifcopy.ifr_flags;
234 i = new Interface(this, ifr.ifr_name, false); 235 i = new Interface(this, ifr.ifr_name, false);
235 i->setAttached(true); 236 i->setAttached(true);
236 if ((flags & IFF_UP) == IFF_UP) 237 if ((flags & IFF_UP) == IFF_UP)
237 i->setStatus(true); 238 i->setStatus(true);
238 else 239 else
239 i->setStatus(false); 240 i->setStatus(false);
240 241
241 if ((flags & IFF_BROADCAST) == IFF_BROADCAST) 242 if ((flags & IFF_BROADCAST) == IFF_BROADCAST)
242 i->setHardwareName("Ethernet"); 243 i->setHardwareName("Ethernet");
243 else if ((flags & IFF_POINTOPOINT) == IFF_POINTOPOINT) 244 else if ((flags & IFF_POINTOPOINT) == IFF_POINTOPOINT)
244 i->setHardwareName("Point to Point"); 245 i->setHardwareName("Point to Point");
245 else if ((flags & IFF_MULTICAST) == IFF_MULTICAST) 246 else if ((flags & IFF_MULTICAST) == IFF_MULTICAST)
246 i->setHardwareName("Multicast"); 247 i->setHardwareName("Multicast");
247 else if ((flags & IFF_LOOPBACK) == IFF_LOOPBACK) 248 else if ((flags & IFF_LOOPBACK) == IFF_LOOPBACK)
248 i->setHardwareName("Loopback"); 249 i->setHardwareName("Loopback");
249 else 250 else
250 i->setHardwareName("Unknown"); 251 i->setHardwareName("Unknown");
251 252
252 owarn << "Adding interface " << ifr.ifr_name << " to interfaceNames\n" << oendl; 253 owarn << "Adding interface " << ifr.ifr_name << " to interfaceNames\n" << oendl;
253 interfaceNames.insert(i->getInterfaceName(), i); 254 interfaceNames.insert(i->getInterfaceName(), i);
254 updateInterface(i); 255 updateInterface(i);
255 connect(i, SIGNAL(updateInterface(Interface*)), 256 connect(i, SIGNAL(updateInterface(Interface*)),
256 this, SLOT(updateInterface(Interface*))); 257 this, SLOT(updateInterface(Interface*)));
257 } 258 }
258 // now lets ask the plugins too ;) 259 // now lets ask the plugins too ;)
259 QMap<Module*, QLibrary*>::Iterator it; 260 QMap<Module*, QLibrary*>::Iterator it;
260 QList<Interface> ilist; 261 QList<Interface> ilist;
261 for( it = libraries.begin(); it != libraries.end(); ++it ) 262 for( it = libraries.begin(); it != libraries.end(); ++it )
262 { 263 {
263 if(it.key()) 264 if(it.key())
264 { 265 {
265 ilist = it.key()->getInterfaces(); 266 ilist = it.key()->getInterfaces();
266 for( i = ilist.first(); i != 0; i = ilist.next() ) 267 for( i = ilist.first(); i != 0; i = ilist.next() )
267 { 268 {
268 owarn << "Adding interface " << i->getInterfaceName().latin1() << " to interfaceNames\n" << oendl; 269 owarn << "Adding interface " << i->getInterfaceName().latin1() << " to interfaceNames\n" << oendl;
269 interfaceNames.insert(i->getInterfaceName(), i); 270 interfaceNames.insert(i->getInterfaceName(), i);
270 updateInterface(i); 271 updateInterface(i);
271 connect(i, SIGNAL(updateInterface(Interface*)), 272 connect(i, SIGNAL(updateInterface(Interface*)),
272 this, SLOT(updateInterface(Interface*))); 273 this, SLOT(updateInterface(Interface*)));
273 } 274 }
274 } 275 }
275 } 276 }
276} 277}
277 278
278/** 279/**
279 * Load all modules that are found in the path 280 * Load all modules that are found in the path
280 * @param path a directory that is scaned for any plugins that can be loaded 281 * @param path a directory that is scaned for any plugins that can be loaded
281 * and attempts to load them 282 * and attempts to load them
282 */ 283 */
283void MainWindowImp::loadModules(const QString &path) 284void MainWindowImp::loadModules(const QString &path)
284{ 285{
285#ifdef DEBUG 286#ifdef DEBUG
286 odebug << "MainWindowImp::loadModules: " << path.latin1() << "" << oendl; 287 odebug << "MainWindowImp::loadModules: " << path.latin1() << "" << oendl;
287#endif 288#endif
288 QDir d(path); 289 QDir d(path);
289 if(!d.exists()) 290 if(!d.exists())
290 return; 291 return;
291 292
292 QString lang = ::getenv("LANG"); 293 QString lang = ::getenv("LANG");
293 // Don't want sym links 294 // Don't want sym links
294 d.setFilter( QDir::Files | QDir::NoSymLinks ); 295 d.setFilter( QDir::Files | QDir::NoSymLinks );
295 const QFileInfoList *list = d.entryInfoList(); 296 const QFileInfoList *list = d.entryInfoList();
296 QFileInfoListIterator it( *list ); 297 QFileInfoListIterator it( *list );
297 QFileInfo *fi; 298 QFileInfo *fi;
298 while ( (fi=it.current()) ) 299 while ( (fi=it.current()) )
299 { 300 {
300 if(fi->fileName().contains(".so")) 301 if(fi->fileName().contains(".so"))
301 { 302 {
302 /* if loaded install translation */ 303 /* if loaded install translation */
303 if( loadPlugin(path + "/" + fi->fileName()) != 0l ){ 304 if( loadPlugin(path + "/" + fi->fileName()) != 0l ){
304 QTranslator *trans = new QTranslator(qApp); 305 QTranslator *trans = new QTranslator(qApp);
305 QString fn = QPEApplication::qpeDir()+"i18n/"+lang+"/"+ fi->fileName().left( fi->fileName().find(".") )+".qm"; 306 QString fn = QPEApplication::qpeDir()+"i18n/"+lang+"/"+ fi->fileName().left( fi->fileName().find(".") )+".qm";
306 if( trans->load( fn ) ) 307 if( trans->load( fn ) )
307 qApp->installTranslator( trans ); 308 qApp->installTranslator( trans );
308 else 309 else
309 delete trans; 310 delete trans;
310 } 311 }
311 odebug << "loaded plugin: >" << QString(path + "/" + fi->fileName()).latin1() << "< " << oendl; 312 odebug << "loaded plugin: >" << QString(path + "/" + fi->fileName()).latin1() << "< " << oendl;
312 } 313 }
313 ++it; 314 ++it;
314 } 315 }
315} 316}
316 317
317/** 318/**
318 * Attempt to load a function and resolve a function. 319 * Attempt to load a function and resolve a function.
319 * @param pluginFileName - the name of the file in which to attempt to load 320 * @param pluginFileName - the name of the file in which to attempt to load
320 * @param resolveString - function pointer to resolve 321 * @param resolveString - function pointer to resolve
321 * @return pointer to the function with name resolveString or NULL 322 * @return pointer to the function with name resolveString or NULL
322 */ 323 */
323Module* MainWindowImp::loadPlugin(const QString &pluginFileName, const QString &resolveString) 324Module* MainWindowImp::loadPlugin(const QString &pluginFileName, const QString &resolveString)
324{ 325{
325#ifdef DEBUG 326#ifdef DEBUG
326 odebug << "MainWindowImp::loadPlugin: " << pluginFileName.latin1() << ": resolving " << resolveString.latin1() << "" << oendl; 327 odebug << "MainWindowImp::loadPlugin: " << pluginFileName.latin1() << ": resolving " << resolveString.latin1() << "" << oendl;
327#endif 328#endif
328 QLibrary *lib = new QLibrary(pluginFileName); 329 QLibrary *lib = new QLibrary(pluginFileName);
329 void *functionPointer = lib->resolve(resolveString); 330 void *functionPointer = lib->resolve(resolveString);
330 if( !functionPointer ) 331 if( !functionPointer )
331 { 332 {
332#ifdef DEBUG 333#ifdef DEBUG
333 odebug << "MainWindowImp::loadPlugin: Warning: " << pluginFileName.latin1() << " is not a plugin" << oendl; 334 odebug << "MainWindowImp::loadPlugin: Warning: " << pluginFileName.latin1() << " is not a plugin" << oendl;
334#endif 335#endif
335 delete lib; 336 delete lib;
336 return 0; 337 return 0;
337 } 338 }
338 // Try to get an object. 339 // Try to get an object.
339 Module *object = ((Module* (*)()) functionPointer)(); 340 Module *object = ((Module* (*)()) functionPointer)();
340 if(object == 0) 341 if(object == 0)
341 { 342 {
342#ifdef DEBUG 343#ifdef DEBUG
343 odebug << "MainWindowImp: Couldn't create object, but did load library!" << oendl; 344 odebug << "MainWindowImp: Couldn't create object, but did load library!" << oendl;
344#endif 345#endif
345 delete lib; 346 delete lib;
346 return 0; 347 return 0;
347 } 348 }
348 349
349 m_handledIfaces += object->handledInterfaceNames(); 350 m_handledIfaces += object->handledInterfaceNames();
350 // Store for deletion later 351 // Store for deletion later
351 libraries.insert(object, lib); 352 libraries.insert(object, lib);
352 return object; 353 return object;
353} 354}
354 355
355/** 356/**
356 * The Add button was clicked. Bring up the add dialog and if OK is hit 357 * The Add button was clicked. Bring up the add dialog and if OK is hit
357 * load the plugin and append it to the list 358 * load the plugin and append it to the list
358 */ 359 */
359void MainWindowImp::addClicked() 360void MainWindowImp::addClicked()
360{ 361{
361 QMap<Module*, QLibrary*>::Iterator it; 362 QMap<Module*, QLibrary*>::Iterator it;
362 QMap<QString, QString> list; 363 QMap<QString, QString> list;
363 QMap<QString, Module*> newInterfaceOwners; 364 QMap<QString, Module*> newInterfaceOwners;
364 365
365 for( it = libraries.begin(); it != libraries.end(); ++it ) 366 for( it = libraries.begin(); it != libraries.end(); ++it )
366 { 367 {
367 if(it.key()) 368 if(it.key())
368 { 369 {
369 (it.key())->possibleNewInterfaces(list); 370 (it.key())->possibleNewInterfaces(list);
370 } 371 }
371 } 372 }
372 // See if the list has anything that we can add. 373 // See if the list has anything that we can add.
373 if(list.count() == 0) 374 if(list.count() == 0)
374 { 375 {
375 QMessageBox::information(this, "Sorry", "Nothing to add.", QMessageBox::Ok); 376 QMessageBox::information(this, "Sorry", "Nothing to add.", QMessageBox::Ok);
376 return; 377 return;
377 } 378 }
378 AddConnectionImp addNewConnection(this, "AddConnectionImp", true); 379 AddConnectionImp addNewConnection(this, "AddConnectionImp", true);
379 addNewConnection.addConnections(list); 380 addNewConnection.addConnections(list);
380 if( QDialog::Accepted == QPEApplication::execDialog( &addNewConnection ) ) 381 if( QDialog::Accepted == QPEApplication::execDialog( &addNewConnection ) )
381 { 382 {
382 QListViewItem *item = addNewConnection.registeredServicesList->currentItem(); 383 QListViewItem *item = addNewConnection.registeredServicesList->currentItem();
383 if(!item) 384 if(!item)
384 return; 385 return;
385 386
386 for( it = libraries.begin(); it != libraries.end(); ++it ) 387 for( it = libraries.begin(); it != libraries.end(); ++it )
387 { 388 {
388 if(it.key()) 389 if(it.key())
389 { 390 {
390 Interface *i = (it.key())->addNewInterface(item->text(0)); 391 Interface *i = (it.key())->addNewInterface(item->text(0));
391 if(i) 392 if(i)
392 { 393 {
393 odebug << "iface name " << i->getInterfaceName().latin1() << "" << oendl; 394 odebug << "iface name " << i->getInterfaceName().latin1() << "" << oendl;
394 interfaceNames.insert(i->getInterfaceName(), i); 395 interfaceNames.insert(i->getInterfaceName(), i);
395 updateInterface(i); 396 updateInterface(i);
396 } 397 }
397 } 398 }
398 } 399 }
399 } 400 }
400} 401}
401 402
402/** 403/**
403 * Prompt the user to see if they really want to do this. 404 * Prompt the user to see if they really want to do this.
404 * If they do then remove from the list and unload. 405 * If they do then remove from the list and unload.
405 */ 406 */
406void MainWindowImp::removeClicked() 407void MainWindowImp::removeClicked()
407{ 408{
408 QListViewItem *item = connectionList->currentItem(); 409 QListViewItem *item = connectionList->currentItem();
409 if(!item) 410 if(!item)
410 { 411 {
411 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok); 412 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok);
412 return; 413 return;
413 } 414 }
414 415
415 Interface *i = interfaceItems[item]; 416 Interface *i = interfaceItems[item];
416 if(i->getModuleOwner() == NULL) 417 if(i->getModuleOwner() == NULL)
417 { 418 {
418 QMessageBox::information(this, "Can't remove interface.", "Interface is built in.", QMessageBox::Ok); 419 QMessageBox::information(this, "Can't remove interface.", "Interface is built in.", QMessageBox::Ok);
419 } 420 }
420 else 421 else
421 { 422 {
422 if(!i->getModuleOwner()->remove(i)) 423 if(!i->getModuleOwner()->remove(i))
423 QMessageBox::information(this, tr("Error"), tr("Unable to remove."), QMessageBox::Ok); 424 QMessageBox::information(this, tr("Error"), tr("Unable to remove."), QMessageBox::Ok);
424 else 425 else
425 { 426 {
426 delete item; 427 delete item;
427 // QMessageBox::information(this, "Success", "Interface was removed.", QMessageBox::Ok); 428 // QMessageBox::information(this, "Success", "Interface was removed.", QMessageBox::Ok);
428 } 429 }
429 } 430 }
430} 431}
431 432
432/** 433/**
433 * Pull up the configure about the currently selected interface. 434 * Pull up the configure about the currently selected interface.
434 * Report an error if no interface is selected. 435 * Report an error if no interface is selected.
435 * If the interface has a module owner then request its configure. 436 * If the interface has a module owner then request its configure.
436 */ 437 */
437void MainWindowImp::configureClicked() 438void MainWindowImp::configureClicked()
438{ 439{
439 QListViewItem *item = connectionList->currentItem(); 440 QListViewItem *item = connectionList->currentItem();
440 if(!item) 441 if(!item)
441 { 442 {
442 QMessageBox::information(this, tr("Sorry"),tr("Please select an interface first."), QMessageBox::Ok); 443 QMessageBox::information(this, tr("Sorry"),tr("Please select an interface first."), QMessageBox::Ok);
443 return; 444 return;
444 } 445 }
445 446
446 QString currentProfileText = currentProfileLabel->text(); 447 QString currentProfileText = currentProfileLabel->text();
447 if(currentProfileText.upper() == "ALL"); 448 if(currentProfileText.upper() == "ALL");
448 currentProfileText = ""; 449 currentProfileText = "";
449 450
450 Interface *i = interfaceItems[item]; 451 Interface *i = interfaceItems[item];
451 452
452 if(i->getModuleOwner()) 453 if(i->getModuleOwner())
453 { 454 {
454 QWidget *moduleConfigure = i->getModuleOwner()->configure(i); 455 QWidget *moduleConfigure = i->getModuleOwner()->configure(i);
455 if(moduleConfigure != NULL) 456 if(moduleConfigure != NULL)
456 { 457 {
457 i->getModuleOwner()->setProfile(currentProfileText); 458 i->getModuleOwner()->setProfile(currentProfileText);
458 QPEApplication::showWidget( moduleConfigure ); 459 QPEApplication::showWidget( moduleConfigure );
459 return; 460 return;
460 } 461 }
461 } 462 }
462 463
463 InterfaceSetupImpDialog *configure = new InterfaceSetupImpDialog(this, "InterfaceSetupImp", i, true, Qt::WDestructiveClose | Qt::WStyle_ContextHelp ); 464 InterfaceSetupImpDialog *configure = new InterfaceSetupImpDialog(this, "InterfaceSetupImp", i, true, Qt::WDestructiveClose | Qt::WStyle_ContextHelp );
464 configure->setProfile(currentProfileText); 465 configure->setProfile(currentProfileText);
465 QPEApplication::showDialog( configure ); 466 QPEApplication::showDialog( configure );
466} 467}
467 468
468/** 469/**
469 * Pull up the information about the currently selected interface. 470 * Pull up the information about the currently selected interface.
470 * Report an error if no interface is selected. 471 * Report an error if no interface is selected.
471 * If the interface has a module owner then request its configure. 472 * If the interface has a module owner then request its configure.
472 */ 473 */
473void MainWindowImp::informationClicked() 474void MainWindowImp::informationClicked()
474{ 475{
475 QListViewItem *item = connectionList->currentItem(); 476 QListViewItem *item = connectionList->currentItem();
476 if(!item) 477 if(!item)
477 { 478 {
478 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok); 479 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok);
479 return; 480 return;
480 } 481 }
481 482
482 Interface *i = interfaceItems[item]; 483 Interface *i = interfaceItems[item];
483 // if(!i->isAttached()){ 484 // if(!i->isAttached()){
484 // QMessageBox::information(this, "Sorry","No information about\na disconnected interface.", QMessageBox::Ok); 485 // QMessageBox::information(this, "Sorry","No information about\na disconnected interface.", QMessageBox::Ok);
485 // return; 486 // return;
486 // } 487 // }
487 488
488 if(i->getModuleOwner()) 489 if(i->getModuleOwner())
489 { 490 {
490 QWidget *moduleInformation = i->getModuleOwner()->information(i); 491 QWidget *moduleInformation = i->getModuleOwner()->information(i);
491 if(moduleInformation != NULL) 492 if(moduleInformation != NULL)
492 { 493 {
493 QPEApplication::showWidget( moduleInformation ); 494 QPEApplication::showWidget( moduleInformation );
494#ifdef DEBUG 495#ifdef DEBUG
495 odebug << "MainWindowImp::informationClicked:: Module owner has created, we showed." << oendl; 496 odebug << "MainWindowImp::informationClicked:: Module owner has created, we showed." << oendl;
496#endif 497#endif
497 return; 498 return;
498 } 499 }
499 } 500 }
500 InterfaceInformationImp *information = new InterfaceInformationImp(this, "InterfaceSetupImp", i, Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog | Qt::WStyle_ContextHelp); 501 InterfaceInformationImp *information = new InterfaceInformationImp(this, "InterfaceSetupImp", i, Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog | Qt::WStyle_ContextHelp);
501 QPEApplication::showWidget( information ); 502 QPEApplication::showWidget( information );
502} 503}
503 504
504/** 505/**
505 * Update this interface. If no QListViewItem exists create one. 506 * Update this interface. If no QListViewItem exists create one.
506 * @param Interface* pointer to the interface that needs to be updated. 507 * @param Interface* pointer to the interface that needs to be updated.
507 */ 508 */
508void MainWindowImp::updateInterface(Interface *i) 509void MainWindowImp::updateInterface(Interface *i)
509{ 510{
510 if(!advancedUserMode) 511 if(!advancedUserMode)
511 { 512 {
512 if(i->getInterfaceName() == "lo") 513 if(i->getInterfaceName() == "lo")
513 return; 514 return;
514 } 515 }
515 516
516 QListViewItem *item = NULL; 517 QListViewItem *item = NULL;
517 518
518 // Find the interface, making it if needed. 519 // Find the interface, making it if needed.
519 if(items.find(i) == items.end()) 520 if(items.find(i) == items.end())
520 { 521 {
521 item = new QListViewItem(connectionList, "", "", ""); 522 item = new QListViewItem(connectionList, "", "", "");
522 // See if you can't find a module owner for this interface 523 // See if you can't find a module owner for this interface
523 QMap<Module*, QLibrary*>::Iterator it; 524 QMap<Module*, QLibrary*>::Iterator it;
524 for( it = libraries.begin(); it != libraries.end(); ++it ) 525 for( it = libraries.begin(); it != libraries.end(); ++it )
525 { 526 {
526 if(it.key()->isOwner(i)) 527 if(it.key()->isOwner(i))
527 i->setModuleOwner(it.key()); 528 i->setModuleOwner(it.key());
528 } 529 }
529 items.insert(i, item); 530 items.insert(i, item);
530 interfaceItems.insert(item, i); 531 interfaceItems.insert(item, i);
531 } 532 }
532 else 533 else
533 item = items[i]; 534 item = items[i];
534 535
535 // Update the icons and information 536 // Update the icons and information
536 item->setPixmap( 0, Opie::Core::OResource::loadPixmap( i->getStatus() ? "up" : "down", Opie::Core::OResource::SmallIcon ) ); 537 item->setPixmap( 0, Opie::Core::OResource::loadPixmap( i->getStatus() ? "up" : "down", Opie::Core::OResource::SmallIcon ) );
537 538
538 QString typeName = "lan"; 539 QString typeName = "lan";
539 if(i->getInterfaceName() == "lo") 540 if(i->getInterfaceName() == "lo")
540 typeName = "lo"; 541 typeName = "lo";
541 if(i->getInterfaceName().contains("irda")) 542 if(i->getInterfaceName().contains("irda"))
542 typeName = "irda"; 543 typeName = "irda";
543 if(i->getInterfaceName().contains("wlan")) 544 if(i->getInterfaceName().contains("wlan"))
544 typeName = "wlan"; 545 typeName = "wlan";
545 if(i->getInterfaceName().contains("usb")) 546 if(i->getInterfaceName().contains("usb"))
546 typeName = "usb"; 547 typeName = "usb";
547 548
548 if(!i->isAttached()) 549 if(!i->isAttached())
549 typeName = "connect_no"; 550 typeName = "connect_no";
550 // Actually try to use the Module 551 // Actually try to use the Module
551 if(i->getModuleOwner() != NULL) 552 if(i->getModuleOwner() != NULL)
552 typeName = i->getModuleOwner()->getPixmapName(i); 553 typeName = i->getModuleOwner()->getPixmapName(i);
553 554
554 item->setPixmap( 1, ( Opie::Core::OResource::loadPixmap( "networksettings/" + typeName, Opie::Core::OResource::SmallIcon ) ) ); 555 item->setPixmap( 1, ( Opie::Core::OResource::loadPixmap( "networksettings/" + typeName, Opie::Core::OResource::SmallIcon ) ) );
555 556
556 item->setText(2, i->getHardwareName()); 557 item->setText(2, i->getHardwareName());
557 item->setText(3, QString("(%1)").arg(i->getInterfaceName())); 558 item->setText(3, QString("(%1)").arg(i->getInterfaceName()));
558 item->setText(4, (i->getStatus()) ? i->getIp() : QString("")); 559 item->setText(4, (i->getStatus()) ? i->getIp() : QString(""));
559} 560}
560 561
561void MainWindowImp::newProfileChanged(const QString& newText) 562void MainWindowImp::newProfileChanged(const QString& newText)
562{ 563{
563 if(newText.length() > 0) 564 if(newText.length() > 0)
564 newProfileButton->setEnabled(true); 565 newProfileButton->setEnabled(true);
565 else 566 else
566 newProfileButton->setEnabled(false); 567 newProfileButton->setEnabled(false);
567} 568}
568 569
569/** 570/**
570 * Adds a new profile to the list of profiles. 571 * Adds a new profile to the list of profiles.
571 * Don't add profiles that already exists. 572 * Don't add profiles that already exists.
572 * Appends to the list and QStringList 573 * Appends to the list and QStringList
573 */ 574 */
574void MainWindowImp::addProfile() 575void MainWindowImp::addProfile()
575{ 576{
576 QString newProfileName = newProfile->text(); 577 QString newProfileName = newProfile->text();
577 if(profiles.grep(newProfileName).count() > 0) 578 if(profiles.grep(newProfileName).count() > 0)
578 { 579 {
579 QMessageBox::information(this, "Can't Add","Profile already exists.", QMessageBox::Ok); 580 QMessageBox::information(this, "Can't Add","Profile already exists.", QMessageBox::Ok);
580 return; 581 return;
581 } 582 }
582 profiles.append(newProfileName); 583 profiles.append(newProfileName);
583 profilesList->insertItem(newProfileName); 584 profilesList->insertItem(newProfileName);
584} 585}
585 586
586/** 587/**
587 * Removes the currently selected profile in the combo. 588 * Removes the currently selected profile in the combo.
588 * Doesn't delete if there are less then 2 profiles. 589 * Doesn't delete if there are less then 2 profiles.
589 */ 590 */
590void MainWindowImp::removeProfile() 591void MainWindowImp::removeProfile()
591{ 592{
592 if(profilesList->count() <= 1) 593 if(profilesList->count() <= 1)
593 { 594 {
594 QMessageBox::information(this, "Can't remove.","At least one profile\nis needed.", QMessageBox::Ok); 595 QMessageBox::information(this, "Can't remove.","At least one profile\nis needed.", QMessageBox::Ok);
595 return; 596 return;
596 } 597 }
597 QString profileToRemove = profilesList->currentText(); 598 QString profileToRemove = profilesList->currentText();
598 if(profileToRemove == "All") 599 if(profileToRemove == "All")
599 { 600 {
600 QMessageBox::information(this, "Can't remove.","Can't remove default.", QMessageBox::Ok); 601 QMessageBox::information(this, "Can't remove.","Can't remove default.", QMessageBox::Ok);
601 return; 602 return;
602 } 603 }
603 // Can't remove the curent profile 604 // Can't remove the curent profile
604 if(profileToRemove == currentProfileLabel->text()) 605 if(profileToRemove == currentProfileLabel->text())
605 { 606 {
606 QMessageBox::information(this, "Can't remove.",QString("%1 is the current profile.").arg(profileToRemove), QMessageBox::Ok); 607 QMessageBox::information(this, "Can't remove.",QString("%1 is the current profile.").arg(profileToRemove), QMessageBox::Ok);
607 return; 608 return;
608 609
609 } 610 }
610 611
611 if(QMessageBox::information(this, "Question",QString("Remove profile: %1").arg(profileToRemove), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok) 612 if(QMessageBox::information(this, "Question",QString("Remove profile: %1").arg(profileToRemove), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
612 { 613 {
613 profiles = QStringList::split(" ", profiles.join(" ").replace(QRegExp(profileToRemove), "")); 614 profiles = QStringList::split(" ", profiles.join(" ").replace(QRegExp(profileToRemove), ""));
614 profilesList->clear(); 615 profilesList->clear();
615 for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it) 616 for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it)
616 profilesList->insertItem((*it)); 617 profilesList->insertItem((*it));
617 618
618 // Remove any interface settings and mappings. 619 // Remove any interface settings and mappings.
619 Interfaces interfaces; 620 Interfaces interfaces;
620 // Go through them one by one 621 // Go through them one by one
621 QMap<Interface*, QListViewItem*>::Iterator it; 622 QMap<Interface*, QListViewItem*>::Iterator it;
622 for( it = items.begin(); it != items.end(); ++it ) 623 for( it = items.begin(); it != items.end(); ++it )
623 { 624 {
624 QString interfaceName = it.key()->getInterfaceName(); 625 QString interfaceName = it.key()->getInterfaceName();
625 odebug << interfaceName.latin1() << oendl; 626 odebug << interfaceName.latin1() << oendl;
626 if(interfaces.setInterface(interfaceName + "_" + profileToRemove)) 627 if(interfaces.setInterface(interfaceName + "_" + profileToRemove))
627 { 628 {
628 interfaces.removeInterface(); 629 interfaces.removeInterface();
629 if(interfaces.setMapping(interfaceName)) 630 if(interfaces.setMapping(interfaceName))
630 { 631 {
631 if(profilesList->count() == 1) 632 if(profilesList->count() == 1)
632 interfaces.removeMapping(); 633 interfaces.removeMapping();
633 else 634 else
634 { 635 {
635 interfaces.removeMap("map", interfaceName + "_" + profileToRemove); 636 interfaces.removeMap("map", interfaceName + "_" + profileToRemove);
636 } 637 }
637 } 638 }
638 interfaces.write(); 639 interfaces.write();
639 break; 640 break;
640 } 641 }
641 } 642 }
642 } 643 }
643} 644}
644 645
645/** 646/**
646 * A new profile has been selected, change. 647 * A new profile has been selected, change.
647 * @param newProfile the new profile. 648 * @param newProfile the new profile.
648 */ 649 */
649void MainWindowImp::changeProfile() 650void MainWindowImp::changeProfile()
650{ 651{
651 if(profilesList->currentItem() == -1) 652 if(profilesList->currentItem() == -1)
652 { 653 {
653 QMessageBox::information(this, "Can't Change.","Please select a profile.", QMessageBox::Ok); 654 QMessageBox::information(this, "Can't Change.","Please select a profile.", QMessageBox::Ok);
654 return; 655 return;
655 } 656 }
656 QString newProfile = profilesList->text(profilesList->currentItem()); 657 QString newProfile = profilesList->text(profilesList->currentItem());
657 if(newProfile != currentProfileLabel->text()) 658 if(newProfile != currentProfileLabel->text())
658 { 659 {
659 currentProfileLabel->setText(newProfile); 660 currentProfileLabel->setText(newProfile);
660 QFile::remove(scheme); 661 QFile::remove(scheme);
661 QFile file(scheme); 662 QFile file(scheme);
662 if ( file.open(IO_ReadWrite) ) 663 if ( file.open(IO_ReadWrite) )
663 { 664 {
664 QTextStream stream( &file ); 665 QTextStream stream( &file );
665 stream << QString("SCHEME=%1").arg(newProfile); 666 stream << QString("SCHEME=%1").arg(newProfile);
666 file.close(); 667 file.close();
667 } 668 }
668 // restart all up devices? 669 // restart all up devices?
669 if(QMessageBox::information(this, "Question","Restart all running interfaces?", QMessageBox::Ok, QMessageBox::No) == QMessageBox::Ok) 670 if(QMessageBox::information(this, "Question","Restart all running interfaces?", QMessageBox::Ok, QMessageBox::No) == QMessageBox::Ok)
670 { 671 {
671 // Go through them one by one 672 // Go through them one by one
672 QMap<Interface*, QListViewItem*>::Iterator it; 673 QMap<Interface*, QListViewItem*>::Iterator it;
673 for( it = items.begin(); it != items.end(); ++it ) 674 for( it = items.begin(); it != items.end(); ++it )
674 { 675 {
675 if(it.key()->getStatus() == true) 676 if(it.key()->getStatus() == true)
676 it.key()->restart(); 677 it.key()->restart();
677 } 678 }
678 } 679 }
679 } 680 }
680 // TODO change the profile in the modules 681 // TODO change the profile in the modules
681} 682}
682 683
683 684
684void MainWindowImp::makeChannel() 685void MainWindowImp::makeChannel()
685{ 686{
686 channel = new QCopChannel( "QPE/Application/networksettings", this ); 687 channel = new QCopChannel( "QPE/Application/networksettings", this );
687 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), 688 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
688 this, SLOT(receive(const QCString&,const QByteArray&)) ); 689 this, SLOT(receive(const QCString&,const QByteArray&)) );
689} 690}
690 691
691void MainWindowImp::receive(const QCString &msg, const QByteArray &arg) 692void MainWindowImp::receive(const QCString &msg, const QByteArray &arg)
692{ 693{
693 bool found = false; 694 bool found = false;
694 odebug << "MainWindowImp::receive QCop msg >"+msg+"<" << oendl; 695 odebug << "MainWindowImp::receive QCop msg >"+msg+"<" << oendl;
695 if (msg == "raise") 696 if (msg == "raise")
696 { 697 {
697 raise(); 698 raise();
698 return; 699 return;
699 } 700 }
700 701
701 QString dest = msg.left(msg.find("(")); 702 QString dest = msg.left(msg.find("("));
702 QCString param = msg.right(msg.length() - msg.find("(") - 1); 703 QCString param = msg.right(msg.length() - msg.find("(") - 1);
703 param = param.left( param.length() - 1 ); 704 param = param.left( param.length() - 1 );
704 odebug << "dest >" << dest.latin1() << "< param >"+param+"<" << oendl; 705 odebug << "dest >" << dest.latin1() << "< param >"+param+"<" << oendl;
705 706
706 QMap<Module*, QLibrary*>::Iterator it; 707 QMap<Module*, QLibrary*>::Iterator it;
707 for( it = libraries.begin(); it != libraries.end(); ++it ) 708 for( it = libraries.begin(); it != libraries.end(); ++it )
708 { 709 {
709 odebug << "plugin >" << it.key()->type().latin1() << "<" << oendl; 710 odebug << "plugin >" << it.key()->type().latin1() << "<" << oendl;
710 if(it.key()->type() == dest) 711 if(it.key()->type() == dest)
711 { 712 {
712 it.key()->receive( param, arg ); 713 it.key()->receive( param, arg );
713 found = true; 714 found = true;
714 } 715 }
715 } 716 }
716 717
717 718
718 if (found) QPEApplication::setKeepRunning(); 719 if (found) QPEApplication::setKeepRunning();
719 else odebug << "Huh what do ya want" << oendl; 720 else odebug << "Huh what do ya want" << oendl;
720} 721}
721 722
722void MainWindowImp::setHostname() 723void MainWindowImp::setHostname()
723{ 724{
724 static QRegExp filter("[^A-Za-z0-9_\\-\\.]"); 725 static QRegExp filter("[^A-Za-z0-9_\\-\\.]");
725 if (filter.match(m_Nameinput->text())!=-1) { 726 if (filter.match(m_Nameinput->text())!=-1) {
726 odebug << "Wrong hostname" << oendl; 727 odebug << "Wrong hostname" << oendl;
727 QMessageBox::critical(0, tr("Sorry"), tr("This is a wrong name.<br>Please use A-Z, a-z, _, - or a single dot.")); 728 QMessageBox::critical(0, tr("Sorry"), tr("This is a wrong name.<br>Please use A-Z, a-z, _, - or a single dot."));
728 return; 729 return;
729 } 730 }
730 731
731 OProcess h; 732 OProcess h;
732 _procTemp=""; 733 _procTemp="";
733 h << "hostname" << m_Nameinput->text(); 734 h << "hostname" << m_Nameinput->text();
734 connect(&h,SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)),this,SLOT(slotHostname(Opie::Core::OProcess*,char*,int))); 735 connect(&h,SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)),this,SLOT(slotHostname(Opie::Core::OProcess*,char*,int)));
735 h.start(OProcess::Block,OProcess::Stderr); 736 if (!h.start(OProcess::Block,OProcess::Stderr))
737 owarn << "Failed execution of 'hostname'. Are the paths correct?" << oendl;
736 odebug << "Got " << _procTemp << " - " << h.exitStatus() << oendl; 738 odebug << "Got " << _procTemp << " - " << h.exitStatus() << oendl;
737 if (h.exitStatus()!=0) { 739 if (h.exitStatus()!=0) {
738 QMessageBox::critical(0, tr("Sorry"), QString(tr("Could not set name.\n%1")).arg(_procTemp.stripWhiteSpace())); 740 QMessageBox::critical(0, tr("Sorry"), QString(tr("Could not set name.\n%1")).arg(_procTemp.stripWhiteSpace()));
739 return; 741 return;
740 } 742 }
741 _procTemp=""; 743 _procTemp="";
742 744
743 QFile f(_HOSTFILE); 745 QFile f(_HOSTFILE);
744 if (f.open(IO_Truncate|IO_WriteOnly)) 746 if (f.open(IO_Truncate|IO_WriteOnly))
745 { 747 {
746 QTextStream s(&f); 748 QTextStream s(&f);
747 s << m_Nameinput->text(); 749 s << m_Nameinput->text();
748 } else { 750 } else {
749 QMessageBox::critical(0, tr("Sorry"), tr("Could not save name.")); 751 QMessageBox::critical(0, tr("Sorry"), tr("Could not save name."));
750 return; 752 return;
751 } 753 }
752 754
753 f.close(); 755 f.close();
754 f.setName(_IRDANAME); 756 f.setName(_IRDANAME);
755 if (f.open(IO_WriteOnly)) 757 if (f.open(IO_WriteOnly))
756 { 758 {
757 QTextStream s(&f); 759 QTextStream s(&f);
758 s << m_Nameinput->text(); 760 s << m_Nameinput->text();
759 } else { 761 } else {
760 QMessageBox::critical(0, tr("Sorry"), tr("Could not set infrared name.")); 762 QMessageBox::critical(0, tr("Sorry"), tr("Could not set infrared name."));
761 } 763 }
762} 764}
763 765
764void MainWindowImp::initHostname() 766void MainWindowImp::initHostname()
765{ 767{
766 OProcess h; 768 OProcess h;
767 _procTemp=""; 769 _procTemp="";
768 770
769 h << "hostname"; 771 h << "hostname";
770 connect(&h,SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)),this,SLOT(slotHostname(Opie::Core::OProcess*,char*,int))); 772 connect(&h,SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)),this,SLOT(slotHostname(Opie::Core::OProcess*,char*,int)));
771 h.start(OProcess::Block,OProcess::AllOutput); 773 if (!h.start(OProcess::Block,OProcess::AllOutput))
774 owarn << "Could not execute 'hostname'. Are the paths correct?" oendl;
772 odebug << "Got " << _procTemp <<oendl; 775 odebug << "Got " << _procTemp <<oendl;
773 m_Nameinput->setText(_procTemp.stripWhiteSpace()); 776 m_Nameinput->setText(_procTemp.stripWhiteSpace());
774 _procTemp=""; 777 _procTemp="";
775} 778}
776 779
777void MainWindowImp::slotHostname(Opie::Core::OProcess */*proc*/, char *buffer, int buflen) 780void MainWindowImp::slotHostname(Opie::Core::OProcess * /*proc*/, char *buffer, int buflen)
778{ 781{
779 if (buflen < 1 || buffer==0) return; 782 if (buflen < 1 || buffer==0) return;
780 char*_t = new char[buflen+1]; 783 char*_t = new char[buflen+1];
781 ::memset(_t,0,buflen+1); 784 ::memset(_t,0,buflen+1);
782 ::memcpy(_t,buffer,buflen); 785 ::memcpy(_t,buffer,buflen);
783 _procTemp+=_t; 786 _procTemp+=_t;
784 delete[]_t; 787 delete[]_t;
785} 788}
diff --git a/noncore/settings/networksettings/ppp/modem.cpp b/noncore/settings/networksettings/ppp/modem.cpp
index 7b2e2a3..17ada9b 100644
--- a/noncore/settings/networksettings/ppp/modem.cpp
+++ b/noncore/settings/networksettings/ppp/modem.cpp
@@ -1,1088 +1,1090 @@
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/* OPIE */ 27/* OPIE */
28#include <opie2/odebug.h> 28#include <opie2/odebug.h>
29using namespace Opie::Core; 29using namespace Opie::Core;
30 30
31/* STD */ 31/* STD */
32#include <errno.h> 32#include <errno.h>
33#include <stdlib.h> 33#include <stdlib.h>
34#include <unistd.h> 34#include <unistd.h>
35#include <fcntl.h> 35#include <fcntl.h>
36#include <signal.h> 36#include <signal.h>
37#include <sys/ioctl.h> 37#include <sys/ioctl.h>
38#include <sys/types.h> 38#include <sys/types.h>
39#include <sys/stat.h> 39#include <sys/stat.h>
40#include <setjmp.h> 40#include <setjmp.h>
41#include <regex.h> 41#include <regex.h>
42#include <qregexp.h> 42#include <qregexp.h>
43#include <assert.h> 43#include <assert.h>
44#include <string.h> 44#include <string.h>
45 45
46#ifdef HAVE_RESOLV_H 46#ifdef HAVE_RESOLV_H
47# include <arpa/nameser.h> 47# include <arpa/nameser.h>
48# include <resolv.h> 48# include <resolv.h>
49#endif 49#endif
50 50
51#ifndef _PATH_RESCONF 51#ifndef _PATH_RESCONF
52#define _PATH_RESCONF "/etc/resolv.conf" 52#define _PATH_RESCONF "/etc/resolv.conf"
53#endif 53#endif
54 54
55#define strlcpy strcpy 55#define strlcpy strcpy
56#include "auth.h" 56#include "auth.h"
57#include "modem.h" 57#include "modem.h"
58#include "pppdata.h" 58#include "pppdata.h"
59 59
60 60
61#define MY_ASSERT(x) if (!(x)) { \ 61#define MY_ASSERT(x) if (!(x)) { \
62 ofatal << "ASSERT: \"" << #x << "\" in " << __FILE__ << " (" << __LINE__ << ")\n" << oendl; \ 62 ofatal << "ASSERT: \"" << #x << "\" in " << __FILE__ << " (" << __LINE__ << ")\n" << oendl; \
63 exit(1); } 63 exit(1); }
64 64
65 65
66static sigjmp_buf jmp_buffer; 66static sigjmp_buf jmp_buffer;
67 67
68//Modem *Modem::modem = 0; 68//Modem *Modem::modem = 0;
69 69
70 70
71const char* pppdPath() { 71const char* pppdPath() {
72 // wasting a few bytes 72 // wasting a few bytes
73 static char buffer[sizeof(PPPDSEARCHPATH)+sizeof(PPPDNAME)]; 73 static char buffer[sizeof(PPPDSEARCHPATH)+sizeof(PPPDNAME)];
74 static char *pppdPath = 0L; 74 static char *pppdPath = 0L;
75 char *p; 75 char *p;
76 76
77 if(pppdPath == 0L) { 77 if(pppdPath == 0L) {
78 const char *c = PPPDSEARCHPATH; 78 const char *c = PPPDSEARCHPATH;
79 while(*c != '\0') { 79 while(*c != '\0') {
80 while(*c == ':') 80 while(*c == ':')
81 c++; 81 c++;
82 p = buffer; 82 p = buffer;
83 while(*c != '\0' && *c != ':') 83 while(*c != '\0' && *c != ':')
84 *p++ = *c++; 84 *p++ = *c++;
85 *p = '\0'; 85 *p = '\0';
86 strcat(p, "/"); 86 strcat(p, "/");
87 strcat(p, PPPDNAME); 87 strcat(p, PPPDNAME);
88 if(access(buffer, F_OK) == 0) 88 if(access(buffer, F_OK) == 0)
89 return (pppdPath = buffer); 89 return (pppdPath = buffer);
90 } 90 }
91 } 91 }
92 92
93 return pppdPath; 93 return pppdPath;
94} 94}
95 95
96 96
97Modem::Modem( PPPData* pd ) 97Modem::Modem( PPPData* pd )
98{ 98{
99 _pppdata = pd; 99 _pppdata = pd;
100 modemfd = -1; 100 modemfd = -1;
101 _pppdExitStatus = -1; 101 _pppdExitStatus = -1;
102 pppdPid = -1; 102 pppdPid = -1;
103 sn = m_modemDebug = 0L; 103 sn = m_modemDebug = 0L;
104 data_mode = false; 104 data_mode = false;
105 modem_is_locked = false; 105 modem_is_locked = false;
106 lockfile[0] = '\0'; 106 lockfile[0] = '\0';
107 device = "/dev/modem"; 107 device = "/dev/modem";
108} 108}
109 109
110 110
111Modem::~Modem() 111Modem::~Modem()
112{ 112{
113} 113}
114 114
115 115
116speed_t Modem::modemspeed() { 116speed_t Modem::modemspeed() {
117 // convert the string modem speed int the gpppdata object to a t_speed type 117 // convert the string modem speed int the gpppdata object to a t_speed type
118 // to set the modem. The constants here should all be ifdef'd because 118 // to set the modem. The constants here should all be ifdef'd because
119 // other systems may not have them 119 // other systems may not have them
120 int i = _pppdata->speed().toInt()/100; 120 int i = _pppdata->speed().toInt()/100;
121 121
122 switch(i) { 122 switch(i) {
123 case 24: 123 case 24:
124 return B2400; 124 return B2400;
125 break; 125 break;
126 case 96: 126 case 96:
127 return B9600; 127 return B9600;
128 break; 128 break;
129 case 192: 129 case 192:
130 return B19200; 130 return B19200;
131 break; 131 break;
132 case 384: 132 case 384:
133 return B38400; 133 return B38400;
134 break; 134 break;
135#ifdef B57600 135#ifdef B57600
136 case 576: 136 case 576:
137 return B57600; 137 return B57600;
138 break; 138 break;
139#endif 139#endif
140 140
141#ifdef B115200 141#ifdef B115200
142 case 1152: 142 case 1152:
143 return B115200; 143 return B115200;
144 break; 144 break;
145#endif 145#endif
146 146
147#ifdef B230400 147#ifdef B230400
148 case 2304: 148 case 2304:
149 return B230400; 149 return B230400;
150 break; 150 break;
151#endif 151#endif
152 152
153#ifdef B460800 153#ifdef B460800
154 case 4608: 154 case 4608:
155 return B460800; 155 return B460800;
156 break; 156 break;
157#endif 157#endif
158 158
159 default: 159 default:
160 return B38400; 160 return B38400;
161 break; 161 break;
162 } 162 }
163} 163}
164 164
165bool Modem::opentty() { 165bool Modem::opentty() {
166 // int flags; 166 // int flags;
167 167
168//begin if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) { 168//begin if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) {
169 close(modemfd); 169 close(modemfd);
170 device = _pppdata->modemDevice(); 170 device = _pppdata->modemDevice();
171 if ((modemfd = open(device, O_RDWR|O_NDELAY|O_NOCTTY)) == -1) { 171 if ((modemfd = open(device, O_RDWR|O_NDELAY|O_NOCTTY)) == -1) {
172 odebug << "error opening modem device !" << oendl; 172 odebug << "error opening modem device !" << oendl;
173 errmsg = QObject::tr("Unable to open modem."); 173 errmsg = QObject::tr("Unable to open modem.");
174 return false; 174 return false;
175 } 175 }
176//bend if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) { 176//bend if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) {
177//} 177//}
178 178
179#if 0 179#if 0
180 if(_pppdata->UseCDLine()) { 180 if(_pppdata->UseCDLine()) {
181 if(ioctl(modemfd, TIOCMGET, &flags) == -1) { 181 if(ioctl(modemfd, TIOCMGET, &flags) == -1) {
182 errmsg = QObject::tr("Unable to detect state of CD line."); 182 errmsg = QObject::tr("Unable to detect state of CD line.");
183 ::close(modemfd); 183 ::close(modemfd);
184 modemfd = -1; 184 modemfd = -1;
185 return false; 185 return false;
186 } 186 }
187 if ((flags&TIOCM_CD) == 0) { 187 if ((flags&TIOCM_CD) == 0) {
188 errmsg = QObject::tr("The modem is not ready."); 188 errmsg = QObject::tr("The modem is not ready.");
189 ::close(modemfd); 189 ::close(modemfd);
190 modemfd = -1; 190 modemfd = -1;
191 return false; 191 return false;
192 } 192 }
193 } 193 }
194#endif 194#endif
195 195
196 tcdrain (modemfd); 196 tcdrain (modemfd);
197 tcflush (modemfd, TCIOFLUSH); 197 tcflush (modemfd, TCIOFLUSH);
198 198
199 if(tcgetattr(modemfd, &tty) < 0){ 199 if(tcgetattr(modemfd, &tty) < 0){
200 // this helps in some cases 200 // this helps in some cases
201 tcsendbreak(modemfd, 0); 201 tcsendbreak(modemfd, 0);
202 sleep(1); 202 sleep(1);
203 if(tcgetattr(modemfd, &tty) < 0){ 203 if(tcgetattr(modemfd, &tty) < 0){
204 errmsg = QObject::tr("The modem is busy."); 204 errmsg = QObject::tr("The modem is busy.");
205 ::close(modemfd); 205 ::close(modemfd);
206 modemfd = -1; 206 modemfd = -1;
207 return false; 207 return false;
208 } 208 }
209 } 209 }
210 210
211 memset(&initial_tty,'\0',sizeof(initial_tty)); 211 memset(&initial_tty,'\0',sizeof(initial_tty));
212 212
213 initial_tty = tty; 213 initial_tty = tty;
214 214
215 tty.c_cc[VMIN] = 0; // nonblocking 215 tty.c_cc[VMIN] = 0; // nonblocking
216 tty.c_cc[VTIME] = 0; 216 tty.c_cc[VTIME] = 0;
217 tty.c_oflag = 0; 217 tty.c_oflag = 0;
218 tty.c_lflag = 0; 218 tty.c_lflag = 0;
219 219
220 tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB); 220 tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB);
221 tty.c_cflag |= CS8 | CREAD; 221 tty.c_cflag |= CS8 | CREAD;
222 tty.c_cflag |= CLOCAL; // ignore modem status lines 222 tty.c_cflag |= CLOCAL; // ignore modem status lines
223 tty.c_iflag = IGNBRK | IGNPAR /* | ISTRIP */ ; 223 tty.c_iflag = IGNBRK | IGNPAR /* | ISTRIP */ ;
224 tty.c_lflag &= ~ICANON; // non-canonical mode 224 tty.c_lflag &= ~ICANON; // non-canonical mode
225 tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE); 225 tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE);
226 226
227 227
228 if(_pppdata->flowcontrol() != PPPData::FlowNone) { 228 if(_pppdata->flowcontrol() != PPPData::FlowNone) {
229 if(_pppdata->flowcontrol() == PPPData::FlowHardware) { 229 if(_pppdata->flowcontrol() == PPPData::FlowHardware) {
230 tty.c_cflag |= CRTSCTS; 230 tty.c_cflag |= CRTSCTS;
231 } 231 }
232 else { 232 else {
233 tty.c_iflag |= IXON | IXOFF; 233 tty.c_iflag |= IXON | IXOFF;
234 tty.c_cc[VSTOP] = 0x13; /* DC3 = XOFF = ^S */ 234 tty.c_cc[VSTOP] = 0x13; /* DC3 = XOFF = ^S */
235 tty.c_cc[VSTART] = 0x11; /* DC1 = XON = ^Q */ 235 tty.c_cc[VSTART] = 0x11; /* DC1 = XON = ^Q */
236 } 236 }
237 } 237 }
238 else { 238 else {
239 tty.c_cflag &= ~CRTSCTS; 239 tty.c_cflag &= ~CRTSCTS;
240 tty.c_iflag &= ~(IXON | IXOFF); 240 tty.c_iflag &= ~(IXON | IXOFF);
241 } 241 }
242 242
243 cfsetospeed(&tty, modemspeed()); 243 cfsetospeed(&tty, modemspeed());
244 cfsetispeed(&tty, modemspeed()); 244 cfsetispeed(&tty, modemspeed());
245 245
246 tcdrain(modemfd); 246 tcdrain(modemfd);
247 247
248 if(tcsetattr(modemfd, TCSANOW, &tty) < 0){ 248 if(tcsetattr(modemfd, TCSANOW, &tty) < 0){
249 errmsg = QObject::tr("The modem is busy."); 249 errmsg = QObject::tr("The modem is busy.");
250 ::close(modemfd); 250 ::close(modemfd);
251 modemfd=-1; 251 modemfd=-1;
252 return false; 252 return false;
253 } 253 }
254 254
255 errmsg = QObject::tr("Modem Ready."); 255 errmsg = QObject::tr("Modem Ready.");
256 return true; 256 return true;
257} 257}
258 258
259 259
260bool Modem::closetty() { 260bool Modem::closetty() {
261 if(modemfd >=0 ) { 261 if(modemfd >=0 ) {
262 stop(); 262 stop();
263 /* discard data not read or transmitted */ 263 /* discard data not read or transmitted */
264 tcflush(modemfd, TCIOFLUSH); 264 tcflush(modemfd, TCIOFLUSH);
265 265
266 if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){ 266 if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){
267 errmsg = QObject::tr("Can't restore tty settings: tcsetattr()\n"); 267 errmsg = QObject::tr("Can't restore tty settings: tcsetattr()\n");
268 ::close(modemfd); 268 ::close(modemfd);
269 modemfd = -1; 269 modemfd = -1;
270 return false; 270 return false;
271 } 271 }
272 ::close(modemfd); 272 ::close(modemfd);
273 modemfd = -1; 273 modemfd = -1;
274 } 274 }
275 275
276 return true; 276 return true;
277} 277}
278 278
279 279
280void Modem::readtty(int) { 280void Modem::readtty(int) {
281 char buffer[200]; 281 char buffer[200];
282 unsigned char c; 282 unsigned char c;
283 int len; 283 int len;
284 284
285 // read data in chunks of up to 200 bytes 285 // read data in chunks of up to 200 bytes
286 if((len = ::read(modemfd, buffer, 200)) > 0) { 286 if((len = ::read(modemfd, buffer, 200)) > 0) {
287 // split buffer into single characters for further processing 287 // split buffer into single characters for further processing
288 for(int i = 0; i < len; i++) { 288 for(int i = 0; i < len; i++) {
289 c = buffer[i] & 0x7F; 289 c = buffer[i] & 0x7F;
290 emit charWaiting(c); 290 emit charWaiting(c);
291 } 291 }
292 } 292 }
293} 293}
294 294
295 295
296void Modem::notify(const QObject *receiver, const char *member) { 296void Modem::notify(const QObject *receiver, const char *member) {
297 connect(this, SIGNAL(charWaiting(unsigned char)), receiver, member); 297 connect(this, SIGNAL(charWaiting(unsigned char)), receiver, member);
298 startNotifier(); 298 startNotifier();
299} 299}
300 300
301 301
302void Modem::stop() { 302void Modem::stop() {
303 disconnect(SIGNAL(charWaiting(unsigned char))); 303 disconnect(SIGNAL(charWaiting(unsigned char)));
304 stopNotifier(); 304 stopNotifier();
305} 305}
306 306
307 307
308void Modem::startNotifier() { 308void Modem::startNotifier() {
309 if(modemfd >= 0) { 309 if(modemfd >= 0) {
310 if(sn == 0) { 310 if(sn == 0) {
311 sn = new QSocketNotifier(modemfd, QSocketNotifier::Read, this); 311 sn = new QSocketNotifier(modemfd, QSocketNotifier::Read, this);
312 connect(sn, SIGNAL(activated(int)), SLOT(readtty(int))); 312 connect(sn, SIGNAL(activated(int)), SLOT(readtty(int)));
313 odebug << "QSocketNotifier started!" << oendl; 313 odebug << "QSocketNotifier started!" << oendl;
314 } else { 314 } else {
315 odebug << "QSocketNotifier re-enabled!" << oendl; 315 odebug << "QSocketNotifier re-enabled!" << oendl;
316 sn->setEnabled(true); 316 sn->setEnabled(true);
317 } 317 }
318 } 318 }
319} 319}
320 320
321 321
322void Modem::stopNotifier() { 322void Modem::stopNotifier() {
323 if(sn != 0) { 323 if(sn != 0) {
324 sn->setEnabled(false); 324 sn->setEnabled(false);
325 disconnect(sn); 325 disconnect(sn);
326 delete sn; 326 delete sn;
327 sn = 0; 327 sn = 0;
328 odebug << "QSocketNotifier stopped!" << oendl; 328 odebug << "QSocketNotifier stopped!" << oendl;
329 } 329 }
330} 330}
331 331
332 332
333void Modem::flush() { 333void Modem::flush() {
334 char c; 334 char c;
335 while(read(modemfd, &c, 1) == 1); 335 while(read(modemfd, &c, 1) == 1);
336} 336}
337 337
338 338
339bool Modem::writeChar(unsigned char c) { 339bool Modem::writeChar(unsigned char c) {
340 int s; 340 int s;
341 do { 341 do {
342 s = write(modemfd, &c, 1); 342 s = write(modemfd, &c, 1);
343 if (s < 0) { 343 if (s < 0) {
344 oerr << "write() in Modem::writeChar failed" << oendl; 344 oerr << "write() in Modem::writeChar failed" << oendl;
345 return false; 345 return false;
346 } 346 }
347 } while(s == 0); 347 } while(s == 0);
348 348
349 return true; 349 return true;
350} 350}
351 351
352 352
353bool Modem::writeLine(const char *buf) { 353bool Modem::writeLine(const char *buf) {
354 int len = strlen(buf); 354 int len = strlen(buf);
355 char *b = new char[len+2]; 355 char *b = new char[len+2];
356 memcpy(b, buf, len); 356 memcpy(b, buf, len);
357 // different modems seem to need different line terminations 357 // different modems seem to need different line terminations
358 switch( _pppdata->enter() ) { 358 switch( _pppdata->enter() ) {
359 case PPPData::EndLF: 359 case PPPData::EndLF:
360 b[len++]='\n'; 360 b[len++]='\n';
361 break; 361 break;
362 case PPPData::EndCR: 362 case PPPData::EndCR:
363 b[len++]='\r'; 363 b[len++]='\r';
364 break; 364 break;
365 case PPPData::EndCRLF: 365 case PPPData::EndCRLF:
366 b[len++]='\r'; 366 b[len++]='\r';
367 b[len++]='\n'; 367 b[len++]='\n';
368 break; 368 break;
369 } 369 }
370 370
371 int l = len; 371 int l = len;
372 while(l) { 372 while(l) {
373 int wr = write(modemfd, &b[len-l], l); 373 int wr = write(modemfd, &b[len-l], l);
374 if(wr < 0) { 374 if(wr < 0) {
375 // TODO do something meaningful with the error code (or ignore it 375 // TODO do something meaningful with the error code (or ignore it
376 oerr << "write() in Modem::writeLine failed" << oendl; 376 oerr << "write() in Modem::writeLine failed" << oendl;
377 delete[] b; 377 delete[] b;
378 return false; 378 return false;
379 } 379 }
380 l -= wr; 380 l -= wr;
381 } 381 }
382 delete[] b; 382 delete[] b;
383 return true; 383 return true;
384} 384}
385 385
386 386
387bool Modem::hangup() { 387bool Modem::hangup() {
388 // this should really get the modem to hang up and go into command mode 388 // this should really get the modem to hang up and go into command mode
389 // If anyone sees a fault in the following please let me know, since 389 // If anyone sees a fault in the following please let me know, since
390 // this is probably the most imporant snippet of code in the whole of 390 // this is probably the most imporant snippet of code in the whole of
391 // kppp. If people complain about kppp being stuck, this piece of code 391 // kppp. If people complain about kppp being stuck, this piece of code
392 // is most likely the reason. 392 // is most likely the reason.
393 struct termios temptty; 393 struct termios temptty;
394 394
395 if(modemfd >= 0) { 395 if(modemfd >= 0) {
396 396
397 // is this Escape & HangupStr stuff really necessary ? (Harri) 397 // is this Escape & HangupStr stuff really necessary ? (Harri)
398 398
399 if (data_mode) escape_to_command_mode(); 399 if (data_mode) escape_to_command_mode();
400 400
401 // Then hangup command 401 // Then hangup command
402 writeLine(_pppdata->modemHangupStr().local8Bit()); 402 writeLine(_pppdata->modemHangupStr().local8Bit());
403 403
404 usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 sec 404 usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 sec
405 405
406#ifndef DEBUG_WO_DIALING 406#ifndef DEBUG_WO_DIALING
407 if (sigsetjmp(jmp_buffer, 1) == 0) { 407 if (sigsetjmp(jmp_buffer, 1) == 0) {
408 // set alarm in case tcsendbreak() hangs 408 // set alarm in case tcsendbreak() hangs
409 signal(SIGALRM, alarm_handler); 409 signal(SIGALRM, alarm_handler);
410 alarm(2); 410 alarm(2);
411 411
412 tcsendbreak(modemfd, 0); 412 tcsendbreak(modemfd, 0);
413 413
414 alarm(0); 414 alarm(0);
415 signal(SIGALRM, SIG_IGN); 415 signal(SIGALRM, SIG_IGN);
416 } else { 416 } else {
417 // we reach this point if the alarm handler got called 417 // we reach this point if the alarm handler got called
418 closetty(); 418 closetty();
419 close(modemfd); 419 close(modemfd);
420 modemfd = -1; 420 modemfd = -1;
421 errmsg = QObject::tr("The modem does not respond."); 421 errmsg = QObject::tr("The modem does not respond.");
422 return false; 422 return false;
423 } 423 }
424 424
425#ifndef __svr4__ // drops DTR but doesn't set it afterwards again. not good for init. 425#ifndef __svr4__ // drops DTR but doesn't set it afterwards again. not good for init.
426 tcgetattr(modemfd, &temptty); 426 tcgetattr(modemfd, &temptty);
427 cfsetospeed(&temptty, B0); 427 cfsetospeed(&temptty, B0);
428 cfsetispeed(&temptty, B0); 428 cfsetispeed(&temptty, B0);
429 tcsetattr(modemfd, TCSAFLUSH, &temptty); 429 tcsetattr(modemfd, TCSAFLUSH, &temptty);
430#else 430#else
431 int modemstat; 431 int modemstat;
432 ioctl(modemfd, TIOCMGET, &modemstat); 432 ioctl(modemfd, TIOCMGET, &modemstat);
433 modemstat &= ~TIOCM_DTR; 433 modemstat &= ~TIOCM_DTR;
434 ioctl(modemfd, TIOCMSET, &modemstat); 434 ioctl(modemfd, TIOCMSET, &modemstat);
435 ioctl(modemfd, TIOCMGET, &modemstat); 435 ioctl(modemfd, TIOCMGET, &modemstat);
436 modemstat |= TIOCM_DTR; 436 modemstat |= TIOCM_DTR;
437 ioctl(modemfd, TIOCMSET, &modemstat); 437 ioctl(modemfd, TIOCMSET, &modemstat);
438#endif 438#endif
439 439
440 usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 secs 440 usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 secs
441 441
442 cfsetospeed(&temptty, modemspeed()); 442 cfsetospeed(&temptty, modemspeed());
443 cfsetispeed(&temptty, modemspeed()); 443 cfsetispeed(&temptty, modemspeed());
444 tcsetattr(modemfd, TCSAFLUSH, &temptty); 444 tcsetattr(modemfd, TCSAFLUSH, &temptty);
445#endif 445#endif
446 return true; 446 return true;
447 } else 447 } else
448 return false; 448 return false;
449} 449}
450 450
451 451
452void Modem::escape_to_command_mode() { 452void Modem::escape_to_command_mode() {
453 // Send Properly bracketed escape code to put the modem back into command state. 453 // Send Properly bracketed escape code to put the modem back into command state.
454 // A modem will accept AT commands only when it is in command state. 454 // A modem will accept AT commands only when it is in command state.
455 // When a modem sends the host the CONNECT string, that signals 455 // When a modem sends the host the CONNECT string, that signals
456 // that the modem is now in the connect state (no long accepts AT commands.) 456 // that the modem is now in the connect state (no long accepts AT commands.)
457 // Need to send properly timed escape sequence to put modem in command state. 457 // Need to send properly timed escape sequence to put modem in command state.
458 // Escape codes and guard times are controlled by S2 and S12 values. 458 // Escape codes and guard times are controlled by S2 and S12 values.
459 // 459 //
460 tcflush(modemfd, TCIOFLUSH); 460 tcflush(modemfd, TCIOFLUSH);
461 461
462 // +3 because quiet time must be greater than guard time. 462 // +3 because quiet time must be greater than guard time.
463 usleep((_pppdata->modemEscapeGuardTime()+3)*20000); 463 usleep((_pppdata->modemEscapeGuardTime()+3)*20000);
464 QCString tmp = _pppdata->modemEscapeStr().local8Bit(); 464 QCString tmp = _pppdata->modemEscapeStr().local8Bit();
465 write(modemfd, tmp.data(), tmp.length()); 465 write(modemfd, tmp.data(), tmp.length());
466 tcflush(modemfd, TCIOFLUSH); 466 tcflush(modemfd, TCIOFLUSH);
467 usleep((_pppdata->modemEscapeGuardTime()+3)*20000); 467 usleep((_pppdata->modemEscapeGuardTime()+3)*20000);
468 468
469 data_mode = false; 469 data_mode = false;
470} 470}
471 471
472 472
473const QString Modem::modemMessage() { 473const QString Modem::modemMessage() {
474 return errmsg; 474 return errmsg;
475} 475}
476 476
477 477
478QString Modem::parseModemSpeed(const QString &s) { 478QString Modem::parseModemSpeed(const QString &s) {
479 // this is a small (and bad) parser for modem speeds 479 // this is a small (and bad) parser for modem speeds
480 int rx = -1; 480 int rx = -1;
481 int tx = -1; 481 int tx = -1;
482 int i; 482 int i;
483 QString result; 483 QString result;
484 484
485 odebug << "Modem reported result string: " << s.latin1() << "" << oendl; 485 odebug << "Modem reported result string: " << s.latin1() << "" << oendl;
486 486
487 const int RXMAX = 7; 487 const int RXMAX = 7;
488 const int TXMAX = 2; 488 const int TXMAX = 2;
489 QRegExp rrx[RXMAX] = { 489 QRegExp rrx[RXMAX] = {
490 QRegExp("[0-9]+[:/ ]RX", false), 490 QRegExp("[0-9]+[:/ ]RX", false),
491 QRegExp("[0-9]+RX", false), 491 QRegExp("[0-9]+RX", false),
492 QRegExp("[/: -][0-9]+[/: ]", false), 492 QRegExp("[/: -][0-9]+[/: ]", false),
493 QRegExp("[/: -][0-9]+$", false), 493 QRegExp("[/: -][0-9]+$", false),
494 QRegExp("CARRIER [^0-9]*[0-9]+", false), 494 QRegExp("CARRIER [^0-9]*[0-9]+", false),
495 QRegExp("CONNECT [^0-9]*[0-9]+", false), 495 QRegExp("CONNECT [^0-9]*[0-9]+", false),
496 QRegExp("[0-9]+") // panic mode 496 QRegExp("[0-9]+") // panic mode
497 }; 497 };
498 498
499 QRegExp trx[TXMAX] = { 499 QRegExp trx[TXMAX] = {
500 QRegExp("[0-9]+[:/ ]TX", false), 500 QRegExp("[0-9]+[:/ ]TX", false),
501 QRegExp("[0-9]+TX", false) 501 QRegExp("[0-9]+TX", false)
502 }; 502 };
503 503
504 for(i = 0; i < RXMAX; i++) { 504 for(i = 0; i < RXMAX; i++) {
505 int len, idx, result; 505 int len, idx, result;
506 if((idx = rrx[i].match(s,0,&len)) > -1) { 506 if((idx = rrx[i].match(s,0,&len)) > -1) {
507// if((idx = rrx[i].search(s)) > -1) { 507// if((idx = rrx[i].search(s)) > -1) {
508 // len = rrx[i].matchedLength(); 508 // len = rrx[i].matchedLength();
509 509
510 // 510 //
511 // rrx[i] has been matched, idx contains the start of the match 511 // rrx[i] has been matched, idx contains the start of the match
512 // and len contains how long the match is. Extract the match. 512 // and len contains how long the match is. Extract the match.
513 // 513 //
514 QString sub = s.mid(idx, len); 514 QString sub = s.mid(idx, len);
515 515
516 // 516 //
517 // Now extract the digits only from the match, which will 517 // Now extract the digits only from the match, which will
518 // then be converted to an int. 518 // then be converted to an int.
519 // 519 //
520 if ((idx = rrx[RXMAX-1].match( sub,0,&len )) > -1) { 520 if ((idx = rrx[RXMAX-1].match( sub,0,&len )) > -1) {
521// if ((idx = rrx[RXMAX-1].search( sub )) > -1) { 521// if ((idx = rrx[RXMAX-1].search( sub )) > -1) {
522// len = rrx[RXMAX-1].matchedLength(); 522// len = rrx[RXMAX-1].matchedLength();
523 sub = sub.mid(idx, len); 523 sub = sub.mid(idx, len);
524 result = sub.toInt(); 524 result = sub.toInt();
525 if(result > 0) { 525 if(result > 0) {
526 rx = result; 526 rx = result;
527 break; 527 break;
528 } 528 }
529 } 529 }
530 } 530 }
531 } 531 }
532 532
533 for(i = 0; i < TXMAX; i++) { 533 for(i = 0; i < TXMAX; i++) {
534 int len, idx, result; 534 int len, idx, result;
535 if((idx = trx[i].match(s,0,&len)) > -1) { 535 if((idx = trx[i].match(s,0,&len)) > -1) {
536// if((idx = trx[i].search(s)) > -1) { 536// if((idx = trx[i].search(s)) > -1) {
537// len = trx[i].matchedLength(); 537// len = trx[i].matchedLength();
538 538
539 // 539 //
540 // trx[i] has been matched, idx contains the start of the match 540 // trx[i] has been matched, idx contains the start of the match
541 // and len contains how long the match is. Extract the match. 541 // and len contains how long the match is. Extract the match.
542 // 542 //
543 QString sub = s.mid(idx, len); 543 QString sub = s.mid(idx, len);
544 544
545 // 545 //
546 // Now extract the digits only from the match, which will then 546 // Now extract the digits only from the match, which will then
547 // be converted to an int. 547 // be converted to an int.
548 // 548 //
549 if((idx = rrx[RXMAX-1].match(sub,0,&len)) > -1) { 549 if((idx = rrx[RXMAX-1].match(sub,0,&len)) > -1) {
550// if((idx = rrx[RXMAX-1].search(sub)) > -1) { 550// if((idx = rrx[RXMAX-1].search(sub)) > -1) {
551// len = rrx[RXMAX-1].matchedLength(); 551// len = rrx[RXMAX-1].matchedLength();
552 sub = sub.mid(idx, len); 552 sub = sub.mid(idx, len);
553 result = sub.toInt(); 553 result = sub.toInt();
554 if(result > 0) { 554 if(result > 0) {
555 tx = result; 555 tx = result;
556 break; 556 break;
557 } 557 }
558 } 558 }
559 } 559 }
560 } 560 }
561 561
562 if(rx == -1 && tx == -1) 562 if(rx == -1 && tx == -1)
563 result = QObject::tr("Unknown speed"); 563 result = QObject::tr("Unknown speed");
564 else if(tx == -1) 564 else if(tx == -1)
565 result.setNum(rx); 565 result.setNum(rx);
566 else if(rx == -1) // should not happen 566 else if(rx == -1) // should not happen
567 result.setNum(tx); 567 result.setNum(tx);
568 else 568 else
569 result.sprintf("%d/%d", rx, tx); 569 result.sprintf("%d/%d", rx, tx);
570 570
571 odebug << "The parsed result is: " << result.latin1() << "" << oendl; 571 odebug << "The parsed result is: " << result.latin1() << "" << oendl;
572 572
573 return result; 573 return result;
574} 574}
575 575
576 576
577// Lock modem device. Returns 0 on success 1 if the modem is locked and -1 if 577// Lock modem device. Returns 0 on success 1 if the modem is locked and -1 if
578// a lock file can't be created ( permission problem ) 578// a lock file can't be created ( permission problem )
579int Modem::lockdevice() { 579int Modem::lockdevice() {
580 int fd; 580 int fd;
581 char newlock[80]=""; // safe 581 char newlock[80]=""; // safe
582 582
583 if(!_pppdata->modemLockFile()) { 583 if(!_pppdata->modemLockFile()) {
584 odebug << "The user doesn't want a lockfile." << oendl; 584 odebug << "The user doesn't want a lockfile." << oendl;
585 return 0; 585 return 0;
586 } 586 }
587 587
588 if (modem_is_locked) 588 if (modem_is_locked)
589 return 1; 589 return 1;
590 590
591 QString lockfile = LOCK_DIR"/LCK.."; 591 QString lockfile = LOCK_DIR"/LCK..";
592 lockfile += _pppdata->modemDevice().mid(5); // append everything after /dev/ 592 lockfile += _pppdata->modemDevice().mid(5); // append everything after /dev/
593 593
594 if(access(QFile::encodeName(lockfile), F_OK) == 0) { 594 if(access(QFile::encodeName(lockfile), F_OK) == 0) {
595// if ((fd = Requester::rq-> 595// if ((fd = Requester::rq->
596if ((fd = openLockfile(QFile::encodeName(lockfile), O_RDONLY)) >= 0) { 596if ((fd = openLockfile(QFile::encodeName(lockfile), O_RDONLY)) >= 0) {
597 // Mario: it's not necessary to read more than lets say 32 bytes. If 597 // Mario: it's not necessary to read more than lets say 32 bytes. If
598 // file has more than 32 bytes, skip the rest 598 // file has more than 32 bytes, skip the rest
599 char oldlock[33]; // safe 599 char oldlock[33]; // safe
600 int sz = read(fd, &oldlock, 32); 600 int sz = read(fd, &oldlock, 32);
601 close (fd); 601 close (fd);
602 if (sz <= 0) 602 if (sz <= 0)
603 return 1; 603 return 1;
604 oldlock[sz] = '\0'; 604 oldlock[sz] = '\0';
605 605
606 odebug << "Device is locked by: " << oldlock << "" << oendl; 606 odebug << "Device is locked by: " << oldlock << "" << oendl;
607 607
608 int oldpid; 608 int oldpid;
609 int match = sscanf(oldlock, "%d", &oldpid); 609 int match = sscanf(oldlock, "%d", &oldpid);
610 610
611 // found a pid in lockfile ? 611 // found a pid in lockfile ?
612 if (match < 1 || oldpid <= 0) 612 if (match < 1 || oldpid <= 0)
613 return 1; 613 return 1;
614 614
615 // check if process exists 615 // check if process exists
616 if (kill((pid_t)oldpid, 0) == 0 || errno != ESRCH) 616 if (kill((pid_t)oldpid, 0) == 0 || errno != ESRCH)
617 return 1; 617 return 1;
618 618
619 odebug << "lockfile is stale" << oendl; 619 odebug << "lockfile is stale" << oendl;
620 } 620 }
621 } 621 }
622 622
623 fd = openLockfile(_pppdata->modemDevice(),O_WRONLY|O_TRUNC|O_CREAT); 623 fd = openLockfile(_pppdata->modemDevice(),O_WRONLY|O_TRUNC|O_CREAT);
624 if(fd >= 0) { 624 if(fd >= 0) {
625 sprintf(newlock,"%010d\n", getpid()); 625 sprintf(newlock,"%010d\n", getpid());
626 odebug << "Locking Device: " << newlock << "" << oendl; 626 odebug << "Locking Device: " << newlock << "" << oendl;
627 627
628 write(fd, newlock, strlen(newlock)); 628 write(fd, newlock, strlen(newlock));
629 close(fd); 629 close(fd);
630 modem_is_locked=true; 630 modem_is_locked=true;
631 631
632 return 0; 632 return 0;
633 } 633 }
634 634
635 return -1; 635 return -1;
636 636
637} 637}
638 638
639 639
640// UnLock modem device 640// UnLock modem device
641void Modem::unlockdevice() { 641void Modem::unlockdevice() {
642 if (modem_is_locked) { 642 if (modem_is_locked) {
643 odebug << "UnLocking Modem Device" << oendl; 643 odebug << "UnLocking Modem Device" << oendl;
644 close(modemfd); 644 close(modemfd);
645 modemfd = -1; 645 modemfd = -1;
646 unlink(lockfile); 646 unlink(lockfile);
647 lockfile[0] = '\0'; 647 lockfile[0] = '\0';
648 modem_is_locked=false; 648 modem_is_locked=false;
649 } 649 }
650} 650}
651 651
652int Modem::openLockfile( QString lockfile, int flags) 652int Modem::openLockfile( QString lockfile, int flags)
653{ 653{
654 int fd; 654 int fd;
655 int mode; 655 int mode;
656 flags = O_RDONLY; 656 flags = O_RDONLY;
657 if(flags == O_WRONLY|O_TRUNC|O_CREAT) 657 if(flags == O_WRONLY|O_TRUNC|O_CREAT)
658 mode = 0644; 658 mode = 0644;
659 else 659 else
660 mode = 0; 660 mode = 0;
661 661
662 lockfile = LOCK_DIR; 662 lockfile = LOCK_DIR;
663 lockfile += "/LCK.."; 663 lockfile += "/LCK..";
664 lockfile += device.right( device.length() - device.findRev("/") -1 ); 664 lockfile += device.right( device.length() - device.findRev("/") -1 );
665 odebug << "lockfile >" << lockfile.latin1() << "<" << oendl; 665 odebug << "lockfile >" << lockfile.latin1() << "<" << oendl;
666 // TODO: 666 // TODO:
667 // struct stat st; 667 // struct stat st;
668 // if(stat(lockfile.data(), &st) == -1) { 668 // if(stat(lockfile.data(), &st) == -1) {
669 // if(errno == EBADF) 669 // if(errno == EBADF)
670 // return -1; 670 // return -1;
671 // } else { 671 // } else {
672 // // make sure that this is a regular file 672 // // make sure that this is a regular file
673 // if(!S_ISREG(st.st_mode)) 673 // if(!S_ISREG(st.st_mode))
674 // return -1; 674 // return -1;
675 // } 675 // }
676 if ((fd = open(lockfile, flags, mode)) == -1) { 676 if ((fd = open(lockfile, flags, mode)) == -1) {
677 odebug << "error opening lockfile!" << oendl; 677 odebug << "error opening lockfile!" << oendl;
678 lockfile = QString::null; 678 lockfile = QString::null;
679 fd = open(DEVNULL, O_RDONLY); 679 fd = open(DEVNULL, O_RDONLY);
680 } else 680 } else
681 fchown(fd, 0, 0); 681 fchown(fd, 0, 0);
682 return fd; 682 return fd;
683} 683}
684 684
685 685
686 686
687void alarm_handler(int) { 687void alarm_handler(int) {
688 // fprintf(stderr, "alarm_handler(): Received SIGALRM\n"); 688 // fprintf(stderr, "alarm_handler(): Received SIGALRM\n");
689 689
690 // jump 690 // jump
691 siglongjmp(jmp_buffer, 1); 691 siglongjmp(jmp_buffer, 1);
692} 692}
693 693
694 694
695const char* Modem::authFile(Auth method, int version) { 695const char* Modem::authFile(Auth method, int version) {
696 switch(method|version) { 696 switch(method|version) {
697 case PAP|Original: 697 case PAP|Original:
698 return PAP_AUTH_FILE; 698 return PAP_AUTH_FILE;
699 break; 699 break;
700 case PAP|New: 700 case PAP|New:
701 return PAP_AUTH_FILE".new"; 701 return PAP_AUTH_FILE".new";
702 break; 702 break;
703 case PAP|Old: 703 case PAP|Old:
704 return PAP_AUTH_FILE".old"; 704 return PAP_AUTH_FILE".old";
705 break; 705 break;
706 case CHAP|Original: 706 case CHAP|Original:
707 return CHAP_AUTH_FILE; 707 return CHAP_AUTH_FILE;
708 break; 708 break;
709 case CHAP|New: 709 case CHAP|New:
710 return CHAP_AUTH_FILE".new"; 710 return CHAP_AUTH_FILE".new";
711 break; 711 break;
712 case CHAP|Old: 712 case CHAP|Old:
713 return CHAP_AUTH_FILE".old"; 713 return CHAP_AUTH_FILE".old";
714 break; 714 break;
715 default: 715 default:
716 return 0L; 716 return 0L;
717 } 717 }
718} 718}
719 719
720 720
721bool Modem::createAuthFile(Auth method, const char *username, const char *password) { 721bool Modem::createAuthFile(Auth method, const char *username, const char *password) {
722 const char *authfile, *oldName, *newName; 722 const char *authfile, *oldName, *newName;
723 char line[100]; 723 char line[100];
724 char regexp[2*MaxStrLen+30]; 724 char regexp[2*MaxStrLen+30];
725 regex_t preg; 725 regex_t preg;
726 726
727 if(!(authfile = authFile(method))) 727 if(!(authfile = authFile(method)))
728 return false; 728 return false;
729 729
730 if(!(newName = authFile(method, New))) 730 if(!(newName = authFile(method, New)))
731 return false; 731 return false;
732 732
733 // look for username, "username" or 'username' 733 // look for username, "username" or 'username'
734 // if you modify this RE you have to adapt regexp's size above 734 // if you modify this RE you have to adapt regexp's size above
735 snprintf(regexp, sizeof(regexp), "^[ \t]*%s[ \t]\\|^[ \t]*[\"\']%s[\"\']", 735 snprintf(regexp, sizeof(regexp), "^[ \t]*%s[ \t]\\|^[ \t]*[\"\']%s[\"\']",
736 username,username); 736 username,username);
737 MY_ASSERT(regcomp(&preg, regexp, 0) == 0); 737 MY_ASSERT(regcomp(&preg, regexp, 0) == 0);
738 738
739 // copy to new file pap- or chap-secrets 739 // copy to new file pap- or chap-secrets
740 int old_umask = umask(0077); 740 int old_umask = umask(0077);
741 FILE *fout = fopen(newName, "w"); 741 FILE *fout = fopen(newName, "w");
742 if(fout) { 742 if(fout) {
743 // copy old file 743 // copy old file
744 FILE *fin = fopen(authfile, "r"); 744 FILE *fin = fopen(authfile, "r");
745 if(fin) { 745 if(fin) {
746 while(fgets(line, sizeof(line), fin)) { 746 while(fgets(line, sizeof(line), fin)) {
747 if(regexec(&preg, line, 0, 0L, 0) == 0) 747 if(regexec(&preg, line, 0, 0L, 0) == 0)
748 continue; 748 continue;
749 fputs(line, fout); 749 fputs(line, fout);
750 } 750 }
751 fclose(fin); 751 fclose(fin);
752 } 752 }
753 753
754 // append user/pass pair 754 // append user/pass pair
755 fprintf(fout, "\"%s\"\t*\t\"%s\"\n", username, password); 755 fprintf(fout, "\"%s\"\t*\t\"%s\"\n", username, password);
756 fclose(fout); 756 fclose(fout);
757 } 757 }
758 758
759 // restore umask 759 // restore umask
760 umask(old_umask); 760 umask(old_umask);
761 761
762 // free memory allocated by regcomp 762 // free memory allocated by regcomp
763 regfree(&preg); 763 regfree(&preg);
764 764
765 if(!(oldName = authFile(method, Old))) 765 if(!(oldName = authFile(method, Old)))
766 return false; 766 return false;
767 767
768 // delete old file if any 768 // delete old file if any
769 unlink(oldName); 769 unlink(oldName);
770 770
771 rename(authfile, oldName); 771 if (rename(authfile, oldName) == -1)
772 rename(newName, authfile); 772 return false;
773 if (rename(newName, authfile) == -1)
774 return false;
773 775
774 return true; 776 return true;
775} 777}
776 778
777 779
778bool Modem::removeAuthFile(Auth method) { 780bool Modem::removeAuthFile(Auth method) {
779 const char *authfile, *oldName; 781 const char *authfile, *oldName;
780 782
781 if(!(authfile = authFile(method))) 783 if(!(authfile = authFile(method)))
782 return false; 784 return false;
783 if(!(oldName = authFile(method, Old))) 785 if(!(oldName = authFile(method, Old)))
784 return false; 786 return false;
785 787
786 if(access(oldName, F_OK) == 0) { 788 if(access(oldName, F_OK) == 0) {
787 unlink(authfile); 789 unlink(authfile);
788 return (rename(oldName, authfile) == 0); 790 return (rename(oldName, authfile) == 0);
789 } else 791 } else
790 return false; 792 return false;
791} 793}
792 794
793 795
794bool Modem::setSecret(int method, const char* name, const char* password) 796bool Modem::setSecret(int method, const char* name, const char* password)
795{ 797{
796 798
797 Auth auth; 799 Auth auth;
798 if(method == AUTH_PAPCHAP) 800 if(method == AUTH_PAPCHAP)
799 return setSecret(AUTH_PAP, name, password) && 801 return setSecret(AUTH_PAP, name, password) &&
800 setSecret(AUTH_CHAP, name, password); 802 setSecret(AUTH_CHAP, name, password);
801 803
802 switch(method) { 804 switch(method) {
803 case AUTH_PAP: 805 case AUTH_PAP:
804 auth = Modem::PAP; 806 auth = Modem::PAP;
805 break; 807 break;
806 case AUTH_CHAP: 808 case AUTH_CHAP:
807 auth = Modem::CHAP; 809 auth = Modem::CHAP;
808 break; 810 break;
809 default: 811 default:
810 return false; 812 return false;
811 } 813 }
812 814
813 return createAuthFile(auth, name, password); 815 return createAuthFile(auth, name, password);
814 816
815} 817}
816 818
817bool Modem::removeSecret(int method) 819bool Modem::removeSecret(int method)
818{ 820{
819 Auth auth; 821 Auth auth;
820 822
821 switch(method) { 823 switch(method) {
822 case AUTH_PAP: 824 case AUTH_PAP:
823 auth = Modem::PAP; 825 auth = Modem::PAP;
824 break; 826 break;
825 case AUTH_CHAP: 827 case AUTH_CHAP:
826 auth = Modem::CHAP; 828 auth = Modem::CHAP;
827 break; 829 break;
828 default: 830 default:
829 return false; 831 return false;
830 } 832 }
831 return removeAuthFile( auth ); 833 return removeAuthFile( auth );
832} 834}
833 835
834int checkForInterface() 836int checkForInterface()
835{ 837{
836// I don't know if Linux needs more initialization to get the ioctl to 838// I don't know if Linux needs more initialization to get the ioctl to
837// work, pppd seems to hint it does. But BSD doesn't, and the following 839// work, pppd seems to hint it does. But BSD doesn't, and the following
838// code should compile. 840// code should compile.
839#if (defined(HAVE_NET_IF_PPP_H) || defined(HAVE_LINUX_IF_PPP_H)) && !defined(__svr4__) 841#if (defined(HAVE_NET_IF_PPP_H) || defined(HAVE_LINUX_IF_PPP_H)) && !defined(__svr4__)
840 int s, ok; 842 int s, ok;
841 struct ifreq ifr; 843 struct ifreq ifr;
842 // extern char *no_ppp_msg; 844 // extern char *no_ppp_msg;
843 845
844 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) 846 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
845 return 1; /* can't tell */ 847 return 1; /* can't tell */
846 848
847 strlcpy(ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name)); 849 strlcpy(ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name));
848 ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0; 850 ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0;
849 close(s); 851 close(s);
850 852
851 if (ok == -1) { 853 if (ok == -1) {
852// This is ifdef'd FreeBSD, because FreeBSD is the only BSD that supports 854// This is ifdef'd FreeBSD, because FreeBSD is the only BSD that supports
853// KLDs, the old LKM interface couldn't handle loading devices 855// KLDs, the old LKM interface couldn't handle loading devices
854// dynamically, and thus can't load ppp support on the fly 856// dynamically, and thus can't load ppp support on the fly
855#ifdef __FreeBSD__ 857#ifdef __FreeBSD__
856 // If we failed to load ppp support and don't have it already. 858 // If we failed to load ppp support and don't have it already.
857 if (kldload("if_ppp") == -1) { 859 if (kldload("if_ppp") == -1) {
858 return -1; 860 return -1;
859 } 861 }
860 return 0; 862 return 0;
861#else 863#else
862 return -1; 864 return -1;
863#endif 865#endif
864 } 866 }
865 return 0; 867 return 0;
866#else 868#else
867// We attempt to use the SunOS/SysVr4 method and stat /dev/ppp 869// We attempt to use the SunOS/SysVr4 method and stat /dev/ppp
868 struct stat buf; 870 struct stat buf;
869 871
870 memset(&buf, 0, sizeof(buf)); 872 memset(&buf, 0, sizeof(buf));
871 return stat("/dev/ppp", &buf); 873 return stat("/dev/ppp", &buf);
872#endif 874#endif
873} 875}
874 876
875bool Modem::execpppd(const char *arguments) { 877bool Modem::execpppd(const char *arguments) {
876 char buf[MAX_CMDLEN]; 878 char buf[MAX_CMDLEN];
877 char *args[MaxArgs]; 879 char *args[MaxArgs];
878 pid_t pgrpid; 880 pid_t pgrpid;
879 881
880 if(modemfd<0) 882 if(modemfd<0)
881 return false; 883 return false;
882 884
883 _pppdExitStatus = -1; 885 _pppdExitStatus = -1;
884 886
885 (void)::pipe( m_pppdLOG ); 887 (void)::pipe( m_pppdLOG );
886 888
887 switch(pppdPid = fork()) 889 switch(pppdPid = fork())
888 { 890 {
889 case -1: 891 case -1:
890 fprintf(stderr,"In parent: fork() failed\n"); 892 fprintf(stderr,"In parent: fork() failed\n");
891 ::close( m_pppdLOG[0] ); 893 ::close( m_pppdLOG[0] );
892 ::close( m_pppdLOG[1] ); 894 ::close( m_pppdLOG[1] );
893 return false; 895 return false;
894 break; 896 break;
895 897
896 case 0: 898 case 0:
897 // let's parse the arguments the user supplied into UNIX suitable form 899 // let's parse the arguments the user supplied into UNIX suitable form
898 // that is a list of pointers each pointing to exactly one word 900 // that is a list of pointers each pointing to exactly one word
899 strlcpy(buf, arguments); 901 strlcpy(buf, arguments);
900 parseargs(buf, args); 902 parseargs(buf, args);
901 // become a session leader and let /dev/ttySx 903 // become a session leader and let /dev/ttySx
902 // be the controlling terminal. 904 // be the controlling terminal.
903 pgrpid = setsid(); 905 pgrpid = setsid();
904#ifdef TIOCSCTTY 906#ifdef TIOCSCTTY
905 if(ioctl(modemfd, TIOCSCTTY, 0)<0) 907 if(ioctl(modemfd, TIOCSCTTY, 0)<0)
906 fprintf(stderr, "ioctl() failed.\n"); 908 fprintf(stderr, "ioctl() failed.\n");
907#elif defined (TIOCSPGRP) 909#elif defined (TIOCSPGRP)
908 if(ioctl(modemfd, TIOCSPGRP, &pgrpid)<0) 910 if(ioctl(modemfd, TIOCSPGRP, &pgrpid)<0)
909 fprintf(stderr, "ioctl() failed.\n"); 911 fprintf(stderr, "ioctl() failed.\n");
910#endif 912#endif
911 if(tcsetpgrp(modemfd, pgrpid)<0) 913 if(tcsetpgrp(modemfd, pgrpid)<0)
912 fprintf(stderr, "tcsetpgrp() failed.\n"); 914 fprintf(stderr, "tcsetpgrp() failed.\n");
913 915
914 ::close( m_pppdLOG[0] ); 916 ::close( m_pppdLOG[0] );
915 ::setenv( "LANG", "C", 1 ); // overwrite 917 ::setenv( "LANG", "C", 1 ); // overwrite
916 dup2(m_pppdLOG[1], 11 ); // for logfd 11 918 dup2(m_pppdLOG[1], 11 ); // for logfd 11
917 dup2(modemfd, 0); 919 dup2(modemfd, 0);
918 dup2(modemfd, 1); 920 dup2(modemfd, 1);
919 921
920 922
921 switch (checkForInterface()) { 923 switch (checkForInterface()) {
922 case 1: 924 case 1:
923 fprintf(stderr, "Cannot determine if kernel supports ppp.\n"); 925 fprintf(stderr, "Cannot determine if kernel supports ppp.\n");
924 break; 926 break;
925 case -1: 927 case -1:
926 fprintf(stderr, "Kernel does not support ppp, oops.\n"); 928 fprintf(stderr, "Kernel does not support ppp, oops.\n");
927 break; 929 break;
928 case 0: 930 case 0:
929 fprintf(stderr, "Kernel supports ppp alright.\n"); 931 fprintf(stderr, "Kernel supports ppp alright.\n");
930 break; 932 break;
931 } 933 }
932 934
933 execve(pppdPath(), args, 0L); 935 execve(pppdPath(), args, 0L);
934 _exit(0); 936 _exit(0);
935 break; 937 break;
936 938
937 default: 939 default:
938 odebug << "In parent: pppd pid " << pppdPid << "\n" << oendl; 940 odebug << "In parent: pppd pid " << pppdPid << "\n" << oendl;
939 close(modemfd); 941 close(modemfd);
940 942
941 ::close( m_pppdLOG[1] ); 943 ::close( m_pppdLOG[1] );
942 // set it to nonblocking io 944 // set it to nonblocking io
943 int flag = ::fcntl( m_pppdLOG[0], F_GETFL ); 945 int flag = ::fcntl( m_pppdLOG[0], F_GETFL );
944 946
945 if ( !(flag & O_NONBLOCK) ) { 947 if ( !(flag & O_NONBLOCK) ) {
946 odebug << "Setting nonblocking io" << oendl; 948 odebug << "Setting nonblocking io" << oendl;
947 flag |= O_NONBLOCK; 949 flag |= O_NONBLOCK;
948 ::fcntl(m_pppdLOG[0], F_SETFL, flag ); 950 ::fcntl(m_pppdLOG[0], F_SETFL, flag );
949 } 951 }
950 952
951 delete m_modemDebug; 953 delete m_modemDebug;
952 m_modemDebug = new QSocketNotifier(m_pppdLOG[0], QSocketNotifier::Read, this ); 954 m_modemDebug = new QSocketNotifier(m_pppdLOG[0], QSocketNotifier::Read, this );
953 connect(m_modemDebug, SIGNAL(activated(int) ), 955 connect(m_modemDebug, SIGNAL(activated(int) ),
954 this, SLOT(slotModemDebug(int) ) ); 956 this, SLOT(slotModemDebug(int) ) );
955 957
956 modemfd = -1; 958 modemfd = -1;
957 m_pppdDev = QString::fromLatin1("ppp0"); 959 m_pppdDev = QString::fromLatin1("ppp0");
958 return true; 960 return true;
959 break; 961 break;
960 } 962 }
961} 963}
962 964
963 965
964bool Modem::killpppd() { 966bool Modem::killpppd() {
965 odebug << "In killpppd and pid is " << pppdPid << "" << oendl; 967 odebug << "In killpppd and pid is " << pppdPid << "" << oendl;
966 if(pppdPid > 0) { 968 if(pppdPid > 0) {
967 delete m_modemDebug; 969 delete m_modemDebug;
968 m_modemDebug = 0; 970 m_modemDebug = 0;
969 odebug << "In killpppd(): Sending SIGTERM to " << pppdPid << "\n" << oendl; 971 odebug << "In killpppd(): Sending SIGTERM to " << pppdPid << "\n" << oendl;
970 if(kill(pppdPid, SIGTERM) < 0) { 972 if(kill(pppdPid, SIGTERM) < 0) {
971 odebug << "Error terminating " << pppdPid << ". Sending SIGKILL\n" << oendl; 973 odebug << "Error terminating " << pppdPid << ". Sending SIGKILL\n" << oendl;
972 if(kill(pppdPid, SIGKILL) < 0) { 974 if(kill(pppdPid, SIGKILL) < 0) {
973 odebug << "Error killing " << pppdPid << "\n" << oendl; 975 odebug << "Error killing " << pppdPid << "\n" << oendl;
974 return false; 976 return false;
975 } 977 }
976 } 978 }
977 } 979 }
978 return true; 980 return true;
979} 981}
980 982
981 983
982void Modem::parseargs(char* buf, char** args) { 984void Modem::parseargs(char* buf, char** args) {
983 int nargs = 0; 985 int nargs = 0;
984 int quotes; 986 int quotes;
985 987
986 while(nargs < MaxArgs-1 && *buf != '\0') { 988 while(nargs < MaxArgs-1 && *buf != '\0') {
987 989
988 quotes = 0; 990 quotes = 0;
989 991
990 // Strip whitespace. Use nulls, so that the previous argument is 992 // Strip whitespace. Use nulls, so that the previous argument is
991 // terminated automatically. 993 // terminated automatically.
992 994
993 while ((*buf == ' ' ) || (*buf == '\t' ) || (*buf == '\n' ) ) 995 while ((*buf == ' ' ) || (*buf == '\t' ) || (*buf == '\n' ) )
994 *buf++ = '\0'; 996 *buf++ = '\0';
995 997
996 // detect begin of quoted argument 998 // detect begin of quoted argument
997 if (*buf == '"' || *buf == '\'') { 999 if (*buf == '"' || *buf == '\'') {
998 quotes = *buf; 1000 quotes = *buf;
999 *buf++ = '\0'; 1001 *buf++ = '\0';
1000 } 1002 }
1001 1003
1002 // save the argument 1004 // save the argument
1003 if(*buf != '\0') { 1005 if(*buf != '\0') {
1004 *args++ = buf; 1006 *args++ = buf;
1005 nargs++; 1007 nargs++;
1006 } 1008 }
1007 1009
1008 if (!quotes) 1010 if (!quotes)
1009 while ((*buf != '\0') && (*buf != '\n') && 1011 while ((*buf != '\0') && (*buf != '\n') &&
1010 (*buf != '\t') && (*buf != ' ')) 1012 (*buf != '\t') && (*buf != ' '))
1011 buf++; 1013 buf++;
1012 else { 1014 else {
1013 while ((*buf != '\0') && (*buf != quotes)) 1015 while ((*buf != '\0') && (*buf != quotes))
1014 buf++; 1016 buf++;
1015 *buf++ = '\0'; 1017 *buf++ = '\0';
1016 } 1018 }
1017 } 1019 }
1018 1020
1019 *args = 0L; 1021 *args = 0L;
1020} 1022}
1021 1023
1022bool Modem::execPPPDaemon(const QString & arguments) 1024bool Modem::execPPPDaemon(const QString & arguments)
1023{ 1025{
1024 if(execpppd(arguments)) { 1026 if(execpppd(arguments)) {
1025 _pppdata->setpppdRunning(true); 1027 _pppdata->setpppdRunning(true);
1026 return true; 1028 return true;
1027 } else 1029 } else
1028 return false; 1030 return false;
1029} 1031}
1030 1032
1031void Modem::killPPPDaemon() 1033void Modem::killPPPDaemon()
1032{ 1034{
1033 _pppdata->setpppdRunning(false); 1035 _pppdata->setpppdRunning(false);
1034 killpppd(); 1036 killpppd();
1035} 1037}
1036 1038
1037int Modem::pppdExitStatus() 1039int Modem::pppdExitStatus()
1038{ 1040{
1039 return _pppdExitStatus; 1041 return _pppdExitStatus;
1040} 1042}
1041 1043
1042int Modem::openResolv(int flags) 1044int Modem::openResolv(int flags)
1043{ 1045{
1044 int fd; 1046 int fd;
1045 if ((fd = open(_PATH_RESCONF, flags)) == -1) { 1047 if ((fd = open(_PATH_RESCONF, flags)) == -1) {
1046 odebug << "error opening resolv.conf!" << oendl; 1048 odebug << "error opening resolv.conf!" << oendl;
1047 fd = open(DEVNULL, O_RDONLY); 1049 fd = open(DEVNULL, O_RDONLY);
1048 } 1050 }
1049 return fd; 1051 return fd;
1050} 1052}
1051 1053
1052bool Modem::setHostname(const QString & name) 1054bool Modem::setHostname(const QString & name)
1053{ 1055{
1054 return sethostname(name, name.length()) == 0; 1056 return sethostname(name, name.length()) == 0;
1055} 1057}
1056 1058
1057QString Modem::pppDevice()const { 1059QString Modem::pppDevice()const {
1058 return m_pppdDev; 1060 return m_pppdDev;
1059} 1061}
1060void Modem::setPPPDevice( const QString& dev ) { 1062void Modem::setPPPDevice( const QString& dev ) {
1061 m_pppdDev = dev; 1063 m_pppdDev = dev;
1062} 1064}
1063pid_t Modem::pppPID()const { 1065pid_t Modem::pppPID()const {
1064 return pppdPid; 1066 return pppdPid;
1065} 1067}
1066void Modem::setPPPDPid( pid_t pid ) { 1068void Modem::setPPPDPid( pid_t pid ) {
1067 odebug << "Modem setting pid" << oendl; 1069 odebug << "Modem setting pid" << oendl;
1068 _pppdExitStatus = -1; 1070 _pppdExitStatus = -1;
1069 pppdPid = pid; 1071 pppdPid = pid;
1070 modemfd = -1; 1072 modemfd = -1;
1071} 1073}
1072void Modem::slotModemDebug(int fd) { 1074void Modem::slotModemDebug(int fd) {
1073 char buf[2049]; 1075 char buf[2049];
1074 int len; 1076 int len;
1075 1077
1076 // read in pppd data look for Using interface 1078 // read in pppd data look for Using interface
1077 // then read the interface 1079 // then read the interface
1078 // we limit to 10 device now 0-9 1080 // we limit to 10 device now 0-9
1079 if((len = ::read(fd, buf, 2048)) > 0) { 1081 if((len = ::read(fd, buf, 2048)) > 0) {
1080 buf[len+1] = '\0'; 1082 buf[len+1] = '\0';
1081 char *found; 1083 char *found;
1082 if ( (found = ::strstr(buf, "Using interface ") ) ) { 1084 if ( (found = ::strstr(buf, "Using interface ") ) ) {
1083 found += 16; 1085 found += 16;
1084 m_pppdDev = QString::fromLatin1(found, 5 ); 1086 m_pppdDev = QString::fromLatin1(found, 5 );
1085 m_pppdDev = m_pppdDev.simplifyWhiteSpace(); 1087 m_pppdDev = m_pppdDev.simplifyWhiteSpace();
1086 } 1088 }
1087 } 1089 }
1088} 1090}