author | kergoth <kergoth> | 2003-08-09 16:24:58 (UTC) |
---|---|---|
committer | kergoth <kergoth> | 2003-08-09 16:24:58 (UTC) |
commit | e16d333ec2e8509fc665921ca106c25325bae9e0 (patch) (side-by-side diff) | |
tree | 9e9068190a15bc9b2a52ab33b40881128f732c0e | |
parent | 1c58d1407f9584fedcdae390a04e2b37e5853361 (diff) | |
download | opie-e16d333ec2e8509fc665921ca106c25325bae9e0.zip opie-e16d333ec2e8509fc665921ca106c25325bae9e0.tar.gz opie-e16d333ec2e8509fc665921ca106c25325bae9e0.tar.bz2 |
Merge from BRANCH_1_0
96 files changed, 1186 insertions, 328 deletions
diff --git a/noncore/applets/networkapplet/opie-networkapplet.control b/noncore/applets/networkapplet/opie-networkapplet.control index ae07eb3..f4ee7be 100644 --- a/noncore/applets/networkapplet/opie-networkapplet.control +++ b/noncore/applets/networkapplet/opie-networkapplet.control @@ -1,10 +1,10 @@ Package: opie-networkapplet Files: plugins/applets/libnetworkapplet.so* pics/networkapplet Priority: optional Section: opie/system Maintainer: Michael 'Mickey' Lauer <mickeyl@handhelds.org> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal, libopie2 (1.8.1), opie-networksettings Description: Network Applet A taskbar applet for controlling network interfaces +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/applets/notesapplet/opie-notesapplet.control b/noncore/applets/notesapplet/opie-notesapplet.control index da02b44..f19b964 100644 --- a/noncore/applets/notesapplet/opie-notesapplet.control +++ b/noncore/applets/notesapplet/opie-notesapplet.control @@ -1,10 +1,10 @@ Package: opie-notesapplet Files: plugins/applets/libnotesapplet.so* Priority: optional Section: opie/system Maintainer: L. J. Potter <ljp@llornkcor.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal -Description: Screenshot Applet +Description: Notes Applet A simple taskbar applet for making quick notes. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/applets/wirelessapplet/opie-wirelessapplet.control b/noncore/applets/wirelessapplet/opie-wirelessapplet.control index ac7fad2..6dfa214 100644 --- a/noncore/applets/wirelessapplet/opie-wirelessapplet.control +++ b/noncore/applets/wirelessapplet/opie-wirelessapplet.control @@ -1,10 +1,10 @@ Package: opie-wirelessapplet Files: plugins/applets/libwirelessapplet.so* Priority: optional Section: opie/system Maintainer: Michael 'Mickey' Lauer <mickey@tm.informatik.uni-frankfurt.de> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION.1 Depends: task-opie-minimal Description: Wireless Applet A wireless network card status taskbar applet for the Opie environment +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/apps/odict/configdlg.cpp b/noncore/apps/odict/configdlg.cpp index 400298d..2103df9 100644 --- a/noncore/apps/odict/configdlg.cpp +++ b/noncore/apps/odict/configdlg.cpp @@ -1,117 +1,107 @@ /*************************************************************************** application: : ODict begin : December 2002 copyright : ( C ) 2002, 2003 by Carsten Niehaus email : cniehaus@handhelds.org **************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * ( at your option ) any later version. * * * **************************************************************************/ #include "configdlg.h" #include "searchmethoddlg.h" #include <qdialog.h> #include <qpe/config.h> #include <qlayout.h> #include <qhbox.h> #include <qvbox.h> #include <qlabel.h> #include <qlistview.h> #include <qpushbutton.h> #include <qlineedit.h> #include <qstringlist.h> -#include <opie/otabwidget.h> - ConfigDlg::ConfigDlg(QWidget *parent, const char *name, bool modal) : QDialog(parent, name, modal) { setCaption( tr( "Options" ) ); QVBoxLayout *vbox_layout = new QVBoxLayout( this ); - tab = new OTabWidget( this, "OTabWidget_tab", OTabWidget::Global, OTabWidget::Bottom ); - vbox_layout->addWidget( tab ); - - /*general settings*/ - settings_tab = new QWidget( tab , "settings_tab" ); - - /*searchmethods*/ - search_tab = new QWidget( tab , "search_tab" ); + search_tab = new QWidget( this , "search_tab" ); QVBoxLayout *vbox_layout_searchtab = new QVBoxLayout( search_tab, 4 , 4 ,"blah" ); QHBox *hbox = new QHBox( search_tab ); list = new QListView( hbox ); list->addColumn( tr( "Searchmethod" ) ); loadSearchMethodNames(); QVBox *vbox = new QVBox( hbox ); - new_button = new QPushButton( "New" , vbox ); - change_button = new QPushButton( "Change" , vbox ); - delete_button = new QPushButton( "Delete" , vbox ); + new_button = new QPushButton( tr( "New" ) , vbox ); + change_button = new QPushButton( tr( "Change" ) , vbox ); + delete_button = new QPushButton( tr( "Delete" ) , vbox ); connect( new_button, SIGNAL( clicked() ), this, SLOT( slotNewMethod() ) ); connect( change_button, SIGNAL( clicked() ), this, SLOT( slotChangeMethod() )); connect( delete_button, SIGNAL( clicked() ), this, SLOT( slotDeleteMethod() )); vbox_layout_searchtab->addWidget( hbox ); - /*add the tabs and maximize*/ - tab->addTab( settings_tab, "pass", tr( "General Settings" ) ); - tab->addTab( search_tab, "zoom", tr( "Searchmethods" ) ); + vbox_layout->addWidget( search_tab ); + showMaximized(); } void ConfigDlg::slotNewMethod() { SearchMethodDlg dlg( this, "SearchMethodDlg", true ); if ( dlg.exec() == QDialog::Accepted ) { dlg.saveItem(); QListViewItem *item = new QListViewItem( list ); item->setText( 0 , dlg.nameLE->text() ); } } void ConfigDlg::slotChangeMethod() { if ( list->selectedItem() ) { SearchMethodDlg dlg( this, "SearchMethodDlg", true, list->selectedItem()->text( 0 ) ); if ( dlg.exec() == QDialog::Accepted ) { dlg.saveItem(); QListViewItem *item = list->selectedItem(); item->setText( 0 , dlg.nameLE->text() ); } } } void ConfigDlg::slotDeleteMethod() { if ( list->selectedItem() ) { Config cfg ( "odict" ); cfg.setGroup( "Method_"+list->selectedItem()->text(0) ); cfg.clearGroup(); //FIXME: this only removes the entries but not the group itself list->takeItem( list->selectedItem() ); } } void ConfigDlg::loadSearchMethodNames() { Config cfg( "odict" ); QStringList groupListCfg = cfg.groupList().grep( "Method_" ); for ( QStringList::Iterator it = groupListCfg.begin() ; it != groupListCfg.end() ; ++it ) { QListViewItem *item = new QListViewItem( list ); cfg.setGroup( *it ); item->setText( 0 , cfg.readEntry( "Name" ) ); } } diff --git a/noncore/apps/odict/configdlg.h b/noncore/apps/odict/configdlg.h index e3ef3ce..6c85989 100644 --- a/noncore/apps/odict/configdlg.h +++ b/noncore/apps/odict/configdlg.h @@ -1,36 +1,34 @@ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * ( at your option ) any later version. * * * **************************************************************************/ class QWidget; -class OTabWidget; class QListView; class QPushButton; #include <qdialog.h> class ConfigDlg : public QDialog { Q_OBJECT public: ConfigDlg(QWidget *parent, const char *name, bool modal=FALSE ); private: - OTabWidget *tab; QWidget *settings_tab, *search_tab; QListView *list; QPushButton *new_button, *change_button, *delete_button; void loadSearchMethodNames(); private slots: void slotNewMethod(); void slotChangeMethod(); void slotDeleteMethod(); }; diff --git a/noncore/apps/odict/odict.cpp b/noncore/apps/odict/odict.cpp index 2028701..010545e 100644 --- a/noncore/apps/odict/odict.cpp +++ b/noncore/apps/odict/odict.cpp @@ -1,230 +1,220 @@ /*************************************************************************** application: : ODict begin : December 2002 copyright : ( C ) 2002, 2003 by Carsten Niehaus email : cniehaus@handhelds.org **************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * ( at your option ) any later version. * * * **************************************************************************/ #include "odict.h" #include "configdlg.h" #include "dingwidget.h" #include <qlayout.h> #include <qpopupmenu.h> #include <qmenubar.h> #include <qmessagebox.h> #include <qhbox.h> #include <qvbox.h> #include <qlabel.h> #include <qpushbutton.h> #include <qlineedit.h> #include <qmainwindow.h> #include <qstring.h> #include <qaction.h> #include <qtextbrowser.h> #include <qcombobox.h> #include <qpe/resource.h> #include <qpe/config.h> ODict::ODict() : QMainWindow() { activated_name = QString::null; vbox = new QVBox( this ); - setCaption( tr( "OPIE-Dictionary" ) ); + setCaption( tr( "Opie-Dictionary" ) ); setupMenus(); QHBox *hbox = new QHBox( vbox ); QLabel* query_label = new QLabel( tr( "Query:" ) , hbox ); query_label->show(); query_le = new QLineEdit( hbox ); query_co = new QComboBox( hbox ); connect( query_co , SIGNAL( activated(const QString&) ), this, SLOT( slotMethodChanged(const QString&) ) ); ok_button = new QPushButton( tr( "&Ok" ), hbox ); connect( ok_button, SIGNAL( released() ), this, SLOT( slotStartQuery() ) ); top_name = new QLabel( vbox ); top_name->setAlignment( AlignHCenter ); browser_top = new QTextBrowser( vbox ); bottom_name = new QLabel( vbox ); bottom_name->setAlignment( AlignHCenter ); browser_bottom = new QTextBrowser( vbox ); ding = new DingWidget(); loadConfig(); setCentralWidget( vbox ); } void ODict::loadConfig() { /* * the name of the last used dictionary */ QString lastname; Config cfg ( "odict" ); cfg.setGroup( "generalsettings" ); casesens = cfg.readEntry( "casesens" ).toInt(); - regexp = cfg.readEntry( "regexp" ).toInt(); QString lastDict = cfg.readEntry( "lastdict" ); int i = 0, e = 0; QStringList groupListCfg = cfg.groupList().grep( "Method_" ); query_co->clear(); for ( QStringList::Iterator it = groupListCfg.begin() ; it != groupListCfg.end() ; ++it ) { QString name; cfg.setGroup( *it ); name = cfg.readEntry( "Name" ); query_co->insertItem( name ); /* * this check is to look up what dictionary has been used the * last time */ if ( lastDict == name ) { e = i; lastname = name; } i++; } /* * now set the two names of the dictionary and the correct QComboBox-Entry */ lookupLanguageNames( lastname ); ding->loadDict( lastname ); ding->loadValues(); query_co->setCurrentItem( e ); top_name->setText( top_name_content ); bottom_name->setText( bottom_name_content ); } void ODict::lookupLanguageNames( QString dictname ) { Config cfg ( "odict" ); cfg.setGroup( "Method_"+dictname ); top_name_content = cfg.readEntry( "Lang1" ); bottom_name_content = cfg.readEntry( "Lang2" ); } void ODict::saveConfig() { Config cfg ( "odict" ); cfg.setGroup( "generalsettings" ); cfg.writeEntry( "casesens" , casesens ); - cfg.writeEntry( "regexp" , regexp ); cfg.writeEntry( "lastdict" , query_co->currentText() ); } void ODict::slotStartQuery() { QString querystring = query_le->text(); if ( !querystring.isEmpty() ) { /* * if the user has not yet defined a dictionary */ if ( !query_co->currentText() ) { switch ( QMessageBox::information( this, tr( "OPIE-Dictionary" ), tr( "No dictionary defined" ), tr( "&Define one" ), tr( "&Cancel" ), 0, // Define a dict 1 ) ) // Cancel choosen { case 0: slotSettings(); break; case 1: // stop here return; } } /* * ok, the user has defined a dict */ ding->setCaseSensitive( casesens ); BroswerContent test = ding->setText( querystring ); browser_top->setText( test.top ); browser_bottom->setText( test.bottom ); } } void ODict::slotSettings() { ConfigDlg dlg( this, "Config" , true); if ( dlg.exec() == QDialog::Accepted ) saveConfig(); } void ODict::slotSetParameter( int count ) { if ( count == 0 ) { if ( casesens ) casesens = false; else casesens = true; } - if ( count == 1 ) - { - if ( regexp ) - regexp = false; - else - regexp = true; - } saveConfig(); } void ODict::slotMethodChanged( const QString& methodnumber ) { activated_name = methodnumber; if ( activated_name != ding->loadedDict() ) { ding->loadDict(activated_name); lookupLanguageNames( activated_name ); top_name->setText( top_name_content ); bottom_name->setText( bottom_name_content ); } } void ODict::setupMenus() { menu = new QMenuBar( this ); settings = new QPopupMenu( menu ); setting_a = new QAction(tr( "Configuration" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect( setting_a, SIGNAL( activated() ), this, SLOT( slotSettings() ) ); setting_a->addTo( settings ); setting_b = new QAction(tr( "Searchmethods" ), Resource::loadPixmap( "edit" ), QString::null, 0, this, 0 ); parameter = new QPopupMenu( menu ); connect( parameter, SIGNAL( activated( int ) ), this, SLOT( slotSetParameter( int ) ) ); parameter->insertItem( tr( "C&ase sensitive" ), 0 ,0 ); - parameter->insertItem( tr( "Allow ®. expressions" ), 2 ); parameter->insertSeparator(); menu->insertItem( tr( "Settings" ) , settings ); menu->insertItem( tr( "Parameter" ) , parameter ); } diff --git a/noncore/apps/odict/odict.h b/noncore/apps/odict/odict.h index 9c037ea..be2a532 100644 --- a/noncore/apps/odict/odict.h +++ b/noncore/apps/odict/odict.h @@ -1,70 +1,70 @@ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * ( at your option ) any later version. * * * **************************************************************************/ #include <qmainwindow.h> class QLabel; class QVBox; class QPopupMenu; class QMenuBar; class QHBox; class QPushButton; class QLineEdit; class QAction; class QVBoxLayout; class QActionGroup; class DingWidget; class QTextBrowser; class QComboBox; class DingWidget; class ODict : public QMainWindow { Q_OBJECT public: ODict(); QVBox *vbox; QTextBrowser *browser_top, *browser_bottom; DingWidget *ding; private: QPopupMenu *help, *settings, *parameter; QMenuBar *menu; QHBox *hbox; QLineEdit *query_le; QComboBox *query_co; QPushButton *ok_button; QVBoxLayout *vbox_layout; QAction *setting_a, *setting_b; void setupMenus(); - bool casesens, completewords, regexp; + bool casesens, completewords; void loadConfig(); void saveConfig(); QString activated_name; QLabel *bottom_name, *top_name; QString top_name_content, bottom_name_content; void lookupLanguageNames( QString ); private slots: void slotStartQuery(); void slotSettings(); void slotSetParameter( int ); void slotMethodChanged( const QString& ); }; diff --git a/noncore/apps/odict/odict.pro b/noncore/apps/odict/odict.pro index 427a5c6..82f6a41 100644 --- a/noncore/apps/odict/odict.pro +++ b/noncore/apps/odict/odict.pro @@ -1,41 +1,41 @@ TEMPLATE = app CONFIG = qt warn_on debug #CONFIG = qt warn_on release HEADERS = odict.h \ searchmethoddlg.h \ configdlg.h \ - dingwidget.h \ + dingwidget.h SOURCES = main.cpp \ odict.cpp \ searchmethoddlg.cpp \ configdlg.cpp \ dingwidget.cpp INCLUDEPATH += $(OPIEDIR)/include DEPENDPATH += $(OPIEDIR)/include LIBS += -lqpe -lstdc++ -lopie TARGET = odict DESTDIR = $(OPIEDIR)/bin TRANSLATIONS = ../../../i18n/de/odict.ts \ ../../../i18n/nl/odict.ts \ ../../../i18n/xx/odict.ts \ ../../../i18n/en/odict.ts \ ../../../i18n/es/odict.ts \ ../../../i18n/fr/odict.ts \ ../../../i18n/hu/odict.ts \ ../../../i18n/ja/odict.ts \ ../../../i18n/ko/odict.ts \ ../../../i18n/no/odict.ts \ ../../../i18n/pl/odict.ts \ ../../../i18n/pt/odict.ts \ ../../../i18n/pt_BR/odict.ts \ ../../../i18n/sl/odict.ts \ ../../../i18n/zh_CN/odict.ts \ ../../../i18n/zh_TW/odict.ts \ ../../../i18n/it/odict.ts \ ../../../i18n/da/odict.ts include ( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/odict/opie-odict.control b/noncore/apps/odict/opie-odict.control index 2fa731f..f684716 100644 --- a/noncore/apps/odict/opie-odict.control +++ b/noncore/apps/odict/opie-odict.control @@ -1,10 +1,10 @@ Package: opie-odict Files: bin/odict apps/Applications/odict.desktop pics/odict/odict.png Priority: optional Section: applications Maintainer: Carsten Niehaus <cniehaus@handhelds.org> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Dictionarylookupprogram Look up words :) +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/apps/tableviewer/db/xmlsource.cpp b/noncore/apps/tableviewer/db/xmlsource.cpp index 7418a85..94fec36 100644 --- a/noncore/apps/tableviewer/db/xmlsource.cpp +++ b/noncore/apps/tableviewer/db/xmlsource.cpp @@ -1,295 +1,297 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "xmlsource.h" #include <qdict.h> #include <stdlib.h> #include <qtextstream.h> +#include "../xmlencodeattr.h" + DBXml::DBXml(DBStore *d) { dstore = d; } QString DBXml::type() { return "xml"; } bool DBXml::openSource(QIODevice *inDev) { bool ok; DBXmlHandler h(dstore); QTextStream tsIn(inDev); QXmlInputSource source(tsIn); QXmlSimpleReader reader; reader.setContentHandler(&h); reader.setErrorHandler(&h); ok = reader.parse(source); return ok; } bool DBXml::saveSource(QIODevice *outDev) { int i; DataElem *elem; KeyList *k; QTextStream outstream(outDev); outstream << "<database name=\"" << dstore->getName() << "\">" << endl; outstream << "<header>" << endl; k = dstore->getKeys(); KeyListIterator it(*k); while(it.current()) { if (!it.current()->delFlag()) { outstream << "<key name=\"KEYID" << it.currentKey() << "\" "; outstream << "type=\"" << TVVariant::typeToName(it.current()->type()) << "\">"; - outstream << it.current()->name() << "</key>" << endl; + outstream << encodeAttr(it.current()->name()) << "</key>" << endl; } ++it; } outstream << "</header>" << endl; dstore->first(); do { elem = dstore->getCurrentData(); if (!elem) break; outstream << "<record>" << endl; it.toFirst(); while (it.current()) { i = it.currentKey(); if (elem->hasValidValue(i)) { outstream << "<KEYID" << i << ">"; if (dstore->getKeyType(i) == TVVariant::Date) { // dates in files are different from displayed dates QDate date = elem->getField(i).toDate(); outstream << date.day() << "/" << date.month() << "/" << date.year(); } else { - outstream << elem->toQString(i); + outstream << encodeAttr(elem->toQString(i)); } outstream << "</KEYID" << i << ">" << endl; } ++it; } outstream << "</record>" << endl; } while(dstore->next()); outstream << "</database>" << endl; return TRUE; } DBXml::~DBXml() {} /*! \class DBXmlHandler \brief An Xml parser for flat tables. An xml parser for parsing the files used by the table viewer application. The format of the xml files can be found at the front of the file dataparser.h */ /*! Constructs a new DBXmlHandler, and sets that the table should be constructed in the DBStore pointed to by ds. */ DBXmlHandler::DBXmlHandler(DBStore *ds) { data_store = ds; current_keyrep = 0; } /*! Destroys the DBXmlHandler */ DBXmlHandler::~DBXmlHandler() { } QString DBXmlHandler::errorProtocol() { qWarning("Error reading file"); return errorProt; } bool DBXmlHandler::startDocument() { errorProt = ""; state = StateInit; return TRUE; } bool DBXmlHandler::startElement(const QString&, const QString&, const QString& qName, const QXmlAttributes& atts) { if (state == StateInit && qName == "database") { // First thing it expects is a <document name="..."> tag state = StateDocument; data_store->setName(atts.value("name")); return TRUE; } if (state == StateDocument && qName == "header") { state = StateHeader; if (current_keyrep) delete current_keyrep; current_keyrep = new KeyList(); return TRUE; } if (state == StateHeader && qName == "key") { /* Ok, adding a new key to our KeyList TODO */ state = StateKey; last_key_type = TVVariant::String; key = atts.value("name"); if (key.isEmpty()) { qWarning("empty key name"); return FALSE; } if(!atts.value("type").isEmpty()) last_key_type = TVVariant::nameToType(atts.value("type")); return TRUE; } if (state == StateDocument && qName == "record") { state = StateRecord; current_data = new DataElem(data_store); // Now expecting a <record> tag return TRUE; } if (state == StateRecord) { state = StateField; /* the qName is the name of a key */ if (!keyIndexList[qName]) { /* invalid key, we failed */ qWarning("Invalid key in record"); return FALSE; } keyIndex = *keyIndexList[qName]; return TRUE; } qWarning("Unable to determine tag type"); return FALSE; } bool DBXmlHandler::endElement(const QString&, const QString&, const QString& qName) { switch(state) { case StateField: // TODO checks 'could' be done of the popped value state = StateRecord; break; case StateKey: // TODO checks 'could' be done of the popped value state = StateHeader; break; case StateHeader: data_store->setKeys(current_keyrep); state = StateDocument; break; case StateRecord: data_store->addItem(current_data); state = StateDocument; break; case StateDocument: // we are done... break; default: // should only get a 'endElement' from one of the above states. qWarning("Invalid end tag"); return FALSE; break; } return TRUE; } bool DBXmlHandler::characters(const QString& ch) { // this is where the 'between tag' stuff happens. // e.g. the stuff between tags. QString ch_simplified = ch.simplifyWhiteSpace(); if (ch_simplified.isEmpty()) return TRUE; if (state == StateKey) { int *tmp_val = new int; /* We just grabbed the display name of a key */ *tmp_val = current_keyrep->addKey(ch_simplified, last_key_type); keyIndexList.insert(key, tmp_val); return TRUE; } if (state == StateField) { /* Ok, need to add data here */ current_data->setField(keyIndex, ch_simplified); return TRUE; } qWarning("Junk characters found... ignored"); return TRUE; } QString DBXmlHandler::errorString() { return "the document is not in the expected file format"; } bool DBXmlHandler::warning(const QXmlParseException& exception) { errorProt += QString("warning parsing error: %1 in line %2, column %3\n" ) .arg(exception.message()) .arg(exception.lineNumber()) .arg(exception.columnNumber()); qWarning(errorProt); return QXmlDefaultHandler::fatalError(exception); } bool DBXmlHandler::error(const QXmlParseException& exception) { errorProt += QString("error parsing error: %1 in line %2, column %3\n" ) .arg(exception.message()) .arg(exception.lineNumber()) .arg(exception.columnNumber()); qWarning(errorProt); return QXmlDefaultHandler::fatalError(exception); } bool DBXmlHandler::fatalError(const QXmlParseException& exception) { errorProt += QString("fatal parsing error: %1 in line %2, column %3\n" ) .arg(exception.message()) .arg(exception.lineNumber()) .arg(exception.columnNumber()); qWarning(errorProt); return QXmlDefaultHandler::fatalError(exception); } diff --git a/noncore/apps/tableviewer/tableviewer.pro b/noncore/apps/tableviewer/tableviewer.pro index 6f73400..f047e0b 100644 --- a/noncore/apps/tableviewer/tableviewer.pro +++ b/noncore/apps/tableviewer/tableviewer.pro @@ -1,58 +1,60 @@ TEMPLATE = app CONFIG = qt warn_on debug DESTDIR = $(OPIEDIR)/bin SUBDIRS = db ui HEADERS = tableviewer.h \ + xmlencodeattr.h \ ui/commonwidgets.h \ ui/tvbrowseview.h \ ui/tvlistview.h \ ui/tvfilterview.h \ ui/tveditview.h \ ui/browsekeyentry.h \ ui/filterkeyentry.h \ ui/tvkeyedit.h \ db/datacache.h \ db/common.h \ db/xmlsource.h \ db/csvsource.h SOURCES = main.cpp \ tableviewer.cpp \ + xmlencodeattr.cpp \ ui/commonwidgets.cpp \ ui/tvbrowseview.cpp \ ui/tvfilterview.cpp \ ui/browsekeyentry.cpp \ ui/filterkeyentry.cpp \ ui/tvlistview.cpp \ ui/tveditview.cpp \ ui/tvkeyedit.cpp \ db/datacache.cpp \ db/xmlsource.cpp \ db/csvsource.cpp \ db/common.cpp INTERFACES = ui/tvkeyedit_gen.ui TARGET = tableviewer INCLUDEPATH += $(OPIEDIR)/include DEPENDPATH += $(OPIEDIR)/include LIBS += -lqpe TRANSLATIONS = ../../../i18n/de/tableviewer.ts \ ../../../i18n/nl/tableviewer.ts \ ../../../i18n/da/tableviewer.ts \ ../../../i18n/xx/tableviewer.ts \ ../../../i18n/en/tableviewer.ts \ ../../../i18n/es/tableviewer.ts \ ../../../i18n/fr/tableviewer.ts \ ../../../i18n/hu/tableviewer.ts \ ../../../i18n/ja/tableviewer.ts \ ../../../i18n/ko/tableviewer.ts \ ../../../i18n/no/tableviewer.ts \ ../../../i18n/pl/tableviewer.ts \ ../../../i18n/pt/tableviewer.ts \ ../../../i18n/pt_BR/tableviewer.ts \ ../../../i18n/sl/tableviewer.ts \ ../../../i18n/zh_CN/tableviewer.ts \ ../../../i18n/zh_TW/tableviewer.ts include ( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/tableviewer/ui/tvbrowseview.cpp b/noncore/apps/tableviewer/ui/tvbrowseview.cpp index f5f2555..22bac55 100644 --- a/noncore/apps/tableviewer/ui/tvbrowseview.cpp +++ b/noncore/apps/tableviewer/ui/tvbrowseview.cpp @@ -1,122 +1,123 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "tvbrowseview.h" #include "browsekeyentry.h" #include <qtoolbutton.h> #include <qtextview.h> #include <qtextbrowser.h> #include <qlayout.h> +#include "../xmlencodeattr.h" /*! \class TVBrowseView \brief The widget describing how to draw the browse view user interface This widget allows for the user to browse through the table, one element at a time, or search on a single key. Its main goal is to show a single element in a readable format and make it easy for the user to rapidly find specific elements in the table. */ /*! Constructs a new TVBrowseView widget */ TVBrowseView::TVBrowseView(TableState *t, QWidget* parent, const char *name, WFlags fl ) { if (!name) setName("BrowseView"); // setSizePolicy(QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding, 0, 0, sizePolicy().hasHeightForWidth() ) ); QVBoxLayout *vlayout = new QVBoxLayout(this); textViewDisplay = new QTextBrowser(this, "textViewDisplay"); vlayout->addWidget( textViewDisplay ); keyEntry = new TVBrowseKeyEntry(this, "keyEntry"); vlayout->addWidget( keyEntry ); /* connect the signals down */ connect(keyEntry, SIGNAL(searchOnKey(int, TVVariant)), this, SIGNAL(searchOnKey(int, TVVariant))); connect(keyEntry, SIGNAL(sortChanged(int)), this, SIGNAL(sortChanged(int))); ts = t; keyEntry->setTableState(t); } /*! Destroys the TVBrowseView widget */ TVBrowseView::~TVBrowseView() { } void TVBrowseView::rebuildData() { if(!ts) return; if(!ts->current_elem) { /* also disable buttons */ textViewDisplay->setText(""); return; } setDisplayText(ts->current_elem); } /* Reset to initial state */ void TVBrowseView::reset() { textViewDisplay->setText(""); keyEntry->reset(); } /*! sets the data element to be displayed to element */ void TVBrowseView::setDisplayText(const DataElem *element) { QString rep = ""; KeyListIterator it(*ts->kRep); while (it.current()) { if (element->hasValidValue(it.currentKey())) { if(it.currentKey() == ts->current_column) { rep += "<A name=\"ckey\"></A><B><FONT COLOR=#FF0000>" - + it.current()->name() + + encodeAttr(it.current()->name()) + ":</FONT></B> "; } else { - rep += "<B>" + it.current()->name() + ":</B> "; + rep += "<B>" + encodeAttr(it.current()->name()) + ":</B> "; } - rep += element->toQString(it.currentKey()) + "<BR>"; + rep += encodeAttr(element->toQString(it.currentKey())) + "<BR>"; } ++it; } textViewDisplay->setText(rep); textViewDisplay->scrollToAnchor("ckey"); } void TVBrowseView::rebuildKeys() { keyEntry->rebuildKeys(); } diff --git a/noncore/apps/tableviewer/xmlencodeattr.cpp b/noncore/apps/tableviewer/xmlencodeattr.cpp new file mode 100644 index 0000000..de264f7 --- a/dev/null +++ b/noncore/apps/tableviewer/xmlencodeattr.cpp @@ -0,0 +1,48 @@ +/* + * xmlencodeattr.h + * + * copyright : (c) 2003 by Joseph Wenninger + * except for a small modification it's identical to qdom.cpp:encodeAttr + * email : jowenn@handhelds.org + * + */ +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "xmlencodeattr.h" +QString encodeAttr( const QString& str ) +{ + QString tmp( str ); + uint len = tmp.length(); + uint i = 0; + while ( i < len ) { + if ( tmp[(int)i] == '<' ) { + tmp.replace( i, 1, "<" ); + len += 3; + i += 4; + } else if ( tmp[(int)i] == '"' ) { + tmp.replace( i, 1, """ ); + len += 5; + i += 6; + } else if ( tmp[(int)i] == '&' ) { + tmp.replace( i, 1, "&" ); + len += 4; + i += 5; + } else if ( tmp[(int)i] == '>' ) { + tmp.replace( i, 1, ">" ); + len += 3; + i += 4; + } else { + ++i; + } + } + + return tmp; +} + diff --git a/noncore/apps/tableviewer/xmlencodeattr.h b/noncore/apps/tableviewer/xmlencodeattr.h new file mode 100644 index 0000000..5fd3b95 --- a/dev/null +++ b/noncore/apps/tableviewer/xmlencodeattr.h @@ -0,0 +1,26 @@ +/* + * xmlencodeattr.h + * + * copyright : (c) 2003 by Joseph Wenninger + * except for a small modification it's identical to qdom.cpp:encodeAttr + * email : jowenn@handhelds.org + * + */ +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef _XML_ENCODE_ATTR_ +#define _XML_ENCODE_ATTR_ + +#include <qstring.h> + +QString encodeAttr( const QString& str ); + +#endif + diff --git a/noncore/comm/keypebble/keypebble.pro b/noncore/comm/keypebble/keypebble.pro index 04f4b64..7af60f9 100644 --- a/noncore/comm/keypebble/keypebble.pro +++ b/noncore/comm/keypebble/keypebble.pro @@ -1,56 +1,55 @@ TEMPLATE = app CONFIG += qt warn_on release DESTDIR = $(OPIEDIR)/bin HEADERS = d3des.h \ krfbbuffer.h \ krfbcanvas.h \ krfbconnection.h \ krfbdecoder.h \ krfblogin.h \ krfbserver.h \ krfbserverinfo.h \ kvnc.h \ kvncconndlg.h \ kvncbookmarkdlg.h \ - version.h \ vncauth.h SOURCES = d3des.c \ vncauth.c \ krfbbuffer.cpp \ krfbcanvas.cpp \ krfbconnection.cpp \ krfbdecoder.cpp \ krfblogin.cpp \ krfbserver.cpp \ kvnc.cpp \ kvncconndlg.cpp \ kvncbookmarkdlg.cpp \ main.cpp INTERFACES = kvncconndlgbase.ui \ kvncbookmarkdlgbase.ui TARGET = keypebble INCLUDEPATH += $(OPIEDIR)/include DEPENDPATH += $(OPIEDIR)/include LIBS += -lqpe TRANSLATIONS = ../../../i18n/de/keypebble.ts \ ../../../i18n/nl/keypebble.ts \ ../../../i18n/da/keypebble.ts \ ../../../i18n/xx/keypebble.ts \ ../../../i18n/en/keypebble.ts \ ../../../i18n/es/keypebble.ts \ ../../../i18n/fr/keypebble.ts \ ../../../i18n/hu/keypebble.ts \ ../../../i18n/ja/keypebble.ts \ ../../../i18n/ko/keypebble.ts \ ../../../i18n/no/keypebble.ts \ ../../../i18n/pl/keypebble.ts \ ../../../i18n/pt/keypebble.ts \ ../../../i18n/pt_BR/keypebble.ts \ ../../../i18n/sl/keypebble.ts \ ../../../i18n/zh_CN/keypebble.ts \ ../../../i18n/zh_TW/keypebble.ts include ( $(OPIEDIR)/include.pro ) diff --git a/noncore/comm/keypebble/opie-keypebble.control b/noncore/comm/keypebble/opie-keypebble.control index 123f307..23e4e89 100644 --- a/noncore/comm/keypebble/opie-keypebble.control +++ b/noncore/comm/keypebble/opie-keypebble.control @@ -1,11 +1,11 @@ Package: opie-keypebble Files: bin/keypebble apps/Applications/keypebble.desktop pics/vnc Priority: optional Section: opie/applications Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm Arch: iPAQ -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: VNC Viewer Virtual Network Computing (VNC) viewer +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/comm/mobilemsg/opie-mobilemsg.control b/noncore/comm/mobilemsg/opie-mobilemsg.control index 1713af5..c5fbc7f 100644 --- a/noncore/comm/mobilemsg/opie-mobilemsg.control +++ b/noncore/comm/mobilemsg/opie-mobilemsg.control @@ -1,10 +1,10 @@ Package: opie-mobilemsg Files: bin/mobilemsg apps/Applications/mobilemsg.desktop Priority: optional Section: opie/comm Maintainer: Bruno Rodrigues <bruno.rodrigues@litux.org> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Mobile Messaging For the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/decorations/flat/opie-deco-flat.control b/noncore/decorations/flat/opie-deco-flat.control index ae64aae..311f37b 100644 --- a/noncore/decorations/flat/opie-deco-flat.control +++ b/noncore/decorations/flat/opie-deco-flat.control @@ -1,10 +1,10 @@ Package: opie-deco-flat Files: plugins/decorations/libflat.so* Priority: optional Section: opie/decorations Maintainer: Robert Griebl <sandman@handhelds.org> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION.1 Depends: task-opie-minimal Description: OPIE window decoration style Flat window decoration style for OPIE. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/decorations/liquid/opie-deco-liquid.control b/noncore/decorations/liquid/opie-deco-liquid.control index 2f91612..c14b8bf 100644 --- a/noncore/decorations/liquid/opie-deco-liquid.control +++ b/noncore/decorations/liquid/opie-deco-liquid.control @@ -1,10 +1,10 @@ Package: opie-deco-liquid Files: plugins/decorations/libliquid.so* Priority: optional Section: opie/decorations Maintainer: Robert Griebl <sandman@handhelds.org> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION.1 Depends: task-opie-minimal Description: OPIE window decoration style Liquid (KDE3) window decoration style for OPIE. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/decorations/polished/opie-deco-polished.control b/noncore/decorations/polished/opie-deco-polished.control index 4d4b4e3..15afa83 100644 --- a/noncore/decorations/polished/opie-deco-polished.control +++ b/noncore/decorations/polished/opie-deco-polished.control @@ -1,10 +1,10 @@ Package: opie-deco-polished Files: plugins/decorations/libpolished.so* Priority: optional Section: opie/decorations Maintainer: Robert Griebl <sandman@handhelds.org> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION.1 Depends: task-opie-minimal Description: OPIE window decoration style Blended window decoration style for OPIE. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/backgammon/backgammon.control b/noncore/games/backgammon/backgammon.control index b75bc60..6468181 100644 --- a/noncore/games/backgammon/backgammon.control +++ b/noncore/games/backgammon/backgammon.control @@ -1,10 +1,10 @@ Package: backgammon Files: bin/backgammon apps/Games/backgammon.desktop pics/backgammon help/en/html/backgammon.html Priority: optional Section: opie/games Maintainer: Ralf Waspe <rwaspe@web.de> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Backgammon Game A Backgammon game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/backgammon/backgammon.cpp b/noncore/games/backgammon/backgammon.cpp index db1a058..06523f1 100644 --- a/noncore/games/backgammon/backgammon.cpp +++ b/noncore/games/backgammon/backgammon.cpp @@ -1,976 +1,974 @@ #include "backgammon.h" #include "aidialog.h" #include "filedialog.h" #include "playerdialog.h" #include "rulesdialog.h" #include "themedialog.h" #include <qdatetime.h> #include <qfile.h> #include <qlayout.h> #include <qmessagebox.h> #include <qstring.h> #include <qtimer.h> #include <qmainwindow.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpe/qpemenubar.h> #include <qpe/resource.h> #include <stdlib.h> BackGammon::BackGammon(QWidget* parent, const char* name, WFlags fl) : QMainWindow(parent, name, fl) { if (!name) setName("BackGammon"); setCaption(tr( "Backgammon") ); setIcon( Resource::loadPixmap( "backgammon" ) ); //general counter varaible int a=0; //the game engine move=new MoveEngine(); //load the default theme Config conf("backgammon"); if(!conf.isValid()) { qDebug("config file does not exist"); conf.setGroup("general"); conf.writeEntry("theme","default"); conf.setGroup("rules"); conf.writeEntry("move_with_pieces_out",false); conf.writeEntry("nice_dice",false); conf.setGroup("display"); conf.writeEntry("small",false); conf.writeEntry("warning",true); conf.setGroup("ai"); conf.writeEntry("rescue",6); conf.writeEntry("eliminate",4); conf.writeEntry("expose",1); conf.writeEntry("protect",5); conf.writeEntry("safe",3); conf.writeEntry("empty",2); } conf.setGroup("general"); theme_name=conf.readEntry("theme","default"); QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; //the rules conf.setGroup("rules"); rules.move_with_pieces_out=conf.readBoolEntry("move_with_pieces_out",false); rules.generous_dice=conf.readBoolEntry("nice_dice",false); move->setRules(rules); //get the AI settings AISettings ai; conf.setGroup("ai"); ai.rescue=conf.readNumEntry("rescue",6); ai.eliminate=conf.readNumEntry("eliminate",4); ai.expose=conf.readNumEntry("expose",1); ai.protect=conf.readNumEntry("protect",5); ai.safe=conf.readNumEntry("safe",3); ai.empty=conf.readNumEntry("empty",2); move->setAISettings(ai); //get the theme component names Config theme(theme_file,Config::File); if(!theme.isValid()) { qDebug("theme file does not exist"); theme.setGroup("theme"); theme.writeEntry("board","casino_board_1"); theme.writeEntry("pieces1","casino_pieces_blue"); theme.writeEntry("pieces2","casino_pieces_white"); theme.writeEntry("dice1","casino_dice"); theme.writeEntry("dice2","casino_dice"); theme.writeEntry("table","casino_table_green"); theme.writeEntry("odds","casino_odds"); } theme.setGroup("theme"); board_name=theme.readEntry("board","casino_board_1"); piecesA_name=theme.readEntry("pieces1","casino_pieces_blue"); piecesB_name=theme.readEntry("pieces2","casino_pieces_white"); diceA_name=theme.readEntry("dice1","casino_dice"); diceB_name=theme.readEntry("dice2","casino_dice"); table_name=theme.readEntry("table","casino_table_green"); odds_name=theme.readEntry("odds","casino_odds"); //the menu QPEMenuBar* menuBar = new QPEMenuBar(this); QPopupMenu* gamemenu= new QPopupMenu(this); gamemenu->insertItem(tr( "New" ),this,SLOT(newgame())); gamemenu->insertSeparator(); gamemenu->insertItem(tr( "Load" ),this,SLOT(loadgame())); gamemenu->insertItem(tr( "Save" ),this,SLOT(savegame())); gamemenu->insertSeparator(); gamemenu->insertItem(tr( "Delete" ),this,SLOT(deletegame())); menuBar->insertItem(tr( "Game" ),gamemenu); QPopupMenu* thememenu= new QPopupMenu(this); thememenu->insertItem(tr( "New" ),this,SLOT(newtheme())); thememenu->insertSeparator(); thememenu->insertItem(tr( "Load"),this,SLOT(loadtheme())); thememenu->insertItem(tr( "Save" ),this,SLOT(savetheme())); thememenu->insertSeparator(); thememenu->insertItem(tr( "Default"),this,SLOT(themedefault())); thememenu->insertItem(tr( "Delete" ),this,SLOT(deletetheme())); menuBar->insertItem(tr( "Theme" ),thememenu); QPopupMenu* optionmenu=new QPopupMenu(this); optionmenu->insertItem(tr( "Player" ),this,SLOT(playerselect())); optionmenu->insertSeparator(); optionmenu->insertItem(tr( "AI" ),this,SLOT(modify_AI())); optionmenu->insertItem(tr( "Rules" ),this,SLOT(setrules())); menuBar->insertItem(tr( "Options"),optionmenu); QWidget* mainarea=new QWidget(this); setCentralWidget(mainarea); //the main area QBoxLayout* layout=new QBoxLayout(mainarea,QBoxLayout::TopToBottom); area=new QCanvas(235,235); - QColor bgColor=palette().color(QPalette::Normal,QColorGroup::Background); - area->setBackgroundColor(bgColor); boardview=new BackGammonView(area,mainarea); boardview->setMaximumHeight(240); layout->addWidget(boardview); connect(boardview,SIGNAL(mouse(int,int)),this,SLOT(mouse(int,int))); //status bar message=new QLabel("<b>Backgammon</b>",mainarea); message->setAlignment(AlignHCenter); layout->addWidget(message); //the marker marker_current=new QCanvasRectangle(area); marker_current->setBrush(QColor(0,0,255)); marker_current->setSize(15,5); marker_current->setZ(1); for(a=0;a<4;a++) { marker_next[a]=new QCanvasRectangle(area); marker_next[a]->setBrush(QColor(0,255,0)); marker_next[a]->setSize(15,5); marker_next[a]->setZ(1); } connect(move,SIGNAL(done_dice1()),this,SLOT(done_dice1())); connect(move,SIGNAL(done_dice2()),this,SLOT(done_dice2())); connect(move,SIGNAL(done_dice3()),this,SLOT(done_dice3())); connect(move,SIGNAL(done_dice4()),this,SLOT(done_dice4())); connect(move,SIGNAL(nomove()),this,SLOT(nomove())); connect(move,SIGNAL(player_finished(int)),this,SLOT(finished(int))); //the pieces p1=new CanvasImageItem*[15]; p1_side=new CanvasImageItem*[15]; QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name)); QImage piece_1_front=piece_1_all.copy(0,0,15,15); QImage piece_1_side=piece_1_all.copy(0,15,15,5); p2=new CanvasImageItem*[15]; p2_side=new CanvasImageItem*[15]; QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name)); QImage piece_2_front=piece_2_all.copy(0,0,15,15); QImage piece_2_side=piece_2_all.copy(0,15,15,5); for(a=0;a<15;a++) { p1[a]=new CanvasImageItem(piece_1_front,area); p1[a]->setSize(15,15); p1_side[a]=new CanvasImageItem(piece_1_side,area); p1_side[a]->setSize(15,5); p2[a]=new CanvasImageItem(piece_2_front,area); p2[a]->setSize(15,15); p2_side[a]=new CanvasImageItem(piece_2_side,area); p2_side[a]->setSize(15,5); } draw(); //the dice QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name)); diceA1=new CanvasImageItem*[7]; diceA2=new CanvasImageItem*[7]; QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name)); diceB1=new CanvasImageItem*[7]; diceB2=new CanvasImageItem*[7]; QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name)); //oddsDice=new CanvasImageItem*[6]; for(a=0;a<7;a++) { QImage dicebgA=dicebgA_all.copy(a*25,0,25,25); diceA1[a]=new CanvasImageItem(dicebgA,area); diceA1[a]->setX(5); diceA1[a]->setY(205-2); diceA1[a]->setZ(1); diceA1[a]->setSize(25,25); diceA2[a]=new CanvasImageItem(dicebgA,area); diceA2[a]->setX(35); diceA2[a]->setY(205-2); diceA2[a]->setZ(1); diceA2[a]->setSize(25,25); QImage dicebgB=dicebgB_all.copy(a*25,0,25,25); diceB1[a]=new CanvasImageItem(dicebgB,area); diceB1[a]->setX(175); diceB1[a]->setY(205-2); diceB1[a]->setZ(1); diceB1[a]->setSize(25,25); diceB2[a]=new CanvasImageItem(dicebgB,area); diceB2[a]->setX(205); diceB2[a]->setY(205-2); diceB2[a]->setZ(1); diceB2[a]->setSize(25,25); /* if(a<6) { QImage oddsbg=oddsbg_all.copy(a*15,0,15,15); oddsDice[a]=new CanvasImageItem(oddsbg,area); oddsDice[a]->setX(110); oddsDice[a]->setY(210-2); oddsDice[a]->setZ(1); oddsDice[a]->setSize(15,15); oddsDice[a]->hide(); } */ } //oddsDice[0]->show(); //set the board QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name)); board=new CanvasImageItem(boardbg,area); board->setX(0); board->setY(0); board->setZ(0); board->setSize(235-2,200-2); board->show(); //the table QImage tablebg(Resource::loadImage("backgammon/table/"+table_name)); table=new CanvasImageItem(tablebg,area); table->setX(0); table->setY(200-2); table->setZ(0); table->setSize(235-2,20); table->show(); //the no move marker QImage nomovebg(Resource::loadImage("backgammon/no_move")); nomove_marker=new CanvasImageItem(nomovebg,area); nomove_marker->setX(0); nomove_marker->setY(200); nomove_marker->setZ(2); nomove_marker->hide(); //default human against computer player1_auto=false; player2_auto=true; //start new game newgame(); } BackGammon::~BackGammon() { //DESTRUCTOR } void BackGammon::newgame() { gameFinished=false; QDateTime now=QDateTime::currentDateTime(); game_name=now.date().toString()+"_"+now.time().toString(); move->reset(); draw(); diceA1_value=7; diceA2_value=7; diceA3_value=7; diceA4_value=7; diceB1_value=7; diceB2_value=7; diceB3_value=7; diceB4_value=7; showdice(); player=2; dice1_played=true; dice2_played=true; dice3_played=true; dice4_played=true; dice_rolled=false; setplayer(); area->update(); } void BackGammon::playerselect() { PlayerDialog* playerdialog=new PlayerDialog(this); playerdialog->setAuto1(player1_auto); playerdialog->setAuto2(player2_auto); if(!playerdialog->exec()) return; player1_auto=playerdialog->getAuto1(); player2_auto=playerdialog->getAuto2(); } void BackGammon::loadgame() { FileDialog* file=new FileDialog(this,"Load Game",".game"); if(!file->exec()) return; game_name=file->filename(); QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; Config game(game_file,Config::File); game.setGroup("dice"); diceA1_value=game.readNumEntry("diceA1_value"); diceA2_value=game.readNumEntry("diceA2_value"); diceA3_value=game.readNumEntry("diceA3_value"); diceA4_value=game.readNumEntry("diceA4_value"); diceB1_value=game.readNumEntry("diceB1_value"); diceB2_value=game.readNumEntry("diceB2_value"); diceB3_value=game.readNumEntry("diceB3_value"); diceB4_value=game.readNumEntry("diceB4_value"); player=game.readNumEntry("player"); dice1_played=game.readBoolEntry("dice1_played"); dice2_played=game.readBoolEntry("dice2_played"); dice3_played=game.readBoolEntry("dice3_played"); dice4_played=game.readBoolEntry("dice4_played"); dice_rolled=game.readBoolEntry("dice_rolled"); player1_auto=game.readBoolEntry("player1_auto"); player2_auto=game.readBoolEntry("player2_auto"); game.setGroup("pieces"); QString label; LoadSave load; for(int a=0;a<28;a++) { label.setNum(a); load.pop[a].total = game.readNumEntry(label,0); } move->loadGame(load); setplayer(); showdice(); draw(); area->update(); } void BackGammon::savegame() { QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; Config game(game_file,Config::File); game.setGroup("dice"); game.writeEntry("diceA1_value",diceA1_value); game.writeEntry("diceA2_value",diceA2_value); game.writeEntry("diceA3_value",diceA3_value); game.writeEntry("diceA4_value",diceA4_value); game.writeEntry("diceB1_value",diceB1_value); game.writeEntry("diceB2_value",diceB3_value); game.writeEntry("diceB3_value",diceB4_value); game.writeEntry("diceB4_value",diceB4_value); game.writeEntry("player",player); game.writeEntry("dice1_played",dice1_played); game.writeEntry("dice2_played",dice2_played); game.writeEntry("dice3_played",dice3_played); game.writeEntry("dice4_played",dice4_played); game.writeEntry("dice_rolled",dice_rolled); game.writeEntry("player1_auto",player1_auto); game.writeEntry("player2_auto",player2_auto); game.setGroup("pieces"); QString label; LoadSave save=move->saveGame(); for(int a=0;a<28;a++) { label.setNum(a); game.writeEntry(label,save.pop[a].total); } QMessageBox::information(this,"Backgammon","Game saved","OK"); } void BackGammon::deletegame() { FileDialog* file=new FileDialog(this,"Delete Game",".game"); if(!file->exec()) return; game_name=file->filename(); QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; if(!QMessageBox::warning(this,"Backgammon","deleted game\n"+game_name+" ?","OK","Cancel")) { QFile(game_file).remove(); } } void BackGammon::newtheme() { ThemeDialog* theme=new ThemeDialog(this); ImageNames names; names.theme=theme_name; names.board=board_name; names.pieces1=piecesA_name; names.pieces2=piecesB_name; names.dice1=diceA_name; names.dice2=diceB_name; names.odds=odds_name; names.table=table_name; theme->setCurrent(names); if(!theme->exec()) return; names=theme->getNames(); theme_name=names.theme; board_name=names.board; piecesA_name=names.pieces1; piecesB_name=names.pieces2; diceA_name=names.dice1; diceB_name=names.dice2; odds_name=names.odds; table_name=names.table; applytheme(); } void BackGammon::loadtheme() { FileDialog* file=new FileDialog(this,"Load Theme",".theme"); if(!file->exec()) return; theme_name=file->filename(); QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; Config theme(theme_file,Config::File); theme.setGroup("theme"); board_name=theme.readEntry("board","board_1"); piecesA_name=theme.readEntry("pieces1","pieces_1"); piecesB_name=theme.readEntry("pieces2","pieces_2"); diceA_name=theme.readEntry("dice1","dice_1"); diceB_name=theme.readEntry("dice2","dice_2"); table_name=theme.readEntry("table","table_1"); odds_name=theme.readEntry("odds","odds_1"); applytheme(); } void BackGammon::savetheme() { if(theme_name=="default") { QMessageBox::information(this,"Backgammon","Sorry\nCannot overwrite default.theme","OK"); return; } QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; if(QMessageBox::information(this,"Backgammon","Save Theme\n"+theme_name,"Yes","No")) return; Config theme(theme_file,Config::File); theme.setGroup("theme"); theme.writeEntry("board",board_name); theme.writeEntry("pieces1",piecesA_name); theme.writeEntry("pieces2",piecesB_name); theme.writeEntry("dice1",diceA_name); theme.writeEntry("dice2",diceB_name); theme.writeEntry("table",table_name); theme.writeEntry("odds",odds_name); } void BackGammon::themedefault() { if(QMessageBox::information(this,"Backgammon","Make Theme\n"+theme_name+"\nthe default theme","Yes","No")) return; Config conf("backgammon"); conf.setGroup("general"); conf.writeEntry("theme",theme_name); } void BackGammon::deletetheme() { FileDialog* file=new FileDialog(this,"Delete Theme",".theme"); if(!file->exec()) return; theme_name=file->filename(); QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; if(!QMessageBox::warning(this,tr( "Backgammon" ),tr( "deleted theme %1?").arg(theme_name),tr( "OK" ),tr( "Cancel" ))) { QFile(theme_file).remove(); } } void BackGammon::modify_AI() { AI_Dialog* ai_mod=new AI_Dialog(this,tr( "Load Theme" ),".theme"); ai_mod->setAISettings(move->getAISettings()); if(!ai_mod->exec()) return; //get the AI settings AISettings ai=ai_mod->getAISettings(); move->setAISettings(ai); //write new settings to conf file Config conf("backgammon"); conf.setGroup("ai"); conf.writeEntry("rescue",ai.rescue); conf.writeEntry("eliminate",ai.eliminate); conf.writeEntry("expose",ai.expose); conf.writeEntry("protect",ai.protect); conf.writeEntry("safe",ai.safe); conf.writeEntry("empty",ai.empty); } void BackGammon::setrules() { RulesDialog* rulesdialog=new RulesDialog(this,tr( "Load Theme" ),".theme"); rulesdialog->setRules(rules); if(!rulesdialog->exec()) return; rules=rulesdialog->getRules(); Config conf("backgammon"); conf.setGroup("rules"); conf.writeEntry("move_with_pieces_out",rules.move_with_pieces_out); conf.writeEntry("nice_dice",rules.generous_dice); move->setRules(rules); } void BackGammon::draw() { Pieces pieces; move->position(pieces); for(int a=0;a<15;a++) { if(!pieces.player1[a].side) { p1[a]->setX(pieces.player1[a].x); p1[a]->setY(pieces.player1[a].y); p1[a]->setZ(pieces.player1[a].z); p1[a]->show(); p1_side[a]->hide(); } else { p1_side[a]->setX(pieces.player1[a].x); p1_side[a]->setY(pieces.player1[a].y); p1_side[a]->setZ(pieces.player1[a].z); p1_side[a]->show(); p1[a]->hide(); } if(!pieces.player2[a].side) { p2[a]->setX(pieces.player2[a].x); p2[a]->setY(pieces.player2[a].y); p2[a]->setZ(pieces.player2[a].z); p2[a]->show(); p2_side[a]->hide(); } else { p2_side[a]->setX(pieces.player2[a].x); p2_side[a]->setY(pieces.player2[a].y); p2_side[a]->setZ(pieces.player2[a].z); p2_side[a]->show(); p2[a]->hide(); } } } void BackGammon::mouse(int x,int y) { if(gameFinished) { newgame(); return; } if(y<=200) //move pieces { if((player==1 && player1_auto) || (player==2 && player2_auto)) return; Marker marker; move->boardpressed(x,y,marker); if(marker.visible_current) { marker_current->setX(marker.x_current); marker_current->setY(marker.y_current); marker_current->show(); } else { marker_current->hide(); } for(int a=0;a<4;a++) { if(marker.visible_next[a]) { marker_next[a]->setX(marker.x_next[a]); marker_next[a]->setY(marker.y_next[a]); marker_next[a]->show(); } else { marker_next[a]->hide(); } } area->update(); } else //roll dice { if(x>=10 && x<=65 && player==1 && !dice_rolled) { dice1_played=false; dice2_played=false; dice3_played=false; dice4_played=false; dice_rolled=true; srand(QTime::currentTime().msec()); diceA1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); diceA2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); if(diceA1_value==diceA2_value) { diceA3_value=diceA1_value; diceA4_value=diceA1_value; } else { diceA3_value=7; dice3_played=true; diceA4_value=7; dice4_played=true; } showdice(); area->update(); move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else if(x>=160 && x<=225 && player==2 && !dice_rolled) { dice1_played=false; dice2_played=false; dice3_played=false; dice4_played=false; dice_rolled=true; srand(QTime::currentTime().msec()); diceB1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); diceB2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); if(diceB1_value==diceB2_value) { diceB3_value=diceB1_value; diceB4_value=diceB1_value; } else { diceB3_value=7; dice3_played=true; diceB4_value=7; dice4_played=true; } showdice(); area->update(); move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::done_dice1() { dice1_played=true; if(player==1) diceA1_value=7; else diceB1_value=7; setplayer(); showdice(); draw(); area->update(); if(!dice2_played || !dice3_played || !dice4_played) { if(player==1) { move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else { move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::done_dice2() { dice2_played=true; if(player==1) diceA2_value=7; else diceB2_value=7; setplayer(); showdice(); draw(); area->update(); if(!dice1_played || !dice3_played || !dice4_played) { if(player==1) { move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else { move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::done_dice3() { dice3_played=true; if(player==1) diceA3_value=7; else diceB3_value=7; setplayer(); showdice(); draw(); area->update(); if(!dice1_played || !dice2_played || !dice4_played) { if(player==1) { move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else { move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::done_dice4() { dice4_played=true; if(player==1) diceA4_value=7; else diceB4_value=7; setplayer(); showdice(); draw(); area->update(); if(!dice1_played || !dice2_played || !dice3_played) { if(player==1) { move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else { move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::nomove() { if(player==1) nomove_marker->setX(0); else nomove_marker->setX(170); nomove_marker->show(); message->setText(tr( "<b>no move</b>" )); dice1_played=true; dice2_played=true; dice3_played=true; dice4_played=true; if(player==1) { diceA1_value=7; diceA2_value=7; diceA3_value=7; diceA4_value=7; } else { diceB1_value=7; diceB2_value=7; diceB3_value=7; diceB4_value=7; } area->update(); QTimer::singleShot(2000,this,SLOT(nomove2())); } void BackGammon::nomove2() { nomove_marker->hide(); setplayer(); showdice(); draw(); area->update(); } void BackGammon::finished(int theplayer) { nomove_marker->hide(); if(theplayer==1) message->setText(tr( "<b>Player 1 wins. Click on board for new game.</b>" )); else message->setText(tr( "<b>Player 2 wins. Click on board for new game.</b>" )); diceA1_value=7; diceA2_value=7; diceB1_value=7; diceB2_value=7; player=0; showdice(); draw(); area->update(); gameFinished=true; } void BackGammon::showdice() { int value_diceA1=diceA1_value-1; if(diceA1_value==7 && diceA3_value!=7) value_diceA1=diceA3_value-1; int value_diceA2=diceA2_value-1; if(diceA2_value==7 && diceA4_value!=7) value_diceA2=diceA4_value-1; int value_diceB1=diceB1_value-1; if(diceB1_value==7 && diceB3_value!=7) value_diceB1=diceB3_value-1; int value_diceB2=diceB2_value-1; if(diceB2_value==7 && diceB4_value!=7) value_diceB2=diceB4_value-1; for(int index=0;index<7;index++) { if(value_diceA1==index) diceA1[index]->show(); else diceA1[index]->hide(); if(value_diceA2==index) diceA2[index]->show(); else diceA2[index]->hide(); if(value_diceB1==index) diceB1[index]->show(); else diceB1[index]->hide(); if(value_diceB2==index) diceB2[index]->show(); else diceB2[index]->hide(); } } void BackGammon::setplayer() { if(dice1_played && dice2_played && dice3_played && dice4_played && player==1) { message->setText(tr( "<b>P2 turn</b>", "P means player" )); dice_rolled=false; player=2; if(player2_auto) QTimer::singleShot(2000,this,SLOT(autoroll_dice2())); } else if(dice1_played && dice2_played && dice3_played && dice4_played && player==2) { message->setText(tr( "<b>P1 turn</b>", "P means player" )); dice_rolled=false; player=1; if(player1_auto) QTimer::singleShot(2000,this,SLOT(autoroll_dice1())); } } void BackGammon::autoroll_dice1() { mouse(20,210); } void BackGammon::autoroll_dice2() { mouse(170,210); } void BackGammon::applytheme() { QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name)); board->setImage(boardbg); QImage tablebg(Resource::loadImage("backgammon/table/"+table_name)); table->setImage(tablebg); QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name)); QImage piece_1_front=piece_1_all.copy(0,0,15,15); QImage piece_1_side=piece_1_all.copy(0,15,15,5); QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name)); QImage piece_2_front=piece_2_all.copy(0,0,15,15); QImage piece_2_side=piece_2_all.copy(0,15,15,5); int a=0; for(a=0;a<15;a++) { p1[a]->setImage(piece_1_front); p1_side[a]->setImage(piece_1_side); p2[a]->setImage(piece_2_front); p2_side[a]->setImage(piece_2_side); } draw(); QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name)); QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name)); QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name)); for(a=0;a<7;a++) { QImage dicebgA=dicebgA_all.copy(a*25,0,25,25); diceA1[a]->setImage(dicebgA); diceA2[a]->setImage(dicebgA); QImage dicebgB=dicebgB_all.copy(a*25,0,25,25); diceB1[a]->setImage(dicebgB); diceB2[a]->setImage(dicebgB); /* if(a<6) { QImage oddsbg=oddsbg_all.copy(a*15,0,15,15); oddsDice[a]->setImage(oddsbg); } */ } } diff --git a/noncore/games/backgammon/backgammon.h b/noncore/games/backgammon/backgammon.h index d803489..e3276f1 100644 --- a/noncore/games/backgammon/backgammon.h +++ b/noncore/games/backgammon/backgammon.h @@ -1,119 +1,120 @@ #ifndef BACKGAMMON_H #define BACKGAMMON_H #include "backgammonview.h" #include "canvasimageitem.h" //#include "rulesdialog.h" #include "moveengine.h" #include <qlabel.h> #include <qmainwindow.h> //#include <qwidget.h> class BackGammon : public QMainWindow { Q_OBJECT private: + //GUI //the "status" bar QLabel* message; //the main drawing area QCanvas* area; BackGammonView* boardview; CanvasImageItem* board; CanvasImageItem* table; CanvasImageItem** p1; CanvasImageItem** p2; CanvasImageItem** p1_side; CanvasImageItem** p2_side; CanvasImageItem** diceA1; CanvasImageItem** diceA2; CanvasImageItem** diceB1; CanvasImageItem** diceB2; //CanvasImageItem** oddsDice; CanvasImageItem* nomove_marker; QCanvasRectangle* marker_current; QCanvasRectangle* marker_next[4]; //ENGINE MoveEngine* move; //the dice values int diceA1_value; int diceA2_value; int diceA3_value; int diceA4_value; int diceB1_value; int diceB2_value; int diceB3_value; int diceB4_value; int player; bool dice1_played; bool dice2_played; bool dice3_played; bool dice4_played; bool dice_rolled; //computer opponent bool player1_auto; bool player2_auto; //the images; QString theme_name; QString board_name; QString piecesA_name; QString piecesB_name; QString diceA_name; QString diceB_name; QString odds_name; QString table_name; //save game QString game_name; //the rules Rules rules; //display settings Display display; //is the game finished ? bool gameFinished; public: BackGammon( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~BackGammon(); private slots: void newgame(); void playerselect(); void loadgame(); void savegame(); void deletegame(); void newtheme(); void loadtheme(); void savetheme(); void themedefault(); void deletetheme(); void modify_AI(); void setrules(); void mouse(int x,int y); void done_dice1(); void done_dice2(); void done_dice3(); void done_dice4(); void nomove(); void nomove2(); void finished(int theplayer); void autoroll_dice1(); void autoroll_dice2(); private: void draw(); void showdice(); void setplayer(); void applytheme(); }; #endif //BACKGAMMON_H diff --git a/noncore/games/bounce/kbounce.cpp b/noncore/games/bounce/kbounce.cpp index 5d8aba3..50f4ef6 100644 --- a/noncore/games/bounce/kbounce.cpp +++ b/noncore/games/bounce/kbounce.cpp @@ -1,311 +1,311 @@ /* * Copyright (C) 2000 Stefan Schimanski <1Stein@gmx.de> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License,Life or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <qlayout.h> #include <qtimer.h> #include <qlcdnumber.h> #include <qmessagebox.h> #include <qmainwindow.h> #include <qpe/qpeapplication.h> #include "kbounce.h" #include "game.h" #include <qlabel.h> KJezzball::KJezzball() : QMainWindow(0), m_gameWidget( 0 ) { setCaption(tr("Bounce")); // setup variables m_game.level = 1; m_game.score = 0; m_state = Idle; menu = menuBar(); game = new QPopupMenu; game->insertItem(tr("&New game"), this, SLOT(newGame()), Key_N ); game->insertItem(tr("&Pause game"), this, SLOT(pauseGame()), Key_P ); game->insertSeparator(); game->insertItem(tr("&About"), this, SLOT(about())); menu->insertItem( tr("&Game"), game ); // create widgets m_view = new QWidget( this, "m_view" ); setCentralWidget( m_view ); m_layout = new QGridLayout( m_view ); m_layout->setSpacing( 0 ); m_layout->setMargin( 0 ); ScoreLabel = new QLabel( m_view, "ScoreLabel" ); ScoreLabel->setText( tr( "Score: 00" ) ); ScoreLabel->setAlignment( int( QLabel::AlignCenter ) ); m_layout->addWidget( ScoreLabel, 1, 0 ); LivesLabel = new QLabel( m_view, "LivesLabel" ); LivesLabel->setText( tr( "Lives: 0%" ) ); LivesLabel->setAlignment( int( QLabel::AlignCenter ) ); m_layout->addWidget( LivesLabel, 1, 2 ); FilledLabel = new QLabel( m_view, "FilledLabel" ); FilledLabel->setText( tr( "Filled: 00%" ) ); FilledLabel->setAlignment( int( QLabel::AlignCenter ) ); m_layout->addWidget( FilledLabel, 1, 1 ); TimeLabel = new QLabel( m_view, "TimeLabel" ); TimeLabel->setText( tr( "Time: 00" ) ); TimeLabel->setAlignment( int( QLabel::AlignCenter ) ); m_layout->addWidget( TimeLabel, 1, 3 ); // create timers m_nextLevelTimer = new QTimer( this, "m_nextLevelTimer" ); connect( m_nextLevelTimer, SIGNAL(timeout()), this, SLOT(switchLevel()) ); m_gameOverTimer = new QTimer( this, "m_gameOverTimer" ); connect( m_gameOverTimer, SIGNAL(timeout()), this, SLOT(gameOverNow()) ); m_timer = new QTimer( this, "m_timer" ); connect( m_timer, SIGNAL(timeout()), this, SLOT(second()) ); // create demo game createLevel( 1 ); } void KJezzball::newGame() { // Check for running game closeGame(); if ( m_state==Idle ) { // update displays m_game.level = 1; m_game.score = 0; setCaption(tr("Bounce Level %1").arg(m_game.level)); ScoreLabel->setText( tr( "Score: %1" ).arg(m_game.score) ); // start new game m_state = Running; createLevel( m_game.level ); startLevel(); } } void KJezzball::about() { - QMessageBox::information( this, "About", - "Written by: Stefan Schimanski\n" + QMessageBox::information( this, tr("About"), + tr("Written by: Stefan Schimanski\n" "Ported by: Martin Imobersteg\n" "\n" "Click to form walls.\n" "Hit space to switch wall direction.\n" "Try to reduce total space by 75%.\n" "\n" "This program is distributed under\n" - "the terms of the GPL v2." ); + "the terms of the GPL v2.") ); } void KJezzball::closeGame() { if ( m_state!=Idle ) { stopLevel(); m_state = Idle; } } void KJezzball::pauseGame() { switch ( m_state ) { case Running: m_state = Paused; m_gameWidget->display( tr("Game paused.\nPress P to continue!") ); stopLevel(); break; case Paused: case Suspend: m_state = Running; m_gameWidget->display( QString::null ); startLevel(); break; case Idle: break; } } void KJezzball::gameOver() { stopLevel(); m_gameOverTimer->start( 100, TRUE ); } void KJezzball::gameOverNow() { m_state = Idle; QString score; score.setNum( m_game.score ); QMessageBox::information( this, "Game Over", tr("Game Over!\nScore: %1").arg(score) ); } void KJezzball::focusOutEvent( QFocusEvent *ev ) { if ( m_state==Running ) { stopLevel(); m_state = Suspend; } QMainWindow::focusOutEvent( ev ); } void KJezzball::focusInEvent ( QFocusEvent *ev ) { if ( m_state==Suspend ) { startLevel(); m_state = Running; } QMainWindow::focusInEvent( ev ); } void KJezzball::second() { m_level.time--; TimeLabel->setText( tr( "Time: %1" ).arg(m_level.time) ); if ( m_level.time<=0 ) { gameOver(); } } void KJezzball::died() { m_level.lifes--; LivesLabel->setText( tr( "Lives: %1" ).arg(m_level.lifes) ); if ( m_level.lifes==0 ) gameOver(); } void KJezzball::newPercent( int percent ) { FilledLabel->setText( tr( "Filled: %1%" ).arg(percent) ); if ( percent>=75 ) { m_level.score = m_level.lifes*15 + (percent-75)*2*(m_game.level+5); nextLevel(); } } void KJezzball::createLevel( int level ) { // destroy old game if ( m_gameWidget ) delete m_gameWidget; m_gameWidget = new JezzGame( level+1, m_view, "m_gameWidget" ); m_gameWidget->show(); m_layout->addMultiCellWidget( m_gameWidget, 0, 0, 0, 3 ); connect( m_gameWidget, SIGNAL(died()), this, SLOT(died()) ); connect( m_gameWidget, SIGNAL(newPercent(int)), this, SLOT(newPercent(int)) ); // update displays m_level.lifes = level+1; LivesLabel->setText( tr( "Lives: %1" ).arg(m_level.lifes) ); FilledLabel->setText( tr( "Filled: 0%" ) ); m_level.time = (level+2)*30; TimeLabel->setText( tr( "Time: %1" ).arg(m_level.time) ); m_level.score = 0; } void KJezzball::startLevel() { if ( m_gameWidget ) { m_timer->start( 1000 ); m_gameWidget->start(); } } void KJezzball::stopLevel() { if ( m_gameWidget ) { m_gameWidget->stop(); m_timer->stop(); } } void KJezzball::nextLevel() { stopLevel(); m_nextLevelTimer->start( 100, TRUE ); } void KJezzball::switchLevel() { m_game.score += m_level.score; ScoreLabel->setText( tr( "Score: %1" ).arg(m_game.score) ); QString score; score.setNum( m_level.score ); QString level; level.setNum( m_game.level ); QString foo = QString( tr("Successfully cleared more than 75%.\n") + tr("%1 points: 15 points per life\n").arg(m_level.lifes*15) + tr("%1 points: Bonus\n").arg((m_gameWidget->percent()-75)*2*(m_game.level+5)) + tr("%1 points: Total score\n").arg(score) + tr("On to level %1.\nYou get %2 lives this time!")).arg(m_game.level+1).arg(m_game.level+2); QMessageBox::information( this, "Success", foo ); m_game.level++; createLevel( m_game.level ); startLevel(); } void KJezzball::keyPressEvent( QKeyEvent *ev ) { if ( ev->key() == Key_Space || ev->key() == Key_Up || ev->key() == Key_Down || ev->key() == Key_Right || ev->key() == Key_Left ) { m_gameWidget->changeCursor(); } else { ev->ignore(); } } diff --git a/noncore/games/buzzword/buzzword.cpp b/noncore/games/buzzword/buzzword.cpp index b870a59..97a17a1 100644 --- a/noncore/games/buzzword/buzzword.cpp +++ b/noncore/games/buzzword/buzzword.cpp @@ -1,182 +1,182 @@ /* * Copyright (C) 2002 Martin Imobersteg <imm@gmx.ch> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License,Life or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <qlayout.h> #include <qmessagebox.h> #include <qmainwindow.h> #include <qlabel.h> #include <qgrid.h> #include <qcolor.h> #include <qbutton.h> #include <qfile.h> #include <qtextstream.h> #include <qstringlist.h> #include <qmessagebox.h> #include <qdir.h> #include <math.h> #include <stdlib.h> #include <qpe/qpeapplication.h> #include "buzzword.h" BuzzLabel::BuzzLabel( QWidget *parent, const char *name ) : QLabel( parent, name ) { } void BuzzLabel::mousePressEvent(QMouseEvent *e) { if(e->button() == LeftButton) { emit clicked(); } } BuzzItem::BuzzItem( int row, int column, QString text, QWidget *parent, const char *name ) : QVBox( parent, name ), _row(row), _column(column) { setFrameStyle( QFrame::Panel | QFrame::Raised ); setLineWidth( 1 ); label = new BuzzLabel(this, "label"); label->setText(text); label->setAlignment( int( QLabel::AlignCenter ) ); connect( label, SIGNAL(clicked()), this, SLOT(flip()) ); } void BuzzItem::flip() { setLineWidth( 1 ); label->setBackgroundColor(label->colorGroup().highlight()); emit clicked(_row, _column); } BuzzWord::BuzzWord() : QMainWindow(0) { setCaption(tr("buZzword")); menu = menuBar(); game = new QPopupMenu; game->insertItem(tr("&New game"), this, SLOT(newGame()), Key_N ); menu->insertItem( tr("&Game"), game ); gridVal = 4; grid = NULL; gameOver = false; newGame(); } void BuzzWord::drawGrid() { QStringList l; QString path = QPEApplication::qpeDir()+"share/buzzword/"; QFile f( path + "buzzwords" ); if ( !f.open( IO_ReadOnly ) ) return; QTextStream t( &f ); while (!t.atEnd()) { l << t.readLine(); } f.close(); grid = new QGrid(gridVal, this); - grid->setFixedSize(240,240); +// grid->setFixedSize( 480, 480 ); for( int c = 0 ; c < gridVal ; c++ ) { for( int r = 0 ; r < gridVal ; r++ ) { uint pos = rand() % l. count(); QString word = QStringList::split(" ", l[pos]).join("\n"); BuzzItem* bi = new BuzzItem( c, r, word, grid ); connect( bi, SIGNAL(clicked(int, int)), this, SLOT(clicked(int,int)) ); map[c][r] = 0; l.remove( l.at( pos )); } } } void BuzzWord::clicked(int row, int column) { if ( ! gameOver ) { int rowTotal = 0; int columnTotal = 0; map[column][row] = 1; for( int c = 0 ; c < gridVal ; c++ ) { for( int r = 0 ; r < gridVal ; r++ ) { if ( map[c][r] == 1 ) rowTotal++; if ( rowTotal == 4 ) { bingo(); } } rowTotal = 0; } for( int r = 0 ; r < gridVal ; r++ ) { for( int c = 0 ; c < gridVal ; c++ ) { if ( map[c][r] == 1 ) columnTotal++; if ( columnTotal == 4 ) { bingo(); } } columnTotal = 0; } if ( map[0][0] && map[1][1] && map[2][2] && map[3][3] ) bingo(); if ( map[0][3] && map[1][2] && map[2][1] && map[3][0] ) bingo(); } } void BuzzWord::bingo() { gameOver = true; QMessageBox::information( this, "BUZZWORD", tr("<h1><b>BINGO !</b></h1>")); } void BuzzWord::newGame() { gameOver = false; delete grid; drawGrid(); setCentralWidget(grid); } diff --git a/noncore/games/fifteen/opie-fifteen.control b/noncore/games/fifteen/opie-fifteen.control index 662fd03..8fa355f 100644 --- a/noncore/games/fifteen/opie-fifteen.control +++ b/noncore/games/fifteen/opie-fifteen.control @@ -1,11 +1,11 @@ Package: opie-fifteen Files: bin/fifteen apps/Games/fifteen.desktop pics/fifteen Priority: optional Section: opie/games Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm Arch: iPAQ -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Fifteen pieces game A game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/go/opie-go.control b/noncore/games/go/opie-go.control index 061c02c..24929de 100644 --- a/noncore/games/go/opie-go.control +++ b/noncore/games/go/opie-go.control @@ -1,10 +1,10 @@ Package: opie-go Files: bin/go apps/Games/go.desktop pics/go Priority: optional Section: opie/games Maintainer: Warwick Allison <warwick@trolltech.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: The game of Go A game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/kpacman/kpacman.cpp b/noncore/games/kpacman/kpacman.cpp index 812e9ea..df27c76 100644 --- a/noncore/games/kpacman/kpacman.cpp +++ b/noncore/games/kpacman/kpacman.cpp @@ -1,368 +1,368 @@ #include "portable.h" #if defined( KDE2_PORT ) #include <kpacman.h> #include <kpacman.moc> #include <kcolordlg.h> #elif defined( QPE_PORT ) #include <qmenubar.h> #include <qpe/config.h> #include <qapplication.h> #include "kpacman.h" #endif #include <qkeycode.h> #include <qcolor.h> #include <qstring.h> #include <qpopmenu.h> #include <qmsgbox.h> Kpacman::Kpacman(QWidget *parent, const char *name) : KTMainWindow(parent, name) { schemesPopup = new QList<QPopupMenu>; schemesPopup->setAutoDelete(TRUE); menu(); m_view = new QWidget( this, "m_view" ); m_view->setBackgroundColor( black ); m_layout = new QGridLayout( m_view ); m_layout->setMargin( 7 ); view = new KpacmanWidget( this, QString(name)+"widget"); m_layout->addWidget( view, 0, 0 ); - setCaption( "KPacman" ); + setCaption( tr("KPacman") ); view->referee->setFocus(); connect(view->referee, SIGNAL(setScore(int, int)), view->score, SLOT(setScore(int, int))); connect(view->referee, SIGNAL(setPoints(int)), view->score, SLOT(set(int))); connect(view->referee, SIGNAL(setLifes(int)), view->status, SLOT(setLifes(int))); connect(view->referee, SIGNAL(setLevel(int)), view->status, SLOT(setLevel(int))); connect(view->referee, SIGNAL(forcedHallOfFame(bool)), this, SLOT(forcedHallOfFame(bool))); connect(view->referee, SIGNAL(togglePaused()), this, SLOT(togglePaused())); connect(view->referee, SIGNAL(toggleNew()), this, SLOT(toggleNew())); connect(view->score, SIGNAL(toggleNew()), this, SLOT(toggleNew())); connect(view->score, SIGNAL(forcedHallOfFame(bool)), this, SLOT(forcedHallOfFame(bool))); APP_CONFIG_BEGIN( cfg ); focusOutPause = !cfg->readBoolEntry("FocusOutPause", TRUE); focusInContinue = !cfg->readBoolEntry("FocusInContinue", TRUE); hideMouseCursor = !cfg->readBoolEntry("HideMouseCursor", TRUE); APP_CONFIG_END( cfg ); toggleFocusOutPause(); toggleFocusInContinue(); toggleHideMouseCursor(); setCentralWidget( m_view ); } Kpacman::~Kpacman() { /* APP_CONFIG_BEGIN( cfg ); cfg->writeEntry("FocusOutPause", focusOutPause); cfg->writeEntry("FocusInContinue", focusInContinue); cfg->writeEntry("HideMouseCursor", hideMouseCursor); APP_CONFIG_END( cfg ); */ delete _menuBar; } void Kpacman::menu() { gamePopup = new QPopupMenu(); CHECK_PTR( gamePopup ); newID = gamePopup->insertItem(tr("&New"), this, SLOT(newKpacman()),Key_F2); pauseID = gamePopup->insertItem(tr("&Pause"), this, SLOT(pauseKpacman()), Key_F3); hofID = gamePopup->insertItem(tr("&Hall of fame"), this, SLOT(toggleHallOfFame()), Key_F4); gamePopup->insertSeparator(); gamePopup->insertItem(tr("&Quit"), this, SLOT(quitKpacman()), CTRL+Key_Q); gamePopup->setCheckable(TRUE); optionsPopup = new QPopupMenu(); CHECK_PTR(optionsPopup); modesPopup = new QPopupMenu(); CHECK_PTR(modesPopup); hideMouseCursorID = optionsPopup->insertItem(tr("&Hide Mousecursor"), this, SLOT(toggleHideMouseCursor()), CTRL+Key_H); optionsPopup->insertSeparator(); if (lookupSchemes() > 0) { optionsPopup->insertItem(tr("&Select graphic scheme"), modesPopup); optionsPopup->insertSeparator(); } focusOutPauseID = optionsPopup->insertItem(tr("&Pause in Background"), this, SLOT(toggleFocusOutPause())); focusInContinueID = optionsPopup->insertItem(tr("&Continue in Foreground"), this, SLOT(toggleFocusInContinue())); optionsPopup->insertSeparator(); optionsPopup->insertItem(tr("Change &keys..."), this, SLOT(confKeys())); #ifndef QPE_PORT QString aboutText = tr("@PACKAGE@ - @VERSION@\n\n" "Joerg Thoennissen (joe@dsite.de)\n\n" "A pacman game for the KDE Desktop\n\n" "The program based on the source of ksnake\n" "by Michel Filippi (mfilippi@sade.rhein-main.de).\n" "The design was strongly influenced by the pacman\n" "(c) 1980 MIDWAY MFG.CO.\n\n" "I like to thank my girlfriend Elke Krueers for\n" "the last 10 years of her friendship.\n"); aboutText.replace(QRegExp("@PACKAGE@"), PACKAGE); aboutText.replace(QRegExp("@VERSION@"), VERSION); QPopupMenu *helpPopup = helpMenu(aboutText, FALSE); #endif //_menuBar = new KMenuBar(this); //CHECK_PTR( _menuBar ); //_menuBar->insertItem(tr("&Game"), gamePopup); //_menuBar->insertItem(tr("&Options"), optionsPopup); //_menuBar->insertSeparator(); #ifndef QPE_PORT _menuBar->insertItem(tr("&Help"), helpPopup); #endif } int Kpacman::lookupSchemes() { APP_CONFIG_BEGIN( cfg ); int ModeCount = cfg->readNumEntry("ModeCount", 0); int Mode = cfg->readNumEntry("Mode", 0); int SchemeCount = cfg->readNumEntry("SchemeCount", 0); int Scheme = cfg->readNumEntry("Scheme", 0); /* if (SchemeCount == 0 || Scheme == -1) { QMessageBox::warning(this, tr("Configuration Error"), tr("There are no schemes defined,\n" "or no scheme is selected.")); APP_CONFIG_END( cfg ); return 0; } */ connect(modesPopup, SIGNAL(activated(int)), this, SLOT(schemeChecked(int))); modeID.resize(ModeCount > 0 ? ModeCount : 0); if (!schemesPopup->isEmpty()) schemesPopup->clear(); SAVE_CONFIG_GROUP( cfg, oldgroup ); QString ModeGroup; QString ModeName; for (int m = 0; m < ModeCount; m++) { ModeGroup.sprintf("Mode %d", m); cfg->setGroup(ModeGroup); ModeName = cfg->readEntry("Description", ModeGroup); QPopupMenu *p = new QPopupMenu; p->setCheckable(TRUE); connect(p, SIGNAL(activated(int)), this, SLOT(schemeChecked(int))); schemesPopup->append(p); modeID[m] = modesPopup->insertItem(ModeName, schemesPopup->at(m)); modesPopup->setItemEnabled(modeID[m], FALSE); modesPopup->setItemChecked(modeID[m], m == Mode); } schemeID.resize(SchemeCount); schemeMode.resize(SchemeCount); QString SchemeGroup; QString SchemeName; int SchemeMode; for (int i = 0; i < SchemeCount; i++) { SchemeGroup.sprintf("Scheme %d", i); cfg->setGroup(SchemeGroup); SchemeName = cfg->readEntry("Description", SchemeGroup); SchemeMode = cfg->readNumEntry("Mode", -1); schemeMode[i] = SchemeMode; if (SchemeMode == -1) { schemeID[i] = modesPopup->insertItem(SchemeName); modesPopup->setItemChecked(schemeID[i], i == Scheme); } else { schemeID[i] = schemesPopup->at(SchemeMode)->insertItem(SchemeName); schemesPopup->at(SchemeMode)-> setItemChecked(schemeID[i], i == Scheme); modesPopup->setItemEnabled(modeID[SchemeMode], TRUE); } } RESTORE_CONFIG_GROUP( cfg, oldgroup ); APP_CONFIG_END( cfg ); return SchemeCount; } void Kpacman::quitKpacman() { APP_QUIT(); } void Kpacman::newKpacman() { if (!gamePopup->isItemEnabled(hofID)) gamePopup->setItemEnabled(hofID, TRUE); if (gamePopup->isItemChecked(hofID)) toggleHallOfFame(); if (gamePopup->isItemChecked(pauseID)) pauseKpacman(); view->referee->play(); } void Kpacman::pauseKpacman() { view->referee->pause(); view->score->setPause(gamePopup->isItemChecked(pauseID)); } void Kpacman::toggleHallOfFame() { gamePopup->setItemChecked(hofID, !gamePopup->isItemChecked(hofID)); view->referee->toggleHallOfFame(); if (gamePopup->isItemChecked(hofID)) { view->referee->lower(); view->status->lower(); } else { view->status->raise(); view->referee->raise(); view->referee->setFocus(); } } /* * Disable or enable the "Hall of fame"-menuitem if the referee says so. * This is done, to disable turning off the "hall of fame"-display, in the automated * sequence of displaying the introduction, the demonstration (or playing) and the * hall of fame. * If on == TRUE then also lower the referee and the status widgets. */ void Kpacman::forcedHallOfFame(bool on) { if (!on && !gamePopup->isItemChecked(hofID)) return; gamePopup->setItemEnabled(hofID, !on); gamePopup->setItemChecked(hofID, on); view->referee->toggleHallOfFame(); if (on) { view->referee->lower(); view->status->lower(); } else { view->status->raise(); view->referee->raise(); view->referee->setFocus(); view->referee->intro(); } } void Kpacman::togglePaused() { static bool checked = FALSE; checked = !checked; gamePopup->setItemChecked( pauseID, checked ); view->score->setPause(gamePopup->isItemChecked(pauseID)); } /* * This disables the "New Game" menuitem to prevent interruptions of the current * play. */ void Kpacman::toggleNew() { gamePopup->setItemEnabled(newID, !gamePopup->isItemEnabled(newID)); } void Kpacman::toggleHideMouseCursor() { hideMouseCursor = !hideMouseCursor; optionsPopup->setItemChecked(hideMouseCursorID, hideMouseCursor); if (hideMouseCursor) view->setCursor(blankCursor); else view->setCursor(arrowCursor); } void Kpacman::toggleFocusOutPause() { focusOutPause = !focusOutPause; optionsPopup->setItemChecked(focusOutPauseID, focusOutPause); view->referee->setFocusOutPause(focusOutPause); } void Kpacman::toggleFocusInContinue() { focusInContinue = !focusInContinue; optionsPopup->setItemChecked(focusInContinueID, focusInContinue); view->referee->setFocusInContinue(focusInContinue); } void Kpacman::confKeys() { Keys *keys = new Keys(); if (keys->exec() == QDialog::Accepted) { view->referee->initKeys(); view->score->initKeys(); } delete keys; } void Kpacman::schemeChecked(int id) { int mode = 0, scheme = -1; for (uint s = 0; s < schemeID.size(); s++) { if (schemeID[s] == id) { scheme = s; mode = schemeMode[s]; } if (schemeMode[s] == -1) { modesPopup->setItemChecked(schemeID[s], schemeID[s] == id); } else { modesPopup->setItemChecked(modeID[schemeMode[s]], schemeMode[s] == mode); schemesPopup->at(schemeMode[s])->setItemChecked(schemeID[s], schemeID[s] == id); } } /* APP_CONFIG_BEGIN( cfg ); cfg->writeEntry("Scheme", scheme); cfg->writeEntry("Mode", mode); APP_CONFIG_END( cfg ); */ view->setScheme(scheme, mode); view->updateGeometry(); updateGeometry(); update(); repaint(TRUE); show(); } diff --git a/noncore/games/mindbreaker/opie-mindbreaker.control b/noncore/games/mindbreaker/opie-mindbreaker.control index 7623d6a..7b5ead6 100644 --- a/noncore/games/mindbreaker/opie-mindbreaker.control +++ b/noncore/games/mindbreaker/opie-mindbreaker.control @@ -1,10 +1,10 @@ Package: opie-mindbreaker Files: bin/mindbreaker apps/Games/mindbreaker.desktop pics/mindbreaker Priority: optional Section: opie/games Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Game: crack the coloured code A game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/minesweep/opie-minesweep.control b/noncore/games/minesweep/opie-minesweep.control index 7236cf8..32f0352 100644 --- a/noncore/games/minesweep/opie-minesweep.control +++ b/noncore/games/minesweep/opie-minesweep.control @@ -1,10 +1,10 @@ Package: opie-minesweep Files: bin/minesweep apps/Games/minesweep.desktop pics/minesweep Priority: optional Section: opie/games Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Game: find the mines A game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/parashoot/opie-parashoot.control b/noncore/games/parashoot/opie-parashoot.control index ad955f5..758d24d 100644 --- a/noncore/games/parashoot/opie-parashoot.control +++ b/noncore/games/parashoot/opie-parashoot.control @@ -1,10 +1,10 @@ Package: opie-parashoot Files: bin/parashoot apps/Games/parashoot.desktop pics/parashoot Priority: optional Section: opie/games Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Game: shoot the parachutists A game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/qasteroids/opie-qasteroids.control b/noncore/games/qasteroids/opie-qasteroids.control index 49cc6b2..25a49b4 100644 --- a/noncore/games/qasteroids/opie-qasteroids.control +++ b/noncore/games/qasteroids/opie-qasteroids.control @@ -1,10 +1,10 @@ Package: opie-qasteroids Files: bin/qasteroids apps/Games/qasteroids.desktop pics/qasteroids/* Priority: optional Section: opie/games Maintainer: Martin Jones <mjones@trolltech.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Game: shoot the asteroids A game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/sfcave-sdl/sfcave-sdl.control b/noncore/games/sfcave-sdl/sfcave-sdl.control index c017280..9bf43ba 100644 --- a/noncore/games/sfcave-sdl/sfcave-sdl.control +++ b/noncore/games/sfcave-sdl/sfcave-sdl.control @@ -1,10 +1,10 @@ Files: bin/sfcave-sdl apps/Games/sfcave-sdl.desktop pics/sfcave-sdl sounds/sfcave-sdl Package: sfcave-sdl Priority: optional Section: Games -Version: $QPE_VERSION-$SUB_VERSION Architecture: arm Maintainer: Andy Qua (andy.qua@blueyonder.co.uk) Depends: libSDL,libSDL_-mixer,libSDL-image,libSDL-gfx Description: SFCave SDL for the Zaurus. Fly though the cave avoiding the walls. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/sfcave/opie-sfcave.control b/noncore/games/sfcave/opie-sfcave.control index 1566959..0ff3e2c 100644 --- a/noncore/games/sfcave/opie-sfcave.control +++ b/noncore/games/sfcave/opie-sfcave.control @@ -1,9 +1,9 @@ Package: opie-sfcave Files: bin/sfcave apps/Games/sfcave.desktop pics/sfcave Priority: optional Section: opie/games Maintainer: Andy Qua <andy.qua@blueyonder.co.uk> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: SFCave for the Zaurus. Fly the dot though the cave avoiding the walls. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/snake/interface.cpp b/noncore/games/snake/interface.cpp index 0f312ac..68e0f14 100644 --- a/noncore/games/snake/interface.cpp +++ b/noncore/games/snake/interface.cpp @@ -1,221 +1,221 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "interface.h" #include <qpe/resource.h> #include <qpe/qpetoolbar.h> #include <qtoolbutton.h> #include <qstyle.h> #include <qapplication.h> #include <qmessagebox.h> SnakeGame::SnakeGame(QWidget* parent, const char* name, WFlags f) : QMainWindow(parent,name,f), canvas(232, 258) { setCaption( tr("Snake") ); QPixmap bg = Resource::loadPixmap("snake/grass"); canvas.setBackgroundPixmap(bg); canvas.setUpdatePeriod(100); snake = 0; cv = new QCanvasView(&canvas, this); pauseTimer = new QTimer(this); connect(pauseTimer, SIGNAL(timeout()), this, SLOT(wait()) ); setToolBarsMovable( FALSE ); QPEToolBar* toolbar = new QPEToolBar( this); toolbar->setHorizontalStretchable( TRUE ); QPixmap newicon = Resource::loadPixmap("ksnake"); setIcon(newicon); (void)new QToolButton(newicon, tr("New Game"), 0, this, SLOT(newGame()), toolbar, "New Game"); scorelabel = new QLabel(toolbar); showScore(0); scorelabel->setBackgroundMode( PaletteButton ); scorelabel->setAlignment( AlignRight | AlignVCenter | ExpandTabs ); toolbar->setStretchableWidget( scorelabel ); setFocusPolicy(StrongFocus); setCentralWidget(cv); QTimer::singleShot( 16, this, SLOT(welcomescreen()) ); gamestopped = true; waitover = true; } SnakeGame::~SnakeGame() { delete snake; } void SnakeGame::resizeEvent(QResizeEvent *) { QSize s = centralWidget()->size(); int fw = style().defaultFrameWidth(); canvas.resize( s.width() - fw - 2, s.height() - fw - 2); } void SnakeGame::welcomescreen() { QCanvasText* title = new QCanvasText(tr("SNAKE!"), &canvas); title->setColor(yellow); title->setFont( QFont("times", 18, QFont::Bold) ); int w = title->boundingRect().width(); title->move(canvas.width()/2 -w/2, canvas.height()/2-110); title->show(); QCanvasPixmapArray* titlearray = new QCanvasPixmapArray(Resource::findPixmap("snake/title")); QCanvasSprite* titlepic = new QCanvasSprite(titlearray, &canvas); titlepic->move(canvas.width()/2 - 33, canvas.height()/2-85); titlepic->show(); QCanvasText* instr = new QCanvasText(tr("Use the arrow keys to guide the\n" "snake to eat the mouse. You must not\n" "crash into the walls, edges or its tail."), &canvas); w = instr->boundingRect().width(); instr->move(canvas.width()/2-w/2, canvas.height()/2-20); instr->setColor(white); instr->show(); - QCanvasText* cont = new QCanvasText(tr("Press Any Key To Start"), &canvas); + QCanvasText* cont = new QCanvasText(tr("Press any key to start"), &canvas); w = cont->boundingRect().width(); cont->move(canvas.width()/2-w/2, canvas.height()-20); cont->setColor(yellow); cont->show(); } void SnakeGame::newGame() { clear(); snake = new Snake(&canvas); connect(snake, SIGNAL(dead()), this, SLOT(gameOver()) ); connect(snake, SIGNAL(targethit()), this, SLOT(levelUp()) ); connect(snake, SIGNAL(scorechanged()), this, SLOT(scoreInc()) ); connect(this, SIGNAL(moveFaster()), snake, SLOT(increaseSpeed()) ); last = 0; targetamount = 1; notargets = 1; level = 1; stage = 1; showScore(0); gamestopped = false; waitover = true; int y = canvas.height()-50; (void)new Obstacle(&canvas, 32); (void)new Obstacle(&canvas, y); createTargets(); } void SnakeGame::showScore(int score) { scorelabel->setText(tr(" Score : %1 ").arg(score) ); } void SnakeGame::scoreInc() { showScore( snake->getScore() ); } void SnakeGame::levelUp() { notargets--; if (notargets == 0) { stage++; if (stage == 3) { level++; emit moveFaster(); targetamount++; stage = 0; } createTargets(); } } void SnakeGame::createTargets() { for (int i = 0; i < targetamount; i++) (void)new Target(&canvas); notargets = targetamount; } void SnakeGame::clear() { delete snake; snake = 0; QCanvasItemList l = canvas.allItems(); for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) { delete *it; } } void SnakeGame::gameOver() { int score = snake->getScore(); QString scoreoutput=""; scoreoutput.setNum(score); QCanvasText* gameover = new QCanvasText(tr("GAME OVER!\n Your Score: %1").arg( scoreoutput), &canvas); gameover->setZ(100); gameover->setColor(yellow); gameover->setFont( QFont("times", 18, QFont::Bold) ); int w = gameover->boundingRect().width(); gameover->move(canvas.width()/2 -w/2, canvas.height()/2 -50); gameover->show(); gamestopped = true; waitover = false; pauseTimer->start(1500); } void SnakeGame::wait() { waitover = true; pauseTimer->stop(); - QCanvasText* cont = new QCanvasText(tr("Press Any Key to Begin a New Game."), + QCanvasText* cont = new QCanvasText(tr("Press any key to begin a new game."), &canvas); cont->setZ(100); cont->setColor(white); int w = cont->boundingRect().width(); cont->move(canvas.width()/2 -w/2, canvas.height()/2); cont->show(); } void SnakeGame::keyPressEvent(QKeyEvent* event) { if (gamestopped) { if (waitover) newGame(); else return; } else { int newkey = event->key(); snake->go(newkey); } } diff --git a/noncore/games/snake/opie-snake.control b/noncore/games/snake/opie-snake.control index 3ab6640..ef4fc61 100644 --- a/noncore/games/snake/opie-snake.control +++ b/noncore/games/snake/opie-snake.control @@ -1,10 +1,10 @@ Package: opie-snake Files: bin/snake apps/Games/snake.desktop pics/snake Priority: optional Section: opie/games Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Game: control the snake A game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/solitaire/canvascardwindow.cpp b/noncore/games/solitaire/canvascardwindow.cpp index e836eb2..317a02d 100644 --- a/noncore/games/solitaire/canvascardwindow.cpp +++ b/noncore/games/solitaire/canvascardwindow.cpp @@ -1,314 +1,314 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "canvascardwindow.h" #include "patiencecardgame.h" #include "freecellcardgame.h" #include "chicanecardgame.h" #include "harpcardgame.h" #include "teeclubcardgame.h" #include <qpe/resource.h> #include <qmainwindow.h> #include <qpopupmenu.h> #include <qstyle.h> CanvasCardWindow::CanvasCardWindow(QWidget* parent, const char* name, WFlags f) : QMainWindow(parent, name, f), canvas(230, 260), snapOn(TRUE), cardBack(4), gameType(0), cardGame(NULL) { setIcon( Resource::loadPixmap( "cards" ) ); // Create Playing Area for Games if ( QPixmap::defaultDepth() < 12 ) { // canvas.setBackgroundColor(QColor(0x51, 0x74, 0x6B)); // canvas.setBackgroundColor(QColor(0x20, 0xb0, 0x50)); canvas.setBackgroundColor(QColor(0x08, 0x98, 0x2D)); } else { QPixmap bg; bg.convertFromImage( Resource::loadImage( "table_pattern" ), ThresholdDither ); canvas.setBackgroundPixmap(bg); } #if defined( QT_QWS_CASSIOPEIA ) canvas.setAdvancePeriod(70); #else canvas.setAdvancePeriod(30); #endif #ifdef _PATIENCE_USE_ACCELS_ QPEMenuBar* menu = menuBar(); QPopupMenu* file = new QPopupMenu; file->insertItem(tr("Patience"), this, SLOT(initPatience()), CTRL+Key_F); file->insertItem(tr("Freecell"), this, SLOT(initFreecell()), CTRL+Key_F); file->insertItem(tr("Chicane"), this, SLOT(initChicane()), CTRL+Key_F); file->insertItem(tr("Harp"), this, SLOT(initHarp()), CTRL+Key_F); file->insertItem(tr("Teeclub"), this, SLOT(initTeeclub()), CTRL+Key_F); menu->insertItem(tr("&Game"), file); menu->insertSeparator(); settings = new QPopupMenu; - settings->insertItem(tr("&Change Card Backs"), this, SLOT(changeCardBacks()), Key_F2); - snap_id = settings->insertItem(tr("&Snap To Position"), this, SLOT(snapToggle()), Key_F3); + settings->insertItem(tr("&Change card backs"), this, SLOT(changeCardBacks()), Key_F2); + snap_id = settings->insertItem(tr("&Snap to position"), this, SLOT(snapToggle()), Key_F3); settings->setCheckable(TRUE); menu->insertItem(tr("&Settings"),settings); menu->insertSeparator(); QPopupMenu* help = new QPopupMenu; help->insertItem(tr("&About"), this, SLOT(help()), Key_F1); help->setItemChecked(dbf_id, TRUE); menu->insertItem(tr("&Help"),help); #else QMenuBar* menu = menuBar(); QPopupMenu* file = new QPopupMenu; file->insertItem(tr("Patience"), this, SLOT(initPatience())); file->insertItem(tr("Freecell"), this, SLOT(initFreecell())); file->insertItem(tr("Chicane"), this, SLOT(initChicane())); file->insertItem(tr("Harp"), this, SLOT(initHarp())); file->insertItem(tr("Teeclub"), this, SLOT(initTeeclub())); menu->insertItem(tr("Play"), file); menu->insertSeparator(); settings = new QPopupMenu; settings->setCheckable(TRUE); - settings->insertItem(tr("Change Card Backs"), this, SLOT(changeCardBacks())); - snap_id = settings->insertItem(tr("Snap To Position"), this, SLOT(snapToggle())); + settings->insertItem(tr("Change card backs"), this, SLOT(changeCardBacks())); + snap_id = settings->insertItem(tr("Snap to position"), this, SLOT(snapToggle())); QString m; - drawId = settings->insertItem(tr("Turn One Card"), this, SLOT(drawnToggle())); + drawId = settings->insertItem(tr("Turn one card"), this, SLOT(drawnToggle())); menu->insertItem(tr("Settings"),settings); settings->setCheckable(TRUE); #endif menu->show(); Config cfg( "Patience" ); cfg.setGroup( "GlobalSettings" ); snapOn = cfg.readBoolEntry( "SnapOn", TRUE); settings->setItemChecked(snap_id, snapOn); gameType = cfg.readNumEntry( "GameType", -1 ); drawThree = cfg.readBoolEntry( "DrawThree", FALSE); if ( gameType == 0 ) { cardGame = new PatienceCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(drawThree ? 3 : 1); setCaption(tr("Patience")); setCentralWidget(cardGame); cardGame->readConfig( cfg ); setCardBacks(); } else if ( gameType == 1 ) { cardGame = new FreecellCardGame( &canvas, snapOn, this ); setCaption(tr("Freecell")); setCentralWidget(cardGame); //cardGame->newGame(); // Until we know how to handle reading freecell config cardGame->readConfig( cfg ); setCardBacks(); } else if ( gameType == 2 ) { cardGame = new ChicaneCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); setCaption(tr("Chicane")); setCentralWidget(cardGame); cardGame->readConfig( cfg ); setCardBacks(); } else if ( gameType == 3 ) { cardGame = new HarpCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); setCaption(tr("Harp")); setCentralWidget(cardGame); cardGame->readConfig( cfg ); setCardBacks(); } else if ( gameType == 4 ) { cardGame = new TeeclubCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); setCaption(tr("Teeclub")); setCentralWidget(cardGame); cardGame->readConfig( cfg ); setCardBacks(); } else { // Probably there isn't a config file or it is broken // Start a new game initPatience(); } updateDraw(); } CanvasCardWindow::~CanvasCardWindow() { if (cardGame) { Config cfg("Patience"); cfg.setGroup( "GlobalSettings" ); cfg.writeEntry( "GameType", gameType ); cfg.writeEntry( "SnapOn", snapOn ); cfg.writeEntry( "DrawThree", drawThree); cfg.write(); cardGame->writeConfig( cfg ); delete cardGame; } } void CanvasCardWindow::resizeEvent(QResizeEvent *) { QSize s = centralWidget()->size(); int fw = style().defaultFrameWidth(); canvas.resize( s.width() - fw - 2, s.height() - fw - 2); } void CanvasCardWindow::initPatience() { // Create New Game if ( cardGame ) delete cardGame; cardGame = new PatienceCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(drawThree ? 3 : 1); gameType = 0; setCaption(tr("Patience")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); updateDraw(); } void CanvasCardWindow::initFreecell() { // Create New Game if ( cardGame ) { delete cardGame; } cardGame = new FreecellCardGame( &canvas, snapOn, this ); gameType = 1; setCaption(tr("Freecell")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); } void CanvasCardWindow::initChicane() { // Create New Game if ( cardGame ) { delete cardGame; } cardGame = new ChicaneCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); gameType = 2; setCaption(tr("Chicane")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); } void CanvasCardWindow::initHarp() { // Create New Game if ( cardGame ) { delete cardGame; } cardGame = new HarpCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); gameType = 3; setCaption(tr("Harp")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); } void CanvasCardWindow::initTeeclub() { // Create New Game if ( cardGame ) { delete cardGame; } cardGame = new TeeclubCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); gameType = 4; setCaption(tr("Teeclub")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); } void CanvasCardWindow::snapToggle() { snapOn = !snapOn; settings->setItemChecked(snap_id, snapOn); cardGame->toggleSnap(); } void CanvasCardWindow::drawnToggle() { drawThree=!drawThree; Config cfg( "Patience" ); cfg.setGroup( "GlobalSettings" ); cardGame->toggleCardsDrawn(); updateDraw(); cfg.writeEntry( "DrawThree", drawThree); cfg.write(); } void CanvasCardWindow::updateDraw() { if(cardGame->cardsDrawn() == 3){ - settings->changeItem(drawId, tr("Turn One Card")); + settings->changeItem(drawId, tr("Turn one card")); } else { - settings->changeItem(drawId, tr("Turn Three Cards")); + settings->changeItem(drawId, tr("Turn three cards")); } } void CanvasCardWindow::setCardBacks() { QCanvasItemList l = canvas.allItems(); for (QCanvasItemList::Iterator it = l.begin(); it != l.end(); ++it) { if ( (*it)->rtti() == canvasCardId ) ((CanvasCard *)(*it))->setCardBack( cardBack ); } } void CanvasCardWindow::changeCardBacks() { cardBack++; if (cardBack == 5) cardBack = 0; setCardBacks(); } diff --git a/noncore/games/solitaire/opie-solitaire.control b/noncore/games/solitaire/opie-solitaire.control index 76e7208..5fa521f 100644 --- a/noncore/games/solitaire/opie-solitaire.control +++ b/noncore/games/solitaire/opie-solitaire.control @@ -1,10 +1,10 @@ Package: opie-solitaire Files: bin/patience apps/Games/patience.desktop pics/cards Priority: optional Section: opie/games Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Game: solitaire card games A solitaire game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/tetrix/opie-tetrix.control b/noncore/games/tetrix/opie-tetrix.control index e335507..e901dbf 100644 --- a/noncore/games/tetrix/opie-tetrix.control +++ b/noncore/games/tetrix/opie-tetrix.control @@ -1,11 +1,11 @@ Package: opie-tetrix Files: bin/tetrix apps/Games/tetrix.desktop pics/tetrix/* Priority: optional Section: opie/games Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm Arch: iPAQ -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Game: control falling blocks A game for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/tictac/main.cpp b/noncore/games/tictac/main.cpp index f2ab334..78fb3b7 100644 --- a/noncore/games/tictac/main.cpp +++ b/noncore/games/tictac/main.cpp @@ -1,31 +1,31 @@ /**************************************************************************** ** $Id$ ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *****************************************************************************/ #include <qpe/qpeapplication.h> #include <stdlib.h> #include "tictac.h" int main( int argc, char **argv ) { QPEApplication a( argc, argv ); int n = 3; if ( argc == 2 ) // get board size n n = atoi(argv[1]); if ( n < 3 || n > 10 ) { // out of range qWarning( "%s: Board size must be from 3x3 to 10x10", argv[0] ); return 1; } TicTacToe ttt( n ); // create game a.setMainWidget( &ttt ); - ttt.setCaption("TicTac"); + ttt.setCaption( QObject::tr("TicTac") ); ttt.show(); // show widget return a.exec(); // go } diff --git a/noncore/games/tictac/opie-tictac.control b/noncore/games/tictac/opie-tictac.control index c4ee36c..0074505 100644 --- a/noncore/games/tictac/opie-tictac.control +++ b/noncore/games/tictac/opie-tictac.control @@ -1,9 +1,9 @@ Package: opie-tictac Files: bin/tictac apps/Games/tictac.desktop pics/tictac Priority: optional Section: opie/games Maintainer: ljp <ljp@llornkcor.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Tic Tac Toe game. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/wordgame/opie-wordgame.control b/noncore/games/wordgame/opie-wordgame.control index 3be8e8f..c7dc126 100644 --- a/noncore/games/wordgame/opie-wordgame.control +++ b/noncore/games/wordgame/opie-wordgame.control @@ -1,11 +1,11 @@ Package: opie-wordgame Files: bin/wordgame apps/Games/wordgame.desktop pics/wordgame Priority: optional Section: opie/games Maintainer: Martin Imobersteg <imm@gmx.ch> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Crossword game A crossword game for the Opie environment. Play against the computer or human opponents. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/games/wordgame/wordgame.cpp b/noncore/games/wordgame/wordgame.cpp index d3160f4..d46e824 100644 --- a/noncore/games/wordgame/wordgame.cpp +++ b/noncore/games/wordgame/wordgame.cpp @@ -1,1519 +1,1519 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "wordgame.h" #include <qpe/applnk.h> #include <qpe/global.h> #include <qpe/filemanager.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qapplication.h> #include <qmessagebox.h> #include <qcombobox.h> #include <qdatetime.h> #include <qfileinfo.h> #include <qfile.h> #include <qdir.h> #include <qiconset.h> #include <qlabel.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qtextstream.h> #include <qtimer.h> #include <qpe/qpetoolbar.h> #include <qtoolbutton.h> #include <qvbox.h> #include <qwidgetstack.h> #include <qpainter.h> #include <qlayout.h> #include <qregexp.h> #include <stdlib.h> #include <unistd.h> #include <pwd.h> #include <sys/types.h> enum RuleEffects { Multiplier=15, MultiplyAll=64, Start=128 }; static int tile_smallw = 16; static int tile_smallh = 16; static int tile_bigw = 22; static int tile_bigh = 22; static int tile_stweak = -2; static int tile_btweak = -1; static const int rack_tiles=7; const char* sampleWGR= "wordgame_shapes\n" "15 15\n" "400001040100004\n" "030000000000030\n" "002002000200200\n" "000300020003000\n" "000020000020000\n" "102001000100201\n" "000000202000000\n" "400200050002004\n" "000000202000000\n" "102001000100201\n" "000020000020000\n" "000300020003000\n" "002002000200200\n" "030000000000030\n" "400001040100004\n" "1 2 3 66 67 194 100 0\n" "1 j 8\n" "1 q 7\n" "1 x 6\n" "1 z 6\n" "1 w 4\n" "1 k 4\n" "1 v 3\n" "1 f 3\n" "2 y 3\n" "2 h 2\n" "2 b 2\n" "2 m 2\n" "3 p 2\n" "3 g 2\n" "3 u 2\n" "4 d 2\n" "4 c 2\n" "5 l 1\n" "5 o 1\n" "7 t 1\n" "7 n 1\n" "7 a 1\n" "7 r 1\n" "8 s 1\n" "8 i 1\n" "11 e 1\n" "0\n"; WordGame::WordGame( QWidget* parent, const char* name, WFlags fl ) : QMainWindow(parent, name, fl) { if ( qApp->desktop()->width() < 240 ) { tile_smallw = 10; tile_smallh = 10; tile_bigw = 16; tile_bigh = 16; tile_stweak = 0; tile_btweak = 0; } setIcon( Resource::loadPixmap( "wordgame/WordGame.png" ) ); setCaption( tr("Word Game") ); setToolBarsMovable( FALSE ); vbox = new QVBox(this); setCentralWidget(vbox); toolbar = new QPEToolBar(this); addToolBar(toolbar, Bottom); reset = new QToolButton(Resource::loadPixmap("back"), tr("Back"), "", this, SLOT(resetTurn()), toolbar); done = new QToolButton(Resource::loadPixmap("done"), tr("Done"), "", this, SLOT(endTurn()), toolbar); scoreinfo = new ScoreInfo(toolbar); scoreinfo->setFont(QFont("Helvetica",10)); new QToolButton(Resource::loadPixmap("finish"), tr("Close"), "", this, SLOT(endGame()), toolbar); toolbar->setStretchableWidget(scoreinfo); cpu = 0; board = 0; bag = 0; racks = 0; aiheart = new QTimer(this); connect(aiheart, SIGNAL(timeout()), this, SLOT(think())); readConfig(); } WordGame::~WordGame() { writeConfig(); } void WordGame::writeConfig() { Config cfg("WordGame"); cfg.setGroup("Game"); cfg.writeEntry("NameList",namelist,';'); cfg.writeEntry("CurrentPlayer",gameover ? 0 : player+1); if ( !gameover ) { cfg.writeEntry("Rules",rules); bag->writeConfig(cfg); board->writeConfig(cfg); scoreinfo->writeConfig(cfg); } for (int p=0; p<nplayers; p++) { cfg.setGroup("Player"+QString::number(p+1)); if ( gameover ) cfg.clearGroup(); else rack(p)->writeConfig(cfg); } } void WordGame::readConfig() { Config cfg("WordGame"); cfg.setGroup("Game"); int currentplayer = cfg.readNumEntry("CurrentPlayer",0); QStringList pnames = cfg.readListEntry("NameList",';'); if ( currentplayer ) { gameover = FALSE; rules = cfg.readEntry("Rules"); if ( rules.find("x-wordgamerules") >= 0 ) { // rules files moved rules = "Sample.rules"; } if ( loadRules(rules) ) { startGame(pnames); bag->readConfig(cfg); board->readConfig(cfg); scoreinfo->readConfig(cfg); for (int p=0; p<nplayers; p++) { cfg.setGroup("Player"+QString::number(p+1)); rack(p)->readConfig(cfg); } player=currentplayer-1; readyRack(player); return; } } // fall-back openGameSelector(pnames); } void WordGame::openGameSelector(const QStringList& initnames) { toolbar->hide(); gameover = FALSE; delete board; board = 0; delete racks; racks = 0; delete cpu; cpu = 0; newgame = new NewGame(vbox); //Rules rules(this); //connect(game.editrules, SIGNAL(clicked()), &rules, SLOT(editRules())); //connect(&rules, SIGNAL(rulesChanged()), &game, SLOT(updateRuleSets())); struct passwd* n = getpwuid(getuid()); QString playername = n ? n->pw_name : ""; if ( playername.isEmpty() ) { playername = "Player"; } newgame->player0->changeItem(playername,0); newgame->player1->setCurrentItem(1); newgame->updateRuleSets(); newgame->show(); connect(newgame->buttonOk, SIGNAL(clicked()), this, SLOT(startGame())); } void WordGame::startGame() { rules = newgame->ruleslist[newgame->rules->currentItem()]; if ( loadRules(rules) ) { QStringList names; names.append(newgame->player0->currentText()); names.append(newgame->player1->currentText()); names.append(newgame->player2->currentText()); names.append(newgame->player3->currentText()); names.append(newgame->player4->currentText()); names.append(newgame->player5->currentText()); delete newgame; startGame(names); } else { // error... delete newgame; close(); } } void WordGame::startGame(const QStringList& playerlist) { toolbar->show(); racks = new QWidgetStack(vbox); racks->setFixedHeight(TileItem::bigHeight()+2); namelist.clear(); nplayers=0; for (QStringList::ConstIterator it=playerlist.begin(); it!=playerlist.end(); ++it) addPlayer(*it); scoreinfo->init(namelist); if ( nplayers ) { player=0; readyRack(player); } board->show(); racks->show(); } bool WordGame::loadRules(const QString &name) { QString filename = Global::applicationFileName( "wordgame", name ); QFile file( filename ); if ( !file.open( IO_ReadOnly ) ) return FALSE; QTextStream ts( &file ); QString title = name; title.truncate( title.length() - 6 ); - setCaption( title ); + //setCaption( title ); QString shapepixmap; ts >> shapepixmap; int htiles,vtiles; ts >> htiles >> vtiles; if ( htiles < 3 || vtiles < 3 ) return FALSE; QString rule_shapes; for (int i=0; i<vtiles; i++) { QString line; ts >> line; rule_shapes += line; } static int rule_effects[12]; int re=0,e; ts >> e; while ( e && re < 10 ) { rule_effects[re] = e; if ( re++ < 10 ) ts >> e; } - QImage shim = Resource::loadImage("wordgame/wordgame_shapes.xpm"); + QImage shim = Resource::loadImage("wordgame/wordgame_shapes"); shim = shim.smoothScale((re-1)*TileItem::smallWidth(),TileItem::smallHeight()); QPixmap bgshapes; bgshapes.convertFromImage(shim); rule_effects[re++] = 100; // default bonus board = new Board(bgshapes, htiles, vtiles, vbox); board->setRules(rule_shapes, rule_effects); connect(board, SIGNAL(temporaryScore(int)), scoreinfo, SLOT(showTemporaryScore(int))); bag = new Bag; int count; ts >> count; while ( count ) { QString text; int value; ts >> text >> value; if ( text == "_" ) text = ""; Tile t(text, value); for (int n=count; n--; ) bag->add(t); ts >> count; } return TRUE; } NewGame::NewGame(QWidget* parent) : NewGameBase(parent) { } void NewGame::updateRuleSets() { rules->clear(); QString rulesDir = Global::applicationFileName( "wordgame", "" ); QDir dir( rulesDir, "*.rules" ); ruleslist = dir.entryList(); if ( ruleslist.isEmpty() ) { // Provide a sample QFile file( rulesDir + "Sample.rules" ); if ( file.open( IO_WriteOnly ) ) { file.writeBlock( sampleWGR, strlen(sampleWGR) ); file.close(); updateRuleSets(); } return; } int newest=0; int newest_age=INT_MAX; QDateTime now = QDateTime::currentDateTime(); QStringList::Iterator it; for ( it = ruleslist.begin(); it != ruleslist.end(); ++it ) { QFileInfo fi((*it)); int age = fi.lastModified().secsTo(now); QString name = *it; name.truncate( name.length()-6 ); // remove extension rules->insertItem( name ); if ( age < newest_age ) { newest_age = age; newest = rules->count()-1; } } rules->setCurrentItem(newest); } Rules::Rules(QWidget* parent) : RulesBase(parent,0,TRUE) { } void Rules::editRules() { if ( exec() ) { // ### create a new set of rules emit rulesChanged(); } } void Rules::deleteRuleSet() { // ### delete existing rule set emit rulesChanged(); } void WordGame::addPlayer(const QString& name) { if ( !name.isEmpty() ) { int colon = name.find(':'); int cpu = (colon >=0 && name.left(2) == "AI") ? name.mid(2,1).toInt() : 0; addPlayer(name,cpu); } } void WordGame::addPlayer(const QString& name, int cpu) { Rack* r = new Rack(rack_tiles,racks); r->setPlayerName(name); r->setComputerization(cpu); racks->addWidget(r, nplayers); refillRack(nplayers); namelist.append(name); ++nplayers; } void WordGame::nextPlayer() { if ( !refillRack(player) ) { endGame(); } else { player = (player+1)%nplayers; scoreinfo->setBoldOne(player); readyRack(player); } } bool WordGame::mayEndGame() { int out=-1; int i; for (i=0; i<nplayers; i++) if ( !rack(i)->count() ) out = i; if ( out<0 ) { if ( QMessageBox::warning(this,tr("End game"), tr("Do you want to end the game early?"), tr("Yes"), tr("No") )!=0 ) { return FALSE; } } return TRUE; } void WordGame::endGame() { if ( gameover ) { close(); return; } if ( !mayEndGame() ) return; int out=-1; int totalleft=0; int i; for (i=0; i<nplayers; i++) { Rack* r = rack(i); int c = r->count(); if ( c ) { int lose=0; for ( int j=0; j<c; j++ ) lose += r->tileRef(j)->value(); totalleft += lose; scoreinfo->addScore(i,-lose); } else { out = i; } } int highest=0; int winner=0; for (i=0; i<nplayers; i++) { int s = scoreinfo->playerScore(i); if ( s > highest ) { highest = s; winner = i; } } if ( out >= 0 ) scoreinfo->addScore(out,totalleft); scoreinfo->setBoldOne(winner); gameover = TRUE; done->setEnabled(TRUE); reset->setEnabled(FALSE); } void WordGame::endTurn() { if ( gameover ) { openGameSelector(namelist); } else { if ( board->checkTurn() ) { if ( board->turnScore() >= 0 ) { scoreinfo->addScore(player,board->turnScore()); board->finalizeTurn(); } else { QApplication::beep(); } nextPlayer(); } } } void WordGame::resetTurn() { board->resetRack(); } void WordGame::passTurn() { // ######## trade? nextPlayer(); } bool WordGame::refillRack(int i) { Rack* r = rack(i); while ( !bag->isEmpty() && !r->isFull() ) { r->addTile(bag->takeRandom()); } return r->count() != 0; } void WordGame::readyRack(int i) { Rack* r = rack(i); racks->raiseWidget(i); board->setCurrentRack(r); done->setEnabled( !r->computerized() ); reset->setEnabled( !r->computerized() ); if ( r->computerized() ) { cpu = new ComputerPlayer(board, r); aiheart->start(0); } } Rack* WordGame::rack(int i) const { return (Rack*)racks->widget(i); } void WordGame::think() { if ( !cpu->step() ) { delete cpu; cpu = 0; aiheart->stop(); if ( board->turnScore() < 0 ) passTurn(); else endTurn(); } } ComputerPlayer::ComputerPlayer(Board* b, Rack* r) : board(b), rack(r), best(new const Tile*[rack_tiles]), best_blankvalues(new Tile[rack_tiles]) { best_score = -1; across=FALSE; dict=0; } ComputerPlayer::~ComputerPlayer() { delete [] best; delete [] best_blankvalues; } bool ComputerPlayer::step() { const QDawg::Node* root = dict ? Global::dawg("WordGame").root() : Global::fixedDawg().root(); QPoint d = across ? QPoint(1,0) : QPoint(0,1); const Tile* tiles[99]; // ### max board size uchar nletter[4095]; // QDawg only handles 0..4095 memset(nletter,0,4096); for (int i=0; i<rack->count(); i++) { const Tile* r = rack->tileRef(i); if ( r->isBlank() ) nletter[0]++; else nletter[r->text()[0].unicode()]++; } Tile blankvalues[99]; // ### max blanks findBest(current, d, root, 0, nletter, tiles, 0, blankvalues, 0); if ( ++current.rx() == board->xTiles() ) { current.rx() = 0; if ( ++current.ry() == board->yTiles() ) { if ( across ) { if ( dict == 1 ) { if ( best_score >= 0 ) { rack->arrangeTiles(best,best_n); rack->setBlanks(best_blankvalues); board->scoreTurn(best_start, best_n, best_dir); board->showTurn(); } return FALSE; } dict++; across = FALSE; current = QPoint(0,0); } else { across = TRUE; current = QPoint(0,0); } } } return TRUE; } void ComputerPlayer::findBest(QPoint at, const QPoint& d, const QDawg::Node* node, ulong used, uchar* nletter, const Tile** tiles, int n, Tile* blankvalues, int blused) { if ( !node ) return; QChar l = node->letter(); const Tile* cur = board->tile(at); if ( cur ) { if ( cur->text()[0] == l ) { bool nextok = board->contains(at+d); if ( node->isWord() && n && (!nextok || !board->tile(at+d)) ) noteChoice(tiles,n,d,blankvalues,blused); if ( nextok ) findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused); // #### text()[1]... } } else { if ( nletter[l.unicode()] || nletter[0] ) { int rc = rack->count(); ulong msk = 1; for ( int x=0; x<rc; x++ ) { if ( !(used&msk) ) { const Tile* t = rack->tileRef(x); if ( t->isBlank() || t->text() == l ) { // #### multi-char value()s bool nextok = board->contains(at+d); tiles[n++] = t; if ( t->isBlank() ) blankvalues[blused++] = Tile(l,0); if ( node->isWord() && (!nextok || !board->tile(at+d)) ) noteChoice(tiles,n,d,blankvalues,blused); used |= msk; // mark nletter[t->text()[0].unicode()]--; if ( nextok ) findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused); n--; nletter[t->text()[0].unicode()]++; if ( t->isBlank() ) { // keep looking blused--; used &= ~msk; // unmark } else { break; } } } msk <<= 1; } } // #### text()[1]... } findBest(at, d, node->next(), used, nletter, tiles, n, blankvalues, blused); } void ComputerPlayer::noteChoice(const Tile** tiles, int n, const QPoint& d, const Tile* blankvalues, int blused) { int s = board->score(current, tiles, n, blankvalues, d, TRUE, 0); /* if (s>0 || current==QPoint(5,1)){ QString st; for ( int i=0; i<n; i++ ) st += tiles[i]->text(); qDebug("%d,%d: %s (%d) for %d",current.x(),current.y(),st.latin1(),n,s); } */ if ( s > best_score ) { int i; for ( i=0; i<n; i++ ) best[i] = tiles[i]; for ( i=0; i<blused; i++ ) best_blankvalues[i] = blankvalues[i]; best_n = n; best_blused = blused; best_score = s; best_dir = d; best_start = current; } } int TileItem::smallWidth() { return tile_smallw; } int TileItem::smallHeight() { return tile_smallh; } int TileItem::bigWidth() { return tile_bigw; } int TileItem::bigHeight() { return tile_bigh; } void TileItem::setState( State state ) { hide(); s = state; show(); // ### use update() in Qt 3.0 } void TileItem::setTile(const Tile& tile) { hide(); t = tile; show(); // ### use update() in Qt 3.0 } void TileItem::setBig(bool b) { big = b; } void TileItem::drawShape(QPainter& p) { static QFont *value_font=0; static QFont *big_font=0; static QFont *small_font=0; if ( !value_font ) { value_font = new QFont("helvetica",8); if ( TileItem::bigWidth() < 20 ) { big_font = new QFont("helvetica",12); small_font = new QFont("helvetica",8); } else { big_font = new QFont("smoothtimes",17); small_font = new QFont("smoothtimes",10); } } QRect area(x(),y(),width(),height()); p.setBrush(s == Floating ? yellow/*lightGray*/ : white); p.drawRect(area); if ( big ) { p.setFont(*value_font); QString n = QString::number(t.value()); int w = p.fontMetrics().width('1'); int h = p.fontMetrics().height(); w *= n.length(); QRect valuearea(x()+width()-w-1,y()+height()-h,w,h); p.drawText(valuearea,AlignCenter,n); p.setFont(*big_font); area = QRect(x(),y()+tile_btweak,width()-4,height()-1); } else { p.setFont(*small_font); area = QRect(x()+1+tile_stweak,y()+1,width(),height()-3); } if ( t.value() == 0 ) p.setPen(darkGray); p.drawText(area,AlignCenter,t.text().upper()); } Board::Board(QPixmap bgshapes, int w, int h, QWidget* parent) : QCanvasView(new QCanvas(bgshapes,w,h, TileItem::smallWidth(), TileItem::smallHeight()), parent) { setFixedSize(w*TileItem::smallWidth(),h*TileItem::smallHeight()); grid = new TileItem*[w*h]; memset(grid,0,w*h*sizeof(TileItem*)); setFrameStyle(0); setHScrollBarMode(AlwaysOff); setVScrollBarMode(AlwaysOff); current_rack = 0; shown_n = 0; } Board::~Board() { delete canvas(); } QSize Board::sizeHint() const { return QSize(canvas()->width(),canvas()->height()); } void Board::writeConfig(Config& cfg) { QStringList t; int n=canvas()->tilesHorizontally()*canvas()->tilesVertically(); for (int i=0; i<n; i++) t.append( grid[i] ? grid[i]->tile().key() : QString(".") ); cfg.writeEntry("Board",t,';'); } void Board::readConfig(Config& cfg) { clear(); QStringList t = cfg.readListEntry("Board",';'); int i=0; int h=canvas()->tilesHorizontally(); for (QStringList::ConstIterator it=t.begin(); it!=t.end(); ++it) { if ( *it != "." ) { QPoint p(i%h,i/h); setTile(p,Tile(*it)); } i++; } canvas()->update(); } void Board::clear() { int n=canvas()->tilesHorizontally()*canvas()->tilesVertically(); for (int i=0; i<n; i++) { delete grid[i]; grid[i]=0; } } void Board::setCurrentRack(Rack* r) { turn_score = -1; current_rack = r; } void Board::resetRack() { unshowTurn(); canvas()->update(); } void Board::contentsMousePressEvent(QMouseEvent* e) { dragstart = e->pos(); } void Board::contentsMouseMoveEvent(QMouseEvent* e) { if ( current_rack && !current_rack->computerized() ) { QPoint d = e->pos() - dragstart; if ( d.x() <= 0 && d.y() <= 0 ) { // None resetRack(); } else { int n; QPoint start=boardPos(dragstart); QPoint end=boardPos(e->pos()); QPoint diff=end-start; QPoint dir; if ( d.x() > d.y() ) { n = diff.x()+1; dir = QPoint(1,0); } else { n = diff.y()+1; dir = QPoint(0,1); } unshowTurn(); // Subtract existing tiles from n QPoint t = start; for ( int i=n; i--; ) { if ( contains(t) && tile(t) ) n--; t += dir; } // Move start back to real start while (contains(start-dir) && tile(start-dir)) start -= dir; scoreTurn(start, n, dir); showTurn(); } } } void Board::finalizeTurn() { int i=0; QPoint at = shown_at; while ( i<shown_n && contains(at) ) { if ( item(at) && item(at)->state() == TileItem::Floating ) { current_rack->remove(item(at)->tile()); setTileState(at,TileItem::Firm); i++; } at += shown_step; } canvas()->update(); } void Board::unshowTurn() { int i=0; QPoint at = shown_at; while ( i<shown_n && i<current_rack->count() && contains(at) ) { if ( item(at) && item(at)->state() == TileItem::Floating ) { unsetTile(at); i++; } at += shown_step; } } void Board::showTurn() { unshowTurn(); QPoint at = shown_at; int i=0; while ( i<shown_n && i<current_rack->count() && contains(at) ) { if ( !tile(at) ) { Tile t = current_rack->tile(i); setTile(at,t); setTileState(at,TileItem::Floating); i++; } at += shown_step; } canvas()->update(); } int Board::bonussedValue(const QPoint& at, int base, int& all_mult) const { int rule = rule_shape[idx(at)]-'0'; int effect = rule_effect[rule]; int mult = effect&Multiplier; if ( effect & MultiplyAll ) { all_mult *= mult; return base; } else { return base * mult; } } bool Board::isStart(const QPoint& at) const { int rule = rule_shape[idx(at)]-'0'; int effect = rule_effect[rule]; return effect&Start; } bool Board::checkTurn() { if ( current_rack->computerized() ) return TRUE; // computer doesn't cheat, and has already set blanks. QPoint at = shown_at; int n = shown_n; QPoint d = shown_step; const Tile* tiles[99]; Tile blankvalues[99]; if ( n > current_rack->count() ) n = current_rack->count(); QDialog check(this,0,TRUE); (new QVBoxLayout(&check))->setAutoAdd(TRUE); QHBox mw(&check); new QLabel(tr("Blanks: "),&mw); int bl=0; QLineEdit* le[99]; for (int i=0; i<n; i++) { tiles[i] = current_rack->tileRef(i); if ( tiles[i]->isBlank() ) { QLineEdit *l = new QLineEdit(&mw); le[bl++] = l; l->setMaxLength(1); l->setFixedSize(l->minimumSizeHint()); } } QHBox btns(&check); connect(new QPushButton(tr("OK"),&btns), SIGNAL(clicked()), &check, SLOT(accept())); connect(new QPushButton(tr("Cancel"),&btns), SIGNAL(clicked()), &check, SLOT(reject())); if ( bl ) { retry: if ( !check.exec() ) { unshowTurn(); canvas()->update(); return FALSE; } for (int b=0; b<bl; b++) { QString v = le[b]->text(); blankvalues[b]=Tile(v,0); if ( v.length() != 1 ) goto retry; } } QStringList words; unshowTurn(); turn_score = score(at,tiles,n,blankvalues,d,FALSE,&words); showTurn(); QStringList to_add; for (QStringList::Iterator it=words.begin(); it!=words.end(); ++it) { if ( !Global::fixedDawg().contains(*it) && !Global::dawg("WordGame").contains(*it) ) { switch (QMessageBox::warning(this, tr("Unknown word"), tr("<p>The word \"%1\" is not in the dictionary.").arg(*it), tr("Add"), tr("Ignore"), tr("Cancel"))) { case 0: // ####### add to wordgame dictionary to_add.append(*it); break; case 1: break; case 2: unshowTurn(); canvas()->update(); return FALSE; } } } if ( to_add.count() ) Global::addWords("WordGame",to_add); return TRUE; } void Board::scoreTurn(const QPoint& at, int n, const QPoint& d) { unshowTurn(); shown_at = at; shown_n = n; shown_step = d; const Tile* tiles[99]; if ( n > current_rack->count() ) n = current_rack->count(); for (int i=0; i<n; i++) tiles[i] = current_rack->tileRef(i); turn_score = score(at,tiles,n,0,d,FALSE,0); emit temporaryScore(turn_score); } int Board::score(QPoint at, const Tile** tiles, int n, const Tile* blankvalue, const QPoint& d, bool checkdict, QStringList* words) const { int total=0; int totalsidetotal=0; // words gets filled with words made // mainword==0 -> // Checks side words, but not main word // -1 means words not in dict, or illegally positioned (eg. not connected) // text is assumed to fit on board. if ( words ) *words=QStringList(); QPoint otherd(d.y(), d.x()); int all_mult = 1; int bl=0; bool connected = FALSE; QString mainword=""; if ( contains(at-d) && tile(at-d) ) { return -1; // preceeding tiles } const Tile* t; for (int i=0; contains(at) && ((t=tile(at)) || i<n); ) { if ( t ) { if ( checkdict || words ) mainword += t->text(); total += t->value(); connected = TRUE; } else { QString sideword; QString tt; if ( tiles[i]->isBlank() ) { if ( blankvalue ) tt = blankvalue[bl++].text(); } else { tt = tiles[i]->text(); } sideword=tt; if ( checkdict || words ) mainword += tt; int side_mult = 1; int tilevalue = bonussedValue(at,tiles[i]->value(),side_mult); all_mult *= side_mult; if ( !connected && isStart(at) ) connected = TRUE; total += tilevalue; int sidetotal = tilevalue; { QPoint side = at-otherd; while ( contains(side) && (t=tile(side)) ) { sidetotal += t->value(); sideword.prepend(t->text()); side -= otherd; } } { QPoint side = at+otherd; while ( contains(side) && (t=tile(side)) ) { sidetotal += t->value(); sideword.append(t->text()); side += otherd; } } if ( sideword.length() > 1 ) { if ( words ) words->append(sideword); if ( checkdict && !Global::fixedDawg().contains(sideword) && !Global::dawg("WordGame").contains(sideword) ) return -1; totalsidetotal += sidetotal * side_mult; connected = TRUE; } i++; } at += d; } if ( words ) words->append(mainword); if ( checkdict && !Global::fixedDawg().contains(mainword) && !Global::dawg("WordGame").contains(mainword) ) return -1; if ( n == rack_tiles ) totalsidetotal += rack_tiles_bonus; return connected ? totalsidetotal + total * all_mult : -1; } QPoint Board::boardPos(const QPoint& p) const { return QPoint(p.x()/canvas()->tileWidth(), p.y()/canvas()->tileHeight()); } void Board::contentsMouseReleaseEvent(QMouseEvent*) { if ( current_rack ) { } } void Board::setRules(const QString& shapes, const int* effects) { rule_shape=shapes; rule_effect=effects; int i=0; int maxre=0; for (int y=0; y<yTiles(); y++) { for (int x=0; x<xTiles(); x++) { int re = shapes[i++]-'0'; if ( re > maxre ) maxre = re; canvas()->setTile(x,y,re); } } rack_tiles_bonus=effects[maxre+1]; } void Board::unsetTile(const QPoint& p) { delete item(p); grid[idx(p)] = 0; } void Board::setTile(const QPoint& p, const Tile& t) { TileItem* it=item(p); if ( !it ) { it = grid[idx(p)] = new TileItem(t,FALSE,canvas()); it->move(p.x()*canvas()->tileWidth(), p.y()*canvas()->tileHeight()); it->show(); } else { it->setTile(t); } } Rack::Rack(int ntiles, QWidget* parent) : QCanvasView( new QCanvas(ntiles*TileItem::bigWidth(),TileItem::bigHeight()), parent), item(ntiles) { setLineWidth(1); setFixedHeight(sizeHint().height()); n = 0; for (int i=0; i<ntiles; i++) item[i]=0; setHScrollBarMode(AlwaysOff); setVScrollBarMode(AlwaysOff); canvas()->setBackgroundColor(gray); dragging = 0; } Rack::~Rack() { clear(); delete canvas(); } QSize Rack::sizeHint() const { return QSize(-1,TileItem::bigHeight()+2); } void Rack::clear() { for (int i=0; i<n; i++) delete item[i]; n=0; } void Rack::writeConfig(Config& cfg) { QStringList l; for (int i=0; i<n; i++) l.append(tile(i).key()); cfg.writeEntry("Tiles",l,';'); } void Rack::readConfig(Config& cfg) { clear(); int x=0; QStringList l = cfg.readListEntry("Tiles",';'); for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) { TileItem *i = new TileItem(Tile(*it),TRUE,canvas()); i->move(x++,0); i->show(); item[n++] = i; } layoutTiles(); } static int cmp_tileitem(const void *a, const void *b) { const TileItem* ia = *(TileItem**)a; const TileItem* ib = *(TileItem**)b; return int(ia->x() - ib->x()); } void Rack::layoutTiles() { int w = TileItem::bigWidth()+2; if ( dragging ) dragging->moveBy(dragging_adj,0); qsort(item.data(), n, sizeof(TileItem*), cmp_tileitem); if ( dragging ) dragging->moveBy(-dragging_adj,0); for (int i=0; i<n ;i++) if ( item[i] == dragging ) { item[i]->setZ(1); } else { item[i]->move(i*w, 0); item[i]->setZ(0); } canvas()->update(); } void Rack::setBlanks(const Tile* bv) { for (int j=0; j<n; j++) { Tile tt = item[j]->tile(); if ( tt.isBlank() ) { tt.setText(bv->text()); item[j]->setTile(tt); bv++; } } } bool Rack::arrangeTiles(const Tile** s, int sn) { bool could = TRUE; for (int j=0; j<n; j++) { Tile tt = item[j]->tile(); int f=-1; for (int i=0; i<sn && f<0; i++) { if (s[i] && *s[i] == tt ) { s[i]=0; f=i; } } if ( f >= 0 ) { item[j]->move(f-999,0); } else { could = FALSE; } } layoutTiles(); return could; } void Rack::addTile(const Tile& t) { TileItem *i = new TileItem(t,TRUE,canvas()); i->show(); item[n++] = i; layoutTiles(); } void Rack::remove(Tile t) { for (int i=0; i<n ;i++) if ( item[i]->tile() == t ) { remove(i); return; } } void Rack::remove(int i) { delete item[i]; n--; for (;i<n;i++) item[i]=item[i+1]; layoutTiles(); } void Rack::resizeEvent(QResizeEvent* e) { canvas()->resize(width()-frameWidth()*2,height()-frameWidth()*2); QCanvasView::resizeEvent(e); } void Rack::contentsMousePressEvent(QMouseEvent* e) { if ( computerized() ) return; QCanvasItemList list = canvas()->collisions(e->pos()); if (list.count()) { dragging = list.first(); dragstart = e->pos()-QPoint(int(dragging->x()),int(dragging->y())); } else { dragging = 0; } } void Rack::contentsMouseMoveEvent(QMouseEvent* e) { if ( computerized() ) return; //int w = TileItem::bigWidth()+2; if ( dragging ) { dragging_adj = TileItem::bigWidth()/2; if ( dragging->x() > e->x()-dragstart.x() ) dragging_adj = -dragging_adj; dragging->move(e->x()-dragstart.x(),0); layoutTiles(); } } void Rack::contentsMouseReleaseEvent(QMouseEvent* e) { if ( computerized() ) return; if ( dragging ) { dragging=0; layoutTiles(); } } Tile::Tile(const QString& key) { int a=key.find('@'); txt = key.left(a); val = key.mid(a+1).toInt(); blank = txt.isEmpty(); } QString Tile::key() const { return txt+"@"+QString::number(val); } Bag::Bag() { tiles.setAutoDelete(TRUE); } void Bag::writeConfig(Config& cfg) { QStringList t; for (QListIterator<Tile> it(tiles); it; ++it) t.append((*it)->key()); cfg.writeEntry("Tiles",t,';'); } void Bag::readConfig(Config& cfg) { tiles.clear(); QStringList t = cfg.readListEntry("Tiles",';'); for (QStringList::ConstIterator it=t.begin(); it!=t.end(); ++it ) add(Tile(*it)); } void Bag::add(const Tile& t) { tiles.append(new Tile(t)); } Tile Bag::takeRandom() { Tile* rp = tiles.take(random()%tiles.count()); Tile r=*rp; return r; } ScoreInfo::ScoreInfo( QWidget* parent, const char* name, WFlags fl ) : QLabel("<P>",parent,name,fl) { score=0; msgtimer = new QTimer(this); connect(msgtimer, SIGNAL(timeout()), this, SLOT(showScores())); setBackgroundMode( PaletteButton ); } ScoreInfo::~ScoreInfo() { if ( score ) delete [] score; } void ScoreInfo::writeConfig(Config& cfg) { QStringList l; for (int i=0; i<(int)names.count(); i++) l.append(QString::number(score[i])); cfg.writeEntry("Scores",l,';'); } void ScoreInfo::readConfig(Config& cfg) { QStringList l = cfg.readListEntry("Scores",';'); int i=0; for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it ) score[i++]=(*it).toInt(); showScores(); } QSize ScoreInfo::sizeHint() const { return QSize(QLabel::sizeHint().width(),fontMetrics().height()); } void ScoreInfo::init(const QStringList& namelist) { names = namelist; if ( score ) delete [] score; score = new int[names.count()]; memset(score,0,sizeof(int)*names.count()); boldone = -1; showScores(); } void ScoreInfo::addScore(int player, int change) { score[player] += change; showScores(); } void ScoreInfo::setBoldOne(int b) { boldone=b; showScores(); } void ScoreInfo::showScores() { QString r="<p>"; int i=0; //int spl=(names.count()+1)/2; // 2 lines for (QStringList::ConstIterator it=names.begin(); it!=names.end(); ) { if ( i==boldone ) r += "<b>"; QString n = *it; n.replace(QRegExp(":.*"),""); r += n; r += ":"; r += QString::number(score[i]); if ( i==boldone ) r += "</b>"; ++i; ++it; if ( it != names.end() ) r += " "; } setText(r); } void ScoreInfo::showTemporaryScore(int amount) { if ( amount < 0 ) setText(tr("<P>Invalid move")); else setText(tr("<P>Score: ")+QString::number(amount)); msgtimer->start(3000,TRUE); } diff --git a/noncore/graphics/drawpad/drawpad.cpp b/noncore/graphics/drawpad/drawpad.cpp index 4db6208..aac6bc1 100644 --- a/noncore/graphics/drawpad/drawpad.cpp +++ b/noncore/graphics/drawpad/drawpad.cpp @@ -1,661 +1,667 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "drawpad.h" #include "drawpadcanvas.h" #include "ellipsetool.h" #include "erasetool.h" #include "exportdialog.h" #include "filledellipsetool.h" #include "filledrectangletool.h" #include "filltool.h" #include "importdialog.h" #include "linetool.h" #include "newpagedialog.h" #include "page.h" #include "pageinformationdialog.h" #include "pointtool.h" #include "rectangletool.h" #include "texttool.h" #include "thumbnailview.h" #include <opie/colordialog.h> #include <opie/colorpopupmenu.h> #include <qpe/applnk.h> #include <qpe/config.h> #include <qpe/global.h> #include <qpe/qpemenubar.h> #include <qpe/qpetoolbar.h> #include <qpe/resource.h> #include <qaction.h> #include <qfile.h> #include <qmessagebox.h> #include <qpainter.h> #include <qspinbox.h> #include <qtoolbutton.h> #include <qtooltip.h> #include <qwhatsthis.h> DrawPad::DrawPad(QWidget* parent, const char* name) : QMainWindow(parent, name, WStyle_ContextHelp) { // init members m_pDrawPadCanvas = new DrawPadCanvas(this, this); connect(m_pDrawPadCanvas, SIGNAL(pagesChanged()), this, SLOT(updateView())); setCentralWidget(m_pDrawPadCanvas); // init menu setToolBarsMovable(false); QPEToolBar* menuToolBar = new QPEToolBar(this); QPEMenuBar* menuBar = new QPEMenuBar(menuToolBar); QPopupMenu* toolsPopupMenu = new QPopupMenu(menuBar); QAction* deleteAllAction = new QAction(tr("Delete All"), QString::null, 0, this); connect(deleteAllAction, SIGNAL(activated()), this, SLOT(deleteAll())); deleteAllAction->addTo(toolsPopupMenu); toolsPopupMenu->insertSeparator(); QAction* importPageAction = new QAction(tr("Import"), tr("Import..."), 0, this); connect(importPageAction, SIGNAL(activated()), this, SLOT(importPage())); importPageAction->addTo(toolsPopupMenu); QAction* exportPageAction = new QAction(tr("Export"), tr("Export..."), 0, this); connect(exportPageAction, SIGNAL(activated()), this, SLOT(exportPage())); exportPageAction->addTo(toolsPopupMenu); toolsPopupMenu->insertSeparator(); QAction* thumbnailViewAction = new QAction(tr("Thumbnail View"), tr("Thumbnail View..."), 0, this); connect(thumbnailViewAction, SIGNAL(activated()), this, SLOT(thumbnailView())); thumbnailViewAction->addTo(toolsPopupMenu); QAction* pageInformationAction = new QAction(tr("Page Information"), tr("Page Information..."), 0, this); connect(pageInformationAction, SIGNAL(activated()), this, SLOT(pageInformation())); pageInformationAction->addTo(toolsPopupMenu); toolsPopupMenu->insertSeparator(); m_pAntiAliasingAction = new QAction(tr("Anti-Aliasing"), QString::null, 0, this); m_pAntiAliasingAction->setToggleAction(true); m_pAntiAliasingAction->addTo(toolsPopupMenu); menuBar->insertItem(tr("Tools"), toolsPopupMenu); // init page toolbar QPEToolBar* pageToolBar = new QPEToolBar(this); QAction* newPageAction = new QAction(tr("New Page"), Resource::loadPixmap("new"), QString::null, 0, this); connect(newPageAction, SIGNAL(activated()), this, SLOT(newPage())); newPageAction->addTo(pageToolBar); newPageAction->setWhatsThis( tr( "Click here to add a new sheet." ) ); QAction* clearPageAction = new QAction(tr("Clear Page"), Resource::loadPixmap("drawpad/clear"), QString::null, 0, this); connect(clearPageAction, SIGNAL(activated()), this, SLOT(clearPage())); clearPageAction->addTo(pageToolBar); clearPageAction->setWhatsThis( tr( "Click here to erase the current sheet." ) ); QAction* deletePageAction = new QAction(tr("Delete Page"), Resource::loadPixmap("trash"), QString::null, 0, this); connect(deletePageAction, SIGNAL(activated()), this, SLOT(deletePage())); deletePageAction->addTo(pageToolBar); deletePageAction->setWhatsThis( tr( "Click here to remove the current sheet." ) ); QPEToolBar* emptyToolBar = new QPEToolBar(this); emptyToolBar->setHorizontalStretchable(true); // init navigation toolbar QPEToolBar* navigationToolBar = new QPEToolBar(this); m_pUndoAction = new QAction(tr("Undo"), Resource::loadIconSet("undo"), QString::null, 0, this); connect(m_pUndoAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(undo())); m_pUndoAction->addTo(navigationToolBar); m_pUndoAction->setWhatsThis( tr( "Click here to undo the last action." ) ); m_pRedoAction = new QAction(tr("Redo"), Resource::loadIconSet("redo"), QString::null, 0, this); connect(m_pRedoAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(redo())); m_pRedoAction->addTo(navigationToolBar); m_pRedoAction->setWhatsThis( tr( "Click here to re-perform the last action." ) ); m_pFirstPageAction = new QAction(tr("First Page"), Resource::loadIconSet("fastback"), QString::null, 0, this); connect(m_pFirstPageAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(goFirstPage())); m_pFirstPageAction->addTo(navigationToolBar); m_pFirstPageAction->setWhatsThis( tr( "Click here to view the first page." ) ); m_pPreviousPageAction = new QAction(tr("Previous Page"), Resource::loadIconSet("back"), QString::null, 0, this); connect(m_pPreviousPageAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(goPreviousPage())); m_pPreviousPageAction->addTo(navigationToolBar); m_pPreviousPageAction->setWhatsThis( tr( "Click here to view the previous page." ) ); m_pNextPageAction = new QAction(tr("Next Page"), Resource::loadIconSet("forward"), QString::null, 0, this); connect(m_pNextPageAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(goNextPage())); m_pNextPageAction->addTo(navigationToolBar); m_pNextPageAction->setWhatsThis( tr( "Click here to view the next page." ) ); m_pLastPageAction = new QAction(tr("Last Page"), Resource::loadIconSet("fastforward"), QString::null, 0, this); connect(m_pLastPageAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(goLastPage())); m_pLastPageAction->addTo(navigationToolBar); m_pLastPageAction->setWhatsThis( tr( "Click here to view the last page." ) ); // init draw mode toolbar QPEToolBar* drawModeToolBar = new QPEToolBar(this); m_pLineToolButton = new QToolButton(drawModeToolBar); m_pLineToolButton->setToggleButton(true); QWhatsThis::add( m_pLineToolButton, tr( "Click here to select one of the available tools to draw lines." ) ); QPopupMenu* linePopupMenu = new QPopupMenu(m_pLineToolButton); m_pPointToolAction = new QAction(tr("Draw Point"), Resource::loadPixmap("drawpad/point"), "", 0, this); connect(m_pPointToolAction, SIGNAL(activated()), this, SLOT(setPointTool())); m_pPointToolAction->addTo(linePopupMenu); m_pLineToolAction = new QAction(tr("Draw Line"), Resource::loadPixmap("drawpad/line"), "", 0, this); connect(m_pLineToolAction, SIGNAL(activated()), this, SLOT(setLineTool())); m_pLineToolAction->addTo(linePopupMenu); m_pLineToolButton->setPopup(linePopupMenu); m_pLineToolButton->setPopupDelay(0); m_pRectangleToolButton = new QToolButton(drawModeToolBar); m_pRectangleToolButton->setToggleButton(true); QWhatsThis::add( m_pRectangleToolButton, tr( "Click here to select one of the available tools to draw rectangles." ) ); QPopupMenu* rectanglePopupMenu = new QPopupMenu(m_pRectangleToolButton); m_pRectangleToolAction = new QAction(tr("Draw Rectangle"), Resource::loadPixmap("drawpad/rectangle"), "", 0, this); connect(m_pRectangleToolAction, SIGNAL(activated()), this, SLOT(setRectangleTool())); m_pRectangleToolAction->addTo(rectanglePopupMenu); m_pFilledRectangleToolAction = new QAction(tr("Draw Filled Rectangle"), Resource::loadPixmap("drawpad/filledrectangle"), "", 0, this); connect(m_pFilledRectangleToolAction, SIGNAL(activated()), this, SLOT(setFilledRectangleTool())); m_pFilledRectangleToolAction->addTo(rectanglePopupMenu); m_pRectangleToolButton->setPopup(rectanglePopupMenu); m_pRectangleToolButton->setPopupDelay(0); m_pEllipseToolButton = new QToolButton(drawModeToolBar); m_pEllipseToolButton->setToggleButton(true); QWhatsThis::add( m_pEllipseToolButton, tr( "Click here to select one of the available tools to draw ellipses." ) ); QPopupMenu* ellipsePopupMenu = new QPopupMenu(m_pEllipseToolButton); m_pEllipseToolAction = new QAction(tr("Draw Ellipse"), Resource::loadPixmap("drawpad/ellipse"), "", 0, this); connect(m_pEllipseToolAction, SIGNAL(activated()), this, SLOT(setEllipseTool())); m_pEllipseToolAction->addTo(ellipsePopupMenu); m_pFilledEllipseToolAction = new QAction(tr("Draw Filled Ellipse"), Resource::loadPixmap("drawpad/filledellipse"), "", 0, this); connect(m_pFilledEllipseToolAction, SIGNAL(activated()), this, SLOT(setFilledEllipseTool())); m_pFilledEllipseToolAction->addTo(ellipsePopupMenu); m_pEllipseToolButton->setPopup(ellipsePopupMenu); m_pEllipseToolButton->setPopupDelay(0); m_pTextToolAction = new QAction(tr("Insert Text"), Resource::loadPixmap("drawpad/text"), QString::null, 0, this); m_pTextToolAction->setToggleAction(true); connect(m_pTextToolAction, SIGNAL(activated()), this, SLOT(setTextTool())); m_pTextToolAction->addTo(drawModeToolBar); m_pTextToolAction->setWhatsThis( tr( "Click here to select the text drawing tool." ) ); m_pFillToolAction = new QAction(tr("Fill Region"), Resource::loadPixmap("drawpad/fill"), QString::null, 0, this); m_pFillToolAction->setToggleAction(true); connect(m_pFillToolAction, SIGNAL(activated()), this, SLOT(setFillTool())); m_pFillToolAction->addTo(drawModeToolBar); m_pFillToolAction->setWhatsThis( tr( "Click here to select the fill tool." ) ); m_pEraseToolAction = new QAction(tr("Erase Point"), Resource::loadPixmap("drawpad/erase"), QString::null, 0, this); m_pEraseToolAction->setToggleAction(true); connect(m_pEraseToolAction, SIGNAL(activated()), this, SLOT(setEraseTool())); m_pEraseToolAction->addTo(drawModeToolBar); m_pEraseToolAction->setWhatsThis( tr( "Click here to select the eraser tool." ) ); m_pTool = 0; setRectangleTool(); setEllipseTool(); setPointTool(); emptyToolBar = new QPEToolBar(this); emptyToolBar->setHorizontalStretchable(true); emptyToolBar->addSeparator(); // init draw parameters toolbar QPEToolBar* drawParametersToolBar = new QPEToolBar(this); m_pPenWidthSpinBox = new QSpinBox(1, 9, 1, drawParametersToolBar); connect(m_pPenWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changePenWidth(int))); QToolTip::add(m_pPenWidthSpinBox, tr("Pen Width")); m_pPenWidthSpinBox->setValue(1); m_pPenWidthSpinBox->setFocusPolicy(QWidget::NoFocus); QWhatsThis::add( m_pPenWidthSpinBox, tr( "Click here to select the width of the drawing pen." ) ); m_pPenColorToolButton = new QToolButton(drawParametersToolBar); m_pPenColorToolButton->setPixmap(Resource::loadPixmap("drawpad/pencolor")); QWhatsThis::add( m_pPenColorToolButton, tr( "Click here to select the color used when drawing." ) ); OColorPopupMenu* penColorPopupMenu = new OColorPopupMenu(Qt::black, m_pPenColorToolButton); connect(penColorPopupMenu, SIGNAL(colorSelected(const QColor&)), this, SLOT(changePenColor(const QColor&))); QToolTip::add(m_pPenColorToolButton, tr("Pen Color")); m_pPenColorToolButton->setPopup(penColorPopupMenu); m_pPenColorToolButton->setPopupDelay(0); changePenColor(Qt::black); m_pBrushColorToolButton = new QToolButton(drawParametersToolBar); m_pBrushColorToolButton->setPixmap(Resource::loadPixmap("drawpad/brushcolor")); QWhatsThis::add( m_pBrushColorToolButton, tr( "Click here to select the color used when filling in areas." ) ); OColorPopupMenu* brushColorPopupMenu = new OColorPopupMenu(Qt::white, m_pBrushColorToolButton); connect(brushColorPopupMenu, SIGNAL(colorSelected(const QColor&)), this, SLOT(changeBrushColor(const QColor&))); QToolTip::add(m_pBrushColorToolButton, tr("Fill Color")); m_pBrushColorToolButton->setPopup(brushColorPopupMenu); m_pBrushColorToolButton->setPopupDelay(0); changeBrushColor(Qt::white); +} + + +void DrawPad::finishStartup() +{ // init pages QFile file(Global::applicationFileName("drawpad", "drawpad.xml")); if (file.open(IO_ReadOnly)) { m_pDrawPadCanvas->load(&file); file.close(); } else { m_pDrawPadCanvas->initialPage(); } loadConfig(); + } DrawPad::~DrawPad() { saveConfig(); QFile file(Global::applicationFileName("drawpad", "drawpad.xml")); if (file.open(IO_WriteOnly)) { m_pDrawPadCanvas->save(&file); file.close(); } } bool DrawPad::antiAliasing() { return (m_pAntiAliasingAction->isOn()); } void DrawPad::newPage() { QRect rect = m_pDrawPadCanvas->contentsRect(); NewPageDialog newPageDialog(rect.width(), rect.height(), m_pen.color(), m_brush.color(), this); if (newPageDialog.exec() == QDialog::Accepted) { m_pDrawPadCanvas->newPage(newPageDialog.selectedTitle(), newPageDialog.selectedWidth(), newPageDialog.selectedHeight(), newPageDialog.selectedColor()); } } void DrawPad::clearPage() { QMessageBox messageBox(tr("Clear Page"), tr("Do you want to clear\nthe current page?"), QMessageBox::Information, QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default, QMessageBox::NoButton, this); messageBox.setButtonText(QMessageBox::Yes, tr("Yes")); messageBox.setButtonText(QMessageBox::No, tr("No")); if (messageBox.exec() == QMessageBox::Yes) { m_pDrawPadCanvas->clearPage(); } } void DrawPad::deletePage() { QMessageBox messageBox(tr("Delete Page"), tr("Do you want to delete\nthe current page?"), QMessageBox::Information, QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default, QMessageBox::NoButton, this); messageBox.setButtonText(QMessageBox::Yes, tr("Yes")); messageBox.setButtonText(QMessageBox::No, tr("No")); if (messageBox.exec() == QMessageBox::Yes) { m_pDrawPadCanvas->deletePage(); } } void DrawPad::setPointTool() { if (m_pTool) { delete m_pTool; } m_pTool = new PointTool(this, m_pDrawPadCanvas); m_pLineToolButton->setIconSet(m_pPointToolAction->iconSet()); QToolTip::add(m_pLineToolButton, m_pPointToolAction->text()); disconnect(m_pLineToolButton, SIGNAL(clicked()), 0, 0); connect(m_pLineToolButton, SIGNAL(clicked()), m_pPointToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(true); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setLineTool() { if (m_pTool) { delete m_pTool; } m_pTool = new LineTool(this, m_pDrawPadCanvas); m_pLineToolButton->setIconSet(m_pLineToolAction->iconSet()); QToolTip::add(m_pLineToolButton, m_pLineToolAction->text()); disconnect(m_pLineToolButton, SIGNAL(clicked()), 0, 0); connect(m_pLineToolButton, SIGNAL(clicked()), m_pLineToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(true); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setRectangleTool() { if (m_pTool) { delete m_pTool; } m_pTool = new RectangleTool(this, m_pDrawPadCanvas); m_pRectangleToolButton->setIconSet(m_pRectangleToolAction->iconSet()); QToolTip::add(m_pRectangleToolButton, m_pRectangleToolAction->text()); disconnect(m_pRectangleToolButton, SIGNAL(clicked()), 0, 0); connect(m_pRectangleToolButton, SIGNAL(clicked()), m_pRectangleToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(true); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setFilledRectangleTool() { if (m_pTool) { delete m_pTool; } m_pTool = new FilledRectangleTool(this, m_pDrawPadCanvas); m_pRectangleToolButton->setIconSet(m_pFilledRectangleToolAction->iconSet()); QToolTip::add(m_pRectangleToolButton, m_pFilledRectangleToolAction->text()); disconnect(m_pRectangleToolButton, SIGNAL(clicked()), 0, 0); connect(m_pRectangleToolButton, SIGNAL(clicked()), m_pFilledRectangleToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(true); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setEllipseTool() { if (m_pTool) { delete m_pTool; } m_pTool = new EllipseTool(this, m_pDrawPadCanvas); m_pEllipseToolButton->setIconSet(m_pEllipseToolAction->iconSet()); QToolTip::add(m_pEllipseToolButton, m_pEllipseToolAction->text()); disconnect(m_pEllipseToolButton, SIGNAL(clicked()), 0, 0); connect(m_pEllipseToolButton, SIGNAL(clicked()), m_pEllipseToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(true); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setFilledEllipseTool() { if (m_pTool) { delete m_pTool; } m_pTool = new FilledEllipseTool(this, m_pDrawPadCanvas); m_pEllipseToolButton->setIconSet(m_pFilledEllipseToolAction->iconSet()); QToolTip::add(m_pEllipseToolButton, m_pFilledEllipseToolAction->text()); disconnect(m_pEllipseToolButton, SIGNAL(clicked()), 0, 0); connect(m_pEllipseToolButton, SIGNAL(clicked()), m_pFilledEllipseToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(true); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setTextTool() { if (m_pTool) { delete m_pTool; } m_pTool = new TextTool(this, m_pDrawPadCanvas); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(true); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setFillTool() { if (m_pTool) { delete m_pTool; } m_pTool = new FillTool(this, m_pDrawPadCanvas); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(true); m_pEraseToolAction->setOn(false); } void DrawPad::setEraseTool() { if (m_pTool) { delete m_pTool; } m_pTool = new EraseTool(this, m_pDrawPadCanvas); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(true); } void DrawPad::changePenWidth(int value) { m_pen.setWidth(value); } void DrawPad::changePenColor(const QColor& color) { m_pen.setColor(color); QPainter painter; painter.begin(m_pPenColorToolButton->pixmap()); painter.fillRect(QRect(0, 12, 14, 2), m_pen.color()); painter.end(); m_pPenColorToolButton->popup()->hide(); } void DrawPad::changeBrushColor(const QColor& color) { m_brush = QBrush(color); QPainter painter; painter.begin(m_pBrushColorToolButton->pixmap()); painter.fillRect(QRect(0, 12, 14, 2), m_brush.color()); painter.end(); m_pBrushColorToolButton->popup()->hide(); } void DrawPad::updateView() { uint pagePosition = m_pDrawPadCanvas->pagePosition(); uint pageCount = m_pDrawPadCanvas->pageCount(); setCaption( tr( "DrawPad - Page %1/%2" ).arg( pagePosition ).arg( pageCount ) ); m_pUndoAction->setEnabled(m_pDrawPadCanvas->currentPage()->undoEnabled()); m_pRedoAction->setEnabled(m_pDrawPadCanvas->currentPage()->redoEnabled()); m_pFirstPageAction->setEnabled(m_pDrawPadCanvas->goPreviousPageEnabled()); m_pPreviousPageAction->setEnabled(m_pDrawPadCanvas->goPreviousPageEnabled()); m_pNextPageAction->setEnabled(m_pDrawPadCanvas->goNextPageEnabled()); m_pLastPageAction->setEnabled(m_pDrawPadCanvas->goNextPageEnabled()); } void DrawPad::deleteAll() { QMessageBox messageBox(tr("Delete All"), tr("Do you want to delete\nall the pages?"), QMessageBox::Information, QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default, QMessageBox::NoButton, this); messageBox.setButtonText(QMessageBox::Yes, tr("Yes")); messageBox.setButtonText(QMessageBox::No, tr("No")); if (messageBox.exec() == QMessageBox::Yes) { m_pDrawPadCanvas->deleteAll(); } } void DrawPad::importPage() { ImportDialog importDialog(this); importDialog.showMaximized(); if (importDialog.exec() == QDialog::Accepted) { const DocLnk* docLnk = importDialog.selected(); if (docLnk) { m_pDrawPadCanvas->importPage(docLnk->file()); delete docLnk; } } } void DrawPad::exportPage() { ExportDialog exportDialog(m_pDrawPadCanvas->pagePosition(), m_pDrawPadCanvas->pageCount(), this); exportDialog.showMaximized(); if (exportDialog.exec() == QDialog::Accepted) { m_pDrawPadCanvas->exportPage(exportDialog.selectedFromPage(), exportDialog.selectedToPage(), exportDialog.selectedName(), exportDialog.selectedFormat()); } } void DrawPad::thumbnailView() { ThumbnailView thumbnailView(this, m_pDrawPadCanvas, this); thumbnailView.showMaximized(); thumbnailView.exec(); } void DrawPad::pageInformation() { PageInformationDialog pageInformationDialog(m_pDrawPadCanvas->currentPage()); if (pageInformationDialog.exec() == QDialog::Accepted) { m_pDrawPadCanvas->currentPage()->setTitle(pageInformationDialog.selectedTitle()); } } void DrawPad::loadConfig() { Config config("drawpad"); config.setGroup("General"); m_pAntiAliasingAction->setOn(config.readBoolEntry("AntiAliasing", false)); m_pPenWidthSpinBox->setValue(config.readNumEntry("PenWidth", 1)); changePenColor(QColor(config.readEntry("PenColor", Qt::black.name()))); changeBrushColor(QColor(config.readEntry("BrushColor", Qt::white.name()))); m_pDrawPadCanvas->selectPage(config.readNumEntry("PagePosition", 1)); } void DrawPad::saveConfig() { Config config("drawpad"); config.setGroup("General"); config.writeEntry("PagePosition", (int)m_pDrawPadCanvas->pagePosition()); config.writeEntry("AntiAliasing", antiAliasing()); config.writeEntry("PenWidth", (int)m_pen.width()); config.writeEntry("PenColor", m_pen.color().name()); config.writeEntry("BrushColor", m_brush.color().name()); } diff --git a/noncore/graphics/drawpad/drawpad.h b/noncore/graphics/drawpad/drawpad.h index 7306228..2cae700 100644 --- a/noncore/graphics/drawpad/drawpad.h +++ b/noncore/graphics/drawpad/drawpad.h @@ -1,110 +1,111 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef DRAWPAD_H #define DRAWPAD_H #include <qmainwindow.h> #include <qpen.h> class DrawPadCanvas; class Tool; class QAction; class QColor; class QSpinBox; class QToolButton; class QWidgetStack; class DrawPad : public QMainWindow { Q_OBJECT public: DrawPad(QWidget* parent = 0, const char* name = 0); ~DrawPad(); Tool* tool() { return m_pTool; } QPen pen() { return m_pen; } QBrush brush() { return m_brush; } bool antiAliasing(); + void finishStartup(); private slots: void newPage(); void clearPage(); void deletePage(); void setPointTool(); void setLineTool(); void setRectangleTool(); void setFilledRectangleTool(); void setEllipseTool(); void setFilledEllipseTool(); void setTextTool(); void setFillTool(); void setEraseTool(); void changePenWidth(int value); void changePenColor(const QColor& color); void changeBrushColor(const QColor& color); void updateView(); void deleteAll(); void importPage(); void exportPage(); void thumbnailView(); void pageInformation(); private: void loadConfig(); void saveConfig(); DrawPadCanvas* m_pDrawPadCanvas; Tool* m_pTool; QPen m_pen; QBrush m_brush; QAction* m_pAntiAliasingAction; QAction* m_pUndoAction; QAction* m_pRedoAction; QAction* m_pFirstPageAction; QAction* m_pPreviousPageAction; QAction* m_pNextPageAction; QAction* m_pLastPageAction; QAction* m_pPointToolAction; QAction* m_pLineToolAction; QAction* m_pRectangleToolAction; QAction* m_pFilledRectangleToolAction; QAction* m_pEllipseToolAction; QAction* m_pFilledEllipseToolAction; QAction* m_pTextToolAction; QAction* m_pFillToolAction; QAction* m_pEraseToolAction; QToolButton* m_pLineToolButton; QToolButton* m_pRectangleToolButton; QToolButton* m_pEllipseToolButton; QToolButton* m_pPenColorToolButton; QToolButton* m_pBrushColorToolButton; QSpinBox* m_pPenWidthSpinBox; }; #endif // DRAWPAD_H diff --git a/noncore/graphics/drawpad/drawpadcanvas.cpp b/noncore/graphics/drawpad/drawpadcanvas.cpp index 025bebb..dec498b 100644 --- a/noncore/graphics/drawpad/drawpadcanvas.cpp +++ b/noncore/graphics/drawpad/drawpadcanvas.cpp @@ -1,510 +1,522 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "drawpadcanvas.h" #include "drawpad.h" #include "page.h" #include "tool.h" #include <qpe/applnk.h> #include <qpe/filemanager.h> #include <qpe/mimetype.h> #include <qbuffer.h> #include <qimage.h> #include <qpainter.h> #include <qtextcodec.h> #include <qtextstream.h> #include <qxml.h> class DrawPadCanvasXmlHandler: public QXmlDefaultHandler { public: DrawPadCanvasXmlHandler(); ~DrawPadCanvasXmlHandler(); QList<Page> pages(); bool startElement(const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts); bool endElement(const QString& namespaceURI, const QString& localName, const QString& qName); bool characters(const QString& ch); private: enum State { Unknown, InTitle, InDate, InData }; State m_state; QString m_title; QDateTime m_date; ulong m_dataLenght; QString m_dataFormat; QList<Page> m_pages; }; DrawPadCanvasXmlHandler::DrawPadCanvasXmlHandler() { m_state = Unknown; } DrawPadCanvasXmlHandler::~DrawPadCanvasXmlHandler() { } QList<Page> DrawPadCanvasXmlHandler::pages() { return m_pages; } bool DrawPadCanvasXmlHandler::startElement(const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts) { Q_CONST_UNUSED(namespaceURI) Q_CONST_UNUSED(localName) if (qName == "image") { m_title = QString(); m_date = QDateTime::currentDateTime(); } else if (qName == "title") { m_state = InTitle; } else if (qName == "date") { m_state = InDate; } else if (qName == "data") { m_state = InData; m_dataLenght = atts.value("length").toULong(); m_dataFormat = atts.value("format"); } return true; } bool DrawPadCanvasXmlHandler::endElement(const QString& namespaceURI, const QString& localName, const QString& qName) { Q_CONST_UNUSED(namespaceURI) Q_CONST_UNUSED(localName) if (qName == "title") { m_state = Unknown; } else if (qName == "date") { m_state = Unknown; } else if (qName == "data") { m_state = Unknown; } return true; } bool DrawPadCanvasXmlHandler::characters(const QString& ch) { if (m_state == InTitle) { m_title = ch; } else if (m_state == InDate) { m_date = QDateTime(QDate(1970, 1, 1)).addSecs(ch.toInt()); } else if (m_state == InData) { QByteArray byteArray(ch.length() / 2); for (int i = 0; i < (int)ch.length() / 2; i++) { char h = ch[2 * i].latin1(); char l = ch[2 * i + 1].latin1(); uchar r = 0; if (h <= '9') { r += h - '0'; } else { r += h - 'a' + 10; } r = r << 4; if (l <= '9') { r += l - '0'; } else { r += l - 'a' + 10; } byteArray[i] = r; } QImage image; image.loadFromData((const uchar*)byteArray.data(), m_dataLenght, m_dataFormat); Page* page = new Page(m_title, image.width(), image.height()); page->setLastModified(m_date); page->pixmap()->convertFromImage(image); m_pages.append(page); } return true; } DrawPadCanvas::DrawPadCanvas(DrawPad* drawPad, QWidget* parent, const char* name) : QScrollView(parent, name) { m_pDrawPad = drawPad; m_pages.setAutoDelete(true); viewport()->setBackgroundMode(QWidget::NoBackground); } DrawPadCanvas::~DrawPadCanvas() { } void DrawPadCanvas::load(QIODevice* ioDevice) { QTextStream textStream(ioDevice); textStream.setCodec(QTextCodec::codecForName("UTF-8")); QXmlInputSource xmlInputSource(textStream); QXmlSimpleReader xmlSimpleReader; DrawPadCanvasXmlHandler drawPadCanvasXmlHandler; xmlSimpleReader.setContentHandler(&drawPadCanvasXmlHandler); xmlSimpleReader.parse(xmlInputSource); m_pages = drawPadCanvasXmlHandler.pages(); if (m_pages.isEmpty()) { - m_pages.append(new Page("", contentsRect().size())); + m_pages.append(new Page("", + clipper()->width()+(verticalScrollBar()->isVisible()?verticalScrollBar()->width():0), + clipper()->height()+(horizontalScrollBar()->isVisible()?horizontalScrollBar()->height():0))); m_pages.current()->pixmap()->fill(Qt::white); } resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::initialPage() { - m_pages.append(new Page("", 236, 232)); + m_pages.append(new Page("", + clipper()->width()+(verticalScrollBar()->isVisible()?verticalScrollBar()->width():0), + clipper()->height()+(horizontalScrollBar()->isVisible()?horizontalScrollBar()->height():0))); + //236, 232)); no more fixed sizes + m_pages.current()->pixmap()->fill(Qt::white); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::save(QIODevice* ioDevice) { QTextStream textStream(ioDevice); textStream.setCodec(QTextCodec::codecForName("UTF-8")); textStream << "<drawpad>" << endl; textStream << " <images>" << endl; QListIterator<Page> bufferIterator(m_pages); for (bufferIterator.toFirst(); bufferIterator.current() != 0; ++bufferIterator) { textStream << " <image>" << endl; textStream << " <title>" << bufferIterator.current()->title() << "</title>" << endl; int intDate = QDateTime(QDate(1970, 1, 1)).secsTo(bufferIterator.current()->lastModified()); textStream << " <date>" << intDate << "</date>" << endl; QImage image = bufferIterator.current()->pixmap()->convertToImage(); QByteArray byteArray; QBuffer buffer(byteArray); QImageIO imageIO(&buffer, "PNG"); buffer.open(IO_WriteOnly); imageIO.setImage(image); imageIO.write(); buffer.close(); textStream << " <data length=\"" << byteArray.size() << "\" format=\"PNG\">"; static const char hexchars[] = "0123456789abcdef"; for (int i = 0; i < (int)byteArray.size(); i++ ) { uchar s = (uchar)byteArray[i]; textStream << hexchars[s >> 4]; textStream << hexchars[s & 0x0f]; } textStream << "</data>" << endl; textStream << " </image>" << endl; } textStream << " </images>" << endl; textStream << "</drawpad>"; } void DrawPadCanvas::importPage(const QString& fileName) { Page* importedPage = new Page(); importedPage->pixmap()->load(fileName); m_pages.insert(m_pages.at() + 1, importedPage); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::exportPage(uint fromPage, uint toPage, const QString& name,const QString& format) { if (fromPage == toPage) { DocLnk docLnk; MimeType mimeType(format); docLnk.setName(name); docLnk.setType(mimeType.id()); FileManager fileManager; QIODevice* ioDevice = fileManager.saveFile(docLnk); QImageIO imageIO(ioDevice, format); QImage image = m_pages.current()->pixmap()->convertToImage(); imageIO.setImage(image); imageIO.write(); delete ioDevice; } else { for (uint i = fromPage; i <= toPage; i++) { DocLnk docLnk; MimeType mimeType(format); docLnk.setName(name + QString::number(i)); docLnk.setType(mimeType.id()); FileManager fileManager; QIODevice* ioDevice = fileManager.saveFile(docLnk); QImageIO imageIO(ioDevice, format); QImage image = m_pages.at(i - 1)->pixmap()->convertToImage(); imageIO.setImage(image); imageIO.write(); delete ioDevice; } } } Page* DrawPadCanvas::currentPage() { return m_pages.current(); } QList<Page> DrawPadCanvas::pages() { return m_pages; } uint DrawPadCanvas::pagePosition() { return (m_pages.at() + 1); } uint DrawPadCanvas::pageCount() { return m_pages.count(); } void DrawPadCanvas::selectPage(Page* page) { m_pages.findRef(page); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::backupPage() { m_pages.current()->backup(); emit pagesChanged(); } void DrawPadCanvas::selectPage(uint pagePosition) { m_pages.at(pagePosition - 1); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::deleteAll() { m_pages.clear(); - m_pages.append(new Page("", contentsRect().size())); + m_pages.append(new Page("", + clipper()->width()+(verticalScrollBar()->isVisible()?verticalScrollBar()->width():0), + clipper()->height()+(horizontalScrollBar()->isVisible()?horizontalScrollBar()->height():0))); + m_pages.current()->pixmap()->fill(Qt::white); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::newPage(QString title, uint width, uint height, const QColor& color) { m_pages.insert(m_pages.at() + 1, new Page(title, width, height)); m_pages.current()->pixmap()->fill(color); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::clearPage() { m_pages.current()->pixmap()->fill(Qt::white); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); } void DrawPadCanvas::deletePage() { m_pages.remove(m_pages.current()); if (m_pages.isEmpty()) { - m_pages.append(new Page("", contentsRect().size())); + m_pages.append(new Page("", + clipper()->width()+(verticalScrollBar()->isVisible()?verticalScrollBar()->width():0), + clipper()->height()+(horizontalScrollBar()->isVisible()?horizontalScrollBar()->height():0))); + m_pages.current()->pixmap()->fill(Qt::white); } resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::movePageUp() { int index = m_pages.at(); Page* page = m_pages.take(); m_pages.insert(index - 1, page); emit pagesChanged(); } void DrawPadCanvas::movePageDown() { int index = m_pages.at(); Page* page = m_pages.take(); m_pages.insert(index + 1, page); emit pagesChanged(); } bool DrawPadCanvas::goPreviousPageEnabled() { return (m_pages.current() != m_pages.getFirst()); } bool DrawPadCanvas::goNextPageEnabled() { return (m_pages.current() != m_pages.getLast()); } void DrawPadCanvas::undo() { m_pages.current()->undo(); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::redo() { m_pages.current()->redo(); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::goFirstPage() { m_pages.first(); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::goPreviousPage() { m_pages.prev(); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::goNextPage() { m_pages.next(); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::goLastPage() { m_pages.last(); resizeContents(m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); viewport()->update(); emit pagesChanged(); } void DrawPadCanvas::contentsMousePressEvent(QMouseEvent* e) { m_pDrawPad->tool()->mousePressEvent(e); } void DrawPadCanvas::contentsMouseReleaseEvent(QMouseEvent* e) { m_pDrawPad->tool()->mouseReleaseEvent(e); } void DrawPadCanvas::contentsMouseMoveEvent(QMouseEvent* e) { m_pDrawPad->tool()->mouseMoveEvent(e); } void DrawPadCanvas::drawContents(QPainter* p, int cx, int cy, int cw, int ch) { QRect clipRect(cx, cy, cw, ch); QRect pixmapRect(0, 0, m_pages.current()->pixmap()->width(), m_pages.current()->pixmap()->height()); QRect drawRect = pixmapRect.intersect(clipRect); p->drawPixmap(drawRect.topLeft(), *(m_pages.current()->pixmap()), drawRect); if (drawRect.right() < clipRect.right()) { p->fillRect(drawRect.right() + 1, cy, cw - drawRect.width(), ch, colorGroup().dark()); } if (drawRect.bottom() < clipRect.bottom()) { p->fillRect(cx, drawRect.bottom() + 1, cw, ch - drawRect.height(), colorGroup().dark()); } } diff --git a/noncore/graphics/drawpad/exportdialog.cpp b/noncore/graphics/drawpad/exportdialog.cpp index 5b11c0e..adbd612 100644 --- a/noncore/graphics/drawpad/exportdialog.cpp +++ b/noncore/graphics/drawpad/exportdialog.cpp @@ -1,173 +1,176 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "exportdialog.h" -#include <qpe/fileselector.h> +#include <opie/ofileselector.h> #include <qbuttongroup.h> #include <qcombobox.h> #include <qgroupbox.h> #include <qimage.h> #include <qlabel.h> #include <qlayout.h> #include <qlineedit.h> #include <qradiobutton.h> #include <qspinbox.h> #include <stdlib.h> ExportDialog::ExportDialog(uint pageAt, uint pageCount, QWidget* parent, const char* name) : QDialog(parent, name, true) { setCaption(tr("DrawPad - Export")); m_pageAt = pageAt; m_pageCount = pageCount; QButtonGroup* selectionButtonGroup = new QButtonGroup(0, Qt::Vertical, tr("Page Selection"), this); connect(selectionButtonGroup, SIGNAL(pressed(int)), this, SLOT(selectionChanged(int))); QRadioButton* selectAllRadioButton = new QRadioButton(tr("All"), selectionButtonGroup); QRadioButton* selectCurrentRadioButton = new QRadioButton(tr("Current"), selectionButtonGroup); QRadioButton* selectRangeRadioButton = new QRadioButton(tr("Range"), selectionButtonGroup); QLabel* toLabel = new QLabel(tr("To:"), selectionButtonGroup); m_pFromPageSpinBox = new QSpinBox(1, m_pageCount, 1, selectionButtonGroup); connect(m_pFromPageSpinBox, SIGNAL(valueChanged(int)), this, SLOT(fromPageChanged(int))); m_pToPageSpinBox = new QSpinBox(1, m_pageCount, 1, selectionButtonGroup); connect(m_pToPageSpinBox, SIGNAL(valueChanged(int)), this, SLOT(toPageChanged(int))); selectionButtonGroup->setButton(1); selectionChanged(1); m_pFromPageSpinBox->setValue(pageAt); m_pToPageSpinBox->setValue(pageAt); QGroupBox* exportGroupBox = new QGroupBox(0, Qt::Vertical, tr("Export As"), this); QLabel* nameLabel = new QLabel(tr("Name:"), exportGroupBox); QLabel* formatLabel = new QLabel(tr("Format:"), exportGroupBox); m_pNameLineEdit = new QLineEdit(exportGroupBox); m_pFormatComboBox = new QComboBox(exportGroupBox); m_pFormatComboBox->insertStrList(QImageIO::outputFormats()); - FileSelector* fileSelector = new FileSelector("image/*", this, "fileselector"); - fileSelector->setNewVisible(false); - fileSelector->setCloseVisible(false); + MimeTypes types; types.insert( tr("All Images"), "image/*" ); + OFileSelector* fileSelector = new OFileSelector(this, OFileSelector::FileSelector, + OFileSelector::Normal, + QString::null, QString::null, + types ); + fileSelector->setNameVisible( false ); QVBoxLayout* mainLayout = new QVBoxLayout(this, 4, 4); selectionButtonGroup->layout()->setSpacing(4); exportGroupBox->layout()->setSpacing(4); QGridLayout* selectionLayout = new QGridLayout(selectionButtonGroup->layout(), 2, 2); QHBoxLayout* rangeLayout = new QHBoxLayout(); QGridLayout* exportLayout = new QGridLayout(exportGroupBox->layout(), 2, 2); selectionLayout->addWidget(selectAllRadioButton, 0, 0); selectionLayout->addWidget(selectCurrentRadioButton, 1, 0); selectionLayout->addWidget(selectRangeRadioButton, 0, 1); selectionLayout->addLayout(rangeLayout, 1, 1); rangeLayout->addWidget(m_pFromPageSpinBox); rangeLayout->addWidget(toLabel); rangeLayout->addWidget(m_pToPageSpinBox); exportLayout->addWidget(nameLabel, 0, 0); exportLayout->addWidget(formatLabel, 1, 0); exportLayout->addWidget(m_pNameLineEdit, 0, 1); exportLayout->addWidget(m_pFormatComboBox, 1, 1); exportLayout->setColStretch(1, 1); mainLayout->addWidget(selectionButtonGroup); mainLayout->addWidget(exportGroupBox); mainLayout->addWidget(fileSelector); m_pNameLineEdit->setFocus(); } ExportDialog::~ExportDialog() { } uint ExportDialog::selectedFromPage() { return (m_pFromPageSpinBox->value()); } uint ExportDialog::selectedToPage() { return (m_pToPageSpinBox->value()); } QString ExportDialog::selectedName() { return (m_pNameLineEdit->text()); } QString ExportDialog::selectedFormat() { return (m_pFormatComboBox->currentText()); } void ExportDialog::accept() { if (!(m_pNameLineEdit->text().isEmpty())) { QDialog::accept(); } } void ExportDialog::selectionChanged(int id) { switch (id) { case 0: m_pFromPageSpinBox->setValue(1); m_pToPageSpinBox->setValue(m_pageCount); m_pFromPageSpinBox->setEnabled(false); m_pToPageSpinBox->setEnabled(false); break; case 1: m_pFromPageSpinBox->setValue(m_pageAt); m_pToPageSpinBox->setValue(m_pageAt); m_pFromPageSpinBox->setEnabled(false); m_pToPageSpinBox->setEnabled(false); break; case 2: m_pFromPageSpinBox->setEnabled(true); m_pToPageSpinBox->setEnabled(true); break; default: break; } } void ExportDialog::fromPageChanged(int value) { if (m_pToPageSpinBox->value() < value) { m_pToPageSpinBox->setValue(value); } } void ExportDialog::toPageChanged(int value) { if (m_pFromPageSpinBox->value() > value) { m_pFromPageSpinBox->setValue(value); } } diff --git a/noncore/graphics/drawpad/importdialog.cpp b/noncore/graphics/drawpad/importdialog.cpp index 1c447cb..9a59a20 100644 --- a/noncore/graphics/drawpad/importdialog.cpp +++ b/noncore/graphics/drawpad/importdialog.cpp @@ -1,113 +1,117 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "importdialog.h" #include <qpe/applnk.h> -#include <qpe/fileselector.h> +#include <opie/ofileselector.h> #include <qcheckbox.h> #include <qimage.h> #include <qlabel.h> #include <qlayout.h> #include <qpushbutton.h> ImportDialog::ImportDialog(QWidget* parent, const char* name) : QDialog(parent, name, true) { setCaption(tr("DrawPad - Import")); - m_pFileSelector = new FileSelector("image/*", this, "fileselector"); + MimeTypes types; types.insert( tr("All images"),"image/*" ); + m_pFileSelector = new OFileSelector(this, + OFileSelector::FileSelector, + OFileSelector::Normal, + QString::null, + QString::null, types ); + m_pFileSelector->setNameVisible( false ); connect(m_pFileSelector, SIGNAL(fileSelected(const DocLnk&)), this, SLOT(fileChanged())); - m_pFileSelector->setNewVisible(false); - m_pFileSelector->setCloseVisible(false); m_pPreviewLabel = new QLabel(this); m_pPreviewLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken); m_pPreviewLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); m_pPreviewLabel->setFixedSize(114, 114); m_pPreviewLabel->setBackgroundMode(QWidget::PaletteMid); m_pAutomaticPreviewCheckBox = new QCheckBox(tr("Automatic preview"), this); m_pAutomaticPreviewCheckBox->setChecked(true); QPushButton* previewPushButton = new QPushButton(tr("Preview"), this); connect(previewPushButton, SIGNAL(clicked()), this, SLOT(preview())); QVBoxLayout* mainLayout = new QVBoxLayout(this, 4, 4); QHBoxLayout* previewLayout = new QHBoxLayout(4); QVBoxLayout* previewSecondLayout = new QVBoxLayout(4); previewSecondLayout->addWidget(m_pAutomaticPreviewCheckBox); previewSecondLayout->addWidget(previewPushButton); previewSecondLayout->addStretch(); previewLayout->addWidget(m_pPreviewLabel); previewLayout->addLayout(previewSecondLayout); mainLayout->addWidget(m_pFileSelector); mainLayout->addLayout(previewLayout); preview(); } ImportDialog::~ImportDialog() { } const DocLnk* ImportDialog::selected() { // FIXME change from pointer to reference -zecke DocLnk *lnk = new DocLnk( m_pFileSelector->selectedDocument() ); return lnk; } void ImportDialog::fileChanged() { if (m_pAutomaticPreviewCheckBox->isChecked()) { preview(); } } void ImportDialog::preview() { const DocLnk* docLnk = selected(); if (docLnk) { QImage image(docLnk->file()); int previewWidth = m_pPreviewLabel->contentsRect().width(); int previewHeight = m_pPreviewLabel->contentsRect().height(); float widthScale = 1.0; float heightScale = 1.0; if (previewWidth < image.width()) { widthScale = (float)previewWidth / float(image.width()); } if (previewHeight < image.height()) { heightScale = (float)previewHeight / float(image.height()); } float scale = (widthScale < heightScale ? widthScale : heightScale); QImage previewImage = image.smoothScale((int)(image.width() * scale) , (int)(image.height() * scale)); QPixmap previewPixmap; previewPixmap.convertFromImage(previewImage); m_pPreviewLabel->setPixmap(previewPixmap); delete docLnk; } } diff --git a/noncore/graphics/drawpad/importdialog.h b/noncore/graphics/drawpad/importdialog.h index ef51d7c..ed655a5 100644 --- a/noncore/graphics/drawpad/importdialog.h +++ b/noncore/graphics/drawpad/importdialog.h @@ -1,45 +1,45 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef IMPORTDIALOG_H #define IMPORTDIALOG_H #include <qdialog.h> class DocLnk; -class FileSelector; +class OFileSelector; class QCheckBox; class QLabel; class ImportDialog : public QDialog { Q_OBJECT public: ImportDialog(QWidget* parent = 0, const char* name = 0); ~ImportDialog(); const DocLnk* selected(); private slots: void fileChanged(); void preview(); private: - FileSelector* m_pFileSelector; + OFileSelector* m_pFileSelector; QLabel* m_pPreviewLabel; QCheckBox* m_pAutomaticPreviewCheckBox; }; #endif // IMPORTDIALOG_H diff --git a/noncore/graphics/drawpad/main.cpp b/noncore/graphics/drawpad/main.cpp index ec628cc..12f8084 100644 --- a/noncore/graphics/drawpad/main.cpp +++ b/noncore/graphics/drawpad/main.cpp @@ -1,27 +1,27 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "drawpad.h" #include <qpe/qpeapplication.h> int main(int argc, char **argv) { QPEApplication a(argc, argv); DrawPad mw; // = new DrawPad();; a.showMainWidget(&mw ); - + mw.finishStartup(); return a.exec(); } diff --git a/noncore/graphics/drawpad/opie-drawpad.control b/noncore/graphics/drawpad/opie-drawpad.control index 1c22186..5095b52 100644 --- a/noncore/graphics/drawpad/opie-drawpad.control +++ b/noncore/graphics/drawpad/opie-drawpad.control @@ -1,12 +1,12 @@ Package: opie-drawpad Files: bin/drawpad apps/1Pim/drawpad.desktop pics/drawpad Priority: optional Section: opie/applications Maintainer: Sébastien Prud'homme <prudhomme@laposte.net> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal, libopie1 Description: A note taking program with basic draw tools DrawPad is an easy note taking program for Zaurus. It can also be used to draw simple images. DrawPad was developed for the Opie project, an alternative to the standard Zaurus environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/graphics/drawpad/texttool.h b/noncore/graphics/drawpad/texttool.h index 3187675..17556a1 100644 --- a/noncore/graphics/drawpad/texttool.h +++ b/noncore/graphics/drawpad/texttool.h @@ -1,46 +1,47 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef TEXTTOOL_H #define TEXTTOOL_H #include "tool.h" #include <qdialog.h> class QLineEdit; class TextToolDialog : public QDialog { + Q_OBJECT public: TextToolDialog(QWidget* parent = 0, const char* name = 0); ~TextToolDialog(); QString text(); private: QLineEdit* m_pLineEdit; }; class TextTool : public Tool { public: TextTool(DrawPad* drawPad, DrawPadCanvas* drawPadCanvas); ~TextTool(); void mousePressEvent(QMouseEvent* e); void mouseReleaseEvent(QMouseEvent* e); void mouseMoveEvent(QMouseEvent* e); }; #endif // TEXTTOOL_H diff --git a/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-Pod.control b/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-Pod.control index 2de15e9..faa041b 100644 --- a/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-Pod.control +++ b/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-Pod.control @@ -1,8 +1,8 @@ Package: opie-mediaplayer2-skin-Pod Files: pics/mediaplayer/skins/Pod Priority: optional Section: opie/applications Maintainer: ljp <llornkcor@handhelds.org> -Version: $QPE_VERSION-$SUB_VERSION Description: Opie Mediaplayer's skin. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-default-landscape.control b/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-default-landscape.control index 570b25a..4bc3c60 100644 --- a/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-default-landscape.control +++ b/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-default-landscape.control @@ -1,9 +1,9 @@ Package: opie-mediaplayer2-skin-default-landscape Files: pics/opieplayer2/skins/default_landscape Priority: optional Section: opie/playerskins Maintainer: L.J.Potter <ljp@llornkcor.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Landscape skin for opie mediaplayer's +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-default.control b/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-default.control index 5cd7509..d076fab 100644 --- a/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-default.control +++ b/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-default.control @@ -1,9 +1,9 @@ Package: opie-mediaplayer2-skin-default Files: pics/opieplayer2/skins/default Priority: optional Section: opie/playerskins Maintainer: L.J.Potter <ljp@llornkcor.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Default skin for opie mediaplayer's +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-techno.control b/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-techno.control index 0ff1427..ad8c1f8 100644 --- a/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-techno.control +++ b/noncore/multimedia/mediaplayerskins/opie-mediaplayer2-skin-techno.control @@ -1,8 +1,8 @@ Package: opie-mediaplayer2-skin-techno Files: pics/mediaplayer/skins/techno Priority: optional Section: opie/applications Maintainer: ljp <llornkcor@handhelds.org> -Version: $QPE_VERSION-$SUB_VERSION Description: Techno Opie Mediaplayer's skin. Adapted from Qtopia +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/multimedia/opieplayer2/audiowidget.cpp b/noncore/multimedia/opieplayer2/audiowidget.cpp index 5d929cb..2c54ae6 100644 --- a/noncore/multimedia/opieplayer2/audiowidget.cpp +++ b/noncore/multimedia/opieplayer2/audiowidget.cpp @@ -1,338 +1,324 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ -#include <qpe/qpeapplication.h> -#include <qpe/resource.h> -#include <qpe/config.h> -#include <opie/oticker.h> - -#include <qwidget.h> -#include <qpixmap.h> -#include <qbutton.h> -#include <qpainter.h> -#include <qframe.h> -#include <qlayout.h> -#include <qdir.h> -#include <stdlib.h> -#include <stdio.h> #include "audiowidget.h" #include "mediaplayerstate.h" #include "playlistwidget.h" namespace { const int xo = -2; // movable x offset const int yo = 22; // movable y offset const MediaWidget::SkinButtonInfo skinInfo[] = { { MediaWidget::Play, "play", MediaWidget::ToggleButton }, { MediaWidget::Stop, "stop", MediaWidget::NormalButton }, { MediaWidget::Next, "next", MediaWidget::NormalButton }, { MediaWidget::Previous, "prev", MediaWidget::NormalButton }, { MediaWidget::VolumeUp, "up", MediaWidget::NormalButton }, { MediaWidget::VolumeDown, "down", MediaWidget::NormalButton }, { MediaWidget::Loop, "loop", MediaWidget::ToggleButton }, { MediaWidget::PlayList, "playlist", MediaWidget::NormalButton }, { MediaWidget::Forward, "forward", MediaWidget::NormalButton }, { MediaWidget::Back, "back", MediaWidget::NormalButton } }; const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] ); void changeTextColor( QWidget * w) { QPalette p = w->palette(); p.setBrush( QColorGroup::Background, QColor( 167, 212, 167 ) ); p.setBrush( QColorGroup::Base, QColor( 167, 212, 167 ) ); w->setPalette( p ); } } AudioWidget::AudioWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name) : MediaWidget( playList, mediaPlayerState, parent, name ), songInfo( this ), slider( Qt::Horizontal, this ), time( this ), audioSliderBeingMoved( false ) { setCaption( tr("OpiePlayer") ); loadSkin(); connect( &mediaPlayerState, SIGNAL( loopingToggled(bool) ), this, SLOT( setLooping(bool) ) ); connect( &mediaPlayerState, SIGNAL( isSeekableToggled( bool ) ), this, SLOT( setSeekable( bool ) ) ); connect( this, SIGNAL( forwardClicked() ), this, SLOT( skipFor() ) ); connect( this, SIGNAL( backClicked() ), this, SLOT( skipBack() ) ); connect( this, SIGNAL( forwardReleased() ), this, SLOT( stopSkip() ) ); connect( this, SIGNAL( backReleased() ), this, SLOT( stopSkip() ) ); // Intialise state setLength( mediaPlayerState.length() ); setPosition( mediaPlayerState.position() ); setLooping( mediaPlayerState.isFullscreen() ); // setPaused( mediaPlayerState->paused() ); setPlaying( mediaPlayerState.isPlaying() ); } AudioWidget::~AudioWidget() { // mediaPlayerState->setPlaying(false); } MediaWidget::GUIInfo AudioWidget::guiInfo() { return GUIInfo( QString::null /* infix */, ::skinInfo, ::buttonCount ); } void AudioWidget::resizeEvent( QResizeEvent *e ) { int h = height(); int w = width(); songInfo.setGeometry( QRect( 2, 2, w - 4, 20 ) ); slider.setFixedWidth( w - 110 ); slider.setGeometry( QRect( 15, h - 22, w - 90, 20 ) ); slider.setBackgroundOrigin( QWidget::ParentOrigin ); time.setGeometry( QRect( w - 85, h - 30, 70, 20 ) ); upperLeftOfButtonMask.rx() = ( w - buttonUpImage.width() ) / 2; upperLeftOfButtonMask.ry() = (( h - buttonUpImage.height() ) / 2) - 10; MediaWidget::resizeEvent( e ); } void AudioWidget::sliderPressed() { audioSliderBeingMoved = TRUE; } void AudioWidget::sliderReleased() { audioSliderBeingMoved = FALSE; if ( slider.width() == 0 ) return; long val = long((double)slider.value() * mediaPlayerState.length() / slider.width()); mediaPlayerState.setPosition( val ); } void AudioWidget::setPosition( long i ) { // qDebug("<<<<<<<<<<<<<<<<<<<<<<<<set position %d",i); updateSlider( i, mediaPlayerState.length() ); } void AudioWidget::setLength( long max ) { updateSlider( mediaPlayerState.position(), max ); } void AudioWidget::setDisplayType( MediaPlayerState::DisplayType mediaType ) { if ( mediaType == MediaPlayerState::Audio ) { // startTimer( 150 ); showMaximized(); return; } killTimers(); hide(); } void AudioWidget::loadSkin() { loadDefaultSkin( guiInfo() ); songInfo.setFocusPolicy( QWidget::NoFocus ); // changeTextColor( &songInfo ); // songInfo.setBackgroundColor( QColor( 167, 212, 167 )); // songInfo.setFrameStyle( QFrame::NoFrame); songInfo.setFrameStyle( QFrame::WinPanel | QFrame::Sunken ); // songInfo.setForegroundColor(Qt::white); slider.setFixedHeight( 20 ); slider.setMinValue( 0 ); slider.setMaxValue( 1 ); slider.setFocusPolicy( QWidget::NoFocus ); slider.setBackgroundPixmap( backgroundPixmap ); // Config cofg("qpe"); // cofg.setGroup("Appearance"); // QColor backgroundcolor = QColor( cofg.readEntry( "Background", "#E5E1D5" ) ); time.setFocusPolicy( QWidget::NoFocus ); time.setAlignment( Qt::AlignCenter ); // time.setFrame(FALSE); // changeTextColor( &time ); resizeEvent( 0 ); } void AudioWidget::setSeekable( bool isSeekable ) { if ( !isSeekable ) { qDebug("<<<<<<<<<<<<<<file is STREAMING>>>>>>>>>>>>>>>>>>>"); if( !slider.isHidden()) { slider.hide(); } disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); disconnect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); disconnect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); } else { // this stops the slider from being moved, thus // does not stop stream when it reaches the end slider.show(); qDebug( " CONNECT SET POSTION " ); connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); connect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); connect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); } } static QString timeAsString( long length ) { int minutes = length / 60; int seconds = length % 60; return QString("%1:%2%3").arg( minutes ).arg( seconds / 10 ).arg( seconds % 10 ); } void AudioWidget::updateSlider( long i, long max ) { time.setText( timeAsString( i ) + " / " + timeAsString( max ) ); // qDebug( timeAsString( i ) + " / " + timeAsString( max ) ) ; if ( max == 0 ) { return; } // Will flicker too much if we don't do this // Scale to something reasonable int width = slider.width(); int val = int((double)i * width / max); if ( !audioSliderBeingMoved ) { if ( slider.value() != val ) { slider.setValue( val ); } if ( slider.maxValue() != width ) { slider.setMaxValue( width ); } } } void AudioWidget::skipFor() { skipDirection = +1; startTimer( 50 ); mediaPlayerState.setPosition( mediaPlayerState.position() + 2 ); } void AudioWidget::skipBack() { skipDirection = -1; startTimer( 50 ); mediaPlayerState.setPosition( mediaPlayerState.position() - 2 ); } void AudioWidget::stopSkip() { killTimers(); } void AudioWidget::timerEvent( QTimerEvent * ) { if ( skipDirection == +1 ) { mediaPlayerState.setPosition( mediaPlayerState.position() + 2 ); } else if ( skipDirection == -1 ) { mediaPlayerState.setPosition( mediaPlayerState.position() - 2 ); } } void AudioWidget::keyReleaseEvent( QKeyEvent *e) { switch ( e->key() ) { ////////////////////////////// Zaurus keys case Key_Home: break; case Key_F9: //activity hide(); // qDebug("Audio F9"); e->accept(); break; case Key_F10: //contacts break; case Key_F11: //menu mediaPlayerState.toggleBlank(); e->accept(); break; case Key_F12: //home break; case Key_F13: //mail mediaPlayerState.toggleBlank(); e->accept(); break; case Key_Space: { e->accept(); mediaPlayerState.togglePaused(); } break; case Key_Down: // toggleButton(6); emit lessClicked(); emit lessReleased(); // toggleButton(6); e->accept(); break; case Key_Up: // toggleButton(5); emit moreClicked(); emit moreReleased(); // toggleButton(5); e->accept(); break; case Key_Right: // toggleButton(3); mediaPlayerState.setNext(); // toggleButton(3); e->accept(); break; case Key_Left: // toggleButton(4); mediaPlayerState.setPrev(); // toggleButton(4); e->accept(); break; case Key_Escape: { } break; }; } diff --git a/noncore/multimedia/opieplayer2/audiowidget.h b/noncore/multimedia/opieplayer2/audiowidget.h index 53dbb88..b436239 100644 --- a/noncore/multimedia/opieplayer2/audiowidget.h +++ b/noncore/multimedia/opieplayer2/audiowidget.h @@ -1,102 +1,95 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef AUDIO_WIDGET_H #define AUDIO_WIDGET_H -#include <qpainter.h> -#include <qdrawutil.h> -#include <qpixmap.h> -#include <qstring.h> -#include <qslider.h> -#include <qframe.h> #include <qlineedit.h> -#include <qimage.h> #include <opie/oticker.h> #include "mediawidget.h" class QPixmap; class AudioWidget : public MediaWidget { Q_OBJECT public: AudioWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent=0, const char* name=0 ); ~AudioWidget(); void setTickerText( const QString &text ) { songInfo.setText( text ); } static MediaWidget::GUIInfo guiInfo(); public slots: void updateSlider( long, long ); void sliderPressed( ); void sliderReleased( ); void setLooping( bool b) { setToggleButton( Loop, b ); } void setPosition( long ); void setSeekable( bool ); public: virtual void setLength( long ); virtual void setPlaying( bool b) { setToggleButton( Play, b ); } virtual void setDisplayType( MediaPlayerState::DisplayType displayType ); virtual void loadSkin(); signals: void sliderMoved(long); protected: void doBlank(); void doUnblank(); void resizeEvent( QResizeEvent *re ); void timerEvent( QTimerEvent *event ); void keyReleaseEvent( QKeyEvent *e); private slots: void skipFor(); void skipBack(); void stopSkip(); private: int skipDirection; QString skin; OTicker songInfo; QSlider slider; QLineEdit time; bool isStreaming : 1; bool audioSliderBeingMoved : 1; }; #endif // AUDIO_WIDGET_H diff --git a/noncore/multimedia/opieplayer2/lib.cpp b/noncore/multimedia/opieplayer2/lib.cpp index d04af08..11ad745 100644 --- a/noncore/multimedia/opieplayer2/lib.cpp +++ b/noncore/multimedia/opieplayer2/lib.cpp @@ -1,400 +1,433 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 LJP <> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ -#include <stdio.h> -#include <stdlib.h> -#include <qimage.h> + #include <qtextstream.h> -#include <qpe/resource.h> -#include <qfile.h> #include <qdir.h> #include <qgfx_qws.h> #include <qdirectpainter_qws.h> #include <assert.h> #include "xinevideowidget.h" #include "frame.h" #include "lib.h" typedef void (*display_xine_frame_t) (void *user_data, uint8_t* frame, int width, int height,int bytes ); extern "C" { xine_vo_driver_t* init_video_out_plugin( xine_t *xine, void* video, display_xine_frame_t, void * ); int null_is_showing_video( const xine_vo_driver_t* self ); void null_set_show_video( const xine_vo_driver_t* self, int show ); int null_is_fullscreen( const xine_vo_driver_t* self ); void null_set_fullscreen( const xine_vo_driver_t* self, int screen ); int null_is_scaling( const xine_vo_driver_t* self ); void null_set_scaling( const xine_vo_driver_t* self, int scale ); void null_set_gui_width( const xine_vo_driver_t* self, int width ); void null_set_gui_height( const xine_vo_driver_t* self, int height ); void null_set_mode( const xine_vo_driver_t* self, int depth, int rgb ); void null_set_videoGamma( const xine_vo_driver_t* self , int value ); void null_display_handler( const xine_vo_driver_t* self, display_xine_frame_t t, void* user_data ); void null_preload_decoders( xine_stream_t *stream ); } using namespace XINE; Lib::Lib( InitializationMode initMode, XineVideoWidget* widget ) { m_initialized = false; m_duringInitialization = false; m_video = false; m_wid = widget; printf("Lib"); QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf"; // get the configuration // not really OO, should be an extra class, later if ( !QFile::exists(configPath) ) { QFile f(configPath); f.open(IO_WriteOnly); QTextStream ts( &f ); ts << "misc.memcpy_method:glibc\n"; + ts << "# uncomment if you experience double speed audio \n #audio.oss_sync_method:softsync\n"; + ts << "codec.ffmpeg_pp_quality:3\n"; + ts << "audio.num_buffers:50\n"; + ts << "audio.size_buffers:4160\n"; + ts << "video.num_buffers:20\n"; + ts << "video.size_buffers:4096\n"; + ts << "audio.out_num_audio_buf:16\n"; + ts << "audio.out_size_audio_buf:8096\n"; + ts << "audio.out_size_zero_buf:1024\n"; + ts << "audio.passthrough_offset:0\n"; f.close(); } if ( initMode == InitializeImmediately ) { initialize(); m_initialized = true; } else start(); } void Lib::run() { qDebug( "Lib::run() started" ); initialize(); m_initialized = true; qDebug( "Lib::run() finished" ); } void Lib::initialize() { m_duringInitialization = true; m_xine = xine_new( ); QString configPath = QDir::homeDirPath() + "/Settings/opiexine.cf"; xine_config_load( m_xine, QFile::encodeName( configPath ) ); xine_init( m_xine ); // allocate oss for sound // and fb for framebuffer m_audioOutput = xine_open_audio_driver( m_xine, "oss", NULL ); m_videoOutput = ::init_video_out_plugin( m_xine, NULL, xine_display_frame, this ); //xine_open_video_driver( m_xine, NULL, XINE_VISUAL_TYPE_FB, NULL); // null_display_handler( m_videoOutput, xine_display_frame, this ); m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput ); if (m_wid != 0 ) { printf( "!0\n" ); setWidget( m_wid ); } m_queue = xine_event_new_queue (m_stream); xine_event_create_listener_thread (m_queue, xine_event_handler, this); ::null_preload_decoders( m_stream ); m_duringInitialization = false; } Lib::~Lib() { assert( isRunning() == false ); assert( m_initialized ); // free( m_config ); xine_close( m_stream ); xine_event_dispose_queue( m_queue ); xine_dispose( m_stream ); xine_exit( m_xine ); /* FIXME either free or delete but valgrind bitches against both */ //free( m_videoOutput ); //delete m_audioOutput; } void Lib::resize ( const QSize &s ) { assert( m_initialized || m_duringInitialization ); if ( s. width ( ) && s. height ( ) ) { ::null_set_gui_width( m_videoOutput, s. width() ); ::null_set_gui_height( m_videoOutput, s. height() ); } } int Lib::majorVersion() { int major, minor, sub; xine_get_version ( &major, &minor, &sub ); return major; } int Lib::minorVersion() { int major, minor, sub; xine_get_version ( &major, &minor, &sub ); return minor; } int Lib::subVersion() { int major, minor, sub; xine_get_version ( &major, &minor, &sub ); return sub; } int Lib::play( const QString& fileName, int startPos, int start_time ) { assert( m_initialized ); + // FIXME actually a hack imho. Should not be needed to dispose the whole stream + // but without we get wrong media length reads from libxine for the second media + //xine_dispose ( m_stream ); QString str = fileName.stripWhiteSpace(); + + //m_stream = xine_stream_new (m_xine, m_audioOutput, m_videoOutput ); + //m_queue = xine_event_new_queue (m_stream); + //xine_event_create_listener_thread (m_queue, xine_event_handler, this); + if ( !xine_open( m_stream, QFile::encodeName(str.utf8() ).data() ) ) { return 0; } return xine_play( m_stream, startPos, start_time); } void Lib::stop() { assert( m_initialized ); qDebug("<<<<<<<< STOP IN LIB TRIGGERED >>>>>>>"); xine_stop( m_stream ); } void Lib::pause( bool toggle ) { assert( m_initialized ); xine_set_param( m_stream, XINE_PARAM_SPEED, toggle ? XINE_SPEED_PAUSE : XINE_SPEED_NORMAL ); } int Lib::speed() const { assert( m_initialized ); return xine_get_param ( m_stream, XINE_PARAM_SPEED ); } void Lib::setSpeed( int speed ) { assert( m_initialized ); xine_set_param ( m_stream, XINE_PARAM_SPEED, speed ); } int Lib::status() const { assert( m_initialized ); return xine_get_status( m_stream ); } int Lib::currentPosition() const { assert( m_initialized ); int pos, time, length; xine_get_pos_length( m_stream, &pos, &time, &length ); return pos; } int Lib::currentTime() const { assert( m_initialized ); int pos, time, length; xine_get_pos_length( m_stream, &pos, &time, &length ); + if ( time > 0 ) { return time/1000; + } else { + return 0; + } } int Lib::length() const { assert( m_initialized ); int pos, time, length; - xine_get_pos_length( m_stream, &pos, &time, &length ); +/* dilb: patch to solve the wrong stream length reported to the GUI*/ + int iRetVal=0, iTestLoop=0; + + do + { + iRetVal = xine_get_pos_length( m_stream, &pos, &time, &length ); + if (iRetVal) + {/* if the function didn't return 0, then pos, time and length are valid.*/ return length/1000; } + /*don't poll too much*/ + usleep(100000); + iTestLoop++; + } + while ( iTestLoop < 10 ); /* if after 1s, we still don't have any +valid stream, then return -1 (this value could be used to make the stream +unseekable, but it should never occur!! Mr. Murphy ? :) ) */ + + return -1; +} bool Lib::isSeekable() const { assert( m_initialized ); return xine_get_stream_info( m_stream, XINE_STREAM_INFO_SEEKABLE ); } void Lib::seekTo( int time ) { assert( m_initialized ); //xine_trick_mode ( m_stream, XINE_TRICK_MODE_SEEK_TO_TIME, time ); NOT IMPLEMENTED YET IN XINE :_( // since its now milliseconds we need *1000 xine_play( m_stream, 0, time*1000 ); } Frame Lib::currentFrame() const { assert( m_initialized ); Frame frame; return frame; }; QString Lib::metaInfo( int number) const { assert( m_initialized ); return xine_get_meta_info( m_stream, number ); } int Lib::error() const { assert( m_initialized ); return xine_get_error( m_stream ); }; void Lib::ensureInitialized() { if ( m_initialized ) return; qDebug( "waiting for initialization thread to finish" ); wait(); qDebug( "initialization thread finished!" ); } void Lib::setWidget( XineVideoWidget *widget ) { m_wid = widget; resize ( m_wid-> size ( ) ); ::null_set_mode( m_videoOutput, qt_screen->depth(), qt_screen->pixelType() ); m_wid->repaint(); } void Lib::receiveMessage( ThreadUtil::ChannelMessage *msg, SendType sendType ) { assert( sendType == ThreadUtil::Channel::OneWay ); handleXineEvent( msg->type() ); delete msg; } void Lib::handleXineEvent( const xine_event_t* t ) { send( new ThreadUtil::ChannelMessage( t->type ), OneWay ); } void Lib::handleXineEvent( int type ) { assert( m_initialized ); if ( type == XINE_EVENT_UI_PLAYBACK_FINISHED ) { emit stopped(); } } void Lib::setShowVideo( bool video ) { assert( m_initialized ); m_video = video; ::null_set_show_video( m_videoOutput, video ); } bool Lib::isShowingVideo() const { assert( m_initialized ); return ::null_is_showing_video( m_videoOutput ); } bool Lib::hasVideo() const { assert( m_initialized ); return xine_get_stream_info( m_stream, 18 ); } void Lib::showVideoFullScreen( bool fullScreen ) { assert( m_initialized ); ::null_set_fullscreen( m_videoOutput, fullScreen ); } bool Lib::isVideoFullScreen() const { assert( m_initialized ); return ::null_is_fullscreen( m_videoOutput ); } void Lib::setScaling( bool scale ) { assert( m_initialized ); ::null_set_scaling( m_videoOutput, scale ); } void Lib::setGamma( int value ) { assert( m_initialized ); - //qDebug( QString( "%1").arg(value) ); - /* int gammaValue = ( 100 + value ); */ ::null_set_videoGamma( m_videoOutput, value ); } bool Lib::isScaling() const { assert( m_initialized ); return ::null_is_scaling( m_videoOutput ); } void Lib::xine_event_handler( void* user_data, const xine_event_t* t ) { ( (Lib*)user_data)->handleXineEvent( t ); } void Lib::xine_display_frame( void* user_data, uint8_t *frame, int width, int height, int bytes ) { ( (Lib*)user_data)->drawFrame( frame, width, height, bytes ); } void Lib::drawFrame( uint8_t* frame, int width, int height, int bytes ) { assert( m_initialized ); if ( !m_video ) { qWarning("not showing video now"); return; } assert( m_wid ); m_wid-> setVideoFrame ( frame, width, height, bytes ); } diff --git a/noncore/multimedia/opieplayer2/lib.h b/noncore/multimedia/opieplayer2/lib.h index 181735c..0ff14d0 100644 --- a/noncore/multimedia/opieplayer2/lib.h +++ b/noncore/multimedia/opieplayer2/lib.h @@ -1,221 +1,216 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 LJP <> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef ZECKEXINELIB_H #define ZECKEXINELIB_H -#include <qcstring.h> -#include <qstring.h> -#include <qobject.h> - #include <xine.h> -//#include "xine.h" #include "threadutil.h" class XineVideoWidget; namespace XINE { /** * Lib wrapps the simple interface * of libxine for easy every day use * This will become a full C++ Wrapper * It supports playing, pausing, info, * stooping, seeking. */ class Frame; class Lib : public ThreadUtil::Channel, private ThreadUtil::Thread { Q_OBJECT public: enum InitializationMode { InitializeImmediately, InitializeInThread }; Lib( InitializationMode initMode, XineVideoWidget* = 0); ~Lib(); static int majorVersion(); static int minorVersion(); static int subVersion(); void resize ( const QSize &s ); int play( const QString& fileName, int startPos = 0, int start_time = 0 ); void stop(); void pause( bool toggle ); int speed() const; /** * Set the speed of the stream, if codec supports it * XINE_SPEED_PAUSE 0 * XINE_SPEED_SLOW_4 1 * XINE_SPEED_SLOW_2 2 * XINE_SPEED_NORMAL 4 * XINE_SPEED_FAST_2 8 *XINE_SPEED_FAST_4 16 */ void setSpeed( int speed = XINE_SPEED_PAUSE ); int status() const; int currentPosition()const; //in seconds int currentTime()const; int length() const; bool isSeekable()const; /** * Whether or not to show video output */ void setShowVideo(bool video); /** * is we show video */ bool isShowingVideo() const; /** * */ void showVideoFullScreen( bool fullScreen ); /** * */ bool isVideoFullScreen() const; /** * Get the meta info (like author etc) from the stream * XINE_META_INFO_TITLE 0 * XINE_META_INFO_COMMENT 1 * XINE_META_INFO_ARTIST 2 * XINE_META_INFO_GENRE 3 * XINE_META_INFO_ALBUM 4 * XINE_META_INFO_YEAR 5 * XINE_META_INFO_VIDEOCODEC 6 * XINE_META_INFO_AUDIOCODEC 7 * XINE_META_INFO_SYSTEMLAYER 8 * XINE_META_INFO_INPUT_PLUGIN 9 */ QString metaInfo( int number ) const; /** * */ bool isScaling() const; /** * seek to a position */ void seekTo( int time ); /** * * @return is media stream has video */ bool hasVideo() const; /** * */ void setScaling( bool ); /** * Set the Gamma value for video output * @param int the value between -100 and 100, 0 is original */ void setGamma( int ); /** * test */ Frame currentFrame() const; /** * Returns the error code * XINE_ERROR_NONE 0 * XINE_ERROR_NO_INPUT_PLUGIN 1 * XINE_ERROR_NO_DEMUXER_PLUGIN 2 * XINE_ERROR_DEMUXER_FAILED 3 */ int error() const; void ensureInitialized(); void setWidget( XineVideoWidget *widget ); signals: void stopped(); void initialized(); protected: virtual void receiveMessage( ThreadUtil::ChannelMessage *msg, SendType sendType ); virtual void run(); private: void initialize(); int m_bytes_per_pixel; bool m_initialized:1; bool m_duringInitialization:1; bool m_video:1; XineVideoWidget *m_wid; xine_t *m_xine; xine_stream_t *m_stream; xine_cfg_entry_t *m_config; xine_vo_driver_t *m_videoOutput; xine_ao_driver_t* m_audioOutput; xine_event_queue_t *m_queue; void handleXineEvent( const xine_event_t* t ); void handleXineEvent( int type ); void drawFrame( uint8_t* frame, int width, int height, int bytes ); // C -> C++ bridge for the event system static void xine_event_handler( void* user_data, const xine_event_t* t); static void xine_display_frame( void* user_data, uint8_t* frame , int width, int height, int bytes ); }; }; #endif diff --git a/noncore/multimedia/opieplayer2/mediadetect.cpp b/noncore/multimedia/opieplayer2/mediadetect.cpp deleted file mode 100644 index 91137db..0000000 --- a/noncore/multimedia/opieplayer2/mediadetect.cpp +++ b/dev/null @@ -1,43 +0,0 @@ -#include <qstring.h> -#include "mediadetect.h" - - -MediaDetect::MediaDetect() { -} - -MediaDetect::~MediaDetect() { -} - -char MediaDetect::videoOrAudio( const QString& fileName ) { - if( (fileName.lower()).right(4) == ".avi" || - (fileName.lower()).right(4) == ".mpg" || - (fileName.lower()).right(4) == ".asf" || - (fileName.lower()).right(4) == ".mov" || - (fileName.lower()).right(5) == ".mpeg" ) { - qDebug("Video out taken"); - return 'v'; - } else if ( (fileName.lower()).right(4) == "·mp1" || - (fileName.lower()).right(4) == ".mp3" || - (fileName.lower()).right(4) == ".ogg" || - (fileName.lower()).right(4) == ".wav" ) { - qDebug("AUDIO out taken"); - return 'a'; - } else if ( (fileName.lower()).left(7) == "http://" && - (fileName.lower()).right(1) == "/" ) { - return 'a'; - } else { - return 'f'; - } -} - -bool MediaDetect::isStreaming( const QString& fileName ) { - // ugly - if( (fileName.lower()).left(4) == "http" ) { - return true; - } else if ( (fileName.lower()).left(3) == "ftp" ) { - return true; - } else { - return false; - } -} - diff --git a/noncore/multimedia/opieplayer2/mediadetect.h b/noncore/multimedia/opieplayer2/mediadetect.h deleted file mode 100644 index bd5ea1d..0000000 --- a/noncore/multimedia/opieplayer2/mediadetect.h +++ b/dev/null @@ -1,31 +0,0 @@ - -#ifndef MEDIADETECT_H -#define MEDIADETECT_H - - -class QString; -class MediaDetect { - -public: - MediaDetect(); - ~MediaDetect(); - - /** - * Look at the filename and decide which gui is to be used - * - * @param filename the filename - * @return the char - a for audio gui, v for video, f for error - */ - char videoOrAudio( const QString& fileName ); - - /** - * Find out if it is a streaming media file - * - * @param filename the filename - * @return if it is a streaming url or not - */ - bool isStreaming( const QString& fileName ); - -}; - -#endif diff --git a/noncore/multimedia/opieplayer2/mediaplayer.cpp b/noncore/multimedia/opieplayer2/mediaplayer.cpp index d4396d2..9f51006 100644 --- a/noncore/multimedia/opieplayer2/mediaplayer.cpp +++ b/noncore/multimedia/opieplayer2/mediaplayer.cpp @@ -1,414 +1,405 @@ #include <qpe/qpeapplication.h> -#include <qpe/qlibrary.h> -#include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qcopenvelope_qws.h> #include <qfileinfo.h> -#include <qmainwindow.h> -#include <qmessagebox.h> -#include <qwidgetstack.h> -#include <qfile.h> - #include "mediaplayer.h" #include "playlistwidget.h" #include "audiowidget.h" #include "videowidget.h" #include "volumecontrol.h" #include "lib.h" #include "mediaplayerstate.h" // for setBacklight() #include <linux/fb.h> #include <sys/file.h> #include <sys/ioctl.h> - - #define FBIOBLANK 0x4611 MediaPlayer::MediaPlayer( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QObject *parent, const char *name ) : QObject( parent, name ), volumeDirection( 0 ), mediaPlayerState( _mediaPlayerState ), playList( _playList ) { m_audioUI = 0; m_videoUI = 0; m_xineControl = 0; xine = new XINE::Lib( XINE::Lib::InitializeInThread ); fd=-1;fl=-1; playList.setCaption( tr( "OpiePlayer: Initializating" ) ); qApp->processEvents(); // QPEApplication::grabKeyboard(); // EVIL connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); connect( &mediaPlayerState, SIGNAL( playingToggled( bool ) ), this, SLOT( setPlaying( bool ) ) ); // What is pauseCheck good for? (Simon) // connect( &mediaPlayerState, SIGNAL( pausedToggled( bool ) ), this, SLOT( pauseCheck( bool ) ) ); connect( &mediaPlayerState, SIGNAL( next() ), this, SLOT( next() ) ); connect( &mediaPlayerState, SIGNAL( prev() ), this, SLOT( prev() ) ); connect( &mediaPlayerState, SIGNAL( blankToggled( bool ) ), this, SLOT ( blank( bool ) ) ); volControl = new VolumeControl; Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default"); playList.setCaption( tr( "OpiePlayer: " ) + QFileInfo(currentPlaylist).baseName() ); m_skinLoader = new SkinLoader; m_skinLoader->schedule( AudioWidget::guiInfo() ); m_skinLoader->schedule( VideoWidget::guiInfo() ); m_skinLoader->start(); } MediaPlayer::~MediaPlayer() { // this shold never happen, but one never knows... if ( xine ) { xine->ensureInitialized(); delete xine; } delete m_xineControl; delete m_audioUI; delete m_videoUI; delete volControl; } void MediaPlayer::pauseCheck( bool b ) { if ( b && !mediaPlayerState.isPlaying() ) { mediaPlayerState.setPaused( FALSE ); } } void MediaPlayer::play() { mediaPlayerState.setPlaying( FALSE ); mediaPlayerState.setPlaying( TRUE ); } void MediaPlayer::setPlaying( bool play ) { if ( !play ) { return; } if ( mediaPlayerState.isPaused() ) { mediaPlayerState.setPaused( FALSE ); return; } QString tickerText, time, fileName; if ( playList.currentTab() != PlayListWidget::CurrentPlayList ) { //if playing in file list.. play in a different way // random and looping settings enabled causes problems here, // since there is no selected file in the playlist, but a selected file in the file list, // so we remember and shutoff l = mediaPlayerState.isLooping(); if(l) { mediaPlayerState.setLooping( false ); } r = mediaPlayerState.isShuffled(); mediaPlayerState.setShuffled( false ); } PlayListWidget::Entry playListEntry = playList.currentEntry(); fileName = playListEntry.name; xineControl()->play( playListEntry.file ); long seconds = mediaPlayerState.length(); time.sprintf("%li:%02i", seconds/60, (int)seconds%60 ); if( fileName.left(4) == "http" ) { fileName = QFileInfo( fileName ).baseName(); if ( xineControl()->getMetaInfo().isEmpty() ) { tickerText = tr( " File: " ) + fileName; } else { tickerText = xineControl()->getMetaInfo(); } } else { if ( xineControl()->getMetaInfo().isEmpty() ) { tickerText = tr( " File: " ) + fileName + tr( ", Length: " ) + time + " "; } else { tickerText = xineControl()->getMetaInfo() + " Length: " + time + " "; } } audioUI()->setTickerText( tickerText ); } void MediaPlayer::prev() { if( playList.currentTab() == PlayListWidget::CurrentPlayList ) { //if using the playlist if ( playList.prev() ) { play(); } else if ( mediaPlayerState.isLooping() ) { if ( playList.last() ) { play(); } } else { mediaPlayerState.setList(); } } } void MediaPlayer::next() { if(playList.currentTab() == PlayListWidget::CurrentPlayList) { //if using the playlist if ( playList.next() ) { play(); } else if ( mediaPlayerState.isLooping() ) { if ( playList.first() ) { play(); } } else { mediaPlayerState.setList(); } } else { //if playing from file list, let's just stop qDebug("<<<<<<<<<<<<<<<<<stop for filelists"); mediaPlayerState.setPlaying(false); mediaPlayerState.setDisplayType( MediaPlayerState::MediaSelection ); if(l) mediaPlayerState.setLooping(l); if(r) mediaPlayerState.setShuffled(r); } qApp->processEvents(); } void MediaPlayer::startDecreasingVolume() { volumeDirection = -1; startTimer( 100 ); volControl->decVol(2); } void MediaPlayer::startIncreasingVolume() { volumeDirection = +1; startTimer( 100 ); volControl->incVol(2); } bool drawnOnScreenDisplay = FALSE; unsigned int onScreenDisplayVolume = 0; const int yoff = 110; void MediaPlayer::stopChangingVolume() { killTimers(); // Get rid of the on-screen display stuff drawnOnScreenDisplay = FALSE; onScreenDisplayVolume = 0; int w=0; int h=0; if( !xineControl()->hasVideo() ) { w = audioUI()->width(); h = audioUI()->height(); audioUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE ); } else { w = videoUI()->width(); h = videoUI()->height(); videoUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE ); } } void MediaPlayer::timerEvent( QTimerEvent * ) { if ( volumeDirection == +1 ) { volControl->incVol( 2 ); } else if ( volumeDirection == -1 ) { volControl->decVol( 2 ); } // TODO FIXME // huh?? unsigned int v= 0; v = volControl->volume(); v = v / 10; if ( drawnOnScreenDisplay && onScreenDisplayVolume == v ) { return; } int w=0; int h=0; if( !xineControl()->hasVideo() ) { w = audioUI()->width(); h = audioUI()->height(); if ( drawnOnScreenDisplay ) { if ( onScreenDisplayVolume > v ) { audioUI()->repaint( ( w - 200 ) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE ); } } drawnOnScreenDisplay = TRUE; onScreenDisplayVolume = v; QPainter p( audioUI() ); p.setPen( QColor( 0x10, 0xD0, 0x10 ) ); p.setBrush( QColor( 0x10, 0xD0, 0x10 ) ); QFont f; f.setPixelSize( 20 ); f.setBold( TRUE ); p.setFont( f ); p.drawText( (w - 200) / 2, h - yoff + 20, tr("Volume") ); for ( unsigned int i = 0; i < 10; i++ ) { if ( v > i ) { p.drawRect( ( w - 200 ) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 ); } else { p.drawRect( ( w - 200 ) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 ); } } } else { w = videoUI()->width(); h = videoUI()->height(); if ( drawnOnScreenDisplay ) { if ( onScreenDisplayVolume > v ) { videoUI()->repaint( (w - 200) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE ); } } drawnOnScreenDisplay = TRUE; onScreenDisplayVolume = v; QPainter p( videoUI() ); p.setPen( QColor( 0x10, 0xD0, 0x10 ) ); p.setBrush( QColor( 0x10, 0xD0, 0x10 ) ); QFont f; f.setPixelSize( 20 ); f.setBold( TRUE ); p.setFont( f ); p.drawText( (w - 200) / 2, h - yoff + 20, tr( "Volume" ) ); for ( unsigned int i = 0; i < 10; i++ ) { if ( v > i ) { p.drawRect( (w - 200) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 ); } else { p.drawRect( (w - 200) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 ); } } } } void MediaPlayer::blank( bool b ) { fd=open("/dev/fb0",O_RDWR); #ifdef QT_QWS_SL5XXX fl= open( "/dev/fl", O_RDWR ); #endif if (fd != -1) { if ( b ) { qDebug("do blanking"); #ifdef QT_QWS_SL5XXX ioctl( fd, FBIOBLANK, 1 ); if(fl !=-1) { ioctl( fl, 2 ); ::close(fl); } #else ioctl( fd, FBIOBLANK, 3 ); #endif isBlanked = TRUE; } else { qDebug("do unblanking"); ioctl( fd, FBIOBLANK, 0); #ifdef QT_QWS_SL5XXX if(fl != -1) { ioctl( fl, 1); ::close(fl); } #endif isBlanked = FALSE; } close( fd ); } else { qDebug("<< /dev/fb0 could not be opened >>"); } } void MediaPlayer::keyReleaseEvent( QKeyEvent *e) { switch ( e->key() ) { ////////////////////////////// Zaurus keys case Key_Home: break; case Key_F9: //activity break; case Key_F10: //contacts break; case Key_F11: //menu break; case Key_F12: //home qDebug("Blank here"); // mediaPlayerState->toggleBlank(); break; case Key_F13: //mail qDebug("Blank here"); // mediaPlayerState->toggleBlank(); break; } } void MediaPlayer::cleanUp() {// this happens on closing Config cfg( "OpiePlayer" ); mediaPlayerState.writeConfig( cfg ); playList.writeDefaultPlaylist( ); // QPEApplication::grabKeyboard(); // QPEApplication::ungrabKeyboard(); } void MediaPlayer::recreateAudioAndVideoWidgets() const { delete m_skinLoader; delete m_xineControl; delete m_audioUI; delete m_videoUI; m_audioUI = new AudioWidget( playList, mediaPlayerState, 0, "audioUI" ); m_videoUI = new VideoWidget( playList, mediaPlayerState, 0, "videoUI" ); connect( m_audioUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) ); connect( m_audioUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) ); connect( m_audioUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) ); connect( m_audioUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) ); connect( m_videoUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) ); connect( m_videoUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) ); connect( m_videoUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) ); connect( m_videoUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) ); if ( !xine ) xine = new XINE::Lib( XINE::Lib::InitializeImmediately ); m_xineControl = new XineControl( xine, m_videoUI->vidWidget(), mediaPlayerState ); xine = 0; } AudioWidget *MediaPlayer::audioUI() const { if ( !m_audioUI ) recreateAudioAndVideoWidgets(); return m_audioUI; } VideoWidget *MediaPlayer::videoUI() const { if ( !m_videoUI ) recreateAudioAndVideoWidgets(); return m_videoUI; } XineControl *MediaPlayer::xineControl() const { if ( !m_xineControl ) recreateAudioAndVideoWidgets(); return m_xineControl; } void MediaPlayer::reloadSkins() { audioUI()->loadSkin(); videoUI()->loadSkin(); } diff --git a/noncore/multimedia/opieplayer2/mediaplayer.h b/noncore/multimedia/opieplayer2/mediaplayer.h index cbe4d86..34ff064 100644 --- a/noncore/multimedia/opieplayer2/mediaplayer.h +++ b/noncore/multimedia/opieplayer2/mediaplayer.h @@ -1,105 +1,102 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 LJP <> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef MEDIA_PLAYER_H #define MEDIA_PLAYER_H -#include <qmainwindow.h> -#include <qframe.h> - #include "xinecontrol.h" #include "playlistwidget.h" #include "skin.h" class DocLnk; class VolumeControl; class MediaPlayerState; class AudioWidget; class VideoWidget; namespace XINE { class Lib; }; class MediaPlayer : public QObject { Q_OBJECT public: MediaPlayer( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QObject *parent, const char *name ); ~MediaPlayer(); public slots: void reloadSkins(); private slots: void setPlaying( bool ); void pauseCheck( bool ); void play(); void next(); void prev(); void startIncreasingVolume(); void startDecreasingVolume(); void stopChangingVolume(); void cleanUp(); void blank( bool ); protected: void timerEvent( QTimerEvent *e ); void keyReleaseEvent( QKeyEvent *e); private: AudioWidget *audioUI() const; VideoWidget *videoUI() const; XineControl *xineControl() const; bool isBlanked, l, r; int fd, fl; int volumeDirection; VolumeControl *volControl; MediaPlayerState &mediaPlayerState; PlayListWidget &playList; void recreateAudioAndVideoWidgets() const; mutable XineControl *m_xineControl; mutable AudioWidget *m_audioUI; mutable VideoWidget *m_videoUI; mutable XINE::Lib *xine; QGuardedPtr<SkinLoader> m_skinLoader; }; #endif // MEDIA_PLAYER_H diff --git a/noncore/multimedia/opieplayer2/mediawidget.cpp b/noncore/multimedia/opieplayer2/mediawidget.cpp index 3953d92..b1f88c9 100644 --- a/noncore/multimedia/opieplayer2/mediawidget.cpp +++ b/noncore/multimedia/opieplayer2/mediawidget.cpp @@ -1,263 +1,265 @@ /* Copyright (C) 2002 Simon Hausmann <simon@lst.de> (C) 2002 Max Reiss <harlekin@handhelds.org> (C) 2002 L. Potter <ljp@llornkcor.com> (C) 2002 Holger Freyther <zecke@handhelds.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ +#include <assert.h> + #include "mediawidget.h" #include "playlistwidget.h" #include "skin.h" #include <assert.h> MediaWidget::MediaWidget( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QWidget *parent, const char *name ) : QWidget( parent, name ), mediaPlayerState( _mediaPlayerState ), playList( _playList ) { connect( &mediaPlayerState, SIGNAL( displayTypeChanged( MediaPlayerState::DisplayType ) ), this, SLOT( setDisplayType( MediaPlayerState::DisplayType ) ) ); connect( &mediaPlayerState, SIGNAL( lengthChanged( long ) ), this, SLOT( setLength( long ) ) ); connect( &mediaPlayerState, SIGNAL( playingToggled( bool ) ), this, SLOT( setPlaying( bool ) ) ); setBackgroundMode( NoBackground ); } MediaWidget::~MediaWidget() { } void MediaWidget::setupButtons( const SkinButtonInfo *skinInfo, uint buttonCount, const Skin &skin ) { buttonMask = skin.buttonMask( skinInfo, buttonCount ); buttons.clear(); buttons.reserve( buttonCount ); for ( uint i = 0; i < buttonCount; ++i ) { Button button = setupButton( skinInfo[ i ], skin ); buttons.push_back( button ); } } MediaWidget::Button MediaWidget::setupButton( const SkinButtonInfo &buttonInfo, const Skin &skin ) { Button button; button.command = buttonInfo.command; button.type = buttonInfo.type; button.mask = skin.buttonMaskImage( buttonInfo.fileName ); return button; } void MediaWidget::loadDefaultSkin( const GUIInfo &guiInfo ) { Skin skin( guiInfo.fileNameInfix ); skin.setCachable( false ); loadSkin( guiInfo.buttonInfo, guiInfo.buttonCount, skin ); } void MediaWidget::loadSkin( const SkinButtonInfo *skinInfo, uint buttonCount, const Skin &skin ) { backgroundPixmap = skin.backgroundPixmap(); buttonUpImage = skin.buttonUpImage(); buttonDownImage = skin.buttonDownImage(); setupButtons( skinInfo, buttonCount, skin ); } void MediaWidget::closeEvent( QCloseEvent * ) { mediaPlayerState.setList(); } void MediaWidget::paintEvent( QPaintEvent *pe ) { QPainter p( this ); if ( mediaPlayerState.isFullscreen() ) { // Clear the background p.setBrush( QBrush( Qt::black ) ); return; } QPixmap buffer( size() ); QPainter bufferedPainter( &buffer ); bufferedPainter.drawTiledPixmap( rect(), backgroundPixmap, QPoint( 0, 0 ) ); paintAllButtons( bufferedPainter ); p.drawPixmap( 0, 0, buffer ); } void MediaWidget::resizeEvent( QResizeEvent *e ) { QPixmap pixUp = combineImageWithBackground( buttonUpImage, backgroundPixmap, upperLeftOfButtonMask ); QPixmap pixDn = combineImageWithBackground( buttonDownImage, backgroundPixmap, upperLeftOfButtonMask ); for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it ) { Button &button = *it; if ( button.mask.isNull() ) continue; button.pixUp = addMaskToPixmap( pixUp, button.mask ); button.pixDown = addMaskToPixmap( pixDn, button.mask ); } QWidget::resizeEvent( e ); } MediaWidget::Button *MediaWidget::buttonAt( const QPoint &position ) { if ( position.x() <= 0 || position.y() <= 0 || position.x() >= buttonMask.width() || position.y() >= buttonMask.height() ) return 0; int pixelIdx = buttonMask.pixelIndex( position.x(), position.y() ); for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it ) if ( it->command + 1 == pixelIdx ) return &( *it ); return 0; } void MediaWidget::mousePressEvent( QMouseEvent *event ) { Button *button = buttonAt( event->pos() - upperLeftOfButtonMask ); if ( !button ) { QWidget::mousePressEvent( event ); return; } switch ( button->command ) { case VolumeUp: emit moreClicked(); return; case VolumeDown: emit lessClicked(); return; case Back: emit backClicked(); return; case Forward: emit forwardClicked(); return; default: break; } } void MediaWidget::mouseReleaseEvent( QMouseEvent *event ) { Button *button = buttonAt( event->pos() - upperLeftOfButtonMask ); if ( !button ) { QWidget::mouseReleaseEvent( event ); return; } if ( button->type == ToggleButton ) toggleButton( *button ); handleCommand( button->command, button->isDown ); } void MediaWidget::makeVisible() { } void MediaWidget::handleCommand( Command command, bool buttonDown ) { switch ( command ) { case Play: mediaPlayerState.togglePaused(); return; case Stop: mediaPlayerState.setPlaying(FALSE); return; case Next: if( playList.currentTab() == PlayListWidget::CurrentPlayList ) mediaPlayerState.setNext(); return; case Previous: if( playList.currentTab() == PlayListWidget::CurrentPlayList ) mediaPlayerState.setPrev(); return; case Loop: mediaPlayerState.setLooping( buttonDown ); return; case VolumeUp: emit moreReleased(); return; case VolumeDown: emit lessReleased(); return; case PlayList: mediaPlayerState.setList(); return; case Forward: emit forwardReleased(); return; case Back: emit backReleased(); return; case FullScreen: mediaPlayerState.setFullscreen( true ); makeVisible(); return; default: assert( false ); } } bool MediaWidget::isOverButton( const QPoint &position, int buttonId ) const { return ( position.x() > 0 && position.y() > 0 && position.x() < buttonMask.width() && position.y() < buttonMask.height() && buttonMask.pixelIndex( position.x(), position.y() ) == buttonId + 1 ); } void MediaWidget::paintAllButtons( QPainter &p ) { for ( ButtonVector::const_iterator it = buttons.begin(); it != buttons.end(); ++it ) paintButton( p, *it ); } void MediaWidget::paintButton( const Button &button ) { QPainter p( this ); paintButton( p, button ); } void MediaWidget::paintButton( QPainter &p, const Button &button ) { if ( button.isDown ) p.drawPixmap( upperLeftOfButtonMask, button.pixDown ); else p.drawPixmap( upperLeftOfButtonMask, button.pixUp ); } void MediaWidget::setToggleButton( Command command, bool down ) { for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it ) if ( it->command == command ) { setToggleButton( *it, down ); return; } } void MediaWidget::setToggleButton( Button &button, bool down ) { if ( down != button.isDown ) toggleButton( button ); } void MediaWidget::toggleButton( Button &button ) { button.isDown = !button.isDown; paintButton( button ); } QPixmap MediaWidget::combineImageWithBackground( const QImage &image, const QPixmap &background, const QPoint &offset ) { QPixmap pix( image.size() ); QPainter p( &pix ); p.drawTiledPixmap( pix.rect(), background, offset ); p.drawImage( 0, 0, image ); return pix; } QPixmap MediaWidget::addMaskToPixmap( const QPixmap &pix, const QBitmap &mask ) { QPixmap result( pix ); result.setMask( mask ); return result; } /* vim: et sw=4 ts=4 */ diff --git a/noncore/multimedia/opieplayer2/om3u.cpp b/noncore/multimedia/opieplayer2/om3u.cpp index 841d950..7183fb4 100644 --- a/noncore/multimedia/opieplayer2/om3u.cpp +++ b/noncore/multimedia/opieplayer2/om3u.cpp @@ -1,166 +1,160 @@ /* This file is part of the Opie Project Copyright (c) 2002 L. Potter <ljp@llornkcor.com> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "playlistwidget.h" #include "om3u.h" #include <qpe/applnk.h> #include <qpe/qpeapplication.h> #include <qpe/storage.h> #include <qpe/mimetype.h> #include <qpe/global.h> #include <qpe/resource.h> #include <qdir.h> #include <qregexp.h> #include <qstring.h> #include <qtextstream.h> #include <qstringlist.h> #include <qcstring.h> //extern PlayListWidget *playList; Om3u::Om3u( const QString &filePath, int mode) : QStringList (){ qDebug("<<<<<<<new m3u "+filePath); f.setName(filePath); f.open(mode); } Om3u::~Om3u(){} void Om3u::readM3u() { // qDebug("<<<<<<reading m3u "+f.name()); QTextStream t(&f); QString s; while ( !t.atEnd() ) { s=t.readLine(); // qDebug(s); if( s.find( "#", 0, TRUE) == -1 ) { if( s.left(2) == "E:" || s.left(2) == "P:" ) { s = s.right( s.length() -2 ); QFileInfo f( s ); QString name = f.baseName(); name = name.right( name.length() - name.findRev( "\\", -1, TRUE ) -1 ); s=s.replace( QRegExp( "\\" ), "/" ); append(s); // qDebug(s); } else { // is url - s.replace( QRegExp( "%20" )," " ); QString name; -// if( name.left( 4 ) == "http" ) { -// name = s.right( s.length() - 7 ); -// } else { name = s; -// } append(name); -// qDebug(name); } } } } void Om3u::readPls() { //it's a pls file QTextStream t( &f ); QString s; while ( !t.atEnd() ) { s = t.readLine(); if( s.left(4) == "File" ) { s = s.right( s.length() - s.find("=",0,true)-1 ); s = s.stripWhiteSpace(); s.replace( QRegExp( "%20" )," "); // qDebug( "adding " + s + " to playlist" ); // numberofentries=2 // File1=http // Title // Length // Version // File2=http s = s.replace( QRegExp( "\\" ), "/" ); QFileInfo f( s ); QString name = f.baseName(); if( name.left( 4 ) == "http" ) { name = s.right( s.length() - 7); } else { name = s; } name = name.right( name.length() - name.findRev( "\\", -1, TRUE) - 1 ); if( s.at( s.length() - 4) == '.') // if this is probably a file append(s); else { //if its a url // if( name.right( 1 ).find( '/' ) == -1) { // s += "/"; // } append(s); } } } } void Om3u::write() { //writes list to m3u file QString list; if(count()>0) { for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) { // qDebug(*it); list += *it+"\n"; } f.writeBlock( list, list.length() ); } // f.close(); } void Om3u::add(const QString &filePath) { //adds to m3u file append(filePath); } void Om3u::remove(const QString &filePath) { //removes from m3u list QString list, currentFile; if(count()>0) { for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) { currentFile=*it; // qDebug(*it); if( filePath != currentFile) list += currentFile+"\n"; } f.writeBlock( list, list.length() ); } } void Om3u::deleteFile(const QString &/*filePath*/) {//deletes m3u file f.close(); f.remove(); } void Om3u::close() { //closes m3u file f.close(); } diff --git a/noncore/multimedia/opieplayer2/opie-mediaplayer2-codecs.control b/noncore/multimedia/opieplayer2/opie-mediaplayer2-codecs.control new file mode 100644 index 0000000..0e71fc5 --- a/dev/null +++ b/noncore/multimedia/opieplayer2/opie-mediaplayer2-codecs.control @@ -0,0 +1,10 @@ +Package: opie-mediaplayer2-codecs +Files: root/usr/lib/libao.so* root/usr/lib/libogg* root/usr/lib/libvorbisidec.so* root/usr/lib/libxine.so* root/usr/lib/xine/* +Section: opie/multimedia +Essential: no +Priority: optional +Version: 0.7-$SUB_VERSION.3 +Architecture: arm +Maintainer: Maximilian Reiss <harlekin@handhelds.org> +Depends: libc6 (>= 2.1), opie-mediaplayer2 +Description: Codecs for opieplayer 2 diff --git a/noncore/multimedia/opieplayer2/opie-mediaplayer2-codecs.postinst b/noncore/multimedia/opieplayer2/opie-mediaplayer2-codecs.postinst new file mode 100755 index 0000000..8e60212 --- a/dev/null +++ b/noncore/multimedia/opieplayer2/opie-mediaplayer2-codecs.postinst @@ -0,0 +1,5 @@ +#!/bin/sh + +[ "$1" = "configure" ] || exit 1 + +ldconfig
\ No newline at end of file diff --git a/noncore/multimedia/opieplayer2/opie-mediaplayer2.control b/noncore/multimedia/opieplayer2/opie-mediaplayer2.control index c072308..10c5d19 100644 --- a/noncore/multimedia/opieplayer2/opie-mediaplayer2.control +++ b/noncore/multimedia/opieplayer2/opie-mediaplayer2.control @@ -1,11 +1,11 @@ Package: opie-mediaplayer2 Files: bin/opieplayer2 apps/Applications/mediaplayer.desktop pics/opieplayer2/add_to_playlist.png pics/opieplayer2/cut.png pics/opieplayer2/delete.png pics/opieplayer2/down.png pics/opieplayer2/loop.png pics/opieplayer2/MPEGPlayer.png pics/opieplayer2/musicfile.png pics/opieplayer2/playlist2.png pics/opieplayer2/play.png pics/opieplayer2/remove_from_playlist.png pics/opieplayer2/shuffle.png pics/opieplayer2/up.png pics/opieplayer2/videofile.png Priority: optional Section: opie/applications Maintainer: L.J.Potter <ljp@llornkcor.com>, Maximilian Reiss <harlekin@handhelds.org> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION -Depends: task-opie-minimal, libopie1, zlib1g, opie-mediaplayer2-skin-default | opie-mediaplayer2-skin-default-landscape , libxine1 | opie-mediaplayer-codecs +Depends: task-opie-minimal, libopie1, zlib1g, libstdc++2.10-glibc2.2, opie-mediaplayer2-skin-default | opie-mediaplayer2-skin-default-landscape , libxine1 | opie-mediaplayer2-codecs Description: The Opie media player The mediaplayer for Opie. It plays mp3, mpeg, wav, ogg, quicktime, divx and more. Also it is streaming capable. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/multimedia/opieplayer2/opieplayer2.pro b/noncore/multimedia/opieplayer2/opieplayer2.pro index 57cd18f..5dabbab 100644 --- a/noncore/multimedia/opieplayer2/opieplayer2.pro +++ b/noncore/multimedia/opieplayer2/opieplayer2.pro @@ -1,48 +1,48 @@ TEMPLATE = app CONFIG = qt warn_on release DESTDIR = $(OPIEDIR)/bin HEADERS = playlistselection.h mediaplayerstate.h xinecontrol.h \ videowidget.h audiowidget.h playlistwidget.h om3u.h mediaplayer.h inputDialog.h \ frame.h lib.h xinevideowidget.h volumecontrol.h playlistwidgetgui.h\ alphablend.h yuv2rgb.h threadutil.h mediawidget.h playlistview.h playlistfileview.h \ skin.h SOURCES = main.cpp \ playlistselection.cpp mediaplayerstate.cpp xinecontrol.cpp \ videowidget.cpp audiowidget.cpp playlistwidget.cpp om3u.cpp mediaplayer.cpp inputDialog.cpp \ frame.cpp lib.cpp nullvideo.c xinevideowidget.cpp volumecontrol.cpp \ playlistwidgetgui.cpp\ - alphablend.c yuv2rgb.c yuv2rgb_arm.c yuv2rgb_arm4l.S \ + alphablend.c yuv2rgb.c yuv2rgb_arm2.c yuv2rgb_arm4l.S \ threadutil.cpp mediawidget.cpp playlistview.cpp playlistfileview.cpp \ skin.cpp TARGET = opieplayer2 INCLUDEPATH += $(OPIEDIR)/include DEPENDPATH += $(OPIEDIR)/include LIBS += -lqpe -lpthread -lopie -lxine -lstdc++ MOC_DIR = qpeobj OBJECTS_DIR = qpeobj #INCLUDEPATH += $(OPIEDIR)/include #DEPENDPATH += $(OPIEDIR)/include TRANSLATIONS = ../../../i18n/de/opieplayer2.ts \ ../../../i18n/nl/opieplayer2.ts \ ../../../i18n/da/opieplayer2.ts \ ../../../i18n/xx/opieplayer2.ts \ ../../../i18n/en/opieplayer2.ts \ ../../../i18n/es/opieplayer2.ts \ ../../../i18n/fr/opieplayer2.ts \ ../../../i18n/hu/opieplayer2.ts \ ../../../i18n/ja/opieplayer2.ts \ ../../../i18n/ko/opieplayer2.ts \ ../../../i18n/no/opieplayer2.ts \ ../../../i18n/pl/opieplayer2.ts \ ../../../i18n/pt/opieplayer2.ts \ ../../../i18n/pt_BR/opieplayer2.ts \ ../../../i18n/sl/opieplayer2.ts \ ../../../i18n/zh_CN/opieplayer2.ts \ ../../../i18n/zh_TW/opieplayer2.ts include ( $(OPIEDIR)/include.pro ) diff --git a/noncore/multimedia/opieplayer2/playlistwidget.cpp b/noncore/multimedia/opieplayer2/playlistwidget.cpp index 5f750ba..a1a1016 100644 --- a/noncore/multimedia/opieplayer2/playlistwidget.cpp +++ b/noncore/multimedia/opieplayer2/playlistwidget.cpp @@ -1,1043 +1,1034 @@ /* This file is part of the Opie Project Copyright (c) 2002,2003 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ -#include <qpe/qpetoolbar.h> -#include <qpe/qpeapplication.h> -#include <qpe/storage.h> -#include <qpe/mimetype.h> -#include <qpe/global.h> -#include <qpe/resource.h> -#include <qpe/config.h> +#include <qtoolbar.h> #include <opie/ofiledialog.h> -#include <qdatetime.h> -#include <qdir.h> #include <qmessagebox.h> -#include <qregexp.h> -#include <qtextstream.h> #include "playlistselection.h" #include "playlistwidget.h" #include "mediaplayerstate.h" #include "inputDialog.h" #include "om3u.h" #include "playlistfileview.h" //only needed for the random play -#include <stdlib.h> #include <assert.h> PlayListWidget::PlayListWidget( MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name ) : PlayListWidgetGui( mediaPlayerState, parent, name ) , currentFileListView( 0 ) { d->tbAddToList = new ToolButton( bar, tr( "Add to Playlist" ), "opieplayer2/add_to_playlist", this , SLOT(addSelected() ) ); d->tbRemoveFromList = new ToolButton( bar, tr( "Remove from Playlist" ), "opieplayer2/remove_from_playlist", this , SLOT(removeSelected() ) ); d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer2/play", this , SLOT( btnPlay( bool) ), TRUE ); d->tbShuffle = new ToolButton( bar, tr( "Randomize" ),"opieplayer2/shuffle", &mediaPlayerState, SLOT( setShuffled( bool ) ), TRUE ); d->tbLoop = new ToolButton( bar, tr( "Loop" ), "opieplayer2/loop", &mediaPlayerState, SLOT( setLooping( bool ) ), TRUE ); (void)new MenuItem( pmPlayList, tr( "Clear List" ), this, SLOT( clearList() ) ); (void)new MenuItem( pmPlayList, tr( "Add all audio files" ), this, SLOT( addAllMusicToList() ) ); (void)new MenuItem( pmPlayList, tr( "Add all video files" ), this, SLOT( addAllVideoToList() ) ); (void)new MenuItem( pmPlayList, tr( "Add all files" ), this, SLOT( addAllToList() ) ); pmPlayList->insertSeparator(-1); (void)new MenuItem( pmPlayList, tr( "Add File" ), this,SLOT( openFile() ) ); (void)new MenuItem( pmPlayList, tr("Add URL"), this,SLOT( openURL() ) ); pmPlayList->insertSeparator(-1); (void)new MenuItem( pmPlayList, tr( "Save Playlist" ), this, SLOT(writem3u() ) ); pmPlayList->insertSeparator(-1); (void)new MenuItem( pmPlayList, tr( "Rescan for Audio Files" ), audioView, SLOT( scanFiles() ) ); (void)new MenuItem( pmPlayList, tr( "Rescan for Video Files" ), videoView, SLOT( scanFiles() ) ); pmView->insertItem( Resource::loadPixmap("fullscreen") , tr( "Full Screen"), &mediaPlayerState, SLOT( toggleFullscreen() ) ); Config cfg( "OpiePlayer" ); bool b= cfg.readBoolEntry("FullScreen", 0); mediaPlayerState.setFullscreen( b ); pmView->setItemChecked( -16, b ); (void)new ToolButton( vbox1, tr( "Move Up" ), "opieplayer2/up", d->selectedFiles, SLOT(moveSelectedUp() ) ); (void)new ToolButton( vbox1, tr( "Remove" ), "opieplayer2/cut", d->selectedFiles, SLOT(removeSelected() ) ); (void)new ToolButton( vbox1, tr( "Move Down" ), "opieplayer2/down", d->selectedFiles, SLOT(moveSelectedDown() ) ); QVBox *stretch2 = new QVBox( vbox1 ); connect( tbDeletePlaylist, ( SIGNAL( released() ) ), SLOT( deletePlaylist() ) ); connect( pmView, SIGNAL( activated( int ) ), this, SLOT( pmViewActivated( int ) ) ); connect( skinsMenu, SIGNAL( activated( int ) ) , this, SLOT( skinsMenuActivated( int ) ) ); connect( d->selectedFiles, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int) ), this,SLOT( playlistViewPressed( int, QListViewItem *, const QPoint&, int ) ) ); connect( audioView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int ) ), this,SLOT( viewPressed( int, QListViewItem *, const QPoint&, int ) ) ); connect( audioView, SIGNAL( returnPressed( QListViewItem *) ), this,SLOT( playIt( QListViewItem *) ) ); connect( audioView, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( addToSelection( QListViewItem *) ) ); connect( videoView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int) ), this,SLOT( viewPressed( int, QListViewItem *, const QPoint&, int) ) ); connect( videoView, SIGNAL( returnPressed( QListViewItem *) ), this,SLOT( playIt( QListViewItem *) ) ); connect( videoView, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( addToSelection( QListViewItem *) ) ); connect( playLists, SIGNAL( fileSelected( const DocLnk &) ), this, SLOT( loadList( const DocLnk & ) ) ); connect( tabWidget, SIGNAL ( currentChanged(QWidget*) ), this, SLOT( tabChanged( QWidget* ) ) ); connect( &mediaPlayerState, SIGNAL( playingToggled( bool ) ), d->tbPlay, SLOT( setOn( bool ) ) ); connect( &mediaPlayerState, SIGNAL( loopingToggled( bool ) ), d->tbLoop, SLOT( setOn( bool ) ) ); connect( &mediaPlayerState, SIGNAL( shuffledToggled( bool ) ), d->tbShuffle, SLOT( setOn( bool ) ) ); connect( d->selectedFiles, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( playIt( QListViewItem *) ) ); connect ( gammaSlider, SIGNAL( valueChanged( int ) ), &mediaPlayerState, SLOT( setVideoGamma( int ) ) ); // see which skins are installed populateSkinsMenu(); initializeStates(); channel = new QCopChannel( "QPE/Application/opieplayer2", this ); connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), this, SLOT( qcopReceive(const QCString&, const QByteArray&)) ); cfg.setGroup("PlayList"); QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default"); loadList(DocLnk( currentPlaylist ) ); tabWidget->showPage( playListTab ); } PlayListWidget::~PlayListWidget() { delete d; } void PlayListWidget::initializeStates() { d->tbPlay->setOn( mediaPlayerState.isPlaying() ); d->tbLoop->setOn( mediaPlayerState.isLooping() ); d->tbShuffle->setOn( mediaPlayerState.isShuffled() ); d->playListFrame->show(); } void PlayListWidget::writeDefaultPlaylist() { Config config( "OpiePlayer" ); config.setGroup( "PlayList" ); QString filename=QPEApplication::documentDir() + "/default.m3u"; QString currentString = config.readEntry( "CurrentPlaylist", filename); if( currentString == filename) { Om3u *m3uList; // qDebug("<<<<<<<<<<<<<default>>>>>>>>>>>>>>>>>>>"); if( d->selectedFiles->first() ) { m3uList = new Om3u(filename, IO_ReadWrite | IO_Truncate); do { // qDebug(d->selectedFiles->current()->file()); m3uList->add( d->selectedFiles->current()->file() ); } while ( d->selectedFiles->next() ); m3uList->write(); m3uList->close(); delete m3uList; } } } void PlayListWidget::addToSelection( const DocLnk& lnk ) { d->setDocumentUsed = FALSE; if( QFileInfo( lnk.file() ).exists() || lnk.file().left(4) == "http" ) { d->selectedFiles->addToSelection( lnk ); } // writeCurrentM3u(); } void PlayListWidget::clearList() { while ( first() ) { d->selectedFiles->removeSelected(); } Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); cfg.writeEntry("CurrentPlaylist","default"); setCaption("OpiePlayer"); } void PlayListWidget::viewPressed( int mouse, QListViewItem *, const QPoint& , int) { switch (mouse) { case LeftButton: break; case RightButton: { QPopupMenu m; m.insertItem( tr( "Play Selected" ), this, SLOT( playSelected() )); m.insertItem( tr( "Add to Playlist" ), this, SLOT( addSelected() )); m.exec( QCursor::pos() ); } break; } } void PlayListWidget::playlistViewPressed( int mouse, QListViewItem *, const QPoint& , int ) { switch (mouse) { case LeftButton: break; case RightButton: { QPopupMenu m; m.insertItem( tr( "Play" ), this, SLOT( playSelected() )); m.insertItem( tr( "Remove" ), this, SLOT( removeSelected() )); m.exec( QCursor::pos() ); } break; } } void PlayListWidget::addAllToList() { audioView->populateView(); QListViewItemIterator audioIt( audioView ); DocLnk lnk; QString filename; // iterate through all items of the listview for ( ; audioIt.current(); ++audioIt ) { filename = audioIt.current()->text(3); lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); } videoView->populateView(); QListViewItemIterator videoIt( videoView ); for ( ; videoIt.current(); ++videoIt ) { filename = videoIt.current()->text(3); lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); } tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::addAllMusicToList() { audioView->populateView(); QListViewItemIterator audioIt( audioView ); DocLnk lnk; QString filename; // iterate through all items of the listview for ( ; audioIt.current(); ++audioIt ) { filename = audioIt.current()->text(3); lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); } tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::addAllVideoToList() { videoView->populateView(); QListViewItemIterator videoIt( videoView ); DocLnk lnk; QString filename; for ( ; videoIt.current(); ++videoIt ) { filename = videoIt.current()->text(3); lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); } tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::setDocument( const QString& fileref ) { // qDebug( "<<<<<<<<set document>>>>>>>>>> "+fileref ); fromSetDocument = TRUE; QFileInfo fileInfo(fileref); if ( !fileInfo.exists() ) { QMessageBox::warning( this, tr( "Invalid File" ), tr( "There was a problem in getting the file." ) ); return; } clearList(); QString extension = fileInfo.extension(false); if( extension.find( "m3u", 0, false) != -1 || extension.find( "pls", 0, false) != -1 ) { readListFromFile( fileref ); } else { clearList(); DocLnk lnk; lnk.setName( fileInfo.baseName() ); //sets name lnk.setFile( fileref ); //sets file name addToSelection( lnk ); writeCurrentM3u(); d->setDocumentUsed = TRUE; mediaPlayerState.setPlaying( FALSE ); mediaPlayerState.setPlaying( TRUE ); } } void PlayListWidget::useSelectedDocument() { d->setDocumentUsed = FALSE; } const DocLnk *PlayListWidget::current() const { // this is fugly assert( currentTab() == CurrentPlayList ); const DocLnk *lnk = d->selectedFiles->current(); if ( !lnk ) { d->selectedFiles->first(); lnk = d->selectedFiles->current(); } assert( lnk ); return lnk; } bool PlayListWidget::prev() { if ( mediaPlayerState.isShuffled() ) { const DocLnk *cur = current(); int j = 1 + (int)(97.0 * rand() / (RAND_MAX + 1.0)); for ( int i = 0; i < j; i++ ) { if ( !d->selectedFiles->next() ) d->selectedFiles->first(); } if ( cur == current() ) if ( !d->selectedFiles->next() ) { d->selectedFiles->first(); } return TRUE; } else { if ( !d->selectedFiles->prev() ) { if ( mediaPlayerState.isLooping() ) { return d->selectedFiles->last(); } else { return FALSE; } } return TRUE; } } bool PlayListWidget::next() { //qDebug("<<<<<<<<<<<<next()"); if ( mediaPlayerState.isShuffled() ) { return prev(); } else { if ( !d->selectedFiles->next() ) { if ( mediaPlayerState.isLooping() ) { return d->selectedFiles->first(); } else { return FALSE; } } return TRUE; } } bool PlayListWidget::first() { return d->selectedFiles->first(); } bool PlayListWidget::last() { return d->selectedFiles->last(); } void PlayListWidget::saveList() { writem3u(); } void PlayListWidget::loadList( const DocLnk & lnk) { QString name = lnk.name(); if( name.length()>0) { setCaption("OpiePlayer: "+name); clearList(); readListFromFile(lnk.file()); tabWidget->setCurrentPage(0); } } void PlayListWidget::addSelected() { assert( inFileListMode() ); QListViewItemIterator it( currentFileListView ); for ( ; it.current(); ++it ) if ( it.current()->isSelected() ) { QString filename = it.current()->text(3); DocLnk lnk; lnk.setName( QFileInfo( filename ).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk ); } currentFileListView->clearSelection(); writeCurrentM3u(); } void PlayListWidget::removeSelected() { d->selectedFiles->removeSelected( ); writeCurrentM3u(); } void PlayListWidget::playIt( QListViewItem *it) { if(!it) return; mediaPlayerState.setPlaying(FALSE); mediaPlayerState.setPlaying(TRUE); d->selectedFiles->unSelect(); } void PlayListWidget::addToSelection( QListViewItem *it) { d->setDocumentUsed = FALSE; if(it) { if ( currentTab() == CurrentPlayList ) return; DocLnk lnk; QString filename; filename=it->text(3); lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); writeCurrentM3u(); // tabWidget->setCurrentPage(0); } } void PlayListWidget::tabChanged(QWidget *) { d->tbPlay->setEnabled( true ); disconnect( audioView, SIGNAL( itemsSelected( bool ) ), d->tbPlay, SLOT( setEnabled( bool ) ) ); disconnect( videoView, SIGNAL( itemsSelected( bool ) ), d->tbPlay, SLOT( setEnabled( bool ) ) ); currentFileListView = 0; switch ( currentTab() ) { case CurrentPlayList: { if( !tbDeletePlaylist->isHidden() ) { tbDeletePlaylist->hide(); } d->tbRemoveFromList->setEnabled(TRUE); d->tbAddToList->setEnabled(FALSE); d->tbPlay->setEnabled( !d->selectedFiles->isEmpty() ); } break; case AudioFiles: { audioView->populateView(); if( !tbDeletePlaylist->isHidden() ) { tbDeletePlaylist->hide(); } d->tbRemoveFromList->setEnabled(FALSE); d->tbAddToList->setEnabled(TRUE); connect( audioView, SIGNAL( itemsSelected( bool ) ), d->tbPlay, SLOT( setEnabled( bool ) ) ); d->tbPlay->setEnabled( audioView->hasSelection() ); currentFileListView = audioView; } break; case VideoFiles: { videoView->populateView(); if( !tbDeletePlaylist->isHidden() ) { tbDeletePlaylist->hide(); } d->tbRemoveFromList->setEnabled(FALSE); d->tbAddToList->setEnabled(TRUE); connect( videoView, SIGNAL( itemsSelected( bool ) ), d->tbPlay, SLOT( setEnabled( bool ) ) ); d->tbPlay->setEnabled( videoView->hasSelection() ); currentFileListView = videoView; } break; case PlayLists: { if( tbDeletePlaylist->isHidden() ) { tbDeletePlaylist->show(); } playLists->reread(); d->tbAddToList->setEnabled(FALSE); d->tbPlay->setEnabled( false ); } break; }; } void PlayListWidget::btnPlay(bool b) { // mediaPlayerState->setPlaying(false); mediaPlayerState.setPlaying(b); insanityBool=FALSE; } void PlayListWidget::deletePlaylist() { switch( QMessageBox::information( this, (tr("Remove Playlist?")), (tr("You really want to delete\nthis playlist?")), (tr("Yes")), (tr("No")), 0 )){ case 0: // Yes clicked, QFile().remove(playLists->selectedDocument().file()); QFile().remove(playLists->selectedDocument().linkFile()); playLists->reread(); break; case 1: // Cancel break; }; } void PlayListWidget::playSelected() { btnPlay( TRUE); } bool PlayListWidget::inFileListMode() const { TabType tab = currentTab(); return tab == AudioFiles || tab == VideoFiles; } void PlayListWidget::openURL() { // http://66.28.164.33:2080 // http://somafm.com/star0242.m3u QString filename, name; InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Add URL"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { filename = fileDlg->text(); qDebug( "Selected filename is " + filename ); // Om3u *m3uList; DocLnk lnk; Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); if(filename.left(4) == "http") { QString m3uFile, m3uFilePath; if(filename.find(":",8,TRUE) != -1) { //found a port m3uFile = filename.left( filename.find( ":",8,TRUE)); m3uFile = m3uFile.right( 7); } else if(filename.left(4) == "http"){ m3uFile=filename; m3uFile = m3uFile.right( m3uFile.length() - 7); } else{ m3uFile=filename; } lnk.setName( filename ); //sets name lnk.setFile( filename ); //sets file name // lnk.setIcon("opieplayer2/musicfile"); d->selectedFiles->addToSelection( lnk ); writeCurrentM3u(); d->selectedFiles->setSelectedItem( lnk.name()); } else if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) { readListFromFile( filename ); } else { lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); writeCurrentM3u(); d->selectedFiles->setSelectedItem( lnk.name()); } } delete fileDlg; } void PlayListWidget::openFile() { QString filename, name; Config cfg( "OpiePlayer" ); cfg.setGroup("Dialog"); MimeTypes types; QStringList audio, video, all; audio << "audio/*"; audio << "playlist/plain"; + audio << "application/ogg"; audio << "audio/x-mpegurl"; video << "video/*"; video << "playlist/plain"; all += audio; all += video; types.insert("All Media Files", all ); types.insert("Audio", audio ); types.insert("Video", video ); QString str = OFileDialog::getOpenFileName( 1, cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"", types, 0 ); - if(str.left(2) == "//") str=str.right(str.length()-1); - cfg.writeEntry("LastDirectory" ,QFileInfo(str).dirPath()); + if(str.left(2) == "//") { + str=str.right(str.length()-1); + } + cfg.writeEntry( "LastDirectory" ,QFileInfo( str ).dirPath() ); if( !str.isEmpty() ) { + qDebug( "Selected filename is " + str ); filename = str; DocLnk lnk; - Config cfg( "OpiePlayer" ); - cfg.setGroup("PlayList"); if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) { readListFromFile( filename ); } else { lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); writeCurrentM3u(); d->selectedFiles->setSelectedItem( lnk.name()); } } } void PlayListWidget::readListFromFile( const QString &filename ) { qDebug( "read list filename " + filename ); QFileInfo fi(filename); Om3u *m3uList; QString s, name; m3uList = new Om3u( filename, IO_ReadOnly ); if(fi.extension(false).find("m3u",0,false) != -1 ) m3uList->readM3u(); else if(fi.extension(false).find("pls",0,false) != -1 ) m3uList->readPls(); DocLnk lnk; for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) { s = *it; // qDebug(s); if(s.left(4)=="http") { lnk.setName( s ); //sets file name lnk.setIcon("opieplayer2/musicfile"); lnk.setFile( s ); //sets file name } else { //is file lnk.setName( QFileInfo(s).baseName()); if(s.left(1) != "/") { lnk.setFile( QFileInfo(filename).dirPath()+"/"+s); } else { lnk.setFile( s); } } d->selectedFiles->addToSelection( lnk ); } Config config( "OpiePlayer" ); config.setGroup( "PlayList" ); config.writeEntry("CurrentPlaylist",filename); config.write(); currentPlayList=filename; m3uList->close(); delete m3uList; d->selectedFiles->setSelectedItem( s); setCaption(tr("OpiePlayer: ")+ QFileInfo(filename).baseName()); } // writes current playlist to current m3u file */ void PlayListWidget::writeCurrentM3u() { qDebug("writing to current m3u"); Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); QString currentPlaylist = cfg.readEntry("CurrentPlaylist","default"); Om3u *m3uList; m3uList = new Om3u( currentPlaylist, IO_ReadWrite | IO_Truncate ); if( d->selectedFiles->first()) { do { // qDebug( "add writeCurrentM3u " +d->selectedFiles->current()->file()); m3uList->add( d->selectedFiles->current()->file() ); } while ( d->selectedFiles->next() ); // qDebug( "<<<<<<<<<<<<>>>>>>>>>>>>>>>>>" ); m3uList->write(); m3uList->close(); } delete m3uList; } /* writes current playlist to m3u file */ void PlayListWidget::writem3u() { //InputDilog *fileDlg; //fileDlg = new InputDialog( this, tr( "Save m3u Playlist " ), TRUE, 0); //fileDlg->exec(); Config cfg( "OpiePlayer" ); cfg.setGroup("Dialog"); MimeTypes types; QStringList audio, video, all; audio << "audio/*"; audio << "playlist/plain"; audio << "audio/x-mpegurl"; video << "video/*"; video << "playlist/plain"; all += audio; all += video; types.insert("All Media Files", all ); types.insert("Audio", audio ); types.insert("Video", video ); QString str = OFileDialog::getOpenFileName( 1, cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"", types, 0 ); if(str.left(2) == "//") str=str.right(str.length()-1); cfg.writeEntry("LastDirectory" ,QFileInfo(str).dirPath()); QString name, filename, list; Om3u *m3uList; if( !str.isEmpty() ) { name = str; // name = fileDlg->text(); // qDebug( filename ); if( name.find("/",0,true) != -1) {// assume they specify a file path filename = name; name = name.right(name.length()- name.findRev("/",-1,true) - 1 ); } else //otherwise dump it somewhere noticable filename = QPEApplication::documentDir() + "/" + name; if( filename.right( 3 ) != "m3u" ) //needs filename extension filename += ".m3u"; if( d->selectedFiles->first()) { //ramble through playlist view m3uList = new Om3u( filename, IO_ReadWrite | IO_Truncate); do { m3uList->add( d->selectedFiles->current()->file()); } while ( d->selectedFiles->next() ); // qDebug( list ); m3uList->write(); m3uList->close(); delete m3uList; //delete fileDlg; DocLnk lnk; lnk.setFile( filename); lnk.setIcon("opieplayer2/playlist2"); lnk.setName( name); //sets file name // qDebug(filename); Config config( "OpiePlayer" ); config.setGroup( "PlayList" ); config.writeEntry("CurrentPlaylist",filename); currentPlayList=filename; if(!lnk.writeLink()) { qDebug("Writing doclink did not work"); } setCaption(tr("OpiePlayer: ") + name); } } } void PlayListWidget::keyReleaseEvent( QKeyEvent *e ) { switch ( e->key() ) { ////////////////////////////// Zaurus keys case Key_F9: //activity // if(audioUI->isHidden()) // audioUI->showMaximized(); break; case Key_F10: //contacts // if( videoUI->isHidden()) // videoUI->showMaximized(); break; case Key_F11: //menu break; case Key_F12: //home // doBlank(); break; case Key_F13: //mail // doUnblank(); break; case Key_Q: //add to playlist addSelected(); break; case Key_R: //remove from playlist removeSelected(); break; // case Key_P: //play // qDebug("Play"); // playSelected(); // break; case Key_Space: // playSelected(); puh break; case Key_1: tabWidget->setCurrentPage( 0 ); break; case Key_2: tabWidget->setCurrentPage( 1 ); break; case Key_3: tabWidget->setCurrentPage( 2 ); break; case Key_4: tabWidget->setCurrentPage( 3 ); break; case Key_Down: if ( !d->selectedFiles->next() ) d->selectedFiles->first(); break; case Key_Up: if ( !d->selectedFiles->prev() ) // d->selectedFiles->last(); break; } } void PlayListWidget::pmViewActivated(int index) { // qDebug("%d", index); switch(index) { case -16: { mediaPlayerState.toggleFullscreen(); bool b=mediaPlayerState.isFullscreen(); pmView->setItemChecked( index, b); Config cfg( "OpiePlayer" ); cfg.writeEntry( "FullScreen", b ); } break; }; } void PlayListWidget::populateSkinsMenu() { int item = 0; defaultSkinIndex = 0; QString skinName; Config cfg( "OpiePlayer" ); cfg.setGroup("Options" ); QString skin = cfg.readEntry( "Skin", "default" ); QDir skinsDir( QPEApplication::qpeDir() + "/pics/opieplayer2/skins" ); skinsDir.setFilter( QDir::Dirs ); skinsDir.setSorting(QDir::Name ); const QFileInfoList *skinslist = skinsDir.entryInfoList(); QFileInfoListIterator it( *skinslist ); QFileInfo *fi; while ( ( fi = it.current() ) ) { skinName = fi->fileName(); // qDebug( fi->fileName() ); if( skinName != "." && skinName != ".." && skinName !="CVS" ) { item = skinsMenu->insertItem( fi->fileName() ) ; } if( skinName == "default" ) { defaultSkinIndex = item; } if( skinName == skin ) { skinsMenu->setItemChecked( item, TRUE ); } ++it; } } void PlayListWidget::skinsMenuActivated( int item ) { for(unsigned int i = defaultSkinIndex; i > defaultSkinIndex - skinsMenu->count(); i-- ) { skinsMenu->setItemChecked( i, FALSE ); } skinsMenu->setItemChecked( item, TRUE ); { Config cfg( "OpiePlayer" ); cfg.setGroup("Options"); cfg.writeEntry("Skin", skinsMenu->text( item ) ); } emit skinSelected(); } PlayListWidget::TabType PlayListWidget::currentTab() const { static const TabType indexToTabType[ TabTypeCount ] = { CurrentPlayList, AudioFiles, VideoFiles, PlayLists }; int index = tabWidget->currentPageIndex(); assert( index < TabTypeCount && index >= 0 ); return indexToTabType[ index ]; } PlayListWidget::Entry PlayListWidget::currentEntry() const { if ( currentTab() == CurrentPlayList ) { const DocLnk *lnk = current(); return Entry( lnk->name(), lnk->file() ); } return Entry( currentFileListPathName() ); } QString PlayListWidget::currentFileListPathName() const { return currentFileListView->currentItem()->text( 3 ); } void PlayListWidget::qcopReceive(const QCString &msg, const QByteArray &data) { qDebug("qcop message "+msg ); QDataStream stream ( data, IO_ReadOnly ); if ( msg == "play()" ) { //plays current selection btnPlay( true); } else if ( msg == "stop()" ) { mediaPlayerState.setPlaying( false); } else if ( msg == "togglePause()" ) { mediaPlayerState.togglePaused(); } else if ( msg == "next()" ) { //select next in list mediaPlayerState.setNext(); } else if ( msg == "prev()" ) { //select previous in list mediaPlayerState.setPrev(); } else if ( msg == "toggleLooping()" ) { //loop or not loop mediaPlayerState.toggleLooping(); } else if ( msg == "toggleShuffled()" ) { //shuffled or not shuffled mediaPlayerState.toggleShuffled(); } else if ( msg == "volUp()" ) { //volume more // emit moreClicked(); // emit moreReleased(); } else if ( msg == "volDown()" ) { //volume less // emit lessClicked(); // emit lessReleased(); } else if ( msg == "play(QString)" ) { //play this now QString file; stream >> file; setDocument( (const QString &) file); } else if ( msg == "add(QString)" ) { //add to playlist QString file; stream >> file; QFileInfo fileInfo(file); DocLnk lnk; lnk.setName( fileInfo.baseName() ); //sets name lnk.setFile( file ); //sets file name addToSelection( lnk ); } else if ( msg == "rem(QString)" ) { //remove from playlist QString file; stream >> file; } } diff --git a/noncore/multimedia/opieplayer2/playlistwidget.h b/noncore/multimedia/opieplayer2/playlistwidget.h index 5230b03..fc305cd 100644 --- a/noncore/multimedia/opieplayer2/playlistwidget.h +++ b/noncore/multimedia/opieplayer2/playlistwidget.h @@ -1,143 +1,138 @@ /* This file is part of the Opie Project Copyright (c) 2002,2003 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef PLAY_LIST_WIDGET_H #define PLAY_LIST_WIDGET_H -#include <qmainwindow.h> -#include <qpe/applnk.h> -#include <qtabwidget.h> -#include <qpe/fileselector.h> + #include <qpushbutton.h> #include <qpopupmenu.h> #include <qpe/qcopenvelope_qws.h> #include "playlistwidgetgui.h" - -//class PlayListWidgetPrivate; class Config; class QListViewItem; class QListView; class QPoint; class QAction; class QLabel; class PlayListWidget : public PlayListWidgetGui { Q_OBJECT public: enum TabType { CurrentPlayList, AudioFiles, VideoFiles, PlayLists }; enum { TabTypeCount = 4 }; struct Entry { Entry( const QString &_name, const QString &_fileName ) : name( _name ), file( _fileName ) {} Entry( const QString &_fileName ) : name( _fileName ), file( _fileName ) {} QString name; QString file; }; PlayListWidget( MediaPlayerState &mediaPlayerState, QWidget* parent=0, const char* name=0 ); ~PlayListWidget(); // retrieve the current playlist entry (media file link) const DocLnk *current() const; void useSelectedDocument(); TabType currentTab() const; Entry currentEntry() const; public slots: bool first(); bool last(); bool next(); bool prev(); void writeDefaultPlaylist( ); QString currentFileListPathName() const; protected: QCopChannel * channel; void keyReleaseEvent( QKeyEvent *e); signals: void skinSelected(); private: int defaultSkinIndex; /* void readm3u(const QString &); */ /* void readPls(const QString &); */ void readListFromFile(const QString &); void initializeStates(); bool inFileListMode() const; private slots: void qcopReceive(const QCString&, const QByteArray&); void populateSkinsMenu(); void skinsMenuActivated(int); void pmViewActivated(int); void writem3u(); void writeCurrentM3u(); void openFile(); void openURL(); void setDocument( const QString& fileref ); void addToSelection( const DocLnk& ); // Add a media file to the playlist void addToSelection( QListViewItem* ); // Add a media file to the playlist void clearList(); void addAllToList(); void addAllMusicToList(); void addAllVideoToList(); void saveList(); // Save the playlist void loadList( const DocLnk &); // Load a playlist void playIt( QListViewItem *); void btnPlay(bool); void deletePlaylist(); void addSelected(); void removeSelected(); void tabChanged(QWidget*); void viewPressed( int, QListViewItem *, const QPoint&, int); void playlistViewPressed( int, QListViewItem *, const QPoint&, int); void playSelected(); private: bool fromSetDocument; bool insanityBool; QString setDocFileRef, currentPlayList; int selected; QListView *currentFileListView; }; #endif // PLAY_LIST_WIDGET_H diff --git a/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp b/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp index 5fc0c39..293bf45 100644 --- a/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp +++ b/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp @@ -1,206 +1,194 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ -#include <qpe/qpemenubar.h> -#include <qpe/qpetoolbar.h> -#include <qpe/fileselector.h> + +#include <qtoolbar.h> #include <qpe/qpeapplication.h> -#include <qpe/storage.h> -#include <qpe/mimetype.h> -#include <qpe/config.h> -#include <qpe/global.h> -#include <qpe/resource.h> - -#include <qpopupmenu.h> -#include <qaction.h> -#include <qcursor.h> -#include <qdir.h> + #include <qlayout.h> +#include <qmenubar.h> #include "playlistselection.h" #include "playlistwidget.h" #include "mediaplayerstate.h" #include "inputDialog.h" #include "playlistfileview.h" -//only needed for the random play -#include <stdlib.h> - #include "mediaplayerstate.h" PlayListWidgetGui::PlayListWidgetGui( MediaPlayerState &_mediaPlayerState, QWidget* parent, const char* name ) : QMainWindow( parent, name ), mediaPlayerState( _mediaPlayerState ) { d = new PlayListWidgetPrivate; d->setDocumentUsed = FALSE; setBackgroundMode( PaletteButton ); setToolBarsMovable( FALSE ); // Create Toolbar - QPEToolBar *toolbar = new QPEToolBar( this ); + QToolBar *toolbar = new QToolBar( this ); toolbar->setHorizontalStretchable( TRUE ); // Create Menubar - QPEMenuBar *menu = new QPEMenuBar( toolbar ); + QMenuBar *menu = new QMenuBar( toolbar ); menu->setMargin( 0 ); - bar = new QPEToolBar( this ); + bar = new QToolBar( this ); bar->setLabel( tr( "Play Operations" ) ); tbDeletePlaylist = new QPushButton( Resource::loadIconSet( "trash" ), "", bar, "close" ); tbDeletePlaylist->setFlat( TRUE ); tbDeletePlaylist->setFixedSize( 20, 20 ); tbDeletePlaylist->hide(); pmPlayList = new QPopupMenu( this ); menu->insertItem( tr( "File" ), pmPlayList ); pmView = new QPopupMenu( this ); menu->insertItem( tr( "View" ), pmView ); pmView->isCheckable(); skinsMenu = new QPopupMenu( this ); pmView->insertItem( tr( "Skins" ), skinsMenu ); skinsMenu->isCheckable(); gammaMenu = new QPopupMenu( this ); pmView->insertItem( tr( "Gamma (Video)" ), gammaMenu ); gammaSlider = new QSlider( QSlider::Vertical, gammaMenu ); gammaSlider->setRange( -40, 40 ); gammaSlider->setTickmarks( QSlider::Left ); gammaSlider->setTickInterval( 20 ); gammaSlider->setFocusPolicy( QWidget::StrongFocus ); gammaSlider->setValue( 0 ); gammaSlider->setMinimumHeight( 50 ); gammaLCD = new QLCDNumber( 3, gammaMenu ); gammaLCD-> setFrameShape ( QFrame::NoFrame ); gammaLCD-> setSegmentStyle ( QLCDNumber::Flat ); gammaMenu->insertItem( gammaSlider ); gammaMenu->insertItem( gammaLCD ); connect( gammaSlider, SIGNAL( valueChanged( int ) ), gammaLCD, SLOT( display( int ) ) ); vbox5 = new QVBox( this ); QVBox *vbox4 = new QVBox( vbox5 ); QHBox *hbox6 = new QHBox( vbox4 ); tabWidget = new QTabWidget( hbox6, "tabWidget" ); playListTab = new QWidget( tabWidget, "PlayListTab" ); tabWidget->insertTab( playListTab, "Playlist"); QGridLayout *Playout = new QGridLayout( playListTab ); Playout->setSpacing( 2); Playout->setMargin( 2); // Add the playlist area QVBox *vbox3 = new QVBox( playListTab ); d->playListFrame = vbox3; QHBox *hbox2 = new QHBox( vbox3 ); d->selectedFiles = new PlayListSelection( hbox2 ); vbox1 = new QVBox( hbox2 ); QPEApplication::setStylusOperation( d->selectedFiles->viewport(), QPEApplication::RightOnHold ); QVBox *stretch1 = new QVBox( vbox1 ); // add stretch Playout->addMultiCellWidget( vbox3, 0, 0, 0, 1 ); QWidget *aTab; aTab = new QWidget( tabWidget, "aTab" ); QGridLayout *Alayout = new QGridLayout( aTab ); Alayout->setSpacing( 2 ); Alayout->setMargin( 2 ); // no m3u's here please - audioView = new PlayListFileView( "audio/mpeg;audio/x-wav;audio/x-ogg", "opieplayer2/musicfile", aTab, "Audioview" ); + audioView = new PlayListFileView( "audio/mpeg;audio/x-wav;application/ogg", "opieplayer2/musicfile", aTab, "Audioview" ); Alayout->addMultiCellWidget( audioView, 0, 0, 0, 1 ); tabWidget->insertTab( aTab, tr( "Audio" ) ); QPEApplication::setStylusOperation( audioView->viewport(), QPEApplication::RightOnHold ); QWidget *vTab; vTab = new QWidget( tabWidget, "vTab" ); QGridLayout *Vlayout = new QGridLayout( vTab ); Vlayout->setSpacing( 2 ); Vlayout->setMargin( 2 ); videoView = new PlayListFileView( "video/*", "opieplayer2/videofile", vTab, "Videoview" ); Vlayout->addMultiCellWidget( videoView, 0, 0, 0, 1 ); QPEApplication::setStylusOperation( videoView->viewport(), QPEApplication::RightOnHold ); tabWidget->insertTab( vTab, tr( "Video" ) ); //playlists list QWidget *LTab; LTab = new QWidget( tabWidget, "LTab" ); QGridLayout *Llayout = new QGridLayout( LTab ); Llayout->setSpacing( 2 ); Llayout->setMargin( 2 ); playLists = new FileSelector( "playlist/plain;audio/x-mpegurl", LTab, "fileselector" , FALSE, FALSE ); Llayout->addMultiCellWidget( playLists, 0, 0, 0, 1 ); tabWidget->insertTab( LTab, tr( "Lists" ) ); setCentralWidget( vbox5 ); } PlayListWidgetGui::~PlayListWidgetGui() { } void PlayListWidgetGui::setView( char view ) { if ( view == 'l' ) showMaximized(); else hide(); } void PlayListWidgetGui::setActiveWindow() { // qDebug("SETTING active window"); // When we get raised we need to ensure that it switches views MediaPlayerState::DisplayType origDisplayType = mediaPlayerState.displayType(); mediaPlayerState.setDisplayType( MediaPlayerState::MediaSelection ); // invalidate mediaPlayerState.setDisplayType( origDisplayType ); // now switch back } diff --git a/noncore/multimedia/opieplayer2/playlistwidgetgui.h b/noncore/multimedia/opieplayer2/playlistwidgetgui.h index c965b0d..c0cd37a 100644 --- a/noncore/multimedia/opieplayer2/playlistwidgetgui.h +++ b/noncore/multimedia/opieplayer2/playlistwidgetgui.h @@ -1,133 +1,129 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef PLAY_LIST_WIDGET_GUI_H #define PLAY_LIST_WIDGET_GUI_H #include <qmainwindow.h> -#include <qpe/applnk.h> #include <qpe/resource.h> -#include <qpe/qpemenubar.h> #include <qtabwidget.h> #include <qpe/fileselector.h> -#include <qpushbutton.h> -#include <qpopupmenu.h> #include <qaction.h> +#include <qtoolbutton.h> #include <qslider.h> #include <qlcdnumber.h> class PlayListWidgetPrivate; class PlayListSelection; class MediaPlayerState; class PlayListFileView; class Config; -class QPEToolBar; +class QToolBar; class QListViewItem; class QListView; class QPoint; class QAction; class QLabel; class PlayListWidgetPrivate { public: QToolButton *tbPlay, *tbFull, *tbLoop, *tbShuffle, *tbAddToList, *tbRemoveFromList, *tbMoveUp, *tbMoveDown, *tbRemove; QFrame *playListFrame; PlayListSelection *selectedFiles; bool setDocumentUsed; }; class ToolButton : public QToolButton { Q_OBJECT public: ToolButton( QWidget *parent, const char *name, const QString& icon, QObject *handler, const QString& slot, bool t = FALSE ) : QToolButton( parent, name ) { setTextLabel( name ); setPixmap( Resource::loadPixmap( icon ) ); setAutoRaise( TRUE ); setFocusPolicy( QWidget::NoFocus ); setToggleButton( t ); connect( this, t ? SIGNAL( toggled(bool) ) : SIGNAL( clicked() ), handler, slot ); - QPEMenuToolFocusManager::manager()->addWidget( this ); } }; class MenuItem : public QAction { public: MenuItem( QWidget *parent, const QString& text, QObject *handler, const QString& slot ) : QAction( text, QString::null, 0, 0 ) { connect( this, SIGNAL( activated() ), handler, slot ); addTo( parent ); } }; class PlayListWidgetGui : public QMainWindow { Q_OBJECT public: PlayListWidgetGui( MediaPlayerState &_mediaPlayerState, QWidget* parent=0, const char* name=0 ); ~PlayListWidgetGui(); protected: QTabWidget * tabWidget; PlayListFileView *audioView, *videoView; QListView *playlistView; QLabel *libString; QPopupMenu *pmView ; QPopupMenu *gammaMenu; QSlider *gammaSlider; QLCDNumber *gammaLCD; bool fromSetDocument; bool insanityBool; QString setDocFileRef; // retrieve the current playlist entry (media file link) QPushButton *tbDeletePlaylist; int selected; QPopupMenu *pmPlayList; FileSelector* playLists; QPopupMenu *skinsMenu; PlayListWidgetPrivate *d; // Private implementation data QVBox *vbox1; QVBox *vbox5; - QPEToolBar *bar; + QToolBar *bar; QWidget *playListTab; void setActiveWindow(); // need to handle this to show the right view void setView( char ); MediaPlayerState &mediaPlayerState; }; #endif diff --git a/noncore/multimedia/opieplayer2/videowidget.cpp b/noncore/multimedia/opieplayer2/videowidget.cpp index 755cd22..c829e03 100644 --- a/noncore/multimedia/opieplayer2/videowidget.cpp +++ b/noncore/multimedia/opieplayer2/videowidget.cpp @@ -1,313 +1,303 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ -#include <qpe/qpeapplication.h> -#include <qpe/resource.h> -#include <qpe/config.h> - - -#include <qwidget.h> -#include <qpainter.h> -#include <qpixmap.h> -#include <qslider.h> -#include <qdrawutil.h> #include "videowidget.h" #include "mediaplayerstate.h" #include "playlistwidget.h" #ifdef Q_WS_QWS # define USE_DIRECT_PAINTER # include <qdirectpainter_qws.h> # include <qgfxraster_qws.h> #endif namespace { const int xo = 2; // movable x offset const int yo = 0; // movable y offset const MediaWidget::SkinButtonInfo skinInfo[] = { { MediaWidget::Play, "play", MediaWidget::ToggleButton }, { MediaWidget::Stop, "stop", MediaWidget::NormalButton }, { MediaWidget::Next, "fwd", MediaWidget::NormalButton }, { MediaWidget::Previous, "back", MediaWidget::NormalButton }, { MediaWidget::VolumeUp, "up", MediaWidget::NormalButton }, { MediaWidget::VolumeDown, "down", MediaWidget::NormalButton }, { MediaWidget::FullScreen, "full", MediaWidget::ToggleButton } }; const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] ); } VideoWidget::VideoWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name ) : MediaWidget( playList, mediaPlayerState, parent, name ), scaledWidth( 0 ), scaledHeight( 0 ), videoSliderBeingMoved( false ) { setCaption( tr("OpiePlayer - Video") ); videoFrame = new XineVideoWidget ( this, "Video frame" ); connect ( videoFrame, SIGNAL( videoResized ( const QSize & )), this, SIGNAL( videoResized ( const QSize & ))); connect ( videoFrame, SIGNAL( clicked () ), this, SLOT ( backToNormal() ) ); slider = 0; loadSkin(); setLength( mediaPlayerState.length() ); setPosition( mediaPlayerState.position() ); setFullscreen( mediaPlayerState.isFullscreen() ); setPlaying( mediaPlayerState.isPlaying() ); } VideoWidget::~VideoWidget() { } MediaWidget::GUIInfo VideoWidget::guiInfo() { return GUIInfo( "V" /* infix */, ::skinInfo, ::buttonCount ); } void VideoWidget::resizeEvent( QResizeEvent *e ) { int h = height(); int w = width(); //int Vh = 160; //int Vw = 220; slider->setFixedWidth( w - 20 ); slider->setGeometry( QRect( 15, h - 22, w - 90, 20 ) ); slider->setBackgroundOrigin( QWidget::ParentOrigin ); slider->setFocusPolicy( QWidget::NoFocus ); slider->setBackgroundPixmap( backgroundPixmap ); upperLeftOfButtonMask.rx() = 0;// ( imgUp->width() ) / 2; if(w>h) upperLeftOfButtonMask.ry() = 0; else upperLeftOfButtonMask.ry() = 185;//(( Vh - imgUp->height() ) / 2) - 10; MediaWidget::resizeEvent( e ); } void VideoWidget::sliderPressed() { videoSliderBeingMoved = TRUE; } void VideoWidget::sliderReleased() { videoSliderBeingMoved = FALSE; if ( slider->width() == 0 ) { return; } long val = long((double)slider->value() * mediaPlayerState.length() / slider->width()); mediaPlayerState.setPosition( val ); } void VideoWidget::setPosition( long i ) { updateSlider( i, mediaPlayerState.length() ); } void VideoWidget::setLength( long max ) { updateSlider( mediaPlayerState.position(), max ); } void VideoWidget::setDisplayType( MediaPlayerState::DisplayType displayType ) { if ( displayType == MediaPlayerState::Video ) { makeVisible(); return; } // Effectively blank the view next time we show it so it looks nicer scaledWidth = 0; scaledHeight = 0; hide(); } void VideoWidget::loadSkin() { loadDefaultSkin( guiInfo() ); delete slider; slider = new QSlider( Qt::Horizontal, this ); slider->setMinValue( 0 ); slider->setMaxValue( 1 ); slider->setBackgroundPixmap( backgroundPixmap ); //slider->setFocusPolicy( QWidget::NoFocus ); resizeEvent( 0 ); } void VideoWidget::updateSlider( long i, long max ) { // Will flicker too much if we don't do this if ( max == 0 ) { return; } int width = slider->width(); int val = int((double)i * width / max); if ( !mediaPlayerState.isFullscreen() && !videoSliderBeingMoved ) { if ( slider->value() != val ) { slider->setValue( val ); } if ( slider->maxValue() != width ) { slider->setMaxValue( width ); } } } void VideoWidget::mouseReleaseEvent( QMouseEvent *event ) { if ( mediaPlayerState.isFullscreen() ) { mediaPlayerState.setFullscreen( FALSE ); makeVisible(); } MediaWidget::mouseReleaseEvent( event ); } void VideoWidget::backToNormal() { mediaPlayerState.setFullscreen( FALSE ); makeVisible(); setToggleButton( FullScreen, false ); } void VideoWidget::makeVisible() { if ( mediaPlayerState.isFullscreen() ) { showFullScreen(); resize( qApp->desktop()->size() ); videoFrame-> setGeometry ( 0, 0, width ( ), height ( )); slider->hide(); disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); disconnect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); disconnect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); } else { showNormal(); showMaximized(); QWidget *d = QApplication::desktop(); int w = d->width(); int h = d->height(); if(w>h) { int newW=(w/2)-(246/2); //this will only work with 320x240 videoFrame->setGeometry( QRect( newW, 4, 240, 170 ) ); } else { videoFrame->setGeometry( QRect( 0, 30, 240, 170 ) ); } if ( !mediaPlayerState.isSeekable() ) { if( !slider->isHidden()) { slider->hide(); } disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); disconnect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); disconnect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); } else { slider->show(); connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); connect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); connect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); } } } void VideoWidget::keyReleaseEvent( QKeyEvent *e) { switch ( e->key() ) { ////////////////////////////// Zaurus keys case Key_Home: break; case Key_F9: //activity break; case Key_F10: //contacts // hide(); break; case Key_F11: //menu break; case Key_F12: //home break; case Key_F13: //mail break; case Key_Space: { if(mediaPlayerState.isPlaying()) { mediaPlayerState.setPlaying(FALSE); } else { mediaPlayerState.setPlaying(TRUE); } } break; case Key_Down: // toggleButton(6); emit lessClicked(); emit lessReleased(); // toggleButton(6); break; case Key_Up: // toggleButton(5); emit moreClicked(); emit moreReleased(); // toggleButton(5); break; case Key_Right: mediaPlayerState.setNext(); break; case Key_Left: mediaPlayerState.setPrev(); break; case Key_Escape: break; }; } XineVideoWidget* VideoWidget::vidWidget() { return videoFrame; } void VideoWidget::setFullscreen ( bool b ) { setToggleButton( FullScreen, b ); } void VideoWidget::setPlaying( bool b) { setToggleButton( Play, b ); } diff --git a/noncore/multimedia/opieplayer2/videowidget.h b/noncore/multimedia/opieplayer2/videowidget.h index 84bc964..8c6896b 100644 --- a/noncore/multimedia/opieplayer2/videowidget.h +++ b/noncore/multimedia/opieplayer2/videowidget.h @@ -1,99 +1,95 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef VIDEO_WIDGET_H #define VIDEO_WIDGET_H -#include <qwidget.h> -#include <qimage.h> -#include <qpixmap.h> #include "xinevideowidget.h" - #include "mediawidget.h" class QPixmap; class QSlider; class VideoWidget : public MediaWidget { Q_OBJECT public: VideoWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent=0, const char* name=0 ); ~VideoWidget(); static MediaWidget::GUIInfo guiInfo(); XineVideoWidget* vidWidget(); public slots: void updateSlider( long, long ); void sliderPressed( ); void sliderReleased( ); void setFullscreen( bool b ); virtual void makeVisible(); void backToNormal(); void setPosition( long ); public: virtual void setPlaying( bool b); virtual void setLength( long ); virtual void setDisplayType( MediaPlayerState::DisplayType displayType ); virtual void loadSkin(); signals: void moreClicked(); void lessClicked(); void sliderMoved( long ); void videoResized ( const QSize &s ); protected: void resizeEvent( QResizeEvent * ); void mouseReleaseEvent( QMouseEvent *event ); void keyReleaseEvent( QKeyEvent *e); private: // Ticker songInfo; QSlider *slider; QImage *currentFrame; int scaledWidth; int scaledHeight; XineVideoWidget* videoFrame; bool videoSliderBeingMoved; }; #endif // VIDEO_WIDGET_H diff --git a/noncore/multimedia/opieplayer2/xinecontrol.cpp b/noncore/multimedia/opieplayer2/xinecontrol.cpp index 1c489e3..a392f4a 100644 --- a/noncore/multimedia/opieplayer2/xinecontrol.cpp +++ b/noncore/multimedia/opieplayer2/xinecontrol.cpp @@ -1,272 +1,272 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qtimer.h> #include <qmessagebox.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/qpeapplication.h> + #include "xinecontrol.h" #include "mediaplayerstate.h" #include "xinevideowidget.h" XineControl::XineControl( XineVideoWidget *xineWidget, MediaPlayerState &_mediaPlayerState, QObject *parent, const char *name ) : QObject( parent, name ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget ) { libXine = new XINE::Lib( XINE::Lib::InitializeImmediately, xineWidget ); init(); } XineControl::XineControl( XINE::Lib *xine, XineVideoWidget *xineWidget, MediaPlayerState &_mediaPlayerState, QObject *parent, const char *name ) : QObject( parent, name ), libXine( xine ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget ) { xine->ensureInitialized(); xine->setWidget( xineWidget ); init(); } void XineControl::init() { connect( &mediaPlayerState, SIGNAL( pausedToggled( bool ) ), this, SLOT( pause( bool ) ) ); connect( this, SIGNAL( positionChanged( long ) ), &mediaPlayerState, SLOT( updatePosition( long ) ) ); connect( &mediaPlayerState, SIGNAL( playingToggled( bool ) ), this, SLOT( stop( bool ) ) ); connect( &mediaPlayerState, SIGNAL( fullscreenToggled( bool ) ), this, SLOT( setFullscreen( bool ) ) ); connect( &mediaPlayerState, SIGNAL( positionChanged( long ) ), this, SLOT( seekTo( long ) ) ); connect( &mediaPlayerState, SIGNAL( videoGammaChanged( int ) ), this, SLOT( setGamma( int ) ) ); connect( libXine, SIGNAL( stopped() ), this, SLOT( nextMedia() ) ); connect( xineVideoWidget, SIGNAL( videoResized( const QSize & ) ), this, SLOT( videoResized ( const QSize & ) ) ); disabledSuspendScreenSaver = FALSE; } XineControl::~XineControl() { #if defined(Q_WS_QWS) && !defined(QT_NO_COP) if ( disabledSuspendScreenSaver ) { disabledSuspendScreenSaver = FALSE; // Re-enable the suspend mode QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; } #endif delete libXine; } void XineControl::play( const QString& fileName ) { + hasVideoChannel = FALSE; hasAudioChannel = FALSE; m_fileName = fileName; qDebug("<<FILENAME: " + fileName + ">>>>"); if ( !libXine->play( fileName, 0, 0 ) ) { QMessageBox::warning( 0l , tr( "Failure" ), getErrorCode() ); // toggle stop so the the play button is reset mediaPlayerState.setPlaying( false ); return; } mediaPlayerState.setPlaying( true ); MediaPlayerState::DisplayType displayType; - // qDebug( QString( "libXine->hasVideo() return : %1 ").arg( libXine->hasVideo() ) ); if ( !libXine->hasVideo() ) { displayType = MediaPlayerState::Audio; qDebug("HAS AUDIO"); libXine->setShowVideo( false ); hasAudioChannel = TRUE; } else { displayType = MediaPlayerState::Video; qDebug("HAS VIDEO"); libXine->setShowVideo( true ); hasVideoChannel = TRUE; } // determine if slider is shown mediaPlayerState.setIsSeekable( libXine->isSeekable() ); // which gui (video / audio) mediaPlayerState.setDisplayType( displayType ); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) if ( !disabledSuspendScreenSaver ) { disabledSuspendScreenSaver = TRUE; // Stop the screen from blanking and power saving state QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << ( displayType == MediaPlayerState::Video ? QPEApplication::Disable : QPEApplication::DisableSuspend ); } #endif length(); position(); } void XineControl::nextMedia() { mediaPlayerState.setNext(); } void XineControl::setGamma( int value ) { libXine->setGamma( value ); } void XineControl::stop( bool isSet ) { if ( !isSet ) { libXine->stop(); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) if ( disabledSuspendScreenSaver ) { disabledSuspendScreenSaver = FALSE; // Re-enable the suspend mode QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; } #endif } } /** * Pause playback * @isSet */ void XineControl::pause( bool isSet) { libXine->pause( isSet ); } /** * get current time in playback */ long XineControl::currentTime() { // todo: jede sekunde überprüfen m_currentTime = libXine->currentTime(); return m_currentTime; QTimer::singleShot( 1000, this, SLOT( currentTime() ) ); } /** * Set the length of the media file */ void XineControl::length() { m_length = libXine->length(); mediaPlayerState.setLength( m_length ); } /** * Reports the position the xine backend is at right now * @return long the postion in seconds */ long XineControl::position() { m_position = ( currentTime() ); mediaPlayerState.updatePosition( m_position ); long emitPos = (long)m_position; emit positionChanged( emitPos ); if( mediaPlayerState.isPlaying() ) { // needs to be stopped the media is stopped QTimer::singleShot( 1000, this, SLOT( position() ) ); } - // qDebug("POSITION : %d", m_position); return m_position; } /** * Set videoplayback to fullscreen * @param isSet */ void XineControl::setFullscreen( bool isSet ) { libXine->showVideoFullScreen( isSet ); } QString XineControl::getMetaInfo() { QString returnString; if ( !libXine->metaInfo( 0 ).isEmpty() ) { returnString += tr( " Title: " + libXine->metaInfo( 0 ) ); } if ( !libXine->metaInfo( 1 ).isEmpty() ) { returnString += tr( " Comment: " + libXine->metaInfo( 1 ) ); } if ( !libXine->metaInfo( 2 ).isEmpty() ) { returnString += tr( " Artist: " + libXine->metaInfo( 2 ) ); } if ( !libXine->metaInfo( 3 ).isEmpty() ) { returnString += tr( " Genre: " + libXine->metaInfo( 3 ) ); } if ( !libXine->metaInfo( 4 ).isEmpty() ) { returnString += tr( " Album: " + libXine->metaInfo( 4 ) ); } if ( !libXine->metaInfo( 5 ).isEmpty() ) { returnString += tr( " Year: " + libXine->metaInfo( 5 ) ); } return returnString; } QString XineControl::getErrorCode() { int errorCode = libXine->error(); qDebug( QString("ERRORCODE: %1 ").arg(errorCode) ); if ( errorCode == 1 ) { return tr( "No input plugin found for this media type" ); } else if ( errorCode == 2 ) { return tr( "No demux plugin found for this media type" ); } else if ( errorCode == 3 ) { return tr( "Demuxing failed for this media type" ); } else if ( errorCode == 4 ) { return tr( "Malformed MRL" ); } else { return tr( "Some other error" ); } } /** * Seek to a position in the track * @param second the second to jump to */ void XineControl::seekTo( long second ) { libXine->seekTo( (int)second ); } void XineControl::videoResized ( const QSize &s ) { libXine->resize( s ); } diff --git a/noncore/multimedia/opieplayer2/xinecontrol.h b/noncore/multimedia/opieplayer2/xinecontrol.h index 0e985d6..3f44f2e 100644 --- a/noncore/multimedia/opieplayer2/xinecontrol.h +++ b/noncore/multimedia/opieplayer2/xinecontrol.h @@ -1,127 +1,126 @@ /* This file is part of the Opie Project Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> Copyright (c) 2002 L. Potter <ljp@llornkcor.com> Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef XINECONTROL_H #define XINECONTROL_H #include "lib.h" -#include <qobject.h> #include "mediaplayerstate.h" class XineControl : public QObject { Q_OBJECT public: XineControl( XineVideoWidget *xineWidget, MediaPlayerState &_mediaPlayerState, QObject *parent = 0, const char *name =0 ); // note that this constructor takes over ownership of the passed // XINE::Lib object. XineControl( XINE::Lib *xine, XineVideoWidget *xineWidget, MediaPlayerState &_mediaPlayerState, QObject *parent = 0, const char *name =0 ); ~XineControl(); bool hasVideo() const { return hasVideoChannel; } bool hasAudio() const { return hasAudioChannel; } public slots: void play( const QString& fileName ); void stop( bool ); /** * Pause the media stream * @param if pause or not */ void pause( bool ); /** * Set videos fullscreen * @param yes or no */ void setFullscreen( bool ); /** * */ long currentTime(); void seekTo( long ); // get length of media file and set it void length(); long position(); /** * Proceed to the next media file in playlist */ void nextMedia(); /** * Get as much info about the stream from xine as possible */ QString getMetaInfo(); /** * get the error code and "translate" it for the user * */ QString getErrorCode(); void videoResized ( const QSize &s ); /** * Set the gamma value of the video output * @param int value between -100 and 100, 0 is original */ void setGamma( int ); private: void init(); XINE::Lib *libXine; long m_currentTime; long m_position; int m_length; QString m_fileName; bool disabledSuspendScreenSaver : 1; bool hasVideoChannel : 1; bool hasAudioChannel : 1; MediaPlayerState &mediaPlayerState; XineVideoWidget *xineVideoWidget; signals: void positionChanged( long ); }; #endif diff --git a/noncore/multimedia/opieplayer2/yuv2rgb_arm2.c b/noncore/multimedia/opieplayer2/yuv2rgb_arm2.c new file mode 100644 index 0000000..cbd32e8 --- a/dev/null +++ b/noncore/multimedia/opieplayer2/yuv2rgb_arm2.c @@ -0,0 +1,875 @@ +/* + * yuv2rgb_arm2.c + * Copyright (C) 2002 Frederic 'dilb' Boulay. + * All Rights Reserved. + * + * Author: Frederic Boulay <dilb@handhelds.org> + * + * you can redistribute this file and/or modify + * it under the terms of the GNU General Public License (version 2) + * as published by the Free Software Foundation. + * + * This file is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * + * The function defined in this file, are derived from work done in the xine + * project. + * In order to improve performance, by strongly reducing memory bandwidth + * needed, the scaling functions are merged with the yuv2rgb function. + */ + +#ifdef __arm__ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <inttypes.h> + +#include "yuv2rgb.h" +#include <xine/xineutils.h> + +/* Prototypes of the "local" functions available here: */ +/* first prototype, function called when no scaling is needed: */ +static void arm_rgb16_noscale(yuv2rgb_t*, uint8_t*, uint8_t*, uint8_t*, uint8_t*); +/* second prototype, function called when no horizontal scaling is needed: */ +static void arm_rgb16_step_dx_32768(yuv2rgb_t*, uint8_t*, uint8_t*, uint8_t*, uint8_t*); +/* third prototype, function called when scaling is needed for zooming in: */ +static void arm_rgb16_step_dx_inf_32768(yuv2rgb_t*, uint8_t*, uint8_t*, uint8_t*, uint8_t*); +/* fourth prototype, function called when scaling is needed for zooming out (between 1x and 2x): */ +static void arm_rgb16_step_dx_bet_32768_65536(yuv2rgb_t*, uint8_t*, uint8_t*, uint8_t*, uint8_t*); +/* fifth prototype, function called when scaling is needed for zooming out (greater than 2x): */ +static void arm_rgb16_step_dx_sup_65536(yuv2rgb_t*, uint8_t*, uint8_t*, uint8_t*, uint8_t*); +/* sixth prototype, function where the decision of the scaling function to use is made.*/ +static void arm_rgb16_2 (yuv2rgb_t*, uint8_t*, uint8_t*, uint8_t*, uint8_t*); + + + + +/* extern function: */ + +/* Function: */ +void yuv2rgb_init_arm (yuv2rgb_factory_t *this) +/* This function initialise the member yuv2rgb_fun, if everything is right +the function optimised for the arm target should be used.*/ + { + if (this->swapped) + return; /*no swapped pixel output upto now*/ + + switch (this->mode) + { + case MODE_16_RGB: + this->yuv2rgb_fun = arm_rgb16_2; + break; + default: + } + } + + + +/* local functions: */ + +/* Function: */ +static void arm_rgb16_2 (yuv2rgb_t *this, uint8_t * _dst, uint8_t * _py, uint8_t * _pu, uint8_t * _pv) +/* This function takes care of applying the right scaling conversion +(yuv2rgb is included in each scaling function!)*/ + { + if (!this->do_scale) + { + arm_rgb16_noscale(this, _dst, _py, _pu, _pv); + return; + } + if (this->step_dx<32768) + { + arm_rgb16_step_dx_inf_32768(this, _dst, _py, _pu, _pv); + return; + } + if (this->step_dx==32768) + { + arm_rgb16_step_dx_32768(this, _dst, _py, _pu, _pv); + return; + } + if (this->step_dx<65536) + { + arm_rgb16_step_dx_bet_32768_65536(this, _dst, _py, _pu, _pv); + return; + } + arm_rgb16_step_dx_sup_65536(this, _dst, _py, _pu, _pv); + return; + } + + +/* Function: */ +static void arm_rgb16_noscale(yuv2rgb_t *this, uint8_t * _dst, uint8_t * _py, uint8_t * _pu, uint8_t * _pv) +/* This function is called when the source and the destination pictures have the same size. + In this case, scaling part is not needed. + (This code is probably far from being optimised, in particular, the asm + generated is not the most efficient, a pure asm version will probably + emerge sooner or later). But at least, this version is faster than what + was used before.*/ + { + int height; + + height=this->dest_height; + + while (height>0) + { + uint16_t *r, *g, *b; + uint8_t *py, *py2, *pu, *pv; + uint16_t *dst, *dst2; + int width; + register uint8_t p1y, p1u, p1v; + + height-=2; + width=this->dest_width; + dst = _dst; + dst2 = _dst + this->rgb_stride; + py = _py; + py2 = _py + this->y_stride; + pu = _pu; + pv = _pv; + + while (width>0) + { + width-=2; + p1y=*py++; + p1u=*pu++; + p1v=*pv++; + + r = this->table_rV[p1v]; + g = (void *) (((uint8_t *)this->table_gU[p1u]) + this->table_gV[p1v]); + b = this->table_bU[p1u]; + + *dst++ = r[p1y] + g[p1y] + b[p1y]; + p1y=*py++; + *dst++ = r[p1y] + g[p1y] + b[p1y]; + + p1y=*py2++; + + *dst2++ = r[p1y] + g[p1y] + b[p1y]; + p1y=*py2++; + *dst2++ = r[p1y] + g[p1y] + b[p1y]; + } + _dst += (this->rgb_stride)<<1; + _py += (this->y_stride)<<1; + _pu += this->uv_stride; + _pv += this->uv_stride; + } + } + + +/* Function: */ +static void arm_rgb16_step_dx_inf_32768(yuv2rgb_t *this, uint8_t * _dst, uint8_t * _py, uint8_t * _pu, uint8_t * _pv) +/* This function is called when the destination picture is bigger than the size + of the source picture. +*/ + { + int recal_uv, height; /* Note about recal_uv: bit0 is for +applying scale on u and v, bit1 is for increments of u and v pointers.*/ + int dy; + + dy = 0; + height = this->dest_height; + recal_uv=1; // 1 for evaluation of scale_line, needed the first time + + while(1) + { + register int dxy; + register int dxuv; + register uint8_t p1y, p2y; + uint8_t dest1y, dest2y; + register uint8_t p1u, p2u; + register uint8_t p1v, p2v; + uint8_t dest1u; + uint8_t dest1v; + int width; + uint8_t *u_buffer; + uint8_t *v_buffer; + uint16_t *r, *g, *b; + uint8_t *py, *pu, *pv; + uint16_t *dst; + + dxy = 0; + dxuv = 0; + width = this->dest_width; + u_buffer=this->u_buffer; + v_buffer=this->v_buffer; + dst = (uint16_t*)_dst; + py = _py; + pu = _pu; + pv = _pv; + + //proceed with line scaling/conversion + if ((recal_uv&1)!=0) + { + recal_uv^=1; //reset bit0. + // init values: + p1u = *pu++; + p2u = *pu++; + p1v = *pv++; + p2v = *pv++; + p1y = *py++; + p2y = *py++; + + //width loop (compute all data for a line). + while (width>0) + { + // proceed with u and v first (ok, and y too finally :)) [scaling part]: + // evaluate 1u, 1v, and 2y + //block1_uvy + dest1u=p1u + ((dxuv*(p2u-p1u))>>15); + dest1v=p1v + ((dxuv*(p2v-p1v))>>15); + // as u and v are evaluated, better save them now + *u_buffer++ = (uint8_t)dest1u; + *v_buffer++ = (uint8_t)dest1v; + + dest1y=p1y + ((dxy*(p2y-p1y))>>15); + + dxuv += this->step_dx; + dxy += this->step_dx; + if (dxuv > 32768) + { + dxuv -= 32768; + p1u = p2u; + p2u = *pu++; //idee pour asm, cf cas then, un merge est possible!!! + p1v = p2v; + p2v = *pv++; + } + if (dxy > 32768) + { + dxy -= 32768; + p1y = p2y; + p2y = *py++; + } + //end block1_uvy + + //block2_y + dest2y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + if (dxy > 32768) + { + dxy -= 32768; + p1y = p2y; + p2y = *py++; // idee pour asm, cf cas then, un merge est possible!!! + } + //end block2_y + + // proceed now with YUV2RGB [conversion part]: + // u and v are currently in dest1u and dest1v + // the 2 y are in dest1y and dest2y. + // RGB(0),DST1(0), RGB(1), DST1(1) + r = this->table_rV[dest1v]; + g = (void *) (((uint8_t *)this->table_gU[dest1u]) + this->table_gV[dest1v]); + b = this->table_bU[dest1u]; + + *dst++ = r[dest1y] + g[dest1y] + b[dest1y]; + *dst++ = r[dest2y] + g[dest2y] + b[dest2y]; + + width -=2; + } + } + else + { + // this case is simple, u and v are already evaluated, + // Note pour moi: r, g et b pourraient etre reutilises!! + + // init values: + p1y = *py++; + p2y = *py++; + + //width loop (compute all data for a line). + while (width>0) + { + // proceed with y [scaling part]: + // evaluate 2y + //block1_y + dest1y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + if (dxy > 32768) + { + dxy -= 32768; + p1y = p2y; + p2y = *py++; + } + //end block1_uvy + + //block2_y + dest2y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + if (dxy > 32768) + { + dxy -= 32768; + p1y = p2y; + p2y = *py++; // idee pour asm, cf cas then, un merge est possible!!! + } + //end block2_y + + // proceed now with YUV2RGB [conversion part]: + // u and v are currently in dest1u and dest1v + // the 2 y are in dest1y and dest2y. + // RGB(0),DST1(0) + dest1u=*u_buffer++; + dest1v=*v_buffer++; + r = this->table_rV[dest1v]; + g = (void *) (((uint8_t *)this->table_gU[dest1u]) + this->table_gV[dest1v]); + b = this->table_bU[dest1u]; + + *dst++ = r[dest1y] + g[dest1y] + b[dest1y]; + *dst++ = r[dest2y] + g[dest2y] + b[dest2y]; + + width -=2; + } + } + // end of line scaling/conversion + dy += this->step_dy; + _dst += this->rgb_stride; + + while (--height > 0 && dy < 32768) + { + xine_fast_memcpy (_dst, (uint8_t*)_dst-this->rgb_stride, this->dest_width*2); // *2 because of int8 cast! + dy += this->step_dy; + _dst += this->rgb_stride; + } + + + if (height <= 0) + break; + + do + { + dy -= 32768; + _py += this->y_stride; + + recal_uv^=2; /*bit 0 for reevaluation of scanline, bit 1 for offset.*/ + + if ((recal_uv&2)==0) + { + _pu += this->uv_stride; + _pv += this->uv_stride; + recal_uv|=1; // if update, then reevaluate scanline! + } + } + while( dy>=32768); + } + } + + + +/* Function: */ +static void arm_rgb16_step_dx_32768(yuv2rgb_t *this, uint8_t * _dst, uint8_t * _py, uint8_t * _pu, uint8_t * _pv) +/* This function is called when the widht of the destination picture is the + same as the size of the source picture. +*/ + { + int recal_uv, height; + int dy; + + dy = 0; + height=this->dest_height; + recal_uv=0; + + while (1) + { + uint16_t *r, *g, *b; + uint8_t *py, *pu, *pv; + uint16_t *dst; + int width; + register uint8_t p1y, p1u, p1v; + + width=this->dest_width; + dst = (uint16_t*)_dst; + py = _py; + pu = _pu; + pv = _pv; + + while (width>0) + { + width-=2; + p1y=*py++; + p1u=*pu++; + p1v=*pv++; + + r = this->table_rV[p1v]; + g = (void *) (((uint8_t *)this->table_gU[p1u]) + this->table_gV[p1v]); + b = this->table_bU[p1u]; + + *dst++ = r[p1y] + g[p1y] + b[p1y]; + p1y=*py++; + *dst++ = r[p1y] + g[p1y] + b[p1y]; + } + + + + // end of line scaling/conversion + dy += this->step_dy; + _dst += this->rgb_stride; + + while (--height > 0 && dy < 32768) + { + xine_fast_memcpy (_dst, (uint8_t*)_dst-this->rgb_stride, this->dest_width*2); // *2 because of int8 cast! + dy += this->step_dy; + _dst += this->rgb_stride; + } + + + if (height <= 0) + break; + + do + { + dy -= 32768; + _py += this->y_stride; + + recal_uv^=2; /*bit 0 for reevaluation of scanline, bit 1 for offset.*/ + + if ((recal_uv&2)==0) + { + _pu += this->uv_stride; + _pv += this->uv_stride; + recal_uv|=1; // if update, then reevaluate scanline! + } + } + while( dy>=32768); + } + } + + + +/* Function: */ +static void arm_rgb16_step_dx_bet_32768_65536(yuv2rgb_t *this, uint8_t * _dst, uint8_t * _py, uint8_t * _pu, uint8_t * _pv) +/* This function is called when the destination picture is between the size + of the source picture, and half its size. +*/ + { + int recal_uv, height; /* Note about recal_uv: bit0 is for +applying scale on u and v, bit1 is for increments of u and v pointers.*/ + int dy; + + dy = 0; + height = this->dest_height; + recal_uv=1; // 1 for evaluation of scale_line, needed the first time + + while(1) + { + register int dxy; + register int dxuv; + register uint8_t p1y, p2y; + uint8_t dest1y, dest2y; + register uint8_t p1u, p2u; + register uint8_t p1v, p2v; + uint8_t dest1u; + uint8_t dest1v; + int width; + uint8_t *u_buffer; + uint8_t *v_buffer; + uint16_t *r, *g, *b; + uint8_t *py, *pu, *pv; + uint16_t *dst; + + dxy = 0; + dxuv = 0; + width = this->dest_width; + u_buffer=this->u_buffer; + v_buffer=this->v_buffer; + dst = (uint16_t*)_dst; + py = _py; + pu = _pu; + pv = _pv; + + //proceed with line scaling/conversion + if ((recal_uv&1)!=0) + { + recal_uv^=1; //reset bit0. + // init values: + p1u = *pu++; + p2u = *pu++; + p1v = *pv++; + p2v = *pv++; + p1y = *py++; + p2y = *py++; + + //width loop (compute all data for a line). + while (width>0) + { + // proceed with u and v first (ok, and y too finally :)) [scaling part]: + // evaluate 1u, 1v, and 2y + //block1_uvy + dest1u=p1u + ((dxuv*(p2u-p1u))>>15); + dest1v=p1v + ((dxuv*(p2v-p1v))>>15); + // as u and v are evaluated, better save them now + *u_buffer++ = (uint8_t)dest1u; + *v_buffer++ = (uint8_t)dest1v; + + dest1y=p1y + ((dxy*(p2y-p1y))>>15); + + dxuv += this->step_dx; + dxy += this->step_dx; + if (dxuv > 65536) + { + dxuv -= 65536; + p1u = *pu++; + p2u = *pu++; + p1v = *pv++; + p2v = *pv++; + } + else + { + dxuv -= 32768; + p1u = p2u; + p2u = *pu++; //idee pour asm, cf cas then, un merge est possible!!! + p1v = p2v; + p2v = *pv++; + } + if (dxy > 65536) + { + dxy -= 65536; + p1y = *py++; + p2y = *py++; + } + else + { + dxy -= 32768; + p1y = p2y; + p2y = *py++; + } + //end block1_uvy + + //block2_y + dest2y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + if (dxy > 65536) + { + dxy -= 65536; + p1y = *py++; + p2y = *py++; + } + else + { + dxy -= 32768; + p1y = p2y; + p2y = *py++; // idee pour asm, cf cas then, un merge est possible!!! + } + //end block2_y + + // proceed now with YUV2RGB [conversion part]: + // u and v are currently in dest1u and dest1v + // the 2 y are in dest1y and dest2y. + // RGB(0),DST1(0), RGB(1), DST1(1) + r = this->table_rV[dest1v]; + g = (void *) (((uint8_t *)this->table_gU[dest1u]) + this->table_gV[dest1v]); + b = this->table_bU[dest1u]; + + *dst++ = r[dest1y] + g[dest1y] + b[dest1y]; + *dst++ = r[dest2y] + g[dest2y] + b[dest2y]; + + width -=2; + } + } + else + { + // this case is simple, u and v are already evaluated, + // Note pour moi: r, g et b pourraient etre reutilises!! + + // init values: + p1y = *py++; + p2y = *py++; + + //width loop (compute all data for a line). + while (width>0) + { + // proceed with y [scaling part]: + // evaluate 2y + //block1_y + dest1y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + if (dxy > 65536) + { + dxy -= 65536; + p1y = *py++; + p2y = *py++; + } + else + { + dxy -= 32768; + p1y = p2y; + p2y = *py++; + } + //end block1_uvy + + //block2_y + dest2y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + if (dxy > 65536) + { + dxy -= 65536; + p1y = *py++; + p2y = *py++; + } + else + { + dxy -= 32768; + p1y = p2y; + p2y = *py++; // idee pour asm, cf cas then, un merge est possible!!! + } + //end block2_y + + // proceed now with YUV2RGB [conversion part]: + // u and v are currently in dest1u and dest1v + // the 2 y are in dest1y and dest2y. + // RGB(0),DST1(0) + dest1u=*u_buffer++; + dest1v=*v_buffer++; + r = this->table_rV[dest1v]; + g = (void *) (((uint8_t *)this->table_gU[dest1u]) + this->table_gV[dest1v]); + b = this->table_bU[dest1u]; + + *dst++ = r[dest1y] + g[dest1y] + b[dest1y]; + *dst++ = r[dest2y] + g[dest2y] + b[dest2y]; + + width -=2; + } + } + // end of line scaling/conversion + dy += this->step_dy; + _dst += this->rgb_stride; + + while (--height > 0 && dy < 32768) + { + xine_fast_memcpy (_dst, (uint8_t*)_dst-this->rgb_stride, this->dest_width*2); // *2 because of int8 cast! + dy += this->step_dy; + _dst += this->rgb_stride; + } + + + if (height <= 0) + break; + + do + { + dy -= 32768; + _py += this->y_stride; + + recal_uv^=2; /*bit 0 for reevaluation of scanline, bit 1 for offset.*/ + + if ((recal_uv&2)==0) + { + _pu += this->uv_stride; + _pv += this->uv_stride; + recal_uv|=1; // if update, then reevaluate scanline! + } + } + while( dy>=32768); + } + } + + + +/* Function: */ +static void arm_rgb16_step_dx_sup_65536(yuv2rgb_t *this, uint8_t * _dst, uint8_t * _py, uint8_t * _pu, uint8_t * _pv) +/* This function is called when the destination picture is smaller than half + the size of the source picture, and half its size. +*/ + { + int recal_uv, height; /* Note about recal_uv: bit0 is for +applying scale on u and v, bit1 is for increments of u and v pointers.*/ + int dy; + + dy = 0; + height = this->dest_height; + recal_uv=1; // 1 for evaluation of scale_line, needed the first time + + while(1) + { + register int dxy; + register int dxuv; + int offdxy, offdxuv; + register uint8_t p1y, p2y; + uint8_t dest1y, dest2y; + register uint8_t p1u, p2u; + register uint8_t p1v, p2v; + uint8_t dest1u; + uint8_t dest1v; + int width; + uint8_t *u_buffer; + uint8_t *v_buffer; + uint16_t *r, *g, *b; + uint8_t *py, *pu, *pv; + uint16_t *dst; + + dxy = 0; + dxuv = 0; + width = this->dest_width; + u_buffer=this->u_buffer; + v_buffer=this->v_buffer; + dst = (uint16_t*)_dst; + py = _py; + pu = _pu; + pv = _pv; + + //proceed with line scaling/conversion + if ((recal_uv&1)!=0) + { + recal_uv^=1; //reset bit0. + // init values: + p1u = *pu++; + p2u = *pu++; + p1v = *pv++; + p2v = *pv++; + p1y = *py++; + p2y = *py++; + + //width loop (compute all data for a line). + while (width>0) + { + // proceed with u and v first (ok, and y too finally :)) [scaling part]: + // evaluate 1u, 1v, and 2y + //block1_uvy + dest1u=p1u + ((dxuv*(p2u-p1u))>>15); + dest1v=p1v + ((dxuv*(p2v-p1v))>>15); + // as u and v are evaluated, better save them now + *u_buffer++ = (uint8_t)dest1u; + *v_buffer++ = (uint8_t)dest1v; + + dest1y=p1y + ((dxy*(p2y-p1y))>>15); + + dxuv += this->step_dx; + dxy += this->step_dx; + + offdxuv=((dxuv-1)>>15); + dxuv-=offdxuv<<15; + pu+=offdxuv-2; + pv+=offdxuv-2; + p1u = *pu++; + p2u = *pu++; + p1v = *pv++; + p2v = *pv++; + offdxy=((dxy-1)>>15); + dxy-=offdxy<<15; + py+=offdxy-2; + p1y = *py++; + p2y = *py++; + + //block2_y + dest2y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + offdxy=((dxy-1)>>15); + dxy-=offdxy<<15; + py+=offdxy-2; + p1y = *py++; + p2y = *py++; + + // proceed now with YUV2RGB [conversion part]: + // u and v are currently in dest1u and dest1v + // the 2 y are in dest1y and dest2y. + // RGB(0),DST1(0), RGB(1), DST1(1) + r = this->table_rV[dest1v]; + g = (void *) (((uint8_t *)this->table_gU[dest1u]) + this->table_gV[dest1v]); + b = this->table_bU[dest1u]; + + *dst++ = r[dest1y] + g[dest1y] + b[dest1y]; + *dst++ = r[dest2y] + g[dest2y] + b[dest2y]; + + width -=2; + } + } + else + { + // this case is simple, u and v are already evaluated, + // Note pour moi: r, g et b pourraient etre reutilises!! + + // init values: + p1y = *py++; + p2y = *py++; + + //width loop (compute all data for a line). + while (width>0) + { + // proceed with y [scaling part]: + // evaluate 2y + //block1_y + dest1y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + offdxy=((dxy-1)>>15); + dxy-=offdxy<<15; + py+=offdxy-2; + p1y = *py++; + p2y = *py++; + + //end block1_uvy + + //block2_y + dest2y=p1y + ((dxy*(p2y-p1y))>>15); + + dxy += this->step_dx; + offdxy=((dxy-1)>>15); + dxy-=offdxy<<15; + py+=offdxy-2; + p1y = *py++; + p2y = *py++; + //end block2_y + + // proceed now with YUV2RGB [conversion part]: + // u and v are currently in dest1u and dest1v + // the 2 y are in dest1y and dest2y. + // RGB(0),DST1(0) + dest1u=*u_buffer++; + dest1v=*v_buffer++; + r = this->table_rV[dest1v]; + g = (void *) (((uint8_t *)this->table_gU[dest1u]) + this->table_gV[dest1v]); + b = this->table_bU[dest1u]; + + *dst++ = r[dest1y] + g[dest1y] + b[dest1y]; + *dst++ = r[dest2y] + g[dest2y] + b[dest2y]; + + width -=2; + } + } + // end of line scaling/conversion + dy += this->step_dy; + _dst += this->rgb_stride; + + while (--height > 0 && dy < 32768) + { + xine_fast_memcpy (_dst, (uint8_t*)_dst-this->rgb_stride, this->dest_width*2); // *2 because of int8 cast! + dy += this->step_dy; + _dst += this->rgb_stride; + } + + + if (height <= 0) + break; + + do + { + dy -= 32768; + _py += this->y_stride; + + recal_uv^=2; /*bit 0 for reevaluation of scanline, bit 1 for offset.*/ + + if ((recal_uv&2)==0) + { + _pu += this->uv_stride; + _pv += this->uv_stride; + recal_uv|=1; // if update, then reevaluate scanline! + } + } + while( dy>=32768); + } + } + + +#endif diff --git a/noncore/multimedia/opierec/opierec.control b/noncore/multimedia/opierec/opierec.control index 96c1b69..a1a2b7e 100644 --- a/noncore/multimedia/opierec/opierec.control +++ b/noncore/multimedia/opierec/opierec.control @@ -1,10 +1,10 @@ -Package: opie-rec +Package: opierec Files: bin/opierec pics/opierec apps/Applications/opierec.desktop Priority: optional Section: multimedia/applications Maintainer: L.J. Potter <ljp@llornkcor.com> Architecture: arm -Version: 1.5-2 -Depends: task-opie-minimal +Depends: opie ($QPE_VERSION) Description: audio sampling recorder A simple audio recording/playing application. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/multimedia/opierec/qtrec.cpp b/noncore/multimedia/opierec/qtrec.cpp index 0307d99..147f63d 100644 --- a/noncore/multimedia/opierec/qtrec.cpp +++ b/noncore/multimedia/opierec/qtrec.cpp @@ -1,2254 +1,2254 @@ /**************************************************************************** // qtrec.cpp Created: Thu Jan 17 11:19:58 2002 copyright 2002 by L.J. Potter <ljp@llornkcor.com> ****************************************************************************/ #define DEV_VERSION #include "pixmaps.h" #include "qtrec.h" #include <pthread.h> extern "C" { #include "adpcm.h" } #include <sys/soundcard.h> // #if defined (QTOPIA_INTERNAL_FSLP) // #include <qpe/lnkproperties.h> // #endif #include <qpe/config.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/qpeapplication.h> #include <qpe/resource.h> #include <qpe/storage.h> #include <qcheckbox.h> #include <qcombobox.h> //#include <qdatetime.h> #include <qdir.h> #include <qgroupbox.h> #include <qlabel.h> #include <qlayout.h> #include <qlistview.h> #include <qmessagebox.h> #include <qpopupmenu.h> #include <qpushbutton.h> #include <qslider.h> #include <qtabwidget.h> #include <qtimer.h> #include <errno.h> #include <fcntl.h> #include <math.h> #include <mntent.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/soundcard.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/vfs.h> #include <unistd.h> #include<sys/wait.h> #include <sys/signal.h> //#define ZAURUS 0 struct adpcm_state encoder_state; struct adpcm_state decoder_state; long findPeak(long input ); //char deviceRates[]; typedef struct { int sampleRate; /* int fragSize; */ /* int blockSize; */ int resolution; //bitrate int channels; //number of channels int fd; //file descriptor int sd; //sound device descriptor int numberSamples; //total number of samples int SecondsToRecord; // number of seconds that should be recorded float numberOfRecordedSeconds; //total number of samples recorded int samplesToRecord; //number of samples to be recorded int inVol; //input volume int outVol; //output volume int format; //wavfile format PCM.. ADPCM const char *fileName; //name of fiel to be played/recorded } fileParameters; fileParameters filePara; bool monitoring, recording; bool stopped; QLabel *timeLabel; QSlider *timeSlider; int sd; #if defined(QT_QWS_EBX) #define DSPSTROUT "/dev/dsp" #define DSPSTRIN "/dev/dsp1" #define DSPSTRMIXEROUT "/dev/mixer" #define DSPSTRMIXERIN "/dev/mixer1" #else #define DSPSTROUT "/dev/dsp" #define DSPSTRIN "/dev/dsp" #define DSPSTRMIXERIN "/dev/mixer" #define DSPSTRMIXEROUT "/dev/mixer" #endif // threaded recording void quickRec() { //void QtRec::quickRec() { qDebug("%d", filePara.numberSamples/filePara.sampleRate * filePara.channels); qDebug("samples %d, rate %d, channels %d", filePara.numberSamples, filePara.sampleRate, filePara.channels); int total = 0; // Total number of bytes read in so far. int bytesWritten, number; count_info info; bytesWritten=0; number=0; QString num, timeString; int level=0; int threshold=0; // if(limit != 0) // t->start( ( limit +.3) , true); recording = true; //rate=filePara.sampleRate; int bits = filePara.resolution; qDebug("bits %d", bits); // if( filePara.format==WAVE_FORMAT_DVI_ADPCM) // else audio_buf_info inInfo; ioctl( filePara.fd, SNDCTL_DSP_GETISPACE, &inInfo); qDebug("ispace is frags %d, total %d", inInfo.fragments, inInfo.fragstotal); if( filePara.resolution == 16 ) { //AFMT_S16_LE) qDebug("AFMT_S16_LE size %d", filePara.SecondsToRecord); qDebug("samples to record %d", filePara.samplesToRecord); qDebug("%d", filePara.sd); level=7; threshold=0; timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds); timeLabel->setText( timeString+ " seconds"); if( filePara.format==WAVE_FORMAT_DVI_ADPCM) { qDebug("start recording WAVE_FORMAT_DVI_ADPCM"); // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>> char abuf[BUFSIZE/2]; short sbuf[BUFSIZE]; short sbuf2[BUFSIZE]; memset( abuf,0,BUFSIZE/2); memset( sbuf,0,BUFSIZE); memset( sbuf2,0,BUFSIZE); for(;;) { if (stopped) { qDebug("quickRec:: stopped"); break; // stop if playing was set to false // return; } number=::read( filePara.sd, sbuf, BUFSIZE); if(number <= 0) { perror("recording error "); qDebug( "%s %d", filePara.fileName, number); // errorStop(); recording=stopped=false; // QMessageBox::message("Note", // "Error recording to file\n%s", // filePara.fileName); return; } //if(stereo == 2) { // adpcm_coder( sbuf2, abuf, number/2, &encoder_state); adpcm_coder( sbuf, abuf, number/2, &encoder_state); bytesWritten = ::write( filePara.fd , abuf, number/4); long peak; for (int i = 0; i < number; i++) { //since Z is mono do normally peak = findPeak((long)sbuf[i]); printf("peak %ld\r",peak); fflush(stdout); } //------------->>>> out to file // if(filePara.channels==1) // total += bytesWritten/2; //mono // else total += bytesWritten; filePara.numberSamples = total; // if( total >= filePara.samplesToRecord) // timeSlider->setValue(0); // else if( filePara.SecondsToRecord !=0) timeSlider->setValue( total); filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate * (float)2; // printf("Writing number %d, bytes %d,total %d, sample rate %d, secs %.2f \n", // number, // bytesWritten , // total, // filePara.sampleRate, // filePara.numberOfRecordedSeconds); // fflush(stdout); ioctl( filePara.sd, SNDCTL_DSP_GETIPTR, &info); // qDebug("%d, %d", info.bytes, (info.bytes / filePara.sampleRate) / 2); timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds); timeLabel->setText( timeString + " seconds"); qApp->processEvents(); if( total >= filePara.samplesToRecord) break; } } else { // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>> qDebug("start recording WAVE_FORMAT_PCM"); short inbuffer[BUFSIZE], outbuffer[BUFSIZE]; memset( inbuffer,0,BUFSIZE); memset( outbuffer,0,BUFSIZE); for(;;) { if (stopped) { qDebug("quickRec:: stopped"); break; // stop if playing was set to false return; } number=::read( filePara.sd, inbuffer, BUFSIZE); if(number <= 0) { perror("recording error "); qDebug( filePara.fileName); recording=stopped=false; // errorStop(); // QMessageBox::message("Note","error recording to file\n%s",filePara.fileName); return;// false; } /* for (int i=0;i< number;i++) { //2*i is left channel outbuffer[i]=inbuffer[i]>>1; // no clippy, please }*/ bytesWritten = ::write( filePara.fd , inbuffer, number); //------------->>>> out to file if(bytesWritten < 0) { // errorStop(); perror("File writing error "); return;// false; } // if(filePara.channels==1) // total += bytesWritten/2; //mono // else total += bytesWritten; long peak; for (int i = 0; i < number; i++) { //since Z is mono do normally peak = findPeak((long)inbuffer[i]); printf("peak %ld\r",peak); fflush(stdout); } filePara.numberSamples = total; if(filePara.SecondsToRecord !=0) timeSlider->setValue( total); // printf("Writing number %d, bytes %d,total %d\r",number, bytesWritten , total); // fflush(stdout); ioctl( filePara.sd, SNDCTL_DSP_GETIPTR, &info); // qDebug("%d, %d", info.bytes, ( info.bytes / filePara.sampleRate) / 2); filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2; timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds); timeLabel->setText( timeString + " seconds"); qApp->processEvents(); if( total >= filePara.samplesToRecord) break; } } //end main loop } else { // <<<<<<<<<<<<<<<<<<<<<<< format = AFMT_U8; unsigned char unsigned_inbuffer[BUFSIZE], unsigned_outbuffer[BUFSIZE]; memset( unsigned_inbuffer, 0, BUFSIZE); memset( unsigned_outbuffer, 0, BUFSIZE); for(;;) { if (stopped) { qDebug("quickRec:: stopped"); break; // stop if playing was set to false } number=::read( filePara.sd, unsigned_inbuffer, BUFSIZE); //-------------<<<< in from device // val = (data ^ 0x80) << 8; //unsigned_outbuffer = (unsigned_inbuffer ^ 0x80) << 8; // if(number <= 0) { // perror("recording error "); // qDebug(filePara.fileName); // // errorStop(); // QMessageBox::message("Note","error recording"); // return;// false; // } // for (int i=0;i< number;i++) { //2*i is left channel // unsigned_outbuffer[i]=unsigned_inbuffer[i]>>1; // no clippy, please // } bytesWritten = ::write( filePara.fd , unsigned_inbuffer, number); //------------->>>> out to file if(bytesWritten < 0) { recording=stopped=false; // errorStop(); QMessageBox::message("Note","There was a problem\nwriting to the file"); perror("File writing error "); return;// false; } total += bytesWritten; filePara.numberSamples = total; // printf("\nWriting number %d, bytes %d,total %d \r",number, bytesWritten , total); // fflush(stdout); if(filePara.SecondsToRecord !=0) timeSlider->setValue( total); filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate; timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds); timeLabel->setText( timeString + " seconds"); qApp->processEvents(); if( total >= filePara.samplesToRecord) break; } //end main loop } // qDebug("Final %d, %d", filePara.samplesToRecord , filePara.numberOfRecordedSeconds); } /// END quickRec() // threaded play void playIt() { } /////////////////<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>> /////////////////<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>> QtRec::QtRec( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { // QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << true; // mute device // autoMute=TRUE; // QPEApplication::grabKeyboard(); // signal(SIGPIPE, SIG_IGN); if ( !name ) setName( "OpieRec" ); init(); initConfig(); initConnections(); renameBox = 0; // open sound device to get volumes soundDevice = new Device( this, DSPSTROUT, DSPSTRMIXEROUT, false); // soundDevice->setDeviceFormat(AFMT_S16_LE); // soundDevice->setDeviceChannels(1); // soundDevice->setDeviceRate( 22050); getInVol(); getOutVol(); soundDevice->closeDevice( true); soundDevice->sd=-1; soundDevice=0; wavFile=0; if(soundDevice) delete soundDevice; initIconView(); if(autoMute) doMute(true); ListView1->setFocus(); playing=false; } QtRec::~QtRec() { } void QtRec::cleanUp() { if(!stopped) { stopped=true; endRecording(); } ListView1->clear(); if(autoMute) doMute(false); if(wavFile) delete wavFile; // if(soundDevice) delete soundDevice; // QPEApplication::grabKeyboard(); // QPEApplication::ungrabKeyboard(); } void QtRec::init() { needsStereoOut=false; QPixmap image3( ( const char** ) image3_data ); QPixmap image4( ( const char** ) image4_data ); QPixmap image6( ( const char** ) image6_data ); stopped=true; setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); QGridLayout *layout = new QGridLayout( this ); layout->setSpacing( 2); layout->setMargin( 2); TabWidget = new QTabWidget( this, "TabWidget" ); layout->addMultiCellWidget(TabWidget, 0, 7, 0, 7); // TabWidget->setTabShape(QTabWidget::Triangular); ///**********<<<<<<<<<<<<>>>>>>>>>>>>*************** tab = new QWidget( TabWidget, "tab" ); QGridLayout *layout1 = new QGridLayout( tab); layout1->setSpacing( 2); layout1->setMargin( 2); timeSlider = new QSlider( 0,100,10,0, QSlider::Horizontal, tab, (const char *) "timeSlider" ); // timeSlider->setFixedWidth(150); layout1->addMultiCellWidget( timeSlider, 1, 1, 0, 3); // timeSlider->setTickmarks(QSlider::Above); timeLabel = new QLabel( tab, "TimeLabel" ); layout1->addMultiCellWidget( timeLabel, 0, 0, 0, 3); playLabel2 = new QLabel(tab, "PlayLabel2" ); - playLabel2->setText("Play"); + playLabel2->setText(tr("Play") ); playLabel2->setFixedHeight(18); layout1->addMultiCellWidget( playLabel2, 0, 0, 4, 4); Stop_PushButton = new QPushButton( tab, "Stop_PushButton" ); layout1->addMultiCellWidget( Stop_PushButton, 1, 1, 4, 4); Stop_PushButton->setFixedSize(22,22); Stop_PushButton->setPixmap( image4 ); toBeginningButton = new QPushButton( tab, "Beginning_PushButton" ); layout1->addMultiCellWidget(toBeginningButton, 1, 1, 5, 5); toBeginningButton->setFixedSize(22,22); toBeginningButton->setPixmap( Resource::loadPixmap("fastback") ); toEndButton = new QPushButton( tab, "End_PushButton" ); layout1->addMultiCellWidget( toEndButton, 1, 1, 6, 6); toEndButton->setFixedSize(22,22); toEndButton->setPixmap( Resource::loadPixmap( "fastforward" ) ); QLabel *recLabel2; recLabel2 = new QLabel( tab, "recLabel2" ); - recLabel2->setText("Rec"); + recLabel2->setText(tr("Rec")); recLabel2->setFixedHeight(18); layout1->addMultiCellWidget( recLabel2, 0, 0, 7, 7); Rec_PushButton = new QPushButton( tab, "Rec_PushButton" ); layout1->addMultiCellWidget( Rec_PushButton, 1, 1, 7, 7); Rec_PushButton->setFixedSize(22,22); Rec_PushButton->setPixmap( image6 ); t = new QTimer( this ); connect( t, SIGNAL( timeout() ), SLOT( timerBreak() ) ); rewindTimer = new QTimer( this ); connect( rewindTimer, SIGNAL( timeout() ), SLOT( rewindTimerTimeout() ) ); forwardTimer = new QTimer( this ); connect( forwardTimer, SIGNAL( timeout() ), SLOT( forwardTimerTimeout() ) ); deleteSoundButton = new QPushButton( tab, "deleteSoundButton" ); layout1->addMultiCellWidget( deleteSoundButton, 1, 1, 8, 8); deleteSoundButton->setText( tr( "Delete" ) ); ListView1 = new QListView( tab, "IconView1" ); layout1->addMultiCellWidget( ListView1, 2, 2, 0, 8); ListView1->addColumn( tr( "Name" ) ); ListView1->setColumnWidth(0,140); ListView1->setSorting( 1, false); ListView1->addColumn( tr( "Time" ) ); //in seconds ListView1->setColumnWidth(1,50); - ListView1->addColumn( "Location"); + ListView1->addColumn( tr("Location") ); ListView1->setColumnWidth(2,50); - ListView1->addColumn( "Date"); + ListView1->addColumn( tr("Date") ); ListView1->setColumnWidth(3,63); ListView1->setColumnWidthMode(0,QListView::Manual); ListView1->setColumnAlignment(1,QListView::AlignCenter); ListView1->setColumnAlignment(2,QListView::AlignRight); ListView1->setColumnAlignment(3,QListView::AlignLeft); ListView1->setAllColumnsShowFocus( true ); QPEApplication::setStylusOperation( ListView1->viewport(),QPEApplication::RightOnHold); TabWidget->insertTab( tab, tr( "Files" ) ); ///**********<<<<<<<<<<<<>>>>>>>>>>>>*************** tab_3 = new QWidget( TabWidget, "tab_3" ); //////////////////////////////////// Layout19 = new QHBoxLayout( tab_3); Layout19->setSpacing( 2 ); Layout19->setMargin( 0 ); Layout18 = new QVBoxLayout(this); Layout18->setSpacing( 2 ); Layout18->setMargin( 0 ); Layout17 = new QHBoxLayout(this); Layout17->setSpacing( 2 ); Layout17->setMargin( 0 ); sampleGroup = new QGroupBox( tab_3, "samplegroup" ); sampleGroup->setTitle( tr( "Sample Rate" ) ); sampleGroup->setFixedSize( 95,50); sampleRateComboBox = new QComboBox( false, sampleGroup, "SampleRateComboBox" ); sampleRateComboBox->setGeometry( QRect( 10, 20, 80, 25 ) ); //#ifndef QT_QWS_EBX sampleRateComboBox->insertItem( tr( "44100")); sampleRateComboBox->insertItem( tr( "32000")); //#endif sampleRateComboBox->insertItem( tr( "22050")); //#ifndef QT_QWS_VERCEL_IDR sampleRateComboBox->insertItem( tr( "16000")); sampleRateComboBox->insertItem( tr( "11025")); sampleRateComboBox->insertItem( tr( "8000")); //#endif Layout17->addWidget( sampleGroup ); sizeGroup= new QGroupBox( tab_3, "sizeGroup" ); sizeGroup->setTitle( tr( "Limit Size" ) ); sizeGroup->setFixedSize(80,50); sizeLimitCombo = new QComboBox( false, sizeGroup, "sizeLimitCombo" ); sizeLimitCombo ->setGeometry( QRect( 5, 20, 70, 25 ) ); sizeLimitCombo->insertItem(tr("Unlimited")); for(int i=1;i<13; i++) { sizeLimitCombo->insertItem( QString::number(i*5)); } // sizeLimitCombo->insertItem(tr("5 secs")); // sizeLimitCombo->insertItem(tr("10 secs")); // sizeLimitCombo->insertItem(tr("15 secs")); // sizeLimitCombo->insertItem(tr("20 secs")); // Layout18->addWidget( sizeGroup ); Layout17->addWidget( sizeGroup ); Layout18->addLayout( Layout17 ); Layout16 = new QHBoxLayout(this); Layout16->setSpacing( 2 ); Layout16->setMargin( 0 ); dirGroup = new QGroupBox( tab_3, "dirGroup" ); dirGroup->setTitle( tr( "File Directory" ) ); dirGroup->setFixedSize(130,50); directoryComboBox = new QComboBox( false, dirGroup, "dirGroup" ); directoryComboBox->setGeometry( QRect( 10, 15, 115, 25 ) ); Layout18->addWidget( dirGroup ); bitGroup = new QGroupBox( tab_3, "bitGroup" ); bitGroup->setTitle( tr( "Bit Depth" ) ); bitGroup->setFixedSize(65,50); bitRateComboBox = new QComboBox( false, bitGroup, "BitRateComboBox" ); bitRateComboBox->insertItem( tr( "16" ) ); bitRateComboBox->insertItem( tr( "8" ) ); bitRateComboBox->setGeometry( QRect( 5, 20, 50, 25 ) ); Layout18->addWidget( bitGroup ); - compressionCheckBox = new QCheckBox ( "Wave Compression (smaller files)", tab_3 ); + compressionCheckBox = new QCheckBox ( tr("Wave Compression (smaller files)"), tab_3 ); Layout18->addWidget( compressionCheckBox ); - autoMuteCheckBox= new QCheckBox ( "auto Mute", tab_3 ); + autoMuteCheckBox= new QCheckBox ( tr("auto Mute"), tab_3 ); Layout18->addWidget( autoMuteCheckBox ); Layout19->addLayout( Layout18 ); QWidget *d = QApplication::desktop(); int width=d->width(); int height=d->height(); if( width < height) { tab_5 = new QWidget( TabWidget, "tab_5" ); QHBoxLayout *Layout19a; Layout19a = new QHBoxLayout( tab_5); Layout19a->setSpacing( 2 ); Layout19a->setMargin( 0 ); Layout15 = new QVBoxLayout(this); Layout15->setSpacing( 2 ); Layout15->setMargin( 0 ); Layout15b = new QVBoxLayout(this); Layout15b->setSpacing( 2 ); Layout15b->setMargin( 0 ); TextLabel2 = new QLabel( tab_5, "InputLabel" ); TextLabel2->setText( tr( "In")); TextLabel2->setFixedWidth(35); Layout15->addWidget( TextLabel2 ); TextLabel3 = new QLabel( tab_5, "OutputLabel" ); TextLabel3->setText( tr( "Out" ) ); Layout15b->addWidget( TextLabel3 ); InputSlider = new QSlider( -100, 0, 10, 0, QSlider::Vertical, tab_5, (const char *) "InputSlider" ); InputSlider->setTickmarks(QSlider::Both); Layout15->addWidget( InputSlider); OutputSlider = new QSlider( -100,0,10,0, QSlider::Vertical,tab_5,(const char *) "OutputSlider" ); OutputSlider->setTickmarks(QSlider::Both); Layout15b->addWidget( OutputSlider ); - outMuteCheckBox = new QCheckBox ( "mute", tab_5 ); + outMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 ); Layout15->addWidget( outMuteCheckBox ); - inMuteCheckBox = new QCheckBox ( "mute", tab_5 ); + inMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 ); inMuteCheckBox-> setFocusPolicy ( QWidget::NoFocus ); Layout15b->addWidget( inMuteCheckBox ); Layout19a->addLayout( Layout15 ); Layout19a->addLayout( Layout15b ); fillDirectoryCombo(); TabWidget->insertTab( tab_3, tr( "Options" ) ); TabWidget->insertTab( tab_5, tr( "Volume" ) ); } else {// landscape // Layout16->addWidget( dirGroup ); // Layout18->addLayout( Layout16 ); Layout15 = new QVBoxLayout(this); Layout15->setSpacing( 2 ); Layout15->setMargin( 0 ); Layout15b = new QVBoxLayout(this); Layout15b->setSpacing( 2 ); Layout15b->setMargin( 0 ); TextLabel2 = new QLabel( tab_3, "InputLabel" ); TextLabel2->setText( tr( "In")); TextLabel2->setFixedWidth(35); Layout15->addWidget( TextLabel2 ); TextLabel3 = new QLabel( tab_3, "OutputLabel" ); TextLabel3->setText( tr( "Out" ) ); Layout15b->addWidget( TextLabel3 ); InputSlider = new QSlider( -100, 0, 10, 0, QSlider::Vertical, tab_3, (const char *) "InputSlider" ); // InputSlider->setTickmarks(QSlider::Both); Layout15->addWidget( InputSlider); OutputSlider = new QSlider( -100,0,10,0, QSlider::Vertical,tab_3,(const char *) "OutputSlider" ); // OutputSlider->setTickmarks(QSlider::Both); Layout15b->addWidget( OutputSlider ); - outMuteCheckBox = new QCheckBox ( "mute", tab_3 ); + outMuteCheckBox = new QCheckBox ( tr("mute"), tab_3 ); Layout15->addWidget( outMuteCheckBox ); - inMuteCheckBox = new QCheckBox ( "mute", tab_3 ); + inMuteCheckBox = new QCheckBox ( tr("mute"), tab_3 ); inMuteCheckBox-> setFocusPolicy ( QWidget::NoFocus ); Layout15b->addWidget( inMuteCheckBox ); Layout19->addLayout( Layout15 ); Layout19->addLayout( Layout15b ); fillDirectoryCombo(); TabWidget->insertTab( tab_3, tr( "Options" ) ); } ///**********<<<<<<<<<<<<>>>>>>>>>>>>*************** // tab_4 = new QWidget( TabWidget, "tab_4" ); // QGridLayout *layout4 = new QGridLayout( tab_4); // layout4->setSpacing( 2); // layout4->setMargin( 2); // TabWidget->insertTab( tab_4, tr( "Help")); // ///////////////////////////////////////////// FIXME change to a real helpfile path // QString url="/index.html"; // HelpWindow *help = new HelpWindow( url, ".", tab_4, "opierec_help"); // layout4->addMultiCellWidget( help, 0, 1, 0, 1); // if( !QFile(url).exists()) { // help->hide(); // //help->showMaximized(); // QLabel *helpLabel; // helpLabel = new QLabel( tab_4, "TimeLabel" ); // layout4->addMultiCellWidget( helpLabel, 0, 3, 0, 4 ); // helpLabel->setText( "<B>OpieRec</B><br>" // "Records files in standard wav format<br>" // "or a compressed version<br>" // "For help, please email the author<br>" // "<B>OpieRec</B> is copyright© 2002 by" // " L.J. Potter<br>llornkcor@handhelds.org<BR>" // "and is licensed under the <B>QPL</B>"); // } ///**********<<<<<<<<<<<<>>>>>>>>>>>>*************** } void QtRec::initIconView() { ListView1->clear(); Config cfg("OpieRec"); cfg.setGroup("Sounds"); QString temp; QPixmap image0( ( const char** ) image0_data ); int nFiles = cfg.readNumEntry("NumberofFiles",0); for(int i=1;i<= nFiles;i++) { QListViewItem * item; QString fileS, mediaLocation, fileDate, filePath; // temp.sprintf("%d",i); temp=cfg.readEntry(temp,""); //reads currentFile filePath = cfg.readEntry(temp,""); //currentFileName QFileInfo info(filePath); fileDate = info.lastModified().toString(); fileS = cfg.readEntry( filePath, "0" );// file length in seconds mediaLocation=getStorage( filePath); if(info.exists()) { item = new QListViewItem( ListView1, temp, fileS, mediaLocation, fileDate); item->setPixmap( 0, image0); if(currentFileName == filePath) ListView1->setSelected( item, true); } } } void QtRec::initConnections() { connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); connect( toBeginningButton, SIGNAL( pressed()), this, SLOT( rewindPressed() )); connect( toBeginningButton, SIGNAL( released()), this, SLOT( rewindReleased() )); connect( toEndButton, SIGNAL( pressed()), this, SLOT( FastforwardPressed() )); connect( toEndButton, SIGNAL( released()), this, SLOT( FastforwardReleased() )); connect( deleteSoundButton, SIGNAL(released()), this, SLOT( deleteSound() )); connect( Stop_PushButton, SIGNAL(released()), this, SLOT( doPlayBtn() )); connect( Rec_PushButton, SIGNAL(released()), this, SLOT( newSound() ) ); connect( TabWidget, SIGNAL( currentChanged( QWidget*)),this, SLOT(thisTab(QWidget*) )); connect( OutputSlider, SIGNAL(sliderReleased()), this, SLOT( changedOutVolume()) ); connect( InputSlider, SIGNAL(sliderReleased()), this, SLOT( changedInVolume()) ); // connect( OutputSlider, SIGNAL(valueChanged( int)), this, SLOT(changedOutVolume(int)) ); // connect( InputSlider, SIGNAL(valueChanged( int)), this, SLOT(changedInVolume(int)) ); connect( sampleRateComboBox, SIGNAL(activated( int)), this, SLOT( changesamplerateCombo(int)) ); connect( bitRateComboBox, SIGNAL(activated( int)), this, SLOT( changebitrateCombo(int)) ); connect( directoryComboBox, SIGNAL(activated( int)), this, SLOT( changeDirCombo(int)) ); connect( sizeLimitCombo, SIGNAL(activated( int)), this, SLOT( changeSizeLimitCombo(int)) ); connect( outMuteCheckBox, SIGNAL(toggled( bool)), this, SLOT( doVolMuting(bool)) ); connect( inMuteCheckBox , SIGNAL(toggled( bool)), this, SLOT( doMicMuting(bool)) ); connect( ListView1,SIGNAL(doubleClicked( QListViewItem*)),this,SLOT( itClick(QListViewItem*))); connect( ListView1, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), this,SLOT( listPressed(int, QListViewItem *, const QPoint&, int)) ); connect( timeSlider, SIGNAL( sliderMoved( int)), this, SLOT( changeTimeSlider(int) )); connect( timeSlider, SIGNAL( sliderPressed( )), this, SLOT( timeSliderPressed() )); connect( timeSlider, SIGNAL( sliderReleased( )), this, SLOT( timeSliderReleased() )); connect( compressionCheckBox, SIGNAL( toggled(bool)),this, SLOT( compressionSelected(bool))); connect( autoMuteCheckBox, SIGNAL( toggled(bool)),this, SLOT( slotAutoMute(bool))); } void QtRec::initConfig() { int index, fred, i; Config cfg("OpieRec"); cfg.setGroup("Settings"); index = cfg.readNumEntry("samplerate",22050); bool ok; for(int ws=0;ws<sampleRateComboBox->count();ws++) { fred = sampleRateComboBox->text(ws).toInt(&ok, 10); if(index == fred) { filePara.sampleRate = fred; sampleRateComboBox->setCurrentItem(ws); } } i=cfg.readNumEntry("bitrate",16); if(i == 16) bitRateComboBox->setCurrentItem( 0); else bitRateComboBox->setCurrentItem( 1); filePara.resolution = i; i=cfg.readNumEntry("sizeLimit", 5 ); QString temp; // for(int i=1;i<13; i++) { // temp = sizeLimitCombo->text(i); // sizeLimitCombo->insertItem( QString::number(i*5)+tr(" secs")); // } sizeLimitCombo->setCurrentItem((i/5)); compressionCheckBox->setChecked( cfg.readBoolEntry("wavCompression",1)); if( compressionCheckBox->isChecked()) { bitRateComboBox->setEnabled(false); bitRateComboBox->setCurrentItem(0); filePara.resolution=16; } autoMuteCheckBox->setChecked( cfg.readBoolEntry("useAutoMute",0)); if( autoMuteCheckBox->isChecked()) slotAutoMute(true); else slotAutoMute(false); Config cofg( "qpe"); cofg.setGroup( "Volume"); outMuteCheckBox->setChecked( cofg.readBoolEntry( "Mute",0)); inMuteCheckBox->setChecked( cofg.readBoolEntry( "MicMute",0)); } //================ void QtRec::stop() { qDebug("<<<<<<<<<stop()"); setRecordButton(false); monitoring=false; stopped=true; if( !recording) endPlaying(); else endRecording(); timeSlider->setValue(0); // QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << true; // mute device } void QtRec::doPlayBtn() { if(!stopped) { - playLabel2->setText("Play"); + playLabel2->setText(tr("Play")); stop(); } else { if(ListView1->currentItem() == 0) return; - playLabel2->setText("Stop"); + playLabel2->setText(tr("Stop")); currentFile = ListView1->currentItem()->text(0); start(); } } void QtRec::start() { //play if(stopped) { qDebug("start::"); QPixmap image3( ( const char** ) image3_data ); Stop_PushButton->setPixmap( image3 ); Stop_PushButton->setDown(true); stopped=false; paused=false; secCount=1; if( openPlayFile()) if( setupAudio( false)) //recording is false doPlay(); } } bool QtRec::rec() { //record qDebug("rec()"); if(!stopped) { qDebug("rec:: !stopped"); monitoring=true; return false; } else { qDebug("go ahead and record"); secCount=1; - playLabel2->setText("Stop"); + playLabel2->setText(tr("Stop")); monitoring=false; setRecordButton(true); stopped=false; if( setupAudio( true)) if(setUpFile()) { qDebug("Ok to start recording"); int fileSize=0; Config cfg("OpieRec"); cfg.setGroup("Settings"); qDebug( "<<<<<<<Device bits %d, device rate %d, device channels %d", soundDevice->getDeviceBits(), soundDevice->getDeviceRate(), soundDevice->getDeviceChannels()); //filePara.sampleRate = cfg.readNumEntry("samplerate", 22050); qDebug("sample rate is %d", filePara.sampleRate); filePara.SecondsToRecord = getCurrentSizeLimit(); qDebug("size limit %d sec", filePara.SecondsToRecord); int diskSize = checkDiskSpace( (const QString &) wavFile->trackName()); if( filePara.SecondsToRecord == 0) { fileSize = diskSize; } else if( filePara.format==WAVE_FORMAT_PCM) { qDebug("WAVE_FORMAT_PCM"); fileSize = (filePara.SecondsToRecord ) * filePara.channels * filePara.sampleRate *(filePara.resolution/8)+1000; } else { qDebug("WAVE_FORMAT_DVI_ADPCM"); fileSize = ((filePara.SecondsToRecord) * filePara.channels * filePara.sampleRate *(filePara.resolution/8) )/4+250; } filePara.samplesToRecord = fileSize; qDebug("filesize should be %d, bits %d, rate %d", filePara.samplesToRecord, filePara.resolution, filePara.sampleRate); if(paused) { paused = false; } // else { qDebug("Setting timeslider %d", filePara.samplesToRecord); // if(fileSize != 0) timeSlider->setRange(0, filePara.samplesToRecord); // } if( diskSize < fileSize/1024) { QMessageBox::warning(this, tr("Low Disk Space"), tr("You are running low of\nrecording space\n" "or a card isn't being recognized")); stopped = true; //we need to be stopped stop(); } else { QString msg; msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution); #ifdef DEV_VERSION setCaption( msg); #endif filePara.fileName=currentFile.latin1(); qDebug("Start recording thread"); pthread_t thread1; pthread_create( &thread1, NULL, (void * (*)(void *))quickRec, NULL/* &*/); // quickRec(); toBeginningButton->setEnabled(false); toEndButton->setEnabled(false); startTimer(1000); } } //end setUpFile } //end setupAudio // _exit( 0); // ///* default: // // /* pid greater than zero is parent getting the child's pid */ // /* printf("Child's pid is %d\n",pid); // waitpid( pid, &status, 0); // printf("Child[%d] exited with status %d\n", pid, status);*/ // while (wait(NULL) != pid) // ; // printf("child %ld terminated normally, return status is zero\n", (long) pid); // endRecording(); /* else { //device was not opened qDebug("Audio device open failed"); return false; } }*/ // } //end fork // } // } return true; } /* This happens when a tab is selected*/ void QtRec::thisTab(QWidget* widg) { if(widg != NULL) { int index=TabWidget->currentPageIndex(); if(index==0) { //file page } if(index ==1) { //control page fillDirectoryCombo(); // soundDevice->getOutVol(); // soundDevice->getInVol(); } if(index==2) { //help page } qApp->processEvents(); update(); } } void QtRec::getOutVol( ) { filePara.outVol = soundDevice->getOutVolume(); qDebug("out vol %d", filePara.outVol); OutputSlider->setValue( -filePara.outVol); } void QtRec::getInVol() { filePara.inVol = soundDevice->getInVolume(); qDebug("in vol %d", filePara.inVol); InputSlider->setValue( -filePara.inVol); } void QtRec::changedOutVolume() { soundDevice->changedOutVolume(-OutputSlider->value()); } void QtRec::changedInVolume( ) { soundDevice->changedInVolume( -InputSlider->value()); } bool QtRec::setupAudio( bool b) { bool ok; int sampleformat, stereo, flags; char * dspString, *mixerString; filePara.resolution = bitRateComboBox->currentText().toInt( &ok,10); //16 if( !b){ // we want to play qDebug("setting up DSP for playing"); if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) { sampleformat = AFMT_S16_LE; filePara.resolution = 16; } else { sampleformat = AFMT_U8; filePara.resolution=8; } stereo = filePara.channels = 1; flags= O_WRONLY; dspString = DSPSTROUT; mixerString = DSPSTRMIXEROUT; } else { // we want to record qDebug("setting up DSP for recording"); if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16") sampleformat = AFMT_S16_LE; else sampleformat = AFMT_U8; if( !compressionCheckBox->isChecked()) { filePara.format=WAVE_FORMAT_PCM; qDebug("WAVE_FORMAT_PCM"); } else { filePara.format=WAVE_FORMAT_DVI_ADPCM; sampleformat=AFMT_S16_LE; qDebug("WAVE_FORMAT_DVI_ADPCM"); } stereo = filePara.channels = 1; // filePara.sampleRate = sampleRateComboBox->currentText().toInt( &ok,10);//44100; flags= O_RDWR; // flags= O_RDONLY; dspString = DSPSTRIN; mixerString = DSPSTRMIXEROUT; } // if(soundDevice) delete soundDevice; qDebug("<<<<<<<<<<<<<<<<<<<open dsp %d %d %d", filePara.sampleRate, filePara.channels, sampleformat); soundDevice = new Device( this, dspString, mixerString, b); // soundDevice->openDsp(); soundDevice->reset(); qDebug("device has been made %d", soundDevice->sd); ////////////////// <<<<<<<<<<<<>>>>>>>>>>>> soundDevice->setDeviceFormat( sampleformat); soundDevice->setDeviceChannels( filePara.channels); soundDevice->setDeviceRate( filePara.sampleRate); soundDevice->getDeviceFragSize(); #ifdef QT_QWS_EBX int frag = FRAGSIZE; soundDevice->setFragSize( frag); soundDevice->getDeviceFragSize(); #endif ///////////////// filePara.sd = soundDevice->sd; if ( filePara.sd == -1) { monitoring=false; stopped=true; update(); setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); stopped=true; return false; } if(autoMute) doMute(false); return true; } bool QtRec::setUpFile() { //setup file for recording qDebug("Setting up wavfile"); // if(wavFile) delete wavFile; wavFile = new WavFile( this, (const QString &)"", true, filePara.sampleRate, filePara.channels, filePara.resolution, filePara.format); filePara.fd = wavFile->wavHandle(); if(filePara.fd == -1) { return false; } else { filePara.channels=1; } return true; } /// <<<<<<<<<<<<<<<< PLAY >>>>>>>>>>>>>>>>>>> bool QtRec::doPlay() { // pthread_t thread2; // pthread_create( &thread2, NULL, (void * (*)(void *))playIt, NULL/* &*/); // qDebug("doPlay file %d", filePara.fd); int bytesWritten, number; recording = false; // int number=0; if( !paused) { qDebug("new"); total=0; bytesWritten=0; filePara.numberOfRecordedSeconds = 0; } else { paused = false; secCount = (int)filePara.numberOfRecordedSeconds; } playing=true; number=0; QString num; // block=BUFSIZE; qDebug("Play number of samples %d", filePara.numberSamples); timeSlider->setRange(0, filePara.numberSamples); timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds); timeLabel->setText( timeString+ tr(" seconds")); if( filePara.format==WAVE_FORMAT_DVI_ADPCM) { qDebug("WAVE_FORMAT_DVI_ADPCM"); } else { qDebug("WAVE_FORMAT_PCM"); } QString msg; msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution); #ifdef DEV_VERSION setCaption( msg); #endif if( filePara.resolution == 16 ) { //AFMT_S16_LE) { qDebug("16 bit"); startTimer(1000); if( filePara.format==WAVE_FORMAT_DVI_ADPCM) { char abuf[BUFSIZE/2]; short sbuf[BUFSIZE]; short sbuf2[BUFSIZE*2]; memset( abuf, 0, BUFSIZE / 2); memset( sbuf, 0, BUFSIZE); memset( sbuf2, 0, BUFSIZE * 2); // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>> for(;;) { // play loop if (stopped) break; // stop if playing was set to false number=::read( filePara.fd, abuf, BUFSIZE/2); adpcm_decoder( abuf, sbuf, number*2, &decoder_state); // for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel // sbuf2[i+1]=sbuf2[i]=sbuf[i]; // } bytesWritten = write ( filePara.sd, sbuf, number*4); // if(filePara.channels==1) // total += bytesWritten/2; //mono // else total += bytesWritten; timeSlider->setValue( total / 4); filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / 2; timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds); // if(filePara.numberOfRecordedSeconds>1) timeLabel->setText( timeString+ tr(" seconds")); // printf("playing number %d, bytes %d, total %d\n",number, bytesWritten, total/4); // printf("playing number %d, bytes %d, total %d totalsamples %d number recorded seconds %.2f\r", // number, bytesWritten, total/4, filePara.numberSamples, filePara.numberOfRecordedSeconds); // fflush(stdout); qApp->processEvents(); if( bytesWritten <= 0 ){//|| secCount > filePara.numberOfRecordedSeconds ) { stopped = true; endPlaying(); } } } else { // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>> short inbuffer[BUFSIZE], outbuffer[BUFSIZE]; memset( inbuffer, 0, BUFSIZE); memset( outbuffer, 0, BUFSIZE); for(;;) { // play loop if (stopped) break; // stop if playing was set to false number=::read( filePara.fd, inbuffer, BUFSIZE); // for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel // // for (int i=0;i< number ; i++) { //2*i is left channel // outbuffer[i+1]= outbuffer[i]=inbuffer[i]; // } bytesWritten = ::write( filePara.sd, inbuffer, number); //-------------->>>> out to device // total+=bytesWritten; // if(filePara.channels==1) // total += bytesWritten/2; //mono // else total += bytesWritten; timeSlider->setValue( total); filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2; timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds); timeLabel->setText( timeString + tr(" seconds")); qApp->processEvents(); if( bytesWritten <= 0 && secCount > filePara.numberOfRecordedSeconds ) { stopped = true; endPlaying(); } } // printf("\nplaying number %d, bytes %d, total %d\r",number, bytesWritten, total); // fflush(stdout); } //end loop } else { /////////////////////////////// format = AFMT_U8; unsigned char unsigned_inbuffer[BUFSIZE], unsigned_outbuffer[BUFSIZE]; memset( unsigned_inbuffer,0,BUFSIZE); for(;;) { // main loop if (stopped) break; // stop if playing was set to false number=::read( filePara.fd, unsigned_inbuffer, BUFSIZE); //data = (val >> 8) ^ 0x80; // unsigned_outbuffer = (unsigned_inbuffer >> 8) ^ 0x80; bytesWritten = write ( filePara.sd, unsigned_inbuffer, number); total+=bytesWritten; timeSlider->setValue( total); filePara.numberOfRecordedSeconds=(float)total/(float)filePara.sampleRate; timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds); timeLabel->setText( timeString + tr(" seconds")); qApp->processEvents(); if( bytesWritten <= 0 && secCount > filePara.numberOfRecordedSeconds ) { stopped = true; endPlaying(); } // printf("Writing number %d, bytes %d, total %d, numberSamples %d\r",number, bytesWritten , total, filePara.numberSamples); // fflush(stdout); } } // qDebug("\nstopped or paused %d", total/4); if(!paused && !stopped) { stopped = true; // endPlaying(); endPlaying(); } return true; } void QtRec::changebitrateCombo(int i) { Config cfg("OpieRec"); cfg.setGroup("Settings"); int bits=0; if(i==0) { bits=16; } else { bits=8; } cfg.writeEntry("bitrate", bits); filePara.resolution=bits; cfg.write(); } void QtRec::changesamplerateCombo(int i) { Config cfg("OpieRec"); cfg.setGroup("Settings"); int rate=0; bool ok; rate = sampleRateComboBox->text(i).toInt(&ok, 10); cfg.writeEntry("samplerate",rate); filePara.sampleRate=rate; /* soundDevice = new Device( this, DSPSTROUT, DSPSTRMIXER, false); soundDevice->openDsp();*/ // // soundDevice->setDeviceFormat(AFMT_S16_LE); // soundDevice->setDeviceChannels(filePara.channels); // soundDevice->setDeviceRate(filePara.sampleRate); // // soundDevice->closeDevice( true); // soundDevice=0; // delete soundDevice; qDebug("Change sample rate %d", rate); cfg.write(); } void QtRec::changeDirCombo(int index) { Config cfg("OpieRec"); cfg.setGroup("Settings"); QString sName = directoryComboBox->text(index); StorageInfo storageInfo; const QList<FileSystem> &fs = storageInfo.fileSystems(); QListIterator<FileSystem> it ( fs ); QString storage; for( ; it.current(); ++it ){ if( sName == (*it)->name()+" "+ (*it)->path() || (*it)->name() == sName ) { const QString path = (*it)->path(); recDir = path; cfg.writeEntry("directory", recDir); qDebug("new rec dir "+recDir); } } cfg.write(); } void QtRec::changeSizeLimitCombo(int) { Config cfg("OpieRec"); cfg.setGroup("Settings"); cfg.writeEntry("sizeLimit", getCurrentSizeLimit() ); cfg.write(); } void QtRec::newSound() { qDebug("<<<<<<<<<new sound"); if( !rec()) { qDebug("rec() failed"); endRecording(); deleteSound(); } } void QtRec::itClick(QListViewItem *item) { currentFile=item->text(0); setCaption("OpieRecord "+currentFile); } void QtRec::deleteSound() { Config cfg("OpieRec"); cfg.setGroup("Sounds"); if( ListView1->currentItem() == NULL) return; #ifndef DEV_VERSION switch ( QMessageBox::warning(this,tr("Delete"), tr("Do you really want to <font size=+2><B>DELETE</B></font>\nthe selected file?"), tr("Yes"),tr("No"),0,1,1) ) { case 0: #endif { QString file = ListView1->currentItem()->text(0); // qDebug("Filename to find is "+file); QString fileName; fileName = cfg.readEntry( file, ""); QFile f(fileName); // qDebug("fileName is "+fileName); if(f.exists()) if( !f.remove()) QMessageBox::message(tr("Error"),tr("Could not remove file.")); int nFiles = cfg.readNumEntry("NumberofFiles",0); bool found=false; for(int i=0;i<nFiles+1;i++) { // qDebug(cfg.readEntry(QString::number(i))); if( cfg.readEntry( QString::number(i),"").find( file,0,true) != -1) { found = true; // qDebug( cfg.readEntry(QString::number(i))+"\n" +cfg.readEntry(QString::number(i+1)) ); cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),"")); } if(found) cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),"")); } cfg.removeEntry(cfg.readEntry(file)); cfg.removeEntry( file); // cfg.removeEntry( QString::number(nFiles)); cfg.writeEntry("NumberofFiles", nFiles-1); cfg.write(); ListView1->takeItem( ListView1->currentItem() ); // ListView1->takeItem( ListView1->itemAt(nFiles) ); delete ListView1->currentItem(); ListView1->clear(); ListView1->setSelected(ListView1->firstChild(), true); initIconView(); update(); } #ifndef DEV_VERSION }; #endif setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); } void QtRec::keyPressEvent( QKeyEvent *e) { switch ( e->key() ) { /* vercel keys-> right side 0 1 0x1030 Key_F1 2 0x1031 Key_F2 3 0x1032 Key_F3 4 0x1016 Key_PageUp 5 0x1017 Key_PageDown 6 --------------- left side Up 0x1013 Key_Up Down 0x1015 Key_Down Left 0x1012 Key_Left Right 0x1014 Key_Right 0x1010 Key_Home */ // case Key_F1: // if(stopped && !recording) // newSound(); // else // stop(); // break; // case Key_F2: { // if( !e->isAutoRepeat()) // rewindPressed(); // } // break; // case Key_F3: { // if( !e->isAutoRepeat()) // FastforwardPressed(); // } // break; ////////////////////////////// Zaurus keys case Key_F9: //activity break; case Key_F10: //contacts break; case Key_F11: //menu break; case Key_F12: //home break; case Key_F13: //mail break; case Key_Space: break; case Key_Delete: break; case Key_Up: // stop(); break; case Key_Down: // newSound(); break; case Key_Left: { qDebug("rewinding"); if( !e->isAutoRepeat()) rewindPressed(); } break; case Key_Right: { if( !e->isAutoRepeat()) FastforwardPressed(); } break; } } void QtRec::keyReleaseEvent( QKeyEvent *e) { switch ( e->key() ) { // case Key_F1: // if(stopped && !recording) // newSound(); // else // stop(); // break; // case Key_F2: // rewindReleased(); // break; // case Key_F3: // FastforwardReleased(); // break; ////////////////////////////// Zaurus keys case Key_F9: //activity break; case Key_F10: //contacts break; case Key_F11: //menu break; case Key_F12: //home if(stopped) doPlayBtn(); else stop(); break; case Key_F13: //mail break; case Key_Space: if(stopped && !recording) newSound(); else stop(); break; case Key_Delete: deleteSound(); break; case Key_Up: // stop(); qDebug("Up"); break; case Key_Down: // start(); // qDebug("Down"); // newSound(); break; case Key_Left: qDebug("Left"); rewindReleased(); break; case Key_Right: qDebug("Right"); FastforwardReleased(); break; } } void QtRec::endRecording() { qDebug("endRecording"); setRecordButton(false); timeSlider->setValue(0); toBeginningButton->setEnabled(true); toEndButton->setEnabled(true); monitoring=false; killTimers(); if(autoMute) doMute(true); soundDevice->closeDevice( true); recording = false; stopped=true; t->stop(); if( wavFile->track.isOpen()) { wavFile->adjustHeaders( filePara.fd, filePara.numberSamples); // soundDevice->sd=-1; filePara.numberSamples=0; // filePara.sd=-1; wavFile->closeFile(); filePara.fd=0; if(wavFile->isTempFile()) { // move tmp file to regular file QString cmd; cmd.sprintf("mv "+ wavFile->trackName() + " " + wavFile->currentFileName); qDebug("moving tmp file to "+currentFileName); system(cmd.latin1()); } qDebug("Just moved "+wavFile->currentFileName); Config cfg("OpieRec"); cfg.setGroup("Sounds"); int nFiles = cfg.readNumEntry( "NumberofFiles",0); currentFile = QFileInfo(wavFile->currentFileName).fileName(); currentFile=currentFile.left(currentFile.length()-4); cfg.writeEntry( "NumberofFiles",nFiles+1); cfg.writeEntry( QString::number( nFiles+1), currentFile); cfg.writeEntry( currentFile, wavFile->currentFileName); QString time; time.sprintf("%.2f", filePara.numberOfRecordedSeconds); cfg.writeEntry( wavFile->currentFileName, time ); qDebug("writing config numberOfRecordedSeconds "+time); cfg.write(); qDebug("finished recording"); timeLabel->setText(""); } if(soundDevice) delete soundDevice; initIconView(); selectItemByName(currentFile); } void QtRec::endPlaying() { qDebug("end playing"); setRecordButton(false); toBeginningButton->setEnabled(true); toEndButton->setEnabled(true); if(autoMute) doMute(true); soundDevice->closeDevice( false); soundDevice->sd=-1; // if(soundDevice) delete soundDevice; qDebug("file and sound device closed"); stopped=true; recording=false; playing=false; timeLabel->setText(""); monitoring=false; total = 0; filePara.numberSamples=0; filePara.sd=-1; wavFile->closeFile(); filePara.fd=0; // if(wavFile) delete wavFile; //this crashes qDebug("track closed"); timeSlider->setValue(0); if(soundDevice) delete soundDevice; } bool QtRec::openPlayFile() { qApp->processEvents(); if( currentFile.isEmpty()) { QMessageBox::message(tr("Opierec"),tr("Please select file to play")); endPlaying(); return false; } QString currentFileName; Config cfg("OpieRec"); cfg.setGroup("Sounds"); int nFiles = cfg.readNumEntry("NumberofFiles",0); for(int i=0;i<nFiles+1;i++) { //look for file if( cfg.readEntry( QString::number(i),"").find( currentFile,0,true) != -1) { currentFileName=cfg.readEntry( currentFile, "" ); qDebug("opening for play: "+currentFileName); } } wavFile = new WavFile(this, currentFileName, false); filePara.fd = wavFile->wavHandle(); if(filePara.fd == -1) { // if(!track.open(IO_ReadOnly)) { QString errorMsg=(QString)strerror(errno); monitoring=false; setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); QMessageBox::message(tr("Note"),tr("Could not open audio file.\n") +errorMsg+"\n"+currentFile); return false; } else { filePara.numberSamples=wavFile->getNumberSamples(); filePara.format = wavFile->getFormat(); // qDebug("file %d, samples %f", filePara.fd, filePara.numberSamples); filePara.sampleRate= wavFile->getSampleRate(); filePara.resolution=wavFile->getResolution(); timeSlider->setPageStep(1); monitoring=true; timeSlider->setRange(0, filePara.numberSamples ); filePara.numberOfRecordedSeconds=(float) filePara.numberSamples / (float)filePara.sampleRate * (float)2; } return true; } void QtRec::listPressed( int mouse, QListViewItem *item, const QPoint &, int ) { if(item == NULL ) return; switch (mouse) { case 1: { if( renameBox !=0 ) //tricky cancelRename(); currentFile=item->text(0); setCaption( "OpieRecord "+currentFile); } break; case 2: showListMenu(item); ListView1->clearSelection(); break; }; } void QtRec::showListMenu(QListViewItem * item) { if(item == NULL) return; QPopupMenu *m = new QPopupMenu(this); m->insertItem( tr("Play"), this, SLOT( doMenuPlay() )); if(Ir::supported()) m->insertItem( tr( "Send with Ir" ), this, SLOT( doBeam() )); m->insertItem( tr( "Rename" ), this, SLOT( doRename() )); // #if defined (QTOPIA_INTERNAL_FSLP) // m->insertItem( tr( "Properties" ), this, SLOT( doProperties() )); // #endif m->insertSeparator(); m->insertItem( tr("Delete"), this, SLOT( deleteSound() ) ); m->exec( QCursor::pos() ); qApp->processEvents(); } void QtRec::fileBeamFinished( Ir *ir) { if(ir) QMessageBox::message( tr("Ir Beam out"), tr("Ir sent.") ,tr("Ok") ); } void QtRec::doBeam() { qApp->processEvents(); if( ListView1->currentItem() == NULL) return; Ir ir; if( ir.supported()) { QString file = ListView1->currentItem()->text(0); Config cfg("OpieRec"); cfg.setGroup("Sounds"); int nFiles = cfg.readNumEntry("NumberofFiles",0); for(int i=0;i<nFiles+1;i++) { if( cfg.readEntry( QString::number(i),"").find(file,0,true) != -1) { QString filePath = cfg.readEntry(file,""); Ir *file = new Ir(this, "IR"); connect(file, SIGNAL(done(Ir*)), this, SLOT( fileBeamFinished( Ir * ))); file->send( filePath, "OPieRec audio file\n"+filePath ); } } } } void QtRec::doMenuPlay() { qApp->processEvents(); currentFile = ListView1->currentItem()->text(0); } void QtRec::doRename() { QRect r = ListView1->itemRect( ListView1->currentItem( )); r = QRect( ListView1->viewportToContents( r.topLeft() ), r.size() ); r.setX( ListView1->contentsX() ); if ( r.width() > ListView1->visibleWidth() ) r.setWidth( ListView1->visibleWidth() ); renameBox = new QLineEdit( ListView1->viewport(), "qt_renamebox" ); renameBox->setFrame(true); renameBox->setText( ListView1->currentItem()->text(0) ); renameBox->selectAll(); renameBox->installEventFilter( this ); ListView1->addChild( renameBox, r.x(), r.y() ); renameBox->resize( r.size() ); ListView1->viewport()->setFocusProxy( renameBox ); renameBox->setFocus(); renameBox->show(); } void QtRec::okRename() { qDebug("okRename"); qDebug(renameBox->text()); QString filename = renameBox->text(); cancelRename(); if( ListView1->currentItem() == NULL) return; Config cfg("OpieRec"); cfg.setGroup("Sounds"); QString file = ListView1->currentItem()->text(0); qDebug("filename is " + filename); int nFiles = cfg.readNumEntry("NumberofFiles",0); for(int i=0;i<nFiles+1;i++) { //look for file if( cfg.readEntry( QString::number(i),"").find(file,0,true) != -1) { QString filePath = cfg.readEntry(file,""); cfg.writeEntry( QString::number(i), filename ); cfg.writeEntry( filename, filePath ); cfg.removeEntry(file); cfg.write(); } } ListView1->takeItem( ListView1->currentItem() ); delete ListView1->currentItem(); ListView1->clear(); initIconView(); update(); } void QtRec::cancelRename() { qDebug("cancel rename"); bool resetFocus = ListView1->viewport()->focusProxy() == renameBox; delete renameBox; renameBox = 0; if ( resetFocus ) { ListView1->viewport()->setFocusProxy( ListView1 ); ListView1->setFocus(); } } bool QtRec::eventFilter( QObject * o, QEvent * e ) { if ( o->inherits( "QLineEdit" ) ) { if ( e->type() == QEvent::KeyPress ) { QKeyEvent *ke = (QKeyEvent*)e; if ( ke->key() == Key_Return || ke->key() == Key_Enter ) { okRename(); return true; } else if ( ke->key() == Key_Escape ) { cancelRename(); return true; } } else if ( e->type() == QEvent::FocusOut ) { cancelRename(); return true; } } return QWidget::eventFilter( o, e ); } int QtRec::getCurrentSizeLimit() { return sizeLimitCombo->currentItem() * 5; } void QtRec::timerBreak() { qDebug("timer break"); stop(); } void QtRec::doVolMuting(bool b) { Config cfg( "qpe" ); cfg. setGroup( "Volume" ); cfg.writeEntry( "Mute",b); cfg.write(); QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << b; } void QtRec::doMicMuting(bool b) { // qDebug("mic mute"); Config cfg( "qpe" ); cfg. setGroup( "Volume" ); cfg.writeEntry( "MicMute",b); cfg.write(); QCopEnvelope( "QPE/System", "micChange(bool)" ) << b; } void QtRec::compressionSelected(bool b) { Config cfg("OpieRec"); cfg.setGroup("Settings"); cfg.writeEntry("wavCompression", b); cfg.writeEntry("bitrate",16); filePara.resolution=16; cfg.write(); if(b) { bitRateComboBox->setEnabled(false); bitRateComboBox->setCurrentItem(0); filePara.resolution=16; } else{ bitRateComboBox->setEnabled(true); } } long QtRec::checkDiskSpace(const QString &path) { struct statfs fs; if ( !statfs( path.latin1(), &fs ) ) { int blkSize = fs.f_bsize; int availBlks = fs.f_bavail; long mult = blkSize / 1024; long div = 1024 / blkSize; if ( !mult ) mult = 1; if ( !div ) div = 1; return availBlks * mult / div; } return -1; } // short f_fstyp; /* File system type */ // long f_bsize; /* Block size */ // long f_frsize; /* Fragment size */ // long f_blocks; /* Total number of blocks*/ // long f_bfree; /* Count of free blocks */ // long f_files; /* Total number of file nodes */ // long f_ffree; /* Count of free file nodes */ // char f_fname[6]; /* Volumename */ // char f_fpack[6]; /* Pack name */ void QtRec::receive( const QCString &msg, const QByteArray & ) { qDebug("Voicerecord received message "+msg); } ///////////////////////////// timerEvent void QtRec::timerEvent( QTimerEvent *e ) { // qDebug( "%d", secCount ); #ifdef DEV_VERSION QString msg; msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution); setCaption( msg +" :: "+QString::number(secCount)); #endif if( !playing ) { if(!recording ){ killTimer(e->timerId()); ///* stopped=true; // recording=false; ///*/ // _exit( 0); } if(filePara.SecondsToRecord < secCount && filePara.SecondsToRecord !=0) { killTimer(e->timerId()); stop(); } } // if( stopped && !paused) { // if( filePara.numberOfRecordedSeconds < secCount) { // stopped = true; // // playing=false; // killTimer(e->timerId()); // endPlaying(); // } // } // qApp->processEvents(); secCount++; } void QtRec::changeTimeSlider(int index) { if(ListView1->currentItem() == 0 || !wavFile->track.isOpen()) return; // qDebug("Slider moved to %d",index); paused = true; stopped = true; sliderPos=index; QString timeString; filePara.numberOfRecordedSeconds=(float)sliderPos/(float)filePara.sampleRate*(float)2; timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); secCount = (int)filePara.numberOfRecordedSeconds; timeLabel->setText( timeString+ tr(" seconds")); } void QtRec::timeSliderPressed() { if(ListView1->currentItem() == 0) return; // qDebug("slider pressed"); paused = true; stopped = true; } void QtRec::timeSliderReleased() { if(ListView1->currentItem() == 0) return; sliderPos=timeSlider->value(); // qDebug("slider released %d", sliderPos); stopped = false; int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); total = newPos*4; filePara.numberOfRecordedSeconds=(float)sliderPos/(float)filePara.sampleRate*(float)2; doPlay(); } void QtRec::rewindPressed() { if(ListView1->currentItem() == 0) return; if( !wavFile->track.isOpen()) { if( !openPlayFile() ) return; else if( !setupAudio( false)) return; } else { killTimers(); paused = true; stopped = true; rewindTimer->start(50, false); } } void QtRec::rewindTimerTimeout() { int sliderValue = timeSlider->value(); sliderValue = sliderValue-(filePara.numberSamples/100); // if(toBeginningButton->isDown()) timeSlider->setValue( sliderValue ) ; // qDebug("%d", sliderValue); QString timeString; filePara.numberOfRecordedSeconds=(float)sliderValue/(float)filePara.sampleRate*(float)2; timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); timeLabel->setText( timeString+ tr(" seconds")); } void QtRec::rewindReleased() { rewindTimer->stop(); if( wavFile->track.isOpen()) { sliderPos=timeSlider->value(); stopped = false; int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); total = newPos*4; // qDebug("rewind released %d", total); startTimer(1000); doPlay(); } } void QtRec::FastforwardPressed() { if(ListView1->currentItem() == 0) return; if( !wavFile->track.isOpen()) if( !openPlayFile() ) return; else if( !setupAudio( false)) return; killTimers(); paused = true; stopped = true; forwardTimer->start(50, false); } void QtRec::forwardTimerTimeout() { int sliderValue = timeSlider->value(); sliderValue = sliderValue +(filePara.numberSamples/100); // if(toEndButton->isDown()) timeSlider->setValue(sliderValue); QString timeString; filePara.numberOfRecordedSeconds=(float)sliderValue/(float)filePara.sampleRate*(float)2; timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); timeLabel->setText( timeString+ tr(" seconds")); } void QtRec::FastforwardReleased() { forwardTimer->stop(); if( wavFile->track.isOpen()) { sliderPos=timeSlider->value(); stopped = false; int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); total = newPos*4; filePara.numberOfRecordedSeconds=(float)sliderPos/(float)filePara.sampleRate*(float)2; startTimer(1000); doPlay(); } } QString QtRec::getStorage(const QString &fileName) { StorageInfo storageInfo; const QList<FileSystem> &fs = storageInfo.fileSystems(); QListIterator<FileSystem> it ( fs ); QString storage; for( ; it.current(); ++it ){ const QString name = (*it)->name(); const QString path = (*it)->path(); const QString disk = (*it)->disk(); if( fileName.find(path,0,true) != -1) storage=name; // const QString options = (*it)->options(); // if( name.find( tr("Internal"),0,true) == -1) { // storageComboBox->insertItem( name +" -> "+disk); // qDebug(name); } return storage; // struct mntent *me; // // if(fileName == "/etc/mtab") { // FILE *mntfp = setmntent( fileName.latin1(), "r" ); // if ( mntfp ) { // while ( (me = getmntent( mntfp )) != 0 ) { // QString filesystemType = me->mnt_type; // } // } // endmntent( mntfp ); } void QtRec::setRecordButton(bool b) { if(b) { //about to record or play Rec_PushButton->setDown(true); QPixmap image3( ( const char** ) image3_data ); Stop_PushButton->setPixmap( image3 ); if(Stop_PushButton->isDown()) Stop_PushButton->setDown(true); - playLabel2->setText("Stop"); + playLabel2->setText(tr("Stop") ); } else { //about to stop QPixmap image4( ( const char** ) image4_data ); Stop_PushButton->setPixmap( image4); if(Stop_PushButton->isDown()) Stop_PushButton->setDown(false); - playLabel2->setText("Play"); + playLabel2->setText(tr("Play") ); if(Rec_PushButton->isDown()) Rec_PushButton->setDown( false); } } void QtRec::fillDirectoryCombo() { if( directoryComboBox->count() > 0) directoryComboBox->clear(); int index=0; Config cfg("OpieRec"); cfg.setGroup("Settings"); QString dir= cfg.readEntry("directory", "/"); StorageInfo storageInfo; const QList<FileSystem> &fs = storageInfo.fileSystems(); QListIterator<FileSystem> it ( fs ); QString storage; for( ; it.current(); ++it ){ const QString name = (*it)->name(); const QString path = (*it)->path(); // directoryComboBox->insertItem(name+" "+path); directoryComboBox->insertItem(name); if(path==dir) directoryComboBox->setCurrentItem(index); index++; } } void QtRec::errorStop() { stopped = true; wavFile->closeFile(); killTimers(); } void QtRec::doMute(bool b) { doVolMuting( b); doMicMuting( b); } void QtRec::slotAutoMute(bool b) { autoMute=b; Config cfg("OpieRec"); cfg.setGroup("Settings"); cfg.writeEntry("useAutoMute",b); doMute(b); outMuteCheckBox->setChecked( b); inMuteCheckBox->setChecked( b); } void QtRec::selectItemByName(const QString & name) { QListViewItemIterator it( ListView1 ); for ( ; it.current(); ++it ) if(name == it.current()->text(0)) ListView1->setCurrentItem(it.current()); } long findPeak(long input ) { // halfLife = time in seconds for output to decay to half value after an impulse static float output = 0.0; int halfLife = .25; float vsf = .0025; float scalar = pow( 0.5, 1.0/(halfLife * filePara.sampleRate )); if( input < 0.0 ) input = -input; // Absolute value. if ( input >= output ) { // When we hit a peak, ride the peak to the top. output = input; } else { // Exponential decay of output when signal is low. output = output * scalar; // // When current gets close to 0.0, set current to 0.0 to prevent FP underflow // which can cause a severe performance degradation due to a flood // of interrupts. // if( output < vsf ) output = 0.0; } return output; } diff --git a/noncore/multimedia/showimg/opie-showimg.control b/noncore/multimedia/showimg/opie-showimg.control index 9dacd94..c543335 100644 --- a/noncore/multimedia/showimg/opie-showimg.control +++ b/noncore/multimedia/showimg/opie-showimg.control @@ -1,11 +1,11 @@ Package: opie-showimg Files: bin/showimg apps/Applications/showimg.desktop pics/imageviewer Priority: optional Section: opie/applications Maintainer: Warwick Allison <warwick@trolltech.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Image Viewer The image viewer for the Opie environment. Supports Whichever formats are compiled into Qt/Embedded (eg. PNG). +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/net/ftplib/ftplib.control b/noncore/net/ftplib/ftplib.control index 3dcb02a..918bcd2 100644 --- a/noncore/net/ftplib/ftplib.control +++ b/noncore/net/ftplib/ftplib.control @@ -1,10 +1,10 @@ Package: ftplib Files: $OPIEDIR/lib/libftplib.* Priority: optional Section: Communications Maintainer: L.J. Potter <ljp@llornkcor.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal Description: Libftp The ftp library for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/net/mailit/opie-mailit.control b/noncore/net/mailit/opie-mailit.control index 65b5b36..77d4102 100644 --- a/noncore/net/mailit/opie-mailit.control +++ b/noncore/net/mailit/opie-mailit.control @@ -1,9 +1,9 @@ Package: opie-mailit Files: bin/mailit apps/1Pim/mailit.desktop pics/mailit Priority: optional Section: opie Maintainer: L.J. Potter <llornkcor@handhelds.org> Architecture: arm -Version: $OPIE_VERSION-$SUB_VERSION +Version: $QPE_VERSION$EXTRAVERSION Description: EMail A simple POP3 email client for the Opie environment. diff --git a/noncore/net/opieftp/opie-ftp.control b/noncore/net/opieftp/opie-ftp.control index 090e9a8..1e82523 100644 --- a/noncore/net/opieftp/opie-ftp.control +++ b/noncore/net/opieftp/opie-ftp.control @@ -1,11 +1,11 @@ Package: opie-ftp Files: bin/opieftp pics/opieftp apps/Applications/opieftp.desktop Priority: optional Section: Communications Maintainer: L.J. Potter <ljp@llornkcor.com> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal, ftplib Replaces: opieftp Description: Opie-Ftp The ftp client for the Opie environment. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/net/opieirc/opie-irc.control b/noncore/net/opieirc/opie-irc.control index f1e6ff8..51a8049 100644 --- a/noncore/net/opieirc/opie-irc.control +++ b/noncore/net/opieirc/opie-irc.control @@ -1,9 +1,9 @@ Package: opie-irc Files: bin/opieirc pics/opieirc apps/Applications/opieirc.desktop help/en/html/opieirc.html help/en/html/opieirc Priority: optional Section: Communications Maintainer: Wenzel Jakob <root@wazlaf.de> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal, libopie1 Description: The Opie IRC client lets you chat on your favorite IRC server using your handheld computer +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/net/opietooth/applet/opie-bluetoothapplet.control b/noncore/net/opietooth/applet/opie-bluetoothapplet.control index b9bd63c..55b9ab0 100644 --- a/noncore/net/opietooth/applet/opie-bluetoothapplet.control +++ b/noncore/net/opietooth/applet/opie-bluetoothapplet.control @@ -1,10 +1,10 @@ Package: opie-bluetoothapplet Files: plugins/applets/libbluetoothapplet.so* pics/bluetoothapplet/* Priority: optional Section: opie/system Maintainer: Maximilian Reiss <max.reiss@gmx.de> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION.1 Depends: task-opie-minimal, libopietooth1 Description: Bluetooth Applet An bluetooth taskbar applet for the Opie environment +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/net/opietooth/lib/libopietooth1.control b/noncore/net/opietooth/lib/libopietooth1.control index 041c9d5..850f0dc 100644 --- a/noncore/net/opietooth/lib/libopietooth1.control +++ b/noncore/net/opietooth/lib/libopietooth1.control @@ -1,10 +1,10 @@ Package: libopietooth1 Files: $OPIEDIR/lib/libopietooth.so.1.0.0 $OPIEDIR/lib/libopietooth.so.1.0 $OPIEDIR/lib/libopietooth.so.1 Priority: optional Section: opie/system Maintainer: Maximilian Reiß <max.reiss@gmx.de> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Replaces: libopietooth Depends: libqte2 (>=2.3.4), libopie, task-bluez Description: Opie bluetooth library +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/unsupported/gsmtool/gsmtool.pro b/noncore/unsupported/gsmtool/gsmtool.pro index 180195f..40d5942 100644 --- a/noncore/unsupported/gsmtool/gsmtool.pro +++ b/noncore/unsupported/gsmtool/gsmtool.pro @@ -1,36 +1,36 @@ TEMPLATE = app #CONFIG = qt warn_on debug CONFIG = qt warn_on release DESTDIR = $(OPIEDIR)/bin HEADERS = gsmtool.h SOURCES = main.cpp gsmtool.cpp # This doesn't actually work... TMAKE_CXXFLAGS += -fexceptions INCLUDEPATH += $(OPIEDIR)/include -INCLUDEPATH += $(GSMLIBDIR) +#INCLUDEPATH += $(GSMLIBDIR) DEPENDPATH += $(OPIEDIR)/include LIBS += -lqpe -L$(GSMLIBDIR)/gsmlib/.libs -lgsmme INTERFACES = gsmtoolbase.ui TARGET = gsmtool TRANSLATIONS = ../../../i18n/de/gsmtool.ts \ ../../../i18n/nl/gsmtool.ts \ ../../../i18n/da/gsmtool.ts \ ../../../i18n/xx/gsmtool.ts \ ../../../i18n/en/gsmtool.ts \ ../../../i18n/es/gsmtool.ts \ ../../../i18n/fr/gsmtool.ts \ ../../../i18n/hu/gsmtool.ts \ ../../../i18n/ja/gsmtool.ts \ ../../../i18n/ko/gsmtool.ts \ ../../../i18n/no/gsmtool.ts \ ../../../i18n/pl/gsmtool.ts \ ../../../i18n/pt/gsmtool.ts \ ../../../i18n/pt_BR/gsmtool.ts \ ../../../i18n/sl/gsmtool.ts \ ../../../i18n/zh_CN/gsmtool.ts \ ../../../i18n/zh_TW/gsmtool.ts include ( $(OPIEDIR)/include.pro ) diff --git a/noncore/unsupported/mail2/addresspicker.cpp b/noncore/unsupported/mail2/addresspicker.cpp index 7f32725..a97b33f 100644 --- a/noncore/unsupported/mail2/addresspicker.cpp +++ b/noncore/unsupported/mail2/addresspicker.cpp @@ -1,117 +1,118 @@ #include <qpushbutton.h> #include <qmessagebox.h> #include <qtextstream.h> #include <qlistbox.h> #include <qfile.h> #include <qpe/resource.h> #include <stdlib.h> #include "addresspicker.h" AddressPicker::AddressPicker(QWidget *parent, const char *name, bool modal, WFlags fl) : AddressPickerBase(parent, name, modal, fl) { okButton->setIconSet(Resource::loadPixmap("enter")); cancelButton->setIconSet(Resource::loadPixmap("editdelete")); connect(okButton, SIGNAL(clicked()), SLOT(accept())); connect(cancelButton, SIGNAL(clicked()), SLOT(close())); QFile f((QString) getenv("HOME") + "/Applications/" + "addressbook/addressbook.xml"); if (f.open(IO_ReadOnly)) { QTextStream stream(&f); + stream.setEncoding( QTextStream::UnicodeUTF8 ); QString content; while (!f.atEnd()) content += stream.readLine() + "\n"; QStringList lines = QStringList::split(QRegExp("\\n"), content); QStringList::Iterator it; for (it = lines.begin(); it != lines.end(); it++) { if ((*it).find(QRegExp("^<Contact.*")) != -1) { int pos = (*it).find("FirstName=\""); QString fname; if (pos != -1) { int i = 1; QChar c; while (c != '"') { c = (*it)[pos + 10 + i]; if (c != '"') fname += c; i++; } } pos = (*it).find("LastName=\""); QString lname; if (pos != -1) { int i = 1; QChar c; while (c != '"') { c = (*it)[pos + 9 + i]; if (c != '"') lname += c; i++; } } pos = (*it).find("DefaultEmail=\""); QString email; if (pos != -1) { int i = 1; QChar c; while (c != '"') { c = (*it)[pos + 13 + i]; if (c != '"') email += c; i++; } } QString tname, temail; if (!fname.isEmpty()) tname += fname; if (!lname.isEmpty()) tname += fname.isEmpty() ? lname : (" " + lname); if (!email.isEmpty()) temail += tname.isEmpty() ? email : (" <" + email + ">"); if (!email.isEmpty()) addressList->insertItem(tname + temail); } } } if (addressList->count() <= 0) { addressList->insertItem(tr("There are no entries in the addressbook.")); addressList->setEnabled(false); okButton->setEnabled(false); } } void AddressPicker::accept() { QListBoxItem *item = addressList->firstItem(); QString names; while (item) { if (item->selected()) names += item->text() + ", "; item = item->next(); } names.replace(names.length() - 2, 2, ""); if (names.isEmpty()) { QMessageBox::information(this, tr("Error"), tr("<p>You have to select" " at least one address entry.</p>"), tr("Ok")); return; } selectedNames = names; QDialog::accept(); } QString AddressPicker::getNames() { QString names = 0; AddressPicker picker(0, 0, true); picker.showMaximized(); picker.show(); int ret = picker.exec(); if (QDialog::Accepted == ret) { return picker.selectedNames; } return 0; } diff --git a/noncore/unsupported/mail2/bend/opie-mailapplet.control b/noncore/unsupported/mail2/bend/opie-mailapplet.control index e5d3c6e..d618643 100644 --- a/noncore/unsupported/mail2/bend/opie-mailapplet.control +++ b/noncore/unsupported/mail2/bend/opie-mailapplet.control @@ -1,10 +1,10 @@ Package: opie-mailapplet Files: plugins/applets/libbend.so* Priority: optional Section: opie/applications Maintainer: Constantin Bergemann <cbergemann@lisa.de> Architecture: arm -Version: 0.0.9-$SUB_VERSION -Depends: task-opie-minimal libopie1 opie-mail2 +Version: $QPE_VERSION$EXTRAVERSION +Depends: task-opie-minimal, libopie1, opie-mail2 Description: A Biff-Like mailchecker License: LGPL diff --git a/noncore/unsupported/mail2/opie-mail2.control b/noncore/unsupported/mail2/opie-mail2.control index 7f8aeb6..976dc0b 100644 --- a/noncore/unsupported/mail2/opie-mail2.control +++ b/noncore/unsupported/mail2/opie-mail2.control @@ -1,10 +1,10 @@ Package: opie-mail2 Files: bin/mail $OPIEDIR/lib/libmail.so* apps/1Pim/mail.desktop pics/mail/*.png sounds/mail/*.wav Priority: optional Section: opie/applications Maintainer: Constantin Bergemann <cbergemann@lisa.de> Architecture: arm -Version: 0.0.9-$SUB_VERSION +Version: $QPE_VERSION$EXTRAVERSION Depends: task-opie-minimal, libopie1 Description: An IMAP mail client License: LGPL diff --git a/noncore/unsupported/mailit/opie-mailit.control b/noncore/unsupported/mailit/opie-mailit.control index 65b5b36..77d4102 100644 --- a/noncore/unsupported/mailit/opie-mailit.control +++ b/noncore/unsupported/mailit/opie-mailit.control @@ -1,9 +1,9 @@ Package: opie-mailit Files: bin/mailit apps/1Pim/mailit.desktop pics/mailit Priority: optional Section: opie Maintainer: L.J. Potter <llornkcor@handhelds.org> Architecture: arm -Version: $OPIE_VERSION-$SUB_VERSION +Version: $QPE_VERSION$EXTRAVERSION Description: EMail A simple POP3 email client for the Opie environment. diff --git a/noncore/unsupported/qpdf/QOutputDev.cpp b/noncore/unsupported/qpdf/QOutputDev.cpp index 52237f5..022d938 100644 --- a/noncore/unsupported/qpdf/QOutputDev.cpp +++ b/noncore/unsupported/qpdf/QOutputDev.cpp @@ -1,1040 +1,1053 @@ ///======================================================================== // // QOutputDev.cc // // Copyright 1996 Derek B. Noonburg // CopyRight 2002 Robert Griebl // //======================================================================== #ifdef __GNUC__ #pragma implementation #endif #include <aconf.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <unistd.h> #include <string.h> #include <ctype.h> #include <math.h> #include <iostream> #include "GString.h" #include "Object.h" #include "Stream.h" #include "Link.h" #include "GfxState.h" #include "GfxFont.h" #include "UnicodeMap.h" #include "CharCodeToUnicode.h" #include "FontFile.h" #include "Error.h" #include "TextOutputDev.h" #include "QOutputDev.h" #include <qpixmap.h> #include <qimage.h> #include <qpainter.h> #include <qdict.h> #include <qtimer.h> #include <qapplication.h> #include <qclipboard.h> //#define QPDFDBG(x) x // special debug mode #define QPDFDBG(x) // normal compilation //------------------------------------------------------------------------ // Constants and macros //------------------------------------------------------------------------ static inline QColor q_col ( const GfxRGB &rgb ) { return QColor ( lrint ( rgb. r * 255 ), lrint ( rgb. g * 255 ), lrint ( rgb. b * 255 )); } //------------------------------------------------------------------------ // Font substitutions //------------------------------------------------------------------------ struct QOutFontSubst { char * m_name; char * m_sname; bool m_bold; bool m_italic; QFont::StyleHint m_hint; }; static QOutFontSubst qStdFonts [] = { { "Helvetica", "Helvetica", false, false, QFont::Helvetica }, { "Helvetica-Oblique", "Helvetica", false, true, QFont::Helvetica }, { "Helvetica-Bold", "Helvetica", true, false, QFont::Helvetica }, { "Helvetica-BoldOblique", "Helvetica", true, true, QFont::Helvetica }, { "Times-Roman", "Times", false, false, QFont::Times }, { "Times-Italic", "Times", false, true, QFont::Times }, { "Times-Bold", "Times", true, false, QFont::Times }, { "Times-BoldItalic", "Times", true, true, QFont::Times }, { "Courier", "Courier", false, false, QFont::Courier }, { "Courier-Oblique", "Courier", false, true, QFont::Courier }, { "Courier-Bold", "Courier", true, false, QFont::Courier }, { "Courier-BoldOblique", "Courier", true, true, QFont::Courier }, { "Symbol", 0, false, false, QFont::AnyStyle }, { "Zapf-Dingbats", 0, false, false, QFont::AnyStyle }, { 0, 0, false, false, QFont::AnyStyle } }; QFont QOutputDev::matchFont ( GfxFont *gfxFont, fp_t m11, fp_t m12, fp_t m21, fp_t m22 ) { static QDict<QOutFontSubst> stdfonts; // build dict for std. fonts on first invocation if ( stdfonts. isEmpty ( )) { for ( QOutFontSubst *ptr = qStdFonts; ptr-> m_name; ptr++ ) { stdfonts. insert ( QString ( ptr-> m_name ), ptr ); } } // compute size and normalized transform matrix int size = lrint ( sqrt ( m21 * m21 + m22 * m22 )); QPDFDBG( printf ( "SET FONT: Name=%s, Size=%d, Bold=%d, Italic=%d, Mono=%d, Serif=%d, Symbol=%d, CID=%d, EmbFN=%s, M=(%f,%f,%f,%f)\n", (( gfxFont-> getName ( )) ? gfxFont-> getName ( )-> getCString ( ) : "<n/a>" ), size, gfxFont-> isBold ( ), gfxFont-> isItalic ( ), gfxFont-> isFixedWidth ( ), gfxFont-> isSerif ( ), gfxFont-> isSymbolic ( ), gfxFont-> isCIDFont ( ), - ( gfxFont-> getEmbeddedFontName ( ) ? gfxFont-> getEmbeddedFontName ( ) : "<n/a>" ), + ( gfxFont-> getEmbeddedFontName ( ) ? gfxFont-> getEmbeddedFontName()-> getCString ( ) : "<n/a>" ), (double) m11, (double) m12, (double) m21, (double) m22 )); QString fname (( gfxFont-> getName ( )) ? gfxFont-> getName ( )-> getCString ( ) : "<n/a>" ); QFont f; f. setPixelSize ( size > 0 ? size : 8 ); // type3 fonts misbehave sometimes // fast lookup for std. fonts QOutFontSubst *subst = stdfonts [fname]; if ( subst ) { if ( subst-> m_sname ) f. setFamily ( subst-> m_sname ); f. setStyleHint ( subst-> m_hint, (QFont::StyleStrategy) ( QFont::PreferOutline | QFont::PreferQuality )); f. setBold ( subst-> m_bold ); f. setItalic ( subst-> m_italic ); } else { QFont::StyleHint sty; if ( gfxFont-> isSerif ( )) sty = QFont::Serif; else if ( gfxFont-> isFixedWidth ( )) sty = QFont::TypeWriter; else sty = QFont::Helvetica; f. setStyleHint ( sty, (QFont::StyleStrategy) ( QFont::PreferOutline | QFont::PreferQuality )); f. setBold ( gfxFont-> isBold ( ) > 0 ); f. setItalic ( gfxFont-> isItalic ( ) > 0 ); f. setFixedPitch ( gfxFont-> isFixedWidth ( ) > 0 ); // common specifiers in font names if ( fname. contains ( "Oblique" ) || fname. contains ( "Italic" )) f. setItalic ( true ); if ( fname. contains ( "Bold" )) f. setWeight ( QFont::Bold ); if ( fname. contains ( "Demi" )) f. setWeight ( QFont::DemiBold ); if ( fname. contains ( "Light" )) f. setWeight ( QFont::Light ); if ( fname. contains ( "Black" )) f. setWeight ( QFont::Black ); } // Treat x-sheared fonts as italic if (( m12 > -0.1 ) && ( m12 < 0.1 ) && ((( m21 > -5.0 ) && ( m21 < -0.1 )) || (( m21 > 0.1 ) && ( m21 < 5.0 )))) { f. setItalic ( true ); } return f; } //------------------------------------------------------------------------ // QOutputDev //------------------------------------------------------------------------ QOutputDev::QOutputDev ( QWidget *parent, const char *name, int flags ) : QScrollView ( parent, name, WRepaintNoErase | WResizeNoErase | flags ) { m_pixmap = 0; m_painter = 0; // create text object m_text = new TextPage ( gFalse ); } QOutputDev::~QOutputDev ( ) { delete m_painter; delete m_pixmap; delete m_text; } void QOutputDev::startPage ( int /*pageNum*/, GfxState *state ) { delete m_pixmap; delete m_painter; m_pixmap = new QPixmap ( lrint ( state-> getPageWidth ( )), lrint ( state-> getPageHeight ( ))); m_painter = new QPainter ( m_pixmap ); QPDFDBG( printf ( "NEW PIXMAP (%ld x %ld)\n", lrint ( state-> getPageWidth ( )), lrint ( state-> getPageHeight ( )))); resizeContents ( m_pixmap-> width ( ), m_pixmap-> height ( )); setContentsPos ( 0, 0 ); m_pixmap-> fill ( white ); // clear window m_text-> clear ( ); // cleat text object viewport ( )-> repaint ( ); } void QOutputDev::endPage ( ) { + QPDFDBG( printf("End page\n") ); m_text-> coalesce ( ); + /* + * I get stupid crashes after endPage is called and then we do clipping + * and other stuff..... + */ +#if 0 delete m_painter; m_painter = 0; +#endif updateContents ( 0, 0, contentsWidth ( ), contentsHeight ( )); } void QOutputDev::drawLink ( Link *link, Catalog */*catalog*/ ) { fp_t x1, y1, x2, y2, w; link-> getBorder ( &x1, &y1, &x2, &y2, &w ); if ( w > 0 ) { int x, y, dx, dy; cvtUserToDev ( x1, y1, &x, &y ); cvtUserToDev ( x2, y2, &dx, &dy ); QPen oldpen = m_painter-> pen ( ); m_painter-> setPen ( blue ); m_painter-> drawRect ( x, y, dx, dy ); m_painter-> setPen ( oldpen ); } } void QOutputDev::saveState ( GfxState */*state*/ ) { + if ( ! m_painter ) + return; + QPDFDBG( printf ( "SAVE (CLIP=%d/%d)\n", m_painter-> hasClipping ( ), !m_painter-> clipRegion ( ). isEmpty ( ))); m_painter-> save ( ); } void QOutputDev::restoreState ( GfxState */*state*/ ) { + if( ! m_painter ) + return; + m_painter-> restore ( ); // m_painter-> setClipRegion ( QRect ( 0, 0, m_pixmap-> width ( ), m_pixmap-> height ( ))); // m_painter-> setClipping ( false ); QPDFDBG ( printf ( "RESTORE (CLIP=%d/%d)\n", m_painter-> hasClipping ( ), !m_painter-> clipRegion ( ). isEmpty ( ))); } void QOutputDev::updateAll ( GfxState *state ) { updateLineAttrs ( state, gTrue ); // updateFlatness ( state ); // updateMiterLimit ( state ); updateFillColor ( state ); updateStrokeColor ( state ); updateFont ( state ); } void QOutputDev::updateCTM ( GfxState *state, fp_t /*m11*/, fp_t /*m12*/, fp_t /*m21*/, fp_t /*m22*/, fp_t /*m31*/, fp_t /*m32*/ ) { updateLineAttrs ( state, gTrue ); } void QOutputDev::updateLineDash ( GfxState *state ) { updateLineAttrs ( state, gTrue ); } void QOutputDev::updateFlatness ( GfxState */*state*/ ) { // not supported QPDFDBG( printf ( "updateFlatness not supported !\n" )); } void QOutputDev::updateLineJoin ( GfxState *state ) { updateLineAttrs ( state, gFalse ); } void QOutputDev::updateLineCap ( GfxState *state ) { updateLineAttrs ( state, gFalse ); } // unimplemented void QOutputDev::updateMiterLimit ( GfxState */*state*/ ) { QPDFDBG( printf ( "updateMiterLimit not supported !\n" )); } void QOutputDev::updateLineWidth ( GfxState *state ) { updateLineAttrs ( state, gFalse ); } void QOutputDev::updateLineAttrs ( GfxState *state, GBool updateDash ) { fp_t *dashPattern; int dashLength; fp_t dashStart; Qt::PenCapStyle cap; Qt::PenJoinStyle join; int width; width = lrint ( state-> getTransformedLineWidth ( )); switch ( state-> getLineCap ( )) { case 0: cap = FlatCap; break; case 1: cap = RoundCap; break; case 2: cap = SquareCap; break; default: qWarning ( "Bad line cap style (%d)\n", state-> getLineCap ( )); cap = FlatCap; break; } switch (state->getLineJoin()) { case 0: join = MiterJoin; break; case 1: join = RoundJoin; break; case 2: join = BevelJoin; break; default: qWarning ( "Bad line join style (%d)\n", state->getLineJoin ( )); join = MiterJoin; break; } state-> getLineDash ( &dashPattern, &dashLength, &dashStart ); QColor oldcol = m_painter-> pen ( ). color ( ); GfxRGB rgb; state-> getStrokeRGB ( &rgb ); oldcol = q_col ( rgb ); m_painter-> setPen ( QPen ( oldcol, width, dashLength > 0 ? DashLine : SolidLine, cap, join )); if ( updateDash && ( dashLength > 0 )) { // Not supported by QT /* char dashList[20]; if (dashLength > 20) dashLength = 20; for ( int i = 0; i < dashLength; ++i ) { dashList[i] = xoutRound(state->transformWidth(dashPattern[i])); if (dashList[i] == 0) dashList[i] = 1; } XSetDashes(display, strokeGC, xoutRound(dashStart), dashList, dashLength); */ } } void QOutputDev::updateFillColor ( GfxState *state ) { GfxRGB rgb; state-> getFillRGB ( &rgb ); m_painter-> setBrush ( q_col ( rgb )); } void QOutputDev::updateStrokeColor ( GfxState *state ) { GfxRGB rgb; state-> getStrokeRGB ( &rgb ); QPen pen = m_painter-> pen ( ); pen. setColor ( q_col ( rgb )); m_painter-> setPen ( pen ); } void QOutputDev::updateFont ( GfxState *state ) { fp_t m11, m12, m21, m22; GfxFont *gfxFont = state-> getFont ( ); if ( !gfxFont ) return; state-> getFontTransMat ( &m11, &m12, &m21, &m22 ); m11 *= state-> getHorizScaling ( ); m12 *= state-> getHorizScaling ( ); QFont font = matchFont ( gfxFont, m11, m12, m21, m22 ); m_painter-> setFont ( font ); m_text-> updateFont ( state ); } void QOutputDev::stroke ( GfxState *state ) { QPointArray points; QArray<int> lengths; // transform points int n = convertPath ( state, points, lengths ); QPDFDBG( printf ( "DRAWING: %d POLYS\n", n )); // draw each subpath int j = 0; for ( int i = 0; i < n; i++ ) { int len = lengths [i]; if ( len >= 2 ) { QPDFDBG( printf ( " - POLY %d: ", i )); QPDFDBG( for ( int ii = 0; ii < len; ii++ )) QPDFDBG( printf ( "(%d/%d) ", points [j+ii]. x ( ), points [j+ii]. y ( ))); QPDFDBG( printf ( "\n" )); m_painter-> drawPolyline ( points, j, len ); } j += len; } qApp-> processEvents ( ); } void QOutputDev::fill ( GfxState *state ) { doFill ( state, true ); } void QOutputDev::eoFill ( GfxState *state ) { doFill ( state, false ); } // // X doesn't color the pixels on the right-most and bottom-most // borders of a polygon. This means that one-pixel-thick polygons // are not colored at all. I think this is supposed to be a // feature, but I can't figure out why. So after it fills a // polygon, it also draws lines around the border. This is done // only for single-component polygons, since it's not very // compatible with the compound polygon kludge (see convertPath()). // void QOutputDev::doFill ( GfxState *state, bool winding ) { QPointArray points; QArray<int> lengths; // transform points int n = convertPath ( state, points, lengths ); QPDFDBG( printf ( "FILLING: %d POLYS\n", n )); QPen oldpen = m_painter-> pen ( ); m_painter-> setPen ( QPen ( NoPen )); // draw each subpath int j = 0; for ( int i = 0; i < n; i++ ) { int len = lengths [i]; if ( len >= 3 ) { QPDFDBG( printf ( " - POLY %d: ", i )); QPDFDBG( for ( int ii = 0; ii < len; ii++ )) QPDFDBG( printf ( "(%d/%d) ", points [j+ii]. x ( ), points [j+ii]. y ( ))); QPDFDBG( printf ( "\n" )); m_painter-> drawPolygon ( points, winding, j, len ); } j += len; } m_painter-> setPen ( oldpen ); qApp-> processEvents ( ); } void QOutputDev::clip ( GfxState *state ) { doClip ( state, true ); } void QOutputDev::eoClip ( GfxState *state ) { doClip ( state, false ); } void QOutputDev::doClip ( GfxState *state, bool winding ) { QPointArray points; QArray<int> lengths; // transform points int n = convertPath ( state, points, lengths ); QRegion region; QPDFDBG( printf ( "CLIPPING: %d POLYS\n", n )); // draw each subpath int j = 0; for ( int i = 0; i < n; i++ ) { int len = lengths [i]; if ( len >= 3 ) { QPointArray dummy; dummy. setRawData ( points. data ( ) + j, len ); QPDFDBG( printf ( " - POLY %d: ", i )); QPDFDBG( for ( int ii = 0; ii < len; ii++ ) printf ( "(%d/%d) ", points [j+ii]. x ( ), points [j+ii]. y ( ))); QPDFDBG( printf ( "\n" )); region |= QRegion ( dummy, winding ); dummy. resetRawData ( points. data ( ) + j, len ); } j += len; } - if ( m_painter-> hasClipping ( )) + if ( m_painter && m_painter-> hasClipping ( )) region &= m_painter-> clipRegion ( ); // m_painter-> setClipRegion ( region ); // m_painter-> setClipping ( true ); // m_painter-> fillRect ( 0, 0, m_pixmap-> width ( ), m_pixmap-> height ( ), red ); // m_painter-> drawText ( points [0]. x ( ) + 10, points [0]. y ( ) + 10, "Bla bla" ); qApp-> processEvents ( ); } // // Transform points in the path and convert curves to line segments. // Builds a set of subpaths and returns the number of subpaths. // If <fillHack> is set, close any unclosed subpaths and activate a // kludge for polygon fills: First, it divides up the subpaths into // non-overlapping polygons by simply comparing bounding rectangles. // Then it connects subaths within a single compound polygon to a single // point so that X can fill the polygon (sort of). // int QOutputDev::convertPath ( GfxState *state, QPointArray &points, QArray<int> &lengths ) { GfxPath *path = state-> getPath ( ); int n = path-> getNumSubpaths ( ); lengths. resize ( n ); // do each subpath for ( int i = 0; i < n; i++ ) { // transform the points lengths [i] = convertSubpath ( state, path-> getSubpath ( i ), points ); } return n; } // // Transform points in a single subpath and convert curves to line // segments. // int QOutputDev::convertSubpath ( GfxState *state, GfxSubpath *subpath, QPointArray &points ) { int oldcnt = points. count ( ); fp_t x0, y0, x1, y1, x2, y2, x3, y3; int m = subpath-> getNumPoints ( ); int i = 0; while ( i < m ) { if ( i >= 1 && subpath-> getCurve ( i )) { state-> transform ( subpath-> getX ( i - 1 ), subpath-> getY ( i - 1 ), &x0, &y0 ); state-> transform ( subpath-> getX ( i ), subpath-> getY ( i ), &x1, &y1 ); state-> transform ( subpath-> getX ( i + 1 ), subpath-> getY ( i + 1 ), &x2, &y2 ); state-> transform ( subpath-> getX ( i + 2 ), subpath-> getY ( i + 2 ), &x3, &y3 ); QPointArray tmp; tmp. setPoints ( 4, lrint ( x0 ), lrint ( y0 ), lrint ( x1 ), lrint ( y1 ), lrint ( x2 ), lrint ( y2 ), lrint ( x3 ), lrint ( y3 )); #if QT_VERSION < 300 tmp = tmp. quadBezier ( ); for ( uint loop = 0; loop < tmp. count ( ); loop++ ) { QPoint p = tmp. point ( loop ); points. putPoints ( points. count ( ), 1, p. x ( ), p. y ( )); } #else tmp = tmp. cubicBezier ( ); points. putPoints ( points. count ( ), tmp. count ( ), tmp ); #endif i += 3; } else { state-> transform ( subpath-> getX ( i ), subpath-> getY ( i ), &x1, &y1 ); points. putPoints ( points. count ( ), 1, lrint ( x1 ), lrint ( y1 )); ++i; } } return points. count ( ) - oldcnt; } void QOutputDev::beginString ( GfxState *state, GString */*s*/ ) { m_text-> beginString ( state ); } void QOutputDev::endString ( GfxState */*state*/ ) { m_text-> endString ( ); } void QOutputDev::drawChar ( GfxState *state, fp_t x, fp_t y, fp_t dx, fp_t dy, fp_t originX, fp_t originY, CharCode code, Unicode *u, int uLen ) { fp_t x1, y1, dx1, dy1; if ( uLen > 0 ) m_text-> addChar ( state, x, y, dx, dy, u, uLen ); // check for invisible text -- this is used by Acrobat Capture if (( state-> getRender ( ) & 3 ) == 3 ) { return; } x -= originX; y -= originY; state-> transform ( x, y, &x1, &y1 ); state-> transformDelta ( dx, dy, &dx1, &dy1 ); if ( uLen > 0 ) { QString str; QFontMetrics fm = m_painter-> fontMetrics ( ); for ( int i = 0; i < uLen; i++ ) { QChar c = QChar ( u [i] ); if ( fm. inFont ( c )) { str [i] = QChar ( u [i] ); } else { str [i] = ' '; QPDFDBG( printf ( "CHARACTER NOT IN FONT: %hx\n", c. unicode ( ))); } } if (( uLen == 1 ) && ( str [0] == ' ' )) return; fp_t m11, m12, m21, m22; state-> getFontTransMat ( &m11, &m12, &m21, &m22 ); m11 *= state-> getHorizScaling ( ); m12 *= state-> getHorizScaling ( ); fp_t fsize = m_painter-> font ( ). pixelSize ( ); #ifndef QT_NO_TRANSFORMATIONS QWMatrix oldmat; bool dorot = (( m12 < -0.1 ) || ( m12 > 0.1 )) && (( m21 < -0.1 ) || ( m21 > 0.1 )); if ( dorot ) { oldmat = m_painter-> worldMatrix ( ); std::cerr << std::endl << "ROTATED: " << m11 << ", " << m12 << ", " << m21 << ", " << m22 << " / SIZE: " << fsize << " / TEXT: " << str. local8Bit ( ) << endl << endl; QWMatrix mat ( lrint ( m11 / fsize ), lrint ( m12 / fsize ), -lrint ( m21 / fsize ), -lrint ( m22 / fsize ), lrint ( x1 ), lrint ( y1 )); m_painter-> setWorldMatrix ( mat ); x1 = 0; y1 = 0; } #endif QPen oldpen = m_painter-> pen ( ); if (!( state-> getRender ( ) & 1 )) { QPen fillpen = oldpen; fillpen. setColor ( m_painter-> brush ( ). color ( )); m_painter-> setPen ( fillpen ); } if ( fsize > 5 ) m_painter-> drawText ( lrint ( x1 ), lrint ( y1 ), str ); else m_painter-> fillRect ( lrint ( x1 ), lrint ( y1 ), lrint ( QMAX( fp_t(1), dx1 )), lrint ( QMAX( fsize, dy1 )), m_painter-> pen ( ). color ( )); m_painter-> setPen ( oldpen ); #ifndef QT_NO_TRANSFORMATIONS if ( dorot ) m_painter-> setWorldMatrix ( oldmat ); #endif QPDFDBG( printf ( "DRAW TEXT: \"%s\" at (%ld/%ld)\n", str. local8Bit ( ). data ( ), lrint ( x1 ), lrint ( y1 ))); } else if ( code != 0 ) { // some PDF files use CID 0, which is .notdef, so just ignore it qWarning ( "Unknown character (CID=%d Unicode=%hx)\n", code, (unsigned short) ( uLen > 0 ? u [0] : (Unicode) 0 )); } qApp-> processEvents ( ); } void QOutputDev::drawImageMask ( GfxState *state, Object */*ref*/, Stream *str, int width, int height, GBool invert, GBool inlineImg ) { // get CTM, check for singular matrix fp_t *ctm = state-> getCTM ( ); if ( fabs ( ctm [0] * ctm [3] - ctm [1] * ctm [2] ) < 0.000001 ) { qWarning ( "Singular CTM in drawImage\n" ); if ( inlineImg ) { str-> reset ( ); int j = height * (( width + 7 ) / 8 ); for ( int i = 0; i < j; i++ ) str->getChar(); str->close(); } return; } GfxRGB rgb; state-> getFillRGB ( &rgb ); uint val = ( lrint ( rgb. r * 255 ) & 0xff ) << 16 | ( lrint ( rgb. g * 255 ) & 0xff ) << 8 | ( lrint ( rgb. b * 255 ) & 0xff ); QImage img ( width, height, 32 ); img. setAlphaBuffer ( true ); QPDFDBG( printf ( "IMAGE MASK (%dx%d)\n", width, height )); // initialize the image stream ImageStream *imgStr = new ImageStream ( str, width, 1, 1 ); imgStr-> reset ( ); uchar **scanlines = img. jumpTable ( ); if ( ctm [3] > 0 ) scanlines += ( height - 1 ); for ( int y = 0; y < height; y++ ) { QRgb *scanline = (QRgb *) *scanlines; if ( ctm [0] < 0 ) scanline += ( width - 1 ); for ( int x = 0; x < width; x++ ) { Guchar alpha; imgStr-> getPixel ( &alpha ); if ( invert ) alpha ^= 1; *scanline = ( alpha == 0 ) ? 0xff000000 | val : val; ctm [0] < 0 ? scanline-- : scanline++; } ctm [3] > 0 ? scanlines-- : scanlines++; qApp-> processEvents ( ); } #ifndef QT_NO_TRANSFORMATIONS QWMatrix mat ( ctm [0] / width, ctm [1], ctm [2], ctm [3] / height, ctm [4], ctm [5] ); std::cerr << "MATRIX T=" << mat. dx ( ) << "/" << mat. dy ( ) << std::endl << " - M=" << mat. m11 ( ) << "/" << mat. m12 ( ) << "/" << mat. m21 ( ) << "/" << mat. m22 ( ) << std::endl; QWMatrix oldmat = m_painter-> worldMatrix ( ); m_painter-> setWorldMatrix ( mat, true ); #ifdef QWS QPixmap pm; pm. convertFromImage ( img ); m_painter-> drawPixmap ( 0, 0, pm ); #else m_painter-> drawImage ( QPoint ( 0, 0 ), img ); #endif m_painter-> setWorldMatrix ( oldmat ); #else if (( ctm [1] < -0.1 ) || ( ctm [1] > 0.1 ) || ( ctm [2] < -0.1 ) || ( ctm [2] > 0.1 )) { QPDFDBG( printf ( "### ROTATED / SHEARED / ETC -- CANNOT DISPLAY THIS IMAGE\n" )); } else { int x = lrint ( ctm [4] ); int y = lrint ( ctm [5] ); int w = lrint ( ctm [0] ); int h = lrint ( ctm [3] ); if ( w < 0 ) { x += w; w = -w; } if ( h < 0 ) { y += h; h = -h; } QPDFDBG( printf ( "DRAWING IMAGE MASKED: %d/%d - %dx%d\n", x, y, w, h )); img = img. smoothScale ( w, h ); qApp-> processEvents ( ); m_painter-> drawImage ( x, y, img ); } #endif delete imgStr; qApp-> processEvents ( ); } void QOutputDev::drawImage(GfxState *state, Object */*ref*/, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg ) { int nComps, nVals, nBits; // image parameters nComps = colorMap->getNumPixelComps ( ); nVals = width * nComps; nBits = colorMap-> getBits ( ); // get CTM, check for singular matrix fp_t *ctm = state-> getCTM ( ); if ( fabs ( ctm [0] * ctm [3] - ctm [1] * ctm [2] ) < 0.000001 ) { qWarning ( "Singular CTM in drawImage\n" ); if ( inlineImg ) { str-> reset ( ); int j = height * (( nVals * nBits + 7 ) / 8 ); for ( int i = 0; i < j; i++ ) str->getChar(); str->close(); } return; } QImage img ( width, height, 32 ); if ( maskColors ) img. setAlphaBuffer ( true ); QPDFDBG( printf ( "IMAGE (%dx%d)\n", width, height )); // initialize the image stream ImageStream *imgStr = new ImageStream ( str, width, nComps, nBits ); imgStr-> reset ( ); Guchar pixBuf [gfxColorMaxComps]; GfxRGB rgb; uchar **scanlines = img. jumpTable ( ); if ( ctm [3] > 0 ) scanlines += ( height - 1 ); for ( int y = 0; y < height; y++ ) { QRgb *scanline = (QRgb *) *scanlines; if ( ctm [0] < 0 ) scanline += ( width - 1 ); for ( int x = 0; x < width; x++ ) { imgStr-> getPixel ( pixBuf ); colorMap-> getRGB ( pixBuf, &rgb ); uint val = ( lrint ( rgb. r * 255 ) & 0xff ) << 16 | ( lrint ( rgb. g * 255 ) & 0xff ) << 8 | ( lrint ( rgb. b * 255 ) & 0xff ); if ( maskColors ) { for ( int k = 0; k < nComps; ++k ) { if (( pixBuf [k] < maskColors [2 * k] ) || ( pixBuf [k] > maskColors [2 * k] )) { val |= 0xff000000; break; } } } *scanline = val; ctm [0] < 0 ? scanline-- : scanline++; } ctm [3] > 0 ? scanlines-- : scanlines++; qApp-> processEvents ( ); } #ifndef QT_NO_TRANSFORMATIONS QWMatrix mat ( ctm [0] / width, ctm [1], ctm [2], ctm [3] / height, ctm [4], ctm [5] ); std::cerr << "MATRIX T=" << mat. dx ( ) << "/" << mat. dy ( ) << std::endl << " - M=" << mat. m11 ( ) << "/" << mat. m12 ( ) << "/" << mat. m21 ( ) << "/" << mat. m22 ( ) << std::endl; QWMatrix oldmat = m_painter-> worldMatrix ( ); m_painter-> setWorldMatrix ( mat, true ); #ifdef QWS QPixmap pm; pm. convertFromImage ( img ); m_painter-> drawPixmap ( 0, 0, pm ); #else m_painter-> drawImage ( QPoint ( 0, 0 ), img ); #endif m_painter-> setWorldMatrix ( oldmat ); #else // QT_NO_TRANSFORMATIONS if (( ctm [1] < -0.1 ) || ( ctm [1] > 0.1 ) || ( ctm [2] < -0.1 ) || ( ctm [2] > 0.1 )) { QPDFDBG( printf ( "### ROTATED / SHEARED / ETC -- CANNOT DISPLAY THIS IMAGE\n" )); } else { int x = lrint ( ctm [4] ); int y = lrint ( ctm [5] ); int w = lrint ( ctm [0] ); int h = lrint ( ctm [3] ); if ( w < 0 ) { x += w; w = -w; } if ( h < 0 ) { y += h; h = -h; } QPDFDBG( printf ( "DRAWING IMAGE: %d/%d - %dx%d\n", x, y, w, h )); img = img. smoothScale ( w, h ); qApp-> processEvents ( ); m_painter-> drawImage ( x, y, img ); } #endif delete imgStr; qApp-> processEvents ( ); } bool QOutputDev::findText ( const QString &str, QRect &r, bool top, bool bottom ) { int l, t, w, h; r. rect ( &l, &t, &w, &h ); bool res = findText ( str, l, t, w, h, top, bottom ); r. setRect ( l, t, w, h ); return res; } bool QOutputDev::findText ( const QString &str, int &l, int &t, int &w, int &h, bool top, bool bottom ) { bool found = false; uint len = str. length ( ); Unicode *s = new Unicode [len]; for ( uint i = 0; i < len; i++ ) s [i] = str [i]. unicode ( ); fp_t x1 = (fp_t) l; fp_t y1 = (fp_t) t; fp_t x2 = (fp_t) l + w - 1; fp_t y2 = (fp_t) t + h - 1; if ( m_text-> findText ( s, len, top, bottom, &x1, &y1, &x2, &y2 )) { l = lrint ( x1 ); t = lrint ( y1 ); w = lrint ( x2 ) - l + 1; h = lrint ( y2 ) - t + 1; found = true; } delete [] s; return found; } GBool QOutputDev::findText ( Unicode *s, int len, GBool top, GBool bottom, int *xMin, int *yMin, int *xMax, int *yMax ) { bool found = false; fp_t xMin1 = (double) *xMin; fp_t yMin1 = (double) *yMin; fp_t xMax1 = (double) *xMax; fp_t yMax1 = (double) *yMax; if ( m_text-> findText ( s, len, top, bottom, &xMin1, &yMin1, &xMax1, &yMax1 )) { *xMin = lrint ( xMin1 ); *xMax = lrint ( xMax1 ); *yMin = lrint ( yMin1 ); *yMax = lrint ( yMax1 ); found = true; } return found; } QString QOutputDev::getText ( int l, int t, int w, int h ) { GString *gstr = m_text-> getText ( l, t, l + w - 1, t + h - 1 ); QString str = gstr-> getCString ( ); delete gstr; return str; } QString QOutputDev::getText ( const QRect &r ) { return getText ( r. left ( ), r. top ( ), r. width ( ), r. height ( )); } void QOutputDev::drawContents ( QPainter *p, int clipx, int clipy, int clipw, int cliph ) { if ( m_pixmap ) p-> drawPixmap ( clipx, clipy, *m_pixmap, clipx, clipy, clipw, cliph ); else p-> fillRect ( clipx, clipy, clipw, cliph, white ); } diff --git a/noncore/unsupported/qpdf/opie-qpdf.control b/noncore/unsupported/qpdf/opie-qpdf.control index 33df3e1..208dcb1 100644 --- a/noncore/unsupported/qpdf/opie-qpdf.control +++ b/noncore/unsupported/qpdf/opie-qpdf.control @@ -1,9 +1,9 @@ Package: opie-qpdf Files: bin/qpdf apps/Applications/qpdf.desktop pics/qpdf/qpdf_icon.png Priority: optional Section: opie/applications Maintainer: Robert Griebl <sandman@handhelds.org> Architecture: arm -Version: $QPE_VERSION-$SUB_VERSION Depends: task-opie-minimal, gzip Description: A PDF viewer for OPIE. +Version: $QPE_VERSION$EXTRAVERSION diff --git a/noncore/unsupported/qpdf/qpdf.cpp b/noncore/unsupported/qpdf/qpdf.cpp index 61f097b..de1dcf3 100644 --- a/noncore/unsupported/qpdf/qpdf.cpp +++ b/noncore/unsupported/qpdf/qpdf.cpp |