What is this error about? - dynamic-linking

ALL,
I'm using Anjuta to do my development.
I created a project for my main application, and then made 2 more: 1 for the static library (libdbinterface.a) and 1 for the dynamic library (libsqlite_lib.so).
Both those libraries contains one exported class each: libdbinterface.a - class Database, libsqlite_lib.so - public SQLiteDatabase : public Database.
Now I'm trying to link libdbinterface.a to libsqlite_lib.so.
So in Anjuta I added following to the "Linker Option" for the target libsqlite_lib.so:
-L/home/igor/dbhandler/Debug/dbinterface -ldbinterface
However, trying to compile I received following error from linker:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.4/../../../../x86_64-pc-linux-gnu/bin/ld: /home/igor/dbhandler/Debug/dbinterface/libdbinterface.a(database.o): relocation R_X86_64_32S against `_ZTV8Database' can not be used when making a shared object; recompile with -fPIC
I tried to recompile libsqlite_lib.so with -fPIC explicitely added to "C++ Options" of that project but that didn't solve it - I still receive the same error.
Unfortunately trying to Google on how to link .a and .so is not helpful.
Can someone sched some light on how to fix this error?
TIA.
[EDIT]
libsqlite_lib.so Makefile - https://bpaste.net/show/1495231e58cc
libdbinterface.a Makefile - https://bpaste.net/show/3a71c119d0fc
libdbinterface.a contains 2 files databse.h:
#ifndef DBMANAGER_DATABASE
#define DBMANAGER_DATABASE
class Field
{
public:
Field(const std::string &columnName, const std::string &columnType, const std::string &columnDefaultValue = "", const bool columnIsNull = false, const bool columnPK = false)
{
column_name = columnName;
column_type = columnType;
column_defaultValue = columnDefaultValue;
column_isNull = columnIsNull;
column_pk = columnPK;
}
private:
std::string column_name, column_type, column_defaultValue;
bool column_isNull, column_pk;
};
struct FKField
{
FKField(const std::string &table_name, const std::string &original_field, const std::string &referenced_field)
{
tableName = table_name;
originalField = original_field;
referencedField = referenced_field;
}
std::string tableName, originalField, referencedField;
};
class Table
{
public:
Table(const std::string &tableName, const std::vector<Field> &tableFields, const std::map<int,std::vector<FKField> > &foreignKeys)
{
table_name = tableName;
table_fields = tableFields;
foreign_keys = foreignKeys;
}
const std::string &GetTableName() { return table_name; }
std::map<int,std::vector<FKField> > &GetForeignKeyVector() { return foreign_keys; }
private:
std::string table_name;
std::vector<Field> table_fields;
std::map<int,std::vector<FKField> > foreign_keys;
};
#ifdef WIN32
class __declspec(dllexport) Database
#else
class Database
#endif
{
private:
struct Impl;
Impl *pimpl;
public:
Database();
virtual ~Database();
Impl &GetTableVector();
static void *operator new(std::size_t size);
static void operator delete(void *ptr, std::size_t size);
virtual int Connect(const char *selectedDSN, std::vector<std::wstring> &errorMsg);
virtual int GetTableListFromDb(std::string &) { return 0; }
};
#endif
and database.cpp:
#ifdef WIN32
#include <windows.h>
#endif
#include <map>
#include <vector>
#include <string>
#include <sqlext.h>
#include "database.h"
struct Database::Impl
{
std::vector<Table> m_tables;
};
Database::Database() : pimpl( new Impl )
{
}
Database::~Database()
{
delete pimpl;
}
void *Database::operator new(std::size_t size)
{
return ::operator new( size );
}
void Database::operator delete(void *ptr, std::size_t size)
{
return ::operator delete( ptr );
}
Database::Impl &Database::GetTableVector()
{
return *pimpl;
}
int Database::Connect(const char *selectedDSN, std::vector<std::wstring> &errorMsg)
{
selectedDSN = selectedDSN;
errorMsg = errorMsg;
return 0;
}
libsqlite_lib.so has also 2 files: database_sqlite.h
#ifndef DBMANAGER_SQLITE
#define DBMANAGER_SQLITE
#ifdef WIN32
class __declspec(dllexport) SQLiteDatabase : public Database
#else
class SQLiteDatabase : public Database
#endif
{
public:
SQLiteDatabase();
~SQLiteDatabase();
virtual int Connect(const char *selectedDSN, std::vector<std::wstring> &errorMsg);
virtual int GetTableListFromDb(std::vector<std::wstring> &errorMsg);
protected:
void GetErrorMessage(int code, std::wstring &errorMsg);
private:
sqlite3 *m_db;
};
#endif
and database_sqlite.cpp with the actual implementation.
[/EDIT]

Well, apparently the solution is to rebuild static library with "-fPIC", not the dynamic one.
Thank you for reading.

Related

C2236 : unexpected token 'struct', did you forget ';' ? C2332 : 'struct' missing a tag name

Having checked posts with similar errors. None of the solutions proposed helped overcoming this issue.
I have checked all my classes for ';' at the end of the definition.....all of them are properly defined.
I have checked the include headers file for header guards. All of them have guards
This is output of building a QT project (desktop GUI app) .
What are the typical causes of these errors aside from what's mentioned above ?
below is the output of the error :
include\ConfigServer.h(85): error C2236: unexpected token 'struct'. Did you forget a ';'?
include\ConfigServer.h(85): error C2332: 'struct': missing tag name
This 'ConfigServer.h' file include 'BlockParam.h' , 'CommsInfo.h' and 'GeoInfo.h' which I have compiled with previously on a separate console project to test their use. They work on a console program.
Any insight ?
#ifndef CONFIGSERVER_H
#define CONFIGSERVER_H
#include <iostream>
#include <iterator>
#include <QObject>
#include <QMap>
#include <QString>
#include <QVector>
#include <QFile>
#include <QXmlStreamReader>
#include <QDebug>
#include "BlockParam.h"
#include "CommsInfo.h"
#include "GeoInfo.h"
#define _delete(x) { if(x) delete x; x = nullptr;}
#define DEBUG 1
#define SHOW(X,B) { if(DEBUG) { std::cout << X << B <<std::endl ; } }
#define DISPLAY(X) { if(DEBUG) { std::cout << X <<std::endl ; } }
enum ENUM_PLATFORM {
NOTSET = 0,
SILSIM = 1, // Desktop Platform
PILSIM = 2, // PIL Platform
HILSIM = 3 // HIL Platform
};
enum ENUM_CONFIG
{
GEOINFO = 1,
COMMS = 2,
MDLPARAM = 3
};
typedef QMap<QString,ConfigInfo*> CfgMap;
class ConfigServer
{
public:
ConfigServer();
~ConfigServer();
bool LoadXmlFile(const QString xmlParmFileName);
bool Validate(Xpci* xpc);
bool IsValidated();
bool errorsOccurred();
QVector<QString> getErrorStrings();
template<class T>
ConfigInfo *GetConfigInfo(QString _inface,QString _pty,bool ebl);
template<class T>
void DisplayContent(T* Cfg) const;
CfgMap *getMap() const;
QVector<CfgMap> *getConfigList() const;
ENUM_PLATFORM PLATFORM;
ENUM_CONFIG CONFIGURATION;
QVector<QString> ErrStringsVector;
private:
void readModelXmlToMap(QXmlStreamReader* reader,CfgMap* ConfigMap_);
template<class T>
bool readCurrentInterfaceElement(QXmlStreamReader* reader,CfgMap* ConfigMap_);
template<class T>
bool readCurrentPropertyElement(QXmlStreamReader* reader,QString interface,CfgMap* ConfigMap_);
bool readCurrentDimensionElement(QXmlStreamReader* reader,unsigned &rowDim,unsigned &colDim);
BlockParam nullBlockParam;
CommsInfo nullCommsInfo;
GeoInfo nullGeoInfo;
CfgMap* ConfigMap = nullptr;
QVector<CfgMap> *ConfigList = nullptr;
unsigned requisite;
bool validated = false;
bool errorFlag = false;
};
template<> bool ConfigServer::readCurrentInterfaceElement<BlockParam>(QXmlStreamReader* reader,CfgMap* ConfigMap_) ;
template<> bool ConfigServer::readCurrentInterfaceElement<CommsInfo>(QXmlStreamReader* reader,CfgMap* ConfigMap_) ;
template<> bool ConfigServer::readCurrentInterfaceElement<GeoInfo>(QXmlStreamReader* reader,CfgMap* ConfigMap_) ;
template<> bool ConfigServer::readCurrentPropertyElement<BlockParam>(QXmlStreamReader *reader,QString interface,CfgMap* ConfigMap_);
template<> bool ConfigServer::readCurrentPropertyElement<CommsInfo>(QXmlStreamReader *reader,QString interface,CfgMap* ConfigMap_);
template<> bool ConfigServer::readCurrentPropertyElement<GeoInfo>(QXmlStreamReader *reader,QString interface,CfgMap* ConfigMap_);
template<> ConfigInfo *ConfigServer::GetConfigInfo<BlockParam>(QString _inface,QString _pty,bool ebl);
template<> ConfigInfo *ConfigServer::GetConfigInfo<CommsInfo>(QString _inface,QString _pty,bool ebl);
template<> ConfigInfo *ConfigServer::GetConfigInfo<GeoInfo>(QString _inface,QString _pty,bool ebl);
template<> void ConfigServer::DisplayContent<BlockParam>(BlockParam* Cfg) const;
template<> void ConfigServer::DisplayContent<CommsInfo>(CommsInfo* Cfg) const;
template<> void ConfigServer::DisplayContent<GeoInfo>(GeoInfo* Cfg) const;
#endif // CONFIGSERVER_H
In Windows headers (which you indirectly include via Qt headers), there are macro definitions that boil down to #define interface struct. Your function declarations then get mangled to
template<> bool ConfigServer::readCurrentPropertyElement<BlockParam>(
..., QString struct, ...);
The QString struct part is obviously nonsense, and the compiler complains.
The easiest workaround would be to avoid using interface as an identifier.

QtRemoteObjects autogenerated replica header complaining about undefined vtable

Started using QtRO and generated files inherently complain about vtable:
#ifndef REP_REMOTEEXAMPLE_H
#define REP_REMOTEEXAMPLE_H
// This is an autogenerated file.
// Do not edit this file, any changes made will be lost the next time it is generated.
#include <QtCore/qobject.h>
#include <QtCore/qdatastream.h>
#include <QtCore/qvariant.h>
#include <QtCore/qmetatype.h>
#include <QtRemoteObjects/qremoteobjectnode.h>
#include <QtRemoteObjects/qremoteobjectpendingcall.h>
#include <QtRemoteObjects/qremoteobjectreplica.h>
class remoteExampleReplica : public QRemoteObjectReplica
{
Q_OBJECT
Q_CLASSINFO(QCLASSINFO_REMOTEOBJECT_TYPE, "remoteExample")
Q_CLASSINFO(QCLASSINFO_REMOTEOBJECT_SIGNATURE, "5e40a606abdd95f709878d419edaa735fce25d0d")
public:
remoteExampleReplica() : QRemoteObjectReplica() { initialize(); }
static void registerMetatypes()
{
static bool initialized = false;
if (initialized)
return;
initialized = true;
}
private:
remoteExampleReplica(QRemoteObjectNode *node, const QString &name = QString())
: QRemoteObjectReplica(ConstructWithNode)
{
initializeNode(node, name);
}
void initialize() override
{
remoteExampleReplica::registerMetatypes();
QVariantList properties;
properties.reserve(0);
setProperties(properties);
}
public:
virtual ~remoteExampleReplica() {}
Q_SIGNALS:
void Close(QString a);
void Open(QString b);
public Q_SLOTS:
void onClosed()
{
static int __repc_index = remoteExampleReplica::staticMetaObject.indexOfSlot("onClosed()");
QVariantList __repc_args;
send(QMetaObject::InvokeMetaMethod, __repc_index, __repc_args);
}
void onOpened()
{
static int __repc_index = remoteExampleReplica::staticMetaObject.indexOfSlot("onOpened()");
QVariantList __repc_args;
send(QMetaObject::InvokeMetaMethod, __repc_index, __repc_args);
}
private:
friend class QT_PREPEND_NAMESPACE(QRemoteObjectNode);
};
#if (QT_VERSION < QT_VERSION_CHECK(5, 5, 0))
#endif
QT_BEGIN_NAMESPACE
QT_END_NAMESPACE
#endif // REP_REMOTEEXAMPLE_H
The issue points to the private constructor. I only included the replica header in my code without really using the remote object as a test run. I've read a lot about vtables how they work and when the linker complains about the vtable but in this case, with the private constructor, I'm not sure what the issue is. Am I missing an implementation of the remote object? Did I not generate the files correctly?
.rep:
class remoteExample
{
SIGNAL(Close(QString a));
SIGNAL(Open(QString b));
SLOT(onClosed());
SLOT(onOpened());
};

How to attach to existing shared memory from Qt?

I have created a shared memory segment with the help of a binary in C and written some data into it. Now I want read that data from Qt. How to attach to existing shared memory from Qt?
QSharedMemory isn't really meant to interoperate with anything else. On Unix, it is implemented via SYSV shared memory, but it passes Qt-specific arguments to ftok:
::ftok(filename.constData(), qHash(filename, proj_id));
You could emulate this behavior in your C code, but I don't think it's necessary.
Instead of opening a shared memory segment, simply map a file to memory, and access it from multiple processes. On Qt, QFile::map does what you need.
The example below shows both techniques: using SYSV shared memory and using memory-mapped files:
// https://github.com/KubaO/stackoverflown/tree/master/questions/sharedmem-interop-39573295
#include <QtCore>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <stdexcept>
#include <string>
First, let's have a shared data structure.
struct Data {
int a = 1;
bool b = true;
char c = 'S';
bool operator==(const Data & o) const { return o.a == a && o.b == b && o.c == c; }
static void compare(const void * a, const void * b) {
auto data1 = reinterpret_cast<const Data*>(a);
auto data2 = reinterpret_cast<const Data*>(b);
Q_ASSERT(*data1 == *data2);
}
};
We definitely want error checking, so let's add some helpers that make that easier:
void check(bool ok, const char * msg, const char * detail) {
if (ok) return;
std::string str{msg};
str.append(": ");
str.append(detail);
throw std::runtime_error{str};
}
void check(int f, const char * msg) { check(f != -1, msg, strerror(errno)); }
void check(void * f, const char * msg) { check(f != MAP_FAILED, msg, strerror(errno)); }
void check(bool rc, const QSharedMemory & shm, const char * msg) { check(rc, msg, shm.errorString().toLocal8Bit()); }
void check(bool rc, const QFile & file, const char * msg) { check(rc, msg, file.errorString().toLocal8Bit()); }
And we need RAII wrappers for C APIs:
struct noncopyable { Q_DISABLE_COPY(noncopyable) noncopyable() {} };
struct ShmId : noncopyable {
int id;
ShmId(int id) : id{id} {}
~ShmId() { if (id != -1) shmctl(id, IPC_RMID, NULL); }
};
struct ShmPtr : noncopyable {
void * ptr;
ShmPtr(void * ptr) : ptr{ptr} {}
~ShmPtr() { if (ptr != (void*)-1) shmdt(ptr); }
};
struct Handle : noncopyable {
int fd;
Handle(int fd) : fd{fd} {}
~Handle() { if (fd != -1) close(fd); }
};
Here's how to interoperates SYSV shared memory sections between C and Qt. Unfortunately, unless you reimplement qHash in C, it's not possible:
void ipc_shm_test() {
QTemporaryFile shmFile;
check(shmFile.open(), shmFile, "shmFile.open");
// SYSV SHM
auto nativeKey = QFile::encodeName(shmFile.fileName());
auto key = ftok(nativeKey.constData(), qHash(nativeKey, 'Q'));
check(key, "ftok");
ShmId id{shmget(key, sizeof(Data), IPC_CREAT | 0600)};
check(id.id, "shmget");
ShmPtr ptr1{shmat(id.id, NULL, 0)};
check(ptr1.ptr, "shmat");
new (ptr1.ptr) Data;
// Qt
QSharedMemory shm;
shm.setNativeKey(shmFile.fileName());
check(shm.attach(QSharedMemory::ReadOnly), shm, "shm.attach");
auto ptr2 = shm.constData();
Data::compare(ptr1.ptr, ptr2);
}
Here's how to interoperate memory-mapped files:
void mmap_test() {
QTemporaryFile shmFile;
check(shmFile.open(), "shmFile.open");
shmFile.write({sizeof(Data), 0});
check(true, shmFile, "shmFile.write");
check(shmFile.flush(), shmFile, "shmFile.flush");
// SYSV MMAP
Handle fd{open(QFile::encodeName(shmFile.fileName()), O_RDWR)};
check(fd.fd, "open");
auto ptr1 = mmap(NULL, sizeof(Data), PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd.fd, 0);
check(ptr1, "mmap");
new (ptr1) Data;
// Qt
auto ptr2 = shmFile.map(0, sizeof(Data));
Data::compare(ptr1, ptr2);
}
And finally, the test harness:
int main() {
try {
ipc_shm_test();
mmap_test();
}
catch (const std::runtime_error & e) {
qWarning() << e.what();
return 1;
}
return 0;
}

C3767: candidate function(s) not accesible

I have this class:
#pragma once
#ifndef _DEFINES_H_
#include "Defines.h"
#endif
#ifndef _GAMETIME_H_
#include "GameTime.h"
#endif
#ifndef _UTILITIES_H_
#include "Utilities.h"
#endif
#ifndef _GAME_H_
using namespace System;
namespace BSGameFramework
{
public ref class Game
{
public:
Game();
virtual ~Game();
void Run(HINSTANCE instance);
string Title;
int WindowWidth;
int WindowHeight;
protected:
virtual void Initialize();
virtual void LoadContent();
virtual void UnloadContent();
virtual void Update(GameTime^ gameTime);
virtual void Draw(GameTime^ gameTime);
private:
HINSTANCE windowHandler;
HWND window;
DateTime lastTime;
TimeSpan totalGameTime;
D3D_DRIVER_TYPE driverType_;
D3D_FEATURE_LEVEL featureLevel_;
ID3D11Device* d3dDevice_;
ID3D11DeviceContext* d3dContext_;
IDXGISwapChain* swapChain_;
ID3D11RenderTargetView* backBufferTarget_;
void Shutdown();
};
}
#define _GAME_H_
#endif
and this is its child:
#pragma once
using namespace BSGameFramework;
public ref class MyGame : Game
{
public:
MyGame()
{
}
};
Then when on my Main I call my Run function:
#include <Windows.h>
#include "MyGame.h"
using namespace BSGameFramework;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
MyGame ^game = gcnew MyGame();
game->Run(hInstance); // Here the error
}
I get this error:
Error 1 error C3767: 'BSGameFramework::Game::Run': candidate function(s) not accessible
C:\Users\Nicola\Desktop\directx prove\BSGameFramework\FrameworkTestCpp\Main.cpp 10 1 FrameworkTestCpp
I've tried to remove the HINSTANCE from Run parameters and all is working fine, but I need it so somebody can explain me why I'm getting this error and how can I solve? Thanks in advance!
I have solved in this way:
inline void Game::Run(IntPtr instance)
{
windowHandler = (HINSTANCE)instance.ToPointer();
// other code
}
now I'm passing an IntPtr that is not a native type, so on main function I have this:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
MyGame ^game = gcnew MyGame();
IntPtr instance(hInstance);
game->Run(instance);
}

How to get list of application icons which are installed in device with Qt

I am working with Qt application in which I want to create a QListWidget with names of all application installed on device and its icon.
So I was unable get all application names and UID of each application from the code in this LINK.
But I was also unable to get the application icons. I tried both this LINK1 & LINK2 but here I came across few more issues like how to convert CGulIcon into QIcon & CApaMaskedBitmap into QIcon.
How can I do this?
If you are unable to get the solution or have any more doubts click here for disscussion.
main.cpp
#include "GetInstalledApps.h"
#include <QtGui>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GetInstalledApps w;
w.showMaximized();
return a.exec();
}
.pro
TEMPLATE = app
TARGET = GetInstalledApps
QT += core \
gui
HEADERS += GetInstalledApps.h
SOURCES += main.cpp \
GetInstalledApps.cpp
FORMS += GetInstalledApps.ui
RESOURCES +=
HEADERS += xqinstaller_p.h \
xqinstaller.h \
SOURCES += xqinstaller_p.cpp \
xqinstaller.cpp
symbian:LIBS += -lswinstcli \
-lcommdb \
-lapparc \
-lefsrv \
-lapgrfx \
symbian:TARGET.CAPABILITY += TrustedUI
symbian:TARGET.UID3 = 0xEF3055F4
GetInstalledApps.h
#ifndef GETINSTALLEDAPPS_H
#define GETINSTALLEDAPPS_H
#include <QtGui/QMainWindow>
#include "ui_GetInstalledApps.h"
#include "xqinstaller.h"
class GetInstalledApps : public QMainWindow
{
Q_OBJECT
public:
GetInstalledApps(QWidget *parent = 0);
~GetInstalledApps();
private:
void GetApps();
private:
Ui::GetInstalledAppsClass ui;
XQInstaller* m_installer;
QMap<QString, uint> m_applications;
QList<QString> m_appNames;
QList<uint> m_appUID;
};
#endif // GETINSTALLEDAPPS_H
GetInstalledApps.cpp
#include "GetInstalledApps.h"
#include <QScrollArea>
GetInstalledApps::GetInstalledApps(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
setWindowTitle("GetAllInstalledApps");
m_installer = new XQInstaller(this);
GetApps();
}
void GetInstalledApps::GetApps()
{
/* Get List of applications.
* type of m_applications is QMap<QString, uint>.
* type of m_installer is XQInstaller
*/
m_applications = m_installer->applications();
/* Get List of application names
type of m_appNames is QList<QString> */
m_appNames = m_applications.keys();
/* Get List of application UID in decimal.
type of m_appUID is QList<uint> */
m_appUID = m_applications.values();
ui.listWidget->clear();
for (int i = 0; i < m_appNames.count(); i++)
{
QString str;
/* convert UID from decimal to hex and then string. */
str.setNum(m_appUID.at(i),16);
/* append name and UID to string */
QString string(m_appNames.at(i)+" UID:"+ str);
/* append string to list widget to display on screen */
ui.listWidget->addItem(string);
}
/* Let's make the UI scale so that we can scroll it. */
QScrollArea* scrollArea = new QScrollArea;
scrollArea->setWidget(ui.listWidget);
scrollArea->setWidgetResizable(true);
setCentralWidget(scrollArea);
}
GetInstalledApps::~GetInstalledApps()
{
}
xqinstaller.h
#ifndef XQINSTALLER_H
#define XQINSTALLER_H
// INCLUDES
#include <QObject>
#include <QMap>
class XQInstallerPrivate;
// CLASS DECLARATION
class XQInstaller : public QObject
{
Q_OBJECT
public:
enum Error {
NoError = 0,
OutOfMemoryError,
AlreadyInUseError,
UserCancelError,
PackageNotSupportedError,
SecurityFailureError,
MissingDependencyError,
NoRightsError,
BusyError,
AccessDeniedError,
UpgradeError,
UnknownError = -1
};
enum Drive {
DriveA, DriveB, DriveC, DriveD, DriveE,
DriveF, DriveG, DriveH, DriveI, DriveJ,
DriveK, DriveL, DriveM, DriveN, DriveO,
DriveP, DriveQ, DriveR, DriveS, DriveT,
DriveU, DriveV, DriveW, DriveX, DriveY,
DriveZ
};
XQInstaller(QObject *parent = 0);
~XQInstaller();
bool install(const QString& file, XQInstaller::Drive drive = XQInstaller::DriveC);
QMap<QString, uint> applications() const;
bool remove(uint uid);
XQInstaller::Error error() const;
Q_SIGNALS:
void applicationInstalled();
void applicationRemoved();
void error(XQInstaller::Error);
private:
friend class XQInstallerPrivate;
XQInstallerPrivate *d;
};
#endif // XQINSTALLER_H
xqinstaller.cpp
#include "xqinstaller.h"
#include "xqinstaller_p.h"
/*!
\class XQInstaller
\brief The XQInstaller class is used to install sis-packages silently.
This extension can be used for example to install back-end applications.
Example:
\code
XQInstaller *installer = new XQInstaller(this);
QMap<QString, uint> applications = installer->applications();
QListWidget *applicationList = new QListWidget(this);
QList<QString> appNames = applications.keys();
for (int i = 0; i < appNames.count(); i++) {
applicationList->addItem(appNames.at(i));
}
\endcode
*/
/*!
Constructs a XQInstaller object with the given parent.
\sa install(), remove()
*/
XQInstaller::XQInstaller(QObject *parent)
: QObject(parent), d(new XQInstallerPrivate(this))
{
}
/*!
Destroys the XQInstaller object.
*/
XQInstaller::~XQInstaller()
{
delete d;
}
/*!
Installs a sis package silently given as parameter.
\param file Sis package
\param drive Drive letter where the sis is installed to. Default value is 'C'.
\return If false is returned, an error has occurred. Call error() to get a value of
XQInstaller::Error that indicates which error occurred
\sa error()
*/
bool XQInstaller::install(const QString& file, XQInstaller::Drive drive)
{
return d->install(file, drive);
}
/*!
Get list of installed applications
If an empty QMap is returned, an error has possibly occurred. Call error() to get a value of
XQInstaller::Error that indicates which error occurred if any
\return List of installed applications
\sa error()
*/
QMap<QString, uint> XQInstaller::applications() const
{
return d->applications();
}
/*!
Removes application specified by the uid
\param uid of the application
\return True if removing was successfully started, otherwise false
\sa error()
*/
bool XQInstaller::remove(uint uid)
{
return d->remove(uid);
}
/*!
\enum XQInstaller::Error
This enum defines the possible errors for a XQInstaller object.
*/
/*! \var XQInstaller::Error XQInstaller::NoError
No error occured.
*/
/*! \var XQInstaller::Error XQInstaller::OutOfMemoryError
Not enough memory.
*/
/*! \var XQInstaller::Error XQInstaller::AlreadyInUseError
Installer is already in used.
*/
/*! \var XQInstaller::Error XQInstaller::UserCancelError
Installer cancelled by the user.
*/
/*! \var XQInstaller::Error XQInstaller::PackageNotSupportedError
Package not supported
*/
/*! \var XQInstaller::Error XQInstaller::SecurityFailureError
Security failure
*/
/*! \var XQInstaller::Error XQInstaller::MissingDependencyError
Missing dependency
*/
/*! \var XQInstaller::Error XQInstaller::NoRightsError
No rights
*/
/*! \var XQInstaller::Error XQInstaller::BusyError
Installer is busy
*/
/*! \var XQInstaller::Error XQInstaller::AccessDeniedError
Access denied
*/
/*! \var XQInstaller::Error XQInstaller::UpgradeError
Error while upgrading
*/
/*! \var XQInstaller::Error XQInstaller::UnknownError
Unknown error.
*/
/*!
Returns the type of error that occurred if the latest function call failed; otherwise returns NoError
\return Error code
*/
XQInstaller::Error XQInstaller::error() const
{
return d->error();
}
/*!
\fn void XQInstaller::applicationInstalled()
This signal is emitted when the application has been installed.
\sa install()
*/
/*!
\fn void XQInstaller::error(XQInstaller::Error)
This signal is emitted if error occured during the asynchronous operation
\sa install()
*/
/*!
\fn void XQInstaller::applicationRemoved()
This signal is emitted when the application has been removed.
\sa remove()
*/
// End of file
xqinstaller_h.h
#ifndef XQINSTALLER_P_H
#define XQINSTALLER_P_H
// INCLUDES
#include "xqinstaller.h"
#include <SWInstApi.h>
#include <SWInstDefs.h>
// FORWARD DECLARATIONS
class QString;
class QFile;
// CLASS DECLARATION
class XQInstallerPrivate: public CActive
{
public:
enum State {
ERemove,
EInstall
};
XQInstallerPrivate(XQInstaller *installer);
~XQInstallerPrivate();
bool install(const QString& file, XQInstaller::Drive drive);
bool remove(uint uid);
QMap<QString, uint> applications() const;
public:
XQInstaller::Error error();
protected:
void DoCancel();
void RunL();
private:
XQInstaller *q;
mutable int iError;
SwiUI::RSWInstSilentLauncher iLauncher;
SwiUI::TInstallOptions iOptions;
SwiUI::TInstallOptionsPckg iOptionsPckg;
SwiUI::TUninstallOptions iUninstallOptions;
SwiUI::TUninstallOptionsPckg iUninstallOptionsPckg;
XQInstallerPrivate::State iState;
TFileName iFileName;
bool iLauncherConnected;
};
#endif /*XQINSTALLER_P_H*/
// End of file
xqinstaller_h.cpp
#include "xqinstaller.h"
#include "xqinstaller_p.h"
#include <f32file.h>
#include <apgcli.h>
XQInstallerPrivate::XQInstallerPrivate(XQInstaller *installer)
: CActive(EPriorityNormal), q(installer), iOptionsPckg(iOptions),
iUninstallOptionsPckg(iUninstallOptions), iLauncherConnected(false)
{
CActiveScheduler::Add(this);
}
XQInstallerPrivate::~XQInstallerPrivate()
{
Cancel();
if (iLauncherConnected) {
iLauncher.Close();
}
}
bool XQInstallerPrivate::install(const QString& file, XQInstaller::Drive drive)
{
int asciiValue = 10; // = 'A'
TRAP(iError,
if (!iLauncherConnected) {
User::LeaveIfError(iLauncher.Connect());
iLauncherConnected = true;
}
if (IsActive()) {
User::Leave(KErrInUse);
}
iState = XQInstallerPrivate::EInstall;
iOptions.iUpgrade = SwiUI::EPolicyAllowed;
iOptions.iOCSP = SwiUI::EPolicyNotAllowed;
iOptions.iDrive = TChar(asciiValue+drive);
iOptions.iUntrusted = SwiUI::EPolicyAllowed;
iOptions.iCapabilities = SwiUI::EPolicyAllowed;
iOptions.iOptionalItems = SwiUI::EPolicyAllowed;
iOptions.iOverwrite = SwiUI::EPolicyAllowed;
TPtrC16 fileName(reinterpret_cast<const TUint16*>(file.utf16()));
iFileName = fileName;
iLauncher.SilentInstall(iStatus, iFileName, iOptionsPckg);
SetActive();
)
return (iError == KErrNone);
}
bool XQInstallerPrivate::remove(uint uid)
{
TRAP(iError,
if (!iLauncherConnected) {
User::LeaveIfError(iLauncher.Connect());
iLauncherConnected = true;
}
if (IsActive()) {
User::Leave(KErrInUse);
}
iState = XQInstallerPrivate::ERemove;
iLauncher.SilentUninstall(iStatus,TUid::Uid(uid),
iUninstallOptionsPckg, SwiUI::KSisxMimeType);
SetActive();
)
return (iError == KErrNone);
}
QMap<QString, uint> XQInstallerPrivate::applications() const
{
RApaLsSession lsSession;
QMap<QString, uint> applications;
// Connect to application architecture server
TRAP(iError,
User::LeaveIfError(lsSession.Connect());
CleanupClosePushL(lsSession);
TApaAppInfo appInfo;
lsSession.GetAllApps();
while (lsSession.GetNextApp(appInfo) == KErrNone) {
TApaAppCapabilityBuf capability;
User::LeaveIfError(lsSession.GetAppCapability(capability,
appInfo.iUid));
if (appInfo.iCaption.Length() > 0 && !capability().iAppIsHidden) {
QString fullName = QString::fromUtf16(
appInfo.iCaption.Ptr(), appInfo.iCaption.Length());
applications.insert(fullName, (TUint)appInfo.iUid.iUid);
}
}
CleanupStack::PopAndDestroy(&lsSession);
)
return applications;
}
void XQInstallerPrivate::DoCancel()
{
if (iState == XQInstallerPrivate::EInstall) {
iLauncher.CancelAsyncRequest(SwiUI::ERequestSilentInstall);
} else if (iState == XQInstallerPrivate::ERemove) {
iLauncher.CancelAsyncRequest(SwiUI::ERequestSilentUninstall);
}
}
void XQInstallerPrivate::RunL()
{
if (iStatus.Int() == KErrNone) {
if (iState == XQInstallerPrivate::EInstall) {
emit q->applicationInstalled();
} else if (iState == XQInstallerPrivate::ERemove) {
emit q->applicationRemoved();
}
} else {
iError = iStatus.Int();
emit q->error(error());
}
}
XQInstaller::Error XQInstallerPrivate::error()
{
switch (iError) {
case KErrNone:
return XQInstaller::NoError;
case SwiUI::KSWInstErrInsufficientMemory:
case KErrNoMemory:
return XQInstaller::OutOfMemoryError;
case SwiUI::KSWInstErrFileInUse:
case KErrInUse:
return XQInstaller::AlreadyInUseError;
case SwiUI::KSWInstErrUserCancel:
return XQInstaller::UserCancelError;
case SwiUI::KSWInstErrPackageNotSupported:
return XQInstaller::PackageNotSupportedError;
case SwiUI::KSWInstErrSecurityFailure:
return XQInstaller::SecurityFailureError;
case SwiUI::KSWInstErrMissingDependency:
return XQInstaller::MissingDependencyError;
case SwiUI::KSWInstErrNoRights:
return XQInstaller::NoRightsError;
case SwiUI::KSWInstErrBusy:
return XQInstaller::BusyError;
case SwiUI::KSWInstErrAccessDenied:
return XQInstaller::AccessDeniedError;
case SwiUI::KSWInstUpgradeError:
return XQInstaller::UpgradeError;
case SwiUI::KSWInstErrGeneralError:
default:
return XQInstaller::UnknownError;
}
}
// End of file
And for getting QIcon::
Hearders Required:
#include <fbs.h> //CFbsBitmap
#include <aknsskininstance.h> //MAknsSkinInstance
#include <aknsutils.h> //AknsUtils
Library required:
LIBRARY fbscli.lib ///CFbsBitmap
LIBRARY aknskins.lib aknskinsrv.lib aknswallpaperutils.lib //MAknsSkinInstance ,AknsUtils
Source Code:
CGulIcon* CMyClass::GetApplicationIconL(const TUid& aAppUID)
{
CFbsBitmap* AppIcon(NULL);
CFbsBitmap* AppIconMsk(NULL);
MAknsSkinInstance* skin = AknsUtils::SkinInstance();
AknsUtils::CreateAppIconLC(skin,aAppUID, EAknsAppIconTypeContext,AppIcon,AppIconMsk);
CleanupStack::Pop(2);
return CGulIcon::NewL(AppIcon,AppIconMsk);
}
Well, for the icon thing look at this: CGullIcon there's a function that returns the Bitmap, a CFbsBitmap. Once you've done that look at this: http://qt-project.org/doc/qt-4.8/qpixmap.html#fromSymbianCFbsBitmap then you create a new QIcon(QPixmap) (QPixmap = the icon you've transformed). So most likely you're first passing it to a CFbsBitmap and then with QPixmap you use fromSymibnaCFbsBitmap().
CApaMaskedBitmap is a sub-class of CFbsBitmap if i'm not wrong, so it should work the same.
And for getting the applications and their UID try to look at this: http://www.developer.nokia.com/Community/Wiki/Get_list_of_installed_applications_and_its_UID_in_Qt

Resources