monav-0.3/0000755000175000017500000000000011554574462012115 5ustar vettervettermonav-0.3/routingdaemon/0000755000175000017500000000000011554574462014770 5ustar vettervettermonav-0.3/routingdaemon/main.cpp0000644000175000017500000000410311522560077016406 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include # #include "routingdaemon.h" Q_IMPORT_PLUGIN( contractionhierarchiesclient ); Q_IMPORT_PLUGIN( gpsgridclient ); QtMsgHandler oldHandler = NULL; RoutingDaemon* servicePointer = NULL; void MessageBoxHandler( QtMsgType type, const char *msg ) { switch (type) { case QtDebugMsg: servicePointer->logMessage( msg, QtServiceBase::Information ); break; case QtWarningMsg: servicePointer->logMessage( msg, QtServiceBase::Warning ); break; case QtCriticalMsg: servicePointer->logMessage( msg, QtServiceBase::Error ); break; case QtFatalMsg: servicePointer->logMessage( msg, QtServiceBase::Error ); exit( -1 ); break; } if ( oldHandler != NULL ) oldHandler( type, msg ); } int main( int argc, char** argv ) { if ( argc == 2 && argv[1] == QString( "--help" ) ) { qDebug() << "usage:" << argv[0]; qDebug() << "\tstarts the service"; qDebug() << "usage:" << argv[0] << "-i | -install"; qDebug() << "\tinstalls the service"; qDebug() << "usage:" << argv[0] << "-u | -uninstall"; qDebug() << "\tuninstalls the service"; qDebug() << "usage:" << argv[0] << "-t | -terminate"; qDebug() << "\tterminates the service"; qDebug() << "usage:" << argv[0] << "-v | -version"; qDebug() << "\tdisplays version and status"; return 1; } RoutingDaemon service( argc, argv ); servicePointer = &service; oldHandler = qInstallMsgHandler( MessageBoxHandler ); return service.exec(); } monav-0.3/routingdaemon/routingdaemon.pro0000644000175000017500000000114111522560077020352 0ustar vettervetterTEMPLATE = app DESTDIR = ../bin INCLUDEPATH += .. DEFINES+=_7ZIP_ST TARGET = monav-daemon QT -= gui QT +=network unix { QMAKE_CXXFLAGS_RELEASE -= -O2 QMAKE_CXXFLAGS_RELEASE += -O3 \ -march=native \ -Wno-unused-function QMAKE_CXXFLAGS_DEBUG += -Wno-unused-function } LIBS += -L../bin/plugins_client -lcontractionhierarchiesclient -lgpsgridclient SOURCES += \ main.cpp \ ../utils/lzma/LzmaDec.c \ ../utils/directoryunpacker.cpp HEADERS += \ signals.h \ routingdaemon.h \ ../utils/lzma/LzmaDec.h \ ../utils/directoryunpacker.h include(qtservice-2.6_1-opensource/src/qtservice.pri) monav-0.3/routingdaemon/signals.h0000644000175000017500000001637111522560077016601 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . Alternatively, this file may be used under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. */ #ifndef SIGNALS_H #define SIGNALS_H #include #include #include #include #include namespace MoNav { // has to be send before each command to identify the following command type struct CommandType { enum Type{ RoutingCommand = 0, UnpackCommand = 1 } value; void post( QIODevice* out ) { qint32 temp = value; out->write( ( const char* ) &temp, sizeof( qint32 ) ); } bool read( QLocalSocket* in ) { while ( in->bytesAvailable() < ( int ) sizeof( qint32 ) ) { if ( in->state() != QLocalSocket::ConnectedState ) return false; in->waitForReadyRead( 100 ); } qint32 temp; in->read( ( char* ) &temp, sizeof( qint32 ) ); value = ( Type ) temp; return true; } }; struct Node { double latitude; double longitude; friend QDataStream& operator<< ( QDataStream& out, const Node& node ) { out << node.latitude; out << node.longitude; return out; } friend QDataStream& operator>> ( QDataStream& in, Node& node ) { in >> node.latitude; in >> node.longitude; return in; } }; struct Edge { unsigned length; // length of the edge == number of edges it represents == number of nodes - 1 unsigned name; // name ID of the edge unsigned type; // type ID of the edge unsigned seconds; // travel time metric for the edge bool branchingPossible; // is it possible to choose between more than one subsequent edge ( turning around on bidirectional edges does not count ) friend QDataStream& operator<< ( QDataStream& out, const Edge& edge ) { out << edge.length; out << edge.name; out << edge.type; out << edge.seconds; out << edge.branchingPossible; return out; } friend QDataStream& operator>> ( QDataStream& in, Edge& edge ) { in >> edge.length; in >> edge.name; in >> edge.type; in >> edge.seconds; in >> edge.branchingPossible; return in; } }; class RoutingCommand { public: RoutingCommand() { lookupRadius = 10000; // 10km should suffice for most applications lookupStrings = false; } // waypoint edge lookup radius in meters double lookupRadius; // lookup street name / type strings? bool lookupStrings; // a valid routing module directory QString dataDirectory; // waypoints of the route QVector< Node > waypoints; void post( QIODevice* out ) { QByteArray buffer; QDataStream stream( &buffer, QIODevice::WriteOnly ); stream << lookupRadius; stream << lookupStrings; stream << dataDirectory; stream << waypoints; qint32 size = buffer.size(); out->write( ( const char* ) &size, sizeof( qint32 ) ); out->write( buffer.data(), size ); } bool read( QLocalSocket* in ) { qint32 size; while ( in->bytesAvailable() < ( int ) sizeof( qint32 ) ) { if ( in->state() != QLocalSocket::ConnectedState ) return false; in->waitForReadyRead( 100 ); } in->read( ( char* ) &size, sizeof( quint32 ) ); while ( in->bytesAvailable() < size ) { if ( in->state() != QLocalSocket::ConnectedState ) return false; in->waitForReadyRead( 100 ); } QByteArray buffer= in->read( size ); QDataStream stream( buffer ); stream >> lookupRadius; stream >> lookupStrings; stream >> dataDirectory; stream >> waypoints; return true; } }; class RoutingResult { public: enum ResultType { LoadFailed = 1, RouteFailed = 2, NameLookupFailed = 3, TypeLookupFailed = 4, Success = 5 } type; double seconds; QVector< Node > pathNodes; QVector< Edge > pathEdges; QStringList nameStrings; QStringList typeStrings; void post( QIODevice* out ) { QByteArray buffer; QDataStream stream( &buffer, QIODevice::WriteOnly ); stream << qint32( type ); stream << seconds; stream << pathNodes; stream << pathEdges; stream << nameStrings; stream << typeStrings; qint32 size = buffer.size(); out->write( ( const char* ) &size, sizeof( qint32 ) ); out->write( buffer.data(), size ); } bool read( QLocalSocket* in ) { qint32 size; while ( in->bytesAvailable() < ( int ) sizeof( qint32 ) ) { if ( in->state() != QLocalSocket::ConnectedState ) return false; in->waitForReadyRead( 100 ); } in->read( ( char* ) &size, sizeof( quint32 ) ); while ( in->bytesAvailable() < size ) { if ( in->state() != QLocalSocket::ConnectedState ) return false; in->waitForReadyRead( 100 ); } QByteArray buffer= in->read( size ); QDataStream stream( buffer ); qint32 temp; stream >> temp; type = ( ResultType ) temp; stream >> seconds; stream >> pathNodes; stream >> pathEdges; stream >> nameStrings; stream >> typeStrings; return true; } }; class UnpackCommand { public: UnpackCommand() { deleteFile = false; } // MoNav Map Module file to be unpacked // it will be unpacked in the directory of the same name // e.g. test.mmm -> test/ QString mapModuleFile; // delete file after unpacking? bool deleteFile; void post( QIODevice* out ) { QByteArray buffer; QDataStream stream( &buffer, QIODevice::WriteOnly ); stream << mapModuleFile; stream << deleteFile; qint32 size = buffer.size(); out->write( ( const char* ) &size, sizeof( qint32 ) ); out->write( buffer.data(), size ); } bool read( QLocalSocket* in ) { qint32 size; while ( in->bytesAvailable() < ( int ) sizeof( qint32 ) ) { if ( in->state() != QLocalSocket::ConnectedState ) return false; in->waitForReadyRead( 100 ); } in->read( ( char* ) &size, sizeof( quint32 ) ); while ( in->bytesAvailable() < size ) { if ( in->state() != QLocalSocket::ConnectedState ) return false; in->waitForReadyRead( 100 ); } QByteArray buffer= in->read( size ); QDataStream stream( buffer ); stream >> mapModuleFile; stream >> deleteFile; return true; } }; class UnpackResult { public: enum ResultType { FailUnpacking = 1, Success = 2 } type; void post( QIODevice* out ) { qint32 temp = type; out->write( ( const char* ) &temp, sizeof( qint32 ) ); } bool read( QLocalSocket* in ) { while ( in->bytesAvailable() < ( int ) sizeof( qint32 ) ) { if ( in->state() != QLocalSocket::ConnectedState ) return false; in->waitForReadyRead( 100 ); } qint32 temp; in->read( ( char* ) &temp, sizeof( qint32 ) ); type = ResultType( temp ); return true; } }; } #endif // SIGNALS_H monav-0.3/routingdaemon/test.cpp0000644000175000017500000001044411551136577016454 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file 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 3 of the License, or (at your option) any later version. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this file. If not, see . */ #include "signals.h" #include #include using namespace MoNav; bool processArguments( CommandType* type, UnpackCommand* unpack, RoutingCommand* routing, int argc, char** argv ) { if ( argc == 2 ) { type->value = CommandType::UnpackCommand; unpack->mapModuleFile = argv[1]; return true; } if ( argc < 6 || ( argc & 1 ) == 1 ) return false; type->value = CommandType::RoutingCommand; routing->dataDirectory = argv[1]; for ( int i = 2; i < argc; i+=2 ) { bool ok; Node coordinate; coordinate.latitude = QString( argv[i] ).toDouble( &ok ); if ( !ok ) return false; coordinate.longitude = QString( argv[i + 1] ).toDouble( &ok ); if ( !ok ) return false; routing->waypoints.push_back( coordinate ); } return true; } int main( int argc, char *argv[] ) { CommandType commandType; UnpackCommand unpackCommand; RoutingCommand routingCommand; routingCommand.lookupStrings = true; if ( !processArguments( &commandType, &unpackCommand, &routingCommand, argc, argv ) ) { qDebug() << "usage:" << argv[0] << "data-directory latitude1 longitude1 latitude2 longitude2 [...latitudeN longitudeN]"; qDebug() << "\tcomputes a route using between the specified waypoints"; qDebug() << "usage:" << argv[0] << "monav-map-module-file"; qDebug() << "\tunpacks a map module"; return 1; } QLocalSocket connection; connection.connectToServer( "MoNavD" ); if ( !connection.waitForConnected() ) { qDebug() << "failed to connect to daemon:" << connection.error(); return 2; } commandType.post( &connection ); if ( commandType.value == CommandType::UnpackCommand ) { unpackCommand.post( &connection ); connection.flush(); UnpackResult reply; reply.type = UnpackResult::FailUnpacking; reply.read( &connection ); qDebug() << connection.state(); if ( reply.type == UnpackResult::FailUnpacking ) { qDebug() << "failed to unpack map file"; return 3; } qDebug() << "finished unpacking map file"; return 0; } routingCommand.post( &connection ); connection.flush(); RoutingResult reply; reply.read( &connection ); qDebug() << connection.state(); if ( reply.type == RoutingResult::LoadFailed ) { qDebug() << "failed to load data directory"; return 3; } else if ( reply.type == RoutingResult::RouteFailed ) { qDebug() << "failed to compute route"; return 3; } else if ( reply.type == RoutingResult::NameLookupFailed ) { qDebug() << "failed to compute route"; return 3; } else if ( reply.type == RoutingResult::TypeLookupFailed ) { qDebug() << "failed to compute route"; return 3; }else if ( reply.type == RoutingResult::Success ) { int seconds = reply.seconds; qDebug() << "distance:" << seconds / 60 / 60 << "h" << ( seconds / 60 ) % 60 << "m" << seconds % 60 << "s"; qDebug() << "nodes:" << reply.pathNodes.size(); qDebug() << "edges:" << reply.pathEdges.size(); unsigned node = 0; for ( int i = 0; i < reply.pathEdges.size(); i++ ) { QString name = reply.nameStrings[reply.pathEdges[i].name]; QString type = reply.typeStrings[reply.pathEdges[i].type]; qDebug() << "name:" << name.toUtf8() << "type:" << type << "nodes:" << reply.pathEdges[i].length + 1 << "seconds:" << reply.pathEdges[i].seconds << "branching possible:" << reply.pathEdges[i].branchingPossible; for ( unsigned j = 0; j <= reply.pathEdges[i].length; j++ ) { QString latitude, longitude; latitude.setNum( reply.pathNodes[j + node].latitude, 'g', 10 ); longitude.setNum( reply.pathNodes[j + node].longitude, 'g', 10 ); qDebug() << latitude.toLatin1().data() << longitude.toLatin1().data(); } node += reply.pathEdges[i].length; } } else { qDebug() << "return value not recognized"; return 5; } } monav-0.3/routingdaemon/daemontest.pro0000644000175000017500000000046411522560077017651 0ustar vettervetterTEMPLATE = app DESTDIR = ../bin INCLUDEPATH += .. TARGET = daemon-test QT -= gui QT +=network unix { QMAKE_CXXFLAGS_RELEASE -= -O2 QMAKE_CXXFLAGS_RELEASE += -O3 \ -march=native \ -Wno-unused-function QMAKE_CXXFLAGS_DEBUG += -Wno-unused-function } SOURCES += \ test.cpp HEADERS += \ signals.h monav-0.3/routingdaemon/qtservice-2.6_1-opensource/0000755000175000017500000000000011554574462021700 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/README.TXT0000644000175000017500000000014511437034034023220 0ustar vettervetterService v2.6 The QtService component is useful for developing Windows services and Unix daemons. monav-0.3/routingdaemon/qtservice-2.6_1-opensource/INSTALL.TXT0000644000175000017500000002237411437034034023401 0ustar vettervetterINSTALLATION INSTRUCTIONS These instructions refer to the package you are installing as some-package.tar.gz or some-package.zip. The .zip file is intended for use on Windows. The directory you choose for the installation will be referred to as your-install-dir. Note to Qt Visual Studio Integration users: In the instructions below, instead of building from command line with nmake, you can use the menu command 'Qt->Open Solution from .pro file' on the .pro files in the example and plugin directories, and then build from within Visual Studio. Unpacking and installation -------------------------- 1. Unpacking the archive (if you have not done so already). On Unix and Mac OS X (in a terminal window): cd your-install-dir gunzip some-package.tar.gz tar xvf some-package.tar This creates the subdirectory some-package containing the files. On Windows: Unpack the .zip archive by right-clicking it in explorer and choosing "Extract All...". If your version of Windows does not have zip support, you can use the infozip tools available from www.info-zip.org. If you are using the infozip tools (in a command prompt window): cd your-install-dir unzip some-package.zip 2. Configuring the package. The configure script is called "configure" on unix/mac and "configure.bat" on Windows. It should be run from a command line after cd'ing to the package directory. You can choose whether you want to use the component by including its source code directly into your project, or build the component as a dynamic shared library (DLL) that is loaded into the application at run-time. The latter may be preferable for technical or licensing (LGPL) reasons. If you want to build a DLL, run the configure script with the argument "-library". Also see the note about usage below. (Components that are Qt plugins, e.g. styles and image formats, are by default built as a plugin DLL.) The configure script will prompt you in some cases for further information. Answer these questions and carefully read the license text before accepting the license conditions. The package cannot be used if you do not accept the license conditions. 3. Building the component and examples (when required). If a DLL is to be built, or if you would like to build the examples, next give the commands qmake make [or nmake if your are using Microsoft Visual C++] The example program(s) can be found in the directory called "examples" or "example". Components that are Qt plugins, e.g. styles and image formats, are ready to be used as soon as they are built, so the rest of this installation instruction can be skipped. 4. Building the Qt Designer plugin (optional). Some of the widget components are provided with plugins for Qt Designer. To build and install the plugin, cd into the some-package/plugin directory and give the commands qmake make [or nmake if your are using Microsoft Visual C++] Restart Qt Designer to make it load the new widget plugin. Note: If you are using the built-in Qt Designer from the Qt Visual Studio Integration, you will need to manually copy the plugin DLL file, i.e. copy %QTDIR%\plugins\designer\some-component.dll to the Qt Visual Studio Integration plugin path, typically: C:\Program Files\Trolltech\Qt VS Integration\plugins Note: If you for some reason are using a Qt Designer that is built in debug mode, you will need to build the plugin in debug mode also. Edit the file plugin.pro in the plugin directory, changing 'release' to 'debug' in the CONFIG line, before running qmake. Solutions components are intended to be used directly from the package directory during development, so there is no 'make install' procedure. Using a component in your project --------------------------------- To use this component in your project, add the following line to the project's .pro file (or do the equivalent in your IDE): include(your-install-dir/some-package/src/some-package.pri) This adds the package's sources and headers to the SOURCES and HEADERS project variables respectively (or, if the component has been configured as a DLL, it adds that library to the LIBS variable), and updates INCLUDEPATH to contain the package's src directory. Additionally, the .pri file may include some dependencies needed by the package. To include a header file from the package in your sources, you can now simply use: #include or alternatively, in pre-Qt 4 style: #include Refer to the documentation to see the classes and headers this components provides. Install documentation (optional) -------------------------------- The HTML documentation for the package's classes is located in the your-install-dir/some-package/doc/html/index.html. You can open this file and read the documentation with any web browser. To install the documentation into Qt Assistant (for Qt version 4.4 and later): 1. In Assistant, open the Edit->Preferences dialog and choose the Documentation tab. Click the Add... button and select the file your-install-dir/some-package/doc/html/some-package.qch For Qt versions prior to 4.4, do instead the following: 1. The directory your-install-dir/some-package/doc/html contains a file called some-package.dcf. Execute the following commands in a shell, command prompt or terminal window: cd your-install-dir/some-package/doc/html/ assistant -addContentFile some-package.dcf The next time you start Qt Assistant, you can access the package's documentation. Removing the documentation from assistant ----------------------------------------- If you have installed the documentation into Qt Assistant, and want to uninstall it, do as follows, for Qt version 4.4 and later: 1. In Assistant, open the Edit->Preferences dialog and choose the Documentation tab. In the list of Registered Documentation, select the item com.nokia.qtsolutions.some-package_version, and click the Remove button. For Qt versions prior to 4.4, do instead the following: 1. The directory your-install-dir/some-package/doc/html contains a file called some-package.dcf. Execute the following commands in a shell, command prompt or terminal window: cd your-install-dir/some-package/doc/html/ assistant -removeContentFile some-package.dcf Using the component as a DLL ---------------------------- 1. Normal components The shared library (DLL) is built and placed in the some-package/lib directory. It is intended to be used directly from there during development. When appropriate, both debug and release versions are built, since the run-time linker will in some cases refuse to load a debug-built DLL into a release-built application or vice versa. The following steps are taken by default to help the dynamic linker to locate the DLL at run-time (during development): Unix: The some-package.pri file will add linker instructions to add the some-package/lib directory to the rpath of the executable. (When distributing, or if your system does not support rpath, you can copy the shared library to another place that is searched by the dynamic linker, e.g. the "lib" directory of your Qt installation.) Mac: The full path to the library is hardcoded into the library itself, from where it is copied into the executable at link time, and ready by the dynamic linker at run-time. (When distributing, you will want to edit these hardcoded paths in the same way as for the Qt DLLs. Refer to the document "Deploying an Application on Mac OS X" in the Qt Reference Documentation.) Windows: the .dll file(s) are copied into the "bin" directory of your Qt installation. The Qt installation will already have set up that directory to be searched by the dynamic linker. 2. Plugins For Qt Solutions plugins (e.g. image formats), both debug and release versions of the plugin are built by default when appropriate, since in some cases the release Qt library will not load a debug plugin, and vice versa. The plugins are automatically copied into the plugins directory of your Qt installation when built, so no further setup is required. Plugins may also be built statically, i.e. as a library that will be linked into your application executable, and so will not need to be redistributed as a separate plugin DLL to end users. Static building is required if Qt itself is built statically. To do it, just add "static" to the CONFIG variable in the plugin/plugin.pro file before building. Refer to the "Static Plugins" section in the chapter "How to Create Qt Plugins" for explanation of how to use a static plugin in your application. The source code of the example program(s) will also typically contain the relevant instructions as comments. Uninstalling ------------ The following command will remove any fils that have been automatically placed outside the package directory itself during installation and building make distclean [or nmake if your are using Microsoft Visual C++] If Qt Assistant documentation or Qt Designer plugins have been installed, they can be uninstalled manually, ref. above. Enjoy! :) - The Qt Solutions Team. monav-0.3/routingdaemon/qtservice-2.6_1-opensource/qtservice.pro0000644000175000017500000000015311437034034024410 0ustar vettervetterTEMPLATE=subdirs CONFIG += ordered include(common.pri) qtservice-uselib:SUBDIRS=buildlib SUBDIRS+=examples monav-0.3/routingdaemon/qtservice-2.6_1-opensource/lib/0000755000175000017500000000000011554574462022446 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/common.pri0000644000175000017500000000043211437034034023665 0ustar vettervetterinfile(config.pri, SOLUTIONS_LIBRARY, yes): CONFIG += qtservice-uselib TEMPLATE += fakelib QTSERVICE_LIBNAME = $$qtLibraryTarget(QtSolutions_Service-2.6) TEMPLATE -= fakelib QTSERVICE_LIBDIR = $$PWD/lib unix:qtservice-uselib:!qtservice-buildlib:QMAKE_RPATHDIR += $$QTSERVICE_LIBDIR monav-0.3/routingdaemon/qtservice-2.6_1-opensource/LICENSE.LGPL0000644000175000017500000006350411437034034023434 0ustar vettervetter GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/0000755000175000017500000000000011554574462023516 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/interactive/0000755000175000017500000000000011554574462026033 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/interactive/main.cpp0000644000175000017500000001054511437034034027452 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include #include #include #include #include #include "qtservice.h" class InteractiveService : public QtService { public: InteractiveService(int argc, char **argv); ~InteractiveService(); protected: void start(); void stop(); void pause(); void resume(); void processCommand(int code); private: QLabel *gui; }; InteractiveService::InteractiveService(int argc, char **argv) : QtService(argc, argv, "Qt Interactive Service"), gui(0) { setServiceDescription("A Qt service with user interface."); setServiceFlags(QtServiceBase::CanBeSuspended); } InteractiveService::~InteractiveService() { } void InteractiveService::start() { #if defined(Q_OS_WIN) if ((QSysInfo::WindowsVersion & QSysInfo::WV_NT_based) && (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)) { logMessage( "Service GUI not allowed on Windows Vista. See the documentation for this example for more information.", QtServiceBase::Error ); return; } #endif qApp->setQuitOnLastWindowClosed(false); gui = new QLabel("Service", 0, Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint); gui->move(QApplication::desktop()->availableGeometry().topLeft()); gui->show(); } void InteractiveService::stop() { delete gui; } void InteractiveService::pause() { if (gui) gui->hide(); } void InteractiveService::resume() { if (gui) gui->show(); } void InteractiveService::processCommand(int code) { gui->setText("Command code " + QString::number(code)); gui->adjustSize(); } int main(int argc, char **argv) { #if !defined(Q_WS_WIN) // QtService stores service settings in SystemScope, which normally require root privileges. // To allow testing this example as non-root, we change the directory of the SystemScope settings file. QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath()); qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData()); #endif InteractiveService service(argc, argv); return service.exec(); } monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/interactive/interactive.pro0000644000175000017500000000013211437034034031050 0ustar vettervetterTEMPLATE = app CONFIG += console qt SOURCES = main.cpp include(../../src/qtservice.pri) monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/interactive/interactive.qdoc0000644000175000017500000000710011437034034031200 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ /*! \page qtservice-example-interactive.html \title An Interactive Service This example implements a service with a simple user interface. Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes. However, although not recommended in the general case, in certain circumstances a service may provide a GUI itself. This is typically only possible if the service process is run as the same user as the one that is logged in, so that it will have access to the screen. Note however that on Windows Vista, service GUIs are not allowed at all, since services run in a diferent session than all user sessions, for security reasons. This example demonstrates how to subclass the QtService class, the use of start(), stop(), pause(), resume(), and how to use processCommand() to receive control commands while running. Here is the complete source code: \quotefile interactive/main.cpp */ monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/server/0000755000175000017500000000000011554574462025024 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/server/main.cpp0000644000175000017500000001444311437034034026444 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include #include #include #include #include #include #include #include #include "qtservice.h" // HttpDaemon is the the class that implements the simple HTTP server. class HttpDaemon : public QTcpServer { Q_OBJECT public: HttpDaemon(quint16 port, QObject* parent = 0) : QTcpServer(parent), disabled(false) { listen(QHostAddress::Any, port); } void incomingConnection(int socket) { if (disabled) return; // When a new client connects, the server constructs a QTcpSocket and all // communication with the client is done over this QTcpSocket. QTcpSocket // works asynchronously, this means that all the communication is done // in the two slots readClient() and discardClient(). QTcpSocket* s = new QTcpSocket(this); connect(s, SIGNAL(readyRead()), this, SLOT(readClient())); connect(s, SIGNAL(disconnected()), this, SLOT(discardClient())); s->setSocketDescriptor(socket); QtServiceBase::instance()->logMessage("New Connection"); } void pause() { disabled = true; } void resume() { disabled = false; } private slots: void readClient() { if (disabled) return; // This slot is called when the client sent data to the server. The // server looks if it was a get request and sends a very simple HTML // document back. QTcpSocket* socket = (QTcpSocket*)sender(); if (socket->canReadLine()) { QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*")); if (tokens[0] == "GET") { QTextStream os(socket); os.setAutoDetectUnicode(true); os << "HTTP/1.0 200 Ok\r\n" "Content-Type: text/html; charset=\"utf-8\"\r\n" "\r\n" "

Nothing to see here

\n" << QDateTime::currentDateTime().toString() << "\n"; socket->close(); QtServiceBase::instance()->logMessage("Wrote to client"); if (socket->state() == QTcpSocket::UnconnectedState) { delete socket; QtServiceBase::instance()->logMessage("Connection closed"); } } } } void discardClient() { QTcpSocket* socket = (QTcpSocket*)sender(); socket->deleteLater(); QtServiceBase::instance()->logMessage("Connection closed"); } private: bool disabled; }; class HttpService : public QtService { public: HttpService(int argc, char **argv) : QtService(argc, argv, "Qt HTTP Daemon") { setServiceDescription("A dummy HTTP service implemented with Qt"); setServiceFlags(QtServiceBase::CanBeSuspended); } protected: void start() { QCoreApplication *app = application(); quint16 port = (app->argc() > 1) ? QString::fromLocal8Bit(app->argv()[1]).toUShort() : 8080; daemon = new HttpDaemon(port, app); if (!daemon->isListening()) { logMessage(QString("Failed to bind to port %1").arg(daemon->serverPort()), QtServiceBase::Error); app->quit(); } } void pause() { daemon->pause(); } void resume() { daemon->resume(); } private: HttpDaemon *daemon; }; #include "main.moc" int main(int argc, char **argv) { #if !defined(Q_WS_WIN) // QtService stores service settings in SystemScope, which normally require root privileges. // To allow testing this example as non-root, we change the directory of the SystemScope settings file. QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath()); qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData()); #endif HttpService service(argc, argv); return service.exec(); } monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/server/server.qdoc0000644000175000017500000000746011437034034027173 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ /*! \page qtservice-example-server.html \title A simple HTTP Server It is a very simple implementation of a HTTP daemon that listens on chosen port (defaultly 8080) and sends back a simple HTML page back for every GET request it gets. After sending the page, it closes the connection. \quotefromfile server/main.cpp \skipto HttpDaemon \printuntil }; The server implementation uses the QtService::logMessage() function to send messages and status reports to the system event log. The server also supports a paused state in which case incoming requests are ignored. The \c HttpService class subclasses QtService to implement the service functionality. \printto protected: The constructor calls the QtService constructor instantiated with QCoreApplication since our service will not use GUI. The first two parameters of our constructor are passed to QtService. The last parameter, "Qt HTTP Daemon", is the name of the service. \printto pause() The implementation of \c start() first checks if the user passed a port number. If yes that port is used by server to listen on. Otherwise default 8080 port is used. Then creates an instance of the HTTP server using operator new, passing the application object as the parent to ensure that the object gets destroyed. \printto private: \printuntil }; The implementations of pause() and resume() forward the request to the server object. \printuntil } The main entry point function creates the service object and uses the \c exec() function to execute the service. */ monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/server/server.pro0000644000175000017500000000020711437034034027035 0ustar vettervetterTARGET = httpservice TEMPLATE = app CONFIG += console qt QT = core network SOURCES = main.cpp include(../../src/qtservice.pri) monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/examples.pro0000644000175000017500000000011411437034034026034 0ustar vettervetterTEMPLATE = subdirs SUBDIRS = interactive \ server \ controller monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/controller/0000755000175000017500000000000011554574462025701 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/controller/controller.pro0000644000175000017500000000014611437034034030571 0ustar vettervetterTEMPLATE = app CONFIG += console qt QT = core SOURCES = main.cpp include(../../src/qtservice.pri) monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/controller/main.cpp0000644000175000017500000001737411437034034027327 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include #include #include #include "qtservice.h" int processArgs(int argc, char **argv) { if (argc > 2) { QString arg1(argv[1]); if (arg1 == QLatin1String("-i") || arg1 == QLatin1String("-install")) { if (argc > 2) { QString account; QString password; QString path(argv[2]); if (argc > 3) account = argv[3]; if (argc > 4) password = argv[4]; printf("The service %s installed.\n", (QtServiceController::install(path, account, password) ? "was" : "was not")); return 0; } } else { QString serviceName(argv[1]); QtServiceController controller(serviceName); QString option(argv[2]); if (option == QLatin1String("-u") || option == QLatin1String("-uninstall")) { printf("The service \"%s\" %s uninstalled.\n", controller.serviceName().toLatin1().constData(), (controller.uninstall() ? "was" : "was not")); return 0; } else if (option == QLatin1String("-s") || option == QLatin1String("-start")) { QStringList args; for (int i = 3; i < argc; ++i) args.append(QString::fromLocal8Bit(argv[i])); printf("The service \"%s\" %s started.\n", controller.serviceName().toLatin1().constData(), (controller.start(args) ? "was" : "was not")); return 0; } else if (option == QLatin1String("-t") || option == QLatin1String("-terminate")) { printf("The service \"%s\" %s stopped.\n", controller.serviceName().toLatin1().constData(), (controller.stop() ? "was" : "was not")); return 0; } else if (option == QLatin1String("-p") || option == QLatin1String("-pause")) { printf("The service \"%s\" %s paused.\n", controller.serviceName().toLatin1().constData(), (controller.pause() ? "was" : "was not")); return 0; } else if (option == QLatin1String("-r") || option == QLatin1String("-resume")) { printf("The service \"%s\" %s resumed.\n", controller.serviceName().toLatin1().constData(), (controller.resume() ? "was" : "was not")); return 0; } else if (option == QLatin1String("-c") || option == QLatin1String("-command")) { if (argc > 3) { QString codestr(argv[3]); int code = codestr.toInt(); printf("The command %s sent to the service \"%s\".\n", (controller.sendCommand(code) ? "was" : "was not"), controller.serviceName().toLatin1().constData()); return 0; } } else if (option == QLatin1String("-v") || option == QLatin1String("-version")) { bool installed = controller.isInstalled(); printf("The service\n" "\t\"%s\"\n\n", controller.serviceName().toLatin1().constData()); printf("is %s", (installed ? "installed" : "not installed")); printf(" and %s\n\n", (controller.isRunning() ? "running" : "not running")); if (installed) { printf("path: %s\n", controller.serviceFilePath().toLatin1().data()); printf("description: %s\n", controller.serviceDescription().toLatin1().data()); printf("startup: %s\n", controller.startupType() == QtServiceController::AutoStartup ? "Auto" : "Manual"); } return 0; } } } printf("controller [-i PATH | SERVICE_NAME [-v | -u | -s | -t | -p | -r | -c CODE] | -h] [-w]\n\n" "\t-i(nstall) PATH\t: Install the service\n" "\t-v(ersion)\t: Print status of the service\n" "\t-u(ninstall)\t: Uninstall the service\n" "\t-s(tart)\t: Start the service\n" "\t-t(erminate)\t: Stop the service\n" "\t-p(ause)\t: Pause the service\n" "\t-r(esume)\t: Resume the service\n" "\t-c(ommand) CODE\t: Send a command to the service\n" "\t-h(elp)\t\t: Print this help info\n" "\t-w(ait)\t\t: Wait for keypress when done\n"); return 0; } int main(int argc, char **argv) { #if !defined(Q_WS_WIN) // QtService stores service settings in SystemScope, which normally require root privileges. // To allow testing this example as non-root, we change the directory of the SystemScope settings file. QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath()); qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData()); #endif int result = processArgs(argc, argv); if (QString::fromLocal8Bit(argv[argc-1]) == QLatin1String("-w") || QString::fromLocal8Bit(argv[argc-1]) == QLatin1String("-wait")) { printf("\nPress Enter to continue..."); QFile input; input.open(stdin, QIODevice::ReadOnly); input.readLine(); printf("\n"); } return result; } monav-0.3/routingdaemon/qtservice-2.6_1-opensource/examples/controller/controller.qdoc0000644000175000017500000000775711437034034030736 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ /*! \page qtservice-example-controller.html \title A simple Service Controller It is a very simple implementation of universal command-line controller. This controller can install and control any service written using QtService component. It demonstrates how to use QtServiceController class. On Windows, this is an alternative to using the "Services" Administrative Tool or the built-in \c sc.exe command-line tool to control services. A note about services on Windows Vista: Installing/uninstalling and starting/stopping services requires security privileges. The simplest way to achieve this is to set the "Run as Administrator" property on the executable (right-click the executable file, select Properties, and choose the Compatibilty tab in the Properties dialog). This applies even if you are logged in as Administrator. Also, the command-line shell should be started with "Run as Administrator". Note that the service itself does not need special privileges to run. Only if you want the service to be able to install itself (the -i option) or similar, then the service will need to be run as Administrator. Otherwise, the recommended procedure is to use a controller such as this example and/or the "Services" Administrative Tool to manage the service. A usability hint: in some circumstances, e.g. when running this example on Windows Vista with the "Run as Administrator" property set, output will be sent to a shell window which will close immediately upon termination, not leaving the user enough time to read the output. In such cases, append the -w(ait) argument, which will make the controller wait for a keypress before terminating. Here is the complete source code: \quotefile controller/main.cpp */ monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/0000755000175000017500000000000011554574462022445 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/index.qdoc0000644000175000017500000000210411437034034024403 0ustar vettervetter/*! \page index.html \title Service \section1 Description The QtService component is useful for developing Windows services and Unix daemons. The project provides a QtService template class that can be used to implement service applications, and a QtServiceController class to control a service. On Windows systems the implementation uses the Service Control Manager. On Unix systems services are implemented as daemons. \section1 Classes \list \i QtServiceController \i QtServiceBase \i QtService\endlist \section1 Examples \list \i \link qtservice-example-interactive.html An Interactive Service \endlink \i \link qtservice-example-server.html A simple HTTP Server \endlink \i \link qtservice-example-controller.html A simple Service Controller \endlink \endlist \section1 Tested platforms \list \i Qt 4.4, 4.5 / Windows XP / MSVC.NET 2005 \i Qt 4.4, 4.5 / Linux / gcc \i Qt 4.4, 4.5 / MacOS X 10.5 / gcc \endlist */monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/images/0000755000175000017500000000000011554574462023712 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/images/qt-logo.png0000644000175000017500000000775311437034034026000 0ustar vettervetterPNG  IHDR9C:uIDATxb?bhJnJnJnJnJnJnԡ Є`r'Q( !!Nb_p??F&F312G.yG&ޏ?}eWSSgb( ~™t齸g0sVv`fcdY8E$xdUUex$xd9DDr=#gdd|Uףw9D- 2b8Ͽebddceᔐ╗SWScaB#cfd]-I\ _20110`xzw/).#'˯"ǯ*˫,+')@lY@}fۯͼ 2@d$1H')&#'ç,ϯ*˧,#/%́XgfdOX8Y9s2GC3g@ fFff.3O|v ,l%?fR_|bb`y엉3+ԇ,̌,4 "ͭ32>{E4އ ˯NԦ+Qefdϛ?6:&Ǜ?|"=\n$FFfF /0"`ddf cfbb`dx՛o yAP ,,eebWaá,QܬLL>5Lll10 m00wTVxOÚ bGB8GtUմXplII ׶R/@2 Y{ ]d9#ule+}N6XfJ"խJ13002³ @K"ŭzo?1000@{ lϿ`?ï2"ecgd H.fFfɆ}Ͽߌ"٭윌 y02000Ac<\po/."?;#ߛ!hgddd\<|\300<|?j"-U L9D8E i[ZP?z5fF6? o"b')~?3311g/ ֯cz߿>pvfL~g'""٭Qd'i `Ϳ'?HۅǞy?200 %)h1.7?."ͭ 32yVfFfGyO/:?LL [,?/?^}|:`luX-tN X"_CkǶ>w:7WlSofFcOv{OD7톚)*$@d"7$1CRgɉi[!.f&v_#ɧ{='JXXc`agպ]R\̅?ӧ_ᄏvѦ_2"g|fە(m )\!&&&F{ ba~>qci.O?l-"s܅Ǐ<Ϟn%hm)tN6P߿0H~̌,|ןhmF>1:19_/رcc7k䱞]ۯ咒SaB[?|}kf~?ɍkF/>9*qpQ( @##ïe1| QXn_ #ơp7B]X?F[a'K+ q/̌,,L L 7tDʡz /#300VnC")"/?110qp￿l_GVWNOU_UIPSCؐ?\e``=_R(2r-d?ÿ_?+78$$ +:xBVFn^?cbdd@yĂf```aba㔆L)J sI2Ҥ!#3 > ^y^~o (?+33d:.cfL(H*sJ`Mg222ڥž15,l l"< List of All Members for QtServiceController
  Home

List of All Members for QtServiceController

This is the complete list of members for QtServiceController, including inherited members.


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice.dcf0000644000175000017500000001232011437034034026054 0ustar vettervetter
QtService application
QtServiceBase MessageType QtServiceBase::Warning QtServiceBase::Error QtServiceBase::Success QtServiceBase::Information ServiceFlag ServiceFlags QtServiceBase::Default QtServiceBase::CannotBeStopped QtServiceBase::CanBeSuspended createApplication exec executeApplication instance logMessage pause processCommand resume serviceDescription serviceFlags serviceName setServiceDescription setServiceFlags setStartupType start startupType stop
QtServiceController StartupType QtServiceController::AutoStartup QtServiceController::ManualStartup install isInstalled isRunning pause resume sendCommand serviceDescription serviceFilePath serviceName start startupType stop uninstall
A simple HTTP Server
A simple Service Controller
An Interactive Service
Service
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice-example-controller.html0000644000175000017500000002734511437034034032113 0ustar vettervetter A simple Service Controller
  Home

A simple Service Controller

It is a very simple implementation of universal command-line controller. This controller can install and control any service written using QtService component. It demonstrates how to use QtServiceController class. On Windows, this is an alternative to using the "Services" Administrative Tool or the built-in sc.exe command-line tool to control services.

A note about services on Windows Vista: Installing/uninstalling and starting/stopping services requires security privileges. The simplest way to achieve this is to set the "Run as Administrator" property on the executable (right-click the executable file, select Properties, and choose the Compatibilty tab in the Properties dialog). This applies even if you are logged in as Administrator. Also, the command-line shell should be started with "Run as Administrator". Note that the service itself does not need special privileges to run. Only if you want the service to be able to install itself (the -i option) or similar, then the service will need to be run as Administrator. Otherwise, the recommended procedure is to use a controller such as this example and/or the "Services" Administrative Tool to manage the service.

A usability hint: in some circumstances, e.g. when running this example on Windows Vista with the "Run as Administrator" property set, output will be sent to a shell window which will close immediately upon termination, not leaving the user enough time to read the output. In such cases, append the -w(ait) argument, which will make the controller wait for a keypress before terminating.

Here is the complete source code:

 /****************************************************************************
 **
 ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
 ** All rights reserved.
 ** Contact: Nokia Corporation (qt-info@nokia.com)
 **
 ** This file is part of a Qt Solutions component.
 **
 ** Commercial Usage
 ** Licensees holding valid Qt Commercial licenses may use this file in
 ** accordance with the Qt Solutions Commercial License Agreement provided
 ** with the Software or, alternatively, in accordance with the terms
 ** contained in a written agreement between you and Nokia.
 **
 ** GNU Lesser General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU Lesser
 ** General Public License version 2.1 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL included in the
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU Lesser General Public License version 2.1 requirements
 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 **
 ** In addition, as a special exception, Nokia gives you certain
 ** additional rights. These rights are described in the Nokia Qt LGPL
 ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
 ** package.
 **
 ** GNU General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU
 ** General Public License version 3.0 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL included in the
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU General Public License version 3.0 requirements will be
 ** met: http://www.gnu.org/copyleft/gpl.html.
 **
 ** Please note Third Party Software included with Qt Solutions may impose
 ** additional restrictions and it is the user's responsibility to ensure
 ** that they have met the licensing requirements of the GPL, LGPL, or Qt
 ** Solutions Commercial license and the relevant license of the Third
 ** Party Software they are using.
 **
 ** If you are unsure which license is appropriate for your use, please
 ** contact Nokia at qt-info@nokia.com.
 **
 ****************************************************************************/

 #include <QtCore/QStringList>
 #include <QtCore/QDir>
 #include <QtCore/QSettings>
 #include "qtservice.h"

 int processArgs(int argc, char **argv)
 {
     if (argc > 2) {
         QString arg1(argv[1]);
         if (arg1 == QLatin1String("-i") ||
             arg1 == QLatin1String("-install")) {
             if (argc > 2) {
                 QString account;
                 QString password;
                 QString path(argv[2]);
                 if (argc > 3)
                     account = argv[3];
                 if (argc > 4)
                     password = argv[4];
                 printf("The service %s installed.\n",
                        (QtServiceController::install(path, account, password) ? "was" : "was not"));
                 return 0;
             }
         } else {
             QString serviceName(argv[1]);
             QtServiceController controller(serviceName);
             QString option(argv[2]);
             if (option == QLatin1String("-u") ||
                 option == QLatin1String("-uninstall")) {
                 printf("The service \"%s\" %s uninstalled.\n",
                             controller.serviceName().toLatin1().constData(),
                             (controller.uninstall() ? "was" : "was not"));
                 return 0;
             } else if (option == QLatin1String("-s") ||
                        option == QLatin1String("-start")) {
                 QStringList args;
                 for (int i = 3; i < argc; ++i)
                     args.append(QString::fromLocal8Bit(argv[i]));
                 printf("The service \"%s\" %s started.\n",
                        controller.serviceName().toLatin1().constData(),
                             (controller.start(args) ? "was" : "was not"));
                 return 0;
             } else if (option == QLatin1String("-t") ||
                        option == QLatin1String("-terminate")) {
                 printf("The service \"%s\" %s stopped.\n",
                        controller.serviceName().toLatin1().constData(),
                        (controller.stop() ? "was" : "was not"));
                 return 0;
             } else if (option == QLatin1String("-p") ||
                     option == QLatin1String("-pause")) {
                 printf("The service \"%s\" %s paused.\n",
                        controller.serviceName().toLatin1().constData(),
                        (controller.pause() ? "was" : "was not"));
                 return 0;
             } else if (option == QLatin1String("-r") ||
                        option == QLatin1String("-resume")) {
                 printf("The service \"%s\" %s resumed.\n",
                        controller.serviceName().toLatin1().constData(),
                        (controller.resume() ? "was" : "was not"));
                 return 0;
             } else if (option == QLatin1String("-c") ||
                        option == QLatin1String("-command")) {
                 if (argc > 3) {
                     QString codestr(argv[3]);
                     int code = codestr.toInt();
                     printf("The command %s sent to the service \"%s\".\n",
                            (controller.sendCommand(code) ? "was" : "was not"),
                            controller.serviceName().toLatin1().constData());
                     return 0;
                 }
             } else if (option == QLatin1String("-v") ||
                     option == QLatin1String("-version")) {
                 bool installed = controller.isInstalled();
                 printf("The service\n"
                         "\t\"%s\"\n\n", controller.serviceName().toLatin1().constData());
                 printf("is %s", (installed ? "installed" : "not installed"));
                 printf(" and %s\n\n", (controller.isRunning() ? "running" : "not running"));
                 if (installed) {
                     printf("path: %s\n", controller.serviceFilePath().toLatin1().data());
                     printf("description: %s\n", controller.serviceDescription().toLatin1().data());
                     printf("startup: %s\n", controller.startupType() == QtServiceController::AutoStartup ? "Auto" : "Manual");
                 }
                 return 0;
             }
         }
     }
     printf("controller [-i PATH | SERVICE_NAME [-v | -u | -s | -t | -p | -r | -c CODE] | -h] [-w]\n\n"
             "\t-i(nstall) PATH\t: Install the service\n"
             "\t-v(ersion)\t: Print status of the service\n"
             "\t-u(ninstall)\t: Uninstall the service\n"
             "\t-s(tart)\t: Start the service\n"
             "\t-t(erminate)\t: Stop the service\n"
             "\t-p(ause)\t: Pause the service\n"
             "\t-r(esume)\t: Resume the service\n"
             "\t-c(ommand) CODE\t: Send a command to the service\n"
             "\t-h(elp)\t\t: Print this help info\n"
             "\t-w(ait)\t\t: Wait for keypress when done\n");
     return 0;
 }

 int main(int argc, char **argv)
 {
 #if !defined(Q_WS_WIN)
     // QtService stores service settings in SystemScope, which normally require root privileges.
     // To allow testing this example as non-root, we change the directory of the SystemScope settings file.
     QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
     qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData());
 #endif

     int result = processArgs(argc, argv);

     if (QString::fromLocal8Bit(argv[argc-1]) == QLatin1String("-w") ||
         QString::fromLocal8Bit(argv[argc-1]) == QLatin1String("-wait")) {
         printf("\nPress Enter to continue...");
         QFile input;
         input.open(stdin, QIODevice::ReadOnly);
         input.readLine();
         printf("\n");
     }

     return result;
 }


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice-example-interactive.html0000644000175000017500000001642411437034034032241 0ustar vettervetter An Interactive Service
  Home

An Interactive Service

This example implements a service with a simple user interface.

Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes.

However, although not recommended in the general case, in certain circumstances a service may provide a GUI itself. This is typically only possible if the service process is run as the same user as the one that is logged in, so that it will have access to the screen. Note however that on Windows Vista, service GUIs are not allowed at all, since services run in a diferent session than all user sessions, for security reasons.

This example demonstrates how to subclass the QtService class, the use of start(), stop(), pause(), resume(), and how to use processCommand() to receive control commands while running.

Here is the complete source code:

 /****************************************************************************
 **
 ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
 ** All rights reserved.
 ** Contact: Nokia Corporation (qt-info@nokia.com)
 **
 ** This file is part of a Qt Solutions component.
 **
 ** Commercial Usage
 ** Licensees holding valid Qt Commercial licenses may use this file in
 ** accordance with the Qt Solutions Commercial License Agreement provided
 ** with the Software or, alternatively, in accordance with the terms
 ** contained in a written agreement between you and Nokia.
 **
 ** GNU Lesser General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU Lesser
 ** General Public License version 2.1 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL included in the
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU Lesser General Public License version 2.1 requirements
 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 **
 ** In addition, as a special exception, Nokia gives you certain
 ** additional rights. These rights are described in the Nokia Qt LGPL
 ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
 ** package.
 **
 ** GNU General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU
 ** General Public License version 3.0 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL included in the
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU General Public License version 3.0 requirements will be
 ** met: http://www.gnu.org/copyleft/gpl.html.
 **
 ** Please note Third Party Software included with Qt Solutions may impose
 ** additional restrictions and it is the user's responsibility to ensure
 ** that they have met the licensing requirements of the GPL, LGPL, or Qt
 ** Solutions Commercial license and the relevant license of the Third
 ** Party Software they are using.
 **
 ** If you are unsure which license is appropriate for your use, please
 ** contact Nokia at qt-info@nokia.com.
 **
 ****************************************************************************/

 #include <QtGui/QApplication>
 #include <QtGui/QDesktopWidget>
 #include <QtGui/QLabel>
 #include <QtCore/QDir>
 #include <QtCore/QSettings>
 #include "qtservice.h"

 class InteractiveService : public QtService<QApplication>
 {
 public:
     InteractiveService(int argc, char **argv);
     ~InteractiveService();

 protected:

     void start();
     void stop();
     void pause();
     void resume();
     void processCommand(int code);

 private:
     QLabel *gui;
 };

 InteractiveService::InteractiveService(int argc, char **argv)
     : QtService<QApplication>(argc, argv, "Qt Interactive Service"), gui(0)
 {
     setServiceDescription("A Qt service with user interface.");
     setServiceFlags(QtServiceBase::CanBeSuspended);
 }

 InteractiveService::~InteractiveService()
 {
 }

 void InteractiveService::start()
 {
 #if defined(Q_OS_WIN)
     if ((QSysInfo::WindowsVersion & QSysInfo::WV_NT_based) &&
         (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)) {
         logMessage( "Service GUI not allowed on Windows Vista. See the documentation for this example for more information.", QtServiceBase::Error );
         return;
     }
 #endif

     qApp->setQuitOnLastWindowClosed(false);

     gui = new QLabel("Service", 0, Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
     gui->move(QApplication::desktop()->availableGeometry().topLeft());
     gui->show();
 }

 void InteractiveService::stop()
 {
     delete gui;
 }

 void InteractiveService::pause()
 {
     if (gui)
         gui->hide();
 }

 void InteractiveService::resume()
 {
     if (gui)
         gui->show();
 }

 void InteractiveService::processCommand(int code)
 {
     gui->setText("Command code " + QString::number(code));
     gui->adjustSize();
 }

 int main(int argc, char **argv)
 {
 #if !defined(Q_WS_WIN)
     // QtService stores service settings in SystemScope, which normally require root privileges.
     // To allow testing this example as non-root, we change the directory of the SystemScope settings file.
     QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
     qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData());
 #endif
     InteractiveService service(argc, argv);
     return service.exec();
 }


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservicebase-members.html0000644000175000017500000000746211437034034030562 0ustar vettervetter List of All Members for QtServiceBase
  Home

List of All Members for QtServiceBase

This is the complete list of members for QtServiceBase, including inherited members.


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservicecontroller.html0000644000175000017500000003725011437034034030401 0ustar vettervetter QtServiceController Class Reference
  Home

QtServiceController Class Reference

The QtServiceController class allows you to control services from separate applications. More...

 #include <QtServiceController>

Public Types

Public Functions

Static Public Members

  • bool install ( const QString & serviceFilePath, const QString & account = QString(), const QString & password = QString() )

Detailed Description

The QtServiceController class allows you to control services from separate applications.

QtServiceController provides a collection of functions that lets you install and run a service controlling its execution, as well as query its status.

In order to run a service, the service must be installed in the system's service database using the install() function. The system will start the service depending on the specified StartupType; it can either be started during system startup, or when a process starts it manually.

Once a service is installed, the service can be run and controlled manually using the start(), stop(), pause(), resume() or sendCommand() functions. You can at any time query for the service's status using the isInstalled() and isRunning() functions, or you can query its properties using the serviceDescription(), serviceFilePath(), serviceName() and startupType() functions. For example:

 MyService service;       \\ which inherits QtService
 QString serviceFilePath;

 QtServiceController controller(service.serviceName());

 if (controller.install(serviceFilePath))
     controller.start()

 if (controller.isRunning())
     QMessageBox::information(this, tr("Service Status"),
                              tr("The %1 service is started").arg(controller.serviceName()));

 ...

 controller.stop();
 controller.uninstall();
 }

An instance of the service controller can only control one single service. To control several services within one application, you must create en equal number of service controllers.

The QtServiceController destructor neither stops nor uninstalls the associated service. To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the uninstall() function.

See also QtServiceBase and QtService.


Member Type Documentation

enum QtServiceController::StartupType

This enum describes when a service should be started.

ConstantValueDescription
QtServiceController::AutoStartup0The service is started during system startup.
QtServiceController::ManualStartup1The service must be started manually by a process.

Warning: The StartupType enum is ignored under UNIX-like systems. A service, or daemon, can only be started manually on such systems with current implementation.

See also startupType().


Member Function Documentation

QtServiceController::QtServiceController ( const QString & name )

Creates a controller object for the service with the given name.

QtServiceController::~QtServiceController ()   [virtual]

Destroys the service controller. This neither stops nor uninstalls the controlled service.

To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the uninstall() function.

See also stop() and QtServiceController::uninstall().

bool QtServiceController::install ( const QString & serviceFilePath, const QString & account = QString(), const QString & password = QString() )   [static]

Installs the service with the given serviceFilePath and returns true if the service is installed successfully; otherwise returns false.

On Windows service is installed in the system's service control manager with the given account and password.

On Unix service configuration is written to QSettings::SystemScope using "QtSoftware" as organization name. account and password arguments are ignored.

Warning: Due to the different implementations of how services (daemons) are installed on various UNIX-like systems, this method doesn't integrate the service into the system's startup scripts.

See also uninstall() and start().

bool QtServiceController::isInstalled () const

Returns true if the service is installed; otherwise returns false.

On Windows it uses the system's service control manager.

On Unix it checks configuration written to QSettings::SystemScope using "QtSoftware" as organization name.

See also install().

bool QtServiceController::isRunning () const

Returns true if the service is running; otherwise returns false. A service must be installed before it can be run using a controller.

See also start() and isInstalled().

bool QtServiceController::pause ()

Requests the running service to pause. If the service's state is QtServiceBase::CanBeSuspended, the service will call the QtServiceBase::pause() implementation. The function does nothing if the service is not running.

Returns true if a running service was successfully paused; otherwise returns false.

See also resume(), QtServiceBase::pause(), and QtServiceBase::ServiceFlags.

bool QtServiceController::resume ()

Requests the running service to continue. If the service's state is QtServiceBase::CanBeSuspended, the service will call the QtServiceBase::resume() implementation. This function does nothing if the service is not running.

Returns true if a running service was successfully resumed; otherwise returns false.

See also pause(), QtServiceBase::resume(), and QtServiceBase::ServiceFlags.

bool QtServiceController::sendCommand ( int code )

Sends the user command code to the service. The service will call the QtServiceBase::processCommand() implementation. This function does nothing if the service is not running.

Returns true if the request was sent to a running service; otherwise returns false.

See also QtServiceBase::processCommand().

QString QtServiceController::serviceDescription () const

Returns the description of the controlled service.

See also install() and serviceName().

QString QtServiceController::serviceFilePath () const

Returns the file path to the controlled service.

See also install() and serviceName().

QString QtServiceController::serviceName () const

Returns the name of the controlled service.

See also QtServiceController() and serviceDescription().

bool QtServiceController::start ( const QStringList & arguments )

Starts the installed service passing the given arguments to the service. A service must be installed before a controller can run it.

Returns true if the service could be started; otherwise returns false.

See also install() and stop().

bool QtServiceController::start ()

This is an overloaded function.

Starts the installed service without passing any arguments to the service.

StartupType QtServiceController::startupType () const

Returns the startup type of the controlled service.

See also install() and serviceName().

bool QtServiceController::stop ()

Requests the running service to stop. The service will call the QtServiceBase::stop() implementation unless the service's state is QtServiceBase::CannotBeStopped. This function does nothing if the service is not running.

Returns true if a running service was successfully stopped; otherwise false.

See also start(), QtServiceBase::stop(), and QtServiceBase::ServiceFlags.

bool QtServiceController::uninstall ()

Uninstalls the service and returns true if successful; otherwise returns false.

On Windows service is uninstalled using the system's service control manager.

On Unix service configuration is cleared using QSettings::SystemScope with "QtSoftware" as organization name.

See also install().


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice.html0000644000175000017500000001763511437034034026302 0ustar vettervetter QtService Class Reference
  Home

QtService Class Reference

The QtService is a convenient template class that allows you to create a service for a particular application type. More...

 #include <QtService>

Inherits QtServiceBase.

Public Functions

Protected Functions

Additional Inherited Members


Detailed Description

The QtService is a convenient template class that allows you to create a service for a particular application type.

A Windows service or Unix daemon (a "service"), is a program that runs "in the background" independently of whether a user is logged in or not. A service is often set up to start when the machine boots up, and will typically run continuously as long as the machine is on.

Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes. (In certain circumstances, a service may provide a GUI itself, ref. the "interactive" example documentation).

Note: On Unix systems, this class relies on facilities provided by the QtNetwork module, provided as part of the Qt Open Source Edition and certain Qt Commercial Editions.

The QtService class functionality is inherited from QtServiceBase, but in addition the QtService class binds an instance of QtServiceBase with an application type.

Typically, you will create a service by subclassing the QtService template class. For example:

 class MyService : public QtService<QApplication>
 {
 public:
     MyService(int argc, char **argv);
     ~MyService();

 protected:
     void start();
     void stop();
     void pause();
     void resume();
     void processCommand(int code);
 };

The application type can be QCoreApplication for services without GUI, QApplication for services with GUI or you can use your own custom application type.

You must reimplement the QtServiceBase::start() function to perform the service's work. Usually you create some main object on the heap which is the heart of your service.

In addition, you might want to reimplement the QtServiceBase::pause(), QtServiceBase::processCommand(), QtServiceBase::resume() and QtServiceBase::stop() to intervene the service's process on controller requests. You can control any given service using an instance of the QtServiceController class which also allows you to control services from separate applications. The mentioned functions are all virtual and won't do anything unless they are reimplemented.

Your custom service is typically instantiated in the application's main function. Then the main function will call your service's exec() function, and return the result of that call. For example:

     int main(int argc, char **argv)
     {
         MyService service(argc, argv);
         return service.exec();
     }

When the exec() function is called, it will parse the service specific arguments passed in argv, perform the required actions, and exit.

If none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller.

See also QtServiceBase and QtServiceController.


Member Function Documentation

QtService::QtService ( int argc, char ** argv, const QString & name )

Constructs a QtService object called name. The argc and argv parameters are parsed after the exec() function has been called. Then they are passed to the application's constructor.

There can only be one QtService object in a process.

See also QtServiceBase().

QtService::~QtService ()

Destroys the service object.

Application * QtService::application () const   [protected]

Returns a pointer to the application object.


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice.index0000644000175000017500000004471011437034034026437 0ustar vettervetter monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice.qhp0000644000175000017500000001742711437034034026125 0ustar vettervetter com.nokia.qtsolutions.qtservice_2.6 qdoc qt qtservice solutions qt qtservice solutions
qtservice-example-controller.html index.html qtservice-example-server.html qtservice-example-interactive.html qtservicebase.html qtservice.html qtservicecontroller.html classic.css images/qt-logo.png monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice.qch0000644000175000017500000016000011437034034026072 0ustar vettervetterSQLite format 3@ &  Jcom.nokia.qtsolutions.qtservice_2.6 1solutions1qtserviceqt -aQt Solutions: Service 65.4&3210 qb5H!EE tableNamespaceTableNamespaceTableCREATE TABLE NamespaceTable (Id INTEGER PRIMARY KEY,Name TEXT )n!]]%tableFilterAttributeTableFilterAttributeTableCREATE TABLE FilterAttributeTable (Id INTEGER PRIMARY KEY, Name TEXT )P!IItableFilterNameTableFilterNameTableCREATE TABLE FilterNameTable (Id INTEGER PRIMARY KEY, Name TEXT )H!99!tableFilterTableFilterTableCREATE TABLE FilterTable (NameId INTEGER, FilterAttributeId INTEGER ) ((c$8!55 tableIndexTableIndexTableCREATE TABLE IndexTable (Id INTEGER PRIMARY KEY, Name TEXT, Identifier TEXT, NamespaceId INTEGER, FileId INTEGER, Anchor TEXT )>!EEutableIndexItemTableIndexItemTable CREATE TABLE IndexItemTable (Id INTEGER, IndexId INTEGER )h!MM9tableIndexFilterTableIndexFilterTable CREATE TABLE IndexFilterTable (FilterAttributeId INTEGER, IndexId INTEGER )n!AA]tableContentsTableContentsTable CREATE TABLE ContentsTable (Id INTEGER PRIMARY KEY, NamespaceId INTEGER, Data BLOB ) 87p index.htmlFQt Solutions: Service Documentation:qtservice-example-server.html(A simple HTTP ServerBqtservice-example-controller.html6A simple Service ControllerDqtservice-example-interactive.html,An Interactive Serviceindex.htmlService  77:9 !YYQtableContentsFilterTableContentsFilterTable CREATE TABLE ContentsFilterTable (FilterAttributeId INTEGER, ContentsId INTEGER )| !aa9tableFileAttributeSetTableFileAttributeSetTableCREATE TABLE FileAttributeSetTable (Id INTEGER, FilterAttributeId INTEGER )D !AA tableFileDataTableFileDataTableCREATE TABLE FileDataTable (Id INTEGER PRIMARY KEY, Data BLOB ) /+ % C{tmf_XQJC            tIc$A U9images/qt-logo.png qt-logo.png3 99classic.css classic.css~mqtservicecontroller.htmlQtServiceController Class ReferenceUEqqtservice.htmlQtService Class ReferencefUqtservicebase.htmlQtServiceBase Class Referencexeqtservice-example-interactive.htmlAn Interactive Servicej]qtservice-example-server.htmlA simple HTTP Server)5)index.htmlServiceyqtservice-example-controller.htmlA simple Service Controller   * G*!AAUtableMetaDataTableMetaDataTableCREATE TABLE MetaDataTable(Name Text, Value BLOB )`!99QtableFolderTableFolderTableCREATE TABLE FolderTable(Id INTEGER PRIMARY KEY, Name Text, NamespaceID INTEGER )` !II1tableFileFilterTableFileFilterTableCREATE TABLE FileFilterTable (FilterAttributeId INTEGER, FileId INTEGER )p !AAatableFileNameTableFileNameTableCREATE TABLE FileNameTable (FolderId INTEGER, Name TEXT, FileId INTEGER, Title TEXT )  qdoc A=YCreationDate2009-12-16T11:43:165qchVersion1.0:-B(4z6Z:24ɹK5|i1 zD"xb̺!V"M jF%tTw!7iB@"b@򔣏i3T0HnF@g^@"`SiPT;qBO%ך$WR+FA 2tc6ER)ȱ*.z2@UJނT5R@7L兢 ӻ\GR/ryʍ|F49Ot଺൮b=O>7tB3B"e-w`O; 凱 |H5 <,Ғdw9Xf$|Fg4J)4qq:"tEEsТFHLBԓ(!ŗ赭(biE\Z FB(ft}PBbN!4i%X 4LJFɐ}q 9Jh5CBOP#'13sF*& hd=Vqw2 $e@Qe,QT 6yNf84F}Rb^ u,|lDdb0iM8Oj hАxcS#(J8h` ØV&7 |F'E8KHD>`Bdg*Sk*n,EkS-fU1eCJN9(e BA˙K˼d@6]u\CSŘz$g|vL"~ {uo9 igTTp-P__q-4P9%*,y#2Qg9Ū(2 $,:%W\$2Vʒ&Q#$UL u&X}b[)̸:4 B;BM 5Ǔ %3 zĄC0bL̚&X`R BqLNhɳAsmzl̿I2"JJ<6Wo/ R˹h3lWrk"1dX 枙FUz!a PT},iip9TDI[A CR[:nF\7Z] gSK<_L-p孅_C2rqro*+a%Z*?aJmŹ!bLs1ݲe: X"ݴM 7Y*;7f*_*@2r\tp٫@k[Ub/@w_0r0*d R ,@P'Y@ؗ19 l%2a.f_Le)>wd VRBE'MWlƚ \7 vm^iCifSɄM0-*ENhbsob vəļʤ/^N$3O-6~ XK yN&JC+Jj>5NP{4fejZ+x[p;uCάP )bԄe0|@?=K 2 {'?vocɟy&Ƕ[iZogs/.r}kmxIrHGToA:ec=߫ @fVrH [)=[C l)TJo*+oU]j4Ws_8 >Y YJ ?9Ni4K0t]!d:)]8HXaH/蘭Bi[|xgU!QR|(SjhaewO~c 5B2@y&=Tfj*Z1Lgwuvw\:s_WjQq{mΗ2læؐa?kqD9fm)d W "?Q`Q?Q,fk%tMvYLWȸpȾKWܐ5翰D:,zER밄' n_oZ0)rQȇ{3GbrFSOn3gxT::+*Va](l^^ŻKM@q>Eejn;3b}:( KkBMB\v'5nu2oٙd6ֳ7 U\k۲4-X7XLnz|Hߩ r(gˣ/r}GBZ9(ğ:9}z~кHoa0 F5o1mj`K.}t^n>LK\CMGbuẋ3SG+7ڼ>sa,oǣpZyz ϒ ќGԜ8lnmŹzynn("-(5^t&lǦՇޞ]s0\ٻEm'Li6DƊ)$ɬ8- R]Tlxof#!Za/!vH <#xVSEƹШ&IM@++E 9EjV4|gv(lvtn9x_?]~I(v4ltK@Kpk**_"F d}GrLGqS?==HNLhWD$p Er+7s- Rb>'$It+XcYAh= J91{Na *jE󴶟MW`c%`l\!܀ \(eYQ̽e/ef^`pq()9<)1AfIr qL`ɦǐ(35Sk:L, Js䤨HJ}_z\Xk| ȅ830ZkM2^x&$0%#.!֢<[UHűOnq'Q^#JL_!On,VM kISs%c e/=W~Z!n+Y؎`('2nƃ\?j>󎶏Lht[z^:kOJg7$S$-UK-=!K5'@ʾ_|&]K+|O9ޖ+ojY`M Ƭ.B.ܶה6m{^q#vɇƮ]l1)\0Wme(^2i,$s){x^i~&C/O 8M%s)Q'j4χR@vlD;UQ\c5 ]>h@#?)6t+:G,I5Mx_W/~ =M% N9q+?2MXj1i !<-rQ”*?9hFk JiqfSaǢGN)oD.1V*k~(>+9 pc{ݨ|B%}[3{6*F865?9̘0bP"nΌlyt²}Ȥ7x$XQ&m&Dn) 6Հ"KMx_<bc?Com*ߎ`s됦mP"LƻvJ݃;F y&_Ϟf2w[gC2Xi2PTQlFm^Ep;KbkHu\%#,WRjW ƌ|3c_/xW@LDZhXͺ.:T)\yUd%i&,p5leld> tibudsV6T9UG[}ʒr\71]KJͮ7P\[>tWydRƦם :`*3movkR^\'Pw۔`ʘ] 1F-[tVTV): sY6A~/ps&\ {NPgFjg GUsc-(kdHT[a qKѵSBWɞ)1;=9e`RD^B)pv~ABp%:}iY?qZ0~q[,T_[EdVnP'x9Na , h궼B)k%lO{mhײvㅈ]'AVrD^.ԥ]$0]WY|boPR?*kMy~ilrbU6uVd!',IY&Ikf@R ut2rd)Cf%_6۫5VSCoOyy<]6WH rJ7S/0 ,fe"|Z4-eKF̀` LX$7W^. P! :,#1_Src+r+K0D'aQmv 6`^, 4 b938)+{n>1\q[CWPxCfbC ]u{]gV@ؠl g#SYJ9HQry6?:ԞTK*[OE;sxXG6r! ,z F 7> xVn7}WLY4hR%l| 4SAq)5IMArfΜr6*,=BsSH=Mi'1f.xZ{s6ߟe9*YVNױcM@$$aL4J\o)ROIX&]vxt'd¤"=GXC+O7'o{yJFzx.r~vLV?Ó˛ P"ZHG< cLyXF@Tz#NN`9 ϟ? 3y5"$AܷhT|OyG`oQZOLh‡`Є }i^D,=Cϝn%b(,zuȈHz?{Eа  +xYo6=bVnֱ=Iw؆h[,*$KR?w8q$>'9a{t*QLL|> R-/^|~ 9{6 0y3t(:r&.`*z$ cAVyOyТAƉ0~#ʺ]vgPi,z?|we!r-KHTPE ƯR #"$C Z_SEL@yZSaѸWafe]Kp -%̂"gT23ٚ8~qa80qJwp7NuNb|fF6E#DtӆZ+A|0o`3xۋY-Mbbۑl}Op~]mաzeST8= ̖ԣ ]"߯7ݥKCxT,mS}%)4f2farM׾X6R/<8 QigyAŊ#c7ӇҶNk~d&csi[HlB5*-Xv t>YbSZRxP['i=$=}]x3=]@/>vg"߹Eԟٝy>Ma w;tlEڦy ?];@Ì/MQê@8/Xb0yȕBkZí%j+m.5 v,F&uUطZeXGmϟ`A#~M7@tU>tur$ =U23r4:bZ~J~DE;8,;'V31wㇳQzWӵ9CF >ԇYgNjnnMQ3`mTϦ~|`&: nf٭1öe >rmw77l7`t5.P-'!nCƿ}[sc='9*[֛x܏KoK憩}Qy[^ Eʿ+ c< 4LcP+h;2KBFb&=Gc3{~ {]prH ;Q{;4,1wF\LaKE'쵸fAPXG.fBoSD@kh &?tcDl*tצr+"يbnLln:*0] =|QESNwʄtg\㽋-N&d%^g\ta4@mhʝowk< ; bt?Elľ6 Cgߦ{D^$/^"e_pnz%S1|`*QUT$U.L"K+4O\&S) ds19.M=qw .'b~97FqjLĴȏ"c F̮+qYqgZɍg*[\ҙGLm;-E2zb*H`2wdn*`"&E꜌ Mg14 g8ug|W4,]y8 ^5%=MVc9TrhmS<_RÎwBf82pe-B]T9`rLeOd8XV @Jg;0ϸgk J9#$L^?m0[X4l.s5P(lۘ[J,UEW<۰!'w!#27!s8"'>Ff K>=8*R=&yvSzq5\^р,:2MDt48py<ˊ(1תbw}&z::gܹ'aQ΀ºJ¿7>K3.WA&fbX^} 9Ogs} ~ƀĬꍟU69>&, 4 Ęgh'~HMEY,2K>;:qM{?b?حITv~ 39g4 +MX7TH./z wYÁ ,Bj%\GizBph6Q ٳ42y_נy>ӀS^s.S6YVW\n0Ef2?Y:^}i |1}`'x*#cIq㩇>4ف"PhRP,(ubn tx—߁c v6=A=W 'x@uu@82bJ)dvgW9xiPov;R,Y;D|(_ X΅[ )LrpmcDuk 5Ahȳfg8l,GykoP xy(^`mȽM. r؀@o]}=~0HHX ꍫ7`t"gd}^ɡ%_G}V{qLeĮR7RFj$ґW=>8l@ :Kb꽀ֶCפm_I̎ua8ŝ4v;&NzMn~\Ht@2T^\$Eqyz ev un ǚ!}F蚞3k;賈%{?m##"{ckU6L4٤.KMQn"#Z+V VQ7w5MZu^2;UET٦v,! "X@kծWwS@!*Qh$Vڟh #1mEYOƗfi6ie0W0DR8' fEHf2Z0=4e4[ML2Oma7Ζ9 00I>`!{aby74+ #4fESB+ҧߥW9`]U>. xIpܣ#SrrR-DCo9YqUZϴ77L䀽)kJ`7'AA;-" *KA|nP9R=}89`6Gvx 5y6dL@r}쭯ī6:\⇤ECiOOW̷o|@$Bt(D.&inC<㠄(63XI4Y5D,.A!a^QfIΞ??+^;!ts`+K*ra, pV.R?e>0tHtv2!#"n"`j)ǡg'}c'KʉI@\4ɌҺerTC!g$@PɁiO2&UVdq2_)_:v`Өf!A=g3^$!{c1!tTM0i)3Fh =&G+6"36}__Ȥ\,NnIc1ӿ #ضQ{ 'V㰙/LzMC}j||=h^_mRپaz$8s2i~2\#~nuvݝ]#[qE ȓ([Mˌ"˄O+JYQO`,oO `2q;@ݯN>qpO~զjȊjY} _78ia\+.0CRKӤH$Ci?%2M1eT VκgfJ4EWν9-p[gT2X:-j0^R_m}JEECnWq4J;t#,F85]i RWBy2hG9<ڬl*#19]J;^SHR\lH0.[FL):eՑZƹ/Nnͽ?=TDXq= @p GpL2JV<ЉsP8pćR~!IZZ%i ,"mCT >yPl9fQRMhQR]i'fᦪn[d7Nܴ&qQoaVʀE U}N7]l%[uR遖V"Ba+[ȷ1@ 4Q,xtc+`NkdӞ YaFmͤGĄwED>iE  [ 9Vìn9ĸA8E!ٲzo4ױ$O0&c*y4'MآJ,?Mna5v5I uP!mjZ $U4. OOZ}en#IObvzVCS }ĿNLVC>k"¬[vv՜ua?&v>V.v,a [2w^2124\ʭ4tE&K#<Ig&SY\93ĎQ@ǃsf)έPAME`.+C&J99Ia^^8>5LZ۾JR;fFJ>K+28`d|aNM sqCa_=l6Eo%vKgGkZiRbtgQa:G+/ėp7UtIEv×491DǻQk]xKBF/Fƭ;a=s?6E)>©rDGeN,rY#snsQi֒9NaQKü|סR)=h}fj[y/t8uB=VC^eڀfS݊ckgpxۙ0Vv"Z},ed"o'"m_jauDn20k?z(@\i$k1ۮ18QM\tz|%?NdWER26:NZG{kJ>ձ&)Ta[dRC_2;]:]<ߚܚfs+@ y ԉi %* Y{G)9x[6:yk|sN{ThZZt)25Y4xrD 4u5~a6'7tt b>Zd7ԯOi;;^~KDӍSOp}z^/GQMS*꣆ƴ ַ{XrWEJoY,p JM.}ڭo}Y]}ye2km(k6<16yXrn 09%0'<&` x"Za.~-S^bnv>7Ҝ~7pb3N(E\6PjffJ6U8T&9*Ħ7s$mN!-πV$4#vʆn95BaMM\2n2梢B"#4ei6U#mWPy@m!mcd5S5q&Qt# MQ4}n⹅2'`k^Ri`! Œ[q}s,˦&w#`3s`69|Ub~Y EXo'8Qǝ !2W8e]~2] ق@Dń $Q9|, q`fSDCDA3Qh耈ueSK1h}0+!hVqs#'J69brfPYS›QA'IIh-rp>j^Lp9\+6~ZKç{C#Ira n( lrCVְٌ*I#C9=mU=Ea)҈G"1" c9{`^\a* )Ȯ\e"! AvuZ\jOp͂fCbIcldu 5EHȇFuwv 9Zu3qAxw_~rS;^-´㐿%?[-?؞ȗ+RmKm[RAw}YCֲ\K̲&Y[aoR\#V ɜӘ?I&8ת1X M_ȬB09-ti n~

l.Yq~&jY$D/U5WfOp%,$q.4 hU&18רID6'6-Ǭ|].EZI&%munJH~ i]4-XPm0|@d*fb:/0fYҋk>;( 6CZzk,f+H" EB%R[ggwV**2p\WA9@j"C*=Tq5w#OˊacDV'2FIJ N0$v7N{oy%ѮW4mF^WrfltgJ4 xG6q饟 =" |2| }d!О09]31 ̖8.Y06_!ϠǫYH;+[a|8Ui&B*W t?aeA 3|g 5'4dƯլ,!)7vL~݈]:)푠9U69UtLi=PM*e%lKx]cGCIoqP%螪]w%:7t\wM;۠lŵkurN&3tsǝ}r(tuR!$Ev)2B{ G9 gwD\TSr {@8puGvϵ7xn8~+>K7@Bөrnhڪٸ[;k4pOLZ4P-6/pMPh Љl{F.p\{| @ţC}Ljʖ;G50Q* 71ؒGl-rPp YgwwQiT} 7 WmC fUQAΰh}Uh1Il)p`⠌TY`/""Yv)Ș2#;4aKÑHGQHȔɳt,+hj~&z :8 ?RB3>5fl ޸_ZՀ(لH@3:a DD|էp9"S'S}} B1${i>Rũ4ltBi% 5I)1$"䓃/t߉$~M0O_Miof)ebBD 4gaJEjp1'OR)T}GK'@`SIhN%1ZGYH22((LE& z~RS*I*>jέ6ncۨUV8X B|A41.cX)y3 `A->[8fW09ێ௣tr[ : t⨛K*zᢺSb+=O~ϯep OwvSPuחwp ݀=8vKc0e߰27]?k`t^ۓcLSRS/K'A0 & gIQBSBd7[0Mn.FcHƵhKi=9qeUwHX!Xaa9fXDHpd$zH*9TвL4rJETP]<"Z SROWUh"PݢU$`6H_C\EwɀLi˸"_%&5wS#"1[8q {TpvSkI ǘ P>BXkXME̩Dը6Ga[u}3xx.ӰB5[Ĺjr/M<,ON& qU_Wg;w_cڑbNqk5?HwTA2G%qO ⟨\rb89ljV {;cz'`2-7~eYF^)e3 UDn#*!9L%I)%pu!un+۸~kiL7WZs~"fT$/`,r1QDb˹I]vc[+F-nO[M L.%hݽx9SX5`wf`SE\uC5V qUSagSAkӋ}kC]Pˬ⭺6UCGlRbEM :%-H%S"З\O0eA͆+m$(QFBï0}oÙ|RJK9?5̩EWe2A7UQw 4E۲ݣSo= 99 }߁IRk7A(ƔfrWrkڳKT2oTq SN0 ML f\#iiVuи!nQaX8/ny\cR=1ZnnjCQ飁b-#N^ ?B<^qg.@RcY¸f"Mk\V@!~#;M#f\麒h׼&ꓕ*a.cEYj353YmeK>(8lԬ;X^d{['^7Lf~mo*VE+ⵧeл_rvo-ĆoQR=PD vZz8+8CLR^|m@R>+e ѽPKwTAz. }_?2o;Yjྦྷ5xt[$%*MS˫w0"4^I/wV^]6&jo%\ /ג )9:8xNޠɹpiė#SNbǙ[y`k)SKH3*?wD+ݣw\toM"[u >R;@ b Hxr0~ Hb\ù"4Z*3v2}."qlp3Efӿ={t^oK,4T\q,,q)KβF6gDB/ɠ+Cb!W`}`u@ dY$=x3nCI@jnQS)t! M>Z{+e5TiΧOamsYZ%kUW [<ߓtIrukK4ϕִ\qdoz4Rp(E6|j$~,M}Fkܼլ>%N}߳՗7}y q|8 gi|\w[)MGŃA,BB^#-8oCL$XRQg0?nCI?ߡ.dU3ؘO( R5W+ IKk{bɵ@>x[s۶\SΒ[fk4uHHB4Zv߾)J;ݺ\No~}; ,:DHy>9zw} t/o%S=v{I ~:> ..]LRK7ip{<:`V|F\ES`>}!'ϟqv:(Tߐ^\k OX{`L@dP5 hCuw8"˘$ULX(- `Fz:98Uab~]<mųJ[m8niat}i SׁP]n#N [lh;+b>t>c8+0i4K$۞X7 5Y,1{@ wvtL">LJh~֖HrpJ3)C]ɮ@*?H9 s'S_{ )oVǦLwU|[~U)o/oz`0d8Iy qAL&L1A( =2 K,Y@=6:hiymRhsdKJQǘ 1Sy2O$b11L_~,vn;jtqeo:n[ۀ') ͡YwU[7TWgR }|8Cm@6 E|ßQ iK89E~ё{7 75!u!(xNM=u;z aåܻBÆ3_H&*pu{Y/ S/ᄳ]<Vd~sOM 122"A0ę`,iô}3Jro9y|M"3S&(D2?3yܬ\4OzwKː0T7!L6W.]0a}F 84xO}qgжJ;6:""-?NzJnk^%u/w[3Y騂YALOM׈aHGQt2-^|^'XܸyPY Vtd' Ll퇩m726u0XșCgWqQ"1M; SfƑSw(OSNHa}y.lJ450)HA{Jt$&|;hH hniS:̓^vvU%jwC҇Xelv[OAg3 %JAdL(!#B$_P k!9iX'cVľmk}ϣj%;}(/18>y$/疬Zʉ7O_J|kQV/C^2iPZh\Ls7U|ung੎xr3Ht`\k@q ôuNwf*\J{j㚷0suH_`,oLhQ &;Y}}{ aqC*-59o5(LXm; r Dhz!#1AY"@;W]#u4NGeU`-;cK~@LOCN>H!8j쉔[Ys_@qvR13RࠩWUwE-)*23vȳuD=!RS9spL= 2hA%' XF[*?A_I8@18+3DVujaG9k!%C҄ U7T} >4tdPyaSYeك2/V&%l㗟[^.oQ@@t`V eZ {*fkv#Gс[?%~Y"oG92)[sxhKHlgp@c&'Xgǥl#i%GZZ4y^41 ˧wtfJjY=X82L;+On- j*bna{RGbqӣc]r*dK4_0 |]~sM/W,3ѳ!^{*7>}PДrH}"$CQ?ke"BtfrYSy ;9QA[ұ?X~iXŶiZRZ=-㼐ْ1+G Qt鮲Ǔ P[;Nc0DR&Q|÷{׵*8@;;s__ϩKvcB}8xgzyC,LtYm̡[mҚ%^j 5QTwqa X .R2(wtiT">9ycLPNXiUكqRMbɡOPL;TRD48c.GOafywU: BE33|76RNABA!Rlv.\iܐYAA~vnρ aZP @7K vq=lG33Y!\N8vq 6!6zF.FllE %jQ۰rM{i|`H&!pw OzpcH1<>Ⱦȡ}#ˇYK&'G4UhhXLnTX(g(7^[_ 4bdJ!>D >s@p:2L:P0kN~0;F B vvD$ڹd2ȐL6\*&Jot^L|,BEig"E\gտ{`q5~M4, /yçdâ?{o235MnbhDtjPSngN nʜb(#iсhQ~`ANX0kNԾM%TIyY NOI;}?=Ӱp#Zb,}w" h#/ĕXw3jmI5]]eicck!ݛ9^5kE, }.9} eeMQtServiceBase::SuccessQtServiceBase::SuccessMessageType-enumuuMQtServiceBase::MessageTypeQtServiceBase::MessageTypeMessageType-enum=AAQtServiceBaseQtServiceBasec5aE~QtServiceQtService::~QtServicedtor.QtServicea9e9applicationQtService::applicationapplication-11QtServiceQtServiceaeeAn Interactive ServiceAn Interactive ServiceuyyA simple Service ControllerA simple Service ControllerY]]A simple HTTP ServerA simple HTTP Server mU MQtServiceBase::CanBeSuspendedQtServiceBase::CanBeSuspendedServiceFlag-enumeeMQtServiceBase::DefaultQtServiceBase::DefaultServiceFlag-enum uuMQtServiceBase::ServiceFlagQtServiceBase::ServiceFlagServiceFlag-enum uuMQtServiceBase::InformationQtServiceBase::InformationMessageType-enum eeMQtServiceBase::WarningQtServiceBase::WarningMessageType-enumy ]]MQtServiceBase::ErrorQtServiceBase::ErrorMessageType-enum TZ1YTE!]!pauseQtServiceBase::pausepausec5q5logMessageQtServiceBase::logMessagelogMessageW-i-instanceQtServiceBase::instanceinstanceUUexecuteApplicationQtServiceBase::executeApplicationexecuteApplication?YexecQtServiceBase::execexecQ QcreateApplicationQtServiceBase::createApplicationcreateApplicationyyMQtServiceBase::ServiceFlagsQtServiceBase::ServiceFlagsServiceFlag-enum# MQtServiceBase::CannotBeStoppedQtServiceBase::CannotBeStoppedServiceFlag-enum 5-IIsetServiceFlagsQtServiceBase::setServiceFlagssetServiceFlags&aasetServiceDescriptionQtServiceBase::setServiceDescriptionsetServiceDescriptioni9u9serviceNameQtServiceBase::serviceNameserviceNameo=y=serviceFlagsQtServiceBase::serviceFlagsserviceFlagsUUserviceDescriptionQtServiceBase::serviceDescriptionserviceDescriptionK%a%resumeQtServiceBase::resumeresume|EEprocessCommandQtServiceBase::processCommandprocessCommand U;U+& MQtServiceController::AutoStartupQtServiceController::AutoStartupStartupType-enum+% MQtServiceController::StartupTypeQtServiceController::StartupTypeStartupType-enumU$YYQtServiceControllerQtServiceController#EU~QtServiceBaseQtServiceBase::~QtServiceBasedtor.QtServiceBase?"YstopQtServiceBase::stopstopi!9u9startupTypeQtServiceBase::startupTypestartupTypeE !]!startQtServiceBase::startstart|EEsetStartupTypeQtServiceBase::setStartupTypesetStartupType @Js[@ .U)UserviceDescriptionQtServiceController::serviceDescriptionserviceDescriptionv-9 9sendCommandQtServiceController::sendCommandsendCommandW,%y%resumeQtServiceController::resumeresumeQ+!u!pauseQtServiceController::pausepausej*11isRunningQtServiceController::isRunningisRunningv)9 9isInstalledQtServiceController::isInstalledisInstalled]()})installQtServiceController::installinstall3' MQtServiceController::ManualStartupQtServiceController::ManualStartupStartupType-enum o,s%6))ServiceService45]1m~QtServiceControllerQtServiceController::~QtServiceControllerdtor.QtServiceControllerj411uninstallQtServiceController::uninstalluninstallK3qstopQtServiceController::stopstopv29 9startupTypeQtServiceController::startupTypestartupTypeQ1!u!startQtServiceController::startstartv09 9serviceNameQtServiceController::serviceNameserviceName/IIserviceFilePathQtServiceController::serviceFilePathserviceFilePath p{tmf_XQJC<5.'  xqjc\UNG@92+$|ung`YRKD=6/(! p&o%n%m%l$k$j$i#h#g#f"e"d"c!b!a!` _ ^ ]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)(' & % $ # " !                2wog_WOG?7/'"6!6 6555444333222111000 / / / . ..---,,,+++~*}*|*{)z)y)x(w(v(u't's'r&q&monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservicebase.html0000644000175000017500000006001211437034034027120 0ustar vettervetter QtServiceBase Class Reference
  Home

QtServiceBase Class Reference

The QtServiceBase class provides an API for implementing Windows services and Unix daemons. More...

 #include <QtServiceBase>

Inherited by QtService.

Public Types

Public Functions

Static Public Members

Protected Functions


Detailed Description

The QtServiceBase class provides an API for implementing Windows services and Unix daemons.

A Windows service or Unix daemon (a "service"), is a program that runs "in the background" independently of whether a user is logged in or not. A service is often set up to start when the machine boots up, and will typically run continuously as long as the machine is on.

Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes. (In certain circumstances, a service may provide a GUI itself, ref. the "interactive" example documentation).

Typically, you will create a service by subclassing the QtService template class which inherits QtServiceBase and allows you to create a service for a particular application type.

The Windows implementation uses the NT Service Control Manager, and the application can be controlled through the system administration tools. Services are usually launched using the system account, which requires that all DLLs that the service executable depends on (i.e. Qt), are located in the same directory as the service, or in a system path.

On Unix a service is implemented as a daemon.

You can retrieve the service's description, state, and startup type using the serviceDescription(), serviceFlags() and startupType() functions respectively. The service's state is decribed by the ServiceFlag enum. The mentioned properites can also be set using the corresponding set functions. In addition you can retrieve the service's name using the serviceName() function.

Several of QtServiceBase's protected functions are called on requests from the QtServiceController class:

You can control any given service using an instance of the QtServiceController class which also allows you to control services from separate applications. The mentioned functions are all virtual and won't do anything unless they are reimplemented. You can reimplement these functions to pause and resume the service's execution, as well as process user commands and perform additional clean-ups before shutting down.

QtServiceBase also provides the static instance() function which returns a pointer to an application's QtServiceBase instance. In addition, a service can report events to the system's event log using the logMessage() function. The MessageType enum describes the different types of messages a service reports.

The implementation of a service application's main function typically creates an service object derived by subclassing the QtService template class. Then the main function will call this service's exec() function, and return the result of that call. For example:

 int main(int argc, char **argv)
 {
     MyService service(argc, argv);
     return service.exec();
 }

When the exec() function is called, it will parse the service specific arguments passed in argv, perform the required actions, and return.

The following arguments are recognized as service specific:

ShortLongExplanation
-i-installInstall the service.
-u-uninstallUninstall the service.
-e-execExecute the service as a standalone application (useful for debug purposes). This is a blocking call, the service will be executed like a normal application. In this mode you will not be able to communicate with the service from the contoller.
-t-terminateStop the service.
-p-pausePause the service.
-r-resumeResume a paused service.
-c cmd-command cmdSend the user defined command code cmd to the service application.
-v-versionDisplay version and status information.

If none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller.

See also QtService and QtServiceController.


Member Type Documentation

enum QtServiceBase::MessageType

This enum describes the different types of messages a service reports to the system log.

ConstantValueDescription
QtServiceBase::Success0An operation has succeeded, e.g. the service is started.
QtServiceBase::Error1An operation failed, e.g. the service failed to start.
QtServiceBase::Warning2An operation caused a warning that might require user interaction.
QtServiceBase::Information3Any type of usually non-critical information.

enum QtServiceBase::ServiceFlag
flags QtServiceBase::ServiceFlags

This enum describes the different states of a service.

ConstantValueDescription
QtServiceBase::Default0x00The service can be stopped, but not suspended.
QtServiceBase::CanBeSuspended0x01The service can be suspended.
QtServiceBase::CannotBeStopped0x02The service cannot be stopped.

The ServiceFlags type is a typedef for QFlags<ServiceFlag>. It stores an OR combination of ServiceFlag values.


Member Function Documentation

QtServiceBase::QtServiceBase ( int argc, char ** argv, const QString & name )

Creates a service instance called name. The argc and argv parameters are parsed after the exec() function has been called. Then they are passed to the application's constructor. The application type is determined by the QtService subclass.

The service is neither installed nor started. The name must not contain any backslashes or be longer than 255 characters. In addition, the name must be unique in the system's service database.

See also exec(), start(), and QtServiceController::install().

QtServiceBase::~QtServiceBase ()   [virtual]

Destroys the service object. This neither stops nor uninstalls the service.

To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the QtServiceController::uninstall() function.

See also stop() and QtServiceController::uninstall().

void QtServiceBase::createApplication ( int & argc, char ** argv )   [pure virtual protected]

Creates the application object using the argc and argv parameters.

This function is only called when no service specific arguments were passed to the service constructor, and is called by exec() before it calls the executeApplication() and start() functions.

The createApplication() function is implemented in QtService, but you might want to reimplement it, for example, if the chosen application type's constructor needs additional arguments.

See also exec() and QtService.

int QtServiceBase::exec ()

Executes the service.

When the exec() function is called, it will parse the service specific arguments passed in argv, perform the required actions, and exit.

If none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller.

See also QtServiceController.

int QtServiceBase::executeApplication ()   [pure virtual protected]

Executes the application previously created with the createApplication() function.

This function is only called when no service specific arguments were passed to the service constructor, and is called by exec() after it has called the createApplication() function and before start() function.

This function is implemented in QtService.

See also exec() and createApplication().

QtServiceBase * QtServiceBase::instance ()   [static]

Returns a pointer to the current application's QtServiceBase instance.

void QtServiceBase::logMessage ( const QString & message, MessageType type = Success, int id = 0, uint category = 0, const QByteArray & data = QByteArray() )

Reports a message of the given type with the given message to the local system event log. The message identifier id and the message category are user defined values. The data parameter can contain arbitrary binary data.

Message strings for id and category must be provided by a message file, which must be registered in the system registry. Refer to the MSDN for more information about how to do this on Windows.

See also MessageType.

void QtServiceBase::pause ()   [virtual protected]

Reimplement this function to pause the service's execution (for example to stop a polling timer, or to ignore socket notifiers).

This function is called in reply to controller requests. The default implementation does nothing.

See also resume() and QtServiceController::pause().

void QtServiceBase::processCommand ( int code )   [virtual protected]

Reimplement this function to process the user command code.

This function is called in reply to controller requests. The default implementation does nothing.

See also QtServiceController::sendCommand().

void QtServiceBase::resume ()   [virtual protected]

Reimplement this function to continue the service after a call to pause().

This function is called in reply to controller requests. The default implementation does nothing.

See also pause() and QtServiceController::resume().

QString QtServiceBase::serviceDescription () const

Returns the description of the service.

See also setServiceDescription() and serviceName().

ServiceFlags QtServiceBase::serviceFlags () const

Returns the service's state which is decribed using the ServiceFlag enum.

See also ServiceFlags and setServiceFlags().

QString QtServiceBase::serviceName () const

Returns the name of the service.

See also QtServiceBase() and serviceDescription().

void QtServiceBase::setServiceDescription ( const QString & description )

Sets the description of the service to the given description.

See also serviceDescription().

void QtServiceBase::setServiceFlags ( ServiceFlags flags )

Sets the service's state to the state described by the given flags.

See also ServiceFlags and serviceFlags().

void QtServiceBase::setStartupType ( QtServiceController::StartupType type )

Sets the service's startup type to the given type.

See also QtServiceController::StartupType and startupType().

void QtServiceBase::start ()   [pure virtual protected]

This function must be implemented in QtServiceBase subclasses in order to perform the service's work. Usually you create some main object on the heap which is the heart of your service.

The function is only called when no service specific arguments were passed to the service constructor, and is called by exec() after it has called the executeApplication() function.

Note that you don't need to create an application object or call its exec() function explicitly.

See also exec(), stop(), and QtServiceController::start().

QtServiceController::StartupType QtServiceBase::startupType () const

Returns the service's startup type.

See also QtServiceController::StartupType and setStartupType().

void QtServiceBase::stop ()   [virtual protected]

Reimplement this function to perform additional cleanups before shutting down (for example deleting a main object if it was created in the start() function).

This function is called in reply to controller requests. The default implementation does nothing.

See also start() and QtServiceController::stop().


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice-example-server.html0000644000175000017500000001645311437034034031234 0ustar vettervetter A simple HTTP Server
  Home

A simple HTTP Server

It is a very simple implementation of a HTTP daemon that listens on chosen port (defaultly 8080) and sends back a simple HTML page back for every GET request it gets. After sending the page, it closes the connection.

 // HttpDaemon is the the class that implements the simple HTTP server.
 class HttpDaemon : public QTcpServer
 {
     Q_OBJECT
 public:
     HttpDaemon(quint16 port, QObject* parent = 0)
         : QTcpServer(parent), disabled(false)
     {
         listen(QHostAddress::Any, port);
     }

     void incomingConnection(int socket)
     {
         if (disabled)
             return;

         // When a new client connects, the server constructs a QTcpSocket and all
         // communication with the client is done over this QTcpSocket. QTcpSocket
         // works asynchronously, this means that all the communication is done
         // in the two slots readClient() and discardClient().
         QTcpSocket* s = new QTcpSocket(this);
         connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
         connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
         s->setSocketDescriptor(socket);

         QtServiceBase::instance()->logMessage("New Connection");
     }

     void pause()
     {
         disabled = true;
     }

     void resume()
     {
         disabled = false;
     }

 private slots:
     void readClient()
     {
         if (disabled)
             return;

         // This slot is called when the client sent data to the server. The
         // server looks if it was a get request and sends a very simple HTML
         // document back.
         QTcpSocket* socket = (QTcpSocket*)sender();
         if (socket->canReadLine()) {
             QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
             if (tokens[0] == "GET") {
                 QTextStream os(socket);
                 os.setAutoDetectUnicode(true);
                 os << "HTTP/1.0 200 Ok\r\n"
                     "Content-Type: text/html; charset=\"utf-8\"\r\n"
                     "\r\n"
                     "<h1>Nothing to see here</h1>\n"
                     << QDateTime::currentDateTime().toString() << "\n";
                 socket->close();

                 QtServiceBase::instance()->logMessage("Wrote to client");

                 if (socket->state() == QTcpSocket::UnconnectedState) {
                     delete socket;
                     QtServiceBase::instance()->logMessage("Connection closed");
                 }
             }
         }
     }
     void discardClient()
     {
         QTcpSocket* socket = (QTcpSocket*)sender();
         socket->deleteLater();

         QtServiceBase::instance()->logMessage("Connection closed");
     }

 private:
     bool disabled;
 };

The server implementation uses the QtService::logMessage() function to send messages and status reports to the system event log. The server also supports a paused state in which case incoming requests are ignored.

The HttpService class subclasses QtService to implement the service functionality.

 class HttpService : public QtService<QCoreApplication>
 {
 public:
     HttpService(int argc, char **argv)
         : QtService<QCoreApplication>(argc, argv, "Qt HTTP Daemon")
     {
         setServiceDescription("A dummy HTTP service implemented with Qt");
         setServiceFlags(QtServiceBase::CanBeSuspended);
     }

The constructor calls the QtService constructor instantiated with QCoreApplication since our service will not use GUI. The first two parameters of our constructor are passed to QtService. The last parameter, "Qt HTTP Daemon", is the name of the service.

 protected:
     void start()
     {
         QCoreApplication *app = application();

         quint16 port = (app->argc() > 1) ?
                 QString::fromLocal8Bit(app->argv()[1]).toUShort() : 8080;
         daemon = new HttpDaemon(port, app);

         if (!daemon->isListening()) {
             logMessage(QString("Failed to bind to port %1").arg(daemon->serverPort()), QtServiceBase::Error);
             app->quit();
         }
     }

The implementation of start() first checks if the user passed a port number. If yes that port is used by server to listen on. Otherwise default 8080 port is used. Then creates an instance of the HTTP server using operator new, passing the application object as the parent to ensure that the object gets destroyed.

     void pause()
     {
         daemon->pause();
     }

     void resume()
     {
         daemon->resume();
     }

 private:
     HttpDaemon *daemon;
 };

The implementations of pause() and resume() forward the request to the server object.

 #include "main.moc"

 int main(int argc, char **argv)
 {
 #if !defined(Q_WS_WIN)
     // QtService stores service settings in SystemScope, which normally require root privileges.
     // To allow testing this example as non-root, we change the directory of the SystemScope settings file.
     QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
     qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData());
 #endif
     HttpService service(argc, argv);
     return service.exec();
 }

The main entry point function creates the service object and uses the exec() function to execute the service.


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/index.html0000644000175000017500000000461711437034034025400 0ustar vettervetter Service
  Home

Service

Description

The QtService component is useful for developing Windows services and Unix daemons.

The project provides a QtService template class that can be used to implement service applications, and a QtServiceController class to control a service.

On Windows systems the implementation uses the Service Control Manager.

On Unix systems services are implemented as daemons.

Classes

Examples

Tested platforms

  • Qt 4.4, 4.5 / Windows XP / MSVC.NET 2005
  • Qt 4.4, 4.5 / Linux / gcc
  • Qt 4.4, 4.5 / MacOS X 10.5 / gcc


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/qtservice-members.html0000644000175000017500000000756711437034034027735 0ustar vettervetter List of All Members for QtService
  Home

List of All Members for QtService

This is the complete list of members for QtService, including inherited members.


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
monav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/images/0000755000175000017500000000000011554574462024656 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/doc/html/images/qt-logo.png0000644000175000017500000000775311437034034026744 0ustar vettervetterPNG  IHDR9C:uIDATxb?bhJnJnJnJnJnJnԡ Є`r'Q( !!Nb_p??F&F312G.yG&ޏ?}eWSSgb( ~™t齸g0sVv`fcdY8E$xdUUex$xd9DDr=#gdd|Uףw9D- 2b8Ͽebddceᔐ╗SWScaB#cfd]-I\ _20110`xzw/).#'˯"ǯ*˫,+')@lY@}fۯͼ 2@d$1H')&#'ç,ϯ*˧,#/%́XgfdOX8Y9s2GC3g@ fFff.3O|v ,l%?fR_|bb`y엉3+ԇ,̌,4 "ͭ32>{E4އ ˯NԦ+Qefdϛ?6:&Ǜ?|"=\n$FFfF /0"`ddf cfbb`dx՛o yAP ,,eebWaá,QܬLL>5Lll10 m00wTVxOÚ bGB8GtUմXplII ׶R/@2 Y{ ]d9#ule+}N6XfJ"խJ13002³ @K"ŭzo?1000@{ lϿ`?ï2"ecgd H.fFfɆ}Ͽߌ"٭윌 y02000Ac<\po/."?;#ߛ!hgddd\<|\300<|?j"-U L9D8E i[ZP?z5fF6? o"b')~?3311g/ ֯cz߿>pvfL~g'""٭Qd'i `Ϳ'?HۅǞy?200 %)h1.7?."ͭ 32yVfFfGyO/:?LL [,?/?^}|:`luX-tN X"_CkǶ>w:7WlSofFcOv{OD7톚)*$@d"7$1CRgɉi[!.f&v_#ɧ{='JXXc`agպ]R\̅?ӧ_ᄏvѦ_2"g|fە(m )\!&&&F{ ba~>qci.O?l-"s܅Ǐ<Ϟn%hm)tN6P߿0H~̌,|ןhmF>1:19_/رcc7k䱞]ۯ咒SaB[?|}kf~?ɍkF/>9*qpQ( @##ïe1| QXn_ #ơp7B]X?F[a'K+ q/̌,,L L 7tDʡz /#300VnC")"/?110qp￿l_GVWNOU_UIPSCؐ?\e``=_R(2r-d?ÿ_?+78$$ +:xBVFn^?cbdd@yĂf```aba㔆L)J sI2Ҥ!#3 > ^y^~o (?+33d:.cfL(H*sJ`Mg222ڥž15,l l"< .licenseAccepted break elif [ "x$answer" = "xe" -o "x$answer" = "xE" ]; then more LGPL_EXCEPTION.txt elif [ "x$answer" = "xl" -o "x$answer" = "xL" ]; then more LICENSE.LGPL elif [ "x$answer" = "xg" -o "x$answer" = "xG" ]; then more LICENSE.GPL3 fi done else while true; do echo echo "Please choose your region." echo echo "Type 1 for North or South America." echo "Type 2 for anywhere outside North and South America." echo echo "Select: " read region if [ "x$region" = "x1" ]; then licenseFile=LICENSE.US break; elif [ "x$region" = "x2" ]; then licenseFile=LICENSE.NO break; fi done while true; do echo echo "License Agreement" echo echo "Type '?' to view the Qt Solutions Commercial License." echo "Type 'yes' to accept this license offer." echo "Type 'no' to decline this license offer." echo echo "Do you accept the terms of this license? " read answer echo if [ "x$answer" = "xno" ]; then echo "You are not licensed to use this software." echo exit 1 elif [ "x$answer" = "xyes" ]; then echo license accepted > .licenseAccepted cp "$licenseFile" LICENSE rm LICENSE.US rm LICENSE.NO break elif [ "x$answer" = "x?" ]; then more "$licenseFile" fi done fi fi rm -f config.pri if [ "x$1" = "x-library" ]; then echo "Configuring to build this component as a dynamic library." echo "SOLUTIONS_LIBRARY = yes" > config.pri fi echo echo "This component is now configured." echo echo "To build the component library (if requested) and example(s)," echo "run qmake and your make command." echo echo "To remove or reconfigure, run make distclean." echo monav-0.3/routingdaemon/qtservice-2.6_1-opensource/buildlib/0000755000175000017500000000000011554574462023466 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/buildlib/buildlib.pro0000644000175000017500000000063711437034034025766 0ustar vettervetterTEMPLATE=lib CONFIG += qt dll qtservice-buildlib mac:CONFIG += absolute_library_soname win32|mac:!wince*:!win32-msvc:!macx-xcode:CONFIG += debug_and_release build_all include(../src/qtservice.pri) TARGET = $$QTSERVICE_LIBNAME DESTDIR = $$QTSERVICE_LIBDIR win32 { DLLDESTDIR = $$[QT_INSTALL_BINS] QMAKE_DISTCLEAN += $$[QT_INSTALL_BINS]\\$${QTSERVICE_LIBNAME}.dll } target.path = $$DESTDIR INSTALLS += target monav-0.3/routingdaemon/qtservice-2.6_1-opensource/LGPL_EXCEPTION.txt0000644000175000017500000000216611437034034024604 0ustar vettervetterNokia Qt LGPL Exception version 1.1 As an additional permission to the GNU Lesser General Public License version 2.1, the object code form of a "work that uses the Library" may incorporate material from a header file that is part of the Library. You may distribute such object code under terms of your choice, provided that: (i) the header files of the Library have not been modified; and (ii) the incorporated material is limited to numerical parameters, data structure layouts, accessors, macros, inline functions and templates; and (iii) you comply with the terms of Section 6 of the GNU Lesser General Public License version 2.1. Moreover, you may apply this exception to a modified version of the Library, provided that such modification does not involve copying material from the Library into the modified Library?s header files unless such material is limited to (i) numerical parameters; (ii) data structure layouts; (iii) accessors; and (iv) small macros, templates and inline functions of five lines or less in length. Furthermore, you are not required to apply this additional permission to a modified version of the Library. monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/0000755000175000017500000000000011554574462022467 5ustar vettervettermonav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtservice_win.cpp0000644000175000017500000007423111437034034026046 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include "qtservice.h" #include "qtservice_p.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(QTSERVICE_DEBUG) #include #endif typedef SERVICE_STATUS_HANDLE(WINAPI*PRegisterServiceCtrlHandler)(const wchar_t*,LPHANDLER_FUNCTION); static PRegisterServiceCtrlHandler pRegisterServiceCtrlHandler = 0; typedef BOOL(WINAPI*PSetServiceStatus)(SERVICE_STATUS_HANDLE,LPSERVICE_STATUS); static PSetServiceStatus pSetServiceStatus = 0; typedef BOOL(WINAPI*PChangeServiceConfig2)(SC_HANDLE,DWORD,LPVOID); static PChangeServiceConfig2 pChangeServiceConfig2 = 0; typedef BOOL(WINAPI*PCloseServiceHandle)(SC_HANDLE); static PCloseServiceHandle pCloseServiceHandle = 0; typedef SC_HANDLE(WINAPI*PCreateService)(SC_HANDLE,LPCTSTR,LPCTSTR,DWORD,DWORD,DWORD,DWORD,LPCTSTR,LPCTSTR,LPDWORD,LPCTSTR,LPCTSTR,LPCTSTR); static PCreateService pCreateService = 0; typedef SC_HANDLE(WINAPI*POpenSCManager)(LPCTSTR,LPCTSTR,DWORD); static POpenSCManager pOpenSCManager = 0; typedef BOOL(WINAPI*PDeleteService)(SC_HANDLE); static PDeleteService pDeleteService = 0; typedef SC_HANDLE(WINAPI*POpenService)(SC_HANDLE,LPCTSTR,DWORD); static POpenService pOpenService = 0; typedef BOOL(WINAPI*PQueryServiceStatus)(SC_HANDLE,LPSERVICE_STATUS); static PQueryServiceStatus pQueryServiceStatus = 0; typedef BOOL(WINAPI*PStartServiceCtrlDispatcher)(CONST SERVICE_TABLE_ENTRY*); static PStartServiceCtrlDispatcher pStartServiceCtrlDispatcher = 0; typedef BOOL(WINAPI*PStartService)(SC_HANDLE,DWORD,const wchar_t**); static PStartService pStartService = 0; typedef BOOL(WINAPI*PControlService)(SC_HANDLE,DWORD,LPSERVICE_STATUS); static PControlService pControlService = 0; typedef HANDLE(WINAPI*PDeregisterEventSource)(HANDLE); static PDeregisterEventSource pDeregisterEventSource = 0; typedef BOOL(WINAPI*PReportEvent)(HANDLE,WORD,WORD,DWORD,PSID,WORD,DWORD,LPCTSTR*,LPVOID); static PReportEvent pReportEvent = 0; typedef HANDLE(WINAPI*PRegisterEventSource)(LPCTSTR,LPCTSTR); static PRegisterEventSource pRegisterEventSource = 0; typedef DWORD(WINAPI*PRegisterServiceProcess)(DWORD,DWORD); static PRegisterServiceProcess pRegisterServiceProcess = 0; typedef BOOL(WINAPI*PQueryServiceConfig)(SC_HANDLE,LPQUERY_SERVICE_CONFIG,DWORD,LPDWORD); static PQueryServiceConfig pQueryServiceConfig = 0; typedef BOOL(WINAPI*PQueryServiceConfig2)(SC_HANDLE,DWORD,LPBYTE,DWORD,LPDWORD); static PQueryServiceConfig2 pQueryServiceConfig2 = 0; #define RESOLVE(name) p##name = (P##name)lib.resolve(#name); #define RESOLVEA(name) p##name = (P##name)lib.resolve(#name"A"); #define RESOLVEW(name) p##name = (P##name)lib.resolve(#name"W"); static bool winServiceInit() { if (!pOpenSCManager) { QLibrary lib("advapi32"); // only resolve unicode versions RESOLVEW(RegisterServiceCtrlHandler); RESOLVE(SetServiceStatus); RESOLVEW(ChangeServiceConfig2); RESOLVE(CloseServiceHandle); RESOLVEW(CreateService); RESOLVEW(OpenSCManager); RESOLVE(DeleteService); RESOLVEW(OpenService); RESOLVE(QueryServiceStatus); RESOLVEW(StartServiceCtrlDispatcher); RESOLVEW(StartService); // need only Ansi version RESOLVE(ControlService); RESOLVE(DeregisterEventSource); RESOLVEW(ReportEvent); RESOLVEW(RegisterEventSource); RESOLVEW(QueryServiceConfig); RESOLVEW(QueryServiceConfig2); } return pOpenSCManager != 0; } bool QtServiceController::isInstalled() const { Q_D(const QtServiceController); bool result = false; if (!winServiceInit()) return result; // Open the Service Control Manager SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); if (hSCM) { // Try to open the service SC_HANDLE hService = pOpenService(hSCM, (wchar_t*)d->serviceName.utf16(), SERVICE_QUERY_CONFIG); if (hService) { result = true; pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } bool QtServiceController::isRunning() const { Q_D(const QtServiceController); bool result = false; if (!winServiceInit()) return result; // Open the Service Control Manager SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); if (hSCM) { // Try to open the service SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_QUERY_STATUS); if (hService) { SERVICE_STATUS info; int res = pQueryServiceStatus(hService, &info); if (res) result = info.dwCurrentState != SERVICE_STOPPED; pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } QString QtServiceController::serviceFilePath() const { Q_D(const QtServiceController); QString result; if (!winServiceInit()) return result; // Open the Service Control Manager SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); if (hSCM) { // Try to open the service SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_QUERY_CONFIG); if (hService) { DWORD sizeNeeded = 0; char data[8 * 1024]; if (pQueryServiceConfig(hService, (LPQUERY_SERVICE_CONFIG)data, 8 * 1024, &sizeNeeded)) { LPQUERY_SERVICE_CONFIG config = (LPQUERY_SERVICE_CONFIG)data; result = QString::fromUtf16((const ushort*)config->lpBinaryPathName); } pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } QString QtServiceController::serviceDescription() const { Q_D(const QtServiceController); QString result; if (!winServiceInit()) return result; // Open the Service Control Manager SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); if (hSCM) { // Try to open the service SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_QUERY_CONFIG); if (hService) { DWORD dwBytesNeeded; char data[8 * 1024]; if (pQueryServiceConfig2( hService, SERVICE_CONFIG_DESCRIPTION, (unsigned char *)data, 8096, &dwBytesNeeded)) { LPSERVICE_DESCRIPTION desc = (LPSERVICE_DESCRIPTION)data; if (desc->lpDescription) result = QString::fromUtf16((const ushort*)desc->lpDescription); } pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } QtServiceController::StartupType QtServiceController::startupType() const { Q_D(const QtServiceController); StartupType result = ManualStartup; if (!winServiceInit()) return result; // Open the Service Control Manager SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); if (hSCM) { // Try to open the service SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_QUERY_CONFIG); if (hService) { DWORD sizeNeeded = 0; char data[8 * 1024]; if (pQueryServiceConfig(hService, (QUERY_SERVICE_CONFIG *)data, 8 * 1024, &sizeNeeded)) { QUERY_SERVICE_CONFIG *config = (QUERY_SERVICE_CONFIG *)data; result = config->dwStartType == SERVICE_DEMAND_START ? ManualStartup : AutoStartup; } pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } bool QtServiceController::uninstall() { Q_D(QtServiceController); bool result = false; if (!winServiceInit()) return result; // Open the Service Control Manager SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS); if (hSCM) { // Try to open the service SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), DELETE); if (hService) { if (pDeleteService(hService)) result = true; pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } bool QtServiceController::start(const QStringList &args) { Q_D(QtServiceController); bool result = false; if (!winServiceInit()) return result; // Open the Service Control Manager SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); if (hSCM) { // Try to open the service SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_START); if (hService) { QVector argv(args.size()); for (int i = 0; i < args.size(); ++i) argv[i] = (const wchar_t*)args.at(i).utf16(); if (pStartService(hService, args.size(), argv.data())) result = true; pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } bool QtServiceController::stop() { Q_D(QtServiceController); bool result = false; if (!winServiceInit()) return result; SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); if (hSCM) { SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_STOP|SERVICE_QUERY_STATUS); if (hService) { SERVICE_STATUS status; if (pControlService(hService, SERVICE_CONTROL_STOP, &status)) { bool stopped = status.dwCurrentState == SERVICE_STOPPED; int i = 0; while(!stopped && i < 10) { Sleep(200); if (!pQueryServiceStatus(hService, &status)) break; stopped = status.dwCurrentState == SERVICE_STOPPED; ++i; } result = stopped; } else { qErrnoWarning(GetLastError(), "stopping"); } pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } bool QtServiceController::pause() { Q_D(QtServiceController); bool result = false; if (!winServiceInit()) return result; SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); if (hSCM) { SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_PAUSE_CONTINUE); if (hService) { SERVICE_STATUS status; if (pControlService(hService, SERVICE_CONTROL_PAUSE, &status)) result = true; pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } bool QtServiceController::resume() { Q_D(QtServiceController); bool result = false; if (!winServiceInit()) return result; SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); if (hSCM) { SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_PAUSE_CONTINUE); if (hService) { SERVICE_STATUS status; if (pControlService(hService, SERVICE_CONTROL_CONTINUE, &status)) result = true; pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } bool QtServiceController::sendCommand(int code) { Q_D(QtServiceController); bool result = false; if (!winServiceInit()) return result; if (code < 0 || code > 127 || !isRunning()) return result; SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); if (hSCM) { SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_USER_DEFINED_CONTROL); if (hService) { SERVICE_STATUS status; if (pControlService(hService, 128 + code, &status)) result = true; pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } #if defined(QTSERVICE_DEBUG) extern void qtServiceLogDebug(QtMsgType type, const char* msg); #endif void QtServiceBase::logMessage(const QString &message, MessageType type, int id, uint category, const QByteArray &data) { #if defined(QTSERVICE_DEBUG) QByteArray dbgMsg("[LOGGED "); switch (type) { case Error: dbgMsg += "Error] " ; break; case Warning: dbgMsg += "Warning] "; break; case Success: dbgMsg += "Success] "; break; case Information: //fall through default: dbgMsg += "Information] "; break; } dbgMsg += message.toAscii(); qtServiceLogDebug((QtMsgType)-1, dbgMsg.constData()); #endif Q_D(QtServiceBase); if (!winServiceInit()) return; WORD wType; switch (type) { case Error: wType = EVENTLOG_ERROR_TYPE; break; case Warning: wType = EVENTLOG_WARNING_TYPE; break; case Information: wType = EVENTLOG_INFORMATION_TYPE; break; default: wType = EVENTLOG_SUCCESS; break; } HANDLE h = pRegisterEventSource(0, (wchar_t *)d->controller.serviceName().utf16()); if (h) { const wchar_t *msg = (wchar_t*)message.utf16(); const char *bindata = data.size() ? data.constData() : 0; pReportEvent(h, wType, category, id, 0, 1, data.size(),(const wchar_t **)&msg, const_cast(bindata)); pDeregisterEventSource(h); } } class QtServiceControllerHandler : public QObject { Q_OBJECT public: QtServiceControllerHandler(QtServiceSysPrivate *sys); protected: void customEvent(QEvent *e); private: QtServiceSysPrivate *d_sys; }; class QtServiceSysPrivate { public: enum { QTSERVICE_STARTUP = 256 }; QtServiceSysPrivate(); void setStatus( DWORD dwState ); void setServiceFlags(QtServiceBase::ServiceFlags flags); DWORD serviceFlags(QtServiceBase::ServiceFlags flags) const; inline bool available() const; static void WINAPI serviceMain( DWORD dwArgc, wchar_t** lpszArgv ); static void WINAPI handler( DWORD dwOpcode ); SERVICE_STATUS status; SERVICE_STATUS_HANDLE serviceStatus; QStringList serviceArgs; static QtServiceSysPrivate *instance; static QCoreApplication::EventFilter nextFilter; QWaitCondition condition; QMutex mutex; QSemaphore startSemaphore; QSemaphore startSemaphore2; QtServiceControllerHandler *controllerHandler; void handleCustomEvent(QEvent *e); }; QtServiceControllerHandler::QtServiceControllerHandler(QtServiceSysPrivate *sys) : QObject(), d_sys(sys) { } void QtServiceControllerHandler::customEvent(QEvent *e) { d_sys->handleCustomEvent(e); } QtServiceSysPrivate *QtServiceSysPrivate::instance = 0; QCoreApplication::EventFilter QtServiceSysPrivate::nextFilter = 0; QtServiceSysPrivate::QtServiceSysPrivate() { instance = this; } inline bool QtServiceSysPrivate::available() const { return 0 != pOpenSCManager; } void WINAPI QtServiceSysPrivate::serviceMain(DWORD dwArgc, wchar_t** lpszArgv) { if (!instance || !QtServiceBase::instance()) return; // Windows spins off a random thread to call this function on // startup, so here we just signal to the QApplication event loop // in the main thread to go ahead with start()'ing the service. for (DWORD i = 0; i < dwArgc; i++) instance->serviceArgs.append(QString::fromUtf16((unsigned short*)lpszArgv[i])); instance->startSemaphore.release(); // let the qapp creation start instance->startSemaphore2.acquire(); // wait until its done // Register the control request handler instance->serviceStatus = pRegisterServiceCtrlHandler((TCHAR*)QtServiceBase::instance()->serviceName().utf16(), handler); if (!instance->serviceStatus) // cannot happen - something is utterly wrong return; handler(QTSERVICE_STARTUP); // Signal startup to the application - // causes QtServiceBase::start() to be called in the main thread // The MSDN doc says that this thread should just exit - the service is // running in the main thread (here, via callbacks in the handler thread). } // The handler() is called from the thread that called // StartServiceCtrlDispatcher, i.e. our HandlerThread, and // not from the main thread that runs the event loop, so we // have to post an event to ourselves, and use a QWaitCondition // and a QMutex to synchronize. void QtServiceSysPrivate::handleCustomEvent(QEvent *e) { int code = e->type() - QEvent::User; switch(code) { case QTSERVICE_STARTUP: // Startup QtServiceBase::instance()->start(); break; case SERVICE_CONTROL_STOP: QtServiceBase::instance()->stop(); QCoreApplication::instance()->quit(); break; case SERVICE_CONTROL_PAUSE: QtServiceBase::instance()->pause(); break; case SERVICE_CONTROL_CONTINUE: QtServiceBase::instance()->resume(); break; default: if (code >= 128 && code <= 255) QtServiceBase::instance()->processCommand(code - 128); break; } mutex.lock(); condition.wakeAll(); mutex.unlock(); } void WINAPI QtServiceSysPrivate::handler( DWORD code ) { if (!instance) return; instance->mutex.lock(); switch (code) { case QTSERVICE_STARTUP: // QtService startup (called from WinMain when started) instance->setStatus(SERVICE_START_PENDING); QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); instance->condition.wait(&instance->mutex); instance->setStatus(SERVICE_RUNNING); break; case SERVICE_CONTROL_STOP: // 1 instance->setStatus(SERVICE_STOP_PENDING); QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); instance->condition.wait(&instance->mutex); // status will be reported as stopped in start() when qapp::exec returns break; case SERVICE_CONTROL_PAUSE: // 2 instance->setStatus(SERVICE_PAUSE_PENDING); QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); instance->condition.wait(&instance->mutex); instance->setStatus(SERVICE_PAUSED); break; case SERVICE_CONTROL_CONTINUE: // 3 instance->setStatus(SERVICE_CONTINUE_PENDING); QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); instance->condition.wait(&instance->mutex); instance->setStatus(SERVICE_RUNNING); break; case SERVICE_CONTROL_INTERROGATE: // 4 break; default: if ( code >= 128 && code <= 255 ) { QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); instance->condition.wait(&instance->mutex); } break; } instance->mutex.unlock(); // Report current status if (instance->available() && instance->status.dwCurrentState != SERVICE_STOPPED) pSetServiceStatus(instance->serviceStatus, &instance->status); } void QtServiceSysPrivate::setStatus(DWORD state) { if (!available()) return; status.dwCurrentState = state; pSetServiceStatus(serviceStatus, &status); } void QtServiceSysPrivate::setServiceFlags(QtServiceBase::ServiceFlags flags) { if (!available()) return; status.dwControlsAccepted = serviceFlags(flags); pSetServiceStatus(serviceStatus, &status); } DWORD QtServiceSysPrivate::serviceFlags(QtServiceBase::ServiceFlags flags) const { DWORD control = 0; if (flags & QtServiceBase::CanBeSuspended) control |= SERVICE_ACCEPT_PAUSE_CONTINUE; if (!(flags & QtServiceBase::CannotBeStopped)) control |= SERVICE_ACCEPT_STOP; return control; } #include "qtservice_win.moc" class HandlerThread : public QThread { public: HandlerThread() : success(true), console(false), QThread() {} bool calledOk() { return success; } bool runningAsConsole() { return console; } protected: bool success, console; void run() { SERVICE_TABLE_ENTRYW st [2]; st[0].lpServiceName = (wchar_t*)QtServiceBase::instance()->serviceName().utf16(); st[0].lpServiceProc = QtServiceSysPrivate::serviceMain; st[1].lpServiceName = 0; st[1].lpServiceProc = 0; success = (pStartServiceCtrlDispatcher(st) != 0); // should block if (!success) { if (GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) { // Means we're started from console, not from service mgr // start() will ask the mgr to start another instance of us as a service instead console = true; } else { QtServiceBase::instance()->logMessage(QString("The Service failed to start [%1]").arg(qt_error_string(GetLastError())), QtServiceBase::Error); } QtServiceSysPrivate::instance->startSemaphore.release(); // let start() continue, since serviceMain won't be doing it } } }; /* Ignore WM_ENDSESSION system events, since they make the Qt kernel quit */ bool myEventFilter(void* message, long* result) { MSG* msg = reinterpret_cast(message); if (!msg || (msg->message != WM_ENDSESSION) || !(msg->lParam & ENDSESSION_LOGOFF)) return QtServiceSysPrivate::nextFilter ? QtServiceSysPrivate::nextFilter(message, result) : false; if (QtServiceSysPrivate::nextFilter) QtServiceSysPrivate::nextFilter(message, result); if (result) *result = TRUE; return true; } /* There are three ways we can be started: - By a service controller (e.g. the Services control panel), with no (service-specific) arguments. ServiceBase::exec() will then call start() below, and the service will start. - From the console, but with no (service-specific) arguments. This means we should ask a controller to start the service (i.e. another instance of this executable), and then just terminate. We discover this case (as different from the above) by the fact that StartServiceCtrlDispatcher will return an error, instead of blocking. - From the console, with -e(xec) argument. ServiceBase::exec() will then call ServiceBasePrivate::exec(), which calls ServiceBasePrivate::run(), which runs the application as a normal program. */ bool QtServiceBasePrivate::start() { sysInit(); if (!winServiceInit()) return false; // Since StartServiceCtrlDispatcher() blocks waiting for service // control events, we need to call it in another thread, so that // the main thread can run the QApplication event loop. HandlerThread* ht = new HandlerThread(); ht->start(); QtServiceSysPrivate* sys = QtServiceSysPrivate::instance; // Wait until service args have been received by serviceMain. // If Windows doesn't call serviceMain (or // StartServiceControlDispatcher doesn't return an error) within // a timeout of 20 secs, something is very wrong; give up if (!sys->startSemaphore.tryAcquire(1, 20000)) return false; if (!ht->calledOk()) { if (ht->runningAsConsole()) return controller.start(args.mid(1)); else return false; } int argc = sys->serviceArgs.size(); QVector argv(argc); QList argvData; for (int i = 0; i < argc; ++i) argvData.append(sys->serviceArgs.at(i).toLocal8Bit()); for (int i = 0; i < argc; ++i) argv[i] = argvData[i].data(); q_ptr->createApplication(argc, argv.data()); QCoreApplication *app = QCoreApplication::instance(); if (!app) return false; QtServiceSysPrivate::nextFilter = app->setEventFilter(myEventFilter); sys->controllerHandler = new QtServiceControllerHandler(sys); sys->startSemaphore2.release(); // let serviceMain continue (and end) sys->status.dwWin32ExitCode = q_ptr->executeApplication(); sys->setStatus(SERVICE_STOPPED); if (ht->isRunning()) ht->wait(1000); // let the handler thread finish delete sys->controllerHandler; sys->controllerHandler = 0; if (ht->isFinished()) delete ht; delete app; sysCleanup(); return true; } bool QtServiceBasePrivate::install(const QString &account, const QString &password) { bool result = false; if (!winServiceInit()) return result; // Open the Service Control Manager SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS); if (hSCM) { QString acc = account; DWORD dwStartType = startupType == QtServiceController::AutoStartup ? SERVICE_AUTO_START : SERVICE_DEMAND_START; DWORD dwServiceType = SERVICE_WIN32_OWN_PROCESS; wchar_t *act = 0; wchar_t *pwd = 0; if (!acc.isEmpty()) { // The act string must contain a string of the format "Domain\UserName", // so if only a username was specified without a domain, default to the local machine domain. if (!acc.contains(QChar('\\'))) { acc.prepend(QLatin1String(".\\")); } if (!acc.endsWith(QLatin1String("\\LocalSystem"))) act = (wchar_t*)acc.utf16(); } if (!password.isEmpty() && act) { pwd = (wchar_t*)password.utf16(); } // Only set INTERACTIVE if act is LocalSystem. (and act should be 0 if it is LocalSystem). if (!act) dwServiceType |= SERVICE_INTERACTIVE_PROCESS; // Create the service SC_HANDLE hService = pCreateService(hSCM, (wchar_t *)controller.serviceName().utf16(), (wchar_t *)controller.serviceName().utf16(), SERVICE_ALL_ACCESS, dwServiceType, // QObject::inherits ( const char * className ) for no inter active ???? dwStartType, SERVICE_ERROR_NORMAL, (wchar_t *)filePath().utf16(), 0, 0, 0, act, pwd); if (hService) { result = true; if (!serviceDescription.isEmpty()) { SERVICE_DESCRIPTION sdesc; sdesc.lpDescription = (wchar_t *)serviceDescription.utf16(); pChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdesc); } pCloseServiceHandle(hService); } pCloseServiceHandle(hSCM); } return result; } QString QtServiceBasePrivate::filePath() const { wchar_t path[_MAX_PATH]; ::GetModuleFileNameW( 0, path, sizeof(path) ); return QString::fromUtf16((unsigned short*)path); } bool QtServiceBasePrivate::sysInit() { sysd = new QtServiceSysPrivate(); sysd->serviceStatus = 0; sysd->status.dwServiceType = SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS; sysd->status.dwCurrentState = SERVICE_STOPPED; sysd->status.dwControlsAccepted = sysd->serviceFlags(serviceFlags); sysd->status.dwWin32ExitCode = NO_ERROR; sysd->status.dwServiceSpecificExitCode = 0; sysd->status.dwCheckPoint = 0; sysd->status.dwWaitHint = 0; return true; } void QtServiceBasePrivate::sysSetPath() { } void QtServiceBasePrivate::sysCleanup() { if (sysd) { delete sysd; sysd = 0; } } void QtServiceBase::setServiceFlags(QtServiceBase::ServiceFlags flags) { if (d_ptr->serviceFlags == flags) return; d_ptr->serviceFlags = flags; if (d_ptr->sysd) d_ptr->sysd->setServiceFlags(flags); } monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtservice_p.h0000644000175000017500000000621211437034034025147 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #ifndef QTSERVICE_P_H #define QTSERVICE_P_H #include #include "qtservice.h" class QtServiceControllerPrivate { Q_DECLARE_PUBLIC(QtServiceController) public: QString serviceName; QtServiceController *q_ptr; }; class QtServiceBasePrivate { Q_DECLARE_PUBLIC(QtServiceBase) public: QtServiceBasePrivate(const QString &name); ~QtServiceBasePrivate(); QtServiceBase *q_ptr; QString serviceDescription; QtServiceController::StartupType startupType; QtServiceBase::ServiceFlags serviceFlags; QStringList args; static class QtServiceBase *instance; QtServiceController controller; void startService(); int run(bool asService, const QStringList &argList); bool install(const QString &account, const QString &password); bool start(); QString filePath() const; bool sysInit(); void sysSetPath(); void sysCleanup(); class QtServiceSysPrivate *sysd; }; #endif monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtservice.h0000644000175000017500000001312411437034034024630 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #ifndef QTSERVICE_H #define QTSERVICE_H #include #if defined(Q_WS_WIN) # if !defined(QT_QTSERVICE_EXPORT) && !defined(QT_QTSERVICE_IMPORT) # define QT_QTSERVICE_EXPORT # elif defined(QT_QTSERVICE_IMPORT) # if defined(QT_QTSERVICE_EXPORT) # undef QT_QTSERVICE_EXPORT # endif # define QT_QTSERVICE_EXPORT __declspec(dllimport) # elif defined(QT_QTSERVICE_EXPORT) # undef QT_QTSERVICE_EXPORT # define QT_QTSERVICE_EXPORT __declspec(dllexport) # endif #else # define QT_QTSERVICE_EXPORT #endif class QStringList; class QtServiceControllerPrivate; class QT_QTSERVICE_EXPORT QtServiceController { Q_DECLARE_PRIVATE(QtServiceController) public: enum StartupType { AutoStartup = 0, ManualStartup }; QtServiceController(const QString &name); virtual ~QtServiceController(); bool isInstalled() const; bool isRunning() const; QString serviceName() const; QString serviceDescription() const; StartupType startupType() const; QString serviceFilePath() const; static bool install(const QString &serviceFilePath, const QString &account = QString(), const QString &password = QString()); bool uninstall(); bool start(const QStringList &arguments); bool start(); bool stop(); bool pause(); bool resume(); bool sendCommand(int code); private: QtServiceControllerPrivate *d_ptr; }; class QtServiceBasePrivate; class QT_QTSERVICE_EXPORT QtServiceBase { Q_DECLARE_PRIVATE(QtServiceBase) public: enum MessageType { Success = 0, Error, Warning, Information }; enum ServiceFlag { Default = 0x00, CanBeSuspended = 0x01, CannotBeStopped = 0x02 }; Q_DECLARE_FLAGS(ServiceFlags, ServiceFlag) QtServiceBase(int argc, char **argv, const QString &name); virtual ~QtServiceBase(); QString serviceName() const; QString serviceDescription() const; void setServiceDescription(const QString &description); QtServiceController::StartupType startupType() const; void setStartupType(QtServiceController::StartupType startupType); ServiceFlags serviceFlags() const; void setServiceFlags(ServiceFlags flags); int exec(); void logMessage(const QString &message, MessageType type = Success, int id = 0, uint category = 0, const QByteArray &data = QByteArray()); static QtServiceBase *instance(); protected: virtual void start() = 0; virtual void stop(); virtual void pause(); virtual void resume(); virtual void processCommand(int code); virtual void createApplication(int &argc, char **argv) = 0; virtual int executeApplication() = 0; private: friend class QtServiceSysPrivate; QtServiceBasePrivate *d_ptr; }; template class QtService : public QtServiceBase { public: QtService(int argc, char **argv, const QString &name) : QtServiceBase(argc, argv, name), app(0) { } ~QtService() { } protected: Application *application() const { return app; } virtual void createApplication(int &argc, char **argv) { app = new Application(argc, argv); QCoreApplication *a = app; Q_UNUSED(a); } virtual int executeApplication() { return Application::exec(); } private: Application *app; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QtServiceBase::ServiceFlags) #endif // QTSERVICE_H monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/QtServiceBase0000644000175000017500000000002711437034034025073 0ustar vettervetter#include "qtservice.h" monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtunixserversocket.cpp0000644000175000017500000000703411437034034027151 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include "qtunixserversocket.h" #include #include #include #include #include #ifndef SUN_LEN #define SUN_LEN(ptr) ((size_t)(((struct sockaddr_un *) 0)->sun_path) \ +strlen ((ptr)->sun_path)) #endif QtUnixServerSocket::QtUnixServerSocket(const QString &path, QObject *parent) : QTcpServer(parent) { setPath(path); } QtUnixServerSocket::QtUnixServerSocket(QObject *parent) : QTcpServer(parent) { } void QtUnixServerSocket::setPath(const QString &path) { path_.clear(); int sock = ::socket(PF_UNIX, SOCK_STREAM, 0); if (sock != -1) { struct sockaddr_un addr; ::memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; ::unlink(path.toLatin1().constData()); // ### This might need to be changed unsigned int pathlen = strlen(path.toLatin1().constData()); if (pathlen > sizeof(addr.sun_path)) pathlen = sizeof(addr.sun_path); ::memcpy(addr.sun_path, path.toLatin1().constData(), pathlen); if ((::bind(sock, (struct sockaddr *)&addr, SUN_LEN(&addr)) != -1) && (::listen(sock, 5) != -1)) { setSocketDescriptor(sock); path_ = path; } } } void QtUnixServerSocket::close() { QTcpServer::close(); if (!path_.isEmpty()) { ::unlink(path_.toLatin1().constData()); path_.clear(); } } monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtservice.pri0000644000175000017500000000127511437034034025177 0ustar vettervetterinclude(../common.pri) INCLUDEPATH += $$PWD DEPENDPATH += $$PWD !win32:QT += network win32:LIBS += -luser32 qtservice-uselib:!qtservice-buildlib { LIBS += -L$$QTSERVICE_LIBDIR -l$$QTSERVICE_LIBNAME } else { HEADERS += $$PWD/qtservice.h \ $$PWD/qtservice_p.h SOURCES += $$PWD/qtservice.cpp win32:SOURCES += $$PWD/qtservice_win.cpp unix:HEADERS += $$PWD/qtunixsocket.h $$PWD/qtunixserversocket.h unix:SOURCES += $$PWD/qtservice_unix.cpp $$PWD/qtunixsocket.cpp $$PWD/qtunixserversocket.cpp } win32 { contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSERVICE_EXPORT else:qtservice-uselib:DEFINES += QT_QTSERVICE_IMPORT } monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtservice_unix.cpp0000644000175000017500000003232311437034034026230 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include "qtservice.h" #include "qtservice_p.h" #include "qtunixsocket.h" #include "qtunixserversocket.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static QString encodeName(const QString &name, bool allowUpper = false) { QString n = name.toLower(); QString legal = QLatin1String("abcdefghijklmnopqrstuvwxyz1234567890"); if (allowUpper) legal += QLatin1String("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); int pos = 0; while (pos < n.size()) { if (legal.indexOf(n[pos]) == -1) n.remove(pos, 1); else ++pos; } return n; } static QString login() { QString l; uid_t uid = getuid(); passwd *pw = getpwuid(uid); if (pw) l = QString(pw->pw_name); return l; } static QString socketPath(const QString &serviceName) { QString sn = encodeName(serviceName); return QString(QLatin1String("/var/tmp/") + sn + QLatin1String(".") + login()); } static bool sendCmd(const QString &serviceName, const QString &cmd) { bool retValue = false; QtUnixSocket sock; if (sock.connectTo(socketPath(serviceName))) { sock.write(QString(cmd+"\r\n").toLatin1().constData()); sock.flush(); sock.waitForReadyRead(-1); QString reply = sock.readAll(); if (reply == QLatin1String("true")) retValue = true; sock.close(); } return retValue; } static QString absPath(const QString &path) { QString ret; if (path[0] != QChar('/')) { // Not an absolute path int slashpos; if ((slashpos = path.lastIndexOf('/')) != -1) { // Relative path QDir dir = QDir::current(); dir.cd(path.left(slashpos)); ret = dir.absolutePath(); } else { // Need to search $PATH char *envPath = ::getenv("PATH"); if (envPath) { QStringList envPaths = QString::fromLocal8Bit(envPath).split(':'); for (int i = 0; i < envPaths.size(); ++i) { if (QFile::exists(envPaths.at(i) + QLatin1String("/") + QString(path))) { QDir dir(envPaths.at(i)); ret = dir.absolutePath(); break; } } } } } else { QFileInfo fi(path); ret = fi.absolutePath(); } return ret; } QString QtServiceBasePrivate::filePath() const { QString ret; if (args.isEmpty()) return ret; QFileInfo fi(args[0]); QDir dir(absPath(args[0])); return dir.absoluteFilePath(fi.fileName()); } QString QtServiceController::serviceDescription() const { QSettings settings(QSettings::SystemScope, "QtSoftware"); settings.beginGroup("services"); settings.beginGroup(serviceName()); QString desc = settings.value("description").toString(); settings.endGroup(); settings.endGroup(); return desc; } QtServiceController::StartupType QtServiceController::startupType() const { QSettings settings(QSettings::SystemScope, "QtSoftware"); settings.beginGroup("services"); settings.beginGroup(serviceName()); StartupType startupType = (StartupType)settings.value("startupType").toInt(); settings.endGroup(); settings.endGroup(); return startupType; } QString QtServiceController::serviceFilePath() const { QSettings settings(QSettings::SystemScope, "QtSoftware"); settings.beginGroup("services"); settings.beginGroup(serviceName()); QString path = settings.value("path").toString(); settings.endGroup(); settings.endGroup(); return path; } bool QtServiceController::uninstall() { QSettings settings(QSettings::SystemScope, "QtSoftware"); settings.beginGroup("services"); settings.remove(serviceName()); settings.endGroup(); settings.sync(); QSettings::Status ret = settings.status(); if (ret == QSettings::AccessError) { fprintf(stderr, "Cannot uninstall \"%s\". Cannot write to: %s. Check permissions.\n", serviceName().toLatin1().constData(), settings.fileName().toLatin1().constData()); } return (ret == QSettings::NoError); } bool QtServiceController::start(const QStringList &arguments) { if (!isInstalled()) return false; if (isRunning()) return false; return QProcess::startDetached(serviceFilePath(), arguments); } bool QtServiceController::stop() { return sendCmd(serviceName(), QLatin1String("terminate")); } bool QtServiceController::pause() { return sendCmd(serviceName(), QLatin1String("pause")); } bool QtServiceController::resume() { return sendCmd(serviceName(), QLatin1String("resume")); } bool QtServiceController::sendCommand(int code) { return sendCmd(serviceName(), QString(QLatin1String("num:") + QString::number(code))); } bool QtServiceController::isInstalled() const { QSettings settings(QSettings::SystemScope, "QtSoftware"); settings.beginGroup("services"); QStringList list = settings.childGroups(); settings.endGroup(); QStringListIterator it(list); while (it.hasNext()) { if (it.next() == serviceName()) return true; } return false; } bool QtServiceController::isRunning() const { QtUnixSocket sock; if (sock.connectTo(socketPath(serviceName()))) return true; return false; } /////////////////////////////////// class QtServiceSysPrivate : public QtUnixServerSocket { Q_OBJECT public: QtServiceSysPrivate(); ~QtServiceSysPrivate(); char *ident; QtServiceBase::ServiceFlags serviceFlags; protected: void incomingConnection(int socketDescriptor); private slots: void slotReady(); void slotClosed(); private: QString getCommand(const QTcpSocket *socket); QMap cache; }; QtServiceSysPrivate::QtServiceSysPrivate() : QtUnixServerSocket(), ident(0), serviceFlags(0) { } QtServiceSysPrivate::~QtServiceSysPrivate() { if (ident) delete[] ident; } void QtServiceSysPrivate::incomingConnection(int socketDescriptor) { QTcpSocket *s = new QTcpSocket(this); s->setSocketDescriptor(socketDescriptor); connect(s, SIGNAL(readyRead()), this, SLOT(slotReady())); connect(s, SIGNAL(disconnected()), this, SLOT(slotClosed())); } void QtServiceSysPrivate::slotReady() { QTcpSocket *s = (QTcpSocket *)sender(); cache[s] += QString(s->readAll()); QString cmd = getCommand(s); while (!cmd.isEmpty()) { bool retValue = false; if (cmd == QLatin1String("terminate")) { if (!(serviceFlags & QtServiceBase::CannotBeStopped)) { QtServiceBase::instance()->stop(); QCoreApplication::instance()->quit(); retValue = true; } } else if (cmd == QLatin1String("pause")) { if (serviceFlags & QtServiceBase::CanBeSuspended) { QtServiceBase::instance()->pause(); retValue = true; } } else if (cmd == QLatin1String("resume")) { if (serviceFlags & QtServiceBase::CanBeSuspended) { QtServiceBase::instance()->resume(); retValue = true; } } else if (cmd == QLatin1String("alive")) { retValue = true; } else if (cmd.length() > 4 && cmd.left(4) == QLatin1String("num:")) { cmd = cmd.mid(4); QtServiceBase::instance()->processCommand(cmd.toInt()); retValue = true; } QString retString; if (retValue) retString = QLatin1String("true"); else retString = QLatin1String("false"); s->write(retString.toLatin1().constData()); s->flush(); cmd = getCommand(s); } } void QtServiceSysPrivate::slotClosed() { QTcpSocket *s = (QTcpSocket *)sender(); s->deleteLater(); } QString QtServiceSysPrivate::getCommand(const QTcpSocket *socket) { int pos = cache[socket].indexOf("\r\n"); if (pos >= 0) { QString ret = cache[socket].left(pos); cache[socket].remove(0, pos+2); return ret; } return ""; } #include "qtservice_unix.moc" bool QtServiceBasePrivate::sysInit() { sysd = new QtServiceSysPrivate; sysd->serviceFlags = serviceFlags; // Restrict permissions on files that are created by the service ::umask(027); return true; } void QtServiceBasePrivate::sysSetPath() { if (sysd) sysd->setPath(socketPath(controller.serviceName())); } void QtServiceBasePrivate::sysCleanup() { if (sysd) { sysd->close(); delete sysd; sysd = 0; } } bool QtServiceBasePrivate::start() { if (sendCmd(controller.serviceName(), "alive")) { // Already running return false; } // Could just call controller.start() here, but that would fail if // we're not installed. We do not want to strictly require installation. ::setenv("QTSERVICE_RUN", "1", 1); // Tell the detached process it's it return QProcess::startDetached(filePath(), args.mid(1), "/"); } bool QtServiceBasePrivate::install(const QString &account, const QString &password) { Q_UNUSED(account) Q_UNUSED(password) QSettings settings(QSettings::SystemScope, "QtSoftware"); settings.beginGroup("services"); settings.beginGroup(controller.serviceName()); settings.setValue("path", filePath()); settings.setValue("description", serviceDescription); settings.setValue("automaticStartup", startupType); settings.endGroup(); settings.endGroup(); settings.sync(); QSettings::Status ret = settings.status(); if (ret == QSettings::AccessError) { fprintf(stderr, "Cannot install \"%s\". Cannot write to: %s. Check permissions.\n", controller.serviceName().toLatin1().constData(), settings.fileName().toLatin1().constData()); } return (ret == QSettings::NoError); } void QtServiceBase::logMessage(const QString &message, QtServiceBase::MessageType type, int, uint, const QByteArray &) { if (!d_ptr->sysd) return; int st; switch(type) { case QtServiceBase::Error: st = LOG_ERR; break; case QtServiceBase::Warning: st = LOG_WARNING; break; default: st = LOG_INFO; } if (!d_ptr->sysd->ident) { QString tmp = encodeName(serviceName(), TRUE); int len = tmp.toLocal8Bit().size(); d_ptr->sysd->ident = new char[len+1]; d_ptr->sysd->ident[len] = '\0'; ::memcpy(d_ptr->sysd->ident, tmp.toLocal8Bit().constData(), len); } openlog(d_ptr->sysd->ident, LOG_PID, LOG_DAEMON); foreach(QString line, message.split('\n')) syslog(st, "%s", line.toLocal8Bit().constData()); closelog(); } void QtServiceBase::setServiceFlags(QtServiceBase::ServiceFlags flags) { if (d_ptr->serviceFlags == flags) return; d_ptr->serviceFlags = flags; if (d_ptr->sysd) d_ptr->sysd->serviceFlags = flags; } monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtunixsocket.h0000644000175000017500000000465511437034034025375 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #ifndef QTUNIXSOCKET_H #define QTUNIXSOCKET_H #include class QtUnixSocket : public QTcpSocket { Q_OBJECT public: QtUnixSocket(QObject *parent = 0); bool connectTo(const QString &path); }; #endif monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtunixserversocket.h0000644000175000017500000000506511437034034026620 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #ifndef QTUNIXSERVERSOCKET_H #define QTUNIXSERVERSOCKET_H #include class QtUnixServerSocket : public QTcpServer { Q_OBJECT public: QtUnixServerSocket(const QString &path, QObject *parent = 0); QtUnixServerSocket(QObject *parent = 0); void setPath(const QString &path); void close(); private: QString path_; }; #endif monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtservice.cpp0000644000175000017500000010617211437034034025171 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include "qtservice.h" #include "qtservice_p.h" #include #include #include #include #include #if defined(QTSERVICE_DEBUG) #include #include #include #include #if defined(Q_OS_WIN32) #include #else #include #include #endif static QFile* f = 0; static void qtServiceCloseDebugLog() { if (!f) return; QString ps(QTime::currentTime().toString("HH:mm:ss.zzz ") + QLatin1String("--- DEBUG LOG CLOSED ---\n\n")); f->write(ps.toAscii()); f->flush(); f->close(); delete f; f = 0; } void qtServiceLogDebug(QtMsgType type, const char* msg) { static QMutex mutex; QMutexLocker locker(&mutex); QString s(QTime::currentTime().toString("HH:mm:ss.zzz ")); s += QString("[%1] ").arg( #if defined(Q_OS_WIN32) GetCurrentProcessId()); #else getpid()); #endif if (!f) { #if defined(Q_OS_WIN32) f = new QFile("c:/service-debuglog.txt"); #else f = new QFile("/tmp/service-debuglog.txt"); #endif if (!f->open(QIODevice::WriteOnly | QIODevice::Append)) { delete f; f = 0; return; } QString ps(QLatin1String("\n") + s + QLatin1String("--- DEBUG LOG OPENED ---\n")); f->write(ps.toAscii()); } switch (type) { case QtWarningMsg: s += QLatin1String("WARNING: "); break; case QtCriticalMsg: s += QLatin1String("CRITICAL: "); break; case QtFatalMsg: s+= QLatin1String("FATAL: "); break; case QtDebugMsg: s += QLatin1String("DEBUG: "); break; default: // Nothing break; } s += msg; s += QLatin1String("\n"); f->write(s.toAscii()); f->flush(); if (type == QtFatalMsg) { qtServiceCloseDebugLog(); exit(1); } } #endif /*! \class QtServiceController \brief The QtServiceController class allows you to control services from separate applications. QtServiceController provides a collection of functions that lets you install and run a service controlling its execution, as well as query its status. In order to run a service, the service must be installed in the system's service database using the install() function. The system will start the service depending on the specified StartupType; it can either be started during system startup, or when a process starts it manually. Once a service is installed, the service can be run and controlled manually using the start(), stop(), pause(), resume() or sendCommand() functions. You can at any time query for the service's status using the isInstalled() and isRunning() functions, or you can query its properties using the serviceDescription(), serviceFilePath(), serviceName() and startupType() functions. For example: \code MyService service; \\ which inherits QtService QString serviceFilePath; QtServiceController controller(service.serviceName()); if (controller.install(serviceFilePath)) controller.start() if (controller.isRunning()) QMessageBox::information(this, tr("Service Status"), tr("The %1 service is started").arg(controller.serviceName())); ... controller.stop(); controller.uninstall(); } \endcode An instance of the service controller can only control one single service. To control several services within one application, you must create en equal number of service controllers. The QtServiceController destructor neither stops nor uninstalls the associated service. To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the uninstall() function. \sa QtServiceBase, QtService */ /*! \enum QtServiceController::StartupType This enum describes when a service should be started. \value AutoStartup The service is started during system startup. \value ManualStartup The service must be started manually by a process. \warning The \a StartupType enum is ignored under UNIX-like systems. A service, or daemon, can only be started manually on such systems with current implementation. \sa startupType() */ /*! Creates a controller object for the service with the given \a name. */ QtServiceController::QtServiceController(const QString &name) : d_ptr(new QtServiceControllerPrivate()) { Q_D(QtServiceController); d->q_ptr = this; d->serviceName = name; } /*! Destroys the service controller. This neither stops nor uninstalls the controlled service. To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the uninstall() function. \sa stop(), QtServiceController::uninstall() */ QtServiceController::~QtServiceController() { delete d_ptr; } /*! \fn bool QtServiceController::isInstalled() const Returns true if the service is installed; otherwise returns false. On Windows it uses the system's service control manager. On Unix it checks configuration written to QSettings::SystemScope using "QtSoftware" as organization name. \sa install() */ /*! \fn bool QtServiceController::isRunning() const Returns true if the service is running; otherwise returns false. A service must be installed before it can be run using a controller. \sa start(), isInstalled() */ /*! Returns the name of the controlled service. \sa QtServiceController(), serviceDescription() */ QString QtServiceController::serviceName() const { Q_D(const QtServiceController); return d->serviceName; } /*! \fn QString QtServiceController::serviceDescription() const Returns the description of the controlled service. \sa install(), serviceName() */ /*! \fn QtServiceController::StartupType QtServiceController::startupType() const Returns the startup type of the controlled service. \sa install(), serviceName() */ /*! \fn QString QtServiceController::serviceFilePath() const Returns the file path to the controlled service. \sa install(), serviceName() */ /*! Installs the service with the given \a serviceFilePath and returns true if the service is installed successfully; otherwise returns false. On Windows service is installed in the system's service control manager with the given \a account and \a password. On Unix service configuration is written to QSettings::SystemScope using "QtSoftware" as organization name. \a account and \a password arguments are ignored. \warning Due to the different implementations of how services (daemons) are installed on various UNIX-like systems, this method doesn't integrate the service into the system's startup scripts. \sa uninstall(), start() */ bool QtServiceController::install(const QString &serviceFilePath, const QString &account, const QString &password) { QStringList arguments; arguments << QLatin1String("-i"); arguments << account; arguments << password; return (QProcess::execute(serviceFilePath, arguments) == 0); } /*! \fn bool QtServiceController::uninstall() Uninstalls the service and returns true if successful; otherwise returns false. On Windows service is uninstalled using the system's service control manager. On Unix service configuration is cleared using QSettings::SystemScope with "QtSoftware" as organization name. \sa install() */ /*! \fn bool QtServiceController::start(const QStringList &arguments) Starts the installed service passing the given \a arguments to the service. A service must be installed before a controller can run it. Returns true if the service could be started; otherwise returns false. \sa install(), stop() */ /*! \overload Starts the installed service without passing any arguments to the service. */ bool QtServiceController::start() { return start(QStringList()); } /*! \fn bool QtServiceController::stop() Requests the running service to stop. The service will call the QtServiceBase::stop() implementation unless the service's state is QtServiceBase::CannotBeStopped. This function does nothing if the service is not running. Returns true if a running service was successfully stopped; otherwise false. \sa start(), QtServiceBase::stop(), QtServiceBase::ServiceFlags */ /*! \fn bool QtServiceController::pause() Requests the running service to pause. If the service's state is QtServiceBase::CanBeSuspended, the service will call the QtServiceBase::pause() implementation. The function does nothing if the service is not running. Returns true if a running service was successfully paused; otherwise returns false. \sa resume(), QtServiceBase::pause(), QtServiceBase::ServiceFlags */ /*! \fn bool QtServiceController::resume() Requests the running service to continue. If the service's state is QtServiceBase::CanBeSuspended, the service will call the QtServiceBase::resume() implementation. This function does nothing if the service is not running. Returns true if a running service was successfully resumed; otherwise returns false. \sa pause(), QtServiceBase::resume(), QtServiceBase::ServiceFlags */ /*! \fn bool QtServiceController::sendCommand(int code) Sends the user command \a code to the service. The service will call the QtServiceBase::processCommand() implementation. This function does nothing if the service is not running. Returns true if the request was sent to a running service; otherwise returns false. \sa QtServiceBase::processCommand() */ class QtServiceStarter : public QObject { Q_OBJECT public: QtServiceStarter(QtServiceBasePrivate *service) : QObject(), d_ptr(service) {} public slots: void slotStart() { d_ptr->startService(); } private: QtServiceBasePrivate *d_ptr; }; #include "qtservice.moc" QtServiceBase *QtServiceBasePrivate::instance = 0; QtServiceBasePrivate::QtServiceBasePrivate(const QString &name) : startupType(QtServiceController::ManualStartup), serviceFlags(0), controller(name) { } QtServiceBasePrivate::~QtServiceBasePrivate() { } void QtServiceBasePrivate::startService() { q_ptr->start(); } int QtServiceBasePrivate::run(bool asService, const QStringList &argList) { int argc = argList.size(); QVector argv(argc); QList argvData; for (int i = 0; i < argc; ++i) argvData.append(argList.at(i).toLocal8Bit()); for (int i = 0; i < argc; ++i) argv[i] = argvData[i].data(); if (asService && !sysInit()) return -1; q_ptr->createApplication(argc, argv.data()); QCoreApplication *app = QCoreApplication::instance(); if (!app) return -1; if (asService) sysSetPath(); QtServiceStarter starter(this); QTimer::singleShot(0, &starter, SLOT(slotStart())); int res = q_ptr->executeApplication(); delete app; if (asService) sysCleanup(); return res; } /*! \class QtServiceBase \brief The QtServiceBase class provides an API for implementing Windows services and Unix daemons. A Windows service or Unix daemon (a "service"), is a program that runs "in the background" independently of whether a user is logged in or not. A service is often set up to start when the machine boots up, and will typically run continuously as long as the machine is on. Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes. (In certain circumstances, a service may provide a GUI itself, ref. the "interactive" example documentation). Typically, you will create a service by subclassing the QtService template class which inherits QtServiceBase and allows you to create a service for a particular application type. The Windows implementation uses the NT Service Control Manager, and the application can be controlled through the system administration tools. Services are usually launched using the system account, which requires that all DLLs that the service executable depends on (i.e. Qt), are located in the same directory as the service, or in a system path. On Unix a service is implemented as a daemon. You can retrieve the service's description, state, and startup type using the serviceDescription(), serviceFlags() and startupType() functions respectively. The service's state is decribed by the ServiceFlag enum. The mentioned properites can also be set using the corresponding set functions. In addition you can retrieve the service's name using the serviceName() function. Several of QtServiceBase's protected functions are called on requests from the QtServiceController class: \list \o start() \o pause() \o processCommand() \o resume() \o stop() \endlist You can control any given service using an instance of the QtServiceController class which also allows you to control services from separate applications. The mentioned functions are all virtual and won't do anything unless they are reimplemented. You can reimplement these functions to pause and resume the service's execution, as well as process user commands and perform additional clean-ups before shutting down. QtServiceBase also provides the static instance() function which returns a pointer to an application's QtServiceBase instance. In addition, a service can report events to the system's event log using the logMessage() function. The MessageType enum describes the different types of messages a service reports. The implementation of a service application's main function typically creates an service object derived by subclassing the QtService template class. Then the main function will call this service's exec() function, and return the result of that call. For example: \code int main(int argc, char **argv) { MyService service(argc, argv); return service.exec(); } \endcode When the exec() function is called, it will parse the service specific arguments passed in \c argv, perform the required actions, and return. \target serviceSpecificArguments The following arguments are recognized as service specific: \table \header \i Short \i Long \i Explanation \row \i -i \i -install \i Install the service. \row \i -u \i -uninstall \i Uninstall the service. \row \i -e \i -exec \i Execute the service as a standalone application (useful for debug purposes). This is a blocking call, the service will be executed like a normal application. In this mode you will not be able to communicate with the service from the contoller. \row \i -t \i -terminate \i Stop the service. \row \i -p \i -pause \i Pause the service. \row \i -r \i -resume \i Resume a paused service. \row \i -c \e{cmd} \i -command \e{cmd} \i Send the user defined command code \e{cmd} to the service application. \row \i -v \i -version \i Display version and status information. \endtable If \e none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller. \sa QtService, QtServiceController */ /*! \enum QtServiceBase::MessageType This enum describes the different types of messages a service reports to the system log. \value Success An operation has succeeded, e.g. the service is started. \value Error An operation failed, e.g. the service failed to start. \value Warning An operation caused a warning that might require user interaction. \value Information Any type of usually non-critical information. */ /*! \enum QtServiceBase::ServiceFlag This enum describes the different states of a service. \value Default The service can be stopped, but not suspended. \value CanBeSuspended The service can be suspended. \value CannotBeStopped The service cannot be stopped. */ /*! Creates a service instance called \a name. The \a argc and \a argv parameters are parsed after the exec() function has been called. Then they are passed to the application's constructor. The application type is determined by the QtService subclass. The service is neither installed nor started. The name must not contain any backslashes or be longer than 255 characters. In addition, the name must be unique in the system's service database. \sa exec(), start(), QtServiceController::install() */ QtServiceBase::QtServiceBase(int argc, char **argv, const QString &name) { #if defined(QTSERVICE_DEBUG) qInstallMsgHandler(qtServiceLogDebug); qAddPostRoutine(qtServiceCloseDebugLog); #endif Q_ASSERT(!QtServiceBasePrivate::instance); QtServiceBasePrivate::instance = this; QString nm(name); if (nm.length() > 255) { qWarning("QtService: 'name' is longer than 255 characters."); nm.truncate(255); } if (nm.contains('\\')) { qWarning("QtService: 'name' contains backslashes '\\'."); nm.replace((QChar)'\\', (QChar)'\0'); } d_ptr = new QtServiceBasePrivate(nm); d_ptr->q_ptr = this; d_ptr->serviceFlags = 0; d_ptr->sysd = 0; for (int i = 0; i < argc; ++i) d_ptr->args.append(QString::fromLocal8Bit(argv[i])); } /*! Destroys the service object. This neither stops nor uninstalls the service. To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the QtServiceController::uninstall() function. \sa stop(), QtServiceController::uninstall() */ QtServiceBase::~QtServiceBase() { delete d_ptr; QtServiceBasePrivate::instance = 0; } /*! Returns the name of the service. \sa QtServiceBase(), serviceDescription() */ QString QtServiceBase::serviceName() const { return d_ptr->controller.serviceName(); } /*! Returns the description of the service. \sa setServiceDescription(), serviceName() */ QString QtServiceBase::serviceDescription() const { return d_ptr->serviceDescription; } /*! Sets the description of the service to the given \a description. \sa serviceDescription() */ void QtServiceBase::setServiceDescription(const QString &description) { d_ptr->serviceDescription = description; } /*! Returns the service's startup type. \sa QtServiceController::StartupType, setStartupType() */ QtServiceController::StartupType QtServiceBase::startupType() const { return d_ptr->startupType; } /*! Sets the service's startup type to the given \a type. \sa QtServiceController::StartupType, startupType() */ void QtServiceBase::setStartupType(QtServiceController::StartupType type) { d_ptr->startupType = type; } /*! Returns the service's state which is decribed using the ServiceFlag enum. \sa ServiceFlags, setServiceFlags() */ QtServiceBase::ServiceFlags QtServiceBase::serviceFlags() const { return d_ptr->serviceFlags; } /*! \fn void QtServiceBase::setServiceFlags(ServiceFlags flags) Sets the service's state to the state described by the given \a flags. \sa ServiceFlags, serviceFlags() */ /*! Executes the service. When the exec() function is called, it will parse the \l {serviceSpecificArguments} {service specific arguments} passed in \c argv, perform the required actions, and exit. If none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller. \sa QtServiceController */ int QtServiceBase::exec() { if (d_ptr->args.size() > 1) { QString a = d_ptr->args.at(1); if (a == QLatin1String("-i") || a == QLatin1String("-install")) { if (!d_ptr->controller.isInstalled()) { QString account; QString password; if (d_ptr->args.size() > 2) account = d_ptr->args.at(2); if (d_ptr->args.size() > 3) password = d_ptr->args.at(3); if (!d_ptr->install(account, password)) { fprintf(stderr, "The service %s could not be installed\n", serviceName().toLatin1().constData()); return -1; } else { printf("The service %s has been installed under: %s\n", serviceName().toLatin1().constData(), d_ptr->filePath().toLatin1().constData()); } } else { fprintf(stderr, "The service %s is already installed\n", serviceName().toLatin1().constData()); } return 0; } else if (a == QLatin1String("-u") || a == QLatin1String("-uninstall")) { if (d_ptr->controller.isInstalled()) { if (!d_ptr->controller.uninstall()) { fprintf(stderr, "The service %s could not be uninstalled\n", serviceName().toLatin1().constData()); return -1; } else { printf("The service %s has been uninstalled.\n", serviceName().toLatin1().constData()); } } else { fprintf(stderr, "The service %s is not installed\n", serviceName().toLatin1().constData()); } return 0; } else if (a == QLatin1String("-v") || a == QLatin1String("-version")) { printf("The service\n" "\t%s\n\t%s\n\n", serviceName().toLatin1().constData(), d_ptr->args.at(0).toLatin1().constData()); printf("is %s", (d_ptr->controller.isInstalled() ? "installed" : "not installed")); printf(" and %s\n\n", (d_ptr->controller.isRunning() ? "running" : "not running")); return 0; } else if (a == QLatin1String("-e") || a == QLatin1String("-exec")) { d_ptr->args.removeAt(1); int ec = d_ptr->run(false, d_ptr->args); if (ec == -1) qErrnoWarning("The service could not be executed."); return ec; } else if (a == QLatin1String("-t") || a == QLatin1String("-terminate")) { if (!d_ptr->controller.stop()) qErrnoWarning("The service could not be stopped."); return 0; } else if (a == QLatin1String("-p") || a == QLatin1String("-pause")) { d_ptr->controller.pause(); return 0; } else if (a == QLatin1String("-r") || a == QLatin1String("-resume")) { d_ptr->controller.resume(); return 0; } else if (a == QLatin1String("-c") || a == QLatin1String("-command")) { int code = 0; if (d_ptr->args.size() > 2) code = d_ptr->args.at(2).toInt(); d_ptr->controller.sendCommand(code); return 0; } else if (a == QLatin1String("-h") || a == QLatin1String("-help")) { printf("\n%s -[i|u|e|s|v|h]\n" "\t-i(nstall) [account] [password]\t: Install the service, optionally using given account and password\n" "\t-u(ninstall)\t: Uninstall the service.\n" "\t-e(xec)\t\t: Run as a regular application. Useful for debugging.\n" "\t-t(erminate)\t: Stop the service.\n" "\t-c(ommand) num\t: Send command code num to the service.\n" "\t-v(ersion)\t: Print version and status information.\n" "\t-h(elp) \t: Show this help\n" "\tNo arguments\t: Start the service.\n", d_ptr->args.at(0).toLatin1().constData()); return 0; } } #if defined(Q_OS_UNIX) if (::getenv("QTSERVICE_RUN")) { // Means we're the detached, real service process. int ec = d_ptr->run(true, d_ptr->args); if (ec == -1) qErrnoWarning("The service failed to run."); return ec; } #endif if (!d_ptr->start()) { fprintf(stderr, "The service %s could not start\n", serviceName().toLatin1().constData()); return -4; } return 0; } /*! \fn void QtServiceBase::logMessage(const QString &message, MessageType type, int id, uint category, const QByteArray &data) Reports a message of the given \a type with the given \a message to the local system event log. The message identifier \a id and the message \a category are user defined values. The \a data parameter can contain arbitrary binary data. Message strings for \a id and \a category must be provided by a message file, which must be registered in the system registry. Refer to the MSDN for more information about how to do this on Windows. \sa MessageType */ /*! Returns a pointer to the current application's QtServiceBase instance. */ QtServiceBase *QtServiceBase::instance() { return QtServiceBasePrivate::instance; } /*! \fn void QtServiceBase::start() This function must be implemented in QtServiceBase subclasses in order to perform the service's work. Usually you create some main object on the heap which is the heart of your service. The function is only called when no service specific arguments were passed to the service constructor, and is called by exec() after it has called the executeApplication() function. Note that you \e don't need to create an application object or call its exec() function explicitly. \sa exec(), stop(), QtServiceController::start() */ /*! Reimplement this function to perform additional cleanups before shutting down (for example deleting a main object if it was created in the start() function). This function is called in reply to controller requests. The default implementation does nothing. \sa start(), QtServiceController::stop() */ void QtServiceBase::stop() { } /*! Reimplement this function to pause the service's execution (for example to stop a polling timer, or to ignore socket notifiers). This function is called in reply to controller requests. The default implementation does nothing. \sa resume(), QtServiceController::pause() */ void QtServiceBase::pause() { } /*! Reimplement this function to continue the service after a call to pause(). This function is called in reply to controller requests. The default implementation does nothing. \sa pause(), QtServiceController::resume() */ void QtServiceBase::resume() { } /*! Reimplement this function to process the user command \a code. This function is called in reply to controller requests. The default implementation does nothing. \sa QtServiceController::sendCommand() */ void QtServiceBase::processCommand(int /*code*/) { } /*! \fn void QtServiceBase::createApplication(int &argc, char **argv) Creates the application object using the \a argc and \a argv parameters. This function is only called when no \l {serviceSpecificArguments}{service specific arguments} were passed to the service constructor, and is called by exec() before it calls the executeApplication() and start() functions. The createApplication() function is implemented in QtService, but you might want to reimplement it, for example, if the chosen application type's constructor needs additional arguments. \sa exec(), QtService */ /*! \fn int QtServiceBase::executeApplication() Executes the application previously created with the createApplication() function. This function is only called when no \l {serviceSpecificArguments}{service specific arguments} were passed to the service constructor, and is called by exec() after it has called the createApplication() function and before start() function. This function is implemented in QtService. \sa exec(), createApplication() */ /*! \class QtService \brief The QtService is a convenient template class that allows you to create a service for a particular application type. A Windows service or Unix daemon (a "service"), is a program that runs "in the background" independently of whether a user is logged in or not. A service is often set up to start when the machine boots up, and will typically run continuously as long as the machine is on. Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes. (In certain circumstances, a service may provide a GUI itself, ref. the "interactive" example documentation). \bold{Note:} On Unix systems, this class relies on facilities provided by the QtNetwork module, provided as part of the \l{Qt Open Source Edition} and certain \l{Qt Commercial Editions}. The QtService class functionality is inherited from QtServiceBase, but in addition the QtService class binds an instance of QtServiceBase with an application type. Typically, you will create a service by subclassing the QtService template class. For example: \code class MyService : public QtService { public: MyService(int argc, char **argv); ~MyService(); protected: void start(); void stop(); void pause(); void resume(); void processCommand(int code); }; \endcode The application type can be QCoreApplication for services without GUI, QApplication for services with GUI or you can use your own custom application type. You must reimplement the QtServiceBase::start() function to perform the service's work. Usually you create some main object on the heap which is the heart of your service. In addition, you might want to reimplement the QtServiceBase::pause(), QtServiceBase::processCommand(), QtServiceBase::resume() and QtServiceBase::stop() to intervene the service's process on controller requests. You can control any given service using an instance of the QtServiceController class which also allows you to control services from separate applications. The mentioned functions are all virtual and won't do anything unless they are reimplemented. Your custom service is typically instantiated in the application's main function. Then the main function will call your service's exec() function, and return the result of that call. For example: \code int main(int argc, char **argv) { MyService service(argc, argv); return service.exec(); } \endcode When the exec() function is called, it will parse the \l {serviceSpecificArguments} {service specific arguments} passed in \c argv, perform the required actions, and exit. If none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller. \sa QtServiceBase, QtServiceController */ /*! \fn QtService::QtService(int argc, char **argv, const QString &name) Constructs a QtService object called \a name. The \a argc and \a argv parameters are parsed after the exec() function has been called. Then they are passed to the application's constructor. There can only be one QtService object in a process. \sa QtServiceBase() */ /*! \fn QtService::~QtService() Destroys the service object. */ /*! \fn Application *QtService::application() const Returns a pointer to the application object. */ /*! \fn void QtService::createApplication(int &argc, char **argv) Creates application object of type Application passing \a argc and \a argv to its constructor. \reimp */ /*! \fn int QtService::executeApplication() \reimp */ monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/qtunixsocket.cpp0000644000175000017500000000626011437034034025722 0ustar vettervetter/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include "qtunixsocket.h" #include #include #include #include #include #ifndef SUN_LEN #define SUN_LEN(ptr) ((size_t)(((struct sockaddr_un *) 0)->sun_path) \ +strlen ((ptr)->sun_path)) #endif QtUnixSocket::QtUnixSocket(QObject *parent) : QTcpSocket(parent) { } bool QtUnixSocket::connectTo(const QString &path) { bool ret = false; int sock = ::socket(PF_UNIX, SOCK_STREAM, 0); if (sock != -1) { struct sockaddr_un addr; ::memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; size_t pathlen = strlen(path.toLatin1().constData()); pathlen = qMin(pathlen, sizeof(addr.sun_path)); ::memcpy(addr.sun_path, path.toLatin1().constData(), pathlen); int err = ::connect(sock, (struct sockaddr *)&addr, SUN_LEN(&addr)); if (err != -1) { setSocketDescriptor(sock); ret = true; } else { ::close(sock); } } return ret; } monav-0.3/routingdaemon/qtservice-2.6_1-opensource/src/QtServiceController0000644000175000017500000000002711437034034026344 0ustar vettervetter#include "qtservice.h" monav-0.3/routingdaemon/qtservice-2.6_1-opensource/LICENSE.GPL30000644000175000017500000010451311437034034023377 0ustar vettervetter GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 3 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. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . monav-0.3/routingdaemon/routingdaemon.h0000644000175000017500000002267511524214364020015 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef ROUTINDDAEMON_H #define ROUTINDDAEMON_H #include "interfaces/irouter.h" #include "interfaces/igpslookup.h" #include "signals.h" #include "qtservice.h" #include "utils/directoryunpacker.h" #include #include #include #include #include #include using namespace MoNav; class RoutingDaemon : public QObject, public QtService< QCoreApplication > { Q_OBJECT public: RoutingDaemon( int argc, char** argv ) : QtService< QCoreApplication >( argc, argv, "MoNav Routing Daemon" ) { setServiceDescription( "The MoNav Routing Daemon" ); m_loaded = false; m_gpsLookup = NULL, m_router = NULL; m_server = new QLocalServer( this ); connect( m_server, SIGNAL(newConnection()), this, SLOT(newConnection()) ); } virtual ~RoutingDaemon() { unloadPlugins(); } public slots: void newConnection() { QLocalSocket* connection = m_server->nextPendingConnection(); connect( connection, SIGNAL(disconnected()), connection, SLOT(deleteLater()) ); CommandType type; if ( !type.read( connection ) ) return; if ( type.value == CommandType::UnpackCommand ) { unpackCommand( connection ); } else if ( type.value == CommandType::RoutingCommand ) { routingCommand( connection ); } } protected: void unpackCommand( QLocalSocket* connection ) { UnpackCommand command; UnpackResult result; if ( !command.read( connection ) ) return; result.type = UnpackResult::Success; DirectoryUnpacker unpacker( command.mapModuleFile ); if ( !unpacker.decompress( command.deleteFile ) ) result.type = UnpackResult::FailUnpacking; result.post( connection ); connection->flush(); connection->disconnectFromServer(); } void routingCommand( QLocalSocket* connection ) { RoutingCommand command; RoutingResult result; if ( !command.read( connection ) ) return; result.type = RoutingResult::Success; if ( !m_loaded || command.dataDirectory != m_dataDirectory ) { unloadPlugins(); m_loaded = loadPlugins( command.dataDirectory ); m_dataDirectory = command.dataDirectory; } if ( m_loaded ) { QVector< IRouter::Node > pathNodes; QVector< IRouter::Edge > pathEdges; double distance = 0; bool success = true; for ( int i = 1; i < command.waypoints.size(); i++ ) { if ( i != 1 ) result.pathNodes.pop_back(); double segmentDistance; GPSCoordinate source( command.waypoints[i - 1].latitude, command.waypoints[i - 1].longitude ); GPSCoordinate target( command.waypoints[i].latitude, command.waypoints[i].longitude ); pathNodes.clear(); pathEdges.clear(); if ( !computeRoute( &segmentDistance, &pathNodes, &pathEdges, source, target, command.lookupRadius ) ) { success = false; break; } distance += segmentDistance; for ( int j = 0; j < pathNodes.size(); j++ ) { Node node; GPSCoordinate gps = pathNodes[j].coordinate.ToGPSCoordinate(); node.latitude = gps.latitude; node.longitude = gps.longitude; result.pathNodes.push_back( node ); } for ( int j = 0; j < pathEdges.size(); j++ ) { Edge edge; edge.length = pathEdges[j].length; edge.name = pathEdges[j].name; edge.type = pathEdges[j].type; edge.seconds = pathEdges[j].seconds; edge.branchingPossible = pathEdges[j].branchingPossible; result.pathEdges.push_back( edge ); } } result.seconds = distance; if ( success ) { if ( command.lookupStrings ) { unsigned lastNameID = std::numeric_limits< unsigned >::max(); QString lastName; unsigned lastTypeID = std::numeric_limits< unsigned >::max(); QString lastType; for ( int j = 0; j < result.pathEdges.size(); j++ ) { if ( lastNameID != result.pathEdges[j].name ) { lastNameID = result.pathEdges[j].name; if ( !m_router->GetName( &lastName, lastNameID ) ) result.type = RoutingResult::NameLookupFailed; result.nameStrings.push_back( lastName ); } if ( lastTypeID != result.pathEdges[j].type ) { lastTypeID = result.pathEdges[j].type; if ( !m_router->GetType( &lastType, lastTypeID ) ) result.type = RoutingResult::TypeLookupFailed; result.typeStrings.push_back( lastType ); } result.pathEdges[j].name = result.nameStrings.size() - 1; result.pathEdges[j].type = result.typeStrings.size() - 1; } } } else { result.type = RoutingResult::RouteFailed; } } else { result.type = RoutingResult::LoadFailed; } if ( connection->state() != QLocalSocket::ConnectedState ) return; result.post( connection ); connection->flush(); connection->disconnectFromServer(); } virtual void start() { if ( !m_server->listen( "MoNavD" ) ) { // try to clean up after possible crash m_server->removeServer( "MoNavD" ); if ( !m_server->listen( "MoNavD" ) ) { qCritical() << "unable to start server"; exit( -1 ); } } } virtual void stop() { m_server->close(); } bool computeRoute( double* resultDistance, QVector< IRouter::Node >* resultNodes, QVector< IRouter::Edge >* resultEdge, GPSCoordinate source, GPSCoordinate target, double lookupRadius ) { if ( m_gpsLookup == NULL || m_router == NULL ) { qCritical() << "tried to query route before setting valid data directory"; return false; } UnsignedCoordinate sourceCoordinate( source ); UnsignedCoordinate targetCoordinate( target ); IGPSLookup::Result sourcePosition; QTime time; time.start(); bool found = m_gpsLookup->GetNearestEdge( &sourcePosition, sourceCoordinate, lookupRadius ); qDebug() << "GPS Lookup:" << time.restart() << "ms"; if ( !found ) { qDebug() << "no edge near source found"; return false; } IGPSLookup::Result targetPosition; found = m_gpsLookup->GetNearestEdge( &targetPosition, targetCoordinate, lookupRadius ); qDebug() << "GPS Lookup:" << time.restart() << "ms"; if ( !found ) { qDebug() << "no edge near target found"; return false; } found = m_router->GetRoute( resultDistance, resultNodes, resultEdge, sourcePosition, targetPosition ); qDebug() << "Routing:" << time.restart() << "ms"; return found; } bool loadPlugins( QString dataDirectory ) { QDir dir( dataDirectory ); QString configFilename = dir.filePath( "Module.ini" ); if ( !QFile::exists( configFilename ) ) { qCritical() << "Not a valid routing module directory: Missing Module.ini"; return false; } QSettings pluginSettings( configFilename, QSettings::IniFormat ); int iniVersion = pluginSettings.value( "configVersion" ).toInt(); if ( iniVersion != 2 ) { qCritical() << "Config File not compatible"; return false; } QString routerName = pluginSettings.value( "router" ).toString(); QString gpsLookupName = pluginSettings.value( "gpsLookup" ).toString(); foreach ( QObject *plugin, QPluginLoader::staticInstances() ) testPlugin( plugin, routerName, gpsLookupName ); try { if ( m_gpsLookup == NULL ) { qCritical() << "GPSLookup plugin not found:" << gpsLookupName; return false; } int gpsLookupFileFormatVersion = pluginSettings.value( "gpsLookupFileFormatVersion" ).toInt(); if ( !m_gpsLookup->IsCompatible( gpsLookupFileFormatVersion ) ) { qCritical() << "GPS Lookup file format not compatible"; return false; } m_gpsLookup->SetInputDirectory( dataDirectory ); if ( !m_gpsLookup->LoadData() ) { qCritical() << "could not load GPSLookup data"; return false; } if ( m_router == NULL ) { qCritical() << "router plugin not found:" << routerName; return false; } int routerFileFormatVersion = pluginSettings.value( "routerFileFormatVersion" ).toInt(); if ( !m_gpsLookup->IsCompatible( routerFileFormatVersion ) ) { qCritical() << "Router file format not compatible"; return false; } m_router->SetInputDirectory( dataDirectory ); if ( !m_router->LoadData() ) { qCritical() << "could not load router data"; return false; } } catch ( ... ) { qCritical() << "caught exception while loading plugins"; return false; } qDebug() << "loaded:" << pluginSettings.value( "name" ).toString() << pluginSettings.value( "description" ).toString(); return true; } void testPlugin( QObject* plugin, QString routerName, QString gpsLookupName ) { if ( IGPSLookup *interface = qobject_cast< IGPSLookup* >( plugin ) ) { qDebug() << "found plugin:" << interface->GetName(); if ( interface->GetName() == gpsLookupName ) m_gpsLookup = interface; } if ( IRouter *interface = qobject_cast< IRouter* >( plugin ) ) { qDebug() << "found plugin:" << interface->GetName(); if ( interface->GetName() == routerName ) m_router = interface; } } void unloadPlugins() { m_router = NULL; m_gpsLookup = NULL; } bool m_loaded; QString m_dataDirectory; IGPSLookup* m_gpsLookup; IRouter* m_router; QLocalServer* m_server; }; #endif // ROUTINDDAEMON_H monav-0.3/bin/0000755000175000017500000000000011554574461012664 5ustar vettervettermonav-0.3/bin/plugins_client/0000755000175000017500000000000011554574461015703 5ustar vettervettermonav-0.3/bin/plugins_preprocessor/0000755000175000017500000000000011554574461017153 5ustar vettervettermonav-0.3/misc/0000755000175000017500000000000011554574461013047 5ustar vettervettermonav-0.3/misc/license_template_christian0000644000175000017500000000125211513155554020344 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */monav-0.3/client/0000755000175000017500000000000011554574462013373 5ustar vettervettermonav-0.3/client/mapmoduleswidget.h0000644000175000017500000000222611524531126017103 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef MAPMODULESWIDGET_H #define MAPMODULESWIDGET_H #include namespace Ui { class MapModulesWidget; } class MapModulesWidget : public QWidget { Q_OBJECT public: explicit MapModulesWidget( QWidget* parent = 0 ); ~MapModulesWidget(); signals: void cancelled(); void selected(); protected slots: void populateData(); void select(); protected: struct PrivateImplementation; PrivateImplementation* d; Ui::MapModulesWidget* m_ui; }; #endif // MAPMODULESWIDGET_H monav-0.3/client/descriptiongenerator.h0000644000175000017500000001711211454673710017773 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef DESCRIPTIONGENERATOR_H #define DESCRIPTIONGENERATOR_H #include "mapdata.h" #include #include #include class DescriptionGenerator { public: DescriptionGenerator() { reset(); } void reset() { m_lastNameID = std::numeric_limits< unsigned >::max(); m_lastTypeID = std::numeric_limits< unsigned >::max(); } void descriptions( QStringList* icons, QStringList* labels, QVector< IRouter::Node > pathNodes, QVector< IRouter::Edge > pathEdges, int maxSeconds = std::numeric_limits< int >::max() ) { icons->clear(); labels->clear(); IRouter* router = MapData::instance()->router(); if ( router == NULL || pathEdges.empty() || pathNodes.empty() ) { *icons = QStringList(); *labels = QStringList(); return; } newDescription( router, pathEdges.first() ); int seconds = 0; int node = 0; GPSCoordinate gps = pathNodes.first().coordinate.ToGPSCoordinate(); for ( int edge = 0; edge < pathEdges.size() - 1; edge++ ) { node += pathEdges[edge].length; GPSCoordinate nextGPS = pathNodes[node].coordinate.ToGPSCoordinate(); m_distance += gps.ApproximateDistance( nextGPS ); gps = nextGPS; m_branchingPossible = pathEdges[edge].branchingPossible; seconds += pathEdges[edge].seconds; if ( m_lastType == "roundabout" && pathEdges[edge + 1].type == m_lastTypeID ) { if ( m_branchingPossible ) m_exitNumber++; continue; } int direction = angle( pathNodes[node - 1].coordinate, pathNodes[node].coordinate, pathNodes[node + 1].coordinate ); bool breakDescription = false; QString type; bool typeAvailable = router->GetType( &type, pathEdges[edge + 1].type ); assert( typeAvailable ); if ( type == "motorway_link" && m_lastType != "motorway_link" ) { for ( int nextEdge = edge + 2; nextEdge < pathEdges.size(); nextEdge++ ) { if ( pathEdges[nextEdge].type != pathEdges[edge + 1].type ) { for ( int otherEdge = edge + 1; otherEdge < nextEdge; otherEdge++ ) pathEdges[otherEdge].name = pathEdges[nextEdge].name; break; } } } if ( ( type == "roundabout" ) != ( m_lastType == "roundabout" ) ) { breakDescription = true; if ( type != "roundabout" ) direction = 0; } else { if ( m_branchingPossible ) { if ( abs( direction ) > 1 ) breakDescription = true; } if ( m_lastNameID != pathEdges[edge + 1].name ) breakDescription = true; } if ( breakDescription ) { describe( icons, labels); if ( seconds >= maxSeconds ) break; newDescription( router, pathEdges[edge + 1] ); m_direction = direction; } } GPSCoordinate nextGPS = pathNodes.back().coordinate.ToGPSCoordinate(); m_distance += gps.ApproximateDistance( nextGPS ); if ( seconds < maxSeconds ) describe( icons, labels ); } protected: int angle( UnsignedCoordinate first, UnsignedCoordinate second, UnsignedCoordinate third ) { double x1 = ( double ) second.x - first.x; // a = (x1,y1) double y1 = ( double ) second.y - first.y; double x2 = ( double ) third.x - second.x; // b = (x2, y2 ) double y2 = ( double ) third.y - second.y; int angle = ( atan2( y1, x1 ) - atan2( y2, x2 ) ) * 180 / M_PI + 720; angle %= 360; static const int forward = 10; static const int sharp = 45; static const int slightly = 20; if ( angle > 180 ) { if ( angle > 360 - forward - slightly ) { if ( angle > 360 - forward ) return 0; else return 1; } else { if ( angle > 180 + sharp ) return 2; else return 3; } } else { if ( angle > forward + slightly ) { if ( angle > 180 - sharp ) return -3; else return -2; } else { if ( angle > forward ) return -1; else return 0; } } } void describe( QStringList* icons, QStringList* labels ) { if ( m_exitNumber != 0 ) { icons->push_back( QString( ":/images/directions/roundabout.png" ) ); labels->push_back( QString( "Enter the roundabout." ) ); icons->push_back( QString( ":/images/directions/roundabout_exit%1.png" ).arg( m_exitNumber ) ); labels->push_back( QString( "Take the %1. exit." ).arg( m_exitNumber ) ); m_exitNumber = 0; return; } QString name = m_lastName; switch ( m_direction ) { case 0: break; case 1: { icons->push_back( ":/images/directions/slightly_right.png" ); labels->push_back( "Keep slightly right" ); break; } case 2: { icons->push_back( ":/images/directions/right.png" ); labels->push_back( "Turn right" ); break; } case 3: { icons->push_back( ":/images/directions/sharply_right.png" ); labels->push_back( "Turn sharply right" ); break; } case -1: { icons->push_back( ":/images/directions/slightly_left.png" ); labels->push_back( "Keep slightly left" ); break; } case -2: { icons->push_back( ":/images/directions/left.png" ); labels->push_back( "Turn left" ); break; } case -3: { icons->push_back( ":/images/directions/sharply_left.png" ); labels->push_back( "Turn sharply left" ); break; } } if ( m_direction != 0 ) { if ( !name.isEmpty() ) labels->back() += " into " + name + "."; else labels->back() += "."; } if ( m_lastType == "motorway_link" ) { if ( m_direction == 0 ) { icons->push_back( ":/images/directions/forward.png" ); labels->push_back( "" ); } if ( !name.isEmpty() ) labels->last() = "Take the ramp towards " + name + "."; else labels->last() = "Take the ramp."; } if ( m_distance > 20 ) { QString distance; if ( m_distance < 100 ) distance = QString( "%1m" ).arg( ( int ) m_distance ); else if ( m_distance < 1000 ) distance = QString( "%1m" ).arg( ( int ) m_distance / 10 * 10 ); else if ( m_distance < 10000 ) distance = QString( "%1.%2km" ).arg( ( int ) m_distance / 1000 ).arg( ( ( int ) m_distance / 100 ) % 10 ); else distance = QString( "%1km" ).arg( ( int ) m_distance / 1000 ); icons->push_back( ":/images/directions/forward.png" ); if ( !name.isEmpty() ) labels->push_back( ( "Continue on " + name + " for " + distance + "." ) ); else labels->push_back( ( "Continue for " + distance + "." ) ); } } void newDescription( IRouter* router, const IRouter::Edge& edge ) { if ( m_lastNameID != edge.name ) { m_lastNameID = edge.name; bool nameAvailable = router->GetName( &m_lastName, m_lastNameID ); assert( nameAvailable ); } if ( m_lastTypeID != edge.type ) { m_lastTypeID = edge.type; bool typeAvailable = router->GetType( &m_lastType, m_lastTypeID ); assert( typeAvailable ); } m_branchingPossible = edge.branchingPossible; m_distance = 0; m_direction = 0; m_exitNumber = m_lastType == "roundabout" ? 1 : 0; } unsigned m_lastNameID; unsigned m_lastTypeID; QString m_lastName; QString m_lastType; bool m_branchingPossible; double m_distance; int m_direction; int m_exitNumber; }; #endif // DESCRIPTIONGENERATOR_H monav-0.3/client/scrollarea.cpp0000644000175000017500000000413211455420653016216 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "scrollarea.h" #include #include #include #include #include ScrollArea::ScrollArea( QWidget* parent ) : QScrollArea( parent ) { m_orientation = Qt::Vertical; } Qt::Orientation ScrollArea::orientation() { return m_orientation; } void ScrollArea::setOrientation( Qt::Orientation orientation ) { m_orientation = orientation; } void ScrollArea::mousePressEvent( QMouseEvent* event ) { event->accept(); } void ScrollArea::mouseMoveEvent( QMouseEvent* event ) { event->accept(); } void ScrollArea::resizeEvent( QResizeEvent* event ) { QScrollArea::resizeEvent( event ); if ( widget() == NULL ) return; int widgetWidth = widget()->sizeHint().width() + 2 * frameWidth(); int widgetHeight = widget()->sizeHint().height() + 2 * frameWidth(); if ( m_orientation == Qt::Vertical ) { if ( widgetHeight > height() ) { widgetWidth += QApplication::style()->pixelMetric( QStyle::PM_ScrollBarExtent ); widgetWidth += QApplication::style()->pixelMetric( QStyle::PM_ScrollView_ScrollBarSpacing ); } setFixedWidth( widgetWidth ); setMaximumHeight( widgetHeight ); } else { if ( widgetWidth > width() ) { widgetHeight += QApplication::style()->pixelMetric( QStyle::PM_ScrollBarExtent ); widgetHeight += QApplication::style()->pixelMetric( QStyle::PM_ScrollView_ScrollBarSpacing ); } setFixedHeight( widgetHeight ); setMaximumWidth( widgetWidth ); } } monav-0.3/client/addressdialog.cpp0000644000175000017500000001371111524531126016672 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "addressdialog.h" #include "ui_addressdialog.h" #include "placechooser.h" #include "streetchooser.h" #include "mapdata.h" #include "utils/qthelpers.h" #include AddressDialog::AddressDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::AddressDialog) { m_ui->setupUi(this); // Windows Mobile Window Flags setWindowFlags( windowFlags() & ( ~Qt::WindowOkButtonHint ) ); setWindowFlags( windowFlags() | Qt::WindowCancelButtonHint ); bool increaseFontSize = true; #ifdef Q_WS_MAEMO_5 setAttribute( Qt::WA_Maemo5StackedWindow ); m_ui->characterList->hide(); increaseFontSize = false; #endif m_skipStreetPosition = false; m_ui->suggestionList->setAlternatingRowColors( true ); m_ui->characterList->setAlternatingRowColors( true ); if ( increaseFontSize ) { QFont font = m_ui->suggestionList->font(); font.setPointSize( font.pointSize() * 1.5 ); m_ui->suggestionList->setFont( font ); m_ui->characterList->setFont( font ); } resetCity(); connectSlots(); } AddressDialog::~AddressDialog() { delete m_ui; } void AddressDialog::connectSlots() { connect( m_ui->cityEdit, SIGNAL(textChanged(QString)), this, SLOT(cityTextChanged(QString)) ); connect( m_ui->streetEdit, SIGNAL(textChanged(QString)), this, SLOT(streetTextChanged(QString)) ); connect( m_ui->suggestionList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(suggestionClicked(QListWidgetItem*)) ); connect( m_ui->characterList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(characterClicked(QListWidgetItem*)) ); connect( m_ui->resetCity, SIGNAL(clicked()), this, SLOT(resetCity()) ); connect( m_ui->resetStreet, SIGNAL(clicked()), this, SLOT(resetStreet()) ); } void AddressDialog::characterClicked( QListWidgetItem * item ) { QString text = item->text(); if ( m_mode == City ) { m_ui->cityEdit->setText( text ); m_ui->cityEdit->setFocus( Qt::OtherFocusReason ); } else if ( m_mode == Street ) { m_ui->streetEdit->setText( text ); m_ui->streetEdit->setFocus( Qt::OtherFocusReason ); } } void AddressDialog::suggestionClicked( QListWidgetItem * item ) { IAddressLookup* addressLookup = MapData::instance()->addressLookup(); if ( addressLookup == NULL ) return; QString text = item->text(); if ( m_mode == City ) { QVector< int > placeIDs; QVector< UnsignedCoordinate > placeCoordinates; if ( !addressLookup->GetPlaceData( text, &placeIDs, &placeCoordinates ) ) return; m_placeID = placeIDs.front(); if ( placeIDs.size() > 1 ) { int id = PlaceChooser::selectPlaces( placeCoordinates, this ); if ( id >= 0 && id < placeIDs.size() ) m_placeID = placeIDs[id]; else return; } m_ui->cityEdit->setText( text ); m_ui->cityEdit->setDisabled( true ); m_ui->streetEdit->setEnabled( true ); m_ui->streetEdit->setFocus(); m_ui->resetStreet->setEnabled( true ); m_mode = Street; streetTextChanged( m_ui->streetEdit->text() ); } else { QVector< int > segmentLength; QVector< UnsignedCoordinate > coordinates; if ( !addressLookup->GetStreetData( m_placeID, text, &segmentLength, &coordinates ) ) return; if ( coordinates.size() == 0 ) return; if ( m_skipStreetPosition ) { m_result = coordinates.first(); accept(); return; } if( !StreetChooser::selectStreet( &m_result, segmentLength, coordinates, this ) ) return; m_ui->streetEdit->setText( text ); accept(); } } void AddressDialog::cityTextChanged( QString text ) { IAddressLookup* addressLookup = MapData::instance()->addressLookup(); if ( addressLookup == NULL ) return; m_ui->suggestionList->clear(); m_ui->characterList->clear(); QStringList suggestions; QStringList characters; Timer time; bool found = addressLookup->GetPlaceSuggestions( text, 10, &suggestions, &characters ); qDebug() << "City Lookup:" << time.elapsed() << "ms"; if ( !found ) return; m_ui->suggestionList->addItems( suggestions ); m_ui->characterList->addItems( characters ); } void AddressDialog::streetTextChanged( QString text) { IAddressLookup* addressLookup = MapData::instance()->addressLookup(); if ( addressLookup == NULL ) return; if ( m_mode != Street ) return; m_ui->suggestionList->clear(); m_ui->characterList->clear(); QStringList suggestions; QStringList characters; Timer time; bool found = addressLookup->GetStreetSuggestions( m_placeID, text, 10, &suggestions, &characters ); qDebug() << "Street Lookup:" << time.elapsed() << "ms"; if ( !found ) return; m_ui->suggestionList->addItems( suggestions ); m_ui->characterList->addItems( characters ); } void AddressDialog::resetCity() { m_ui->cityEdit->setEnabled( true ); m_ui->resetCity->setEnabled( true ); m_ui->streetEdit->setDisabled( true ); m_ui->resetStreet->setDisabled( true ); m_ui->streetEdit->setText( "" ); m_ui->cityEdit->setText( "" ); m_mode = City; cityTextChanged( "" ); m_ui->cityEdit->setFocus( Qt::OtherFocusReason ); } void AddressDialog::resetStreet() { m_ui->streetEdit->setText( "" ); streetTextChanged( "" ); m_ui->streetEdit->setFocus( Qt::OtherFocusReason ); } bool AddressDialog::getAddress( UnsignedCoordinate* result, QWidget* p, bool cityOnly ) { if ( result == NULL ) return false; AddressDialog* window = new AddressDialog( p ); window->m_skipStreetPosition = cityOnly; int value = window->exec(); if ( value == Accepted ) *result = window->m_result; delete window; return value == Accepted; } monav-0.3/client/addressdialog.h0000644000175000017500000000305511454673710016347 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef ADDRESSDIALOG_H #define ADDRESSDIALOG_H #include #include #include "interfaces/iaddresslookup.h" #include "interfaces/irenderer.h" #include "interfaces/igpslookup.h" namespace Ui { class AddressDialog; } class AddressDialog : public QDialog { Q_OBJECT public: explicit AddressDialog(QWidget *parent = 0); ~AddressDialog(); static bool getAddress( UnsignedCoordinate* result, QWidget* p, bool cityOnly = false ); public slots: void characterClicked( QListWidgetItem* item ); void suggestionClicked( QListWidgetItem* item ); void cityTextChanged( QString text ); void streetTextChanged( QString text ); void resetCity(); void resetStreet(); protected: void connectSlots(); enum { City = 0, Street = 1 } m_mode; int m_placeID; UnsignedCoordinate m_result; bool m_skipStreetPosition; Ui::AddressDialog* m_ui; }; #endif // ADDRESSDIALOG_H monav-0.3/client/worldmapchooser.cpp0000644000175000017500000001257111553070724017304 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "worldmapchooser.h" #include "ui_worldmapchooser.h" #include #include #include #include #include #include #include struct WorldMapChooser::PrivateImplementation { QVector< MapData::MapPackage > maps; double minX; double minY; double maxX; double maxY; int highlight; QVector< QRect > rects; QString background; }; WorldMapChooser::WorldMapChooser( QWidget* parent ) : QWidget( parent ), m_ui(new Ui::WorldMapChooser) { m_ui->setupUi(this); d = new PrivateImplementation; d->minX = 0; d->minY = 0; d->maxX = 1; d->maxY = 1; QDir dir( ":/images/world" ); // crude heuristic: the largest image will be the most accurate one // in praxis only one image should exist as an appropiate one shouldbe selected during // the build process QStringList candidates = dir.entryList( QDir::Files, QDir::Size ); if ( !candidates.isEmpty() ) d->background = dir.filePath( candidates.first() ); } WorldMapChooser::~WorldMapChooser() { delete d; delete m_ui; } void WorldMapChooser::showEvent( QShowEvent* ) { QResizeEvent event( size(), size() ); resizeEvent( &event ); } void WorldMapChooser::hideEvent( QHideEvent* ) { // save memory m_ui->label->setPixmap( QPixmap() ); } void WorldMapChooser::setHighlight( int id ) { d->highlight = id; update(); } void WorldMapChooser::mouseReleaseEvent( QMouseEvent* event ) { if ( event->button() != Qt::LeftButton ) { event->ignore(); return; } QVector< int > result; for ( int i = 0; i < d->rects.size(); i++ ) { if ( d->rects[i].contains( event->pos() ) ) { result.push_back( i ); } } if ( result.size() > 0 ) { int next = 0; if ( result.contains( d->highlight ) ) { next = result.indexOf( d->highlight ); next = ( next + 1 ) % result.size(); } d->highlight = result[next]; emit clicked( d->highlight ); QResizeEvent event( size(), size() ); resizeEvent( &event ); } event->accept(); } void WorldMapChooser::setMaps( QVector maps ) { d->maps = maps; if ( maps.size() == 0 ) { d->minX = 0; d->minY = 0; d->maxX = 1; d->maxY = 1; } else { d->minX = 1; d->minY = 1; d->maxX = 0; d->maxY = 0; for ( int i = 0; i < maps.size(); i++ ) { ProjectedCoordinate min = maps[i].min.ToProjectedCoordinate(); ProjectedCoordinate max = maps[i].max.ToProjectedCoordinate(); d->minX = std::min( min.x, d->minX ); d->maxX = std::max( max.x, d->maxX ); d->minY = std::min( min.y, d->minY ); d->maxY = std::max( max.y, d->maxY ); } double rangeX = d->maxX - d->minX; double rangeY = d->maxY - d->minY; if ( rangeX == 0 ) rangeX = 1; if ( rangeY == 0 ) rangeY = 1; d->minX = std::max( d->minX - rangeX * 0.1, 0.0 ); d->minY = std::max( d->minY - rangeY * 0.1, 0.0 ); d->maxX = std::min( d->maxX + rangeX * 0.1, 1.0 ); d->maxY = std::min( d->maxY + rangeY * 0.1, 1.0 ); } QResizeEvent event( size(), size() ); resizeEvent( &event ); } void WorldMapChooser::resizeEvent( QResizeEvent* event ) { int width = event->size().width(); int height = event->size().height(); double rangeX = d->maxX - d->minX; double rangeY = d->maxY - d->minY; double minX = d->minX; double maxX = d->maxX; double minY = d->minY; double maxY = d->maxY; if ( rangeX / rangeY > ( double ) width / height ) { double move = rangeX / width * height - rangeY; minY -= move / 2; maxY += move / 2; rangeY = rangeX / width * height; } else if ( rangeX / rangeY < ( double ) width / height ) { double move = rangeY * width / height - rangeX; minX -= move / 2; maxX += move / 2; rangeX = rangeY * width / height; } d->rects.clear(); QPixmap image( width, height ); if ( !image.isNull() ) { image.fill( Qt::transparent ); QPainter painter( &image ); QPixmap background( d->background ); painter.setRenderHint( QPainter::SmoothPixmapTransform ); painter.drawPixmap( QRect( 0, 0, width, height ), background, QRect( minX * background.width(), minY * background.width() - 192 / 1024.0 * background.width(), rangeX * background.width(), rangeY * background.width() ) ); for ( int i = 0; i < d->maps.size(); i++ ) { ProjectedCoordinate min = d->maps[i].min.ToProjectedCoordinate(); ProjectedCoordinate max = d->maps[i].max.ToProjectedCoordinate(); int left = ( min.x - minX ) * width / rangeX; int top = ( min.y - minY ) * height / rangeY; int right = ( max.x - minX ) * width / rangeX; int bottom = ( max.y - minY ) * height / rangeY; if ( d->highlight == i ) painter.setBrush( QColor( 128, 128, 128, 128 ) ); else painter.setBrush( Qt::NoBrush ); QRect rect( left, top, right - left, bottom - top ); painter.drawRect( rect ); d->rects.push_back( rect ); } } m_ui->label->setPixmap( image ); } monav-0.3/client/gpsdialog.ui0000644000175000017500000000552711455433366015711 0ustar vettervetter GPSDialog 0 0 171 159 GPS Information Latitude: TextLabel Longitude: TextLabel Heading: TextLabel Height: TextLabel Speed: TextLabel Vertical Speed: TextLabel Time: TextLabel monav-0.3/client/placechooser.cpp0000644000175000017500000000761611537476247016563 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "placechooser.h" #include "ui_placechooser.h" #include "interfaces/irenderer.h" #include "mapdata.h" #include "globalsettings.h" struct PlaceChooser::PrivateImplementation { QVector< UnsignedCoordinate > places; int place; UnsignedCoordinate selected; }; PlaceChooser::PlaceChooser( QWidget* parent ) : QDialog( parent ), m_ui( new Ui::PlaceChooser ) { m_ui->setupUi( this ); d = new PrivateImplementation; m_ui->zoomBar->hide(); connect( m_ui->zoomBar, SIGNAL(valueChanged(int)), this, SLOT(setZoom(int)) ); connect( m_ui->paintArea, SIGNAL(zoomChanged(int)), this, SLOT(setZoom(int)) ); connect( m_ui->previousButton, SIGNAL(clicked()), this, SLOT(previousPlace()) ); connect( m_ui->nextButton, SIGNAL(clicked()), this, SLOT(nextPlace()) ); connect( m_ui->headerLabel, SIGNAL(clicked()), this, SLOT(accept()) ); connect( m_ui->zoomIn, SIGNAL(clicked()), this, SLOT(addZoom()) ); connect( m_ui->zoomOut, SIGNAL(clicked()), this, SLOT(subtractZoom()) ); int iconSize = GlobalSettings::iconSize(); QSize size( iconSize, iconSize ); m_ui->previousButton->setIconSize( size ); m_ui->nextButton->setIconSize( size ); m_ui->zoomIn->setIconSize( size ); m_ui->zoomOut->setIconSize( size ); IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; int maxZoom = renderer->GetMaxZoom(); m_ui->zoomBar->setMaximum( maxZoom ); m_ui->paintArea->setMaxZoom( maxZoom ); setZoom( GlobalSettings::zoomPlaceChooser()); m_ui->paintArea->setVirtualZoom( GlobalSettings::magnification() ); } PlaceChooser::~PlaceChooser() { delete d; delete m_ui; } void PlaceChooser::addZoom() { setZoom( GlobalSettings::zoomPlaceChooser() + 1 ); } void PlaceChooser::subtractZoom() { setZoom( GlobalSettings::zoomPlaceChooser() - 1 ); } void PlaceChooser::setZoom( int zoom ) { IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; if( zoom > renderer->GetMaxZoom() ) zoom = renderer->GetMaxZoom(); if( zoom < 0 ) zoom = 0; m_ui->zoomBar->setValue( zoom ); m_ui->paintArea->setZoom( zoom ); GlobalSettings::setZoomPlaceChooser( zoom ); } void PlaceChooser::nextPlace() { d->place = ( d->place + 1 ) % d->places.size(); m_ui->headerLabel->setText( QString( tr( "Choose City (%1/%2)" ) ).arg( d->place + 1 ).arg( d->places.size() ) ); m_ui->paintArea->setCenter( d->places[d->place].ToProjectedCoordinate() ); } void PlaceChooser::previousPlace() { d->place = ( d->place + d->places.size() - 1 ) % d->places.size(); m_ui->headerLabel->setText( QString( tr( "Choose City (%1/%2)" ) ).arg( d->place + 1 ).arg( d->places.size() ) ); m_ui->paintArea->setCenter( d->places[d->place].ToProjectedCoordinate() ); } int PlaceChooser::selectPlaces( QVector< UnsignedCoordinate > places, QWidget* p ) { if ( places.size() == 0 ) return -1; PlaceChooser* window = new PlaceChooser( p ); window->d->places = places; window->d->place = 0; window->m_ui->headerLabel->setText( QString( tr( "Choose City (%1/%2)" ) ).arg( 1 ).arg( places.size() ) ); window->m_ui->paintArea->setCenter( places.first().ToProjectedCoordinate() ); window->m_ui->paintArea->setPOIs( places ); int value = window->exec(); int id = -1; if ( value == Accepted ) id = window->d->place; delete window; return id; } monav-0.3/client/generalsettingsdialog.ui0000644000175000017500000001527111551034370020300 0ustar vettervetter GeneralSettingsDialog 0 0 252 243 Settings 4 0 GUI Map Magnification: 1 Icon Size: 16 256 Default Popup Menus Overlay Menus Qt::Vertical 20 36 Routing Rotate Map automatically Qt::Vertical 20 136 Logging The GPS position is logged to a file for later use. The GPS position is logged to a file for later use. Enable Logging Click to select the logfile folder Click to select the logfile folder Click to clear the tracklog Click to clear the tracklog Clear Tracklog Qt::Vertical 20 78 Close pushButton clicked() GeneralSettingsDialog accept() 198 177 238 297 monav-0.3/client/streetchooser.ui0000644000175000017500000003203311524531126016607 0ustar vettervetter StreetChooser 0 0 400 300 MoNav - Choose Location 0 0 0 0 0 0 Qt::Horizontal 1 1 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 true QFrame::StyledPanel QFrame::Raised 4 2 Choose Qt::Horizontal 1 1 0 0 Qt::Horizontal 1 1 0 Qt::Vertical 1 1 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 true QFrame::StyledPanel QFrame::Raised 0 2 0 0 Qt::NoFocus + :/images/oxygen/zoom-in.png:/images/oxygen/zoom-in.png true 0 0 Qt::NoFocus - :/images/oxygen/zoom-out.png:/images/oxygen/zoom-out.png true Qt::Vertical 1 1 0 0 10 1 Qt::Vertical QSlider::TicksBothSides PaintWidget QWidget
paintwidget.h
1
monav-0.3/client/gpsdialog.cpp0000644000175000017500000000514711456035572016052 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "gpsdialog.h" #include "ui_gpsdialog.h" #include "routinglogic.h" GPSDialog::GPSDialog( QWidget *parent ) : QDialog( parent ), m_ui( new Ui::GPSDialog ) { m_ui->setupUi(this); // Windows Mobile Window Flags setWindowFlags( windowFlags() & ( ~Qt::WindowOkButtonHint ) ); #ifdef Q_WS_MAEMO_5 setAttribute( Qt::WA_Maemo5StackedWindow ); #endif gpsInfoUpdated(); connect( RoutingLogic::instance(), SIGNAL(gpsInfoChanged()), this, SLOT(gpsInfoUpdated()) ); } void GPSDialog::gpsInfoUpdated() { const RoutingLogic::GPSInfo& gpsInfo = RoutingLogic::instance()->gpsInfo(); if ( gpsInfo.position.IsValid() ) { GPSCoordinate gps = gpsInfo.position.ToGPSCoordinate(); m_ui->latitude->setText( QString::number( gps.latitude ) + QString::fromUtf8( "\302\260" ) + " +- " + QString::number( gpsInfo.horizontalAccuracy ) + "m" ); m_ui->longitude->setText( QString::number( gps.longitude ) + QString::fromUtf8( "\302\260" ) + " +- " + QString::number( gpsInfo.horizontalAccuracy ) + "m" ); } else { m_ui->latitude->setText( tr( "N/A" ) ); m_ui->longitude->setText( tr( "N/A" ) ); } if ( gpsInfo.heading >= 0 ) m_ui->heading->setText( QString::number( gpsInfo.heading ) + QString::fromUtf8( "\302\260" ) ); else m_ui->heading->setText( tr( "N/A" ) ); if ( gpsInfo.altitude >= 0 ) m_ui->height->setText( QString::number( gpsInfo.altitude ) + " +- " + QString::number( gpsInfo.verticalAccuracy ) + "m" ); else m_ui->height->setText( tr( "N/A" ) ); if ( gpsInfo.groundSpeed >= 0 ) m_ui->speed->setText( QString::number( gpsInfo.groundSpeed ) + "m/s" ); else m_ui->speed->setText( tr( "N/A" ) ); if ( gpsInfo.verticalSpeed >= 0 ) m_ui->verticalSpeed->setText( QString::number( gpsInfo.verticalSpeed ) + "m/s" ); else m_ui->verticalSpeed->setText( tr( "N/A" ) ); if ( gpsInfo.timestamp.isValid() ) m_ui->time->setText( gpsInfo.timestamp.toString() ); else m_ui->time->setText( tr( "N/A" ) ); } GPSDialog::~GPSDialog() { delete m_ui; } monav-0.3/client/routedescriptiondialog.ui0000644000175000017500000000275311524532041020503 0ustar vettervetter RouteDescriptionDialog 0 0 400 300 Route Description 4 2 0 0 ... Qt::LeftArrow QAbstractItemView::NoEditTriggers QAbstractItemView::NoSelection QListView::Adjust true monav-0.3/client/main.cpp0000644000175000017500000000506611542725337015026 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include #include "mainwindow.h" #include "mapdata.h" #include #include #include #include #include #ifdef Q_WS_MAEMO_5 #include #endif Q_IMPORT_PLUGIN( mapnikrendererclient ); Q_IMPORT_PLUGIN( contractionhierarchiesclient ); Q_IMPORT_PLUGIN( gpsgridclient ); Q_IMPORT_PLUGIN( unicodetournamenttrieclient ); Q_IMPORT_PLUGIN( osmrendererclient ); Q_IMPORT_PLUGIN( qtilerendererclient ); void MessageBoxHandler(QtMsgType type, const char *msg) { if ( QApplication::instance() != NULL ) { const bool isGuiThread = QThread::currentThread() == QApplication::instance()->thread(); if ( isGuiThread ) { #ifdef Q_WS_MAEMO_5 switch (type) { case QtDebugMsg: //QMessageBox::information(0, "Debug message", msg, QMessageBox::Ok); break; case QtWarningMsg: QMaemo5InformationBox::information( NULL, msg, QMaemo5InformationBox::NoTimeout ); break; case QtCriticalMsg: QMaemo5InformationBox::information( NULL, msg, QMaemo5InformationBox::NoTimeout ); break; case QtFatalMsg: QMaemo5InformationBox::information( NULL, msg, QMaemo5InformationBox::NoTimeout ); exit( -1 ); } #else switch (type) { case QtDebugMsg: //QMessageBox::information(0, "Debug message", msg, QMessageBox::Ok); break; case QtWarningMsg: QMessageBox::warning(0, "Warning", msg, QMessageBox::Ok); break; case QtCriticalMsg: QMessageBox::critical(0, "Critical error", msg, QMessageBox::Ok); break; case QtFatalMsg: QMessageBox::critical(0, "Fatal error", msg, QMessageBox::Ok); exit( -1 ); } #endif } } printf( "%s\n", msg ); } int main(int argc, char *argv[]) { QApplication a(argc, argv); qInstallMsgHandler( MessageBoxHandler ); a.connect( &a, SIGNAL(aboutToQuit()), MapData::instance(), SLOT(cleanup()) ); MainWindow w; w.show(); return a.exec(); } monav-0.3/client/mappackageswidget.cpp0000644000175000017500000001472011553076564017562 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "mappackageswidget.h" #include "ui_mappackageswidget.h" #include "mapdata.h" #include #include #include #include #include #include #include #include struct MapPackagesWidget::PrivateImplementation { struct Server { QString name; QString url; int id; }; int selected; QString path; QVector< MapData::MapPackage > maps; QVector< Server > servers; void populateInstalled( QListWidget* list ); void highlightButton( QPushButton* button, bool highlight ); }; MapPackagesWidget::MapPackagesWidget( QWidget* parent ) : QWidget( parent ), m_ui( new Ui::MapPackagesWidget ) { m_ui->setupUi( this ); d = new PrivateImplementation; // Remove non-functional pages // TODO remove this when functionality is available // m_ui->updatable->deleteLater(); // m_ui->downloadable->deleteLater(); QSettings settings( "MoNavClient" ); settings.beginGroup( "MapPackages" ); d->path = settings.value( "path" ).toString(); bool worldMap = settings.value( "worldmap", true ).toBool(); m_ui->installedList->setVisible( !worldMap ); m_ui->worldMap->setVisible( worldMap ); m_ui->switchSelection->setChecked( worldMap ); int entries = settings.beginReadArray( "server" ); for ( int i = 0; i < entries; i++ ) { settings.setArrayIndex( i ); PrivateImplementation::Server server; server.name = settings.value( "name" ).toString(); server.url = settings.value( "url" ).toString(); server.id = settings.value( "id" ).toInt(); } settings.endArray(); // TODO: INSERT DEFAULT SERVER connect( m_ui->changeDirectory, SIGNAL(clicked()), this, SLOT(directory()) ); connect( m_ui->load, SIGNAL(clicked()), this, SLOT(load()) ); // connect( m_ui->check, SIGNAL(clicked()), this, SLOT(check()) ); // connect( m_ui->update, SIGNAL(clicked()), this, SLOT(check()) ); // connect( m_ui->download, SIGNAL(clicked()), this, SLOT(download()) ); // ADD SERVER // BACK // CLICK connect( m_ui->installedList, SIGNAL(itemSelectionChanged()), this, SLOT(mapSelectionChanged()) ); // connect( m_ui->updateList, SIGNAL(itemSelectionChanged()), this, SLOT(updateSelectionChanged()) ); // connect( m_ui->downloadList, SIGNAL(itemSelectionChanged()), this, SLOT(downloadSelectionChanged()) ); connect( m_ui->worldMap, SIGNAL(clicked(int)), this, SLOT(selected(int)) ); d->populateInstalled( m_ui->installedList ); d->highlightButton( m_ui->changeDirectory, m_ui->installedList->count() == 0 ); m_ui->worldMap->setMaps( d->maps ); m_ui->worldMap->setHighlight( d->selected ); } MapPackagesWidget::~MapPackagesWidget() { QSettings settings( "MoNavClient" ); settings.beginGroup( "MapPackages" ); settings.setValue( "path", d->path ); settings.setValue( "worldmap", m_ui->switchSelection->isChecked() ); settings.beginWriteArray( "server", d->servers.size() ); for ( int i = 0; i < d->servers.size(); i++ ) { settings.setArrayIndex( i ); settings.setValue( "name", d->servers[i].name ); settings.setValue( "url", d->servers[i].url ); settings.setValue( "id", d->servers[i].id ); } settings.endArray(); delete d; delete m_ui; } void MapPackagesWidget::resizeEvent ( QResizeEvent* /*event*/ ) { // TODO CHANGE ORIENTATION } void MapPackagesWidget::showEvent( QShowEvent* /*event*/ ) { if ( !QFile::exists( d->path ) ) { //QMessageBox::information( this, "Data Directory", "Before proceeding be sure to select a valid data directory", "Ok" ); } } void MapPackagesWidget::selected( int id ) { m_ui->installedList->item( id )->setSelected( true ); } void MapPackagesWidget::mapSelectionChanged() { bool selected = m_ui->installedList->selectedItems().size() == 1; if ( selected ) m_ui->worldMap->setHighlight( m_ui->installedList->selectedItems().first()->data( Qt::UserRole ).toInt() ); m_ui->load->setEnabled( selected ); m_ui->deleteMap->setEnabled( selected ); } void MapPackagesWidget::updateSelectionChanged() { // bool selected = m_ui->updateList->selectedItems().size() > 0; // m_ui->update->setEnabled( selected ); } void MapPackagesWidget::downloadSelectionChanged() { // bool selected = m_ui->downloadList->selectedItems().size() > 0; // m_ui->download->setEnabled( selected ); } void MapPackagesWidget::load() { QList< QListWidgetItem* > items = m_ui->installedList->selectedItems(); if ( items.size() != 1 ) { qDebug() << "Error: only one map should be selected"; return; } int index = items.first()->data( Qt::UserRole ).toInt(); MapData* mapData = MapData::instance(); mapData->setPath( d->maps[index].path ); if ( !mapData->loadInformation() ) return; emit mapChanged(); } void MapPackagesWidget::directory() { QString newDir = QFileDialog::getExistingDirectory( this, "MoNav Data Directory", d->path ); if ( newDir.isEmpty() || newDir == d->path ) return; d->path = newDir; d->populateInstalled( m_ui->installedList ); d->highlightButton( m_ui->changeDirectory, m_ui->installedList->count() == 0 ); m_ui->worldMap->setMaps( d->maps ); m_ui->worldMap->setHighlight( d->selected ); } void MapPackagesWidget::check() { } void MapPackagesWidget::update() { } void MapPackagesWidget::download() { } void MapPackagesWidget::PrivateImplementation::populateInstalled( QListWidget* list ) { list->clear(); maps.clear(); selected = -1; MapData* mapData = MapData::instance(); if ( !mapData->searchForMapPackages( path, &maps, 2 ) ) return; for ( int i = 0; i < maps.size(); i++ ) { QListWidgetItem* item = new QListWidgetItem( maps[i].name ); item->setData( Qt::UserRole, i ); list->addItem( item ); if ( maps[i].path == mapData->path() ) { item->setSelected( true ); selected = i; } } } void MapPackagesWidget::PrivateImplementation::highlightButton( QPushButton* button, bool highlight ) { QFont font = button->font(); font.setBold( highlight ); font.setUnderline( highlight ); button->setFont( font ); } monav-0.3/client/routedescriptiondialog.cpp0000644000175000017500000000304111524532041020637 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "routedescriptiondialog.h" #include "ui_routedescriptiondialog.h" #include "routinglogic.h" #include #include RouteDescriptionWidget::RouteDescriptionWidget( QWidget *parent ) : QWidget( parent ), m_ui(new Ui::RouteDescriptionDialog) { m_ui->setupUi(this); connect( m_ui->back, SIGNAL(clicked()), this, SIGNAL(closed()) ); instructionsChanged(); } RouteDescriptionWidget::~RouteDescriptionWidget() { delete m_ui; } void RouteDescriptionWidget::instructionsChanged() { m_ui->descriptionList->clear(); QStringList labels; QStringList icons; RoutingLogic::instance()->instructions( &labels, &icons ); assert( icons.size() == labels.size() ); for ( int entry = 0; entry < icons.size(); entry++ ) { new QListWidgetItem( QIcon( icons[entry] ), labels[entry], m_ui->descriptionList ); qDebug() << "Route Description:" << labels[entry]; } } monav-0.3/client/mapmoduleswidget.cpp0000644000175000017500000001127711552540716017452 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "mapdata.h" #include "mapmoduleswidget.h" #include "ui_mapmoduleswidget.h" #include #include #include //#include //#include //#include struct MapModulesWidget::PrivateImplementation { QVector< MapData::Module > rendering; QVector< MapData::Module > routing; QVector< MapData::Module > addressLookup; }; MapModulesWidget::MapModulesWidget( QWidget* parent ) : QWidget( parent ), m_ui( new Ui::MapModulesWidget ) { m_ui->setupUi( this ); d = new PrivateImplementation; connect( m_ui->select, SIGNAL(clicked()), this, SLOT(select()) ); connect( m_ui->cancel, SIGNAL(clicked()), this, SIGNAL(cancelled()) ); populateData(); } MapModulesWidget::~MapModulesWidget() { delete d; delete m_ui; } void MapModulesWidget::populateData() { MapData* mapData = MapData::instance(); m_ui->routing->clear(); m_ui->rendering->clear(); m_ui->addressLookup->clear(); /*QDir dir( mapData->path() ); dir.setNameFilters( QStringList( "*.mmm" ) ); QStringList packedModules = dir.entryList( QDir::Files, QDir::Name ); if ( packedModules.size() > 0 ) { int button = QMessageBox::question( NULL, "Packed Map Modules", "Found packed map modules, do you want to unpack them?", "Unpack", "Ignore", "Delete" ); if ( button == 0 ) { QProgressDialog progress; progress.setWindowTitle( "MoNav - Unpacking" ); progress.setWindowModality( Qt::ApplicationModal ); progress.setMaximum( packedModules.size() ); for ( int i = 0; i < packedModules.size(); i++ ) { QString filename = dir.filePath( packedModules[i] ); QFuture< bool > future = QtConcurrent::run( MapData::unpackModule, filename ); QFutureWatcher< bool > watcher; connect( &watcher, SIGNAL(finished()), &progress, SLOT(accept()) ); watcher.setFuture( future ); progress.setLabelText( "Unpacking Module: " + packedModules[i] ); progress.setValue( i ); int result = progress.exec(); if ( result == QProgressDialog::Rejected ) { future.waitForFinished(); break; } if ( !future.result() ) { int button = QMessageBox::question( NULL, "Packed Map Modules", "Failed to unpack module: " + packedModules[i], "Ignore", "Delete" ); if ( button == 1 ) { QFile::remove( dir.filePath( packedModules[i] ) ); } } } mapData->loadInformation(); } else if ( button == 3 ) { foreach( QString filename, packedModules ) { QFile::remove( filename ); } } }*/ if ( !mapData->informationLoaded() ) return; d->routing = mapData->modules( MapData::Routing ); d->rendering = mapData->modules( MapData::Rendering ); d->addressLookup = mapData->modules( MapData::AddressLookup ); for ( int i = 0; i < d->routing.size(); i++ ) m_ui->routing->addItem( d->routing[i].name ); for ( int i = 0; i < d->rendering.size(); i++ ) m_ui->rendering->addItem( d->rendering[i].name ); for ( int i = 0; i < d->addressLookup.size(); i++ ) m_ui->addressLookup->addItem( d->addressLookup[i].name ); QString lastRouting; QString lastRendering; QString lastAddressLookup; mapData->lastModules( &lastRouting, &lastRendering, &lastAddressLookup ); int routing = m_ui->routing->findText( lastRouting ); int rendering = m_ui->rendering->findText( lastRendering ); int addressLookup = m_ui->addressLookup->findText( lastAddressLookup ); if ( routing != -1 ) m_ui->routing->setCurrentIndex( routing ); if ( rendering != -1 ) m_ui->rendering->setCurrentIndex( rendering ); if ( addressLookup != -1 ) m_ui->addressLookup->setCurrentIndex( addressLookup ); } void MapModulesWidget::select() { int routingIndex = m_ui->routing->currentIndex(); int renderingIndex = m_ui->rendering->currentIndex(); int addressLookupIndex = m_ui->addressLookup->currentIndex(); if ( routingIndex == -1 ) return; if ( renderingIndex == -1 ) return; if ( addressLookupIndex == -1 ) return; MapData* mapData = MapData::instance(); if ( mapData->load( d->routing[routingIndex], d->rendering[renderingIndex], d->addressLookup[addressLookupIndex] ) ) emit selected(); return; } monav-0.3/client/routinglogic.h0000644000175000017500000000612011550371036016234 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef ROUTINGLOGIC_H #define ROUTINGLOGIC_H #include "utils/coordinates.h" #include "interfaces/irouter.h" #include #include #include #include #include #ifndef NOQTMOBILE #include QTM_USE_NAMESPACE #endif class RoutingLogic : public QObject { Q_OBJECT public: // GPS information struct GPSInfo { UnsignedCoordinate position; double altitude; double heading; double groundSpeed; double verticalSpeed; double horizontalAccuracy; double verticalAccuracy; QDateTime timestamp; }; // return the instance of RoutingLogic static RoutingLogic* instance(); // the waypoints used to calculate the route, excluding the source QVector< UnsignedCoordinate > waypoints() const; // source UnsignedCoordinate source() const; // target == last waypoint UnsignedCoordinate target() const; // route description via its nodes' coordinate QVector< IRouter::Node > route() const; // is the source linked to the GPS reciever? bool gpsLink() const; // GPS information const GPSInfo& gpsInfo() const; // clears the waypoints/ target / route void clear(); // driving instruction for the current route void instructions( QStringList* labels, QStringList* icons, int maxSeconds = std::numeric_limits< int >::max() ); signals: void instructionsChanged(); void routeChanged(); void distanceChanged( double meter ); void travelTimeChanged( double seconds ); void waypointReached( int id ); void waypointsChanged(); void gpsInfoChanged(); void gpsLinkChanged( bool linked ); void sourceChanged(); public slots: // sets the waypoints void setWaypoints( QVector< UnsignedCoordinate > waypoints ); // sets a waypoint. If the coordinate is not valid the waypoint id is removed void setWaypoint( int id, UnsignedCoordinate coordinate ); // sets the source coordinate void setSource( UnsignedCoordinate coordinate ); // sets the target coordine == last waypoint. Inserte a waypoint if necessary. void setTarget( UnsignedCoordinate target ); // links / unlinks GPS and source coordinate void setGPSLink( bool linked ); protected: RoutingLogic(); ~RoutingLogic(); void computeRoute(); void updateInstructions(); void clearRoute(); struct PrivateImplementation; PrivateImplementation* const d; protected slots: void dataLoaded(); #ifndef NOQTMOBILE void positionUpdated( const QGeoPositionInfo& update ); #endif }; #endif // ROUTINGLOGIC_H monav-0.3/client/generalsettingsdialog.h0000644000175000017500000000242211541337240020105 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef GENERALSETTINGSDIALOG_H #define GENERALSETTINGSDIALOG_H #include #include namespace Ui { class GeneralSettingsDialog; } class GeneralSettingsDialog : public QDialog { Q_OBJECT public: explicit GeneralSettingsDialog( QWidget* parent = 0 ); ~GeneralSettingsDialog(); // not necessary to call after exec, as exec does this itself void fillSettings() const; public slots: int exec(); void setDefaultIconSize(); void selectPathLogging(); protected slots: void confirmClearTracklog(); private: Ui::GeneralSettingsDialog* m_ui; }; #endif // GENERALSETTINGSDIALOG_H monav-0.3/client/mappackageswidget.ui0000644000175000017500000000640411553076564017415 0ustar vettervetter MapPackagesWidget Form 2 4 0 Installed Data Directory Load Delete Qt::Vertical 20 40 World Map true WorldMapChooser QWidget
worldmapchooser.h
1
switchSelection toggled(bool) installedList setHidden(bool) 774 569 539 523 switchSelection toggled(bool) worldMap setVisible(bool) 750 568 693 443
monav-0.3/client/mapmoduleswidget.ui0000644000175000017500000000673611553067704017313 0ustar vettervetter MapModulesWidget 0 0 400 300 Module Selection Qt::Vertical 20 40 Qt::Horizontal 79 123 QFormLayout::AllNonFixedFieldsGrow QFormLayout::WrapLongRows Routing Rendering Address Lookup Cancel Select Modules Qt::Horizontal 78 20 Qt::Vertical 20 40 monav-0.3/client/mainwindow.ui0000644000175000017500000012035611551042742016101 0ustar vettervetter MainWindow 0 0 536 523 MoNav :/images/source.png:/images/source.png 0 0 0 0 0 0 0 Qt::Horizontal 1 1 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 true QFrame::StyledPanel QFrame::Raised 4 2 Qt::NoFocus ... :/images/oxygen/emblem-unlocked.png:/images/oxygen/emblem-unlocked.png true true Qt::NoFocus ... :/images/map.png:/images/map.png true Qt::Horizontal 1 1 0 0 Qt::Vertical 1 1 0 1 255 255 255 237 237 237 255 255 255 237 237 237 237 237 237 237 237 237 QFrame::StyledPanel QFrame::Raised Qt::ScrollBarAlwaysOff true Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop 0 0 27 48 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 0 QLayout::SetMinimumSize 2 Qt::NoFocus ... :/images/target.png:/images/target.png true Qt::NoFocus ... :/images/source.png:/images/source.png true Qt::Vertical 1 1 Qt::Horizontal 1 1 0 Qt::Vertical 1 1 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 true QFrame::StyledPanel QFrame::Raised 0 2 0 0 Qt::NoFocus + :/images/oxygen/zoom-in.png:/images/oxygen/zoom-in.png true 0 0 Qt::NoFocus - :/images/oxygen/zoom-out.png:/images/oxygen/zoom-out.png true Qt::Vertical 1 1 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 true QFrame::StyledPanel QFrame::Raised 4 2 4 Qt::NoFocus ... true 0 0 0 0 0 0 144 144 144 Label1 true 4 Qt::NoFocus ... true 0 0 0 0 0 0 144 144 144 Label2 true 0 Qt::Horizontal 1 1 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 true QFrame::StyledPanel QFrame::Raised 0 2 Qt::NoFocus ... :/images/oxygen/bookmarks.png:/images/oxygen/bookmarks.png true Qt::NoFocus ... :/images/oxygen/go-next.png:/images/oxygen/go-next.png true Qt::NoFocus ... :/images/oxygen/configure.png:/images/oxygen/configure.png true Qt::Horizontal 1 1 0 0 10 1 Qt::Vertical QSlider::TicksBothSides 0 0 536 21 PaintWidget QWidget
paintwidget.h
1
ScrollArea QScrollArea
scrollarea.h
1
lockButton toggled(bool) menuWidget setHidden(bool) 233 61 278 483 lockButton toggled(bool) waypointsWidget setHidden(bool) 215 42 68 105
monav-0.3/client/globalsettings.h0000644000175000017500000000320411545155121016547 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef GLOBALSETTINGS_H #define GLOBALSETTINGS_H class QSettings; class GlobalSettings { public: static void saveSettings( QSettings* settings ); static void loadSettings( QSettings* settings ); static int iconSize(); static void setIconSize( int size ); static void setDefaultIconsSize(); static bool autoRotation(); static void setAutoRotation( bool autoRotation ); enum MenuMode { MenuPopup, MenuOverlay }; static MenuMode menuMode(); static void setMenuMode( MenuMode mode ); static int magnification(); static void setMagnification( int factor ); static int zoomMainMap(); static void setZoomMainMap( int zoom ); static int zoomPlaceChooser(); static void setZoomPlaceChooser( int zoom ); static int zoomStreetChooser(); static void setZoomStreetChooser( int zoom ); private: struct PrivateImplementation; PrivateImplementation* d; GlobalSettings(); ~GlobalSettings(); static GlobalSettings* privateInstance(); }; #endif // GLOBALSETTINGS_H monav-0.3/client/bookmarksdialog.h0000644000175000017500000000334711454673710016716 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef BOOKMARKSDIALOG_H #define BOOKMARKSDIALOG_H #include "utils/coordinates.h" #include #include #include #ifdef Q_WS_MAEMO_5 #include #include #endif namespace Ui { class BookmarksDialog; } class BookmarksDialog : public QDialog { Q_OBJECT public: explicit BookmarksDialog(QWidget *parent = 0); ~BookmarksDialog(); UnsignedCoordinate getCoordinate(); static bool showBookmarks( UnsignedCoordinate* result, QWidget* p = NULL ); public slots: void deleteBookmark(); void chooseBookmark(); void addTargetBookmark(); void addSourceBookmark(); void currentItemChanged( QItemSelection current, QItemSelection previous ); protected: void connectSlots(); QStandardItemModel m_names; QVector< UnsignedCoordinate > m_coordinates; int m_chosen; UnsignedCoordinate m_target; UnsignedCoordinate m_source; #ifdef Q_WS_MAEMO_5 QMaemo5ValueButton* m_valueButton; QMaemo5ListPickSelector* m_selector; #endif Ui::BookmarksDialog *m_ui; }; #endif // BOOKMARKSDIALOG_H monav-0.3/client/routedescriptiondialog.h0000644000175000017500000000220311524532041020303 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef ROUTEDESCRIPTIONDIALOG_H #define ROUTEDESCRIPTIONDIALOG_H #include #include namespace Ui { class RouteDescriptionDialog; } class RouteDescriptionWidget : public QWidget { Q_OBJECT public: explicit RouteDescriptionWidget( QWidget *parent = 0 ); ~RouteDescriptionWidget(); signals: void closed(); public slots: void instructionsChanged(); protected: Ui::RouteDescriptionDialog* m_ui; }; #endif // ROUTEDESCRIPTIONDIALOG_H monav-0.3/client/mapdata.cpp0000644000175000017500000004231211525214144015472 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "mapdata.h" #include "utils/qthelpers.h" #include "utils/directoryunpacker.h" #include #include #include #include struct MapData::PrivateImplementation { enum { ConfigVersion = 2 }; QString path; bool loaded; bool informationLoaded; QString addressLookupName; QString gpsLookupName; QString rendererName; QString routerName; QString lastRoutingModule; QString lastRenderingModule; QString lastAddressLookupModule; // stores pointers to all dynamically loaded plugins QList< QPluginLoader* > plugins; // stores a pointer to the current renderer plugin IRenderer* renderer; // stores a pointer to the current address lookup plugin IAddressLookup* addressLookup; // stores a pointer to the current GPS lookup plugin IGPSLookup* gpsLookup; // stores a pointer to the current router plugin IRouter* router; MapPackage information; QVector< MapData::Module > routingModules; QVector< MapData::Module > renderingModules; QVector< MapData::Module > addressLookupModules; bool testPlugin( QObject* plugin ); void findRoutingModules(); void findRenderingModules(); void findAddressLookupModules(); static int findModule( QString name, QVector< MapData::Module > modules ); static bool loadInformation( QString directory, MapPackage* data ); }; bool MapData::PrivateImplementation::testPlugin( QObject* plugin ) { bool needed = false; if ( IRenderer *interface = qobject_cast< IRenderer* >( plugin ) ) { if ( interface->GetName() == rendererName ) { renderer = interface; needed = true; } } if ( IAddressLookup *interface = qobject_cast< IAddressLookup* >( plugin ) ) { if ( interface->GetName() == addressLookupName ) { addressLookup = interface; needed = true; } } if ( IGPSLookup *interface = qobject_cast< IGPSLookup* >( plugin ) ) { if ( interface->GetName() == gpsLookupName ) { gpsLookup = interface; needed = true; } } if ( IRouter *interface = qobject_cast< IRouter* >( plugin ) ) { if ( interface->GetName() == routerName ) { router = interface; needed = true; } } return needed; } MapData::MapData() : QObject( NULL ), d( new PrivateImplementation ) { d->loaded = false; d->informationLoaded = false; d->addressLookup = NULL; d->gpsLookup = NULL; d->renderer = NULL; d->router = NULL; QSettings settings( "MoNavClient" ); settings.beginGroup( "MapData" ); d->path = settings.value( "path" ).toString(); d->lastRoutingModule = settings.value( "routingModule" ).toString(); d->lastRenderingModule = settings.value( "renderingModule" ).toString(); d->lastAddressLookupModule = settings.value( "addressLookupModule" ).toString(); } MapData::~MapData() { delete d; } void MapData::cleanup() { //delete static plugins // neccessary as Qt does not delete static instances itself // CHECK WHENEVER QT VERSION CHANGES!!! foreach ( QObject *plugin, QPluginLoader::staticInstances() ) delete plugin; QSettings settings( "MoNavClient" ); settings.beginGroup( "MapData" ); settings.setValue( "path", d->path ); settings.setValue( "routingModule", d->lastRoutingModule ); settings.setValue( "renderingModule", d->lastRenderingModule ); settings.setValue( "addressLookupModule", d->lastAddressLookupModule ); } MapData* MapData::instance() { static MapData mapData; return &mapData; } QString MapData::path() const { return d->path; } void MapData::setPath( QString path ) { unload(); d->path = path; } void MapData::lastModules( QString* routing, QString* rendering, QString* addressLookup ) { *routing = d->lastRoutingModule; *rendering = d->lastRenderingModule; *addressLookup = d->lastAddressLookupModule; } bool MapData::PrivateImplementation::loadInformation( QString directory, MapData::MapPackage* data ) { QString configFilename = fileInDirectory( directory, "MoNav.ini" ); if ( !QFile::exists( configFilename ) ) return false; QSettings config( configFilename, QSettings::IniFormat ); int configVersion = config.value( "configVersion" ).toInt(); if ( configVersion != ConfigVersion ) { qDebug() << "config version not compatible:" << configVersion << "vs" << ConfigVersion; return false; } if ( data == NULL ) return true; bool ok = true; bool fail = false; data->name = config.value( "name" ).toString(); data->path = directory; data->min.x = config.value( "minX" ).toUInt( &ok ); fail = fail || !ok; data->max.x = config.value( "maxX" ).toUInt( &ok ); fail = fail || !ok; data->min.y = config.value( "minY" ).toUInt( &ok ); fail = fail || !ok; data->max.y = config.value( "maxY" ).toUInt( &ok); fail = fail || !ok; if ( fail ) { qDebug() << "invalid settings encountered"; return false; } return true; } bool MapData::containsMapData( QString directory, MapPackage *data ) { return PrivateImplementation::loadInformation( directory, data ); } bool MapData::containsMapData( MapPackage* data ) const { return d->loadInformation( d->path, data ); } bool MapData::searchForMapPackages( QString directory, QVector* data, int depth ) { if ( data == NULL ) return false; QDir dir( directory ); if ( !dir.exists() ) { qDebug() << "directory does not exist:" << directory; return false; } QStringList dirList; dirList.push_back( directory ); int currentDepth = 0; int nextDepthPosition = 1; MapPackage information; for ( int position = 0; position < dirList.size(); position++ ) { if ( position == nextDepthPosition ) { nextDepthPosition = dirList.size(); currentDepth++; } QString name = dirList[position]; if ( containsMapData( name, &information ) ) { data->push_back( information ); continue; // explicitly exclude nested map packages } if ( currentDepth >= depth ) continue; QDir subDir( name ); QStringList subDirs = subDir.entryList( QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name ); for ( int i = 0; i < subDirs.size(); i++ ) dirList.append( subDir.filePath( subDirs[i] ) ); } return true; } bool MapData::unpackModule( QString filename ) { DirectoryUnpacker unpacker( filename ); if ( !unpacker.decompress() ) return false; return true; } bool MapData::loaded() const { return d->loaded; } int MapData::PrivateImplementation::findModule( QString name, QVector< MapData::Module > modules ) { for ( int i = 0; i < modules.size(); i++ ) { if ( modules[i].name == name ) return i; } return -1; } bool MapData::loadLast() { if ( !informationLoaded() ) { qCritical() << "Information not loaded"; return false; } int routingIndex = d->findModule( d->lastRoutingModule, d->routingModules ); if ( routingIndex == -1 ) { qDebug() << "routing module not found:" << d->lastRoutingModule; return false; } int renderingIndex = d->findModule( d->lastRenderingModule, d->renderingModules ); if ( renderingIndex == -1 ) { qDebug() << "rendering module not found:" << d->lastRenderingModule; return false; } int addressLookupIndex = d->findModule( d->lastAddressLookupModule, d->addressLookupModules ); if ( addressLookupIndex == -1 ) { qDebug() << "address lookup module not found:" << d->lastAddressLookupModule; return false; } if ( !load( d->routingModules[routingIndex], d->renderingModules[renderingIndex], d->addressLookupModules[addressLookupIndex] ) ) { qDebug() << "loading last modules failed"; return false; } return true; } bool MapData::load( const Module& routingModule, const Module& renderingModule, const Module& addressLookupModule ) { if ( !informationLoaded() ) { qCritical() << "Information not loaded"; return false; } if ( d->loaded ) unload(); if ( routingModule.plugins.size() != 2 ) { qCritical() << "Illegal routing module passed"; return false; } d->routerName = routingModule.plugins[0]; d->gpsLookupName = routingModule.plugins[1]; if ( renderingModule.plugins.size() != 1 ) { qCritical() << "Illegal rendering module passed"; return false; } d->rendererName = renderingModule.plugins[0]; if ( addressLookupModule.plugins.size() != 1 ) { qCritical() << "Illegal address lookup module passed"; return false; } d->addressLookupName = addressLookupModule.plugins[0]; QDir pluginDir( QApplication::applicationDirPath() ); if ( pluginDir.cd( "plugins_client" ) ) { foreach ( QString fileName, pluginDir.entryList( QDir::Files ) ) { QPluginLoader* loader = new QPluginLoader( pluginDir.absoluteFilePath( fileName ) ); if ( !loader->load() ) qDebug( "%s", loader->errorString().toAscii().constData() ); if ( d->testPlugin( loader->instance() ) ) d->plugins.append( loader ); else { loader->unload(); delete loader; } } } foreach ( QObject *plugin, QPluginLoader::staticInstances() ) d->testPlugin( plugin ); // check for success and unload plugins otherwise // check if all plugins were found bool success = true; if ( d->router == NULL ) { qCritical() << "Router plugin missing:" << d->routerName; success = false; } if ( d->gpsLookup == NULL ) { qCritical() << "GPS Lookup plugin missing:" << d->gpsLookupName; success = false; } if ( d->renderer == NULL ) { qCritical() << "Renderer plugin missing:" << d->rendererName; success = false; } if ( d->addressLookup == NULL ) { qCritical() << "Address lookup plugin missing:" << d->addressLookupName; } // check if file formats are compatible if ( success ) { if ( !d->router->IsCompatible( routingModule.fileFormats[0] ) ) { qCritical() << "Router file format not compatible"; success = false; } if ( !d->gpsLookup->IsCompatible( routingModule.fileFormats[1] ) ) { qCritical() << "GPS Lookup file format not compatible"; success = false; } if ( !d->renderer->IsCompatible( renderingModule.fileFormats[0] ) ) { qCritical() << "Renderer file format not compatible"; success = false; } if ( !d->addressLookup->IsCompatible( addressLookupModule.fileFormats[0] ) ) { qCritical() << "Address Lookup file format not compatible"; success = false; } } // check if data can be loaded if ( success ) { d->router->SetInputDirectory( routingModule.path ); d->gpsLookup->SetInputDirectory( routingModule.path ); d->renderer->SetInputDirectory( renderingModule.path ); d->addressLookup->SetInputDirectory( addressLookupModule.path ); if ( !d->router->LoadData() ) { qCritical() << "Failed to load router data"; success = false; } if ( !d->gpsLookup->LoadData() ) { qCritical() << "Failed to load gps lookup data"; success = false; } if ( !d->renderer->LoadData() ) { qCritical() << "Failed to load renderer data"; success = false; } if ( !d->addressLookup->LoadData() ) { qCritical() << "Failed to load address lookup data"; success = false; } if ( !success ) { d->router->UnloadData(); d->gpsLookup->UnloadData(); d->renderer->UnloadData(); d->addressLookup->UnloadData(); } } if ( !success ) { d->addressLookup = NULL; d->gpsLookup = NULL; d->renderer = NULL; d->router = NULL; foreach( QPluginLoader* pluginLoader, d->plugins ) { pluginLoader->unload(); delete pluginLoader; } d->plugins.clear(); return false; } d->lastRoutingModule = routingModule.name; d->lastRenderingModule = renderingModule.name; d->lastAddressLookupModule = addressLookupModule.name; d->loaded = true; emit dataLoaded(); return true; } bool MapData::unload() { if ( !d->loaded ) return true; if ( d->loaded ) { if ( d->addressLookup != NULL ) d->addressLookup->UnloadData(); if ( d->gpsLookup != NULL ) d->gpsLookup->UnloadData(); if ( d->renderer != NULL ) d->renderer->UnloadData(); if ( d->router != NULL ) d->router->UnloadData(); } d->addressLookup = NULL; d->gpsLookup = NULL; d->renderer = NULL; d->router = NULL; foreach( QPluginLoader* pluginLoader, d->plugins ) { pluginLoader->unload(); delete pluginLoader; } d->plugins.clear(); d->loaded = false; emit dataUnloaded(); return true; } bool MapData::informationLoaded() const { return d->informationLoaded; } void MapData::PrivateImplementation::findRoutingModules() { routingModules.clear(); // get potentially interesting subdirs QDir dir( path ); dir.setNameFilters( QStringList( "routing_*" ) ); QStringList subDirs = dir.entryList( QDir::Dirs, QDir::Name ); // check each dir whether it contains suitable data for ( int i = 0; i < subDirs.size(); i++ ) { QString configFilename = fileInDirectory( dir.filePath( subDirs[i] ), "Module.ini" ); if ( !QFile::exists( configFilename ) ) continue; QSettings config( configFilename, QSettings::IniFormat ); int configVersion = config.value( "configVersion" ).toInt(); if ( configVersion != ConfigVersion ) { qCritical() << "config version found in" << configFilename << "not compatible:" << configVersion << "vs" << ConfigVersion; continue; } MapData::Module module; module.name = config.value( "name", "No Name" ).toString(); module.path = dir.filePath( subDirs[i] ); module.plugins.push_back( config.value( "router" ).toString() ); module.plugins.push_back( config.value( "gpsLookup" ).toString() ); module.fileFormats.push_back( config.value( "routerFileFormatVersion", -1 ).toInt() ); module.fileFormats.push_back( config.value( "gpsLookupFileFormatVersion", -1 ).toInt() ); routingModules.push_back( module ); } } void MapData::PrivateImplementation::findRenderingModules() { renderingModules.clear(); // get potentially interesting subdirs QDir dir( path ); dir.setNameFilters( QStringList( "rendering_*" ) ); QStringList subDirs = dir.entryList( QDir::Dirs, QDir::Name ); // check each dir whether it contains suitable data for ( int i = 0; i < subDirs.size(); i++ ) { QString configFilename = fileInDirectory( dir.filePath( subDirs[i] ), "Module.ini" ); if ( !QFile::exists( configFilename ) ) continue; QSettings config( configFilename, QSettings::IniFormat ); int configVersion = config.value( "configVersion" ).toInt(); if ( configVersion != ConfigVersion ) { qCritical() << "config version found in" << configFilename << "not compatible:" << configVersion << "vs" << ConfigVersion; continue; } MapData::Module module; module.name = config.value( "name", "No Name" ).toString(); module.path = dir.filePath( subDirs[i] ); module.plugins.push_back( config.value( "renderer" ).toString() ); module.fileFormats.push_back( config.value( "rendererFileFormatVersion", -1 ).toInt() ); renderingModules.push_back( module ); } } void MapData::PrivateImplementation::findAddressLookupModules() { addressLookupModules.clear(); // get potentially interesting subdirs QDir dir( path ); dir.setNameFilters( QStringList( "address_*" ) ); QStringList subDirs = dir.entryList( QDir::Dirs, QDir::Name ); // check each dir whether it contains suitable data for ( int i = 0; i < subDirs.size(); i++ ) { QString configFilename = fileInDirectory( dir.filePath( subDirs[i] ), "Module.ini" ); if ( !QFile::exists( configFilename ) ) continue; QSettings config( configFilename, QSettings::IniFormat ); int configVersion = config.value( "configVersion" ).toInt(); if ( configVersion != ConfigVersion ) { qCritical() << "config version found in" << configFilename << "not compatible:" << configVersion << "vs" << ConfigVersion; continue; } MapData::Module module; module.name = config.value( "name", "No Name" ).toString(); module.path = dir.filePath( subDirs[i] ); module.plugins.push_back( config.value( "addressLookup" ).toString() ); module.fileFormats.push_back( config.value( "addressLookupFileFormatVersion", -1 ).toInt() ); addressLookupModules.push_back( module ); } } bool MapData::loadInformation() { d->informationLoaded = false; if ( d->loaded ) { if ( !unload() ) { qCritical() << "failed to unload current map package"; return false; } } if ( !d->loadInformation( d->path, &d->information ) ) { qDebug() << "failed to load map information"; return false; } // search for modules d->findRoutingModules(); d->findRenderingModules(); d->findAddressLookupModules(); d->informationLoaded = true; emit informationChanged(); return true; } QVector< MapData::Module > MapData::modules( ModuleType plugin ) const { if ( !d->informationLoaded ) return QVector< MapData::Module >(); switch ( plugin ) { case Routing: return d->routingModules; case Rendering: return d->renderingModules; case AddressLookup: return d->addressLookupModules; } // should never reach this code return QVector< MapData::Module >(); } const MapData::MapPackage& MapData::information() const { return d->information; } IAddressLookup* MapData::addressLookup() { return d->addressLookup; } IGPSLookup* MapData::gpsLookup() { return d->gpsLookup; } IRenderer* MapData::renderer() { return d->renderer; } IRouter* MapData::router() { return d->router; } monav-0.3/client/globalsettings.cpp0000644000175000017500000001203511545155121017104 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "globalsettings.h" #include #include #include #include struct GlobalSettings::PrivateImplementation { int iconSize; int defaultIconSize; bool useDefaultIconSize; int magnification; MenuMode menuMode; int zoomMainMap; int zoomStreetChooser; int zoomPlaceChooser; bool autoRotation; }; GlobalSettings::GlobalSettings() { d = new PrivateImplementation; d->defaultIconSize = QApplication::style()->pixelMetric( QStyle::PM_ToolBarIconSize ); } GlobalSettings::~GlobalSettings() { delete d; } GlobalSettings* GlobalSettings::privateInstance() { static GlobalSettings globalSettings; return &globalSettings; } void GlobalSettings::loadSettings( QSettings *settings ) { GlobalSettings* instance = privateInstance(); settings->beginGroup( "Global Settings" ); instance->d->iconSize = settings->value( "iconSize", instance->d->defaultIconSize ).toInt(); instance->d->useDefaultIconSize = settings->value( "useDefaultIconSize", true ).toBool(); instance->d->magnification = settings->value( "magnification", 1 ).toInt(); instance->d->menuMode = MenuMode( settings->value( "menuMode", ( int ) MenuOverlay ).toInt() ); instance->d->zoomMainMap = settings->value( "zoomMainMap", 9 ).toInt(); instance->d->zoomStreetChooser = settings->value( "zoomStreetChooser", 14 ).toInt(); instance->d->zoomPlaceChooser = settings->value( "zoomPlaceChooser", 11 ).toInt(); instance->d->autoRotation = settings->value( "autoRotation", true ).toBool(); settings->endGroup(); } void GlobalSettings::saveSettings( QSettings *settings ) { GlobalSettings* instance = privateInstance(); settings->beginGroup( "Global Settings" ); settings->setValue( "iconSize", instance->d->iconSize ); settings->setValue( "useDefaultIconSize", instance->d->useDefaultIconSize ); settings->setValue( "magnification", instance->d->magnification ); settings->setValue( "menuMode", ( int ) instance->d->menuMode ); settings->setValue( "zoomMainMap", instance->d->zoomMainMap ); settings->setValue( "zoomStreetChooser", instance->d->zoomStreetChooser ); settings->setValue( "zoomPlaceChooser", instance->d->zoomPlaceChooser ); settings->setValue( "autoRotation", instance->d->autoRotation ); settings->endGroup(); } int GlobalSettings::iconSize() { GlobalSettings* instance = privateInstance(); if ( instance->d->useDefaultIconSize ) return instance->d->defaultIconSize; else return instance->d->iconSize; } void GlobalSettings::setIconSize( int size ) { GlobalSettings* instance = privateInstance(); instance->d->iconSize = size; instance->d->useDefaultIconSize = size == instance->d->defaultIconSize; } bool GlobalSettings::autoRotation() { GlobalSettings* instance = privateInstance(); return instance->d->autoRotation; } void GlobalSettings::setAutoRotation( bool autoRotation ) { GlobalSettings* instance = privateInstance(); instance->d->autoRotation = autoRotation; } void GlobalSettings::setDefaultIconsSize() { GlobalSettings* instance = privateInstance(); instance->d->iconSize = instance->d->defaultIconSize; instance->d->useDefaultIconSize = true; } int GlobalSettings::magnification() { GlobalSettings* instance = privateInstance(); return instance->d->magnification; } void GlobalSettings::setMagnification( int factor ) { GlobalSettings* instance = privateInstance(); instance->d->magnification = factor; } int GlobalSettings::zoomMainMap() { GlobalSettings* instance = privateInstance(); return instance->d->zoomMainMap; } void GlobalSettings::setZoomMainMap( int zoom ) { GlobalSettings* instance = privateInstance(); instance->d->zoomMainMap = zoom; } int GlobalSettings::zoomPlaceChooser() { GlobalSettings* instance = privateInstance(); return instance->d->zoomPlaceChooser; } void GlobalSettings::setZoomPlaceChooser( int zoom ) { GlobalSettings* instance = privateInstance(); instance->d->zoomPlaceChooser = zoom; } int GlobalSettings::zoomStreetChooser() { GlobalSettings* instance = privateInstance(); return instance->d->zoomStreetChooser; } void GlobalSettings::setZoomStreetChooser( int zoom ) { GlobalSettings* instance = privateInstance(); instance->d->zoomStreetChooser = zoom; } GlobalSettings::MenuMode GlobalSettings::menuMode() { GlobalSettings* instance = privateInstance(); return instance->d->menuMode; } void GlobalSettings::setMenuMode( MenuMode mode ) { GlobalSettings* instance = privateInstance(); instance->d->menuMode = mode; } monav-0.3/client/gpsdialog.h0000644000175000017500000000174111455433366015515 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef GPSDIALOG_H #define GPSDIALOG_H #include namespace Ui { class GPSDialog; } class GPSDialog : public QDialog { Q_OBJECT public: explicit GPSDialog( QWidget* parent = 0 ); ~GPSDialog(); public slots: void gpsInfoUpdated(); private: Ui::GPSDialog* m_ui; }; #endif // GPSDIALOG_H monav-0.3/client/paintwidget.h0000644000175000017500000000443311537454273016065 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef PAINTWIDGET_H #define PAINTWIDGET_H #include #include "interfaces/irenderer.h" #include "interfaces/irouter.h" #include "logger.h" namespace Ui { class PaintWidget; } class PaintWidget : public QWidget { Q_OBJECT public: PaintWidget(QWidget *parent = 0); ~PaintWidget(); public slots: void setFixed( bool f ); void setKeepPositionVisible( bool visibility ); void setZoom( int z ); void setMaxZoom( int z ); void setCenter( const ProjectedCoordinate c ); void setPOIs( QVector< UnsignedCoordinate > p ); void setPOI( UnsignedCoordinate p ); void setStreetPolygons( QVector< int > polygonEndpointsStreet, QVector< UnsignedCoordinate > polygonCoordsStreet ); void setTracklogPolygons( QVector< int > polygonEndpointsTracklog, QVector< UnsignedCoordinate > polygonCoordsTracklog ); void setVirtualZoom( int z ); void routeChanged(); void trackChanged(); void waypointsChanged(); void sourceChanged(); void dataLoaded(); signals: void zoomChanged( int z ); void mouseClicked( ProjectedCoordinate clickPos ); void contextMenu( QPoint globalPos ); protected: void paintEvent( QPaintEvent* ); void mouseMoveEvent( QMouseEvent * event ); void mousePressEvent( QMouseEvent * event ); void mouseReleaseEvent( QMouseEvent* event ); void wheelEvent( QWheelEvent * event ); void contextMenuEvent( QContextMenuEvent *event) ; IRenderer::PaintRequest m_request; int m_maxZoom; int m_lastMouseX; int m_lastMouseY; int m_startMouseX; int m_startMouseY; bool m_drag; bool m_mouseDown; int m_wheelDelta; bool m_fixed; bool m_keepPositionVisible; Ui::PaintWidget* m_ui; }; #endif // PAINTWIDGET_H monav-0.3/client/worldmapchooser.h0000644000175000017500000000255111525007300016733 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef WORLDMAPCHOOSER_H #define WORLDMAPCHOOSER_H #include #include "mapdata.h" namespace Ui { class WorldMapChooser; } class WorldMapChooser : public QWidget { Q_OBJECT public: explicit WorldMapChooser( QWidget* parent = 0 ); ~WorldMapChooser(); void setMaps( QVector< MapData::MapPackage > maps ); public slots: void setHighlight( int id ); signals: void clicked( int id ); protected: void resizeEvent( QResizeEvent* event ); void showEvent( QShowEvent* ); void hideEvent( QHideEvent* ); void mouseReleaseEvent( QMouseEvent* event ); private: struct PrivateImplementation; PrivateImplementation*d ; Ui::WorldMapChooser* m_ui; }; #endif // WORLDMAPCHOOSER_H monav-0.3/client/bookmarksdialog.ui0000644000175000017500000000265211454652313017076 0ustar vettervetter BookmarksDialog 0 0 253 392 Bookmarks true false Select Add Departure Add Destination false Delete monav-0.3/client/client.pro0000644000175000017500000000435011550373565015372 0ustar vettervetter# ------------------------------------------------- # Project created by QtCreator 2010-06-15T15:30:10 # ------------------------------------------------- TARGET = MoNavClient TEMPLATE = app INCLUDEPATH += .. SOURCES += main.cpp \ paintwidget.cpp \ addressdialog.cpp \ bookmarksdialog.cpp \ routedescriptiondialog.cpp \ mapdata.cpp \ routinglogic.cpp \ overlaywidget.cpp \ scrollarea.cpp \ gpsdialog.cpp \ generalsettingsdialog.cpp \ logger.cpp \ ../utils/directoryunpacker.cpp \ ../utils/lzma/LzmaDec.c \ mappackageswidget.cpp \ mainwindow.cpp \ mapmoduleswidget.cpp \ placechooser.cpp \ globalsettings.cpp \ streetchooser.cpp \ worldmapchooser.cpp HEADERS += \ paintwidget.h \ ../utils/coordinates.h \ ../utils/config.h \ ../interfaces/irenderer.h \ ../interfaces/iaddresslookup.h \ addressdialog.h \ ../interfaces/igpslookup.h \ ../interfaces/irouter.h \ bookmarksdialog.h \ routedescriptiondialog.h \ descriptiongenerator.h \ mapdata.h \ routinglogic.h \ fullscreenexitbutton.h \ overlaywidget.h \ scrollarea.h \ gpsdialog.h \ generalsettingsdialog.h \ logger.h \ ../utils/directoryunpacker.h \ ../utils/lzma/LzmaDec.h \ mappackageswidget.h \ mainwindow.h \ mapmoduleswidget.h \ placechooser.h \ globalsettings.h \ streetchooser.h \ worldmapchooser.h FORMS += \ paintwidget.ui \ addressdialog.ui \ bookmarksdialog.ui \ routedescriptiondialog.ui \ gpsdialog.ui \ generalsettingsdialog.ui \ mappackageswidget.ui \ mainwindow.ui \ mapmoduleswidget.ui \ placechooser.ui \ streetchooser.ui \ worldmapchooser.ui DESTDIR = ../bin TARGET = monav unix { QMAKE_CXXFLAGS_RELEASE -= -O2 QMAKE_CXXFLAGS_RELEASE += -O3 \ -Wno-unused-function QMAKE_CXXFLAGS_DEBUG += -Wno-unused-function } maemo5 { QT += maemo5 } RESOURCES += images.qrc LIBS += -L../bin/plugins_client -lmapnikrendererclient -lcontractionhierarchiesclient -lgpsgridclient -losmrendererclient -lunicodetournamenttrieclient -lqtilerendererclient #required by osmrendererclient QT += network CONFIG += mobility MOBILITY += location unix:!symbian { maemo5 { target.path = /opt/usr/bin } else { target.path = /usr/local/bin } INSTALLS += target } monav-0.3/client/fullscreenexitbutton.h0000644000175000017500000000665311552765706020047 0ustar vettervetter/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef FULLSCREENEXITBUTTON_H #define FULLSCREENEXITBUTTON_H #include #include class FullScreenExitButton : public QToolButton { Q_OBJECT public: inline explicit FullScreenExitButton(QWidget *parent); protected: inline bool eventFilter(QObject *obj, QEvent *ev); }; FullScreenExitButton::FullScreenExitButton(QWidget *parent) : QToolButton(parent) { Q_ASSERT(parent); // set the fullsize icon from Maemo's theme setIcon(QIcon::fromTheme(QLatin1String("general_fullsize"))); // ensure that our size is fixed to our ideal size setFixedSize(sizeHint()); // set the background to 0.5 alpha QPalette pal = palette(); QColor backgroundColor = pal.color(backgroundRole()); backgroundColor.setAlpha(128); pal.setColor(backgroundRole(), backgroundColor); setPalette(pal); // ensure that we're painting our background setAutoFillBackground(true); // when we're clicked, tell the parent to exit fullscreen connect(this, SIGNAL(clicked()), parent, SLOT(showNormal())); // install an event filter to listen for the parent's events parent->installEventFilter(this); } bool FullScreenExitButton::eventFilter(QObject *obj, QEvent *ev) { if (obj != parent()) return QToolButton::eventFilter(obj, ev); QWidget *parent = parentWidget(); bool isFullScreen = parent->windowState() & Qt::WindowFullScreen; switch (ev->type()) { case QEvent::WindowStateChange: disconnect( parent ); if ( isFullScreen ) connect(this, SIGNAL(clicked()), parent, SLOT(showNormal())); else connect(this, SIGNAL(clicked()), parent, SLOT(showFullScreen())); //setVisible(isFullScreen); if (isFullScreen) raise(); // fall through case QEvent::Resize: if (isVisible()) move( parent->width() - width(), parent->height() - height() ); break; default: break; } return QToolButton::eventFilter(obj, ev); } #endif monav-0.3/client/images.qrc0000644000175000017500000000451311525007300015326 0ustar vettervetter images/placeholder.png images/directions/forward.png images/directions/left.png images/directions/right.png images/map.png images/route.png images/source.png images/target.png images/address.png images/bookmark.png images/oxygen/configure.png images/oxygen/network-wireless.png images/oxygen/preferences-system.png images/oxygen/folder-tar.png images/oxygen/hwinfo.png images/directions/roundabout.png images/directions/roundabout_exit1.png images/directions/roundabout_exit2.png images/directions/roundabout_exit3.png images/directions/roundabout_exit4.png images/directions/sharply_left.png images/directions/sharply_left.svg images/directions/sharply_right.png images/directions/sharply_right.svg images/directions/slightly_left.png images/directions/slightly_left.svg images/directions/slightly_right.png images/directions/slightly_right.svg images/oxygen/emblem-locked.png images/oxygen/emblem-unlocked.png images/oxygen/start-here.png images/oxygen/go-next.png images/oxygen/go-previous.png images/oxygen/zoom-in.png images/oxygen/zoom-out.png images/oxygen/bookmarks.png images/oxygen/list-add.png images/oxygen/list-remove.png images/waypoint1.png images/waypoint2.png images/waypoint3.png images/waypoint4.png images/world/world256x128_48.jpg images/world/world512x256_96.jpg images/world/world1024x512_192.jpg images/world/world2048x1024_384.jpg monav-0.3/client/generalsettingsdialog.cpp0000644000175000017500000000754411551034370020451 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include #include "generalsettingsdialog.h" #include "ui_generalsettingsdialog.h" #include "globalsettings.h" #include "logger.h" GeneralSettingsDialog::GeneralSettingsDialog( QWidget* parent ) : QDialog( parent ), m_ui( new Ui::GeneralSettingsDialog ) { m_ui->setupUi( this ); // Windows Mobile Window Flags setWindowFlags( windowFlags() & ( ~Qt::WindowOkButtonHint ) ); setWindowFlags( windowFlags() | Qt::WindowCancelButtonHint ); m_ui->iconSize->setValue( GlobalSettings::iconSize() ); if ( GlobalSettings::menuMode() == GlobalSettings::MenuPopup ) m_ui->popup->setChecked( true ); else m_ui->overlay->setChecked( true ); m_ui->magnification->setValue( GlobalSettings::magnification() ); connect( m_ui->defaultIconSize, SIGNAL(clicked()), this, SLOT(setDefaultIconSize()) ); m_ui->checkBoxMapRotation->setChecked( GlobalSettings::autoRotation() ); m_ui->checkBoxLogging->setChecked(Logger::instance()->loggingEnabled()); m_ui->lineEditPathLogging->setText(Logger::instance()->directory()); connect( m_ui->pushButtonPathLogging, SIGNAL(clicked()), this, SLOT(selectPathLogging()) ); connect( m_ui->pushButtonClearTracklog, SIGNAL(clicked()), this, SLOT(confirmClearTracklog()) ); QSettings settings( "MoNavClient" ); settings.beginGroup( "GeneralSettingsDialog" ); restoreGeometry( settings.value( "geometry" ).toByteArray() ); m_ui->settingsList->setCurrentIndex( settings.value( "currentPage", 0 ).toInt() ); } GeneralSettingsDialog::~GeneralSettingsDialog() { QSettings settings( "MoNavClient" ); settings.beginGroup( "GeneralSettingsDialog" ); settings.setValue( "geometry", saveGeometry() ); settings.setValue( "currentPage", m_ui->settingsList->currentIndex() ); delete m_ui; } int GeneralSettingsDialog::exec() { int value = QDialog::exec(); fillSettings(); return value; } void GeneralSettingsDialog::fillSettings() const { GlobalSettings::setIconSize( m_ui->iconSize->value() ); GlobalSettings::setMagnification( m_ui->magnification->value() ); if ( m_ui->overlay->isChecked() ) GlobalSettings::setMenuMode( GlobalSettings::MenuOverlay ); else GlobalSettings::setMenuMode( GlobalSettings::MenuPopup ); GlobalSettings::setAutoRotation( m_ui->checkBoxMapRotation->isChecked() ); Logger::instance()->setLoggingEnabled(m_ui->checkBoxLogging->isChecked()); Logger::instance()->setDirectory(m_ui->lineEditPathLogging->text()); } void GeneralSettingsDialog::setDefaultIconSize() { GlobalSettings::setDefaultIconsSize(); m_ui->iconSize->setValue( GlobalSettings::iconSize() ); } void GeneralSettingsDialog::selectPathLogging() { QString path = m_ui->lineEditPathLogging->text(); path = QFileDialog::getExistingDirectory (this, tr("Select Logging Directory"), path, QFileDialog::ShowDirsOnly); m_ui->lineEditPathLogging->setText(path); } void GeneralSettingsDialog::confirmClearTracklog() { QMessageBox messageBox; messageBox.setWindowTitle( tr( "Clear Tracklog" ) ); messageBox.setText("This will discard the current tracklog."); messageBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); messageBox.setDefaultButton(QMessageBox::Cancel); int returnValue = messageBox.exec(); if ( returnValue == QMessageBox::Ok ) Logger::instance()->clearTracklog(); } monav-0.3/client/scrollarea.h0000644000175000017500000000254511455420653015671 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef SCROLLAREA_H #define SCROLLAREA_H #include // resizes the ScrollArea to always fit the contents in one direction and scroll in the other direction // default orientation is Vertical, i.e., no horizontal scrollbar should appear class ScrollArea : public QScrollArea { Q_OBJECT public: explicit ScrollArea( QWidget* parent = 0 ); Qt::Orientation orientation(); signals: public slots: void setOrientation( Qt::Orientation orientation ); protected: virtual void resizeEvent( QResizeEvent* event ); virtual void mousePressEvent( QMouseEvent* event ); virtual void mouseMoveEvent( QMouseEvent* event ); Qt::Orientation m_orientation; }; #endif // SCROLLAREA_H monav-0.3/client/placechooser.h0000644000175000017500000000242411537476247016220 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef PLACECHOOSER_H #define PLACECHOOSER_H #include "utils/coordinates.h" #include #include namespace Ui { class PlaceChooser; } class PlaceChooser : public QDialog { Q_OBJECT public: explicit PlaceChooser( QWidget* parent = 0 ); ~PlaceChooser(); static int selectPlaces( QVector< UnsignedCoordinate > places, QWidget* p = NULL ); protected slots: void addZoom(); void subtractZoom(); void setZoom( int zoom ); void previousPlace(); void nextPlace(); private: struct PrivateImplementation; PrivateImplementation* d; Ui::PlaceChooser* m_ui; }; #endif // PLACECHOOSER_H monav-0.3/client/overlaywidget.h0000644000175000017500000000274011455420653016424 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef OVERLAYWIDGET_H #define OVERLAYWIDGET_H #include "scrollarea.h" #include #include #include class OverlayWidget : public QWidget { Q_OBJECT public: explicit OverlayWidget( QWidget *parent = 0, QString title = "" ); void addAction( QAction *action ); void addActions( QList< QAction* > actions ); QList< QAction* > actions() const; signals: public slots: protected: virtual void mousePressEvent( QMouseEvent* event ); virtual void mouseReleaseEvent( QMouseEvent* event ); bool eventFilter( QObject *obj, QEvent* ev ); virtual void hideEvent( QHideEvent* event ); virtual void showEvent( QShowEvent* event ); void setOrientation(); QToolBar* m_centralWidget; ScrollArea* m_scrollArea; QGridLayout* m_grid; bool m_mouseDown; }; #endif // OVERLAYWIDGET_H monav-0.3/client/mapdata.h0000644000175000017500000000722511525201243015137 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef MAPDATA_H #define MAPDATA_H #include "interfaces/iaddresslookup.h" #include "interfaces/igpslookup.h" #include "interfaces/irenderer.h" #include "interfaces/irouter.h" #include "utils/coordinates.h" #include #include #include // Manages map data and plugins // all settings are stored in MoNav/MapData class MapData : public QObject { Q_OBJECT public: enum ModuleType { AddressLookup = 0, Rendering = 2, Routing = 3 }; struct Module { // name of the module QString name; // path of the module // mostly used for internal porpuses QString path; // name of plugins required QStringList plugins; // file formats QVector< int > fileFormats; }; struct MapPackage { // name of the map packge QString name; // path of the map package QString path; // bounding box of the map package UnsignedCoordinate min; UnsignedCoordinate max; }; ~MapData(); // returns the instance of MapData static MapData* instance(); // the path of the current map package QString path() const; void setPath( QString path ); // does the directory contain MapData? static bool containsMapData( QString directory, MapPackage* data = NULL ); bool containsMapData( MapPackage* data = NULL ) const; // searches recursivly in subdirectories for map data static bool searchForMapPackages( QString directory, QVector< MapPackage >* data, int depth = 2 ); static bool unpackModule( QString filename ); // names of the last loaded modules void lastModules( QString* routing, QString* rendering, QString* addressLookup ); // is a map loaded? bool loaded() const; // tries to load the current directory // automatically calls loadInformation() bool load( const Module& routingModule, const Module& renderingModule, const Module& addressLookupModule ); // tries loading modules by searching for the last used module names bool loadLast(); // tries to unload the map data bool unload(); // is the map information loaded? bool informationLoaded() const; // loads information about the map data // -> module list, map package name, bounding box bool loadInformation(); // Information about the current directory // only valid after loadInformation() or load() was called successfully // the information associated with the current map package const MapPackage& information() const; // returns all available modules QVector< Module > modules( ModuleType plugin ) const; // returns an instance of a required plugin // only available after a successfull call to load() / loadLast() IAddressLookup* addressLookup(); IGPSLookup* gpsLookup(); IRenderer* renderer(); IRouter* router(); signals: void dataLoaded(); void dataUnloaded(); void informationChanged(); public slots: // call before the QApplication object is destroyed // neccessary as Qt does not delete static instances itself // CHECK WHENEVER QT VERSION CHANGES!!! void cleanup(); private: MapData(); struct PrivateImplementation; PrivateImplementation* const d; }; #endif // MAPDATA_H monav-0.3/client/mainwindow.cpp0000644000175000017500000005663611552632364016265 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "mapdata.h" #include "mappackageswidget.h" #include "mapmoduleswidget.h" #include "overlaywidget.h" #include "generalsettingsdialog.h" #include "addressdialog.h" #include "bookmarksdialog.h" #include "routinglogic.h" #include "routedescriptiondialog.h" #include "gpsdialog.h" #include "globalsettings.h" #include #include #include #include #include #include #include #include #include #ifdef Q_WS_MAEMO_5 #include "fullscreenexitbutton.h" #include #include #include #endif struct MainWindow::PrivateImplementation { enum Mode { Source, Target, POI, NoSelection }; OverlayWidget* targetOverlay; OverlayWidget* sourceOverlay; OverlayWidget* gotoOverlay; OverlayWidget* settingsOverlay; QMenu* targetMenu; QMenu* sourceMenu; QMenu* gotoMenu; QMenu* settingsMenu; QSignalMapper* waypointMapper; int currentWaypoint; int maxZoom; bool fixed; Mode mode; void setupMenu(); void resizeIcons(); }; MainWindow::MainWindow( QWidget* parent ) : QMainWindow( parent ), m_ui( new Ui::MainWindow ) { m_ui->setupUi( this ); d = new PrivateImplementation; setupMenu(); m_ui->zoomBar->hide(); m_ui->infoWidget->hide(); m_ui->tapMode->hide(); m_ui->paintArea->setKeepPositionVisible( true ); // ensure that we're painting our background setAutoFillBackground(true); d->mode = PrivateImplementation::NoSelection; d->fixed = false; QSettings settings( "MoNavClient" ); // explicitly look for geometry as out own might not be initialized properly yet. if ( settings.contains( "geometry" ) ) setGeometry( settings.value( "geometry" ).toRect() ); GlobalSettings::loadSettings( &settings ); resizeIcons(); connectSlots(); waypointsChanged(); #ifdef Q_WS_MAEMO_5 grabZoomKeys( true ); new FullScreenExitButton(this); showFullScreen(); #endif MapData* mapData = MapData::instance(); if ( mapData->loadInformation() ) mapData->loadLast(); if ( !mapData->informationLoaded() ) { displayMapChooser(); } else if ( !mapData->loaded() ) { displayModuleChooser(); } } MainWindow::~MainWindow() { QSettings settings( "MoNavClient" ); settings.setValue( "geometry", geometry() ); GlobalSettings::saveSettings( &settings ); delete d; delete m_ui; } void MainWindow::connectSlots() { MapData* mapData = MapData::instance(); connect( m_ui->zoomBar, SIGNAL(valueChanged(int)), this, SLOT(setZoom(int)) ); connect( m_ui->paintArea, SIGNAL(zoomChanged(int)), this, SLOT(setZoom(int)) ); connect( m_ui->paintArea, SIGNAL(mouseClicked(ProjectedCoordinate)), this, SLOT(mouseClicked(ProjectedCoordinate)) ); connect( m_ui->zoomIn, SIGNAL(clicked()), this, SLOT(addZoom()) ); connect( m_ui->zoomOut, SIGNAL(clicked()), this, SLOT(subtractZoom()) ); connect( m_ui->infoIcon1, SIGNAL(clicked()), this, SLOT(showInstructions()) ); connect( m_ui->infoIcon2, SIGNAL(clicked()), this, SLOT(showInstructions()) ); connect( mapData, SIGNAL(informationChanged()), this, SLOT(informationLoaded()) ); connect( mapData, SIGNAL(dataLoaded()), this, SLOT(dataLoaded()) ); connect( RoutingLogic::instance(), SIGNAL(instructionsChanged()), this, SLOT(instructionsChanged()) ); connect( RoutingLogic::instance(), SIGNAL(waypointsChanged()), this, SLOT(waypointsChanged()) ); connect( m_ui->lockButton, SIGNAL(clicked()), this, SLOT(toggleLocked()) ); connect( m_ui->bookmarks, SIGNAL(clicked()), this, SLOT(bookmarks()) ); connect( m_ui->show, SIGNAL(clicked()), this, SLOT(gotoMenu()) ); connect( m_ui->settings, SIGNAL(clicked()), this, SLOT(settingsMenu()) ); d->waypointMapper = new QSignalMapper( this ); connect( d->waypointMapper, SIGNAL(mapped(int)), SLOT(setWaypointID(int)) ); connect( m_ui->source, SIGNAL(clicked()), d->waypointMapper, SLOT(map()) ); d->waypointMapper->setMapping( m_ui->source, -1 ); connect( m_ui->source, SIGNAL(clicked()), this, SLOT(sourceMenu()) ); connect( m_ui->target, SIGNAL(clicked()), d->waypointMapper, SLOT(map()) ); d->waypointMapper->setMapping( m_ui->target, 0 ); connect( m_ui->target, SIGNAL(clicked()), this, SLOT(targetMenu()) ); connect( m_ui->tapMode, SIGNAL(clicked()), this, SLOT(setModeNoSelection()) ); } void MainWindow::setupMenu() { d->gotoMenu = new QMenu( tr( "Show" ), this ); d->gotoMenu->addAction( QIcon( ":/images/oxygen/network-wireless.png" ), tr( "GPS-Location" ), this, SLOT(gotoGpsLocation()) ); d->gotoMenu->addAction( QIcon( ":/images/source.png" ), tr( "Departure" ), this, SLOT(gotoSource()) ); d->gotoMenu->addAction( QIcon( ":/images/target.png" ), tr( "Destination" ), this, SLOT(gotoTarget()) ); d->gotoMenu->addAction( QIcon( ":/images/oxygen/bookmarks.png" ), tr( "Bookmark..." ), this, SLOT(gotoBookmark()) ); d->gotoMenu->addAction( QIcon( ":/images/address.png" ), tr( "Address..." ), this, SLOT(gotoAddress()) ); d->gotoMenu->addAction( QIcon( ":/images/oxygen/network-wireless.png" ), tr( "GPS-Coordinate..." ), this, SLOT(gotoGpsCoordinate()) ); d->gotoOverlay = new OverlayWidget( this, tr( "Show" ) ); d->gotoOverlay->addActions( d->gotoMenu->actions() ); d->sourceMenu = new QMenu( tr( "Departure" ), this ); d->sourceMenu->addAction( QIcon( ":/images/map.png" ), tr( "Tap on Map" ), this, SLOT(setModeSourceSelection()) ); d->sourceMenu->addAction( QIcon( ":/images/oxygen/bookmarks.png" ), tr( "Bookmark" ), this, SLOT(sourceByBookmark()) ); d->sourceMenu->addAction( QIcon( ":/images/address.png" ), tr( "Address" ), this, SLOT(sourceByAddress()) ); d->sourceMenu->addAction( QIcon( ":/images/oxygen/network-wireless.png" ), tr( "GPS-Location" ), this, SLOT(sourceByGPS()) ); d->sourceOverlay = new OverlayWidget( this, tr( "Departure" ) ); d->sourceOverlay->addActions( d->sourceMenu->actions() ); d->targetMenu = new QMenu( tr( "Destination" ), this ); d->targetMenu->addAction( QIcon( ":/images/map.png" ), tr( "Tap on Map" ), this, SLOT(setModeTargetSelection()) ); d->targetMenu->addAction( QIcon( ":/images/oxygen/bookmarks.png" ), tr( "Bookmark" ), this, SLOT(targetByBookmark()) ); d->targetMenu->addAction( QIcon( ":/images/address.png" ), tr( "Address" ), this, SLOT(targetByAddress()) ); d->targetMenu->addSeparator(); d->targetMenu->addAction( QIcon( ":/images/oxygen/list-add.png" ), tr( "+Waypoint" ), this, SLOT(addRoutepoint()) ); d->targetMenu->addAction( QIcon( ":/images/oxygen/list-remove.png" ), tr( "-Waypoint" ), this, SLOT(subductRoutepoint()) ); d->targetOverlay = new OverlayWidget( this, tr( "Destination" ) ); d->targetOverlay->addActions( d->targetMenu->actions() ); d->settingsMenu = new QMenu( tr( "Settings" ), this ); d->settingsMenu->addAction( QIcon( ":/images/oxygen/folder-tar.png" ), tr( "Map Packages" ), this, SLOT(displayMapChooser()) ); d->settingsMenu->addAction( QIcon( ":/images/oxygen/folder-tar.png" ), tr( "Map Modules" ), this, SLOT(displayModuleChooser()) ); d->settingsMenu->addAction( QIcon( ":/images/oxygen/preferences-system.png" ), tr( "General" ), this, SLOT(settingsGeneral()) ); d->settingsMenu->addAction( QIcon( ":/images/oxygen/network-wireless.png" ), tr( "GPS Lookup" ), this, SLOT(settingsGPSLookup()) ); d->settingsMenu->addAction( QIcon( ":/images/map.png" ), tr( "Renderer" ), this, SLOT(settingsRenderer()) ); d->settingsMenu->addAction( QIcon( ":/images/route.png" ), tr( "Router" ), this, SLOT(settingsRouter()) ); d->settingsMenu->addAction( QIcon( ":/images/address.png" ), tr( "Address Lookup" ), this, SLOT(settingsAddressLookup()) ); d->settingsMenu->addAction( QIcon( ":/images/oxygen/hwinfo.png" ), tr( "GPS Receiver" ), this, SLOT(settingsGPS()) ); d->settingsOverlay = new OverlayWidget( this, tr( "Settings" ) ); d->settingsOverlay->addActions( d->settingsMenu->actions() ); } void MainWindow::resizeIcons() { // a bit hackish right now // find all suitable children and resize their icons // TODO find cleaner way int iconSize = GlobalSettings::iconSize(); foreach ( QToolButton* button, this->findChildren< QToolButton* >() ) button->setIconSize( QSize( iconSize, iconSize ) ); foreach ( QToolBar* button, this->findChildren< QToolBar* >() ) button->setIconSize( QSize( iconSize, iconSize ) ); m_ui->waypointsWidget->setMinimumSize( m_ui->waypointsWidget->widget()->sizeHint() ); } void MainWindow::showInstructions() { RouteDescriptionWidget* widget = new RouteDescriptionWidget( this ); int index = m_ui->stacked->addWidget( widget ); m_ui->stacked->setCurrentIndex( index ); connect( widget, SIGNAL(closed()), widget, SLOT(deleteLater()) ); } void MainWindow::displayMapChooser() { MapPackagesWidget* widget = new MapPackagesWidget(); int index = m_ui->stacked->addWidget( widget ); m_ui->stacked->setCurrentIndex( index ); widget->show(); setWindowTitle( "MoNav - Map Packages" ); connect( widget, SIGNAL(mapChanged()), this, SLOT(mapLoaded()) ); } void MainWindow::displayModuleChooser() { MapModulesWidget* widget = new MapModulesWidget(); int index = m_ui->stacked->addWidget( widget ); m_ui->stacked->setCurrentIndex( index ); widget->show(); setWindowTitle( "MoNav - Map Modules" ); connect( widget, SIGNAL(selected()), this, SLOT(modulesLoaded()) ); connect( widget, SIGNAL(cancelled()), this, SLOT(modulesCancelled()) ); } void MainWindow::mapLoaded() { MapData* mapData = MapData::instance(); if ( !mapData->informationLoaded() ) return; if ( m_ui->stacked->count() <= 1 ) return; QWidget* widget = m_ui->stacked->currentWidget(); widget->deleteLater(); if ( !mapData->loadLast() ) displayModuleChooser(); } void MainWindow::modulesCancelled() { if ( m_ui->stacked->count() <= 1 ) return; QWidget* widget = m_ui->stacked->currentWidget(); widget->deleteLater(); MapData* mapData = MapData::instance(); if ( !mapData->loaded() ) { if ( !mapData->loadLast() ) displayMapChooser(); } } void MainWindow::modulesLoaded() { if ( m_ui->stacked->count() <= 1 ) return; QWidget* widget = m_ui->stacked->currentWidget(); widget->deleteLater(); } void MainWindow::informationLoaded() { MapData* mapData = MapData::instance(); if ( !mapData->informationLoaded() ) return; this->setWindowTitle( "MoNav - " + mapData->information().name ); } void MainWindow::dataLoaded() { IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; d->maxZoom = renderer->GetMaxZoom(); m_ui->zoomBar->setMaximum( d->maxZoom ); m_ui->paintArea->setMaxZoom( d->maxZoom ); setZoom( GlobalSettings::zoomMainMap()); m_ui->paintArea->setVirtualZoom( GlobalSettings::magnification() ); m_ui->paintArea->setCenter( RoutingLogic::instance()->source().ToProjectedCoordinate() ); m_ui->paintArea->setKeepPositionVisible( true ); this->setWindowTitle( "MoNav - " + MapData::instance()->information().name ); } void MainWindow::instructionsChanged() { if ( !d->fixed ) return; QStringList label; QStringList icon; RoutingLogic::instance()->instructions( &label, &icon, 60 ); m_ui->infoWidget->setHidden( label.empty() ); if ( label.isEmpty() ) return; m_ui->infoLabel1->setText( label[0] ); m_ui->infoIcon1->setIcon( QIcon( icon[0] ) ); m_ui->infoIcon2->setHidden( label.size() == 1 ); m_ui->infoLabel2->setHidden( label.size() == 1 ); if ( label.size() == 1 ) return; m_ui->infoLabel2->setText( label[1] ); m_ui->infoIcon2->setIcon( QIcon( icon[1] ) ); } // SETTINGS void MainWindow::settingsGeneral() { GeneralSettingsDialog* window = new GeneralSettingsDialog; window->exec(); delete window; resizeIcons(); m_ui->paintArea->setVirtualZoom( GlobalSettings::magnification() ); } void MainWindow::settingsRenderer() { IRenderer* renderer = MapData::instance()->renderer(); if ( renderer != NULL ) renderer->ShowSettings(); } void MainWindow::settingsRouter() { IRouter* router = MapData::instance()->router(); if ( router != NULL ) router->ShowSettings(); } void MainWindow::settingsGPSLookup() { IGPSLookup* gpsLookup = MapData::instance()->gpsLookup(); if( gpsLookup != NULL ) gpsLookup->ShowSettings(); } void MainWindow::settingsAddressLookup() { IAddressLookup* addressLookup = MapData::instance()->addressLookup(); if ( addressLookup != NULL ) addressLookup->ShowSettings(); } void MainWindow::settingsGPS() { GPSDialog* window = new GPSDialog( this ); window->exec(); delete window; } // MENUES void MainWindow::gotoMenu() { if ( GlobalSettings::menuMode() == GlobalSettings::MenuPopup ) { QPoint position = m_ui->show->mapToGlobal( QPoint( m_ui->show->width() / 2, m_ui->show->height() / 2 ) ); d->gotoMenu->exec( position ); } else { d->gotoOverlay->show(); } } void MainWindow::settingsMenu() { if ( GlobalSettings::menuMode() == GlobalSettings::MenuPopup ) { QPoint position = m_ui->settings->mapToGlobal( QPoint( m_ui->settings->width() / 2, m_ui->settings->height() / 2 ) ); d->settingsMenu->exec( position ); } else { d->settingsOverlay->show(); } } void MainWindow::sourceMenu() { if ( GlobalSettings::menuMode() == GlobalSettings::MenuPopup ) { QPoint position = m_ui->source->mapToGlobal( QPoint( m_ui->source->width() / 2, m_ui->source->height() / 2 ) ); d->sourceMenu->exec( position ); } else { d->sourceOverlay->show(); } } void MainWindow::targetMenu() { if ( GlobalSettings::menuMode() == GlobalSettings::MenuPopup ) { QPoint position = m_ui->target->mapToGlobal( QPoint( m_ui->target->width() / 2, m_ui->target->height() / 2 ) ); d->targetMenu->exec( position ); } else { d->targetOverlay->show(); } } // EVENTS void MainWindow::resizeEvent( QResizeEvent* event ) { QBoxLayout* box = qobject_cast< QBoxLayout* >( m_ui->infoWidget->layout() ); assert ( box != NULL ); if ( event->size().width() > event->size().height() ) box->setDirection( QBoxLayout::LeftToRight ); else box->setDirection( QBoxLayout::TopToBottom ); } #ifdef Q_WS_MAEMO_5 void MainWindow::grabZoomKeys( bool grab ) { if ( !winId() ) { qWarning() << "Can't grab keys unless we have a window id"; return; } unsigned long val = ( grab ) ? 1 : 0; Atom atom = XInternAtom( QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False ); if ( !atom ) { qWarning() << "Unable to obtain _HILDON_ZOOM_KEY_ATOM. This will only work on a Maemo 5 device!"; return; } XChangeProperty ( QX11Info::display(), winId(), atom, XA_INTEGER, 32, PropModeReplace, reinterpret_cast< unsigned char* >( &val ), 1 ); } void MainWindow::keyPressEvent( QKeyEvent* event ) { switch (event->key()) { case Qt::Key_F7: addZoom(); event->accept(); break; case Qt::Key_F8: this->subtractZoom(); event->accept(); break; } QWidget::keyPressEvent(event); } #endif // SLOTS void MainWindow::setModeSourceSelection() { m_ui->paintArea->setKeepPositionVisible( false ); d->mode = PrivateImplementation::Source; m_ui->waypointsWidget->setVisible( false ); m_ui->menuWidget->setVisible( false ); m_ui->lockButton->setVisible( false ); m_ui->tapMode->setVisible( true ); } void MainWindow::setModeTargetSelection() { m_ui->paintArea->setKeepPositionVisible( false ); d->mode = PrivateImplementation::Target; m_ui->waypointsWidget->setVisible( false ); m_ui->menuWidget->setVisible( false ); m_ui->lockButton->setVisible( false ); m_ui->tapMode->setVisible( true ); } void MainWindow::setModeNoSelection() { d->mode = PrivateImplementation::NoSelection; m_ui->waypointsWidget->setVisible( true ); m_ui->menuWidget->setVisible( true ); m_ui->lockButton->setVisible( true ); m_ui->tapMode->setVisible( false ); } void MainWindow::mouseClicked( ProjectedCoordinate clickPos ) { UnsignedCoordinate coordinate( clickPos ); if ( d->mode == PrivateImplementation::Source ) { RoutingLogic::instance()->setSource( coordinate ); } else if ( d->mode == PrivateImplementation::Target ) { RoutingLogic::instance()->setWaypoint( d->currentWaypoint, coordinate ); } else if ( d->mode == PrivateImplementation::POI ){ //m_selected = coordinate; //m_ui->paintArea->setPOI( coordinate ); //return; } //m_mode = None; // might be contra-productiv for some use cases. E.g., many new users just want to click around the map and wonder about the blazingly fast routing *g* } void MainWindow::gotoGpsLocation() { const RoutingLogic::GPSInfo& gpsInfo = RoutingLogic::instance()->gpsInfo(); if ( !gpsInfo.position.IsValid() ) return; GPSCoordinate gps( gpsInfo.position.ToGPSCoordinate().latitude, gpsInfo.position.ToGPSCoordinate().longitude ); m_ui->paintArea->setCenter( ProjectedCoordinate( gps ) ); m_ui->paintArea->setKeepPositionVisible( true ); IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; setZoom( renderer->GetMaxZoom() - 5 ); } void MainWindow::gotoSource() { UnsignedCoordinate coordinate = RoutingLogic::instance()->source(); if ( !coordinate.IsValid() ) return; m_ui->paintArea->setCenter( coordinate.ToProjectedCoordinate() ); m_ui->paintArea->setKeepPositionVisible( true ); IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; setZoom( renderer->GetMaxZoom() - 5 ); } void MainWindow::gotoTarget() { UnsignedCoordinate coordinate = RoutingLogic::instance()->target(); if ( !coordinate.IsValid() ) return; m_ui->paintArea->setCenter( coordinate.ToProjectedCoordinate() ); m_ui->paintArea->setKeepPositionVisible( false ); IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; setZoom( renderer->GetMaxZoom() - 5 ); } void MainWindow::gotoBookmark() { UnsignedCoordinate result; if ( !BookmarksDialog::showBookmarks( &result, this ) ) return; m_ui->paintArea->setCenter( result.ToProjectedCoordinate() ); m_ui->paintArea->setKeepPositionVisible( false ); IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; setZoom( renderer->GetMaxZoom() - 5 ); } void MainWindow::gotoAddress() { if ( MapData::instance()->addressLookup() == NULL ) return; UnsignedCoordinate result; if ( !AddressDialog::getAddress( &result, this, true ) ) return; m_ui->paintArea->setCenter( result.ToProjectedCoordinate() ); m_ui->paintArea->setKeepPositionVisible( false ); IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; setZoom( renderer->GetMaxZoom() - 5 ); } void MainWindow::gotoGpsCoordinate() { bool ok = false; double latitude = QInputDialog::getDouble( this, "Enter Coordinate", "Enter Latitude", 0, -90, 90, 5, &ok ); if ( !ok ) return; double longitude = QInputDialog::getDouble( this, "Enter Coordinate", "Enter Longitude", 0, -180, 180, 5, &ok ); if ( !ok ) return; GPSCoordinate gps( latitude, longitude ); m_ui->paintArea->setCenter( ProjectedCoordinate( gps ) ); m_ui->paintArea->setKeepPositionVisible( false ); IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; setZoom( renderer->GetMaxZoom() - 5 ); } void MainWindow::sourceByBookmark() { UnsignedCoordinate result; if ( !BookmarksDialog::showBookmarks( &result, this ) ) return; RoutingLogic::instance()->setSource( result ); m_ui->paintArea->setCenter( result.ToProjectedCoordinate() ); } void MainWindow::sourceByAddress() { if ( MapData::instance()->addressLookup() == NULL ) return; UnsignedCoordinate result; if ( !AddressDialog::getAddress( &result, this ) ) return; RoutingLogic::instance()->setSource( result ); m_ui->paintArea->setCenter( result.ToProjectedCoordinate() ); } void MainWindow::sourceByGPS() { RoutingLogic::instance()->setGPSLink( true ); } void MainWindow::setWaypointID( int id ) { d->currentWaypoint = id; } void MainWindow::targetByBookmark() { UnsignedCoordinate result; if ( !BookmarksDialog::showBookmarks( &result, this ) ) return; RoutingLogic::instance()->setWaypoint( d->currentWaypoint, result ); m_ui->paintArea->setCenter( result.ToProjectedCoordinate() ); } void MainWindow::targetByAddress() { if ( MapData::instance()->addressLookup() == NULL ) return; UnsignedCoordinate result; if ( !AddressDialog::getAddress( &result, this ) ) return; RoutingLogic::instance()->setWaypoint( d->currentWaypoint, result ); m_ui->paintArea->setCenter( result.ToProjectedCoordinate() ); } void MainWindow::subductRoutepoint() { RoutingLogic* routingLogic = RoutingLogic::instance(); QVector< UnsignedCoordinate > waypoints = routingLogic->waypoints(); if ( d->currentWaypoint >= waypoints.size() ) return; waypoints.remove( d->currentWaypoint ); routingLogic->setWaypoints( waypoints ); } void MainWindow::addRoutepoint() { RoutingLogic* routingLogic = RoutingLogic::instance(); QVector< UnsignedCoordinate > waypoints = routingLogic->waypoints(); if ( waypoints.empty() ) waypoints.resize( d->currentWaypoint ); waypoints.insert( d->currentWaypoint, UnsignedCoordinate() ); routingLogic->setWaypoints( waypoints ); } void MainWindow::bookmarks() { UnsignedCoordinate result; if ( !BookmarksDialog::showBookmarks( &result, this ) ) return; m_ui->paintArea->setCenter( result.ToProjectedCoordinate() ); } void MainWindow::addZoom() { setZoom( GlobalSettings::zoomMainMap() + 1 ); } void MainWindow::subtractZoom() { setZoom( GlobalSettings::zoomMainMap() - 1 ); } void MainWindow::setZoom( int zoom ) { IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; if( zoom > renderer->GetMaxZoom() ) zoom = renderer->GetMaxZoom(); if( zoom < 0 ) zoom = 0; m_ui->zoomBar->setValue( zoom ); m_ui->paintArea->setZoom( zoom ); GlobalSettings::setZoomMainMap( zoom ); } void MainWindow::toggleLocked() { d->fixed = !d->fixed; m_ui->paintArea->setFixed( d->fixed ); if ( d->fixed ) { m_ui->lockButton->setIcon( QIcon( ":images/oxygen/emblem-locked.png") ); instructionsChanged(); } else { m_ui->lockButton->setIcon( QIcon( ":images/oxygen/emblem-unlocked.png") ); m_ui->infoWidget->hide(); } } void MainWindow::waypointsChanged() { QList< QToolButton* > waypointButtons = findChildren< QToolButton* >( "waypoint" ); foreach( QToolButton* button, waypointButtons ) button->deleteLater(); QVector< UnsignedCoordinate > waypoints = RoutingLogic::instance()->waypoints(); for ( int i = 0; i < waypoints.size() - 1; i++ ) { int id = waypoints.size() - 1 - i; QToolButton* button = new QToolButton( NULL ); if ( QFile::exists( QString( ":/images/waypoint%1.png" ).arg( id ) ) ) button->setIcon( QIcon( QString( ":/images/waypoint%1.png" ).arg( id ) ) ); else button->setIcon( QIcon( ":/images/target.png" ) ); button->setIconSize( QSize( GlobalSettings::iconSize(), GlobalSettings::iconSize() ) ); button->setAutoRaise( true ); button->setObjectName( "waypoint" ); m_ui->scrollAreaWidgetContents->layout()->addWidget( button ); d->waypointMapper->setMapping( button, id - 1 ); connect( button, SIGNAL(clicked()), d->waypointMapper, SLOT(map()) ); connect( button, SIGNAL(clicked()), this, SLOT(targetMenu()) ); button->show(); } if ( !waypoints.empty() ) d->waypointMapper->setMapping( m_ui->target, waypoints.size() - 1 ); else d->waypointMapper->setMapping( m_ui->target, 0 ); m_ui->scrollAreaWidgetContents->layout()->addWidget( m_ui->source ); } monav-0.3/client/mainwindow.h0000644000175000017500000000452211551042742015707 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include #include "utils/coordinates.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow( QWidget* parent = 0 ); ~MainWindow(); protected slots: void informationLoaded(); void mapLoaded(); void modulesLoaded(); void modulesCancelled(); void dataLoaded(); void mouseClicked( ProjectedCoordinate clickPos ); void addZoom(); void subtractZoom(); void setZoom( int zoom ); void settingsGeneral(); void settingsRenderer(); void settingsRouter(); void settingsGPSLookup(); void settingsAddressLookup(); void settingsGPS(); void gotoSource(); void gotoGpsCoordinate(); void gotoGpsLocation(); void gotoTarget(); void gotoBookmark(); void gotoAddress(); void sourceByBookmark(); void sourceByAddress(); void sourceByGPS(); void setWaypointID( int id ); void waypointsChanged(); void targetByBookmark(); void targetByAddress(); void subductRoutepoint(); void addRoutepoint(); void bookmarks(); void setModeSourceSelection(); void setModeTargetSelection(); void setModeNoSelection(); void toggleLocked(); void gotoMenu(); void settingsMenu(); void sourceMenu(); void targetMenu(); void showInstructions(); void instructionsChanged(); void displayMapChooser(); void displayModuleChooser(); protected: virtual void resizeEvent( QResizeEvent* event ); void connectSlots(); void setupMenu(); void resizeIcons(); #ifdef Q_WS_MAEMO_5 void grabZoomKeys( bool grab ); void keyPressEvent( QKeyEvent* event ); #endif struct PrivateImplementation; PrivateImplementation* d; Ui::MainWindow* m_ui; }; #endif // MAINWINDOW_H monav-0.3/client/logger.h0000644000175000017500000000313511545155121015010 0ustar vettervetter/* Copyright 2010 Christoph Eckert ce@christeck.de This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #ifndef LOGGER_H #define LOGGER_H #include #include #include #include #include #include #include #include #include "../utils/coordinates.h" #include "routinglogic.h" class Logger : public QObject { Q_OBJECT public: static Logger* instance(); ~Logger(); bool loggingEnabled(); void setLoggingEnabled(bool); QString directory(); void setDirectory(QString); QVector< int > polygonEndpointsTracklog(); QVector< UnsignedCoordinate > polygonCoordsTracklog(); public slots: void positionChanged(); void initialize(); void clearTracklog(); signals: void trackChanged(); protected: explicit Logger( QObject* parent = 0 ); bool readGpxLog(); bool writeGpxLog(); QFile m_logFile; QDateTime m_lastFlushTime; bool m_loggingEnabled; QString m_tracklogPath; QString m_tracklogPrefix; QVector m_gpsInfoBuffer; }; #endif // LOGGER_H monav-0.3/client/placechooser.ui0000644000175000017500000003452011524531126016370 0ustar vettervetter PlaceChooser 0 0 754 557 MoNav - Choose Place 0 0 0 0 0 0 Qt::Horizontal 1 1 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 true QFrame::StyledPanel QFrame::Raised 4 2 Qt::NoFocus ... :/images/oxygen/go-previous.png:/images/oxygen/go-previous.png true Choose Qt::NoFocus ... :/images/oxygen/go-next.png:/images/oxygen/go-next.png true Qt::Horizontal 1 1 0 0 Qt::Horizontal 1 1 0 Qt::Vertical 1 1 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 true QFrame::StyledPanel QFrame::Raised 0 2 0 0 Qt::NoFocus + :/images/oxygen/zoom-in.png:/images/oxygen/zoom-in.png true 0 0 Qt::NoFocus - :/images/oxygen/zoom-out.png:/images/oxygen/zoom-out.png true Qt::Vertical 1 1 0 0 10 1 Qt::Vertical QSlider::TicksBothSides PaintWidget QWidget
paintwidget.h
1
monav-0.3/client/routinglogic.cpp0000644000175000017500000002316111551000615016564 0ustar vettervetter/* Copyright 2010 Christian Vetter veaac.fdirct@gmail.com This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "routinglogic.h" #include "descriptiongenerator.h" #include "mapdata.h" #include "utils/qthelpers.h" #include "logger.h" #include #include #include struct RoutingLogic::PrivateImplementation { GPSInfo gpsInfo; UnsignedCoordinate source; QVector< UnsignedCoordinate > waypoints; QVector< IRouter::Node > pathNodes; QVector< IRouter::Edge > pathEdges; double distance; double travelTime; DescriptionGenerator descriptionGenerator; QStringList labels; QStringList icons; bool linked; #ifndef NOQTMOBILE // the current GPS source QGeoPositionInfoSource* gpsSource; #endif }; RoutingLogic::RoutingLogic() : d( new PrivateImplementation ) { d->linked = true; d->distance = -1; d->travelTime = -1; d->gpsInfo.altitude = -1; d->gpsInfo.groundSpeed = -1; d->gpsInfo.verticalSpeed = -1; d->gpsInfo.heading = -1; d->gpsInfo.horizontalAccuracy = -1; d->gpsInfo.verticalAccuracy = -1; QSettings settings( "MoNavClient" ); settings.beginGroup( "Routing" ); d->source.x = settings.value( "source.x", d->source.x ).toUInt(); d->source.y = settings.value( "source.y", d->source.y ).toUInt(); #ifndef NOQTMOBILE d->gpsSource = QGeoPositionInfoSource::createDefaultSource( this ); if ( d->gpsSource == NULL ) { qDebug() << "No GPS Sensor found! GPS Updates are not available"; } else { // prevent QtMobility from cheating // documemenation states that it would provide updates as fast as possible if nothing was specified // nevertheless, it did provide only one every 5 seconds on the N900 // with this setting on every second d->gpsSource->setUpdateInterval( 1000 ); d->gpsSource->startUpdates(); connect( d->gpsSource, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo)) ); } #endif for ( int i = 0; i < settings.value( "amountRoutepoints", 0 ).toInt(); i++ ) { UnsignedCoordinate coordinate; bool ok = true; coordinate.x = settings.value( QString( "routepointx%1" ).arg( i + 1 ), coordinate.x ).toUInt( &ok ); if ( !ok ) continue; coordinate.y = settings.value( QString( "routepointy%1" ).arg( i + 1 ), coordinate.y ).toUInt( &ok ); if ( !ok ) continue; if ( coordinate.IsValid() ) d->waypoints.append( coordinate ); } connect( this, SIGNAL(gpsInfoChanged()), Logger::instance(), SLOT(positionChanged()) ); connect( MapData::instance(), SIGNAL(dataLoaded()), this, SLOT(dataLoaded()) ); computeRoute(); emit waypointsChanged(); } RoutingLogic::~RoutingLogic() { #ifndef NOQTMOBILE if ( d->gpsSource != NULL ) delete d->gpsSource; #endif QSettings settings( "MoNavClient" ); settings.beginGroup( "Routing" ); settings.setValue( "source.x", d->source.x ); settings.setValue( "source.y", d->source.y ); settings.setValue( "amountRoutepoints", d->waypoints.size() ); for ( int i = 0; i < d->waypoints.size(); i++ ){ settings.setValue( QString( "routepointx%1" ).arg( i + 1 ), d->waypoints[i].x ); settings.setValue( QString( "routepointy%1" ).arg( i + 1 ), d->waypoints[i].y ); } delete d; } RoutingLogic* RoutingLogic::instance() { static RoutingLogic routingLogic; return &routingLogic; } #ifndef NOQTMOBILE void RoutingLogic::positionUpdated( const QGeoPositionInfo& update ) { if ( !update.isValid() ) return; GPSCoordinate gps; gps.latitude = update.coordinate().latitude(); gps.longitude = update.coordinate().longitude(); d->gpsInfo.position = UnsignedCoordinate( gps ); d->gpsInfo.altitude = update.coordinate().altitude(); d->gpsInfo.timestamp = update.timestamp(); if ( update.hasAttribute( QGeoPositionInfo::Direction ) ) d->gpsInfo.heading = update.attribute( QGeoPositionInfo::Direction ); if ( update.hasAttribute( QGeoPositionInfo::GroundSpeed ) ) d->gpsInfo.groundSpeed = update.attribute( QGeoPositionInfo::GroundSpeed ); if ( update.hasAttribute( QGeoPositionInfo::VerticalSpeed ) ) d->gpsInfo.verticalSpeed = update.attribute( QGeoPositionInfo::VerticalSpeed ); if ( update.hasAttribute( QGeoPositionInfo::HorizontalAccuracy ) ) d->gpsInfo.horizontalAccuracy = update.attribute( QGeoPositionInfo::HorizontalAccuracy ); if ( update.hasAttribute( QGeoPositionInfo::VerticalAccuracy ) ) d->gpsInfo.verticalAccuracy = update.attribute( QGeoPositionInfo::VerticalAccuracy ); if ( d->linked ) { d->source = d->gpsInfo.position; emit sourceChanged(); computeRoute(); } emit gpsInfoChanged(); } #endif QVector< UnsignedCoordinate > RoutingLogic::waypoints() const { return d->waypoints; } UnsignedCoordinate RoutingLogic::source() const { return d->source; } UnsignedCoordinate RoutingLogic::target() const { if ( d->waypoints.empty() ) return UnsignedCoordinate(); return d->waypoints.last(); } bool RoutingLogic::gpsLink() const { return d->linked; } const RoutingLogic::GPSInfo& RoutingLogic::gpsInfo() const { return d->gpsInfo; } QVector< IRouter::Node > RoutingLogic::route() const { return d->pathNodes; } void RoutingLogic::clear() { d->waypoints.clear(); computeRoute(); } void RoutingLogic::instructions( QStringList* labels, QStringList* icons, int maxSeconds ) { d->descriptionGenerator.reset(); d->descriptionGenerator.descriptions( &d->icons, &d->labels, d->pathNodes, d->pathEdges, maxSeconds ); *labels = d->labels; *icons = d->icons; } void RoutingLogic::setWaypoints( QVector waypoints ) { bool changed = waypoints != d->waypoints; d->waypoints = waypoints; if ( changed ) { computeRoute(); emit waypointsChanged(); } } void RoutingLogic::setWaypoint( int id, UnsignedCoordinate coordinate ) { if ( d->waypoints.size() <= id ) d->waypoints.resize( id + 1 ); d->waypoints[id] = coordinate; while ( !d->waypoints.empty() && !d->waypoints.back().IsValid() ) d->waypoints.pop_back(); computeRoute(); emit waypointsChanged(); } void RoutingLogic::setSource( UnsignedCoordinate coordinate ) { setGPSLink( false ); d->source = coordinate; computeRoute(); emit sourceChanged(); } void RoutingLogic::setTarget( UnsignedCoordinate target ) { int index = d->waypoints.empty() ? 0 : d->waypoints.size() - 1; setWaypoint( index, target ); } void RoutingLogic::setGPSLink( bool linked ) { if ( linked == d->linked ) return; d->linked = linked; if ( d->gpsInfo.position.IsValid() ) { d->source = d->gpsInfo.position; emit sourceChanged(); computeRoute(); } emit gpsLinkChanged( d->linked ); } void RoutingLogic::computeRoute() { IGPSLookup* gpsLookup = MapData::instance()->gpsLookup(); if ( gpsLookup == NULL ) return; IRouter* router = MapData::instance()->router(); if ( router == NULL ) return; if ( !d->source.IsValid() ) { clearRoute(); return; } QVector< UnsignedCoordinate > waypoints; int passedRoutepoint = 0; waypoints.push_back( d->source ); for ( int i = 0; i < d->waypoints.size(); i++ ) { if ( d->waypoints[i].IsValid() ) waypoints.push_back( d->waypoints[i] ); if ( waypoints[0].ToGPSCoordinate().ApproximateDistance( d->waypoints[i].ToGPSCoordinate() ) < 50 ) { waypoints.remove( 1, waypoints.size() - 1 ); passedRoutepoint = i + 1; } } if ( passedRoutepoint > 0 ) { d->waypoints.remove( 0, passedRoutepoint ); emit waypointsChanged(); } if ( waypoints.size() < 2 ) { clearRoute(); return; } QVector< IGPSLookup::Result > gps; for ( int i = 0; i < waypoints.size(); i++ ) { Timer time; IGPSLookup::Result result; bool found = gpsLookup->GetNearestEdge( &result, waypoints[i], 1000 ); qDebug() << "GPS Lookup:" << time.elapsed() << "ms"; if ( !found ) { clearRoute(); return; } gps.push_back( result ); } d->pathNodes.clear(); d->pathEdges.clear(); for ( int i = 1; i < waypoints.size(); i++ ) { QVector< IRouter::Node > nodes; QVector< IRouter::Edge > edges; double travelTime; Timer time; bool found = router->GetRoute( &travelTime, &nodes, &edges, gps[i - 1], gps[i] ); qDebug() << "Routing:" << time.elapsed() << "ms"; if ( found ) { if ( i == 1 ) { d->pathNodes = nodes; d->pathEdges = edges; } else { for ( int j = 1; j < nodes.size(); j++ ) d->pathNodes.push_back( nodes[j] ); for ( int j = 1; j < edges.size(); j++ ) d->pathEdges.push_back( edges[j] ); } d->travelTime += travelTime; } else { d->travelTime = -1; break; } } d->distance = waypoints.first().ToGPSCoordinate().ApproximateDistance( waypoints.last().ToGPSCoordinate() ); emit routeChanged(); emit instructionsChanged(); emit distanceChanged( d->distance ); emit travelTimeChanged( d->travelTime ); } void RoutingLogic::clearRoute() { d->distance = -1; d->travelTime = -1; d->pathEdges.clear(); d->pathNodes.clear(); d->icons.clear(); d->labels.clear(); emit routeChanged(); emit instructionsChanged(); emit distanceChanged( d->distance ); emit travelTimeChanged( d->travelTime ); } void RoutingLogic::dataLoaded() { if ( !d->source.IsValid() ) { const MapData::MapPackage& package = MapData::instance()->information(); d->source.x = ( ( double ) package.max.x + package.min.x ) / 2; d->source.y = ( ( double ) package.max.y + package.min.y ) / 2; emit sourceChanged(); } computeRoute(); } monav-0.3/client/worldmapchooser.ui0000644000175000017500000000231311525007300017115 0ustar vettervetter WorldMapChooser 0 0 400 300 0 0 MoNav - Map Chooser 0 0 0 0 World Map Qt::AlignCenter monav-0.3/client/logger.cpp0000644000175000017500000002004611551032766015351 0ustar vettervetter/* Copyright 2010 Christoph Eckert ce@christeck.de This file is part of MoNav. MoNav 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 3 of the License, or (at your option) any later version. MoNav 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 MoNav. If not, see . */ #include "logger.h" #include "routinglogic.h" #include "utils/qthelpers.h" Logger* Logger::instance() { static Logger logger; return &logger; } Logger::Logger( QObject* parent ) : QObject( parent ) { initialize(); readGpxLog(); } Logger::~Logger() { writeGpxLog(); } void Logger::initialize() { m_lastFlushTime = QDateTime::currentDateTime(); QSettings settings( "MoNavClient" ); m_loggingEnabled = settings.value( "LoggingEnabled", false ).toBool(); m_tracklogPath = settings.value( "LogFilePath", QDir::homePath() ).toString(); m_tracklogPrefix = tr( "MoNav Track" ); QString tracklogFilename = m_tracklogPrefix; QDateTime currentDateTime = QDateTime::currentDateTime(); tracklogFilename.append( currentDateTime.toString( " yyyy-MM-dd" ) ); tracklogFilename.append( ".gpx" ); m_logFile.setFileName( fileInDirectory( m_tracklogPath, tracklogFilename ) ); } QVector< int > Logger::polygonEndpointsTracklog() { QVector endpoints; bool append = false; int invalidElements = 0; for (int i = 0; i < m_gpsInfoBuffer.size(); i++) { if( !m_gpsInfoBuffer.at(i).position.IsValid() ) { invalidElements++; append = true; continue; } if (append == true || endpoints.size() == 0) { endpoints.append(i+1-invalidElements); append = false; continue; } endpoints.pop_back(); endpoints.append(i+1-invalidElements); } return endpoints; } QVector< UnsignedCoordinate > Logger::polygonCoordsTracklog() { QVector coordinates; for (int i = 0; i < m_gpsInfoBuffer.size(); i++) { if( m_gpsInfoBuffer.at(i).position.IsValid() ) coordinates.append(m_gpsInfoBuffer.at(i).position); } return coordinates; } void Logger::positionChanged() { if ( !m_loggingEnabled ) return; const RoutingLogic::GPSInfo& gpsInfo = RoutingLogic::instance()->gpsInfo(); if ( !gpsInfo.position.IsValid() ) return; m_gpsInfoBuffer.append(gpsInfo); int flushSecondsPassed = m_lastFlushTime.secsTo( QDateTime::currentDateTime() ); if ( flushSecondsPassed >= 300 ) writeGpxLog(); emit trackChanged(); } bool Logger::writeGpxLog() { QString backupFilename = m_logFile.fileName().remove( m_logFile.fileName().size() -4, 4 ).append( "-bck.gpx" ); if ( m_logFile.exists() && m_logFile.exists(backupFilename)) m_logFile.remove( backupFilename ); if ( !m_logFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) ){ m_loggingEnabled = false; qDebug() << "Logger: Cannot write " << m_logFile.fileName() << ". Logging disabled."; return false; } QString trackName = m_tracklogPrefix; QDateTime currentDateTime = QDateTime::currentDateTime(); trackName.append( currentDateTime.toString( " yyyy-MM-dd" ) ); trackName.prepend(" "); trackName.append("\n"); QTextStream gpxStream(&m_logFile); gpxStream << QString("\n").toUtf8(); gpxStream << QString("\n").toUtf8(); gpxStream << QString(" \n").toUtf8(); gpxStream << trackName; bool insideTracksegment = false; for (int i = 0; i < m_gpsInfoBuffer.size(); i++) { if (!m_gpsInfoBuffer.at(i).position.IsValid() && insideTracksegment) { gpxStream << " \n"; insideTracksegment = false; continue; } if (!m_gpsInfoBuffer.at(i).position.IsValid() && !insideTracksegment) { continue; } if (m_gpsInfoBuffer.at(i).position.IsValid() && !insideTracksegment) { gpxStream << " \n"; insideTracksegment = true; } if (m_gpsInfoBuffer.at(i).position.IsValid() && insideTracksegment) { QString lat = QString::number(m_gpsInfoBuffer.at(i).position.ToGPSCoordinate().latitude).prepend(" \n"); QString ele = QString::number(m_gpsInfoBuffer.at(i).altitude).prepend(" ").append("\n"); QString time = m_gpsInfoBuffer.at(i).timestamp.toString( "yyyy-MM-ddThh:mm:ss" ).prepend(" \n"); gpxStream << lat.toUtf8(); gpxStream << lon.toUtf8(); if (!ele.contains("nan")) gpxStream << ele.toUtf8(); gpxStream << time.toUtf8(); gpxStream << QString(" \n").toUtf8(); } } if (insideTracksegment) { gpxStream << QString(" \n").toUtf8(); } gpxStream << QString(" \n").toUtf8(); gpxStream << QString("\n").toUtf8(); m_logFile.close(); m_lastFlushTime = QDateTime::currentDateTime(); return true; } bool Logger::readGpxLog() { m_gpsInfoBuffer.clear(); if ( !m_logFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) { return false; } QString lineBuffer; QString latString; QString lonString; QString eleString; QString timeString; QStringList tempList; bool insideTrackpoint = false; while ( !m_logFile.atEnd() ) { lineBuffer = m_logFile.readLine(); lineBuffer = lineBuffer.simplified(); if (!insideTrackpoint) { latString = ""; lonString = ""; eleString = ""; timeString = ""; } if (lineBuffer.contains("")) { lineBuffer = lineBuffer.remove(""); lineBuffer = lineBuffer.remove(""); eleString = lineBuffer; } if (lineBuffer.contains("